-
-
Notifications
You must be signed in to change notification settings - Fork 277
/
convert.go
352 lines (294 loc) · 9.62 KB
/
convert.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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
package okex
import (
"fmt"
"strconv"
"strings"
"github.com/c9s/bbgo/pkg/exchange/okex/okexapi"
"github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/types"
)
func toGlobalSymbol(symbol string) string {
return strings.ReplaceAll(symbol, "-", "")
}
//go:generate sh -c "echo \"package okex\nvar spotSymbolMap = map[string]string{\n\" $(curl -s -L 'https://www.okx.com/api/v5/public/instruments?instType=SPOT' | jq -r '.data[] | \"\\(.instId | sub(\"-\" ; \"\") | tojson ): \\( .instId | tojson),\n\"') \"\n}\" > symbols.go"
//go:generate go run gensymbols.go
func toLocalSymbol(symbol string) string {
if s, ok := spotSymbolMap[symbol]; ok {
return s
}
log.Errorf("failed to look up local symbol from %s", symbol)
return symbol
}
func toGlobalTicker(marketTicker okexapi.MarketTicker) *types.Ticker {
return &types.Ticker{
Time: marketTicker.Timestamp.Time(),
Volume: marketTicker.Volume24H,
Last: marketTicker.Last,
Open: marketTicker.Open24H,
High: marketTicker.High24H,
Low: marketTicker.Low24H,
Buy: marketTicker.BidPrice,
Sell: marketTicker.AskPrice,
}
}
func toGlobalBalance(account *okexapi.Account) types.BalanceMap {
var balanceMap = types.BalanceMap{}
for _, balanceDetail := range account.Details {
balanceMap[balanceDetail.Currency] = types.Balance{
Currency: balanceDetail.Currency,
Available: balanceDetail.CashBalance,
Locked: balanceDetail.Frozen,
}
}
return balanceMap
}
type WebsocketSubscription struct {
Channel Channel `json:"channel"`
InstrumentID string `json:"instId,omitempty"`
InstrumentType string `json:"instType,omitempty"`
}
var CandleChannels = []string{
"candle1Y",
"candle6M", "candle3M", "candle1M",
"candle1W",
"candle1D", "candle2D", "candle3D", "candle5D",
"candle12H", "candle6H", "candle4H", "candle2H", "candle1H",
"candle30m", "candle15m", "candle5m", "candle3m", "candle1m",
}
func convertIntervalToCandle(interval types.Interval) string {
s := interval.String()
switch s {
case "1h", "2h", "4h", "6h", "12h", "1d", "3d":
return "candle" + strings.ToUpper(s)
case "1m", "5m", "15m", "30m":
return "candle" + s
}
return "candle" + s
}
func convertSubscription(s types.Subscription) (WebsocketSubscription, error) {
// binance uses lower case symbol name,
// for kline, it's "<symbol>@kline_<interval>"
// for depth, it's "<symbol>@depth OR <symbol>@depth@100ms"
switch s.Channel {
case types.KLineChannel:
// Channel names are:
return WebsocketSubscription{
Channel: Channel(convertIntervalToCandle(s.Options.Interval)),
InstrumentID: toLocalSymbol(s.Symbol),
}, nil
case types.BookChannel:
if s.Options.Depth != types.DepthLevel400 {
return WebsocketSubscription{}, fmt.Errorf("%s depth not supported", s.Options.Depth)
}
return WebsocketSubscription{
Channel: ChannelBooks,
InstrumentID: toLocalSymbol(s.Symbol),
}, nil
case types.BookTickerChannel:
return WebsocketSubscription{
Channel: ChannelBook5,
InstrumentID: toLocalSymbol(s.Symbol),
}, nil
case types.MarketTradeChannel:
return WebsocketSubscription{
Channel: ChannelMarketTrades,
InstrumentID: toLocalSymbol(s.Symbol),
}, nil
}
return WebsocketSubscription{}, fmt.Errorf("unsupported public stream channel %s", s.Channel)
}
func toLocalSideType(side types.SideType) okexapi.SideType {
return okexapi.SideType(strings.ToLower(string(side)))
}
func tradeToGlobal(trade okexapi.Trade) types.Trade {
side := toGlobalSide(trade.Side)
return types.Trade{
ID: uint64(trade.TradeId),
OrderID: uint64(trade.OrderId),
Exchange: types.ExchangeOKEx,
Price: trade.FillPrice,
Quantity: trade.FillSize,
QuoteQuantity: trade.FillPrice.Mul(trade.FillSize),
Symbol: toGlobalSymbol(trade.InstrumentId),
Side: side,
IsBuyer: side == types.SideTypeBuy,
IsMaker: trade.ExecutionType == okexapi.LiquidityTypeMaker,
Time: types.Time(trade.Timestamp),
// The fees obtained from the exchange are negative, hence they are forcibly converted to positive.
Fee: trade.Fee.Abs(),
FeeCurrency: trade.FeeCurrency,
IsMargin: false,
IsFutures: false,
IsIsolated: false,
}
}
func processMarketBuySize(o *okexapi.OrderDetail) (fixedpoint.Value, error) {
switch o.State {
case okexapi.OrderStateLive, okexapi.OrderStateCanceled:
return fixedpoint.Zero, nil
case okexapi.OrderStatePartiallyFilled:
if o.FillPrice.IsZero() {
return fixedpoint.Zero, fmt.Errorf("fillPrice for a partialFilled should not be zero")
}
return o.Size.Div(o.FillPrice), nil
case okexapi.OrderStateFilled:
return o.AccumulatedFillSize, nil
default:
return fixedpoint.Zero, fmt.Errorf("unexpected status: %s", o.State)
}
}
func orderDetailToGlobal(order *okexapi.OrderDetail) (*types.Order, error) {
side := toGlobalSide(order.Side)
orderType, err := toGlobalOrderType(order.OrderType)
if err != nil {
return nil, err
}
timeInForce := types.TimeInForceGTC
switch order.OrderType {
case okexapi.OrderTypeFOK:
timeInForce = types.TimeInForceFOK
case okexapi.OrderTypeIOC:
timeInForce = types.TimeInForceIOC
}
orderStatus, err := toGlobalOrderStatus(order.State)
if err != nil {
return nil, err
}
size := order.Size
if order.Side == okexapi.SideTypeBuy &&
order.OrderType == okexapi.OrderTypeMarket &&
order.TargetCurrency == okexapi.TargetCurrencyQuote {
size, err = processMarketBuySize(order)
if err != nil {
return nil, err
}
}
return &types.Order{
SubmitOrder: types.SubmitOrder{
ClientOrderID: order.ClientOrderId,
Symbol: toGlobalSymbol(order.InstrumentID),
Side: side,
Type: orderType,
Price: order.Price,
Quantity: size,
AveragePrice: order.AvgPrice,
TimeInForce: timeInForce,
},
Exchange: types.ExchangeOKEx,
OrderID: uint64(order.OrderId),
UUID: strconv.FormatInt(int64(order.OrderId), 10),
Status: orderStatus,
OriginalStatus: string(order.State),
ExecutedQuantity: order.AccumulatedFillSize,
IsWorking: order.State.IsWorking(),
CreationTime: types.Time(order.CreatedTime),
UpdateTime: types.Time(order.UpdatedTime),
}, nil
}
func toGlobalOrderStatus(state okexapi.OrderState) (types.OrderStatus, error) {
switch state {
case okexapi.OrderStateCanceled:
return types.OrderStatusCanceled, nil
case okexapi.OrderStateLive:
return types.OrderStatusNew, nil
case okexapi.OrderStatePartiallyFilled:
return types.OrderStatusPartiallyFilled, nil
case okexapi.OrderStateFilled:
return types.OrderStatusFilled, nil
}
return "", fmt.Errorf("unknown or unsupported okex order state: %s", state)
}
func toLocalOrderType(orderType types.OrderType) (okexapi.OrderType, error) {
switch orderType {
case types.OrderTypeMarket:
return okexapi.OrderTypeMarket, nil
case types.OrderTypeLimit:
return okexapi.OrderTypeLimit, nil
case types.OrderTypeLimitMaker:
return okexapi.OrderTypePostOnly, nil
}
return "", fmt.Errorf("unknown or unsupported okex order type: %s", orderType)
}
func toGlobalOrderType(orderType okexapi.OrderType) (types.OrderType, error) {
// IOC, FOK are only allowed with limit order type, so we assume the order type is always limit order for FOK, IOC orders
switch orderType {
case okexapi.OrderTypeMarket:
return types.OrderTypeMarket, nil
case okexapi.OrderTypeLimit, okexapi.OrderTypeFOK, okexapi.OrderTypeIOC:
return types.OrderTypeLimit, nil
case okexapi.OrderTypePostOnly:
return types.OrderTypeLimitMaker, nil
}
return "", fmt.Errorf("unknown or unsupported okex order type: %s", orderType)
}
func toLocalInterval(interval types.Interval) (string, error) {
if _, ok := SupportedIntervals[interval]; !ok {
return "", fmt.Errorf("interval %s is not supported", interval)
}
in, ok := ToLocalInterval[interval]
if !ok {
return "", fmt.Errorf("interval %s is not supported, got local interval %s", interval, in)
}
return in, nil
}
func toGlobalSide(side okexapi.SideType) (s types.SideType) {
switch string(side) {
case "sell":
s = types.SideTypeSell
case "buy":
s = types.SideTypeBuy
}
return s
}
func toGlobalOrder(okexOrder *okexapi.OrderDetails) (*types.Order, error) {
orderID, err := strconv.ParseInt(okexOrder.OrderID, 10, 64)
if err != nil {
return nil, err
}
side := toGlobalSide(okexOrder.Side)
orderType, err := toGlobalOrderType(okexOrder.OrderType)
if err != nil {
return nil, err
}
timeInForce := types.TimeInForceGTC
switch okexOrder.OrderType {
case okexapi.OrderTypeFOK:
timeInForce = types.TimeInForceFOK
case okexapi.OrderTypeIOC:
timeInForce = types.TimeInForceIOC
}
orderStatus, err := toGlobalOrderStatus(okexOrder.State)
if err != nil {
return nil, err
}
isWorking := false
switch orderStatus {
case types.OrderStatusNew, types.OrderStatusPartiallyFilled:
isWorking = true
}
isMargin := false
if okexOrder.InstrumentType == okexapi.InstrumentTypeMARGIN {
isMargin = true
}
return &types.Order{
SubmitOrder: types.SubmitOrder{
ClientOrderID: okexOrder.ClientOrderID,
Symbol: toGlobalSymbol(okexOrder.InstrumentID),
Side: side,
Type: orderType,
Price: okexOrder.Price,
Quantity: okexOrder.Quantity,
StopPrice: fixedpoint.Zero, // not supported yet
TimeInForce: timeInForce,
},
Exchange: types.ExchangeOKEx,
OrderID: uint64(orderID),
Status: orderStatus,
ExecutedQuantity: okexOrder.FilledQuantity,
IsWorking: isWorking,
CreationTime: types.Time(okexOrder.CreationTime),
UpdateTime: types.Time(okexOrder.UpdateTime),
IsMargin: isMargin,
IsIsolated: false,
}, nil
}