kumex

package module
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Apr 1, 2020 License: MIT Imports: 24 Imported by: 2

README

Go SDK for KuMex API

The detailed document https://docs.kumex.com, in order to receive the latest API change notifications, please Watch this repository.

Latest Version GoDoc Build Status Go Report Card Sourcegraph

Install

go get github.com/Kucoin/kumex-go-sdk

Usage

Choose environment
Environment BaseUri
Production https://api.kumex.com(DEFAULT) https://api.kumex.top
Sandbox https://sandbox-api.kumex.com
Create ApiService
s := kumex.NewApiService( 
	// kumex.ApiBaseURIOption("https://api.kumex.com"), 
	kumex.ApiKeyOption("key"),
	kumex.ApiSecretOption("secret"),
	kumex.ApiPassPhraseOption("passphrase"),
)

// Or add these options into the environmental variable
// Bash: 
// export API_BASE_URI=https://api.kumex.com
// export API_KEY=key
// export API_SECRET=secret
// export API_PASSPHRASE=passphrase
// s := NewApiServiceFromEnv()
Debug mode & logging
// Require package github.com/sirupsen/logrus
// Debug mode will record the logs of API and WebSocket to files.
// Default values: LogLevel=logrus.DebugLevel, LogDirectory="/tmp"
kumex.DebugMode = true
// Or export API_DEBUG_MODE=1

// Logging in your code
// kumex.SetLoggerDirectory("/tmp")
// logrus.SetLevel(logrus.DebugLevel)
logrus.Debugln("I'm a debug message")
Examples

See the test case for more examples.

Example of API without authentication
rsp, err := s.ServerTime()
if err != nil {
    log.Printf("Error: %s", err.Error())
    // Handle error
    return
}

var ts int64
if err := rsp.ReadData(&ts); err != nil {
    // Handle error
    return
}
log.Printf("The server time: %d", ts)
Example of API with authentication
// Without pagination
rsp, err := s.AccountOverview()
if err != nil {
    // Handle error
    return
}

as := kumex.AccountsModel{}
if err := rsp.ReadData(&as); err != nil {
    // Handle error
    return
}

for _, a := range as {
    log.Printf("Available balance: %s %s => %s", a.Type, a.Currency, a.Available)
}
// Handle pagination
rsp, err := s.Orders(map[string]string{}, &kumex.PaginationParam{CurrentPage: 1, PageSize: 10})
if err != nil {
    // Handle error
    return
}

os := kumex.OrdersModel{}
pa, err := rsp.ReadPaginationData(&os)
if err != nil {
    // Handle error
    return
}
log.Printf("Total num: %d, total page: %d", pa.TotalNum, pa.TotalPage)
for _, o := range os {
    log.Printf("Order: %s, %s, %s", o.Id, o.Type, o.Price)
}
Example of WebSocket feed

Require package gorilla/websocket

go get github.com/gorilla/websocket github.com/pkg/errors
rsp, err := s.WebSocketPublicToken()
if err != nil {
    // Handle error
    return
}

tk := &kumex.WebSocketTokenModel{}
if err := rsp.ReadData(tk); err != nil {
    // Handle error
    return
}

c := s.NewWebSocketClient(tk)
// c.AcceptUserMessage = true 


mc, ec, err := c.Connect()
if err != nil {
    // Handle error
    return
}

ch1 := kumex.NewSubscribeMessage("/contractMarket/ticker:XBTUSDM", false)
ch2 := kumex.NewSubscribeMessage("/contractMarket/ticker:XBTUSDM", false)
uch := kumex.NewUnsubscribeMessage("/contractMarket/ticker:XBTUSDM", false)

if err := c.Subscribe(ch1, ch2); err != nil {
    // Handle error
    return
}

