Documentation
¶
Index ¶
- Constants
- Variables
- func AlgoOrderID(exg interface{}, trade *MyTrade) string
- func BoolFromInfo(info map[string]interface{}, keys ...string) (bool, bool)
- func BuildClientOrderID(exchange interface{}, namespace string, orderID int64, clientID string, ...) (string, bool)
- func BuildLegacyClientOrderID(exchangeName, namespace string, orderID int64, clientID string, randomize bool) string
- func BuildSymbolSet(symbols []string) map[string]struct{}
- func CheckWsError(msg map[string]string) *errs.Error
- func CheckWsErrorWith(msg map[string]string, mapper func(status int, content string) *errs.Error) *errs.Error
- func ContextFromParams(params map[string]interface{}) context.Context
- func DefaultCareMarkets() []string
- func EnsureArrStr(text string) string
- func FillAccountAccessFromInfo(acc *AccountAccess, info map[string]interface{})
- func GetHostFlowChan(host string) chan struct{}
- func GetHostRetryWait(host string, randAdd bool) int64
- func GetOrderEventOrderID(exg interface{}, trade *MyTrade) string
- func GetProxy() string
- func GetWsOutChan[T any](e *Exchange, chanKey string, create func(int) T, args map[string]interface{}) T
- func IsContract(marketType string) bool
- func IsOrderDone(status string) bool
- func IsPermanentWsError(err *errs.Error) bool
- func MergeAccountAccess(dst *AccountAccess, src *AccountAccess)
- func NewHttpClient() *http.Client
- func NormalizeOrderTimestamp(exg interface{}, order *Order, fallback int64) int64
- func NormalizePosMode(mode string) string
- func ParseBool(val interface{}) (bool, bool)
- func ParseClientOrderID(exg interface{}, botName, clientID string) int64
- func PosModeFromBool(dual bool) string
- func RedactLogText(raw string) string
- func SetBoolArg(args map[string]interface{}, key string, fmtType BoolFmt)
- func SetHostRetryWait(host string, waitMS int64)
- func SetProxy(proxyUrl string) *errs.Error
- func TickersToPriceMap(tickers []*Ticker, symbolSet map[string]struct{}) map[string]float64
- func WriteOutChan[T any](e *Exchange, chanKey string, msg T, popIfNeed bool) bool
- type Account
- type AccountAccess
- type AccountConfig
- type ApiRes
- type Asset
- type AsyncConn
- type Balances
- type BanExchange
- type BaseLvgBracket
- type BoolFmt
- type ChainNetwork
- type ClientOrderCapability
- type ClientOrderIDCapability
- type CodeLimits
- type Credential
- type Currency
- type CurrencyMap
- type Entry
- type Exchange
- func (e *Exchange) AddWsChanRefs(chanKey string, keys ...string)
- func (*Exchange) AlgoOrderID(trade *MyTrade) string
- func (e *Exchange) CacheApiRes(endpoint string, res *HttpRes)
- func (e *Exchange) CalcMaintMargin(symbol string, cost float64) (float64, *errs.Error)
- func (e *Exchange) CalculateFee(symbol, odType, side string, amount float64, price float64, isMaker bool, ...) (*Fee, *errs.Error)
- func (e *Exchange) Call(method string, params map[string]interface{}) (*HttpRes, *errs.Error)
- func (e *Exchange) CancelOrder(id string, symbol string, params map[string]interface{}) (*Order, *errs.Error)
- func (e *Exchange) CheckRiskyAllowed(api *Entry, accID string) *errs.Error
- func (e *Exchange) CheckSymbols(symbols ...string) ([]string, []string)
- func (e *Exchange) Close() *errs.Error
- func (e *Exchange) CloseWsFile()
- func (e *Exchange) CreateOrder(symbol, odType, side string, amount float64, price float64, ...) (*Order, *errs.Error)
- func (e *Exchange) DelWsChanRefs(chanKey string, keys ...string) int
- func (e *Exchange) DumpWS(name string, data interface{})
- func (e *Exchange) EditOrder(symbol, orderId, side string, amount, price float64, ...) (*Order, *errs.Error)
- func (e *Exchange) FetchAccountAccess(params map[string]interface{}) (*AccountAccess, *errs.Error)
- func (e *Exchange) FetchAccountPositions(symbols []string, params map[string]interface{}) ([]*Position, *errs.Error)
- func (e *Exchange) FetchBalance(params map[string]interface{}) (*Balances, *errs.Error)
- func (e *Exchange) FetchFundingRate(symbol string, params map[string]interface{}) (*FundingRateCur, *errs.Error)
- func (e *Exchange) FetchFundingRateHistory(symbol string, since int64, limit int, params map[string]interface{}) ([]*FundingRate, *errs.Error)
- func (e *Exchange) FetchFundingRates(symbols []string, params map[string]interface{}) ([]*FundingRateCur, *errs.Error)
- func (e *Exchange) FetchIncomeHistory(inType string, symbol string, since int64, limit int, ...) ([]*Income, *errs.Error)
- func (e *Exchange) FetchLastPrices(symbols []string, params map[string]interface{}) ([]*LastPrice, *errs.Error)
- func (e *Exchange) FetchOHLCV(symbol, timeframe string, since int64, limit int, ...) ([]*Kline, *errs.Error)
- func (e *Exchange) FetchOpenOrders(symbol string, since int64, limit int, params map[string]interface{}) ([]*Order, *errs.Error)
- func (e *Exchange) FetchOrder(symbol, orderId string, params map[string]interface{}) (*Order, *errs.Error)
- func (e *Exchange) FetchOrderBook(symbol string, limit int, params map[string]interface{}) (*OrderBook, *errs.Error)
- func (e *Exchange) FetchOrders(symbol string, since int64, limit int, params map[string]interface{}) ([]*Order, *errs.Error)
- func (e *Exchange) FetchPositions(symbols []string, params map[string]interface{}) ([]*Position, *errs.Error)
- func (e *Exchange) FetchTicker(symbol string, params map[string]interface{}) (*Ticker, *errs.Error)
- func (e *Exchange) FetchTickerPrice(symbol string, params map[string]interface{}) (map[string]float64, *errs.Error)
- func (e *Exchange) FetchTickers(symbols []string, params map[string]interface{}) ([]*Ticker, *errs.Error)
- func (e *Exchange) FindWSClient(key string) (*WsClient, bool)
- func (e *Exchange) GetAccName(params map[string]interface{}) string
- func (e *Exchange) GetAccount(id string) (*Account, *errs.Error)
- func (e *Exchange) GetAccountCreds(id string) (string, *Credential, *errs.Error)
- func (e *Exchange) GetArgsMarket(symbol string, args map[string]interface{}) (*Market, *errs.Error)
- func (e *Exchange) GetArgsMarketType(args map[string]interface{}, symbol string) (string, string)
- func (e *Exchange) GetCacheKey(endpoint string, params map[string]interface{}) string
- func (e *Exchange) GetClient(wsUrl string, marketType, accName string) (*WsClient, *errs.Error)
- func (e *Exchange) GetClientContext(ctx context.Context, wsUrl string, marketType, accName string) (*WsClient, *errs.Error)
- func (e *Exchange) GetCurMarkets() MarketMap
- func (e *Exchange) GetExg() *Exchange
- func (e *Exchange) GetHost(name string) string
- func (e *Exchange) GetID() string
- func (e *Exchange) GetLeverage(symbol string, notional float64, account string) (float64, float64)
- func (e *Exchange) GetMarket(symbol string) (*Market, *errs.Error)
- func (e *Exchange) GetMarketBy(symbol string) (*Market, bool)
- func (e *Exchange) GetMarketById(marketId, marketType string) *Market
- func (e *Exchange) GetMarketID(symbol string) (string, *errs.Error)
- func (e *Exchange) GetMarketIDByArgs(args map[string]interface{}, required bool) (string, *errs.Error)
- func (e *Exchange) GetNetDisable() bool
- func (*Exchange) GetOrderEventOrderID(trade *MyTrade) string
- func (e *Exchange) GetPriceOnePip(pair string) (float64, *errs.Error)
- func (e *Exchange) GetReplayTo() int64
- func (e *Exchange) GetRetryNum(key string, defVal int) int
- func (e *Exchange) GetTimeFrame(timeframe string) string
- func (e *Exchange) HasApi(key, market string) bool
- func (e *Exchange) Info() *ExgInfo
- func (e *Exchange) Init() *errs.Error
- func (e *Exchange) InitLeverageBrackets() *errs.Error
- func (e *Exchange) IsContract(marketType string) bool
- func (e *Exchange) LoadArgsMarket(symbol string, params map[string]interface{}) (map[string]interface{}, *Market, *errs.Error)
- func (e *Exchange) LoadArgsMarketType(args map[string]interface{}, symbols ...string) (string, string, *errs.Error)
- func (e *Exchange) LoadLeverageBrackets(reload bool, params map[string]interface{}) *errs.Error
- func (e *Exchange) LoadMarkets(reload bool, params map[string]interface{}) (MarketMap, *errs.Error)
- func (e *Exchange) MapMarket(exgSID string, year int) (*Market, *errs.Error)
- func (e *Exchange) MilliSeconds() int64
- func (e *Exchange) Nonce() int64
- func (*Exchange) NormalizeOrderTimestamp(order *Order, fallback int64) int64
- func (*Exchange) ParseClientOrderID(botName, clientID string) int64
- func (e *Exchange) PopAccName(params map[string]interface{}) string
- func (e *Exchange) PrecAmount(m *Market, amount float64) (float64, *errs.Error)
- func (e *Exchange) PrecCost(m *Market, cost float64) (float64, *errs.Error)
- func (e *Exchange) PrecFee(m *Market, fee float64) (float64, *errs.Error)
- func (e *Exchange) PrecPrice(m *Market, price float64) (float64, *errs.Error)
- func (e *Exchange) PriceOnePip(symbol string) (float64, *errs.Error)
- func (e *Exchange) ReplayAll() *errs.Error
- func (e *Exchange) ReplayOne() *errs.Error
- func (e *Exchange) RequestApi(ctx context.Context, cacheKey string, api *Entry, ...) *HttpRes
- func (e *Exchange) RequestApiRetry(ctx context.Context, endpoint string, params map[string]interface{}, ...) *HttpRes
- func (e *Exchange) RequestApiRetryAdv(ctx context.Context, endpoint string, params map[string]interface{}, ...) *HttpRes
- func (e *Exchange) SafeCurrency(currId string) *Currency
- func (e *Exchange) SafeCurrencyCode(currId string) string
- func (e *Exchange) SafeMarket(marketId, delimiter, marketType string) *Market
- func (e *Exchange) SafeSymbol(marketId, delimiter, marketType string) string
- func (e *Exchange) SetDump(path string) *errs.Error
- func (e *Exchange) SetFees(fees map[string]map[string]float64)
- func (e *Exchange) SetLeverage(leverage float64, symbol string, params map[string]interface{}) (map[string]interface{}, *errs.Error)
- func (e *Exchange) SetMarketType(marketType, contractType string) *errs.Error
- func (e *Exchange) SetNetDisable(v bool)
- func (e *Exchange) SetOnHost(cb func(n string) string)
- func (e *Exchange) SetOnWsChan(cb FuncOnWsChan)
- func (e *Exchange) SetReplay(path string) *errs.Error
- func (e *Exchange) UnWatchMarkPrices(symbols []string, params map[string]interface{}) *errs.Error
- func (e *Exchange) UnWatchOHLCVs(jobs [][2]string, params map[string]interface{}) *errs.Error
- func (e *Exchange) UnWatchOrderBooks(symbols []string, params map[string]interface{}) *errs.Error
- func (e *Exchange) UnWatchTrades(symbols []string, params map[string]interface{}) *errs.Error
- func (e *Exchange) WSClientSnapshot() []*WsClient
- func (e *Exchange) WaitWsCheck(delay time.Duration) bool
- func (e *Exchange) WatchAccountConfig(params map[string]interface{}) (chan *AccountConfig, *errs.Error)
- func (e *Exchange) WatchBalance(params map[string]interface{}) (chan *Balances, *errs.Error)
- func (e *Exchange) WatchMarkPrices(symbols []string, params map[string]interface{}) (chan map[string]float64, *errs.Error)
- func (e *Exchange) WatchMyTrades(params map[string]interface{}) (chan *MyTrade, *errs.Error)
- func (e *Exchange) WatchOHLCVs(jobs [][2]string, params map[string]interface{}) (chan *PairTFKline, *errs.Error)
- func (e *Exchange) WatchOrderBooks(symbols []string, limit int, params map[string]interface{}) (chan *OrderBook, *errs.Error)
- func (e *Exchange) WatchPositions(params map[string]interface{}) (chan []*Position, *errs.Error)
- func (e *Exchange) WatchTrades(symbols []string, params map[string]interface{}) (chan *Trade, *errs.Error)
- type ExecutionCapability
- type ExecutionProof
- type ExgFee
- type ExgHosts
- type ExgInfo
- type Fee
- type FeeTierItem
- type FeeTiers
- type FuncAuthWS
- type FuncCalcFee
- type FuncCalcRateLimiterCost
- type FuncFetchCurr
- type FuncFetchMarkets
- type FuncGetWsJob
- type FuncMapApiError
- type FuncOnWsChan
- type FuncOnWsClose
- type FuncOnWsErr
- type FuncOnWsMethod
- type FuncOnWsMsg
- type FuncOnWsReCon
- type FuncSign
- type FundingCash
- type FundingCashCapability
- type FundingRate
- type FundingRateCur
- type HttpHeader
- type HttpReq
- type HttpRes
- type ISymbolLvgBracket
- type Income
- type Kline
- type LastPrice
- type LimitRange
- type LvgBracket
- type Market
- type MarketArrMap
- type MarketLimits
- type MarketMap
- type MyTrade
- type OHLCVArchiveFetcher
- type OHLCVArr
- type OdBookShotLog
- type OdBookSide
- type Order
- type OrderBook
- type OrderEventCapability
- type OrderEventOrderIDCapability
- type PairTFKline
- type Position
- type Precision
- type PriceSymbolCapability
- type SubStat
- type SymbolLvgBrackets
- type SymbolScopedMarketLoader
- type Ticker
- type Trade
- type TradeFee
- type WebSocket
- func (ws *WebSocket) Close() error
- func (ws *WebSocket) GetID() int
- func (ws *WebSocket) IsOK() bool
- func (ws *WebSocket) NextWriter() (io.WriteCloser, error)
- func (ws *WebSocket) ReConnect() error
- func (ws *WebSocket) ReadMsg() ([]byte, error)
- func (ws *WebSocket) SetID(v int)
- func (ws *WebSocket) WriteClose() error
- type WsClient
- func (c *WsClient) Close()
- func (c *WsClient) DeferConnReady(connID int) uint64
- func (c *WsClient) FailConn(connID int, generation uint64, permanent bool)
- func (c *WsClient) GetConnSubStats(timeout int64) map[int]*SubStat
- func (c *WsClient) GetSubKeys(connID int) []string
- func (c *WsClient) HandleRawMsg(msgRaw []byte)
- func (c *WsClient) HasSubKeyPrefix(prefix string) bool
- func (c *WsClient) LockConns() (map[int]*AsyncConn, *deadlock.Mutex)
- func (c *WsClient) LockOdBookLimits() (map[string]int, *deadlock.Mutex)
- func (c *WsClient) MarkConnReady(connID int, generation uint64) bool
- func (c *WsClient) Prefix(key string) string
- func (c *WsClient) SetSubsKeyStamp(key string, stamp int64)
- func (c *WsClient) UpdateSubs(connID int, isSub bool, keys []string) (string, *AsyncConn)
- func (c *WsClient) Write(conn *AsyncConn, msg interface{}, info *WsJobInfo) *errs.Error
- func (c *WsClient) WriteRaw(conn *AsyncConn, data []byte) *errs.Error
- func (c *WsClient) WriteRecovery(conn *AsyncConn, msg interface{}, info *WsJobInfo) *errs.Error
- func (c *WsClient) WriteRecoveryFor(conn *AsyncConn, generation uint64, msg interface{}, info *WsJobInfo) *errs.Error
- type WsConn
- type WsJobInfo
- type WsLog
- type WsMsg
Constants ¶
const ( ParamClientOrderId = "clientOrderId" ParamOrderIds = "orderIdList" ParamOrigClientOrderIDs = "origClientOrderIdList" ParamSor = "sor" // smart order route, for create order in spot ParamPostOnly = "postOnly" ParamTimeInForce = "timeInForce" ParamTriggerPrice = "triggerPrice" ParamStopLossPrice = "stopLossPrice" ParamTakeProfitPrice = "takeProfitPrice" ParamTrailingDelta = "trailingDelta" ParamReduceOnly = "reduceOnly" ParamCost = "cost" ParamClosePosition = "closePosition" // 触发后全部平仓 ParamActivationPrice = "activationPrice" ParamCallbackRate = "callbackRate" // 跟踪止损回调百分比 ParamAlgoOrder = "algoOrder" ParamWorkingType = "workingType" ParamPriceMatch = "priceMatch" ParamPriceProtect = "priceProtect" ParamSelfTradePreventionMode = "selfTradePreventionMode" ParamTag = "tag" ParamBanAmend = "banAmend" ParamPxAmendType = "pxAmendType" ParamGoodTillDate = "goodTillDate" ParamRolling = "rolling" ParamTest = "test" ParamMarginMode = "marginMode" ParamSymbol = "symbol" ParamSymbols = "symbols" ParamPositionSide = "positionSide" ParamProxy = "proxy" ParamName = "name" ParamMethod = "method" ParamInterval = "interval" ParamAccount = "account" ParamBalance = "balance" ParamMarket = "market" ParamContract = "contract" ParamBrokerId = "brokerId" ParamLimit = "limit" ParamUntil = "until" ParamRetry = "retry" ParamLoopIntv = "loopIntv" ParamDirection = "direction" // ParamAutoClip allows an exchange adapter to automatically clip/split parameters (e.g. time range) // to satisfy exchange-specific constraints instead of returning an error. ParamAutoClip = "autoClip" ParamDebug = "debug" ParamNoCache = "noCache" ParamAfter = "after" // Pagination cursor - records after this ID ParamBefore = "before" // Pagination cursor - records before this ID ParamCurrency = "currency" // Currency code ParamArchive = "archive" // Whether to use archive endpoint ParamSettleCoins = "settleCoins" // Settlement coins for account-scoped queries ParamFullSnapshot = "fullSnapshot" // Require a complete result or return an error ParamSettledCash = "settledCash" )
const ( HasFail = 1 << iota HasOk HasEmulated )
const ( BoolNull = 0 BoolFalse = -1 BoolTrue = 1 )
const ( OptProxy = "Proxy" OptApiKey = "ApiKey" OptApiSecret = "ApiSecret" OptPassword = "Password" OptAccCreds = "Creds" OptAccName = "AccName" OptNoTrade = "NoTrade" OptUserAgent = "UserAgent" OptReqHeaders = "ReqHeaders" OptCareMarkets = "CareMarkets" OptMarketType = "MarketType" OptContractType = "ContractType" OptTimeInForce = "TimeInForce" OptWsIntvs = "WsIntvs" // ws 订阅间隔 OptRetries = "Retries" OptWsConn = "WsConn" OptAuthRefreshSecs = "AuthRefreshSecs" OptPositionMethod = "PositionMethod" OptDebugWs = "DebugWs" OptDebugApi = "DebugApi" OptApiCaches = "ApiCaches" OptFees = "Fees" OptDumpPath = "DumpPath" OptDumpBatchSize = "DumpBatchSize" OptReplayPath = "ReplayPath" OptEnv = "Env" OptWsTimeout = "WsTimeout" OptRecvWindow = "RecvWindow" )
const ( PrecModeDecimalPlace = utils.PrecModeDecimalPlace // 保留小数点后位数 PrecModeSignifDigits = utils.PrecModeSignifDigits // 保留有效数字位数 PrecModeTickSize = utils.PrecModeTickSize // 返回给定数字的整数倍 )
const ( MarketSpot = "spot" // 现货交易 MarketMargin = "margin" // 保证金杠杆现货交易 margin trade MarketLinear = "linear" MarketInverse = "inverse" MarketOption = "option" // 期权 for option contracts MarketSwap = "swap" // 永续合约 for perpetual swap futures that don't have a delivery date MarketFuture = "future" // 有交割日的期货 for expiring futures contracts that have a delivery/settlement date )
const ( MarginCross = "cross" MarginIsolated = "isolated" )
const ( PosModeHedge = "hedge" PosModeOneWay = "oneway" )
const ( AcctModeSpot = "spot" AcctModeSingleCurrencyMargin = "single_currency_margin" AcctModeMultiCurrencyMargin = "multi_currency_margin" AcctModePortfolioMargin = "portfolio_margin" )
const ( OdStatusOpen = "open" OdStatusPartFilled = "part_filled" OdStatusFilled = "filled" OdStatusCanceled = "canceled" OdStatusCanceling = "canceling" OdStatusRejected = "rejected" OdStatusExpired = "expired" )
const ( OdTypeMarket = "market" OdTypeLimit = "limit" OdTypeLimitMaker = "limit_maker" OdTypeStop = "stop" OdTypeStopMarket = "stop_market" OdTypeStopLoss = "stop_loss" OdTypeStopLossLimit = "stop_loss_limit" OdTypeTakeProfit = "take_profit" OdTypeTakeProfitLimit = "take_profit_limit" OdTypeTakeProfitMarket = "take_profit_market" OdTypeTrailingStopMarket = "trailing_stop_market" )
此处订单类型全部使用币安订单类型小写
const ( OdSideBuy = "buy" OdSideSell = "sell" )
const ( PosSideLong = "long" PosSideShort = "short" PosSideBoth = "both" )
const ( TimeInForceGTC = "GTC" // Good Till Cancel 一直有效,直到被成交或取消 TimeInForceIOC = "IOC" // Immediate or Cancel 无法立即成交的部分取消 TimeInForceFOK = "FOK" // Fill or Kill 无法全部立即成交就撤销 TimeInForceGTX = "GTX" // Good Till Crossing 无法成为挂单方就取消 TimeInForceGTD = "GTD" // Good Till Date 在特定时间前有效,到期自动取消 TimeInForcePO = "PO" // Post Only )
const ( ApiFetchTicker = "FetchTicker" ApiFetchTickers = "FetchTickers" ApiFetchTickerPrice = "FetchTickerPrice" ApiLoadLeverageBrackets = "LoadLeverageBrackets" ApiFetchCurrencies = "FetchCurrencies" ApiGetLeverage = "GetLeverage" ApiFetchOHLCV = "FetchOHLCV" ApiFetchOrderBook = "FetchOrderBook" ApiFetchOrder = "FetchOrder" ApiFetchOrders = "FetchOrders" ApiFetchBalance = "FetchBalance" ApiFetchAccountPositions = "FetchAccountPositions" ApiFetchPositions = "FetchPositions" ApiFetchOpenOrders = "FetchOpenOrders" ApiCreateOrder = "CreateOrder" ApiEditOrder = "EditOrder" ApiCancelOrder = "CancelOrder" ApiSetLeverage = "SetLeverage" ApiCalcMaintMargin = "CalcMaintMargin" ApiWatchOrderBooks = "WatchOrderBooks" ApiUnWatchOrderBooks = "UnWatchOrderBooks" ApiWatchOHLCVs = "WatchOHLCVs" ApiUnWatchOHLCVs = "UnWatchOHLCVs" ApiWatchMarkPrices = "WatchMarkPrices" ApiUnWatchMarkPrices = "UnWatchMarkPrices" ApiWatchTrades = "WatchTrades" ApiUnWatchTrades = "UnWatchTrades" ApiWatchMyTrades = "WatchMyTrades" ApiWatchBalance = "WatchBalance" ApiWatchPositions = "WatchPositions" ApiWatchAccountConfig = "WatchAccountConfig" )
const (
DefTimeInForce = TimeInForceGTC
)
const (
MidListenKey = "listenKey"
)
const ParamCompleteOrder = "completeOrder"
ParamCompleteOrder asks order queries to return a complete cumulative quantity, cost, fee and terminal-state snapshot. Implementations must fail closed when the venue cannot prove completeness.
const ParamContext = "context"
ParamContext binds a synchronous SDK request to the caller's cancellation and deadline. Exchange adapters consume and remove this value before encoding request parameters.
Variables ¶
var ( DefReqHeaders = map[string]string{ "User-Agent": "Go-http-client/1.1", "Connection": "keep-alive", "Accept": "application/json", } DefCurrCodeMap = map[string]string{ "XBT": "BTC", "BCC": "BCH", "BCHSV": "BSV", } DefWsIntvs = map[string]int{ "WatchOrderBooks": 100, } DefRetries = map[string]int{ "FetchOrderBook": 1, "FetchPositionsRisk": 1, } HostRetryWaits = map[string]int64{} HostHttpConcurr = 3 // Maximum concurrent number of HTTP requests per domain name 每个域名发起http请求最大并发数 )
var ( AllMarketTypes = map[string]struct{}{ MarketSpot: {}, MarketMargin: {}, MarketLinear: {}, MarketInverse: {}, MarketOption: {}, } AllContractTypes = map[string]struct{}{ MarketSwap: {}, MarketFuture: {}, } )
var ( ParamHandshakeTimeout = "HandshakeTimeout" ParamChanCaps = "ChanCaps" ParamChanCap = "ChanCap" )
var (
DefChanCaps = map[string]int{
"@depth": 1000,
}
)
var (
LocUTC, _ = time.LoadLocation("UTC")
)
Functions ¶
func AlgoOrderID ¶ added in v0.2.64
AlgoOrderID delegates to an optional exchange capability.
func BoolFromInfo ¶ added in v0.2.47
func BuildClientOrderID ¶ added in v0.2.64
func BuildClientOrderID(exchange interface{}, namespace string, orderID int64, clientID string, randomize bool) (string, bool)
BuildClientOrderID delegates formatting to an adapter. The boolean reports whether the adapter exposes the capability; an empty identifier is valid only as the result of an adapter that deliberately returned one.
func BuildLegacyClientOrderID ¶ added in v0.2.64
func BuildLegacyClientOrderID(exchangeName, namespace string, orderID int64, clientID string, randomize bool) string
BuildLegacyClientOrderID preserves the pre-capability format for callers that do not have an adapter instance yet. Exchange-specific layouts remain owned by this boundary rather than being reconstructed by consumers.
func BuildSymbolSet ¶ added in v0.2.48
BuildSymbolSet converts symbols to a lookup set. Returns nil for empty input.
func CheckWsError ¶ added in v0.1.2
CheckWsError 从websocket返回的消息结果中,检查是否有错误信息
func CheckWsErrorWith ¶ added in v0.2.57
func ContextFromParams ¶ added in v0.2.65
ContextFromParams extracts the optional transport context and removes it from the parameter map before venue encoding.
func DefaultCareMarkets ¶ added in v0.2.48
func DefaultCareMarkets() []string
func EnsureArrStr ¶ added in v0.2.0
func FillAccountAccessFromInfo ¶ added in v0.2.47
func FillAccountAccessFromInfo(acc *AccountAccess, info map[string]interface{})
func GetHostFlowChan ¶ added in v0.2.5
func GetHostFlowChan(host string) chan struct{}
func GetHostRetryWait ¶ added in v0.2.5
func GetOrderEventOrderID ¶ added in v0.2.64
GetOrderEventOrderID delegates to the narrow optional capability.
func GetProxy ¶ added in v0.2.54
func GetProxy() string
GetProxy returns the current global proxy URL string, or empty if not set.
func GetWsOutChan ¶ added in v0.1.2
func GetWsOutChan[T any](e *Exchange, chanKey string, create func(int) T, args map[string]interface{}) T
GetWsOutChan 获取指定msgHash的输出通道 如果不存在则创建新的并存储
func IsContract ¶ added in v0.1.3
func IsOrderDone ¶ added in v0.2.1
func IsPermanentWsError ¶ added in v0.2.61
func MergeAccountAccess ¶ added in v0.2.47
func MergeAccountAccess(dst *AccountAccess, src *AccountAccess)
func NewHttpClient ¶ added in v0.2.54
NewHttpClient creates an *http.Client that inherits the global proxy set via SetProxy. Callers may further customise the returned client.
func NormalizeOrderTimestamp ¶ added in v0.2.64
NormalizeOrderTimestamp delegates to an optional exchange capability.
func NormalizePosMode ¶ added in v0.2.47
func ParseClientOrderID ¶ added in v0.2.64
ParseClientOrderID delegates to an optional exchange capability.
func PosModeFromBool ¶ added in v0.2.47
func RedactLogText ¶ added in v0.2.61
func SetBoolArg ¶ added in v0.2.39
func SetHostRetryWait ¶ added in v0.2.5
func SetProxy ¶ added in v0.2.54
SetProxy sets a process-wide HTTP proxy. It also patches http.DefaultTransport so that any code using http.Get / http.DefaultClient automatically goes through the proxy.
- "no" : explicitly disable proxy
- "" : if globalProxy is already set, keep it; otherwise try HTTPS_PROXY / HTTP_PROXY env, then system proxy
- other : use as proxy URL
func TickersToPriceMap ¶ added in v0.2.48
TickersToPriceMap converts tickers to symbol->last price map; filters by symbolSet when provided.
Types ¶
type Account ¶
type Account struct {
Name string
NoTrade bool
Creds *Credential
MarPositions map[string][]*Position // marketType: Position List
MarBalances map[string]*Balances // marketType: Balances
Leverages map[string]int // 币种当前的杠杆倍数
Data map[string]interface{}
LockPos *deadlock.Mutex
LockBalance *deadlock.Mutex
LockLeverage *deadlock.Mutex
LockData *deadlock.Mutex
}
type AccountAccess ¶ added in v0.2.47
type AccountAccess struct {
TradeAllowed bool
TradeKnown bool
WithdrawAllowed bool
WithdrawKnown bool
IPAny bool
IPKnown bool
PosMode string
AcctMode string
AcctLv string
MarginMode string
Info map[string]interface{}
}
func (*AccountAccess) HasAny ¶ added in v0.2.47
func (a *AccountAccess) HasAny() bool
type AccountConfig ¶ added in v0.2.0
type AsyncConn ¶ added in v0.2.4
type AsyncConn struct {
WsConn
// contains filtered or unexported fields
}
type Balances ¶
type BanExchange ¶
type BanExchange interface {
LoadMarkets(reload bool, params map[string]interface{}) (MarketMap, *errs.Error)
GetCurMarkets() MarketMap
GetMarket(symbol string) (*Market, *errs.Error)
/*
Map the original variety ID of the exchange to a standard symbol, where year is the year where the K-line data is located
将交易所原始品种ID映射为标准symbol,year是K线数据所在年
*/
MapMarket(rawID string, year int) (*Market, *errs.Error)
FetchTicker(symbol string, params map[string]interface{}) (*Ticker, *errs.Error)
FetchTickers(symbols []string, params map[string]interface{}) ([]*Ticker, *errs.Error)
FetchTickerPrice(symbol string, params map[string]interface{}) (map[string]float64, *errs.Error)
LoadLeverageBrackets(reload bool, params map[string]interface{}) *errs.Error
InitLeverageBrackets() *errs.Error
GetLeverage(symbol string, notional float64, account string) (float64, float64)
CheckSymbols(symbols ...string) ([]string, []string)
Info() *ExgInfo
FetchOHLCV(symbol, timeframe string, since int64, limit int, params map[string]interface{}) ([]*Kline, *errs.Error)
FetchOrderBook(symbol string, limit int, params map[string]interface{}) (*OrderBook, *errs.Error)
FetchLastPrices(symbols []string, params map[string]interface{}) ([]*LastPrice, *errs.Error)
FetchFundingRate(symbol string, params map[string]interface{}) (*FundingRateCur, *errs.Error)
FetchFundingRates(symbols []string, params map[string]interface{}) ([]*FundingRateCur, *errs.Error)
FetchFundingRateHistory(symbol string, since int64, limit int, params map[string]interface{}) ([]*FundingRate, *errs.Error)
// FetchOrder query given order
FetchOrder(symbol, id string, params map[string]interface{}) (*Order, *errs.Error)
// FetchOrders Get all account orders; active, canceled, or filled. (symbol required)
FetchOrders(symbol string, since int64, limit int, params map[string]interface{}) ([]*Order, *errs.Error)
FetchBalance(params map[string]interface{}) (*Balances, *errs.Error)
FetchAccountAccess(params map[string]interface{}) (*AccountAccess, *errs.Error)
// FetchAccountPositions Get account positions on all symbols
FetchAccountPositions(symbols []string, params map[string]interface{}) ([]*Position, *errs.Error)
// FetchPositions Get position risks (default) or account positions on all symbols
FetchPositions(symbols []string, params map[string]interface{}) ([]*Position, *errs.Error)
// FetchOpenOrders gets open orders for one or all symbols. ParamFullSnapshot
// includes exchange-native conditional order classes and fails unless the
// adapter can prove the result is complete within limit.
FetchOpenOrders(symbol string, since int64, limit int, params map[string]interface{}) ([]*Order, *errs.Error)
FetchIncomeHistory(inType string, symbol string, since int64, limit int, params map[string]interface{}) ([]*Income, *errs.Error)
CreateOrder(symbol, odType, side string, amount, price float64, params map[string]interface{}) (*Order, *errs.Error)
EditOrder(symbol, orderId, side string, amount, price float64, params map[string]interface{}) (*Order, *errs.Error)
CancelOrder(id string, symbol string, params map[string]interface{}) (*Order, *errs.Error)
SetFees(fees map[string]map[string]float64)
CalculateFee(symbol, odType, side string, amount float64, price float64, isMaker bool, params map[string]interface{}) (*Fee, *errs.Error)
SetLeverage(leverage float64, symbol string, params map[string]interface{}) (map[string]interface{}, *errs.Error)
CalcMaintMargin(symbol string, cost float64) (float64, *errs.Error)
Call(method string, params map[string]interface{}) (*HttpRes, *errs.Error)
WatchOrderBooks(symbols []string, limit int, params map[string]interface{}) (chan *OrderBook, *errs.Error)
UnWatchOrderBooks(symbols []string, params map[string]interface{}) *errs.Error
WatchOHLCVs(jobs [][2]string, params map[string]interface{}) (chan *PairTFKline, *errs.Error)
UnWatchOHLCVs(jobs [][2]string, params map[string]interface{}) *errs.Error
WatchMarkPrices(symbols []string, params map[string]interface{}) (chan map[string]float64, *errs.Error)
UnWatchMarkPrices(symbols []string, params map[string]interface{}) *errs.Error
WatchTrades(symbols []string, params map[string]interface{}) (chan *Trade, *errs.Error)
UnWatchTrades(symbols []string, params map[string]interface{}) *errs.Error
WatchMyTrades(params map[string]interface{}) (chan *MyTrade, *errs.Error)
WatchBalance(params map[string]interface{}) (chan *Balances, *errs.Error)
WatchPositions(params map[string]interface{}) (chan []*Position, *errs.Error)
WatchAccountConfig(params map[string]interface{}) (chan *AccountConfig, *errs.Error)
// SetDump Record all websocket messages to the specified file 将websocket所有消息记录到指定文件
SetDump(path string) *errs.Error
// SetReplay Replay all websocket messages from the specified file 从指定文件重放所有websocket消息
SetReplay(path string) *errs.Error
// GetReplayTo Retrieve the 13 bit timestamp of the next message to be replayed, with sys. MaxInt64 indicating no next message 获取下一个要重放的消息13位时间戳,sys.MaxInt64表示无下一个消息
GetReplayTo() int64
// ReplayOne Replay the next websocket message 重放下一个websocket消息
ReplayOne() *errs.Error
// ReplayAll Replay all recorded websocket messages 重放所有记录的websocket消息
ReplayAll() *errs.Error
// SetOnWsChan Trigger callback when creating a new websocket message chan 创建新websocket消息chan时触发回调
SetOnWsChan(cb FuncOnWsChan)
PrecAmount(m *Market, amount float64) (float64, *errs.Error)
PrecPrice(m *Market, price float64) (float64, *errs.Error)
PrecCost(m *Market, cost float64) (float64, *errs.Error)
PrecFee(m *Market, fee float64) (float64, *errs.Error)
HasApi(key, market string) bool
SetOnHost(cb func(n string) string)
PriceOnePip(symbol string) (float64, *errs.Error)
IsContract(marketType string) bool
MilliSeconds() int64
GetAccount(id string) (*Account, *errs.Error)
SetMarketType(marketType, contractType string) *errs.Error
GetExg() *Exchange
Close() *errs.Error
GetNetDisable() bool
SetNetDisable(v bool)
}
type BaseLvgBracket ¶ added in v0.2.44
type BaseLvgBracket struct {
Bracket int `json:"bracket"` // tier level
InitialLeverage int `json:"initialLeverage"` // max initial leverage for this tier
MaintMarginRatio float64 `json:"maintMarginRatio"` // maintenance margin ratio
Cum float64 `json:"cum"` // cumulative maintenance margin
}
BaseLvgBracket holds leverage tier information shared across exchanges.
type ChainNetwork ¶
type ClientOrderCapability ¶ added in v0.2.64
type ClientOrderCapability interface {
BuildClientOrderID(namespace string, orderID int64, clientID string, randomize bool) string
}
ClientOrderCapability exposes the adapter-owned client order ID contract. Different exchanges impose different character sets and layouts, so the caller must not construct these identifiers from an exchange name.
func GetClientOrderCapability ¶ added in v0.2.64
func GetClientOrderCapability(exchange interface{}) ClientOrderCapability
GetClientOrderCapability returns the optional adapter capability.
type ClientOrderIDCapability ¶ added in v0.2.64
type ClientOrderIDCapability = ClientOrderCapability
ClientOrderIDCapability is an alias for callers that use the identifier terminology already present in normalized order data.
type CodeLimits ¶
type CodeLimits struct {
Amount *LimitRange
Withdraw *LimitRange
Deposit *LimitRange
}
func (*CodeLimits) ToString ¶ added in v0.1.2
func (l *CodeLimits) ToString() string
type Credential ¶
func (*Credential) CheckFilled ¶ added in v0.1.2
func (c *Credential) CheckFilled(keys map[string]bool) *errs.Error
type Currency ¶
type Currency struct {
ID string
Name string
Code string
Type string
NumericID int
Precision float64
PrecMode int // 保留精度的模式:PrecModeDecimalPlace/PrecModeSignifDigits/PrecModeTickSize
Active bool
Deposit bool
Withdraw bool
Networks []*ChainNetwork
Fee float64
Fees map[string]float64
Limits *CodeLimits
Info map[string]interface{}
}
type CurrencyMap ¶
************************** Currency **************************
type Exchange ¶
type Exchange struct {
*ExgInfo
Hosts *ExgHosts
Fees *ExgFee
Apis map[string]*Entry // 所有API的路径
Has map[string]map[string]int // 是否定义了某个API
Options map[string]interface{} // 用户传入的配置
Proxy func(*http.Request) (*url.URL, error)
CredKeys map[string]bool // cred keys required for exchange
Accounts map[string]*Account // name: account
DefAccName string // default account name
EnableRateLimit int // 是否启用请求速率控制:BoolNull/BoolTrue/BoolFalse
RateLimit int64 // 请求速率控制毫秒数,最小间隔单位
CalcRateLimiterCost FuncCalcRateLimiterCost
MapApiError FuncMapApiError
WsTimeout int64 // websocket msg timeout in milliseconds
WsChecking bool
MarketsWait chan interface{} // whether is loading markets
CareMarkets []string // markets to be fetch: spot/linear/inverse/option
Symbols []string
IDs []string
TimeFrames map[string]string // map timeframe from common to specific
CurrCodeMap map[string]string // common code maps
Retries map[string]int // retry nums for methods
TimeDelay int64 // 系统时钟延迟的毫秒数
HttpClient *http.Client
NetDisable bool
WSClients map[string]*WsClient // accName@url: websocket clients
WsIntvs map[string]int // milli secs interval for ws endpoints
WsOutChans map[string]interface{} // accName@url+msgHash: chan Type
WsChanRefs map[string]map[string]struct{} // accName@url+msgHash: symbols use this chan
WsCache []*WsLog // websocket cache logs waiting for replay/dump
WsNextMS int64 // timestamp of next replay log
WsReplayTo int64 // timestamp of latest replay log
WsFile *os.File // file to replay/dump
WsWriter *gzip.Writer
WsEncoder *gob.Encoder
WsReader *gzip.Reader
WsDecoder *gob.Decoder
WsBatchSize int
WsReplayFn map[string]func(item *WsLog) *errs.Error
KeyTimeStamps map[string]int64 // key: int64 更新的时间戳
// for calling sub struct func in parent struct
Sign FuncSign
FetchCurrencies FuncFetchCurr
FetchMarkets FuncFetchMarkets
AuthWS FuncAuthWS
CalcFee FuncCalcFee
GetRetryWait func(e *errs.Error) int // 根据错误信息计算重试间隔秒数,<0表示无需重试
CheckWsTimeout func()
OnWsMsg FuncOnWsMsg
OnWsErr FuncOnWsErr
OnWsClose FuncOnWsClose
OnWsReCon FuncOnWsReCon
OnWsChan FuncOnWsChan
Flags map[string]string
// contains filtered or unexported fields
}
func (*Exchange) AddWsChanRefs ¶ added in v0.1.2
func (*Exchange) AlgoOrderID ¶ added in v0.2.64
func (*Exchange) CacheApiRes ¶ added in v0.2.20
func (*Exchange) CalcMaintMargin ¶ added in v0.1.2
func (*Exchange) CalculateFee ¶ added in v0.1.2
func (*Exchange) CancelOrder ¶ added in v0.1.2
func (*Exchange) CheckRiskyAllowed ¶ added in v0.2.42
CheckRiskyAllowed 检查当前账户是否允许执行危险操作 如果api.Risky为true且账户NoTrade为true,返回错误
func (*Exchange) CheckSymbols ¶ added in v0.1.3
CheckSymbols split valid and invalid symbols
func (*Exchange) CloseWsFile ¶ added in v0.2.3
func (e *Exchange) CloseWsFile()
func (*Exchange) CreateOrder ¶ added in v0.1.2
func (*Exchange) DelWsChanRefs ¶ added in v0.1.2
func (*Exchange) FetchAccountAccess ¶ added in v0.2.47
func (e *Exchange) FetchAccountAccess(params map[string]interface{}) (*AccountAccess, *errs.Error)
func (*Exchange) FetchAccountPositions ¶ added in v0.2.6
func (*Exchange) FetchBalance ¶ added in v0.1.2
func (*Exchange) FetchFundingRate ¶ added in v0.2.7
func (*Exchange) FetchFundingRateHistory ¶ added in v0.2.6
func (*Exchange) FetchFundingRates ¶ added in v0.2.7
func (*Exchange) FetchIncomeHistory ¶ added in v0.2.6
func (*Exchange) FetchLastPrices ¶ added in v0.2.7
func (*Exchange) FetchOHLCV ¶ added in v0.1.2
func (*Exchange) FetchOpenOrders ¶ added in v0.1.2
func (*Exchange) FetchOrder ¶ added in v0.2.6
func (*Exchange) FetchOrderBook ¶ added in v0.1.2
func (*Exchange) FetchOrders ¶ added in v0.1.2
func (*Exchange) FetchPositions ¶ added in v0.1.2
func (*Exchange) FetchTicker ¶ added in v0.1.2
func (*Exchange) FetchTickerPrice ¶ added in v0.2.6
func (*Exchange) FetchTickers ¶ added in v0.1.2
func (*Exchange) FindWSClient ¶ added in v0.2.61
func (*Exchange) GetAccName ¶ added in v0.1.2
func (*Exchange) GetAccount ¶ added in v0.1.2
func (*Exchange) GetAccountCreds ¶ added in v0.1.2
func (*Exchange) GetArgsMarket ¶ added in v0.1.2
GetArgsMarket 从symbol和args中的market+inverse得到对应的Market对象
func (*Exchange) GetArgsMarketType ¶ added in v0.1.2
func (*Exchange) GetCacheKey ¶ added in v0.2.20
func (*Exchange) GetClientContext ¶ added in v0.2.65
func (e *Exchange) GetClientContext(ctx context.Context, wsUrl string, marketType, accName string) (*WsClient, *errs.Error)
GetClientContext bounds only client initialization; an established stream and its reconnects remain independent of the request deadline.
func (*Exchange) GetCurMarkets ¶ added in v0.1.2
func (*Exchange) GetLeverage ¶ added in v0.2.0
func (*Exchange) GetMarket ¶ added in v0.1.2
GetMarket 获取市场信息
symbol ccxt的symbol、交易所的ID,必须严格正确,如果可能错误, 根据当前的MarketType和MarketInverse过滤匹配
func (*Exchange) GetMarketBy ¶ added in v0.2.38
func (*Exchange) GetMarketById ¶ added in v0.1.2
GetMarketById get market by exchange id (Upper Required!)
func (*Exchange) GetMarketIDByArgs ¶ added in v0.1.2
func (*Exchange) GetNetDisable ¶ added in v0.2.33
func (*Exchange) GetOrderEventOrderID ¶ added in v0.2.64
func (*Exchange) GetPriceOnePip ¶ added in v0.1.2
func (*Exchange) GetReplayTo ¶ added in v0.2.3
func (*Exchange) GetRetryNum ¶ added in v0.1.2
GetRetryNum 返回失败时重试次数,未设置时默认0
func (*Exchange) GetTimeFrame ¶ added in v0.1.2
func (*Exchange) InitLeverageBrackets ¶ added in v0.2.31
func (*Exchange) IsContract ¶ added in v0.1.2
func (*Exchange) LoadArgsMarket ¶ added in v0.1.2
func (e *Exchange) LoadArgsMarket(symbol string, params map[string]interface{}) (map[string]interface{}, *Market, *errs.Error)
LoadArgsMarket LoadMarkets && GetArgsMarket
func (*Exchange) LoadArgsMarketType ¶ added in v0.1.2
func (*Exchange) LoadLeverageBrackets ¶ added in v0.1.2
func (*Exchange) LoadMarkets ¶ added in v0.1.2
func (*Exchange) MilliSeconds ¶ added in v0.1.2
func (*Exchange) NormalizeOrderTimestamp ¶ added in v0.2.64
func (*Exchange) ParseClientOrderID ¶ added in v0.2.64
The base exchange provides explicit no-correlation semantics for adapters that do not have exchange-specific order event identifiers.
func (*Exchange) PopAccName ¶ added in v0.2.1
func (*Exchange) PrecAmount ¶ added in v0.1.2
func (*Exchange) PriceOnePip ¶ added in v0.1.2
PriceOnePip Get's the "1 pip" value for this pair.
Used in PriceFilter to calculate the 1pip movements.
func (*Exchange) RequestApi ¶ added in v0.1.2
func (e *Exchange) RequestApi(ctx context.Context, cacheKey string, api *Entry, params map[string]interface{}, cache, debug bool) *HttpRes
RequestApi Request exchange API without checking cache Concurrency control: Same host, default concurrent 3 times at the same time
请求交易所API,不检查缓存 并发控制:同一个host,默认同时并发3
func (*Exchange) RequestApiRetry ¶ added in v0.1.2
func (*Exchange) RequestApiRetryAdv ¶ added in v0.2.20
func (*Exchange) SafeCurrency ¶ added in v0.1.2
func (*Exchange) SafeCurrencyCode ¶ added in v0.1.2
func (*Exchange) SafeSymbol ¶ added in v0.1.2
SafeSymbol 将交易所品种ID转为规范化品种ID
marketType TradeSpot/TradeMargin/TradeSwap/TradeFuture/TradeOption
linear/inverse
func (*Exchange) SetLeverage ¶ added in v0.1.2
func (*Exchange) SetMarketType ¶ added in v0.1.2
func (*Exchange) SetNetDisable ¶ added in v0.2.33
func (*Exchange) SetOnWsChan ¶ added in v0.2.3
func (e *Exchange) SetOnWsChan(cb FuncOnWsChan)
func (*Exchange) UnWatchMarkPrices ¶ added in v0.2.1
func (*Exchange) UnWatchOHLCVs ¶ added in v0.2.1
func (*Exchange) UnWatchOrderBooks ¶ added in v0.2.1
func (*Exchange) UnWatchTrades ¶ added in v0.2.1
func (*Exchange) WSClientSnapshot ¶ added in v0.2.61
func (*Exchange) WaitWsCheck ¶ added in v0.2.61
func (*Exchange) WatchAccountConfig ¶ added in v0.2.1
func (e *Exchange) WatchAccountConfig(params map[string]interface{}) (chan *AccountConfig, *errs.Error)
func (*Exchange) WatchBalance ¶ added in v0.2.1
func (*Exchange) WatchMarkPrices ¶ added in v0.2.1
func (*Exchange) WatchMyTrades ¶ added in v0.2.1
func (*Exchange) WatchOHLCVs ¶ added in v0.2.1
func (*Exchange) WatchOrderBooks ¶ added in v0.2.1
func (*Exchange) WatchPositions ¶ added in v0.2.1
type ExecutionCapability ¶ added in v0.2.65
type ExecutionCapability interface {
VerifyExecution(context.Context, string, string) (ExecutionProof, *errs.Error)
}
ExecutionCapability is an optional adapter-owned live execution contract. VerifyExecution must perform only read-only checks; all subsequent SDK calls receive ParamContext and are expected to honor its cancellation.
type ExecutionProof ¶ added in v0.2.65
type ExecutionProof struct {
Account string
Currency string
EvidenceID string
ContextBound bool
StableClientID bool
QueryClientID bool
AuthoritativeNotFound bool
CompleteCumulativeReports bool
CompleteAccountSnapshot bool
SettledCash bool
NetLinearPositions bool
PostOnly bool
}
ExecutionProof is the venue capability evidence consumed by higher-level execution engines. Flags describe observed, verified behavior; they are not configuration declarations.
type ExgHosts ¶
type ExgInfo ¶ added in v0.2.1
type ExgInfo struct {
ID string // 交易所ID
Name string // 显示名称
Countries []string // 可用国家
NoHoliday bool // true表示365天全年开放
FullDay bool // true表示一天24小时可交易
Min1mHole int // 1分钟K线空洞的最小间隔,少于此认为正常无交易而非空洞
FixedLvg bool // 杠杆倍率是否固定不可修改
DebugWS bool // 是否输出WS调试信息
DebugAPI bool // 是否输出API请求测试信息
UserAgent string // UserAgent of http request
ReqHeaders map[string]string // http headers for request exchange
CurrenciesById CurrencyMap // CurrencyMap index by id
CurrenciesByCode CurrencyMap // CurrencyMap index by code
Markets MarketMap // cache for all markets
MarketsById MarketArrMap // markets index by id
OrderBooks map[string]*OrderBook // symbol: OrderBook update by wss
MarkPrices map[string]map[string]float64 // marketType: symbol: mark price
OdBookLock deadlock.Mutex
MarkPriceLock deadlock.Mutex
MarketsByIdLock deadlock.Mutex
MarketsLock deadlock.Mutex
CurrByCodeLock deadlock.Mutex
CurrByIdLock deadlock.Mutex
PrecPadZero bool // padding zero for precision
MarketType string // MarketSpot/MarketMargin/MarketLinear/MarketInverse/MarketOption
ContractType string // MarketSwap/MarketFuture
MarginMode string // MarginCross/MarginIsolated
TimeInForce string // GTC/IOC/FOK
}
type FeeTierItem ¶
type FeeTiers ¶
type FeeTiers struct {
Taker []*FeeTierItem
Maker []*FeeTierItem
}
type FuncAuthWS ¶ added in v0.2.1
type FuncCalcFee ¶ added in v0.2.1
type FuncCalcRateLimiterCost ¶ added in v0.2.5
type FuncFetchCurr ¶
type FuncFetchCurr = func(params map[string]interface{}) (CurrencyMap, *errs.Error)
type FuncFetchMarkets ¶
type FuncMapApiError ¶ added in v0.2.57
type FuncOnWsChan ¶ added in v0.2.3
type FuncOnWsChan = func(key string, out interface{})
key: acc@url#marketType@method
type FuncOnWsClose ¶
type FuncOnWsErr ¶
type FuncOnWsMethod ¶
type FuncOnWsMsg ¶
type FuncOnWsReCon ¶ added in v0.2.1
type FundingCash ¶ added in v0.2.65
type FundingCashCapability ¶ added in v0.2.65
type FundingRate ¶ added in v0.2.6
type FundingRateCur ¶ added in v0.2.7
type FundingRateCur struct {
Symbol string `json:"symbol"`
FundingRate float64 `json:"fundingRate"`
Timestamp int64 `json:"timestamp"`
MarkPrice float64 `json:"markPrice,omitempty"`
IndexPrice float64 `json:"indexPrice,omitempty"`
InterestRate float64 `json:"interestRate,omitempty"`
EstimatedSettlePrice float64 `json:"estimatedSettlePrice,omitempty"`
FundingTimestamp int64 `json:"fundingTimestamp,omitempty"`
NextFundingRate float64 `json:"nextFundingRate,omitempty"`
NextFundingTimestamp int64 `json:"nextFundingTimestamp,omitempty"`
PrevFundingRate float64 `json:"prevFundingRate,omitempty"`
PrevFundingTimestamp int64 `json:"prevFundingTimestamp,omitempty"`
Interval string `json:"interval,omitempty"`
Info map[string]interface{} `json:"info"`
}
type HttpHeader ¶ added in v0.1.2
func (HttpHeader) MarshalLogObject ¶ added in v0.1.2
func (h HttpHeader) MarshalLogObject(enc zapcore.ObjectEncoder) error
type ISymbolLvgBracket ¶ added in v0.2.44
type ISymbolLvgBracket interface {
ToStdBracket() *SymbolLvgBrackets
GetSymbol() string
}
ISymbolLvgBracket converts exchange-specific brackets to normalized brackets.
type Kline ¶
type LastPrice ¶ added in v0.2.7
type LastPrice struct {
Symbol string `json:"symbol"`
Timestamp int64 `json:"timestamp"`
Price float64 `json:"price"`
Info map[string]interface{} `json:"info"`
}
func TickersToLastPrices ¶ added in v0.2.48
TickersToLastPrices converts tickers to last price list; filters by symbolSet when provided.
type LimitRange ¶
func (*LimitRange) ToString ¶ added in v0.1.2
func (r *LimitRange) ToString() string
type LvgBracket ¶ added in v0.2.44
type LvgBracket struct {
BaseLvgBracket
Capacity float64
Floor float64
}
LvgBracket is a normalized leverage bracket with floor/capacity.
type Market ¶
type Market struct {
ID string `json:"id"`
LowercaseID string `json:"lowercaseId"`
Symbol string `json:"symbol"`
Base string `json:"base"`
Quote string `json:"quote"`
Settle string `json:"settle"`
BaseID string `json:"baseId"`
QuoteID string `json:"quoteId"`
SettleID string `json:"settleId"`
ExgReal string `json:"exgReal"`
Type string `json:"type"` // spot/linear/inverse/option 无法区分margin 和ccxt的值不同
Combined bool `json:"combined"` // 是否是二次组合的数据
Spot bool `json:"spot"` // 现货市场
Margin bool `json:"margin"` // 保证金杠杆市场
Swap bool `json:"swap"` // 期货永续合约市场
Future bool `json:"future"` // 期货市场
Option bool `json:"option"` // 期权市场
Active bool `json:"active"` // 是否可交易
Contract bool `json:"contract"` // 是否是合约
Linear bool `json:"linear"` // usd-based contract
Inverse bool `json:"inverse"` // coin-based contract
Taker float64 `json:"taker"` // 吃单方费率
Maker float64 `json:"maker"` // 挂单方费率
ContractSize float64 `json:"contractSize"`
Expiry int64 `json:"expiry"` // 过期的13毫秒数
ExpiryDatetime string `json:"expiryDatetime"`
Strike float64 `json:"strike"`
OptionType string `json:"optionType"`
DayTimes [][2]int64 `json:"dayTimes"` // 日盘交易时间
NightTimes [][2]int64 `json:"nightTimes"` // 夜盘交易时间
Precision *Precision `json:"precision"`
Limits *MarketLimits `json:"limits"`
Created int64 `json:"created"`
FeeSide string `json:"feeSide"` // get/give/base/quote/other
Info map[string]interface{} `json:"info"`
Fee interface{}
}
func (*Market) GetTradeTimes ¶ added in v0.2.1
type MarketArrMap ¶
type MarketLimits ¶
type MarketLimits struct {
Leverage *LimitRange `json:"leverage"`
Amount *LimitRange `json:"amount"`
Price *LimitRange `json:"price"`
Cost *LimitRange `json:"cost"`
Market *LimitRange `json:"market"`
}
func (*MarketLimits) ToString ¶ added in v0.1.2
func (l *MarketLimits) ToString() string
type MyTrade ¶
type MyTrade struct {
Trade
Filled float64 `json:"filled"` // 订单累计成交量(不止当前交易)
ClientID string `json:"clientID"` // 客户端订单ID
AlgoId string `json:"algoId"` // 触发此订单的算法订单ID(OKX触发单触发后会生成新ordId)
Average float64 `json:"average"` // 平均成交价格
State string `json:"state"` // 状态
PosSide string `json:"posSide"` // 持仓方向 long/short
ReduceOnly bool `json:"reduceOnly"` // 是否是只减仓单
Info map[string]interface{} `json:"info"`
}
type OHLCVArchiveFetcher ¶ added in v0.2.62
type OHLCVArchiveFetcher interface {
FetchOHLCVArchive(ctx context.Context, symbol, timeframe string, startMS, endMS int64) (
klines []*Kline, available bool, err *errs.Error)
}
OHLCVArchiveFetcher is an optional exchange capability for immutable historical candlestick files. Callers can fall back to FetchOHLCV when available is false; an error means the archive request itself failed.
type OdBookShotLog ¶ added in v0.2.3
type OdBookSide ¶ added in v0.2.3
type OdBookSide struct {
IsBuy bool `json:"is_buy"`
Price []float64 `json:"price"` // bid: desc ask: asc
Size []float64 `json:"size"`
Depth int `json:"depth"`
Lock deadlock.Mutex
}
OdBookSide On one side of the order book. No need to add a lock, as only one goroutine can be modified 订单簿一侧。不需要加锁,因为只有一个goroutine可以修改
func NewOdBookSide ¶ added in v0.2.3
func NewOdBookSide(isBuy bool, depth int, deltas [][2]float64) *OdBookSide
func (*OdBookSide) AvgPrice ¶ added in v0.2.3
func (obs *OdBookSide) AvgPrice(volume float64) (float64, float64, float64)
AvgPrice return average price, filled rate, change rate of first & last
func (*OdBookSide) Level ¶ added in v0.2.6
func (obs *OdBookSide) Level(i int) (float64, float64)
Level return price&size for given level (i is started from 0)
func (*OdBookSide) Set ¶ added in v0.2.3
func (obs *OdBookSide) Set(price, size float64)
func (*OdBookSide) SumVolTo ¶ added in v0.2.3
func (obs *OdBookSide) SumVolTo(price float64) (float64, float64)
SumVolTo return (total volume to price, filled rate)
func (*OdBookSide) Update ¶ added in v0.2.3
func (obs *OdBookSide) Update(deltas [][2]float64)
type Order ¶
type Order struct {
Info map[string]interface{} `json:"info"`
ID string `json:"id"`
ClientOrderID string `json:"clientOrderId"`
Datetime string `json:"datetime"`
Timestamp int64 `json:"timestamp"`
LastTradeTimestamp int64 `json:"lastTradeTimestamp"`
LastUpdateTimestamp int64 `json:"lastUpdateTimestamp"`
Status string `json:"status"`
Symbol string `json:"symbol"`
Type string `json:"type"`
TimeInForce string `json:"timeInForce"`
PositionSide string `json:"positionSide"`
Side string `json:"side"`
Price float64 `json:"price"`
Average float64 `json:"average"`
Amount float64 `json:"amount"`
Filled float64 `json:"filled"`
Remaining float64 `json:"remaining"`
TriggerPrice float64 `json:"triggerPrice"`
StopPrice float64 `json:"stopPrice"`
TakeProfitPrice float64 `json:"takeProfitPrice"`
StopLossPrice float64 `json:"stopLossPrice"`
Cost float64 `json:"cost"`
PostOnly bool `json:"postOnly"`
ReduceOnly bool `json:"reduceOnly"`
Trades []*Trade `json:"trades"`
Fee *Fee `json:"fee"`
}
type OrderBook ¶
type OrderBook struct {
Symbol string `json:"symbol"`
TimeStamp int64 `json:"timestamp"`
Asks *OdBookSide `json:"asks"`
Bids *OdBookSide `json:"bids"`
Nonce int64 `json:"nonce"` // latest update id
Limit int `json:"limit"`
Cache []map[string]string
}
type OrderEventCapability ¶ added in v0.2.64
type OrderEventCapability interface {
OrderEventOrderIDCapability
ParseClientOrderID(botName, clientID string) int64
AlgoOrderID(trade *MyTrade) string
NormalizeOrderTimestamp(order *Order, fallback int64) int64
}
OrderEventCapability contains exchange-owned order event semantics. The base Exchange supplies explicit no-correlation defaults for adapters that do not need exchange-specific handling.
func GetOrderEventCapability ¶ added in v0.2.64
func GetOrderEventCapability(exg interface{}) OrderEventCapability
GetOrderEventCapability returns an exchange capability when it is exposed, otherwise a safe implementation that never guesses an order association.
type OrderEventOrderIDCapability ¶ added in v0.2.64
OrderEventOrderIDCapability is the narrow optional capability needed to map a triggered trade to its canonical algo order ID.
type PairTFKline ¶ added in v0.1.3
type Position ¶
type Position struct {
ID string `json:"id"`
Symbol string `json:"symbol"`
TimeStamp int64 `json:"timestamp"`
Isolated bool `json:"isolated"` // 隔离
Hedged bool `json:"hedged"` // 对冲
Side string `json:"side"` // long or short
Contracts float64 `json:"contracts"` // 合约数量
ContractSize float64 `json:"contractSize"` // 单份合约价值
EntryPrice float64 `json:"entryPrice"` // 入场价格
MarkPrice float64 `json:"markPrice"` // 标记价格
Notional float64 `json:"notional"` // 名义价值
Leverage int `json:"leverage"` // 杠杆倍数
Collateral float64 `json:"collateral"` // 当前保证金:初始保证金+未实现盈亏
InitialMargin float64 `json:"initialMargin"` // 初始保证金额
MaintMargin float64 `json:"maintenanceMargin"` // 维持保证金额
InitialMarginPct float64 `json:"initialMarginPercentage"` // 初始保证金率
MaintMarginPct float64 `json:"maintenanceMarginPercentage"` // 维持保证金率
UnrealizedPnl float64 `json:"unrealizedPnl"` // 未实现盈亏
LiquidationPrice float64 `json:"liquidationPrice"` // 清算价格
MarginMode string `json:"marginMode"` // cross/isolated
MarginRatio float64 `json:"marginRatio"`
Percentage float64 `json:"percentage"` // 未实现盈亏百分比
Info map[string]interface{} `json:"info"`
}
type Precision ¶
type Precision struct {
Amount float64 `json:"amount"`
Price float64 `json:"price"`
Base float64 `json:"base"`
Quote float64 `json:"quote"`
ModeAmount int `json:"modeAmount"` // PrecModeTickSize/PrecModeSignifDigits/PrecModeDecimalPlace
ModePrice int `json:"modePrice"`
ModeBase int `json:"modeBase"`
ModeQuote int `json:"modeQuote"`
}
type PriceSymbolCapability ¶ added in v0.2.64
PriceSymbolCapability exposes adapter-owned quote and identifier semantics for symbols that cannot be represented by generic slash-delimited markets.
type SymbolLvgBrackets ¶ added in v0.2.44
type SymbolLvgBrackets struct {
Symbol string `json:"symbol"`
NotionalCoef float64 `json:"notionalCoef"`
Brackets []*LvgBracket
}
SymbolLvgBrackets holds all leverage brackets for a symbol or family.
type SymbolScopedMarketLoader ¶ added in v0.2.64
type SymbolScopedMarketLoader interface {
LoadMarketsForSymbols(reload bool, symbols []string) (MarketMap, *errs.Error)
}
SymbolScopedMarketLoader is an optional adapter capability for exchanges whose market metadata can only be loaded for an explicit symbol set. Generic callers must not infer this behavior from the market type.
type Ticker ¶
type Ticker struct {
Symbol string `json:"symbol"`
TimeStamp int64 `json:"timestamp"`
Bid float64 `json:"bid"`
BidVolume float64 `json:"bidVolume"`
Ask float64 `json:"ask"`
AskVolume float64 `json:"askVolume"`
High float64 `json:"high"`
Low float64 `json:"low"`
Open float64 `json:"open"`
Close float64 `json:"close"`
Last float64 `json:"last"`
Change float64 `json:"change"`
Percentage float64 `json:"percentage"`
Average float64 `json:"average"`
Vwap float64 `json:"vwap"`
BaseVolume float64 `json:"baseVolume"`
QuoteVolume float64 `json:"quoteVolume"`
PreviousClose float64 `json:"previousClose"`
MarkPrice float64 `json:"markPrice"`
IndexPrice float64 `json:"indexPrice"`
Info map[string]interface{} `json:"info"`
}
func FilterTickers ¶ added in v0.2.48
FilterTickers filters tickers by symbolSet when provided.
type Trade ¶
type Trade struct {
ID string `json:"id"` // 交易ID
Symbol string `json:"symbol"` // 币种ID
Side string `json:"side"` // buy/sell
Type string `json:"type"` // market/limit
Amount float64 `json:"amount"` // 当前交易的数量
Price float64 `json:"price"` // 价格
Cost float64 `json:"cost"` // 当前交易花费
Order string `json:"order"` // 当前交易所属订单号
Timestamp int64 `json:"timestamp"` // 时间戳
Maker bool `json:"maker"` // 是否maker
Fee *Fee `json:"fee"` // 手续费
Info map[string]interface{} `json:"info"`
}
type WebSocket ¶
type WebSocket struct {
// contains filtered or unexported fields
}
func (*WebSocket) NextWriter ¶ added in v0.1.2
func (ws *WebSocket) NextWriter() (io.WriteCloser, error)
func (*WebSocket) WriteClose ¶ added in v0.1.2
type WsClient ¶
type WsClient struct {
Exg *Exchange
URL string
LogURL string
AccName string
MarketType string
Key string
Debug bool
JobInfos map[string]*WsJobInfo // request id: Sub Data
ChanCaps map[string]int // msgHash: cap size of cache msg
SubscribeKeys map[string]int // Subscription key, used to restore subscription after reconnection 订阅的key,用于重连后恢复订阅
SubsKeyStamps map[string]int64 // 记录订阅key上次收到消息的时间戳,用于检测超时自动重新订阅
OnMessage func(client *WsClient, msg *WsMsg)
OnError func(client *WsClient, err *errs.Error)
OnClose func(client *WsClient, err *errs.Error)
OnReConn func(client *WsClient, connID int) *errs.Error
NextConnId int
// contains filtered or unexported fields
}
func (*WsClient) DeferConnReady ¶ added in v0.2.61
func (*WsClient) GetConnSubStats ¶ added in v0.2.23
func (*WsClient) GetSubKeys ¶ added in v0.2.4
func (*WsClient) HandleRawMsg ¶ added in v0.2.3
func (*WsClient) HasSubKeyPrefix ¶ added in v0.2.46
HasSubKeyPrefix checks if any subscription key starts with the given prefix.
func (*WsClient) LockOdBookLimits ¶ added in v0.2.23
func (*WsClient) MarkConnReady ¶ added in v0.2.61
func (*WsClient) SetSubsKeyStamp ¶ added in v0.2.21
func (*WsClient) UpdateSubs ¶ added in v0.2.1
func (*WsClient) Write ¶ added in v0.1.2
Write send a message to the WS server to set the information required for processing task results 发送消息到ws服务器,可设置处理任务结果需要的信息 jobID: The task ID of this message uniquely identifies this request 此次消息的任务ID,唯一标识此次请求 jobInfo: The main information of this task will be used when receiving the task results 此次任务的主要信息,在收到任务结果时使用
func (*WsClient) WriteRaw ¶ added in v0.2.46
WriteRaw sends raw bytes without JSON marshaling (e.g., for OKX ping/pong)
func (*WsClient) WriteRecovery ¶ added in v0.2.61
type WsJobInfo ¶
type WsJobInfo struct {
ID string
MsgHash string
Name string
Symbols []string
Method func(client *WsClient, msg map[string]string, info *WsJobInfo)
Params map[string]interface{}
}
WsJobInfo store callback data for calling websocket API. Used for processing when returning results. 调用websocket api时暂存的任务信息。用于返回结果时处理。