core

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: 19 Imported by: 7

Documentation

Index

Constants

View Source
const (
	MinStakeAmount = 5.5 // Minimum billing amount 最小开单金额
	StepTotal      = 1000
	KBatchSize     = 900 // The maximum number of K lines returned by the exchange in a single request. When 1000, the API weight is too large. 单次请求交易所最大返回K线数量, 1000时api权重过大
	DefaultDateFmt = "2006-01-02 15:04:05"
	DateFmt        = "2006-01-02"
	DelayBatchMS   = 3000  // Number of milliseconds to defer batch logic 批量逻辑推迟的毫秒数
	PrefMinRate    = 0.001 // Job minimum opening ratio, directly use MinStakeAmount to open a position job最低开仓比率,直接使用MinStakeAmount开仓
	AmtDust        = 1e-8
	DownKNumMin    = 100000 // 经测试,单个goroutine每分钟下载K线约100k个
)
View Source
const (
	RunModeLive     = "live"
	RunModeBackTest = "backtest"
	RunModeOther    = "other"
)
View Source
const (
	RunEnvProd   = "prod"
	RunEnvTest   = "test"
	RunEnvDryRun = "dry_run"
)
View Source
const (
	OdDirtShort = iota - 1
	OdDirtBoth
	OdDirtLong
)
View Source
const (
	WsSubKLine = "uohlcv"
	WsSubDepth = "depth"
	WsSubTrade = "trade"
)
View Source
const (
	EnterTagUnknown  = "unknown"
	EnterTagUserOpen = "user_open"
	EnterTagThird    = "third"
)
View Source
const (
	ExitTagUnknown      = "unknown"
	ExitTagCancel       = "cancel"
	ExitTagHedgeOff     = "hedge_off"
	ExitTagBotStop      = "bot_stop"
	ExitTagForceExit    = "force_exit"
	ExitTagNoMatch      = "no_match"
	ExitTagUserExit     = "user_exit"
	ExitTagThird        = "third"
	ExitTagCli          = "cli"
	ExitTagFatalErr     = "fatal_err"
	ExitTagPairDel      = "pair_del"
	ExitTagStopLoss     = "stop_loss"
	ExitTagSLTake       = "sl_take"
	ExitTagTrailingStop = "trailing_stop"
	ExitTagTakeProfit   = "take_profit"
	ExitTagDrawDown     = "draw_down"
	ExitTagDataStuck    = "data_stuck"
	ExitTagLiquidation  = "liquidation"
	ExitTagEnvEnd       = "env_end"
	ExitTagEntExp       = "ent_expire" // enter limit expired
	ExitTagExitDelay    = "exit_delay"
)
View Source
const (
	OrderTypeEmpty = iota
	OrderTypeMarket
	OrderTypeLimit
	OrderTypeLimitMaker
)
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 (
	AdjNone   = 1
	AdjFront  = 2
	AdjBehind = 3
)
View Source
const (
	VTypeUniform = iota // UNIFORM LINEAR DISTRIBUTION 均匀线性分布
	VTypeNorm           // Normal distribution, specifying mean and standard deviation 正态分布,指定均值和标准差
)
View Source
const (
	LowCostIgnore  = "ignore"
	LowCostKeepBig = "keepBig"
	LowCostKeepAll = "keepAll"
)
View Source
const (
	ErrRunTime        = -100
	ErrTimeout        = -101
	ErrCacheErr       = -102
	ErrMarshalFail    = -103
	ErrCompressFail   = -104
	ErrDeCompressFail = -105
	ErrDecryptFail    = -106
	ErrEncryptFail    = -107

	ErrBadConfig     = -110
	ErrInvalidPath   = -111
	ErrInvalidTF     = -112
	ErrInvalidSymbol = -113
	ErrInvalidBars   = -114
	ErrInvalidAddr   = -115
	ErrInvalidCost   = -116

	ErrDbConnFail        = -120
	ErrDbReadFail        = -121
	ErrDbExecFail        = -122
	ErrDbUniqueViolation = -123

	ErrLiquidation  = -130
	ErrLowFunds     = -131
	ErrLowSrcAmount = -132
	ErrExgNotInit   = -133

	ErrNetWriteFail = -140
	ErrNetReadFail  = -141
	ErrNetUnknown   = -142
	ErrNetTimeout   = -143
	ErrNetTemporary = -144
	ErrNetConnect   = -145

	ErrIOReadFail  = -150
	ErrIOWriteFail = -151
	ErrEOF         = -152

	ErrAuthFail      = -200
	ErrRemoteError   = -201
	ErrOutOfResource = -202
)
View Source
const (
	MSMinStamp = int64(1001894400000) // 2001-10-01T00:00:00.000Z
)

Variables

