banexg

package module
v0.2.13 Latest Latest
Warning

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

Go to latest
Published: Jan 29, 2025 License: MIT Imports: 26 Imported by: 16

README

BanExg - CryptoCurrency Exchange Trading Library

A Go library for cryptocurrency trading, whose most interfaces are consistent with CCXT.
Note: This project is currently in the pre-release state, the main interface test has passed, but it has not yet been tested in the long-term production environment.
Currently supported exchanges: binance, china. Both implement the interface BanExchange

How to Use

var options = map[string]interface{}{}
// more option keys can be found by type `banexg.Opt...`
options[banexg.OptMarketType] = banexg.MarketLinear  // usd based future market
exchange, err := bex.New('binance', options)

// You can also instantiate an exchange object directly
// exchange, err := binance.NewExchange(options)

// exchange is a BanExchange interface object
res, err := exg.FetchOHLCV("ETH/USDT:USDT", "1d", 0, 10, nil)
if err != nil {
    panic(err)
}
for _, k := range res {
    fmt.Printf("%v, %v %v %v %v %v\n", k.Time, k.Open, k.High, k.Low, k.Close, int(k.Volume))
}

Complete Initialization Options

// The following parameters can be passed when initializing the exchange object
var options = map[string]interface{}{
    // Proxy server address
    banexg.OptProxy: "http://127.0.0.1:7890",  
    
    // API key configuration method 1: directly configure a single account
    banexg.OptApiKey: "your-api-key",      // API Key
    banexg.OptApiSecret: "your-secret",    // API Secret
    
    // API key configuration method 2: configure multiple accounts
    banexg.OptAccCreds: map[string]map[string]interface{}{
        "account1": {
            "ApiKey": "key1",
            "ApiSecret": "secret1", 
        },
        "account2": {
            "ApiKey": "key2", 
            "ApiSecret": "secret2",
        },
    },
    banexg.OptAccName: "account1",  // Set default account
    
    // HTTP request related
    banexg.OptUserAgent: "Mozilla/5.0",  // Custom User-Agent
    banexg.OptReqHeaders: map[string]string{  // Custom request headers
        "X-Custom": "value",
    },
    
    // Market type settings
    banexg.OptMarketType: banexg.MarketLinear,     // Set default market type: spot/contract etc
    banexg.OptContractType: banexg.MarketSwap,     // Set contract type: perpetual/delivery
    banexg.OptTimeInForce: banexg.TimeInForceGTC,  // Order validity type
    
    // WebSocket related
    banexg.OptWsIntvs: map[string]int{  // WebSocket subscription intervals (milliseconds)
        "WatchOrderBooks": 100,  // Orderbook subscription interval
    },
    
    // API retry settings
    banexg.OptRetries: map[string]int{  // API call retry count
        "FetchOrderBook": 3,     // Retry 3 times when fetching orderbook
        "FetchPositions": 2,     // Retry 2 times when fetching positions
    },
    
    // API cache settings
    banexg.OptApiCaches: map[string]int{  // API result cache time (seconds)
        "FetchMarkets": 3600,    // Cache market info for 1 hour
    },
    
    // Fee settings
    banexg.OptFees: map[string]map[string]float64{
        "linear": {              // USDT-M contract fees
            "maker": 0.0002,     // Maker fee rate
            "taker": 0.0004,     // Taker fee rate
        },
        "inverse": {             // Coin-M contract fees
            "maker": 0.0001,
            "taker": 0.0005,
        },
    },
    
    // Debug options
    banexg.OptDebugWS: true,    // Print WebSocket debug info
    banexg.OptDebugAPI: true,   // Print API debug info
    
    // Data capture and replay
    banexg.OptDumpPath: "./ws_dump",      // WebSocket data save path
    banexg.OptDumpBatchSize: 1000,        // Number of messages per batch save
    banexg.OptReplayPath: "./ws_replay",  // Replay data path
}

// Create exchange instance with parameters
exchange, err := bex.New("binance", options)
if err != nil {
    panic(err) 
}

All above parameters are optional, pass according to actual needs. Some important notes:

  1. API key configuration supports two methods:

    • Directly configure single account via OptApiKey and OptApiSecret
    • Configure multiple accounts via OptAccCreds and specify default account with OptAccName
  2. Market type (OptMarketType) options:

    • MarketSpot: Spot
    • MarketMargin: Margin
    • MarketLinear: USDT-M Futures
    • MarketInverse: Coin-M Futures
    • MarketOption: Options
  3. Contract type (OptContractType) options:

    • MarketSwap: Perpetual contracts
    • MarketFuture: Delivery contracts
  4. Time in force (OptTimeInForce) options:

    • TimeInForceGTC: Good Till Cancel
    • TimeInForceIOC: Immediate or Cancel
    • TimeInForceFOK: Fill or Kill
    • TimeInForceGTX: Good Till Crossing
    • TimeInForceGTD: Good Till Date
    • TimeInForcePO: Post Only
  5. API cache and retry counts can be set individually for different interfaces

  6. Fees can be set with different rates for different market types

