biz

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Jul 19, 2026 License: AGPL-3.0 Imports: 49 Imported by: 2

Documentation

Index

Constants

View Source
const (
	RemoteSourceWeb      = "web"
	RemoteSourceTelegram = "telegram"
	RemoteSourceCLI      = "cli"

	RemoteActionCloseOrder    = "close_order"
	RemoteActionTradingSwitch = "trading_switch"
)
View Source
const (
	AmtDust = 1e-8
)

Variables

View Source
var AInfer_ServiceDesc = grpc.ServiceDesc{
	ServiceName: "AInfer",
	HandlerType: (*AInferServer)(nil),
	Methods: []grpc.MethodDesc{
		{
			MethodName: "Trend",
			Handler:    _AInfer_Trend_Handler,
		},
		{
			MethodName: "Trade",
			Handler:    _AInfer_Trade_Handler,
		},
	},
	Streams:  []grpc.StreamDesc{},
	Metadata: "aifea.proto",
}

AInfer_ServiceDesc is the grpc.ServiceDesc for AInfer service. It's only intended for direct use with grpc.RegisterService, and not to be introspected or modified (even as a copy)

View Source
var FeaFeeder_ServiceDesc = grpc.ServiceDesc{
	ServiceName: "FeaFeeder",
	HandlerType: (*FeaFeederServer)(nil),
	Methods:     []grpc.MethodDesc{},
	Streams: []grpc.StreamDesc{
		{
			StreamName:    "SubFeatures",
			Handler:       _FeaFeeder_SubFeatures_Handler,
			ServerStreams: true,
		},
	},
	Metadata: "aifea.proto",
}

FeaFeeder_ServiceDesc is the grpc.ServiceDesc for FeaFeeder service. It's only intended for direct use with grpc.RegisterService, and not to be introspected or modified (even as a copy)

View Source
var (
	FeaGenerators = map[string]FnFeaStream{} // Task feature generation function registration for SubFeatures. 任务特征生成函数注册
)
View Source
var File_aifea_proto protoreflect.FileDescriptor

Functions

func AddBatchJob

func AddBatchJob(account, tf string, job *strat.StratJob, infoEnv *ta.BarEnv)

AddBatchJob Add batch entry tasks. Even if the job has no entry tasks, this method should be called to postpone the entry time TFEnterMS 添加批量入场任务。 即使job没有入场任务,也应该调用此方法,用于推迟入场时间TFEnterMS

func AggBigKlines added in v0.2.4

func AggBigKlines(args *config.CmdArgs) *errs.Error

func CalcCorrelation

func CalcCorrelation(args *config.CmdArgs) *errs.Error

CalcCorrelation calculate correlation for pairs; generate csv or images

func CallLocalLiveOdMgrsData added in v0.4.0

func CallLocalLiveOdMgrsData(msg *data.SeriesMsg, rows []*orm.DataSeries) *errs.Error

func CallLocalLiveOdMgrsSeries added in v0.4.0

func CallLocalLiveOdMgrsSeries(msg *data.SeriesMsg, rows []*orm.DataSeries) *errs.Error

func CleanUpOdMgr

func CleanUpOdMgr() *errs.Error

func CloseAccOrders added in v0.2.12

func CloseAccOrders(acc string, odList []*ormo.InOutOrder, req *strat.ExitReq) (int, int, *errs.Error)

func DownExgOrders added in v0.2.9

func DownExgOrders(args []string) error

func EnsurePricesLoaded added in v0.2.17

func EnsurePricesLoaded()

func ExportAdjFactors

func ExportAdjFactors(args *config.CmdArgs) *errs.Error

func ExportKlines

func ExportKlines(args *config.CmdArgs, prg utils.PrgCB) *errs.Error

func FindOpenOrders added in v0.4.0

func FindOpenOrders(account string, orderID int64) ([]*ormo.InOutOrder, *errs.Error)

func GetAllOdMgr added in v0.1.15

func GetAllOdMgr() map[string]IOrderMgr

func InitDataDir added in v0.1.20

func InitDataDir() *errs.Error

func InitFakeWallets

func InitFakeWallets(symbols ...string)

InitFakeWallets Initialize a wallet object from a configuration file 从配置文件初始化一个钱包对象

func InitLiveOrderMgr

func InitLiveOrderMgr(callBack func(od *ormo.InOutOrder, isEnter bool))

func InitLocalLiveOrderMgr added in v0.2.21

func InitLocalLiveOrderMgr(callBack FnOdCb, showLog bool)

func InitLocalOrderMgr

func InitLocalOrderMgr(callBack FnOdCb, showLog bool)

func InitOdSubs

func InitOdSubs()

InitOdSubs 为所有策略OnOrderChange注册订单事件监听。

只需在LoadStratJobs后调用一次,交易的Accounts不变就始终生效

func InitTelegramOrderManager added in v0.2.23

func InitTelegramOrderManager()

InitTelegramOrderManager 初始化 Telegram 订单管理器

func LoadCalendars

