pivotshort: improve post order & add margin

This commit is contained in:
austin362667 2022-06-02 21:34:26 +08:00
parent 6936503cde
commit 2aac5bb273
2 changed files with 57 additions and 34 deletions

View File

@ -8,24 +8,29 @@ sessions:
exchangeStrategies: exchangeStrategies:
- on: binance - on: binance
pivotshort: pivotshort:
symbol: BTCBUSD symbol: GMTUSDT
interval: 5m interval: 5m
quantity: 1.0
pivotLength: 60 pivotLength: 120
stopLossRatio: 0.8% stopLossRatio: 0.5%
catBounceRatio: 3% takeProfitRatio: 13%
numLayers: 5
shadowTPRatio: 2% shadowTPRatio: 2%
catBounceRatio: 1%
quantity: 1200
numLayers: 4
# marginOrderSideEffect: borrow
backtest: backtest:
sessions: sessions:
- binance - binance
startTime: "2022-01-01" startTime: "2022-04-01"
endTime: "2022-05-10" endTime: "2022-06-03"
symbols: symbols:
- BTCBUSD - GMTUSDT
account: account:
binance: binance:
balances: balances:
BTC: 1.0 GMT: 5_000.0
BUSD: 40_000.0 USDT: 5_000.0

View File

@ -13,10 +13,6 @@ import (
const ID = "pivotshort" const ID = "pivotshort"
var fifteen = fixedpoint.NewFromInt(15)
var three = fixedpoint.NewFromInt(3)
var two = fixedpoint.NewFromInt(2)
var log = logrus.WithField("strategy", ID) var log = logrus.WithField("strategy", ID)
func init() { func init() {
@ -32,21 +28,24 @@ type Strategy struct {
*bbgo.Notifiability *bbgo.Notifiability
*bbgo.Persistence *bbgo.Persistence
Environment *bbgo.Environment Environment *bbgo.Environment
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"` Quantity fixedpoint.Value `json:"quantity"`
TotalQuantity fixedpoint.Value `json:"totalQuantity"`
// persistence fields // persistence fields
Position *types.Position `json:"position,omitempty" persistence:"position"` Position *types.Position `json:"position,omitempty" persistence:"position"`
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"` StopLossRatio fixedpoint.Value `json:"stopLossRatio"`
CatBounceRatio fixedpoint.Value `json:"catBounceRatio"` TakeProfitRatio fixedpoint.Value `json:"takeProfitRatio"`
NumLayers fixedpoint.Value `json:"numLayers"` CatBounceRatio fixedpoint.Value `json:"catBounceRatio"`
ShadowTPRatio fixedpoint.Value `json:"shadowTPRatio"` 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
@ -78,6 +77,10 @@ func (s *Strategy) placeOrder(ctx context.Context, price fixedpoint.Value, qty f
Price: price, Price: price,
Quantity: qty, Quantity: qty,
} }
if s.session.Margin {
submitOrder.MarginSideEffect = s.MarginOrderSideEffect
}
createdOrders, err := orderExecutor.SubmitOrders(ctx, submitOrder) createdOrders, err := orderExecutor.SubmitOrders(ctx, submitOrder)
if err != nil { if err != nil {
log.WithError(err).Errorf("can not place orders") log.WithError(err).Errorf("can not place orders")
@ -197,32 +200,33 @@ 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.CatBounceRatio.Div(s.NumLayers)
q := s.Quantity.Div(s.NumLayers) q := s.Quantity
log.Info(futuresMode) if !s.TotalQuantity.IsZero() {
q = s.TotalQuantity.Div(s.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 err := s.activeMakerOrders.GracefulCancel(ctx, s.session.Exchange); err != nil {
log.WithError(err).Errorf("graceful cancel order error")
}
if s.pivot.LastLow() > 0. { if s.pivot.LastLow() > 0. {
log.Info(s.pivot.LastLow(), kline.EndTime) log.Info(s.pivot.LastLow(), kline.EndTime)
lastLow = fixedpoint.NewFromFloat(s.pivot.LastLow()) lastLow = fixedpoint.NewFromFloat(s.pivot.LastLow())
} else { } else {
if !lastLow.IsZero() && !s.Position.GetBase().IsZero() { if !lastLow.IsZero() && s.Position.IsShort() && !s.Position.IsDust(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.StopLossRatio)) > 0 {
// SL // SL
log.Infof("SL triggered") log.Infof("SL triggered")
s.ClosePosition(ctx, fixedpoint.One) s.ClosePosition(ctx, fixedpoint.One)
s.tradeCollector.Process() s.tradeCollector.Process()
} else if R.Compare(fixedpoint.One.Sub(s.StopLossRatio.Mul(fifteen))) < 0 { } else if R.Compare(fixedpoint.One.Sub(s.TakeProfitRatio)) < 0 {
// TP // TP
log.Infof("TP triggered") log.Infof("TP triggered")
s.ClosePosition(ctx, fixedpoint.One) s.ClosePosition(ctx, fixedpoint.One)
s.tradeCollector.Process()
} else if kline.GetLowerShadowHeight().Div(kline.Close).Compare(s.ShadowTPRatio) > 0 { } else if kline.GetLowerShadowHeight().Div(kline.Close).Compare(s.ShadowTPRatio) > 0 {
// shadow TP // shadow TP
log.Infof("shadow TP triggered") log.Infof("shadow TP triggered")
@ -235,12 +239,26 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
if !lastLow.IsZero() { if !lastLow.IsZero() {
pivotBuffer = append(pivotBuffer, lastLow)
if err := s.activeMakerOrders.GracefulCancel(ctx, s.session.Exchange); err != nil {
log.WithError(err).Errorf("graceful cancel order error")
}
postPrice := kline.Close
for l := len(pivotBuffer) - 1; l > 0; l-- {
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.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 := lastLow.Mul(fixedpoint.One.Add(s.CatBounceRatio.Sub(fixedpoint.NewFromFloat(d.Float64() * float64(i))))) p := postPrice.Mul(fixedpoint.One.Add(s.CatBounceRatio.Sub(fixedpoint.NewFromFloat(d.Float64() * float64(i)))))
// //
if futuresMode { if futuresMode {
//log.Infof("futures mode on ") //log.Infof("futures mode on ")