mirror of
https://github.com/c9s/bbgo.git
synced 2024-11-10 01:01:56 +00:00
pivotshort: improve market sell when breaks previous pivot low only
pivotshort: improve market sell when breaks previous pivot low only
This commit is contained in:
parent
48764c2b74
commit
3c40f9e90e
|
@ -3,10 +3,10 @@ sessions:
|
|||
binance:
|
||||
exchange: binance
|
||||
envVarPrefix: binance
|
||||
margin: true
|
||||
isolatedMargin: true
|
||||
isolatedMarginSymbol: GMTUSDT
|
||||
# futures: true
|
||||
# margin: true
|
||||
# isolatedMargin: true
|
||||
# isolatedMarginSymbol: GMTUSDT
|
||||
# futures: true
|
||||
|
||||
exchangeStrategies:
|
||||
- on: binance
|
||||
|
@ -17,28 +17,25 @@ exchangeStrategies:
|
|||
pivotLength: 120
|
||||
|
||||
entry:
|
||||
immediate: true
|
||||
catBounceRatio: 1%
|
||||
quantity: 20
|
||||
numLayers: 3
|
||||
marginOrderSideEffect: borrow
|
||||
quantity: 3000.0
|
||||
# marginOrderSideEffect: borrow
|
||||
|
||||
exit:
|
||||
takeProfitPercentage: 13%
|
||||
stopLossPercentage: 0.5%
|
||||
shadowTakeProfitRatio: 3%
|
||||
marginOrderSideEffect: repay
|
||||
takeProfitPercentage: 25%
|
||||
stopLossPercentage: 1%
|
||||
lowerShadowRatio: 0.95
|
||||
# marginOrderSideEffect: repay
|
||||
|
||||
|
||||
backtest:
|
||||
sessions:
|
||||
- binance
|
||||
startTime: "2022-04-01"
|
||||
startTime: "2022-05-01"
|
||||
endTime: "2022-06-03"
|
||||
symbols:
|
||||
- GMTUSDT
|
||||
account:
|
||||
binance:
|
||||
balances:
|
||||
GMT: 3_000.0
|
||||
USDT: 3_000.0
|
||||
GMT: 3010.0
|
||||
USDT: 1000.0
|
||||
|
|
|
@ -3,7 +3,6 @@ package pivotshort
|
|||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/c9s/bbgo/pkg/bbgo"
|
||||
|
@ -25,17 +24,14 @@ type IntervalWindowSetting struct {
|
|||
}
|
||||
|
||||
type Entry struct {
|
||||
Immediate bool `json:"immediate"`
|
||||
CatBounceRatio fixedpoint.Value `json:"catBounceRatio"`
|
||||
Quantity fixedpoint.Value `json:"quantity"`
|
||||
NumLayers int `json:"numLayers"`
|
||||
MarginSideEffect types.MarginOrderSideEffectType `json:"marginOrderSideEffect"`
|
||||
}
|
||||
|
||||
type Exit struct {
|
||||
TakeProfitPercentage fixedpoint.Value `json:"takeProfitPercentage"`
|
||||
StopLossPercentage fixedpoint.Value `json:"stopLossPercentage"`
|
||||
ShadowTPRatio fixedpoint.Value `json:"shadowTakeProfitRatio"`
|
||||
LowerShadowRatio fixedpoint.Value `json:"lowerShadowRatio"`
|
||||
MarginSideEffect types.MarginOrderSideEffectType `json:"marginOrderSideEffect"`
|
||||
}
|
||||
|
||||
|
@ -44,18 +40,17 @@ type Strategy struct {
|
|||
*bbgo.Notifiability
|
||||
*bbgo.Persistence
|
||||
|
||||
Environment *bbgo.Environment
|
||||
Symbol string `json:"symbol"`
|
||||
Market types.Market
|
||||
Interval types.Interval `json:"interval"`
|
||||
TotalQuantity fixedpoint.Value `json:"totalQuantity"`
|
||||
Environment *bbgo.Environment
|
||||
Symbol string `json:"symbol"`
|
||||
Market types.Market
|
||||
Interval types.Interval `json:"interval"`
|
||||
|
||||
// persistence fields
|
||||
Position *types.Position `json:"position,omitempty" persistence:"position"`
|
||||
ProfitStats *types.ProfitStats `json:"profitStats,omitempty" persistence:"profit_stats"`
|
||||
|
||||
PivotLength int `json:"pivotLength"`
|
||||
LastLow fixedpoint.Value
|
||||
LastLow float64
|
||||
|
||||
Entry Entry
|
||||
Exit Exit
|
||||
|
@ -67,7 +62,7 @@ type Strategy struct {
|
|||
session *bbgo.ExchangeSession
|
||||
|
||||
pivot *indicator.Pivot
|
||||
pivotLowPrices []fixedpoint.Value
|
||||
pivotLowPrices []float64
|
||||
|
||||
// StrategyController
|
||||
bbgo.StrategyController
|
||||
|
@ -80,7 +75,18 @@ func (s *Strategy) ID() string {
|
|||
func (s *Strategy) Subscribe(session *bbgo.ExchangeSession) {
|
||||
log.Infof("subscribe %s", s.Symbol)
|
||||
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: s.Interval})
|
||||
// session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: types.Interval1d})
|
||||
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: types.Interval1m})
|
||||
}
|
||||
|
||||
func (s *Strategy) submitOrders(ctx context.Context, orderExecutor bbgo.OrderExecutor, submitOrders ...types.SubmitOrder) {
|
||||
createdOrders, err := orderExecutor.SubmitOrders(ctx, submitOrders...)
|
||||
if err != nil {
|
||||
log.WithError(err).Errorf("can not place orders")
|
||||
}
|
||||
|
||||
s.orderStore.Add(createdOrders...)
|
||||
s.activeMakerOrders.Add(createdOrders...)
|
||||
s.tradeCollector.Process()
|
||||
}
|
||||
|
||||
func (s *Strategy) placeMarketSell(ctx context.Context, orderExecutor bbgo.OrderExecutor) {
|
||||
|
@ -113,66 +119,21 @@ func (s *Strategy) placeMarketSell(ctx context.Context, orderExecutor bbgo.Order
|
|||
s.submitOrders(ctx, orderExecutor, submitOrder)
|
||||
}
|
||||
|
||||
func (s *Strategy) placeOrder(ctx context.Context, lastLow fixedpoint.Value, limitPrice fixedpoint.Value, currentPrice fixedpoint.Value, qty fixedpoint.Value, orderExecutor bbgo.OrderExecutor) {
|
||||
submitOrder := types.SubmitOrder{
|
||||
Symbol: s.Symbol,
|
||||
Side: types.SideTypeSell,
|
||||
Type: types.OrderTypeLimit,
|
||||
Price: limitPrice,
|
||||
Quantity: qty,
|
||||
}
|
||||
if !lastLow.IsZero() && s.Entry.Immediate && lastLow.Compare(currentPrice) <= 0 {
|
||||
submitOrder.Type = types.OrderTypeMarket
|
||||
}
|
||||
if s.session.Margin {
|
||||
submitOrder.MarginSideEffect = s.Entry.MarginSideEffect
|
||||
}
|
||||
|
||||
s.submitOrders(ctx, orderExecutor, submitOrder)
|
||||
}
|
||||
|
||||
func (s *Strategy) submitOrders(ctx context.Context, orderExecutor bbgo.OrderExecutor, submitOrders ...types.SubmitOrder) {
|
||||
createdOrders, err := orderExecutor.SubmitOrders(ctx, submitOrders...)
|
||||
if err != nil {
|
||||
log.WithError(err).Errorf("can not place orders")
|
||||
}
|
||||
|
||||
s.orderStore.Add(createdOrders...)
|
||||
s.activeMakerOrders.Add(createdOrders...)
|
||||
s.tradeCollector.Process()
|
||||
// check if position can be close or not
|
||||
func canClosePosition(position *types.Position, price fixedpoint.Value) bool {
|
||||
return position.IsShort() && !(position.IsClosed() || position.IsDust(price))
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
submitOrder := s.Position.NewClosePositionOrder(percentage) //types.SubmitOrder{
|
||||
|
||||
// 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 {
|
||||
return fmt.Errorf("order quantity %v is too small, less than %v", quantity, s.Market.MinQuantity)
|
||||
}
|
||||
|
||||
submitOrder := types.SubmitOrder{
|
||||
Symbol: s.Symbol,
|
||||
Side: side,
|
||||
Type: types.OrderTypeMarket,
|
||||
Quantity: quantity,
|
||||
Market: s.Market,
|
||||
}
|
||||
if s.session.Margin {
|
||||
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 buy order to close position by %v", s.Symbol, percentage)
|
||||
|
||||
createdOrders, err := s.session.Exchange.SubmitOrders(ctx, submitOrder)
|
||||
createdOrders, err := s.session.Exchange.SubmitOrders(ctx, *submitOrder)
|
||||
if err != nil {
|
||||
log.WithError(err).Errorf("can not place position close order")
|
||||
}
|
||||
|
@ -186,57 +147,6 @@ func (s *Strategy) InstanceID() string {
|
|||
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)
|
||||
}
|
||||
|
||||
// findHigherPivotLow checks the pivot low prices and return the low that is higher than the current price
|
||||
func (s *Strategy) findHigherPivotLow(price fixedpoint.Value) (fixedpoint.Value, bool) {
|
||||
for l := len(s.pivotLowPrices) - 1; l > 0; l-- {
|
||||
if s.pivotLowPrices[l].Compare(price) > 0 {
|
||||
return s.pivotLowPrices[l], true
|
||||
}
|
||||
}
|
||||
|
||||
return price, false
|
||||
}
|
||||
|
||||
func (s *Strategy) placeBounceSellOrders(ctx context.Context, lastLow fixedpoint.Value, limitPrice fixedpoint.Value, currentPrice fixedpoint.Value, orderExecutor bbgo.OrderExecutor) {
|
||||
futuresMode := s.session.Futures || s.session.IsolatedFutures
|
||||
numLayers := fixedpoint.NewFromInt(int64(s.Entry.NumLayers))
|
||||
d := s.Entry.CatBounceRatio.Div(numLayers)
|
||||
q := s.Entry.Quantity
|
||||
if !s.TotalQuantity.IsZero() {
|
||||
q = s.TotalQuantity.Div(numLayers)
|
||||
}
|
||||
|
||||
for i := 0; i < s.Entry.NumLayers; i++ {
|
||||
balances := s.session.GetAccount().Balances()
|
||||
quoteBalance, _ := balances[s.Market.QuoteCurrency]
|
||||
baseBalance, _ := balances[s.Market.BaseCurrency]
|
||||
|
||||
p := limitPrice.Mul(fixedpoint.One.Add(s.Entry.CatBounceRatio.Sub(fixedpoint.NewFromFloat(d.Float64() * float64(i)))))
|
||||
|
||||
if futuresMode {
|
||||
// log.Infof("futures mode on")
|
||||
if q.Mul(p).Compare(quoteBalance.Available) <= 0 {
|
||||
s.placeOrder(ctx, lastLow, p, currentPrice, q, orderExecutor)
|
||||
}
|
||||
} else if s.Environment.IsBackTesting() {
|
||||
// log.Infof("spot backtest mode on")
|
||||
if q.Compare(baseBalance.Available) <= 0 {
|
||||
s.placeOrder(ctx, lastLow, p, currentPrice, q, orderExecutor)
|
||||
}
|
||||
} else {
|
||||
// log.Infof("spot mode on")
|
||||
if q.Compare(baseBalance.Available) <= 0 {
|
||||
s.placeOrder(ctx, lastLow, p, currentPrice, q, orderExecutor)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) error {
|
||||
// initial required information
|
||||
s.session = session
|
||||
|
@ -293,24 +203,49 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
|
|||
s.pivot = &indicator.Pivot{IntervalWindow: iw}
|
||||
s.pivot.Bind(st)
|
||||
|
||||
s.LastLow = fixedpoint.Zero
|
||||
s.LastLow = 0.
|
||||
|
||||
session.UserDataStream.OnStart(func() {
|
||||
if price, ok := session.LastPrice(s.Symbol); ok {
|
||||
if limitPrice, ok := s.findHigherPivotLow(price); ok {
|
||||
log.Infof("%s placing limit sell start from %f adds up to %f percent with %d layers of orders", s.Symbol, limitPrice.Float64(), s.Entry.CatBounceRatio.Mul(fixedpoint.NewFromInt(100)).Float64(), s.Entry.NumLayers)
|
||||
s.placeBounceSellOrders(ctx, s.LastLow, limitPrice, price, orderExecutor)
|
||||
}
|
||||
}
|
||||
//if price, ok := session.LastPrice(s.Symbol); ok {
|
||||
//if limitPrice, ok := s.findHigherPivotLow(price); ok {
|
||||
// log.Infof("%s placing limit sell start from %f adds up to %f percent with %d layers of orders", s.Symbol, limitPrice.Float64(), s.Entry.CatBounceRatio.Mul(fixedpoint.NewFromInt(100)).Float64(), s.Entry.NumLayers)
|
||||
// s.placeBounceSellOrders(ctx, limitPrice, price, orderExecutor)
|
||||
//}
|
||||
//}
|
||||
})
|
||||
|
||||
session.MarketDataStream.OnKLine(func(kline types.KLine) {
|
||||
// TODO: handle stop loss here, faster than closed kline
|
||||
_, found := s.findHigherPivotLow(kline.Close)
|
||||
if !found && s.Entry.Immediate && (s.Position.IsClosed() || s.Position.IsDust(kline.Close)) {
|
||||
s.Notify("price breaks the previous low, submitting market sell to open a short position")
|
||||
s.placeMarketSell(ctx, orderExecutor)
|
||||
// Always check whether you can open a short position or not
|
||||
session.MarketDataStream.OnKLineClosed(func(kline types.KLine) {
|
||||
if kline.Symbol != s.Symbol || kline.Interval != types.Interval1m {
|
||||
return
|
||||
}
|
||||
// TODO: handle stop loss here, faster than closed kline
|
||||
if canClosePosition(s.Position, kline.Close) {
|
||||
// calculate return rate
|
||||
R := kline.Close.Sub(s.Position.AverageCost).Div(s.Position.AverageCost)
|
||||
if R.Compare(s.Exit.StopLossPercentage) > 0 {
|
||||
// SL
|
||||
s.Notify("%s SL triggered", s.Symbol)
|
||||
s.ClosePosition(ctx, fixedpoint.One)
|
||||
} else if R.Compare(s.Exit.TakeProfitPercentage.Neg()) < 0 && kline.GetLowerShadowRatio().Compare(s.Exit.LowerShadowRatio) > 0 {
|
||||
// TP
|
||||
s.Notify("%s TP triggered", s.Symbol)
|
||||
s.ClosePosition(ctx, fixedpoint.One)
|
||||
}
|
||||
}
|
||||
|
||||
if len(s.pivotLowPrices) > 0 {
|
||||
latestPivotLow := s.pivotLowPrices[len(s.pivotLowPrices)-1]
|
||||
|
||||
if kline.Close.Float64() > latestPivotLow && (s.Position.IsClosed() || s.Position.IsDust(kline.Close)) {
|
||||
if err := s.activeMakerOrders.GracefulCancel(ctx, s.session.Exchange); err != nil {
|
||||
log.WithError(err).Errorf("graceful cancel order error")
|
||||
}
|
||||
s.Notify("price breaks the previous low, submitting market sell to open a short position")
|
||||
s.placeMarketSell(ctx, orderExecutor)
|
||||
}
|
||||
}
|
||||
|
||||
})
|
||||
|
||||
session.MarketDataStream.OnKLineClosed(func(kline types.KLine) {
|
||||
|
@ -320,41 +255,10 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
|
|||
|
||||
if s.pivot.LastLow() > 0. {
|
||||
log.Infof("pivot low signal detected: %f %s", s.pivot.LastLow(), kline.EndTime.Time())
|
||||
s.LastLow = fixedpoint.NewFromFloat(s.pivot.LastLow())
|
||||
} else {
|
||||
if canClosePosition(s.Position, s.LastLow, kline.Close) {
|
||||
R := kline.Close.Div(s.Position.AverageCost)
|
||||
if R.Compare(fixedpoint.One.Add(s.Exit.StopLossPercentage)) > 0 {
|
||||
// SL
|
||||
s.Notify("%s SL triggered", s.Symbol)
|
||||
s.ClosePosition(ctx, fixedpoint.One)
|
||||
s.tradeCollector.Process()
|
||||
} else if R.Compare(fixedpoint.One.Sub(s.Exit.TakeProfitPercentage)) < 0 {
|
||||
// TP
|
||||
s.Notify("%s TP triggered", s.Symbol)
|
||||
s.ClosePosition(ctx, fixedpoint.One)
|
||||
} else if kline.GetLowerShadowHeight().Div(kline.Close).Compare(s.Exit.ShadowTPRatio) > 0 {
|
||||
// shadow TP
|
||||
s.Notify("%s shadow TP triggered", s.Symbol)
|
||||
s.ClosePosition(ctx, fixedpoint.One)
|
||||
}
|
||||
}
|
||||
s.LastLow = fixedpoint.Zero
|
||||
}
|
||||
|
||||
if !s.LastLow.IsZero() {
|
||||
|
||||
s.LastLow = s.pivot.LastLow()
|
||||
s.pivotLowPrices = append(s.pivotLowPrices, s.LastLow)
|
||||
|
||||
if err := s.activeMakerOrders.GracefulCancel(ctx, s.session.Exchange); err != nil {
|
||||
log.WithError(err).Errorf("graceful cancel order error")
|
||||
}
|
||||
|
||||
if limitPrice, ok := s.findHigherPivotLow(kline.Close); ok {
|
||||
log.Infof("%s place limit sell start from %f adds up to %f percent with %d layers of orders", s.Symbol, limitPrice.Float64(), s.Entry.CatBounceRatio.Mul(fixedpoint.NewFromInt(100)).Float64(), s.Entry.NumLayers)
|
||||
s.placeBounceSellOrders(ctx, s.LastLow, limitPrice, kline.Close, orderExecutor)
|
||||
}
|
||||
}
|
||||
|
||||
})
|
||||
|
||||
return nil
|
||||
|
|
Loading…
Reference in New Issue
Block a user