Categorygithub.com/cshep4/crypto-dot-com-exchange-go
modulepackage
0.2.0
Repository: https://github.com/cshep4/crypto-dot-com-exchange-go.git
Documentation: pkg.go.dev

# README

Crypto.com Exchange

Go client for the Crypto.com Spot Exchange REST API.

Installation

To import the package, run:

go get github.com/cshep4/crypto-dot-com-exchange-go

Setup

An instance of the client can be created like this:

import (
    cdcexchange "github.com/cshep4/crypto-dot-com-exchange-go"
)

client, err := cdcexchange.New("<api_key>", "<secret_key>")
if err != nil {
    return err
}

// optional, configuration can be updated with UpdateConfig
err = client.UpdateConfig("<api_key>", "<secret_key>")
if err != nil {
    return err
}

Optional Configurations

UAT Sandbox Environment

The client can be configured to make requests against the UAT Sandbox environment using the WithUATEnvironment functional option like so:

import (
    cdcexchange "github.com/cshep4/crypto-dot-com-exchange-go"
)

client, err := cdcexchange.New("<api_key>", "<secret_key>", 
    cdcexchange.WithUATEnvironment(),
)
if err != nil {
    return err
}

Production Environment

The client can be configured to make requests against the Production environment using the WithProductionEnvironment functional option. Clients will make requests against this environment by default even if this is not specified.

import (
    cdcexchange "github.com/cshep4/crypto-dot-com-exchange-go"
)

client, err := cdcexchange.New("<api_key>", "<secret_key>", 
    cdcexchange.WithProductionEnvironment(),
)
if err != nil {
    return err
}

Custom HTTP Client

The client can be configured to use a custom HTTP client using the WithHTTPClient functional option. This can be used to create custom timeouts, enable tracing, etc. This is initialised like so:

import (
    "net/http"

    cdcexchange "github.com/cshep4/crypto-dot-com-exchange-go"
)

client, err := cdcexchange.New("<api_key>", "<secret_key>",
    cdcexchange.WithHTTPClient(&http.Client{
        Timeout: 15 * time.Second,
    }),
)
if err != nil {
    return err
}

Supported API (Official Docs):

The supported APIs for each module are listed below.

✅ - API is supported

⚠️ - API is not yet supported (hopefully should be available soon!)

Each API module is separated into separate interfaces, however the CryptoDotComExchange interface can be used to access all methods:

// CryptoDotComExchange is a Crypto.com Exchange client for all available APIs.
type CryptoDotComExchange interface {
    // UpdateConfig can be used to update the configuration of the client object.
    // (e.g. change api key, secret key, environment, etc).
    UpdateConfig(apiKey string, secretKey string, opts ...ClientOption) error
    CommonAPI
    SpotTradingAPI
    MarginTradingAPI
    DerivativesTransferAPI
    SubAccountAPI
    Websocket
}

Client interfaces can be found in client.go.

Common API

// CommonAPI is a Crypto.com Exchange client for Common API.
type CommonAPI interface {
    // GetInstruments provides information on all supported instruments (e.g. BTC_USDT).
    //
    // Method: public/get-instruments
    GetInstruments(ctx context.Context) ([]Instrument, error)
    // GetBook fetches the public order book for a particular instrument and depth.
    //
    // Method: public/get-book
    GetBook(ctx context.Context, instrument string, depth int) (*BookResult, error)
    // GetTickers fetches the public tickers for an instrument (e.g. BTC_USDT).
    //
    // instrument can be left blank to retrieve tickers for ALL instruments.
    //
    // Method: public/get-ticker
    GetTickers(ctx context.Context, instrument string) ([]Ticker, error)
}
MethodSupport
public/auth⚠️
public/get-instruments
public/get-book
public/get-candlestick⚠️
public/get-ticker
public/get-trades⚠️
private/set-cancel-on-disconnect⚠️
private/get-cancel-on-disconnect⚠️
private/create-withdrawal⚠️
private/get-withdrawal-history⚠️
private/get-deposit-history⚠️
private/get-deposit-address⚠️

Spot Trading API

