-
Notifications
You must be signed in to change notification settings - Fork 0
/
strategy.go
159 lines (128 loc) · 3.53 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
package random
import (
"context"
"fmt"
"math/rand"
"sync"
"github.com/robfig/cron/v3"
"github.com/sirupsen/logrus"
"github.com/puper/bbgo/pkg/bbgo"
"github.com/puper/bbgo/pkg/strategy/common"
"github.com/puper/bbgo/pkg/types"
)
const ID = "random"
var log = logrus.WithField("strategy", ID)
func init() {
bbgo.RegisterStrategy(ID, &Strategy{})
}
type Strategy struct {
*common.Strategy
Environment *bbgo.Environment
Market types.Market
Symbol string `json:"symbol"`
Schedule string `json:"schedule"`
OnStart bool `json:"onStart"`
DryRun bool `json:"dryRun"`
bbgo.QuantityOrAmount
cron *cron.Cron
}
func (s *Strategy) Defaults() error {
return nil
}
func (s *Strategy) Initialize() error {
s.Strategy = &common.Strategy{}
return nil
}
func (s *Strategy) ID() string {
return ID
}
func (s *Strategy) InstanceID() string {
return fmt.Sprintf("%s:%s", ID, s.Symbol)
}
func (s *Strategy) Validate() error {
if s.Schedule == "" {
return fmt.Errorf("schedule is required")
}
if err := s.QuantityOrAmount.Validate(); err != nil {
return err
}
return nil
}
func (s *Strategy) Subscribe(session *bbgo.ExchangeSession) {}
func (s *Strategy) Run(ctx context.Context, _ bbgo.OrderExecutor, session *bbgo.ExchangeSession) error {
s.Strategy.Initialize(ctx, s.Environment, session, s.Market, s.ID(), s.InstanceID())
session.UserDataStream.OnStart(func() {
if s.OnStart {
s.placeOrder()
}
})
// the shutdown handler, you can cancel all orders
bbgo.OnShutdown(ctx, func(ctx context.Context, wg *sync.WaitGroup) {
defer wg.Done()
_ = s.OrderExecutor.GracefulCancel(ctx)
})
s.cron = cron.New()
s.cron.AddFunc(s.Schedule, s.placeOrder)
s.cron.Start()
return nil
}
func (s *Strategy) placeOrder() {
ctx := context.Background()
baseBalance, ok := s.Session.GetAccount().Balance(s.Market.BaseCurrency)
if !ok {
log.Errorf("base balance not found")
return
}
quoteBalance, ok := s.Session.GetAccount().Balance(s.Market.QuoteCurrency)
if !ok {
log.Errorf("quote balance not found")
return
}
ticker, err := s.Session.Exchange.QueryTicker(ctx, s.Symbol)
if err != nil {
log.WithError(err).Error("query ticker error")
return
}
sellQuantity := s.CalculateQuantity(ticker.Sell)
buyQuantity := s.CalculateQuantity(ticker.Buy)
sellQuantity = s.Market.AdjustQuantityByMinNotional(sellQuantity, ticker.Sell)
buyQuantity = s.Market.AdjustQuantityByMinNotional(buyQuantity, ticker.Buy)
orderForm := []types.SubmitOrder{}
if baseBalance.Available.Compare(sellQuantity) > 0 {
orderForm = append(orderForm, types.SubmitOrder{
Symbol: s.Symbol,
Side: types.SideTypeSell,
Type: types.OrderTypeMarket,
Quantity: sellQuantity,
})
} else {
log.Infof("base balance: %s is not enough", baseBalance.Available.String())
}
if quoteBalance.Available.Div(ticker.Buy).Compare(buyQuantity) > 0 {
orderForm = append(orderForm, types.SubmitOrder{
Symbol: s.Symbol,
Side: types.SideTypeBuy,
Type: types.OrderTypeMarket,
Quantity: buyQuantity,
})
} else {
log.Infof("quote balance: %s is not enough", quoteBalance.Available.String())
}
var order types.SubmitOrder
if len(orderForm) == 0 {
log.Infof("both base and quote balance are not enough, skip submit order")
return
} else {
order = orderForm[rand.Intn(len(orderForm))]
}
log.Infof("submit order: %s", order.String())
if s.DryRun {
log.Infof("dry run, skip submit order")
return
}
_, err = s.OrderExecutor.SubmitOrders(ctx, order)
if err != nil {
log.WithError(err).Error("submit order error")
return
}
}