kucoin

package module
v1.0.7 Latest Latest
Warning

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

Go to latest
Published: Mar 28, 2019 License: MIT Imports: 20 Imported by: 0

README

Go SDK for KuCoin API

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

Latest Version GoDoc Build Status Go Report Card

Install

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

Usage

Choose environment
Environment BaseUri
Production DEFAULT https://openapi-v2.kucoin.com
Sandbox https://openapi-sandbox.kucoin.com
Create ApiService
s := kucoin.NewApiService( 
	// kucoin.ApiBaseURIOption("https://openapi-v2.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://openapi-v2.kucoin.com
// export API_KEY=key
// export API_SECRET=secret
// export API_PASSPHRASE=passphrase
// s := NewApiServiceFromEnv()
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.Accounts("", "")
if err != nil {
    // Handle error
    return
}

as := kucoin.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{}, &kucoin.PaginationParam{CurrentPage: 1, PageSize: 10})
if err != nil {
    // Handle error
    return
}

os := kucoin.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 := &kucoin.WebSocketTokenModel{}
if err := rsp.ReadData(tk); err != nil {
    // Handle error
    return
}

c := s.NewWebSocketClient(tk)

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

ch1 := kucoin.NewSubscribeMessage("/market/ticker:KCS-BTC", false)
ch2 := kucoin.NewSubscribeMessage("/market/ticker:ETH-BTC", false)
uch := kucoin.NewUnsubscribeMessage("/market/ticker:ETH-BTC", 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", kucoin.ToJsonString(m))
        t := &kucoin.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 ETH-BTC")
            if err = c.Unsubscribe(uch); err != nil {
                log.Printf("Error: %s", err.Error())
                // Handle error
                return
            }
        }
        if i == 10 {
            log.Println("Subscribe ETH-BTC")
            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.CreateAccount() YES https://docs.kucoin.com/#create-an-account
ApiService.Accounts() YES https://docs.kucoin.com/#list-accounts
ApiService.Account() YES https://docs.kucoin.com/#get-an-account
ApiService.AccountLedgers() YES https://docs.kucoin.com/#get-account-ledgers
ApiService.AccountHolds() YES https://docs.kucoin.com/#get-holds
ApiService.InnerTransfer() YES https://docs.kucoin.com/#inner-transfer
Deposit
API Authentication Description
ApiService.CreateDepositAddress() YES https://docs.kucoin.com/#create-deposit-address
ApiService.DepositAddresses() YES https://docs.kucoin.com/#get-deposit-address
ApiService.Deposits() YES https://docs.kucoin.com/#get-deposit-list
Fill
API Authentication Description
ApiService.Fills() YES https://docs.kucoin.com/#list-fills
ApiService.RecentFills() YES https://docs.kucoin.com/#recent-fills
Order
API Authentication Description
ApiService.CreateOrder() YES https://docs.kucoin.com/#place-a-new-order
ApiService.CancelOrder() YES https://docs.kucoin.com/#cancel-an-order
ApiService.CancelOrders() YES https://docs.kucoin.com/#cancel-all-orders
ApiService.Orders() YES https://docs.kucoin.com/#list-orders
ApiService.Order() YES https://docs.kucoin.com/#get-an-order
ApiService.RecentOrders() YES https://docs.kucoin.com/#recent-orders
WebSocket Feed
API Authentication Description
ApiService.WebSocketPublicToken() NO https://docs.kucoin.com/#apply-connect-token
ApiService.WebSocketPrivateToken() YES https://docs.kucoin.com/#apply-connect-token
ApiService.NewWebSocketClient() - https://docs.kucoin.com/#websocket-feed
Withdrawal
API Authentication Description
ApiService.WithdrawalQuotas() YES https://docs.kucoin.com/#get-withdrawal-quotas
ApiService.Withdrawals() YES https://docs.kucoin.com/#get-withdrawals-list
ApiService.ApplyWithdrawal() YES https://docs.kucoin.com/#apply-withdraw
ApiService.CancelWithdrawal() YES https://docs.kucoin.com/#cancel-withdrawal
Currency
API Authentication Description
ApiService.Currencies() NO https://docs.kucoin.com/#get-currencies
ApiService.Currency() NO https://docs.kucoin.com/#get-currency-detail
ApiService.Prices() NO https://docs.kucoin.com/#get-fiat-price
Symbol
API Authentication Description
ApiService.Symbols() NO https://docs.kucoin.com/#get-symbols-list
ApiService.TickerLevel1() NO https://docs.kucoin.com/#get-ticker
ApiService.Tickers() NO https://docs.kucoin.com/#get-all-tickers
ApiService.AggregatedPartOrderBook() NO https://docs.kucoin.com/#get-part-order-book-aggregated
ApiService.AggregatedFullOrderBook() NO https://docs.kucoin.com/#get-full-order-book-aggregated
ApiService.AtomicFullOrderBook() NO https://docs.kucoin.com/#get-full-order-book-atomic
ApiService.TradeHistories() NO https://docs.kucoin.com/#get-trade-histories
ApiService.KLines() NO https://docs.kucoin.com/#get-klines
ApiService.Stats24hr() NO https://docs.kucoin.com/#get-24hr-stats
ApiService.Markets() NO https://docs.kucoin.com/#get-market-list
Time
API Authentication Description
ApiService.ServerTime() NO https://docs.kucoin.com/#server-time

Run tests

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

# Run tests
go test -v

License

MIT

Documentation

Overview

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

Index

Constants

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

All message types of WebSocket.

View Source
const (
	ApiSuccess = "200000"
)

The predefined API codes

View Source
const ProductionApiBaseURI = "https://openapi-v2.kucoin.com"

ProductionApiBaseURI is api base uri for production.

Variables

This section is empty.

Functions

func IntToString

func IntToString(i int64) string

IntToString converts int64 to string.

func ToJsonString

func ToJsonString(v interface{}) string

ToJsonString converts any value to JSON string.

Types

type AccountHoldModel

type AccountHoldModel struct {
	Currency   string `json:"currency"`
	HoldAmount string `json:"holdAmount"`
	BizType    string `json:"bizType"`
	OrderId    string `json:"orderId"`
	CreatedAt  int64  `json:"createdAt"`
	UpdatedAt  int64  `json:"updatedAt"`
}

An AccountHoldModel represents the holds on an account for any active orders or pending withdraw requests. As an order is filled, the hold amount is updated. If an order is canceled, any remaining hold is removed. For a withdraw, once it is completed, the hold is removed.

type AccountHoldsModel

type AccountHoldsModel []*AccountHoldModel

An AccountHoldsModel is the set of *AccountHoldModel.

type AccountLedgerModel added in v1.0.3

type AccountLedgerModel struct {
	Currency  string          `json:"currency"`
	Amount    string          `json:"amount"`
	Fee       string          `json:"fee"`
	Balance   string          `json:"balance"`
	BizType   string          `json:"bizType"`
	Direction string          `json:"direction"`
	CreatedAt int64           `json:"createdAt"`
	Context   json.RawMessage `json:"context"`
}

An AccountLedgerModel represents account activity either increases or decreases your account balance.

type AccountLedgersModel added in v1.0.3

type AccountLedgersModel []*AccountLedgerModel

An AccountLedgersModel the set of *AccountLedgerModel.

type AccountModel

type AccountModel struct {
	Id        string `json:"id"`
	Currency  string `json:"currency"`
	Type      string `json:"type"`
	Balance   string `json:"balance"`
	Available string `json:"available"`
	Holds     string `json:"holds"`
}

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 json.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) Account

