kumex

package module
v1.1.4 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2024 License: MIT Imports: 26 Imported by: 2

README

Go SDK for KuMex API

The detailed document https://docs.kucoin.com/futures, 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/kucoin-futures-go-sdk

Usage

Choose environment
Environment BaseUri
Production https://api-futures.kucoin.com(DEFAULT) https://api-futures.kucoin.cc
Sandbox https://api-sandbox-futures.kucoin.com
Create ApiService
Note

To reinforce the security of the API, KuCoin upgraded the API key to version 2.0, the validation logic has also been changed. It is recommended to create(https://www.kucoin.com/account/api) and update your API key to version 2.0. The API key of version 1.0 will be still valid until May 1, 2021.

// API key version 2.0
s :=  kucoin.NewApiService( 
	// kucoin.ApiBaseURIOption("https://api.kucoin.com"), 
	kucoin.ApiKeyOption("key"),
	kucoin.ApiSecretOption("secret"),
	kucoin.ApiPassPhraseOption("passphrase"),
	kucoin.ApiKeyVersionOption(ApiKeyVersionV2)
)

// API key version 1.0
s := kucoin.NewApiService( 
	// kucoin.ApiBaseURIOption("https://api.kucoin.com"), 
	kucoin.ApiKeyOption("key"),
	kucoin.ApiSecretOption("secret"),
	kucoin.ApiPassPhraseOption("passphrase"), 
)

// Or add these options into the environmental variable
// Bash: 
// export API_BASE_URI=https://api-futures.kucoin.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:XBTUSDTM", false)
ch2 := kumex.NewSubscribeMessage("/contractMarket/ticker:XBTUSDTM", false)
uch := kumex.NewUnsubscribeMessage("/contractMarket/ticker:XBTUSDTM", 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 XBTUSDTM")
            if err = c.Unsubscribe(uch); err != nil {
                log.Printf("Error: %s", err.Error())
                // Handle error
                return
            }
        }
        if i == 10 {
            log.Println("Subscribe XBTUSDTM")
            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.kucoin.com/futures/#get-account-overview
ApiService.TransactionHistory() YES https://docs.kucoin.com/futures/#get-transaction-history
Deposit
API Authentication Description
ApiService.DepositAddresses() YES https://docs.kucoin.com/futures/#get-deposit-address
ApiService.Deposits() YES https://docs.kucoin.com/futures/#get-deposit-list
Withdrawal
API Authentication Description
ApiService.WithdrawalQuotas() YES https://docs.kucoin.com/futures/#get-withdrawal-quotas
ApiService.ApplyWithdrawal() YES https://docs.kucoin.com/futures/#apply-withdraw
ApiService.Withdrawals() YES https://docs.kucoin.com/futures/#get-withdrawals-list
ApiService.CancelWithdrawal() YES https://docs.kucoin.com/futures/#cancel-withdrawal
Transfer
API Authentication Description
ApiService.TransferOut() YES https://docs.kucoin.com/futures/#transfer-out
ApiService.TransferOutV2() YES https://docs.kucoin.com/futures/#transfer-funds-to-kucoin-main-account
ApiService.TransferList() YES https://docs.kucoin.com/futures/#get-transfer-list
ApiService.CancelTransfer() YES https://docs.kucoin.com/futures/#cancel-transfer
Fill
API Authentication Description
ApiService.Fills() YES https://docs.kucoin.com/futures/#list-fills
ApiService.RecentFills() YES https://docs.kucoin.com/futures/#recent-fills
ApiService.openOrderStatistics() YES https://docs.kucoin.com/futures/#open-order-statistics
Order
API Authentication Description
ApiService.CreateOrder() YES https://docs.kucoin.com/futures/#place-a-new-order
ApiService.CancelOrder() YES https://docs.kucoin.com/futures/#cancel-an-order
ApiService.CancelOrders() YES https://docs.kucoin.com/futures/#cancel-all-orders
ApiService.StopOrders() YES https://docs.kucoin.com/futures/#get-untriggered-stop-order-list
ApiService.Orders() YES https://docs.kucoin.com/futures/#list-orders
ApiService.Order() YES https://docs.kucoin.com/futures/#get-an-order
ApiService.RecentOrders() YES https://docs.kucoin.com/futures/#recent-orders
Market
API Authentication Description
ApiService.Ticker() NO https://docs.kucoin.com/futures/#get-real-time-ticker
ApiService.Level2Snapshot() NO https://docs.kucoin.com/futures/#get-full-order-book-level-2
ApiService.Level2MessageQuery()() NO https://docs.kucoin.com/futures/#level-2-pulling-messages
ApiService.Level3Snapshot() NO https://docs.kucoin.com/futures/#get-full-order-book-level-3
ApiService.Level3MessageQuery() NO https://docs.kucoin.com/futures/#level-3-pulling-messages
ApiService.TradeHistory() NO https://docs.kucoin.com/futures/#transaction-history
ApiService.InterestQuery() NO https://docs.kucoin.com/futures/#get-interest-rate-list
ApiService.IndexQuery() NO https://docs.kucoin.com/futures/#get-index-list
ApiService.MarkPrice() NO https://docs.kucoin.com/futures/#get-current-mark-price
ApiService.PremiumQuery() NO https://docs.kucoin.com/futures/#get-premium-index
ApiService.FundingRate() NO https://docs.kucoin.com/futures/#get-current-funding-rate
Symbol
API Authentication Description
ApiService.ActiveContracts() NO https://docs.kucoin.com/futures/#get-open-contract-list
ApiService.Contracts() NO https://docs.kucoin.com/futures/#get-order-info-of-the-contract
WebSocket Feed
API Authentication Description
ApiService.WebSocketPublicToken() NO https://docs.kucoin.com/futures/#apply-connect-token
ApiService.WebSocketPrivateToken() YES https://docs.kucoin.com/futures/#apply-connect-token
ApiService.NewWebSocketClient() - https://docs.kucoin.com/futures/#websocket-feed
Time
API Authentication Description
ApiService.ServerTime() NO https://docs.kucoin.com/futures/#server-time

Run tests

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

# 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.kucoin.com/futures

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 ApiKeyVersionV1 = "1"

ApiKeyVersionV1 is v1 api key version

View Source
const ApiKeyVersionV2 = "2"

ApiKeyVersionV2 is v2 api key version

View Source
const (
	ApiSuccess = "200000"
)

The predefined API codes

View Source
const ProductionApiBaseURI = "https://api-futures.kucoin.com"

ProductionApiBaseURI is api base uri for production.

Variables

View Source
var (
	// Version is SDK version.
	Version = "1.0.5"
	// 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 AllTickersModel added in v1.1.2

type AllTickersModel []TickerItem

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) AllTickers added in v1.1.2

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

AllTickers Get Latest Ticker for All Contracts

func (*ApiService) ApplyWithdrawal

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

ApplyWithdrawal applies a withdrawal. Deprecated

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) CancelOrderClientId added in v1.1.0

func (as *ApiService) CancelOrderClientId(clientOid, symbol string) (*ApiResponse, error)

CancelOrderClientId cancel order with order client id

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

func (*ApiService) CancelWithdrawal

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

CancelWithdrawal cancels a withdrawal by withdrawalId. Deprecated

func (*ApiService) ChangeCrossUserLeverage added in v1.1.3

func (as *ApiService) ChangeCrossUserLeverage(symbol string, leverage string) (*ApiResponse, error)

ChangeCrossUserLeverage modify the current symbol’s cross-margin leverage multiple

func (*ApiService) ChangeMarginMode added in v1.1.3

func (as *ApiService) ChangeMarginMode(symbol string, marginMode string) (*ApiResponse, error)

ChangeMarginMode modify the margin mode of the current symbol

func (*ApiService) ChangeRiskLimitLevel

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

ContractsRiskLimit adjust contract risk limit level

func (*ApiService) Contracts

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

Contracts Get Order Info. of the Contract.

func (*ApiService) ContractsRiskLimitLevel

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

ContractsRiskLimitLevel obtain information about risk limit level of a specific contract

func (*ApiService) CreateMultiOrders added in v1.1.1

func (as *ApiService) CreateMultiOrders(p []*CreateOrderReq) (*ApiResponse, error)

CreateMultiOrders places multi order.

func (*ApiService) CreateOrder

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

CreateOrder places a new order.

func (*ApiService) CreateOrderTest added in v1.1.1

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

CreateOrderTest places a new order.

func (*ApiService) CreateSTOrder added in v1.1.2

func (as *ApiService) CreateSTOrder(p *STOrderReq) (*ApiResponse, error)

CreateSTOrder Place take profit and stop loss order

func (*ApiService) CreateSubApiKey added in v1.0.7

func (as *ApiService) CreateSubApiKey(p map[string]string) (*ApiResponse, error)

CreateSubApiKey This endpoint can be used to create Futures APIs for sub-accounts.

func (*ApiService) DeleteSubApiKey added in v1.0.7

func (as *ApiService) DeleteSubApiKey(apiKey, passphrase, subName string) (*ApiResponse, error)

DeleteSubApiKey This endpoint can be used to delete sub-account Futures APIs.

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

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

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) FundingRatesTimeRange added in v1.1.0