func LoadCalendars(args *config.CmdArgs) *errs.Error

func LoadZipSeries added in v0.4.0

func LoadZipSeries(inPath string, fid int, file *zip.File, arg interface{}) *errs.Error

func MakeCheckFatalStop

func MakeCheckFatalStop(maxIntv int) func()

CheckFatalStop Check if the global stop loss is triggered. This method should be called regularly via cron 检查是否触发全局止损,此方法应通过cron定期调用

func NewDownExgOrdersCommand added in v0.4.1

func NewDownExgOrdersCommand() *cobra.Command

func PurgeKlines

func PurgeKlines(args *config.CmdArgs) *errs.Error

func RefreshJobs added in v0.1.29

func RefreshJobs(pairs []string, pairTfScores map[string]map[string]float64, showLog bool, pBar *utils.StagedPrg) (map[string]map[string]int, *errs.Error)

func RefreshPairs added in v0.1.29

func RefreshPairs(showLog bool, timeMS int64, pBar *utils.StagedPrg) ([]string, map[string]map[string]float64, *errs.Error)

func RegisterAInferServer

func RegisterAInferServer(s grpc.ServiceRegistrar, srv AInferServer)

func RegisterFeaFeederServer

func RegisterFeaFeederServer(s grpc.ServiceRegistrar, srv FeaFeederServer)

func ResetVars

func ResetVars()

func RestoreDryRunWalletSnapshot added in v0.2.29

func RestoreDryRunWalletSnapshot(account string) bool

func RestoreVars added in v0.1.29

func RestoreVars(backup *VarsBackup)

RestoreVars 从备份中恢复所有全局变量

func RunDataServer

func RunDataServer(args *config.CmdArgs) *errs.Error

func RunHistSeries added in v0.4.0

func RunHistSeries(args *RunHistSeriesArgs) *errs.Error

RunHistSeries Replay OHLCV-shaped DataSeries within a specified time range for multiple symbols, supporting multiple timeFrames and returning n future min-timeframe events. 对多个品种回放指定时间范围的 DataSeries,支持多周期,支持返回未来 n 个最小周期事件。

func SaveDryRunWalletSnapshot added in v0.2.29

func SaveDryRunWalletSnapshot(account string, timeMS int64, force bool) *errs.Error

func SaveLiveWalletSnapshot added in v0.2.29

func SaveLiveWalletSnapshot(account string, timeMS int64, force bool) *errs.Error

func SaveLiveWalletSnapshots added in v0.2.29

func SaveLiveWalletSnapshots(force bool)

func SetupComs

func SetupComs(args *config.CmdArgs) *errs.Error

func SetupComsExg added in v0.1.12

func SetupComsExg(args *config.CmdArgs) *errs.Error

func StartLiveOdMgr

func StartLiveOdMgr()

func StartLiveWalletSnapshots added in v0.2.29

func StartLiveWalletSnapshots()

func TestKLineConsistency added in v0.2.18

func TestKLineConsistency(args []string) error

TestKLineConsistency checks the consistency of K-line data in dump files It verifies: 1. Each K-line's time is within 2 minutes of its row time 2. The interval between consecutive K-lines matches the timeframe 3. Reports any missing K-lines

func TryFireBatches

func TryFireBatches(currMS int64, isWarmUp bool) int

func UpdateWalletByBalances added in v0.2.1

func UpdateWalletByBalances(wallets *BanWallets, item *banexg.Balances)

func VerifyTriggerOds

func VerifyTriggerOds()

VerifyTriggerOds Check if there is a triggerable limit order. If so, submit it to the exchange and it should be called every minute. Only for real trading 检查是否有可触发的限价单,如有,提交到交易所,应被每分钟调用 仅实盘使用

func WatchLiveBalances

func WatchLiveBalances()

WatchLiveBalances 币安推送的余额经常不够及时导致不准确,推荐定期主动拉取更新

Types

type AInferClient

type AInferClient interface {
	Trend(ctx context.Context, in *ArrMap, opts ...grpc.CallOption) (*ArrMap, error)
	Trade(ctx context.Context, in *ArrMap, opts ...grpc.CallOption) (*ArrMap, error)
}

AInferClient is the client API for AInfer service.

For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.

func NewAInferClient

func NewAInferClient(cc grpc.ClientConnInterface) AInferClient

type AInferServer

type AInferServer interface {
	Trend(context.Context, *ArrMap) (*ArrMap, error)
	Trade(context.Context, *ArrMap) (*ArrMap, error)
	// contains filtered or unexported methods
}

AInferServer is the server API for AInfer service. All implementations must embed UnimplementedAInferServer for forward compatibility

type ArrMap

type ArrMap struct {
	Codes []string           `protobuf:"bytes,1,rep,name=codes,proto3" json:"codes,omitempty"`
	Mats  map[string]*NumArr `` /* 149-byte string literal not displayed */
	// contains filtered or unexported fields
}

func (*ArrMap) Descriptor deprecated

func (*ArrMap) Descriptor() ([]byte, []int)