View Source
var (
	RunMode       string                               // live / backtest / other
	RunEnv        string                               // prod / test / dry_run
	StartAt       int64                                // start timestamp(13 digits) 启动时间,13位时间戳
	EnvReal       bool                                 // LiveMode && RunEnv != RunEnvDryRun submit the order to the exchange(run_env:prod/test) 提交订单到交易所run_env:prod/test
	LiveMode      bool                                 // Whether real-time mode(real trade/dry run) 是否是实时模式:实盘+模拟运行
	BackTestMode  bool                                 // 回测模式
	TFSecs        map[string]int                       // All time frames involved 所有涉及的时间周期
	ExgName       string                               // current exchange name 交易所名称
	Market        string                               // current market name 当前市场
	IsContract    bool                                 // Is the current market a contract market? 当前市场是否是合约市场, linear/inverse/option
	CheckWallets  bool                                 // Should the wallet be updated? 当前是否应该更新钱包
	ContractType  string                               // current contract type. 当前合约类型
	StgPairTfs    = make(map[string]map[string]string) // strategy:symbols:timeframe 策略: 标的: 周期
	Pairs         []string                             // All global symbols, in the order after the targets are refreshed 全局所有的标的,按标的刷新后的顺序
	PairsMap      = make(map[string]bool)              // All global symbols(bool value means whether allow open order) 全局所有的标的(值表示是否允许开单)
	BanPairsUntil = make(map[string]int64)             // symbols not allowed for trading before the specified timestamp 在指定时间戳前禁止交易的品种
	NoEnterUntil  = make(map[string]int64)             // account: The 13-digit timestamp before the account is allowed to trade 禁止开单的截止13位时间戳
	TfPairHits    = map[string]map[string]int{}        // tf[pair[hits]]The number of bars for each currency in each period within a period of time, used for timing output 一段时间内各周期各币种的bar数量,用于定时输出
	JobPerfs      = make(map[string]*JobPerf)          // stagy_pair_tf: JobPerf Record the billing amount ratio of the task. If the winning rate is low, the billing amount should be reduced. 记录任务的开单金额比率,胜率低的要减少开单金额
	StratPerfSta  = make(map[string]*PerfSta)          // stagy: Job任务状态
	LastBarMs     int64                                // The end time of the last bar received, a 13-digit timestamp 上次收到bar的结束时间,13位时间戳
	LastCopiedMs  int64                                // 上次收到爬虫进程推送k线的时间戳
	OdBooks       = map[string]*banexg.OrderBook{}     // Cache all order books received from crawler 缓存所有从爬虫收到的订单簿
	NumTaCache    = 1500                               // The number of historical values cached during indicator calculation, default 1500 指标计算时缓存的历史值数量,默认1500
	OrderMatchTfs = make(map[string]bool)              // Timeframes to match for order 订单撮合的周期

	ExitCalls []func() // CALLBACK TO STOP EXECUTION 停止执行的回调

	CPUProfile bool
	MemProfile bool
	NetDisable bool

	SimOrderMatch bool // 是否正处于回测订单撮合
	NewNumInSim   int  // 撮合时创建新订单的数量
	ParallelOnBar bool // 是否启用并行OnBar执行

	LockOdMatch sync.RWMutex

	ConcurNum = 2 // The maximum number of K-line tasks to be downloaded at the same time. If it is too high, a 429 current limit will occur. 最大同时下载K线任务数,过大会出现429限流
	Version   = "v0.2.30"
	UIVersion = "v0.2.30"
	SysLang   string // language code for current system 当前系统语言设置
	DevDbPath string
)
View Source
var (
	TfPairHitsLock deadlock.RWMutex
	Ctx            context.Context // Used to stop all goroutines at the same time 用于全部goroutine同时停止
	StopAll        func()          // Stop all robot threads 停止全部机器人线程
	BotRunning     bool            // Is the robot running? 机器人是否正在运行
)
View Source
var (
	Cache *ristretto.Cache
)
View Source
var LowCostVals = map[string]int{
	LowCostIgnore:  0,
	LowCostKeepBig: 1,
	LowCostKeepAll: 2,
}
View Source
var OdTypeMap = map[int]string{
	OrderTypeEmpty:      "empty",
	OrderTypeMarket:     "market",
	OrderTypeLimit:      "limit",
	OrderTypeLimitMaker: "limit_maker",
}

Functions

func CountDigit added in v0.2.4

func CountDigit(text string) int

func DumpPerfs

func DumpPerfs(outDir string)

func GetCacheVal

func GetCacheVal[T any](key interface{}, defVal T) T

func GetOdBook added in v0.2.23

func GetOdBook(pair string) (*banexg.OrderBook, bool)

func GroupByPairQuotes

func GroupByPairQuotes(items map[string][]string, doSort bool) string

GroupByPairQuotes format `[key]:pairs...` as below 【key】 Quote: Base1 Base2 ...

func IsFiat

func IsFiat(code string) bool

IsFiat Is it legal tender? 是否是法币

func IsLimitOrder

func IsLimitOrder(t int) bool

func KeyStratPairTf

func KeyStratPairTf(stagy, pair, tf string) string

func MarshalYaml added in v0.1.18

func MarshalYaml(v any) ([]byte, error)

func RunExitCalls

func RunExitCalls()

func SetOdBook added in v0.2.23

func SetOdBook(pair string, book *banexg.OrderBook)

func SetRunEnv