API List

// Load market information
LoadMarkets(reload bool, params map[string]interface{}) (MarketMap, *errs.Error)
GetCurMarkets() MarketMap
GetMarket(symbol string) (*Market, *errs.Error)
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
GetLeverage(symbol string, notional float64, account string) (float64, float64)
CheckSymbols(symbols ...string) ([]string, []string)
Info() *ExgInfo

// Fetch OHLCV, orderbook, funding rate etc
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)

// Authentication: fetch orders, balance, positions
FetchOrder(symbol, orderId string, params map[string]interface{}) (*Order, *errs.Error)
FetchOrders(symbol string, since int64, limit int, params map[string]interface{}) ([]*Order, *errs.Error)
FetchBalance(params map[string]interface{}) (*Balances, *errs.Error)
FetchAccountPositions(symbols []string, params map[string]interface{}) ([]*Position, *errs.Error)
FetchPositions(symbols []string, params map[string]interface{}) ([]*Position, *errs.Error)
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)

// Authentication: create, modify, cancel orders
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)

// Set/calculate fees; set leverage, calculate maintenance margin
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)

// WebSocket related: watch orderbook, klines, mark price, trades, balance, positions, account config
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)

// WebSocket data capture and replay (for backtesting)
SetDump(path string) *errs.Error
SetReplay(path string) *errs.Error
GetReplayTo() int64
ReplayOne() *errs.Error
ReplayAll() *errs.Error
SetOnWsChan(cb FuncOnWsChan)

// Precision handling
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)

// Others
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

Note

Use Options instead of direct fields assign to initialized a Exchange

When an exchange object is initialized, some fields of simple types like int will have default type values. When setting these in the Init method, it's impossible to distinguish whether the current value is one set by the user or the default value. Therefore, any configuration needed from outside should be passed in through Options, and then these Options should be read and set onto the corresponding fields in the Init method.

Market Type
Spot Margin Contract Linear Contract Inverse Option
Swap Linear future Linear swap Inverse future Inverse option linear option inverse
Desc spot margin USDⓈ-M Perpetual USDⓈ-M Futures COIN-M Perpetual COIN-M Futures USDⓈ-M Option COIN-M Option
Common parameter naming adjustments

ccxt.defaultType -> MarketType
The default market type of the current exchange. It can be set during initialization using OptMarketType or by modifying the MarketType property of the exchange at any time.
Valid Values: MarketSpot/MarketMargin/MarketLinear/MarketInverse/MarketOption
In ccxt, the naming of defaultType for Binance is inconsistent with other exchanges. In banexg, a unified naming convention has been applied.

ContractType
The contract type for the current exchange, with options of swap for perpetual contracts and future for contracts with an expiration date.
It can be set during initialization using OptContractType or by modifying the ContractType property of the exchange after initialization.

Contact Me

Email: anyongjin163@163.com
WeChat: jingyingsuixing

Documentation

Index

Constants

View Source
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" // 触发后全部平仓
	ParamCallbackRate       = "callbackRate"  // 跟踪止损回调百分比
	ParamRolling            = "rolling"
	ParamTest               = "test"
	ParamMarginMode         = "marginMode"
	ParamSymbol             = "symbol"
	ParamSymbols            = "symbols"
	ParamPositionSide       = "positionSide"
	ParamProxy              = "proxy"
	ParamName               = "name"
	ParamMethod             = "method"
	ParamInterval           = "interval"
	ParamAccount            = "account"
	ParamMarket             = "market"
	ParamContract           = "contract"
	ParamBrokerId           = "brokerId"
	ParamLimit              = "limit"
	ParamUntil              = "until"
)
View Source
const (
	HasFail = 1 << iota
	HasOk
	HasEmulated
)
View Source
const (
	BoolNull  = 0
	BoolFalse = -1
	BoolTrue  = 1
)
View Source
const (
	OptProxy           = "Proxy"
	OptApiKey          = "ApiKey"
	OptApiSecret       = "ApiSecret"
	OptAccCreds        = "Creds"
	OptAccName         = "AccName"
	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"
)
View Source
const (
	PrecModeDecimalPlace = utils.PrecModeDecimalPlace // 保留小数点后位数
	PrecModeSignifDigits = utils.PrecModeSignifDigits // 保留有效数字位数
	PrecModeTickSize     = utils.PrecModeTickSize     // 返回给定数字的整数倍
)
View Source
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
)
View Source
const (
	MarginCross    = "cross"
	MarginIsolated = "isolated"
)
View Source
const (
	OdStatusOpen       = "open"
	OdStatusPartFilled = "part_filled"
	OdStatusFilled     = "filled"
	OdStatusCanceled   = "canceled"
	OdStatusCanceling  = "canceling"
	OdStatusRejected   = "rejected"
	OdStatusExpired    = "expired"
)
View Source
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"
)