var i = 0
for {
    select {
    case err := <-ec:
        c.Stop() // Stop subscribing the WebSocket feed
        log.Printf("Error: %s", err.Error())
        // Handle error
        return
    case msg := <-mc:
        // log.Printf("Received: %s", kumex.ToJsonString(m))
        t := &kumex.TickerLevel1Model{}
        if err := msg.ReadData(t); err != nil {
            log.Printf("Failure to read: %s", err.Error())
            return
        }
        log.Printf("Ticker: %s, %s, %s, %s", msg.Topic, t.Sequence, t.Price, t.Size)
        i++
        if i == 5 {
            log.Println("Unsubscribe XBTUSDM")
            if err = c.Unsubscribe(uch); err != nil {
                log.Printf("Error: %s", err.Error())
                // Handle error
                return
            }
        }
        if i == 10 {
            log.Println("Subscribe XBTUSDM")
            if err = c.Subscribe(ch2); err != nil {
                log.Printf("Error: %s", err.Error())
                // Handle error
                return
            }
        }
        if i == 15 {
            log.Println("Exit subscription")
            c.Stop() // Stop subscribing the WebSocket feed
            return
        }
    }
}
API list
Account
API Authentication Description
ApiService.AccountOverview() YES https://docs.kumex.com/#get-account-overview
ApiService.TransactionHistory() YES https://docs.kumex.com/#get-transaction-history
Deposit
API Authentication Description
ApiService.DepositAddresses() YES https://docs.kumex.com/#get-deposit-address
ApiService.Deposits() YES https://docs.kumex.com/#get-deposit-list
Withdrawal
API Authentication Description
ApiService.WithdrawalQuotas() YES https://docs.kumex.com/#get-withdrawal-quotas
ApiService.ApplyWithdrawal() YES https://docs.kumex.com/#apply-withdraw
ApiService.Withdrawals() YES https://docs.kumex.com/#get-withdrawals-list
ApiService.CancelWithdrawal() YES https://docs.kumex.com/#cancel-withdrawal
Transfer
API Authentication Description
ApiService.TransferOut() YES https://docs.kumex.com/#transfer-out
ApiService.TransferOutV2() YES https://docs.kumex.com/#transfer-funds-to-kucoin-main-account
ApiService.TransferList() YES https://docs.kumex.com/#get-transfer-list
ApiService.CancelTransfer() YES https://docs.kumex.com/#cancel-transfer
Fill
API Authentication Description
ApiService.Fills() YES https://docs.kumex.com/#list-fills
ApiService.RecentFills() YES https://docs.kumex.com/#recent-fills
ApiService.openOrderStatistics() YES https://docs.kumex.com/#open-order-statistics
Order
API Authentication Description
ApiService.CreateOrder() YES https://docs.kumex.com/#place-a-new-order
ApiService.CancelOrder() YES https://docs.kumex.com/#cancel-an-order
ApiService.CancelOrders() YES https://docs.kumex.com/#cancel-all-orders
ApiService.StopOrders() YES https://docs.kumex.com/#get-untriggered-stop-order-list
ApiService.Orders() YES https://docs.kumex.com/#list-orders
ApiService.Order() YES https://docs.kumex.com/#get-an-order
ApiService.RecentOrders() YES https://docs.kumex.com/#recent-orders
Market
API Authentication Description
ApiService.Ticker() NO https://docs.kumex.com/#get-real-time-ticker
ApiService.Level2Snapshot() NO https://docs.kumex.com/#get-full-order-book-level-2
ApiService.Level2MessageQuery()() NO https://docs.kumex.com/#level-2-pulling-messages
ApiService.Level3Snapshot() NO https://docs.kumex.com/#get-full-order-book-level-3
ApiService.Level3MessageQuery() NO https://docs.kumex.com/#level-3-pulling-messages
ApiService.TradeHistory() NO https://docs.kumex.com/#transaction-history
ApiService.InterestQuery() NO https://docs.kumex.com/#get-interest-rate-list
ApiService.IndexQuery() NO https://docs.kumex.com/#get-index-list
ApiService.MarkPrice() NO https://docs.kumex.com/#get-current-mark-price
ApiService.PremiumQuery() NO https://docs.kumex.com/#get-premium-index
ApiService.FundingRate() NO https://docs.kumex.com/#get-current-funding-rate
Symbol
API Authentication Description
ApiService.ActiveContracts() NO https://docs.kumex.com/#get-open-contract-list
ApiService.Contracts() NO https://docs.kumex.com/#get-order-info-of-the-contract
WebSocket Feed
API Authentication Description
ApiService.WebSocketPublicToken() NO https://docs.kumex.com/#apply-connect-token
ApiService.WebSocketPrivateToken() YES https://docs.kumex.com/#apply-connect-token
ApiService.NewWebSocketClient() - https://docs.kumex.com/#websocket-feed
Time
API Authentication Description
ApiService.ServerTime() NO https://docs.kumex.com/#server-time

Run tests

# Add your API configuration items into the environmental variable first
export API_BASE_URI=https://api.kumex.com
export API_KEY=key
export API_SECRET=secret
export API_PASSPHRASE=passphrase

# Run tests
go test -v

License

MIT

Documentation

Overview

Package kumex provides two kinds of APIs: `RESTful API` and `WebSocket feed`. The official document: https://docs.kumex.com

Index

Constants

View Source
const (
	WelcomeMessage     = "welcome"
	PingMessage        = "ping"
	PongMessage        = "pong"
	SubscribeMessage   = "subscribe"
	AckMessage         = "ack"
	UnsubscribeMessage = "unsubscribe"
	ErrorMessage       = "error"
	Message            = "message"
	Notice             = "notice"
	Command            = "command"
)

All message types of WebSocket.

View Source
const (
	ApiSuccess = "200000"
)

The predefined API codes

View Source
const ProductionApiBaseURI = "https://api.kumex.com"

ProductionApiBaseURI is api base uri for production.

Variables

View Source
var (
	// Version is SDK version.
	Version = "1.0.3"
	// DebugMode will record the logs of API and WebSocket to files in the directory "kumex.LogDirectory" according to the minimum log level "kumex.LogLevel".
	DebugMode = os.Getenv("API_DEBUG_MODE") == "1"
)

Functions

func IntToString

func IntToString(i int64) string

IntToString converts int64 to string.

func SetLoggerDirectory

func SetLoggerDirectory(directory string)

SetLoggerDirectory sets the directory for logrus output.

func ToJsonString

func ToJsonString(v interface{}) string

ToJsonString converts any value to JSON string.

Types

type AccountModel

type AccountModel struct {
	AccountEquity    float64 `json:"accountEquity"`
	UnrealisedPNL    float64 `json:"unrealisedPNL"`
	MarginBalance    float64 `json:"marginBalance"`
	PositionMargin   float64 `json:"positionMargin"`
	OrderMargin      float64 `json:"orderMargin"`
	FrozenFunds      float64 `json:"frozenFunds"`
	AvailableBalance float64 `json:"availableBalance"`
	Currency         string  `json:"currency"`
}

An AccountModel represents an account.

type AccountsModel

type AccountsModel []*AccountModel

An AccountsModel is the set of *AccountModel.

type ApiResponse

type ApiResponse struct {
	Code    string              `json:"code"`
	RawData jsoniter.RawMessage `json:"data"` // delay parsing
	Message string              `json:"msg"`
	// contains filtered or unexported fields
}

An ApiResponse represents a API response wrapped Response.

func (*ApiResponse) ApiSuccessful

func (ar *ApiResponse) ApiSuccessful() bool

ApiSuccessful judges the success of API.

func (*ApiResponse) HttpSuccessful

func (ar *ApiResponse) HttpSuccessful() bool

HttpSuccessful judges the success of http.

func (*ApiResponse) ReadData

func (ar *ApiResponse) ReadData(v interface{}) error

