strat

package
v0.2.30 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 9, 2026 License: AGPL-3.0 Imports: 24 Imported by: 7

README

策略热加载的几种方案

由于策略经常需要增删或更新,需要和机器人分开分发。go不支持二进制分发包,目前调研到下面几种动态加载方案。
由于本项目采用go最主要目的是改善性能,而策略和系统涉及到很多次交互,是最大的性能瓶颈,故使用goloader方案。

goloader

重用了golang编译器的输出,不需要自己写编译器,就能支持所有golang的语言特征。
只进行符号重定位,和提供runtime信息,可以卸载加载的代码,复用了runtime,支持windows,linux,macos 和原生go性能相同,是所有方案中性能最好的。

go原生plugin

可参考使用tidb文档
官方文档
一文搞懂Go语言的plugin
Go Plugin,一个凉了快半截的特性?

【优点】

  • 性能接近原生go,非常快,大概有原生70%的性能

【缺点】

  • 只支持linux,mac,不支持windows
  • 要求插件和主程序打包版本完全一致
  • 要求所有依赖包版本完全一致
  • 有一定的入侵风险
WebAssembly

将插件部分打包为wasi,然后主程序嵌入一个wasm运行时,由运行时加载插件并运行。
go没有原生支持wasm,所以目前有两种方法:

  1. 使用Cgo链接一个C或Rust的运行时
  2. 使用wazero作为运行时

wasmer 16.7 star
使用CGo+LLVM编译器,性能接近原生;
wasm-micro-runtime 4.2 star
使用CGo嵌入到Go程序中
wasmtime 13.5 start 使用CGo嵌入到Go程序中,性能比wasmer-LLVM慢一些
wasm3 6.5 star
Go绑定不支持Windows, WasmEdge 7.2 star
使用CGo嵌入到Go主程序
extism 2.8 star
使用wazero集成到go主程序
wazero 4.2 star
纯go实现的,使用TinyGo,优于CGo嵌入

go-tengo脚本

Github
这是基于纯go写的动态解释性脚本语言,支持预编译。性能接近原生python,比原生go慢50倍。
未测试与gp-plugin-grpc的性能对比,应该tengo稍快。

go-plugin-grpc

Github
这是基于grpc的插件方案,支持所有主要语言。

【优点】

  • 支持语言多
  • 双向通信调用
  • 进程隔离,无安全风险

【缺点】

  • 性能应该是最差的,尤其在频繁通信的时候。

Documentation

Index

Constants

View Source
const (
	OdChgNew       = iota // New order 新订单
	OdChgEnter            // Create an entry order 创建入场订单
	OdChgEnterFill        // Order entry completed 订单入场完成
	OdChgExit             // Order request to exit  订单请求退出
	OdChgExitFill         // Order exit completed 订单退出完成
)

Variables

View Source
var (
	Versions    = make(map[string]int)                             // stratName: int 策略版本号
	Envs        = make(map[string]*ta.BarEnv)                      // pair_tf: BarEnv
	TmpEnvs     = make(map[string]*ta.BarEnv)                      // pair_tf: BarEnv
	AccJobs     = make(map[string]map[string]map[string]*StratJob) // account: pair_tf: [stratID]StratJob
	AccInfoJobs = make(map[string]map[string]map[string]*StratJob) // account: pair_tf: [stratID_pair]StratJob 额外订阅
	PairStrats  = make(map[string]map[string]*TradeStrat)          // pair:[stratID]TradeStrat 所有的订阅策略,注意有些策略对象虽然Name相同但不是同一个实例
	ForbidJobs  = make(map[string]map[string]bool)                 // pair_tf: [stratID] occupy
	WsSubJobs   = make(map[string]map[string]map[*StratJob]bool)   // msgType: pair: job

	BatchTasks  = map[string]*BatchMap{} // tf_account_strat: pair: task 每个bar周期更新(只适用于单交易所单市场)
	LastBatchMS = int64(0)               // timeMS The timestamp of the last batch execution is only used for backtesting 上次批量执行的时间戳,仅用于回测

	WsSubUnWatch func(map[string][]string)
)
View Source
var (
	FailOpenCostTooLess    = "CostTooLess"
	FailOpenBadDirtOrLimit = "BadDirtOrLimit"
	FailOpenNanNum         = "NanNum"
	FailOpenBadStopLoss    = "BadStopLoss"
	FailOpenBadTakeProfit  = "BadTakeProfit"
	FailOpenBarTooLate     = "BarTooLate"
	FailOpenNoEntry        = "NoEntry"
	FailOpenNumLimit       = "NumLimit"
	FailOpenNumLimitPol    = "NumLimitPol"
)
View Source
var (
	StratMake = make(map[string]FuncMakeStrat) // 已加载的策略缓存

)

