-
-
Notifications
You must be signed in to change notification settings - Fork 307
/
Copy pathstrategy.go
370 lines (304 loc) · 9.98 KB
/
strategy.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
package xbalance
import (
"context"
"encoding/json"
"fmt"
"sync"
"time"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/slack-go/slack"
"github.com/c9s/bbgo/pkg/bbgo"
"github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/types"
"github.com/c9s/bbgo/pkg/util/templateutil"
"github.com/c9s/bbgo/pkg/util/timejitter"
)
const ID = "xbalance"
const stateKey = "state-v1"
var priceFixer = fixedpoint.NewFromFloat(0.99)
func init() {
bbgo.RegisterStrategy(ID, &Strategy{})
}
type State struct {
Asset string `json:"asset"`
DailyNumberOfTransfers int `json:"dailyNumberOfTransfers,omitempty"`
DailyAmountOfTransfers fixedpoint.Value `json:"dailyAmountOfTransfers,omitempty"`
Since int64 `json:"since"`
}
func (s *State) IsOver24Hours() bool {
return time.Since(time.Unix(s.Since, 0)) >= 24*time.Hour
}
func (s *State) PlainText() string {
return templateutil.Render(`{{ .Asset }} transfer stats:
daily number of transfers: {{ .DailyNumberOfTransfers }}
daily amount of transfers {{ .DailyAmountOfTransfers.Float64 }}`, s)
}
func (s *State) SlackAttachment() slack.Attachment {
return slack.Attachment{
// Pretext: "",
// Text: text,
Title: s.Asset + " Transfer States",
Fields: []slack.AttachmentField{
{Title: "Total Number of Transfers", Value: fmt.Sprintf("%d", s.DailyNumberOfTransfers), Short: true},
{Title: "Total Amount of Transfers", Value: s.DailyAmountOfTransfers.String(), Short: true},
},
Footer: templateutil.Render("Since {{ . }}", time.Unix(s.Since, 0).Format(time.RFC822)),
}
}
func (s *State) Reset() {
var beginningOfTheDay = types.BeginningOfTheDay(time.Now().Local())
*s = State{
DailyNumberOfTransfers: 0,
DailyAmountOfTransfers: fixedpoint.Zero,
Since: beginningOfTheDay.Unix(),
}
}
type WithdrawalRequest struct {
FromSession string `json:"fromSession"`
ToSession string `json:"toSession"`
Asset string `json:"asset"`
Amount fixedpoint.Value `json:"amount"`
}
func (r *WithdrawalRequest) String() string {
return fmt.Sprintf("WITHDRAWAL REQUEST: sending %s %s from %s -> %s",
r.Amount.FormatString(4),
r.Asset,
r.FromSession,
r.ToSession,
)
}
func (r *WithdrawalRequest) PlainText() string {
return fmt.Sprintf("Withdraw request: sending %s %s from %s -> %s",
r.Amount.FormatString(4),
r.Asset,
r.FromSession,
r.ToSession,
)
}
func (r *WithdrawalRequest) SlackAttachment() slack.Attachment {
var color = "#DC143C"
title := templateutil.Render(`Withdraw Request {{ .Asset }}`, r)
return slack.Attachment{
// Pretext: "",
// Text: text,
Title: title,
Color: color,
Fields: []slack.AttachmentField{
{Title: "Asset", Value: r.Asset, Short: true},
{Title: "Amount", Value: r.Amount.FormatString(4), Short: true},
{Title: "From", Value: r.FromSession},
{Title: "To", Value: r.ToSession},
},
Footer: templateutil.Render("Time {{ . }}", time.Now().Format(time.RFC822)),
// FooterIcon: "",
}
}
type Address struct {
Address string `json:"address"`
AddressTag string `json:"addressTag"`
Network string `json:"network"`
ForeignFee fixedpoint.Value `json:"foreignFee"`
}
func (a *Address) UnmarshalJSON(body []byte) error {
var arg interface{}
err := json.Unmarshal(body, &arg)
if err != nil {
return err
}
switch argT := arg.(type) {
case string:
a.Address = argT
return nil
}
type addressTemplate Address
return json.Unmarshal(body, (*addressTemplate)(a))
}
type Strategy struct {
Interval types.Duration `json:"interval"`
Addresses map[string]Address `json:"addresses"`
MaxDailyNumberOfTransfer int `json:"maxDailyNumberOfTransfer"`
MaxDailyAmountOfTransfer fixedpoint.Value `json:"maxDailyAmountOfTransfer"`
CheckOnStart bool `json:"checkOnStart"`
Asset string `json:"asset"`
// Low is the low balance level for triggering transfer
Low fixedpoint.Value `json:"low"`
// Middle is the middle balance level used for re-fill asset
Middle fixedpoint.Value `json:"middle"`
Verbose bool `json:"verbose"`
State *State `persistence:"state"`
}
func (s *Strategy) ID() string {
return ID
}
func (s *Strategy) CrossSubscribe(sessions map[string]*bbgo.ExchangeSession) {}
func (s *Strategy) checkBalance(ctx context.Context, sessions map[string]*bbgo.ExchangeSession) {
if s.Verbose {
bbgo.Notify("📝 Checking %s low balance level exchange session...", s.Asset)
}
var total fixedpoint.Value
for _, session := range sessions {
if b, ok := session.GetAccount().Balance(s.Asset); ok {
total = total.Add(b.Total())
}
}
lowLevelSession, lowLevelBalance, err := s.findLowBalanceLevelSession(sessions)
if err != nil {
bbgo.Notify("Can not find low balance level session: %s", err.Error())
log.WithError(err).Errorf("Can not find low balance level session")
return
}
if lowLevelSession == nil {
if s.Verbose {
bbgo.Notify("✅ All %s balances are looking good, total value: %v", s.Asset, total)
}
return
}
bbgo.Notify("⚠️ Found low level %s balance from session %s: %v", s.Asset, lowLevelSession.Name, lowLevelBalance)
middle := s.Middle
if middle.IsZero() {
middle = total.Div(fixedpoint.NewFromInt(int64(len(sessions)))).Mul(priceFixer)
bbgo.Notify("Total value %v %s, setting middle to %v", total, s.Asset, middle)
}
requiredAmount := middle.Sub(lowLevelBalance.Available)
bbgo.Notify("Need %v %s to satisfy the middle balance level %v", requiredAmount, s.Asset, middle)
fromSession, _, err := s.findHighestBalanceLevelSession(sessions, requiredAmount)
if err != nil || fromSession == nil {
bbgo.Notify("Can not find session with enough balance")
log.WithError(err).Errorf("can not find session with enough balance")
return
}
withdrawalService, ok := fromSession.Exchange.(types.ExchangeWithdrawalService)
if !ok {
log.Errorf("exchange %s does not implement withdrawal service, we can not withdrawal", fromSession.ExchangeName)
return
}
if !fromSession.Withdrawal {
bbgo.Notify("The withdrawal function exchange session %s is not enabled", fromSession.Name)
log.Errorf("The withdrawal function of exchange session %s is not enabled", fromSession.Name)
return
}
toAddress, ok := s.Addresses[lowLevelSession.Name]
if !ok {
log.Errorf("%s address of session %s not found", s.Asset, lowLevelSession.Name)
bbgo.Notify("%s address of session %s not found", s.Asset, lowLevelSession.Name)
return
}
if toAddress.ForeignFee.Sign() > 0 {
requiredAmount = requiredAmount.Add(toAddress.ForeignFee)
}
if s.State != nil {
if s.MaxDailyNumberOfTransfer > 0 {
if s.State.DailyNumberOfTransfers >= s.MaxDailyNumberOfTransfer {
bbgo.Notify("⚠️ Exceeded %s max daily number of transfers %d (current %d), skipping transfer...",
s.Asset,
s.MaxDailyNumberOfTransfer,
s.State.DailyNumberOfTransfers)
return
}
}
if s.MaxDailyAmountOfTransfer.Sign() > 0 {
if s.State.DailyAmountOfTransfers.Compare(s.MaxDailyAmountOfTransfer) >= 0 {
bbgo.Notify("⚠️ Exceeded %s max daily amount of transfers %v (current %v), skipping transfer...",
s.Asset,
s.MaxDailyAmountOfTransfer,
s.State.DailyAmountOfTransfers)
return
}
}
}
bbgo.Notify(&WithdrawalRequest{
FromSession: fromSession.Name,
ToSession: lowLevelSession.Name,
Asset: s.Asset,
Amount: requiredAmount,
})
if err := withdrawalService.Withdraw(ctx, s.Asset, requiredAmount, toAddress.Address, &types.WithdrawalOptions{
Network: toAddress.Network,
AddressTag: toAddress.AddressTag,
}); err != nil {
log.WithError(err).Errorf("withdrawal failed")
bbgo.Notify("withdrawal request failed, error: %v", err)
return
}
bbgo.Notify("%s withdrawal request sent", s.Asset)
if s.State != nil {
if s.State.IsOver24Hours() {
s.State.Reset()
}
s.State.DailyNumberOfTransfers += 1
s.State.DailyAmountOfTransfers = s.State.DailyAmountOfTransfers.Add(requiredAmount)
bbgo.Sync(ctx, s)
}
}
func (s *Strategy) findHighestBalanceLevelSession(
sessions map[string]*bbgo.ExchangeSession, requiredAmount fixedpoint.Value,
) (*bbgo.ExchangeSession, types.Balance, error) {
var balance types.Balance
var maxBalanceLevel = fixedpoint.Zero
var maxBalanceSession *bbgo.ExchangeSession = nil
for sessionID := range s.Addresses {
session, ok := sessions[sessionID]
if !ok {
return nil, balance, fmt.Errorf("session %s does not exist", sessionID)
}
if b, ok := session.GetAccount().Balance(s.Asset); ok {
if b.Available.Sub(requiredAmount).Compare(s.Low) > 0 && b.Available.Compare(maxBalanceLevel) > 0 {
maxBalanceLevel = b.Available
maxBalanceSession = session
balance = b
}
}
}
return maxBalanceSession, balance, nil
}
func (s *Strategy) findLowBalanceLevelSession(sessions map[string]*bbgo.ExchangeSession) (*bbgo.ExchangeSession, types.Balance, error) {
var balance types.Balance
for sessionID := range s.Addresses {
session, ok := sessions[sessionID]
if !ok {
return nil, balance, fmt.Errorf("session %s does not exist", sessionID)
}
balance, ok = session.GetAccount().Balance(s.Asset)
if ok {
if balance.Available.Compare(s.Low) <= 0 {
return session, balance, nil
}
}
}
return nil, balance, nil
}
func (s *Strategy) newDefaultState() *State {
return &State{
Asset: s.Asset,
DailyNumberOfTransfers: 0,
DailyAmountOfTransfers: fixedpoint.Zero,
}
}
func (s *Strategy) CrossRun(ctx context.Context, _ bbgo.OrderExecutionRouter, sessions map[string]*bbgo.ExchangeSession) error {
if s.Interval == 0 {
return errors.New("interval can not be zero")
}
if s.State == nil {
s.State = s.newDefaultState()
}
bbgo.OnShutdown(ctx, func(ctx context.Context, wg *sync.WaitGroup) {
defer wg.Done()
})
if s.CheckOnStart {
s.checkBalance(ctx, sessions)
}
go func() {
ticker := time.NewTicker(timejitter.Milliseconds(s.Interval.Duration(), 1000))
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
s.checkBalance(ctx, sessions)
}
}
}()
return nil
}