此处订单类型全部使用币安订单类型小写

View Source
const (
	OdSideBuy  = "buy"
	OdSideSell = "sell"
)
View Source
const (
	PosSideLong  = "long"
	PosSideShort = "short"
	PosSideBoth  = "both"
)
View Source
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
)
View Source
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"
)
View Source
const (
	DefTimeInForce = TimeInForceGTC
)
View Source
const (
	MidListenKey = "listenKey"
)

Variables

View Source
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请求最大并发数
)
View Source
var (
	AllMarketTypes = map[string]struct{}{
		MarketSpot:    {},
		MarketMargin:  {},
		MarketLinear:  {},
		MarketInverse: {},
		MarketOption:  {},
	}
	AllContractTypes = map[string]struct{}{
		MarketSwap:   {},
		MarketFuture: {},
	}
)
View Source
var (
	ParamHandshakeTimeout = "HandshakeTimeout"
	ParamChanCaps         = "ChanCaps"
	ParamChanCap          = "ChanCap"
)
View Source
var (
	DefChanCaps = map[string]int{
		"@depth": 1000,
	}
)
View Source
var (
	LocUTC, _ = time.LoadLocation("UTC")
)

Functions

func CheckWsError added in v0.1.2

func CheckWsError(msg map[string]string) *errs.Error

CheckWsError 从websocket返回的消息结果中,检查是否有错误信息

func EnsureArrStr added in v0.2.0

func EnsureArrStr(text string) string

func GetHostFlowChan added in v0.2.5

func GetHostFlowChan(host string) chan struct{}

func GetHostRetryWait added in v0.2.5

func GetHostRetryWait(host string, randAdd bool) int64

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 IsContract(marketType string) bool

func IsOrderDone added in v0.2.1

func IsOrderDone(status string) bool

func SetHostRetryWait added in v0.2.5

func SetHostRetryWait(host string, waitMS int64)

func WriteOutChan added in v0.1.2

func WriteOutChan[T any](e *Exchange, chanKey string, msg T, popIfNeed bool) bool

Types

type Account

type Account struct {
	Name         string
	Creds        *Credential
	MarPositions map[string][]*Position // marketType: Position List
	MarBalances  map[string]*Balances   // marketType: Balances
	Leverages    map[string]int         // 币种当前的杠杆倍数
	Data         map[string]interface{}
	LockPos      *sync.Mutex
	LockBalance  *sync.Mutex
	LockLeverage *sync.Mutex
	LockData     *sync.Mutex
}

type AccountConfig added in v0.2.0

type AccountConfig struct {
	Symbol   string
	Leverage int
}

type ApiRes added in v0.2.6

type ApiRes[T any] struct {
	*HttpRes
	Result T `json:"content"`
}

type Asset

type Asset struct {
	Code  string
	Free  float64
	Used  float64
	Total float64
	Debt  float64
	UPol  float64
}

func (*Asset) IsEmpty added in v0.1.2

func (a *Asset) IsEmpty() bool

type AsyncConn added in v0.2.4

type AsyncConn struct {
	WsConn
	Send chan []byte
	// contains filtered or unexported fields
}

type Balances

type Balances struct {
	TimeStamp      int64
	Free           map[string]float64
	Used           map[string]float64
	Total          map[string]float64
	Assets         map[string]*Asset
	IsolatedAssets map[string]map[string]*Asset // 逐仓账户资产,键是symbol
	Info           interface{}
}

func (*Balances) Init added in v0.1.2

func (b *Balances) Init() *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
	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)

	// FetchOrder query given order
	FetchOrder(symbol, orderId 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)
	// 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 Get all open orders on a symbol or all symbol.
	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)
	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)

	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)

	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
}

type ChainNetwork

type ChainNetwork struct {
	ID        string
	Network   string
	Name      string
	Active    bool
	Fee       float64
	Precision float64
	Deposit   bool
	Withdraw  bool
	Limits    *CodeLimits
	Info      interface{}
}

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

type Credential struct {
	ApiKey   string
	Secret   string
	UID      string
	Password string
}

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      interface{}
}

type CurrencyMap

type CurrencyMap = map[string]*Currency

************************** Currency **************************

type Entry

type Entry struct {
	Path      string
	Host      string
	RawHost   string
	Url       string
	Method    string
	Cost      float64
	More      map[string]interface{}
	CacheSecs int
}

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   *url.URL

	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

	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

	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表示无需重试

	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 (e *Exchange) AddWsChanRefs(chanKey string, keys ...string)

func (*Exchange) CalcMaintMargin added in v0.1.2

func (e *Exchange) CalcMaintMargin(symbol string, cost float64) (float64, *errs.Error)

func (*Exchange) CalculateFee added in v0.1.2

func (e *Exchange) CalculateFee(symbol, odType, side string, amount float64, price float64, isMaker bool,
	params map[string]interface{}) (*Fee, *errs.Error)