ReadData read the api response `data` as JSON into v.

func (*ApiResponse) ReadPaginationData

func (ar *ApiResponse) ReadPaginationData(v interface{}) (*PaginationModel, error)

ReadPaginationData read the data `items` as JSON into v, and returns *PaginationModel.

type ApiService

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

An ApiService provides a HTTP client and a signer to make a HTTP request with the signature to KuCoin API.

func NewApiService

func NewApiService(opts ...ApiServiceOption) *ApiService

NewApiService creates a instance of ApiService by passing ApiServiceOptions, then you can call methods.

func NewApiServiceFromEnv

func NewApiServiceFromEnv() *ApiService

NewApiServiceFromEnv creates a instance of ApiService by environmental variables such as `API_BASE_URI` `API_KEY` `API_SECRET` `API_PASSPHRASE`, then you can call the methods of ApiService.

func (*ApiService) AccountOverview

func (as *ApiService) AccountOverview(params map[string]string) (*ApiResponse, error)

AccountOverview returns a list of accounts. See the Deposits section for documentation on how to deposit funds to begin trading.

func (*ApiService) ActiveContracts

func (as *ApiService) ActiveContracts() (*ApiResponse, error)

ActiveContracts Get Open Contract List.

func (*ApiService) ApplyWithdrawal

func (as *ApiService) ApplyWithdrawal(currency, address, amount string, options map[string]string) (*ApiResponse, error)

ApplyWithdrawal applies a withdrawal.

func (*ApiService) AutoDepositStatus

func (as *ApiService) AutoDepositStatus(params map[string]string) (*ApiResponse, error)

AutoDepositStatus Enable/Disable of Auto-Deposit Margin.

func (*ApiService) Call

func (as *ApiService) Call(request *Request) (*ApiResponse, error)

Call calls the API by passing *Request and returns *ApiResponse.

func (*ApiService) CancelOrder

func (as *ApiService) CancelOrder(orderId string) (*ApiResponse, error)

CancelOrder cancels a previously placed order.

func (*ApiService) CancelOrders

func (as *ApiService) CancelOrders(symbol string) (*ApiResponse, error)

CancelOrders cancels all orders of the symbol. With best effort, cancel all open orders. The response is a list of ids of the canceled orders.

func (*ApiService) CancelTransfer

func (as *ApiService) CancelTransfer(applyId string) (*ApiResponse, error)

CancelTransfer Cancel Transfer-Out Request.

func (*ApiService) CancelWithdrawal

func (as *ApiService) CancelWithdrawal(withdrawalId string) (*ApiResponse, error)

CancelWithdrawal cancels a withdrawal by withdrawalId.

func (*ApiService) Contracts

func (as *ApiService) Contracts(symbol string) (*ApiResponse, error)

Contracts Get Order Info. of the Contract.

func (*ApiService) CreateOrder

func (as *ApiService) CreateOrder(params map[string]string) (*ApiResponse, error)

CreateOrder places a new order.

func (*ApiService) DepositAddresses

func (as *ApiService) DepositAddresses(currency string) (*ApiResponse, error)

DepositAddresses returns the deposit address of currency for deposit. If return data is empty, you may need create a deposit address first.

func (*ApiService) DepositMargin

func (as *ApiService) DepositMargin(params map[string]string) (*ApiResponse, error)

DepositMargin Add Margin Manually.

func (*ApiService) Deposits

func (as *ApiService) Deposits(params map[string]string, pagination *PaginationParam) (*ApiResponse, error)

Deposits returns a list of deposit.

func (*ApiService) Fills

func (as *ApiService) Fills(params map[string]string, pagination *PaginationParam) (*ApiResponse, error)

Fills returns a list of recent fills.

func (*ApiService) FundingHistory

func (as *ApiService) FundingHistory(params map[string]string) (*ApiResponse, error)

FundingHistory Get Funding History.

func (*ApiService) FundingRate

func (as *ApiService) FundingRate(Symbol string) (*ApiResponse, error)

FundingRate Get Current Funding Rate.

func (*ApiService) IndexQuery

func (as *ApiService) IndexQuery(params map[string]string, pagination *PaginationParam) (*ApiResponse, error)

IndexQuery Get Index List.

func (*ApiService) InterestQuery

func (as *ApiService) InterestQuery(params map[string]string, pagination *PaginationParam) (*ApiResponse, error)

InterestQuery Get Interest Rate List .

func (*ApiService) Level2MessageQuery

func (as *ApiService) Level2MessageQuery(symbol string, start, end int64) (*ApiResponse, error)

Level2MessageQuery Level 2 Pulling Messages.

func (*ApiService) Level2Snapshot

func (as *ApiService) Level2Snapshot(symbol string) (*ApiResponse, error)

Level2Snapshot Get Full Order Book - Level 2.

func (*ApiService) Level3MessageQuery

func (as *ApiService) Level3MessageQuery(symbol string, start, end int64) (*ApiResponse, error)

Level3MessageQuery Level 3 Pulling Messages.

func (*ApiService) Level3Snapshot

func (as *ApiService) Level3Snapshot(symbol string) (*ApiResponse, error)

Level3Snapshot Get Full Order Book - Level 3.

func (*ApiService) MarkPrice

func (as *ApiService) MarkPrice(Symbol string) (*ApiResponse, error)

MarkPrice Get Current Mark Price

func (*ApiService) NewWebSocketClient

func (as *ApiService) NewWebSocketClient(token *WebSocketTokenModel) *WebSocketClient

NewWebSocketClient creates an instance of WebSocketClient.

func (*ApiService) OpenOrderStatistics

func (as *ApiService) OpenOrderStatistics(symbol string) (*ApiResponse, error)

OpenOrderStatistics Active Order Value Calculation.

func (*ApiService) Order