func (as *ApiService) FundingRatesTimeRange(symbol, from, to string) (*ApiResponse, error)

FundingRatesTimeRange Get Funding rates info .

func (*ApiService) GetCrossUserLeverage added in v1.1.3

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

GetCrossUserLeverage query the current symbol’s cross-margin leverage multiple

func (*ApiService) GetMarginMode added in v1.1.3

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

GetMarginMode can query the margin mode of the current symbol.

func (*ApiService) GetMaxOpenSize added in v1.1.2

func (as *ApiService) GetMaxOpenSize(r *GetMaxOpenSizeReq) (*ApiResponse, error)

GetMaxOpenSize Get Maximum Open Position Size

func (*ApiService) GetPositionsHistoryV1 added in v1.1.1

func (as *ApiService) GetPositionsHistoryV1(r *GetPositionsHistoryV1Req) (*ApiResponse, error)

GetPositionsHistoryV1 This interface can query position history information records

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

func (as *ApiService) KLines(symbol, granularity string, startAt, endAt int64) (*ApiResponse, error)

Data are returned in grouped buckets based on requested type. Parameter #2 granularity is the type of granularity patterns(minute). Parameter #3 #4 startAt, endAt is millisecond.

func (*ApiService) Level2MessageQuery

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

Level2MessageQuery Level 2 Pulling Messages. Deprecated

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

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