Deprecated: Use ArrMap.ProtoReflect.Descriptor instead.

func (*ArrMap) GetCodes

func (x *ArrMap) GetCodes() []string

func (*ArrMap) GetMats

func (x *ArrMap) GetMats() map[string]*NumArr

func (*ArrMap) ProtoMessage

func (*ArrMap) ProtoMessage()

func (*ArrMap) ProtoReflect

func (x *ArrMap) ProtoReflect() protoreflect.Message

func (*ArrMap) Reset

func (x *ArrMap) Reset()

func (*ArrMap) String

func (x *ArrMap) String() string

type BanWallets

type BanWallets struct {
	Items   map[string]*ItemWallet
	Account string
	IsWatch bool
}

func GetWallets

func GetWallets(account string) *BanWallets

func (*BanWallets) AvaLegal

func (w *BanWallets) AvaLegal(symbols []string) float64

func (*BanWallets) Cancel

func (w *BanWallets) Cancel(odKey string, symbol string, addAmount float64, fromPending bool)

Cancel Unlock the quantity of currency (frozens/pendings) and add it to available again 取消对币种的数量锁定(frozens/pendings),重新加到available上

func (*BanWallets) ConfirmOdEnter

func (w *BanWallets) ConfirmOdEnter(od *ormo.InOutOrder, enterPrice float64)

func (*BanWallets) ConfirmOdExit

func (w *BanWallets) ConfirmOdExit(od *ormo.InOutOrder, exitPrice float64)

func (*BanWallets) ConfirmPending

func (w *BanWallets) ConfirmPending(odKey string, srcKey string, srcAmount float64, tgtKey string, tgtAmount float64, toFrozen bool) bool

ConfirmPending Confirm deduction from src and add to tgt's balance 从src中确认扣除,添加到tgt的余额中

func (*BanWallets) CostAva

func (w *BanWallets) CostAva(odKey string, symbol string, amount float64, negative bool, minRate float64) (float64, *errs.Error)

CostAva Deducted from the available balance of a certain coin and added to pending, used only for backtesting 从某个币的可用余额中扣除,添加到pending中,仅用于回测 negative : Whether to allow negative balances (used for short orders) 是否允许负数余额(空单用到) minRate: Minimum order opening ratio 最小开单倍率 return: Actual amount deducted, errs.Error

func (*BanWallets) CostFrozen

func (w *BanWallets) CostFrozen(odKey string, symbol string, amount float64) float64

CostFrozen This method is not used for contracts Deduct from frozen, if not enough, deduct the remainder from available After deduction, add to pending

此方法不用于合约
从frozen中扣除,如果不够,从available扣除剩余部分
扣除后,添加到pending中

func (*BanWallets) CutPart

func (w *BanWallets) CutPart(srcKey string, tgtKey string, symbol string, rate float64)

func (*BanWallets) DumpAvas

func (w *BanWallets) DumpAvas() map[string]float64

func (*BanWallets) EnterOd

func (w *BanWallets) EnterOd(od *ormo.InOutOrder) (float64, *errs.Error)

EnterOd Both real offer and simulation are executed, which can prevent excessive consumption during real offer.

If the balance is insufficient, an exception will be issued Need to call confirm_od_enter to confirm. You can also call cancel to cancel 实盘和模拟都执行,实盘时可防止过度消费

如果余额不足,会发出异常
需要调用confirm_od_enter确认。也可调用cancel取消

func (*BanWallets) ExitOd

func (w *BanWallets) ExitOd(od *ormo.InOutOrder, baseAmount float64)

func (*BanWallets) FiatValue

func (w *BanWallets) FiatValue(withUpol bool, symbols ...string) float64

FiatValue Returns the value of the given currency against fiat currency. Returns all currencies if empty 返回给定币种的对法币价值。为空时返回所有币种

func (*BanWallets) Get

func (w *BanWallets) Get(code string) *ItemWallet

func (*BanWallets) GetAmountByLegal

func (w *BanWallets) GetAmountByLegal(symbol string, legalCost float64) float64

func (*BanWallets) GetWithdrawLegal

func (w *BanWallets) GetWithdrawLegal(symbols []string) float64

func (*BanWallets) LegalValue added in v0.2.29

func (w *BanWallets) LegalValue(kind LegalValueKind, symbols []string, withUPol bool) float64

func (*BanWallets) SetWallets

func (w *BanWallets) SetWallets(data map[string]float64)

func (*BanWallets) TotalLegal

func (w *BanWallets) TotalLegal(symbols []string, withUPol bool) float64

func (*BanWallets) TryUpdateStakePctAmt

func (w *BanWallets) TryUpdateStakePctAmt()

TryUpdateStakePctAmt Update single billing amount Backtesting mode should call this method when the order is closed 更新单笔开单金额 回测模式应在订单平仓时调用此方法

func (*BanWallets) UnrealizedPOLLegal

func (w *BanWallets) UnrealizedPOLLegal(symbols []string) float64

func (*BanWallets) UpdateOds

