goghostex

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Jun 16, 2023 License: BSD-3-Clause Imports: 24 Imported by: 0

README

goghostex

Workflow License

README: English | 中文

Goghostex is a open source API of TOP crypto currency exchanges. You can use it directly for your data collector or trading program.

Feature

The list of goghost supported API.As below:

SPOT MARGIN FUTURE SWAP
OKEX YES YES YES NO
BINANCE YES NO NO NO

Clone

git clone https://github.com/deforceHK/goghostex.git

Install

go install

Test

go test -v ./{package name}/... -count=1 -test.run {func name}

Todos

  • Add cli features.
  • Support bitmex exchange.
  • Support bitstamp exchange.

LICENSE

The project use the New BSD License

Credits

Documentation

Index

Constants

View Source
const (
	KLINE_PERIOD_1MIN = 1 + iota
	KLINE_PERIOD_3MIN
	KLINE_PERIOD_5MIN
	KLINE_PERIOD_15MIN
	KLINE_PERIOD_30MIN
	KLINE_PERIOD_60MIN
	KLINE_PERIOD_1H
	KLINE_PERIOD_2H
	KLINE_PERIOD_4H
	KLINE_PERIOD_6H
	KLINE_PERIOD_8H
	KLINE_PERIOD_12H
	KLINE_PERIOD_1DAY
	KLINE_PERIOD_3DAY
	KLINE_PERIOD_1WEEK
	KLINE_PERIOD_1MONTH
	KLINE_PERIOD_1YEAR
)

k线周期

View Source
const (
	THIS_WEEK_CONTRACT    = "this_week"    //周合约
	NEXT_WEEK_CONTRACT    = "next_week"    //次周合约
	QUARTER_CONTRACT      = "quarter"      //季度合约
	NEXT_QUARTER_CONTRACT = "next_quarter" //次季合约
	SWAP_CONTRACT         = "swap"         //永续合约
)
View Source
const (
	SUBJECT_SETTLE                  = "settle"
	SUBJECT_COMMISSION              = "commission"
	SUBJECT_FUNDING_FEE             = "funding_fee"
	SUBJECT_FREEZE                  = "freeze"
	SUBJECT_UNFREEZE                = "unfreeze"
	SUBJECT_COLLATERAL_TRANSFER_IN  = "transfer_collateral_in"
	SUBJECT_COLLATERAL_TRANSFER_OUT = "transfer_collateral_out"
	SUBJECT_TRANSFER_IN             = "transfer_in"
	SUBJECT_TRANSFER_OUT            = "transfer_out"
)

account flow subject

View Source
const (
	OKEX     = "okex"
	BINANCE  = "binance"
	COINBASE = "coinbase"
	BITSTAMP = "bitstamp"
	GATE     = "gate"
	KRAKEN   = "kraken"
)

exchanges const

View Source
const (
	CROSS    = "cross"
	ISOLATED = "isolated"
)
View Source
const (
	TRADE_TYPE_FUTURE = "future"
	TRADE_TYPE_SPOT   = "spot"
	TRADE_TYPE_SWAP   = "swap"
	TRADE_TYPE_MARGIN = "margin"
)
View Source
const (
	SETTLE_MODE_BASIS   int64 = 1
	SETTLE_MODE_COUNTER int64 = 2
)
View Source
const (
	GO_BIRTHDAY = "2006-01-02 15:04:05"
)

Variables