Functions

func AddAccFailOpen added in v0.1.33

func AddAccFailOpen(acc, tag string)

func AddAccFailOpens added in v0.2.9

func AddAccFailOpens(acc, tag string, num int)

func AddOdSub

func AddOdSub(acc string, cb FnOdChange)

func AddStratGroup added in v0.1.7

func AddStratGroup(group string, items map[string]FuncMakeStrat)

func CalcDrawDownExitRate

func CalcDrawDownExitRate(maxChg float64) float64

func CalcJobPerfs

func CalcJobPerfs(cfg *config.StratPerfConfig, p *core.PerfSta, perfs []*core.JobPerf)

func CalcJobScores

func CalcJobScores(pair, tf, stgy string) *errs.Error

func CalcPairTfScores added in v0.1.29

func CalcPairTfScores(exchange banexg.BanExchange, pairs []string) (map[string]map[string]float64, *errs.Error)

CalcPairTfScores Calculate the K-line quality score of each dimension of the trading pair 计算交易对各维度K线质量分数

func CallStratSymbols added in v0.2.16

func CallStratSymbols(stgy *TradeStrat, curPairs []string, tfScores map[string]map[string]float64) ([]*orm.ExSymbol, *errs.Error)

func CheckCustomExits added in v0.2.16

func CheckCustomExits(job *StratJob) *errs.Error

func CheckJobInOutNum added in v0.2.22

func CheckJobInOutNum(job *StratJob, tag string, inNum, outNum int)

func DumpAccFailOpens added in v0.1.33

func DumpAccFailOpens() string

func ExitStratJobs

func ExitStratJobs()

func FireOdChange

func FireOdChange(acc string, od *ormo.InOutOrder, evt int)

func GetHistOrders added in v0.2.24

func GetHistOrders(args ormo.GetHistOrdersArgs) ([]*ormo.InOutOrder, *errs.Error)

func GetInfoJobs

func GetInfoJobs(account string) map[string]map[string]*StratJob

func GetJobInOutNum added in v0.2.22

func GetJobInOutNum(job *StratJob) (int, int)

func GetJobKeys added in v0.1.29

func GetJobKeys() map[string]map[string]bool

GetJobKeys 获取已订阅的所有策略任务记录 return map[pair_tf][stratID]bool

func GetJobs

func GetJobs(account string) map[string]map[string]*StratJob

GetJobs 返回:pair_tf: [stratID]StratJob

func GetStratPerf

func GetStratPerf(pair, strat string) *config.StratPerfConfig

func JobForbidType added in v0.1.29

func JobForbidType(pair, tf, stratID string) int

JobForbidType 0 allow; 1 forbid; 2 forbid & occupy a slot

func ListStrats added in v0.2.9

func ListStrats(args []string) error

func LoadStratJobs

func LoadStratJobs(pairs []string, tfScores map[string]map[string]float64) (map[string]map[string]int, map[string][]*ormo.InOutOrder, *errs.Error)

LoadStratJobs Loading strategies and trading pairs 加载策略和交易对