func (*Exchange) CancelOrder added in v0.1.2

func (e *Exchange) CancelOrder(id string, symbol string, params map[string]interface{}) (*Order, *errs.Error)

func (*Exchange) CheckSymbols added in v0.1.3

func (e *Exchange) CheckSymbols(symbols ...string) ([]string, []string)

CheckSymbols split valid and invalid symbols

func (*Exchange) Close added in v0.2.0

func (e *Exchange) Close() *errs.Error

func (*Exchange) CloseWsFile added in v0.2.3

func (e *Exchange) CloseWsFile()

func (*Exchange) CreateOrder added in v0.1.2

func (e *Exchange) CreateOrder(symbol, odType, side string, amount float64, price float64, params map[string]interface{}) (*Order, *errs.Error)

func (*Exchange) DelWsChanRefs added in v0.1.2

func (e *Exchange) DelWsChanRefs(chanKey string, keys ...string) int

func (*Exchange) DumpWS added in v0.2.3

func (e *Exchange) DumpWS(name string, data interface{})

func (*Exchange) EditOrder added in v0.2.6

func (e *Exchange) EditOrder(symbol, orderId, side string, amount, price float64, params map[string]interface{}) (*Order, *errs.Error)

func (*Exchange) FetchAccountPositions added in v0.2.6

func (e *Exchange) FetchAccountPositions(symbols []string, params map[string]interface{}) ([]*Position, *errs.Error)

func (*Exchange) FetchBalance added in v0.1.2

func (e *Exchange) FetchBalance(params map[string]interface{}) (*Balances, *errs.Error)

func (*Exchange) FetchFundingRate added in v0.2.7

func (e *Exchange) FetchFundingRate(symbol string, params map[string]interface{}) (*FundingRateCur, *errs.Error)

func (*Exchange) FetchFundingRateHistory added in v0.2.6

func (e *Exchange) FetchFundingRateHistory(symbol string, since int64, limit int, params map[string]interface{}) ([]*FundingRate, *errs.Error)

func (*Exchange) FetchFundingRates added in v0.2.7

func (e *Exchange) FetchFundingRates(symbols []string, params map[string]interface{}) ([]*FundingRateCur, *errs.Error)

func (*Exchange) FetchIncomeHistory added in v0.2.6

func (e *Exchange) FetchIncomeHistory(inType string, symbol string, since int64, limit int, params map[string]interface{}) ([]*Income, *errs.Error)

func (*Exchange) FetchLastPrices added in v0.2.7

func (e *Exchange) FetchLastPrices(symbols []string, params map[string]interface{}) ([]*LastPrice, *errs.Error)

func (*Exchange) FetchOHLCV added in v0.1.2

func (e *Exchange) FetchOHLCV(symbol, timeframe string, since int64, limit int, params map[string]interface{}) ([]*Kline, *errs.Error)

func (*Exchange) FetchOpenOrders added in v0.1.2

func (e *Exchange) FetchOpenOrders(symbol string, since int64, limit int, params map[string]interface{}) ([]*Order, *errs.Error)

func (*Exchange) FetchOrder added in v0.2.6

func (e *Exchange) FetchOrder(symbol, orderId string, params map[string]interface{}) (*Order, *errs.Error)

func (*Exchange) FetchOrderBook added in v0.1.2

func (e *Exchange) FetchOrderBook(symbol string, limit int, params map[string]interface{}) (*OrderBook, *errs.Error)

func (*Exchange) FetchOrders added in v0.1.2

func (e *Exchange) FetchOrders(symbol string, since int64, limit int, params map[string]interface{}) ([]*Order, *errs.Error)

func (*Exchange) FetchPositions added in v0.1.2

func (e *Exchange) FetchPositions(symbols []string, params map[string]interface{}) ([]*Position, *errs.Error)

func (*Exchange) FetchTicker added in v0.1.2

func (e *Exchange) FetchTicker(symbol string, params map[string]interface{}) (*Ticker, *errs.Error)

func (*Exchange) FetchTickerPrice added in v0.2.6

func (e *Exchange) FetchTickerPrice(symbol string, params map[string]interface{}) (map[string]float64, *errs.Error)

func (*Exchange) FetchTickers added in v0.1.2

func (e *Exchange) FetchTickers(symbols []string, params map[string]interface{}) ([]*Ticker, *errs.Error)

func (*Exchange) GetAccName added in v0.1.2

func (e *Exchange) GetAccName(params map[string]interface{}) string

func (*Exchange) GetAccount added in v0.1.2

func (e *Exchange) GetAccount(id string) (*Account, *errs.Error)

func (*Exchange) GetAccountCreds added in v0.1.2

func (e *Exchange) GetAccountCreds(id string) (string, *Credential, *errs.Error)

func (*Exchange) GetArgsMarket added in v0.1.2

func (e *Exchange) GetArgsMarket(symbol string, args map[string]interface{}) (*Market, *errs.Error)