Level3SnapshotV2 Get Full Order Book - Level 3.

func (*ApiService) MarkPrice

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

MarkPrice Get Current Mark Price

func (*ApiService) MaxWithdrawMarginV1 added in v1.1.1

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

MaxWithdrawMarginV1 This interface can query the maximum amount of margin that the current position supports withdrawal.

func (*ApiService) ModifySubApiKey added in v1.0.7

func (as *ApiService) ModifySubApiKey(p map[string]string) (*ApiResponse, error)

ModifySubApiKey TThis endpoint can be used to modify sub-account Futures APIs.

func (*ApiService) NewWebSocketClient

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

NewWebSocketClient creates an instance of WebSocketClient.

func (*ApiService) ObtainStopOrders added in v1.0.7

func (as *ApiService) ObtainStopOrders(symbol string, page *PaginationParam) (*ApiResponse, error)

ObtainStopOrders represents an order.

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

func (as *ApiService) OrderByClientOid(clientOid string) (*ApiResponse, error)

Order returns a single order by client Oid.

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(currency string) (*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(symbol string) (*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) ServiceStatus

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

ServiceStatus returns the service status.

func (*ApiService) StopOrders

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

StopOrders represents an order.

func (*ApiService) SubAccountsBalance added in v1.0.8

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

SubAccountsBalance Get All Sub-Accounts Balance - Futures

func (*ApiService) SubApiKeys added in v1.0.7

func (as *ApiService) SubApiKeys(apiKey, subName string) (*ApiResponse, error)

SubApiKeys This endpoint can be used to obtain a list of Futures APIs pertaining to a sub-account.

func (*ApiService) Ticker

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

Ticker Get Real-Time Ticker.

func (*ApiService) TradeFeesV1 added in v1.1.1

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

TradeFeesV1 This interface is for the actual fee rate of the trading pair. The fee rate of your sub-account is the same as that of the master account.

func (*ApiService) TradeHistory

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

TradeHistory returns a list the latest trades for a symbol.

func (*ApiService) TradeStatistics added in v1.1.0

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

TradeStatistics Get 24h trade statistics.

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) TransferIn added in v1.0.7