func (w *BanWallets) UpdateOds(odList []*ormo.InOutOrder, currency string) *errs.Error

UpdateOds Update order. Currently only for futures contract orders, the margin ratio of contract orders needs to be updated.

Incoming orders must be for the same fixed currency. Margin ratio: (position notional value * maintenance margin ratio - maintenance margin quick calculation) / (wallet balance + unrealized profit and loss) Wallet balance = initial net transfer balance (including initial margin) + realized profit and loss + net funding fee - handling fee 更新订单。目前只针对期货合约订单,需要更新合约订单的保证金比率。

传入的订单必然都是同一个定价币的订单
保证金比率: (仓位名义价值 * 维持保证金率 - 维持保证金速算数) / (钱包余额 + 未实现盈亏)
钱包余额 = 初始净划入余额(含初始保证金) + 已实现盈亏 + 净资金费用 - 手续费

func (*BanWallets) WithdrawLegal

func (w *BanWallets) WithdrawLegal(amount float64, symbols []string)

WithdrawLegal Withdraw cash from the balance, thereby prohibiting a portion of the money from being billed. 从余额提现,从而禁止一部分钱开单。

type DataServer

type DataServer struct {
	*UnimplementedFeaFeederServer
	// contains filtered or unexported fields
}

func (*DataServer) SubFeatures

func (s *DataServer) SubFeatures(req *SubReq, rsp FeaFeeder_SubFeaturesServer) error

SubFeatures Subscribe to feature data stream You need to register the task feature data stream generation function in FeaGenerators to initiate grpc request normally. 订阅特征数据流 需要自行注册任务特征数据流生成函数到 FeaGenerators 中,才能正常发起grpc请求

type ExgOrderSet added in v0.2.9

type ExgOrderSet struct {
	Account string
	Name    string
	Market  string
	Data    map[string]*PairOrders
	// contains filtered or unexported fields
}

func GetExgOrderSet added in v0.2.9

func GetExgOrderSet(account, exgName, market string) (*ExgOrderSet, *errs.Error)

func (*ExgOrderSet) Download added in v0.2.9

func (s *ExgOrderSet) Download(startMS, endMS int64, pairs []string, force bool) *errs.Error

Download 下载指定时间范围内的订单记录

func (*ExgOrderSet) Get added in v0.2.9

func (s *ExgOrderSet) Get(startMS, endMS int64, pairs []string, botName string) (map[string][]*banexg.Order, *errs.Error)

Get 获取指定时间范围和交易对的订单记录

type FeaFeederClient

type FeaFeederClient interface {
	SubFeatures(ctx context.Context, in *SubReq, opts ...grpc.CallOption) (FeaFeeder_SubFeaturesClient, error)
}

FeaFeederClient is the client API for FeaFeeder service.

For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.

func NewFeaFeederClient

func NewFeaFeederClient(cc grpc.ClientConnInterface) FeaFeederClient

type FeaFeederServer

type FeaFeederServer interface {
	SubFeatures(*SubReq, FeaFeeder_SubFeaturesServer) error
	// contains filtered or unexported methods
}

FeaFeederServer is the server API for FeaFeeder service. All implementations must embed UnimplementedFeaFeederServer for forward compatibility

type FeaFeeder_SubFeaturesClient

type FeaFeeder_SubFeaturesClient interface {
	Recv() (*ArrMap, error)
	grpc.ClientStream
}

type FeaFeeder_SubFeaturesServer

type FeaFeeder_SubFeaturesServer interface {
	Send(*ArrMap) error
	grpc.ServerStream
}

type FnFeaStream

type FnFeaStream = func(exsList []*orm.ExSymbol, req *SubReq, rsp FeaFeeder_SubFeaturesServer) error

type FnOdCb added in v0.1.29

type FnOdCb = func(od *ormo.InOutOrder, isEnter bool)

type FuncApplyMyTrade

type FuncApplyMyTrade = func(od *ormo.InOutOrder, subOd *ormo.ExOrder, trade *banexg.MyTrade) *errs.Error

type FuncHandleIOrder

type FuncHandleIOrder = func(order *ormo.InOutOrder) *errs.Error

type FuncHandleMyOrder

type FuncHandleMyOrder = func(trade *banexg.Order) bool

type IOrderMgr

type IOrderMgr interface {
	ProcessOrders(job *strat.StratJob) ([]*ormo.InOutOrder, []*ormo.InOutOrder, *errs.Error)
	EditOrder(od *ormo.InOutOrder, action string)
	RelayOrders(orders []*ormo.InOutOrder) *errs.Error
	EnterOrder(exs *orm.ExSymbol, tf string, req *strat.EnterReq) (*ormo.InOutOrder, *errs.Error)
	ExitOpenOrders(pairs string, req *strat.ExitReq) ([]*ormo.InOutOrder, *errs.Error)
	ExitOrder(od *ormo.InOutOrder, req *strat.ExitReq) (*ormo.InOutOrder, *errs.Error)
	UpdateByDataSeries(allOpens []*ormo.InOutOrder, evt *orm.DataSeries) *errs.Error
	ExitAndFill(orders []*ormo.InOutOrder, req *strat.ExitReq) *errs.Error
	OnEnvEnd(evt *orm.DataSeries) *errs.Error
	CleanUp() *errs.Error
}

