core

package
v0.1.16 Latest Latest
Warning

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

Go to latest
Published: Dec 30, 2024 License: AGPL-3.0 Imports: 19 Imported by: 3

Documentation

Index

Constants

View Source
const (
	MinStakeAmount = 10 // 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"
	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 (
	EnterTagUnknown  = "unknown"
	EnterTagUserOpen = "user_open"
	EnterTagThird    = "third"
)
View Source
const (
	ExitTagUnknown     = "unknown"
	ExitTagCancel      = "cancel"
	ExitTagBotStop     = "bot_stop"
	ExitTagForceExit   = "force_exit"
	ExitTagUserExit    = "user_exit"
	ExitTagThird       = "third"
	ExitTagFatalErr    = "fatal_err"
	ExitTagPairDel     = "pair_del"
	ExitTagStopLoss    = "stop_loss"
	ExitTagSLTake      = "sl_take"
	ExitTagTakeProfit  = "take_profit"
	ExitTagDrawDown    = "draw_down"
	ExitTagDataStuck   = "data_stuck"
	ExitTagLiquidation = "liquidation"
	ExitTagEnvEnd      = "env_end"
	ExitTagEntExp      = "ent_exp" // enter limit expired
)
View Source
const (
	OrderTypeEmpty = iota
	OrderTypeMarket
	OrderTypeLimit
	OrderTypeLimitMaker
)
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 (
	ErrBadConfig = -1*iota - 100
	ErrInvalidPath
	ErrIOReadFail
	ErrIOWriteFail
	ErrDbConnFail
	ErrDbReadFail
	ErrDbExecFail
	ErrDbUniqueViolation
	ErrLiquidation
	ErrLowFunds
	ErrLowSrcAmount
	ErrInvalidCost
	ErrExgNotInit
	ErrCacheErr
	ErrInvalidTF
	ErrInvalidSymbol
	ErrInvalidBars
	ErrInvalidAddr
	ErrRunTime
	ErrMarshalFail
	ErrCompressFail
	ErrDeCompressFail
	ErrTimeout
	ErrEOF

	ErrNetWriteFail
	ErrNetReadFail
	ErrNetUnknown
	ErrNetTimeout
	ErrNetTemporary
	ErrNetConnect
)
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                                 // Whether to actually submit the order to the exchange(run_env:prod/test) 是否是提交到交易所真实订单模式run_env:prod/test
	LiveMode      bool                                 // Whether real-time mode(real trade/dry run) 是否是实时模式:实盘+模拟运行
	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 全局所有的标的
	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位时间戳
	BookPairs     = make(map[string]bool)              // Monitor the currency of the trading pair 监听交易对的币种
	PairCopiedMs  = map[string][2]int64{}              // The latest time that all targets received K lines from the crawler, as well as the waiting interval, are used to determine whether there are any that have not been received for a long time. 所有标的从爬虫收到K线的最新时间,以及等待间隔,用于判断是否有长期未收到的。
	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位时间戳
	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
	Cron          = cron.New(cron.WithSeconds())       // Use cron to run tasks regularly 使用cron定时运行任务

	ExitCalls []func()  // CALLBACK TO STOP EXECUTION 停止执行的回调
	MemOut    io.Writer // Output memory profile 进行内存profile的输出

	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       = "0.1.16"
	UIVersion     = "0.1.15"
	LogFile       string
	DevDbPath     string
	HeavyTask     string  // 后台排他性耗时任务名称
	HeavyProgress float64 // 后台排他性耗时任务进度

	HeavyTriggers = make(map[string]PrgCB)
)
View Source
var (
	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 ErrCodeNames = map[int]string{
	ErrBadConfig:         "BadConfig",
	ErrInvalidPath:       "InvalidPath",
	ErrIOReadFail:        "IOReadFail",
	ErrIOWriteFail:       "IOWriteFail",
	ErrDbConnFail:        "DbConnFail",
	ErrDbReadFail:        "DbReadFail",
	ErrDbExecFail:        "DbExecFail",
	ErrDbUniqueViolation: "DbUniqueViolation",
	ErrLiquidation:       "Liquidation",
	ErrLowFunds:          "LowFunds",
	ErrLowSrcAmount:      "LowSrcAmount",
	ErrInvalidCost:       "InvalidCost",
	ErrExgNotInit:        "ExgNotInit",
	ErrCacheErr:          "CacheErr",
	ErrInvalidTF:         "InvalidTF",
	ErrInvalidSymbol:     "InvalidSymbol",
	ErrInvalidBars:       "InvalidBars",
	ErrInvalidAddr:       "InvalidAddr",
	ErrRunTime:           "RunTime",
	ErrMarshalFail:       "MarshalFail",
	ErrCompressFail:      "CompressFail",
	ErrDeCompressFail:    "DeCompressFail",
	ErrTimeout:           "Timeout",
	ErrEOF:               "EOF",
	ErrNetWriteFail:      "NetWriteFail",
	ErrNetReadFail:       "NetReadFail",
	ErrNetUnknown:        "NetUnknown",
	ErrNetTimeout:        "NetTimeout",
	ErrNetTemporary:      "NetTemporary",
	ErrNetConnect:        "NetConnect",
}

Functions

func DumpPerfs

func DumpPerfs(outDir string)

func GetCacheVal

func GetCacheVal[T any](key string, defVal T) T

func GetPrice

func GetPrice(symbol string) float64

func GetPriceSafe

func GetPriceSafe(symbol string) float64

func GroupByPairQuotes

func GroupByPairQuotes(items map[string][]string) 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 IsMaker

func IsMaker(pair, side string, price float64) bool

func IsPriceEmpty

func IsPriceEmpty() bool

func KeyStratPairTf

func KeyStratPairTf(stagy, pair, tf string) string

func PrintStratGroups

func PrintStratGroups()

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

func RunExitCalls

func RunExitCalls()

func SetBarPrice

func SetBarPrice(pair string, price float64)

func SetHeavyProgress added in v0.1.12

func SetHeavyProgress(done int, total int)

func SetPairMs

func SetPairMs(pair string, barMS, waitMS int64)

SetPairMs update LastBarMs/wait interval from spider 更新bot端从爬虫收到的标的最新时间和等待间隔

func SetPrice

func SetPrice(pair string, price float64)

func SetPrices

func SetPrices(data map[string]float64)

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 SnapMem

func SnapMem(name string)

func SplitSymbol

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

SplitSymbol return Base,Quote,Settle,Identifier

Types

type DownRange

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

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 Param

type Param struct {
	Name  string
	VType int
	Min   float64
	Max   float64
	Mean  float64
	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 StrVal

type StrVal struct {
	Str string
	Val float64
}

type TfScore

type TfScore struct {
	TF    string
	Score float64
}

Jump to

Keyboard shortcuts

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