WIP: strategy: pivot: pivot low shorting strategy

This commit is contained in:
austin362667 2022-05-10 05:11:22 +08:00 committed by Austin Liu
parent cbb720a5f7
commit 60a8c1f42b
4 changed files with 337 additions and 0 deletions

31
config/pivot.yaml Normal file
View File

@ -0,0 +1,31 @@
sessions:
binance:
exchange: binance
envVarPrefix: binance
# futures: true
exchangeStrategies:
- on: binance
pivot:
symbol: BTCBUSD
interval: 1h
quantity: 0.95
stopLossRatio: 0.8%
catBounceRatio: 3%
backtest:
sessions:
- binance
# for testing max draw down (MDD) at 03-12
# see here for more details
# https://www.investopedia.com/terms/m/maximum-drawdown-mdd.asp
startTime: "2022-01-01"
endTime: "2022-05-10"
symbols:
- BTCBUSD
account:
binance:
balances:
BTC: 1.0
BUSD: 5_000.0

119
pkg/strategy/pivot/pivot.go Normal file
View File

@ -0,0 +1,119 @@
package pivot
import (
"fmt"
"time"
"github.com/c9s/bbgo/pkg/indicator"
"github.com/c9s/bbgo/pkg/types"
)
var zeroTime time.Time
type KLineValueMapper func(k types.KLine) float64
//go:generate callbackgen -type Pivot
type Pivot struct {
types.IntervalWindow
// Values
Lows types.Float64Slice // higher low
Highs types.Float64Slice // lower high
EndTime time.Time
UpdateCallbacks []func(valueLow, valueHigh float64)
}
func (inc *Pivot) LastLow() float64 {
if len(inc.Lows) == 0 {
return 0.0
}
return inc.Lows[len(inc.Lows)-1]
}
func (inc *Pivot) LastHigh() float64 {
if len(inc.Highs) == 0 {
return 0.0
}
return inc.Highs[len(inc.Highs)-1]
}
func (inc *Pivot) calculateAndUpdate(klines []types.KLine) {
if len(klines) < inc.Window {
return
}
var end = len(klines) - 1
var lastKLine = klines[end]
if inc.EndTime != zeroTime && lastKLine.GetEndTime().Before(inc.EndTime) {
return
}
var recentT = klines[end-(inc.Window-1) : end+1]
l, h, err := calculatePivot(recentT, inc.Window, KLineLowPriceMapper, KLineHighPriceMapper)
if err != nil {
log.WithError(err).Error("can not calculate pivots")
return
}
inc.Lows.Push(l)
inc.Highs.Push(h)
if len(inc.Lows) > indicator.MaxNumOfVOL {
inc.Lows = inc.Lows[indicator.MaxNumOfVOLTruncateSize-1:]
}
if len(inc.Highs) > indicator.MaxNumOfVOL {
inc.Highs = inc.Highs[indicator.MaxNumOfVOLTruncateSize-1:]
}
inc.EndTime = klines[end].GetEndTime().Time()
inc.EmitUpdate(l, h)
}
func (inc *Pivot) handleKLineWindowUpdate(interval types.Interval, window types.KLineWindow) {
if inc.Interval != interval {
return
}
inc.calculateAndUpdate(window)
}
func (inc *Pivot) Bind(updater indicator.KLineWindowUpdater) {
updater.OnKLineWindowUpdate(inc.handleKLineWindowUpdate)
}
func calculatePivot(klines []types.KLine, window int, valLow KLineValueMapper, valHigh KLineValueMapper) (float64, float64, error) {
length := len(klines)
if length == 0 || length < window {
return 0., 0., fmt.Errorf("insufficient elements for calculating VOL with window = %d", window)
}
var lows types.Float64Slice
var highs types.Float64Slice
for _, k := range klines {
lows.Push(valLow(k))
highs.Push(valHigh(k))
}
pl := 0.
if lows.Min() == lows.Index(int(window/2.)) {
pl = lows.Min()
}
ph := 0.
if highs.Max() == highs.Index(int(window/2.)) {
ph = highs.Max()
}
return pl, ph, nil
}
func KLineLowPriceMapper(k types.KLine) float64 {
return k.Low.Float64()
}
func KLineHighPriceMapper(k types.KLine) float64 {
return k.High.Float64()
}

View File

@ -0,0 +1,15 @@
// Code generated by "callbackgen -type Pivot"; DO NOT EDIT.
package pivot
import ()
func (inc *Pivot) OnUpdate(cb func(valueLow float64, valueHigh float64)) {
inc.UpdateCallbacks = append(inc.UpdateCallbacks, cb)
}
func (inc *Pivot) EmitUpdate(valueLow float64, valueHigh float64) {
for _, cb := range inc.UpdateCallbacks {
cb(valueLow, valueHigh)
}
}