func GetOdMgr

func GetOdMgr(account string) IOrderMgr

type IOrderMgrLive

type IOrderMgrLive interface {
	IOrderMgr
	SyncExgOrders() ([]*ormo.InOutOrder, []*ormo.InOutOrder, []*ormo.InOutOrder, *errs.Error)
	WatchMyTrades()
	TrialUnMatchesForever()
	ConsumeOrderQueue()
}

type ItemWallet

type ItemWallet struct {
	Coin          string             // Coin code, not pair 币代码,非交易对
	Available     float64            // Available balance 可用余额
	Pendings      map[string]float64 // Lock the amount when buying or selling. The key can be the order id. 买入卖出时锁定金额,键可以是订单id
	Frozens       map[string]float64 // Long-term frozen amount for short orders, etc. The key can be the order ID. 空单等长期冻结金额,键可以是订单id
	UnrealizedPOL float64            // The public unrealized profit and loss of this currency, used by the contract, can be deducted from the margin of other orders. Recalculated every bar. 此币的公共未实现盈亏,合约用到,可抵扣其他订单保证金占用。每个bar重新计算
	UsedUPol      float64            // Used unrealized profit and loss (used as margin for other orders). 已占用的未实现盈亏(用作其他订单的保证金)
	Withdraw      float64            // Cash withdrawal from balance will not be used for trading. 从余额提现的,不会用于交易
	// contains filtered or unexported fields
}

func (*ItemWallet) FiatValue

func (iw *ItemWallet) FiatValue(withUpol bool) float64

FiatValue Get the fiat currency value of this wallet 获取此钱包的法币价值

func (*ItemWallet) Reset

func (iw *ItemWallet) Reset()

func (*ItemWallet) SetFrozen

func (iw *ItemWallet) SetFrozen(odKey string, amount float64, withAvailable bool) *errs.Error

SetFrozen Set the frozen amount to a fixed value. Can be synchronized from balance or pending.

Any shortage is taken from the other side, and excess is added to the other side. 设置冻结金额为固定值。可从余额或pending中同步。

不足则从另一侧取用,超出则添加到另一侧。

func (*ItemWallet) SetMargin

func (iw *ItemWallet) SetMargin(odKey string, amount float64) *errs.Error

SetMargin Set margin occupancy. Take priority from unrealized pol used upol. When insufficient, it will be taken from the balance. Released to balance when exceeded 设置保证金占用。优先从unrealized_pol-used_upol中取。不足时从余额中取。

超出时释放到余额

func (*ItemWallet) Total

func (iw *ItemWallet) Total(withUpol bool) float64

Total: Available+Withdraw+Pendings+Frozens+[UnrealizedPOL]

func (*ItemWallet) Used added in v0.2.4

func (iw *ItemWallet) Used() float64

type LegalValueKind added in v0.2.29

type LegalValueKind uint8
const (
	LegalValueAvailable LegalValueKind = iota
	LegalValueTotal
	LegalValueUnrealizedPOL
	LegalValueWithdraw
)

type LiveOrderMgr

type LiveOrderMgr struct {
	OrderMgr
	// contains filtered or unexported fields
}

func GetLiveOdMgr

func GetLiveOdMgr(account string) *LiveOrderMgr

func (*LiveOrderMgr) CleanUp

func (o *LiveOrderMgr) CleanUp() *errs.Error

func (*LiveOrderMgr) ConsumeOrderQueue

func (o *LiveOrderMgr) ConsumeOrderQueue()

func (*LiveOrderMgr) EditOrder added in v0.2.16

func (o *LiveOrderMgr) EditOrder(od *ormo.InOutOrder, action string)

func (*LiveOrderMgr) ExitAndFill added in v0.1.29

func (o *LiveOrderMgr) ExitAndFill(orders []*ormo.InOutOrder, req *strat.ExitReq) *errs.Error

func (*LiveOrderMgr) OnEnvEnd

func (o *LiveOrderMgr) OnEnvEnd(evt *orm.DataSeries) *errs.Error

func (*LiveOrderMgr) ProcessOrders

func (o *LiveOrderMgr) ProcessOrders(job *strat.StratJob) ([]*ormo.InOutOrder, []*ormo.InOutOrder, *errs.Error)

func (*LiveOrderMgr) SyncExgOrders

func (o *LiveOrderMgr) SyncExgOrders() ([]*ormo.InOutOrder, []*ormo.InOutOrder, []*ormo.InOutOrder, *errs.Error)

SyncExgOrders Synchronize the latest local orders of the exchange