func (as *ApiService) Order(orderId string) (*ApiResponse, error)

Order returns a single order by order id.

func (*ApiService) Orders

func (as *ApiService) Orders(params map[string]string, pagination *PaginationParam) (*ApiResponse, error)

Orders returns a list your current orders.

func (*ApiService) Position

func (as *ApiService) Position(symbol string) (*ApiResponse, error)

Position Get Position Details.

func (*ApiService) Positions

func (as *ApiService) Positions() (*ApiResponse, error)

Positions Get Position List.

func (*ApiService) PremiumQuery

func (as *ApiService) PremiumQuery(params map[string]string, pagination *PaginationParam) (*ApiResponse, error)

PremiumQuery Get Premium Index.

func (*ApiService) RecentDoneOrders

func (as *ApiService) RecentDoneOrders() (*ApiResponse, error)

RecentDoneOrders returns the recent orders of the latest transactions within 24 hours.

func (*ApiService) RecentFills

func (as *ApiService) RecentFills() (*ApiResponse, error)

RecentFills returns the recent fills of the latest transactions within 24 hours.

func (*ApiService) ServerTime

func (as *ApiService) ServerTime() (*ApiResponse, error)

ServerTime returns the API server time.

func (*ApiService) StopOrders

func (as *ApiService) StopOrders(symbol string) (*ApiResponse, error)

StopOrders represents an order.

func (*ApiService) Ticker

func (as *ApiService) Ticker(symbol string) (*ApiResponse, error)

Ticker Get Real-Time Ticker.

func (*ApiService) TradeHistory

func (as *ApiService) TradeHistory(symbol string) (*ApiResponse, error)

TradeHistory returns a list the latest trades for a symbol.

func (*ApiService) TransactionHistory

func (as *ApiService) TransactionHistory(params map[string]string, pagination *PaginationParam) (*ApiResponse, error)

TransactionHistory returns a list of ledgers. Account activity either increases or decreases your account balance. Items are paginated and sorted latest first.

func (*ApiService) TransferList

func (as *ApiService) TransferList(params map[string]string, pagination *PaginationParam) (*ApiResponse, error)

TransferList returns a list of deposit.

func (*ApiService) TransferOut

func (as *ApiService) TransferOut(bizNo, amount string) (*ApiResponse, error)

TransferOut Transfer Funds to KuCoin-Main Account.

func (*ApiService) TransferOutV2 added in v1.0.3

func (as *ApiService) TransferOutV2(bizNo, amount, currency string) (*ApiResponse, error)

TransferOut Transfer Funds to KuCoin-Main Account.

func (*ApiService) WebSocketPrivateToken

func (as *ApiService) WebSocketPrivateToken() (*ApiResponse, error)

WebSocketPrivateToken returns the token for private channel.

func (*ApiService) WebSocketPublicToken

func (as *ApiService) WebSocketPublicToken() (*ApiResponse, error)

WebSocketPublicToken returns the token for public channel.

func (*ApiService) WithdrawalQuotas

func (as *ApiService) WithdrawalQuotas(currency string) (*ApiResponse, error)

WithdrawalQuotas returns the quotas of withdrawal.

func (*ApiService) Withdrawals

func (as *ApiService) Withdrawals(params map[string]string, pagination *PaginationParam) (*ApiResponse, error)

Withdrawals returns a list of withdrawals.

type ApiServiceOption

type ApiServiceOption func(service *ApiService)

An ApiServiceOption is a option parameter to create the instance of ApiService.

func ApiBaseURIOption

func ApiBaseURIOption(uri string) ApiServiceOption

ApiBaseURIOption creates a instance of ApiServiceOption about apiBaseURI.

func ApiKeyOption

func ApiKeyOption(key string) ApiServiceOption

ApiKeyOption creates a instance of ApiServiceOption about apiKey.

func ApiPassPhraseOption

func ApiPassPhraseOption(passPhrase string) ApiServiceOption

ApiPassPhraseOption creates a instance of ApiServiceOption about apiPassPhrase.

func ApiSecretOption

func ApiSecretOption(secret string) ApiServiceOption

ApiSecretOption creates a instance of ApiServiceOption about apiSecret.

func ApiSkipVerifyTlsOption

func ApiSkipVerifyTlsOption(skipVerifyTls bool) ApiServiceOption

ApiSkipVerifyTlsOption creates a instance of ApiServiceOption about apiSkipVerifyTls.

type ApplyWithdrawalResultModel

type ApplyWithdrawalResultModel struct {
	WithdrawalId string `json:"withdrawalId"`
}

ApplyWithdrawalResultModel represents the result of ApplyWithdrawal().

type BasicRequester

type BasicRequester struct {
}

A BasicRequester represents a basic implement of Requester by http.Client.

func (*BasicRequester) Request

func (br *BasicRequester) Request(request *Request, timeout time.Duration) (*Response, error)

Request makes a http request.

type CancelOrderResultModel

type CancelOrderResultModel struct {
	CancelledOrderIds []string `json:"cancelledOrderIds"`
}

A CancelOrderResultModel represents the result of CancelOrder().

type CancelTransferModel

type CancelTransferModel struct {
	ApplyId string `json:"applyId"`
}

CancelTransferModel represents the result of CancelWithdrawal().

type CancelWithdrawalResultModel

type CancelWithdrawalResultModel struct {
	CancelledWithdrawIds []string `json:"cancelledWithdrawIds"`
}

CancelWithdrawalResultModel represents the result of CancelWithdrawal().

type ContractsModel