func (as *ApiService) Account(accountId string) (*ApiResponse, error)

Account returns an account when you know the accountId.

func (*ApiService) AccountHolds

func (as *ApiService) AccountHolds(accountId string, pagination *PaginationParam) (*ApiResponse, error)

AccountHolds returns a list of currency hold. Holds are placed on an account for any active orders or pending withdraw requests. As an order is filled, the hold amount is updated. If an order is canceled, any remaining hold is removed. For a withdraw, once it is completed, the hold is removed.

func (*ApiService) AccountLedgers added in v1.0.3

func (as *ApiService) AccountLedgers(accountId string, startAt, endAt int64, pagination *PaginationParam) (*ApiResponse, error)

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

func (*ApiService) Accounts

func (as *ApiService) Accounts(currency, typo string) (*ApiResponse, error)

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

func (*ApiService) AggregatedFullOrderBook

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

AggregatedFullOrderBook returns a list of open orders(aggregated) for a symbol.

func (*ApiService) AggregatedPartOrderBook added in v1.0.3

func (as *ApiService) AggregatedPartOrderBook(symbol string, depth int64) (*ApiResponse, error)

AggregatedPartOrderBook returns a list of open orders(aggregated) for a symbol.

func (*ApiService) ApplyWithdrawal

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

ApplyWithdrawal applies a withdrawal.

