banexg

package module
v0.2.3 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2024 License: MIT Imports: 27 Imported by: 19

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
Since I don't have the energy to update the document at present, I suggest that you check the inf.go interface for specific use, as well as the specific exchange method; welcome to help improve the document and code.

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))
}

Note

sonic's large integer deserialization problem

This project uses sonic as the json serialization library. It is known that float64 will be used when deserializing int64 long integers, resulting in precision loss. Currently, UseInt64 is used to force the use of int64 to parse long integers, but this item is only effective under the amd64 chip. Others such as arm64 or mac m1 will still use sonic's default behavior.

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.

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"
)
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,
	}
)
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 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 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 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 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)

	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
	PriceOnePip(symbol string) (float64, *errs.Error)
	IsContract(marketType string) bool
	MilliSeconds() int64

	GetAccount(id string) (*Account, *errs.Error)
	SetMarketType(marketType, contractType string) *errs.Error
	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
	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 // 请求速率控制毫秒数,最小间隔单位

	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
	WsReplayMS  int64
	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) FetchBalance added in v0.1.2

func (e *Exchange) FetchBalance(params map[string]interface{}) (*Balances, *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) 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) 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) 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) (int, int)

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

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 string, params map[string]interface{}) *HttpRes

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 int, 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) 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 // 币本位合约
}

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

	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 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) *errs.Error

type FuncSign

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

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

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(depth float64) (float64, float64)

AvgPrice get (average price, last price)

func (*OdBookSide) Limit added in v0.2.3

func (obs *OdBookSide) Limit()

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
	Cache     []map[string]string
}

func (*OrderBook) AvgPrice added in v0.2.3

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

func (*OrderBook) SetSide added in v0.1.2

func (b *OrderBook) SetSide(text string, isBuy 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

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"`
	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) 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) WriteClose added in v0.1.2

func (ws *WebSocket) WriteClose() error

type WsClient

type WsClient struct {
	Exg        *Exchange
	Conn       WsConn
	URL        string
	AccName    string
	MarketType string
	Key        string
	Debug      bool
	Send       chan []byte

	JobInfos      map[string]*WsJobInfo // request id: Sub Data
	ChanCaps      map[string]int        // msgHash: cap size of cache msg
	SubscribeKeys map[string]bool       // 订阅的key,用于重连后恢复订阅
	OnMessage     func(client *WsClient, msg *WsMsg)
	OnError       func(client *WsClient, err *errs.Error)
	OnClose       func(client *WsClient, err *errs.Error)
	// contains filtered or unexported fields
}

func (*WsClient) Close added in v0.1.2

func (c *WsClient) Close()

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(isSub bool, keys []string) string

func (*WsClient) Write added in v0.1.2

func (c *WsClient) Write(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
}

type WsJobInfo

type WsJobInfo struct {
	ID      string
	MsgHash string
	Name    string
	Symbols []string
	Method  func(client *WsClient, msg map[string]string, info *WsJobInfo)
	Limit   int
	Params  map[string]interface{}
}

WsJobInfo 调用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