strat Package
The strat package provides trading strategy-related functionality definitions and implementations.
Main Structures
TradeStrat
Core structure for trading strategy, defines basic properties and behaviors of a strategy.
Public fields:
Name string- Strategy nameVersion int- Strategy version numberWarmupNum int- Number of candlesticks needed for warmupMinTfScore float64- Minimum time frame quality, default 0.75WsSubs map[string]string- WsSubs map[string]string // websocket subscription: core.WsSubKLine, core.WsSubTrade, core.WsSubDepthDrawDownExit bool- Whether to enable drawdown exitHedgeOff bool- turn off future hedge modeBatchInOut bool- Whether to batch execute entry/exitBatchInfo bool- Whether to perform batch processing after OnInfoBarStakeRate float64- Relative basic amount billing rateStopLoss float64- Stop loss rate for all orders opened by this strategy (without leverage)StopEnterBars int- Timeout candlestick number for limit entry ordersEachMaxLong int- Maximum number of long orders per trading pair, -1 to disableEachMaxShort int- Maximum number of short orders per trading pair, -1 to disableAllowTFs []string- Allowed running time periods, use global configuration when not providedOutputs []string- Content of the text file output by the strategy, where each string is one linePolicy *config.RunPolicyConfig- Strategy running configuration
StratJob
Strategy task instance, responsible for executing specific trading operations.
Public fields:
Strat *TradeStrat- Parent strategyEnv *ta.BarEnv- Indicator environmentEntrys []*EnterReq- Entry request listExits []*ExitReq- Exit request listLongOrders []*ormo.InOutOrder- Long order listShortOrders []*ormo.InOutOrder- Short order listSymbol *orm.ExSymbol- Currently running currencyTimeFrame string- Current running time frameAccount string- Account to which the current task belongsTPMaxs map[int64]float64- Price at maximum profit of the orderOrderNum int- Total number of unfinished ordersEnteredNum int- Number of fully/partially entered ordersCheckMS int64- Last timestamp of signal processing, 13-digit millisecondsMaxOpenLong int- Maximum number of long positions, 0 for unlimited, -1 to disableMaxOpenShort int- Maximum number of short positions, 0 for unlimited, -1 to disableCloseLong bool- Whether to allow closing long positionsCloseShort bool- Whether to allow closing short positionsExgStopLoss bool- Whether to allow exchange stop lossLongSLPrice float64- Default long stop loss price when opening positionShortSLPrice float64- Default short stop loss price when opening positionExgTakeProfit bool- Whether to allow exchange take profitLongTPPrice float64- Default long take profit price when opening positionShortTPPrice float64- Default short take profit price when opening positionIsWarmUp bool- Whether currently in warmup stateMore interface{}- Additional information for strategy customization
JobEnv
Represents a job for additional product data in OnBatchInfos.
Public fields:
Job *StratJob- Strategy job instanceEnv *ta.BarEnv- Indicator runtime environmentSymbol string- Trading pair name
BatchMap
Batch execution task pool for all targets in the current exchange market time cycle.
Public fields:
Map map[string]*JobEnv- Task mappingTFMSecs int64- Time frame millisecondsExecMS int64- Timestamp for executing batch tasks, delayed by a few seconds upon receiving a new target; execution starts when delay exceeds DelayBatchMS without receiving new targets
PairSub
Trading pair subscription information.
Public fields:
Pair string- Trading pair nameTimeFrame string- Time frameWarmupNum int- Warmup number
EnterReq
Open position request structure.
Public fields:
Tag string- Entry signalStgyName string- Strategy nameShort bool- Whether to short sellOrderType int- Order typeLimit float64- Entry price for limit order, order will be submitted as limit order when specifiedStop float64- Stop price, buy orders enter when the price rises to the trigger price (vice versa for sell orders).CostRate float64- Opening ratio, default 1x according to configuration, used for calculating LegalCostLegalCost float64- Amount in fiat currency, ignores CostRate when specifiedLeverage float64- Leverage ratioAmount float64- Entry target amount, calculated from LegalCost and priceStopLossVal float64- Distance from entry price to stop loss price, used to calculate StopLossStopLoss float64- Stop loss trigger price, submits a stop loss order on exchange when not emptyStopLossLimit float64- Stop loss limit price, StopLoss not available when providedStopLossRate float64- Stop loss exit ratio, 0 means full exit, must be between (0,1]StopLossTag string- Reason for stop lossTakeProfitVal float64- Distance from entry price to take profit price, used to calculate TakeProfitTakeProfit float64- Take profit trigger price, submits a take profit order on exchange when not emptyTakeProfitLimit float64- Take profit limit price, TakeProfit not available when providedTakeProfitRate float64- Take profit exit ratio, 0 means full exit, must be between (0,1]TakeProfitTag string- Reason for take profitStopBars int- Number of bars after which unfilled entry limit order will be cancelledClientID string- Used to set the trailing part of the ClientOrderID submitted to the exchange.Infos map[string]string- Used to store additional information for the order.
ExitReq
Close position request structure.
Public fields:
Tag string- Exit signalStgyName string- Strategy nameEnterTag string- Only exit orders with EnterTag as entry signalDirt int- Direction (core.OdDirt*), long/short/bothOrderType int- Order typeLimit float64- Exit price for limit order, order will be submitted as limit order when specifiedExitRate float64- Exit ratio, default 100% means all orders exitAmount float64- Target amount to exit, ExitRate invalid when specifiedOrderID int64- Only exit specified orderUnFillOnly bool- When True, only exit unfilled portionFilledOnly bool- When True, only exit filled ordersForce bool- Whether to force exit
Strategy Management Methods
New
Create a new trading strategy instance.
Parameters:
pol *config.RunPolicyConfig- Strategy running configuration
Returns:
*TradeStrat- Trading strategy instance
Get
Get strategy instance based on trading pair and strategy ID.
Parameters:
pair string- Trading pair namestratID string- Strategy ID
Returns:
*TradeStrat- Trading strategy instance, returns nil if not exists
GetStratPerf
Get strategy performance configuration.
Parameters:
pair string- Trading pair namestrat string- Strategy name
Returns:
*config.StratPerfConfig- Strategy performance configuration
AddStratGroup
Add strategy group.
Parameters:
group string- Strategy group nameitems map[string]FuncMakeStrat- Strategy creation function mapping
Order Management Methods
GetJobs
Get all strategy jobs for the specified account.
Parameters:
account string- Account name
Returns:
map[string]map[string]*StratJob- Job mapping grouped by trading pair and strategy
GetInfoJobs
Get information strategy jobs for the specified account.
Parameters:
account string- Account name
Returns:
map[string]map[string]*StratJob- Information job mapping grouped by trading pair and strategy
AddOdSub
Add order change subscription.
Parameters:
acc string- Account namecb FnOdChange- Order change callback function
FireOdChange
Trigger order change event.
Parameters:
acc string- Account nameod *ormo.InOutOrder- Order objectevt int- Event type
Performance Calculation Methods
CalcJobScores
Calculate strategy job scores.
Parameters:
pair string- Trading pair nametf string- Time framestgy string- Strategy name
Returns:
*errs.Error- Error information
CalcJobPerfs
Calculate strategy job performance.
Parameters:
cfg *config.StratPerfConfig- Performance configurationp *core.PerfSta- Performance statistics objectperfs []*core.JobPerf- Performance data list
CalcDrawDownExitRate
Calculate drawdown exit rate.
Parameters:
maxChg float64- Maximum change rate
Returns:
float64- Calculated exit rate
System Management Methods
LoadStratJobs
Load strategy jobs.
Parameters:
pairs []string- Trading pair listtfScores map[string]map[string]float64- Time frame score mapping
Returns:
map[string]map[string]int- Job status mappingmap[string][]*ormo.InOutOrder- Order mapping*errs.Error- Error information
ExitStratJobs
Exit all strategy jobs.