GetArgsMarket 从symbol和args中的market+inverse得到对应的Market对象

func (*Exchange) GetArgsMarketType added in v0.1.2

func (e *Exchange) GetArgsMarketType(args map[string]interface{}, symbol string) (string, string)

func (*Exchange) GetClient added in v0.1.2

func (e *Exchange) GetClient(wsUrl string, marketType, accName string) (*WsClient, *errs.Error)

func (*Exchange) GetCurMarkets added in v0.1.2

func (e *Exchange) GetCurMarkets() MarketMap

func (*Exchange) GetExg added in v0.2.6

func (e *Exchange) GetExg() *Exchange

func (*Exchange) GetHost added in v0.2.5

func (e *Exchange) GetHost(name string) string

func (*Exchange) GetID added in v0.1.2

func (e *Exchange) GetID() string

func (*Exchange) GetLeverage added in v0.2.0

func (e *Exchange) GetLeverage(symbol string, notional float64, account string) (float64, float64)

func (*Exchange) GetMarket added in v0.1.2

func (e *Exchange) GetMarket(symbol string) (*Market, *errs.Error)

GetMarket 获取市场信息

symbol ccxt的symbol、交易所的ID,必须严格正确,如果可能错误,
根据当前的MarketType和MarketInverse过滤匹配

func (*Exchange) GetMarketById added in v0.1.2

func (e *Exchange) GetMarketById(marketId, marketType string) *Market

GetMarketById get market by exchange id (Upper Required!)

func (*Exchange) GetMarketID added in v0.1.2

func (e *Exchange) GetMarketID(symbol string) (string, *errs.Error)

GetMarketID

从CCXT的symbol得到交易所ID

func (*Exchange) GetMarketIDByArgs added in v0.1.2

func (e *Exchange) GetMarketIDByArgs(args map[string]interface{}, required bool) (string, *errs.Error)

func (*Exchange) GetPriceOnePip added in v0.1.2

func (e *Exchange) GetPriceOnePip(pair string) (float64, *errs.Error)

func (*Exchange) GetReplayTo added in v0.2.3

func (e *Exchange) GetReplayTo() int64

func (*Exchange) GetRetryNum added in v0.1.2

func (e *Exchange) GetRetryNum(key string, defVal int) int

GetRetryNum 返回失败时重试次数,未设置时默认0

func (*Exchange) GetTimeFrame added in v0.1.2

func (e *Exchange) GetTimeFrame(timeframe string) string

func (*Exchange) HasApi added in v0.1.2

func (e *Exchange) HasApi(key, market string) bool

func (*Exchange) Info added in v0.2.1

func (e *Exchange) Info() *ExgInfo

func (*Exchange) Init added in v0.1.2

func (e *Exchange) Init() *errs.Error

func (*Exchange) IsContract added in v0.1.2

func (e *Exchange) IsContract(marketType string) bool

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 (e *Exchange) LoadArgsMarketType(args map[string]interface{}, symbols ...string) (string, string, *errs.Error)

func (*Exchange) LoadLeverageBrackets added in v0.1.2

func (e *Exchange) LoadLeverageBrackets(reload bool, params map[string]interface{}) *errs.Error

func (*Exchange) LoadMarkets added in v0.1.2

func (e *Exchange) LoadMarkets(reload bool, params map[string]interface{}) (MarketMap, *errs.Error)

func (*Exchange) MapMarket added in v0.2.1

func (e *Exchange) MapMarket(exgSID string, year int) (*Market, *errs.Error)

func (*Exchange) MilliSeconds added in v0.1.2

func (e *Exchange) MilliSeconds() int64

func (*Exchange) Nonce added in v0.1.2

func (e *Exchange) Nonce() int64

func (*Exchange) PopAccName added in v0.2.1

func (e *Exchange) PopAccName(params map[string]interface{}) string

func (*Exchange) PrecAmount added in v0.1.2

func (e *Exchange) PrecAmount(m *Market, amount float64) (float64, *errs.Error)

func (*Exchange) PrecCost added in v0.1.2

func (e *Exchange) PrecCost(m *Market, cost float64) (float64, *errs.Error)

func (*Exchange) PrecFee added in v0.1.2

func (e *Exchange) PrecFee(m *Market, fee float64) (float64, *errs.Error)

func (*Exchange) PrecPrice added in v0.1.2

func (e *Exchange) PrecPrice(m *Market, price float64) (float64, *errs.Error)

func (*Exchange) PriceOnePip added in v0.1.2

func (e *Exchange) PriceOnePip(symbol string) (float64, *errs.Error)

PriceOnePip Get's the "1 pip" value for this pair.

Used in PriceFilter to calculate the 1pip movements.

func (*Exchange) ReplayAll added in v0.2.3

func (e *Exchange) ReplayAll() *errs.Error

func (*Exchange) ReplayOne added in v0.2.3

func (e *Exchange) ReplayOne() *errs.Error