type ContractsModel struct {
	BaseCurrency       string  `json:"baseCurrency"`
	FairMethod         string  `json:"fairMethod"`
	FundingBaseSymbol  string  `json:"fundingBaseSymbol"`
	FundingQuoteSymbol string  `json:"fundingQuoteSymbol"`
	FundingRateSymbol  string  `json:"fundingRateSymbol"`
	IndexSymbol        string  `json:"indexSymbol"`
	IsDeleverage       bool    `json:"isDeleverage"`
	InitialMargin      string  `json:"baseCurrency"`
	IsInverse          bool    `json:"isInverse"`
	IsQuanto           bool    `json:"isQuanto"`
	LotSize            string  `json:"lotSize"`
	MaintainMargin     string  `json:"maintainMargin"`
	MakerFeeRate       string  `json:"makerFeeRate"`
	MakerFixFee        string  `json:"makerFixFee"`
	MarkMethod         string  `json:"markMethod"`
	MaxOrderQty        string  `json:"maxOrderQty"`
	MaxPrice           string  `json:"maxPrice"`
	MaxRiskLimit       string  `json:"maxRiskLimit"`
	MinRiskLimit       string  `json:"minRiskLimit"`
	Multiplier         string  `json:"multiplier"`
	QuoteCurrency      string  `json:"quoteCurrency"`
	RiskStep           string  `json:"riskStep"`
	RootSymbol         string  `json:"rootSymbol"`
	Status             string  `json:"status"`
	Symbol             string  `json:"symbol"`
	TakerFeeRate       string  `json:"takerFeeRate"`
	TakerFixFee        string  `json:"takerFixFee"`
	TickSize           string  `json:"tickSize"`
	MaxLeverage        float32 `json:"maxLeverage"`
}

A ContractsModel is the struct.

type CreateOrderResultModel

type CreateOrderResultModel struct {
	OrderId string `json:"orderId"`
}

A CreateOrderResultModel represents the result of CreateOrder().

type DepositAddressModel

type DepositAddressModel struct {
	Address string `json:"address"`
	Memo    string `json:"memo"`
}

A DepositAddressModel represents a deposit address of currency for deposit.

type DepositAddressesModel

type DepositAddressesModel []*DepositAddressModel

A DepositAddressesModel is the set of *DepositAddressModel.

type DepositModel

type DepositModel struct {
	Currency   string `json:"currency"`
	Status     string `json:"status"`
	Address    string `json:"address"`
	IsInner    bool   `json:"isInner"`
	Amount     string `json:"amount"`
	Fee        string `json:"fee"`
	WalletTxId string `json:"walletTxId"`
	CreatedAt  int64  `json:"createdAt"`
}

A DepositModel represents a deposit record.

type DepositsModel

type DepositsModel []*DepositModel

A DepositsModel represents a deposit list.

type FillModel

type FillModel struct {
	Symbol         string  `json:"symbol"`
	TradeId        string  `json:"tradeId"`
	OrderId        string  `json:"orderId"`
	Side           string  `json:"side"`
	Liquidity      string  `json:"liquidity"`
	Price          string  `json:"price"`
	Size           float64 `json:"size"`
	Value          string  `json:"value"`
	FeeRate        string  `json:"feeRate"`
	FixFee         string  `json:"fixFee"`
	FeeCurrency    string  `json:"feeCurrency"`
	Stop           string  `json:"stop"`
	Fee            string  `json:"fee"`
	OrderType      string  `json:"orderType"`
	TradeType      string  `json:"tradeType"`
	CreatedAt      int64   `json:"createdAt"`
	SettleCurrency string  `json:"settleCurrency"`
	TradeTime      int64   `json:"tradeTime"`
}

A FillModel represents the structure of fill.

type FillsModel

type FillsModel []*FillModel

A FillsModel is the set of *FillModel.

type FundingListModel

type FundingListModel struct {
	HasMore  bool            `json:"hasMore"`
	DataList []*FundingModel `json:"dataList"` // delay parsing
}

A FundingListModel is the set of *FundingModel.

type FundingModel

type FundingModel struct {
	Id             int64   `json:"id"`
	Symbol         string  `json:"symbol"`
	TimePoint      int64   `json:"timePoint"`
	FundingRate    float64 `json:"fundingRate"`
	MarkPrice      float64 `json:"markPrice"`
	PositionQty    float32 `json:"positionQty"`
	PositionCost   float64 `json:"positionCost"`
	Funding        float64 `json:"funding"`
	SettleCurrency string  `json:"settleCurrency"`
}

A FundingModel represents a funding record.

type FundingRateModel

type FundingRateModel struct {
	Symbol         string  `json:"symbol"`
	Granularity    int64   `json:"granularity"`
	TimePoint      int64   `json:"timePoint"`
	Value          float32 `json:"value"`
	PredictedValue float32 `json:"predictedValue"`
}

A FundingRateModel is the struct.

type IndexModel

type IndexModel struct {
	Symbol          string          `json:"symbol"`
	Granularity     int             `json:"granularity"`
	TimePoint       int64           `json:"timePoint"`
	Value           float32         `json:"value"`
	DecomposionList [][]interface{} `json:"decomposionList"`
}

IndexModel is the struct.

type IndexQueryModel

type IndexQueryModel struct {
	HasMore  bool          `json:"hasMore"`
	DataList []*IndexModel `json:"dataList"` // delay parsing
}

A IndexQueryModel is the set of *IndexModel.

type InterestModel

type InterestModel struct {
	Symbol      string  `json:"symbol"`
	Granularity int     `json:"granularity"`
	TimePoint   int64   `json:"timePoint"`
	Value       float32 `json:"value"`
}

InterestModel is the struct.

type InterestsModel

type InterestsModel struct {
	HasMore  bool             `json:"hasMore"`
	DataList []*InterestModel `json:"dataList"` // delay parsing
}

InterestsModel is the set of *InterestModel.

type KcSigner

type KcSigner struct {
	Sha256Signer
	// contains filtered or unexported fields
}

KcSigner is the implement of Signer for kumex.

func NewKcSigner