func SetRunEnv(env string)

func SetRunMode

func SetRunMode(mode string)

func Setup

func Setup() *errs.Error

func Sleep

func Sleep(d time.Duration) bool

func SplitDigits added in v0.2.4

func SplitDigits(s string) []string

func SplitSymbol

func SplitSymbol(pair string) (string, string, string, string)

SplitSymbol return Base,Quote,Settle,Identifier

Types

type ApiClient added in v0.2.16

type ApiClient struct {
	IP        string
	UserAgent string
	User      string
	AccRoles  map[string]string
	Token     string
}

type DownRange

type DownRange struct {
	Start   int64
	End     int64
	Reverse bool // Indicates whether downloading should be done from back to front 指示是否应该从后往前下载
}

type Ema added in v0.2.9

type Ema struct {
	Alpha float64
	Val   float64
	Age   int
}

func NewEMA added in v0.2.9

func NewEMA(alpha float64) *Ema

func (*Ema) Reset added in v0.2.9

func (e *Ema) Reset()

func (*Ema) Update added in v0.2.9

func (e *Ema) Update(val float64) float64

type Int64Flt added in v0.2.23

type Int64Flt struct {
	Int int64
	Val float64
}

type JobPerf

type JobPerf struct {
	Num       int
	TotProfit float64 // TOTAL PROFIT 总利润
	Score     float64 // Order opening ratio, less than 1 means reducing the order opening 开单倍率,小于1表示减少开单
}

func (*JobPerf) GetAmount

func (p *JobPerf) GetAmount(amount float64) float64

type NumSet added in v0.2.9

type NumSet struct {
	Stamp     int64
	AlignUnit int64
	Data      map[string]float64
	CallBack  func(int64, map[string]float64)
	Lock      deadlock.Mutex
}

NumSet 时间间隔内数据收集

func NewNumSet added in v0.2.9

func NewNumSet(alignUnit int64, callback func(int64, map[string]float64)) *NumSet

func (*NumSet) Update added in v0.2.9

func (ns *NumSet) Update(stamp int64, key string, val float64)

type Param

type Param struct {
	Name  string
	VType int // VTypeNorm / VTypeUniform
	Min   float64
	Max   float64
	Mean  float64
	IsInt bool
	Rate  float64 // Valid for normal distribution, defaults to 1. The larger the value, the more the random values tend to be Mean. 正态分布时有效,默认1,值越大,随机值越趋向于Mean
	// contains filtered or unexported fields
}

func PNorm

func PNorm(min, max float64) *Param

func PNormF

func PNormF(min, max, mean, rate float64) *Param

func PUniform

func PUniform(min, max float64) *Param

func (*Param) OptSpace

func (p *Param) OptSpace() (float64, float64)

OptSpace Returns a uniformly distributed interval for use in hyperparameter searches 返回一个均匀分布的区间,用于超参数搜索

func (*Param) ToRegular

func (p *Param) ToRegular(x float64) (float64, bool)

ToRegular Hyperparameter values that map a uniform distribution to a normal distribution 将均匀分布映射为正态分布的超参数值

type PerfSta

type PerfSta struct {
	OdNum    int         `yaml:"od_num" mapstructure:"od_num"`
	LastGpAt int         `yaml:"last_gp_at" mapstructure:"last_gp_at"` // The number of orders for the last time clustering was performed 上次执行聚类的订单数量
	Splits   *[4]float64 `yaml:"splits" mapstructure:"splits"`
	Delta    float64     `yaml:"delta" mapstructure:"delta"` // Multiplier before logarithmizing TotProfit 对TotProfit进行对数处理前的乘数
}

PerfSta Statistics of a certain strategy for all targets 某个策略针对所有标的的统计信息

func GetPerfSta

func GetPerfSta(stagy string) *PerfSta

func (*PerfSta) FindGID

func (p *PerfSta) FindGID(val float64) int

func (*PerfSta) Log2

func (p *PerfSta) Log2(profit float64) float64

type PrgCB added in v0.1.12

type PrgCB func(done int, total int)

type StrAny added in v0.1.33

type StrAny struct {
	Str string `json:"str"`
	Val any    `json:"val"`
}

type StrFloat added in v0.2.23

type StrFloat struct {
	Str string
	Val float64
}

type StrInt64 added in v0.1.29

type StrInt64 struct {
	Str string `json:"str"`
	Int int64  `json:"int"`
}

type StrVal

type StrVal[T comparable] struct {
	Str string `json:"str"`
	Val T      `json:"val"`
}

type TfScore

type TfScore struct {
	TF    string
	Score float64
}

type TimeValueRange added in v0.2.24

type TimeValueRange struct {
	StartMS    int64   `json:"startMS"`
	StopMS     int64   `json:"stopMS"`
	StartValue float64 `json:"startValue"`
	StopValue  float64 `json:"stopValue"`
	ValueChg   float64 `json:"-"`
}

func (*TimeValueRange) SetEnd added in v0.2.24

func (t *TimeValueRange) SetEnd(timeMS int64, val float64)

Jump to

Keyboard shortcuts

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