View Source
var (
	UNKNOWN = Currency{"UNKNOWN", ""}

	USD = Currency{"USD", ""}
	EUR = Currency{"EUR", ""}
	CNY = Currency{"CNY", ""}
	KRW = Currency{"KRW", ""}
	JPY = Currency{"JPY", ""}
	SGD = Currency{"SGD", ""}
	HKD = Currency{"HKD", ""}

	USDT = Currency{"USDT", ""}
	USDC = Currency{"USDC", "https://www.centre.io/"}
	PAX  = Currency{"PAX", "https://www.paxos.com/"}
	DAI  = Currency{"DAI", ""}
	BUSD = Currency{"BUSD", ""}

	BTC   = Currency{"BTC", "https://bitcoin.org/"}
	XBT   = Currency{"XBT", ""}
	BCH   = Currency{"BCH", ""}
	LTC   = Currency{"LTC", ""}
	ETH   = Currency{"ETH", ""}
	ETC   = Currency{"ETC", ""}
	EOS   = Currency{"EOS", ""}
	BTS   = Currency{"BTS", ""}
	QTUM  = Currency{"QTUM", ""}
	SC    = Currency{"SC", ""}
	ANS   = Currency{"ANS", ""}
	ZEC   = Currency{"ZEC", ""}
	DCR   = Currency{"DCR", ""}
	XRP   = Currency{"XRP", ""}
	NEO   = Currency{"NEO", ""}
	BSV   = Currency{"BSV", ""}
	LINK  = Currency{"LINK", ""}
	XTZ   = Currency{"XTZ", ""}
	DASH  = Currency{"DASH", ""}
	ADA   = Currency{"ADA", ""}
	DOT   = Currency{"DOT", ""}
	FIL   = Currency{"FIL", ""}
	SOL   = Currency{"SOL", ""}
	ATOM  = Currency{"ATOM", ""}
	MATIC = Currency{"MATIC", ""}
	AVAX  = Currency{"AVAX", ""}
	ALGO  = Currency{"ALGO", ""}
	AR    = Currency{"AR", ""}

	UNI   = Currency{"UNI", ""}
	SUSHI = Currency{"SUSHI", ""}
	AAVE  = Currency{"AAVE", ""}
	COMP  = Currency{"COMP", ""}
	YFI   = Currency{"YFI", ""}
	YFII  = Currency{"YFII", ""}

	OKB = Currency{"OKB", "OKB is a global utility token issued by OK Blockchain Foundation. "}
	HT  = Currency{"HT", "HuoBi Token. "}
	BNB = Currency{"BNB", "BNB, or Binance Coin, is a cryptocurrency created by Binance. "}

	SHIT = Currency{"SHIT", "SHIT, There are some many shit coin in the market, we make the currency for dev."}
)
View Source
var (
	BTC_USD = Pair{Basis: BTC, Counter: USD}
	LTC_USD = Pair{Basis: LTC, Counter: USD}
	ETH_USD = Pair{Basis: ETH, Counter: USD}
	EOS_USD = Pair{Basis: EOS, Counter: USD}

	BTC_USDT = Pair{Basis: BTC, Counter: USDT}
	ETH_USDT = Pair{Basis: ETH, Counter: USDT}
)
View Source
var PeriodMillisecond = map[int]int64{
	KLINE_PERIOD_1MIN:  60 * 1000,
	KLINE_PERIOD_3MIN:  3 * 60 * 1000,
	KLINE_PERIOD_5MIN:  5 * 60 * 1000,
	KLINE_PERIOD_15MIN: 15 * 60 * 1000,
	KLINE_PERIOD_30MIN: 30 * 60 * 1000,
	KLINE_PERIOD_60MIN: 60 * 60 * 1000,
	KLINE_PERIOD_1H:    60 * 60 * 1000,
	KLINE_PERIOD_2H:    2 * 60 * 60 * 1000,
	KLINE_PERIOD_4H:    4 * 60 * 60 * 1000,
	KLINE_PERIOD_6H:    6 * 60 * 60 * 1000,
	KLINE_PERIOD_8H:    8 * 60 * 60 * 1000,
	KLINE_PERIOD_12H:   12 * 60 * 60 * 1000,
	KLINE_PERIOD_1DAY:  24 * 60 * 60 * 1000,
	KLINE_PERIOD_3DAY:  3 * 24 * 60 * 60 * 1000,
	KLINE_PERIOD_1WEEK: 7 * 24 * 60 * 60 * 1000,
}

Functions

func FlateUnCompress

func FlateUnCompress(data []byte) ([]byte, error)

func FloatToPrice

func FloatToPrice(v float64, n int64, tickSize float64) string

FloatToPrice n :保留的小数点位数,去除末尾多余的0(StripTrailingZeros),并加入ticksize

func FloatToString

func FloatToString(v float64, n int64) string

FloatToString n :保留的小数点位数,去除末尾多余的0(StripTrailingZeros)

func GetParamHmacMD5Sign

func GetParamHmacMD5Sign(secret, params string) (string, error)

func GetParamHmacSHA1Sign

func GetParamHmacSHA1Sign(secret, params string) (string, error)

func GetParamHmacSHA256Base64Sign

func GetParamHmacSHA256Base64Sign(secret, params string) (string, error)

func GetParamHmacSHA256Sign

func GetParamHmacSHA256Sign(secret, params string) (string, error)

func GetParamHmacSHA512Base64Sign

func GetParamHmacSHA512Base64Sign(hmac_key string, hmac_data string) string

func GetParamHmacSHA512Sign

func GetParamHmacSHA512Sign(secret, params string) (string, error)

func GetParamHmacSha384Sign