更新以下全局变量: Update the following global variables: core.TFSecs core.StgPairTfs core.BookPairs strat.Versions strat.Envs strat.PairStrats strat.AccJobs strat.AccInfoJobs

return:pair:timeframe:warmNum, acc:exit orders, error

func PrintStratGroups added in v0.2.16

func PrintStratGroups()

PrintStratGroups print strategy+timeframe from `core.StgPairTfs` 从core.StgPairTfs输出策略+时间周期的币种信息到控制台

Types

type BatchMap

type BatchMap struct {
	Map     map[string]*JobEnv
	TFMSecs int64
	ExecMS  int64 // The timestamp for executing batch tasks is delayed by a few seconds upon receiving a new target; Delay exceeded and BatchMS did not receive, start execution 执行批量任务的时间戳,每收到新的标的,推迟几秒;超过DelayBatchMS未收到,开始执行
}

BatchMap Batch execution task pool for all targets in the current exchange market time cycle 当前交易所-市场-时间周期下,所有标的的批量执行任务池

type CalcDDExitRate

type CalcDDExitRate func(s *StratJob, od *ormo.InOutOrder, maxChg float64) float64

type EnterReq

type EnterReq struct {
	Tag             string  // Entry signal 入场信号
	StratName       string  // Strategy Name 策略名称
	Short           bool    // Whether to short sell or not 是否做空
	OrderType       int     // 订单类型, core.OrderType*
	Limit           float64 // The entry price of a limit order will be submitted as a limit order when specified 限价单入场价格,指定时订单将作为限价单提交
	Stop            float64 // Stop price, buy orders enter when the price rises to the trigger price (vice versa for sell orders). 止损(触发价格),做多订单时价格上涨到触发价格才入场(做空相反)
	CostRate        float64 // The opening ratio is set to 1 times by default according to the configuration. Used for calculating LegalList 开仓倍率、默认按配置1倍。用于计算LegalCost
	LegalCost       float64 // Spend the amount in fiat currency. Ignore CostRate when specified 花费法币金额。指定时忽略CostRate
	Leverage        float64 // Leverage ratio 杠杆倍数
	Amount          float64 // The number of admission targets is calculated by LegalList and price 入场标的数量,由LegalCost和price计算
	StopLossVal     float64 // The distance from the entry price to the stop loss price is used to calculate StopLoss 入场价格到止损价格的距离,用于计算StopLoss
	StopLoss        float64 // Stop loss trigger price, submit a stop loss order on the exchange when it is not empty 止损触发价格,不为空时在交易所提交一个止损单
	StopLossLimit   float64 // Stop loss limit price, does not provide the use of StopLoss 止损限制价格,不提供使用StopLoss
	StopLossRate    float64 // Stop loss exit ratio, 0 means all exits, needs to be between (0,1) 止损退出比例,0表示全部退出,需介于(0,1]之间
	StopLossTag     string  // Reason for Stop Loss 止损原因
	ActivationPrice float64 // Activation Price for Trailing Stop 追踪止损激活价格
	CallbackPct     float64 // Callback Percentage for Trailing Stop 追踪止损回调百分比, [0.1, 10]
	TakeProfitVal   float64 // The distance from the entry price to the take profit price is used to calculate TakeProfit 入场价格到止盈价格的距离,用于计算TakeProfit
	TakeProfit      float64 // When the take profit trigger price is not empty, submit a take profit order on the exchange. 止盈触发价格,不为空时在交易所提交一个止盈单。
	TakeProfitLimit float64 // Profit taking limit price, TakeProfit is not available for use 止盈限制价格,不提供使用TakeProfit
	TakeProfitRate  float64 // Take profit exit ratio, 0 indicates full exit, needs to be between (0,1) 止盈退出比率,0表示全部退出,需介于(0,1]之间
	TakeProfitTag   string  // Reason for profit taking 止盈原因
	StopBars        int     // If the entry limit order exceeds how many bars and is not executed, it will be cancelled 入场限价单超过多少个bar未成交则取消
	ClientID        string  // used as suffix of ClientOrderID to exchange
	Infos           map[string]string
	Log             bool // 是否自动记录错误日志
}