First, use fetch_account_positions to fetch the positions of all coins in the exchange. If there are no open orders locally: If the exchange has no positions: Ignore If the exchange has all positions: Treat it as a new order opened by the user and create a new order tracking If there are open orders locally: Get the last time of the local order as the start time, and query all subsequent orders through the fetch_orders interface. Determine the current status of open orders from the exchange order records: closed, partially closed, unclosed For redundant positions, treat them as new orders opened by the user and create new order tracking. 将交易所最新状态本地订单进行同步,机器人启动时初始化

先通过fetch_account_positions抓取交易所所有币的仓位情况。
如果本地没有未平仓订单:
    如果交易所没有持仓:忽略
    如果交易所有持仓:视为用户开的新订单,创建新订单跟踪
如果本地有未平仓订单:
     获取本地订单的最后时间作为起始时间,通过fetch_orders接口查询此后所有订单。
     从交易所订单记录来确定未平仓订单的当前状态:已平仓、部分平仓、未平仓
     对于冗余的仓位,视为用户开的新订单,创建新订单跟踪。

func (*LiveOrderMgr) SyncLocalOrders added in v0.2.2

func (o *LiveOrderMgr) SyncLocalOrders() ([]*ormo.InOutOrder, *errs.Error)

SyncLocalOrders 将交易所仓位和本地仓位对比,关闭本地多余仓位对应订单

定期执行,用于解决币安偶发止损成交但状态为expired导致本地订单未更新问题。

func (*LiveOrderMgr) TrialUnMatchesForever

func (o *LiveOrderMgr) TrialUnMatchesForever()

func (*LiveOrderMgr) UpdateByDataSeries added in v0.4.0

func (o *LiveOrderMgr) UpdateByDataSeries(allOpens []*ormo.InOutOrder, evt *orm.DataSeries) *errs.Error

func (*LiveOrderMgr) WatchLeverages

func (o *LiveOrderMgr) WatchLeverages()

func (*LiveOrderMgr) WatchMyTrades

func (o *LiveOrderMgr) WatchMyTrades()

type LocalLiveOrderMgr added in v0.2.21

type LocalLiveOrderMgr struct {
	LocalOrderMgr
}

func (*LocalLiveOrderMgr) CleanUp added in v0.2.22

func (o *LocalLiveOrderMgr) CleanUp() *errs.Error

type LocalOrderMgr

type LocalOrderMgr struct {
	OrderMgr
	// contains filtered or unexported fields
}

func (*LocalOrderMgr) CleanUp

func (o *LocalOrderMgr) CleanUp() *errs.Error

func (*LocalOrderMgr) EditOrder added in v0.2.16

func (o *LocalOrderMgr) EditOrder(od *ormo.InOutOrder, action string)

func (*LocalOrderMgr) ExitAndFill added in v0.1.29

func (o *LocalOrderMgr) ExitAndFill(orders []*ormo.InOutOrder, req *strat.ExitReq) *errs.Error

func (*LocalOrderMgr) OnEnvEnd

func (o *LocalOrderMgr) OnEnvEnd(evt *orm.DataSeries) *errs.Error

func (*LocalOrderMgr) ProcessOrders

func (o *LocalOrderMgr) ProcessOrders(job *strat.StratJob) ([]*ormo.InOutOrder, []*ormo.InOutOrder, *errs.Error)

func (*LocalOrderMgr) UpdateByDataSeries added in v0.4.0

func (o *LocalOrderMgr) UpdateByDataSeries(allOpens []*ormo.InOutOrder, evt *orm.DataSeries) *errs.Error

type NumArr

type NumArr struct {
	Data  []float64 `protobuf:"fixed64,1,rep,packed,name=data,proto3" json:"data,omitempty"`
	Shape []int32   `protobuf:"varint,2,rep,packed,name=shape,proto3" json:"shape,omitempty"`
	// contains filtered or unexported fields
}

func (*NumArr) Descriptor deprecated

func (*NumArr) Descriptor() ([]byte, []int)

Deprecated: Use NumArr.ProtoReflect.Descriptor instead.

func (*NumArr) GetData

func (x *NumArr) GetData() []float64

func (*NumArr) GetShape

func (x *NumArr) GetShape() []int32

func (*NumArr) ProtoMessage

func (*NumArr) ProtoMessage()

func (*NumArr) ProtoReflect

func (x *NumArr) ProtoReflect() protoreflect.Message

func (*NumArr) Reset

func (x *NumArr) Reset()

func (*NumArr) String

func (x *NumArr) String() string

type OdQItem

type OdQItem struct {
	Order  *ormo.InOutOrder
	Action string
}

type OrderMgr

type OrderMgr struct {
	Account string
	BarMS   int64
	// contains filtered or unexported fields
}

func (*OrderMgr) CleanUp

func (o *OrderMgr) CleanUp() *errs.Error

func (*OrderMgr) CutOrder

func (o *OrderMgr) CutOrder(od *ormo.InOutOrder, enterRate, exitRate float64) *ormo.InOutOrder

func (*OrderMgr) EnterOrder

func (o *OrderMgr) EnterOrder(exs *orm.ExSymbol, tf string, req *strat.EnterReq) (*ormo.InOutOrder, *errs.Error)