func GetParamHmacSha384Sign(secret, params string) (string, error)

for bitfinex.com

func GetParamMD5Sign

func GetParamMD5Sign(secret, params string) (string, error)

*

*md5签名,okcoin和huobi适用

func GetPrecision

func GetPrecision(minSize float64) int

func GetPrecisionInt64

func GetPrecisionInt64(minSize float64) int64

func GetSHA

func GetSHA(text string) (string, error)

func GzipUnCompress

func GzipUnCompress(data []byte) ([]byte, error)

func NewHttpRequest

func NewHttpRequest(
	client *http.Client,
	reqType,
	reqUrl,
	postData string,
	requstHeaders map[string]string,
) ([]byte, error)

func ToFloat64

func ToFloat64(v interface{}) float64

func ToInt

func ToInt(v interface{}) int

func ToInt64

func ToInt64(v interface{}) int64

func ToUint64

func ToUint64(v interface{}) uint64

func UUID

func UUID() string

func ValuesToJson

func ValuesToJson(v url.Values) ([]byte, error)

Types

type APIConfig

type APIConfig struct {
	HttpClient    *http.Client
	LastTimestamp int64
	Endpoint      string
	ApiKey        string
	ApiSecretKey  string
	ApiPassphrase string //for okex.com v3 api
	ClientId      string //for bitstamp.net , huobi.pro
	Location      *time.Location
}

*

*
* models about API config
*
*

type Account

type Account struct {
	Exchange    string
	Asset       float64 //总资产
	NetAsset    float64 //净资产
	SubAccounts map[string]SubAccount
}

models about account

type Currency

type Currency struct {
	Symbol string `json:"symbol"`
	Desc   string `json:"-"`
}

func NewCurrency

func NewCurrency(symbol, desc string) Currency

func (Currency) Eq

func (c Currency) Eq(c2 Currency) bool

func (Currency) String

func (c Currency) String() string

type Depth

type Depth struct {
	Pair      Pair
	Timestamp int64
	Sequence  int64 // The increasing sequence, cause the http return sequence is not sure.
	Date      string
	AskList   DepthRecords // Ascending order
	BidList   DepthRecords // Descending order
}

func (*Depth) Verify

func (depth *Depth) Verify() error

Verify the depth data is right

type DepthRecord

type DepthRecord struct {
	Price  float64
	Amount float64
}

type DepthRecords

type DepthRecords []DepthRecord

func (DepthRecords) Len

func (dr DepthRecords) Len() int

func (DepthRecords) Less

func (dr DepthRecords) Less(i, j int) bool

func (DepthRecords) Swap

func (dr DepthRecords) Swap(i, j int)

type Error

type Error interface {
	error
	Code() int
}

func NewError

func NewError(code int, message string, args ...interface{}) Error

New creates a new API error with a code and a message

type FutureAPIConfig

type FutureAPIConfig struct {
	APIConfig
	Lever int // lever number , for future
}

*

*
* models about API config
*

type FutureAccount

type FutureAccount struct {
	SubAccount map[Currency]FutureSubAccount
	Exchange   string
}

type FutureAccountItem

type FutureAccountItem struct {
	Pair         Pair
	ContractName string
	Exchange     string
	Subject      string

	SettleMode     int64 // 1: basis 2: counter
	SettleCurrency Currency
	Amount         float64
	Timestamp      int64
	DateTime       string
	Info           string
}

type FutureContract

type FutureContract struct {
	Pair         Pair   `json:"-"`
	Symbol       string `json:"symbol"`
	Exchange     string `json:"exchange"`
	ContractType string `json:"contract_type"` // eg: this_week next_week quarter next_quarter
	ContractName string `json:"contract_name"` // eg: BTC-USD-201025
	SettleMode   int64  `json:"settle_mode"`   // 1: BASIS 2: COUNTER

	OpenTimestamp int64  `json:"open_timestamp"`
	OpenDate      string `json:"open_date"`
	DueTimestamp  int64  `json:"due_timestamp"`
	DueDate       string `json:"due_date"`

	UnitAmount      float64 `json:"unit_amount"`
	TickSize        float64 `json:"tick_size"`
	PricePrecision  int64   `json:"price_precision"`
	AmountPrecision int64   `json:"amount_precision"`

	MaxScalePriceLimit float64 `json:"max_scale_price_limit"`
	MinScalePriceLimit float64 `json:"min_scale_price_limit"`
}

type FutureContracts

