-
-
Notifications
You must be signed in to change notification settings - Fork 278
/
strategy.go
221 lines (182 loc) · 6.57 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
package techsignal
import (
"context"
"errors"
"strings"
"time"
"github.com/sirupsen/logrus"
"github.com/c9s/bbgo/pkg/exchange/binance"
"github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/bbgo"
"github.com/c9s/bbgo/pkg/types"
)
const ID = "techsignal"
var log = logrus.WithField("strategy", ID)
func init() {
// Register the pointer of the strategy struct,
// so that bbgo knows what struct to be used to unmarshal the configs (YAML or JSON)
// Note: built-in strategies need to imported manually in the bbgo cmd package.
bbgo.RegisterStrategy(ID, &Strategy{})
}
type Strategy struct {
// These fields will be filled from the config file (it translates YAML to JSON)
Symbol string `json:"symbol"`
Market types.Market `json:"-"`
FundingRate *struct {
High fixedpoint.Value `json:"high"`
Neutral fixedpoint.Value `json:"neutral"`
DiffThreshold fixedpoint.Value `json:"diffThreshold"`
} `json:"fundingRate"`
SupportDetection []struct {
Interval types.Interval `json:"interval"`
// MovingAverageType is the moving average indicator type that we want to use,
// it could be SMA or EWMA
MovingAverageType string `json:"movingAverageType"`
// MovingAverageInterval is the interval of k-lines for the moving average indicator to calculate,
// it could be "1m", "5m", "1h" and so on. note that, the moving averages are calculated from
// the k-line data we subscribed
MovingAverageInterval types.Interval `json:"movingAverageInterval"`
// MovingAverageWindow is the number of the window size of the moving average indicator.
// The number of k-lines in the window. generally used window sizes are 7, 25 and 99 in the TradingView.
MovingAverageWindow int `json:"movingAverageWindow"`
MinVolume fixedpoint.Value `json:"minVolume"`
MinQuoteVolume fixedpoint.Value `json:"minQuoteVolume"`
} `json:"supportDetection"`
}
func (s *Strategy) ID() string {
return ID
}
func (s *Strategy) Subscribe(session *bbgo.ExchangeSession) {
// session.Subscribe(types.BookChannel, s.Symbol, types.SubscribeOptions{})
for _, detection := range s.SupportDetection {
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{
Interval: detection.Interval,
})
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{
Interval: detection.MovingAverageInterval,
})
}
}
func (s *Strategy) Validate() error {
if len(s.Symbol) == 0 {
return errors.New("symbol is required")
}
return nil
}
func (s *Strategy) listenToFundingRate(ctx context.Context, exchange *binance.Exchange) {
var previousIndex, fundingRate24HoursLowIndex *types.PremiumIndex
fundingRateTicker := time.NewTicker(1 * time.Hour)
defer fundingRateTicker.Stop()
for {
select {
case <-ctx.Done():
return
case <-fundingRateTicker.C:
index, err := exchange.QueryPremiumIndex(ctx, s.Symbol)
if err != nil {
log.WithError(err).Error("can not query last funding rate")
continue
}
fundingRate := index.LastFundingRate
if fundingRate.Compare(s.FundingRate.High) >= 0 {
bbgo.Notify("%s funding rate %s is too high! threshold %s",
s.Symbol,
fundingRate.Percentage(),
s.FundingRate.High.Percentage(),
)
} else {
if previousIndex != nil {
if s.FundingRate.DiffThreshold.IsZero() {
// 0.6%
s.FundingRate.DiffThreshold = fixedpoint.NewFromFloat(0.006 * 0.01)
}
diff := fundingRate.Sub(previousIndex.LastFundingRate)
if diff.Abs().Compare(s.FundingRate.DiffThreshold) > 0 {
bbgo.Notify("%s funding rate changed %s, current funding rate %s",
s.Symbol,
diff.SignedPercentage(),
fundingRate.Percentage(),
)
}
}
}
previousIndex = index
if fundingRate24HoursLowIndex != nil {
if fundingRate24HoursLowIndex.Time.Before(time.Now().Add(24 * time.Hour)) {
fundingRate24HoursLowIndex = index
}
if fundingRate.Compare(fundingRate24HoursLowIndex.LastFundingRate) < 0 {
fundingRate24HoursLowIndex = index
}
} else {
fundingRate24HoursLowIndex = index
}
}
}
}
func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) error {
standardIndicatorSet := session.StandardIndicatorSet(s.Symbol)
if s.FundingRate != nil {
if binanceExchange, ok := session.Exchange.(*binance.Exchange); ok {
go s.listenToFundingRate(ctx, binanceExchange)
} else {
log.Error("exchange does not support funding rate api")
}
}
session.MarketDataStream.OnKLineClosed(func(kline types.KLine) {
// skip k-lines from other symbols
if kline.Symbol != s.Symbol {
return
}
for _, detection := range s.SupportDetection {
if kline.Interval != detection.Interval {
continue
}
closePrice := kline.GetClose()
var ma types.Float64Indicator
switch strings.ToLower(detection.MovingAverageType) {
case "sma":
ma = standardIndicatorSet.SMA(types.IntervalWindow{
Interval: detection.MovingAverageInterval,
Window: detection.MovingAverageWindow,
})
case "ema", "ewma":
ma = standardIndicatorSet.EWMA(types.IntervalWindow{
Interval: detection.MovingAverageInterval,
Window: detection.MovingAverageWindow,
})
default:
ma = standardIndicatorSet.EWMA(types.IntervalWindow{
Interval: detection.MovingAverageInterval,
Window: detection.MovingAverageWindow,
})
}
var lastMA = ma.Last()
// skip if the closed price is above the moving average
if closePrice.Float64() > lastMA {
log.Infof("skip %s support closed price %f > last ma %f", s.Symbol, closePrice.Float64(), lastMA)
return
}
prettyBaseVolume := s.Market.BaseCurrencyFormatter()
prettyQuoteVolume := s.Market.QuoteCurrencyFormatter()
if detection.MinVolume.Sign() > 0 && kline.Volume.Compare(detection.MinVolume) > 0 {
bbgo.Notify("Detected %s %s support base volume %s > min base volume %s, quote volume %s",
s.Symbol, detection.Interval.String(),
prettyBaseVolume.FormatMoney(kline.Volume.Trunc()),
prettyBaseVolume.FormatMoney(detection.MinVolume.Trunc()),
prettyQuoteVolume.FormatMoney(kline.QuoteVolume.Trunc()),
)
bbgo.Notify(kline)
} else if detection.MinQuoteVolume.Sign() > 0 && kline.QuoteVolume.Compare(detection.MinQuoteVolume) > 0 {
bbgo.Notify("Detected %s %s support quote volume %s > min quote volume %s, base volume %s",
s.Symbol, detection.Interval.String(),
prettyQuoteVolume.FormatMoney(kline.QuoteVolume.Trunc()),
prettyQuoteVolume.FormatMoney(detection.MinQuoteVolume.Trunc()),
prettyBaseVolume.FormatMoney(kline.Volume.Trunc()),
)
bbgo.Notify(kline)
}
}
})
return nil
}