Merge pull request #791 from c9s/strategy/pivotshort

strategy: pivotshort: refactor breaklow logics
This commit is contained in:
Yo-An Lin 2022-07-01 18:05:00 +08:00 committed by GitHub
commit f2ba901b51
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 241 additions and 259 deletions

View File

@ -65,7 +65,7 @@ func (e *GeneralOrderExecutor) BindProfitStats(profitStats *types.ProfitStats) {
}
profitStats.AddProfit(*profit)
Notify(&profitStats)
Notify(profitStats)
})
}

View File

@ -215,18 +215,6 @@ func (s *Strategy) ClosePosition(ctx context.Context, percentage fixedpoint.Valu
return s.orderExecutor.ClosePosition(ctx, percentage)
}
// Deprecated: LoadState method is migrated to the persistence struct tag.
func (s *Strategy) LoadState() error {
var state State
// load position
if err := s.Persistence.Load(&state, ID, s.Symbol, stateKey); err == nil {
s.state = &state
}
return nil
}
func (s *Strategy) getCurrentAllowedExposurePosition(bandPercentage float64) (fixedpoint.Value, error) {
if s.DynamicExposurePositionScale != nil {
v, err := s.DynamicExposurePositionScale.Scale(bandPercentage)
@ -505,18 +493,8 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
// If position is nil, we need to allocate a new position for calculation
if s.Position == nil {
// restore state (legacy)
if err := s.LoadState(); err != nil {
return err
}
// fallback to the legacy position struct in the state
if s.state != nil && s.state.Position != nil && !s.state.Position.Base.IsZero() {
s.Position = s.state.Position
} else {
s.Position = types.NewPositionFromMarket(s.Market)
}
}
if s.session.MakerFeeRate.Sign() > 0 || s.session.TakerFeeRate.Sign() > 0 {
s.Position.SetExchangeFeeRate(s.session.ExchangeName, types.ExchangeFee{
@ -526,14 +504,8 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
}
if s.ProfitStats == nil {
if s.state != nil {
// copy profit stats
p2 := s.state.ProfitStats
s.ProfitStats = &p2
} else {
s.ProfitStats = types.NewProfitStats(s.Market)
}
}
// Always update the position fields
s.Position.Strategy = ID

View File

@ -0,0 +1,193 @@
package pivotshort
import (
"context"
"github.com/c9s/bbgo/pkg/bbgo"
"github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/indicator"
"github.com/c9s/bbgo/pkg/types"
)
// BreakLow -- when price breaks the previous pivot low, we set a trade entry
type BreakLow struct {
Symbol string
Market types.Market
types.IntervalWindow
// Ratio is a number less than 1.0, price * ratio will be the price triggers the short order.
Ratio fixedpoint.Value `json:"ratio"`
// MarketOrder is the option to enable market order short.
MarketOrder bool `json:"marketOrder"`
// BounceRatio is a ratio used for placing the limit order sell price
// limit sell price = breakLowPrice * (1 + BounceRatio)
BounceRatio fixedpoint.Value `json:"bounceRatio"`
Quantity fixedpoint.Value `json:"quantity"`
StopEMARange fixedpoint.Value `json:"stopEMARange"`
StopEMA *types.IntervalWindow `json:"stopEMA"`
lastLow fixedpoint.Value
pivot *indicator.Pivot
stopEWMA *indicator.EWMA
pivotLowPrices []fixedpoint.Value
orderExecutor *bbgo.GeneralOrderExecutor
session *bbgo.ExchangeSession
}
func (s *BreakLow) Bind(session *bbgo.ExchangeSession, orderExecutor *bbgo.GeneralOrderExecutor) {
s.session = session
s.orderExecutor = orderExecutor
position := orderExecutor.Position()
symbol := position.Symbol
store, _ := session.MarketDataStore(symbol)
standardIndicator, _ := session.StandardIndicatorSet(symbol)
s.lastLow = fixedpoint.Zero
s.pivot = &indicator.Pivot{IntervalWindow: s.IntervalWindow}
s.pivot.Bind(store)
preloadPivot(s.pivot, store)
if s.StopEMA != nil {
s.stopEWMA = standardIndicator.EWMA(*s.StopEMA)
}
// update pivot low data
session.MarketDataStream.OnKLineClosed(types.KLineWith(symbol, s.Interval, func(kline types.KLine) {
lastLow := fixedpoint.NewFromFloat(s.pivot.LastLow())
if lastLow.IsZero() {
return
}
if lastLow.Compare(s.lastLow) != 0 {
log.Infof("new pivot low detected: %f %s", s.pivot.LastLow(), kline.EndTime.Time())
}
s.lastLow = lastLow
s.pivotLowPrices = append(s.pivotLowPrices, s.lastLow)
}))
session.MarketDataStream.OnKLineClosed(types.KLineWith(symbol, types.Interval1m, func(kline types.KLine) {
if position.IsOpened(kline.Close) {
return
}
if len(s.pivotLowPrices) == 0 {
log.Infof("currently there is no pivot low prices, skip placing orders...")
return
}
previousLow := s.pivotLowPrices[len(s.pivotLowPrices)-1]
// truncate the pivot low prices
if len(s.pivotLowPrices) > 10 {
s.pivotLowPrices = s.pivotLowPrices[len(s.pivotLowPrices)-10:]
}
ratio := fixedpoint.One.Add(s.Ratio)
breakPrice := previousLow.Mul(ratio)
openPrice := kline.Open
closePrice := kline.Close
// if previous low is not break, skip
if closePrice.Compare(breakPrice) >= 0 {
return
}
// we need the price cross the break line or we do nothing
if !(openPrice.Compare(breakPrice) > 0 && closePrice.Compare(breakPrice) < 0) {
log.Infof("%s kline is not between the break low price %f", kline.Symbol, breakPrice.Float64())
return
}
// force direction to be down
if closePrice.Compare(openPrice) >= 0 {
log.Infof("%s price %f is closed higher than the open price %f, skip this break", kline.Symbol, closePrice.Float64(), openPrice.Float64())
// skip UP klines
return
}
log.Infof("%s breakLow signal detected, closed price %f < breakPrice %f", kline.Symbol, closePrice.Float64(), breakPrice.Float64())
// stop EMA protection
if s.stopEWMA != nil {
ema := fixedpoint.NewFromFloat(s.stopEWMA.Last())
if ema.IsZero() {
return
}
emaStopShortPrice := ema.Mul(fixedpoint.One.Sub(s.StopEMARange))
if closePrice.Compare(emaStopShortPrice) < 0 {
log.Infof("stopEMA protection: close price %f < EMA(%v) = %f", closePrice.Float64(), s.StopEMA, ema.Float64())
return
}
}
ctx := context.Background()
// graceful cancel all active orders
_ = orderExecutor.GracefulCancel(ctx)
quantity := s.useQuantityOrBaseBalance(s.Quantity)
if s.MarketOrder {
bbgo.Notify("%s price %f breaks the previous low %f with ratio %f, submitting market sell to open a short position", symbol, kline.Close.Float64(), previousLow.Float64(), s.Ratio.Float64())
_, _ = s.orderExecutor.SubmitOrders(ctx, types.SubmitOrder{
Symbol: s.Symbol,
Side: types.SideTypeSell,
Type: types.OrderTypeMarket,
Quantity: quantity,
MarginSideEffect: types.SideEffectTypeMarginBuy,
Tag: "breakLowMarket",
})
} else {
sellPrice := previousLow.Mul(fixedpoint.One.Add(s.BounceRatio))
bbgo.Notify("%s price %f breaks the previous low %f with ratio %f, submitting limit sell @ %f", symbol, kline.Close.Float64(), previousLow.Float64(), s.Ratio.Float64(), sellPrice.Float64())
_, _ = s.orderExecutor.SubmitOrders(ctx, types.SubmitOrder{
Symbol: kline.Symbol,
Side: types.SideTypeSell,
Type: types.OrderTypeLimit,
Price: sellPrice,
Quantity: quantity,
MarginSideEffect: types.SideEffectTypeMarginBuy,
Tag: "breakLowLimit",
})
}
}))
if !bbgo.IsBackTesting {
// use market trade to submit short order
session.MarketDataStream.OnMarketTrade(func(trade types.Trade) {
})
}
}
func (s *BreakLow) useQuantityOrBaseBalance(quantity fixedpoint.Value) fixedpoint.Value {
if s.session.Margin || s.session.IsolatedMargin || s.session.Futures || s.session.IsolatedFutures {
return quantity
}
balance, hasBalance := s.session.Account.Balance(s.Market.BaseCurrency)
if hasBalance {
if quantity.IsZero() {
bbgo.Notify("sell quantity is not set, submitting sell with all base balance: %s", balance.Available.String())
quantity = balance.Available
} else {
quantity = fixedpoint.Min(quantity, balance.Available)
}
}
if quantity.IsZero() {
log.Errorf("quantity is zero, can not submit sell order, please check settings")
}
return quantity
}

View File

@ -2,6 +2,7 @@ package pivotshort
import (
"context"
"sort"
"github.com/c9s/bbgo/pkg/bbgo"
"github.com/c9s/bbgo/pkg/fixedpoint"
@ -144,3 +145,28 @@ func (s *ResistanceShort) placeResistanceOrders(ctx context.Context, resistanceP
}
s.activeOrders.Add(createdOrders...)
}
func findPossibleResistancePrices(closePrice float64, minDistance float64, lows []float64) []float64 {
// sort float64 in increasing order
// lower to higher prices
sort.Float64s(lows)
var resistancePrices []float64
for _, low := range lows {
if low < closePrice {
continue
}
last := closePrice
if len(resistancePrices) > 0 {
last = resistancePrices[len(resistancePrices)-1]
}
if (low / last) < (1.0 + minDistance) {
continue
}
resistancePrices = append(resistancePrices, low)
}
return resistancePrices
}

View File

@ -4,7 +4,6 @@ import (
"context"
"fmt"
"os"
"sort"
"sync"
"github.com/sirupsen/logrus"
@ -31,23 +30,6 @@ type IntervalWindowSetting struct {
types.IntervalWindow
}
// BreakLow -- when price breaks the previous pivot low, we set a trade entry
type BreakLow struct {
// Ratio is a number less than 1.0, price * ratio will be the price triggers the short order.
Ratio fixedpoint.Value `json:"ratio"`
// MarketOrder is the option to enable market order short.
MarketOrder bool `json:"marketOrder"`
// BounceRatio is a ratio used for placing the limit order sell price
// limit sell price = breakLowPrice * (1 + BounceRatio)
BounceRatio fixedpoint.Value `json:"bounceRatio"`
Quantity fixedpoint.Value `json:"quantity"`
StopEMARange fixedpoint.Value `json:"stopEMARange"`
StopEMA *types.IntervalWindow `json:"stopEMA"`
}
type Strategy struct {
Environment *bbgo.Environment
Symbol string `json:"symbol"`
@ -62,7 +44,7 @@ type Strategy struct {
TradeStats *types.TradeStats `persistence:"trade_stats"`
// BreakLow is one of the entry method
BreakLow BreakLow `json:"breakLow"`
BreakLow *BreakLow `json:"breakLow"`
// ResistanceShort is one of the entry method
ResistanceShort *ResistanceShort `json:"resistanceShort"`
@ -72,12 +54,6 @@ type Strategy struct {
session *bbgo.ExchangeSession
orderExecutor *bbgo.GeneralOrderExecutor
lastLow fixedpoint.Value
pivot *indicator.Pivot
resistancePivot *indicator.Pivot
stopEWMA *indicator.EWMA
pivotLowPrices []fixedpoint.Value
// StrategyController
bbgo.StrategyController
}
@ -95,6 +71,10 @@ func (s *Strategy) Subscribe(session *bbgo.ExchangeSession) {
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: s.ResistanceShort.Interval})
}
if s.BreakLow != nil {
dynamic.InheritStructValues(s.BreakLow, s)
}
if !bbgo.IsBackTesting {
session.Subscribe(types.MarketTradeChannel, s.Symbol, types.SubscribeOptions{})
}
@ -129,8 +109,6 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
s.TradeStats = &types.TradeStats{}
}
s.lastLow = fixedpoint.Zero
// StrategyController
s.Status = types.StrategyStatusRunning
@ -157,32 +135,6 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
})
s.orderExecutor.Bind()
store, _ := session.MarketDataStore(s.Symbol)
standardIndicator, _ := session.StandardIndicatorSet(s.Symbol)
s.pivot = &indicator.Pivot{IntervalWindow: s.IntervalWindow}
s.pivot.Bind(store)
preloadPivot(s.pivot, store)
// update pivot low data
session.MarketDataStream.OnKLineClosed(types.KLineWith(s.Symbol, s.Interval, func(kline types.KLine) {
lastLow := fixedpoint.NewFromFloat(s.pivot.LastLow())
if lastLow.IsZero() {
return
}
if lastLow.Compare(s.lastLow) != 0 {
log.Infof("new pivot low detected: %f %s", s.pivot.LastLow(), kline.EndTime.Time())
}
s.lastLow = lastLow
s.pivotLowPrices = append(s.pivotLowPrices, s.lastLow)
}))
if s.BreakLow.StopEMA != nil {
s.stopEWMA = standardIndicator.EWMA(*s.BreakLow.StopEMA)
}
for _, method := range s.ExitMethods {
method.Bind(session, s.orderExecutor)
}
@ -191,78 +143,8 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
s.ResistanceShort.Bind(session, s.orderExecutor)
}
session.MarketDataStream.OnKLineClosed(types.KLineWith(s.Symbol, types.Interval1m, func(kline types.KLine) {
if s.Status != types.StrategyStatusRunning {
return
}
if s.Position.IsOpened(kline.Close) {
return
}
if len(s.pivotLowPrices) == 0 {
log.Infof("currently there is no pivot low prices, skip placing orders...")
return
}
previousLow := s.pivotLowPrices[len(s.pivotLowPrices)-1]
// truncate the pivot low prices
if len(s.pivotLowPrices) > 10 {
s.pivotLowPrices = s.pivotLowPrices[len(s.pivotLowPrices)-10:]
}
ratio := fixedpoint.One.Add(s.BreakLow.Ratio)
breakPrice := previousLow.Mul(ratio)
openPrice := kline.Open
closePrice := kline.Close
// if previous low is not break, skip
if closePrice.Compare(breakPrice) >= 0 {
return
}
// we need the price cross the break line or we do nothing
if !(openPrice.Compare(breakPrice) > 0 && closePrice.Compare(breakPrice) < 0) {
return
}
log.Infof("%s breakLow signal detected, closed price %f < breakPrice %f", kline.Symbol, closePrice.Float64(), breakPrice.Float64())
// stop EMA protection
if s.stopEWMA != nil {
ema := fixedpoint.NewFromFloat(s.stopEWMA.Last())
if ema.IsZero() {
return
}
emaStopShortPrice := ema.Mul(fixedpoint.One.Sub(s.BreakLow.StopEMARange))
if closePrice.Compare(emaStopShortPrice) < 0 {
log.Infof("stopEMA protection: close price %f < EMA(%v) = %f", closePrice.Float64(), s.BreakLow.StopEMA, ema.Float64())
return
}
}
// graceful cancel all active orders
_ = s.orderExecutor.GracefulCancel(ctx)
quantity := s.useQuantityOrBaseBalance(s.BreakLow.Quantity)
if s.BreakLow.MarketOrder {
bbgo.Notify("%s price %f breaks the previous low %f with ratio %f, submitting market sell to open a short position", s.Symbol, kline.Close.Float64(), previousLow.Float64(), s.BreakLow.Ratio.Float64())
s.placeMarketSell(ctx, quantity, "breakLowMarket")
} else {
sellPrice := previousLow.Mul(fixedpoint.One.Add(s.BreakLow.BounceRatio))
bbgo.Notify("%s price %f breaks the previous low %f with ratio %f, submitting limit sell @ %f", s.Symbol, kline.Close.Float64(), previousLow.Float64(), s.BreakLow.Ratio.Float64(), sellPrice.Float64())
s.placeLimitSell(ctx, sellPrice, quantity, "breakLowLimit")
}
}))
if !bbgo.IsBackTesting {
// use market trade to submit short order
session.MarketDataStream.OnMarketTrade(func(trade types.Trade) {
})
if s.BreakLow != nil {
s.BreakLow.Bind(session, s.orderExecutor)
}
bbgo.OnShutdown(func(ctx context.Context, wg *sync.WaitGroup) {
@ -275,97 +157,6 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
return nil
}
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) placeOrder(ctx context.Context, price fixedpoint.Value, quantity fixedpoint.Value) {
_, _ = s.orderExecutor.SubmitOrders(ctx, types.SubmitOrder{
Symbol: s.Symbol,
Side: types.SideTypeSell,
Type: types.OrderTypeLimitMaker,
Price: price,
Quantity: quantity,
})
}
func (s *Strategy) useQuantityOrBaseBalance(quantity fixedpoint.Value) fixedpoint.Value {
if s.session.Margin || s.session.IsolatedMargin || s.session.Futures || s.session.IsolatedFutures {
return quantity
}
balance, hasBalance := s.session.Account.Balance(s.Market.BaseCurrency)
if hasBalance {
if quantity.IsZero() {
bbgo.Notify("sell quantity is not set, submitting sell with all base balance: %s", balance.Available.String())
quantity = balance.Available
} else {
quantity = fixedpoint.Min(quantity, balance.Available)
}
}
if quantity.IsZero() {
log.Errorf("quantity is zero, can not submit sell order, please check settings")
}
return quantity
}
func (s *Strategy) placeLimitSell(ctx context.Context, price, quantity fixedpoint.Value, tag string) {
_, _ = s.orderExecutor.SubmitOrders(ctx, types.SubmitOrder{
Symbol: s.Symbol,
Price: price,
Side: types.SideTypeSell,
Type: types.OrderTypeLimit,
Quantity: quantity,
MarginSideEffect: types.SideEffectTypeMarginBuy,
Tag: tag,
})
}
func (s *Strategy) placeMarketSell(ctx context.Context, quantity fixedpoint.Value, tag string) {
_, _ = s.orderExecutor.SubmitOrders(ctx, types.SubmitOrder{
Symbol: s.Symbol,
Side: types.SideTypeSell,
Type: types.OrderTypeMarket,
Quantity: quantity,
MarginSideEffect: types.SideEffectTypeMarginBuy,
Tag: tag,
})
}
func findPossibleResistancePrices(closePrice float64, minDistance float64, lows []float64) []float64 {
// sort float64 in increasing order
// lower to higher prices
sort.Float64s(lows)
var resistancePrices []float64
for _, low := range lows {
if low < closePrice {
continue
}
last := closePrice
if len(resistancePrices) > 0 {
last = resistancePrices[len(resistancePrices)-1]
}
if (low / last) < (1.0 + minDistance) {
continue
}
resistancePrices = append(resistancePrices, low)
}
return resistancePrices
}
func preloadPivot(pivot *indicator.Pivot, store *bbgo.MarketDataStore) *types.KLine {
klines, ok := store.KLinesOfInterval(pivot.Interval)
if !ok {

View File

@ -279,11 +279,11 @@ func (s *ProfitStats) PlainText() string {
return fmt.Sprintf("%s Profit Today\n"+
"Profit %s %s\n"+
"Net profit %s %s\n"+
"Trade Loss %s %s\n"+
"Gross Loss %s %s\n"+
"Summary:\n"+
"Accumulated Profit %s %s\n"+
"Accumulated Net Profit %s %s\n"+
"Accumulated Trade Loss %s %s\n"+
"Accumulated Gross Loss %s %s\n"+
"Since %s",
s.Symbol,
s.TodayPnL.String(), s.QuoteCurrency,