View File

@ -0,0 +1,172 @@
package pivot
import (
"context"
"fmt"
"github.com/c9s/bbgo/pkg/bbgo"
"github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/types"
"github.com/sirupsen/logrus"
)
const ID = "pivot"
var three = fixedpoint.NewFromInt(3)
var log = logrus.WithField("strategy", ID)
func init() {
bbgo.RegisterStrategy(ID, &Strategy{})
}
type IntervalWindowSetting struct {
types.IntervalWindow
}
type Strategy struct {
Symbol string `json:"symbol"`
Market types.Market
Interval types.Interval `json:"interval"`
Quantity fixedpoint.Value `json:"quantity"`
Position *types.Position `json:"position,omitempty"`
StopLossRatio fixedpoint.Value `json:"stopLossRatio"`
CatBounceRatio fixedpoint.Value `json:"catBounceRatio"`
activeMakerOrders *bbgo.LocalActiveOrderBook
orderStore *bbgo.OrderStore
tradeCollector *bbgo.TradeCollector
session *bbgo.ExchangeSession
book *types.StreamOrderBook
//pivotHigh *PIVOTHIGH
pivot *Pivot
}
func (s *Strategy) ID() string {
return ID
}
func (s *Strategy) Subscribe(session *bbgo.ExchangeSession) {
log.Infof("subscribe %s", s.Symbol)
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: s.Interval.String()})
//session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: types.Interval1d.String()})
}
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 {
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: s.Quantity,
Market: s.Market,
}
//s.Notify("Submitting %s %s order to close position by %v", s.Symbol, side.String(), percentage, submitOrder)
createdOrders, err := s.session.Exchange.SubmitOrders(ctx, submitOrder)
if err != nil {
log.WithError(err).Errorf("can not place position close order")
}
s.orderStore.Add(createdOrders...)
s.activeMakerOrders.Add(createdOrders...)
return err
}
func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) error {
// initial required information
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.BindStream(session.UserDataStream)
s.orderStore = bbgo.NewOrderStore(s.Symbol)
s.orderStore.BindStream(session.UserDataStream)
if s.Position == nil {
s.Position = types.NewPositionFromMarket(s.Market)
}
s.tradeCollector = bbgo.NewTradeCollector(s.Symbol, s.Position, s.orderStore)
s.tradeCollector.BindStream(session.UserDataStream)
iw := types.IntervalWindow{Window: 100, Interval: s.Interval}
st, _ := session.MarketDataStore(s.Symbol)
s.pivot = &Pivot{IntervalWindow: iw}
s.pivot.Bind(st)
session.UserDataStream.OnStart(func() {
log.Infof("connected")
})
var lastLow fixedpoint.Value
session.MarketDataStream.OnKLineClosed(func(kline types.KLine) {
if kline.Symbol != s.Symbol || kline.Interval != s.Interval {
return
}
if err := s.activeMakerOrders.GracefulCancel(ctx, s.session.Exchange); err != nil {
log.WithError(err).Errorf("graceful cancel order error")
}
log.Info(s.pivot.LastLow())
if s.pivot.LastLow() > 0. {
lastLow = fixedpoint.NewFromFloat(s.pivot.LastLow())
} else {
lastLow = fixedpoint.Zero
// SL || TP
if kline.Close.Div(s.Position.AverageCost).Compare(fixedpoint.One.Add(s.StopLossRatio)) > 0 || kline.Close.Div(s.Position.AverageCost).Compare(fixedpoint.One.Sub(s.StopLossRatio.Mul(fixedpoint.NewFromInt(15)))) < 0 {
if s.Position.GetBase().Compare(s.Quantity.Neg()) <= 0 {
s.ClosePosition(ctx, fixedpoint.One)
s.tradeCollector.Process()
}
}
}
if !lastLow.IsZero() {
if s.Position.GetBase().Compare(s.Quantity.Neg()) > 0 {
submitOrder := types.SubmitOrder{
Symbol: s.Symbol,
Side: types.SideTypeSell,
//Type: types.OrderTypeMarket,
Type: types.OrderTypeLimit,
//Price: kline.Close,
Price: lastLow.Mul(fixedpoint.One.Add(s.CatBounceRatio)),
Quantity: s.Quantity,
}
createdOrders, err := orderExecutor.SubmitOrders(ctx, submitOrder)
if err != nil {
log.WithError(err).Errorf("can not place orders")
}
s.orderStore.Add(createdOrders...)
s.activeMakerOrders.Add(createdOrders...)
s.tradeCollector.Process()
}
}
})
return nil
}