func (*Exchange) RequestApi added in v0.1.2

func (e *Exchange) RequestApi(ctx context.Context, endpoint, cacheKey string, api *Entry, params map[string]interface{}) *HttpRes

RequestApi Request exchange API without checking cache Concurrent control: Same host, default concurrent 3 times at the same time

请求交易所API,不检查缓存 并发控制:同一个host,默认同时并发3

func (*Exchange) RequestApiRetry added in v0.1.2

func (e *Exchange) RequestApiRetry(ctx context.Context, endpoint string, params map[string]interface{}, retryNum int) *HttpRes

func (*Exchange) SafeCurrency added in v0.1.2

func (e *Exchange) SafeCurrency(currId string) *Currency

func (*Exchange) SafeCurrencyCode added in v0.1.2

func (e *Exchange) SafeCurrencyCode(currId string) string

func (*Exchange) SafeMarket added in v0.1.2

func (e *Exchange) SafeMarket(marketId, delimiter, marketType string) *Market

SafeMarket

从交易所品种ID转为规范化市场信息

func (*Exchange) SafeSymbol added in v0.1.2

func (e *Exchange) SafeSymbol(marketId, delimiter, marketType string) string

SafeSymbol 将交易所品种ID转为规范化品种ID

marketType TradeSpot/TradeMargin/TradeSwap/TradeFuture/TradeOption

linear/inverse

func (*Exchange) SetDump added in v0.2.3

func (e *Exchange) SetDump(path string) *errs.Error

func (*Exchange) SetFees added in v0.2.1

func (e *Exchange) SetFees(fees map[string]map[string]float64)

func (*Exchange) SetLeverage added in v0.1.2

func (e *Exchange) SetLeverage(leverage float64, symbol string, params map[string]interface{}) (map[string]interface{}, *errs.Error)

func (*Exchange) SetMarketType added in v0.1.2

func (e *Exchange) SetMarketType(marketType, contractType string) *errs.Error

func (*Exchange) SetOnHost added in v0.2.5

func (e *Exchange) SetOnHost(cb func(n string) string)

func (*Exchange) SetOnWsChan added in v0.2.3

func (e *Exchange) SetOnWsChan(cb FuncOnWsChan)

func (*Exchange) SetReplay added in v0.2.3

func (e *Exchange) SetReplay(path string) *errs.Error

func (*Exchange) UnWatchMarkPrices added in v0.2.1

func (e *Exchange) UnWatchMarkPrices(symbols []string, params map[string]interface{}) *errs.Error

func (*Exchange) UnWatchOHLCVs added in v0.2.1

func (e *Exchange) UnWatchOHLCVs(jobs [][2]string, params map[string]interface{}) *errs.Error

func (*Exchange) UnWatchOrderBooks added in v0.2.1

func (e *Exchange) UnWatchOrderBooks(symbols []string, params map[string]interface{}) *errs.Error

func (*Exchange) UnWatchTrades added in v0.2.1

func (e *Exchange) UnWatchTrades(symbols []string, params map[string]interface{}) *errs.Error

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 (e *Exchange) WatchBalance(params map[string]interface{}) (chan *Balances, *errs.Error)

func (*Exchange) WatchMarkPrices added in v0.2.1

func (e *Exchange) WatchMarkPrices(symbols []string, params map[string]interface{}) (chan map[string]float64, *errs.Error)

func (*Exchange) WatchMyTrades added in v0.2.1

func (e *Exchange) WatchMyTrades(params map[string]interface{}) (chan *MyTrade, *errs.Error)

func (*Exchange) WatchOHLCVs added in v0.2.1

func (e *Exchange) WatchOHLCVs(jobs [][2]string, params map[string]interface{}) (chan *PairTFKline, *errs.Error)

func (*Exchange) WatchOrderBooks added in v0.2.1

func (e *Exchange) WatchOrderBooks(symbols []string, limit int, params map[string]interface{}) (chan *OrderBook, *errs.Error)

func (*Exchange) WatchPositions added in v0.2.1

func (e *Exchange) WatchPositions(params map[string]interface{}) (chan []*Position, *errs.Error)

func (*Exchange) WatchTrades added in v0.2.1

func (e *Exchange) WatchTrades(symbols []string, params map[string]interface{}) (chan *Trade, *errs.Error)

type ExgFee

type ExgFee struct {
	Main    *TradeFee //默认
	Linear  *TradeFee //U本位合约
	Inverse *TradeFee // 币本位合约
	Option  *TradeFee
}

type ExgHosts

type ExgHosts struct {
	TestNet bool
	Test    map[string]string
	Prod    map[string]string
	Www     string
	Doc     []string
	Fees    string
}

func (*ExgHosts) GetHost added in v0.1.2

func (h *ExgHosts) GetHost(key string) string

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       sync.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 Fee

type Fee struct {
	IsMaker  bool    `json:"isMaker"` // for calculate fee
	Currency string  `json:"currency"`
	Cost     float64 `json:"cost"`
	Rate     float64 `json:"rate,omitempty"`
}

