2022-05-27 06:36:48 +00:00
|
|
|
package supertrend
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
2022-06-19 04:29:36 +00:00
|
|
|
"sync"
|
|
|
|
|
2022-06-21 07:57:26 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/util"
|
|
|
|
|
2022-06-19 04:29:36 +00:00
|
|
|
"github.com/pkg/errors"
|
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
|
2022-05-27 06:36:48 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/bbgo"
|
|
|
|
"github.com/c9s/bbgo/pkg/fixedpoint"
|
|
|
|
"github.com/c9s/bbgo/pkg/indicator"
|
|
|
|
"github.com/c9s/bbgo/pkg/types"
|
|
|
|
)
|
|
|
|
|
|
|
|
const ID = "supertrend"
|
|
|
|
|
|
|
|
const stateKey = "state-v1"
|
|
|
|
|
|
|
|
var log = logrus.WithField("strategy", ID)
|
|
|
|
|
2022-07-05 07:59:35 +00:00
|
|
|
// TODO: SL by fixed percentage
|
|
|
|
// TODO: limit order if possible
|
|
|
|
// TODO: lingre as indicator
|
|
|
|
// TODO: types.TradeStats
|
|
|
|
|
2022-05-27 06:36:48 +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.
|
|
|
|
bbgo.RegisterStrategy(ID, &Strategy{})
|
|
|
|
}
|
|
|
|
|
2022-06-30 08:35:00 +00:00
|
|
|
// LinGre is Linear Regression baseline
|
|
|
|
type LinGre struct {
|
|
|
|
types.IntervalWindow
|
|
|
|
baseLineSlope float64
|
|
|
|
}
|
|
|
|
|
|
|
|
// Update Linear Regression baseline slope
|
|
|
|
func (lg *LinGre) Update(klines []types.KLine) {
|
|
|
|
if len(klines) < lg.Window {
|
|
|
|
lg.baseLineSlope = 0
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
var sumX, sumY, sumXSqr, sumXY float64 = 0, 0, 0, 0
|
|
|
|
end := len(klines) - 1 // The last kline
|
|
|
|
for i := end; i >= end-lg.Window+1; i-- {
|
|
|
|
val := klines[i].GetClose().Float64()
|
|
|
|
per := float64(end - i + 1)
|
|
|
|
sumX += per
|
|
|
|
sumY += val
|
|
|
|
sumXSqr += per * per
|
|
|
|
sumXY += val * per
|
|
|
|
}
|
|
|
|
length := float64(lg.Window)
|
|
|
|
slope := (length*sumXY - sumX*sumY) / (length*sumXSqr - sumX*sumX)
|
|
|
|
average := sumY / length
|
|
|
|
endPrice := average - slope*sumX/length + slope
|
|
|
|
startPrice := endPrice + slope*(length-1)
|
|
|
|
lg.baseLineSlope = (length - 1) / (endPrice - startPrice)
|
|
|
|
|
|
|
|
log.Debugf("linear regression baseline slope: %f", lg.baseLineSlope)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (lg *LinGre) handleKLineWindowUpdate(interval types.Interval, window types.KLineWindow) {
|
|
|
|
if lg.Interval != interval {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
lg.Update(window)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (lg *LinGre) Bind(updater indicator.KLineWindowUpdater) {
|
|
|
|
updater.OnKLineWindowUpdate(lg.handleKLineWindowUpdate)
|
|
|
|
}
|
|
|
|
|
2022-05-27 06:36:48 +00:00
|
|
|
type Strategy struct {
|
|
|
|
*bbgo.Graceful
|
|
|
|
*bbgo.Persistence
|
|
|
|
|
2022-05-27 10:24:08 +00:00
|
|
|
Environment *bbgo.Environment
|
|
|
|
session *bbgo.ExchangeSession
|
|
|
|
Market types.Market
|
2022-05-27 06:36:48 +00:00
|
|
|
|
|
|
|
// persistence fields
|
|
|
|
Position *types.Position `json:"position,omitempty" persistence:"position"`
|
|
|
|
ProfitStats *types.ProfitStats `json:"profitStats,omitempty" persistence:"profit_stats"`
|
|
|
|
|
|
|
|
// Order and trade
|
2022-06-20 05:39:07 +00:00
|
|
|
orderExecutor *bbgo.GeneralOrderExecutor
|
|
|
|
|
2022-05-27 06:36:48 +00:00
|
|
|
// groupID is the group ID used for the strategy instance for canceling orders
|
|
|
|
groupID uint32
|
|
|
|
|
2022-05-30 08:48:07 +00:00
|
|
|
stopC chan struct{}
|
|
|
|
|
2022-05-27 06:36:48 +00:00
|
|
|
// Symbol is the market symbol you want to trade
|
|
|
|
Symbol string `json:"symbol"`
|
|
|
|
|
|
|
|
// Interval is how long do you want to update your order price and quantity
|
|
|
|
Interval types.Interval `json:"interval"`
|
|
|
|
|
2022-06-02 05:47:16 +00:00
|
|
|
// FastDEMAWindow DEMA window for checking breakout
|
2022-05-30 06:52:51 +00:00
|
|
|
FastDEMAWindow int `json:"fastDEMAWindow"`
|
2022-06-02 05:47:16 +00:00
|
|
|
// SlowDEMAWindow DEMA window for checking breakout
|
2022-05-30 06:52:51 +00:00
|
|
|
SlowDEMAWindow int `json:"slowDEMAWindow"`
|
2022-06-02 05:47:16 +00:00
|
|
|
fastDEMA *indicator.DEMA
|
|
|
|
slowDEMA *indicator.DEMA
|
2022-05-27 06:36:48 +00:00
|
|
|
|
|
|
|
// SuperTrend indicator
|
2022-06-19 04:29:36 +00:00
|
|
|
// SuperTrend SuperTrend `json:"superTrend"`
|
2022-06-02 05:32:57 +00:00
|
|
|
Supertrend *indicator.Supertrend
|
|
|
|
// SupertrendWindow ATR window for calculation of supertrend
|
|
|
|
SupertrendWindow int `json:"supertrendWindow"`
|
|
|
|
// SupertrendMultiplier ATR multiplier for calculation of supertrend
|
|
|
|
SupertrendMultiplier float64 `json:"supertrendMultiplier"`
|
2022-05-27 06:36:48 +00:00
|
|
|
|
2022-07-05 07:59:35 +00:00
|
|
|
// LinearRegression Use linear regression as trend confirmation
|
|
|
|
LinearRegression *LinGre `json:"linearRegression,omitempty"`
|
2022-06-30 08:35:00 +00:00
|
|
|
|
2022-05-30 08:07:36 +00:00
|
|
|
// Leverage
|
|
|
|
Leverage float64 `json:"leverage"`
|
|
|
|
|
2022-07-05 07:59:35 +00:00
|
|
|
// TakeProfitAtrMultiplier TP according to ATR multiple, 0 to disable this
|
|
|
|
TakeProfitAtrMultiplier float64 `json:"takeProfitAtrMultiplier"`
|
2022-05-31 04:53:14 +00:00
|
|
|
|
2022-07-05 07:59:35 +00:00
|
|
|
// StopLossByTriggeringK Set SL price to the low/high of the triggering Kline
|
2022-05-31 04:53:14 +00:00
|
|
|
StopLossByTriggeringK bool `json:"stopLossByTriggeringK"`
|
|
|
|
|
2022-07-05 07:59:35 +00:00
|
|
|
// StopByReversedSupertrend TP/SL by reversed supertrend signal
|
|
|
|
StopByReversedSupertrend bool `json:"stopByReversedSupertrend"`
|
|
|
|
|
|
|
|
// StopByReversedDema TP/SL by reversed DEMA signal
|
|
|
|
StopByReversedDema bool `json:"stopByReversedDema"`
|
|
|
|
|
|
|
|
// StopByReversedLinGre TP/SL by reversed linear regression signal
|
|
|
|
StopByReversedLinGre bool `json:"stopByReversedLinGre"`
|
2022-05-31 04:53:14 +00:00
|
|
|
|
|
|
|
currentTakeProfitPrice fixedpoint.Value
|
|
|
|
currentStopLossPrice fixedpoint.Value
|
2022-05-27 06:36:48 +00:00
|
|
|
|
|
|
|
// StrategyController
|
|
|
|
bbgo.StrategyController
|
|
|
|
}
|
|
|
|
|
|
|
|
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 len(s.Symbol) == 0 {
|
|
|
|
return errors.New("symbol is required")
|
|
|
|
}
|
|
|
|
|
2022-05-30 08:22:13 +00:00
|
|
|
if len(s.Interval) == 0 {
|
|
|
|
return errors.New("interval is required")
|
|
|
|
}
|
|
|
|
|
|
|
|
if s.Leverage == 0.0 {
|
|
|
|
return errors.New("leverage is required")
|
|
|
|
}
|
|
|
|
|
2022-05-27 06:36:48 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Strategy) Subscribe(session *bbgo.ExchangeSession) {
|
|
|
|
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: s.Interval})
|
2022-05-30 06:52:51 +00:00
|
|
|
}
|
2022-05-27 06:36:48 +00:00
|
|
|
|
2022-05-30 08:26:17 +00:00
|
|
|
// Position control
|
|
|
|
|
|
|
|
func (s *Strategy) CurrentPosition() *types.Position {
|
|
|
|
return s.Position
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Strategy) ClosePosition(ctx context.Context, percentage fixedpoint.Value) error {
|
|
|
|
base := s.Position.GetBase()
|
|
|
|
if base.IsZero() {
|
|
|
|
return fmt.Errorf("no opened %s position", s.Position.Symbol)
|
|
|
|
}
|
|
|
|
|
|
|
|
// make it negative
|
|
|
|
quantity := base.Mul(percentage).Abs()
|
|
|
|
side := types.SideTypeBuy
|
|
|
|
if base.Sign() > 0 {
|
|
|
|
side = types.SideTypeSell
|
|
|
|
}
|
|
|
|
|
|
|
|
if quantity.Compare(s.Market.MinQuantity) < 0 {
|
2022-06-16 09:14:50 +00:00
|
|
|
return fmt.Errorf("%s order quantity %v is too small, less than %v", s.Symbol, quantity, s.Market.MinQuantity)
|
2022-05-30 08:26:17 +00:00
|
|
|
}
|
|
|
|
|
2022-06-01 02:26:04 +00:00
|
|
|
orderForm := s.generateOrderForm(side, quantity, types.SideEffectTypeAutoRepay)
|
2022-05-30 08:26:17 +00:00
|
|
|
|
2022-07-05 08:25:02 +00:00
|
|
|
bbgo.Notify("submitting %s %s order to close position by %v", s.Symbol, side.String(), percentage, orderForm)
|
2022-05-30 08:26:17 +00:00
|
|
|
|
2022-06-20 05:39:07 +00:00
|
|
|
_, err := s.orderExecutor.SubmitOrders(ctx, orderForm)
|
2022-05-30 08:26:17 +00:00
|
|
|
if err != nil {
|
2022-06-16 09:14:50 +00:00
|
|
|
log.WithError(err).Errorf("can not place %s position close order", s.Symbol)
|
2022-06-19 04:29:36 +00:00
|
|
|
bbgo.Notify("can not place %s position close order", s.Symbol)
|
2022-05-30 08:26:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-06-01 02:26:04 +00:00
|
|
|
// setupIndicators initializes indicators
|
|
|
|
func (s *Strategy) setupIndicators() {
|
2022-07-05 08:25:02 +00:00
|
|
|
// K-line store for indicators
|
|
|
|
kLineStore, _ := s.session.MarketDataStore(s.Symbol)
|
|
|
|
|
|
|
|
// DEMA
|
2022-05-30 06:52:51 +00:00
|
|
|
if s.FastDEMAWindow == 0 {
|
|
|
|
s.FastDEMAWindow = 144
|
2022-05-27 06:36:48 +00:00
|
|
|
}
|
2022-06-02 05:47:16 +00:00
|
|
|
s.fastDEMA = &indicator.DEMA{IntervalWindow: types.IntervalWindow{Interval: s.Interval, Window: s.FastDEMAWindow}}
|
2022-05-27 06:36:48 +00:00
|
|
|
|
2022-05-30 06:52:51 +00:00
|
|
|
if s.SlowDEMAWindow == 0 {
|
|
|
|
s.SlowDEMAWindow = 169
|
2022-05-27 06:36:48 +00:00
|
|
|
}
|
2022-06-02 05:47:16 +00:00
|
|
|
s.slowDEMA = &indicator.DEMA{IntervalWindow: types.IntervalWindow{Interval: s.Interval, Window: s.SlowDEMAWindow}}
|
2022-07-05 08:25:02 +00:00
|
|
|
// Preload
|
|
|
|
if klines, ok := kLineStore.KLinesOfInterval(s.fastDEMA.Interval); ok {
|
|
|
|
for i := 0; i < len(*klines); i++ {
|
|
|
|
s.fastDEMA.Update((*klines)[i].GetClose().Float64())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if klines, ok := kLineStore.KLinesOfInterval(s.slowDEMA.Interval); ok {
|
|
|
|
for i := 0; i < len(*klines); i++ {
|
|
|
|
s.slowDEMA.Update((*klines)[i].GetClose().Float64())
|
|
|
|
}
|
|
|
|
}
|
2022-05-27 06:36:48 +00:00
|
|
|
|
2022-07-05 08:25:02 +00:00
|
|
|
// Supertrend
|
2022-06-02 05:32:57 +00:00
|
|
|
if s.SupertrendWindow == 0 {
|
|
|
|
s.SupertrendWindow = 39
|
2022-05-30 06:52:51 +00:00
|
|
|
}
|
2022-06-02 05:32:57 +00:00
|
|
|
if s.SupertrendMultiplier == 0 {
|
|
|
|
s.SupertrendMultiplier = 3
|
2022-05-30 06:52:51 +00:00
|
|
|
}
|
2022-06-02 05:32:57 +00:00
|
|
|
s.Supertrend = &indicator.Supertrend{IntervalWindow: types.IntervalWindow{Window: s.SupertrendWindow, Interval: s.Interval}, ATRMultiplier: s.SupertrendMultiplier}
|
|
|
|
s.Supertrend.AverageTrueRange = &indicator.ATR{IntervalWindow: types.IntervalWindow{Window: s.SupertrendWindow, Interval: s.Interval}}
|
2022-07-05 08:25:02 +00:00
|
|
|
s.Supertrend.Bind(kLineStore)
|
|
|
|
// Preload
|
|
|
|
if klines, ok := kLineStore.KLinesOfInterval(s.Supertrend.Interval); ok {
|
|
|
|
for i := 0; i < len(*klines); i++ {
|
|
|
|
s.Supertrend.Update((*klines)[i].GetHigh().Float64(), (*klines)[i].GetLow().Float64(), (*klines)[i].GetClose().Float64())
|
|
|
|
}
|
|
|
|
}
|
2022-06-02 05:32:57 +00:00
|
|
|
|
2022-07-05 08:25:02 +00:00
|
|
|
// Linear Regression
|
|
|
|
if s.LinearRegression != nil {
|
|
|
|
if s.LinearRegression.Window == 0 {
|
|
|
|
s.LinearRegression = nil
|
|
|
|
} else {
|
|
|
|
s.LinearRegression.Bind(kLineStore)
|
2022-05-30 08:07:36 +00:00
|
|
|
|
2022-07-05 08:25:02 +00:00
|
|
|
// Preload
|
|
|
|
if klines, ok := kLineStore.KLinesOfInterval(s.LinearRegression.Interval); ok {
|
|
|
|
s.LinearRegression.Update((*klines)[0:])
|
|
|
|
}
|
|
|
|
}
|
2022-05-30 08:07:36 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-06-01 02:26:04 +00:00
|
|
|
func (s *Strategy) generateOrderForm(side types.SideType, quantity fixedpoint.Value, marginOrderSideEffect types.MarginOrderSideEffectType) types.SubmitOrder {
|
2022-05-30 08:07:36 +00:00
|
|
|
orderForm := types.SubmitOrder{
|
2022-05-31 07:46:55 +00:00
|
|
|
Symbol: s.Symbol,
|
|
|
|
Market: s.Market,
|
|
|
|
Side: side,
|
|
|
|
Type: types.OrderTypeMarket,
|
|
|
|
Quantity: quantity,
|
|
|
|
MarginSideEffect: marginOrderSideEffect,
|
2022-06-20 05:39:07 +00:00
|
|
|
GroupID: s.groupID,
|
2022-05-30 08:07:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return orderForm
|
|
|
|
}
|
|
|
|
|
2022-06-01 02:26:04 +00:00
|
|
|
// calculateQuantity returns leveraged quantity
|
|
|
|
func (s *Strategy) calculateQuantity(currentPrice fixedpoint.Value) fixedpoint.Value {
|
|
|
|
balance, ok := s.session.GetAccount().Balance(s.Market.QuoteCurrency)
|
|
|
|
if !ok {
|
2022-06-16 09:14:50 +00:00
|
|
|
log.Errorf("can not update %s balance from exchange", s.Symbol)
|
2022-06-01 02:26:04 +00:00
|
|
|
return fixedpoint.Zero
|
|
|
|
}
|
|
|
|
|
2022-05-30 08:07:36 +00:00
|
|
|
amountAvailable := balance.Available.Mul(fixedpoint.NewFromFloat(s.Leverage))
|
|
|
|
quantity := amountAvailable.Div(currentPrice)
|
|
|
|
|
|
|
|
return quantity
|
|
|
|
}
|
|
|
|
|
2022-05-27 06:36:48 +00:00
|
|
|
func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) error {
|
|
|
|
s.session = session
|
|
|
|
|
2022-06-20 05:39:07 +00:00
|
|
|
// calculate group id for orders
|
|
|
|
instanceID := s.InstanceID()
|
|
|
|
s.groupID = util.FNV32(instanceID)
|
|
|
|
|
2022-05-27 06:36:48 +00:00
|
|
|
// If position is nil, we need to allocate a new position for calculation
|
|
|
|
if s.Position == nil {
|
|
|
|
s.Position = types.NewPositionFromMarket(s.Market)
|
|
|
|
}
|
|
|
|
// Always update the position fields
|
|
|
|
s.Position.Strategy = ID
|
|
|
|
s.Position.StrategyInstanceID = s.InstanceID()
|
|
|
|
|
2022-06-20 05:39:07 +00:00
|
|
|
// Set fee rate
|
|
|
|
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-05-30 08:48:07 +00:00
|
|
|
|
|
|
|
// Profit
|
2022-05-27 06:36:48 +00:00
|
|
|
if s.ProfitStats == nil {
|
|
|
|
s.ProfitStats = types.NewProfitStats(s.Market)
|
|
|
|
}
|
|
|
|
|
2022-06-20 05:39:07 +00:00
|
|
|
// Setup order executor
|
|
|
|
s.orderExecutor = bbgo.NewGeneralOrderExecutor(session, s.Symbol, ID, instanceID, s.Position)
|
|
|
|
s.orderExecutor.BindEnvironment(s.Environment)
|
|
|
|
s.orderExecutor.BindProfitStats(s.ProfitStats)
|
|
|
|
s.orderExecutor.Bind()
|
|
|
|
|
|
|
|
// Sync position to redis on trade
|
|
|
|
s.orderExecutor.TradeCollector().OnPositionUpdate(func(position *types.Position) {
|
2022-06-21 07:57:26 +00:00
|
|
|
bbgo.Sync(s)
|
2022-06-20 05:39:07 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
s.stopC = make(chan struct{})
|
2022-05-27 06:36:48 +00:00
|
|
|
|
|
|
|
// StrategyController
|
|
|
|
s.Status = types.StrategyStatusRunning
|
|
|
|
|
2022-05-30 08:35:10 +00:00
|
|
|
s.OnSuspend(func() {
|
2022-06-20 05:39:07 +00:00
|
|
|
_ = s.orderExecutor.GracefulCancel(ctx)
|
2022-05-30 08:35:10 +00:00
|
|
|
_ = s.Persistence.Sync(s)
|
|
|
|
})
|
|
|
|
|
|
|
|
s.OnEmergencyStop(func() {
|
2022-06-20 05:39:07 +00:00
|
|
|
_ = s.orderExecutor.GracefulCancel(ctx)
|
2022-05-30 08:35:10 +00:00
|
|
|
// Close 100% position
|
2022-06-20 05:39:07 +00:00
|
|
|
_ = s.ClosePosition(ctx, fixedpoint.One)
|
2022-05-30 08:35:10 +00:00
|
|
|
})
|
|
|
|
|
2022-05-27 06:36:48 +00:00
|
|
|
// Setup indicators
|
2022-06-01 02:26:04 +00:00
|
|
|
s.setupIndicators()
|
2022-05-27 06:36:48 +00:00
|
|
|
|
2022-05-31 04:53:14 +00:00
|
|
|
s.currentStopLossPrice = fixedpoint.Zero
|
|
|
|
s.currentTakeProfitPrice = fixedpoint.Zero
|
|
|
|
|
2022-05-27 06:36:48 +00:00
|
|
|
session.MarketDataStream.OnKLineClosed(func(kline types.KLine) {
|
2022-05-30 08:35:10 +00:00
|
|
|
// StrategyController
|
|
|
|
if s.Status != types.StrategyStatusRunning {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-05-30 08:07:36 +00:00
|
|
|
// skip k-lines from other symbols or other intervals
|
|
|
|
if kline.Symbol != s.Symbol || kline.Interval != s.Interval {
|
2022-05-27 06:36:48 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-05-30 08:07:36 +00:00
|
|
|
closePrice := kline.GetClose().Float64()
|
|
|
|
openPrice := kline.GetOpen().Float64()
|
2022-07-05 07:59:35 +00:00
|
|
|
|
|
|
|
// Supertrend signal
|
2022-06-02 05:32:57 +00:00
|
|
|
stSignal := s.Supertrend.GetSignal()
|
2022-07-05 07:59:35 +00:00
|
|
|
|
|
|
|
// DEMA signal
|
2022-05-27 06:36:48 +00:00
|
|
|
var demaSignal types.Direction
|
2022-06-02 05:47:16 +00:00
|
|
|
if closePrice > s.fastDEMA.Last() && closePrice > s.slowDEMA.Last() && !(openPrice > s.fastDEMA.Last() && openPrice > s.slowDEMA.Last()) {
|
2022-05-27 06:36:48 +00:00
|
|
|
demaSignal = types.DirectionUp
|
2022-06-02 05:47:16 +00:00
|
|
|
} else if closePrice < s.fastDEMA.Last() && closePrice < s.slowDEMA.Last() && !(openPrice < s.fastDEMA.Last() && openPrice < s.slowDEMA.Last()) {
|
2022-05-27 06:36:48 +00:00
|
|
|
demaSignal = types.DirectionDown
|
|
|
|
} else {
|
|
|
|
demaSignal = types.DirectionNone
|
|
|
|
}
|
|
|
|
|
2022-07-05 07:59:35 +00:00
|
|
|
// Linear Regression signal
|
|
|
|
var lgSignal types.Direction
|
|
|
|
if s.LinearRegression != nil {
|
|
|
|
switch {
|
|
|
|
case s.LinearRegression.baseLineSlope > 0:
|
|
|
|
lgSignal = types.DirectionUp
|
|
|
|
case s.LinearRegression.baseLineSlope < 0:
|
|
|
|
lgSignal = types.DirectionDown
|
|
|
|
default:
|
|
|
|
lgSignal = types.DirectionNone
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-06-01 02:51:57 +00:00
|
|
|
base := s.Position.GetBase()
|
|
|
|
baseSign := base.Sign()
|
|
|
|
|
2022-07-05 07:59:35 +00:00
|
|
|
// TP/SL if there's non-dust position and meets the criteria
|
2022-06-01 02:51:57 +00:00
|
|
|
if !s.Market.IsDustQuantity(base.Abs(), kline.GetClose()) {
|
2022-07-05 07:59:35 +00:00
|
|
|
stopNow := false
|
|
|
|
|
2022-05-31 04:53:14 +00:00
|
|
|
if s.StopLossByTriggeringK && !s.currentStopLossPrice.IsZero() && ((baseSign < 0 && kline.GetClose().Compare(s.currentStopLossPrice) > 0) || (baseSign > 0 && kline.GetClose().Compare(s.currentStopLossPrice) < 0)) {
|
2022-07-05 07:59:35 +00:00
|
|
|
// SL by triggering Kline low/high
|
|
|
|
bbgo.Notify("%s stop loss by triggering the kline low/high", s.Symbol)
|
|
|
|
stopNow = true
|
|
|
|
} else if s.TakeProfitAtrMultiplier > 0 && !s.currentTakeProfitPrice.IsZero() && ((baseSign < 0 && kline.GetClose().Compare(s.currentTakeProfitPrice) < 0) || (baseSign > 0 && kline.GetClose().Compare(s.currentTakeProfitPrice) > 0)) {
|
2022-05-31 04:53:14 +00:00
|
|
|
// TP by multiple of ATR
|
2022-07-05 07:59:35 +00:00
|
|
|
bbgo.Notify("%s take profit by multiple of ATR", s.Symbol)
|
|
|
|
stopNow = true
|
|
|
|
} else if s.StopByReversedSupertrend && ((baseSign < 0 && stSignal == types.DirectionUp) || (baseSign > 0 && stSignal == types.DirectionDown)) {
|
|
|
|
// Use supertrend signal to TP/SL
|
|
|
|
bbgo.Notify("%s stop by the reversed signal of Supertrend", s.Symbol)
|
|
|
|
stopNow = true
|
|
|
|
} else if s.StopByReversedDema && ((baseSign < 0 && demaSignal == types.DirectionUp) || (baseSign > 0 && demaSignal == types.DirectionDown)) {
|
|
|
|
// Use DEMA signal to TP/SL
|
|
|
|
bbgo.Notify("%s stop by the reversed signal of DEMA", s.Symbol)
|
|
|
|
stopNow = true
|
|
|
|
} else if s.StopByReversedLinGre && ((baseSign < 0 && lgSignal == types.DirectionUp) || (baseSign > 0 && lgSignal == types.DirectionDown)) {
|
|
|
|
// Use linear regression signal to TP/SL
|
|
|
|
bbgo.Notify("%s stop by the reversed signal of linear regression", s.Symbol)
|
|
|
|
stopNow = true
|
|
|
|
}
|
|
|
|
|
|
|
|
if stopNow {
|
2022-06-16 09:14:50 +00:00
|
|
|
if err := s.ClosePosition(ctx, fixedpoint.One); err == nil {
|
2022-05-31 04:53:14 +00:00
|
|
|
s.currentStopLossPrice = fixedpoint.Zero
|
|
|
|
s.currentTakeProfitPrice = fixedpoint.Zero
|
|
|
|
}
|
2022-06-30 08:35:00 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-05-30 08:07:36 +00:00
|
|
|
// Open position
|
2022-05-27 06:36:48 +00:00
|
|
|
var side types.SideType
|
2022-06-30 08:35:00 +00:00
|
|
|
if stSignal == types.DirectionUp && demaSignal == types.DirectionUp && (s.LinearRegression == nil || lgSignal == types.DirectionUp) {
|
2022-05-27 06:36:48 +00:00
|
|
|
side = types.SideTypeBuy
|
2022-05-31 04:53:14 +00:00
|
|
|
if s.StopLossByTriggeringK {
|
|
|
|
s.currentStopLossPrice = kline.GetLow()
|
|
|
|
}
|
2022-07-05 07:59:35 +00:00
|
|
|
if s.TakeProfitAtrMultiplier > 0 {
|
|
|
|
s.currentTakeProfitPrice = kline.GetClose().Add(fixedpoint.NewFromFloat(s.Supertrend.AverageTrueRange.Last() * s.TakeProfitAtrMultiplier))
|
2022-05-31 04:53:14 +00:00
|
|
|
}
|
2022-06-30 08:35:00 +00:00
|
|
|
} else if stSignal == types.DirectionDown && demaSignal == types.DirectionDown && (s.LinearRegression == nil || lgSignal == types.DirectionDown) {
|
2022-05-27 06:36:48 +00:00
|
|
|
side = types.SideTypeSell
|
2022-05-31 04:53:14 +00:00
|
|
|
if s.StopLossByTriggeringK {
|
|
|
|
s.currentStopLossPrice = kline.GetHigh()
|
|
|
|
}
|
2022-07-05 07:59:35 +00:00
|
|
|
if s.TakeProfitAtrMultiplier > 0 {
|
|
|
|
s.currentTakeProfitPrice = kline.GetClose().Sub(fixedpoint.NewFromFloat(s.Supertrend.AverageTrueRange.Last() * s.TakeProfitAtrMultiplier))
|
2022-05-31 04:53:14 +00:00
|
|
|
}
|
2022-05-27 06:36:48 +00:00
|
|
|
}
|
|
|
|
|
2022-06-17 02:15:54 +00:00
|
|
|
// The default value of side is an empty string. Unless side is set by the checks above, the result of the following condition is false
|
2022-05-27 06:36:48 +00:00
|
|
|
if side == types.SideTypeSell || side == types.SideTypeBuy {
|
2022-06-19 04:29:36 +00:00
|
|
|
bbgo.Notify("open %s position for signal %v", s.Symbol, side)
|
2022-05-31 04:53:14 +00:00
|
|
|
// Close opposite position if any
|
2022-06-16 09:14:50 +00:00
|
|
|
if !s.Position.IsDust(kline.GetClose()) {
|
|
|
|
if (side == types.SideTypeSell && s.Position.IsLong()) || (side == types.SideTypeBuy && s.Position.IsShort()) {
|
2022-06-19 04:29:36 +00:00
|
|
|
bbgo.Notify("close existing %s position before open a new position", s.Symbol)
|
2022-06-16 09:14:50 +00:00
|
|
|
_ = s.ClosePosition(ctx, fixedpoint.One)
|
2022-06-15 04:22:26 +00:00
|
|
|
} else {
|
2022-06-19 04:29:36 +00:00
|
|
|
bbgo.Notify("existing %s position has the same direction with the signal", s.Symbol)
|
2022-06-15 04:22:26 +00:00
|
|
|
return
|
2022-05-31 04:53:14 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-06-01 02:26:04 +00:00
|
|
|
orderForm := s.generateOrderForm(side, s.calculateQuantity(kline.GetClose()), types.SideEffectTypeMarginBuy)
|
2022-05-30 08:07:36 +00:00
|
|
|
log.Infof("submit open position order %v", orderForm)
|
2022-06-20 05:39:07 +00:00
|
|
|
_, err := s.orderExecutor.SubmitOrders(ctx, orderForm)
|
2022-05-27 06:36:48 +00:00
|
|
|
if err != nil {
|
2022-06-16 09:14:50 +00:00
|
|
|
log.WithError(err).Errorf("can not place %s open position order", s.Symbol)
|
2022-06-19 04:29:36 +00:00
|
|
|
bbgo.Notify("can not place %s open position order", s.Symbol)
|
2022-05-27 06:36:48 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
2022-05-30 08:48:07 +00:00
|
|
|
// Graceful shutdown
|
|
|
|
s.Graceful.OnShutdown(func(ctx context.Context, wg *sync.WaitGroup) {
|
|
|
|
defer wg.Done()
|
|
|
|
close(s.stopC)
|
|
|
|
|
2022-06-20 05:39:07 +00:00
|
|
|
_ = s.orderExecutor.GracefulCancel(ctx)
|
2022-05-30 08:48:07 +00:00
|
|
|
})
|
|
|
|
|
2022-05-27 06:36:48 +00:00
|
|
|
return nil
|
|
|
|
}
|