bbgo_origin/pkg/strategy/atrpin/strategy.go

239 lines
6.4 KiB
Go
Raw Permalink 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
2024-06-02 06:49:20 +00:00
// handle missing trades, will be removed in the future
TakeProfitByExpectedBaseBalance bool `json:"takeProfitByExpectedBaseBalance"`
ExpectedBaseBalance fixedpoint.Value `json:"expectedBaseBalance"`
2023-09-26 07:32:55 +00:00
bbgo.QuantityOrAmount
// bbgo.OpenPositionOptions
2024-05-20 06:08:46 +00:00
logger *logrus.Entry
2023-09-26 07:32:55 +00:00
}
func (s *Strategy) Initialize() error {
2024-05-15 15:38:34 +00:00
if s.Strategy == nil {
s.Strategy = &common.Strategy{}
}
2024-05-20 06:08:46 +00:00
s.logger = log.WithFields(logrus.Fields{
"symbol": s.Symbol,
"window": s.Window,
})
return nil
}
2024-06-02 06:49:20 +00:00
func (s *Strategy) Validate() error {
if s.ExpectedBaseBalance.Sign() < 0 {
return fmt.Errorf("expectedBaseBalance should be non-negative")
}
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 {
2024-05-20 06:08:46 +00:00
s.logger.WithError(err).Error("unable to cancel open orders...")
return
2023-09-26 07:32:55 +00:00
}
2023-09-26 12:43:14 +00:00
account, err := session.UpdateAccount(ctx)
if err != nil {
2024-05-20 06:08:46 +00:00
s.logger.WithError(err).Error("unable to update account")
2023-09-26 12:43:14 +00:00
return
}
baseBalance, ok := account.Balance(s.Market.BaseCurrency)
if !ok {
2024-05-20 06:08:46 +00:00
s.logger.Errorf("%s balance not found", s.Market.BaseCurrency)
2024-05-03 06:56:09 +00:00
return
}
quoteBalance, ok := account.Balance(s.Market.QuoteCurrency)
if !ok {
2024-05-20 06:08:46 +00:00
s.logger.Errorf("%s balance not found", s.Market.QuoteCurrency)
2024-05-03 06:56:09 +00:00
return
}
2023-09-26 12:43:14 +00:00
2023-09-26 07:32:55 +00:00
lastAtr := atr.Last(0)
2024-05-20 06:08:46 +00:00
s.logger.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))
2024-05-20 06:08:46 +00:00
s.logger.Infof("priceRange: %f", priceRange.Float64())
2023-09-26 12:43:14 +00:00
2023-09-26 07:32:55 +00:00
ticker, err := session.Exchange.QueryTicker(ctx, s.Symbol)
if err != nil {
2024-05-20 06:08:46 +00:00
s.logger.WithError(err).Error("unable to query ticker")
2023-09-26 07:32:55 +00:00
return
}
2024-05-20 06:08:46 +00:00
s.logger.Info(ticker.String())
2023-09-26 12:43:14 +00:00
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-05-20 06:08:46 +00:00
s.logger.Infof("position: %+v", position)
2023-09-26 12:43:14 +00:00
2024-06-02 06:49:20 +00:00
base := position.GetBase()
if s.TakeProfitByExpectedBaseBalance {
base = baseBalance.Available.Sub(s.ExpectedBaseBalance)
}
side := types.SideTypeSell
takerPrice := ticker.Buy
if base.Sign() < 0 {
side = types.SideTypeBuy
takerPrice = ticker.Sell
2024-02-06 09:21:26 +00:00
}
2023-09-26 07:32:55 +00:00
2024-06-20 09:39:20 +00:00
positionQuantity := base.Abs()
if !s.Market.IsDustQuantity(positionQuantity, takerPrice) {
2024-05-20 06:08:46 +00:00
s.logger.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,
2024-06-20 09:39:20 +00:00
Quantity: positionQuantity,
2023-09-26 12:43:14 +00:00
Market: s.Market,
TimeInForce: types.TimeInForceGTC,
Tag: "takeProfit",
})
2024-05-20 06:08:46 +00:00
s.logger.Infof("SUBMIT TAKER ORDER: %+v", orderForms)
2023-09-26 12:43:14 +00:00
if _, err := s.Strategy.OrderExecutor.SubmitOrders(ctx, orderForms...); err != nil {
2024-05-20 06:08:46 +00:00
s.logger.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-05-20 06:08:46 +00:00
s.logger.Infof("no %s order to place", s.Symbol)
2023-09-26 12:43:14 +00:00
return
}
2024-05-20 06:08:46 +00:00
s.logger.Infof("%s bid/ask: %f/%f", s.Symbol, bidPrice.Float64(), askPrice.Float64())
2023-09-26 07:32:55 +00:00
2024-05-20 06:08:46 +00:00
s.logger.Infof("submit orders: %+v", orderForms)
2023-09-26 07:32:55 +00:00
if _, err := s.Strategy.OrderExecutor.SubmitOrders(ctx, orderForms...); err != nil {
2024-05-20 06:08:46 +00:00
s.logger.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 {
2024-05-20 06:08:46 +00:00
s.logger.WithError(err).Error("unable to cancel open orders...")
2023-09-26 12:43:14 +00:00
}
2024-05-03 06:56:09 +00:00
bbgo.Sync(ctx, s)
2023-09-26 07:32:55 +00:00
})
return nil
}