func NewKcSigner(key, secret, passPhrase string) *KcSigner

NewKcSigner creates a instance of KcSigner.

func (*KcSigner) Headers

func (ks *KcSigner) Headers(plain string) map[string]string

Headers returns a map of signature header.

func (*KcSigner) Sign

func (ks *KcSigner) Sign(plain []byte) []byte

Sign makes a signature by sha256 with `apiKey` `apiSecret` `apiPassPhrase`.

type Level2MessageQueryListModel

type Level2MessageQueryListModel []*Level2MessageQueryModel

Level2MessageQueryListModel the set of *Level2MessageQueryModel.

type Level2MessageQueryModel

type Level2MessageQueryModel struct {
	Symbol   string `json:"symbol"`
	Sequence int    `json:"sequence"`
	Change   string `json:"change"`
}

Level2MessageQueryModel represents level2 ticker message.

type Level2SnapshotModel

type Level2SnapshotModel struct {
	Symbol   string      `json:"symbol"`
	Sequence int         `json:"sequence"`
	Asks     [][]float32 `json:"asks"`
	Bids     [][]float32 `json:"bids"`
}

Level2SnapshotModel represents level2 ticker.

type Level3MessageQueryListModel

type Level3MessageQueryListModel []*Level3MessageQueryModel

Level3MessageQueryListModel is the set of *Level3MessageQueryModel

type Level3MessageQueryModel

type Level3MessageQueryModel struct {
	Symbol    string `json:"symbol"`
	Sequence  int    `json:"sequence"`
	Side      string `json:"side"`
	OrderTime int64  `json:"orderTime"`
	Size      int    `json:"size"`
	OrderId   string `json:"orderId"`
	Price     string `json:"price"`
	Type      string `json:"type"`
	ClientOid string `json:"clientOid"`
	Ts        int64  `json:"ts"`
}

Level3MessageQueryModel represents level3 ticker message.

type Level3SnapshotModel

type Level3SnapshotModel struct {
	Symbol   string          `json:"symbol"`
	Sequence int             `json:"sequence"`
	Asks     [][]interface{} `json:"asks"`
	Bids     [][]interface{} `json:"bids"`
}

Level3SnapshotModel represents level3 ticker message.

type MarkPriceModel

type MarkPriceModel struct {
	Symbol      string  `json:"symbol"`
	Granularity float32 `json:"granularity"`
	TimePoint   int64   `json:"timePoint"`
	Value       float32 `json:"value"`
	IndexPrice  float32 `json:"indexPrice"`
}

A MarkPriceModel is the struct.

type OpenOrderStatisticsModel

type OpenOrderStatisticsModel struct {
	OpenOrderBuySize  int32  `json:"openOrderBuySize"`
	OpenOrderSellSize int32  `json:"openOrderSellSize"`
	OpenOrderBuyCost  string `json:"openOrderBuyCost"`
	OpenOrderSellCost string `json:"openOrderSellCost"`
	SettleCurrency    string `json:"settleCurrency"`
}

A OpenOrderStatisticsModel represents the struct of fill.

type OrderModel

type OrderModel struct {
	Id             string `json:"id"`
	Symbol         string `json:"symbol"`
	Type           string `json:"type"`
	Side           string `json:"side"`
	Price          string `json:"price"`
	Size           int64  `json:"size"`
	Value          string `json:"value"`
	DealValue      string `json:"dealValue"`
	DealSize       int64  `json:"dealSize"`
	Stp            string `json:"stp"`
	Stop           string `json:"stop"`
	StopPriceType  string `json:"stopPriceType"`
	StopTriggered  bool   `json:"stopTriggered"`
	StopPrice      string `json:"stopPrice"`
	TimeInForce    string `json:"timeInForce"`
	PostOnly       bool   `json:"postOnly"`
	Hidden         bool   `json:"hidden"`
	IceBerg        bool   `json:"iceberg"`
	VisibleSize    string `json:"visibleSize"`
	Leverage       string `json:"leverage"`
	ForceHold      bool   `json:"forceHold"`
	CloseOrder     bool   `json:"closeOrder"`
	CloseOnly      bool   `json:"closeOnly"`
	ClientOid      string `json:"clientOid"`
	Remark         string `json:"remark"`
	IsActive       bool   `json:"isActive"`
	CancelExist    bool   `json:"cancelExist"`
	CreatedAt      int64  `json:"createdAt"`
	UpdatedAt      int64  `json:"updatedAt"`
	SettleCurrency string `json:"settleCurrency"`
	Status         string `json:"status"`
}

An OrderModel represents an order.

type OrdersModel

type OrdersModel []*OrderModel

A OrdersModel is the set of *OrderModel.

type PaginationModel

type PaginationModel struct {
	CurrentPage int64           `json:"currentPage"`
	PageSize    int64           `json:"pageSize"`
	TotalNum    int64           `json:"totalNum"`
	TotalPage   int64           `json:"totalPage"`
	RawItems    json.RawMessage `json:"items"` // delay parsing
}

A PaginationModel represents the pagination in a response.

func (*PaginationModel) ReadItems

func (p *PaginationModel) ReadItems(v interface{}) error

ReadItems read the `items` into v.

type PaginationParam

type PaginationParam struct {
	CurrentPage int64
	PageSize    int64
}

A PaginationParam represents the pagination parameters `currentPage` `pageSize` in a request .

func (*PaginationParam) ReadParam

func (p *PaginationParam) ReadParam(params map[string]string)

ReadParam read pagination parameters into params.

type PositionModel