type FeeTierItem

type FeeTierItem struct {
	Amount float64
	Rate   float64
}

type FeeTiers

type FeeTiers struct {
	Taker []*FeeTierItem
	Maker []*FeeTierItem
}

type FuncAuthWS added in v0.2.1

type FuncAuthWS = func(acc *Account, params map[string]interface{}) *errs.Error

type FuncCalcFee added in v0.2.1

type FuncCalcFee = func(market *Market, curr string, maker bool, amount, price decimal.Decimal, params map[string]interface{}) (*Fee, *errs.Error)

type FuncCalcRateLimiterCost added in v0.2.5

type FuncCalcRateLimiterCost = func(api *Entry, params map[string]interface{}) float64

type FuncFetchCurr

type FuncFetchCurr = func(params map[string]interface{}) (CurrencyMap, *errs.Error)

type FuncFetchMarkets

type FuncFetchMarkets = func(marketTypes []string, params map[string]interface{}) (MarketMap, *errs.Error)

type FuncGetWsJob

type FuncGetWsJob = func(client *WsClient) (*WsJobInfo, *errs.Error)

type FuncOnWsChan added in v0.2.3

type FuncOnWsChan = func(key string, out interface{})

key: acc@url#marketType@method

type FuncOnWsClose

type FuncOnWsClose = func(client *WsClient, err *errs.Error)

type FuncOnWsErr

type FuncOnWsErr = func(client *WsClient, err *errs.Error)

type FuncOnWsMethod

type FuncOnWsMethod = func(client *WsClient, msg map[string]string, info *WsJobInfo)

type FuncOnWsMsg

type FuncOnWsMsg = func(client *WsClient, msg *WsMsg)

type FuncOnWsReCon added in v0.2.1

type FuncOnWsReCon = func(client *WsClient, connID int) *errs.Error

type FuncSign

type FuncSign = func(api *Entry, params map[string]interface{}) *HttpReq

type FundingRate added in v0.2.6

type FundingRate struct {
	Symbol      string      `json:"symbol"`
	FundingRate float64     `json:"fundingRate"`
	Timestamp   int64       `json:"timestamp"`
	Info        interface{} `json:"info"`
}

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                 interface{} `json:"info"`
}

type HttpHeader added in v0.1.2

type HttpHeader http.Header

func (HttpHeader) MarshalLogObject added in v0.1.2

func (h HttpHeader) MarshalLogObject(enc zapcore.ObjectEncoder) error

type HttpReq

type HttpReq struct {
	AccName string
	Url     string
	Method  string
	Headers http.Header
	Body    string
	Private bool // 此请求需要认证信息
	Error   *errs.Error
}

type HttpRes

type HttpRes struct {
	AccName string      `json:"acc_name"`
	Url     string      `json:"url"`
	Status  int         `json:"status"`
	Headers http.Header `json:"headers"`
	Content string      `json:"content"`
	Error   *errs.Error
}

type Income added in v0.2.1

type Income struct {
	Symbol     string  `json:"symbol"`
	IncomeType string  `json:"incomeType"`
	Income     float64 `json:"income"`
	Asset      string  `json:"asset"`
	Info       string  `json:"info"`
	Time       int64   `json:"time"`
	TranID     string  `json:"tranId"`
	TradeID    string  `json:"tradeId"`
}

type Kline

type Kline struct {
	Time   int64
	Open   float64
	High   float64
	Low    float64
	Close  float64
	Volume float64
	Info   float64
}

func (*Kline) Clone added in v0.2.0

func (k *Kline) Clone() *Kline

type LastPrice added in v0.2.7

type LastPrice struct {
	Symbol    string      `json:"symbol"`
	Timestamp int64       `json:"timestamp"`
	Price     float64     `json:"price"`
	Info      interface{} `json:"info"`
}

type LimitRange

type LimitRange struct {
	Min float64
	Max float64
}

func (*LimitRange) ToString added in v0.1.2

func (r *LimitRange) ToString() string

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           interface{}   `json:"info"`
}

func (*Market) GetTradeTimes added in v0.2.1

func (m *Market) GetTradeTimes() [][2]int64

type MarketArrMap

type MarketArrMap = map[string][]*Market

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 MarketMap

type MarketMap = map[string]*Market

type MyTrade

type MyTrade struct {
	Trade
	Filled     float64     `json:"filled"`     // 订单累计成交量(不止当前交易)
	ClientID   string      `json:"clientID"`   // 客户端订单ID
	Average    float64     `json:"average"`    // 平均成交价格
	State      string      `json:"state"`      // 状态
	PosSide    string      `json:"posSide"`    // 持仓方向 long/short
	ReduceOnly bool        `json:"reduceOnly"` // 是否是只减仓单
	Info       interface{} `json:"info"`
}

type OHLCVArr added in v0.1.2

type OHLCVArr = [6]float64

