2022-07-01 10:38:25 +00:00
|
|
|
package drift
|
|
|
|
|
|
|
|
import (
|
2022-08-03 06:10:56 +00:00
|
|
|
"bytes"
|
2022-07-01 10:38:25 +00:00
|
|
|
"context"
|
2022-07-15 03:30:04 +00:00
|
|
|
"errors"
|
2022-07-01 10:38:25 +00:00
|
|
|
"fmt"
|
2022-07-14 03:46:19 +00:00
|
|
|
"math"
|
2022-07-01 10:38:25 +00:00
|
|
|
"os"
|
2022-08-10 11:36:30 +00:00
|
|
|
"strconv"
|
2022-07-01 10:38:25 +00:00
|
|
|
"sync"
|
2022-09-02 03:05:00 +00:00
|
|
|
"time"
|
2022-07-01 10:38:25 +00:00
|
|
|
|
|
|
|
"github.com/sirupsen/logrus"
|
2022-09-28 11:06:37 +00:00
|
|
|
"go.uber.org/multierr"
|
2022-07-01 10:38:25 +00:00
|
|
|
|
|
|
|
"github.com/c9s/bbgo/pkg/bbgo"
|
2022-08-25 09:31:42 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/datatype/floats"
|
2022-09-27 11:26:59 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/dynamic"
|
2022-07-01 10:38:25 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/fixedpoint"
|
|
|
|
"github.com/c9s/bbgo/pkg/indicator"
|
2022-08-03 08:34:51 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/interact"
|
2022-07-01 10:38:25 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/types"
|
|
|
|
"github.com/c9s/bbgo/pkg/util"
|
|
|
|
)
|
|
|
|
|
|
|
|
const ID = "drift"
|
|
|
|
|
|
|
|
var log = logrus.WithField("strategy", ID)
|
2022-07-14 03:46:19 +00:00
|
|
|
var Four fixedpoint.Value = fixedpoint.NewFromInt(4)
|
|
|
|
var Three fixedpoint.Value = fixedpoint.NewFromInt(3)
|
|
|
|
var Two fixedpoint.Value = fixedpoint.NewFromInt(2)
|
|
|
|
var Delta fixedpoint.Value = fixedpoint.NewFromFloat(0.01)
|
2022-08-10 11:36:30 +00:00
|
|
|
var Fee = 0.0008 // taker fee % * 2, for upper bound
|
2022-07-01 10:38:25 +00:00
|
|
|
|
|
|
|
func init() {
|
|
|
|
bbgo.RegisterStrategy(ID, &Strategy{})
|
|
|
|
}
|
|
|
|
|
2022-09-28 11:06:37 +00:00
|
|
|
func filterErrors(errs []error) (es []error) {
|
|
|
|
for _, e := range errs {
|
|
|
|
if _, ok := e.(types.ZeroAssetError); ok {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if bbgo.ErrExceededSubmitOrderRetryLimit == e {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
es = append(es, e)
|
|
|
|
}
|
|
|
|
return es
|
|
|
|
}
|
|
|
|
|
2022-07-01 10:38:25 +00:00
|
|
|
type Strategy struct {
|
|
|
|
Symbol string `json:"symbol"`
|
|
|
|
|
2022-09-22 04:01:26 +00:00
|
|
|
bbgo.OpenPositionOptions
|
2022-07-01 10:38:25 +00:00
|
|
|
bbgo.StrategyController
|
|
|
|
types.Market
|
|
|
|
types.IntervalWindow
|
2022-09-06 05:43:05 +00:00
|
|
|
bbgo.SourceSelector
|
2022-07-01 10:38:25 +00:00
|
|
|
|
|
|
|
*bbgo.Environment
|
2022-07-14 03:51:55 +00:00
|
|
|
*types.Position `persistence:"position"`
|
|
|
|
*types.ProfitStats `persistence:"profit_stats"`
|
|
|
|
*types.TradeStats `persistence:"trade_stats"`
|
2022-07-01 10:38:25 +00:00
|
|
|
|
2022-10-20 11:03:10 +00:00
|
|
|
MinInterval types.Interval `json:"MinInterval"` // minimum interval referred for doing stoploss/trailing exists and updating highest/lowest
|
|
|
|
|
2022-10-27 08:31:39 +00:00
|
|
|
elapsed *types.Queue
|
2022-10-20 11:03:10 +00:00
|
|
|
priceLines *types.Queue
|
|
|
|
trendLine types.UpdatableSeriesExtend
|
|
|
|
ma types.UpdatableSeriesExtend
|
|
|
|
stdevHigh *indicator.StdDev
|
|
|
|
stdevLow *indicator.StdDev
|
|
|
|
drift *DriftMA
|
|
|
|
atr *indicator.ATR
|
|
|
|
midPrice fixedpoint.Value // the midPrice is the average of bestBid and bestAsk in public orderbook
|
|
|
|
lock sync.RWMutex `ignore:"true"` // lock for midPrice
|
|
|
|
positionLock sync.RWMutex `ignore:"true"` // lock for highest/lowest and p
|
2022-10-27 08:31:39 +00:00
|
|
|
pendingLock sync.Mutex `ignore:"true"`
|
2022-10-20 11:03:10 +00:00
|
|
|
startTime time.Time // trading start time
|
|
|
|
maxCounterBuyCanceled int // the largest counter of the order on the buy side been cancelled. meaning the latest cancelled buy order.
|
|
|
|
maxCounterSellCanceled int // the largest counter of the order on the sell side been cancelled. meaning the latest cancelled sell order.
|
|
|
|
orderPendingCounter map[uint64]int // records the timepoint when the orders are created, using the counter at the time.
|
|
|
|
frameKLine *types.KLine // last kline in Interval
|
|
|
|
klineMin *types.KLine // last kline in MinInterval
|
|
|
|
|
|
|
|
beta float64 // last beta value from trendline's linear regression (previous slope of the trendline)
|
|
|
|
|
|
|
|
Debug bool `json:"debug" modifiable:"true"` // to print debug message or not
|
|
|
|
UseStopLoss bool `json:"useStopLoss" modifiable:"true"` // whether to use stoploss rate to do stoploss
|
|
|
|
UseAtr bool `json:"useAtr" modifiable:"true"` // use atr as stoploss
|
|
|
|
StopLoss fixedpoint.Value `json:"stoploss" modifiable:"true"` // stoploss rate
|
|
|
|
PredictOffset int `json:"predictOffset"` // the lookback length for the prediction using linear regression
|
|
|
|
HighLowVarianceMultiplier float64 `json:"hlVarianceMultiplier" modifiable:"true"` // modifier to set the limit order price
|
|
|
|
NoTrailingStopLoss bool `json:"noTrailingStopLoss" modifiable:"true"` // turn off the trailing exit and stoploss
|
|
|
|
HLRangeWindow int `json:"hlRangeWindow"` // ma window for kline high/low changes
|
|
|
|
SmootherWindow int `json:"smootherWindow"` // window that controls the smoothness of drift
|
|
|
|
FisherTransformWindow int `json:"fisherTransformWindow"` // fisher transform window to filter drift's negative signals
|
|
|
|
ATRWindow int `json:"atrWindow"` // window for atr indicator
|
|
|
|
PendingMinInterval int `json:"pendingMinInterval" modifiable:"true"` // if order not be traded for pendingMinInterval of time, cancel it.
|
|
|
|
NoRebalance bool `json:"noRebalance" modifiable:"true"` // disable rebalance
|
|
|
|
TrendWindow int `json:"trendWindow"` // trendLine is used for rebalancing the position. When trendLine goes up, hold base, otherwise hold quote
|
|
|
|
RebalanceFilter float64 `json:"rebalanceFilter" modifiable:"true"` // beta filter on the Linear Regression of trendLine
|
2022-09-13 11:40:07 +00:00
|
|
|
TrailingCallbackRate []float64 `json:"trailingCallbackRate" modifiable:"true"`
|
|
|
|
TrailingActivationRatio []float64 `json:"trailingActivationRatio" modifiable:"true"`
|
|
|
|
|
2022-10-20 11:03:10 +00:00
|
|
|
buyPrice float64 `persistence:"buy_price"` // price when a long position is opened
|
|
|
|
sellPrice float64 `persistence:"sell_price"` // price when a short position is opened
|
|
|
|
highestPrice float64 `persistence:"highest_price"` // highestPrice when the position is opened
|
|
|
|
lowestPrice float64 `persistence:"lowest_price"` // lowestPrice when the position is opened
|
2022-07-22 04:32:37 +00:00
|
|
|
|
2022-07-15 10:59:37 +00:00
|
|
|
// This is not related to trade but for statistics graph generation
|
|
|
|
// Will deduct fee in percentage from every trade
|
|
|
|
GraphPNLDeductFee bool `json:"graphPNLDeductFee"`
|
2022-10-27 08:31:39 +00:00
|
|
|
CanvasPath string `json:"canvasPath"` // backtest related. the path to store the indicator graph
|
|
|
|
GraphPNLPath string `json:"graphPNLPath"` // backtest related. the path to store the pnl % graph per trade graph.
|
|
|
|
GraphCumPNLPath string `json:"graphCumPNLPath"` // backtest related. the path to store the asset changes in graph
|
|
|
|
GraphElapsedPath string `json:"graphElapsedPath"` // the path to store the elapsed time in ms
|
|
|
|
GenerateGraph bool `json:"generateGraph"` // whether to generate graph when shutdown
|
2022-07-15 10:59:37 +00:00
|
|
|
|
2022-07-05 11:43:05 +00:00
|
|
|
ExitMethods bbgo.ExitMethodSet `json:"exits"`
|
|
|
|
Session *bbgo.ExchangeSession
|
2023-05-04 05:50:01 +00:00
|
|
|
|
|
|
|
*bbgo.FastOrderExecutor
|
2022-07-14 03:46:19 +00:00
|
|
|
|
|
|
|
getLastPrice func() fixedpoint.Value
|
|
|
|
}
|
|
|
|
|
2022-07-01 10:38:25 +00:00
|
|
|
func (s *Strategy) ID() string {
|
|
|
|
return ID
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Strategy) InstanceID() string {
|
2022-08-16 03:50:30 +00:00
|
|
|
return fmt.Sprintf("%s:%s:%v", ID, s.Symbol, bbgo.IsBackTesting)
|
2022-07-01 10:38:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Strategy) Subscribe(session *bbgo.ExchangeSession) {
|
2022-09-06 05:26:17 +00:00
|
|
|
// by default, bbgo only pre-subscribe 1000 klines.
|
|
|
|
// this is not enough if we're subscribing 30m intervals using SerialMarketDataStore
|
2022-07-01 10:38:25 +00:00
|
|
|
|
|
|
|
if !bbgo.IsBackTesting {
|
2022-07-14 04:44:05 +00:00
|
|
|
session.Subscribe(types.BookTickerChannel, s.Symbol, types.SubscribeOptions{})
|
2022-10-20 11:03:10 +00:00
|
|
|
session.Subscribe(types.MarketTradeChannel, s.Symbol, types.SubscribeOptions{})
|
2022-10-19 04:17:44 +00:00
|
|
|
// able to preload
|
|
|
|
if s.MinInterval.Milliseconds() >= types.Interval1s.Milliseconds() && s.MinInterval.Milliseconds()%types.Interval1s.Milliseconds() == 0 {
|
|
|
|
maxWindow := (s.Window + s.SmootherWindow + s.FisherTransformWindow) * (s.Interval.Milliseconds() / s.MinInterval.Milliseconds())
|
|
|
|
bbgo.KLinePreloadLimit = int64((maxWindow/1000 + 1) * 1000)
|
|
|
|
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{
|
|
|
|
Interval: s.MinInterval,
|
|
|
|
})
|
|
|
|
} else {
|
|
|
|
bbgo.KLinePreloadLimit = 0
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
maxWindow := (s.Window + s.SmootherWindow + s.FisherTransformWindow) * (s.Interval.Milliseconds() / s.MinInterval.Milliseconds())
|
|
|
|
bbgo.KLinePreloadLimit = int64((maxWindow/1000 + 1) * 1000)
|
|
|
|
// gave up preload
|
|
|
|
if s.Interval.Milliseconds() < s.MinInterval.Milliseconds() {
|
|
|
|
bbgo.KLinePreloadLimit = 0
|
|
|
|
}
|
|
|
|
log.Errorf("set kLinePreloadLimit to %d, %d %d", bbgo.KLinePreloadLimit, s.Interval.Milliseconds()/s.MinInterval.Milliseconds(), maxWindow)
|
|
|
|
if bbgo.KLinePreloadLimit > 0 {
|
|
|
|
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{
|
|
|
|
Interval: s.MinInterval,
|
|
|
|
})
|
|
|
|
}
|
2022-07-01 10:38:25 +00:00
|
|
|
}
|
2022-07-05 11:43:05 +00:00
|
|
|
s.ExitMethods.SetAndSubscribe(session, s)
|
2022-07-01 10:38:25 +00:00
|
|
|
}
|
|
|
|
|
2022-07-20 10:49:56 +00:00
|
|
|
func (s *Strategy) CurrentPosition() *types.Position {
|
|
|
|
return s.Position
|
|
|
|
}
|
|
|
|
|
2022-11-16 09:10:58 +00:00
|
|
|
func (s *Strategy) SubmitOrder(ctx context.Context, submitOrder types.SubmitOrder) (*types.Order, error) {
|
|
|
|
formattedOrder, err := s.Session.FormatOrder(submitOrder)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2023-03-23 04:58:10 +00:00
|
|
|
createdOrders, errIdx, err := bbgo.BatchPlaceOrder(ctx, s.Session.Exchange, nil, formattedOrder)
|
2022-11-16 09:10:58 +00:00
|
|
|
if len(errIdx) > 0 {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return &createdOrders[0], err
|
|
|
|
}
|
|
|
|
|
2022-09-29 11:31:10 +00:00
|
|
|
const closeOrderRetryLimit = 5
|
|
|
|
|
2022-09-27 11:26:59 +00:00
|
|
|
func (s *Strategy) ClosePosition(ctx context.Context, percentage fixedpoint.Value) error {
|
2022-11-16 09:10:58 +00:00
|
|
|
order := s.Position.NewMarketCloseOrder(percentage)
|
2022-07-12 10:14:57 +00:00
|
|
|
if order == nil {
|
2022-09-27 11:26:59 +00:00
|
|
|
return nil
|
2022-07-20 10:49:56 +00:00
|
|
|
}
|
2022-07-15 10:59:37 +00:00
|
|
|
order.Tag = "close"
|
2022-07-04 12:13:54 +00:00
|
|
|
order.TimeInForce = ""
|
2022-09-29 11:31:10 +00:00
|
|
|
|
2022-09-22 04:01:26 +00:00
|
|
|
order.MarginSideEffect = types.SideEffectTypeAutoRepay
|
2022-09-29 11:31:10 +00:00
|
|
|
for i := 0; i < closeOrderRetryLimit; i++ {
|
|
|
|
price := s.getLastPrice()
|
2022-11-09 08:43:51 +00:00
|
|
|
balances := s.Session.GetAccount().Balances()
|
|
|
|
baseBalance := balances[s.Market.BaseCurrency].Total()
|
2022-09-29 11:31:10 +00:00
|
|
|
if order.Side == types.SideTypeBuy {
|
2022-11-09 08:43:51 +00:00
|
|
|
quoteAmount := balances[s.Market.QuoteCurrency].Total().Div(price)
|
2022-09-29 11:31:10 +00:00
|
|
|
if order.Quantity.Compare(quoteAmount) > 0 {
|
|
|
|
order.Quantity = quoteAmount
|
|
|
|
}
|
|
|
|
} else if order.Side == types.SideTypeSell && order.Quantity.Compare(baseBalance) > 0 {
|
|
|
|
order.Quantity = baseBalance
|
|
|
|
}
|
2022-07-04 12:13:54 +00:00
|
|
|
if s.Market.IsDustQuantity(order.Quantity, price) {
|
2022-09-27 11:26:59 +00:00
|
|
|
return nil
|
2022-07-04 12:13:54 +00:00
|
|
|
}
|
2022-11-16 09:10:58 +00:00
|
|
|
o, err := s.SubmitOrder(ctx, *order)
|
2022-07-04 12:13:54 +00:00
|
|
|
if err != nil {
|
|
|
|
order.Quantity = order.Quantity.Mul(fixedpoint.One.Sub(Delta))
|
|
|
|
continue
|
|
|
|
}
|
2022-11-09 08:43:51 +00:00
|
|
|
|
2022-11-16 09:10:58 +00:00
|
|
|
if o != nil {
|
|
|
|
if o.Status == types.OrderStatusNew || o.Status == types.OrderStatusPartiallyFilled {
|
|
|
|
log.Errorf("created Order when Close: %v", o)
|
2022-11-09 08:43:51 +00:00
|
|
|
}
|
|
|
|
}
|
2022-09-27 11:26:59 +00:00
|
|
|
return nil
|
2022-07-04 12:13:54 +00:00
|
|
|
}
|
2022-09-29 11:31:10 +00:00
|
|
|
return errors.New("exceed retry limit")
|
2022-07-04 12:13:54 +00:00
|
|
|
}
|
|
|
|
|
2022-09-06 05:26:17 +00:00
|
|
|
func (s *Strategy) initIndicators(store *bbgo.SerialMarketDataStore) error {
|
2022-07-28 10:34:12 +00:00
|
|
|
s.ma = &indicator.SMA{IntervalWindow: types.IntervalWindow{Interval: s.Interval, Window: s.HLRangeWindow}}
|
|
|
|
s.stdevHigh = &indicator.StdDev{IntervalWindow: types.IntervalWindow{Interval: s.Interval, Window: s.HLRangeWindow}}
|
|
|
|
s.stdevLow = &indicator.StdDev{IntervalWindow: types.IntervalWindow{Interval: s.Interval, Window: s.HLRangeWindow}}
|
2022-07-25 10:36:22 +00:00
|
|
|
s.drift = &DriftMA{
|
2022-08-23 08:22:45 +00:00
|
|
|
drift: &indicator.WeightedDrift{
|
2022-07-25 10:36:22 +00:00
|
|
|
MA: &indicator.SMA{IntervalWindow: s.IntervalWindow},
|
|
|
|
IntervalWindow: s.IntervalWindow,
|
|
|
|
},
|
|
|
|
ma1: &indicator.EWMA{
|
2022-07-28 10:34:12 +00:00
|
|
|
IntervalWindow: types.IntervalWindow{Interval: s.Interval, Window: s.SmootherWindow},
|
2022-07-25 10:36:22 +00:00
|
|
|
},
|
|
|
|
ma2: &indicator.FisherTransform{
|
2022-07-28 10:34:12 +00:00
|
|
|
IntervalWindow: types.IntervalWindow{Interval: s.Interval, Window: s.FisherTransformWindow},
|
2022-07-25 10:36:22 +00:00
|
|
|
},
|
2022-07-14 03:46:19 +00:00
|
|
|
}
|
2022-07-25 10:36:22 +00:00
|
|
|
s.drift.SeriesBase.Series = s.drift
|
2022-07-28 10:34:12 +00:00
|
|
|
s.atr = &indicator.ATR{IntervalWindow: types.IntervalWindow{Interval: s.Interval, Window: s.ATRWindow}}
|
2022-08-02 11:21:44 +00:00
|
|
|
s.trendLine = &indicator.EWMA{IntervalWindow: types.IntervalWindow{Interval: s.Interval, Window: s.TrendWindow}}
|
|
|
|
|
2022-10-19 04:17:44 +00:00
|
|
|
if bbgo.KLinePreloadLimit == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
2022-07-01 10:38:25 +00:00
|
|
|
klines, ok := store.KLinesOfInterval(s.Interval)
|
2022-09-02 03:05:00 +00:00
|
|
|
klinesLength := len(*klines)
|
|
|
|
if !ok || klinesLength == 0 {
|
2022-07-15 03:30:04 +00:00
|
|
|
return errors.New("klines not exists")
|
2022-07-01 10:38:25 +00:00
|
|
|
}
|
2022-09-22 04:01:26 +00:00
|
|
|
log.Infof("loaded %d klines", klinesLength)
|
2022-07-01 10:38:25 +00:00
|
|
|
for _, kline := range *klines {
|
2022-09-02 03:05:00 +00:00
|
|
|
source := s.GetSource(&kline).Float64()
|
2022-07-19 09:38:42 +00:00
|
|
|
high := kline.High.Float64()
|
|
|
|
low := kline.Low.Float64()
|
|
|
|
s.ma.Update(source)
|
2023-05-31 11:35:44 +00:00
|
|
|
s.stdevHigh.Update(high - s.ma.Last(0))
|
|
|
|
s.stdevLow.Update(s.ma.Last(0) - low)
|
2022-09-16 10:11:36 +00:00
|
|
|
s.drift.Update(source, kline.Volume.Abs().Float64())
|
2022-08-02 11:21:44 +00:00
|
|
|
s.trendLine.Update(source)
|
2022-07-14 05:50:37 +00:00
|
|
|
s.atr.PushK(kline)
|
2022-09-02 03:05:00 +00:00
|
|
|
s.priceLines.Update(source)
|
2022-08-03 06:10:56 +00:00
|
|
|
}
|
2022-08-10 11:36:30 +00:00
|
|
|
if s.frameKLine != nil && klines != nil {
|
|
|
|
s.frameKLine.Set(&(*klines)[len(*klines)-1])
|
2022-08-02 11:21:44 +00:00
|
|
|
}
|
2022-10-19 04:17:44 +00:00
|
|
|
klines, ok = store.KLinesOfInterval(s.MinInterval)
|
2022-09-02 03:05:00 +00:00
|
|
|
klinesLength = len(*klines)
|
|
|
|
if !ok || klinesLength == 0 {
|
2022-08-02 11:21:44 +00:00
|
|
|
return errors.New("klines not exists")
|
|
|
|
}
|
2022-10-19 04:17:44 +00:00
|
|
|
log.Infof("loaded %d klines%s", klinesLength, s.MinInterval)
|
|
|
|
if s.klineMin != nil && klines != nil {
|
|
|
|
s.klineMin.Set(&(*klines)[len(*klines)-1])
|
2022-08-10 11:36:30 +00:00
|
|
|
}
|
2022-07-15 03:30:04 +00:00
|
|
|
return nil
|
|
|
|
}
|
2022-07-01 10:38:25 +00:00
|
|
|
|
2022-10-27 08:31:39 +00:00
|
|
|
func (s *Strategy) smartCancel(ctx context.Context, pricef, atr float64, syscounter int) (int, error) {
|
2023-05-04 05:50:01 +00:00
|
|
|
nonTraded := s.FastOrderExecutor.ActiveMakerOrders().Orders()
|
2022-07-29 06:55:23 +00:00
|
|
|
if len(nonTraded) > 0 {
|
|
|
|
if len(nonTraded) > 1 {
|
|
|
|
log.Errorf("should only have one order to cancel, got %d", len(nonTraded))
|
|
|
|
}
|
|
|
|
toCancel := false
|
|
|
|
|
|
|
|
for _, order := range nonTraded {
|
2022-09-06 10:08:05 +00:00
|
|
|
if order.Status != types.OrderStatusNew && order.Status != types.OrderStatusPartiallyFilled {
|
|
|
|
continue
|
|
|
|
}
|
2022-10-27 08:31:39 +00:00
|
|
|
s.pendingLock.Lock()
|
|
|
|
counter := s.orderPendingCounter[order.OrderID]
|
|
|
|
s.pendingLock.Unlock()
|
|
|
|
|
|
|
|
log.Warnf("%v | counter: %d, system: %d", order, counter, syscounter)
|
|
|
|
if syscounter-counter > s.PendingMinInterval {
|
2022-07-29 06:55:23 +00:00
|
|
|
toCancel = true
|
|
|
|
} else if order.Side == types.SideTypeBuy {
|
2022-08-08 05:55:01 +00:00
|
|
|
// 75% of the probability
|
2022-10-27 08:31:39 +00:00
|
|
|
if order.Price.Float64()+atr*2 <= pricef {
|
2022-07-29 06:55:23 +00:00
|
|
|
toCancel = true
|
|
|
|
}
|
|
|
|
} else if order.Side == types.SideTypeSell {
|
2022-08-08 05:55:01 +00:00
|
|
|
// 75% of the probability
|
2022-10-27 08:31:39 +00:00
|
|
|
if order.Price.Float64()-atr*2 >= pricef {
|
2022-07-29 06:55:23 +00:00
|
|
|
toCancel = true
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
panic("not supported side for the order")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if toCancel {
|
2023-05-04 05:50:01 +00:00
|
|
|
err := s.FastOrderExecutor.Cancel(ctx)
|
2022-11-09 08:43:51 +00:00
|
|
|
s.pendingLock.Lock()
|
|
|
|
counters := s.orderPendingCounter
|
|
|
|
s.orderPendingCounter = make(map[uint64]int)
|
|
|
|
s.pendingLock.Unlock()
|
2022-07-29 06:55:23 +00:00
|
|
|
// TODO: clean orderPendingCounter on cancel/trade
|
2022-10-03 05:00:18 +00:00
|
|
|
for _, order := range nonTraded {
|
2022-11-09 08:43:51 +00:00
|
|
|
counter := counters[order.OrderID]
|
2022-10-20 11:03:10 +00:00
|
|
|
if order.Side == types.SideTypeSell {
|
2022-10-27 08:31:39 +00:00
|
|
|
if s.maxCounterSellCanceled < counter {
|
|
|
|
s.maxCounterSellCanceled = counter
|
2022-10-20 11:03:10 +00:00
|
|
|
}
|
|
|
|
} else {
|
2022-10-27 08:31:39 +00:00
|
|
|
if s.maxCounterBuyCanceled < counter {
|
|
|
|
s.maxCounterBuyCanceled = counter
|
2022-10-20 11:03:10 +00:00
|
|
|
}
|
|
|
|
}
|
2022-07-29 06:55:23 +00:00
|
|
|
}
|
2022-08-10 11:36:30 +00:00
|
|
|
log.Warnf("cancel all %v", err)
|
2022-07-29 06:55:23 +00:00
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return len(nonTraded), nil
|
|
|
|
}
|
|
|
|
|
2022-08-02 11:21:44 +00:00
|
|
|
func (s *Strategy) trailingCheck(price float64, direction string) bool {
|
|
|
|
if s.highestPrice > 0 && s.highestPrice < price {
|
|
|
|
s.highestPrice = price
|
|
|
|
}
|
|
|
|
if s.lowestPrice > 0 && s.lowestPrice > price {
|
|
|
|
s.lowestPrice = price
|
|
|
|
}
|
|
|
|
isShort := direction == "short"
|
2022-09-29 11:15:10 +00:00
|
|
|
if isShort && s.sellPrice == 0 || !isShort && s.buyPrice == 0 {
|
|
|
|
return false
|
|
|
|
}
|
2022-08-02 11:21:44 +00:00
|
|
|
for i := len(s.TrailingCallbackRate) - 1; i >= 0; i-- {
|
|
|
|
trailingCallbackRate := s.TrailingCallbackRate[i]
|
|
|
|
trailingActivationRatio := s.TrailingActivationRatio[i]
|
|
|
|
if isShort {
|
2022-08-10 11:36:30 +00:00
|
|
|
if (s.sellPrice-s.lowestPrice)/s.lowestPrice > trailingActivationRatio {
|
2022-08-02 11:21:44 +00:00
|
|
|
return (price-s.lowestPrice)/s.lowestPrice > trailingCallbackRate
|
|
|
|
}
|
|
|
|
} else {
|
2022-08-10 11:36:30 +00:00
|
|
|
if (s.highestPrice-s.buyPrice)/s.buyPrice > trailingActivationRatio {
|
2022-10-03 05:00:18 +00:00
|
|
|
return (s.highestPrice-price)/s.buyPrice > trailingCallbackRate
|
2022-08-02 11:21:44 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2022-07-27 03:17:33 +00:00
|
|
|
func (s *Strategy) initTickerFunctions(ctx context.Context) {
|
2022-07-14 10:33:47 +00:00
|
|
|
if s.IsBackTesting() {
|
2022-07-14 03:46:19 +00:00
|
|
|
s.getLastPrice = func() fixedpoint.Value {
|
|
|
|
lastPrice, ok := s.Session.LastPrice(s.Symbol)
|
|
|
|
if !ok {
|
|
|
|
log.Error("cannot get lastprice")
|
|
|
|
}
|
|
|
|
return lastPrice
|
2022-07-01 10:38:25 +00:00
|
|
|
}
|
2022-07-14 03:46:19 +00:00
|
|
|
} else {
|
2022-07-15 03:30:04 +00:00
|
|
|
s.Session.MarketDataStream.OnBookTickerUpdate(func(ticker types.BookTicker) {
|
2022-07-14 03:46:19 +00:00
|
|
|
bestBid := ticker.Buy
|
|
|
|
bestAsk := ticker.Sell
|
|
|
|
|
2022-08-15 11:50:34 +00:00
|
|
|
if !util.TryLock(&s.lock) {
|
2022-07-15 03:30:04 +00:00
|
|
|
return
|
2022-07-14 03:46:19 +00:00
|
|
|
}
|
2022-08-15 11:50:34 +00:00
|
|
|
if !bestAsk.IsZero() && !bestBid.IsZero() {
|
|
|
|
s.midPrice = bestAsk.Add(bestBid).Div(Two)
|
|
|
|
} else if !bestAsk.IsZero() {
|
|
|
|
s.midPrice = bestAsk
|
|
|
|
} else {
|
|
|
|
s.midPrice = bestBid
|
|
|
|
}
|
2022-08-10 11:36:30 +00:00
|
|
|
s.lock.Unlock()
|
2022-08-15 11:50:34 +00:00
|
|
|
|
2022-10-20 11:03:10 +00:00
|
|
|
// we removed realtime stoploss and trailingStop.
|
2022-08-15 11:50:34 +00:00
|
|
|
|
2022-07-14 03:46:19 +00:00
|
|
|
})
|
|
|
|
s.getLastPrice = func() (lastPrice fixedpoint.Value) {
|
|
|
|
var ok bool
|
|
|
|
s.lock.RLock()
|
2022-08-10 11:36:30 +00:00
|
|
|
defer s.lock.RUnlock()
|
2022-07-14 03:46:19 +00:00
|
|
|
if s.midPrice.IsZero() {
|
|
|
|
lastPrice, ok = s.Session.LastPrice(s.Symbol)
|
|
|
|
if !ok {
|
|
|
|
log.Error("cannot get lastprice")
|
|
|
|
return lastPrice
|
|
|
|
}
|
2022-07-01 10:38:25 +00:00
|
|
|
} else {
|
2022-07-14 03:46:19 +00:00
|
|
|
lastPrice = s.midPrice
|
2022-07-01 10:38:25 +00:00
|
|
|
}
|
2022-07-14 03:46:19 +00:00
|
|
|
return lastPrice
|
2022-07-01 10:38:25 +00:00
|
|
|
}
|
2022-07-14 03:46:19 +00:00
|
|
|
}
|
2022-07-01 10:38:25 +00:00
|
|
|
|
2022-07-15 03:30:04 +00:00
|
|
|
}
|
|
|
|
|
2022-08-02 11:21:44 +00:00
|
|
|
// Sending new rebalance orders cost too much.
|
|
|
|
// Modify the position instead to expect the strategy itself rebalance on Close
|
2022-08-10 11:36:30 +00:00
|
|
|
func (s *Strategy) Rebalance(ctx context.Context) {
|
2022-08-02 11:21:44 +00:00
|
|
|
price := s.getLastPrice()
|
|
|
|
_, beta := types.LinearRegression(s.trendLine, 3)
|
|
|
|
if math.Abs(beta) > s.RebalanceFilter && math.Abs(s.beta) > s.RebalanceFilter || math.Abs(s.beta) < s.RebalanceFilter && math.Abs(beta) < s.RebalanceFilter {
|
|
|
|
return
|
|
|
|
}
|
2023-05-04 05:50:01 +00:00
|
|
|
balances := s.FastOrderExecutor.Session().GetAccount().Balances()
|
2022-08-02 11:21:44 +00:00
|
|
|
baseBalance := balances[s.Market.BaseCurrency].Total()
|
|
|
|
quoteBalance := balances[s.Market.QuoteCurrency].Total()
|
|
|
|
total := baseBalance.Add(quoteBalance.Div(price))
|
|
|
|
percentage := fixedpoint.One.Sub(Delta)
|
2022-11-16 09:10:58 +00:00
|
|
|
log.Infof("rebalance beta %f %v", beta, s.Position)
|
2022-08-02 11:21:44 +00:00
|
|
|
if beta > s.RebalanceFilter {
|
|
|
|
if total.Mul(percentage).Compare(baseBalance) > 0 {
|
|
|
|
q := total.Mul(percentage).Sub(baseBalance)
|
2022-11-16 09:10:58 +00:00
|
|
|
s.Position.Lock()
|
|
|
|
defer s.Position.Unlock()
|
|
|
|
s.Position.Base = q.Neg()
|
|
|
|
s.Position.Quote = q.Mul(price)
|
|
|
|
s.Position.AverageCost = price
|
2022-08-02 11:21:44 +00:00
|
|
|
}
|
|
|
|
} else if beta <= -s.RebalanceFilter {
|
|
|
|
if total.Mul(percentage).Compare(quoteBalance.Div(price)) > 0 {
|
|
|
|
q := total.Mul(percentage).Sub(quoteBalance.Div(price))
|
2022-11-16 09:10:58 +00:00
|
|
|
s.Position.Lock()
|
|
|
|
defer s.Position.Unlock()
|
|
|
|
s.Position.Base = q
|
|
|
|
s.Position.Quote = q.Mul(price).Neg()
|
|
|
|
s.Position.AverageCost = price
|
2022-08-02 11:21:44 +00:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if total.Div(Two).Compare(quoteBalance.Div(price)) > 0 {
|
|
|
|
q := total.Div(Two).Sub(quoteBalance.Div(price))
|
2022-11-16 09:10:58 +00:00
|
|
|
s.Position.Lock()
|
|
|
|
defer s.Position.Unlock()
|
|
|
|
s.Position.Base = q
|
|
|
|
s.Position.Quote = q.Mul(price).Neg()
|
|
|
|
s.Position.AverageCost = price
|
2022-08-02 11:21:44 +00:00
|
|
|
} else if total.Div(Two).Compare(baseBalance) > 0 {
|
|
|
|
q := total.Div(Two).Sub(baseBalance)
|
2022-11-16 09:10:58 +00:00
|
|
|
s.Position.Lock()
|
|
|
|
defer s.Position.Unlock()
|
|
|
|
s.Position.Base = q.Neg()
|
|
|
|
s.Position.Quote = q.Mul(price)
|
|
|
|
s.Position.AverageCost = price
|
2022-08-02 11:21:44 +00:00
|
|
|
} else {
|
2022-11-16 09:10:58 +00:00
|
|
|
s.Position.Lock()
|
|
|
|
defer s.Position.Unlock()
|
|
|
|
s.Position.Reset()
|
2022-08-02 11:21:44 +00:00
|
|
|
}
|
|
|
|
}
|
2022-11-16 09:10:58 +00:00
|
|
|
log.Infof("rebalanceafter %v %v %v", baseBalance, quoteBalance, s.Position)
|
2022-08-02 11:21:44 +00:00
|
|
|
s.beta = beta
|
|
|
|
}
|
|
|
|
|
2022-08-16 03:30:29 +00:00
|
|
|
func (s *Strategy) CalcAssetValue(price fixedpoint.Value) fixedpoint.Value {
|
|
|
|
balances := s.Session.GetAccount().Balances()
|
|
|
|
return balances[s.Market.BaseCurrency].Total().Mul(price).Add(balances[s.Market.QuoteCurrency].Total())
|
|
|
|
}
|
|
|
|
|
2022-10-27 08:31:39 +00:00
|
|
|
func (s *Strategy) klineHandlerMin(ctx context.Context, kline types.KLine, counter int) {
|
2022-10-19 04:17:44 +00:00
|
|
|
s.klineMin.Set(&kline)
|
2022-09-02 03:05:00 +00:00
|
|
|
if s.Status != types.StrategyStatusRunning {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
// for doing the trailing stoploss during backtesting
|
2023-05-31 11:35:44 +00:00
|
|
|
atr := s.atr.Last(0)
|
2022-09-02 03:05:00 +00:00
|
|
|
price := s.getLastPrice()
|
|
|
|
pricef := price.Float64()
|
|
|
|
|
2022-09-13 11:40:07 +00:00
|
|
|
lowf := math.Min(kline.Low.Float64(), pricef)
|
|
|
|
highf := math.Max(kline.High.Float64(), pricef)
|
|
|
|
s.positionLock.Lock()
|
|
|
|
if s.lowestPrice > 0 && lowf < s.lowestPrice {
|
|
|
|
s.lowestPrice = lowf
|
|
|
|
}
|
|
|
|
if s.highestPrice > 0 && highf > s.highestPrice {
|
|
|
|
s.highestPrice = highf
|
|
|
|
}
|
2022-10-20 11:03:10 +00:00
|
|
|
s.positionLock.Unlock()
|
2022-09-13 11:40:07 +00:00
|
|
|
|
2022-09-02 03:05:00 +00:00
|
|
|
numPending := 0
|
2022-09-13 11:40:07 +00:00
|
|
|
var err error
|
2022-10-27 08:31:39 +00:00
|
|
|
if numPending, err = s.smartCancel(ctx, pricef, atr, counter); err != nil {
|
2022-09-02 03:05:00 +00:00
|
|
|
log.WithError(err).Errorf("cannot cancel orders")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if numPending > 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-10-20 11:03:10 +00:00
|
|
|
if s.NoTrailingStopLoss {
|
2022-09-13 11:40:07 +00:00
|
|
|
return
|
2022-09-02 03:05:00 +00:00
|
|
|
}
|
2022-09-13 11:40:07 +00:00
|
|
|
|
2022-09-29 11:15:10 +00:00
|
|
|
exitCondition := s.CheckStopLoss() || s.trailingCheck(highf, "short") || s.trailingCheck(lowf, "long")
|
|
|
|
if exitCondition {
|
2022-09-02 03:05:00 +00:00
|
|
|
_ = s.ClosePosition(ctx, fixedpoint.One)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-10-27 08:31:39 +00:00
|
|
|
func (s *Strategy) klineHandler(ctx context.Context, kline types.KLine, counter int) {
|
|
|
|
start := time.Now()
|
|
|
|
defer func() {
|
|
|
|
end := time.Now()
|
|
|
|
elapsed := end.Sub(start)
|
|
|
|
s.elapsed.Update(float64(elapsed) / 1000000)
|
|
|
|
}()
|
2022-09-02 03:05:00 +00:00
|
|
|
s.frameKLine.Set(&kline)
|
|
|
|
|
2022-09-22 04:01:26 +00:00
|
|
|
source := s.GetSource(&kline)
|
2022-09-02 03:05:00 +00:00
|
|
|
sourcef := source.Float64()
|
2022-10-27 08:31:39 +00:00
|
|
|
|
2022-09-02 03:05:00 +00:00
|
|
|
s.priceLines.Update(sourcef)
|
2022-11-09 08:43:51 +00:00
|
|
|
s.ma.Update(sourcef)
|
2022-09-02 03:05:00 +00:00
|
|
|
s.trendLine.Update(sourcef)
|
|
|
|
|
2022-10-27 08:31:39 +00:00
|
|
|
s.drift.Update(sourcef, kline.Volume.Abs().Float64())
|
2022-09-02 03:05:00 +00:00
|
|
|
s.atr.PushK(kline)
|
2023-05-31 11:35:44 +00:00
|
|
|
atr := s.atr.Last(0)
|
2022-10-27 08:31:39 +00:00
|
|
|
|
2023-03-23 04:58:10 +00:00
|
|
|
price := kline.Close // s.getLastPrice()
|
2022-09-02 03:05:00 +00:00
|
|
|
pricef := price.Float64()
|
|
|
|
lowf := math.Min(kline.Low.Float64(), pricef)
|
|
|
|
highf := math.Max(kline.High.Float64(), pricef)
|
2022-10-27 08:31:39 +00:00
|
|
|
lowdiff := pricef - lowf
|
2022-09-02 03:05:00 +00:00
|
|
|
s.stdevLow.Update(lowdiff)
|
2022-10-27 08:31:39 +00:00
|
|
|
highdiff := highf - pricef
|
2022-09-02 03:05:00 +00:00
|
|
|
s.stdevHigh.Update(highdiff)
|
2022-10-27 08:31:39 +00:00
|
|
|
|
2022-10-20 11:03:10 +00:00
|
|
|
drift := s.drift.Array(2)
|
2022-10-27 08:31:39 +00:00
|
|
|
|
2022-09-16 10:11:36 +00:00
|
|
|
if len(drift) < 2 || len(drift) < s.PredictOffset {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
ddrift := s.drift.drift.Array(2)
|
|
|
|
if len(ddrift) < 2 || len(ddrift) < s.PredictOffset {
|
|
|
|
return
|
|
|
|
}
|
2022-09-02 03:05:00 +00:00
|
|
|
|
|
|
|
if s.Status != types.StrategyStatusRunning {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-05-31 11:35:44 +00:00
|
|
|
log.Infof("highdiff: %3.2f open: %8v, close: %8v, high: %8v, low: %8v, time: %v %v", s.stdevHigh.Last(0), kline.Open, kline.Close, kline.High, kline.Low, kline.StartTime, kline.EndTime)
|
2022-10-20 11:03:10 +00:00
|
|
|
|
|
|
|
s.positionLock.Lock()
|
2022-09-02 03:05:00 +00:00
|
|
|
if s.lowestPrice > 0 && lowf < s.lowestPrice {
|
|
|
|
s.lowestPrice = lowf
|
|
|
|
}
|
|
|
|
if s.highestPrice > 0 && highf > s.highestPrice {
|
|
|
|
s.highestPrice = highf
|
|
|
|
}
|
2022-10-20 11:03:10 +00:00
|
|
|
s.positionLock.Unlock()
|
2022-09-02 03:05:00 +00:00
|
|
|
|
|
|
|
if !s.NoRebalance {
|
|
|
|
s.Rebalance(ctx)
|
|
|
|
}
|
|
|
|
|
2022-10-20 11:03:10 +00:00
|
|
|
if s.Debug {
|
2023-05-04 05:50:01 +00:00
|
|
|
balances := s.FastOrderExecutor.Session().GetAccount().Balances()
|
2022-10-20 11:03:10 +00:00
|
|
|
bbgo.Notify("source: %.4f, price: %.4f, drift[0]: %.4f, ddrift[0]: %.4f, lowf %.4f, highf: %.4f lowest: %.4f highest: %.4f sp %.4f bp %.4f",
|
|
|
|
sourcef, pricef, drift[0], ddrift[0], atr, lowf, highf, s.lowestPrice, s.highestPrice, s.sellPrice, s.buyPrice)
|
|
|
|
// Notify will parse args to strings and process separately
|
|
|
|
bbgo.Notify("balances: [Total] %v %s [Base] %s(%v %s) [Quote] %s",
|
|
|
|
s.CalcAssetValue(price),
|
|
|
|
s.Market.QuoteCurrency,
|
|
|
|
balances[s.Market.BaseCurrency].String(),
|
|
|
|
balances[s.Market.BaseCurrency].Total().Mul(price),
|
|
|
|
s.Market.QuoteCurrency,
|
|
|
|
balances[s.Market.QuoteCurrency].String(),
|
|
|
|
)
|
|
|
|
}
|
2022-09-02 03:05:00 +00:00
|
|
|
|
2022-09-28 11:06:37 +00:00
|
|
|
shortCondition := drift[1] >= 0 && drift[0] <= 0 || (drift[1] >= drift[0] && drift[1] <= 0) || ddrift[1] >= 0 && ddrift[0] <= 0 || (ddrift[1] >= ddrift[0] && ddrift[1] <= 0)
|
|
|
|
longCondition := drift[1] <= 0 && drift[0] >= 0 || (drift[1] <= drift[0] && drift[1] >= 0) || ddrift[1] <= 0 && ddrift[0] >= 0 || (ddrift[1] <= ddrift[0] && ddrift[1] >= 0)
|
2022-09-02 03:05:00 +00:00
|
|
|
if shortCondition && longCondition {
|
2023-05-31 11:35:44 +00:00
|
|
|
if s.priceLines.Index(1) > s.priceLines.Last(0) {
|
2022-09-02 03:05:00 +00:00
|
|
|
longCondition = false
|
|
|
|
} else {
|
|
|
|
shortCondition = false
|
|
|
|
}
|
|
|
|
}
|
2022-10-20 11:03:10 +00:00
|
|
|
exitCondition := !s.NoTrailingStopLoss && (s.CheckStopLoss() || s.trailingCheck(pricef, "short") || s.trailingCheck(pricef, "long"))
|
2022-09-02 03:05:00 +00:00
|
|
|
|
2022-10-20 11:03:10 +00:00
|
|
|
if exitCondition || longCondition || shortCondition {
|
|
|
|
var err error
|
|
|
|
var hold int
|
2022-10-27 08:31:39 +00:00
|
|
|
if hold, err = s.smartCancel(ctx, pricef, atr, counter); err != nil {
|
2022-09-02 03:05:00 +00:00
|
|
|
log.WithError(err).Errorf("cannot cancel orders")
|
|
|
|
}
|
2022-10-20 11:03:10 +00:00
|
|
|
if hold > 0 {
|
2022-09-28 11:06:37 +00:00
|
|
|
return
|
2022-09-26 11:16:27 +00:00
|
|
|
}
|
2022-10-20 11:03:10 +00:00
|
|
|
} else {
|
2022-10-27 08:31:39 +00:00
|
|
|
if _, err := s.smartCancel(ctx, pricef, atr, counter); err != nil {
|
2022-10-20 11:03:10 +00:00
|
|
|
log.WithError(err).Errorf("cannot cancel orders")
|
|
|
|
}
|
|
|
|
return
|
2022-09-02 03:05:00 +00:00
|
|
|
}
|
2022-11-09 08:43:51 +00:00
|
|
|
if exitCondition {
|
|
|
|
_ = s.ClosePosition(ctx, fixedpoint.One)
|
|
|
|
return
|
|
|
|
}
|
2022-09-22 04:01:26 +00:00
|
|
|
|
2022-09-02 03:05:00 +00:00
|
|
|
if longCondition {
|
2023-05-31 11:35:44 +00:00
|
|
|
source = source.Sub(fixedpoint.NewFromFloat(s.stdevLow.Last(0) * s.HighLowVarianceMultiplier))
|
2022-09-22 04:01:26 +00:00
|
|
|
if source.Compare(price) > 0 {
|
|
|
|
source = price
|
2022-10-03 05:00:18 +00:00
|
|
|
}
|
2022-10-20 11:03:10 +00:00
|
|
|
|
2022-09-22 04:01:26 +00:00
|
|
|
opt := s.OpenPositionOptions
|
|
|
|
opt.Long = true
|
2022-10-20 11:03:10 +00:00
|
|
|
opt.LimitOrder = true
|
|
|
|
// force to use market taker
|
2022-11-09 08:43:51 +00:00
|
|
|
if counter-s.maxCounterBuyCanceled <= s.PendingMinInterval && s.maxCounterBuyCanceled > s.maxCounterSellCanceled {
|
2022-10-20 11:03:10 +00:00
|
|
|
opt.LimitOrder = false
|
2022-11-09 08:43:51 +00:00
|
|
|
source = price
|
2022-10-20 11:03:10 +00:00
|
|
|
}
|
2022-09-22 04:01:26 +00:00
|
|
|
opt.Price = source
|
|
|
|
opt.Tags = []string{"long"}
|
2022-10-27 08:31:39 +00:00
|
|
|
|
2023-05-04 05:50:01 +00:00
|
|
|
submitOrder, err := s.FastOrderExecutor.NewOrderFromOpenPosition(ctx, &opt)
|
2022-09-02 03:05:00 +00:00
|
|
|
if err != nil {
|
2022-09-28 11:06:37 +00:00
|
|
|
errs := filterErrors(multierr.Errors(err))
|
|
|
|
if len(errs) > 0 {
|
|
|
|
log.Errorf("%v", errs)
|
|
|
|
log.WithError(err).Errorf("cannot place buy order")
|
2022-09-22 11:26:18 +00:00
|
|
|
}
|
2022-09-02 03:05:00 +00:00
|
|
|
return
|
|
|
|
}
|
2022-11-09 08:43:51 +00:00
|
|
|
if submitOrder == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-05-31 11:35:44 +00:00
|
|
|
log.Infof("source in long %v %v %f", source, price, s.stdevLow.Last(0))
|
2022-11-09 08:43:51 +00:00
|
|
|
|
2022-11-16 09:10:58 +00:00
|
|
|
o, err := s.SubmitOrder(ctx, *submitOrder)
|
2022-11-09 08:43:51 +00:00
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Errorf("cannot place buy order")
|
|
|
|
return
|
|
|
|
}
|
2022-10-27 08:31:39 +00:00
|
|
|
|
2022-11-16 09:10:58 +00:00
|
|
|
log.Infof("order %v", o)
|
|
|
|
if o != nil {
|
|
|
|
if o.Status == types.OrderStatusNew || o.Status == types.OrderStatusPartiallyFilled {
|
|
|
|
s.pendingLock.Lock()
|
|
|
|
if _, ok := s.orderPendingCounter[o.OrderID]; !ok {
|
2022-10-27 08:31:39 +00:00
|
|
|
s.orderPendingCounter[o.OrderID] = counter
|
|
|
|
}
|
2022-11-16 09:10:58 +00:00
|
|
|
s.pendingLock.Unlock()
|
2022-10-27 08:31:39 +00:00
|
|
|
}
|
2022-09-22 04:01:26 +00:00
|
|
|
}
|
2022-09-02 03:05:00 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
if shortCondition {
|
2023-05-31 11:35:44 +00:00
|
|
|
source = source.Add(fixedpoint.NewFromFloat(s.stdevHigh.Last(0) * s.HighLowVarianceMultiplier))
|
2022-09-22 04:01:26 +00:00
|
|
|
if source.Compare(price) < 0 {
|
|
|
|
source = price
|
2022-10-03 05:00:18 +00:00
|
|
|
}
|
2022-09-02 03:05:00 +00:00
|
|
|
|
2023-05-31 11:35:44 +00:00
|
|
|
log.Infof("source in short: %v %v %f", source, price, s.stdevLow.Last(0))
|
2022-09-02 03:05:00 +00:00
|
|
|
|
2022-09-22 04:01:26 +00:00
|
|
|
opt := s.OpenPositionOptions
|
|
|
|
opt.Short = true
|
2022-10-20 11:03:10 +00:00
|
|
|
opt.LimitOrder = true
|
2022-11-09 08:43:51 +00:00
|
|
|
if counter-s.maxCounterSellCanceled <= s.PendingMinInterval && s.maxCounterSellCanceled > s.maxCounterBuyCanceled {
|
2022-10-20 11:03:10 +00:00
|
|
|
opt.LimitOrder = false
|
2022-11-09 08:43:51 +00:00
|
|
|
source = price
|
2022-10-20 11:03:10 +00:00
|
|
|
}
|
2022-11-09 08:43:51 +00:00
|
|
|
opt.Price = source
|
2022-09-26 11:16:27 +00:00
|
|
|
opt.Tags = []string{"short"}
|
2023-05-04 05:50:01 +00:00
|
|
|
submitOrder, err := s.FastOrderExecutor.NewOrderFromOpenPosition(ctx, &opt)
|
2022-09-02 03:05:00 +00:00
|
|
|
if err != nil {
|
2022-09-28 11:06:37 +00:00
|
|
|
errs := filterErrors(multierr.Errors(err))
|
|
|
|
if len(errs) > 0 {
|
|
|
|
log.WithError(err).Errorf("cannot place sell order")
|
2022-09-22 11:26:18 +00:00
|
|
|
}
|
2022-09-02 03:05:00 +00:00
|
|
|
return
|
|
|
|
}
|
2022-11-09 08:43:51 +00:00
|
|
|
if submitOrder == nil {
|
|
|
|
return
|
|
|
|
}
|
2022-11-16 09:10:58 +00:00
|
|
|
o, err := s.SubmitOrder(ctx, *submitOrder)
|
2022-11-09 08:43:51 +00:00
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Errorf("cannot place sell order")
|
|
|
|
return
|
|
|
|
}
|
2022-11-16 09:10:58 +00:00
|
|
|
log.Infof("order %v", o)
|
|
|
|
if o != nil {
|
|
|
|
if o.Status == types.OrderStatusNew || o.Status == types.OrderStatusPartiallyFilled {
|
|
|
|
s.pendingLock.Lock()
|
|
|
|
if _, ok := s.orderPendingCounter[o.OrderID]; !ok {
|
2022-10-27 08:31:39 +00:00
|
|
|
s.orderPendingCounter[o.OrderID] = counter
|
|
|
|
}
|
2022-11-16 09:10:58 +00:00
|
|
|
s.pendingLock.Unlock()
|
2022-10-27 08:31:39 +00:00
|
|
|
}
|
2022-09-22 04:01:26 +00:00
|
|
|
}
|
2022-09-02 03:05:00 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-07-15 03:30:04 +00:00
|
|
|
func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) error {
|
2022-09-22 04:01:26 +00:00
|
|
|
if s.Leverage == fixedpoint.Zero {
|
|
|
|
s.Leverage = fixedpoint.One
|
|
|
|
}
|
2022-07-15 03:30:04 +00:00
|
|
|
instanceID := s.InstanceID()
|
|
|
|
// Will be set by persistence if there's any from DB
|
|
|
|
if s.Position == nil {
|
|
|
|
s.Position = types.NewPositionFromMarket(s.Market)
|
2022-11-16 09:10:58 +00:00
|
|
|
}
|
|
|
|
if s.Session.MakerFeeRate.Sign() > 0 || s.Session.TakerFeeRate.Sign() > 0 {
|
|
|
|
s.Position.SetExchangeFeeRate(s.Session.ExchangeName, types.ExchangeFee{
|
|
|
|
MakerFeeRate: s.Session.MakerFeeRate,
|
|
|
|
TakerFeeRate: s.Session.TakerFeeRate,
|
|
|
|
})
|
2022-07-15 03:30:04 +00:00
|
|
|
}
|
|
|
|
if s.ProfitStats == nil {
|
|
|
|
s.ProfitStats = types.NewProfitStats(s.Market)
|
|
|
|
}
|
|
|
|
if s.TradeStats == nil {
|
|
|
|
s.TradeStats = types.NewTradeStats(s.Symbol)
|
|
|
|
}
|
|
|
|
// StrategyController
|
|
|
|
s.Status = types.StrategyStatusRunning
|
|
|
|
|
|
|
|
s.OnSuspend(func() {
|
2023-05-04 05:50:01 +00:00
|
|
|
_ = s.FastOrderExecutor.GracefulCancel(ctx)
|
2022-07-15 03:30:04 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
s.OnEmergencyStop(func() {
|
2023-05-04 05:50:01 +00:00
|
|
|
_ = s.FastOrderExecutor.GracefulCancel(ctx)
|
2022-07-20 10:49:56 +00:00
|
|
|
_ = s.ClosePosition(ctx, fixedpoint.One)
|
2022-07-15 03:30:04 +00:00
|
|
|
})
|
|
|
|
|
2022-11-16 09:10:58 +00:00
|
|
|
profitChart := floats.Slice{1., 1.}
|
2022-08-16 03:30:29 +00:00
|
|
|
price, _ := s.Session.LastPrice(s.Symbol)
|
2022-08-16 03:45:40 +00:00
|
|
|
initAsset := s.CalcAssetValue(price).Float64()
|
2022-08-25 09:31:42 +00:00
|
|
|
cumProfit := floats.Slice{initAsset, initAsset}
|
2022-08-10 11:36:30 +00:00
|
|
|
modify := func(p float64) float64 {
|
2022-07-22 04:32:37 +00:00
|
|
|
return p
|
|
|
|
}
|
|
|
|
if s.GraphPNLDeductFee {
|
2022-08-10 11:36:30 +00:00
|
|
|
modify = func(p float64) float64 {
|
|
|
|
return p * (1. - Fee)
|
2022-07-15 10:59:37 +00:00
|
|
|
}
|
2022-07-22 04:32:37 +00:00
|
|
|
}
|
2022-11-16 09:10:58 +00:00
|
|
|
|
2023-05-04 05:50:01 +00:00
|
|
|
s.FastOrderExecutor = bbgo.NewFastOrderExecutor(session, s.Symbol, ID, instanceID, s.Position)
|
|
|
|
s.FastOrderExecutor.DisableNotify()
|
|
|
|
orderStore := s.FastOrderExecutor.OrderStore()
|
2022-11-16 09:10:58 +00:00
|
|
|
orderStore.AddOrderUpdate = true
|
|
|
|
orderStore.RemoveCancelled = true
|
|
|
|
orderStore.RemoveFilled = true
|
2023-05-04 05:50:01 +00:00
|
|
|
activeOrders := s.FastOrderExecutor.ActiveMakerOrders()
|
|
|
|
tradeCollector := s.FastOrderExecutor.TradeCollector()
|
2022-11-16 09:10:58 +00:00
|
|
|
tradeStore := tradeCollector.TradeStore()
|
|
|
|
|
|
|
|
syscounter := 0
|
|
|
|
|
|
|
|
// Modify activeOrders to force write order updates
|
|
|
|
s.Session.UserDataStream.OnOrderUpdate(func(order types.Order) {
|
|
|
|
hasSymbol := len(activeOrders.Symbol) > 0
|
|
|
|
if hasSymbol && order.Symbol != activeOrders.Symbol {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
switch order.Status {
|
|
|
|
case types.OrderStatusFilled:
|
|
|
|
s.pendingLock.Lock()
|
|
|
|
s.orderPendingCounter = make(map[uint64]int)
|
|
|
|
s.pendingLock.Unlock()
|
|
|
|
// make sure we have the order and we remove it
|
|
|
|
activeOrders.Remove(order)
|
|
|
|
|
|
|
|
case types.OrderStatusPartiallyFilled:
|
|
|
|
s.pendingLock.Lock()
|
|
|
|
if _, ok := s.orderPendingCounter[order.OrderID]; !ok {
|
|
|
|
s.orderPendingCounter[order.OrderID] = syscounter
|
|
|
|
}
|
|
|
|
s.pendingLock.Unlock()
|
|
|
|
activeOrders.Add(order)
|
|
|
|
|
|
|
|
case types.OrderStatusNew:
|
|
|
|
s.pendingLock.Lock()
|
|
|
|
if _, ok := s.orderPendingCounter[order.OrderID]; !ok {
|
|
|
|
s.orderPendingCounter[order.OrderID] = syscounter
|
|
|
|
}
|
|
|
|
s.pendingLock.Unlock()
|
|
|
|
activeOrders.Add(order)
|
|
|
|
|
|
|
|
case types.OrderStatusCanceled, types.OrderStatusRejected:
|
|
|
|
log.Debugf("[ActiveOrderBook] order status %s, removing order %s", order.Status, order)
|
|
|
|
s.pendingLock.Lock()
|
|
|
|
s.orderPendingCounter = make(map[uint64]int)
|
|
|
|
s.pendingLock.Unlock()
|
|
|
|
activeOrders.Remove(order)
|
|
|
|
|
|
|
|
default:
|
|
|
|
log.Errorf("unhandled order status: %s", order.Status)
|
|
|
|
}
|
|
|
|
orderStore.HandleOrderUpdate(order)
|
|
|
|
})
|
2022-11-09 08:43:51 +00:00
|
|
|
s.Session.UserDataStream.OnTradeUpdate(func(trade types.Trade) {
|
|
|
|
if trade.Symbol != s.Symbol {
|
|
|
|
return
|
|
|
|
}
|
2022-11-16 09:10:58 +00:00
|
|
|
profit, netProfit, madeProfit := s.Position.AddTrade(trade)
|
|
|
|
tradeStore.Add(trade)
|
|
|
|
if madeProfit {
|
|
|
|
p := s.Position.NewProfit(trade, profit, netProfit)
|
|
|
|
s.Environment.RecordPosition(s.Position, trade, &p)
|
2023-08-29 08:12:31 +00:00
|
|
|
s.TradeStats.AddProfit(&p)
|
2022-11-16 09:10:58 +00:00
|
|
|
s.ProfitStats.AddTrade(trade)
|
2023-08-29 08:12:31 +00:00
|
|
|
s.ProfitStats.AddProfit(&p)
|
2022-11-16 09:10:58 +00:00
|
|
|
bbgo.Notify(&p)
|
|
|
|
bbgo.Notify(s.ProfitStats)
|
|
|
|
}
|
|
|
|
|
2022-08-10 11:36:30 +00:00
|
|
|
price := trade.Price.Float64()
|
|
|
|
|
|
|
|
if s.buyPrice > 0 {
|
2022-11-16 09:10:58 +00:00
|
|
|
profitChart.Update(modify(price / s.buyPrice))
|
2022-08-16 03:30:29 +00:00
|
|
|
cumProfit.Update(s.CalcAssetValue(trade.Price).Float64())
|
2022-08-10 11:36:30 +00:00
|
|
|
} else if s.sellPrice > 0 {
|
2022-11-16 09:10:58 +00:00
|
|
|
profitChart.Update(modify(s.sellPrice / price))
|
2022-08-16 03:30:29 +00:00
|
|
|
cumProfit.Update(s.CalcAssetValue(trade.Price).Float64())
|
2022-08-10 11:36:30 +00:00
|
|
|
}
|
|
|
|
s.positionLock.Lock()
|
2022-11-16 09:10:58 +00:00
|
|
|
if s.Position.IsDust(trade.Price) {
|
2022-09-28 11:06:37 +00:00
|
|
|
s.buyPrice = 0
|
|
|
|
s.sellPrice = 0
|
|
|
|
s.highestPrice = 0
|
|
|
|
s.lowestPrice = 0
|
2022-11-16 09:10:58 +00:00
|
|
|
} else if s.Position.IsLong() {
|
|
|
|
s.buyPrice = s.Position.ApproximateAverageCost.Float64()
|
2022-09-28 11:06:37 +00:00
|
|
|
s.sellPrice = 0
|
|
|
|
s.highestPrice = math.Max(s.buyPrice, s.highestPrice)
|
2022-10-03 05:00:18 +00:00
|
|
|
s.lowestPrice = s.buyPrice
|
2022-11-16 09:10:58 +00:00
|
|
|
} else if s.Position.IsShort() {
|
|
|
|
s.sellPrice = s.Position.ApproximateAverageCost.Float64()
|
2022-09-28 11:06:37 +00:00
|
|
|
s.buyPrice = 0
|
2022-10-03 05:00:18 +00:00
|
|
|
s.highestPrice = s.sellPrice
|
2022-09-29 11:15:10 +00:00
|
|
|
if s.lowestPrice == 0 {
|
|
|
|
s.lowestPrice = s.sellPrice
|
|
|
|
} else {
|
|
|
|
s.lowestPrice = math.Min(s.lowestPrice, s.sellPrice)
|
|
|
|
}
|
2022-08-09 04:26:02 +00:00
|
|
|
}
|
2022-10-20 11:03:10 +00:00
|
|
|
s.positionLock.Unlock()
|
2022-07-22 04:32:37 +00:00
|
|
|
})
|
2022-07-15 03:30:04 +00:00
|
|
|
|
2022-11-09 08:43:51 +00:00
|
|
|
s.orderPendingCounter = make(map[uint64]int)
|
|
|
|
|
|
|
|
// Exit methods from config
|
|
|
|
for _, method := range s.ExitMethods {
|
|
|
|
method.Bind(session, s.GeneralOrderExecutor)
|
|
|
|
}
|
|
|
|
|
2022-08-10 11:36:30 +00:00
|
|
|
s.frameKLine = &types.KLine{}
|
2022-10-19 04:17:44 +00:00
|
|
|
s.klineMin = &types.KLine{}
|
2022-09-02 03:05:00 +00:00
|
|
|
s.priceLines = types.NewQueue(300)
|
2022-10-27 08:31:39 +00:00
|
|
|
s.elapsed = types.NewQueue(60000)
|
2022-07-15 03:30:04 +00:00
|
|
|
|
2022-09-06 05:26:17 +00:00
|
|
|
s.initTickerFunctions(ctx)
|
2022-10-19 04:17:44 +00:00
|
|
|
s.startTime = s.Environment.StartTime()
|
|
|
|
s.TradeStats.SetIntervalProfitCollector(types.NewIntervalProfitCollector(types.Interval1d, s.startTime))
|
|
|
|
s.TradeStats.SetIntervalProfitCollector(types.NewIntervalProfitCollector(types.Interval1w, s.startTime))
|
2022-09-02 03:05:00 +00:00
|
|
|
|
2022-11-16 09:10:58 +00:00
|
|
|
s.InitDrawCommands(&profitChart, &cumProfit)
|
2022-08-03 06:10:56 +00:00
|
|
|
|
2022-08-03 11:41:16 +00:00
|
|
|
bbgo.RegisterCommand("/config", "Show latest config", func(reply interact.Reply) {
|
|
|
|
var buffer bytes.Buffer
|
2022-08-08 05:55:01 +00:00
|
|
|
s.Print(&buffer, false)
|
2022-08-03 11:41:16 +00:00
|
|
|
reply.Message(buffer.String())
|
|
|
|
})
|
|
|
|
|
2022-08-10 11:36:30 +00:00
|
|
|
bbgo.RegisterCommand("/dump", "Dump internal params", func(reply interact.Reply) {
|
|
|
|
reply.Message("Please enter series output length:")
|
|
|
|
}).Next(func(length string, reply interact.Reply) {
|
|
|
|
var buffer bytes.Buffer
|
|
|
|
l, err := strconv.Atoi(length)
|
|
|
|
if err != nil {
|
2022-09-27 11:26:59 +00:00
|
|
|
dynamic.ParamDump(s, &buffer)
|
2022-08-10 11:36:30 +00:00
|
|
|
} else {
|
2022-09-27 11:26:59 +00:00
|
|
|
dynamic.ParamDump(s, &buffer, l)
|
2022-07-01 10:38:25 +00:00
|
|
|
}
|
2022-08-10 11:36:30 +00:00
|
|
|
reply.Message(buffer.String())
|
|
|
|
})
|
|
|
|
|
2022-09-13 11:40:07 +00:00
|
|
|
bbgo.RegisterModifier(s)
|
|
|
|
|
2022-10-19 04:17:44 +00:00
|
|
|
// event trigger order: s.Interval => s.MinInterval
|
|
|
|
store, ok := session.SerialMarketDataStore(ctx, s.Symbol, []types.Interval{s.Interval, s.MinInterval}, !bbgo.IsBackTesting)
|
2022-09-02 03:05:00 +00:00
|
|
|
if !ok {
|
2022-10-19 04:17:44 +00:00
|
|
|
panic("cannot get " + s.MinInterval + " history")
|
2022-09-02 03:05:00 +00:00
|
|
|
}
|
2022-09-06 05:26:17 +00:00
|
|
|
if err := s.initIndicators(store); err != nil {
|
|
|
|
log.WithError(err).Errorf("initIndicator failed")
|
|
|
|
return nil
|
|
|
|
}
|
2022-10-19 04:17:44 +00:00
|
|
|
|
2022-09-02 03:05:00 +00:00
|
|
|
store.OnKLineClosed(func(kline types.KLine) {
|
2022-10-27 08:31:39 +00:00
|
|
|
counter := int(kline.StartTime.Time().Add(kline.Interval.Duration()).Sub(s.startTime).Milliseconds()) / s.MinInterval.Milliseconds()
|
2022-11-16 09:10:58 +00:00
|
|
|
syscounter = counter
|
2022-09-26 11:16:27 +00:00
|
|
|
if kline.Interval == s.Interval {
|
2022-10-27 08:31:39 +00:00
|
|
|
s.klineHandler(ctx, kline, counter)
|
2022-10-19 04:17:44 +00:00
|
|
|
} else if kline.Interval == s.MinInterval {
|
2022-10-27 08:31:39 +00:00
|
|
|
s.klineHandlerMin(ctx, kline, counter)
|
2022-08-02 11:21:44 +00:00
|
|
|
}
|
2022-07-01 10:38:25 +00:00
|
|
|
})
|
|
|
|
|
2022-10-03 08:01:08 +00:00
|
|
|
bbgo.OnShutdown(ctx, func(ctx context.Context, wg *sync.WaitGroup) {
|
2022-07-15 08:00:38 +00:00
|
|
|
|
2022-11-09 08:43:51 +00:00
|
|
|
if !bbgo.IsBackTesting {
|
|
|
|
bbgo.Sync(ctx, s)
|
|
|
|
}
|
|
|
|
|
2022-08-08 05:55:01 +00:00
|
|
|
var buffer bytes.Buffer
|
|
|
|
|
|
|
|
s.Print(&buffer, true, true)
|
2022-08-15 11:50:34 +00:00
|
|
|
|
|
|
|
fmt.Fprintln(&buffer, "--- NonProfitable Dates ---")
|
|
|
|
for _, daypnl := range s.TradeStats.IntervalProfits[types.Interval1d].GetNonProfitableIntervals() {
|
|
|
|
fmt.Fprintf(&buffer, "%s\n", daypnl)
|
|
|
|
}
|
2022-08-08 05:55:01 +00:00
|
|
|
fmt.Fprintln(&buffer, s.TradeStats.BriefString())
|
2022-07-15 08:00:38 +00:00
|
|
|
|
2022-11-09 08:43:51 +00:00
|
|
|
fmt.Fprintf(&buffer, "%v\n", s.orderPendingCounter)
|
|
|
|
|
2022-08-08 05:55:01 +00:00
|
|
|
os.Stdout.Write(buffer.Bytes())
|
2022-07-15 08:00:38 +00:00
|
|
|
|
2022-07-15 10:59:37 +00:00
|
|
|
if s.GenerateGraph {
|
2022-11-16 09:10:58 +00:00
|
|
|
s.Draw(s.frameKLine.StartTime, &profitChart, &cumProfit)
|
2022-07-15 10:59:37 +00:00
|
|
|
}
|
2022-07-01 10:38:25 +00:00
|
|
|
wg.Done()
|
|
|
|
})
|
|
|
|
return nil
|
|
|
|
}
|