banexg

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 5, 2024 License: MIT Imports: 23 Imported by: 0

README

BanExg - CryptoCurrency Exchange Trading Library

A Go library for cryptocurrency trading, whose most interfaces are consistent with CCXT.
Please note that this library is under development and is not ready for production!

Notes

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"
	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"
	OptPrecisionMode   = "PrecisionMode"
	OptMarketType      = "MarketType"
	OptContractType    = "ContractType"
	OptTimeInForce     = "TimeInForce"
	OptWsIntvs         = "WsIntvs" // ws 订阅间隔
	OptRetries         = "Retries"
	OptWsConn          = "WsConn"
	OptAuthRefreshSecs = "AuthRefreshSecs"
	OptPositionMethod  = "PositionMethod"
	OptDebugWS         = "DebugWS"
)
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"
	OdStatusClosed    = "closed"
	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 (
	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,
	}
)

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

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)
	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) (int, int)
	CheckSymbols(symbols ...string) ([]string, []string)

	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)

	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)

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

	CalculateFee(symbol, odType, side string, amount float64, price float64, isMaker bool, params map[string]interface{}) (*Fee, *errs.Error)
	SetLeverage(leverage int, 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)

	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)
	PrecMode() int

	HasApi(key 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
	GetID() string
	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
	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{}
}

type Exchange

type Exchange struct {
	ID        string   // 交易所ID
	Name      string   // 显示名称
	Countries []string // 可用国家
	Hosts     *ExgHosts
	Fees      *ExgFee
	Apis      map[string]Entry       // 所有API的路径
	Has       map[string]int         // 是否定义了某个API
	Options   map[string]interface{} // 用户传入的配置
	Proxy     *url.URL
	DebugWS   bool // 是否输出WS调试信息

	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 // 请求速率控制毫秒数,最小间隔单位

	UserAgent  string            // UserAgent of http request
	ReqHeaders map[string]string // http headers for request exchange

	MarketsWait chan interface{} // whether is loading markets
	Markets     MarketMap        //cache for all markets
	MarketsById MarketArrMap     // markets index by id
	CareMarkets []string         // markets to be fetch: spot/linear/inverse/option

	Symbols    []string
	IDs        []string
	TimeFrames map[string]string // map timeframe from common to specific

	Retries map[string]int // retry nums for methods

	CurrenciesById   CurrencyMap       // CurrencyMap index by id
	CurrenciesByCode CurrencyMap       // CurrencyMap index by code
	CurrCodeMap      map[string]string // common code maps

	TimeDelay  int64 // 系统时钟延迟的毫秒数
	HttpClient *http.Client

	PrecisionMode int    // 2:PrecModeDecimalPlace  3:PrecModeSignifDigits  4:PrecModeTickSize
	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

	OrderBooks map[string]*OrderBook         // symbol: OrderBook update by wss
	MarkPrices map[string]map[string]float64 // marketType: symbol: mark price

	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

	KeyTimeStamps map[string]int64 // key: int64 更新的时间戳

	// for calling sub struct func in parent struct
	Sign            FuncSign
	FetchCurrencies FuncFetchCurr
	FetchMarkets    FuncFetchMarkets
	Authenticate    FuncAuth
	GetRetryWait    func(e *errs.Error) int // 根据错误信息计算重试间隔秒数,<0表示无需重试

	OnWsMsg   FuncOnWsMsg
	OnWsErr   FuncOnWsErr
	OnWsClose FuncOnWsClose

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

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) 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) 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) PrecMode added in v0.1.2

func (e *Exchange) PrecMode() int

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

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 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 FuncAuth

type FuncAuth = func(params map[string]interface{}) (*Account, *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 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 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
	Error   *errs.Error
}

type HttpRes

type HttpRes struct {
	AccName string
	Status  int
	Headers http.Header
	Content string
	Error   *errs.Error
}

type Kline

type Kline struct {
	Time   int64
	Open   float64
	High   float64
	Low    float64
	Close  float64
	Volume 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"`
	Type           string        `json:"type"` // spot/linear/inverse/option 无法区分margin 和ccxt的值不同
	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"`
	ExpiryDatetime string        `json:"expiryDatetime"`
	Strike         float64       `json:"strike"`
	OptionType     string        `json:"optionType"`
	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"`
}

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

type OrderBook

type OrderBook struct {
	Symbol    string         `json:"symbol"`
	TimeStamp int64          `json:"timestamp"`
	Asks      *OrderBookSide `json:"asks"`
	Bids      *OrderBookSide `json:"bids"`
	Nonce     int64          // latest update id
	Cache     []map[string]string
}

func (*OrderBook) LimitPrice added in v0.2.0

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

func (*OrderBook) SetSide added in v0.1.2

func (ob *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 OrderBookSide

type OrderBookSide struct {
	IsBuy bool
	Rows  [][2]float64 // [][price, size]
	Index []float64
	Depth int
}

OrderBookSide 订单簿一侧。不需要加锁,因为只有一个goroutine可以修改

func NewOrderBookSide added in v0.1.2

func NewOrderBookSide(isBuy bool, depth int, deltas [][2]float64) *OrderBookSide

func (*OrderBookSide) Limit added in v0.1.2

func (obs *OrderBookSide) Limit()

func (*OrderBookSide) Store added in v0.1.2

func (obs *OrderBookSide) Store(price, size float64)

func (*OrderBookSide) StoreArray added in v0.1.2

func (obs *OrderBookSide) StoreArray(delta [2]float64)

func (*OrderBookSide) Update added in v0.1.2

func (obs *OrderBookSide) Update(deltas [][2]float64)

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

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
}

func (*WebSocket) Close added in v0.1.2

func (ws *WebSocket) Close() error

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 {
	Conn       WsConn
	URL        string
	AccName    string
	MarketType string
	Debug      bool
	Send       chan []byte

	JobInfos  map[string]*WsJobInfo // request id: Sub Data
	ChanCaps  map[string]int        // msgHash: cap size of cache msg
	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) Prefix added in v0.1.2

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

func (*WsClient) Write added in v0.1.2

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

Write 发送消息到ws服务器,可设置处理任务结果需要的信息 jobID: 此次消息的任务ID,唯一标识此次请求 jobInfo: 此次任务的主要信息,在收到任务结果时使用

type WsConn added in v0.1.2

type WsConn interface {
	Close() error
	WriteClose() error
	NextWriter() (io.WriteCloser, error)
	ReadMsg() ([]byte, error)
}

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