// SpotTradingAPI is a Crypto.com Exchange client for Spot Trading API.
type SpotTradingAPI interface {
    // GetAccountSummary returns the account balance of a user for a particular token.
    //
    // currency can be left blank to retrieve balances for ALL tokens.
    //
    // Method: private/get-account-summary
    GetAccountSummary(ctx context.Context, currency string) ([]Account, error)
    // CreateOrder creates a new BUY or SELL order on the Exchange.
    //
    // This call is asynchronous, so the response is simply a confirmation of the request.
    //
    // The user.order subscription can be used to check when the order is successfully created.
    //
    // Method: private/create-order
    CreateOrder(ctx context.Context, req CreateOrderRequest) (*CreateOrderResult, error)
    // CancelOrder cancels an existing order on the Exchange.
    //
    // This call is asynchronous, so the response is simply a confirmation of the request.
    //
    // The user.order subscription can be used to check when the order is successfully cancelled.
    //
    // Method: private/cancel-order
    CancelOrder(ctx context.Context, instrumentName string, orderID string) error
    // CancelAllOrders cancels  all orders for a particular instrument/pair.
    //
    // This call is asynchronous, so the response is simply a confirmation of the request.
    //
    // The user.order subscription can be used to check when the order is successfully cancelled.
    //
    // Method: private/cancel-all-orders
    CancelAllOrders(ctx context.Context, instrumentName string) error
    // GetOrderHistory gets the order history for a particular instrument.
    //
    // Pagination is handled using page size (Default: 20, Max: 200) & number (0-based).
    // If paging is used, enumerate each page (starting with 0) until an empty order_list array appears in the response.
    //
    // req.InstrumentName can be left blank to get open orders for all instruments.
    //
    // Method: private/get-order-history
    GetOrderHistory(ctx context.Context, req GetOrderHistoryRequest) ([]Order, error)
    // GetOpenOrders gets all open orders for a particular instrument.
    //
    // Pagination is handled using page size (Default: 20, Max: 200) & number (0-based).
    //
    // req.InstrumentName can be left blank to get open orders for all instruments.
    //
    // Method: private/get-open-orders
    GetOpenOrders(ctx context.Context, req GetOpenOrdersRequest) (*GetOpenOrdersResult, error)
    // GetOrderDetail gets details of an order for a particular order ID.
    //
    // Method: private/get-order-detail
    GetOrderDetail(ctx context.Context, orderID string) (*GetOrderDetailResult, error)
    // GetTrades gets all executed trades for a particular instrument.
    //
    // Pagination is handled using page size (Default: 20, Max: 200) & number (0-based).
    // If paging is used, enumerate each page (starting with 0) until an empty trade_list array appears in the response.
    //
    // req.InstrumentName can be left blank to get executed trades for all instruments.
    //
    // Method: private/get-trades
    GetTrades(ctx context.Context, req GetTradesRequest) ([]Trade, error)
}
MethodSupport
private/get-account-summary
private/create-order
private/cancel-order
private/cancel-all-orders
private/get-order-history
private/get-open-orders
private/get-order-detail
private/get-trades

Margin Trading API

// MarginTradingAPI is a Crypto.com Exchange client for Margin Trading API.
type MarginTradingAPI interface {
}
MethodSupport
public/margin/get-transfer-currencies⚠️
public/margin/get-loan-currencies⚠️
private/margin/get-user-config⚠️
private/margin/get-account-summary⚠️
private/margin/transfer⚠️
private/margin/borrow⚠️
private/margin/repay⚠️
private/margin/get-transfer-history⚠️
private/margin/get-borrow-history⚠️
private/margin/get-interest-history⚠️
private/margin/get-repay-history⚠️
private/margin/get-liquidation-history⚠️
private/margin/get-liquidation-orders⚠️
private/margin/create-order⚠️
private/margin/cancel-order⚠️
private/margin/cancel-all-orders⚠️
private/margin/get-order-history⚠️
private/margin/get-open-orders⚠️
private/margin/get-order-detail⚠️
private/margin/get-trades⚠️

Derivatives Transfer API

// DerivativesTransferAPI is a Crypto.com Exchange client for Derivatives Transfer API.
type DerivativesTransferAPI interface {
}
MethodSupport
private/deriv/transfer⚠️
private/deriv/get-transfer-history⚠️

Sub-account API

// SubAccountAPI is a Crypto.com Exchange client for Sub-account API.
type SubAccountAPI interface {
}
MethodSupport
private/subaccount/get-sub-accounts⚠️
private/subaccount/get-transfer-history⚠️
private/subaccount/transfer⚠️

Websocket

// Websocket is a Crypto.com Exchange client websocket methods & channels.
type Websocket interface {
}

Websocket Heartbeats

MethodSupport
public/respond-heartbeat⚠️

Websocket Subscriptions

ChannelSupport
user.order.{instrument_name}⚠️
user.trade.{instrument_name}⚠️
user.balance⚠️
user.margin.order.{instrument_name}⚠️
user.margin.trade.{instrument_name}⚠️
user.margin.balance⚠️
book.{instrument_name}.{depth}⚠️
ticker.{instrument_name}⚠️
trade.{instrument_name}⚠️
candlestick.{interval}.{instrument_name}⚠️

Errors

Custom errors are returned based on the HTTP status code and reason codes returned in the API response. Official documentation on reason codes can be found here. All errors returned from the client can be found in the errors package.

Custom error handling on client errors can be implemented like so:

import (
    "errors"

    cdcerrors "github.com/cshep4/crypto-dot-com-exchange-go/errors"
    cdcexchange "github.com/cshep4/crypto-dot-com-exchange-go"
)

...

res, err := client.GetAccountSummary(ctx, "CRO")
if err != nil {
    switch {
    case errors.Is(err, cdcerrors.ErrSystemError):
        // handle system error
    case errors.Is(err, cdcerrors.ErrUnauthorized):
        // handle unauthorized error
    case errors.Is(err, cdcerrors.ErrIllegalIP):
        // handle illegal IP error
    ...

    }

    return err
}

Resoonse errors can also be cast to retrieve the response code and HTTP status code:

import (
    "errors"
    "log"
    
    cdcerrors "github.com/cshep4/crypto-dot-com-exchange-go/errors"
    cdcexchange "github.com/cshep4/crypto-dot-com-exchange-go"
)

...

res, err := client.GetAccountSummary(ctx, "CRO")
if err != nil {
    var responseError cdcerrors.ResponseError
    if errors.Is(err, &responseError) {
        // response code
        log.Println(responseError.Code)
		
        // HTTP status code
        log.Println(responseError.HTTPStatusCode)

        // underlying error
        log.Println(responseError.Err)
    }
	
    return err
}

Response Codes

CodeHTTP StatusClient ErrorMessage CodeDescription
0200nil--Success
10001500ErrSystemErrorSYS_ERRORMalformed request, (E.g. not using application/json for REST)
10002401ErrUnauthorizedUNAUTHORIZEDNot authenticated, or key/signature incorrect
10003401ErrIllegalIPIP_ILLEGALIP address not whitelisted
10004400ErrBadRequestBAD_REQUESTMissing required fields
10005401ErrUserTierInvalidUSER_TIER_INVALIDDisallowed based on user tier
10006429ErrTooManyRequestsTOO_MANY_REQUESTSRequests have exceeded rate limits
10007400ErrInvalidNonceINVALID_NONCENonce value differs by more than 30 seconds from server
10008400ErrMethodNotFoundMETHOD_NOT_FOUNDInvalid method specified
10009400ErrInvalidDateRangeINVALID_DATE_RANGEInvalid date range
20001400ErrDuplicateRecordDUPLICATE_RECORDDuplicated record
20002400ErrNegativeBalanceNEGATIVE_BALANCEInsufficient balance
30003400ErrSymbolNotFoundSYMBOL_NOT_FOUNDInvalid instrument_name specified
30004400ErrSideNotSupportedSIDE_NOT_SUPPORTEDInvalid side specified
30005400ErrOrderTypeNotSupportedORDERTYPE_NOT_SUPPORTEDInvalid type specified
30006400ErrMinPriceViolatedMIN_PRICE_VIOLATEDPrice is lower than the minimum
30007400ErrMaxPriceViolatedMAX_PRICE_VIOLATEDPrice is higher than the maximum
30008400ErrMinQuantityViolatedMIN_QUANTITY_VIOLATEDQuantity is lower than the minimum
30009400ErrMaxQuantityViolatedMAX_QUANTITY_VIOLATEDQuantity is higher than the maximum
30010400ErrMissingArgumentMISSING_ARGUMENTRequired argument is blank or missing
30013400ErrInvalidPricePrecisionINVALID_PRICE_PRECISIONToo many decimal places for Price
30014400ErrInvalidQuantityPrecisionINVALID_QUANTITY_PRECISIONToo many decimal places for Quantity
30016400ErrMinNotionalViolatedMIN_NOTIONAL_VIOLATEDThe notional amount is less than the minimum
30017400ErrMaxNotionalViolatedMAX_NOTIONAL_VIOLATEDThe notional amount exceeds the maximum
30023400ErrMinAmountViolatedMIN_AMOUNT_VIOLATEDAmount is lower than the minimum
30024400ErrMaxAmountViolatedMAX_AMOUNT_VIOLATEDAmount is higher than the maximum
30025400ErrAmountPrecisionOverflowAMOUNT_PRECISION_OVERFLOWAmount precision exceeds the maximum
40001400ErrMGInvalidAccountStatusMG_INVALID_ACCOUNT_STATUSOperation has failed due to your account's status. Please try again later.
40002400ErrMGTransferActiveLoanMG_TRANSFER_ACTIVE_LOANTransfer has failed due to holding an active loan. Please repay your loan and try again later.
40003400ErrMGInvalidLoanCurrencyMG_INVALID_LOAN_CURRENCYCurrency is not same as loan currency of active loan
40004400ErrMGInvalidRepayAmountMG_INVALID_REPAY_AMOUNTOnly supporting full repayment of all margin loans
40005400ErrMGNoActiveLoanMG_NO_ACTIVE_LOANNo active loan
40006400ErrMGBlockedBorrowMG_BLOCKED_BORROWBorrow has been suspended. Please try again later.
40007400ErrMGBlockedNewOrderMG_BLOCKED_NEW_ORDERPlacing new order has been suspended. Please try again later.
50001400ErrMGCreditLineNotMaintainedDW_CREDIT_LINE_NOT_MAINTAINEDPlease ensure your credit line is maintained and try again later.

# Packages

No description provided by the author

# Functions

New will construct a new instance of client.
WithHTTPClient will allow the client to be initialised with a custom http client.
WithProductionEnvironment will initialise the client to make requests against the production environment.
WithUATEnvironment will initialise the client to make requests against the UAT sandbox environment.

# Constants

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author

# Structs

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
CancelAllOrdersResponse is the base response returned from the private/cancel-all-orders API.
CancelOrderResponse is the base response returned from the private/cancel-order API.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author

# Interfaces

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author

# Type aliases

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author