func (as *ApiService) TransferIn(currency, payAccountType, amount string) (*ApiResponse, error)

TransferIn The amount to be transferred will be deducted from the KuCoin Futures Account. Please ensure that you have sufficient funds in your KuCoin Futures Account, or the transfer will fail. Once the transfer arrives your KuCoin-Main Account, the endpoint will respond and return the applyId. This ID could be used to cancel the transfer request.

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

func (*ApiService) TransferOutV2

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

TransferOutV2 Transfer Funds to KuCoin-Main Account.

func (*ApiService) TransferOutV3 added in v1.0.7

func (as *ApiService) TransferOutV3(currency, recAccountType, amount string) (*ApiResponse, error)

TransferOutV3 The amount to be transferred will be deducted from the KuCoin Futures Account. Please ensure that you have sufficient funds in your KuCoin Futures Account, or the transfer will fail. Once the transfer arrives your KuCoin-Main Account, the endpoint will respond and return the applyId. This ID could be used to cancel the transfer request.

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) WithdrawMarginV1 added in v1.1.1

func (as *ApiService) WithdrawMarginV1(r *WithdrawMarginV1Req) (*ApiResponse, error)

WithdrawMarginV1 Remove Margin Manually

func (*ApiService) WithdrawalQuotas

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

WithdrawalQuotas returns the quotas of withdrawal. Deprecated

func (*ApiService) Withdrawals

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

Withdrawals returns a list of withdrawals. Deprecated

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 ApiKeyVersionOption

func ApiKeyVersionOption(apiKeyVersion string) ApiServiceOption

ApiKeyVersionOption creates a instance of ApiServiceOption about apiKeyVersion.

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 CancelOrderClientIdResultModel added in v1.1.1

type CancelOrderClientIdResultModel struct {
	ClientOid string `json:"clientOid"`
}

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"`
	InitialMargin      float32 `json:"initialMargin"`
	IsDeleverage       bool    `json:"isDeleverage"`
	IsInverse          bool    `json:"isInverse"`
	IsQuanto           bool    `json:"isQuanto"`
	LotSize            float32 `json:"lotSize"`
	MaintainMargin     float32 `json:"maintainMargin"`
	MakerFeeRate       float32 `json:"makerFeeRate"`
	MakerFixFee        float32 `json:"makerFixFee"`
	MarkMethod         string  `json:"markMethod"`
	MaxOrderQty        float32 `json:"maxOrderQty"`
	MaxPrice           float32 `json:"maxPrice"`
	MaxRiskLimit       float32 `json:"maxRiskLimit"`
	MinRiskLimit       float32 `json:"minRiskLimit"`
	Multiplier         float32 `json:"multiplier"`
	QuoteCurrency      string  `json:"quoteCurrency"`
	RiskStep           int     `json:"riskStep"`
	RootSymbol         string  `json:"rootSymbol"`
	Status             string  `json:"status"`
	Symbol             string  `json:"symbol"`
	TakerFeeRate       float32 `json:"takerFeeRate"`
	TakerFixFee        float32 `json:"takerFixFee"`
	TickSize           float32 `json:"tickSize"`
	Type               string  `json:"type"`
	MaxLeverage        float32 `json:"maxLeverage"`
	VolumeOf24h        float64 `json:"volumeOf24h"`
	TurnoverOf24h      float64 `json:"turnoverOf24h"`
	OpenInterest       string  `json:"openInterest"`
}

A ContractsModel is the struct.

type ContractsModels

type ContractsModels []*ContractsModel

type ContractsRiskLimitLevelModel

type ContractsRiskLimitLevelModel []*RiskLimitLevelModel

ContractRiskLimitLevelModel represents a Contract risk limit level info.

type CreateMultiOrdersRes added in v1.1.1

type CreateMultiOrdersRes []*CreateOrderRes

type CreateOrderReq added in v1.1.1

