2021-10-14 04:04:56 +00:00
|
|
|
package emastop
|
2020-12-03 00:52:32 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
"strings"
|
2020-12-03 01:26:10 +00:00
|
|
|
"sync"
|
2020-12-03 00:52:32 +00:00
|
|
|
|
2020-12-03 01:26:10 +00:00
|
|
|
"github.com/sirupsen/logrus"
|
2020-12-03 00:52:32 +00:00
|
|
|
|
|
|
|
"github.com/c9s/bbgo/pkg/bbgo"
|
|
|
|
"github.com/c9s/bbgo/pkg/fixedpoint"
|
|
|
|
"github.com/c9s/bbgo/pkg/types"
|
|
|
|
)
|
|
|
|
|
2021-10-14 04:04:56 +00:00
|
|
|
const ID = "emastop"
|
2021-02-03 01:08:05 +00:00
|
|
|
|
|
|
|
var log = logrus.WithField("strategy", ID)
|
2020-12-03 01:26:10 +00:00
|
|
|
|
2020-12-03 00:52:32 +00:00
|
|
|
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.
|
2021-02-03 01:08:05 +00:00
|
|
|
bbgo.RegisterStrategy(ID, &Strategy{})
|
2020-12-03 00:52:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type Strategy struct {
|
2020-12-03 01:26:10 +00:00
|
|
|
*bbgo.Graceful
|
|
|
|
|
2020-12-04 11:40:05 +00:00
|
|
|
// The notification system will be injected into the strategy automatically.
|
|
|
|
// This field will be injected automatically since it's a single exchange strategy.
|
|
|
|
*bbgo.Notifiability
|
|
|
|
|
2020-12-03 00:52:32 +00:00
|
|
|
SourceExchangeName string `json:"sourceExchange"`
|
|
|
|
|
|
|
|
TargetExchangeName string `json:"targetExchange"`
|
|
|
|
|
|
|
|
// These fields will be filled from the config file (it translates YAML to JSON)
|
|
|
|
Symbol string `json:"symbol"`
|
|
|
|
|
|
|
|
// Interval is the interval of the kline channel we want to subscribe,
|
|
|
|
// the kline event will trigger the strategy to check if we need to submit order.
|
|
|
|
Interval types.Interval `json:"interval"`
|
|
|
|
|
|
|
|
Quantity fixedpoint.Value `json:"quantity"`
|
|
|
|
|
2020-12-03 01:41:41 +00:00
|
|
|
BalancePercentage fixedpoint.Value `json:"balancePercentage"`
|
|
|
|
|
2020-12-03 00:52:32 +00:00
|
|
|
OrderType string `json:"orderType"`
|
|
|
|
|
|
|
|
PriceRatio fixedpoint.Value `json:"priceRatio"`
|
|
|
|
|
2020-12-03 01:50:36 +00:00
|
|
|
StopPriceRatio fixedpoint.Value `json:"stopPriceRatio"`
|
|
|
|
|
2020-12-03 00:52:32 +00:00
|
|
|
// 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"`
|
|
|
|
|
|
|
|
order types.Order
|
|
|
|
}
|
|
|
|
|
2021-02-03 01:08:05 +00:00
|
|
|
func (s *Strategy) ID() string {
|
|
|
|
return ID
|
|
|
|
}
|
|
|
|
|
2020-12-21 05:40:23 +00:00
|
|
|
func (s *Strategy) Subscribe(session *bbgo.ExchangeSession) {
|
|
|
|
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: s.Interval.String()})
|
|
|
|
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: s.MovingAverageInterval.String()})
|
|
|
|
}
|
|
|
|
|
2020-12-03 01:31:40 +00:00
|
|
|
func (s *Strategy) CrossSubscribe(sessions map[string]*bbgo.ExchangeSession) {
|
2020-12-03 00:52:32 +00:00
|
|
|
sourceSession := sessions[s.SourceExchangeName]
|
2020-12-21 05:40:23 +00:00
|
|
|
s.Subscribe(sourceSession)
|
2020-12-03 00:52:32 +00:00
|
|
|
|
|
|
|
// make sure we have the connection alive
|
|
|
|
targetSession := sessions[s.TargetExchangeName]
|
|
|
|
targetSession.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: s.Interval.String()})
|
|
|
|
}
|
|
|
|
|
2022-03-16 10:25:27 +00:00
|
|
|
func (s *Strategy) clear(ctx context.Context, orderExecutor bbgo.OrderExecutor) {
|
2020-12-03 00:52:32 +00:00
|
|
|
if s.order.OrderID > 0 {
|
2022-03-16 10:25:27 +00:00
|
|
|
if err := orderExecutor.CancelOrders(ctx, s.order); err != nil {
|
2020-12-31 05:07:39 +00:00
|
|
|
log.WithError(err).Errorf("can not cancel trailingstop order: %+v", s.order)
|
2020-12-03 00:52:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// clear out the existing order
|
|
|
|
s.order = types.Order{}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
func (s *Strategy) place(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession, indicator types.Float64Indicator, closePrice fixedpoint.Value) {
|
|
|
|
closePriceF := closePrice.Float64()
|
|
|
|
movingAveragePriceF := indicator.Last()
|
2020-12-03 00:52:32 +00:00
|
|
|
|
|
|
|
// skip it if it's near zero because it's not loaded yet
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
if movingAveragePriceF < 0.0001 {
|
|
|
|
log.Warnf("moving average price is near 0: %f", movingAveragePriceF)
|
2020-12-03 00:52:32 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// place stop limit order only when the closed price is greater than the moving average price
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
if closePriceF <= movingAveragePriceF {
|
|
|
|
log.Warnf("close price %v is less than moving average price %f", closePrice, movingAveragePriceF)
|
2020-12-03 00:52:32 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
movingAveragePrice := fixedpoint.NewFromFloat(movingAveragePriceF)
|
|
|
|
|
|
|
|
var price = fixedpoint.Zero
|
2020-12-03 00:52:32 +00:00
|
|
|
var orderType = types.OrderTypeStopMarket
|
|
|
|
|
|
|
|
switch strings.ToLower(s.OrderType) {
|
|
|
|
case "market":
|
|
|
|
orderType = types.OrderTypeStopMarket
|
|
|
|
case "limit":
|
|
|
|
orderType = types.OrderTypeStopLimit
|
|
|
|
price = movingAveragePrice
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
if s.PriceRatio.Sign() > 0 {
|
|
|
|
price = price.Mul(s.PriceRatio)
|
2020-12-03 00:52:32 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-03 01:41:41 +00:00
|
|
|
market, ok := session.Market(s.Symbol)
|
|
|
|
if !ok {
|
|
|
|
log.Errorf("market not found, symbol %s", s.Symbol)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
quantity := s.Quantity
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
if s.BalancePercentage.Sign() > 0 {
|
2020-12-03 01:41:41 +00:00
|
|
|
|
2022-04-23 07:43:11 +00:00
|
|
|
if balance, ok := session.GetAccount().Balance(market.BaseCurrency); ok {
|
2020-12-03 01:41:41 +00:00
|
|
|
quantity = balance.Available.Mul(s.BalancePercentage)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
amount := quantity.Mul(closePrice)
|
|
|
|
if amount.Compare(market.MinNotional) < 0 {
|
|
|
|
log.Errorf("the amount of stop order (%v) is less than min notional %v", amount, market.MinNotional)
|
2020-12-03 01:41:41 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-12-03 01:50:36 +00:00
|
|
|
var stopPrice = movingAveragePrice
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
if s.StopPriceRatio.Sign() > 0 {
|
|
|
|
stopPrice = stopPrice.Mul(s.StopPriceRatio)
|
2020-12-03 01:50:36 +00:00
|
|
|
}
|
|
|
|
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
log.Infof("placing trailingstop order %s at stop price %v, quantity %v", s.Symbol, stopPrice, quantity)
|
2020-12-03 08:46:02 +00:00
|
|
|
|
2020-12-03 00:52:32 +00:00
|
|
|
retOrders, err := orderExecutor.SubmitOrders(ctx, types.SubmitOrder{
|
|
|
|
Symbol: s.Symbol,
|
|
|
|
Side: types.SideTypeSell,
|
|
|
|
Type: orderType,
|
|
|
|
Price: price,
|
2020-12-03 01:50:36 +00:00
|
|
|
StopPrice: stopPrice,
|
fix bollgrid, emstop, flashcrash, funding, grid, pricealert, pricedrop, rebalance, schedule, swing, xbalance, xgap, xmaker and speedup fixedpoint
2022-02-04 11:39:23 +00:00
|
|
|
Quantity: quantity,
|
2020-12-03 00:52:32 +00:00
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Error("submit order error")
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(retOrders) > 0 {
|
|
|
|
s.order = retOrders[0]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Strategy) handleOrderUpdate(order types.Order) {
|
|
|
|
if order.OrderID == s.order.OrderID {
|
|
|
|
s.order = order
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-14 05:15:08 +00:00
|
|
|
func (s *Strategy) loadIndicator(sourceSession *bbgo.ExchangeSession) (types.Float64Indicator, error) {
|
2020-12-31 09:12:35 +00:00
|
|
|
var standardIndicatorSet, ok = sourceSession.StandardIndicatorSet(s.Symbol)
|
|
|
|
if !ok {
|
|
|
|
return nil, fmt.Errorf("standardIndicatorSet is nil, symbol %s", s.Symbol)
|
|
|
|
}
|
|
|
|
|
|
|
|
var iw = types.IntervalWindow{Interval: s.MovingAverageInterval, Window: s.MovingAverageWindow}
|
|
|
|
|
|
|
|
switch strings.ToUpper(s.MovingAverageType) {
|
|
|
|
case "SMA":
|
|
|
|
return standardIndicatorSet.SMA(iw), nil
|
|
|
|
|
|
|
|
case "EWMA", "EMA":
|
|
|
|
return standardIndicatorSet.EWMA(iw), nil
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil, fmt.Errorf("unsupported moving average type: %s", s.MovingAverageType)
|
|
|
|
}
|
|
|
|
|
2020-12-21 05:40:23 +00:00
|
|
|
func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) error {
|
2020-12-31 09:12:35 +00:00
|
|
|
indicator, err := s.loadIndicator(session)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-05-27 06:45:06 +00:00
|
|
|
session.UserDataStream.OnOrderUpdate(s.handleOrderUpdate)
|
2020-12-31 09:12:35 +00:00
|
|
|
|
2021-05-27 06:45:06 +00:00
|
|
|
// session.UserDataStream.OnKLineClosed
|
2021-05-27 19:13:50 +00:00
|
|
|
session.MarketDataStream.OnKLineClosed(func(kline types.KLine) {
|
2020-12-31 09:12:35 +00:00
|
|
|
// skip k-lines from other symbols
|
|
|
|
if kline.Symbol != s.Symbol || kline.Interval != s.Interval {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
closePrice := kline.Close
|
|
|
|
|
|
|
|
// ok, it's our call, we need to cancel the stop limit order first
|
2022-03-16 10:25:27 +00:00
|
|
|
s.clear(ctx, orderExecutor)
|
2020-12-31 09:12:35 +00:00
|
|
|
s.place(ctx, orderExecutor, session, indicator, closePrice)
|
|
|
|
})
|
|
|
|
|
|
|
|
s.Graceful.OnShutdown(func(ctx context.Context, wg *sync.WaitGroup) {
|
|
|
|
defer wg.Done()
|
|
|
|
log.Infof("canceling trailingstop order...")
|
2022-03-16 10:25:27 +00:00
|
|
|
s.clear(ctx, orderExecutor)
|
2020-12-31 09:12:35 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
if lastPrice, ok := session.LastPrice(s.Symbol); ok {
|
|
|
|
s.place(ctx, orderExecutor, session, indicator, lastPrice)
|
|
|
|
}
|
|
|
|
|
2020-12-21 05:40:23 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-12-03 01:31:40 +00:00
|
|
|
func (s *Strategy) CrossRun(ctx context.Context, _ bbgo.OrderExecutionRouter, sessions map[string]*bbgo.ExchangeSession) error {
|
2020-12-03 00:52:32 +00:00
|
|
|
// source session
|
|
|
|
sourceSession := sessions[s.SourceExchangeName]
|
|
|
|
|
|
|
|
// target exchange
|
|
|
|
session := sessions[s.TargetExchangeName]
|
|
|
|
orderExecutor := bbgo.ExchangeOrderExecutor{
|
|
|
|
Session: session,
|
|
|
|
}
|
|
|
|
|
2020-12-31 09:12:35 +00:00
|
|
|
indicator, err := s.loadIndicator(sourceSession)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2020-12-03 00:52:32 +00:00
|
|
|
}
|
|
|
|
|
2021-05-27 06:45:06 +00:00
|
|
|
session.UserDataStream.OnOrderUpdate(s.handleOrderUpdate)
|
2020-12-03 00:52:32 +00:00
|
|
|
|
2021-05-27 06:45:06 +00:00
|
|
|
// session.UserDataStream.OnKLineClosed
|
2021-05-27 19:13:50 +00:00
|
|
|
sourceSession.MarketDataStream.OnKLineClosed(func(kline types.KLine) {
|
2020-12-03 00:52:32 +00:00
|
|
|
// skip k-lines from other symbols
|
2020-12-31 09:12:35 +00:00
|
|
|
if kline.Symbol != s.Symbol || kline.Interval != s.Interval {
|
2020-12-03 00:52:32 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
closePrice := kline.Close
|
|
|
|
|
|
|
|
// ok, it's our call, we need to cancel the stop limit order first
|
2022-03-16 10:25:27 +00:00
|
|
|
s.clear(ctx, &orderExecutor)
|
2020-12-03 01:41:41 +00:00
|
|
|
s.place(ctx, &orderExecutor, session, indicator, closePrice)
|
2020-12-03 00:52:32 +00:00
|
|
|
})
|
2020-12-03 01:26:10 +00:00
|
|
|
|
|
|
|
s.Graceful.OnShutdown(func(ctx context.Context, wg *sync.WaitGroup) {
|
|
|
|
defer wg.Done()
|
2020-12-31 05:07:39 +00:00
|
|
|
log.Infof("canceling trailingstop order...")
|
2022-03-16 10:25:27 +00:00
|
|
|
s.clear(ctx, &orderExecutor)
|
2020-12-03 01:26:10 +00:00
|
|
|
})
|
|
|
|
|
2020-12-08 02:26:20 +00:00
|
|
|
if lastPrice, ok := session.LastPrice(s.Symbol); ok {
|
2020-12-04 11:40:05 +00:00
|
|
|
s.place(ctx, &orderExecutor, session, indicator, lastPrice)
|
|
|
|
}
|
|
|
|
|
2020-12-03 00:52:32 +00:00
|
|
|
return nil
|
|
|
|
}
|