type PositionModel struct {
	Id                string `json:"id"`
	Symbol            string `json:"symbol"`
	AutoDeposit       bool   `json:"autoDeposit"`
	MaintMarginReq    string `json:"maintMarginReq"`
	RiskLimit         string `json:"riskLimit"`
	RealLeverage      string `json:"realLeverage"`
	CrossMode         bool   `json:"crossMode"`
	DelevPercentage   string `json:"delevPercentage"`
	OpeningTimestamp  string `json:"openingTimestamp"`
	CurrentTimestamp  string `json:"currentTimestamp"`
	CurrentQty        string `json:"currentQty"`
	CurrentCost       string `json:"currentCost"`
	CurrentComm       string `json:"currentComm"`
	UnrealisedCost    string `json:"unrealisedCost"`
	RealisedGrossCost string `json:"realisedGrossCost"`
	RealisedCost      string `json:"realisedCost"`
	IsOpen            bool   `json:"isOpen"`
	MarkPrice         string `json:"markPrice"`
	MarkValue         string `json:"markValue"`
	PosCost           string `json:"posCost"`
	PosCross          string `json:"posCross"`
	PosInit           string `json:"posInit"`
	PosComm           string `json:"posComm"`
	PosLoss           string `json:"posLoss"`
	PosMargin         string `json:"posMargin"`
	PosMaint          string `json:"posMaint"`
	MaintMargin       string `json:"maintMargin"`
	RealisedGrossPnl  string `json:"realisedGrossPnl"`
	RealisedPnl       string `json:"realisedPnl"`
	UnrealisedPnl     string `json:"unrealisedPnl"`
	UnrealisedPnlPcnt string `json:"unrealisedPnlPcnt"`
	UnrealisedRoePcnt string `json:"unrealisedRoePcnt"`
	AvgEntryPrice     string `json:"avgEntryPrice"`
	LiquidationPrice  string `json:"liquidationPrice"`
	BankruptPrice     string `json:"bankruptPrice"`
	SettleCurrency    string `json:"settleCurrency"`
}

A PositionModel represents a position info.

type PremiumModel

type PremiumModel struct {
	Symbol      string `json:"symbol"`
	Granularity string `json:"granularity"`
	TimePoint   string `json:"timePoint"`
	Value       string `json:"value"`
}

A PremiumModel is the struct.

type PremiumsModel

type PremiumsModel struct {
	HasMore  bool            `json:"hasMore"`
	DataList []*PremiumModel `json:"dataList"` // delay parsing
}

A PremiumsModel is the set of *PremiumModel.

type Request

type Request struct {
	BaseURI       string
	Method        string
	Path          string
	Query         url.Values
	Body          []byte
	Header        http.Header
	Timeout       time.Duration
	SkipVerifyTls bool
	// contains filtered or unexported fields
}

A Request represents a HTTP request.

func NewRequest

func NewRequest(method, path string, params map[string]string) *Request

NewRequest creates a instance of Request.

func (*Request) FullURL

func (r *Request) FullURL() string

FullURL returns the full url.

func (*Request) HttpRequest

func (r *Request) HttpRequest() (*http.Request, error)

HttpRequest creates a instance of *http.Request.

func (*Request) RequestURI

func (r *Request) RequestURI() string

RequestURI returns the request uri.

type Requester

type Requester interface {
	Request(request *Request, timeout time.Duration) (*Response, error)
}

Requester contains Request() method, can launch a http request.

type Response

type Response struct {
	*http.Response
	// contains filtered or unexported fields
}

A Response represents a HTTP response.

func (*Response) ReadBody

func (r *Response) ReadBody() ([]byte, error)

ReadBody read the response data, then return it.

func (*Response) ReadJsonBody

func (r *Response) ReadJsonBody(v interface{}) error

ReadJsonBody read the response data as JSON into v.

type Sha256Signer

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

Sha256Signer is the sha256 Signer.

func (*Sha256Signer) Sign

func (ss *Sha256Signer) Sign(plain []byte) []byte

Sign makes a signature by sha256.

type Signer

type Signer interface {
	Sign(plain []byte) []byte
}

Signer interface contains Sign() method.

type TickerLevel1Model

type TickerLevel1Model struct {
	Sequence     int    `json:"sequence"`
	Symbol       string `json:"symbol"`
	Side         string `json:"side"`
	Size         int    `json:"size"`
	Price        string `json:"price"`
	BestBidSize  int    `json:"bestBidSize"`
	BestBidPrice string `json:"bestBidPrice"`
	BestAskSize  int    `json:"bestAskSize"`
	BestAskPrice string `json:"bestAskPrice"`
	TradeId      string `json:"tradeId"`
	Ts           int64  `json:"ts"`
}

A TickerLevel1Model represents ticker include only the inside (i.e. best) bid and ask data, last price and last trade size.

type TradeHistoryModel

type TradeHistoryModel struct {
	Sequence     int    `json:"sequence"`
	TradeId      string `json:"tradeId"`
	TakerOrderId string `json:"takerOrderId"`
	MakerOrderId string `json:"makerOrderId"`
	Price        string `json:"price"`
	Size         int    `json:"size"`
	Side         string `json:"side"`
	Time         int64  `json:"t"`
}

TradeHistoryModel represents a the latest trades for a symbol.

type TradesHistoryModel

type TradesHistoryModel []*TradeHistoryModel

TradesHistoryModel is the set of *TradeHistoryModel.

type TransactionHistoryListModel

type TransactionHistoryListModel []*TransactionHistoryModel

An TransactionHistoryListModel the set of *TransactionHistoryModel.

type TransactionHistoryModel

type TransactionHistoryModel struct {
	Time          string `json:"time"`
	Type          string `json:"type"`
	Amount        string `json:"amount"`
	Fee           string `json:"fee"`
	AccountEquity string `json:"accountEquity"`
	Status        string `json:"status"`
	Remarks       string `json:"remark"`
	Offset        string `json:"offset"`
	Currency      string `json:"currency"`
}

A TransactionHistoryModel represents a sub-account user.

type TransferModel