type FutureContracts struct {
	ContractTypeKV map[string]*FutureContract `json:"contract_type_kv"`
	ContractNameKV map[string]*FutureContract `json:"contract_name_kv"`
	DueTimestampKV map[string]*FutureContract `json:"due_timestamp_kv"`
}

type FutureDepth

type FutureDepth struct {
	ContractType string // for future
	ContractName string // for future
	Pair         Pair
	Timestamp    int64
	DueTimestamp int64
	// The increasing sequence, cause the http return sequence is not sure.
	Sequence int64
	Date     string
	AskList  DepthRecords // Ascending order
	BidList  DepthRecords // Descending order
}

func (FutureDepth) Verify

func (fd FutureDepth) Verify() error

Do not trust the data from exchange, just verify it.

type FutureKline

type FutureKline struct {
	Kline        `json:",-"` // 按照kline中的字段进行解析。
	ContractType string      `json:"contract_type"`
	DueTimestamp int64       `json:"due_timestamp"`
	DueDate      string      `json:"due_date"`
	Vol2         float64     `json:"vol_2"` //个数
}

func GetAscFutureKline

func GetAscFutureKline(klines []*FutureKline) []*FutureKline

type FutureOrder

type FutureOrder struct {
	// cid is important, when the order api return wrong, you can find it in unfinished api
	Cid            string
	OrderId        string
	Price          float64
	Amount         int64
	AvgPrice       float64
	DealAmount     int64
	PlaceTimestamp int64
	PlaceDatetime  string
	DealTimestamp  int64 // unit: ms
	DealDatetime   string
	Status         TradeStatus
	PlaceType      PlaceType  // place order type 0:NORMAL 1:MAKER_ONLY 2:FOK 3:IOC
	Type           FutureType // type 1:OPEN_LONG 2:OPEN_SHORT 3:LIQUIDATE_LONG 4: LIQUIDATE_SHORT
	LeverRate      int64
	Fee            float64
	Pair           Pair
	ContractType   string
	ContractName   string // for future
	Exchange       string
}

type FuturePosition

type FuturePosition struct {
	BuyAmount           float64
	BuyAvailable        float64
	BuyPriceAvg         float64
	BuyPriceCost        float64
	BuyProfitReal       float64
	CreateDate          int64
	LeverRate           int
	SellAmount          float64
	SellAvailable       float64
	SellPriceAvg        float64
	SellPriceCost       float64
	SellProfitReal      float64
	Symbol              Pair //btc_usd:比特币,ltc_usd:莱特币
	ContractType        string
	ContractId          int64
	ForceLiquidatePrice float64 //预估爆仓价
}

type FutureRestAPI

type FutureRestAPI interface {

	// public api
	GetExchangeName() string
	GetContract(pair Pair, contractType string) (*FutureContract, error)
	GetTicker(pair Pair, contractType string) (*FutureTicker, []byte, error)
	GetDepth(pair Pair, contractType string, size int) (*FutureDepth, []byte, error)
	GetLimit(pair Pair, contractType string) (float64, float64, error)
	GetIndex(pair Pair) (float64, []byte, error)
	GetMark(pair Pair, contractType string) (float64, []byte, error)
	GetKlineRecords(contractType string, pair Pair, period, size, since int) ([]*FutureKline, []byte, error)
	GetTrades(pair Pair, contractType string) ([]*Trade, []byte, error)

	// private api
	GetAccount() (*FutureAccount, []byte, error)
	PlaceOrder(order *FutureOrder) ([]byte, error)
	CancelOrder(order *FutureOrder) ([]byte, error)
	GetOrders(pair Pair, contractType string) ([]*FutureOrder, []byte, error)
	GetOrder(order *FutureOrder) ([]byte, error)
	GetPairFlow(pair Pair) ([]*FutureAccountItem, []byte, error)

	// util api
	KeepAlive()
}

type FutureRule

type FutureRule struct {
	Rule        `json:",-"` // 按照Rule里面的规则进行。
	ContractVal float64     `json:"contract_val"` //合约一手价格
}

type FutureSubAccount

type FutureSubAccount struct {
	Currency Currency
	// The future margin 期货保证金 == marginFilled+ marginUnFilled
	Margin float64
	// The future is filled 已经成交的订单占用的期货保证金
	MarginDealed float64
	// The future is unfilled 未成交的订单占用的保证金
	MarginUnDealed float64
	// 保证金率
	MarginRate float64
	// 总值
	BalanceTotal float64
	// 净值
	// BalanceNet = BalanceTotal + ProfitUnreal + ProfitReal
	BalanceNet float64
	// 可提取
	// BalanceAvail = BalanceNet - Margin
	BalanceAvail float64
	//已实现盈亏
	ProfitReal float64
	// 未实现盈亏
	ProfitUnreal float64
}

