forked from c9s/bbgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stream.go
306 lines (246 loc) · 6.94 KB
/
stream.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
package max
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"os"
"strconv"
"time"
"github.com/google/uuid"
max "github.com/c9s/bbgo/pkg/exchange/max/maxapi"
"github.com/c9s/bbgo/pkg/types"
)
//go:generate callbackgen -type Stream
type Stream struct {
types.StandardStream
types.MarginSettings
key, secret string
privateChannels []string
authEventCallbacks []func(e max.AuthEvent)
bookEventCallbacks []func(e max.BookEvent)
tradeEventCallbacks []func(e max.PublicTradeEvent)
kLineEventCallbacks []func(e max.KLineEvent)
errorEventCallbacks []func(e max.ErrorEvent)
subscriptionEventCallbacks []func(e max.SubscriptionEvent)
tradeUpdateEventCallbacks []func(e max.TradeUpdateEvent)
tradeSnapshotEventCallbacks []func(e max.TradeSnapshotEvent)
orderUpdateEventCallbacks []func(e max.OrderUpdateEvent)
orderSnapshotEventCallbacks []func(e max.OrderSnapshotEvent)
adRatioEventCallbacks []func(e max.ADRatioEvent)
debtEventCallbacks []func(e max.DebtEvent)
accountSnapshotEventCallbacks []func(e max.AccountSnapshotEvent)
accountUpdateEventCallbacks []func(e max.AccountUpdateEvent)
}
func NewStream(key, secret string) *Stream {
stream := &Stream{
StandardStream: types.NewStandardStream(),
key: key,
// pragma: allowlist nextline secret
secret: secret,
}
stream.SetEndpointCreator(stream.getEndpoint)
stream.SetParser(max.ParseMessage)
stream.SetDispatcher(stream.dispatchEvent)
stream.OnConnect(stream.handleConnect)
stream.OnAuthEvent(func(e max.AuthEvent) {
log.Infof("max websocket connection authenticated: %+v", e)
stream.EmitAuth()
})
stream.OnKLineEvent(stream.handleKLineEvent)
stream.OnOrderSnapshotEvent(stream.handleOrderSnapshotEvent)
stream.OnOrderUpdateEvent(stream.handleOrderUpdateEvent)
stream.OnTradeUpdateEvent(stream.handleTradeEvent)
stream.OnBookEvent(stream.handleBookEvent)
stream.OnAccountSnapshotEvent(stream.handleAccountSnapshotEvent)
stream.OnAccountUpdateEvent(stream.handleAccountUpdateEvent)
return stream
}
func (s *Stream) getEndpoint(ctx context.Context) (string, error) {
url := os.Getenv("MAX_API_WS_URL")
if url == "" {
url = max.WebSocketURL
}
return url, nil
}
func (s *Stream) SetPrivateChannels(channels []string) {
s.privateChannels = channels
}
func (s *Stream) handleConnect() {
if s.PublicOnly {
cmd := &max.WebsocketCommand{
Action: "subscribe",
}
for _, sub := range s.Subscriptions {
var depth int
if len(sub.Options.Depth) > 0 {
switch sub.Options.Depth {
case types.DepthLevelFull:
depth = 50
case types.DepthLevelMedium:
depth = 20
case types.DepthLevel1:
depth = 1
case types.DepthLevel5:
depth = 5
default:
depth = 20
}
}
cmd.Subscriptions = append(cmd.Subscriptions, max.Subscription{
Channel: string(sub.Channel),
Market: toLocalSymbol(sub.Symbol),
Depth: depth,
Resolution: sub.Options.Interval.String(),
})
}
if err := s.Conn.WriteJSON(cmd); err != nil {
log.WithError(err).Error("failed to send subscription request")
}
} else {
var filters []string
if len(s.privateChannels) > 0 {
// TODO: maybe check the valid private channels
filters = s.privateChannels
} else if s.MarginSettings.IsMargin {
filters = []string{
"mwallet_order",
"mwallet_trade",
"mwallet_account",
"ad_ratio",
"borrowing",
}
}
log.Debugf("user data websocket filters: %v", filters)
nonce := time.Now().UnixNano() / int64(time.Millisecond)
auth := &max.AuthMessage{
// pragma: allowlist nextline secret
Action: "auth",
// pragma: allowlist nextline secret
APIKey: s.key,
Nonce: nonce,
Signature: signPayload(strconv.FormatInt(nonce, 10), s.secret),
ID: uuid.New().String(),
Filters: filters,
}
if err := s.Conn.WriteJSON(auth); err != nil {
log.WithError(err).Error("failed to send auth request")
}
}
}
func (s *Stream) handleKLineEvent(e max.KLineEvent) {
kline := e.KLine.KLine()
s.EmitKLine(kline)
if kline.Closed {
s.EmitKLineClosed(kline)
}
}
func (s *Stream) handleOrderSnapshotEvent(e max.OrderSnapshotEvent) {
for _, o := range e.Orders {
globalOrder, err := convertWebSocketOrderUpdate(o)
if err != nil {
log.WithError(err).Error("websocket order snapshot convert error")
continue
}
s.EmitOrderUpdate(*globalOrder)
}
}
func (s *Stream) handleOrderUpdateEvent(e max.OrderUpdateEvent) {
for _, o := range e.Orders {
globalOrder, err := convertWebSocketOrderUpdate(o)
if err != nil {
log.WithError(err).Error("websocket order update convert error")
continue
}
s.EmitOrderUpdate(*globalOrder)
}
}
func (s *Stream) handleTradeEvent(e max.TradeUpdateEvent) {
for _, tradeUpdate := range e.Trades {
trade, err := convertWebSocketTrade(tradeUpdate)
if err != nil {
log.WithError(err).Error("websocket trade update convert error")
return
}
s.EmitTradeUpdate(*trade)
}
}
func (s *Stream) handleBookEvent(e max.BookEvent) {
newBook, err := e.OrderBook()
if err != nil {
log.WithError(err).Error("book convert error")
return
}
newBook.Symbol = toGlobalSymbol(e.Market)
newBook.Time = e.Time()
switch e.Event {
case "snapshot":
s.EmitBookSnapshot(newBook)
case "update":
s.EmitBookUpdate(newBook)
}
}
func (s *Stream) handleAccountSnapshotEvent(e max.AccountSnapshotEvent) {
snapshot := map[string]types.Balance{}
for _, bm := range e.Balances {
balance, err := bm.Balance()
if err != nil {
continue
}
snapshot[balance.Currency] = *balance
}
s.EmitBalanceSnapshot(snapshot)
}
func (s *Stream) handleAccountUpdateEvent(e max.AccountUpdateEvent) {
snapshot := map[string]types.Balance{}
for _, bm := range e.Balances {
balance, err := bm.Balance()
if err != nil {
continue
}
snapshot[toGlobalCurrency(balance.Currency)] = *balance
}
s.EmitBalanceUpdate(snapshot)
}
func (s *Stream) dispatchEvent(e interface{}) {
switch e := e.(type) {
case *max.AuthEvent:
s.EmitAuthEvent(*e)
case *max.BookEvent:
s.EmitBookEvent(*e)
case *max.PublicTradeEvent:
s.EmitTradeEvent(*e)
case *max.KLineEvent:
s.EmitKLineEvent(*e)
case *max.ErrorEvent:
s.EmitErrorEvent(*e)
case *max.SubscriptionEvent:
s.EmitSubscriptionEvent(*e)
case *max.TradeSnapshotEvent:
s.EmitTradeSnapshotEvent(*e)
case *max.TradeUpdateEvent:
s.EmitTradeUpdateEvent(*e)
case *max.AccountSnapshotEvent:
s.EmitAccountSnapshotEvent(*e)
case *max.AccountUpdateEvent:
s.EmitAccountUpdateEvent(*e)
case *max.OrderSnapshotEvent:
s.EmitOrderSnapshotEvent(*e)
case *max.OrderUpdateEvent:
s.EmitOrderUpdateEvent(*e)
case *max.ADRatioEvent:
s.EmitAdRatioEvent(*e)
case *max.DebtEvent:
s.EmitDebtEvent(*e)
default:
log.Warnf("unhandled %T event: %+v", e, e)
}
}
func signPayload(payload string, secret string) string {
var sig = hmac.New(sha256.New, []byte(secret))
_, err := sig.Write([]byte(payload))
if err != nil {
return ""
}
return hex.EncodeToString(sig.Sum(nil))
}