func (*ApiService) AtomicFullOrderBook

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

AtomicFullOrderBook returns a list of open orders for a symbol. Level-3 order book includes all bids and asks (non-aggregated, each item in Level-3 means a single order).

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

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

CancelWithdrawal cancels a withdrawal by withdrawalId.

func (*ApiService) CreateAccount

func (as *ApiService) CreateAccount(typo, currency string) (*ApiResponse, error)

CreateAccount creates an account according to type(main|trade) and currency Parameter #1 typo is type of account.

func (*ApiService) CreateDepositAddress

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

CreateDepositAddress creates a deposit address.

func (*ApiService) CreateOrder

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

CreateOrder places a new order.

func (*ApiService) Currencies

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

Currencies returns a list of known currencies.

func (*ApiService) Currency

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

Currency returns the details of the currency.

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

func (as *ApiService) InnerTransfer(clientOid, payAccountId, recAccountId, amount string) (*ApiResponse, error)

InnerTransfer makes a currency transfer internally. The inner transfer interface is used for assets transfer among the accounts of a user and is free of charges on the platform. For example, a user could transfer assets for free form the main account to the trading account on the platform.

func (*ApiService) KLines added in v1.0.5

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

KLines returns the k lines for a symbol. Data are returned in grouped buckets based on requested type. Parameter #2 typo is the type of candlestick patterns.

func (*ApiService) Markets

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

Markets returns the transaction currencies for the entire trading market.

func (*ApiService) NewWebSocketClient

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

NewWebSocketClient creates an instance of WebSocketClient.

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) Prices added in v1.0.4

func (as *ApiService) Prices(base, currencies string) (*ApiResponse, error)

Prices returns the fiat prices for currency.

func (*ApiService) RecentFills added in v1.0.1

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

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

func (*ApiService) RecentOrders added in v1.0.1

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

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

func (*ApiService) ServerTime

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

ServerTime returns the API server time.

func (*ApiService) Stats24hr

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

Stats24hr returns 24 hr stats for the symbol. volume is in base currency units. open, high, low are in quote currency units.

func (*ApiService) Symbols

func (as *ApiService) Symbols(market string) (*ApiResponse, error)

Symbols returns a list of available currency pairs for trading.

func (*ApiService) TickerLevel1 added in v1.0.3

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

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

func (*ApiService) Tickers added in v1.0.3

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

Tickers returns all tickers as TickersResponseModel for all trading pairs in the market (including 24h volume).

func (*ApiService) TradeHistories

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

TradeHistories returns a list the latest trades for a symbol.

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 CancelWithdrawalResultModel

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

CancelWithdrawalResultModel represents the result of CancelWithdrawal().

type CreateOrderResultModel

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

A CreateOrderResultModel represents the result of CreateOrder().

type CurrenciesModel

type CurrenciesModel []*CurrencyModel

A CurrenciesModel is the set of *CurrencyModel.

type CurrencyModel

type CurrencyModel struct {
	Name              string `json:"name"`
	Currency          string `json:"currency"`
	FullName          string `json:"fullName"`
	Precision         uint8  `json:"precision"`
	WithdrawalMinSize string `json:"withdrawalMinSize"`
	WithdrawalMinFee  string `json:"withdrawalMinFee"`
	IsWithdrawEnabled bool   `json:"isWithdrawEnabled"`
	IsDepositEnabled  bool   `json:"isDepositEnabled"`
}

