-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcommon.go
462 lines (434 loc) · 10.6 KB
/
common.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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
package banexg
import (
"fmt"
"github.com/banbox/banexg/bntp"
"github.com/banbox/banexg/errs"
"github.com/banbox/banexg/log"
"github.com/banbox/banexg/utils"
"go.uber.org/zap"
"math"
"math/rand"
"sort"
"strconv"
"strings"
)
func (p *Precision) ToString() string {
return fmt.Sprintf("%v-%v-%v-%v", p.Amount, p.Price, p.Base, p.Quote)
}
func (r *LimitRange) ToString() string {
return fmt.Sprintf("[%v-%v]", r.Min, r.Max)
}
func (l *MarketLimits) ToString() string {
if l == nil {
return ""
}
var b strings.Builder
if l.Leverage != nil {
b.WriteString("l:")
b.WriteString(l.Leverage.ToString())
}
if l.Amount != nil {
b.WriteString("a:")
b.WriteString(l.Amount.ToString())
}
if l.Price != nil {
b.WriteString("p:")
b.WriteString(l.Price.ToString())
}
if l.Cost != nil {
b.WriteString("c:")
b.WriteString(l.Cost.ToString())
}
if l.Market != nil {
b.WriteString("m:")
b.WriteString(l.Market.ToString())
}
return b.String()
}
func (l *CodeLimits) ToString() string {
if l == nil {
return ""
}
var b strings.Builder
if l.Amount != nil {
b.WriteString("a:")
b.WriteString(l.Amount.ToString())
}
if l.Withdraw != nil {
b.WriteString("w:")
b.WriteString(l.Withdraw.ToString())
}
if l.Deposit != nil {
b.WriteString("d:")
b.WriteString(l.Deposit.ToString())
}
return b.String()
}
func (b *Balances) Init() *Balances {
if b.TimeStamp == 0 {
b.TimeStamp = bntp.UTCStamp()
}
if b.Free == nil {
b.Free = map[string]float64{}
}
if b.Used == nil {
b.Used = map[string]float64{}
}
if b.Total == nil {
b.Total = map[string]float64{}
}
for code, ast := range b.Assets {
if ast.Total == 0 {
ast.Total = ast.Used + ast.Free
}
b.Free[code] = ast.Free
b.Used[code] = ast.Used
b.Total[code] = ast.Total
}
return b
}
func (a *Asset) IsEmpty() bool {
return utils.EqualNearly(a.Used+a.Free, 0) && utils.EqualNearly(a.Debt, 0)
}
func (b *OrderBook) SetSide(text string, isBuy, replace bool) {
var arr = make([][2]string, 0)
err := utils.UnmarshalString(text, &arr, utils.JsonNumDefault)
if err != nil {
log.Error("unmarshal od book side fail", zap.Error(err))
return
}
side := b.Asks
if isBuy {
side = b.Bids
}
if replace {
var prices = make([]float64, len(arr))
var sizes = make([]float64, len(arr))
for i, row := range arr {
prices[i], _ = strconv.ParseFloat(row[0], 64)
sizes[i], _ = strconv.ParseFloat(row[1], 64)
}
side.Lock.Lock()
side.Price = prices
side.Size = sizes
side.Lock.Unlock()
} else {
var valArr = make([][2]float64, len(arr))
for i, row := range arr {
val1, _ := strconv.ParseFloat(row[0], 64)
val2, _ := strconv.ParseFloat(row[1], 64)
valArr[i][0] = val1
valArr[i][1] = val2
}
side.Update(valArr)
}
}
func NewOdBookSide(isBuy bool, depth int, deltas [][2]float64) *OdBookSide {
obs := &OdBookSide{
IsBuy: isBuy,
Depth: depth,
Price: make([]float64, 0, len(deltas)),
Size: make([]float64, 0, len(deltas)),
}
obs.Update(deltas)
return obs
}
func (obs *OdBookSide) Update(deltas [][2]float64) {
obs.Lock.Lock()
for _, delta := range deltas {
obs.Set(delta[0], delta[1])
}
for len(obs.Price) > obs.Depth {
obs.Size = obs.Size[:obs.Depth]
obs.Price = obs.Price[:obs.Depth]
}
obs.Lock.Unlock()
}
func (obs *OdBookSide) Set(price, size float64) {
oldLen := len(obs.Price)
prices := obs.Price
var index int
if obs.IsBuy {
// desc order
index = sort.Search(oldLen, func(i int) bool {
return prices[i] <= price
})
} else {
// asc order
index = sort.Search(oldLen, func(i int) bool {
return prices[i] >= price
})
}
if size > 0 {
if index < oldLen && prices[index] == price {
obs.Size[index] = size
} else {
obs.Price = append(prices, 0)
copy(obs.Price[index+1:], prices[index:])
obs.Price[index] = price
obs.Size = append(obs.Size, 0)
copy(obs.Size[index+1:], obs.Size[index:])
obs.Size[index] = size
}
} else if index < oldLen && prices[index] == price {
obs.Price = append(prices[:index], prices[index+1:]...)
obs.Size = append(obs.Size[:index], obs.Size[index+1:]...)
}
}
/*
SumVolTo return (total volume to price, filled rate)
*/
func (obs *OdBookSide) SumVolTo(price float64) (float64, float64) {
dirt := float64(1)
if obs.IsBuy {
dirt = float64(-1)
}
if len(obs.Price) == 0 {
return 0, 1
}
obs.Lock.Lock()
volSum := float64(0)
lastPrice := float64(0)
firstPrice := obs.Price[0]
for i, p := range obs.Price {
lastPrice = p
priceDiff := p - price
if priceDiff*dirt >= 0 {
obs.Lock.Unlock()
return volSum, 1
}
volSum += obs.Size[i]
}
obs.Lock.Unlock()
return volSum, math.Abs(lastPrice-firstPrice) / math.Abs(price-firstPrice)
}
/*
Level
return price&size for given level (i is started from 0)
*/
func (obs *OdBookSide) Level(i int) (float64, float64) {
var price, amount = float64(0), float64(0)
obs.Lock.Lock()
if len(obs.Price) > i {
price = obs.Price[i]
}
if len(obs.Size) > i {
amount = obs.Size[i]
}
obs.Lock.Unlock()
return price, amount
}
/*
AvgPrice
return average price, filled rate, change rate of first & last
*/
func (obs *OdBookSide) AvgPrice(volume float64) (float64, float64, float64) {
obs.Lock.Lock()
prices, sizes := obs.Price, obs.Size
obs.Lock.Unlock()
volSum, lastPrice, cost := float64(0), float64(0), float64(0)
for i, price := range prices {
size := sizes[i]
volSum += size
lastPrice = price
cost += size * price
if volSum >= volume {
break
}
}
if volSum == 0 {
return 0, 0, 0
}
price0 := prices[0]
if volSum < volume {
lastPrice = price0 + (lastPrice-price0)*volume/volSum
chgRate := math.Abs(lastPrice-price0) / price0
return price0*0.3 + lastPrice*0.7, volSum / volume, chgRate
}
chgRate := math.Abs(lastPrice-price0) / price0
return cost / volSum, 1, chgRate
}
func (b *OrderBook) AvgPrice(side string, depth float64) (float64, float64, float64) {
book := b.Asks
if side == OdSideBuy {
book = b.Bids
}
return book.AvgPrice(depth)
}
/*
SumVolTo
get sum volume between current price and target price
second return val is rate filled
*/
func (b *OrderBook) SumVolTo(side string, price float64) (float64, float64) {
book := b.Asks
if side == OdSideBuy {
book = b.Bids
}
return book.SumVolTo(price)
}
func (b *OrderBook) Reset() {
b.Asks.Lock.Lock()
b.Bids.Lock.Lock()
b.Nonce = 0
b.Bids.Size = nil
b.Bids.Price = nil
b.Asks.Size = nil
b.Asks.Price = nil
b.Cache = nil
b.Bids.Lock.Unlock()
b.Asks.Lock.Unlock()
}
func (b *OrderBook) Update(book *OrderBook) {
b.TimeStamp = book.TimeStamp
b.Nonce = book.Nonce
b.Cache = nil
b.Asks.Lock.Lock()
b.Bids.Lock.Lock()
b.Asks.Price = book.Asks.Price
b.Asks.Size = book.Asks.Size
b.Bids.Price = book.Bids.Price
b.Bids.Size = book.Bids.Size
b.Bids.Lock.Unlock()
b.Asks.Lock.Unlock()
}
func (k *Kline) Clone() *Kline {
return &Kline{
Time: k.Time,
Open: k.Open,
High: k.High,
Low: k.Low,
Close: k.Close,
Volume: k.Volume,
Info: k.Info,
}
}
func EnsureArrStr(text string) string {
text = strings.TrimSpace(text)
if text == "" {
return "[]"
} else if strings.HasPrefix(text, "[") {
return text
}
return strings.Join([]string{"[", text, "]"}, "")
}
/*
MergeMyTrades
将WatchMyTrades收到的同Symbol+Order的交易,合并为Order
*/
func MergeMyTrades(trades []*MyTrade) (*Order, *errs.Error) {
if len(trades) == 0 {
return nil, nil
}
sort.Slice(trades, func(i, j int) bool {
return trades[i].Timestamp < trades[j].Timestamp
})
first := trades[0]
od := &Order{
ID: first.Order,
ClientOrderID: first.ClientID,
Datetime: utils.ISO8601(first.Timestamp),
Timestamp: first.Timestamp,
LastTradeTimestamp: first.Timestamp,
LastUpdateTimestamp: first.Timestamp,
Status: "",
Symbol: first.Symbol,
Type: first.Type,
PositionSide: first.PosSide,
Side: first.Side,
Price: first.Price,
Average: first.Average,
Amount: first.Amount,
Filled: first.Filled,
Remaining: 0,
Cost: first.Cost,
ReduceOnly: first.ReduceOnly,
Trades: make([]*Trade, 0, len(trades)),
Fee: &Fee{},
}
od.Trades = append(od.Trades, &first.Trade)
if first.Fee != nil {
od.Fee.Cost = first.Fee.Cost
od.Fee.Currency = first.Fee.Currency
od.Fee.IsMaker = first.Fee.IsMaker
od.Fee.Rate = first.Fee.Rate
}
var statusDone bool
for _, trade := range trades[1:] {
if trade.Amount == 0 {
continue
}
if trade.Symbol != od.Symbol || trade.Order != od.ID || trade.Side != od.Side {
msg := fmt.Sprintf("all trades to merge must be same pair, orderId, side, %s %s %s %s %s %s",
trade.Symbol, od.Symbol, trade.Order, od.ID, trade.Side, od.Side)
return nil, errs.NewMsg(errs.CodeParamInvalid, msg)
}
od.LastTradeTimestamp = trade.Timestamp
od.LastUpdateTimestamp = trade.Timestamp
od.Amount += trade.Amount
od.Filled = trade.Filled
od.Cost += trade.Cost
od.Average = trade.Average
od.Price = trade.Average
od.ReduceOnly = od.ReduceOnly && trade.ReduceOnly
od.Trades = append(od.Trades, &trade.Trade)
if trade.Fee != nil {
od.Fee.Cost += trade.Fee.Cost
od.Fee.Currency = trade.Fee.Currency
od.Fee.IsMaker = trade.Fee.IsMaker
od.Fee.Rate = trade.Fee.Rate
}
if !statusDone {
od.Status = trade.State
statusDone = IsOrderDone(trade.State)
}
}
if od.Average == 0 && od.Filled > 0 {
od.Average = od.Cost / od.Filled
od.Price = od.Average
}
return od, nil
}
func IsOrderDone(status string) bool {
return status == OdStatusFilled || status == OdStatusCanceled || status == OdStatusExpired || status == OdStatusRejected
}
func (m *Market) GetTradeTimes() [][2]int64 {
times := make([][2]int64, 0, len(m.DayTimes))
times = append(times, m.DayTimes...)
times = append(times, m.NightTimes...)
sort.Slice(times, func(i, j int) bool {
return times[i][0] < times[j][0]
})
return times
}
func GetHostRetryWait(host string, randAdd bool) int64 {
var waitMS int64
hostWaitLock.Lock()
if until, ok := HostRetryWaits[host]; ok {
waitMS = until - bntp.UTCStamp()
if waitMS < 0 {
delete(HostRetryWaits, host)
} else if randAdd {
// 随机增加10s内延迟,避免全部同一时间发起
randWait := int64(rand.Float32() * 10000)
waitMS += randWait
}
}
hostWaitLock.Unlock()
return waitMS
}
func SetHostRetryWait(host string, waitMS int64) {
hostWaitLock.Lock()
HostRetryWaits[host] = bntp.UTCStamp() + waitMS
hostWaitLock.Unlock()
}
func GetHostFlowChan(host string) chan struct{} {
hostFlowLock.Lock()
out, ok := hostFlowChans[host]
if !ok {
out = make(chan struct{}, HostHttpConcurr)
hostFlowChans[host] = out
}
hostFlowLock.Unlock()
return out
}