Documentation
¶
Overview ¶
Package perpetuals provides perpetual futures trading functionality for the DEX VM. This file implements Auto-Deleveraging (ADL) for when the insurance fund is depleted.
ADL Flow: 1. Liquidation occurs but insurance fund cannot cover the loss 2. ADL engine identifies profitable opposing positions (sorted by PnL ranking) 3. Positions are partially closed against the liquidated position at bankruptcy price 4. Affected users are compensated from remaining insurance fund 5. This prevents socialized losses from affecting all traders
Priority Ranking: - Positions are ranked by profitability (highest profit first) - Only opposing positions (shorts for long liquidation, longs for short liquidation) are eligible - Maximum reduction per position is configurable (default 50%)
Index ¶
- Variables
- func CalculateInitialMargin(notional *big.Int, leverage uint16) *big.Int
- func CalculateLiquidationPriceTiered(side Side, entryPrice *big.Int, notional *big.Int, leverage uint16, ...) *big.Int
- func CalculateMaintenanceMargin(notional *big.Int, mmRate uint16, mmAmount *big.Int) *big.Int
- func CalculateSLPrice(positionSide Side, entryPrice *big.Int, percent uint16) *big.Int
- func CalculateTPPercent(positionSide Side, entryPrice, tpPrice *big.Int) uint16
- func CalculateTPPrice(positionSide Side, entryPrice *big.Int, percent uint16) *big.Int
- func GetVIPTierFees(volume30d *big.Int, vipTiers []*VIPTier) (uint16, uint16)
- func ShouldTriggerSL(positionSide Side, currentPrice, slPrice *big.Int) bool
- func ShouldTriggerTP(positionSide Side, currentPrice, tpPrice *big.Int) bool
- func UpdateTrailingStop(order *TPSLOrder, positionSide Side, currentPrice *big.Int) bool
- func ValidateTPSL(positionSide Side, entryPrice, tpPrice, slPrice *big.Int) error
- type ADLAffectedPosition
- type ADLCandidate
- type ADLConfig
- type ADLEvent
- type ADLStatistics
- type AutoDeleveragingEngine
- func (e *AutoDeleveragingEngine) Execute(symbol string, liquidatedPositionID ids.ID, liquidatedSide bool, ...) (*ADLEvent, error)
- func (e *AutoDeleveragingEngine) GetCandidateCount(symbol string) (longs, shorts int)
- func (e *AutoDeleveragingEngine) GetEvents(limit int) []interface{}
- func (e *AutoDeleveragingEngine) RemoveCandidate(positionID ids.ID, symbol string, side bool)
- func (e *AutoDeleveragingEngine) RemoveCandidateNoLock(positionID ids.ID, symbol string, side bool)
- func (e *AutoDeleveragingEngine) ShouldTriggerADL(currentFund, targetFund *big.Int) bool
- func (e *AutoDeleveragingEngine) Statistics() interface{}
- func (e *AutoDeleveragingEngine) UpdateCandidate(candidate *ADLCandidate)
- type DefaultPriceOracle
- type Engine
- func (e *Engine) AddToInsuranceFund(amount *big.Int)
- func (e *Engine) CheckAndLiquidate(market string) ([]*LiquidationEvent, error)
- func (e *Engine) ClosePosition(traderID ids.ID, market string) (*big.Int, error)
- func (e *Engine) CreateAccount(traderID ids.ID) *MarginAccount
- func (e *Engine) CreateMarket(symbol string, baseAsset, quoteAsset ids.ID, initialPrice *big.Int, ...) (*Market, error)
- func (e *Engine) Deposit(traderID ids.ID, amount *big.Int) error
- func (e *Engine) GetAccount(traderID ids.ID) (interface{}, error)
- func (e *Engine) GetAllMarkets() []interface{}
- func (e *Engine) GetAllPositions(traderID ids.ID) ([]interface{}, error)
- func (e *Engine) GetFundingPayments() []*FundingPayment
- func (e *Engine) GetInsuranceFund() *big.Int
- func (e *Engine) GetLiquidations() []*LiquidationEvent
- func (e *Engine) GetMarginRatio(traderID ids.ID) (*big.Int, error)
- func (e *Engine) GetMarket(symbol string) (interface{}, error)
- func (e *Engine) GetPosition(traderID ids.ID, market string) (interface{}, error)
- func (e *Engine) GetTWAPPrice(market string) (*big.Int, error)
- func (e *Engine) OpenPosition(traderID ids.ID, market string, side Side, size *big.Int, leverage uint16, ...) (*Position, error)
- func (e *Engine) ProcessFunding(market string) ([]*FundingPayment, error)
- func (e *Engine) SetPriceOracle(oracle PriceOracle)
- func (e *Engine) UpdateMarkPrice(symbol string, newPrice *big.Int) error
- func (e *Engine) Withdraw(traderID ids.ID, amount *big.Int) error
- type FundingPayment
- type LeverageTier
- type LiquidationEvent
- type MarginAccount
- type MarginMode
- type Market
- type Order
- type OrderStatus
- type Position
- type PriceOracle
- type RebatePayment
- type Referee
- type ReferralCode
- type ReferralEngine
- func (e *ReferralEngine) ClaimRebates(referrerID ids.ID) (*big.Int, error)
- func (e *ReferralEngine) CreateReferralCode(ownerID ids.ID, code string) (*ReferralCode, error)
- func (e *ReferralEngine) DeactivateCode(code string, ownerID ids.ID) error
- func (e *ReferralEngine) GetFeeDiscount(traderID ids.ID) uint16
- func (e *ReferralEngine) GetReferee(refereeID ids.ID) (*Referee, error)
- func (e *ReferralEngine) GetReferralCode(code string) (*ReferralCode, error)
- func (e *ReferralEngine) GetReferralsByCode(code string) []*Referee
- func (e *ReferralEngine) GetReferrer(referrerID ids.ID) (*Referrer, error)
- func (e *ReferralEngine) GetStats() *ReferralStats
- func (e *ReferralEngine) ProcessTradeRebate(traderID ids.ID, tradeID ids.ID, market string, notionalVolume *big.Int, ...) (*RebatePayment, *big.Int, error)
- func (e *ReferralEngine) SetCustomRebateRate(code string, rate uint16) error
- func (e *ReferralEngine) UseReferralCode(userID ids.ID, code string) error
- type ReferralStats
- type ReferralTier
- type Referrer
- type Side
- type TPSLConfig
- type TPSLManager
- func (m *TPSLManager) CancelOrder(orderID ids.ID) error
- func (m *TPSLManager) CancelOrdersForPosition(positionID ids.ID)
- func (m *TPSLManager) CheckTriggers(market string, markPrice, lastPrice, indexPrice *big.Int, ...) []*TPSLOrder
- func (m *TPSLManager) CreateTPSL(positionID ids.ID, traderID ids.ID, market string, positionSide Side, ...) (*TPSLOrder, error)
- func (m *TPSLManager) CreateTrailingStop(positionID ids.ID, traderID ids.ID, market string, positionSide Side, ...) (*TPSLOrder, error)
- func (m *TPSLManager) GetOrdersForPosition(positionID ids.ID) []*TPSLOrder
- type TPSLOrder
- type TPSLStatus
- type TPSLType
- type TierConfig
- type TimeInForce
- type Trade
- type TriggerType
- type VIPTier
Constants ¶
This section is empty.
Variables ¶
var ( ErrNoADLCandidates = errors.New("no ADL candidates available") ErrADLDisabled = errors.New("ADL is disabled") ErrInsufficientADL = errors.New("insufficient ADL capacity to cover loss") ErrInvalidADLPercentage = errors.New("invalid ADL reduction percentage") )
var ( // Errors ErrMarketNotFound = errors.New("market not found") ErrMarketExists = errors.New("market already exists") ErrPositionNotFound = errors.New("position not found") ErrInsufficientMargin = errors.New("insufficient margin") ErrInsufficientBalance = errors.New("insufficient balance") ErrExceedsMaxLeverage = errors.New("exceeds maximum leverage") ErrOrderSizeTooSmall = errors.New("order size below minimum") ErrInvalidPrice = errors.New("invalid price") ErrReduceOnlyViolation = errors.New("reduce-only order would increase position") ErrPositionWouldLiquidate = errors.New("position would be immediately liquidatable") ErrNoOpenPosition = errors.New("no open position to close") ErrInvalidLeverage = errors.New("invalid leverage") // Constants PrecisionFactor = new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil) // 1e18 for price precision BasisPointDenom = big.NewInt(10000) // 10000 basis points = 100% )
var ( ErrReferralCodeExists = errors.New("referral code already exists") ErrReferralCodeNotFound = errors.New("referral code not found") ErrSelfReferral = errors.New("cannot use own referral code") ErrAlreadyReferred = errors.New("user already has a referrer") ErrInvalidRebateRate = errors.New("invalid rebate rate") ErrReferralNotActive = errors.New("referral program not active") )
var ( ErrInvalidTPSL = errors.New("invalid take profit/stop loss configuration") ErrTPSLAlreadyExists = errors.New("TP/SL order already exists for position") ErrTPSLNotFound = errors.New("TP/SL order not found") ErrTPBelowEntry = errors.New("take profit must be above entry for long, below for short") ErrSLAboveEntry = errors.New("stop loss must be below entry for long, above for short") )
Functions ¶
func CalculateInitialMargin ¶
CalculateInitialMargin calculates the required initial margin for a position Initial Margin = Notional Value / Leverage
func CalculateLiquidationPriceTiered ¶
func CalculateLiquidationPriceTiered( side Side, entryPrice *big.Int, notional *big.Int, leverage uint16, tc *TierConfig, ) *big.Int
CalculateLiquidationPriceTiered calculates liquidation price with tiered margins
func CalculateMaintenanceMargin ¶
CalculateMaintenanceMargin calculates the maintenance margin for a position Maintenance Margin = Notional Value * Maintenance Margin Rate - Maintenance Amount
func CalculateSLPrice ¶
CalculateSLPrice calculates stop loss price from percentage For long: SL = Entry * (1 - percent/10000) For short: SL = Entry * (1 + percent/10000)
func CalculateTPPercent ¶
CalculateTPPercent calculates take profit percentage from target price
func CalculateTPPrice ¶
CalculateTPPrice calculates take profit price from percentage For long: TP = Entry * (1 + percent/10000) For short: TP = Entry * (1 - percent/10000)
func GetVIPTierFees ¶
GetVIPTierFees returns maker/taker fees for a given volume
func ShouldTriggerSL ¶
ShouldTriggerSL checks if stop loss should trigger at current price
func ShouldTriggerTP ¶
ShouldTriggerTP checks if take profit should trigger at current price
func UpdateTrailingStop ¶
UpdateTrailingStop updates trailing stop based on current price
Types ¶
type ADLAffectedPosition ¶ added in v1.22.76
type ADLAffectedPosition struct {
// PositionID is the affected position
PositionID ids.ID
// UserID is the position owner
UserID ids.ShortID
// OriginalSize is the size before ADL
OriginalSize uint64
// ReducedSize is the amount reduced by ADL
ReducedSize uint64
// ReductionPercentage is the percentage of position reduced
ReductionPercentage float64
// ExecutionPrice is the price at which the reduction occurred
ExecutionPrice uint64
// CompensationPaid is the compensation paid to the user
CompensationPaid *big.Int
// PnLRealized is the PnL realized from the reduction
PnLRealized *big.Int
}
ADLAffectedPosition represents a position affected by auto-deleveraging.
type ADLCandidate ¶ added in v1.22.76
type ADLCandidate struct {
// PositionID uniquely identifies the position
PositionID ids.ID
// UserID is the owner of the position
UserID ids.ShortID
// Symbol is the trading pair
Symbol string
// Side is the position side (true = long, false = short)
Side bool
// Size is the current position size
Size uint64
// EntryPrice is the average entry price
EntryPrice uint64
// UnrealizedPnL is the current unrealized profit/loss
UnrealizedPnL *big.Int
// PnLRanking is the profit ranking score (higher = more profitable)
PnLRanking float64
// Leverage is the current leverage
Leverage uint64
// MarginBalance is the current margin balance
MarginBalance *big.Int
}
ADLCandidate represents a position eligible for auto-deleveraging.
type ADLConfig ¶ added in v1.22.76
type ADLConfig struct {
// Enabled controls whether ADL is active
Enabled bool
// Threshold is the insurance fund depletion ratio that triggers ADL
// When insurance fund falls below this percentage of target, ADL activates
// Default: 0.2 (20%)
Threshold float64
// MaxReductionPerPosition is the maximum percentage of any single position
// that can be reduced in a single ADL event
// Default: 0.5 (50%)
MaxReductionPerPosition float64
// MinProfitForADL is the minimum unrealized profit required for a position
// to be eligible for ADL (protects small profitable positions)
// Default: $100
MinProfitForADL *big.Int
// CompensationRate is the percentage of mark price paid as compensation
// Default: 0.001 (0.1%)
CompensationRate float64
}
ADLConfig configures the auto-deleveraging engine.
func DefaultADLConfig ¶ added in v1.22.76
func DefaultADLConfig() ADLConfig
DefaultADLConfig returns the default ADL configuration.
type ADLEvent ¶ added in v1.22.76
type ADLEvent struct {
// EventID uniquely identifies this ADL event
EventID ids.ID
// Timestamp is when the ADL occurred
Timestamp time.Time
// Symbol is the affected trading pair
Symbol string
// LiquidatedPositionID is the position that triggered ADL
LiquidatedPositionID ids.ID
// TriggerReason describes why ADL was triggered
TriggerReason string
// AffectedPositions lists all positions affected by this ADL
AffectedPositions []*ADLAffectedPosition
// TotalReduced is the total position size reduced
TotalReduced uint64
// TotalCompensation is the total compensation paid
TotalCompensation *big.Int
// InsuranceFundBefore is the insurance fund balance before ADL
InsuranceFundBefore *big.Int
// InsuranceFundAfter is the insurance fund balance after ADL
InsuranceFundAfter *big.Int
}
ADLEvent represents an auto-deleveraging event.
type ADLStatistics ¶ added in v1.22.76
type ADLStatistics struct {
TotalEvents uint64 `json:"totalEvents"`
TotalReduced *big.Int `json:"totalReduced"`
TotalCompensation *big.Int `json:"totalCompensation"`
LongCandidates int `json:"longCandidates"`
ShortCandidates int `json:"shortCandidates"`
}
ADLStatistics contains ADL engine statistics.
type AutoDeleveragingEngine ¶ added in v1.22.76
type AutoDeleveragingEngine struct {
// contains filtered or unexported fields
}
AutoDeleveragingEngine manages auto-deleveraging for the DEX.
func NewAutoDeleveragingEngine ¶ added in v1.22.76
func NewAutoDeleveragingEngine(config ADLConfig) *AutoDeleveragingEngine
NewAutoDeleveragingEngine creates a new ADL engine.
func (*AutoDeleveragingEngine) Execute ¶ added in v1.22.76
func (e *AutoDeleveragingEngine) Execute( symbol string, liquidatedPositionID ids.ID, liquidatedSide bool, sizeToDeleverage uint64, bankruptcyPrice uint64, insuranceFundBefore *big.Int, ) (*ADLEvent, error)
Execute performs auto-deleveraging for a liquidated position. liquidatedSide: true = long being liquidated (need to match with shorts) sizeToDeleverage: the size that needs to be covered bankruptcyPrice: the price at which the liquidated position is bankrupt
func (*AutoDeleveragingEngine) GetCandidateCount ¶ added in v1.22.76
func (e *AutoDeleveragingEngine) GetCandidateCount(symbol string) (longs, shorts int)
GetCandidateCount returns the number of ADL candidates for a symbol.
func (*AutoDeleveragingEngine) GetEvents ¶ added in v1.22.76
func (e *AutoDeleveragingEngine) GetEvents(limit int) []interface{}
GetEvents returns recent ADL events as interface{} slice for API compatibility.
func (*AutoDeleveragingEngine) RemoveCandidate ¶ added in v1.22.76
func (e *AutoDeleveragingEngine) RemoveCandidate(positionID ids.ID, symbol string, side bool)
RemoveCandidate removes an ADL candidate (position closed).
func (*AutoDeleveragingEngine) RemoveCandidateNoLock ¶ added in v1.22.76
func (e *AutoDeleveragingEngine) RemoveCandidateNoLock(positionID ids.ID, symbol string, side bool)
RemoveCandidateNoLock removes a candidate without acquiring lock.
func (*AutoDeleveragingEngine) ShouldTriggerADL ¶ added in v1.22.76
func (e *AutoDeleveragingEngine) ShouldTriggerADL(currentFund, targetFund *big.Int) bool
ShouldTriggerADL checks if ADL should be triggered based on insurance fund ratio.
func (*AutoDeleveragingEngine) Statistics ¶ added in v1.22.76
func (e *AutoDeleveragingEngine) Statistics() interface{}
Statistics returns ADL engine statistics as interface{} for API compatibility.
func (*AutoDeleveragingEngine) UpdateCandidate ¶ added in v1.22.76
func (e *AutoDeleveragingEngine) UpdateCandidate(candidate *ADLCandidate)
UpdateCandidate adds or updates an ADL candidate.
type DefaultPriceOracle ¶
type DefaultPriceOracle struct {
// contains filtered or unexported fields
}
DefaultPriceOracle uses last traded price as mark price
func (*DefaultPriceOracle) GetIndexPrice ¶
func (o *DefaultPriceOracle) GetIndexPrice(market string) (*big.Int, error)
func (*DefaultPriceOracle) GetMarkPrice ¶
func (o *DefaultPriceOracle) GetMarkPrice(market string) (*big.Int, error)
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine is the main perpetuals trading engine
func (*Engine) AddToInsuranceFund ¶
AddToInsuranceFund adds funds to the insurance fund
func (*Engine) CheckAndLiquidate ¶
func (e *Engine) CheckAndLiquidate(market string) ([]*LiquidationEvent, error)
CheckAndLiquidate checks positions for liquidation and executes if needed
func (*Engine) ClosePosition ¶
ClosePosition closes a position
func (*Engine) CreateAccount ¶
func (e *Engine) CreateAccount(traderID ids.ID) *MarginAccount
CreateAccount creates or gets a margin account for a trader
func (*Engine) CreateMarket ¶
func (e *Engine) CreateMarket( symbol string, baseAsset, quoteAsset ids.ID, initialPrice *big.Int, maxLeverage uint16, minSize *big.Int, tickSize *big.Int, makerFee, takerFee uint16, maintenanceMargin, initialMargin uint16, ) (*Market, error)
CreateMarket creates a new perpetual market
func (*Engine) GetAccount ¶
GetAccount returns a trader's margin account. Returns interface{} for API compatibility.
func (*Engine) GetAllMarkets ¶
func (e *Engine) GetAllMarkets() []interface{}
GetAllMarkets returns all markets as interface{} slice for API compatibility.
func (*Engine) GetAllPositions ¶
GetAllPositions returns all positions for a trader. Returns []interface{} for API compatibility.
func (*Engine) GetFundingPayments ¶
func (e *Engine) GetFundingPayments() []*FundingPayment
GetFundingPayments returns all funding payments
func (*Engine) GetInsuranceFund ¶
GetInsuranceFund returns the current insurance fund balance
func (*Engine) GetLiquidations ¶
func (e *Engine) GetLiquidations() []*LiquidationEvent
GetLiquidations returns all liquidation events
func (*Engine) GetMarginRatio ¶
GetMarginRatio calculates the margin ratio for an account
func (*Engine) GetMarket ¶
GetMarket returns a market by symbol. Returns interface{} for API compatibility.
func (*Engine) GetPosition ¶
GetPosition returns a position. Returns interface{} for API compatibility.
func (*Engine) GetTWAPPrice ¶ added in v1.22.76
GetTWAPPrice returns the time-weighted average price for a market. This should be used for liquidations to prevent flash crash manipulation.
func (*Engine) OpenPosition ¶
func (e *Engine) OpenPosition( traderID ids.ID, market string, side Side, size *big.Int, leverage uint16, marginMode MarginMode, ) (*Position, error)
OpenPosition opens or increases a position
func (*Engine) ProcessFunding ¶
func (e *Engine) ProcessFunding(market string) ([]*FundingPayment, error)
ProcessFunding processes funding payments for all positions
func (*Engine) SetPriceOracle ¶
func (e *Engine) SetPriceOracle(oracle PriceOracle)
SetPriceOracle sets a custom price oracle
func (*Engine) UpdateMarkPrice ¶
UpdateMarkPrice updates the mark price for a market
type FundingPayment ¶
type FundingPayment struct {
ID ids.ID // Payment ID
Position ids.ID // Position ID
Market string // Market symbol
Trader ids.ID // Trader ID
Amount *big.Int // Payment amount (negative = paid, positive = received)
FundingRate *big.Int // Funding rate at time of payment
Timestamp time.Time
}
FundingPayment represents a funding payment
type LeverageTier ¶
type LeverageTier struct {
MinNotional *big.Int // Minimum notional value (in quote asset, e.g., USDT)
MaxNotional *big.Int // Maximum notional value
MaxLeverage uint16 // Maximum leverage for this tier
MaintenanceMargin uint16 // Maintenance margin rate in basis points
MaintenanceAmount *big.Int // Maintenance amount deduction
}
LeverageTier represents a tier in the tiered leverage system Based on position notional value, max leverage decreases
func DefaultLeverageTiers ¶
func DefaultLeverageTiers() []*LeverageTier
DefaultLeverageTiers returns the standard Aster DEX-style tiered leverage system Supports up to 1001x leverage for small positions
type LiquidationEvent ¶
type LiquidationEvent struct {
ID ids.ID // Event ID
Position *Position // Liquidated position (snapshot)
LiquidationPrice *big.Int // Price at liquidation
LiquidationSize *big.Int // Size liquidated
InsurancePayout *big.Int // Amount from insurance fund
PnL *big.Int // P&L of liquidated position
Liquidator ids.ID // Liquidator (can be system or keeper)
Timestamp time.Time
}
LiquidationEvent represents a liquidation
type MarginAccount ¶
type MarginAccount struct {
TraderID ids.ID // Trader ID
Balance *big.Int // Total account balance
AvailableBalance *big.Int // Available balance for new positions
LockedMargin *big.Int // Margin locked in positions
UnrealizedPnL *big.Int // Total unrealized P&L across all positions
MarginRatio *big.Int // Current margin ratio (scaled by 1e18)
Positions map[string]*Position // Active positions by market
Mode MarginMode // Default margin mode
UpdatedAt time.Time
}
MarginAccount represents a trader's margin account
func NewMarginAccount ¶
func NewMarginAccount(traderID ids.ID) *MarginAccount
NewMarginAccount creates a new margin account
type MarginMode ¶
type MarginMode uint8
MarginMode represents the margin mode for a position
const ( CrossMargin MarginMode = iota IsolatedMargin )
func (MarginMode) String ¶
func (m MarginMode) String() string
type Market ¶
type Market struct {
Symbol string // Market symbol (e.g., "BTC-PERP")
BaseAsset ids.ID // Base asset ID
QuoteAsset ids.ID // Quote asset ID (usually USDC)
IndexPrice *big.Int // Current index price from oracle
MarkPrice *big.Int // Current mark price
LastPrice *big.Int // Last traded price
FundingRate *big.Int // Current funding rate (scaled by 1e18)
NextFundingTime time.Time // Next funding payment time
OpenInterestLong *big.Int // Total long open interest
OpenInterestShort *big.Int // Total short open interest
Volume24h *big.Int // 24h trading volume
MaxLeverage uint16 // Maximum allowed leverage
MinSize *big.Int // Minimum position size
TickSize *big.Int // Minimum price tick
MakerFee uint16 // Maker fee in basis points
TakerFee uint16 // Taker fee in basis points
MaintenanceMargin uint16 // Maintenance margin ratio in basis points
InitialMargin uint16 // Initial margin ratio in basis points
MaxFundingRate *big.Int // Maximum funding rate per period
FundingInterval time.Duration // Funding interval (typically 8 hours)
InsuranceFund *big.Int // Insurance fund balance for this market
CreatedAt time.Time
UpdatedAt time.Time
}
Market represents a perpetual futures market
type Order ¶
type Order struct {
ID ids.ID // Order ID
Trader ids.ID // Trader ID
Market string // Market symbol
Side Side // Long or Short
Size *big.Int // Order size
Price *big.Int // Limit price (nil for market orders)
IsMarket bool // True for market orders
ReduceOnly bool // Only reduce position, don't increase
PostOnly bool // Only maker, reject if would take
TimeInForce TimeInForce
Leverage uint16 // Desired leverage
MarginMode MarginMode
FilledSize *big.Int // Amount filled
AvgFillPrice *big.Int // Average fill price
Status OrderStatus
CreatedAt time.Time
UpdatedAt time.Time
}
Order represents a perpetual futures order
type OrderStatus ¶
type OrderStatus uint8
OrderStatus represents the status of an order
const ( OrderPending OrderStatus = iota OrderOpen OrderPartiallyFilled OrderFilled OrderCancelled OrderExpired OrderRejected )
type Position ¶
type Position struct {
ID ids.ID // Unique position ID
Trader ids.ID // Trader account ID
Market string // Market symbol (e.g., "BTC-PERP")
Side Side // Long or Short
Size *big.Int // Position size in base units (e.g., satoshis)
EntryPrice *big.Int // Average entry price (scaled by 1e18)
Margin *big.Int // Margin collateral locked
MarginMode MarginMode // Cross or Isolated
Leverage uint16 // Leverage multiplier (e.g., 10 = 10x)
LiquidationPrice *big.Int // Price at which position is liquidated
TakeProfit *big.Int // Optional take profit price
StopLoss *big.Int // Optional stop loss price
UnrealizedPnL *big.Int // Current unrealized P&L
RealizedPnL *big.Int // Total realized P&L
FundingPaid *big.Int // Total funding payments made/received
OpenedAt time.Time // When position was opened
UpdatedAt time.Time // Last update time
}
Position represents a perpetual futures position
type PriceOracle ¶
type PriceOracle interface {
GetIndexPrice(market string) (*big.Int, error)
GetMarkPrice(market string) (*big.Int, error)
}
PriceOracle provides price feeds for the engine
type RebatePayment ¶
type RebatePayment struct {
ID ids.ID // Payment ID
ReferrerID ids.ID // Recipient
RefereeID ids.ID // Source trader
TradeID ids.ID // Associated trade
Market string // Market
TradeVolume *big.Int // Trade notional volume
TradeFee *big.Int // Original trade fee
RebateAmount *big.Int // Rebate amount
Tier uint8 // Tier at time of payment
Timestamp time.Time
}
RebatePayment represents a rebate payment
type Referee ¶
type Referee struct {
ID ids.ID // Referee ID
ReferrerID ids.ID // Who referred them
ReferralCode string // Code used
TotalVolume *big.Int // Total trading volume
TotalDiscount *big.Int // Total fee discounts received
IsActive bool // Active in last 30 days
ReferredAt time.Time
LastActiveAt time.Time
}
Referee represents a referred user
type ReferralCode ¶
type ReferralCode struct {
Code string // Unique referral code
Owner ids.ID // Owner of the code
CustomRebate uint16 // Custom rebate rate (0 = use tier default)
IsActive bool // Whether code is active
CreatedAt time.Time
UpdatedAt time.Time
}
ReferralCode represents a referral code
type ReferralEngine ¶
type ReferralEngine struct {
// contains filtered or unexported fields
}
ReferralEngine manages the referral/rebate system
func NewReferralEngine ¶
func NewReferralEngine() *ReferralEngine
NewReferralEngine creates a new referral engine
func (*ReferralEngine) ClaimRebates ¶
ClaimRebates allows a referrer to claim pending rebates
func (*ReferralEngine) CreateReferralCode ¶
func (e *ReferralEngine) CreateReferralCode(ownerID ids.ID, code string) (*ReferralCode, error)
CreateReferralCode creates a new referral code for a user
func (*ReferralEngine) DeactivateCode ¶
func (e *ReferralEngine) DeactivateCode(code string, ownerID ids.ID) error
DeactivateCode deactivates a referral code
func (*ReferralEngine) GetFeeDiscount ¶
func (e *ReferralEngine) GetFeeDiscount(traderID ids.ID) uint16
GetFeeDiscount returns the fee discount for a trader
func (*ReferralEngine) GetReferee ¶
func (e *ReferralEngine) GetReferee(refereeID ids.ID) (*Referee, error)
GetReferee returns referee info
func (*ReferralEngine) GetReferralCode ¶
func (e *ReferralEngine) GetReferralCode(code string) (*ReferralCode, error)
GetReferralCode returns a referral code
func (*ReferralEngine) GetReferralsByCode ¶
func (e *ReferralEngine) GetReferralsByCode(code string) []*Referee
GetReferralsByCode returns all referees who used a specific code
func (*ReferralEngine) GetReferrer ¶
func (e *ReferralEngine) GetReferrer(referrerID ids.ID) (*Referrer, error)
GetReferrer returns referrer info
func (*ReferralEngine) GetStats ¶
func (e *ReferralEngine) GetStats() *ReferralStats
GetStats returns referral program stats
func (*ReferralEngine) ProcessTradeRebate ¶
func (e *ReferralEngine) ProcessTradeRebate( traderID ids.ID, tradeID ids.ID, market string, notionalVolume *big.Int, tradeFee *big.Int, ) (*RebatePayment, *big.Int, error)
ProcessTradeRebate calculates and records rebates for a trade
func (*ReferralEngine) SetCustomRebateRate ¶
func (e *ReferralEngine) SetCustomRebateRate(code string, rate uint16) error
SetCustomRebateRate sets a custom rebate rate for a code
func (*ReferralEngine) UseReferralCode ¶
func (e *ReferralEngine) UseReferralCode(userID ids.ID, code string) error
UseReferralCode links a new user to a referrer
type ReferralStats ¶
type ReferralStats struct {
TotalReferrers uint64 // Total number of referrers
TotalReferees uint64 // Total referred users
TotalRebatesPaid *big.Int // Total rebates paid out
TotalDiscountsGiven *big.Int // Total discounts given
ActiveReferrers30d uint64 // Referrers active in 30 days
Volume30d *big.Int // Total referred volume in 30 days
}
ReferralStats provides statistics for the referral program
type ReferralTier ¶
type ReferralTier struct {
Tier uint8 // Tier level (1-6)
MinVolume *big.Int // Minimum 30-day trading volume
MinReferrals uint32 // Minimum active referrals
ReferrerRebate uint16 // Rebate % for referrer (basis points, 10000 = 100%)
RefereeDiscount uint16 // Fee discount % for referee (basis points)
}
ReferralTier represents a tier in the referral program
func DefaultReferralTiers ¶
func DefaultReferralTiers() []*ReferralTier
DefaultReferralTiers returns the standard referral tiers
type Referrer ¶
type Referrer struct {
ID ids.ID // Referrer ID
Codes []string // Active referral codes
Tier uint8 // Current tier
TotalReferrals uint32 // Total number of referrals
ActiveReferrals uint32 // Active referrals (traded in last 30 days)
TotalVolume *big.Int // Total referred volume
Volume30d *big.Int // Last 30 day referred volume
TotalRebates *big.Int // Total rebates earned
PendingRebates *big.Int // Pending rebates to claim
CreatedAt time.Time
UpdatedAt time.Time
}
Referrer represents a referrer in the system
type TPSLConfig ¶
TPSLConfig holds the configuration for TP/SL orders on a position
func (*TPSLConfig) Clone ¶
func (c *TPSLConfig) Clone() *TPSLConfig
Clone creates a deep copy of TPSLConfig
type TPSLManager ¶
type TPSLManager struct {
// contains filtered or unexported fields
}
TPSLManager manages TP/SL orders
func (*TPSLManager) CancelOrder ¶
func (m *TPSLManager) CancelOrder(orderID ids.ID) error
CancelOrder cancels a TP/SL order
func (*TPSLManager) CancelOrdersForPosition ¶
func (m *TPSLManager) CancelOrdersForPosition(positionID ids.ID)
CancelOrdersForPosition cancels all TP/SL orders for a position
func (*TPSLManager) CheckTriggers ¶
func (m *TPSLManager) CheckTriggers( market string, markPrice, lastPrice, indexPrice *big.Int, getPositionSide func(positionID ids.ID) (Side, bool), ) []*TPSLOrder
CheckTriggers checks all TP/SL orders against current prices
func (*TPSLManager) CreateTPSL ¶
func (m *TPSLManager) CreateTPSL( positionID ids.ID, traderID ids.ID, market string, positionSide Side, entryPrice *big.Int, tpslType TPSLType, triggerPrice *big.Int, triggerType TriggerType, orderPrice *big.Int, size *big.Int, sizePercent uint16, ) (*TPSLOrder, error)
CreateTPSL creates a new TP/SL order
func (*TPSLManager) CreateTrailingStop ¶
func (m *TPSLManager) CreateTrailingStop( positionID ids.ID, traderID ids.ID, market string, positionSide Side, trailingDelta *big.Int, trailingPercent uint16, activationPrice *big.Int, size *big.Int, sizePercent uint16, ) (*TPSLOrder, error)
CreateTrailingStop creates a trailing stop order
func (*TPSLManager) GetOrdersForPosition ¶
func (m *TPSLManager) GetOrdersForPosition(positionID ids.ID) []*TPSLOrder
GetOrdersForPosition returns all TP/SL orders for a position
type TPSLOrder ¶
type TPSLOrder struct {
ID ids.ID // Unique order ID
PositionID ids.ID // Associated position
TraderID ids.ID // Trader who owns this
Market string // Market symbol
Type TPSLType // Take profit or Stop loss
Side Side // Side to close (opposite of position side)
TriggerPrice *big.Int // Price at which to trigger
TriggerType TriggerType // What price to watch
OrderPrice *big.Int // Execution price (nil = market order)
Size *big.Int // Size to close (nil = full position)
SizePercent uint16 // Size as percentage (0-10000 basis points)
// Trailing stop specific
TrailingDelta *big.Int // Distance to trail from high/low
TrailingPercent uint16 // Trail as percentage
ActivationPrice *big.Int // Price at which trailing starts
HighestPrice *big.Int // Highest price since activation (for long)
LowestPrice *big.Int // Lowest price since activation (for short)
// Metadata
Status TPSLStatus
TriggeredAt *time.Time
ExecutedAt *time.Time
CreatedAt time.Time
UpdatedAt time.Time
}
TPSLOrder represents a Take Profit or Stop Loss order
type TPSLStatus ¶
type TPSLStatus uint8
TPSLStatus represents the status of a TP/SL order
const ( TPSLPending TPSLStatus = iota TPSLActive TPSLTriggered TPSLExecuted TPSLCancelled TPSLExpired )
func (TPSLStatus) String ¶
func (s TPSLStatus) String() string
type TierConfig ¶
type TierConfig struct {
Tiers []*LeverageTier
GlobalMaxLeverage uint16 // Global max leverage (can be lower than tier max)
}
TierConfig stores the leverage tier configuration for a market
func NewTierConfig ¶
func NewTierConfig() *TierConfig
NewTierConfig creates a new tier configuration with default tiers
func (*TierConfig) GetMaintenanceMarginForNotional ¶
GetMaintenanceMarginForNotional returns the maintenance margin rate and amount
func (*TierConfig) GetMaxLeverageForNotional ¶
func (tc *TierConfig) GetMaxLeverageForNotional(notional *big.Int) uint16
GetMaxLeverageForNotional returns the maximum leverage allowed for a notional position size
func (*TierConfig) GetTierForNotional ¶
func (tc *TierConfig) GetTierForNotional(notional *big.Int) *LeverageTier
GetTierForNotional returns the leverage tier for a given notional value
type TimeInForce ¶
type TimeInForce uint8
TimeInForce specifies how long an order remains active
const ( GTC TimeInForce = iota // Good Till Cancel IOC // Immediate or Cancel FOK // Fill or Kill )
type Trade ¶
type Trade struct {
ID ids.ID // Trade ID
Market string // Market symbol
MakerOrder ids.ID // Maker order ID
TakerOrder ids.ID // Taker order ID
Maker ids.ID // Maker trader ID
Taker ids.ID // Taker trader ID
Side Side // Taker side
Price *big.Int // Execution price
Size *big.Int // Trade size
MakerFee *big.Int // Fee paid by maker
TakerFee *big.Int // Fee paid by taker
Timestamp time.Time // Execution time
}
Trade represents an executed trade
type TriggerType ¶
type TriggerType uint8
TriggerType specifies when TP/SL triggers
const ( TriggerOnMarkPrice TriggerType = iota TriggerOnLastPrice TriggerOnIndexPrice )
type VIPTier ¶
type VIPTier struct {
Tier uint8 // VIP level (0-9)
MinVolume30d *big.Int // Minimum 30-day trading volume
MakerFee uint16 // Maker fee in basis points
TakerFee uint16 // Taker fee in basis points
}
VIPTier represents a VIP fee tier based on trading volume
func DefaultVIPTiers ¶
func DefaultVIPTiers() []*VIPTier
DefaultVIPTiers returns standard VIP fee tiers