strat

package
v0.1.23 Latest Latest
Warning

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

Go to latest
Published: Jan 3, 2025 License: AGPL-3.0 Imports: 20 Imported by: 3

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 订单退出完成
)
View Source
const (
	BatchTypeInOut = iota
	BatchTypeInfo
)

Variables

View Source
var (
	Versions    = make(map[string]int)                             // stratName: int 策略版本号
	Envs        = make(map[string]*ta.BarEnv)                      // pair_tf: BarEnv
	AccJobs     = make(map[string]map[string]map[string]*StratJob) // account: pair_tf: [stratName]StratJob
	AccInfoJobs = make(map[string]map[string]map[string]*StratJob) // account: pair_tf: [stratName]StratJob 额外订阅
	PairStrats  = make(map[string]map[string]*TradeStrat)          // pair:[stratName]TradeStrat 所有的订阅策略

	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 上次批量执行的时间戳,仅用于回测

)
View Source
var (
	StratMake = make(map[string]FuncMakeStrat) // 已加载的策略缓存
)

Functions

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 ExitStratJobs

func ExitStratJobs()

func FireOdChange

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

func GetInfoJobs

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

func GetJobs

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

GetJobs 返回:pair_tf: [stratName]StratJob

func GetStratPerf

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

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

返回对应关系:[(pair, timeframe, 预热数量, 策略列表), ...]

Types

type BatchMap

type BatchMap struct {
	Map     map[string]*BatchTask
	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 BatchTask

type BatchTask struct {
	Job  *StratJob
	Type int
}

type CalcDDExitRate

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

type EnterReq

type EnterReq struct {
	Tag             string  // Entry signal 入场信号
	StgyName        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 限价单入场价格,指定时订单将作为限价单提交
	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 止损原因
	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未成交则取消
}

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

type ExitReq

type ExitReq struct {
	Tag        string  // Exit signal 退出信号
	StgyName   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 是否强制退出
}

ExitReq 请求平仓

func (*ExitReq) Clone

func (q *ExitReq) Clone() *ExitReq

type FnOdChange

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

type FuncMakeStrat

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

type PairSub

type PairSub struct {
	Pair      string
	TimeFrame string
	WarmupNum int
}

type PickTimeFrameFunc

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

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位毫秒
	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

***************************** StagyJob的成员方法 ****************************************

func (*StratJob) CheckCustomExits

func (s *StratJob) CheckCustomExits(snap map[int64]*ormo.InOutSnap) ([]*ormo.InOutEdit, *errs.Error)

func (*StratJob) CloseOrders

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

func (*StratJob) GetOrderNum

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

func (*StratJob) GetOrders

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

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) SetAllStopLoss

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

func (*StratJob) SetAllTakeProfit

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

func (*StratJob) SnapOrderStates

func (s *StratJob) SnapOrderStates() map[int64]*ormo.InOutSnap

type TradeStrat

type TradeStrat struct {
	Name          string
	Version       int
	WarmupNum     int
	MinTfScore    float64 // Minimum time cycle quality, default 0.8 最小时间周期质量,默认0.8
	WatchBook     bool
	DrawDownExit  bool
	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 相对基础金额开单倍率
	StopEnterBars int
	EachMaxLong   int      // max number of long open orders for one pair, -1 for disable
	EachMaxShort  int      // max number of short open orders for one pair, -1 for disable
	AllowTFs      []string // Allow running time period, use global configuration when not provided 允许运行的时间周期,不提供时使用全局配置
	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
	OnStartUp           func(s *StratJob)
	OnBar               func(s *StratJob)
	OnInfoBar           func(s *StratJob, e *ta.BarEnv, pair, tf string)    // Other dependent bar data 其他依赖的bar数据
	OnTrades            func(s *StratJob, trades []*banexg.Trade)           // Transaction by transaction data 逐笔交易数据
	OnBatchJobs         func(jobs []*StratJob)                              // All target jobs at the current time, used for bulk opening/closing of orders 当前时间所有标的job,用于批量开单/平仓
	OnBatchInfos        func(jobs map[string]*StratJob)                     // 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 为指定币选择适合的交易周期
	OnShutDown          func(s *StratJob)                                   // Callback when the robot stops 机器人停止时回调
}

func Get

func Get(pair, stratID string) *TradeStrat

func New

func (*TradeStrat) GetStakeAmount

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

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