tokenomy

package module
v0.15.2 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2023 License: MIT Imports: 20 Imported by: 0

README

=  tokenomy-go
:url-gocard: https://goreportcard.com/report/github.com/tokenomy/tokenomy-go
:url-goref: https://pkg.go.dev/github.com/tokenomy/tokenomy-go

image:https://pkg.go.dev/badge/github.com/tokenomy/tokenomy-go.svg[Go Reference, link={url-goref}]
image:https://goreportcard.com/badge/github.com/tokenomy/tokenomy-go.svg[Go Report Card, link={url-gocard}]

This is the official Go module for client of Tokenomy API v1 and v2.

Documentation for API v1 is available at
https://exchange.tokenomy.com/help/api[API v1 help page]
and the
https://pkg.go.dev/github.com/tokenomy/tokenomy-go/v1?tab=doc[Go doc page].

Documentation for API v2 is available at
https://exchange.tokenomy.com/help/api/v2[API v2 help page]
and the
https://pkg.go.dev/github.com/tokenomy/tokenomy-go/v2?tab=doc[Go doc page].

Note that, this module is in development state, still in v0, and may
subject to changes in the future release until v1 is reached.

Tokenomy provide public and private APIs.
The public APIs can be accessed directly, without any keys or credential.
The private APIs can only be accessed by using token and secret keys (API
credential).

An API credential can be retrieved manually by logging in into your
https://exchange.tokenomy.com[Tokenomy Exchange account]
and open the
https://exchange.tokenomy.com/trade_api["Trade API" menu section].
Please keep these credentials safe and do not reveal it to any external party.


==  License

----
Copyright (c) 2019 Tokenomy Technologies Ltd. All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
----

Documentation

Overview

Package tokenomy is the official Go module for client of Tokenomy API v2.

The documentation for API v2 is available at https://api.tokenomy.com/ and for the Go module at https://pkg.go.dev/github.com/tokenomy/tokenomy-go?tab=doc.

Note that, this module is in development state, still in v0, and may subject to changes in the future release until v1 is reached.

Tokenomy provide public and private APIs. The public APIs can be accessed directly, without any keys or credential. The private APIs can only be accessed by using token and secret keys (API credential).