type FutureTicker

type FutureTicker struct {
	Ticker
	ContractType string `json:"contract_type"`
	ContractName string `json:"contract_name"`
}

type FutureType

type FutureType int64
const (
	OPEN_LONG       FutureType = 1 + iota //开多
	OPEN_SHORT                            //开空
	LIQUIDATE_LONG                        //平多
	LIQUIDATE_SHORT                       //平空
)

func (FutureType) String

func (ft FutureType) String() string

type FutureWebsocketAPI

type FutureWebsocketAPI interface {
	Init()

	Subscribe(channel string) error

	Start()

	Close()
}

type Kline

type Kline struct {
	Pair      Pair    `json:"symbol"`
	Exchange  string  `json:"exchange"`
	Timestamp int64   `json:"timestamp"`
	Date      string  `json:"date"`
	Open      float64 `json:"open"`
	Close     float64 `json:"close"`
	High      float64 `json:"high"`
	Low       float64 `json:"low"`
	Vol       float64 `json:"vol"`
}

func GetAscKline

func GetAscKline(klines []*Kline) []*Kline

type Loan

type Loan struct {
	Pair              Pair       // The loan currency pair
	Currency          Currency   // Currency
	Amount            float64    // Loan amount
	AmountLoaned      float64    // Loaned amount
	AmountInterest    float64    // Loan interest
	Status            LoanStatus // The loan record status
	LoanId            string     // Remote loan record id
	LoanTimestamp     int64      // Loan timestamp
	LoanDate          string     // Loan date
	RepayId           string     // Remote loan record repay id
	RepayTimestamp    int64      // Repay Timestamp
	RepayDate         string     // Repay Date
	RepayDeadlineDate string     // Repay Deadline Date
}

type LoanStatus

type LoanStatus int
const (
	LOAN_UNFINISH LoanStatus = iota
	LOAN_PART_FINISH
	LOAN_FINISH

	LOAN_FAIL
	LOAN_REPAY
)

type MarginAccount

type MarginAccount struct {
	Pair       Pair
	SubAccount map[string]MarginSubAccount

	LiquidationPrice float64 //预计爆仓价格
	RiskRate         float64
	MarginRatio      float64
}

type MarginRestAPI

type MarginRestAPI interface {
	// public api
	GetTicker(pair Pair) (*Ticker, []byte, error)
	GetDepth(pair Pair, size int) (*Depth, []byte, error)
	GetKlineRecords(pair Pair, period, size, since int) ([]*Kline, []byte, error)
	GetExchangeName() string

	// private api
	GetAccount(pair Pair) (*MarginAccount, []byte, error)
	PlaceOrder(order *Order) ([]byte, error)
	CancelOrder(order *Order) ([]byte, error)
	GetOrder(order *Order) ([]byte, error)
	GetOrders(pair Pair) ([]*Order, []byte, error) // all orders desc recently
	GetUnFinishOrders(pair Pair) ([]*Order, []byte, error)
	PlaceLoan(loan *Loan) ([]byte, error)
	GetLoan(loan *Loan) ([]byte, error)
	ReturnLoan(loan *Loan) ([]byte, error)

	// util api
	KeepAlive()
}

api interface

type MarginSubAccount

type MarginSubAccount struct {
	Currency Currency
	// Amount = AmountNet + AmountLoaned = AmountAvail + AmountFrozen
	Amount float64
	// 可用额度
	AmountAvail float64
	// 冻结额度
	AmountFrozen float64
	// 净值额度
	AmountNet float64
	// 已借贷额度
	AmountLoaned float64
	// 当前借贷费用
	LoaningFee float64
}

type OHLC

type OHLC struct {
	Symbol    string  `json:"symbol"`
	Exchange  string  `json:"exchange"`
	Timestamp int64   `json:"timestamp"`
	Date      string  `json:"date"`
	Open      float64 `json:"open"`
	Close     float64 `json:"close"`
	High      float64 `json:"high"`
	Low       float64 `json:"low"`
	Vol       float64 `json:"vol"`
}

type Order

type Order struct {
	// cid is important, when the order api return wrong, you can find it in unfinished api
	Cid            string
	Price          float64
	Amount         float64
	AvgPrice       float64
	DealAmount     float64
	Fee            float64
	OrderId        string
	OrderTimestamp int64
	OrderDate      string
	Status         TradeStatus
	Pair           Pair
	Side           TradeSide
	//0:NORMAL,1:ONLY_MAKER,2:FOK,3:IOC
	OrderType PlaceType
}