EnterReq 打开一个订单。默认开多。如需开空short=False

func (*EnterReq) Clone added in v0.2.18

func (q *EnterReq) Clone() *EnterReq

func (*EnterReq) GetZapFields added in v0.2.18

func (q *EnterReq) GetZapFields(s *StratJob, fields ...zap.Field) []zap.Field

type ExitReq

type ExitReq struct {
	Tag        string  // Exit signal 退出信号
	StratName  string  // Strategy Name 策略名称
	EnterTag   string  // Only exit orders with EnterTag as the entry signal 只退出入场信号为EnterTag的订单
	Dirt       int     // core.OdDirt* long/short/both
	OrderType  int     // 订单类型, core.OrderType*
	Limit      float64 // Limit order exit price, the order will be submitted as a limit order when specified 限价单退出价格,指定时订单将作为限价单提交
	ExitRate   float64 // Exit rate, default is 100%, which means all orders are exited 退出比率,默认100%即所有订单全部退出
	Amount     float64 // The number of targets to be exited. ExitRate is invalid when specified 要退出的标的数量。指定时ExitRate无效
	OrderID    int64   // Only exit specified orders 只退出指定订单
	UnFillOnly bool    // When True, exit orders which hasn't been filled only. True时只退出尚未入场的部分
	FilledOnly bool    // Only exit orders that have already entered when True True时只退出已入场的订单
	Force      bool    // Whether to force exit 是否强制退出
	Log        bool    // 是否自动记录错误日志
}

ExitReq 请求平仓

func (*ExitReq) Clone

func (q *ExitReq) Clone() *ExitReq

func (*ExitReq) GetZapFields added in v0.2.18

func (q *ExitReq) GetZapFields(s *StratJob, fields ...zap.Field) []zap.Field

type FnOdChange

type FnOdChange func(acc string, od *ormo.InOutOrder, evt int)

type FnOnPostApi added in v0.2.16

type FnOnPostApi func(client *core.ApiClient, msg map[string]interface{}, jobs map[string]map[string]*StratJob) error

type FuncMakeStrat

type FuncMakeStrat = func(pol *config.RunPolicyConfig) *TradeStrat

type JobEnv added in v0.2.14

type JobEnv struct {
	Job    *StratJob
	Env    *ta.BarEnv
	Symbol string
}

type PairSub

type PairSub struct {
	Pair      string
	TimeFrame string
	WarmupNum int
}

type PickTimeFrameFunc

type PickTimeFrameFunc func(symbol string, tfScores []*core.TfScore) string

type PolicyGroup added in v0.1.29

type PolicyGroup struct {
	Policies []*config.RunPolicyConfig
	StartMS  int64
}

func RelayPolicyGroups added in v0.1.29

func RelayPolicyGroups() []*PolicyGroup

RelayPolicyGroups 获取需要接力开单的策略分组

将策略按最小周期划分为多个组。组内多个策略的最小周期最大差距不能超过5倍。 用于对不同起止时间且不同周期的策略,划分不同组,提高整体效率

type StratJob