type CreateOrderReq struct {
	// BASE PARAMETERS
	ClientOid     string `json:"clientOid"`
	Side          string `json:"side"`
	Symbol        string `json:"symbol,omitempty"`
	Leverage      string `json:"leverage,omitempty"`
	Type          string `json:"type,omitempty"`
	Remark        string `json:"remark,omitempty"`
	Stop          string `json:"stop,omitempty"`
	StopPrice     string `json:"stopPrice,omitempty"`
	StopPriceType string `json:"stopPriceType,omitempty"`
	ReduceOnly    string `json:"reduceOnly,omitempty"`
	CloseOrder    string `json:"closeOrder,omitempty"`
	ForceHold     string `json:"forceHold,omitempty"`
	Stp           string `json:"stp,omitempty"`
	MarginMode    string `json:"marginMode,omitempty"` // Margin mode: ISOLATED, CROSS, default: ISOLATED

	// MARKET ORDER PARAMETERS
	Size string `json:"size,omitempty"`

	// LIMIT ORDER PARAMETERS
	Price       string `json:"price,omitempty"`
	TimeInForce string `json:"timeInForce,omitempty"`
	PostOnly    bool   `json:"postOnly,omitempty"`
	Hidden      bool   `json:"hidden,omitempty"`
	IceBerg     bool   `json:"iceberg,omitempty"`
	VisibleSize string `json:"visibleSize,omitempty"`
}

type CreateOrderRes added in v1.1.1

type CreateOrderRes struct {
	OrderId   string `json:"orderId"`
	ClientOid string `json:"clientOid"`
	Symbol    string `json:"symbol"`
}

type CreateOrderResultModel

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

A CreateOrderResultModel represents the result of CreateOrder().

type CreateSubApiKeyRes added in v1.0.7

type CreateSubApiKeyRes struct {
	SubName     string          `json:"subName"`
	Remark      string          `json:"remark"`
	ApiKey      string          `json:"apiKey"`
	Permission  string          `json:"permission"`
	IpWhitelist string          `json:"ipWhitelist"`
	CreatedAt   jsoniter.Number `json:"createdAt"`
	ApiSecret   string          `json:"apiSecret"`
	Passphrase  string          `json:"passphrase"`
}

type DeleteSubApiKeyRes added in v1.0.7

type DeleteSubApiKeyRes struct {
	ApiKey  string `json:"apiKey"`
	SubName string `json:"subName"`
}

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"`
	OpenFeePay     string  `json:"openFeePay"`
	CloseFeePay    string  `json:"closeFeePay"`
	MarginMode     string  `json:"marginMode"`
}

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 FundingTimeRangeRateModel added in v1.1.0

type FundingTimeRangeRateModel struct {
	Symbol      string  `json:"symbol"`
	TimePoint   float64 `json:"timePoint"`
	FundingRate float64 `json:"fundingRate"`
}

type FundingTimeRangeRatesModel added in v1.1.0

type FundingTimeRangeRatesModel []*FundingTimeRangeRateModel

type GetMaxOpenSizeReq added in v1.1.2

type GetMaxOpenSizeReq struct {
	Symbol   string `url:"symbol"`
	Price    string `url:"price"`
	Leverage string `url:"leverage"`
}

type GetMaxOpenSizeResp added in v1.1.2

type GetMaxOpenSizeResp struct {
	Symbol          string `json:"symbol"`
	MaxBuyOpenSize  int    `json:"maxBuyOpenSize"`
	MaxSellOpenSize int    `json:"leverage"`
}

type GetPositionsHistoryV1Req added in v1.1.1

type GetPositionsHistoryV1Req struct {
	Symbol string `url:"symbol,omitempty"`
	From   int64  `url:"from,omitempty"`
	To     int64  `url:"to,omitempty"`
	Limit  int    `url:"limit,omitempty"`
	PageID int    `url:"pageId,omitempty"`
}

type GetPositionsHistoryV1Resp added in v1.1.1

type GetPositionsHistoryV1Resp struct {
	CurrentPage int                    `json:"currentPage"`
	PageSize    int                    `json:"pageSize"`
	TotalNum    int                    `json:"totalNum"`
	TotalPage   int                    `json:"totalPage"`
	Items       []PositionsHistoryItem `json:"items"`
}

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 KLineModel

type KLineModel []interface{}

KLineModel represents the k lines for a symbol.

type KLinesModel

type KLinesModel []*KLineModel

