Documentation ¶
Index ¶
- Variables
- func CheckFundingRatePrerequisites(getFundingData, includePredicted, includePayments bool) error
- type CollateralCalculator
- type Contract
- type ContractSettlementType
- type ContractType
- type MultiPositionTracker
- func (m *MultiPositionTracker) GetPositions() []Position
- func (m *MultiPositionTracker) Liquidate(price decimal.Decimal, t time.Time) error
- func (m *MultiPositionTracker) TrackFundingDetails(d *fundingrate.HistoricalRates) error
- func (m *MultiPositionTracker) TrackNewOrder(d *order.Detail) error
- func (m *MultiPositionTracker) UpdateOpenPositionUnrealisedPNL(last float64, updated time.Time) (decimal.Decimal, error)
- type MultiPositionTrackerSetup
- type OpenInterest
- type PNLCalculation
- type PNLCalculator
- type PNLCalculatorRequest
- type PNLResult
- type Position
- type PositionController
- func (c *PositionController) ClearPositionsForExchange(exch string, item asset.Item, pair currency.Pair) error
- func (c *PositionController) GetAllOpenPositions() ([]Position, error)
- func (c *PositionController) GetOpenPosition(exch string, item asset.Item, pair currency.Pair) (*Position, error)
- func (c *PositionController) GetPositionsForExchange(exch string, item asset.Item, pair currency.Pair) ([]Position, error)
- func (c *PositionController) LastUpdated() (time.Time, error)
- func (c *PositionController) SetCollateralCurrency(exch string, item asset.Item, pair currency.Pair, ...) error
- func (c *PositionController) TrackFundingDetails(d *fundingrate.HistoricalRates) error
- func (c *PositionController) TrackNewOrder(d *order.Detail) error
- func (c *PositionController) UpdateOpenPositionUnrealisedPNL(exch string, item asset.Item, pair currency.Pair, last float64, ...) (decimal.Decimal, error)
- type PositionDetails
- type PositionResponse
- type PositionSummary
- type PositionSummaryRequest
- type PositionTracker
- func (p *PositionTracker) GetLatestPNLSnapshot() (PNLResult, error)
- func (p *PositionTracker) GetRealisedPNL() decimal.Decimal
- func (p *PositionTracker) GetStats() *Position
- func (p *PositionTracker) Liquidate(price decimal.Decimal, t time.Time) error
- func (p *PositionTracker) TrackFundingDetails(d *fundingrate.HistoricalRates) error
- func (p *PositionTracker) TrackNewOrder(d *order.Detail, isInitialOrder bool) error
- func (p *PositionTracker) TrackPNLByTime(t time.Time, currentPrice float64) error
- type PositionTrackerSetup
- type PositionsRequest
- type TotalCollateralCalculator
- type TotalCollateralResponse
Constants ¶
This section is empty.
Variables ¶
var ( // ErrPositionClosed returned when attempting to amend a closed position ErrPositionClosed = errors.New("the position is closed") // ErrNilPNLCalculator is raised when pnl calculation is requested for // an exchange, but the fields are not set properly ErrNilPNLCalculator = errors.New("nil pnl calculator received") // ErrPositionLiquidated is raised when checking PNL status only for // it to be liquidated ErrPositionLiquidated = errors.New("position liquidated") // ErrNotFuturesAsset returned when futures data is requested on a non-futures asset ErrNotFuturesAsset = errors.New("asset type is not futures") // ErrUSDValueRequired returned when usd value unset ErrUSDValueRequired = errors.New("USD value required") // ErrOfflineCalculationSet is raised when collateral calculation is set to be offline, yet is attempted online ErrOfflineCalculationSet = errors.New("offline calculation set") // ErrPositionNotFound is raised when a position is not found ErrPositionNotFound = errors.New("position not found") // ErrNotPerpetualFuture is returned when a currency is not a perpetual future ErrNotPerpetualFuture = errors.New("not a perpetual future") // ErrNoPositionsFound returned when there is no positions returned ErrNoPositionsFound = errors.New("no positions found") // ErrGetFundingDataRequired is returned when requesting funding rate data without the prerequisite ErrGetFundingDataRequired = errors.New("getfundingdata is a prerequisite") // ErrOrderHistoryTooLarge is returned when you lookup order history, but with too early a start date ErrOrderHistoryTooLarge = errors.New("order history start date too long ago") )
Functions ¶
func CheckFundingRatePrerequisites ¶
CheckFundingRatePrerequisites is a simple check to see if the requested data meets the prerequisite
Types ¶
type CollateralCalculator ¶
type CollateralCalculator struct { CalculateOffline bool CollateralCurrency currency.Code Asset asset.Item Side order.Side USDPrice decimal.Decimal IsLiquidating bool IsForNewPosition bool FreeCollateral decimal.Decimal LockedCollateral decimal.Decimal UnrealisedPNL decimal.Decimal }
CollateralCalculator is used to determine the size of collateral holdings for an exchange eg on Bybit, the collateral is scaled depending on what currency it is
type Contract ¶
type Contract struct { Exchange string Name currency.Pair Underlying currency.Pair Asset asset.Item StartDate time.Time EndDate time.Time IsActive bool Status string Type ContractType SettlementType ContractSettlementType // Optional values if the exchange offers them SettlementCurrencies currency.Currencies MarginCurrency currency.Code Multiplier float64 MaxLeverage float64 LatestRate fundingrate.Rate FundingRateFloor decimal.Decimal FundingRateCeiling decimal.Decimal }
Contract holds details on futures contracts
type ContractSettlementType ¶
type ContractSettlementType uint8
ContractSettlementType holds the various style of contracts offered by futures exchanges
const ( UnsetSettlementType ContractSettlementType = iota Linear Inverse Quanto LinearOrInverse )
ContractSettlementType definitions
func (ContractSettlementType) String ¶
func (d ContractSettlementType) String() string
String returns the string representation of a contract settlement type
type ContractType ¶
type ContractType uint8
ContractType holds the various style of contracts offered by futures exchanges
const ( UnsetContractType ContractType = iota Perpetual LongDated Weekly Fortnightly ThreeWeekly Monthly Quarterly SemiAnnually HalfYearly NineMonthly Yearly Unknown )
ContractType definitions
func (ContractType) String ¶
func (c ContractType) String() string
String returns the string representation of the contract type
type MultiPositionTracker ¶
type MultiPositionTracker struct {
// contains filtered or unexported fields
}
MultiPositionTracker will track the performance of futures positions over time. If an old position tracker is closed, then the position controller will create a new one to track the current positions
func SetupMultiPositionTracker ¶
func SetupMultiPositionTracker(setup *MultiPositionTrackerSetup) (*MultiPositionTracker, error)
SetupMultiPositionTracker creates a futures order tracker for a specific exchange
func (*MultiPositionTracker) GetPositions ¶
func (m *MultiPositionTracker) GetPositions() []Position
GetPositions returns all positions
func (*MultiPositionTracker) Liquidate ¶
Liquidate will update the latest open position's to reflect its liquidated status
func (*MultiPositionTracker) TrackFundingDetails ¶
func (m *MultiPositionTracker) TrackFundingDetails(d *fundingrate.HistoricalRates) error
TrackFundingDetails applies funding rate details to a tracked position
func (*MultiPositionTracker) TrackNewOrder ¶
func (m *MultiPositionTracker) TrackNewOrder(d *order.Detail) error
TrackNewOrder upserts an order to the tracker and updates position status and exposure. PNL is calculated separately as it requires mark prices
func (*MultiPositionTracker) UpdateOpenPositionUnrealisedPNL ¶
func (m *MultiPositionTracker) UpdateOpenPositionUnrealisedPNL(last float64, updated time.Time) (decimal.Decimal, error)
UpdateOpenPositionUnrealisedPNL updates the pnl for the latest open position based on the last price and the time
type MultiPositionTrackerSetup ¶
type MultiPositionTrackerSetup struct { Exchange string Asset asset.Item Pair currency.Pair Underlying currency.Code CollateralCurrency currency.Code OfflineCalculation bool UseExchangePNLCalculation bool ExchangePNLCalculation PNLCalculation }
MultiPositionTrackerSetup holds the parameters required to set up a multi position tracker
type OpenInterest ¶
type OpenInterest struct { Key key.ExchangePairAsset OpenInterest float64 }
OpenInterest holds open interest data for an exchange pair asset
type PNLCalculation ¶
type PNLCalculation interface { CalculatePNL(context.Context, *PNLCalculatorRequest) (*PNLResult, error) GetCurrencyForRealisedPNL(realisedAsset asset.Item, realisedPair currency.Pair) (currency.Code, asset.Item, error) }
PNLCalculation is an interface to allow multiple ways of calculating PNL to be used for futures positions
type PNLCalculator ¶
type PNLCalculator struct{}
PNLCalculator implements the PNLCalculation interface to call CalculatePNL and is used when a user wishes to have a consistent method of calculating PNL across different exchanges
func (*PNLCalculator) CalculatePNL ¶
func (p *PNLCalculator) CalculatePNL(_ context.Context, calc *PNLCalculatorRequest) (*PNLResult, error)
CalculatePNL this is a localised generic way of calculating open positions' worth, it is an implementation of the PNLCalculation interface
func (*PNLCalculator) GetCurrencyForRealisedPNL ¶
func (p *PNLCalculator) GetCurrencyForRealisedPNL(realisedAsset asset.Item, realisedPair currency.Pair) (currency.Code, asset.Item, error)
GetCurrencyForRealisedPNL is a generic handling of determining the asset to assign realised PNL into, which is just itself
type PNLCalculatorRequest ¶
type PNLCalculatorRequest struct { Pair currency.Pair CalculateOffline bool Underlying currency.Code Asset asset.Item Leverage decimal.Decimal EntryPrice decimal.Decimal EntryAmount decimal.Decimal Amount decimal.Decimal CurrentPrice decimal.Decimal PreviousPrice decimal.Decimal Time time.Time OrderID string Fee decimal.Decimal PNLHistory []PNLResult Exposure decimal.Decimal OrderDirection order.Side OpeningDirection order.Side CurrentDirection order.Side }
PNLCalculatorRequest is used to calculate PNL values for an open position
type PNLResult ¶
type PNLResult struct { Status order.Status Time time.Time UnrealisedPNL decimal.Decimal RealisedPNLBeforeFees decimal.Decimal RealisedPNL decimal.Decimal Price decimal.Decimal Exposure decimal.Decimal Direction order.Side Fee decimal.Decimal IsLiquidated bool // Is event is supposed to show that something has happened and it isn't just tracking in time IsOrder bool }
PNLResult stores a PNL result from a point in time
type Position ¶
type Position struct { Exchange string Asset asset.Item Pair currency.Pair Underlying currency.Code CollateralCurrency currency.Code RealisedPNL decimal.Decimal UnrealisedPNL decimal.Decimal Status order.Status OpeningDate time.Time OpeningPrice decimal.Decimal OpeningSize decimal.Decimal OpeningDirection order.Side LatestPrice decimal.Decimal LatestSize decimal.Decimal LatestDirection order.Side LastUpdated time.Time CloseDate time.Time Orders []order.Detail PNLHistory []PNLResult FundingRates fundingrate.HistoricalRates }
Position is a basic holder for position information
type PositionController ¶
type PositionController struct {
// contains filtered or unexported fields
}
PositionController manages all futures orders across all exchanges assets and pairs its purpose is to handle the minutia of tracking and so all you need to do is send all orders to the position controller and its all tracked happily
func SetupPositionController ¶
func SetupPositionController() PositionController
SetupPositionController creates a position controller to track futures orders
func (*PositionController) ClearPositionsForExchange ¶
func (c *PositionController) ClearPositionsForExchange(exch string, item asset.Item, pair currency.Pair) error
ClearPositionsForExchange resets positions for an exchange, asset, pair that has been stored
func (*PositionController) GetAllOpenPositions ¶
func (c *PositionController) GetAllOpenPositions() ([]Position, error)
GetAllOpenPositions returns all open positions with optional filters
func (*PositionController) GetOpenPosition ¶
func (c *PositionController) GetOpenPosition(exch string, item asset.Item, pair currency.Pair) (*Position, error)
GetOpenPosition returns an open positions that matches the exchange, asset, pair
func (*PositionController) GetPositionsForExchange ¶
func (c *PositionController) GetPositionsForExchange(exch string, item asset.Item, pair currency.Pair) ([]Position, error)
GetPositionsForExchange returns all positions for an exchange, asset pair that is stored in the position controller
func (*PositionController) LastUpdated ¶
func (c *PositionController) LastUpdated() (time.Time, error)
LastUpdated is used for the order manager as a way of knowing what span of time to check for orders
func (*PositionController) SetCollateralCurrency ¶
func (c *PositionController) SetCollateralCurrency(exch string, item asset.Item, pair currency.Pair, collateralCurrency currency.Code) error
SetCollateralCurrency allows the setting of a collateral currency to all child trackers when using position controller for futures orders tracking
func (*PositionController) TrackFundingDetails ¶
func (c *PositionController) TrackFundingDetails(d *fundingrate.HistoricalRates) error
TrackFundingDetails applies funding rate details to a tracked position
func (*PositionController) TrackNewOrder ¶
func (c *PositionController) TrackNewOrder(d *order.Detail) error
TrackNewOrder sets up the maps to then create a multi position tracker which funnels down into the position tracker, to then track an order's pnl
func (*PositionController) UpdateOpenPositionUnrealisedPNL ¶
func (c *PositionController) UpdateOpenPositionUnrealisedPNL(exch string, item asset.Item, pair currency.Pair, last float64, updated time.Time) (decimal.Decimal, error)
UpdateOpenPositionUnrealisedPNL finds an open position from an exchange asset pair, then calculates the unrealisedPNL using the latest ticker data
type PositionDetails ¶
type PositionDetails struct { Exchange string Asset asset.Item Pair currency.Pair Orders []order.Detail }
PositionDetails are used to track open positions in the order manager
type PositionResponse ¶
type PositionResponse struct { Pair currency.Pair Asset asset.Item ContractSettlementType ContractSettlementType Orders []order.Detail }
PositionResponse are used to track open positions in the order manager
type PositionSummary ¶
type PositionSummary struct { Pair currency.Pair Asset asset.Item MarginType margin.Type CollateralMode collateral.Mode // The currency in which the values are quoted against. Isn't always pair.Quote // eg BTC-USDC-230929's quote in GCT is 230929, but the currency should be USDC Currency currency.Code StartDate time.Time AvailableEquity decimal.Decimal CashBalance decimal.Decimal DiscountEquity decimal.Decimal EquityUSD decimal.Decimal IsolatedEquity decimal.Decimal IsolatedLiabilities decimal.Decimal IsolatedUPL decimal.Decimal NotionalLeverage decimal.Decimal TotalEquity decimal.Decimal StrategyEquity decimal.Decimal MarginBalance decimal.Decimal IsolatedMargin decimal.Decimal NotionalSize decimal.Decimal Leverage decimal.Decimal MaintenanceMarginRequirement decimal.Decimal InitialMarginRequirement decimal.Decimal EstimatedLiquidationPrice decimal.Decimal CollateralUsed decimal.Decimal MarkPrice decimal.Decimal CurrentSize decimal.Decimal ContractSize decimal.Decimal ContractMultiplier decimal.Decimal ContractSettlementType ContractSettlementType AverageOpenPrice decimal.Decimal UnrealisedPNL decimal.Decimal RealisedPNL decimal.Decimal MaintenanceMarginFraction decimal.Decimal FreeCollateral decimal.Decimal TotalCollateral decimal.Decimal FrozenBalance decimal.Decimal EquityOfCurrency decimal.Decimal }
PositionSummary returns basic details on an open position
type PositionSummaryRequest ¶
type PositionSummaryRequest struct { Asset asset.Item Pair currency.Pair // UnderlyingPair is optional if the exchange requires it for a contract like BTCUSDT-13333337 UnderlyingPair currency.Pair // offline calculation requirements below CalculateOffline bool Direction order.Side FreeCollateral decimal.Decimal TotalCollateral decimal.Decimal CurrentPrice decimal.Decimal CurrentSize decimal.Decimal CollateralUsed decimal.Decimal NotionalPrice decimal.Decimal MaxLeverageForAccount decimal.Decimal TotalOpenPositionNotional decimal.Decimal // EstimatePosition if enabled, can be used to calculate a new position EstimatePosition bool // These fields are also used for offline calculation OpeningPrice decimal.Decimal OpeningSize decimal.Decimal Leverage decimal.Decimal TotalAccountValue decimal.Decimal }
PositionSummaryRequest is used to request a summary of an open position
type PositionTracker ¶
type PositionTracker struct { PNLCalculation // contains filtered or unexported fields }
PositionTracker tracks futures orders until the overall position is considered closed eg a user can open a short position, append to it via two more shorts, reduce via a small long and finally close off the remainder via another long. All of these actions are to be captured within one position tracker. It allows for a user to understand their PNL specifically for futures positions. Utilising spot/futures arbitrage will not be tracked completely within this position tracker, however, can still provide a good timeline of performance until the position is closed
func SetupPositionTracker ¶
func SetupPositionTracker(setup *PositionTrackerSetup) (*PositionTracker, error)
SetupPositionTracker creates a new position tracker to track n futures orders until the position(s) are closed
func (*PositionTracker) GetLatestPNLSnapshot ¶
func (p *PositionTracker) GetLatestPNLSnapshot() (PNLResult, error)
GetLatestPNLSnapshot takes the latest pnl history value and returns it
func (*PositionTracker) GetRealisedPNL ¶
func (p *PositionTracker) GetRealisedPNL() decimal.Decimal
GetRealisedPNL returns the realised pnl if the order is closed
func (*PositionTracker) GetStats ¶
func (p *PositionTracker) GetStats() *Position
GetStats returns a summary of a future position
func (*PositionTracker) Liquidate ¶
Liquidate will update the positions stats to reflect its liquidation
func (*PositionTracker) TrackFundingDetails ¶
func (p *PositionTracker) TrackFundingDetails(d *fundingrate.HistoricalRates) error
TrackFundingDetails sets funding rates to a position
func (*PositionTracker) TrackNewOrder ¶
func (p *PositionTracker) TrackNewOrder(d *order.Detail, isInitialOrder bool) error
TrackNewOrder knows how things are going for a given futures contract
func (*PositionTracker) TrackPNLByTime ¶
func (p *PositionTracker) TrackPNLByTime(t time.Time, currentPrice float64) error
TrackPNLByTime calculates the PNL based on a position tracker's exposure and current pricing. Adds the entry to PNL history to track over time
type PositionTrackerSetup ¶
type PositionTrackerSetup struct { Exchange string Asset asset.Item Pair currency.Pair EntryPrice decimal.Decimal Underlying currency.Code CollateralCurrency currency.Code Side order.Side UseExchangePNLCalculation bool OfflineCalculation bool PNLCalculator PNLCalculation }
PositionTrackerSetup contains all required fields to setup a position tracker
type PositionsRequest ¶
type PositionsRequest struct { Asset asset.Item Pairs currency.Pairs StartDate time.Time EndDate time.Time // RespectOrderHistoryLimits is designed for the order manager // it allows for orders to be tracked if the start date in the config is // beyond the allowable limits by the API, rather than returning an error RespectOrderHistoryLimits bool }
PositionsRequest defines the request to retrieve futures position data
type TotalCollateralCalculator ¶
type TotalCollateralCalculator struct { CollateralAssets []CollateralCalculator CalculateOffline bool FetchPositions bool }
TotalCollateralCalculator holds many collateral calculators to calculate total collateral standing with one struct
type TotalCollateralResponse ¶
type TotalCollateralResponse struct { CollateralCurrency currency.Code TotalValueOfPositiveSpotBalances decimal.Decimal CollateralContributedByPositiveSpotBalances decimal.Decimal UsedCollateral decimal.Decimal UsedBreakdown *collateral.UsedBreakdown AvailableCollateral decimal.Decimal AvailableMaintenanceCollateral decimal.Decimal UnrealisedPNL decimal.Decimal BreakdownByCurrency []collateral.ByCurrency BreakdownOfPositions []collateral.ByPosition }
TotalCollateralResponse holds all collateral