*

*
* models about trade
*
*

type Pair

type Pair struct {
	//The target currency, you want to buy or long
	//目标货币,你想买或者做多的。
	Basis Currency
	//The counter currency, you use it to buy or to mortgage
	//计数货币,你想用它来购买或者用它来做为抵押物。
	Counter Currency
}

func NewPair

func NewPair(symbol string, sepChar string) Pair

func (Pair) Eq

func (pair Pair) Eq(otherPair Pair) bool

func (Pair) String

func (pair Pair) String() string

func (Pair) ToSwapContractName

func (pair Pair) ToSwapContractName() string

func (Pair) ToSymbol

func (pair Pair) ToSymbol(joinChar string, isUpper bool) string

type PlaceType

type PlaceType int
const (
	NORMAL     PlaceType = iota // normal order, need to cancel (GTC)
	ONLY_MAKER                  // only maker
	FOK                         // fill or kill
	IOC                         // Immediate or Cancel
)

func (PlaceType) String

func (ot PlaceType) String() string

type Rule

type Rule struct {
	Pair    Pair
	Base    Currency
	Counter Currency

	BaseMinSize      float64
	BasePrecision    int
	CounterPrecision int
}

type SpotRestAPI

type SpotRestAPI interface {

	// public api
	GetExchangeName() string
	//GetExchangeRule(pair Pair) (*Rule, []byte, error)
	GetTicker(pair Pair) (*Ticker, []byte, error)
	GetDepth(pair Pair, size int) (*Depth, []byte, error)
	GetKlineRecords(pair Pair, period, size, since int) ([]*Kline, []byte, error)
	GetTrades(pair Pair, since int64) ([]*Trade, error)

	// private api
	GetAccount() (*Account, []byte, error)
	PlaceOrder(order *Order) ([]byte, error)
	CancelOrder(order *Order) ([]byte, error)
	GetOrder(order *Order) ([]byte, error)
	GetOrders(pair Pair) ([]*Order, error) // dealed orders
	GetUnFinishOrders(pair Pair) ([]*Order, []byte, error)

	// util api
	KeepAlive()

	// v2 API
	GetOHLCs(symbol string, period, size, since int) ([]*OHLC, []byte, error)
}

api interface

type SubAccount

type SubAccount struct {
	Currency     Currency
	Amount       float64
	AmountFrozen float64
}

type SwapAccount

type SwapAccount struct {
	Exchange string
	// In swap, the usdt is default.
	Currency Currency
	// The future margin 期货保证金 == marginFilled+ marginUnFilled
	Margin float64
	// The future is filled 已经成交的订单占用的期货保证金
	MarginPosition float64
	// The future is unfilled 未成交的订单占用的保证金
	MarginOpen float64
	// 保证金率
	MarginRate float64
	// 总值
	BalanceTotal float64
	// 净值
	// BalanceNet = BalanceTotal + ProfitUnreal + ProfitReal
	BalanceNet float64
	// 可提取
	// BalanceAvail = BalanceNet - Margin
	BalanceAvail float64
	//已实现盈亏
	ProfitReal float64
	// 未实现盈亏
	ProfitUnreal float64

	Positions []*SwapPosition
}

type SwapAccountItem

type SwapAccountItem struct {
	Pair     Pair
	Exchange string
	Subject  string

	SettleMode     int64 // 1: basis 2: counter
	SettleCurrency Currency
	Amount         float64
	Timestamp      int64
	DateTime       string
	Info           string
}

type SwapContract

type SwapContract struct {
	Pair         Pair   `json:"-"`
	Symbol       string `json:"symbol"`
	Exchange     string `json:"exchange"`
	ContractName string `json:"contract_name"` // 标准contract_name和具体交易所无关,以ok的规则为准。
	SettleMode   int64  `json:"settle_mode"`   // 1: BASIS 币本位 2: COUNTER U本位

	UnitAmount      float64 `json:"unit_amount"`
	TickSize        float64 `json:"tick_size"`
	PricePrecision  int64   `json:"price_precision"`
	AmountPrecision int64   `json:"amount_precision"`
}

type SwapContracts

type SwapContracts struct {
	// 按照合约到期日期查找,以ok的命名规则为准吧 BTC-USD-SWAP BTC-USDT-SWAP
	ContractNameKV map[string]*SwapContract `json:"contract_name_kv"`
}

type SwapDepth