A CurrencyModel represents a model of known currency.

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 {
	Address    string `json:"address"`
	Memo       string `json:"memo"`
	Amount     string `json:"amount"`
	Fee        string `json:"fee"`
	Currency   string `json:"currency"`
	IsInner    bool   `json:"isInner"`
	WalletTxId string `json:"walletTxId"`
	Status     string `json:"status"`
	CreatedAt  int64  `json:"createdAt"`
	UpdatedAt  int64  `json:"updatedAt"`
}

A DepositModel represents a deposit record.

type DepositsModel

type DepositsModel []*DepositModel

A DepositsModel is the set of *DepositModel.

type FillModel

type FillModel struct {
	Symbol         string `json:"symbol"`
	TradeId        string `json:"tradeId"`
	OrderId        string `json:"orderId"`
	CounterOrderId string `json:"counterOrderId"`
	Side           string `json:"side"`
	Liquidity      string `json:"liquidity"`
	ForceTaker     bool   `json:"forceTaker"`
	Price          string `json:"price"`
	Size           string `json:"size"`
	Funds          string `json:"funds"`
	Fee            string `json:"fee"`
	FeeRate        string `json:"feeRate"`
	FeeCurrency    string `json:"feeCurrency"`
	Stop           string `json:"stop"`
	Type           string `json:"type"`
	CreatedAt      int64  `json:"createdAt"`
}

A FillModel represents the structure of fill.

type FillsModel

type FillsModel []*FillModel

A FillsModel is the set of *FillModel.

type FullOrderBookModel

type FullOrderBookModel struct {
	Sequence string     `json:"sequence"`
	Bids     [][]string `json:"bids"`
	Asks     [][]string `json:"asks"`
}

A FullOrderBookModel represents a list of open orders for a symbol, with full depth.

type InterTransferResultModel

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

An InterTransferResultModel represents the result of a inner-transfer operation.

type KLineModel added in v1.0.5

type KLineModel []string

KLineModel represents the k lines for a symbol. Rates are returned in grouped buckets based on requested type.

type KLinesModel added in v1.0.5

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

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 OrderModel

type OrderModel struct {
	Id            string `json:"id"`
	Symbol        string `json:"symbol"`
	OpType        string `json:"opType"`
	Type          string `json:"type"`
	Side          string `json:"side"`
	Price         string `json:"price"`
	Size          string `json:"size"`
	Funds         string `json:"funds"`
	DealFunds     string `json:"dealFunds"`
	DealSize      string `json:"dealSize"`
	Fee           string `json:"fee"`
	FeeCurrency   string `json:"feeCurrency"`
	Stp           string `json:"stp"`
	Stop          string `json:"stop"`
	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"`
	CancelAfter   uint64 `json:"cancelAfter"`
	Channel       string `json:"channel"`
	ClientOid     string `json:"clientOid"`
	Remark        string `json:"remark"`
	Tags          string `json:"tags"`
	IsActive      bool   `json:"isActive"`
	CancelExist   bool   `json:"cancelExist"`
	CreatedAt     int64  `json:"createdAt"`
}

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 PartOrderBookModel

type PartOrderBookModel struct {
	Sequence string     `json:"sequence"`
	Bids     [][]string `json:"bids"`
	Asks     [][]string `json:"asks"`
}

A PartOrderBookModel represents a list of open orders for a symbol, a part of Order Book within 100 depth for each side(ask or bid).

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 Stats24hrModel

type Stats24hrModel struct {
	Symbol      string `json:"symbol"`
	ChangeRate  string `json:"changeRate"`
	ChangePrice string `json:"changePrice"`
	Open        string `json:"open"`
	Close       string `json:"close"`
	High        string `json:"high"`
	Low         string `json:"low"`
	Vol         string `json:"vol"`
	VolValue    string `json:"volValue"`
}