type TransferModel struct {
	ApplyId   string `json:"applyId"`
	Currency  string `json:"currency"`
	Status    string `json:"status"`
	Amount    string `json:"amount"`
	Reason    string `json:"reason"`
	Offset    int64  `json:"offset"`
	CreatedAt int64  `json:"createdAt"`
}

A TransferModel represents a transfer record.

type TransferOutModel

type TransferOutModel struct {
	ApplyId string `json:"applyId"`
}

A TransferOutModel represents a transfer out record.

type TransferOutV2Model added in v1.0.3

type TransferOutV2Model struct {
	ApplyId string `json:"applyId"`
}

A TransferOutModel represents a transfer out record.

type TransfersModel

type TransfersModel []*TransferModel

A TransfersModel represents a transfer list.

type WebSocketClient

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

A WebSocketClient represents a connection to WebSocket server.

func (*WebSocketClient) Connect

func (wc *WebSocketClient) Connect() (<-chan *WebSocketDownstreamMessage, <-chan error, error)

Connect connects the WebSocket server.

func (*WebSocketClient) Stop

func (wc *WebSocketClient) Stop()

Stop stops subscribing the specified channel, all goroutines quit.

func (*WebSocketClient) Subscribe

func (wc *WebSocketClient) Subscribe(channels ...*WebSocketSubscribeMessage) error

Subscribe subscribes the specified channel.

func (*WebSocketClient) Unsubscribe

func (wc *WebSocketClient) Unsubscribe(channels ...*WebSocketUnsubscribeMessage) error

Unsubscribe unsubscribes the specified channel.

type WebSocketDownstreamMessage

type WebSocketDownstreamMessage struct {
	*WebSocketMessage
	Sn      string          `json:"sn"`
	Topic   string          `json:"topic"`
	Subject string          `json:"subject"`
	RawData json.RawMessage `json:"data"`
}

A WebSocketDownstreamMessage represents a message from the WebSocket server to client.

func (*WebSocketDownstreamMessage) ReadData

func (m *WebSocketDownstreamMessage) ReadData(v interface{}) error

ReadData read the data in channel.

type WebSocketMessage

type WebSocketMessage struct {
	Id   string `json:"id"`
	Type string `json:"type"`
}

A WebSocketMessage represents a message between the WebSocket client and server.

func NewPingMessage

func NewPingMessage() *WebSocketMessage

NewPingMessage creates a ping message instance.

type WebSocketServerModel

type WebSocketServerModel struct {
	PingInterval int64  `json:"pingInterval"`
	Endpoint     string `json:"endpoint"`
	Protocol     string `json:"protocol"`
	Encrypt      bool   `json:"encrypt"`
	PingTimeout  int64  `json:"pingTimeout"`
}

A WebSocketServerModel contains some servers for WebSocket feed.

type WebSocketServersModel

type WebSocketServersModel []*WebSocketServerModel

A WebSocketServersModel is the set of *WebSocketServerModel.

func (WebSocketServersModel) RandomServer

func (s WebSocketServersModel) RandomServer() (*WebSocketServerModel, error)

RandomServer returns a server randomly.

type WebSocketSubscribeMessage

type WebSocketSubscribeMessage struct {
	*WebSocketMessage
	Topic          string `json:"topic"`
	PrivateChannel bool   `json:"privateChannel"`
	Response       bool   `json:"response"`
}

A WebSocketSubscribeMessage represents a message to subscribe the public/private channel.

func NewSubscribeMessage

func NewSubscribeMessage(topic string, privateChannel bool) *WebSocketSubscribeMessage

NewSubscribeMessage creates a subscribe message instance.

type WebSocketTokenModel

type WebSocketTokenModel struct {
	Token             string                `json:"token"`
	Servers           WebSocketServersModel `json:"instanceServers"`
	AcceptUserMessage bool                  `json:"acceptUserMessage"`
}

A WebSocketTokenModel contains a token and some servers for WebSocket feed.

type WebSocketUnsubscribeMessage

type WebSocketUnsubscribeMessage WebSocketSubscribeMessage

A WebSocketUnsubscribeMessage represents a message to unsubscribe the public/private channel.

func NewUnsubscribeMessage

func NewUnsubscribeMessage(topic string, privateChannel bool) *WebSocketUnsubscribeMessage

NewUnsubscribeMessage creates a unsubscribe message instance.

type WithdrawalModel

type WithdrawalModel struct {
	WithdrawalId string `json:"withdrawalId"`
	Currency     string `json:"currency"`
	Status       string `json:"status"`
	Address      string `json:"address"`
	IsInner      bool   `json:"isInner"`
	Amount       string `json:"amount"`
	Fee          string `json:"fee"`
	WalletTxId   string `json:"walletTxId"`
	CreatedAt    int64  `json:"createdAt"`
	Remark       string `json:"remark"`
	Reason       string `json:"reason"`
}

A WithdrawalModel represents a withdrawal.

type WithdrawalQuotasModel

type WithdrawalQuotasModel struct {
	Currency            string  `json:"currency"`
	LimitAmount         float32 `json:"limitAmount"`
	UsedAmount          float32 `json:"usedAmount"`
	RemainAmount        float32 `json:"remainAmount"`
	AvailableAmount     float32 `json:"availableAmount"`
	WithdrawMinSize     float32 `json:"withdrawMinSize"`
	InnerWithdrawMinFee float32 `json:"innerWithdrawMinFee"`
	WithdrawMinFee      float32 `json:"withdrawMinFee"`
	IsWithdrawEnabled   bool    `json:"isWithdrawEnabled"`
	Precision           uint8   `json:"precision"`
}

A WithdrawalQuotasModel represents the quotas for a currency.

type WithdrawalsModel

type WithdrawalsModel []*WithdrawalModel

A WithdrawalsModel is the set of *WithdrawalModel.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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