type OdBookShotLog added in v0.2.3

type OdBookShotLog struct {
	MarketType string     `json:"marketType,omitempty"`
	Symbol     string     `json:"symbol,omitempty"`
	ChanKey    string     `json:"chanKey,omitempty"`
	Book       *OrderBook `json:"book,omitempty"`
}

type OdBookSide added in v0.2.3

type OdBookSide struct {
	IsBuy bool
	Price []float64 // bid: desc   ask: asc
	Size  []float64
	Depth int
	Lock  sync.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                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"`
}

func MergeMyTrades added in v0.2.1

func MergeMyTrades(trades []*MyTrade) (*Order, *errs.Error)

MergeMyTrades 将WatchMyTrades收到的同Symbol+Order的交易,合并为Order

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
}

func (*OrderBook) AvgPrice added in v0.2.3

func (b *OrderBook) AvgPrice(side string, depth float64) (float64, float64, float64)

func (*OrderBook) Reset added in v0.2.4

func (b *OrderBook) Reset()

func (*OrderBook) SetSide added in v0.1.2

func (b *OrderBook) SetSide(text string, isBuy, replace bool)

func (*OrderBook) SumVolTo added in v0.2.0

func (b *OrderBook) SumVolTo(side string, price float64) (float64, float64)

SumVolTo get sum volume between current price and target price second return val is rate filled

func (*OrderBook) Update added in v0.2.4

func (b *OrderBook) Update(book *OrderBook)

type PairTFKline added in v0.1.3

type PairTFKline struct {
	Kline
	Symbol    string
	TimeFrame string
}

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             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"`
}

func (*Precision) ToString added in v0.1.2

func (p *Precision) ToString() string

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          interface{} `json:"info"`
}

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      interface{} `json:"info"`
}

type TradeFee

type TradeFee struct {
	FeeSide    string
	TierBased  bool
	Percentage bool
	Taker      float64
	Maker      float64
	Tiers      *FeeTiers
}

type WebSocket

type WebSocket struct {
	Conn *websocket.Conn
	// contains filtered or unexported fields
}

func (*WebSocket) Close added in v0.1.2

func (ws *WebSocket) Close() error

func (*WebSocket) GetID added in v0.2.4

func (ws *WebSocket) GetID() int

func (*WebSocket) IsOK added in v0.2.1

func (ws *WebSocket) IsOK() bool

func (*WebSocket) NextWriter added in v0.1.2

func (ws *WebSocket) NextWriter() (io.WriteCloser, error)

func (*WebSocket) ReadMsg added in v0.1.2

func (ws *WebSocket) ReadMsg() ([]byte, error)

func (*WebSocket) SetID added in v0.2.4

func (ws *WebSocket) SetID(v int)

func (*WebSocket) WriteClose added in v0.1.2

func (ws *WebSocket) WriteClose() error

type WsClient

type WsClient struct {
	Exg           *Exchange
	Conns         map[int]*AsyncConn
	URL           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,用于重连后恢复订阅
	OdBookLimits  map[string]int        // Record the depth of each target subscription order book for easy cancellation 记录每个标的订阅订单簿的深度,方便取消
	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

	LimitsLock sync.Mutex // for OdBookLimits
	// contains filtered or unexported fields
}

func (*WsClient) Close added in v0.1.2

func (c *WsClient) Close()

func (*WsClient) GetSubKeys added in v0.2.4

func (c *WsClient) GetSubKeys(connID int) []string

func (*WsClient) HandleRawMsg added in v0.2.3

func (c *WsClient) HandleRawMsg(msgRaw []byte)

func (*WsClient) Prefix added in v0.1.2

func (c *WsClient) Prefix(key string) string

func (*WsClient) UpdateSubs added in v0.2.1

func (c *WsClient) UpdateSubs(connID int, isSub bool, keys []string) (string, *AsyncConn)

func (*WsClient) Write added in v0.1.2

func (c *WsClient) Write(conn *AsyncConn, msg interface{}, info *WsJobInfo) *errs.Error

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 此次任务的主要信息,在收到任务结果时使用

type WsConn added in v0.1.2

type WsConn interface {
	Close() error
	WriteClose() error
	NextWriter() (io.WriteCloser, error)
	ReadMsg() ([]byte, error)
	IsOK() bool
	GetID() int
	SetID(id int)
}

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时暂存的任务信息。用于返回结果时处理。

type WsLog added in v0.2.3

type WsLog struct {
	Name    string `json:"name,omitempty"`
	TimeMS  int64  `json:"timeMS,omitempty"`
	Content string `json:"content,omitempty"`
}

type WsMsg

type WsMsg struct {
	Event   string
	ID      string
	IsArray bool
	Text    string
	Object  map[string]string
	List    []map[string]string
}

WsMsg 表示websocket收到的消息

func NewWsMsg added in v0.1.2

func NewWsMsg(msgText string) (*WsMsg, *errs.Error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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