An API credential can be retrieved manually by logging in into your Tokenomy account (https://exchange.tokenomy.com) through the "Trade API" menu section (https://exchange.tokenomy.com/trade_api). Please keep these credentials safe and do not reveal it to any external party.

Index

Constants

View Source
const (
	APIMarketDepths     = "/v2/market/depths"
	APIMarketInfo       = "/v2/market/info"
	APIMarketTradesOpen = "/v2/market/trades/open"
	APIMarketPrices     = "/v2/market/prices"
	APIMarketTicker     = "/v2/market/ticker"
	APIMarketTrades     = "/v2/market/trades"
	APIMarketSummaries  = "/v2/market/summaries"

	APIUserInfo         = "/v2/user/info"
	APIUserTrades       = "/v2/user/trades"
	APIUserOrdersClosed = "/v2/user/orders/closed"
	APIUserOrdersOpen   = "/v2/user/orders/open"
	APIUserOrderInfo    = "/v2/user/order"
	APIUserTransactions = "/v2/user/transactions"
	APIUserWithdraw     = "/v2/user/withdraw"

	APITradeAsk       = "/v2/trade/ask"
	APITradeBid       = "/v2/trade/bid"
	APITradeBulk      = "/v2/trade/bulk"
	APITradeCancelAll = "/v2/trade/cancel/all"
	APITradeCancelAsk = "/v2/trade/cancel/ask"
	APITradeCancelBid = "/v2/trade/cancel/bid"

	WSPrivate = "/v2/user/ws"

	WSPublic             = "/v2/ws"
	WSPublicSubscription = "/v2/ws/subscription"
)

List of API endpoints.

View Source
const (
	AssetNameAchain          = "achain"
	AssetNameBalancer        = "bal"
	AssetNameBinancechain    = "bnb"
	AssetNameBitcoin         = "btc"
	AssetNameBitcoinCash     = "bch"
	AssetNameCardano         = "ada"
	AssetNameChainlink       = "link"
	AssetNameCompound        = "comp"
	AssetNameDai             = "dai"
	AssetNameEthereum        = "eth"
	AssetNameEthereumclassic = "etc"
	AssetNameHara            = "hart"
	AssetNameIdk             = "idk"
	AssetNameInmax           = "inx"
	AssetNameLitecoin        = "ltc"
	AssetNameNeo             = "neo"
	AssetNamePolkadot        = "dot"
	AssetNameSolana          = "sol"
	AssetNameStellar         = "xlm"
	AssetNameTether          = "usdt"
	AssetNameTezos           = "xtz"
	AssetNameTokenomy        = "ten"
	AssetNameUsdc            = "usdc"
	AssetNameXanpool         = "xlp"
	AssetNameAvalanche       = "avax"
)

List of known asset names. The list is updated rarely, it may contains asset that has been delisted or did not contains new asset in the Tokenomy platform.

View Source
const (
	PairBitcoinCashBitcoin = AssetNameBitcoinCash + `_` + AssetNameBitcoin // bch_btc
	PairEthereumBitcoin    = AssetNameEthereum + `_` + AssetNameBitcoin    // eth_btc
	PairLitecoinBitcoin    = AssetNameLitecoin + `_` + AssetNameBitcoin    // ltc_btc
	PairPolkadotBitcoin    = AssetNamePolkadot + `_` + AssetNameBitcoin    // dot_btc
	PairSolanaBitcoin      = AssetNameSolana + `_` + AssetNameBitcoin      // sol_btc
	PairStellarBitcoin     = AssetNameStellar + `_` + AssetNameBitcoin     // xlm_btc
	PairTokenomyBitcoin    = AssetNameTokenomy + `_` + AssetNameBitcoin    // ten_btc
	PairUsdcBitcoin        = AssetNameUsdc + `_` + AssetNameBitcoin        // usdc_btc

	PairBitcoinIdk   = AssetNameBitcoin + `_` + AssetNameIdk   // btc_idk
	PairCardanoIdk   = AssetNameCardano + `_` + AssetNameIdk   // ada_idk
	PairChainlinkIdk = AssetNameChainlink + `_` + AssetNameIdk // link_idk
	PairCompoundIdk  = AssetNameCompound + `_` + AssetNameIdk  // comp_idk
	PairDaiIdk       = AssetNameDai + `_` + AssetNameIdk       // dai_idk
	PairEthereumIdk  = AssetNameEthereum + `_` + AssetNameIdk  // eth_idk
	PairPolkadotIdk  = AssetNamePolkadot + `_` + AssetNameIdk  // dot_idk
	PairSolanaIdk    = AssetNameSolana + `_` + AssetNameIdk    // sol_idk
	PairTetherIdk    = AssetNameTether + `_` + AssetNameIdk    // usdt_idk
	PairTezosIdk     = AssetNameTezos + `_` + AssetNameIdk     // xtz_idk
	PairTokenomyIdk  = AssetNameTokenomy + `_` + AssetNameIdk  // ten_idk

	PairCardanoTether  = AssetNameCardano + `_` + AssetNameTether  // ada_usdt
	PairBitcoinTether  = AssetNameBitcoin + `_` + AssetNameTether  // btc_usdt
	PairEthereumTether = AssetNameEthereum + `_` + AssetNameTether // eth_usdt
	PairIdkTether      = AssetNameIdk + `_` + AssetNameTether      // idk_usdt
	PairPolkadotTether = AssetNamePolkadot + `_` + AssetNameTether // dot_usdt
	PairSolanaTether   = AssetNameSolana + `_` + AssetNameTether   // sol_usdt
	PairTokenomyTether = AssetNameTokenomy + `_` + AssetNameTether // ten_usdt
	PairTezosTether    = AssetNameTezos + `_` + AssetNameTether    // xtz_usdt
)

List of valid pairs. The list is updated rarely, so it may contains pairs that has been delisted or did not contains new pairs in the Tokenomy platform.

View Source
const (
	TradeMethodLimit  = "limit"
	TradeMethodMarket = "market"
)

List of trade's method.

View Source
const (
	TradeTypeAsk = "sell"
	TradeTypeBid = "buy"
)

List of trade's type.

View Source
const (
	TradeStatusCancelled = "cancelled"
	TradeStatusFilled    = "filled"
)

List of valid trade's status.

View Source
const (
	EnvNameAddress = "TOKENOMY_ADDRESS"
	EnvNameDebug   = "TOKENOMY_DEBUG"
	EnvNameToken   = "TOKENOMY_TOKEN"
	EnvNameSecret  = "TOKENOMY_SECRET"
	EnvNameTestE2E = "TOKENOMY_TEST_E2E"
)

List of knowns environment variables.

View Source
const (
	HeaderNameSign = "Sign"
	HeaderNameKey  = "Key"
)

List of knowns HTTP headers.

View Source
const (
	ParamNameAddress       = "address"
	ParamNameAddressType   = "address_type"
	ParamNameAmount        = "amount"
	ParamNameAsset         = "asset"
	ParamNameIDAfter       = "id_after"
	ParamNameIDBefore      = "id_before"
	ParamNameLimit         = "limit"
	ParamNameMemo          = "memo"
	ParamNameMethod        = "method"
	ParamNameNetwork       = "network"
	ParamNameNonce         = "nonce"
	ParamNameOffset        = "offset"
	ParamNameOrderID       = "order_id"
	ParamNameOrderMethod   = "order_method"
	ParamNamePair          = "pair"
	ParamNamePostOnly      = "post_only"
	ParamNamePrice         = "price"
	ParamNameReceiveWindow = "recv_window"
	ParamNameRequestID     = "request_id"
	ParamNameSort          = "sort"
	ParamNameTimeAfter     = "time_after"
	ParamNameTimeBefore    = "time_before"
	ParamNameTimeInForce   = "time_in_force"
	ParamNameTimestamp     = "timestamp"
	ParamNameTradeID       = "trade_id"
	ParamNameTradeMethod   = "trade_method"
	ParamNameType          = "type"
)

List of knowns parameter names.

View Source
const (
	SortAscending  = "asc"
	SortDescending = "desc"
)

List of valid sort values.

View Source
const DefaultAddress = "https://api.tokenomy.com"

DefaultAddress contains the official API domain.

View Source
const DefaultLimit = 100

DefaultLimit define maximum number of record fetched per request.

View Source
const (
	TimeInForceFOK = "FOK" // Fill-or-Kill.
)

List of valid values for TradeRequest.TimeInForce.

View Source
const Version = `0.15.2`

Version the latest tagged version.

View Source
const (
	WSMessageUserOrdersTaken = "/v2/user/orders/taken"
)

List of WebSocket broadcast messages.

Variables

View Source
var (
	ErrInvalidAmount = &errors.E{
		Code:    http.StatusBadRequest,
		Message: "invalid or empty amount parameter",
		Name:    "ERR_INVALID_AMOUNT",
	}
	ErrInvalidAsset = &errors.E{
		Code:    http.StatusBadRequest,
		Message: "invalid or empty asset parameter",
		Name:    "ERR_INVALID_ASSET",
	}
	ErrInvalidPair = &errors.E{
		Code:    http.StatusBadRequest,
		Message: "invalid or empty pair parameter",
		Name:    "ERR_INVALID_PAIR",
	}
	ErrInvalidPrice = &errors.E{
		Code:    http.StatusBadRequest,
		Message: "invalid or empty price parameter",
		Name:    "ERR_INVALID_PRICE",
	}
	ErrInvalidRequestID = &errors.E{
		Code:    http.StatusBadRequest,
		Message: "invalid or empty request ID",
		Name:    "ERR_INVALID_REQUEST_ID",
	}
	ErrInvalidSortBy = &errors.E{
		Code:    http.StatusBadRequest,
		Message: `invalid sort-by parameter, its either "asc" or "desc"`,
		Name:    "ERR_INVALID_SORT_BY",
	}
	ErrInvalidTradeID = &errors.E{
		Code:    http.StatusBadRequest,
		Message: "invalid trade ID",
		Name:    "ERR_INVALID_TRADE_ID",
	}
	ErrInvalidTradeMethod = &errors.E{
		Code:    http.StatusBadRequest,
		Message: `invalid or empty trade method, its either "limit" or "market"`,
		Name:    "ERR_INVALID_TRADE_METHOD",
	}
	ErrInvalidTradeType = &errors.E{
		Code:    http.StatusBadRequest,
		Message: `invalid or empty trade type, its either "buy" or "sell"`,
		Name:    "ERR_INVALID_TRADE_TYPE",
	}

	ErrAssetKYCRequired = &errors.E{
		Code:    http.StatusForbidden,
		Message: `the traded asset require user account to finish KYC process`,
		Name:    "ERR_ASSET_KYC_REQUIRED",
	}
	ErrAssetCountryBlacklisted = &errors.E{
		Code:    http.StatusForbidden,
		Message: `the traded asset is not allowed in user account country`,
		Name:    "ERR_ASSET_COUNTRY_BLACKLISTED",
	}
	ErrAssetTermsRequired = &errors.E{
		Code:    http.StatusForbidden,
		Message: `the traded asset require user account to accept terms of sale`,
		Name:    "ERR_ASSET_TERMS_REQUIRED",
	}

	ErrTradeFillOrKill = &liberrors.E{
		Code:    http.StatusUnprocessableEntity,
		Message: "not enough amount in the market to process fill-or-kill order",
		Name:    "ERR_TRADE_FILL_OR_KILL",
	}

	ErrWalletAddress = &errors.E{
		Code:    http.StatusBadRequest,
		Message: "invalid or empty wallet address",
		Name:    "ERR_WALLET_ADDRESS",
	}
)

List of predefined errors.

Functions

func Sign

func Sign(payload, secret string) string

Sign the payload using secret and return it as encoded hexadecimal characters.

Types

type Asset added in v0.14.0

type Asset struct {
	Name             string `json:"name"`
	IsWithoutNetwork bool   `json:"is_without_network"`
}

Asset contains basic information of an asset

type AssetTransactions added in v0.10.0

type AssetTransactions struct {
	Deposit  map[string][]DepositItem  `json:"deposit"`
	Withdraw map[string][]WithdrawItem `json:"withdraw"`
}

AssetTransactions contains list of deposit and withdraw transaction.

type BulkOrderItem added in v0.15.0

type BulkOrderItem struct {
	liberrors.E
	TradeRequest

	ID    int64 `json:"id,omitempty"`
	RefID int64 `json:"ref_id,omitempty"`
}

BulkOrderItem represent single order in bulk trading.

type Client

type Client struct {
	*libhttp.Client

	User *User
	// contains filtered or unexported fields
}

Client for Tokenomy REST API v2.

func NewClient added in v0.10.0

func NewClient(env *Environment) (cl *Client, err error)

NewClient create and initialize new client for REST API v2.

The Environment Address parameter define the REST API v2 address, if its empty it will set to value in DefaultAddress.

The Environment' Token and Secret parameters are used to authenticate the client when accessing private API.

By default, the Token and Secret is read from environment variables "TOKENOMY_TOKEN" and "TOKENOMY_SECRET", the parameters will override the default value, if its set. If both environment variables and the parameters are empty, the client can only access the public API.

func (*Client) Authenticate added in v0.10.0

func (cl *Client) Authenticate() (err error)

Authenticate the current client's connection using token and secret keys.

func (*Client) MarketDepths added in v0.10.0

func (cl *Client) MarketDepths(pairName string) (depths *MarketDepths, err error)

MarketDepths fetch list of market's depth for specific pair.

func (*Client) MarketInfo added in v0.10.0

func (cl *Client) MarketInfo() (marketInfos []MarketInfo, err error)

MarketInfo return information about all the pair in the platform.

func (*Client) MarketPrices added in v0.10.0

func (cl *Client) MarketPrices() (marketPrices MarketPrices, err error)

MarketPrices return list of all latest pair's prices.

func (*Client) MarketSummaries added in v0.10.0

func (cl *Client) MarketSummaries() (summaries *MarketSummaries, err error)

MarketSummaries return the summaries (ticker) of all pairs.

func (*Client) MarketTicker added in v0.10.0

func (cl *Client) MarketTicker(pairName string) (tick *MarketTicker, err error)

MarketTicker return the ticker information on specific pair.

func (*Client) MarketTrades added in v0.10.0

func (cl *Client) MarketTrades(pairName string, offset, limit int64) (
	marketTrades *MarketTrades, err error,
)

MarketTrades return list of all completed trades in the market, specific to pair, grouped by ask and bid.

func (*Client) MarketTradesOpen added in v0.10.0

func (cl *Client) MarketTradesOpen(pairName string) (openTrades *TradesOpen, err error)

MarketTradesOpen return list of all open trades in the market, specific to pair's name, grouped by ask and bid.

func (*Client) TradeAsk

func (cl *Client) TradeAsk(treq *TradeRequest) (
	tres *TradeResponse, err error,
)

TradeAsk request to sell the coin on market with specific method, amount, and price. The method parameter define the mode of sell, its either "market" (default) or "limit". If the method is "market", it will only accept amount parameter, otherwise if the method is "limit", the amount and price must not be zero.

The pairName parameter define the coin and base assets to be traded, in the following format: "coin_base".

The amount parameter define the volume of coin we want to sell.

The price parameter define the number of base that we want to sell the amount of coin.

func (*Client) TradeBid

func (cl *Client) TradeBid(treq *TradeRequest) (
	tres *TradeResponse, err error,
)

TradeBid request to buy the coin on market with specific method, amount, and price. The method parameter define the mode of buy, its either "market" or "limit", default to "market" if its empty. If the method is "market", it will only accept amount parameter, otherwise if the method is "limit", the amount and price must not be zero.

The pairName parameter define the coin and base assets to be traded, in the following format: "coin_base".

The amount parameter define the volume of coin we want to buy.

The price parameter define the number of base that we want to buy the amount of coin.

func (*Client) TradeBulk added in v0.15.0

func (cl *Client) TradeBulk(tbReq *TradeBulk) (tbRes *TradeBulk, err error)

TradeBulk request trade with multiple orders and/or cancellation.

func (*Client) TradeCancel added in v0.10.0

func (cl *Client) TradeCancel(trade *Trade) (*Trade, error)

TradeCancel cancel the open trade using ID and pair information in Trade.

func (*Client) TradeCancelAll added in v0.10.0

func (cl *Client) TradeCancelAll() (canceled []Trade, err error)

TradeCancelAll cancel all user's open ask and bid orders.

func (*Client) TradeCancelAsk

func (cl *Client) TradeCancelAsk(pairName string, id int64) (
	trade *TradeResponse, err error,
)

TradeCancelAsk cancel the specific open sell by pair and ID.

func (*Client) TradeCancelBid

func (cl *Client) TradeCancelBid(pairName string, id int64) (
	trade *TradeResponse, err error,
)

TradeCancelBid cancel the specific open buy by pair and ID.

func (*Client) UserInfo added in v0.10.0

func (cl *Client) UserInfo() (user *User, err error)

UserInfo fetch the user information and balances.

This method require authentication.

func (*Client) UserOrderInfo added in v0.10.0

func (cl *Client) UserOrderInfo(pairName string, id int64) (
	trade *Trade, err error,
)

UserOrderInfo fetch a single user's trade information based on pair's name and trade ID.

This method require authentication.

func (*Client) UserOrdersClosed added in v0.10.0

func (cl *Client) UserOrdersClosed(pairName string, timeAfter, timeBefore int64) (
	trades []Trade, err error,
)

UserOrdersClosed fetch the user closed orders based on pair's name. The timeAfter and timeBefore parameters define a filter of records by range of submit time. If timeAfter is zero, its default to current timestamp. If timeBefore is zero, its default to timeAfter - 1 hour.

This method require authentication.

func (*Client) UserOrdersOpen added in v0.10.0

func (cl *Client) UserOrdersOpen(pairName string) (
	pairTradesOpen PairTradesOpen, err error,
)

UserOrdersOpen fetch the user open trades based on pair's name.

This method require authentication.

func (*Client) UserTrades added in v0.10.0

func (cl *Client) UserTrades(tp ListTradeParams) (trades []Trade, err error)

UserTrades list the user's trade history, ordered from latest to oldest one.

This method require authentication.

func (*Client) UserTransactions added in v0.10.0

func (cl *Client) UserTransactions(asset string, limit int64) (trans *AssetTransactions, err error)

UserTransactions fetch all user deposit and withdraw transaction history. If the asset name is not empty, it will fetch only the deposit and withdraw based on the asset name.

The limit parameter define the maximum record in result set.

This method require authentication.

func (*Client) UserWithdraw added in v0.10.0

func (cl *Client) UserWithdraw(
	requestID, asset, network, address, addressType, memo string,
	amount *big.Rat,
) (withdraw *WithdrawItem, err error)

UserWithdraw withdraw your assets into another address. This method accept withdrawing all coins except TEN.

This method require the "withdraw" permission, otherwise it will return a “No permission” error.

You also need to prepare a Callback URL, when setting up the API keys. Callback URL is an URL that our system will call to verify your withdrawal request. Various parameters will be sent to Callback URL so please make sure that this information is in your application. If all the data is correct, the callback URL should return HTTP response 200 with string “ok” (without quotes), and we will process the withdrawn in our system, otherwise the request will be fail.

type DepositItem added in v0.10.0

type DepositItem struct {
	Amount      *big.Rat `json:"amount"`
	FinalAmount *big.Rat `json:"final_amount"`
	Asset       string   `json:"asset,omitempty"`
	Status      string   `json:"status"`
	ID          int64    `json:"id"`
	SuccessTime int64    `json:"success_time"`
}

DepositItem contains the information of deposit.

type Depth added in v0.10.0

type Depth struct {
	Amount    *big.Rat `json:"amount"` // DEPRECATED: replaced with total_base and total_coin.
	Price     *big.Rat `json:"price"`
	TotalBase *big.Rat `json:"total_base"`
	TotalCoin *big.Rat `json:"total_coin"`
}

Depth contains total amount of remaining open orders grouped by price. Each depth is specific to pair.

type Environment

type Environment struct {
	// Address of API server, optional. It will default to DefaultAddress
	// constant on each package.
	Address string

	// Token, required, is the public part of API key.
	Token string

	// Secret, required, is the private part of API key.
	Secret string

	//
	// Debug define level of logging in our library.
	// debug value is set from environment variable "TOKENOMY_DEBUG".
	// TOKENOMY_DEBUG=1 is for logging in configuration.
	// TOKENOMY_DEBUG=2 is for logging input and output.
	//
	Debug int

	// IsInsecure, optional, allow self-signed certificate, should be use
	// for testing only.
	IsInsecure bool
}

Environment contains default and dynamic values that gathered from external resources, for example system environment variables.

func NewEnvironment

func NewEnvironment(token, secret string) (env *Environment)

NewEnvironment create and initialize environment.

If token and/or secret is empty it will set from environment variables TOKENOMY_TOKEN and TOKENOMY_SECRET.

type ListTradeParams added in v0.14.0

type ListTradeParams struct {
	Pair string

	// The Sort field define how the record ordered. Valid values is "asc"
	// for ascending or "desc" for descending.
	Sort string

	// The Offset field define the number of rows to be skipped.
	Offset int64

	// The Limit field define the maximum number of record fetched, if its not
	// set default to DefaultLimit.
	Limit int64

	// The IDAfter filter rows with ID greater or equal than its value.
	IDAfter int64

	// The IDBefore filter rows with ID less than or equal to its value.
	IDBefore int64

	// The TimeAfter filter rows with trade's time greater or equal than its
	// value.
	TimeAfter int64

	// Then TimeBefore filter rows with trade's time less or equal than its value.
	TimeBefore int64
}

ListTradeParams represent parameters for querying user's trades, closed, and open orders.

type MarketDepths added in v0.10.0

type MarketDepths struct {
	Pair string   `json:"pair"`
	Asks []*Depth `json:"asks"`
	Bids []*Depth `json:"bids"`
}

MarketDepths contains list of depth on open asks and bids.

func (*MarketDepths) GetAskByPrice added in v0.10.0

func (depths *MarketDepths) GetAskByPrice(price *big.Rat) (depth *Depth)

GetAskByPrice get the depth record from list of Asks by its price.

func (*MarketDepths) GetBidByPrice added in v0.10.0

func (depths *MarketDepths) GetBidByPrice(price *big.Rat) (depth *Depth)

GetBidByPrice get the depth record from list of Bids by its price.

type MarketInfo added in v0.10.0

type MarketInfo struct {
	PriceMinimum  *big.Rat `json:"price_minimum"`
	AmountMinimum *big.Rat `json:"amount_minimum"`

	ID        string `json:"id"`
	Symbol    string `json:"symbol"` // Deprecated, use Pair field.
	Pair      string `json:"pair"`
	CoinAsset string `json:"coin_asset"`
	BaseAsset string `json:"base_asset"`

	PricePrecision  int `json:"price_precision"`
	AmountPrecision int `json:"amount_precision"`

	IsActive bool `json:"is_active"`
}

MarketInfo contains the pair information to be consumed by public.

type MarketPrices added in v0.10.0

type MarketPrices map[string]*big.Rat

MarketPrices contains mapping between pair and its latest price in the market.

type MarketSummaries added in v0.10.0

type MarketSummaries struct {
	Prices        map[string]*big.Rat     `json:"prices"`
	Prices24h     map[string]*big.Rat     `json:"prices_24h"`
	Prices7d      map[string]*big.Rat     `json:"prices_7d"`
	PricesChanges map[string]*big.Rat     `json:"prices_changes"`
	Tickers       map[string]MarketTicker `json:"tickers"`
}

MarketSummaries contains all pair's latest tick value, last price, price changes, price past 24 hours ago, and price past 7 days ago.

type MarketTicker added in v0.11.0

type MarketTicker struct {
	// LowestAskPrice contains the lowest sell price in open orders.
	LowestAskPrice *big.Rat `json:"ask"`

	// HighestBidPrice contains the highest buy price in open orders.
	HighestBidPrice *big.Rat `json:"bid"`

	// HighestPrice24H contains the highest price in closed trades since
	// the last 24 hours.
	HighestPrice24H *big.Rat `json:"high"`

	// LowestPrice24H contains the lowest price in closed trades since the
	// last 24 hours.
	LowestPrice24H *big.Rat `json:"low"`

	// LastPrice contains the last traded price.
	LastPrice *big.Rat `json:"last_price"`

	// VolumeBase24H contains the total base asset has been traded since
	// the last 24 hours.
	VolumeBase24H *big.Rat `json:"volume_base"`

	// VolumeCoin24H contains the total coin asset has been traded since
	// the last 24 hours.
	VolumeCoin24H *big.Rat `json:"volume_coin"`

	PairName string `json:"pair"`
}

MarketTicker contains the pair tick information in the market.

type MarketTrades added in v0.7.0

type MarketTrades struct {
	Asks []Trade `json:"asks"`
	Bids []Trade `json:"bids"`
}

MarketTrades contains list of closed trade grouped by asks and bids.

type OrdersClosedHandler added in v0.10.0

type OrdersClosedHandler func(trade *Trade)

OrdersClosedHandler define a callback when receiving order closed broadcast from server.

type PairTradesOpen added in v0.10.0

type PairTradesOpen map[string]TradesOpen

PairTradesOpen contains mapping of pair and their open trades information.

type PublicSubscription added in v0.9.0

type PublicSubscription struct {
	Depths    []string `json:"depths"`
	Ticker    []string `json:"ticker"`
	Trades    []string `json:"trades"`
	Summaries bool     `json:"summaries"`
}

PublicSubscription contains list of pairs that currently subscribed for each topic: "depths", "ticker", and "trades".

type Response added in v0.10.0

type Response http.EndpointResponse

Response contains the HTTP response from server.

type Trade added in v0.2.0

type Trade struct {
	Price *big.Rat `json:"price,omitempty"`

	BaseAmount *big.Rat `json:"base_amount,omitempty"`
	BaseFilled *big.Rat `json:"base_filled,omitempty"`
	BaseRemain *big.Rat `json:"base_remain,omitempty"`

	CoinAmount *big.Rat `json:"coin_amount,omitempty"`
	CoinFilled *big.Rat `json:"coin_filled,omitempty"`
	CoinRemain *big.Rat `json:"coin_remain,omitempty"`

	Pair   string `json:"pair,omitempty"`
	Type   string `json:"type,omitempty"`   // Its either "sell" or "buy".
	Method string `json:"method,omitempty"` // Its either "limit" or "market".
	Status string `json:"status,omitempty"` // Status for closed trade, its either "cancelled" or "filled".

	BaseAsset string `json:"base_asset,omitempty"`
	CoinAsset string `json:"coin_asset,omitempty"`

	ID         int64 `json:"id,omitempty"`
	SubmitTime int64 `json:"submit_time,omitempty"`
	FinishTime int64 `json:"finish_time,omitempty"`
}

Trade contains information about trade bid or ask, either open or closed.

type TradeBulk added in v0.15.0

type TradeBulk struct {
	Pair      string           `json:"pair"`
	Orders    []*BulkOrderItem `json:"orders"`
	Cancel    []*BulkOrderItem `json:"cancel"`
	Timestamp int64            `json:"timestamp"`
}

TradeBulk contains the request for bulk trading.

type TradeRequest added in v0.8.0

type TradeRequest struct {
	Price  *big.Rat `json:"price"`
	Amount *big.Rat `json:"amount"`

	// Type of trade, its either "buy" or "sell".
	Type string `json:"type"`

	// Method of trading, its either "limit" or "market".
	// Default to "limit" if its empty.
	Method string `json:"method,omitempty"`

	// Pair name using "<coin>_<base>" format.
	Pair string `json:"pair"`

	// TimeInForce parameter only applicable if Method is "limit".
	// This option may change the behaviour of order "limit" processed by
	// broker.
	// Currently, the valid values are empty "" (default) or "FOK"
	// (fill-or-kill).
	//
	// If its empty, the order request processed normally as "limit"
	// request.
	//
	// If its "FOK", the order will be success only if only all of
	// requested amount is fulfilled, otherwise it will return as an error
	// ErrTradeFillOrKill.
	TimeInForce string `json:"time_in_force,omitempty"`

	// IsPostOnly parameter only applicable if Method is "limit".
	// If its true, the order will be success if only if no matching
	// trades happened, otherwise it will return an error.
	IsPostOnly bool `json:"post_only,omitempty"`
}

TradeRequest contains parameters for trading.

func (*TradeRequest) Pack added in v0.8.0

func (treq *TradeRequest) Pack() (
	params url.Values, wsparams *WebSocketParams, err error,
)

Pack the TradeRequest object to be send by REST and/or WebSocket client.

type TradeResponse

type TradeResponse struct {
	Order *Trade `json:"order"`
	User  User   `json:"user"`
	// Trades contains matched orders, only available on v2.
	Trades []Trade `json:"trades,omitempty"`
}

TradeResponse contains the recorded order information in the market and part of full amount of order that have been completed (matched) as a list of trades.

type TradesOpen added in v0.10.0

type TradesOpen struct {
	Asks []Trade `json:"asks"`
	Bids []Trade `json:"bids"`
}

TradesOpen contains the open asks and bids in the market place.

type User

type User struct {
	*UserAssets

	Notifications *UserNotifications `json:"notifications,omitempty"`
	Wallets       UserWallets        `json:"wallets,omitempty"`
	Email         string             `json:"email"`
	FullName      string             `json:"full_name"`
	ID            int64              `json:"id"`
}

User contains user information including profile, balances, and frozen balances.

type UserAssets

type UserAssets struct {
	Balances          map[string]*big.Rat `json:"balances,omitempty"`
	FrozenBalances    map[string]*big.Rat `json:"frozen_balances,omitempty"`
	BalancesInt       map[string]int64    `json:"-"`
	FrozenBalancesInt map[string]int64    `json:"-"`
}

UserAssets contains mapping between asset name and its value.

func NewUserAssets

func NewUserAssets() (assets *UserAssets)

NewUserAssets create and initialize all fields in UserAssets.

func (*UserAssets) Copy

func (assets *UserAssets) Copy() *UserAssets

Copy create a new copy of assets.

type UserNotifications added in v0.4.2

type UserNotifications struct {
	UserID                 int64 `json:"-"`
	Deposit                bool  `json:"deposit"`
	Login                  bool  `json:"login"`
	Withdraw               bool  `json:"withdraw"`
	Order                  bool  `json:"order"`
	FixedDeposit           bool  `json:"fixed_deposit"`
	FixedDepositNearMature bool  `json:"fixed_deposit_near_mature"`
	FixedDepositReward     bool  `json:"fixed_deposit_reward"`
	DualCurrencyInvest     bool  `json:"dual_currency_invest"`
	DualCurrencyReward     bool  `json:"dual_currency_reward"`
	Staking                bool  `json:"staking"`
	Unstaking              bool  `json:"unstaking"`
	StakingReward          bool  `json:"staking_reward"`
	Created                int64 `json:"-"`
	Updated                int64 `json:"-"`
}

UserNotifications contains user's status of notification in the system. If its true, user will receive notification (mostly by email), otherwise no notification will be send to user.

type UserWallets

type UserWallets map[string]string

UserWallets represent mapping between asset name and its wallet address.

type WebSocketParams added in v0.8.0

type WebSocketParams struct {
	Address     string `json:"address,omitempty"`
	AddressType string `json:"address_type,omitempty"`
	Asset       string `json:"asset,omitempty"`
	IDSortBy    string `json:"id_sort_by,omitempty"`
	Memo        string `json:"memo,omitempty"`
	Network     string `json:"network,omitempty"`
	RequestID   string `json:"request_id,omitempty"`

	TradeRequest
	PublicSubscription

	IDAfter  int64 `json:"id_after,omitempty"`
	IDBefore int64 `json:"id_before,omitempty"`

	TimeAfter  int64 `json:"time_after,omitempty"`
	TimeBefore int64 `json:"time_before,omitempty"`

	TradeID int64 `json:"trade_id,omitempty"`

	Limit  int64 `json:"limit,omitempty"`
	Offset int64 `json:"offset,omitempty"`
}

WebSocketParams contains the request parameters for WebSocket client.

func (*WebSocketParams) Pack added in v0.8.0

func (wsparams *WebSocketParams) Pack() (b []byte, err error)

Pack the WebSocket parameters as JSON.

func (*WebSocketParams) Unpack added in v0.8.0

func (wsparams *WebSocketParams) Unpack(b []byte) (err error)

Unpack the parameters from JSON bytes.

type WebSocketPrivate added in v0.10.0

type WebSocketPrivate struct {

	// HandleOrdersClosed define the callback that will be called
	// automatically by client when one of the user's orders closed in the
	// market.
	HandleOrdersClosed OrdersClosedHandler
	// contains filtered or unexported fields
}

WebSocketPrivate define the private WebSocket client for APIv2.

func NewWebSocketPrivate added in v0.10.0

func NewWebSocketPrivate(env *Environment) (
	cl *WebSocketPrivate, err error,
)

NewWebSocketPrivate create and initialize new WebSocket connection to private endpoint.

func (*WebSocketPrivate) Close added in v0.10.0

func (cl *WebSocketPrivate) Close() error

Close the connection and release all the resource.

func (*WebSocketPrivate) TradeAsk added in v0.10.0

func (cl *WebSocketPrivate) TradeAsk(treq *TradeRequest) (
	trade *TradeResponse, err error,
)

TradeAsk request to sell the coin on market with specific method, amount, and price. The method parameter define the mode of sell, its either "market" (default) or "limit". If the method is "market", it will only accept amount parameter, otherwise if the method is "limit", the amount and price must not be zero.

The pairName parameter define the coin and base assets to be traded, in the following format: "coin_base".

The amount parameter define the volume of coin we want to sell.

The price parameter define the number of base that we want to sell the amount of coin.

func (*WebSocketPrivate) TradeBid added in v0.10.0

func (cl *WebSocketPrivate) TradeBid(treq *TradeRequest) (
	trade *TradeResponse, err error,
)

TradeBid request to buy the coin on market with specific method, amount, and price. The method parameter define the mode of buy, its either "market" (default) or "limit". If the method is "market", it will only accept amount parameter, otherwise if the method is "limit", the amount and price must not be zero.

The pairName parameter define the coin and base assets to be traded, in the following format: "coin_base".

The amount parameter define the volume of coin we want to buy.

The price parameter define the number of base that we want to buy the amount of coin.

func (*WebSocketPrivate) TradeCancel added in v0.10.0

func (cl *WebSocketPrivate) TradeCancel(trade *Trade) (
	*Trade, error,
)

TradeCancel cancel the open trade using ID and pair information in Trade.

func (*WebSocketPrivate) TradeCancelAll added in v0.10.0

func (cl *WebSocketPrivate) TradeCancelAll() (
	trades []Trade, err error,
)

TradeCancelAll cancel all user's open ask and bid orders.

func (*WebSocketPrivate) TradeCancelAsk added in v0.10.0

func (cl *WebSocketPrivate) TradeCancelAsk(pairName string, id int64) (
	trade *TradeResponse, err error,
)

TradeCancelAsk cancel the specific open sell by pair and ID.

func (*WebSocketPrivate) TradeCancelBid added in v0.10.0

func (cl *WebSocketPrivate) TradeCancelBid(pairName string, id int64) (
	trade *TradeResponse, err error,
)

TradeCancelBid cancel the specific open buy by pair and ID.

func (*WebSocketPrivate) UserInfo added in v0.10.0

func (cl *WebSocketPrivate) UserInfo() (user *User, err error)

UserInfo fetch the user information and balances.

func (*WebSocketPrivate) UserOrderInfo added in v0.10.0

func (cl *WebSocketPrivate) UserOrderInfo(pairName string, id int64) (
	trade *Trade, err error,
)

UserOrderInfo fetch a single user's trade information based on pair's name and trade ID.

func (*WebSocketPrivate) UserOrdersOpen added in v0.10.0

func (cl *WebSocketPrivate) UserOrdersOpen(pairName string) (
	pairTradesOpen PairTradesOpen, err error,
)

UserOrdersOpen fetch the user open orders based on pair's name.

type WebSocketPublic added in v0.10.0

type WebSocketPublic struct {

	// NotifTrades is a channel that will receive public order books
	// (open, closed, cancelled order) after calling SubscribeTrades
	// method.
	NotifTrades <-chan Trade
	NotifDepths <-chan MarketDepths
	// contains filtered or unexported fields
}

WebSocketPublic define a WebSocket client for public APIs.

func NewWebSocketPublic added in v0.10.0

func NewWebSocketPublic(env *Environment) (
	cl *WebSocketPublic, err error,
)

NewWebSocketPublic create new WebSocket connection to public APIs.

func (*WebSocketPublic) Close added in v0.10.0

func (cl *WebSocketPublic) Close() error

Close the connection and release all the resource.

func (*WebSocketPublic) MarketDepths added in v0.10.0

func (cl *WebSocketPublic) MarketDepths(pair string) (
	depths *MarketDepths, err error,
)

MarketDepths fetch list of market's depth for specific pair.

func (*WebSocketPublic) MarketPrices added in v0.11.0

func (cl *WebSocketPublic) MarketPrices() (mprices MarketPrices, err error)

MarketPrices fetch the latest pair price from the market.

func (*WebSocketPublic) MarketSummaries added in v0.14.0

func (cl *WebSocketPublic) MarketSummaries() (summaries *MarketSummaries, err error)

MarketSummaries get the market summaries.

func (*WebSocketPublic) MarketTicker added in v0.10.0

func (cl *WebSocketPublic) MarketTicker(pair string) (tick *MarketTicker, err error)

MarketTicker return the ticker information on specific pair.

func (*WebSocketPublic) MarketTrades added in v0.10.0

func (cl *WebSocketPublic) MarketTrades(pair string, offset, limit int64) (
	marketTrades *MarketTrades, err error,
)

MarketTrades return list of all completed trades in the market, specific to pair, grouped by ask and bid.

func (*WebSocketPublic) SubscribeDepths added in v0.10.0

func (cl *WebSocketPublic) SubscribeDepths(pairNames []string) (
	*PublicSubscription, error,
)

SubscribeDepths subscribe to changes on market depths based on list of pair names.

Multiple calls on this method will not clear previously subscribed pairs. For example, if the first call subscribed to pair "X" and the second call subscribed to pair "Y", the client has two subscription: "X" and "Y", NOT "Y".

func (*WebSocketPublic) SubscribeTrades added in v0.10.0

func (cl *WebSocketPublic) SubscribeTrades(pairNames []string) (
	*PublicSubscription, error,
)

SubscribeTrades subscribe to changes on public order books.

Multiple calls on this method will not clear previously subscribed pairs. For example, if the first call subscribed to pair "X" and the second call subscribed to pair "Y", the client has two subscription: "X" and "Y", NOT "Y".

The order books (open, closed, and/or cancelled) can be retrieved from NotifTrades field.

func (*WebSocketPublic) Subscription added in v0.10.0

func (cl *WebSocketPublic) Subscription() (*PublicSubscription, error)

Subscription return the list and status of subscription.

func (*WebSocketPublic) UnsubscribeDepths added in v0.10.0

func (cl *WebSocketPublic) UnsubscribeDepths(pairNames []string) (
	*PublicSubscription, error,
)

UnsubscribeDepths stop receiving broadcast notification on topic "depths" on specific pairs.

If parameter is empty, it will unsubscribe all registered pairs.

On success it will return the latest subscription.

func (*WebSocketPublic) UnsubscribeTrades added in v0.10.0

func (cl *WebSocketPublic) UnsubscribeTrades(pairNames []string) (
	*PublicSubscription, error,
)

UnsubscribeTrades stop receiving broadcast notification on topic "trades" on specific pairs. If parameter is empty, it will unsubscribe all registered pairs.

On success it will return the latest subscription.

type WithdrawItem added in v0.10.0

type WithdrawItem struct {
	Amount      *big.Rat `json:"amount,omitempty"`
	Fee         *big.Rat `json:"fee,omitempty"`
	FinalAmount *big.Rat `json:"final_amount,omitempty"`

	RequestID   string `json:"request_id,omitempty"`
	RequesterIP string `json:"requester_ip,omitempty"`
	Asset       string `json:"asset,omitempty"`
	Network     string `json:"network,omitempty"`
	Status      string `json:"status,omitempty"`
	Address     string `json:"address,omitempty"`
	AddressType string `json:"address_type,omitempty"`
	Memo        string `json:"memo,omitempty"`

	ID          int64 `json:"id,omitempty"`
	SubmitTime  int64 `json:"submit_time,omitempty"`
	SuccessTime int64 `json:"success_time,omitempty"`
}

WithdrawItem contains the information of single withdraw transaction.

Jump to

Keyboard shortcuts

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