type SwapDepth struct {
	Pair      Pair
	Timestamp int64
	Sequence  int64 // The increasing sequence, cause the http return sequence is not sure.
	Date      string
	AskList   DepthRecords // Ascending order
	BidList   DepthRecords // Descending order
}

func (*SwapDepth) Verify

func (depth *SwapDepth) Verify() error

Verify the depth data is right

type SwapKline

type SwapKline struct {
	Pair      Pair    `json:"-"`
	Exchange  string  `json:"exchange"`
	Timestamp int64   `json:"timestamp"`
	Date      string  `json:"date"`
	Open      float64 `json:"open"`
	Close     float64 `json:"close"`
	High      float64 `json:"high"`
	Low       float64 `json:"low"`
	Vol       float64 `json:"vol"`
}

func GetAscSwapKline

func GetAscSwapKline(klines []*SwapKline) []*SwapKline

type SwapOrder

type SwapOrder struct {
	// cid is important, when the order api return wrong, you can find it in unfinished api
	Cid            string
	OrderId        string
	Price          float64
	Amount         float64
	AvgPrice       float64
	DealAmount     float64
	PlaceTimestamp int64
	PlaceDatetime  string
	DealTimestamp  int64 // unit: ms
	DealDatetime   string
	Status         TradeStatus
	PlaceType      PlaceType  // place_type 0:NORMAL 1:MAKER_ONLY 2:FOK 3:IOC
	Type           FutureType // type 1:OPEN_LONG 2:OPEN_SHORT 3:LIQUIDATE_LONG 4: LIQUIDATE_SHORT
	MarginType     string     // margin_type 全仓:crossed 逐仓:isolated
	LeverRate      int64
	Fee            float64
	Pair           Pair
	Exchange       string
}

type SwapPosition

type SwapPosition struct {
	Pair           Pair
	Type           FutureType //open_long or open_short
	Amount         float64    // position amount
	Price          float64    // position price
	MarkPrice      float64
	LiquidatePrice float64
	MarginType     string
	MarginAmount   float64
	Leverage       int64
}

type SwapRestAPI

type SwapRestAPI interface {
	// public api
	GetExchangeName() string
	GetTicker(pair Pair) (*SwapTicker, []byte, error)
	GetDepth(pair Pair, size int) (*SwapDepth, []byte, error)
	GetContract(pair Pair) *SwapContract
	GetLimit(pair Pair) (float64, float64, error)
	GetKline(pair Pair, period, size, since int) ([]*SwapKline, []byte, error)
	GetOpenAmount(pair Pair) (float64, int64, []byte, error)
	GetFundingFees(pair Pair) ([][]interface{}, []byte, error)
	GetFundingFee(pair Pair) (float64, error)

	// private api
	GetAccount() (*SwapAccount, []byte, error)
	PlaceOrder(order *SwapOrder) ([]byte, error)
	CancelOrder(order *SwapOrder) ([]byte, error)
	GetOrder(order *SwapOrder) ([]byte, error)
	GetOrders(pair Pair) ([]*SwapOrder, []byte, error)
	GetUnFinishOrders(pair Pair) ([]*SwapOrder, []byte, error)
	GetPosition(pair Pair, openType FutureType) (*SwapPosition, []byte, error)
	AddMargin(pair Pair, openType FutureType, marginAmount float64) ([]byte, error)
	ReduceMargin(pair Pair, openType FutureType, marginAmount float64) ([]byte, error)
	GetAccountFlow() ([]*SwapAccountItem, []byte, error)
	GetPairFlow(pair Pair) ([]*SwapAccountItem, []byte, error)

	// util api
	KeepAlive()
}

type SwapTicker

type SwapTicker struct {
	Pair      Pair    `json:"-"`
	Last      float64 `json:"last"`
	Buy       float64 `json:"buy"`
	Sell      float64 `json:"sell"`
	High      float64 `json:"high"`
	Low       float64 `json:"low"`
	Vol       float64 `json:"vol"`
	Timestamp int64   `json:"timestamp"` // unit:ms
	Date      string  `json:"date"`      // date: format yyyy-mm-dd HH:MM:SS, the timezone define in apiconfig
}

type Ticker

type Ticker struct {
	Pair      Pair    `json:"-"`
	Last      float64 `json:"last"`
	Buy       float64 `json:"buy"`
	Sell      float64 `json:"sell"`
	High      float64 `json:"high"`
	Low       float64 `json:"low"`
	Vol       float64 `json:"vol"`
	Timestamp int64   `json:"timestamp"` // unit:ms
	Date      string  `json:"date"`      // date: format yyyy-mm-dd HH:MM:SS, the timezone define in apiconfig
}

