refine atrpin strategy

This commit is contained in:
c9s 2023-09-26 20:43:14 +08:00
parent 3b6e1e32a4
commit e52e53aa42
No known key found for this signature in database
GPG Key ID: 7385E7E464CB0A54
2 changed files with 117 additions and 24 deletions

39
config/atrpin.yaml Normal file
View File

@ -0,0 +1,39 @@
sessions:
max:
exchange: max
envVarPrefix: max
persistence:
json:
directory: var/data
redis:
host: 127.0.0.1
port: 6379
db: 0
exchangeStrategies:
- on: max
atrpin:
symbol: BTCUSDT
interval: 5m
window: 14
multiplier: 100.0
amount: 1000
backtest:
startTime: "2018-10-01"
endTime: "2018-11-01"
symbols:
- BTCUSDT
sessions:
- max
# syncSecKLines: true
accounts:
max:
makerFeeRate: 0.0%
takerFeeRate: 0.075%
balances:
BTC: 1.0
USDT: 10_000.0

View File

@ -28,7 +28,7 @@ type Strategy struct {
Symbol string `json:"symbol"` Symbol string `json:"symbol"`
Interval types.Interval `json:"interval"` Interval types.Interval `json:"interval"`
Window int `json:"slowWindow"` Window int `json:"window"`
Multiplier float64 `json:"multiplier"` Multiplier float64 `json:"multiplier"`
bbgo.QuantityOrAmount bbgo.QuantityOrAmount
@ -45,6 +45,7 @@ func (s *Strategy) InstanceID() string {
func (s *Strategy) Subscribe(session *bbgo.ExchangeSession) { func (s *Strategy) Subscribe(session *bbgo.ExchangeSession) {
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: s.Interval}) session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: s.Interval})
session.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: types.Interval1m})
} }
func (s *Strategy) Defaults() error { func (s *Strategy) Defaults() error {
@ -64,12 +65,23 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
s.Strategy.Initialize(ctx, s.Environment, session, s.Market, ID, s.InstanceID()) s.Strategy.Initialize(ctx, s.Environment, session, s.Market, ID, s.InstanceID())
atr := session.Indicators(s.Symbol).ATR(s.Interval, s.Window) atr := session.Indicators(s.Symbol).ATR(s.Interval, s.Window)
session.UserDataStream.OnKLine(types.KLineWith(s.Symbol, s.Interval, func(k types.KLine) {
session.MarketDataStream.OnKLineClosed(types.KLineWith(s.Symbol, s.Interval, func(k types.KLine) {
if err := s.Strategy.OrderExecutor.GracefulCancel(ctx); err != nil { if err := s.Strategy.OrderExecutor.GracefulCancel(ctx); err != nil {
log.WithError(err).Error("unable to cancel open orders...") log.WithError(err).Error("unable to cancel open orders...")
} }
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)
lastAtr := atr.Last(0) lastAtr := atr.Last(0)
log.Infof("atr: %f", lastAtr)
// protection // protection
if lastAtr <= k.High.Sub(k.Low).Float64() { if lastAtr <= k.High.Sub(k.Low).Float64() {
@ -78,13 +90,20 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
priceRange := fixedpoint.NewFromFloat(lastAtr * s.Multiplier) priceRange := fixedpoint.NewFromFloat(lastAtr * s.Multiplier)
// if the atr is too small, apply the price range protection with 10%
// priceRange protection 10%
priceRange = fixedpoint.Max(priceRange, k.Close.Mul(fixedpoint.NewFromFloat(0.1)))
log.Infof("priceRange: %f", priceRange.Float64())
ticker, err := session.Exchange.QueryTicker(ctx, s.Symbol) ticker, err := session.Exchange.QueryTicker(ctx, s.Symbol)
if err != nil { if err != nil {
log.WithError(err).Error("unable to query ticker") log.WithError(err).Error("unable to query ticker")
return return
} }
bidPrice := ticker.Buy.Sub(priceRange) log.Info(ticker.String())
bidPrice := fixedpoint.Max(ticker.Buy.Sub(priceRange), s.Market.TickSize)
askPrice := ticker.Sell.Add(priceRange) askPrice := ticker.Sell.Add(priceRange)
bidQuantity := s.QuantityOrAmount.CalculateQuantity(bidPrice) bidQuantity := s.QuantityOrAmount.CalculateQuantity(bidPrice)
@ -94,41 +113,72 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
position := s.Strategy.OrderExecutor.Position() position := s.Strategy.OrderExecutor.Position()
if !position.IsDust() { if !position.IsDust() {
log.Infof("position: %+v", position)
side := types.SideTypeSell side := types.SideTypeSell
takerPrice := fixedpoint.Zero takerPrice := fixedpoint.Zero
if position.IsShort() { if position.IsShort() {
side = types.SideTypeBuy side = types.SideTypeBuy
takerPrice = askPrice takerPrice = ticker.Sell
} else if position.IsLong() { } else if position.IsLong() {
side = types.SideTypeSell side = types.SideTypeSell
takerPrice = bidPrice takerPrice = ticker.Buy
} }
orderForms = append(orderForms, types.SubmitOrder{ orderForms = append(orderForms, types.SubmitOrder{
Symbol: s.Symbol, Symbol: s.Symbol,
Side: side, Type: types.OrderTypeLimit,
Price: takerPrice, Side: side,
Quantity: position.GetQuantity(), Price: takerPrice,
Market: s.Market, 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 {
log.WithError(err).Error("unable to submit orders")
}
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",
}) })
} }
orderForms = append(orderForms, types.SubmitOrder{ bidQuantity = s.Market.AdjustQuantityByMinNotional(bidQuantity, bidPrice)
Symbol: s.Symbol, if !s.Market.IsDustQuantity(bidQuantity, bidPrice) && bidQuantity.Mul(bidPrice).Compare(quoteBalance.Available) < 0 {
Side: types.SideTypeSell, orderForms = append(orderForms, types.SubmitOrder{
Price: askPrice, Symbol: s.Symbol,
Quantity: askQuantity, Side: types.SideTypeBuy,
Market: s.Market, Type: types.OrderTypeLimitMaker,
}) Price: bidPrice,
Quantity: bidQuantity,
Market: s.Market,
Tag: "pinOrder",
})
}
orderForms = append(orderForms, types.SubmitOrder{ if len(orderForms) == 0 {
Symbol: s.Symbol, log.Infof("no order to place")
Side: types.SideTypeBuy, return
Price: bidPrice, }
Quantity: bidQuantity,
Market: s.Market, log.Infof("bid/ask: %f/%f", bidPrice.Float64(), askPrice.Float64())
})
if _, err := s.Strategy.OrderExecutor.SubmitOrders(ctx, orderForms...); err != nil { if _, err := s.Strategy.OrderExecutor.SubmitOrders(ctx, orderForms...); err != nil {
log.WithError(err).Error("unable to submit orders") log.WithError(err).Error("unable to submit orders")
@ -137,6 +187,10 @@ func (s *Strategy) Run(ctx context.Context, orderExecutor bbgo.OrderExecutor, se
bbgo.OnShutdown(ctx, func(ctx context.Context, wg *sync.WaitGroup) { bbgo.OnShutdown(ctx, func(ctx context.Context, wg *sync.WaitGroup) {
defer wg.Done() defer wg.Done()
if err := s.Strategy.OrderExecutor.GracefulCancel(ctx); err != nil {
log.WithError(err).Error("unable to cancel open orders...")
}
}) })
return nil return nil