bbgo_origin/pkg/strategy/atrpin/strategy.go

203 lines
5.4 KiB
Go
Raw Normal View History

2023-09-26 07:32:55 +00:00
package atrpin
import (
"context"
"fmt"
"sync"
"github.com/c9s/bbgo/pkg/bbgo"
"github.com/c9s/bbgo/pkg/fixedpoint"
"github.com/c9s/bbgo/pkg/strategy/common"
"github.com/c9s/bbgo/pkg/types"
2024-02-06 07:08:01 +00:00
"github.com/sirupsen/logrus"
2023-09-26 07:32:55 +00:00
)
const ID = "atrpin"
2024-02-06 07:08:01 +00:00
var log = logrus.WithField("strategy", ID)
2023-09-26 07:32:55 +00:00
func init() {
bbgo.RegisterStrategy(ID, &Strategy{})
}
type Strategy struct {
*common.Strategy
2023-09-26 07:32:55 +00:00
Environment *bbgo.Environment
Market types.Market
Symbol string `json:"symbol"`
2023-09-27 06:25:49 +00:00
Interval types.Interval `json:"interval"`
Window int `json:"window"`
Multiplier float64 `json:"multiplier"`
MinPriceRange fixedpoint.Value `json:"minPriceRange"`
2023-09-26 07:32:55 +00:00
bbgo.QuantityOrAmount
// bbgo.OpenPositionOptions
}
func (s *Strategy) Initialize() error {
s.Strategy = &common.Strategy{}
return nil
}
2023-09-26 07:32:55 +00:00
func (s *Strategy) ID() string {
return ID
}
func (s *Strategy) InstanceID() string {
return fmt.Sprintf("%s:%s:%s:%d", ID, s.Symbol, s.Interval, s.Window)
}
func (s *Strategy) Subscribe(session *bbgo.ExchangeSession) {
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: s.Interval})
2023-09-26 12:43:14 +00:00
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: types.Interval1m})
2023-09-26 07:32:55 +00:00
}
func (s *Strategy) Defaults() error {
if s.Multiplier == 0.0 {
s.Multiplier = 10.0
}
if s.Interval == "" {
s.Interval = types.Interval5m
}
return nil
}
func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, session *bbgo.ExchangeSession) error {
s.Strategy.Initialize(ctx, s.Environment, session, s.Market, ID, s.InstanceID())
atr := session.Indicators(s.Symbol).ATR(s.Interval, s.Window)
2023-09-26 12:43:14 +00:00
session.MarketDataStream.OnKLineClosed(types.KLineWith(s.Symbol, s.Interval, func(k types.KLine) {
2023-09-26 07:32:55 +00:00
if err := s.Strategy.OrderExecutor.GracefulCancel(ctx); err != nil {
log.WithError(err).Error("unable to cancel open orders...")
}
2023-09-26 12:43:14 +00:00
account, err := session.UpdateAccount(ctx)
if err != nil {
log.WithError(err).Error("unable to update account")
return
}
baseBalance, _ := account.Balance(s.Market.BaseCurrency)
quoteBalance, _ := account.Balance(s.Market.QuoteCurrency)
2023-09-26 07:32:55 +00:00
lastAtr := atr.Last(0)
2023-09-26 12:43:14 +00:00
log.Infof("atr: %f", lastAtr)
2023-09-26 07:32:55 +00:00
// protection
if lastAtr <= k.High.Sub(k.Low).Float64() {
lastAtr = k.High.Sub(k.Low).Float64()
}
priceRange := fixedpoint.NewFromFloat(lastAtr * s.Multiplier)
2023-09-26 12:43:14 +00:00
// if the atr is too small, apply the price range protection with 10%
// priceRange protection 10%
2023-09-27 06:25:49 +00:00
priceRange = fixedpoint.Max(priceRange, k.Close.Mul(s.MinPriceRange))
2023-09-26 12:43:14 +00:00
log.Infof("priceRange: %f", priceRange.Float64())
2023-09-26 07:32:55 +00:00
ticker, err := session.Exchange.QueryTicker(ctx, s.Symbol)
if err != nil {
log.WithError(err).Error("unable to query ticker")
return
}
2023-09-26 12:43:14 +00:00
log.Info(ticker.String())
bidPrice := fixedpoint.Max(ticker.Buy.Sub(priceRange), s.Market.TickSize)
2023-09-26 07:32:55 +00:00
askPrice := ticker.Sell.Add(priceRange)
bidQuantity := s.QuantityOrAmount.CalculateQuantity(bidPrice)
askQuantity := s.QuantityOrAmount.CalculateQuantity(askPrice)
var orderForms []types.SubmitOrder
position := s.Strategy.OrderExecutor.Position()
2024-02-06 04:14:13 +00:00
log.Infof("position: %+v", position)
2023-09-26 12:43:14 +00:00
2024-02-06 09:21:26 +00:00
side := types.SideTypeBuy
takerPrice := ticker.Sell
if position.IsLong() {
side = types.SideTypeSell
takerPrice = ticker.Buy
}
2023-09-26 07:32:55 +00:00
2024-02-06 09:21:26 +00:00
if !position.IsDust(takerPrice) {
log.Infof("%s position is not dust", s.Symbol)
2023-09-26 07:32:55 +00:00
2023-09-26 12:43:14 +00:00
orderForms = append(orderForms, types.SubmitOrder{
Symbol: s.Symbol,
Type: types.OrderTypeLimit,
Side: side,
Price: takerPrice,
Quantity: position.GetQuantity(),
Market: s.Market,
TimeInForce: types.TimeInForceGTC,
Tag: "takeProfit",
})
log.Infof("SUBMIT TAKER ORDER: %+v", orderForms)
if _, err := s.Strategy.OrderExecutor.SubmitOrders(ctx, orderForms...); err != nil {
2024-02-06 09:03:51 +00:00
log.WithError(err).Errorf("unable to submit orders: %+v", orderForms)
2023-09-26 12:43:14 +00:00
}
return
}
askQuantity = s.Market.AdjustQuantityByMinNotional(askQuantity, askPrice)
if !s.Market.IsDustQuantity(askQuantity, askPrice) && askQuantity.Compare(baseBalance.Available) < 0 {
orderForms = append(orderForms, types.SubmitOrder{
Symbol: s.Symbol,
Side: types.SideTypeSell,
Type: types.OrderTypeLimitMaker,
Quantity: askQuantity,
Price: askPrice,
Market: s.Market,
TimeInForce: types.TimeInForceGTC,
Tag: "pinOrder",
})
}
bidQuantity = s.Market.AdjustQuantityByMinNotional(bidQuantity, bidPrice)
if !s.Market.IsDustQuantity(bidQuantity, bidPrice) && bidQuantity.Mul(bidPrice).Compare(quoteBalance.Available) < 0 {
2023-09-26 07:32:55 +00:00
orderForms = append(orderForms, types.SubmitOrder{
Symbol: s.Symbol,
2023-09-26 12:43:14 +00:00
Side: types.SideTypeBuy,
Type: types.OrderTypeLimitMaker,
Price: bidPrice,
Quantity: bidQuantity,
2023-09-26 07:32:55 +00:00
Market: s.Market,
2023-09-26 12:43:14 +00:00
Tag: "pinOrder",
2023-09-26 07:32:55 +00:00
})
}
2023-09-26 12:43:14 +00:00
if len(orderForms) == 0 {
2024-02-06 09:03:51 +00:00
log.Infof("no %s order to place", s.Symbol)
2023-09-26 12:43:14 +00:00
return
}
2024-02-06 09:03:51 +00:00
log.Infof("%s bid/ask: %f/%f", s.Symbol, bidPrice.Float64(), askPrice.Float64())
2023-09-26 07:32:55 +00:00
2024-04-16 04:53:51 +00:00
log.Infof("submit orders: %+v", orderForms)
2023-09-26 07:32:55 +00:00
if _, err := s.Strategy.OrderExecutor.SubmitOrders(ctx, orderForms...); err != nil {
2024-02-06 09:03:51 +00:00
log.WithError(err).Errorf("unable to submit orders: %+v", orderForms)
2023-09-26 07:32:55 +00:00
}
}))
bbgo.OnShutdown(ctx, func(ctx context.Context, wg *sync.WaitGroup) {
defer wg.Done()
2023-09-26 12:43:14 +00:00
if err := s.Strategy.OrderExecutor.GracefulCancel(ctx); err != nil {
log.WithError(err).Error("unable to cancel open orders...")
}
2023-09-26 07:32:55 +00:00
})
return nil
}