type Trade

type Trade struct {
	Tid       int64     `json:"tid"`
	Type      TradeSide `json:"type"`
	Amount    float64   `json:"amount,string"`
	Price     float64   `json:"price,string"`
	Timestamp int64     `json:"timestamp"`
	Pair      Pair      `json:"-"`
}

record

type TradeSide

type TradeSide int64
const (
	BUY TradeSide = 1 + iota
	SELL
	BUY_MARKET
	SELL_MARKET
)

func (TradeSide) String

func (ts TradeSide) String() string

type TradeStatus

type TradeStatus int64
const (
	ORDER_UNFINISH TradeStatus = iota
	ORDER_PART_FINISH
	ORDER_FINISH
	ORDER_CANCEL
	ORDER_REJECT
	ORDER_CANCEL_ING
	ORDER_FAIL
)

func (TradeStatus) String

func (ts TradeStatus) String() string

type WsBuilder

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

websocket build config

func NewWsBuilder

func NewWsBuilder() *WsBuilder

func (*WsBuilder) Build

func (b *WsBuilder) Build() *WsConn

func (*WsBuilder) Dump

func (b *WsBuilder) Dump() *WsBuilder

func (*WsBuilder) ErrorHandleFunc

func (b *WsBuilder) ErrorHandleFunc(f func(err error)) *WsBuilder

func (*WsBuilder) Heartbeat

func (b *WsBuilder) Heartbeat(data []byte, dataType int, t time.Duration) *WsBuilder

func (*WsBuilder) ProtoHandleFunc

func (b *WsBuilder) ProtoHandleFunc(f func([]byte) error) *WsBuilder

func (*WsBuilder) ProxyUrl

func (b *WsBuilder) ProxyUrl(proxyUrl string) *WsBuilder

func (*WsBuilder) ReconnectIntervalTime

func (b *WsBuilder) ReconnectIntervalTime(t time.Duration) *WsBuilder

func (*WsBuilder) ReqHeader

func (b *WsBuilder) ReqHeader(key, value string) *WsBuilder

func (*WsBuilder) UnCompressFunc

func (b *WsBuilder) UnCompressFunc(f func([]byte) ([]byte, error)) *WsBuilder

func (*WsBuilder) WsUrl

func (b *WsBuilder) WsUrl(wsUrl string) *WsBuilder

type WsConfig

type WsConfig struct {
	WsUrl                 string              // websocket server url, necessary
	ProxyUrl              string              // proxy url, not necessary
	ReqHeaders            map[string][]string // set the head info ,when connecting, not necessary
	HeartbeatIntervalTime time.Duration       // the heartbeat interval, necessary
	HeartbeatData         []byte              // the raw text of heartbeat data for example: ping, necessary if heartbeatfunc is nil
	HeartbeatDataType     int

	//HeartbeatFunc         func() interface{}           // the json text of heartbeat data , necessary if heartbeatdata is nil
	ReconnectIntervalTime time.Duration                // force reconnect on XXX time duration, not necessary
	ProtoHandleFunc       func([]byte) error           // the message handle func, necessary
	UnCompressFunc        func([]byte) ([]byte, error) // the uncompress func, not necessary
	ErrorHandleFunc       func(err error)              // the error handle func, not necessary
	IsDump                bool                         // is print the connect info, not necessary
}

type WsConn

type WsConn struct {
	*websocket.Conn
	sync.Mutex
	WsConfig
	// contains filtered or unexported fields
}

func (*WsConn) CloseWs

func (ws *WsConn) CloseWs()

func (*WsConn) HeartbeatTimer

func (ws *WsConn) HeartbeatTimer()

func (*WsConn) NewWs

func (ws *WsConn) NewWs() *WsConn

func (*WsConn) ReConnect

func (ws *WsConn) ReConnect()

func (*WsConn) ReConnectTimer

func (ws *WsConn) ReConnectTimer()

func (*WsConn) ReceiveMessage

func (ws *WsConn) ReceiveMessage()

func (*WsConn) SendJsonMessage

func (ws *WsConn) SendJsonMessage(v interface{}) error

func (*WsConn) SendTextMessage

func (ws *WsConn) SendTextMessage(data []byte) error

func (*WsConn) Subscribe

func (ws *WsConn) Subscribe(subEvent interface{}) error

func (*WsConn) UpdateActiveTime

func (ws *WsConn) UpdateActiveTime()

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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