func (*OrderMgr) ExitOpenOrders

func (o *OrderMgr) ExitOpenOrders(pairs string, req *strat.ExitReq) ([]*ormo.InOutOrder, *errs.Error)

func (*OrderMgr) ExitOrder

func (o *OrderMgr) ExitOrder(od *ormo.InOutOrder, req *strat.ExitReq) (*ormo.InOutOrder, *errs.Error)

func (*OrderMgr) ProcessOrders

func (o *OrderMgr) ProcessOrders(job *strat.StratJob) ([]*ormo.InOutOrder, []*ormo.InOutOrder, *errs.Error)

ProcessOrders Execute order entry and exit requests Create pending orders, the returned orders are not actually entered or exited; Backtest: the caller executes the entry/exit order according to the next bar and updates the status Live trading: monitor the exchange to return the order status to update the entry and exit 执行订单入场出场请求 创建待执行订单,返回的订单实际并未入场或出场; 回测:调用方根据下一个bar执行入场/出场订单,更新状态 实盘:监听交易所返回订单状态更新入场出场

func (*OrderMgr) RelayOrders added in v0.1.29

func (o *OrderMgr) RelayOrders(orders []*ormo.InOutOrder) *errs.Error

func (*OrderMgr) UpdateByDataSeries added in v0.4.0

func (o *OrderMgr) UpdateByDataSeries(allOpens []*ormo.InOutOrder, evt *orm.DataSeries) *errs.Error

UpdateByDataSeries Use the price to update the profit of the order, etc. It may trigger a margin call 使用价格更新订单的利润等。可能会触发爆仓

type PairOrders added in v0.2.9

type PairOrders struct {
	Symbol  string
	Orders  []*banexg.Order
	StartMS int64
	EndMS   int64
}

type PairValItem

type PairValItem struct {
	AvgVol   float64
	LastVol  float64
	ExpireMS int64
}

type RemoteCommand added in v0.4.0

type RemoteCommand struct {
	Source       string
	Actor        string
	Account      string
	Action       string
	Idempotency  string
	Confirmed    bool
	OrderID      int64
	All          bool
	Enable       bool
	DisableHours int
	UntilMS      int64
	ExitTag      string
	ExecClose    func() (int, int, *errs.Error)
}

type RemoteCommandResult added in v0.4.0

type RemoteCommandResult struct {
	Idempotent bool
	CloseNum   int
	FailNum    int
	UntilMS    int64
}

func CloseBotOrdersRemote added in v0.4.0

func CloseBotOrdersRemote(cmd RemoteCommand) (*RemoteCommandResult, *errs.Error)

func RunRemoteCommand added in v0.4.0

func RunRemoteCommand(cmd RemoteCommand) (*RemoteCommandResult, *errs.Error)

type RemoteCommandService added in v0.4.0

type RemoteCommandService struct {
	// contains filtered or unexported fields
}

func NewRemoteCommandService added in v0.4.0

func NewRemoteCommandService() *RemoteCommandService

func (*RemoteCommandService) Run added in v0.4.0

type RunHistSeriesArgs added in v0.4.0

type RunHistSeriesArgs struct {
	ExsList     []*orm.ExSymbol
	Start       int64
	End         int64
	ViewNextNum int // number of future bars to get
	TfWarms     map[string]int
	OnEnvEnd    func(evt *orm.DataSeries)
	VerCh       chan int // write -1 to exit;
	OnData      func(evt *orm.DataSeries, nexts []*orm.DataSeries)
}

type SubReq

type SubReq struct {
	Exchange string   `protobuf:"bytes,1,opt,name=exchange,proto3" json:"exchange,omitempty"`
	Market   string   `protobuf:"bytes,2,opt,name=market,proto3" json:"market,omitempty"`
	Codes    []string `protobuf:"bytes,3,rep,name=codes,proto3" json:"codes,omitempty"`
	Start    int64    `protobuf:"varint,4,opt,name=start,proto3" json:"start,omitempty"`
	End      int64    `protobuf:"varint,5,opt,name=end,proto3" json:"end,omitempty"`
	Task     string   `protobuf:"bytes,6,opt,name=task,proto3" json:"task,omitempty"`
	Sample   int32    `protobuf:"varint,7,opt,name=sample,proto3" json:"sample,omitempty"`
	// contains filtered or unexported fields
}

func (*SubReq) Descriptor deprecated

func (*SubReq) Descriptor() ([]byte, []int)

Deprecated: Use SubReq.ProtoReflect.Descriptor instead.

func (*SubReq) GetCodes

func (x *SubReq) GetCodes() []string

func (*SubReq) GetEnd

func (x *SubReq) GetEnd() int64

func (*SubReq) GetExchange

func (x *SubReq) GetExchange() string

func (*SubReq) GetMarket

func (x *SubReq) GetMarket() string

func (*SubReq) GetSample

func (x *SubReq) GetSample() int32

func (*SubReq) GetStart

func (x *SubReq) GetStart() int64

func (*SubReq) GetTask

