Skip to content

Commit

Permalink
max: optimize book parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
c9s committed Jan 24, 2024
1 parent fcd367b commit e67155d
Showing 1 changed file with 13 additions and 42 deletions.
55 changes: 13 additions & 42 deletions pkg/exchange/max/maxapi/public_parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -208,81 +208,52 @@ func parseKLineEvent(val *fastjson.Value) (*KLineEvent, error) {
return &event, nil
}

func parseBookEvent(val *fastjson.Value) (*BookEvent, error) {
event := BookEvent{
func parseBookEvent(val *fastjson.Value) (event *BookEvent, err error) {
event = &BookEvent{
Event: string(val.GetStringBytes("e")),
Market: string(val.GetStringBytes("M")),
Channel: string(val.GetStringBytes("c")),
Timestamp: val.GetInt64("T"),
}

// t := time.Unix(0, event.Timestamp*int64(time.Millisecond))

var err error
event.Asks, err = parseBookEntries2(val.GetArray("a"))
if err != nil {
return nil, err
return event, err
}

event.Bids, err = parseBookEntries2(val.GetArray("b"))
if err != nil {
return nil, err
}

return &event, nil
}

type BookEntry struct {
Side int
Time time.Time
Price string
Volume string
}

func (e *BookEntry) PriceVolumePair() (pv types.PriceVolume, err error) {
pv.Price, err = fixedpoint.NewFromString(e.Price)
if err != nil {
return pv, err
}

pv.Volume, err = fixedpoint.NewFromString(e.Volume)
if err != nil {
return pv, err
}

return pv, err
return event, err
}

// parseBookEntries2 parses JSON struct like `[["233330", "0.33"], ....]`
func parseBookEntries2(vals []*fastjson.Value) (types.PriceVolumeSlice, error) {
entries := make(types.PriceVolumeSlice, 0, 50)
func parseBookEntries2(vals []*fastjson.Value) (entries types.PriceVolumeSlice, err error) {
entries = make(types.PriceVolumeSlice, 0, 50)
for _, entry := range vals {
pv, err := entry.Array()
arr, err := entry.Array()
if err != nil {
return nil, err
}

if len(pv) < 2 {
if len(arr) < 2 {
return nil, ErrIncorrectBookEntryElementLength
}

price, err := fixedpoint.NewFromString(string(pv[0].GetStringBytes()))
var pv types.PriceVolume
pv.Price, err = fixedpoint.NewFromString(string(arr[0].GetStringBytes()))
if err != nil {
return nil, err
}

volume, err := fixedpoint.NewFromString(string(pv[1].GetStringBytes()))
pv.Volume, err = fixedpoint.NewFromString(string(arr[1].GetStringBytes()))
if err != nil {
return nil, err
}

entries = append(entries, types.PriceVolume{
Price: price,
Volume: volume,
})
entries = append(entries, pv)
}

return entries, nil
return entries, err
}

// parseBookEntries parses JSON struct like `[["233330", "0.33"], ....]`
Expand Down

0 comments on commit e67155d

Please sign in to comment.