-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathspot.go
329 lines (310 loc) · 10.2 KB
/
spot.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
package trade
import (
"github.com/beaquant/utils"
"github.com/nntaoli-project/GoEx"
"github.com/sirupsen/logrus"
"math"
"time"
)
type SpotTradeManager struct {
exchange goex.API //交易所
pair goex.CurrencyPair //货币对
opMode OpMode //下单方式:吃单|挂单|挂单等待
maxSpace float64 //挂单失效距离
slidePrice float64 //下单滑动价
maxAmount float64 //开仓最大单次下单量
minStocks float64 //最小交易数量
retryDelayMs time.Duration //失败重试(毫秒)
waitMakeMs int //失败重试(毫秒)
logger *logrus.Logger //logger
priceDot int //价格小数精度
amountDot int //数量小数精度
waitFrozen bool //数量小数精度
}
type OpMode int
const (
OPMODE_TAKE = 1 + iota
OPMODE_MAKE
OPMODE_MAKE_WAIT
)
func (op OpMode) String() string {
switch op {
case OPMODE_TAKE:
return "OPMODE_TAKE"
case OPMODE_MAKE:
return "OPMODE_MAKE"
case OPMODE_MAKE_WAIT:
return "OPMODE_MAKE_WAIT"
default:
return "UNKNOWN"
}
}
type Account struct {
Pair goex.CurrencyPair `json:"pair"`
Balance float64 `json:"balance"`
FrozenBalance float64 `json:"frozen_balance"`
Stocks float64 `json:"stocks"`
FrozenStocks float64 `json:"frozen_stocks"`
}
func NewSportManager(
exchange goex.API,
pair goex.CurrencyPair,
opMode OpMode,
maxSpace float64,
slidePrice float64,
maxAmount float64,
minStocks float64,
retryDelayMs int,
waitMakeMs int,
logger *logrus.Logger,
priceDot int,
amountDot int,
waitFrozen bool,
) *SpotTradeManager {
if logger == nil {
logger = logrus.New()
}
utils.SetDelay(retryDelayMs)
return &SpotTradeManager{
exchange: exchange,
pair: pair,
opMode: opMode,
maxAmount: maxAmount,
maxSpace: maxSpace,
slidePrice: slidePrice,
minStocks: minStocks,
retryDelayMs: time.Duration(retryDelayMs) * time.Millisecond,
waitMakeMs: waitMakeMs,
logger: logger,
priceDot: priceDot,
amountDot: amountDot,
waitFrozen: waitFrozen,
}
}
func (spot *SpotTradeManager) CancelPendingOrders(orderType goex.TradeSide) {
for {
orders := utils.RE(spot.exchange.GetUnfinishOrders, spot.pair).([]goex.Order)
if len(orders) == 0 {
break
}
for j := 0; j < len(orders); j++ {
if orders[j].Side != orderType {
continue
}
spot.exchange.CancelOrder(orders[j].OrderID2, spot.pair)
if j < len(orders)-1 {
time.Sleep(spot.retryDelayMs)
}
}
}
}
func (spot *SpotTradeManager) CancelAllPendingOrders() {
for {
orders := utils.RE(spot.exchange.GetUnfinishOrders, spot.pair).([]goex.Order)
if len(orders) == 0 {
break
}
for j := 0; j < len(orders); j++ {
spot.exchange.CancelOrder(orders[j].OrderID2, spot.pair)
if j < len(orders)-1 {
time.Sleep(spot.retryDelayMs)
}
}
}
}
func (spot *SpotTradeManager) StripOrders(orderId string) *goex.Order {
var order = new(goex.Order)
if orderId == "" {
spot.CancelAllPendingOrders()
}
for {
orders := utils.RE(spot.exchange.GetUnfinishOrders, spot.pair).([]goex.Order)
if len(orders) == 0 {
break
}
var dropped = 0
for j := 0; j < len(orders); j++ {
if orders[j].OrderID2 == orderId {
order = &orders[j]
} else {
spot.exchange.CancelOrder(orders[j].OrderID2, spot.pair)
dropped++
if j < len(orders)-1 {
time.Sleep(spot.retryDelayMs)
}
}
}
if dropped == 0 {
break
}
}
return order
}
func (spot *SpotTradeManager) GetAccount(waitFrozen bool) *Account {
var account = new(Account)
var alreadyAlert = false
for {
acc := utils.RE(spot.exchange.GetAccount).(*goex.Account)
for _, v := range acc.SubAccounts {
if v.Currency == spot.pair.CurrencyB {
account.Balance = v.Amount
account.FrozenBalance = v.ForzenAmount
} else if v.Currency == spot.pair.CurrencyA {
account.Stocks = v.Amount
account.FrozenStocks = v.ForzenAmount
}
}
if !waitFrozen || (account.FrozenStocks < spot.minStocks && account.FrozenBalance < 0.01) {
break
}
if !alreadyAlert {
alreadyAlert = true
spot.logger.Infoln("发现账户有冻结的钱或币", account)
}
time.Sleep(spot.retryDelayMs)
}
account.Pair = spot.pair
return account
}
func (spot *SpotTradeManager) tradeFunc(tradeType goex.TradeSide) (func(amount, price string, currency goex.CurrencyPair) (*goex.Order, error), bool) {
switch tradeType {
case goex.BUY:
return spot.exchange.LimitBuy, true
case goex.SELL:
return spot.exchange.LimitSell, false
case goex.BUY_MARKET:
return spot.exchange.MarketBuy, true
case goex.SELL_MARKET:
return spot.exchange.MarketSell, false
default:
spot.logger.Fatalln("UNKNOWN tradeType")
}
panic("UNKNOWN tradeType")
}
func (spot *SpotTradeManager) trade(opMode OpMode, tradeType goex.TradeSide, tradeAmount float64) *goex.Order {
var initAccount = spot.GetAccount(spot.waitFrozen)
var nowAccount = initAccount
var order *goex.Order = nil
var prePrice = 0.0
var firstPrice = 0.0
var dealAmount = 0.0
var diffMoney = 0.0
var isFirst = true
var err error
var tradeFunc, isBuy = spot.tradeFunc(tradeType)
for {
var ticker = utils.RE(spot.exchange.GetTicker, spot.pair).(*goex.Ticker)
var tradePrice = 0.0
if isBuy {
if opMode == OPMODE_TAKE {
tradePrice = utils.Float64Round(ticker.Sell+spot.slidePrice, spot.priceDot)
} else if opMode == OPMODE_MAKE {
tradePrice = utils.Float64Round(ticker.Buy+spot.slidePrice, spot.priceDot)
} else if opMode == OPMODE_MAKE_WAIT {
tradePrice = utils.Float64Round(ticker.Buy, spot.priceDot)
}
} else {
if opMode == OPMODE_TAKE {
tradePrice = utils.Float64Round(ticker.Buy-spot.slidePrice, spot.priceDot)
} else if opMode == OPMODE_MAKE {
tradePrice = utils.Float64Round(ticker.Sell-spot.slidePrice, spot.priceDot)
} else if opMode == OPMODE_MAKE_WAIT {
tradePrice = utils.Float64Round(ticker.Sell, spot.priceDot)
}
}
if opMode == OPMODE_MAKE_WAIT { //if make_wait fail, change to make
for wait := 0; wait < spot.waitMakeMs/int(spot.retryDelayMs.Nanoseconds()/time.Millisecond.Nanoseconds()); wait++ {
order, err = tradeFunc(utils.Float64RoundString(tradeAmount, spot.amountDot), utils.Float64RoundString(tradePrice, spot.priceDot), spot.pair)
spot.logger.Infof("[ %-4s ] %s @ %s", tradeType.String(), utils.Float64RoundString(tradeAmount, spot.amountDot), utils.Float64RoundString(tradePrice, spot.priceDot))
if err != nil {
time.Sleep(spot.retryDelayMs)
continue
}
for ; wait < spot.waitMakeMs/int(spot.retryDelayMs.Nanoseconds()/time.Millisecond.Nanoseconds()); wait++ {
order = utils.RE(spot.exchange.GetOneOrder, order.OrderID2, spot.pair).(*goex.Order)
if order.Status == goex.ORDER_FINISH {
return order
} else {
time.Sleep(spot.retryDelayMs)
continue
}
}
if wait >= spot.waitMakeMs/int(spot.retryDelayMs.Nanoseconds()/time.Millisecond.Nanoseconds()) && order.Status != goex.ORDER_FINISH {
utils.RE(spot.exchange.CancelOrder, order.OrderID2, spot.pair)
return spot.trade(OPMODE_MAKE, tradeType, tradeAmount-order.DealAmount) //递归
}
}
}
if order == nil {
if isFirst {
isFirst = false
firstPrice = tradePrice
} else {
nowAccount = spot.GetAccount(spot.waitFrozen)
}
var doAmount = 0.0
if isBuy {
diffMoney = utils.Float64Round(initAccount.Balance-nowAccount.Balance, 8)
dealAmount = utils.Float64Round(nowAccount.Stocks-initAccount.Stocks, spot.amountDot*2) // 如果保留小数过少,会引起在小交易量交易时,计算出的成交价格误差较大。
doAmount = math.Min(math.Min(spot.maxAmount, tradeAmount-dealAmount), utils.Float64Round((nowAccount.Balance*0.95)/tradePrice, spot.amountDot))
} else {
diffMoney = utils.Float64Round(nowAccount.Balance-initAccount.Balance, 8)
dealAmount = utils.Float64Round(initAccount.Stocks-nowAccount.Stocks, spot.amountDot*2)
doAmount = math.Min(math.Min(spot.maxAmount, tradeAmount-dealAmount), nowAccount.Stocks)
}
spot.logger.Infoln(tradeType.String(), "diffMoney:", diffMoney, "dealAmount:", dealAmount, "doAmount:", doAmount, "balance:", utils.Float64RoundString(nowAccount.Balance, 8))
if doAmount < spot.minStocks {
break
}
prePrice = tradePrice
order, err = tradeFunc(utils.Float64RoundString(doAmount, spot.amountDot), utils.Float64RoundString(tradePrice, spot.priceDot), spot.pair)
spot.logger.Infof("[ %-4s ] %s @ %s, balance:%s", tradeType.String(),
utils.Float64RoundString(tradeAmount, spot.amountDot),
utils.Float64RoundString(tradePrice, spot.priceDot),
utils.Float64RoundString(nowAccount.Balance, 8),
)
if err != nil {
spot.CancelPendingOrders(tradeType)
}
} else {
if opMode == OPMODE_TAKE || (math.Abs(tradePrice-prePrice) > spot.maxSpace) {
order = nil
spot.CancelAllPendingOrders()
if math.Abs(tradePrice-prePrice) > spot.maxSpace {
spot.logger.Warningf("step over max space, tradePrice:%s, prePrice:%s, spot.maxSpace:%f", utils.Float64RoundString(tradePrice, spot.priceDot), utils.Float64RoundString(prePrice, spot.priceDot), spot.maxSpace)
}
} else {
var ord = spot.StripOrders(order.OrderID2)
if ord == nil {
order = nil
}
}
}
time.Sleep(spot.retryDelayMs)
}
if dealAmount <= 0 {
return nil
}
return &goex.Order{
Side: tradeType,
Currency: spot.pair,
Price: firstPrice,
Amount: tradeAmount,
AvgPrice: utils.Float64Round(diffMoney/dealAmount, spot.priceDot),
DealAmount: utils.Float64Round(dealAmount, spot.amountDot),
}
}
func (spot *SpotTradeManager) Buy(amount float64) *goex.Order {
if amount < spot.minStocks {
spot.logger.Errorf("amount < minStocks : %s < %s", utils.Float64RoundString(amount, spot.amountDot), utils.Float64RoundString(spot.minStocks, spot.amountDot))
return nil
}
return spot.trade(spot.opMode, goex.BUY, amount)
}
func (spot *SpotTradeManager) Sell(amount float64) *goex.Order {
if amount < spot.minStocks {
spot.logger.Errorf("amount < minStocks : %s < %s", utils.Float64RoundString(amount, spot.amountDot), utils.Float64RoundString(spot.minStocks, spot.amountDot))
return nil
}
return spot.trade(spot.opMode, goex.SELL, amount)
}