2023-11-27 09:45:12 +00:00
|
|
|
package xdepthmaker
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2023-11-30 09:10:09 +00:00
|
|
|
stderrors "errors"
|
2023-11-27 09:45:12 +00:00
|
|
|
"fmt"
|
2024-09-24 08:12:17 +00:00
|
|
|
"strings"
|
2023-11-27 09:45:12 +00:00
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
"golang.org/x/time/rate"
|
|
|
|
|
|
|
|
"github.com/c9s/bbgo/pkg/bbgo"
|
2024-08-08 09:37:58 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/core"
|
2023-12-11 08:56:19 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/exchange/retry"
|
2023-11-27 09:45:12 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/fixedpoint"
|
2024-09-27 10:29:44 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/pricesolver"
|
|
|
|
"github.com/c9s/bbgo/pkg/sigchan"
|
2024-03-06 12:31:53 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/strategy/common"
|
2024-09-23 14:16:53 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/strategy/xmaker"
|
2023-11-27 09:45:12 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/types"
|
|
|
|
"github.com/c9s/bbgo/pkg/util"
|
2024-09-23 10:26:23 +00:00
|
|
|
"github.com/c9s/bbgo/pkg/util/tradingutil"
|
2023-11-27 09:45:12 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var lastPriceModifier = fixedpoint.NewFromFloat(1.001)
|
|
|
|
var minGap = fixedpoint.NewFromFloat(1.02)
|
|
|
|
var defaultMargin = fixedpoint.NewFromFloat(0.003)
|
|
|
|
|
|
|
|
var Two = fixedpoint.NewFromInt(2)
|
|
|
|
|
2023-12-11 09:59:16 +00:00
|
|
|
const priceUpdateTimeout = 5 * time.Minute
|
2023-11-27 09:45:12 +00:00
|
|
|
|
|
|
|
const ID = "xdepthmaker"
|
|
|
|
|
|
|
|
var log = logrus.WithField("strategy", ID)
|
|
|
|
|
2024-09-24 08:12:17 +00:00
|
|
|
var ErrZeroQuantity = stderrors.New("quantity is zero")
|
|
|
|
var ErrDustQuantity = stderrors.New("quantity is dust")
|
|
|
|
var ErrZeroPrice = stderrors.New("price is zero")
|
|
|
|
|
2023-11-27 09:45:12 +00:00
|
|
|
func init() {
|
|
|
|
bbgo.RegisterStrategy(ID, &Strategy{})
|
|
|
|
}
|
|
|
|
|
2023-11-28 07:54:06 +00:00
|
|
|
type CrossExchangeMarketMakingStrategy struct {
|
|
|
|
ctx, parent context.Context
|
|
|
|
cancel context.CancelFunc
|
|
|
|
|
|
|
|
Environ *bbgo.Environment
|
|
|
|
|
|
|
|
makerSession, hedgeSession *bbgo.ExchangeSession
|
|
|
|
makerMarket, hedgeMarket types.Market
|
|
|
|
|
2023-11-28 08:46:58 +00:00
|
|
|
// persistence fields
|
2024-09-23 10:26:23 +00:00
|
|
|
Position *types.Position `json:"position,omitempty" persistence:"position"`
|
|
|
|
ProfitStats *types.ProfitStats `json:"profitStats,omitempty" persistence:"profit_stats"`
|
|
|
|
|
|
|
|
CoveredPosition fixedpoint.MutexValue
|
2024-08-10 07:50:20 +00:00
|
|
|
|
|
|
|
core.ConverterManager
|
|
|
|
|
|
|
|
mu sync.Mutex
|
2023-11-28 07:54:06 +00:00
|
|
|
|
|
|
|
MakerOrderExecutor, HedgeOrderExecutor *bbgo.GeneralOrderExecutor
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *CrossExchangeMarketMakingStrategy) Initialize(
|
|
|
|
ctx context.Context, environ *bbgo.Environment,
|
|
|
|
makerSession, hedgeSession *bbgo.ExchangeSession,
|
2024-08-07 08:01:56 +00:00
|
|
|
symbol, hedgeSymbol,
|
|
|
|
strategyID, instanceID string,
|
2023-11-28 07:54:06 +00:00
|
|
|
) error {
|
|
|
|
s.parent = ctx
|
|
|
|
s.ctx, s.cancel = context.WithCancel(ctx)
|
|
|
|
|
|
|
|
s.Environ = environ
|
|
|
|
|
|
|
|
s.makerSession = makerSession
|
|
|
|
s.hedgeSession = hedgeSession
|
|
|
|
|
|
|
|
var ok bool
|
2024-08-07 08:01:56 +00:00
|
|
|
s.hedgeMarket, ok = s.hedgeSession.Market(hedgeSymbol)
|
2023-11-28 07:54:06 +00:00
|
|
|
if !ok {
|
2024-08-07 08:01:56 +00:00
|
|
|
return fmt.Errorf("hedge session market %s is not defined", hedgeSymbol)
|
2023-11-28 07:54:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
s.makerMarket, ok = s.makerSession.Market(symbol)
|
|
|
|
if !ok {
|
|
|
|
return fmt.Errorf("maker session market %s is not defined", symbol)
|
|
|
|
}
|
|
|
|
|
2024-08-12 07:56:24 +00:00
|
|
|
if err := s.ConverterManager.Initialize(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2023-11-28 07:54:06 +00:00
|
|
|
if s.ProfitStats == nil {
|
|
|
|
s.ProfitStats = types.NewProfitStats(s.makerMarket)
|
|
|
|
}
|
|
|
|
|
|
|
|
if s.Position == nil {
|
|
|
|
s.Position = types.NewPositionFromMarket(s.makerMarket)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Always update the position fields
|
|
|
|
s.Position.Strategy = strategyID
|
|
|
|
s.Position.StrategyInstanceID = instanceID
|
|
|
|
|
|
|
|
// if anyone of the fee rate is defined, this assumes that both are defined.
|
|
|
|
// so that zero maker fee could be applied
|
|
|
|
for _, ses := range []*bbgo.ExchangeSession{makerSession, hedgeSession} {
|
|
|
|
if ses.MakerFeeRate.Sign() > 0 || ses.TakerFeeRate.Sign() > 0 {
|
|
|
|
s.Position.SetExchangeFeeRate(ses.ExchangeName, types.ExchangeFee{
|
|
|
|
MakerFeeRate: ses.MakerFeeRate,
|
|
|
|
TakerFeeRate: ses.TakerFeeRate,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
s.MakerOrderExecutor = bbgo.NewGeneralOrderExecutor(
|
|
|
|
makerSession,
|
|
|
|
s.makerMarket.Symbol,
|
|
|
|
strategyID, instanceID,
|
|
|
|
s.Position)
|
2024-08-10 07:50:20 +00:00
|
|
|
|
|
|
|
// update converter manager
|
|
|
|
s.MakerOrderExecutor.TradeCollector().ConverterManager = s.ConverterManager
|
|
|
|
|
2023-11-28 07:54:06 +00:00
|
|
|
s.MakerOrderExecutor.BindEnvironment(environ)
|
|
|
|
s.MakerOrderExecutor.BindProfitStats(s.ProfitStats)
|
|
|
|
s.MakerOrderExecutor.Bind()
|
|
|
|
s.MakerOrderExecutor.TradeCollector().OnPositionUpdate(func(position *types.Position) {
|
|
|
|
// bbgo.Sync(ctx, s)
|
|
|
|
})
|
|
|
|
|
|
|
|
s.HedgeOrderExecutor = bbgo.NewGeneralOrderExecutor(
|
|
|
|
hedgeSession,
|
|
|
|
s.hedgeMarket.Symbol,
|
|
|
|
strategyID, instanceID,
|
|
|
|
s.Position)
|
|
|
|
s.HedgeOrderExecutor.BindEnvironment(environ)
|
|
|
|
s.HedgeOrderExecutor.BindProfitStats(s.ProfitStats)
|
|
|
|
s.HedgeOrderExecutor.Bind()
|
2024-08-10 07:50:20 +00:00
|
|
|
|
|
|
|
s.HedgeOrderExecutor.TradeCollector().ConverterManager = s.ConverterManager
|
|
|
|
|
2023-11-28 07:54:06 +00:00
|
|
|
s.HedgeOrderExecutor.TradeCollector().OnPositionUpdate(func(position *types.Position) {
|
|
|
|
// bbgo.Sync(ctx, s)
|
|
|
|
})
|
|
|
|
|
2024-09-25 05:36:31 +00:00
|
|
|
s.HedgeOrderExecutor.ActiveMakerOrders().OnCanceled(func(o types.Order) {
|
|
|
|
remaining := o.Quantity.Sub(o.ExecutedQuantity)
|
2024-09-25 08:23:06 +00:00
|
|
|
|
|
|
|
log.Infof("canceled order #%d, remaining quantity: %f", o.OrderID, remaining.Float64())
|
|
|
|
|
2024-09-25 05:36:31 +00:00
|
|
|
switch o.Side {
|
|
|
|
case types.SideTypeSell:
|
|
|
|
remaining = remaining.Neg()
|
|
|
|
}
|
|
|
|
|
2024-09-25 08:48:24 +00:00
|
|
|
remaining = remaining.Neg()
|
|
|
|
coveredPosition := s.CoveredPosition.Get()
|
2024-09-25 05:36:31 +00:00
|
|
|
s.CoveredPosition.Sub(remaining)
|
2024-09-25 08:23:06 +00:00
|
|
|
|
2024-09-25 08:48:24 +00:00
|
|
|
log.Infof("coveredPosition %f - %f => %f", coveredPosition.Float64(), remaining.Float64(), s.CoveredPosition.Get().Float64())
|
2024-09-25 05:36:31 +00:00
|
|
|
})
|
|
|
|
|
2023-12-20 14:28:20 +00:00
|
|
|
s.HedgeOrderExecutor.TradeCollector().OnTrade(func(trade types.Trade, profit, netProfit fixedpoint.Value) {
|
2023-11-28 08:46:58 +00:00
|
|
|
c := trade.PositionChange()
|
2023-11-29 08:19:22 +00:00
|
|
|
|
|
|
|
// sync covered position
|
|
|
|
// sell trade -> negative delta ->
|
|
|
|
// 1) long position -> reduce long position
|
|
|
|
// 2) short position -> increase short position
|
|
|
|
// buy trade -> positive delta ->
|
|
|
|
// 1) short position -> reduce short position
|
|
|
|
// 2) short position -> increase short position
|
2024-09-23 10:26:23 +00:00
|
|
|
s.CoveredPosition.Add(c)
|
2023-12-20 14:28:20 +00:00
|
|
|
})
|
2023-11-28 07:54:06 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-09-24 08:12:17 +00:00
|
|
|
type HedgeStrategy string
|
|
|
|
|
|
|
|
const (
|
|
|
|
HedgeStrategyMarket HedgeStrategy = "market"
|
|
|
|
HedgeStrategyBboCounterParty1 HedgeStrategy = "bbo-counter-party-1"
|
2024-09-27 10:29:44 +00:00
|
|
|
HedgeStrategyBboCounterParty3 HedgeStrategy = "bbo-counter-party-3"
|
|
|
|
HedgeStrategyBboCounterParty5 HedgeStrategy = "bbo-counter-party-5"
|
2024-09-24 08:12:17 +00:00
|
|
|
HedgeStrategyBboQueue1 HedgeStrategy = "bbo-queue-1"
|
|
|
|
)
|
|
|
|
|
2023-11-27 09:45:12 +00:00
|
|
|
type Strategy struct {
|
2023-11-28 07:54:06 +00:00
|
|
|
*CrossExchangeMarketMakingStrategy
|
|
|
|
|
2023-11-27 09:45:12 +00:00
|
|
|
Environment *bbgo.Environment
|
|
|
|
|
2024-08-12 07:02:02 +00:00
|
|
|
// Symbol is the maker exchange symbol
|
2023-11-27 09:45:12 +00:00
|
|
|
Symbol string `json:"symbol"`
|
|
|
|
|
2024-08-07 08:01:56 +00:00
|
|
|
// HedgeSymbol is the symbol for the hedge exchange
|
|
|
|
// symbol could be different from the maker exchange
|
|
|
|
HedgeSymbol string `json:"hedgeSymbol"`
|
2023-11-27 09:45:12 +00:00
|
|
|
|
|
|
|
// MakerExchange session name
|
|
|
|
MakerExchange string `json:"makerExchange"`
|
|
|
|
|
2024-08-07 08:01:56 +00:00
|
|
|
// HedgeExchange session name
|
|
|
|
HedgeExchange string `json:"hedgeExchange"`
|
|
|
|
|
2024-09-27 12:00:48 +00:00
|
|
|
FastLayerUpdateInterval types.Duration `json:"fastLayerUpdateInterval"`
|
|
|
|
NumOfFastLayers int `json:"numOfFastLayers"`
|
2024-08-07 08:01:56 +00:00
|
|
|
|
|
|
|
HedgeInterval types.Duration `json:"hedgeInterval"`
|
2023-11-30 09:18:05 +00:00
|
|
|
|
2024-09-24 08:12:17 +00:00
|
|
|
HedgeStrategy HedgeStrategy `json:"hedgeStrategy"`
|
|
|
|
|
2024-09-25 07:52:23 +00:00
|
|
|
HedgeMaxOrderQuantity fixedpoint.Value `json:"hedgeMaxOrderQuantity"`
|
|
|
|
|
2023-11-30 09:18:05 +00:00
|
|
|
FullReplenishInterval types.Duration `json:"fullReplenishInterval"`
|
|
|
|
|
2023-11-27 09:45:12 +00:00
|
|
|
OrderCancelWaitTime types.Duration `json:"orderCancelWaitTime"`
|
|
|
|
|
2023-11-30 09:18:05 +00:00
|
|
|
Margin fixedpoint.Value `json:"margin"`
|
|
|
|
BidMargin fixedpoint.Value `json:"bidMargin"`
|
|
|
|
AskMargin fixedpoint.Value `json:"askMargin"`
|
2023-11-27 09:45:12 +00:00
|
|
|
|
|
|
|
StopHedgeQuoteBalance fixedpoint.Value `json:"stopHedgeQuoteBalance"`
|
|
|
|
StopHedgeBaseBalance fixedpoint.Value `json:"stopHedgeBaseBalance"`
|
|
|
|
|
|
|
|
// Quantity is used for fixed quantity of the first layer
|
|
|
|
Quantity fixedpoint.Value `json:"quantity"`
|
|
|
|
|
|
|
|
// QuantityScale helps user to define the quantity by layer scale
|
|
|
|
QuantityScale *bbgo.LayerScale `json:"quantityScale,omitempty"`
|
|
|
|
|
2023-11-30 02:32:03 +00:00
|
|
|
// DepthScale helps user to define the depth by layer scale
|
|
|
|
DepthScale *bbgo.LayerScale `json:"depthScale,omitempty"`
|
|
|
|
|
2023-11-27 09:45:12 +00:00
|
|
|
// MaxExposurePosition defines the unhedged quantity of stop
|
|
|
|
MaxExposurePosition fixedpoint.Value `json:"maxExposurePosition"`
|
|
|
|
|
2024-03-06 04:48:48 +00:00
|
|
|
DisableHedge bool `json:"disableHedge"`
|
|
|
|
|
2023-11-27 09:45:12 +00:00
|
|
|
NotifyTrade bool `json:"notifyTrade"`
|
|
|
|
|
|
|
|
// RecoverTrade tries to find the missing trades via the REStful API
|
|
|
|
RecoverTrade bool `json:"recoverTrade"`
|
|
|
|
|
2024-09-27 12:00:48 +00:00
|
|
|
PriceImpactRatio fixedpoint.Value `json:"priceImpactRatio"`
|
|
|
|
|
2023-11-27 09:45:12 +00:00
|
|
|
RecoverTradeScanPeriod types.Duration `json:"recoverTradeScanPeriod"`
|
|
|
|
|
|
|
|
NumLayers int `json:"numLayers"`
|
|
|
|
|
|
|
|
// Pips is the pips of the layer prices
|
|
|
|
Pips fixedpoint.Value `json:"pips"`
|
|
|
|
|
2024-07-08 06:15:15 +00:00
|
|
|
ProfitFixerConfig *common.ProfitFixerConfig `json:"profitFixer,omitempty"`
|
2024-03-05 10:12:30 +00:00
|
|
|
|
2023-11-27 09:45:12 +00:00
|
|
|
// --------------------------------
|
2023-11-27 09:55:46 +00:00
|
|
|
// private fields
|
|
|
|
// --------------------------------
|
2023-11-27 09:45:12 +00:00
|
|
|
|
2023-11-28 07:56:39 +00:00
|
|
|
// pricingBook is the order book (depth) from the hedging session
|
2024-09-24 08:12:17 +00:00
|
|
|
sourceBook *types.StreamOrderBook
|
2023-11-28 07:56:39 +00:00
|
|
|
|
2023-11-27 09:45:12 +00:00
|
|
|
hedgeErrorLimiter *rate.Limiter
|
|
|
|
hedgeErrorRateReservation *rate.Reservation
|
|
|
|
|
2023-11-30 05:44:35 +00:00
|
|
|
askPriceHeartBeat, bidPriceHeartBeat *types.PriceHeartBeat
|
2023-11-27 09:45:12 +00:00
|
|
|
|
2024-09-24 08:14:03 +00:00
|
|
|
lastSourcePrice fixedpoint.MutexValue
|
2023-11-27 09:45:12 +00:00
|
|
|
|
2024-09-27 10:29:44 +00:00
|
|
|
stopC chan struct{}
|
|
|
|
fullReplenishTriggerC sigchan.Chan
|
2024-09-24 08:12:17 +00:00
|
|
|
|
|
|
|
logger logrus.FieldLogger
|
2024-09-27 05:24:03 +00:00
|
|
|
|
2024-09-27 10:29:44 +00:00
|
|
|
makerConnectivity, hedgerConnectivity *types.Connectivity
|
|
|
|
connectivityGroup *types.ConnectivityGroup
|
|
|
|
|
|
|
|
priceSolver *pricesolver.SimplePriceSolver
|
2024-09-27 12:00:48 +00:00
|
|
|
bboMonitor *bbgo.BboMonitor
|
2023-11-27 09:45:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Strategy) ID() string {
|
|
|
|
return ID
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Strategy) InstanceID() string {
|
2024-09-24 08:12:17 +00:00
|
|
|
// this generates a unique instance ID for the strategy
|
|
|
|
return strings.Join([]string{
|
|
|
|
ID,
|
|
|
|
s.MakerExchange,
|
|
|
|
s.Symbol,
|
|
|
|
s.HedgeExchange,
|
|
|
|
s.HedgeSymbol,
|
|
|
|
}, "-")
|
2023-11-27 09:45:12 +00:00
|
|
|
}
|
|
|
|
|
2023-12-18 06:31:51 +00:00
|
|
|
func (s *Strategy) Initialize() error {
|
|
|
|
if s.CrossExchangeMarketMakingStrategy == nil {
|
|
|
|
s.CrossExchangeMarketMakingStrategy = &CrossExchangeMarketMakingStrategy{}
|
|
|
|
}
|
|
|
|
|
|
|
|
s.bidPriceHeartBeat = types.NewPriceHeartBeat(priceUpdateTimeout)
|
|
|
|
s.askPriceHeartBeat = types.NewPriceHeartBeat(priceUpdateTimeout)
|
2024-09-24 08:12:17 +00:00
|
|
|
s.logger = log.WithFields(logrus.Fields{
|
|
|
|
"symbol": s.Symbol,
|
|
|
|
"strategy": ID,
|
|
|
|
"strategy_instance": s.InstanceID(),
|
|
|
|
})
|
|
|
|
|
2023-12-18 06:31:51 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-11-27 09:45:12 +00:00
|
|
|
func (s *Strategy) CrossSubscribe(sessions map[string]*bbgo.ExchangeSession) {
|
2023-11-28 07:56:39 +00:00
|
|
|
makerSession, hedgeSession, err := selectSessions2(sessions, s.MakerExchange, s.HedgeExchange)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
2023-11-27 09:45:12 +00:00
|
|
|
}
|
|
|
|
|
2024-08-07 08:01:56 +00:00
|
|
|
hedgeSession.Subscribe(types.BookChannel, s.HedgeSymbol, types.SubscribeOptions{
|
2023-11-28 08:58:54 +00:00
|
|
|
Depth: types.DepthLevelMedium,
|
2023-12-07 09:38:39 +00:00
|
|
|
Speed: types.SpeedLow,
|
2023-11-28 08:58:54 +00:00
|
|
|
})
|
|
|
|
|
2024-08-07 08:01:56 +00:00
|
|
|
hedgeSession.Subscribe(types.KLineChannel, s.HedgeSymbol, types.SubscribeOptions{Interval: "1m"})
|
2024-09-27 10:29:44 +00:00
|
|
|
hedgeSession.Subscribe(types.KLineChannel, hedgeSession.Exchange.PlatformFeeCurrency()+"USDT", types.SubscribeOptions{Interval: "1m"})
|
2024-08-12 07:02:02 +00:00
|
|
|
|
2023-11-27 09:45:12 +00:00
|
|
|
makerSession.Subscribe(types.KLineChannel, s.Symbol, types.SubscribeOptions{Interval: "1m"})
|
2024-09-27 10:29:44 +00:00
|
|
|
makerSession.Subscribe(types.KLineChannel, makerSession.Exchange.PlatformFeeCurrency()+"USDT", types.SubscribeOptions{Interval: "1m"})
|
2023-11-27 09:45:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Strategy) Validate() error {
|
2023-11-28 09:01:11 +00:00
|
|
|
if s.MakerExchange == "" {
|
|
|
|
return errors.New("maker exchange is not configured")
|
|
|
|
}
|
|
|
|
|
|
|
|
if s.HedgeExchange == "" {
|
2024-09-24 08:14:03 +00:00
|
|
|
return errors.New("hedge exchange is not configured")
|
2023-11-28 09:01:11 +00:00
|
|
|
}
|
|
|
|
|
2023-11-30 02:32:03 +00:00
|
|
|
if s.DepthScale == nil {
|
|
|
|
return errors.New("depthScale can not be empty")
|
2023-11-27 09:45:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if len(s.Symbol) == 0 {
|
|
|
|
return errors.New("symbol is required")
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Strategy) Defaults() error {
|
2024-09-27 12:00:48 +00:00
|
|
|
if s.FastLayerUpdateInterval == 0 {
|
|
|
|
s.FastLayerUpdateInterval = types.Duration(5 * time.Second)
|
2023-11-27 09:45:12 +00:00
|
|
|
}
|
|
|
|
|
2024-09-27 12:00:48 +00:00
|
|
|
if s.NumOfFastLayers == 0 {
|
|
|
|
s.NumOfFastLayers = 5
|
2024-09-27 09:53:21 +00:00
|
|
|
}
|
|
|
|
|
2023-11-30 09:18:05 +00:00
|
|
|
if s.FullReplenishInterval == 0 {
|
2024-03-06 05:13:18 +00:00
|
|
|
s.FullReplenishInterval = types.Duration(10 * time.Minute)
|
2023-11-30 09:18:05 +00:00
|
|
|
}
|
|
|
|
|
2023-11-27 09:45:12 +00:00
|
|
|
if s.HedgeInterval == 0 {
|
|
|
|
s.HedgeInterval = types.Duration(3 * time.Second)
|
|
|
|
}
|
|
|
|
|
2024-09-24 08:12:17 +00:00
|
|
|
if s.HedgeStrategy == "" {
|
|
|
|
s.HedgeStrategy = HedgeStrategyMarket
|
|
|
|
}
|
|
|
|
|
2024-08-07 08:01:56 +00:00
|
|
|
if s.HedgeSymbol == "" {
|
|
|
|
s.HedgeSymbol = s.Symbol
|
|
|
|
}
|
|
|
|
|
2023-11-27 09:45:12 +00:00
|
|
|
if s.NumLayers == 0 {
|
|
|
|
s.NumLayers = 1
|
|
|
|
}
|
|
|
|
|
|
|
|
if s.Margin.IsZero() {
|
|
|
|
s.Margin = defaultMargin
|
|
|
|
}
|
|
|
|
|
|
|
|
if s.BidMargin.IsZero() {
|
|
|
|
if !s.Margin.IsZero() {
|
|
|
|
s.BidMargin = s.Margin
|
|
|
|
} else {
|
|
|
|
s.BidMargin = defaultMargin
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if s.AskMargin.IsZero() {
|
|
|
|
if !s.Margin.IsZero() {
|
|
|
|
s.AskMargin = s.Margin
|
|
|
|
} else {
|
|
|
|
s.AskMargin = defaultMargin
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
s.hedgeErrorLimiter = rate.NewLimiter(rate.Every(1*time.Minute), 1)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-09-26 09:57:12 +00:00
|
|
|
func (s *Strategy) quoteWorker(ctx context.Context) {
|
2024-09-27 12:00:48 +00:00
|
|
|
updateTicker := time.NewTicker(util.MillisecondsJitter(s.FastLayerUpdateInterval.Duration(), 200))
|
2024-09-26 09:57:12 +00:00
|
|
|
defer updateTicker.Stop()
|
|
|
|
|
|
|
|
fullReplenishTicker := time.NewTicker(util.MillisecondsJitter(s.FullReplenishInterval.Duration(), 200))
|
|
|
|
defer fullReplenishTicker.Stop()
|
|
|
|
|
|
|
|
// clean up the previous open orders
|
|
|
|
if err := s.cleanUpOpenOrders(ctx, s.makerSession); err != nil {
|
|
|
|
log.WithError(err).Errorf("error cleaning up open orders")
|
2024-09-27 06:27:20 +00:00
|
|
|
return
|
2024-09-26 09:57:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
s.updateQuote(ctx, 0)
|
|
|
|
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return
|
|
|
|
|
|
|
|
case <-s.stopC:
|
|
|
|
log.Warnf("%s maker goroutine stopped, due to the stop signal", s.Symbol)
|
|
|
|
return
|
|
|
|
|
2024-09-27 10:29:44 +00:00
|
|
|
case <-s.fullReplenishTriggerC:
|
|
|
|
// force trigger full replenish
|
|
|
|
s.updateQuote(ctx, 0)
|
|
|
|
|
2024-09-26 09:57:12 +00:00
|
|
|
case <-fullReplenishTicker.C:
|
|
|
|
s.updateQuote(ctx, 0)
|
2024-09-27 12:00:48 +00:00
|
|
|
|
|
|
|
case <-updateTicker.C:
|
|
|
|
s.updateQuote(ctx, s.NumOfFastLayers)
|
2024-09-26 09:57:12 +00:00
|
|
|
|
|
|
|
case sig, ok := <-s.sourceBook.C:
|
|
|
|
// when any book change event happened
|
|
|
|
if !ok {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-09-27 12:00:48 +00:00
|
|
|
changed := s.bboMonitor.UpdateFromBook(s.sourceBook)
|
|
|
|
if changed || sig.Type == types.BookSignalSnapshot {
|
2024-09-26 09:57:12 +00:00
|
|
|
s.updateQuote(ctx, 0)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Strategy) hedgeWorker(ctx context.Context) {
|
|
|
|
ticker := time.NewTicker(util.MillisecondsJitter(s.HedgeInterval.Duration(), 200))
|
|
|
|
defer ticker.Stop()
|
|
|
|
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
s.logger.Warnf("maker goroutine stopped, due to context canceled")
|
|
|
|
return
|
|
|
|
|
|
|
|
case <-s.stopC:
|
|
|
|
s.logger.Warnf("maker goroutine stopped, due to the stop signal")
|
|
|
|
return
|
|
|
|
|
|
|
|
case <-ticker.C:
|
|
|
|
// For positive position and positive covered position:
|
|
|
|
// uncover position = +5 - +3 (covered position) = 2
|
|
|
|
//
|
|
|
|
// For positive position and negative covered position:
|
|
|
|
// uncover position = +5 - (-3) (covered position) = 8
|
|
|
|
//
|
|
|
|
// meaning we bought 5 on MAX and sent buy order with 3 on binance
|
|
|
|
//
|
|
|
|
// For negative position:
|
|
|
|
// uncover position = -5 - -3 (covered position) = -2
|
|
|
|
s.HedgeOrderExecutor.TradeCollector().Process()
|
|
|
|
s.MakerOrderExecutor.TradeCollector().Process()
|
|
|
|
|
|
|
|
position := s.Position.GetBase()
|
|
|
|
|
|
|
|
coveredPosition := s.CoveredPosition.Get()
|
|
|
|
uncoverPosition := position.Sub(coveredPosition)
|
|
|
|
|
|
|
|
absPos := uncoverPosition.Abs()
|
|
|
|
if !s.hedgeMarket.IsDustQuantity(absPos, s.lastSourcePrice.Get()) {
|
|
|
|
log.Infof("%s base position %v coveredPosition: %v uncoverPosition: %v",
|
|
|
|
s.Symbol,
|
|
|
|
position,
|
|
|
|
coveredPosition,
|
|
|
|
uncoverPosition,
|
|
|
|
)
|
|
|
|
|
|
|
|
if !s.DisableHedge {
|
|
|
|
if err := s.Hedge(ctx, uncoverPosition.Neg()); err != nil {
|
|
|
|
//goland:noinspection GoDirectComparisonOfErrors
|
|
|
|
switch err {
|
|
|
|
case ErrZeroQuantity, ErrDustQuantity:
|
|
|
|
default:
|
|
|
|
s.logger.WithError(err).Errorf("unable to hedge position")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-11-27 09:45:12 +00:00
|
|
|
func (s *Strategy) CrossRun(
|
2023-11-29 01:39:03 +00:00
|
|
|
ctx context.Context, _ bbgo.OrderExecutionRouter,
|
|
|
|
sessions map[string]*bbgo.ExchangeSession,
|
2023-11-27 09:45:12 +00:00
|
|
|
) error {
|
2023-11-28 07:54:06 +00:00
|
|
|
makerSession, hedgeSession, err := selectSessions2(sessions, s.MakerExchange, s.HedgeExchange)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2023-11-27 09:45:12 +00:00
|
|
|
}
|
|
|
|
|
2023-12-18 14:17:52 +00:00
|
|
|
log.Infof("makerSession: %s hedgeSession: %s", makerSession.Name, hedgeSession.Name)
|
|
|
|
|
2024-03-05 10:12:30 +00:00
|
|
|
if s.ProfitFixerConfig != nil {
|
2024-03-06 09:48:53 +00:00
|
|
|
bbgo.Notify("Fixing %s profitStats and position...", s.Symbol)
|
|
|
|
|
2024-03-06 09:47:18 +00:00
|
|
|
log.Infof("profitFixer is enabled, checking checkpoint: %+v", s.ProfitFixerConfig.TradesSince)
|
|
|
|
|
2024-03-05 10:12:30 +00:00
|
|
|
if s.ProfitFixerConfig.TradesSince.Time().IsZero() {
|
|
|
|
return errors.New("tradesSince time can not be zero")
|
|
|
|
}
|
|
|
|
|
2024-03-06 09:19:50 +00:00
|
|
|
makerMarket, _ := makerSession.Market(s.Symbol)
|
2024-03-06 08:10:22 +00:00
|
|
|
s.CrossExchangeMarketMakingStrategy.Position = types.NewPositionFromMarket(makerMarket)
|
|
|
|
s.CrossExchangeMarketMakingStrategy.ProfitStats = types.NewProfitStats(makerMarket)
|
2024-03-05 13:11:51 +00:00
|
|
|
|
2024-03-06 13:56:32 +00:00
|
|
|
fixer := common.NewProfitFixer()
|
2024-08-12 07:02:02 +00:00
|
|
|
fixer.ConverterManager = s.ConverterManager
|
|
|
|
|
2024-03-06 09:47:18 +00:00
|
|
|
if ss, ok := makerSession.Exchange.(types.ExchangeTradeHistoryService); ok {
|
|
|
|
log.Infof("adding makerSession %s to profitFixer", makerSession.Name)
|
|
|
|
fixer.AddExchange(makerSession.Name, ss)
|
|
|
|
}
|
|
|
|
|
|
|
|
if ss, ok := hedgeSession.Exchange.(types.ExchangeTradeHistoryService); ok {
|
|
|
|
log.Infof("adding hedgeSession %s to profitFixer", hedgeSession.Name)
|
|
|
|
fixer.AddExchange(hedgeSession.Name, ss)
|
|
|
|
}
|
2024-03-06 09:19:50 +00:00
|
|
|
|
2024-03-06 13:56:32 +00:00
|
|
|
if err2 := fixer.Fix(ctx, makerMarket.Symbol,
|
|
|
|
s.ProfitFixerConfig.TradesSince.Time(),
|
|
|
|
time.Now(),
|
|
|
|
s.CrossExchangeMarketMakingStrategy.ProfitStats,
|
|
|
|
s.CrossExchangeMarketMakingStrategy.Position); err2 != nil {
|
2024-03-05 10:12:30 +00:00
|
|
|
return err2
|
|
|
|
}
|
2024-03-06 09:48:53 +00:00
|
|
|
|
|
|
|
bbgo.Notify("Fixed %s position", s.Symbol, s.CrossExchangeMarketMakingStrategy.Position)
|
|
|
|
bbgo.Notify("Fixed %s profitStats", s.Symbol, s.CrossExchangeMarketMakingStrategy.ProfitStats)
|
2024-03-05 10:12:30 +00:00
|
|
|
}
|
|
|
|
|
2024-03-06 08:10:22 +00:00
|
|
|
if err := s.CrossExchangeMarketMakingStrategy.Initialize(ctx,
|
|
|
|
s.Environment,
|
2024-08-07 08:01:56 +00:00
|
|
|
makerSession, hedgeSession,
|
|
|
|
s.Symbol, s.HedgeSymbol,
|
|
|
|
ID, s.InstanceID()); err != nil {
|
2024-03-06 04:53:36 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2024-09-24 08:12:17 +00:00
|
|
|
s.sourceBook = types.NewStreamBook(s.HedgeSymbol, s.hedgeSession.ExchangeName)
|
|
|
|
s.sourceBook.BindStream(s.hedgeSession.MarketDataStream)
|
2024-03-06 04:53:36 +00:00
|
|
|
|
2024-09-27 10:29:44 +00:00
|
|
|
s.priceSolver = pricesolver.NewSimplePriceResolver(s.makerSession.Markets())
|
|
|
|
s.priceSolver.BindStream(s.hedgeSession.MarketDataStream)
|
|
|
|
s.priceSolver.BindStream(s.makerSession.MarketDataStream)
|
|
|
|
|
2024-09-27 12:00:48 +00:00
|
|
|
s.bboMonitor = bbgo.NewBboMonitor()
|
|
|
|
if !s.PriceImpactRatio.IsZero() {
|
|
|
|
s.bboMonitor.SetPriceImpactRatio(s.PriceImpactRatio)
|
|
|
|
}
|
|
|
|
|
2024-09-27 10:29:44 +00:00
|
|
|
if err := s.priceSolver.UpdateFromTickers(ctx, s.makerSession.Exchange,
|
|
|
|
s.Symbol, s.makerSession.Exchange.PlatformFeeCurrency()+"USDT"); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := s.priceSolver.UpdateFromTickers(ctx, s.hedgeSession.Exchange, s.HedgeSymbol); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
s.makerSession.MarketDataStream.OnKLineClosed(types.KLineWith(s.Symbol, types.Interval1m, func(k types.KLine) {
|
|
|
|
s.priceSolver.Update(k.Symbol, k.Close)
|
|
|
|
feeToken := s.makerSession.Exchange.PlatformFeeCurrency()
|
|
|
|
if feePrice, ok := s.priceSolver.ResolvePrice(feeToken, "USDT"); ok {
|
|
|
|
s.Position.SetFeeAverageCost(feeToken, feePrice)
|
|
|
|
}
|
|
|
|
}))
|
|
|
|
|
2024-03-06 04:53:36 +00:00
|
|
|
s.stopC = make(chan struct{})
|
2024-09-27 10:29:44 +00:00
|
|
|
s.fullReplenishTriggerC = sigchan.New(1)
|
2024-03-06 04:53:36 +00:00
|
|
|
|
2024-09-27 10:29:44 +00:00
|
|
|
s.makerConnectivity = types.NewConnectivity()
|
|
|
|
s.makerConnectivity.Bind(s.makerSession.UserDataStream)
|
2024-09-27 05:24:03 +00:00
|
|
|
|
2024-09-27 10:29:44 +00:00
|
|
|
s.hedgerConnectivity = types.NewConnectivity()
|
|
|
|
s.hedgerConnectivity.Bind(s.hedgeSession.UserDataStream)
|
2024-09-27 05:24:03 +00:00
|
|
|
|
2024-09-27 10:29:44 +00:00
|
|
|
connGroup := types.NewConnectivityGroup(s.makerConnectivity, s.hedgerConnectivity)
|
2024-09-27 05:24:03 +00:00
|
|
|
s.connectivityGroup = connGroup
|
2024-03-06 04:53:36 +00:00
|
|
|
|
2024-03-05 10:12:30 +00:00
|
|
|
if s.RecoverTrade {
|
|
|
|
go s.runTradeRecover(ctx)
|
|
|
|
}
|
|
|
|
|
2023-11-27 09:45:12 +00:00
|
|
|
go func() {
|
2023-12-11 08:56:19 +00:00
|
|
|
log.Infof("waiting for user data stream to get authenticated")
|
|
|
|
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return
|
2024-09-27 05:24:03 +00:00
|
|
|
case <-connGroup.AllAuthedC(ctx, time.Minute):
|
2023-12-11 08:56:19 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
log.Infof("user data stream authenticated, start placing orders...")
|
|
|
|
|
2024-09-26 09:57:12 +00:00
|
|
|
go s.hedgeWorker(ctx)
|
|
|
|
go s.quoteWorker(ctx)
|
2023-11-27 09:45:12 +00:00
|
|
|
}()
|
|
|
|
|
|
|
|
bbgo.OnShutdown(ctx, func(ctx context.Context, wg *sync.WaitGroup) {
|
|
|
|
defer wg.Done()
|
|
|
|
|
2024-09-27 10:29:44 +00:00
|
|
|
bbgo.Notify("Shutting down %s: %s", ID, s.Symbol)
|
|
|
|
|
2023-11-27 09:45:12 +00:00
|
|
|
close(s.stopC)
|
|
|
|
|
|
|
|
// wait for the quoter to stop
|
2024-09-27 12:00:48 +00:00
|
|
|
time.Sleep(s.FastLayerUpdateInterval.Duration())
|
2023-11-27 09:45:12 +00:00
|
|
|
|
2023-12-13 08:29:07 +00:00
|
|
|
if err := s.MakerOrderExecutor.GracefulCancel(ctx); err != nil {
|
2023-11-28 08:46:58 +00:00
|
|
|
log.WithError(err).Errorf("graceful cancel %s order error", s.Symbol)
|
|
|
|
}
|
|
|
|
|
2023-12-13 08:29:07 +00:00
|
|
|
if err := s.HedgeOrderExecutor.GracefulCancel(ctx); err != nil {
|
2024-08-07 08:01:56 +00:00
|
|
|
log.WithError(err).Errorf("graceful cancel %s order error", s.HedgeSymbol)
|
2023-11-27 09:45:12 +00:00
|
|
|
}
|
|
|
|
|
2024-09-23 10:26:23 +00:00
|
|
|
if err := tradingutil.UniversalCancelAllOrders(ctx, s.makerSession.Exchange, s.Symbol, s.MakerOrderExecutor.ActiveMakerOrders().Orders()); err != nil {
|
|
|
|
log.WithError(err).Errorf("unable to cancel all orders")
|
|
|
|
}
|
|
|
|
|
2024-09-27 10:29:44 +00:00
|
|
|
// process collected trades
|
|
|
|
s.HedgeOrderExecutor.TradeCollector().Process()
|
|
|
|
s.MakerOrderExecutor.TradeCollector().Process()
|
|
|
|
|
2023-12-18 14:30:16 +00:00
|
|
|
bbgo.Sync(ctx, s)
|
2024-09-27 10:29:44 +00:00
|
|
|
|
|
|
|
bbgo.Notify("Shutdown %s: %s position", ID, s.Symbol, s.Position)
|
2023-11-27 09:45:12 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-09-24 08:12:17 +00:00
|
|
|
func (s *Strategy) Hedge(ctx context.Context, pos fixedpoint.Value) error {
|
2023-11-27 09:45:12 +00:00
|
|
|
if pos.IsZero() {
|
2024-09-24 08:12:17 +00:00
|
|
|
return nil
|
2023-11-27 09:45:12 +00:00
|
|
|
}
|
|
|
|
|
2024-09-23 10:28:46 +00:00
|
|
|
// the default side
|
|
|
|
side := types.SideTypeBuy
|
2023-11-27 09:45:12 +00:00
|
|
|
if pos.Sign() < 0 {
|
|
|
|
side = types.SideTypeSell
|
|
|
|
}
|
|
|
|
|
2024-09-23 10:28:46 +00:00
|
|
|
quantity := pos.Abs()
|
|
|
|
|
2024-09-25 08:24:34 +00:00
|
|
|
if s.HedgeMaxOrderQuantity.Sign() > 0 && quantity.Compare(s.HedgeMaxOrderQuantity) > 0 {
|
2024-09-25 07:52:23 +00:00
|
|
|
s.logger.Infof("hedgeMaxOrderQuantity is set to %s, limiting the given quantity %s", s.HedgeMaxOrderQuantity.String(), quantity.String())
|
|
|
|
quantity = fixedpoint.Min(s.HedgeMaxOrderQuantity, quantity)
|
|
|
|
}
|
|
|
|
|
2024-09-27 10:29:44 +00:00
|
|
|
defer func() {
|
|
|
|
s.fullReplenishTriggerC.Emit()
|
|
|
|
}()
|
|
|
|
|
2024-09-24 08:12:17 +00:00
|
|
|
switch s.HedgeStrategy {
|
|
|
|
case HedgeStrategyMarket:
|
|
|
|
return s.executeHedgeMarket(ctx, side, quantity)
|
|
|
|
case HedgeStrategyBboCounterParty1:
|
2024-09-27 10:29:44 +00:00
|
|
|
return s.executeHedgeBboCounterPartyWithIndex(ctx, side, 1, quantity)
|
|
|
|
case HedgeStrategyBboCounterParty3:
|
|
|
|
return s.executeHedgeBboCounterPartyWithIndex(ctx, side, 3, quantity)
|
|
|
|
case HedgeStrategyBboCounterParty5:
|
|
|
|
return s.executeHedgeBboCounterPartyWithIndex(ctx, side, 5, quantity)
|
2024-09-24 09:10:50 +00:00
|
|
|
case HedgeStrategyBboQueue1:
|
|
|
|
return s.executeHedgeBboQueue1(ctx, side, quantity)
|
2024-09-24 08:33:53 +00:00
|
|
|
default:
|
2024-09-24 09:10:50 +00:00
|
|
|
return fmt.Errorf("unsupported or invalid hedge strategy setup %q, please check your configuration", s.HedgeStrategy)
|
2024-09-24 08:12:17 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-09-27 10:29:44 +00:00
|
|
|
func (s *Strategy) executeHedgeBboCounterPartyWithIndex(
|
2024-09-24 08:12:17 +00:00
|
|
|
ctx context.Context,
|
|
|
|
side types.SideType,
|
2024-09-27 10:29:44 +00:00
|
|
|
idx int,
|
2024-09-24 08:12:17 +00:00
|
|
|
quantity fixedpoint.Value,
|
|
|
|
) error {
|
2024-09-24 08:14:03 +00:00
|
|
|
price := s.lastSourcePrice.Get()
|
2024-09-27 10:29:44 +00:00
|
|
|
|
|
|
|
sideBook := s.sourceBook.SideBook(side.Reverse())
|
|
|
|
if pv, ok := sideBook.ElemOrLast(idx); ok {
|
|
|
|
price = pv.Price
|
2023-11-27 09:45:12 +00:00
|
|
|
}
|
|
|
|
|
2024-09-24 08:14:03 +00:00
|
|
|
if price.IsZero() {
|
2024-09-24 08:12:17 +00:00
|
|
|
return ErrZeroPrice
|
2023-11-27 09:45:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// adjust quantity according to the balances
|
2023-11-28 07:54:06 +00:00
|
|
|
account := s.hedgeSession.GetAccount()
|
2023-11-27 09:45:12 +00:00
|
|
|
|
2024-09-23 14:16:53 +00:00
|
|
|
quantity = xmaker.AdjustHedgeQuantityWithAvailableBalance(account,
|
2024-09-24 08:12:17 +00:00
|
|
|
s.hedgeMarket,
|
|
|
|
side,
|
|
|
|
quantity,
|
2024-09-24 08:14:03 +00:00
|
|
|
price)
|
2023-11-27 09:45:12 +00:00
|
|
|
|
|
|
|
// truncate quantity for the supported precision
|
2023-11-28 07:54:06 +00:00
|
|
|
quantity = s.hedgeMarket.TruncateQuantity(quantity)
|
2024-09-24 08:12:17 +00:00
|
|
|
if quantity.IsZero() {
|
|
|
|
return ErrZeroQuantity
|
|
|
|
}
|
2023-11-27 09:45:12 +00:00
|
|
|
|
2024-09-24 08:14:03 +00:00
|
|
|
if s.hedgeMarket.IsDustQuantity(quantity, price) {
|
2024-09-24 08:12:17 +00:00
|
|
|
return ErrDustQuantity
|
2023-11-27 09:45:12 +00:00
|
|
|
}
|
|
|
|
|
2024-09-24 08:33:53 +00:00
|
|
|
// submit order as limit taker
|
2024-09-24 08:12:17 +00:00
|
|
|
return s.executeHedgeOrder(ctx, types.SubmitOrder{
|
|
|
|
Market: s.hedgeMarket,
|
|
|
|
Symbol: s.hedgeMarket.Symbol,
|
|
|
|
Type: types.OrderTypeLimit,
|
2024-09-24 09:10:50 +00:00
|
|
|
Price: price,
|
|
|
|
Side: side,
|
|
|
|
Quantity: quantity,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Strategy) executeHedgeBboQueue1(
|
|
|
|
ctx context.Context,
|
|
|
|
side types.SideType,
|
|
|
|
quantity fixedpoint.Value,
|
|
|
|
) error {
|
|
|
|
price := s.lastSourcePrice.Get()
|
|
|
|
if sourcePrice := s.getSourceBboPrice(side); sourcePrice.Sign() > 0 {
|
|
|
|
price = sourcePrice
|
|
|
|
}
|
|
|
|
|
|
|
|
if price.IsZero() {
|
|
|
|
return ErrZeroPrice
|
|
|
|
}
|
|
|
|
|
|
|
|
// adjust quantity according to the balances
|
|
|
|
account := s.hedgeSession.GetAccount()
|
|
|
|
|
|
|
|
quantity = xmaker.AdjustHedgeQuantityWithAvailableBalance(account,
|
|
|
|
s.hedgeMarket,
|
|
|
|
side,
|
|
|
|
quantity,
|
|
|
|
price)
|
|
|
|
|
|
|
|
// truncate quantity for the supported precision
|
|
|
|
quantity = s.hedgeMarket.TruncateQuantity(quantity)
|
|
|
|
if quantity.IsZero() {
|
|
|
|
return ErrZeroQuantity
|
|
|
|
}
|
|
|
|
|
|
|
|
if s.hedgeMarket.IsDustQuantity(quantity, price) {
|
|
|
|
return ErrDustQuantity
|
|
|
|
}
|
|
|
|
|
|
|
|
// submit order as limit taker
|
|
|
|
return s.executeHedgeOrder(ctx, types.SubmitOrder{
|
|
|
|
Market: s.hedgeMarket,
|
|
|
|
Symbol: s.hedgeMarket.Symbol,
|
|
|
|
Type: types.OrderTypeLimit,
|
2024-09-24 08:33:53 +00:00
|
|
|
Price: price,
|
2024-09-24 08:12:17 +00:00
|
|
|
Side: side,
|
|
|
|
Quantity: quantity,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Strategy) executeHedgeMarket(
|
|
|
|
ctx context.Context,
|
|
|
|
side types.SideType,
|
|
|
|
quantity fixedpoint.Value,
|
|
|
|
) error {
|
2024-09-24 08:14:03 +00:00
|
|
|
price := s.lastSourcePrice.Get()
|
2024-09-24 08:12:17 +00:00
|
|
|
if sourcePrice := s.getSourceBboPrice(side.Reverse()); sourcePrice.Sign() > 0 {
|
2024-09-24 08:14:03 +00:00
|
|
|
price = sourcePrice
|
2024-09-24 08:12:17 +00:00
|
|
|
}
|
|
|
|
|
2024-09-24 08:14:03 +00:00
|
|
|
if price.IsZero() {
|
2024-09-24 08:12:17 +00:00
|
|
|
return ErrZeroPrice
|
|
|
|
}
|
|
|
|
|
|
|
|
// adjust quantity according to the balances
|
|
|
|
account := s.hedgeSession.GetAccount()
|
|
|
|
|
|
|
|
quantity = xmaker.AdjustHedgeQuantityWithAvailableBalance(account,
|
|
|
|
s.hedgeMarket,
|
|
|
|
side,
|
|
|
|
quantity,
|
2024-09-24 08:14:03 +00:00
|
|
|
price)
|
2024-09-24 08:12:17 +00:00
|
|
|
|
|
|
|
// truncate quantity for the supported precision
|
|
|
|
quantity = s.hedgeMarket.TruncateQuantity(quantity)
|
|
|
|
if quantity.IsZero() {
|
|
|
|
return ErrZeroQuantity
|
2023-11-27 09:45:12 +00:00
|
|
|
}
|
|
|
|
|
2024-09-24 08:14:03 +00:00
|
|
|
if s.hedgeMarket.IsDustQuantity(quantity, price) {
|
2024-09-24 08:12:17 +00:00
|
|
|
return ErrDustQuantity
|
|
|
|
}
|
2023-11-29 01:39:03 +00:00
|
|
|
|
2024-09-24 08:12:17 +00:00
|
|
|
return s.executeHedgeOrder(ctx, types.SubmitOrder{
|
2023-11-28 07:54:06 +00:00
|
|
|
Market: s.hedgeMarket,
|
2024-08-07 08:01:56 +00:00
|
|
|
Symbol: s.hedgeMarket.Symbol,
|
2023-11-27 09:45:12 +00:00
|
|
|
Type: types.OrderTypeMarket,
|
|
|
|
Side: side,
|
|
|
|
Quantity: quantity,
|
|
|
|
})
|
2024-09-24 08:12:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// getSourceBboPrice returns the best bid offering price from the source order book
|
|
|
|
func (s *Strategy) getSourceBboPrice(side types.SideType) fixedpoint.Value {
|
2024-09-24 08:33:53 +00:00
|
|
|
bid, ask, ok := s.sourceBook.BestBidAndAsk()
|
|
|
|
if !ok {
|
|
|
|
return fixedpoint.Zero
|
|
|
|
}
|
2024-09-24 08:12:17 +00:00
|
|
|
|
2024-09-24 08:33:53 +00:00
|
|
|
switch side {
|
2024-09-24 08:12:17 +00:00
|
|
|
case types.SideTypeSell:
|
2024-09-24 08:33:53 +00:00
|
|
|
return ask.Price
|
2024-09-24 08:12:17 +00:00
|
|
|
case types.SideTypeBuy:
|
2024-09-24 08:33:53 +00:00
|
|
|
return bid.Price
|
2024-09-24 08:12:17 +00:00
|
|
|
}
|
|
|
|
return fixedpoint.Zero
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Strategy) executeHedgeOrder(ctx context.Context, submitOrder types.SubmitOrder) error {
|
2024-09-24 08:33:53 +00:00
|
|
|
if err := s.HedgeOrderExecutor.GracefulCancel(ctx); err != nil {
|
|
|
|
s.logger.WithError(err).Warnf("graceful cancel order error")
|
|
|
|
}
|
|
|
|
|
2024-09-24 08:12:17 +00:00
|
|
|
if s.hedgeErrorRateReservation != nil {
|
|
|
|
if !s.hedgeErrorRateReservation.OK() {
|
|
|
|
s.logger.Warnf("rate reservation hitted, skip executing hedge order")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
bbgo.Notify("Hit hedge error rate limit, waiting...")
|
|
|
|
time.Sleep(s.hedgeErrorRateReservation.Delay())
|
|
|
|
|
|
|
|
// reset reservation
|
|
|
|
s.hedgeErrorRateReservation = nil
|
|
|
|
}
|
|
|
|
|
2024-09-24 08:33:53 +00:00
|
|
|
bbgo.Notify("Submitting hedge %s order on %s %s %s %s @ %s",
|
|
|
|
submitOrder.Type, s.HedgeSymbol, s.HedgeExchange,
|
2024-09-24 08:12:17 +00:00
|
|
|
submitOrder.Side.String(),
|
2024-09-24 08:33:53 +00:00
|
|
|
submitOrder.Quantity.String(),
|
|
|
|
submitOrder.Price.String(),
|
|
|
|
)
|
2023-11-27 09:45:12 +00:00
|
|
|
|
2024-09-24 08:12:17 +00:00
|
|
|
_, err := s.HedgeOrderExecutor.SubmitOrders(ctx, submitOrder)
|
2023-11-27 09:45:12 +00:00
|
|
|
if err != nil {
|
2024-09-24 08:12:17 +00:00
|
|
|
// allocate a new reservation
|
2023-11-27 09:45:12 +00:00
|
|
|
s.hedgeErrorRateReservation = s.hedgeErrorLimiter.Reserve()
|
2024-09-24 08:12:17 +00:00
|
|
|
return err
|
2023-11-27 09:45:12 +00:00
|
|
|
}
|
|
|
|
|
2023-11-29 08:19:22 +00:00
|
|
|
// if the hedge is on sell side, then we should add positive position
|
2024-09-24 08:12:17 +00:00
|
|
|
switch submitOrder.Side {
|
2023-11-29 08:19:22 +00:00
|
|
|
case types.SideTypeSell:
|
2024-09-24 08:12:17 +00:00
|
|
|
s.CoveredPosition.Add(submitOrder.Quantity)
|
2023-11-29 08:19:22 +00:00
|
|
|
case types.SideTypeBuy:
|
2024-09-24 08:12:17 +00:00
|
|
|
s.CoveredPosition.Add(submitOrder.Quantity.Neg())
|
2023-11-27 09:45:12 +00:00
|
|
|
}
|
2024-09-24 08:12:17 +00:00
|
|
|
|
|
|
|
return nil
|
2023-11-27 09:45:12 +00:00
|
|
|
}
|
|
|
|
|
2023-11-29 01:39:03 +00:00
|
|
|
func (s *Strategy) runTradeRecover(ctx context.Context) {
|
2023-11-27 09:45:12 +00:00
|
|
|
tradeScanInterval := s.RecoverTradeScanPeriod.Duration()
|
|
|
|
if tradeScanInterval == 0 {
|
|
|
|
tradeScanInterval = 30 * time.Minute
|
|
|
|
}
|
|
|
|
|
|
|
|
tradeScanOverlapBufferPeriod := 5 * time.Minute
|
|
|
|
|
|
|
|
tradeScanTicker := time.NewTicker(tradeScanInterval)
|
|
|
|
defer tradeScanTicker.Stop()
|
|
|
|
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return
|
|
|
|
|
|
|
|
case <-tradeScanTicker.C:
|
|
|
|
log.Infof("scanning trades from %s ago...", tradeScanInterval)
|
|
|
|
|
2024-03-05 10:12:30 +00:00
|
|
|
startTime := time.Now().Add(-tradeScanInterval).Add(-tradeScanOverlapBufferPeriod)
|
2023-11-27 09:45:12 +00:00
|
|
|
|
2024-08-07 08:01:56 +00:00
|
|
|
if err := s.HedgeOrderExecutor.TradeCollector().Recover(ctx, s.hedgeSession.Exchange.(types.ExchangeTradeHistoryService), s.HedgeSymbol, startTime); err != nil {
|
2024-03-05 10:12:30 +00:00
|
|
|
log.WithError(err).Errorf("query trades error")
|
|
|
|
}
|
2023-11-27 09:45:12 +00:00
|
|
|
|
2024-03-05 10:12:30 +00:00
|
|
|
if err := s.MakerOrderExecutor.TradeCollector().Recover(ctx, s.makerSession.Exchange.(types.ExchangeTradeHistoryService), s.Symbol, startTime); err != nil {
|
|
|
|
log.WithError(err).Errorf("query trades error")
|
2023-11-27 09:45:12 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-11 08:56:19 +00:00
|
|
|
func (s *Strategy) generateMakerOrders(
|
2024-08-07 08:01:56 +00:00
|
|
|
pricingBook *types.StreamOrderBook,
|
|
|
|
maxLayer int,
|
|
|
|
availableBase, availableQuote fixedpoint.Value,
|
2023-12-11 08:56:19 +00:00
|
|
|
) ([]types.SubmitOrder, error) {
|
|
|
|
_, _, hasPrice := pricingBook.BestBidAndAsk()
|
2023-11-30 02:32:03 +00:00
|
|
|
if !hasPrice {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
var submitOrders []types.SubmitOrder
|
|
|
|
var accumulatedBidQuantity = fixedpoint.Zero
|
|
|
|
var accumulatedAskQuantity = fixedpoint.Zero
|
|
|
|
var accumulatedBidQuoteQuantity = fixedpoint.Zero
|
|
|
|
|
2023-12-11 09:59:16 +00:00
|
|
|
// copy the pricing book because during the generation the book data could change
|
|
|
|
dupPricingBook := pricingBook.Copy()
|
|
|
|
|
2023-12-12 08:37:43 +00:00
|
|
|
log.Infof("pricingBook: \n\tbids: %+v \n\tasks: %+v",
|
2023-12-11 09:59:16 +00:00
|
|
|
dupPricingBook.SideBook(types.SideTypeBuy),
|
|
|
|
dupPricingBook.SideBook(types.SideTypeSell))
|
|
|
|
|
2023-11-30 09:10:09 +00:00
|
|
|
if maxLayer == 0 || maxLayer > s.NumLayers {
|
|
|
|
maxLayer = s.NumLayers
|
|
|
|
}
|
|
|
|
|
2023-12-11 08:56:19 +00:00
|
|
|
var availableBalances = map[types.SideType]fixedpoint.Value{
|
|
|
|
types.SideTypeBuy: availableQuote,
|
|
|
|
types.SideTypeSell: availableBase,
|
|
|
|
}
|
|
|
|
|
2023-11-30 02:32:03 +00:00
|
|
|
for _, side := range []types.SideType{types.SideTypeBuy, types.SideTypeSell} {
|
2023-12-11 08:56:19 +00:00
|
|
|
sideBook := dupPricingBook.SideBook(side)
|
|
|
|
if sideBook.Len() == 0 {
|
|
|
|
log.Warnf("orderbook %s side is empty", side)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
availableSideBalance, ok := availableBalances[side]
|
|
|
|
if !ok {
|
|
|
|
log.Warnf("no available balance for side %s side", side)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2024-09-25 07:52:52 +00:00
|
|
|
accumulatedDepth := fixedpoint.Zero
|
|
|
|
lastMakerPrice := fixedpoint.Zero
|
|
|
|
|
2023-12-11 08:56:19 +00:00
|
|
|
layerLoop:
|
2023-11-30 09:10:09 +00:00
|
|
|
for i := 1; i <= maxLayer; i++ {
|
2023-12-11 08:56:19 +00:00
|
|
|
// simple break, we need to check the market minNotional and minQuantity later
|
|
|
|
if !availableSideBalance.Eq(fixedpoint.PosInf) {
|
|
|
|
if availableSideBalance.IsZero() || availableSideBalance.Sign() < 0 {
|
|
|
|
break layerLoop
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-11-30 02:32:03 +00:00
|
|
|
requiredDepthFloat, err := s.DepthScale.Scale(i)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrapf(err, "depthScale scale error")
|
|
|
|
}
|
|
|
|
|
|
|
|
// requiredDepth is the required depth in quote currency
|
|
|
|
requiredDepth := fixedpoint.NewFromFloat(requiredDepthFloat)
|
2024-09-25 07:52:52 +00:00
|
|
|
accumulatedDepth = accumulatedDepth.Add(requiredDepth)
|
2023-11-30 02:32:03 +00:00
|
|
|
|
2024-09-25 07:52:52 +00:00
|
|
|
index := sideBook.IndexByQuoteVolumeDepth(accumulatedDepth)
|
2023-11-30 02:32:03 +00:00
|
|
|
|
|
|
|
pvs := types.PriceVolumeSlice{}
|
|
|
|
if index == -1 {
|
|
|
|
pvs = sideBook[:]
|
|
|
|
} else {
|
|
|
|
pvs = sideBook[0 : index+1]
|
|
|
|
}
|
|
|
|
|
2023-12-11 08:56:19 +00:00
|
|
|
if len(pvs) == 0 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2024-09-25 07:52:52 +00:00
|
|
|
depthPrice := pvs.AverageDepthPriceByQuote(accumulatedDepth, 0)
|
2023-11-30 02:32:03 +00:00
|
|
|
|
|
|
|
switch side {
|
|
|
|
case types.SideTypeBuy:
|
|
|
|
if s.BidMargin.Sign() > 0 {
|
|
|
|
depthPrice = depthPrice.Mul(fixedpoint.One.Sub(s.BidMargin))
|
|
|
|
}
|
|
|
|
|
|
|
|
depthPrice = depthPrice.Round(s.makerMarket.PricePrecision+1, fixedpoint.Down)
|
|
|
|
|
|
|
|
case types.SideTypeSell:
|
|
|
|
if s.AskMargin.Sign() > 0 {
|
|
|
|
depthPrice = depthPrice.Mul(fixedpoint.One.Add(s.AskMargin))
|
|
|
|
}
|
|
|
|
|
|
|
|
depthPrice = depthPrice.Round(s.makerMarket.PricePrecision+1, fixedpoint.Up)
|
|
|
|
}
|
|
|
|
|
|
|
|
depthPrice = s.makerMarket.TruncatePrice(depthPrice)
|
|
|
|
|
2024-09-25 07:52:52 +00:00
|
|
|
if lastMakerPrice.Sign() > 0 && depthPrice.Compare(lastMakerPrice) == 0 {
|
|
|
|
switch side {
|
|
|
|
case types.SideTypeBuy:
|
|
|
|
depthPrice = depthPrice.Sub(s.makerMarket.TickSize)
|
|
|
|
case types.SideTypeSell:
|
|
|
|
depthPrice = depthPrice.Add(s.makerMarket.TickSize)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-11-30 02:32:03 +00:00
|
|
|
quantity := requiredDepth.Div(depthPrice)
|
|
|
|
quantity = s.makerMarket.TruncateQuantity(quantity)
|
2024-09-25 07:52:52 +00:00
|
|
|
|
|
|
|
s.logger.Infof("%d) %s required depth: %f %s@%s", i, side, accumulatedDepth.Float64(), quantity.String(), depthPrice.String())
|
2023-11-30 02:32:03 +00:00
|
|
|
|
|
|
|
switch side {
|
|
|
|
case types.SideTypeBuy:
|
|
|
|
quantity = quantity.Sub(accumulatedBidQuantity)
|
|
|
|
|
|
|
|
accumulatedBidQuantity = accumulatedBidQuantity.Add(quantity)
|
|
|
|
quoteQuantity := fixedpoint.Mul(quantity, depthPrice)
|
|
|
|
quoteQuantity = quoteQuantity.Round(s.makerMarket.PricePrecision, fixedpoint.Up)
|
2023-12-11 08:56:19 +00:00
|
|
|
|
|
|
|
if !availableSideBalance.Eq(fixedpoint.PosInf) && availableSideBalance.Compare(quoteQuantity) <= 0 {
|
|
|
|
quoteQuantity = availableSideBalance
|
|
|
|
quantity = quoteQuantity.Div(depthPrice).Round(s.makerMarket.PricePrecision, fixedpoint.Down)
|
|
|
|
}
|
|
|
|
|
|
|
|
if quantity.Compare(s.makerMarket.MinQuantity) <= 0 || quoteQuantity.Compare(s.makerMarket.MinNotional) <= 0 {
|
|
|
|
break layerLoop
|
|
|
|
}
|
|
|
|
|
|
|
|
availableSideBalance = availableSideBalance.Sub(quoteQuantity)
|
|
|
|
|
2023-11-30 02:32:03 +00:00
|
|
|
accumulatedBidQuoteQuantity = accumulatedBidQuoteQuantity.Add(quoteQuantity)
|
|
|
|
|
|
|
|
case types.SideTypeSell:
|
|
|
|
quantity = quantity.Sub(accumulatedAskQuantity)
|
2023-12-11 08:56:19 +00:00
|
|
|
quoteQuantity := quantity.Mul(depthPrice)
|
|
|
|
|
|
|
|
// balance check
|
|
|
|
if !availableSideBalance.Eq(fixedpoint.PosInf) && availableSideBalance.Compare(quantity) <= 0 {
|
|
|
|
break layerLoop
|
|
|
|
}
|
|
|
|
|
|
|
|
if quantity.Compare(s.makerMarket.MinQuantity) <= 0 || quoteQuantity.Compare(s.makerMarket.MinNotional) <= 0 {
|
|
|
|
break layerLoop
|
|
|
|
}
|
|
|
|
|
|
|
|
availableSideBalance = availableSideBalance.Sub(quantity)
|
2023-11-30 02:32:03 +00:00
|
|
|
|
2023-12-11 08:56:19 +00:00
|
|
|
accumulatedAskQuantity = accumulatedAskQuantity.Add(quantity)
|
2023-11-30 02:32:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
submitOrders = append(submitOrders, types.SubmitOrder{
|
2024-08-07 08:01:56 +00:00
|
|
|
Symbol: s.makerMarket.Symbol,
|
2023-11-30 02:32:03 +00:00
|
|
|
Type: types.OrderTypeLimitMaker,
|
|
|
|
Market: s.makerMarket,
|
|
|
|
Side: side,
|
|
|
|
Price: depthPrice,
|
|
|
|
Quantity: quantity,
|
|
|
|
})
|
2024-09-25 07:52:52 +00:00
|
|
|
|
|
|
|
lastMakerPrice = depthPrice
|
2023-11-30 02:32:03 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return submitOrders, nil
|
|
|
|
}
|
|
|
|
|
2023-11-30 09:10:09 +00:00
|
|
|
func (s *Strategy) partiallyCancelOrders(ctx context.Context, maxLayer int) error {
|
|
|
|
buyOrders, sellOrders := s.MakerOrderExecutor.ActiveMakerOrders().Orders().SeparateBySide()
|
|
|
|
buyOrders = types.SortOrdersByPrice(buyOrders, true)
|
|
|
|
sellOrders = types.SortOrdersByPrice(sellOrders, false)
|
|
|
|
|
|
|
|
buyOrdersToCancel := buyOrders[0:min(maxLayer, len(buyOrders))]
|
|
|
|
sellOrdersToCancel := sellOrders[0:min(maxLayer, len(sellOrders))]
|
|
|
|
|
|
|
|
err1 := s.MakerOrderExecutor.GracefulCancel(ctx, buyOrdersToCancel...)
|
|
|
|
err2 := s.MakerOrderExecutor.GracefulCancel(ctx, sellOrdersToCancel...)
|
|
|
|
return stderrors.Join(err1, err2)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Strategy) updateQuote(ctx context.Context, maxLayer int) {
|
|
|
|
if maxLayer == 0 {
|
|
|
|
if err := s.MakerOrderExecutor.GracefulCancel(ctx); err != nil {
|
|
|
|
log.WithError(err).Warnf("there are some %s orders not canceled, skipping placing maker orders", s.Symbol)
|
|
|
|
s.MakerOrderExecutor.ActiveMakerOrders().Print()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if err := s.partiallyCancelOrders(ctx, maxLayer); err != nil {
|
|
|
|
log.WithError(err).Warnf("%s partial order cancel failed", s.Symbol)
|
|
|
|
return
|
|
|
|
}
|
2023-11-27 09:45:12 +00:00
|
|
|
}
|
|
|
|
|
2023-11-29 01:39:03 +00:00
|
|
|
numOfMakerOrders := s.MakerOrderExecutor.ActiveMakerOrders().NumOfOrders()
|
|
|
|
if numOfMakerOrders > 0 {
|
|
|
|
log.Warnf("maker orders are not all canceled")
|
2023-11-27 09:45:12 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-09-27 10:29:44 +00:00
|
|
|
// if it's disconnected or context is canceled, then return
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return
|
|
|
|
case <-s.makerConnectivity.DisconnectedC():
|
|
|
|
return
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
|
2024-09-24 08:12:17 +00:00
|
|
|
bestBid, bestAsk, hasPrice := s.sourceBook.BestBidAndAsk()
|
2023-11-27 09:45:12 +00:00
|
|
|
if !hasPrice {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-11-30 05:55:46 +00:00
|
|
|
bestBidPrice := bestBid.Price
|
|
|
|
bestAskPrice := bestAsk.Price
|
2024-08-07 08:01:56 +00:00
|
|
|
log.Infof("%s book ticker: best ask / best bid = %v / %v", s.HedgeSymbol, bestAskPrice, bestBidPrice)
|
2023-11-30 05:55:46 +00:00
|
|
|
|
2024-09-24 08:14:03 +00:00
|
|
|
s.lastSourcePrice.Set(bestBidPrice.Add(bestAskPrice).Div(Two))
|
2023-11-27 09:45:12 +00:00
|
|
|
|
2024-09-24 08:12:17 +00:00
|
|
|
bookLastUpdateTime := s.sourceBook.LastUpdateTime()
|
2023-11-27 09:45:12 +00:00
|
|
|
|
2023-11-30 05:44:35 +00:00
|
|
|
if _, err := s.bidPriceHeartBeat.Update(bestBid); err != nil {
|
2023-12-11 09:05:07 +00:00
|
|
|
log.WithError(err).Warnf("quote update error, %s price not updating, order book last update: %s ago",
|
2023-11-27 09:45:12 +00:00
|
|
|
s.Symbol,
|
|
|
|
time.Since(bookLastUpdateTime))
|
|
|
|
}
|
|
|
|
|
2023-11-30 05:44:35 +00:00
|
|
|
if _, err := s.askPriceHeartBeat.Update(bestAsk); err != nil {
|
2023-12-11 09:05:07 +00:00
|
|
|
log.WithError(err).Warnf("quote update error, %s price not updating, order book last update: %s ago",
|
2023-11-27 09:45:12 +00:00
|
|
|
s.Symbol,
|
|
|
|
time.Since(bookLastUpdateTime))
|
|
|
|
}
|
|
|
|
|
2023-12-11 08:56:19 +00:00
|
|
|
balances, err := s.MakerOrderExecutor.Session().Exchange.QueryAccountBalances(ctx)
|
|
|
|
if err != nil {
|
2024-09-25 07:52:52 +00:00
|
|
|
s.logger.WithError(err).Errorf("balance query error")
|
2023-12-11 08:56:19 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Infof("balances: %+v", balances.NotZero())
|
|
|
|
|
|
|
|
quoteBalance, ok := balances[s.makerMarket.QuoteCurrency]
|
|
|
|
if !ok {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
baseBalance, ok := balances[s.makerMarket.BaseCurrency]
|
|
|
|
if !ok {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-09-25 07:52:52 +00:00
|
|
|
s.logger.Infof("quote balance: %s, base balance: %s", quoteBalance, baseBalance)
|
2023-12-11 08:56:19 +00:00
|
|
|
|
2024-09-24 08:12:17 +00:00
|
|
|
submitOrders, err := s.generateMakerOrders(s.sourceBook, maxLayer, baseBalance.Available, quoteBalance.Available)
|
2023-11-30 05:55:46 +00:00
|
|
|
if err != nil {
|
2024-09-25 07:52:52 +00:00
|
|
|
s.logger.WithError(err).Errorf("generate order error")
|
2023-11-27 09:45:12 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(submitOrders) == 0 {
|
2024-09-25 07:52:52 +00:00
|
|
|
s.logger.Warnf("no orders are generated")
|
2023-11-27 09:45:12 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-12-20 13:54:32 +00:00
|
|
|
_, err = s.MakerOrderExecutor.SubmitOrders(ctx, submitOrders...)
|
2023-11-27 09:45:12 +00:00
|
|
|
if err != nil {
|
2024-09-27 10:29:44 +00:00
|
|
|
s.logger.WithError(err).Errorf("submit order error: %s", err.Error())
|
2023-11-27 09:45:12 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
2023-11-28 07:54:06 +00:00
|
|
|
|
2023-12-20 13:54:32 +00:00
|
|
|
func (s *Strategy) cleanUpOpenOrders(ctx context.Context, session *bbgo.ExchangeSession) error {
|
|
|
|
openOrders, err := retry.QueryOpenOrdersUntilSuccessful(ctx, session.Exchange, s.Symbol)
|
2023-12-11 08:56:19 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2023-12-13 08:29:07 +00:00
|
|
|
if len(openOrders) == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-09-27 10:29:44 +00:00
|
|
|
return tradingutil.UniversalCancelAllOrders(ctx, session.Exchange, s.Symbol, openOrders)
|
2023-12-11 08:56:19 +00:00
|
|
|
}
|
|
|
|
|
2023-11-28 07:54:06 +00:00
|
|
|
func selectSessions2(
|
|
|
|
sessions map[string]*bbgo.ExchangeSession, n1, n2 string,
|
|
|
|
) (s1, s2 *bbgo.ExchangeSession, err error) {
|
|
|
|
for _, n := range []string{n1, n2} {
|
|
|
|
if _, ok := sessions[n]; !ok {
|
|
|
|
return nil, nil, fmt.Errorf("session %s is not defined", n)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
s1 = sessions[n1]
|
|
|
|
s2 = sessions[n2]
|
|
|
|
return s1, s2, nil
|
|
|
|
}
|
2023-11-30 02:32:03 +00:00
|
|
|
|
2023-11-30 09:10:09 +00:00
|
|
|
func min(a, b int) int {
|
|
|
|
if a < b {
|
|
|
|
return a
|
|
|
|
}
|
|
|
|
|
|
|
|
return b
|
|
|
|
}
|