A Stats24hrModel represents 24 hr stats for the symbol. Volume is in base currency units. Open, high, low are in quote currency units.

type SymbolModel

type SymbolModel struct {
	Symbol         string `json:"symbol"`
	Name           string `json:"name"`
	BaseCurrency   string `json:"baseCurrency"`
	QuoteCurrency  string `json:"quoteCurrency"`
	BaseMinSize    string `json:"baseMinSize"`
	QuoteMinSize   string `json:"quoteMinSize"`
	BaseMaxSize    string `json:"baseMaxSize"`
	QuoteMaxSize   string `json:"quoteMaxSize"`
	BaseIncrement  string `json:"baseIncrement"`
	QuoteIncrement string `json:"quoteIncrement"`
	PriceIncrement string `json:"priceIncrement"`
	EnableTrading  bool   `json:"enableTrading"`
}

A SymbolModel represents an available currency pairs for trading.

type SymbolsModel

type SymbolsModel []*SymbolModel

A SymbolsModel is the set of *SymbolModel.

type TickerLevel1Model added in v1.0.3

type TickerLevel1Model struct {
	Sequence    string `json:"sequence"`
	Price       string `json:"price"`
	Size        string `json:"size"`
	BestBid     string `json:"bestBid"`
	BestBidSize string `json:"bestBidSize"`
	BestAsk     string `json:"bestAsk"`
	BestAskSize string `json:"bestAskSize"`
	Time        int64  `json:"time"`
}

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

type TickerModel

type TickerModel struct {
	Symbol      string `json:"symbol"`
	Buy         string `json:"buy"`
	Sell        string `json:"sell"`
	ChangeRate  string `json:"changeRate"`
	ChangePrice string `json:"changePrice"`
	High        string `json:"high"`
	Low         string `json:"low"`
	Vol         string `json:"vol"`
	VolValue    string `json:"volValue"`
	Last        string `json:"last"`
}

A TickerModel represents a market ticker for all trading pairs in the market (including 24h volume).

type TickersModel added in v1.0.3

type TickersModel []*TickerModel

A TickersModel is the set of *MarketTickerModel.

type TickersResponseModel added in v1.0.3

type TickersResponseModel struct {
	Time    int64        `json:"time"`
	Tickers TickersModel `json:"ticker"`
}

TickersResponseModel represents the response model of MarketTickers().

type TradeHistoriesModel

type TradeHistoriesModel []*TradeHistoryModel

A TradeHistoriesModel is the set of *TradeHistoryModel.

type TradeHistoryModel

type TradeHistoryModel struct {
	Sequence string `json:"sequence"`
	Price    string `json:"price"`
	Size     string `json:"size"`
	Side     string `json:"side"`
	Time     int64  `json:"time"`
}

A TradeHistoryModel represents a the latest trades for a symbol.

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

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

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

type WebSocketUnsubscribeMessage added in v1.0.6

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 {
	Id         string `json:"id"`
	Address    string `json:"address"`
	Memo       string `json:"memo"`
	Currency   string `json:"currency"`
	Amount     string `json:"amount"`
	Fee        string `json:"fee"`
	WalletTxId string `json:"walletTxId"`
	IsInner    bool   `json:"isInner"`
	Status     string `json:"status"`
	CreatedAt  int64  `json:"createdAt"`
	UpdatedAt  int64  `json:"updatedAt"`
}

A WithdrawalModel represents a withdrawal.

type WithdrawalQuotasModel

type WithdrawalQuotasModel struct {
	Currency            string `json:"currency"`
	AvailableAmount     string `json:"availableAmount"`
	RemainAmount        string `json:"remainAmount"`
	WithdrawMinSize     string `json:"withdrawMinSize"`
	LimitBTCAmount      string `json:"limitBTCAmount"`
	InnerWithdrawMinFee string `json:"innerWithdrawMinFee"`
	UsedBTCAmount       string `json:"usedBTCAmount"`
	IsWithdrawEnabled   bool   `json:"isWithdrawEnabled"`
	WithdrawMinFee      string `json:"withdrawMinFee"`
	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