A KLinesModel is the set of *KLineModel.

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 NewKcSignerV2

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

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

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

Level3SnapshotV2Model represents level3 ticker message.

type MarginModeModel added in v1.1.3

type MarginModeModel struct {
	Symbol     string `json:"symbol"`     //symbol of the contract
	MarginMode string `json:"marginMode"` //Margin mode: ISOLATED (isolated), CROSS (cross margin).
}

type MarginUserLeverage added in v1.1.3

type MarginUserLeverage struct {
	Symbol   string `json:"symbol"`   //symbol of the contract
	Leverage string `json:"leverage"` //Leverage multiple
}

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 ModifySubApiKeyRes added in v1.0.7

type ModifySubApiKeyRes struct {
	SubName     string `json:"subName"`
	Permission  string `json:"permission"`
	IpWhitelist string `json:"ipWhitelist"`
	ApiKey      string `json:"apiKey"`
}

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    int64  `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"`
	MarginMode     string `json:"marginMode"`
}

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    jsoniter.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 {
	UserId            string `json:"userId"`
	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"`
	MaintainMargin    string `json:"maintainMargin"`
	RiskLimitLevel    string `json:"riskLimitLevel"`
	MarginMode        string `json:"marginMode"`
	PositionSide      string `json:"positionSide"`
	Leverage          string `json:"leverage"`
	PosFunding        string `json:"posFunding"`
}

A PositionModel represents a position info.

type PositionsHistoryItem added in v1.1.1

type PositionsHistoryItem struct {
	CloseID           string   `json:"closeId"`
	PositionID        string   `json:"positionId"`
	UID               int64    `json:"uid"`
	UserID            string   `json:"userId"`
	Symbol            string   `json:"symbol"`
	SettleCurrency    string   `json:"settleCurrency"`
	Leverage          string   `json:"leverage"`
	Type              string   `json:"type"`
	Side              *string  `json:"side"`
	CloseSize         *float64 `json:"closeSize"`
	PNL               string   `json:"pnl"`
	RealisedGrossCost string   `json:"realisedGrossCost"`
	WithdrawPNL       string   `json:"withdrawPnl"`
	ROE               *float64 `json:"roe"`
	TradeFee          string   `json:"tradeFee"`
	FundingFee        string   `json:"fundingFee"`
	OpenTime          int64    `json:"openTime"`
	CloseTime         int64    `json:"closeTime"`
	OpenPrice         *float64 `json:"openPrice"`
	ClosePrice        *float64 `json:"closePrice"`
}

type PositionsModel added in v1.0.7

type PositionsModel []*PositionModel

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 interface{}) *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 RiskLimitLevelModel

type RiskLimitLevelModel struct {
	Symbol         string  `json:"symbol"`
	Level          int64   `json:"level"`
	MaxRiskLimit   int64   `json:"maxRiskLimit"`
	MinRiskLimit   int64   `json:"minRiskLimit"`
	MaxLeverage    int64   `json:"maxLeverage"`
	InitialMargin  float64 `json:"initialMargin"`
	MaintainMargin float64 `json:"maintainMargin"`
}

RiskLimitLevelModel represents a Contract risk limit level info.

type STOrderReq added in v1.1.2

type STOrderReq struct {
	ClientOid            string `json:"clientOid"`
	Side                 string `json:"side"`
	Symbol               string `json:"symbol"`
	Leverage             string `json:"leverage"`
	Type                 string `json:"type"`
	Remark               string `json:"remark"`
	TriggerStopUpPrice   string `json:"triggerStopUpPrice"`
	StopPriceType        string `json:"stopPriceType"`
	TriggerStopDownPrice string `json:"triggerStopDownPrice"`
	ReduceOnly           bool   `json:"reduceOnly"`
	CloseOrder           bool   `json:"closeOrder"`
	ForceHold            bool   `json:"forceHold"`
	Stp                  string `json:"stp"`
	Price                string `json:"price"`
	Size                 int    `json:"size"`
	TimeInForce          string `json:"timeInForce"`
	PostOnly             bool   `json:"postOnly"`
	Hidden               bool   `json:"hidden"`
	Iceberg              bool   `json:"iceberg"`
	VisibleSize          int    `json:"visibleSize"`
	MarginMode           string `json:"marginMode"`
}