type StratJob struct {
	Strat         *TradeStrat
	Env           *ta.BarEnv
	Entrys        []*EnterReq
	Exits         []*ExitReq
	LongOrders    []*ormo.InOutOrder
	ShortOrders   []*ormo.InOutOrder
	Symbol        *orm.ExSymbol     // The currently running currency 当前运行的币种
	TimeFrame     string            // The current running time cycle 当前运行的时间周期
	Account       string            // The account to which the current task belongs 当前任务所属账号
	TPMaxs        map[int64]float64 // Price at maximum profit of the order 订单最大盈利时价格
	OrderNum      int               // All unfinished order quantities 所有未完成订单数量
	EnteredNum    int               // The number of fully/part entered orders 已完全/部分入场的订单数量
	CheckMS       int64             // Last timestamp of signal processing, 13 milliseconds 上次处理信号的时间戳,13位毫秒
	LastBarMS     int64             // End timestamp of the previous candlestick 上个K线的结束时间戳,13位毫秒
	MaxOpenLong   int               // Max open number for long position, 0 for any, -1 for disabled 最大开多数量,0不限制,-1禁止开多
	MaxOpenShort  int               // Max open number for short position, 0 for any, -1 for disabled 最大开空数量,0不限制,-1禁止开空
	CloseLong     bool              // whether to allow close long position 是否允许平多
	CloseShort    bool              // whether to allow close short position 是否允许平空
	ExgStopLoss   bool              // whether to allow stop losses in exchange side 是否允许交易所止损
	LongSLPrice   float64           // Default long stop loss price when opening a position 开仓时默认做多止损价格
	ShortSLPrice  float64           // Default short stop price when opening a position 开仓时默认做空止损价格
	ExgTakeProfit bool              // whether to allow take profit in exchange side  是否允许交易所止盈
	LongTPPrice   float64           // Default long take profit price when opening a position 开仓时默认做多止盈价格
	ShortTPPrice  float64           // Default short take profit price when opening a position 开仓时默认做空止盈价格
	IsWarmUp      bool              // whether in a preheating state 当前是否处于预热状态
	More          interface{}       // Additional information for policy customization 策略自定义的额外信息
}

func (*StratJob) CanOpen added in v0.1.11

func (s *StratJob) CanOpen(short bool) bool

***************************** StratJob的成员方法 ****************************************

func (*StratJob) CloseOrders

func (s *StratJob) CloseOrders(req *ExitReq) *errs.Error

func (*StratJob) GetAvgCostPrice added in v0.2.19

func (s *StratJob) GetAvgCostPrice(odList ...*ormo.InOutOrder) float64

func (*StratJob) GetOrderNum

func (s *StratJob) GetOrderNum(dirt float64) int

func (*StratJob) GetOrders

func (s *StratJob) GetOrders(dirt float64) []*ormo.InOutOrder

func (*StratJob) GetTmpEnv added in v0.2.19

func (s *StratJob) GetTmpEnv(stamp int64, o, h, l, c, v, i float64) *ta.BarEnv

func (*StratJob) InitBar

func (s *StratJob) InitBar(curOrders []*ormo.InOutOrder)

func (*StratJob) OpenOrder

func (s *StratJob) OpenOrder(req *EnterReq) *errs.Error

func (*StratJob) Position

func (s *StratJob) Position(dirt float64, enterTag string) float64

Position Retrieve the position size and return a multiple based on the benchmark amount. 获取仓位大小,返回基于基准金额的倍数。 side long/short/空 enterTag 入场标签,可为空

func (*StratJob) PositionAvgPrice added in v0.2.23

func (s *StratJob) PositionAvgPrice(dirt float64, enterTag string) float64

func (*StratJob) SetAllStopLoss

func (s *StratJob) SetAllStopLoss(dirt float64, args *ormo.ExitTrigger) *errs.Error

func (*StratJob) SetAllTakeProfit

func (s *StratJob) SetAllTakeProfit(dirt float64, args *ormo.ExitTrigger) *errs.Error

func (*StratJob) UpdateOrders added in v0.2.22

func (s *StratJob) UpdateOrders(curOrders []*ormo.InOutOrder)

type TradeStrat