func (x *SubReq) GetTask() string

func (*SubReq) ProtoMessage

func (*SubReq) ProtoMessage()

func (*SubReq) ProtoReflect

func (x *SubReq) ProtoReflect() protoreflect.Message

func (*SubReq) Reset

func (x *SubReq) Reset()

func (*SubReq) String

func (x *SubReq) String() string

type TelegramOrderManager added in v0.2.23

type TelegramOrderManager struct{}

TelegramOrderManager 实现 rpc.OrderManagerInterface 接口

func NewTelegramOrderManager added in v0.2.23

func NewTelegramOrderManager() *TelegramOrderManager

NewTelegramOrderManager 创建 Telegram 订单管理器

func (*TelegramOrderManager) CloseAllOrders added in v0.2.23

func (m *TelegramOrderManager) CloseAllOrders(account string) (int, int, error)

CloseAllOrders 平仓所有订单

func (*TelegramOrderManager) CloseOrder added in v0.2.23

func (m *TelegramOrderManager) CloseOrder(account string, orderID int64) error

CloseOrder 平仓指定订单

func (*TelegramOrderManager) DisableTrading added in v0.4.0

func (m *TelegramOrderManager) DisableTrading(account string, hours int) (int64, error)

func (*TelegramOrderManager) EnableTrading added in v0.4.0

func (m *TelegramOrderManager) EnableTrading(account string) error

func (*TelegramOrderManager) GetActiveOrders added in v0.2.23

func (m *TelegramOrderManager) GetActiveOrders(account string) ([]*rpc.OrderInfo, error)

GetActiveOrders 获取活跃订单列表

func (*TelegramOrderManager) GetOrderStats added in v0.2.23

func (m *TelegramOrderManager) GetOrderStats(account string) (longCount, shortCount int, err error)

GetOrderStats 获取订单统计信息

type Trader

type Trader struct {
}

func (*Trader) FeedDataSeries added in v0.4.0

func (t *Trader) FeedDataSeries(evt *orm.DataSeries) *errs.Error

func (*Trader) FeedSeries added in v0.4.0

func (t *Trader) FeedSeries(evt *orm.DataSeries) *errs.Error

func (*Trader) OnEnvEnd

func (t *Trader) OnEnvEnd(evt *orm.DataSeries)

func (*Trader) OnEnvSeries added in v0.4.0

func (t *Trader) OnEnvSeries(evt *orm.DataSeries) (*ta.BarEnv, *errs.Error)

type UnimplementedAInferServer

type UnimplementedAInferServer struct {
}

UnimplementedAInferServer must be embedded to have forward compatible implementations.

func (UnimplementedAInferServer) Trade

func (UnimplementedAInferServer) Trend

type UnimplementedFeaFeederServer

type UnimplementedFeaFeederServer struct {
}

UnimplementedFeaFeederServer must be embedded to have forward compatible implementations.

func (UnimplementedFeaFeederServer) SubFeatures

type UnsafeAInferServer

type UnsafeAInferServer interface {
	// contains filtered or unexported methods
}

UnsafeAInferServer may be embedded to opt out of forward compatibility for this service. Use of this interface is not recommended, as added methods to AInferServer will result in compilation errors.

type UnsafeFeaFeederServer

type UnsafeFeaFeederServer interface {
	// contains filtered or unexported methods
}

UnsafeFeaFeederServer may be embedded to opt out of forward compatibility for this service. Use of this interface is not recommended, as added methods to FeaFeederServer will result in compilation errors.

type VarsBackup added in v0.1.29

type VarsBackup struct {
	Pairs         []string
	PairMap       map[string]bool
	NoEnterUntil  map[string]int64
	PairCopiedMs  map[string][2]int64
	TfPairHits    map[string]map[string]int
	JobPerfs      map[string]*core.JobPerf
	StratPerfSta  map[string]*core.PerfSta
	AccLiveOdMgrs map[string]*LiveOrderMgr
	AccOdMgrs     map[string]IOrderMgr
	AccWallets    map[string]*BanWallets
	LastBarMs     int64
	OdBooks       map[string]*banexg.OrderBook
	HistODs       []*ormo.InOutOrder
	Envs          map[string]*ta.BarEnv
	TmpEnvs       map[string]*ta.BarEnv
	AccJobs       map[string]map[string]map[string]*strat.StratJob
	AccInfoJobs   map[string]map[string]map[string]*strat.StratJob
	PairStrats    map[string]map[string]*strat.TradeStrat
	WsSubJobs     map[string]map[string]map[*strat.StratJob]bool
	BatchTasks    map[string]*strat.BatchMap
	ForbidJobs    map[string]map[string]bool
	LastBatchMS   int64
	OrmoBackup    *ormo.VarsBackup
}

func BackupVars added in v0.1.29

func BackupVars() *VarsBackup

BackupVars 备份所有全局变量

type VolPrice

type VolPrice struct {
	BuyPrice  float64
	SellPrice float64
	ExpireMS  int64
}

Jump to

Keyboard shortcuts

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