type STOrderRes added in v1.1.2

type STOrderRes struct {
	OrderId   string `json:"orderId"`
	ClientOid string `json:"clientOid"`
}

type ServiceStatusModel

type ServiceStatusModel struct {
	Status string `json:"status"`
	Msg    string `json:"msg"`
}

A ServiceStatusModel represents the structure of service status.

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 SubAccountBalanceModel added in v1.0.8

type SubAccountBalanceModel struct {
	Summary struct {
		AccountEquityTotal    jsoniter.Number `json:"accountEquityTotal"`
		UnrealisedPNLTotal    jsoniter.Number `json:"unrealisedPNLTotal"`
		MarginBalanceTotal    jsoniter.Number `json:"marginBalanceTotal"`
		PositionMarginTotal   jsoniter.Number `json:"positionMarginTotal"`
		OrderMarginTotal      jsoniter.Number `json:"orderMarginTotal"`
		FrozenFundsTotal      jsoniter.Number `json:"frozenFundsTotal"`
		AvailableBalanceTotal jsoniter.Number `json:"availableBalanceTotal"`
		Currency              string          `json:"currency"`
	} `json:"summary"`
	Accounts []struct {
		AccountName      string          `json:"accountName"`
		AccountEquity    jsoniter.Number `json:"accountEquity"`
		UnrealisedPNL    jsoniter.Number `json:"unrealisedPNL"`
		MarginBalance    jsoniter.Number `json:"marginBalance"`
		PositionMargin   jsoniter.Number `json:"positionMargin"`
		OrderMargin      jsoniter.Number `json:"orderMargin"`
		FrozenFunds      jsoniter.Number `json:"frozenFunds"`
		AvailableBalance jsoniter.Number `json:"availableBalance"`
		Currency         string          `json:"currency"`
	} `json:"accounts"`
}

type SubApiKeyModel added in v1.0.7

type SubApiKeyModel struct {
	SubName     string          `json:"subName"`
	Remark      string          `json:"remark"`
	ApiKey      string          `json:"apiKey"`
	Permission  string          `json:"permission"`
	IpWhitelist string          `json:"ipWhitelist"`
	CreatedAt   jsoniter.Number `json:"createdAt"`
}

type SubApiKeysModel added in v1.0.7

type SubApiKeysModel []*SubApiKeyModel

type TickerItem added in v1.1.2

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

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 TradeFeesV1Resp added in v1.1.1

type TradeFeesV1Resp struct {
	Symbol       string `json:"symbol"`
	TakerFeeRate string `json:"takerFeeRate"`
	MakerFeeRate string `json:"makerFeeRate"`
}

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 TradeStatisticsModel added in v1.1.0

type TradeStatisticsModel struct {
	TurnoverOf24h jsoniter.Number `json:"turnoverOf24h"`
}

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

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

type TransferOutV3Res added in v1.0.7

type TransferOutV3Res struct {
	ApplyId        string          `json:"applyId"`
	BizNo          string          `json:"bizNo"`
	PayAccountType string          `json:"payAccountType"`
	PayTag         string          `json:"payTag"`
	Remark         string          `json:"remark"`
	RecAccountType string          `json:"recAccountType"`
	RecTag         string          `json:"recTag"`
	RecRemark      string          `json:"recRemark"`
	RecSystem      string          `json:"recSystem"`
	Status         string          `json:"status"`
	Currency       string          `json:"currency"`
	Amount         string          `json:"amount"`
	Fee            string          `json:"fee"`
	Sn             big.Int         `json:"sn"`
	Reason         string          `json:"reason"`
	CreatedAt      jsoniter.Number `json:"createdAt"`
	UpdatedAt      jsoniter.Number `json:"updatedAt"`
}

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      int64           `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 WithdrawMarginV1Req added in v1.1.1

type WithdrawMarginV1Req struct {
	Symbol         string `json:"symbol"`
	WithdrawAmount string `json:"withdrawAmount"`
}

type WithdrawalModel

type WithdrawalModel struct {
	WithdrawalId string `json:"withdrawalId"`
	Currency     string `json:"currency"`
	Status       string `json:"status"`
	Address      string `json:"address"`
	Memo         string `json:"memo"`
	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