Documentation
¶
Index ¶
- Constants
- func AdjustHedgeQuantityWithAvailableBalance(account *types.Account, market types.Market, side types.SideType, ...) fixedpoint.Value
- func DirectionDivergence(signals []float64, weights []float64, tau float64, epsM float64) (m, pSign, D2 float64)
- type BaseHedgeExecutorConfig
- type BestPriceHedge
- type CounterpartyHedgeExecutor
- type CounterpartyHedgeExecutorConfig
- type DebtQuotaResult
- type DebtQuotaWorker
- type DelayedHedge
- type FastCancel
- type FeeMode
- type HedgeExecutor
- type HedgeMarket
- func (m *HedgeMarket) GetBaseQuoteAvailableBalances() (baseAvailable, quoteAvailable fixedpoint.Value)
- func (m *HedgeMarket) GetQuotePrice() (bid, ask fixedpoint.Value)
- func (m *HedgeMarket) GetQuotePriceByBaseAmount(baseAmount fixedpoint.Value) (bid, ask fixedpoint.Value)
- func (m *HedgeMarket) GetQuotePriceByQuoteAmount(quoteAmount fixedpoint.Value) (bid, ask fixedpoint.Value)
- func (m *HedgeMarket) GetQuotePriceBySessionBalances() (bid, ask fixedpoint.Value)
- func (m *HedgeMarket) InstanceID() string
- func (m *HedgeMarket) OnRedispatchPosition(f func(position fixedpoint.Value))
- func (m *HedgeMarket) RedispatchCoveredPosition(coveredPosition fixedpoint.Value) error
- func (m *HedgeMarket) RedispatchUncoveredPosition(uncoveredPosition fixedpoint.Value) error
- func (m *HedgeMarket) Restore(ctx context.Context, namespace string) error
- func (m *HedgeMarket) SetLogger(logger logrus.FieldLogger)
- func (m *HedgeMarket) SetPriceFeeMode(mode FeeMode)
- func (m *HedgeMarket) Start(ctx context.Context) error
- func (m *HedgeMarket) Stop(shutdownCtx context.Context)
- func (m *HedgeMarket) Sync(ctx context.Context, namespace string)
- func (m *HedgeMarket) WaitForReady(ctx context.Context)
- type HedgeMarketConfig
- type HedgeMethod
- type MarketOrderHedgeExecutor
- type MarketOrderHedgeExecutorConfig
- type MutexFloat64
- type PositionExposure
- func (m *PositionExposure) Close(delta fixedpoint.Value)
- func (m *PositionExposure) Cover(delta fixedpoint.Value)
- func (m *PositionExposure) EmitClose(d fixedpoint.Value)
- func (m *PositionExposure) EmitCover(d fixedpoint.Value)
- func (m *PositionExposure) EmitOpen(d fixedpoint.Value)
- func (m *PositionExposure) GetUncovered() fixedpoint.Value
- func (m *PositionExposure) IsClosed() bool
- func (m *PositionExposure) OnClose(cb func(d fixedpoint.Value))
- func (m *PositionExposure) OnCover(cb func(d fixedpoint.Value))
- func (m *PositionExposure) OnOpen(cb func(d fixedpoint.Value))
- func (m *PositionExposure) Open(delta fixedpoint.Value)
- func (m *PositionExposure) SetLogger(logger logrus.FieldLogger)
- func (m *PositionExposure) SetMetricsLabels(strategyType, strategyID, exchange, symbol string)
- func (m *PositionExposure) String() string
- func (m *PositionExposure) Uncover(delta fixedpoint.Value)
- type ProfitStats
- type Quote
- type RatioBase
- type SessionBinder
- type SignalMargin
- type SplitHedge
- func (h *SplitHedge) GetBalanceWeightedQuotePrice() (bid, ask fixedpoint.Value, ret bool)
- func (h *SplitHedge) Hedge(ctx context.Context, uncoveredPosition, hedgeDelta fixedpoint.Value) error
- func (h *SplitHedge) InitializeAndBind(sessions map[string]*bbgo.ExchangeSession, strategy *Strategy) error
- func (h *SplitHedge) Start(ctx context.Context) error
- func (h *SplitHedge) Stop(shutdownCtx context.Context) error
- func (h *SplitHedge) UnmarshalJSON(data []byte) error
- type SplitHedgeAlgo
- type SplitHedgeProportionAlgo
- type SplitHedgeProportionMarket
- type SpreadMaker
- type State
- type Strategy
- func (s *Strategy) AggregateSignal(ctx context.Context) (float64, error)
- func (s *Strategy) CrossRun(ctx context.Context, _ bbgo.OrderExecutionRouter, ...) error
- func (s *Strategy) CrossSubscribe(sessions map[string]*bbgo.ExchangeSession)
- func (s *Strategy) Defaults() error
- func (s *Strategy) ID() string
- func (s *Strategy) Initialize() error
- func (s *Strategy) InstanceID() string
- func (s *Strategy) PrintConfig(f io.Writer, pretty bool, withColor ...bool)
- func (s *Strategy) Validate() error
- type SyntheticHedge
- func (s *SyntheticHedge) GetQuotePrices() (fixedpoint.Value, fixedpoint.Value, bool)
- func (s *SyntheticHedge) Hedge(_ context.Context, uncoveredPosition, hedgeDelta fixedpoint.Value) error
- func (s *SyntheticHedge) InitializeAndBind(sessions map[string]*bbgo.ExchangeSession, strategy *Strategy) error
- func (s *SyntheticHedge) Start(ctx context.Context) error
- func (s *SyntheticHedge) Stop(shutdownCtx context.Context) error
Constants ¶
const ID = "xmaker"
const TradeTagMock = "mock"
Variables ¶
This section is empty.
Functions ¶
func AdjustHedgeQuantityWithAvailableBalance ¶ added in v1.61.0
func AdjustHedgeQuantityWithAvailableBalance( account *types.Account, market types.Market, side types.SideType, quantity, lastPrice fixedpoint.Value, ) fixedpoint.Value
func DirectionDivergence ¶ added in v1.64.0
func DirectionDivergence(signals []float64, weights []float64, tau float64, epsM float64) (m, pSign, D2 float64)
DirectionDivergence computes (m, pSign, D2) given signals and weights. m : weighted mean of signals pSign : total normalized weight aligned with mean direction and |s_i| >= tau D2 : 1 - pSign
Types ¶
type BaseHedgeExecutorConfig ¶ added in v1.63.0
type BaseHedgeExecutorConfig struct {
}
type BestPriceHedge ¶ added in v1.64.0
type BestPriceHedge struct {
Enabled bool `json:"enabled"`
BelowAmount fixedpoint.Value `json:"belowAmount"`
}
type CounterpartyHedgeExecutor ¶ added in v1.63.0
type CounterpartyHedgeExecutor struct {
HedgeExecutor
*HedgeMarket
// contains filtered or unexported fields
}
func (*CounterpartyHedgeExecutor) Clear ¶ added in v1.64.0
func (m *CounterpartyHedgeExecutor) Clear(ctx context.Context) error
func (*CounterpartyHedgeExecutor) Hedge ¶ added in v1.64.0
func (m *CounterpartyHedgeExecutor) Hedge( ctx context.Context, uncoveredPosition, hedgeDelta, quantity fixedpoint.Value, side types.SideType, ) error
type CounterpartyHedgeExecutorConfig ¶ added in v1.63.0
type CounterpartyHedgeExecutorConfig struct {
BaseHedgeExecutorConfig
PriceLevel int `json:"priceLevel"`
}
type DebtQuotaResult ¶ added in v1.64.0
type DebtQuotaResult struct {
AmountInQuote fixedpoint.Value
DebtValue fixedpoint.Value
NetValueInUsd fixedpoint.Value
TotalValueInUsd fixedpoint.Value
MarginLevel fixedpoint.Value
}
type DebtQuotaWorker ¶ added in v1.64.0
type DebtQuotaWorker struct {
// contains filtered or unexported fields
}
func (*DebtQuotaWorker) Run ¶ added in v1.64.0
func (w *DebtQuotaWorker) Run(ctx context.Context, sesWorker *sessionworker.Handle)
type DelayedHedge ¶ added in v1.61.0
type DelayedHedge struct {
// EnableDelayHedge enables the delay hedge feature
Enabled bool `json:"enabled"`
// MaxDelayDuration is the maximum delay duration to hedge the position
MaxDelayDuration types.Duration `json:"maxDelay"`
// FixedDelayDuration is the fixed delay duration
FixedDelayDuration types.Duration `json:"fixedDelay"`
// SignalThreshold is the signal threshold to trigger the delay hedge
SignalThreshold float64 `json:"signalThreshold"`
// DynamicDelayScale is the dynamic delay scale
DynamicDelayScale *bbgo.SlideRule `json:"dynamicDelayScale,omitempty"`
}
type FastCancel ¶ added in v1.64.0
type FastCancel struct {
Enabled bool `json:"enabled"`
SourceSession string `json:"session"`
// Symbol is the source symbol
Symbol string `json:"symbol"`
TriggerSpread fixedpoint.Value `json:"triggerSpread"`
MarketTradeC chan types.Trade
// contains filtered or unexported fields
}
func (*FastCancel) InitializeAndBind ¶ added in v1.64.0
func (c *FastCancel) InitializeAndBind(sessions map[string]*bbgo.ExchangeSession, strategy *Strategy) error
func (*FastCancel) Validate ¶ added in v1.64.0
func (c *FastCancel) Validate() error
type FeeMode ¶ added in v1.64.0
type FeeMode string
FeeMode controls which fee rate is applied when computing hedge quote prices. - taker: use session.TakerFeeRate (default, crossing the spread) - maker: use session.MakerFeeRate (posting liquidity) - none: do not apply any fee to the computed prices Note: This affects only pricing used by HedgeMarket when evaluating hedge decisions.
type HedgeExecutor ¶ added in v1.63.0
type HedgeExecutor interface {
// Hedge executes a hedge order based on the uncovered position and the hedge delta
// uncoveredPosition: the current uncovered position that needs to be hedged
// hedgeDelta: the delta that needs to be hedged, which is the negative of uncoveredPosition
// quantity: the absolute value of hedgeDelta, which is the order quantity to be hedged
// side: the side of the hedge order, which is determined by the sign of hedgeDelta
Hedge(
ctx context.Context,
uncoveredPosition, hedgeDelta, quantity fixedpoint.Value,
side types.SideType,
) error
// Clear clears any pending orders or state related to hedging
Clear(ctx context.Context) error
}
type HedgeMarket ¶ added in v1.63.0
type HedgeMarket struct {
*HedgeMarketConfig
Position *types.Position
// contains filtered or unexported fields
}
HedgeMarket represents a market used for hedging the main strategy's position. It manages the connectivity, order book, position exposure, and executes hedge orders When the main strategy's position changes, it updates the position exposure and triggers the hedge logic to maintain a neutral position.
func InitializeHedgeMarketFromConfig ¶ added in v1.64.0
func InitializeHedgeMarketFromConfig( c *HedgeMarketConfig, sessions map[string]*bbgo.ExchangeSession, ) (*HedgeMarket, error)
func NewHedgeMarket ¶ added in v1.64.0
func NewHedgeMarket( config *HedgeMarketConfig, session *bbgo.ExchangeSession, market types.Market, ) *HedgeMarket
func (*HedgeMarket) GetBaseQuoteAvailableBalances ¶ added in v1.64.0
func (m *HedgeMarket) GetBaseQuoteAvailableBalances() (baseAvailable, quoteAvailable fixedpoint.Value)
GetBaseQuoteAvailableBalances returns the available balances of base and quote currencies for the current market's session account in one call. If a balance does not exist in the account, this method returns fixedpoint.Zero for it.
func (*HedgeMarket) GetQuotePrice ¶ added in v1.64.0
func (m *HedgeMarket) GetQuotePrice() (bid, ask fixedpoint.Value)
GetQuotePrice returns the current bid and ask prices for hedging, adjusted by the configured fee mode and quoting depth.
Implementation detail: - If QuotingDepthInQuote is configured, delegate to GetQuotePriceByQuoteAmount. - Else if QuotingDepth is configured, delegate to GetQuotePriceByBaseAmount. - Else, fall back to best bid/ask with fee application.
func (*HedgeMarket) GetQuotePriceByBaseAmount ¶ added in v1.64.0
func (m *HedgeMarket) GetQuotePriceByBaseAmount(baseAmount fixedpoint.Value) (bid, ask fixedpoint.Value)
GetQuotePriceByBaseAmount returns bid/ask prices averaged over the given base amount, adjusted by taker fee (ask: +fee, bid: -fee).
func (*HedgeMarket) GetQuotePriceByQuoteAmount ¶ added in v1.64.0
func (m *HedgeMarket) GetQuotePriceByQuoteAmount(quoteAmount fixedpoint.Value) (bid, ask fixedpoint.Value)
GetQuotePriceByQuoteAmount returns bid/ask prices averaged over the given quote amount, adjusted by taker fee (ask: +fee, bid: -fee). This reflects the effective prices when submitting taker orders crossing the spread.
func (*HedgeMarket) GetQuotePriceBySessionBalances ¶ added in v1.64.0
func (m *HedgeMarket) GetQuotePriceBySessionBalances() (bid, ask fixedpoint.Value)
GetQuotePriceBySessionBalances computes bid/ask quote prices based on the current session's available balances as the depth inputs:
- bid side uses base currency available balance as base depth
- ask side uses quote currency available balance as quote depth
Prices are then adjusted by the configured fee mode and stored into m.quotingPrice as a snapshot.
func (*HedgeMarket) InstanceID ¶ added in v1.63.0
func (m *HedgeMarket) InstanceID() string
func (*HedgeMarket) OnRedispatchPosition ¶ added in v1.64.0
func (m *HedgeMarket) OnRedispatchPosition(f func(position fixedpoint.Value))
func (*HedgeMarket) RedispatchCoveredPosition ¶ added in v1.64.0
func (m *HedgeMarket) RedispatchCoveredPosition(coveredPosition fixedpoint.Value) error
func (*HedgeMarket) RedispatchUncoveredPosition ¶ added in v1.64.0
func (m *HedgeMarket) RedispatchUncoveredPosition(uncoveredPosition fixedpoint.Value) error
RedispatchUncoveredPosition redispatches the uncovered position to the parent SplitHedge
func (*HedgeMarket) Restore ¶ added in v1.63.0
func (m *HedgeMarket) Restore(ctx context.Context, namespace string) error
Restore loads the position from persistence and restores it to the HedgeMarket.
func (*HedgeMarket) SetLogger ¶ added in v1.64.0
func (m *HedgeMarket) SetLogger(logger logrus.FieldLogger)
func (*HedgeMarket) SetPriceFeeMode ¶ added in v1.64.0
func (m *HedgeMarket) SetPriceFeeMode(mode FeeMode)
SetPriceFeeMode sets the fee mode used when computing hedge quote prices. This method is safe to call at runtime.
func (*HedgeMarket) Stop ¶ added in v1.63.0
func (m *HedgeMarket) Stop(shutdownCtx context.Context)
func (*HedgeMarket) Sync ¶ added in v1.63.0
func (m *HedgeMarket) Sync(ctx context.Context, namespace string)
func (*HedgeMarket) WaitForReady ¶ added in v1.63.0
func (m *HedgeMarket) WaitForReady(ctx context.Context)
type HedgeMarketConfig ¶ added in v1.63.0
type HedgeMarketConfig struct {
SymbolSelector string `json:"symbolSelector"`
HedgeMethod HedgeMethod `json:"hedgeMethod"`
HedgeInterval types.Duration `json:"hedgeInterval"`
MinMarginLevel fixedpoint.Value `json:"minMarginLevel"`
MaxLeverage fixedpoint.Value `json:"maxLeverage"`
HedgeMethodMarket *MarketOrderHedgeExecutorConfig `json:"hedgeMethodMarket,omitempty"` // for backward compatibility, this is the default hedge method
HedgeMethodCounterparty *CounterpartyHedgeExecutorConfig `json:"hedgeMethodCounterparty,omitempty"` // for backward compatibility, this is the default hedge method
HedgeMethodQueue *struct {
PriceLevel int `json:"priceLevel"`
} `json:"hedgeMethodQueue,omitempty"` // for backward compatibility, this is the default hedge method
QuotingDepth fixedpoint.Value `json:"quotingDepth"`
QuotingDepthInQuote fixedpoint.Value `json:"quotingDepthInQuote"`
}
func (*HedgeMarketConfig) Defaults ¶ added in v1.64.0
func (c *HedgeMarketConfig) Defaults() error
func (*HedgeMarketConfig) ResolveQuotingDepthInBase ¶ added in v1.64.0
func (c *HedgeMarketConfig) ResolveQuotingDepthInBase(latestPrice fixedpoint.Value) fixedpoint.Value
ResolveQuotingDepthInBase returns the quoting depth in base currency. Priority:
- If QuotingDepth (base) is configured (> 0), return it directly.
- Else if QuotingDepthInQuote is configured and latestPrice > 0, convert quote depth to base via quote / latestPrice.
- Otherwise return zero.
func (*HedgeMarketConfig) ResolveQuotingDepthInQuote ¶ added in v1.64.0
func (c *HedgeMarketConfig) ResolveQuotingDepthInQuote(latestPrice fixedpoint.Value) fixedpoint.Value
ResolveQuotingDepthInQuote returns the quoting depth in quote currency. Priority:
- If QuotingDepthInQuote is configured (> 0), return it directly.
- Else if QuotingDepth (base) is configured and latestPrice > 0, convert base depth to quote via base * latestPrice.
- Otherwise return zero.
type HedgeMethod ¶ added in v1.63.0
type HedgeMethod string
const ( // HedgeMethodMarket is the default hedge method that uses the market order to hedge HedgeMethodMarket HedgeMethod = "market" // HedgeMethodCounterparty is a hedge method that uses limit order at the specific counterparty price level to hedge HedgeMethodCounterparty HedgeMethod = "counterparty" // HedgeMethodQueue is a hedge method that uses limit order at the first price level in the queue to hedge HedgeMethodQueue HedgeMethod = "queue" )
type MarketOrderHedgeExecutor ¶ added in v1.63.0
type MarketOrderHedgeExecutor struct {
*HedgeMarket
// contains filtered or unexported fields
}
func NewMarketOrderHedgeExecutor ¶ added in v1.64.0
func NewMarketOrderHedgeExecutor( market *HedgeMarket, config *MarketOrderHedgeExecutorConfig, ) *MarketOrderHedgeExecutor
func (*MarketOrderHedgeExecutor) Clear ¶ added in v1.64.0
func (m *MarketOrderHedgeExecutor) Clear(ctx context.Context) error
func (*MarketOrderHedgeExecutor) Hedge ¶ added in v1.64.0
func (m *MarketOrderHedgeExecutor) Hedge( ctx context.Context, uncoveredPosition, hedgeDelta, quantity fixedpoint.Value, side types.SideType, ) error
type MarketOrderHedgeExecutorConfig ¶ added in v1.63.0
type MarketOrderHedgeExecutorConfig struct {
BaseHedgeExecutorConfig
MaxOrderQuantity fixedpoint.Value `json:"maxOrderQuantity,omitempty"` // max order quantity for market order hedge
}
type MutexFloat64 ¶ added in v1.61.0
type MutexFloat64 struct {
// contains filtered or unexported fields
}
func (*MutexFloat64) Get ¶ added in v1.61.0
func (m *MutexFloat64) Get() float64
func (*MutexFloat64) Set ¶ added in v1.61.0
func (m *MutexFloat64) Set(v float64)
type PositionExposure ¶ added in v1.63.0
type PositionExposure struct {
// contains filtered or unexported fields
}
func NewPositionExposure ¶ added in v1.64.0
func NewPositionExposure(symbol string) *PositionExposure
func (*PositionExposure) Close ¶ added in v1.63.0
func (m *PositionExposure) Close(delta fixedpoint.Value)
func (*PositionExposure) Cover ¶ added in v1.63.0
func (m *PositionExposure) Cover(delta fixedpoint.Value)
func (*PositionExposure) EmitClose ¶ added in v1.63.0
func (m *PositionExposure) EmitClose(d fixedpoint.Value)
func (*PositionExposure) EmitCover ¶ added in v1.63.0
func (m *PositionExposure) EmitCover(d fixedpoint.Value)
func (*PositionExposure) EmitOpen ¶ added in v1.64.0
func (m *PositionExposure) EmitOpen(d fixedpoint.Value)
func (*PositionExposure) GetUncovered ¶ added in v1.63.0
func (m *PositionExposure) GetUncovered() fixedpoint.Value
func (*PositionExposure) IsClosed ¶ added in v1.63.0
func (m *PositionExposure) IsClosed() bool
func (*PositionExposure) OnClose ¶ added in v1.63.0
func (m *PositionExposure) OnClose(cb func(d fixedpoint.Value))
func (*PositionExposure) OnCover ¶ added in v1.63.0
func (m *PositionExposure) OnCover(cb func(d fixedpoint.Value))
func (*PositionExposure) OnOpen ¶ added in v1.64.0
func (m *PositionExposure) OnOpen(cb func(d fixedpoint.Value))
func (*PositionExposure) Open ¶ added in v1.63.0
func (m *PositionExposure) Open(delta fixedpoint.Value)
func (*PositionExposure) SetLogger ¶ added in v1.64.0
func (m *PositionExposure) SetLogger(logger logrus.FieldLogger)
func (*PositionExposure) SetMetricsLabels ¶ added in v1.64.0
func (m *PositionExposure) SetMetricsLabels(strategyType, strategyID, exchange, symbol string)
func (*PositionExposure) String ¶ added in v1.64.0
func (m *PositionExposure) String() string
func (*PositionExposure) Uncover ¶ added in v1.64.0
func (m *PositionExposure) Uncover(delta fixedpoint.Value)
type ProfitStats ¶ added in v1.17.0
type ProfitStats struct {
*types.ProfitStats
MakerExchange types.ExchangeName `json:"makerExchange"`
AccumulatedMakerVolume fixedpoint.Value `json:"accumulatedMakerVolume,omitempty"`
AccumulatedMakerBidVolume fixedpoint.Value `json:"accumulatedMakerBidVolume,omitempty"`
AccumulatedMakerAskVolume fixedpoint.Value `json:"accumulatedMakerAskVolume,omitempty"`
TodayMakerVolume fixedpoint.Value `json:"todayMakerVolume,omitempty"`
TodayMakerBidVolume fixedpoint.Value `json:"todayMakerBidVolume,omitempty"`
TodayMakerAskVolume fixedpoint.Value `json:"todayMakerAskVolume,omitempty"`
// contains filtered or unexported fields
}
func (*ProfitStats) AddTrade ¶ added in v1.17.0
func (s *ProfitStats) AddTrade(trade types.Trade)
func (*ProfitStats) ResetToday ¶ added in v1.17.0
func (s *ProfitStats) ResetToday()
type Quote ¶ added in v1.60.1
type Quote struct {
BestBidPrice, BestAskPrice fixedpoint.Value
BidMargin, AskMargin fixedpoint.Value
// BidLayerPips is the price pips between each layer
BidLayerPips, AskLayerPips fixedpoint.Value
}
Quote stores the source prices and margins for quoting for both bid and ask sides
type SessionBinder ¶ added in v1.60.1
type SignalMargin ¶ added in v1.61.0
type SplitHedge ¶ added in v1.64.0
type SplitHedge struct {
Enabled bool `json:"enabled"`
Algo SplitHedgeAlgo `json:"algo"`
BestPriceHedge *BestPriceHedge `json:"bestPriceHedge"`
ProportionAlgo *SplitHedgeProportionAlgo `json:"proportionAlgo"`
// HedgeMarkets stores session name to hedge market config mapping.
HedgeMarkets map[string]*HedgeMarketConfig `json:"hedgeMarkets"`
// contains filtered or unexported fields
}
func (*SplitHedge) GetBalanceWeightedQuotePrice ¶ added in v1.64.0
func (h *SplitHedge) GetBalanceWeightedQuotePrice() (bid, ask fixedpoint.Value, ret bool)
GetBalanceWeightedQuotePrice returns the balance-weighted bid and ask prices across all hedge markets.
Weighting rules: - Ask side is weighted by base currency available balance of each hedge market session. - Bid side is weighted by quote currency available balance of each hedge market session.
For margin accounts (mkt.session.Margin is true): - The debt quota (borrowing capacity) is included in the weight. - Bid weight = quoteAvail + debtQuota. - Ask weight = baseAvail + (debtQuota / askPrice).
Per-market prices are obtained by calling HedgeMarket.GetQuotePriceBySessionBalances(), which already considers the market's current book and the session balances as depth.
If the total weight for a side is zero (e.g., no base balances for ask weighting), the corresponding returned price will be zero.
func (*SplitHedge) Hedge ¶ added in v1.64.0
func (h *SplitHedge) Hedge( ctx context.Context, uncoveredPosition, hedgeDelta fixedpoint.Value, ) error
func (*SplitHedge) InitializeAndBind ¶ added in v1.64.0
func (h *SplitHedge) InitializeAndBind(sessions map[string]*bbgo.ExchangeSession, strategy *Strategy) error
TODO: see if we can remove this *Strategy dependency, it's a huge effort to refactor it out
func (*SplitHedge) Stop ¶ added in v1.64.0
func (h *SplitHedge) Stop(shutdownCtx context.Context) error
func (*SplitHedge) UnmarshalJSON ¶ added in v1.64.0
func (h *SplitHedge) UnmarshalJSON(data []byte) error
type SplitHedgeAlgo ¶ added in v1.64.0
type SplitHedgeAlgo string
const (
SplitHedgeAlgoProportion SplitHedgeAlgo = "proportion"
)
type SplitHedgeProportionAlgo ¶ added in v1.64.0
type SplitHedgeProportionAlgo struct {
// RatioBase controls how per-market ratio is applied when calculating each slice.
// - "remaining": apply the ratio to the remaining quantity after prior markets.
// - "total" (default): apply the ratio to the original total quantity for every market.
RatioBase RatioBase `json:"ratioBase"`
ProportionMarkets []*SplitHedgeProportionMarket `json:"markets"`
}
type SplitHedgeProportionMarket ¶ added in v1.64.0
type SplitHedgeProportionMarket struct {
Name string `json:"name"`
Ratio fixedpoint.Value `json:"ratio"`
MaxQuantity fixedpoint.Value `json:"maxQuantity"`
MaxQuoteQuantity fixedpoint.Value `json:"maxQuoteQuantity"`
}
func (*SplitHedgeProportionMarket) CalculateQuantity ¶ added in v1.64.0
func (m *SplitHedgeProportionMarket) CalculateQuantity(totalQuantity, price fixedpoint.Value) fixedpoint.Value
CalculateQuantity calculates the order quantity for this market based on total quantity and price. It applies ratio, maxQuantity, and maxQuoteQuantity constraints.
type SpreadMaker ¶ added in v1.62.0
type SpreadMaker struct {
Enabled bool `json:"enabled"`
MinProfitRatio fixedpoint.Value `json:"minProfitRatio"`
MaxQuoteAmount fixedpoint.Value `json:"maxQuoteAmount"`
MaxOrderLifespan types.Duration `json:"maxOrderLifespan"`
SignalThreshold float64 `json:"signalThreshold"`
ReverseSignalOrderCancel bool `json:"reverseSignalOrderCancel"`
MakerOnly bool `json:"makerOnly"`
// contains filtered or unexported fields
}
func (*SpreadMaker) Bind ¶ added in v1.62.0
func (c *SpreadMaker) Bind(ctx context.Context, session *bbgo.ExchangeSession, symbol string) error
func (*SpreadMaker) Defaults ¶ added in v1.62.0
func (c *SpreadMaker) Defaults() error
type State ¶
type State struct {
CoveredPosition fixedpoint.Value `json:"coveredPosition,omitempty"`
// Deprecated:
Position *types.Position `json:"position,omitempty"`
// Deprecated:
ProfitStats ProfitStats `json:"profitStats,omitempty"`
}
type Strategy ¶
type Strategy struct {
common.StrategyProfitFixer
Environment *bbgo.Environment
// Symbol is the maker Symbol
Symbol string `json:"symbol"`
MakerSymbol string `json:"makerSymbol"`
// MakerExchange session name
MakerExchange string `json:"makerExchange"`
MakerSession string `json:"makerSession"`
// SourceSymbol allows subscribing to a different symbol for price/book
SourceSymbol string `json:"sourceSymbol,omitempty"`
// SourceExchange session name
SourceExchange string `json:"sourceExchange"`
HedgeSession string `json:"hedgeSession"`
UpdateInterval types.Duration `json:"updateInterval"`
HedgeInterval types.Duration `json:"hedgeInterval"`
OrderCancelWaitTime types.Duration `json:"orderCancelWaitTime"`
EnableSignalMargin bool `json:"enableSignalMargin"`
// Direction-divergence (D2) control — optional risk widener driven by signal direction conflicts
EnableDirectionDivergence bool `json:"enableDirectionDivergence"`
DivergenceTau float64 `json:"divergenceTau,omitempty"` // magnitude threshold to ignore weak signals (τ)
DivergenceEpsM float64 `json:"divergenceEpsM,omitempty"` // "no-consensus" threshold on |m|
DivergenceMarginK float64 `json:"divergenceMarginK,omitempty"` // k used to widen margins: margin *= (1 + k*D2)
// Divergence-driven size and side controls
DivergenceSizeK float64 `json:"divergenceSizeK,omitempty"` // sizeScale = max(0, 1 - k*D2)
DivergenceDisableThreshold float64 `json:"divergenceDisableThreshold,omitempty"` // if D2 >= threshold, disable reverse side
SignalSource string `json:"signalSource,omitempty"`
SignalConfigList *signal.DynamicConfig `json:"signals"`
SignalReverseSideMargin *SignalMargin `json:"signalReverseSideMargin,omitempty"`
SignalTrendSideMarginDiscount *SignalMargin `json:"signalTrendSideMarginDiscount,omitempty"`
// Margin is the default margin for the quote
Margin fixedpoint.Value `json:"margin"`
BidMargin fixedpoint.Value `json:"bidMargin"`
AskMargin fixedpoint.Value `json:"askMargin"`
// MinMargin is the minimum margin protection for signal margin
MinMargin *fixedpoint.Value `json:"minMargin"`
UseDepthPrice bool `json:"useDepthPrice"`
DepthQuantity fixedpoint.Value `json:"depthQuantity"`
// TODO: move SourceDepthLevel to HedgeMarket
SourceDepthLevel types.Depth `json:"sourceDepthLevel"`
MakerOnly bool `json:"makerOnly"`
// MaxHedgeDelayDuration is the maximum delay duration to hedge the position
MaxDelayHedgeDuration types.Duration `json:"maxHedgeDelayDuration"`
DelayHedgeSignalThreshold float64 `json:"delayHedgeSignalThreshold"`
DelayedHedge *DelayedHedge `json:"delayedHedge,omitempty"`
SplitHedge *SplitHedge `json:"splitHedge,omitempty"`
SpreadMaker *SpreadMaker `json:"spreadMaker,omitempty"`
FastCancel *FastCancel `json:"fastCancel,omitempty"`
EnableBollBandMargin bool `json:"enableBollBandMargin"`
BollBandInterval types.Interval `json:"bollBandInterval"`
BollBandMargin fixedpoint.Value `json:"bollBandMargin"`
BollBandMarginFactor fixedpoint.Value `json:"bollBandMarginFactor"`
// MinMarginLevel is the minimum margin level to trigger the hedge
MinMarginLevel fixedpoint.Value `json:"minMarginLevel"`
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"`
// QuantityMultiplier is the factor that multiplies the quantity of the previous layer
QuantityMultiplier fixedpoint.Value `json:"quantityMultiplier"`
// QuantityScale helps user to define the quantity by layer scale
QuantityScale *bbgo.LayerScale `json:"quantityScale,omitempty"`
// MaxExposurePosition defines the unhedged quantity of stop
MaxExposurePosition fixedpoint.Value `json:"maxExposurePosition"`
MaxHedgeAccountLeverage fixedpoint.Value `json:"maxHedgeAccountLeverage"`
MaxHedgeQuoteQuantityPerOrder fixedpoint.Value `json:"maxHedgeQuoteQuantityPerOrder"`
DisableHedge bool `json:"disableHedge"`
NotifyTrade bool `json:"notifyTrade"`
NotifyIgnoreSmallAmountProfitTrade fixedpoint.Value `json:"notifyIgnoreSmallAmountProfitTrade"`
EnableArbitrage bool `json:"enableArbitrage"`
// RecoverTrade tries to find the missing trades via the REStful API
RecoverTrade bool `json:"recoverTrade"`
RecoverTradeScanPeriod types.Duration `json:"recoverTradeScanPeriod"`
MaxQuoteQuotaRatio fixedpoint.Value `json:"maxQuoteQuotaRatio,omitempty"`
NumLayers int `json:"numLayers"`
// Pips is the pips of the layer prices
Pips fixedpoint.Value `json:"pips"`
UseSandbox bool `json:"useSandbox,omitempty"`
SandboxExchangeBalances map[string]fixedpoint.Value `json:"sandboxExchangeBalances,omitempty"`
SyntheticHedge *SyntheticHedge `json:"syntheticHedge,omitempty"`
AuthTimeout types.Duration `json:"authTimeout,omitempty"`
CircuitBreaker *circuitbreaker.BasicCircuitBreaker `json:"circuitBreaker"`
// persistence fields
Position *types.Position `json:"position,omitempty" persistence:"position"`
ProfitStats *ProfitStats `json:"profitStats,omitempty" persistence:"profit_stats"`
// contains filtered or unexported fields
}
func (*Strategy) AggregateSignal ¶ added in v1.64.0
TODO: move this AggregateSignal to the signal package
func (*Strategy) CrossRun ¶
func (s *Strategy) CrossRun( ctx context.Context, _ bbgo.OrderExecutionRouter, sessions map[string]*bbgo.ExchangeSession, ) error
func (*Strategy) CrossSubscribe ¶
func (s *Strategy) CrossSubscribe(sessions map[string]*bbgo.ExchangeSession)
func (*Strategy) Initialize ¶ added in v1.55.0
func (*Strategy) InstanceID ¶ added in v1.33.0
func (*Strategy) PrintConfig ¶ added in v1.61.0
type SyntheticHedge ¶ added in v1.63.0
type SyntheticHedge struct {
// SyntheticHedge is a strategy that uses synthetic hedging to manage risk
Enabled bool `json:"enabled"`
Source *HedgeMarketConfig `json:"source"`
Fiat *HedgeMarketConfig `json:"fiat"`
// contains filtered or unexported fields
}
SyntheticHedge is a strategy that uses synthetic hedging to manage risk SourceSymbol could be something like binance.BTCUSDT FiatSymbol could be something like max.USDTTWD
func (*SyntheticHedge) GetQuotePrices ¶ added in v1.63.0
func (s *SyntheticHedge) GetQuotePrices() (fixedpoint.Value, fixedpoint.Value, bool)
func (*SyntheticHedge) Hedge ¶ added in v1.63.0
func (s *SyntheticHedge) Hedge( _ context.Context, uncoveredPosition, hedgeDelta fixedpoint.Value, ) error
Hedge is the main function to perform the synthetic hedging: 1) use the snapshot price as the source average cost 2) submit the hedge order to the source makerExchange 3) query trades from of the hedge order. 4) build up the source hedge position for the average cost. 5) submit fiat hedge order to the fiat market to convert the quote. 6) merge the positions.
func (*SyntheticHedge) InitializeAndBind ¶ added in v1.63.0
func (s *SyntheticHedge) InitializeAndBind(sessions map[string]*bbgo.ExchangeSession, strategy *Strategy) error
InitializeAndBind not a good way to initialize the synthetic hedge with the strategy instance but we need to build the trade collector to update the profit and position