pivotshort: clean up

This commit is contained in:
austin362667 2022-06-03 16:38:06 +08:00
parent 30be15dd34
commit 9dab39849b
2 changed files with 74 additions and 56 deletions

View File

@ -12,16 +12,21 @@ exchangeStrategies:
interval: 5m interval: 5m
pivotLength: 120 pivotLength: 120
stopLossRatio: 0.5%
takeProfitRatio: 13%
shadowTPRatio: 2%
entry:
catBounceRatio: 1% catBounceRatio: 1%
quantity: 1200 quantity: 1000
numLayers: 4 numLayers: 3
# marginOrderSideEffect: borrow # marginOrderSideEffect: borrow
exit:
takeProfitPercentage: 13%
stopLossPercentage: 0.5%
shadowTPRatio: 13%
# marginOrderSideEffect: repay
backtest: backtest:
sessions: sessions:
- binance - binance
@ -32,5 +37,5 @@ backtest:
account: account:
binance: binance:
balances: balances:
GMT: 5_000.0 GMT: 3_000.0
USDT: 5_000.0 USDT: 3_000.0

View File

@ -23,6 +23,20 @@ type IntervalWindowSetting struct {
types.IntervalWindow types.IntervalWindow
} }
type Entry struct {
CatBounceRatio fixedpoint.Value `json:"catBounceRatio"`
Quantity fixedpoint.Value `json:"quantity"`
NumLayers fixedpoint.Value `json:"numLayers"`
MarginSideEffect types.MarginOrderSideEffectType `json:"marginOrderSideEffect"`
}
type Exit struct {
TakeProfitPercentage fixedpoint.Value `json:"takeProfitPercentage"`
StopLossPercentage fixedpoint.Value `json:"stopLossPercentage"`
ShadowTPRatio fixedpoint.Value `json:"shadowTPRatio"`
MarginSideEffect types.MarginOrderSideEffectType `json:"marginOrderSideEffect"`
}
type Strategy struct { type Strategy struct {
*bbgo.Graceful *bbgo.Graceful
*bbgo.Notifiability *bbgo.Notifiability
@ -32,7 +46,6 @@ type Strategy struct {
Symbol string `json:"symbol"` Symbol string `json:"symbol"`
Market types.Market Market types.Market
Interval types.Interval `json:"interval"` Interval types.Interval `json:"interval"`
Quantity fixedpoint.Value `json:"quantity"`
TotalQuantity fixedpoint.Value `json:"totalQuantity"` TotalQuantity fixedpoint.Value `json:"totalQuantity"`
// persistence fields // persistence fields
@ -40,12 +53,9 @@ type Strategy struct {
ProfitStats *types.ProfitStats `json:"profitStats,omitempty" persistence:"profit_stats"` ProfitStats *types.ProfitStats `json:"profitStats,omitempty" persistence:"profit_stats"`
PivotLength int `json:"pivotLength"` PivotLength int `json:"pivotLength"`
StopLossRatio fixedpoint.Value `json:"stopLossRatio"`
TakeProfitRatio fixedpoint.Value `json:"takeProfitRatio"` Entry Entry
CatBounceRatio fixedpoint.Value `json:"catBounceRatio"` Exit Exit
NumLayers fixedpoint.Value `json:"numLayers"`
ShadowTPRatio fixedpoint.Value `json:"shadowTPRatio"`
MarginOrderSideEffect types.MarginOrderSideEffectType `json:"marginOrderSideEffect"`
activeMakerOrders *bbgo.LocalActiveOrderBook activeMakerOrders *bbgo.LocalActiveOrderBook
orderStore *bbgo.OrderStore orderStore *bbgo.OrderStore
@ -54,6 +64,7 @@ type Strategy struct {
session *bbgo.ExchangeSession session *bbgo.ExchangeSession
pivot *indicator.Pivot pivot *indicator.Pivot
pivotBuffer []fixedpoint.Value
// StrategyController // StrategyController
bbgo.StrategyController bbgo.StrategyController
@ -78,7 +89,7 @@ func (s *Strategy) placeOrder(ctx context.Context, price fixedpoint.Value, qty f
Quantity: qty, Quantity: qty,
} }
if s.session.Margin { if s.session.Margin {
submitOrder.MarginSideEffect = s.MarginOrderSideEffect submitOrder.MarginSideEffect = s.Entry.MarginSideEffect
} }
createdOrders, err := orderExecutor.SubmitOrders(ctx, submitOrder) createdOrders, err := orderExecutor.SubmitOrders(ctx, submitOrder)
@ -115,7 +126,7 @@ func (s *Strategy) ClosePosition(ctx context.Context, percentage fixedpoint.Valu
Market: s.Market, Market: s.Market,
} }
if s.session.Margin { if s.session.Margin {
submitOrder.MarginSideEffect = s.MarginOrderSideEffect submitOrder.MarginSideEffect = s.Exit.MarginSideEffect
} }
//s.Notify("Submitting %s %s order to close position by %v", s.Symbol, side.String(), percentage, submitOrder) //s.Notify("Submitting %s %s order to close position by %v", s.Symbol, side.String(), percentage, submitOrder)
@ -133,13 +144,24 @@ func (s *Strategy) InstanceID() string {
return fmt.Sprintf("%s:%s", ID, s.Symbol) return fmt.Sprintf("%s:%s", ID, s.Symbol)
} }
// check if position can be close or not
func canClosePosition(position *types.Position, signal fixedpoint.Value, price fixedpoint.Value) bool {
return !signal.IsZero() && position.IsShort() && !position.IsDust(price)
}
// get last available pivot low, the most recent pivot point higher than current price
func (s *Strategy) getValidPivotLow(price fixedpoint.Value) fixedpoint.Value {
for l := len(s.pivotBuffer) - 1; l > 0; l-- {
if s.pivotBuffer[l].Compare(price) > 0 {
return s.pivotBuffer[l]
}
}
return price
}
func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) error { func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) error {
// initial required information // initial required information
s.session = session s.session = session
//s.prevClose = fixedpoint.Zero
// first we need to get market data store(cached market data) from the exchange session
//st, _ := session.MarketDataStore(s.Symbol)
s.activeMakerOrders = bbgo.NewLocalActiveOrderBook(s.Symbol) s.activeMakerOrders = bbgo.NewLocalActiveOrderBook(s.Symbol)
s.activeMakerOrders.BindStream(session.UserDataStream) s.activeMakerOrders.BindStream(session.UserDataStream)
@ -151,9 +173,7 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
s.Position = types.NewPositionFromMarket(s.Market) s.Position = types.NewPositionFromMarket(s.Market)
} }
// calculate group id for orders
instanceID := s.InstanceID() instanceID := s.InstanceID()
//s.groupID = util.FNV32(instanceID)
// Always update the position fields // Always update the position fields
s.Position.Strategy = ID s.Position.Strategy = ID
@ -202,37 +222,35 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
var lastLow fixedpoint.Value var lastLow fixedpoint.Value
futuresMode := s.session.Futures || s.session.IsolatedFutures futuresMode := s.session.Futures || s.session.IsolatedFutures
d := s.CatBounceRatio.Div(s.NumLayers) d := s.Entry.CatBounceRatio.Div(s.Entry.NumLayers)
q := s.Quantity q := s.Entry.Quantity
if !s.TotalQuantity.IsZero() { if !s.TotalQuantity.IsZero() {
q = s.TotalQuantity.Div(s.NumLayers) q = s.TotalQuantity.Div(s.Entry.NumLayers)
} }
var pivotBuffer []fixedpoint.Value
session.MarketDataStream.OnKLineClosed(func(kline types.KLine) { session.MarketDataStream.OnKLineClosed(func(kline types.KLine) {
if kline.Symbol != s.Symbol || kline.Interval != s.Interval { if kline.Symbol != s.Symbol || kline.Interval != s.Interval {
return return
} }
if s.pivot.LastLow() > 0. { if s.pivot.LastLow() > 0. {
log.Info(s.pivot.LastLow(), kline.EndTime) log.Infof("pivot low signal detected: %f %s", s.pivot.LastLow(), kline.EndTime.Time())
lastLow = fixedpoint.NewFromFloat(s.pivot.LastLow()) lastLow = fixedpoint.NewFromFloat(s.pivot.LastLow())
} else { } else {
if !lastLow.IsZero() && s.Position.IsShort() && !s.Position.IsDust(kline.Close) { if canClosePosition(s.Position, lastLow, kline.Close) {
R := kline.Close.Div(s.Position.AverageCost) R := kline.Close.Div(s.Position.AverageCost)
if R.Compare(fixedpoint.One.Add(s.StopLossRatio)) > 0 { if R.Compare(fixedpoint.One.Add(s.Exit.StopLossPercentage)) > 0 {
// SL // SL
log.Infof("SL triggered") log.Infof("%s SL triggered", s.Symbol)
s.ClosePosition(ctx, fixedpoint.One) s.ClosePosition(ctx, fixedpoint.One)
s.tradeCollector.Process() s.tradeCollector.Process()
} else if R.Compare(fixedpoint.One.Sub(s.TakeProfitRatio)) < 0 { } else if R.Compare(fixedpoint.One.Sub(s.Exit.TakeProfitPercentage)) < 0 {
// TP // TP
log.Infof("TP triggered") log.Infof("%s TP triggered", s.Symbol)
s.ClosePosition(ctx, fixedpoint.One) s.ClosePosition(ctx, fixedpoint.One)
} else if kline.GetLowerShadowHeight().Div(kline.Close).Compare(s.ShadowTPRatio) > 0 { } else if kline.GetLowerShadowHeight().Div(kline.Close).Compare(s.Exit.ShadowTPRatio) > 0 {
// shadow TP // shadow TP
log.Infof("shadow TP triggered") log.Infof("%s shadow TP triggered", s.Symbol)
s.ClosePosition(ctx, fixedpoint.One) s.ClosePosition(ctx, fixedpoint.One)
s.tradeCollector.Process() s.tradeCollector.Process()
} }
@ -242,42 +260,37 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
if !lastLow.IsZero() { if !lastLow.IsZero() {
pivotBuffer = append(pivotBuffer, lastLow) s.pivotBuffer = append(s.pivotBuffer, lastLow)
if err := s.activeMakerOrders.GracefulCancel(ctx, s.session.Exchange); err != nil { if err := s.activeMakerOrders.GracefulCancel(ctx, s.session.Exchange); err != nil {
log.WithError(err).Errorf("graceful cancel order error") log.WithError(err).Errorf("graceful cancel order error")
} }
postPrice := kline.Close limitPrice := s.getValidPivotLow(kline.Close)
for l := len(pivotBuffer) - 1; l > 0; l-- { log.Infof("place limit sell start from %f adds up to %f percent with %f layers of orders", limitPrice.Float64(), s.Entry.CatBounceRatio.Mul(fixedpoint.NewFromInt(100)).Float64(), s.Entry.NumLayers.Float64())
if pivotBuffer[l].Compare(kline.Close) > 0 {
postPrice = pivotBuffer[l]
break
}
}
for i := 0; i < int(s.NumLayers.Float64()); i++ { for i := 0; i < int(s.Entry.NumLayers.Float64()); i++ {
balances := s.session.GetAccount().Balances() balances := s.session.GetAccount().Balances()
quoteBalance, _ := balances[s.Market.QuoteCurrency] quoteBalance, _ := balances[s.Market.QuoteCurrency]
baseBalance, _ := balances[s.Market.BaseCurrency] baseBalance, _ := balances[s.Market.BaseCurrency]
p := postPrice.Mul(fixedpoint.One.Add(s.CatBounceRatio.Sub(fixedpoint.NewFromFloat(d.Float64() * float64(i))))) p := limitPrice.Mul(fixedpoint.One.Add(s.Entry.CatBounceRatio.Sub(fixedpoint.NewFromFloat(d.Float64() * float64(i)))))
//
if futuresMode { if futuresMode {
//log.Infof("futures mode on") //log.Infof("futures mode on")
if q.Mul(p).Compare(quoteBalance.Available) < 0 { if q.Mul(p).Compare(quoteBalance.Available) <= 0 {
s.placeOrder(ctx, p, q, orderExecutor) s.placeOrder(ctx, p, q, orderExecutor)
s.tradeCollector.Process() s.tradeCollector.Process()
} }
} else if s.Environment.IsBackTesting() { } else if s.Environment.IsBackTesting() {
//log.Infof("spot backtest mode on") //log.Infof("spot backtest mode on")
if q.Compare(baseBalance.Available) < 0 { if q.Compare(baseBalance.Available) <= 0 {
s.placeOrder(ctx, p, q, orderExecutor) s.placeOrder(ctx, p, q, orderExecutor)
s.tradeCollector.Process() s.tradeCollector.Process()
} }
} else { } else {
//log.Infof("spot mode on") //log.Infof("spot mode on")
if q.Compare(baseBalance.Available) < 0 { if q.Compare(baseBalance.Available) <= 0 {
s.placeOrder(ctx, p, q, orderExecutor) s.placeOrder(ctx, p, q, orderExecutor)
s.tradeCollector.Process() s.tradeCollector.Process()
} }