type TradeStrat struct {
	Name            string
	Version         int
	WarmupNum       int
	OdBarMax        int     // default: 500. Estimated maximum bar hold number for orders (used to find unfinished positions for backtesting) 预计订单持仓最大bar数量(用于查找回测未完成持仓)
	MinTfScore      float64 // Minimum time cycle quality, default 0.8 最小时间周期质量,默认0.8
	WsSubs          map[string]string
	DrawDownExit    bool
	HedgeOff        bool    // turn off future hedge mode 关闭合约双向持仓
	BatchInOut      bool    // Whether to batch execute entry/exit 是否批量执行入场/出场
	BatchInfo       bool    // whether to perform batch processing after OninfoBar 是否对OnInfoBar后执行批量处理
	StakeRate       float64 // Relative basic amount billing rate 相对基础金额开单倍率
	StopLoss        float64 // Default stoploss without leverage 此策略默认止损比率,不带杠杆
	StopEnterBars   int
	OrderOnRotation string      // close/hold/open 品种切换时旧的job:立刻平仓,允许持有不许开单,允许开单和持有
	EachMaxLong     int         // max number of long open orders for one pair, -1 for disable, 0 for no limit
	EachMaxShort    int         // max number of short open orders for one pair, -1 for disable, 0 for no limit
	TimeFrames      string      // Comma separated time period 逗号分割的时间周期
	RunTimeFrames   []string    // Allow running time period, use global configuration when not provided 允许运行的时间周期,不提供时使用全局配置
	RefineTF        interface{} // specific the matching timeframe 指定撮合周期,如"5m", "3-6", 5
	Outputs         []string    // The content of the text file output by the strategy, where each string is one line 策略输出的文本文件内容,每个字符串是一行
	Policy          *config.RunPolicyConfig

	OnPairInfos         func(s *StratJob) []*PairSub
	OnSymbols           func(items []string) []string // return modified pairs
	OnStartUp           func(s *StratJob)
	OnBar               func(s *StratJob)
	OnInfoBar           func(s *StratJob, e *ta.BarEnv, pair, tf string)       // Other dependent bar data 其他依赖的bar数据
	OnWsTrades          func(s *StratJob, pair string, trades []*banexg.Trade) // Transaction by transaction data 逐笔交易数据
	OnWsDepth           func(s *StratJob, dep *banexg.OrderBook)               // Websocket order book websocket推送深度信息
	OnWsKline           func(s *StratJob, pair string, k *banexg.Kline)        // websocket real-time kline(may unfinish) Websocket推送的实时K线
	OnBatchJobs         func(jobs []*StratJob)                                 // All target jobs at the current time, used for bulk opening/closing of orders 当前时间所有标的job,用于批量开单/平仓
	OnBatchInfos        func(tf string, jobs map[string]*JobEnv)               // All info marked jobs at the current time, used for batch processing 当前时间所有info标的job,用于批量处理
	OnCheckExit         func(s *StratJob, od *ormo.InOutOrder) *ExitReq        // Custom order exit logic 自定义订单退出逻辑
	OnOrderChange       func(s *StratJob, od *ormo.InOutOrder, chgType int)    // Order update callback 订单更新回调
	GetDrawDownExitRate CalcDDExitRate                                         // Calculate the ratio of tracking profit taking, drawdown, and exit 计算跟踪止盈回撤退出的比率
	PickTimeFrame       PickTimeFrameFunc                                      // Choose a suitable trading cycle for the specified currency 为指定币选择适合的交易周期
	OnPostApi           FnOnPostApi                                            // callback for post api PostAPI时的策略回调
	OnShutDown          func(s *StratJob)                                      // Callback when the robot stops 机器人停止时回调
	OnStratExit         func()
}

func Get

func Get(pair, stratID string) *TradeStrat

func New

func (*TradeStrat) GetStakeAmount

func (s *TradeStrat) GetStakeAmount(j *StratJob) float64

func (*TradeStrat) WriteOutput added in v0.2.18

func (s *TradeStrat) WriteOutput(line string, date bool)

type Warms added in v0.1.11

type Warms map[string]map[string]int

func (Warms) Update added in v0.1.11

func (w Warms) Update(pair, tf string, num int)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL