-
-
Notifications
You must be signed in to change notification settings - Fork 300
/
Copy pathstrategy.go
269 lines (216 loc) · 7.04 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
package marketcap
import (
"context"
"fmt"
"os"
"github.com/sirupsen/logrus"
"github.com/c9s/bbgo/pkg/bbgo"
"github.com/c9s/bbgo/pkg/datasource/coinmarketcap"
"github.com/c9s/bbgo/pkg/datatype/floats"
"github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/types"
)
const ID = "marketcap"
var log = logrus.WithField("strategy", ID)
func init() {
bbgo.RegisterStrategy(ID, &Strategy{})
}
type Strategy struct {
datasource *coinmarketcap.DataSource
// interval to rebalance the portfolio
Interval types.Interval `json:"interval"`
QuoteCurrency string `json:"quoteCurrency"`
QuoteCurrencyWeight fixedpoint.Value `json:"quoteCurrencyWeight"`
BaseCurrencies []string `json:"baseCurrencies"`
Threshold fixedpoint.Value `json:"threshold"`
// max amount to buy or sell per order
MaxAmount fixedpoint.Value `json:"maxAmount"`
// interval to query marketcap data from coinmarketcap
QueryInterval types.Interval `json:"queryInterval"`
OrderType types.OrderType `json:"orderType"`
DryRun bool `json:"dryRun"`
subscribeSymbol string
activeOrderBook *bbgo.ActiveOrderBook
targetWeights types.ValueMap
}
func (s *Strategy) Defaults() error {
if s.OrderType == "" {
s.OrderType = types.OrderTypeLimitMaker
}
return nil
}
func (s *Strategy) Initialize() error {
apiKey := os.Getenv("COINMARKETCAP_API_KEY")
s.datasource = coinmarketcap.New(apiKey)
// select one symbol to subscribe
s.subscribeSymbol = s.BaseCurrencies[0] + s.QuoteCurrency
s.activeOrderBook = bbgo.NewActiveOrderBook("")
s.targetWeights = types.ValueMap{}
return nil
}
func (s *Strategy) ID() string {
return ID
}
func (s *Strategy) Validate() error {
if len(s.BaseCurrencies) == 0 {
return fmt.Errorf("taretCurrencies should not be empty")
}
for _, c := range s.BaseCurrencies {
if c == s.QuoteCurrency {
return fmt.Errorf("targetCurrencies contain baseCurrency")
}
}
if s.Threshold.Sign() < 0 {
return fmt.Errorf("threshold should not less than 0")
}
if s.MaxAmount.Sign() < 0 {
return fmt.Errorf("maxAmount shoud not less than 0")
}
return nil
}
func (s *Strategy) Subscribe(session *bbgo.ExchangeSession) {
symbol := s.BaseCurrencies[0] + s.QuoteCurrency
session.Subscribe(types.KLineChannel, symbol, types.SubscribeOptions{Interval: s.Interval})
session.Subscribe(types.KLineChannel, symbol, types.SubscribeOptions{Interval: s.QueryInterval})
}
func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) error {
s.activeOrderBook.BindStream(session.UserDataStream)
s.updateTargetWeights(ctx)
session.MarketDataStream.OnKLineClosed(func(kline types.KLine) {
if kline.Interval == s.QueryInterval {
s.updateTargetWeights(ctx)
}
if kline.Interval == s.Interval {
s.rebalance(ctx, orderExecutor, session)
}
})
return nil
}
func (s *Strategy) rebalance(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) {
if err := orderExecutor.CancelOrders(ctx, s.activeOrderBook.Orders()...); err != nil {
log.WithError(err).Error("failed to cancel orders")
}
submitOrders := s.generateSubmitOrders(ctx, session)
for _, submitOrder := range submitOrders {
log.Infof("generated submit order: %s", submitOrder.String())
}
if s.DryRun {
return
}
createdOrders, err := orderExecutor.SubmitOrders(ctx, submitOrders...)
if err != nil {
log.WithError(err).Error("failed to submit orders")
return
}
s.activeOrderBook.Add(createdOrders...)
}
func (s *Strategy) generateSubmitOrders(ctx context.Context, session *bbgo.ExchangeSession) (submitOrders []types.SubmitOrder) {
prices := s.prices(ctx, session)
marketValues := prices.Mul(s.quantities(session))
currentWeights := marketValues.Normalize()
for currency, targetWeight := range s.targetWeights {
if currency == s.QuoteCurrency {
continue
}
symbol := currency + s.QuoteCurrency
currentWeight := currentWeights[currency]
currentPrice := prices[currency]
log.Infof("%s price: %v, current weight: %v, target weight: %v",
symbol,
currentPrice,
currentWeight,
targetWeight)
// calculate the difference between current weight and target weight
// if the difference is less than threshold, then we will not create the order
weightDifference := targetWeight.Sub(currentWeight)
if weightDifference.Abs().Compare(s.Threshold) < 0 {
log.Infof("%s weight distance |%v - %v| = |%v| less than the threshold: %v",
symbol,
currentWeight,
targetWeight,
weightDifference,
s.Threshold)
continue
}
quantity := weightDifference.Mul(marketValues.Sum()).Div(currentPrice)
side := types.SideTypeBuy
if quantity.Sign() < 0 {
side = types.SideTypeSell
quantity = quantity.Abs()
}
if s.MaxAmount.Sign() > 0 {
quantity = bbgo.AdjustQuantityByMaxAmount(quantity, currentPrice, s.MaxAmount)
log.Infof("adjust the quantity %v (%s %s @ %v) by max amount %v",
quantity,
symbol,
side.String(),
currentPrice,
s.MaxAmount)
}
order := types.SubmitOrder{
Symbol: symbol,
Side: side,
Type: s.OrderType,
Quantity: quantity,
Price: currentPrice,
}
submitOrders = append(submitOrders, order)
}
return submitOrders
}
func (s *Strategy) updateTargetWeights(ctx context.Context) {
m := floats.Map{}
// get marketcap from coinmarketcap
// set higher query limit to avoid target currency not in the list
marketcaps, err := s.datasource.QueryMarketCapInUSD(ctx, 100)
if err != nil {
log.WithError(err).Error("failed to query market cap")
}
for _, currency := range s.BaseCurrencies {
m[currency] = marketcaps[currency]
}
// normalize
m = m.Normalize()
// rescale by 1 - baseWeight
m = m.MulScalar(1.0 - s.QuoteCurrencyWeight.Float64())
// append base weight
m[s.QuoteCurrency] = s.QuoteCurrencyWeight.Float64()
// convert to types.ValueMap
for currency, weight := range m {
s.targetWeights[currency] = fixedpoint.NewFromFloat(weight)
}
log.Infof("target weights: %v", s.targetWeights)
}
func (s *Strategy) prices(ctx context.Context, session *bbgo.ExchangeSession) types.ValueMap {
tickers, err := session.Exchange.QueryTickers(ctx, s.symbols()...)
if err != nil {
log.WithError(err).Error("failed to query tickers")
return nil
}
prices := types.ValueMap{}
for _, currency := range s.BaseCurrencies {
prices[currency] = tickers[currency+s.QuoteCurrency].Last
}
// append base currency price
prices[s.QuoteCurrency] = fixedpoint.One
return prices
}
func (s *Strategy) quantities(session *bbgo.ExchangeSession) types.ValueMap {
balances := session.Account.Balances()
quantities := types.ValueMap{}
for _, currency := range s.currencies() {
quantities[currency] = balances[currency].Total()
}
return quantities
}
func (s *Strategy) symbols() (symbols []string) {
for _, currency := range s.BaseCurrencies {
symbols = append(symbols, currency+s.QuoteCurrency)
}
return symbols
}
func (s *Strategy) currencies() (currencies []string) {
currencies = append(currencies, s.BaseCurrencies...)
currencies = append(currencies, s.QuoteCurrency)
return currencies
}