Documentation
¶
Overview ¶
Package klingex provides the official Go SDK for the KlingEx Exchange API.
Index ¶
- Constants
- type AddLiquidityRequest
- type AddLiquidityResult
- type Asset
- type AssetInfo
- type AssetStatusDetail
- type AuthenticationError
- type BulkCreateGiftCodeRequest
- type BulkCreateGiftCodeResponse
- type CancelAllOrdersResponse
- type CancelOrderParams
- type CancelOrderResponse
- type Client
- type ClientOption
- type CreateGiftCodeRequest
- type CreateGiftCodeResponse
- type CreateInvoiceRequest
- type CreateInvoiceResponse
- type Error
- type GetInvoicesOptions
- type GetOHLCVOptions
- type GetOrderBookOptions
- type GetOrdersHistoryOptions
- type GetSparklinesOptions
- type GetStatsOptions
- type GiftCodesService
- type HTTPClient
- func (c *HTTPClient) Delete(path string, params map[string]string, authenticated bool) ([]byte, error)
- func (c *HTTPClient) Get(path string, params map[string]string, authenticated bool) ([]byte, error)
- func (c *HTTPClient) Post(path string, body interface{}, authenticated bool) ([]byte, error)
- func (c *HTTPClient) Put(path string, body interface{}, authenticated bool) ([]byte, error)
- func (c *HTTPClient) Request(method, path string, params map[string]string, body interface{}, ...) ([]byte, error)
- type HTTPClientOption
- type Invoice
- type InvoiceDenomination
- type InvoiceDenominationRequest
- type InvoiceFeeStats
- type InvoiceListResponse
- type InvoicePayment
- type InvoicePaymentOption
- type InvoiceStatusResponse
- type InvoiceSummary
- type InvoicesService
- func (s *InvoicesService) CancelInvoice(invoiceID string) error
- func (s *InvoicesService) CreateInvoice(req CreateInvoiceRequest) (*Invoice, error)
- func (s *InvoicesService) GetFeeStats() (*InvoiceFeeStats, error)
- func (s *InvoicesService) GetInvoice(invoiceID string) (*Invoice, error)
- func (s *InvoicesService) GetInvoices(opts *GetInvoicesOptions) (*InvoiceListResponse, error)
- func (s *InvoicesService) GetPdf(invoiceID string) ([]byte, error)
- func (s *InvoicesService) GetPublic(invoiceID string) (*PublicInvoice, error)
- func (s *InvoicesService) GetStatus(invoiceID string) (*InvoiceStatusResponse, error)
- type ListPoolOptions
- type Market
- type MarketInfo
- type MarketsService
- func (s *MarketsService) GetAssetInfo(assetID int) (*AssetInfo, error)
- func (s *MarketsService) GetAssetInfoBySymbol(symbol string) (*AssetInfo, error)
- func (s *MarketsService) GetAssets() ([]Asset, error)
- func (s *MarketsService) GetMarketInfo(baseSymbol, quoteSymbol string) (*MarketInfo, error)
- func (s *MarketsService) GetMarkets() ([]Market, error)
- func (s *MarketsService) GetOHLCV(marketID int, opts *GetOHLCVOptions) ([]OHLCV, error)
- func (s *MarketsService) GetOrderBook(marketID int, opts *GetOrderBookOptions) (*OrderBook, error)
- func (s *MarketsService) GetSparklines(opts *GetSparklinesOptions) (*SparklinesResponse, error)
- func (s *MarketsService) GetTicker(tickerID string) (*Ticker, error)
- func (s *MarketsService) GetTickers() ([]Ticker, error)
- func (s *MarketsService) GetTrades(marketID int) ([]Trade, error)
- type MessageHandler
- type MiningPoolBlock
- type MiningPoolBlocksResponse
- type MiningPoolConfig
- type MiningPoolLeaderboard
- type MiningPoolLeaderboardEntry
- type MiningPoolPayout
- type MiningPoolPayoutsResponse
- type MiningPoolReward
- type MiningPoolRewardsResponse
- type MiningPoolService
- func (s *MiningPoolService) GetBlocks(opts *ListPoolOptions) (*MiningPoolBlocksResponse, error)
- func (s *MiningPoolService) GetConfigs() ([]MiningPoolConfig, error)
- func (s *MiningPoolService) GetLeaderboard(symbol, period string) (*MiningPoolLeaderboard, error)
- func (s *MiningPoolService) GetMyPayouts(opts *ListPoolOptions) (*MiningPoolPayoutsResponse, error)
- func (s *MiningPoolService) GetMyRewards(opts *ListPoolOptions) (*MiningPoolRewardsResponse, error)
- func (s *MiningPoolService) GetMyWorkers(symbol string) (*MiningPoolWorkersResponse, error)
- func (s *MiningPoolService) GetStats(opts GetStatsOptions) (*MiningPoolStats, error)
- type MiningPoolStats
- type MiningPoolStatsCurrent
- type MiningPoolStatsSnapshot
- type MiningPoolWorker
- type MiningPoolWorkersResponse
- type OHLCV
- type Order
- type OrderBook
- type OrderHistory
- type OrderSide
- type OrderStatus
- type OrdersHistoryResponse
- type OrdersService
- func (s *OrdersService) CancelAllOrders(tradingPairID int) (*CancelAllOrdersResponse, error)
- func (s *OrdersService) CancelOrder(orderID string, tradingPairID int) (*CancelOrderResponse, error)
- func (s *OrdersService) GetOpenOrders() ([]Order, error)
- func (s *OrdersService) GetOrder(orderID string) (*Order, error)
- func (s *OrdersService) GetOrdersByMarket(tradingPairID int) ([]Order, error)
- func (s *OrdersService) GetOrdersHistory(opts *GetOrdersHistoryOptions) (*OrdersHistoryResponse, error)
- func (s *OrdersService) GetUserOrders() ([]Order, error)
- func (s *OrdersService) SubmitOrder(symbol string, tradingPairID int, side OrderSide, quantity string, ...) (*SubmitOrderResponse, error)
- type PlaceOrderParams
- type PoolDetail
- type PoolListItem
- type PoolsService
- func (s *PoolsService) AddLiquidity(req AddLiquidityRequest) (*AddLiquidityResult, error)
- func (s *PoolsService) Get(poolID int) (*PoolDetail, error)
- func (s *PoolsService) List() ([]PoolListItem, error)
- func (s *PoolsService) PositionHistory(poolID, days int) (*PositionHistoryResponse, error)
- func (s *PoolsService) Positions() ([]UserPosition, error)
- func (s *PoolsService) RemoveLiquidity(req RemoveLiquidityRequest) (*RemoveLiquidityResult, error)
- type PositionHistoryResponse
- type PositionHistorySnapshot
- type PublicInvoice
- type RateLimitError
- type RemoveLiquidityRequest
- type RemoveLiquidityResult
- type SparklinePoint
- type SparklinesResponse
- type StatusCounts
- type SubmitOrderResponse
- type SubmitWithdrawalRequest
- type SubmitWithdrawalResponse
- type Ticker
- type Trade
- type UserBalance
- type UserOrdersResponse
- type UserPosition
- type ValidationError
- type WalletAssetSync
- type WalletChainGroup
- type WalletService
- type WalletStatus
- type WalletSyncInfo
- type WalletsService
- type WebSocket
- func (ws *WebSocket) CancelOrder(ctx context.Context, params CancelOrderParams) (*WsCancelResult, error)
- func (ws *WebSocket) Close() error
- func (ws *WebSocket) Connect() error
- func (ws *WebSocket) Done() <-chan struct{}
- func (ws *WebSocket) On(channel string, handler MessageHandler)
- func (ws *WebSocket) Ping() error
- func (ws *WebSocket) PlaceOrder(ctx context.Context, params PlaceOrderParams) (*WsOrderResult, error)
- func (ws *WebSocket) SubscribeAccountEvents(handler MessageHandler) error
- func (ws *WebSocket) SubscribeInvoice(invoiceID string, handler MessageHandler) error
- func (ws *WebSocket) SubscribeMarket(market string, handler MessageHandler) error
- func (ws *WebSocket) SubscribeOHLCV(marketID int, timeframe string, handler MessageHandler) error
- func (ws *WebSocket) SubscribeOrderBook(market string, handler MessageHandler) error
- func (ws *WebSocket) SubscribeQR(sessionToken string, handler MessageHandler) error
- func (ws *WebSocket) SubscribeTicker(market string, handler MessageHandler) error
- func (ws *WebSocket) SubscribeTrades(market string, handler MessageHandler) error
- func (ws *WebSocket) SubscribeUserBalance(handler MessageHandler) error
- func (ws *WebSocket) SubscribeUserChannel(channel string, handler MessageHandler) error
- func (ws *WebSocket) SubscribeUserDeposits(handler MessageHandler) error
- func (ws *WebSocket) SubscribeUserNotifications(handler MessageHandler) error
- func (ws *WebSocket) SubscribeUserOrders(handler MessageHandler) error
- func (ws *WebSocket) SubscribeUserTrades(handler MessageHandler) error
- func (ws *WebSocket) SubscribeUserTransfers(handler MessageHandler) error
- func (ws *WebSocket) SubscribeUserWithdrawals(handler MessageHandler) error
- func (ws *WebSocket) UnsubscribeInvoice(invoiceID string) error
- func (ws *WebSocket) UnsubscribeMarket(market string) error
- func (ws *WebSocket) UnsubscribeOHLCV(marketID int, timeframe string) error
- func (ws *WebSocket) UnsubscribeQR(sessionToken string) error
- func (ws *WebSocket) UnsubscribeUserChannel(channel string) error
- type WebSocketMessage
- type WebSocketOption
- type WithdrawalsService
- type WsAuthResult
- type WsCancelResult
- type WsOrderResult
Constants ¶
const ( UserChannelBalance = "balance" UserChannelOrders = "orders" UserChannelTransfer = "transfer" UserChannelDeposits = "deposits" UserChannelWithdrawals = "withdrawals" UserChannelNotifications = "notifications" UserChannelTrades = "trades" UserChannelAccount = "account" )
User channel names accepted by the WebSocket server. These map 1:1 to the `type` field in {"action":"subscribe","type":"..."} envelopes.
const (
MarketChannelMarkets = "markets" // markets-list updates
)
Special public market channels.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type AddLiquidityRequest ¶
type AddLiquidityRequest struct {
PoolID int `json:"pool_id"`
BaseAmountMax string `json:"base_amount_max"` // max base willing to deposit
QuoteAmountMax string `json:"quote_amount_max"` // max quote willing to deposit
MinLPTokens string `json:"min_lp_tokens"` // slippage protection
}
AddLiquidityRequest is the user-facing request to add liquidity.
type AddLiquidityResult ¶
type AddLiquidityResult struct {
PoolID int `json:"pool_id"`
BaseUsed string `json:"base_used"`
QuoteUsed string `json:"quote_used"`
LPTokensMinted string `json:"lp_tokens_minted"`
IsBootstrap bool `json:"is_bootstrap"`
TotalLPSupply string `json:"total_lp_supply"`
}
AddLiquidityResult is returned after a successful add-liquidity operation.
type Asset ¶
type Asset struct {
Symbol string `json:"symbol"`
Name string `json:"name"`
Decimals int `json:"decimals"`
IsCrypto bool `json:"is_crypto"`
ChainType *string `json:"chain_type,omitempty"`
ChainID *int `json:"chain_id,omitempty"`
EVMNetwork *string `json:"evm_network,omitempty"`
ContractAddress *string `json:"contract_address,omitempty"`
IsActive bool `json:"is_active"`
WithdrawalEnabled bool `json:"withdrawal_enabled"`
Website *string `json:"website,omitempty"`
TwitterURL *string `json:"twitter_url,omitempty"`
DiscordURL *string `json:"discord_url,omitempty"`
TelegramURL *string `json:"telegram_url,omitempty"`
Description *string `json:"description,omitempty"`
}
Asset represents basic asset information returned by GET /api/assets. Note: the list endpoint does not include numeric ID, withdrawal_fee, etc. Use AssetInfo (GET /api/asset-info/:id) for the full per-asset detail.
type AssetInfo ¶
type AssetInfo struct {
Symbol string `json:"symbol"`
Name string `json:"name"`
Decimals int `json:"decimals"`
IsCrypto bool `json:"is_crypto"`
ChainType *string `json:"chain_type,omitempty"`
ChainID *int `json:"chain_id,omitempty"`
EVMNetwork *string `json:"evm_network,omitempty"`
ContractAddress *string `json:"contract_address,omitempty"`
ExplorerURL *string `json:"explorer_url,omitempty"`
IsActive bool `json:"is_active"`
WithdrawalEnabled bool `json:"withdrawal_enabled"`
MinDeposit string `json:"min_deposit"`
MinWithdrawal string `json:"min_withdrawal"`
WithdrawalFee string `json:"withdrawal_fee"`
DepositFee string `json:"deposit_fee"`
DepositFeeThreshold string `json:"deposit_fee_threshold"`
Website *string `json:"website,omitempty"`
TwitterURL *string `json:"twitter_url,omitempty"`
DiscordURL *string `json:"discord_url,omitempty"`
TelegramURL *string `json:"telegram_url,omitempty"`
Description *string `json:"description,omitempty"`
}
AssetInfo is the detailed asset view returned by GET /api/asset-info/:id and GET /api/asset-info/symbol/:symbol.
type AssetStatusDetail ¶
type AssetStatusDetail struct {
AssetID int `json:"asset_id"`
Symbol string `json:"symbol"`
Name string `json:"name"`
ChainType *string `json:"chain_type,omitempty"`
NetworkName string `json:"network_name"`
ChainID *int `json:"chain_id,omitempty"`
ContractAddress *string `json:"contract_address,omitempty"`
ExplorerURL *string `json:"explorer_url,omitempty"`
IsActive *bool `json:"is_active,omitempty"`
WithdrawalEnabled bool `json:"withdrawal_enabled"`
DepositConfirmsRequired int `json:"deposit_confirms_required"`
SyncInfo WalletSyncInfo `json:"sync_info"`
}
AssetStatusDetail is the response from GET /api/wallets/status/:assetId.
type AuthenticationError ¶
AuthenticationError represents an authentication failure
func NewAuthenticationError ¶
func NewAuthenticationError(message string) *AuthenticationError
NewAuthenticationError creates a new authentication error
func (*AuthenticationError) Error ¶
func (e *AuthenticationError) Error() string
type BulkCreateGiftCodeRequest ¶
type BulkCreateGiftCodeRequest struct {
AssetID int `json:"asset_id"`
AmountPerCode string `json:"amount_per_code"`
Count int `json:"count"`
Message string `json:"message,omitempty"`
HideAmount bool `json:"hide_amount,omitempty"`
ExpiresInDays *int `json:"expires_in_days,omitempty"`
}
BulkCreateGiftCodeRequest is the POST /api/gift-codes/bulk body.
Count must be 2..100. AmountPerCode is in the asset's base units.
type BulkCreateGiftCodeResponse ¶
type BulkCreateGiftCodeResponse struct {
GiftCodes []CreateGiftCodeResponse `json:"gift_codes"`
TotalAmount string `json:"total_amount"`
TotalFormatted string `json:"total_amount_formatted"`
Count int `json:"count"`
NewBalance string `json:"new_balance"`
}
BulkCreateGiftCodeResponse is the response from POST /api/gift-codes/bulk.
type CancelAllOrdersResponse ¶
type CancelAllOrdersResponse struct {
Message string `json:"message"`
CancelledCount int `json:"cancelledCount"`
TotalOrders int `json:"totalOrders"`
CancelledOrderIDs []string `json:"cancelledOrderIds"`
TotalReleasedBalance string `json:"totalReleasedBalance"`
}
CancelAllOrdersResponse is the response from POST /api/cancel-all-orders.
type CancelOrderParams ¶
type CancelOrderParams struct {
OrderID string `json:"orderId"`
TradingPairID int `json:"tradingPairId"`
}
CancelOrderParams contains parameters for cancelling an order via WebSocket.
type CancelOrderResponse ¶
type CancelOrderResponse struct {
Message string `json:"message"`
ReleasedBalance string `json:"released_balance"`
}
CancelOrderResponse is the response from POST /api/cancel-order.
type Client ¶
type Client struct {
Markets *MarketsService
Orders *OrdersService
Wallet *WalletService
Wallets *WalletsService
Invoices *InvoicesService
Withdrawals *WithdrawalsService
Pools *PoolsService
MiningPool *MiningPoolService
GiftCodes *GiftCodesService
// contains filtered or unexported fields
}
Client is the main KlingEx API client.
func NewClient ¶
func NewClient(apiKey string, opts ...ClientOption) *Client
NewClient creates a new KlingEx client.
For public endpoints (markets, tickers, pool stats, etc.) the API key is optional. For authenticated endpoints (orders, wallet, withdrawals, invoices, gift codes, mining-pool user data, LP positions) supply an API key with the appropriate scope.
Example:
// Public API only
client := klingex.NewClient("")
markets, _ := client.Markets.GetMarkets()
// Authenticated API
client := klingex.NewClient("your_api_key")
balances, _ := client.Wallet.GetUserBalances()
type ClientOption ¶
type ClientOption func(*Client)
ClientOption configures the client.
func WithClientBaseURL ¶
func WithClientBaseURL(url string) ClientOption
WithClientBaseURL sets a custom base URL.
func WithClientTimeout ¶
func WithClientTimeout(timeout time.Duration) ClientOption
WithClientTimeout sets the request timeout.
type CreateGiftCodeRequest ¶
type CreateGiftCodeRequest struct {
AssetID int `json:"asset_id"`
Amount string `json:"amount"`
Message string `json:"message,omitempty"`
HideAmount bool `json:"hide_amount,omitempty"`
ExpiresInDays *int `json:"expires_in_days,omitempty"`
}
CreateGiftCodeRequest is the POST /api/gift-codes body.
Amount is the asset's base-unit string (validated server-side against the per-asset min/max gift-code limits). Message ≤ 500 chars. ExpiresInDays must be 1..365 when provided.
type CreateGiftCodeResponse ¶
type CreateGiftCodeResponse struct {
GiftCodeID string `json:"gift_code_id"`
Code string `json:"code"`
FormattedCode string `json:"formatted_code"`
AssetID int `json:"asset_id"`
AssetSymbol string `json:"asset_symbol"`
AssetDecimals int `json:"asset_decimals"`
Amount string `json:"amount"`
AmountFormatted string `json:"amount_formatted"`
HideAmount bool `json:"hide_amount"`
Message string `json:"message,omitempty"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
NewBalance string `json:"new_balance"`
}
CreateGiftCodeResponse is the per-code response payload.
type CreateInvoiceRequest ¶
type CreateInvoiceRequest struct {
ExternalID string `json:"external_id,omitempty"`
Denomination InvoiceDenominationRequest `json:"denomination"`
AcceptedCoins []string `json:"accepted_coins"` // e.g. ["BTC","ETH","USDT"]
ExpiresInMinutes int `json:"expires_in_minutes,omitempty"`
Description string `json:"description,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
BuyerEmail string `json:"buyer_email,omitempty"`
PaymentTolerance int `json:"payment_tolerance,omitempty"` // 90..100, default 100
}
CreateInvoiceRequest is the POST /api/invoices body.
type CreateInvoiceResponse ¶
CreateInvoiceResponse wraps the {message, data} envelope returned by POST /api/invoices.
type GetInvoicesOptions ¶
type GetInvoicesOptions struct {
Status string // pending | paid | overpaid | underpaid | expired | cancelled
ExternalID string
Page int
PageSize int // 1..100, default 20
}
GetInvoicesOptions filters the list-invoices request.
type GetOHLCVOptions ¶
type GetOHLCVOptions struct {
Timeframe string // 1m, 5m, 15m, 1h, 4h, 1d, etc.
Limit int // 1..10000
StartDate time.Time // optional
EndDate time.Time // optional
}
GetOHLCVOptions configures the OHLCV query. StartDate/EndDate are RFC3339 timestamps (UTC). Limit is 1..10000.
type GetOrderBookOptions ¶
type GetOrderBookOptions struct {
// IsCmc requests the CMC-format orderbook keyed by ticker_id. The
// MarketsService.GetOrderBook(marketID, ...) entrypoint targets the
// UI format and forces IsCmc=false; this option exists for future use.
IsCmc bool
}
GetOrderBookOptions controls orderbook formatting.
type GetOrdersHistoryOptions ¶
type GetOrdersHistoryOptions struct {
Limit int
Offset int
Status string
TradingPairID int // 0 = no filter
Market string // BASE-QUOTE or BASE/QUOTE
Side string
Type string
Search string
From string
To string
}
GetOrdersHistoryOptions filters the orders-history request.
All fields are optional. Status must be one of: pending, partial, filled, cancelled, rejected. Side must be buy or sell (case- insensitive). Type must be limit or market. From / To are YYYY-MM-DD inclusive dates.
type GetSparklinesOptions ¶
type GetSparklinesOptions struct {
Timeframe string // e.g. "1D", "1h"; default "1D" server-side
Limit int // 1..10000; default 30 server-side
}
GetSparklinesOptions controls the sparkline timeframe/count.
type GetStatsOptions ¶
GetStatsOptions configures the pool-stats request. Symbol is required; Period defaults to "24h" if empty (valid: 1h, 6h, 24h, 7d, 30d).
type GiftCodesService ¶
type GiftCodesService struct {
// contains filtered or unexported fields
}
GiftCodesService handles creation of redeemable gift codes via API key.
Only the creation endpoints (Create + CreateBulk) accept API keys with the `trade` scope. Redemption and listing are JWT-only and not exposed here.
API-key callers bypass interactive 2FA prompts; the scope grant is the authorization step.
func NewGiftCodesService ¶
func NewGiftCodesService(client *HTTPClient) *GiftCodesService
NewGiftCodesService creates a new gift codes service.
func (*GiftCodesService) Create ¶
func (s *GiftCodesService) Create(req CreateGiftCodeRequest) (*CreateGiftCodeResponse, error)
Create issues a single gift code, debiting the caller's wallet.
POST /api/gift-codes (API-key `trade` scope).
func (*GiftCodesService) CreateBulk ¶
func (s *GiftCodesService) CreateBulk(req BulkCreateGiftCodeRequest) (*BulkCreateGiftCodeResponse, error)
CreateBulk issues several equal-amount gift codes in one call.
POST /api/gift-codes/bulk (API-key `trade` scope).
type HTTPClient ¶
type HTTPClient struct {
// contains filtered or unexported fields
}
HTTPClient handles HTTP requests to the KlingEx API
func NewHTTPClient ¶
func NewHTTPClient(apiKey string, opts ...HTTPClientOption) *HTTPClient
NewHTTPClient creates a new HTTP client
func (*HTTPClient) Delete ¶
func (c *HTTPClient) Delete(path string, params map[string]string, authenticated bool) ([]byte, error)
Delete makes a DELETE request
func (*HTTPClient) Post ¶
func (c *HTTPClient) Post(path string, body interface{}, authenticated bool) ([]byte, error)
Post makes a POST request
type HTTPClientOption ¶
type HTTPClientOption func(*HTTPClient)
HTTPClientOption configures the HTTP client
func WithHTTPClient ¶
func WithHTTPClient(client *http.Client) HTTPClientOption
WithHTTPClient sets a custom HTTP client
func WithTimeout ¶
func WithTimeout(timeout time.Duration) HTTPClientOption
WithTimeout sets the request timeout
type Invoice ¶
type Invoice struct {
ID string `json:"id"`
ExternalID *string `json:"external_id,omitempty"`
Status string `json:"status"`
Denomination InvoiceDenomination `json:"denomination"`
PaymentOptions []InvoicePaymentOption `json:"payment_options,omitempty"`
Payments []InvoicePayment `json:"payments,omitempty"`
Description *string `json:"description,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
BuyerEmail *string `json:"buyer_email,omitempty"`
FeeRateBps int `json:"fee_rate_bps"`
FeeRatePercent string `json:"fee_rate_percent"`
TotalReceived string `json:"total_received,omitempty"`
FeeAmount string `json:"fee_amount,omitempty"`
NetAmount string `json:"net_amount,omitempty"`
ExpiresAt time.Time `json:"expires_at"`
PaidAt *time.Time `json:"paid_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
PaymentPageURL string `json:"payment_page_url,omitempty"`
}
Invoice represents the full invoice payload returned by GET /api/invoices/:id.
type InvoiceDenomination ¶
type InvoiceDenomination struct {
Type string `json:"type"`
Currency string `json:"currency"`
Amount string `json:"amount"`
Decimals int `json:"decimals"`
}
InvoiceDenomination describes the asset/amount the invoice is denominated in.
type InvoiceDenominationRequest ¶
type InvoiceDenominationRequest struct {
Type string `json:"type,omitempty"` // optional, server defaults to "crypto"
Currency string `json:"currency"` // e.g. "USDT"
Amount string `json:"amount"` // human-readable
}
InvoiceDenominationRequest is the per-invoice amount specification sent to POST /api/invoices. Currency is an asset symbol (the backend currently restricts it to USDT). Amount is human-readable (e.g. "100.00" for 100 USDT).
type InvoiceFeeStats ¶
type InvoiceFeeStats struct {
CurrentFeeRateBps int `json:"current_fee_rate_bps"`
CurrentFeeRatePercent string `json:"current_fee_rate_percent"`
PaidInvoiceCount int `json:"paid_invoice_count"`
TotalFeesCollected string `json:"total_fees_collected"`
TotalNetAmount string `json:"total_net_amount"`
}
InvoiceFeeStats is the response body for GET /api/invoices/fees. Aggregate merchant statistics; not a per-invoice fee estimate.
type InvoiceListResponse ¶
type InvoiceListResponse struct {
Invoices []InvoiceSummary `json:"invoices"`
TotalCount int `json:"total_count"`
Page int `json:"page"`
PageSize int `json:"page_size"`
}
InvoiceListResponse is the data wrapper for GET /api/invoices.
type InvoicePayment ¶
type InvoicePayment struct {
ID string `json:"id"`
AssetID int `json:"asset_id"`
Symbol string `json:"symbol"`
Amount string `json:"amount"`
TxHash string `json:"tx_hash"`
FromAddress *string `json:"from_address,omitempty"`
Status string `json:"status"`
Confirmations int `json:"confirmations"`
ConfirmationsRequired int `json:"confirmations_required"`
DenominationValue *string `json:"denomination_value,omitempty"`
ExchangeRateUsed *string `json:"exchange_rate_used,omitempty"`
ConfirmedAt *time.Time `json:"confirmed_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
InvoicePayment is one received payment toward an invoice.
type InvoicePaymentOption ¶
type InvoicePaymentOption struct {
AssetID int `json:"asset_id"`
Symbol string `json:"symbol"`
Name string `json:"name"`
ChainType string `json:"chain_type,omitempty"`
ChainID *int `json:"chain_id,omitempty"`
Network string `json:"network,omitempty"`
Address string `json:"address"`
ShieldedAddress *string `json:"shielded_address,omitempty"`
ExpectedAmount string `json:"expected_amount"`
ExchangeRate *string `json:"exchange_rate,omitempty"`
QRCodeData string `json:"qr_code_data,omitempty"`
}
InvoicePaymentOption is one address/coin the invoice can be paid to.
type InvoiceStatusResponse ¶
type InvoiceStatusResponse struct {
InvoiceID string `json:"invoice_id"`
Status string `json:"status"`
TotalPaidPercent float64 `json:"total_paid_percent"`
Payments []InvoicePayment `json:"payments,omitempty"`
PaidAt *time.Time `json:"paid_at,omitempty"`
TimeRemainingMs int64 `json:"time_remaining_ms"`
}
InvoiceStatusResponse is the response body for the public polling endpoint GET /api/invoices/:invoiceId/status.
type InvoiceSummary ¶
type InvoiceSummary struct {
ID string `json:"id"`
ExternalID *string `json:"external_id,omitempty"`
Status string `json:"status"`
DenominationType string `json:"denomination_type"`
DenominationCurrency string `json:"denomination_currency"`
Amount string `json:"amount"`
TotalReceived string `json:"total_received"`
FeeAmount string `json:"fee_amount"`
NetAmount string `json:"net_amount"`
ExpiresAt time.Time `json:"expires_at"`
PaidAt *time.Time `json:"paid_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
InvoiceSummary is a row in the list-invoices response.
type InvoicesService ¶
type InvoicesService struct {
// contains filtered or unexported fields
}
InvoicesService handles merchant invoice creation/listing/cancellation.
Creating and cancelling invoices require the `trade` API-key scope; read operations require `read`. The PDF download requires `read`. All endpoints require the caller to already be registered as a merchant — register via the web UI first.
func NewInvoicesService ¶
func NewInvoicesService(client *HTTPClient) *InvoicesService
NewInvoicesService creates a new invoices service.
func (*InvoicesService) CancelInvoice ¶
func (s *InvoicesService) CancelInvoice(invoiceID string) error
CancelInvoice cancels a pending invoice.
POST /api/invoices/:invoiceId/cancel (API-key `trade` scope).
func (*InvoicesService) CreateInvoice ¶
func (s *InvoicesService) CreateInvoice(req CreateInvoiceRequest) (*Invoice, error)
CreateInvoice creates a new invoice and returns the parsed Invoice payload.
POST /api/invoices (API-key `trade` scope).
func (*InvoicesService) GetFeeStats ¶
func (s *InvoicesService) GetFeeStats() (*InvoiceFeeStats, error)
GetFeeStats returns the aggregate merchant fee statistics.
GET /api/invoices/fees (API-key `read` scope). The response is the aggregate "fees collected" view, not a per-invoice fee estimate.
func (*InvoicesService) GetInvoice ¶
func (s *InvoicesService) GetInvoice(invoiceID string) (*Invoice, error)
GetInvoice retrieves a single invoice by ID.
GET /api/invoices/:invoiceId (API-key `read` scope).
func (*InvoicesService) GetInvoices ¶
func (s *InvoicesService) GetInvoices(opts *GetInvoicesOptions) (*InvoiceListResponse, error)
GetInvoices retrieves the paginated invoice list.
GET /api/invoices (API-key `read` scope).
func (*InvoicesService) GetPdf ¶
func (s *InvoicesService) GetPdf(invoiceID string) ([]byte, error)
GetPdf downloads the invoice PDF as raw bytes.
GET /api/invoices/:invoiceId/pdf (API-key `read` scope). Returns the application/pdf bytes; only paid invoices can be downloaded (backend rejects unpaid invoices with 400).
func (*InvoicesService) GetPublic ¶
func (s *InvoicesService) GetPublic(invoiceID string) (*PublicInvoice, error)
GetPublic fetches the public payment-page view of an invoice. No auth.
GET /api/invoices/:invoiceId/pay. Contains payment_options, merchant_name, and the remaining-time countdown used by the hosted pay page.
func (*InvoicesService) GetStatus ¶
func (s *InvoicesService) GetStatus(invoiceID string) (*InvoiceStatusResponse, error)
GetStatus polls invoice payment status. Public endpoint, no auth required.
GET /api/invoices/:invoiceId/status. Lightweight version of GetInvoice intended for unauthenticated payment-page polling.
type ListPoolOptions ¶
ListPoolOptions filters the public block list and the authenticated rewards/payouts endpoints. Symbol is optional (filter by coin) and only honored where applicable.
type Market ¶
type Market struct {
ID int `json:"id"`
BaseAssetID int `json:"base_asset_id"`
QuoteAssetID int `json:"quote_asset_id"`
MinTradeAmount string `json:"min_trade_amount"`
MaxTradeAmount *string `json:"max_trade_amount,omitempty"`
TickSize string `json:"tick_size"`
StepSize string `json:"step_size"`
MakerFeeRate string `json:"maker_fee_rate"`
TakerFeeRate string `json:"taker_fee_rate"`
PriceDecimals int `json:"price_decimals"`
IsActive bool `json:"is_active"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
BaseAssetSymbol string `json:"base_asset_symbol"`
BaseAssetName string `json:"base_asset_name"`
QuoteAssetSymbol string `json:"quote_asset_symbol"`
QuoteAssetName string `json:"quote_asset_name"`
Volume24h *string `json:"volume_24h,omitempty"`
PriceChange24h *string `json:"priceChange24h,omitempty"`
LastPrice *string `json:"last_price,omitempty"`
BaseDecimals int `json:"base_decimals"`
QuoteDecimals int `json:"quote_decimals"`
Volume24hHuman *string `json:"volume_24h_human,omitempty"`
}
Market represents a trading market/pair returned by GET /api/markets. All numeric fields the backend models as *decimal.Decimal are surfaced as *string here to preserve precision and nullability.
type MarketInfo ¶
type MarketInfo struct {
TradingPairID int `json:"trading_pair_id"`
BaseSymbol string `json:"base_symbol"`
BaseDecimals int `json:"base_decimals"`
QuoteSymbol string `json:"quote_symbol"`
QuoteDecimals int `json:"quote_decimals"`
MinTradeAmount string `json:"min_trade_amount"`
MaxTradeAmount *string `json:"max_trade_amount,omitempty"`
TickSize string `json:"tick_size"`
StepSize string `json:"step_size"`
MakerFeeRate string `json:"maker_fee_rate"`
TakerFeeRate string `json:"taker_fee_rate"`
PriceDecimals int `json:"price_decimals"`
}
MarketInfo is the response from GET /api/market-info?baseAssetSymbol="eAssetSymbol=.
type MarketsService ¶
type MarketsService struct {
// contains filtered or unexported fields
}
MarketsService handles public market-data API calls.
func NewMarketsService ¶
func NewMarketsService(client *HTTPClient) *MarketsService
NewMarketsService creates a new markets service.
func (*MarketsService) GetAssetInfo ¶
func (s *MarketsService) GetAssetInfo(assetID int) (*AssetInfo, error)
GetAssetInfo retrieves the detailed asset record by numeric ID.
GET /api/asset-info/:id — public.
func (*MarketsService) GetAssetInfoBySymbol ¶
func (s *MarketsService) GetAssetInfoBySymbol(symbol string) (*AssetInfo, error)
GetAssetInfoBySymbol retrieves the detailed asset record by symbol.
GET /api/asset-info/symbol/:symbol — public.
func (*MarketsService) GetAssets ¶
func (s *MarketsService) GetAssets() ([]Asset, error)
GetAssets retrieves all listed assets.
GET /api/assets — public. Response is wrapped in {"assets": [...]}.
func (*MarketsService) GetMarketInfo ¶
func (s *MarketsService) GetMarketInfo(baseSymbol, quoteSymbol string) (*MarketInfo, error)
GetMarketInfo resolves trading-pair details by asset symbol pair.
GET /api/market-info?baseAssetSymbol="eAssetSymbol= — public.
func (*MarketsService) GetMarkets ¶
func (s *MarketsService) GetMarkets() ([]Market, error)
GetMarkets retrieves all trading pairs.
GET /api/markets — public. Returns array directly.
func (*MarketsService) GetOHLCV ¶
func (s *MarketsService) GetOHLCV(marketID int, opts *GetOHLCVOptions) ([]OHLCV, error)
GetOHLCV retrieves candlestick data for a market.
GET /api/ohlcv?marketId=&timeframe=&limit=&startDate=&endDate= — public. startDate / endDate are sent as RFC3339 strings.
func (*MarketsService) GetOrderBook ¶
func (s *MarketsService) GetOrderBook(marketID int, opts *GetOrderBookOptions) (*OrderBook, error)
GetOrderBook retrieves the orderbook for a market by numeric trading-pair ID.
GET /api/orderbook?marketId=&isCmc=false — public.
func (*MarketsService) GetSparklines ¶
func (s *MarketsService) GetSparklines(opts *GetSparklinesOptions) (*SparklinesResponse, error)
GetSparklines returns recent close-price points for every market, keyed by ticker symbol.
GET /api/markets/sparklines — public.
func (*MarketsService) GetTicker ¶
func (s *MarketsService) GetTicker(tickerID string) (*Ticker, error)
GetTicker retrieves a single ticker by its CMC ticker_id (e.g. "BTC_USDT"). Implemented as a client-side filter over GetTickers since the backend has no per-ID endpoint.
func (*MarketsService) GetTickers ¶
func (s *MarketsService) GetTickers() ([]Ticker, error)
GetTickers retrieves CMC-format tickers for all markets.
GET /api/tickers — public.
type MessageHandler ¶
type MessageHandler func(msg WebSocketMessage)
MessageHandler receives messages dispatched for a channel.
type MiningPoolBlock ¶
type MiningPoolBlock struct {
ID int `json:"id"`
AssetID int `json:"asset_id"`
Symbol string `json:"symbol"`
BlockHeight int64 `json:"block_height"`
BlockHash string `json:"block_hash"`
BlockReward string `json:"block_reward"`
PoolFee string `json:"pool_fee"`
Confirmations int `json:"confirmations"`
RequiredConfirmations int `json:"required_confirmations"`
Status string `json:"status"`
FoundAt time.Time `json:"found_at"`
MaturedAt *time.Time `json:"matured_at,omitempty"`
CreditedAt *time.Time `json:"credited_at,omitempty"`
AssetDecimals int `json:"asset_decimals"`
}
MiningPoolBlock is one found-block row.
type MiningPoolBlocksResponse ¶
type MiningPoolBlocksResponse struct {
Blocks []MiningPoolBlock `json:"blocks"`
Total int `json:"total"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
MiningPoolBlocksResponse wraps a paginated set of blocks.
type MiningPoolConfig ¶
type MiningPoolConfig struct {
Algorithm string `json:"algorithm"`
Symbol string `json:"symbol"`
StratumPort int `json:"stratum_port"`
PoolFeePercent float64 `json:"pool_fee_percent"`
PoolHashrate string `json:"pool_hashrate"`
MinDifficulty float64 `json:"min_difficulty"`
}
MiningPoolConfig is the public per-coin configuration.
type MiningPoolLeaderboard ¶
type MiningPoolLeaderboard struct {
Symbol string `json:"symbol"`
Period string `json:"period"`
Miners []MiningPoolLeaderboardEntry `json:"miners"`
}
MiningPoolLeaderboard is the response from GET /api/pool/leaderboard.
type MiningPoolLeaderboardEntry ¶
type MiningPoolLeaderboardEntry struct {
UserID string `json:"user_id"`
TotalRewards string `json:"total_rewards"`
RewardFormatted string `json:"reward_formatted"`
BlocksFound int `json:"blocks_found"`
Hashrate string `json:"hashrate"`
WorkerCount int `json:"worker_count"`
}
MiningPoolLeaderboardEntry is one row of the public leaderboard.
type MiningPoolPayout ¶
type MiningPoolPayout struct {
ID string `json:"id"`
WalletID string `json:"wallet_id"`
RewardID *string `json:"reward_id,omitempty"`
BlockID *int `json:"block_id,omitempty"`
AssetID int `json:"asset_id"`
AssetSymbol string `json:"asset_symbol"`
AssetName string `json:"asset_name"`
AssetDecimals int `json:"asset_decimals"`
Amount string `json:"amount"`
AmountFormatted string `json:"amount_formatted"`
CreatedAt time.Time `json:"created_at"`
BlockHeight *int64 `json:"block_height,omitempty"`
BlockHash *string `json:"block_hash,omitempty"`
}
MiningPoolPayout is one wallet-credit payout row for the caller.
type MiningPoolPayoutsResponse ¶
type MiningPoolPayoutsResponse struct {
Payouts []MiningPoolPayout `json:"payouts"`
Total int `json:"total"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
MiningPoolPayoutsResponse wraps a paginated set of caller payouts.
type MiningPoolReward ¶
type MiningPoolReward struct {
ID string `json:"id"`
BlockID int `json:"block_id"`
AssetID int `json:"asset_id"`
AssetSymbol string `json:"asset_symbol"`
AssetName string `json:"asset_name"`
AssetDecimals int `json:"asset_decimals"`
RewardAmount string `json:"reward_amount"`
RewardAmountFormatted string `json:"reward_amount_formatted"`
Status string `json:"status"`
CreatedAt time.Time `json:"created_at"`
CreditedAt *time.Time `json:"credited_at,omitempty"`
BlockHeight int64 `json:"block_height"`
BlockHash string `json:"block_hash"`
BlockStatus string `json:"block_status"`
Confirmations int `json:"confirmations"`
RequiredConfirmations int `json:"required_confirmations"`
FoundAt time.Time `json:"found_at"`
}
MiningPoolReward is one PPLNS reward row for the caller.
type MiningPoolRewardsResponse ¶
type MiningPoolRewardsResponse struct {
Rewards []MiningPoolReward `json:"rewards"`
Total int `json:"total"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
MiningPoolRewardsResponse wraps a paginated set of caller rewards.
type MiningPoolService ¶
type MiningPoolService struct {
// contains filtered or unexported fields
}
MiningPoolService exposes the public + authenticated mining-pool endpoints.
- GetConfigs/Blocks/Stats/Leaderboard are public.
- GetMyWorkers/GetMyRewards/GetMyPayouts require JWT or an API key with the `read` scope.
func NewMiningPoolService ¶
func NewMiningPoolService(client *HTTPClient) *MiningPoolService
NewMiningPoolService creates a new mining-pool service.
func (*MiningPoolService) GetBlocks ¶
func (s *MiningPoolService) GetBlocks(opts *ListPoolOptions) (*MiningPoolBlocksResponse, error)
GetBlocks lists recent found blocks across the pool (public).
GET /api/pool/blocks
func (*MiningPoolService) GetConfigs ¶
func (s *MiningPoolService) GetConfigs() ([]MiningPoolConfig, error)
GetConfigs returns all enabled mining-pool configurations (public).
GET /api/pool/configs
func (*MiningPoolService) GetLeaderboard ¶
func (s *MiningPoolService) GetLeaderboard(symbol, period string) (*MiningPoolLeaderboard, error)
GetLeaderboard returns the top miners for a coin over a period (public). Period defaults to "24h" if empty.
GET /api/pool/leaderboard?symbol=&period=
func (*MiningPoolService) GetMyPayouts ¶
func (s *MiningPoolService) GetMyPayouts(opts *ListPoolOptions) (*MiningPoolPayoutsResponse, error)
GetMyPayouts returns the caller's wallet-credit payouts. Requires `read` scope.
GET /api/pool/my-payouts
func (*MiningPoolService) GetMyRewards ¶
func (s *MiningPoolService) GetMyRewards(opts *ListPoolOptions) (*MiningPoolRewardsResponse, error)
GetMyRewards returns the caller's PPLNS rewards. Requires `read` scope.
GET /api/pool/my-rewards
func (*MiningPoolService) GetMyWorkers ¶
func (s *MiningPoolService) GetMyWorkers(symbol string) (*MiningPoolWorkersResponse, error)
GetMyWorkers returns the caller's workers, optionally filtered to one coin (empty symbol means all coins). Requires API-key `read` scope.
GET /api/pool/my-workers
func (*MiningPoolService) GetStats ¶
func (s *MiningPoolService) GetStats(opts GetStatsOptions) (*MiningPoolStats, error)
GetStats returns the current and historical pool stats for one coin (public).
GET /api/pool/stats?symbol=&period=
type MiningPoolStats ¶
type MiningPoolStats struct {
Symbol string `json:"symbol"`
Current MiningPoolStatsCurrent `json:"current"`
History []MiningPoolStatsSnapshot `json:"history"`
}
MiningPoolStats is the response from GET /api/pool/stats.
type MiningPoolStatsCurrent ¶
type MiningPoolStatsCurrent struct {
PoolHashrate string `json:"pool_hashrate"`
NetworkHashrate string `json:"network_hashrate"`
NetworkDifficulty float64 `json:"network_difficulty"`
OnlineWorkers int `json:"online_workers"`
ActiveMiners int `json:"active_miners"`
BlockHeight int64 `json:"block_height"`
Blocks24h *int `json:"blocks_24h,omitempty"`
CurrentEffort *float64 `json:"current_effort,omitempty"`
TTFMinutes *float64 `json:"ttf_minutes,omitempty"`
LastBlockFound *time.Time `json:"last_block_found,omitempty"`
Luck24h *float64 `json:"luck_24h,omitempty"`
}
MiningPoolStatsCurrent is the instantaneous pool view.
type MiningPoolStatsSnapshot ¶
type MiningPoolStatsSnapshot struct {
Timestamp time.Time `json:"timestamp"`
PoolHashrate string `json:"pool_hashrate"`
NetworkHashrate string `json:"network_hashrate"`
NetworkDifficulty float64 `json:"network_difficulty"`
OnlineWorkers int `json:"online_workers"`
ActiveMiners int `json:"active_miners"`
}
MiningPoolStatsSnapshot is one historical pool snapshot.
type MiningPoolWorker ¶
type MiningPoolWorker struct {
WorkerName string `json:"worker_name"`
Symbol string `json:"symbol"`
Hashrate1m string `json:"hashrate_1m"`
Difficulty float64 `json:"difficulty"`
IsOnline bool `json:"is_online"`
ConnectedAt *time.Time `json:"connected_at,omitempty"`
DisconnectedAt *time.Time `json:"disconnected_at,omitempty"`
}
MiningPoolWorker is one worker entry from GET /api/pool/my-workers.
type MiningPoolWorkersResponse ¶
type MiningPoolWorkersResponse struct {
Workers []MiningPoolWorker `json:"workers"`
}
MiningPoolWorkersResponse wraps the worker list.
type OHLCV ¶
type OHLCV struct {
TimeBucket time.Time `json:"time_bucket"`
OpenPrice *string `json:"open_price,omitempty"`
HighPrice *string `json:"high_price,omitempty"`
LowPrice *string `json:"low_price,omitempty"`
ClosePrice *string `json:"close_price,omitempty"`
Volume *string `json:"volume,omitempty"`
NumberOfTrades *int64 `json:"number_of_trades,omitempty"`
}
OHLCV represents one candlestick from GET /api/ohlcv. Numeric fields are pointers because the backend may return null for empty buckets.
type Order ¶
type Order struct {
ID string `json:"id"`
TradingPairID int `json:"trading_pair_id"`
Side OrderSide `json:"side"`
Type string `json:"type"`
Price string `json:"price"`
Amount string `json:"amount"`
FilledAmount string `json:"filled_amount"`
Status OrderStatus `json:"status"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
Order represents an order returned by GET /api/user-orders.
type OrderBook ¶
type OrderBook struct {
TradingPairID int `json:"trading_pair_id"`
BaseSymbol string `json:"base_symbol"`
QuoteSymbol string `json:"quote_symbol"`
Bids [][]json.RawMessage `json:"bids"`
Asks [][]json.RawMessage `json:"asks"`
}
OrderBook represents an orderbook snapshot from GET /api/orderbook. Backend returns bids/asks as [][]any; each inner pair contains [price, quantity] (typically as strings).
type OrderHistory ¶
type OrderHistory struct {
ID string `json:"id"`
TradingPairID int `json:"trading_pair_id"`
BaseSymbol string `json:"base_symbol"`
QuoteSymbol string `json:"quote_symbol"`
Type string `json:"type"`
Side string `json:"side"`
Status string `json:"status"`
Price *string `json:"price,omitempty"`
Amount string `json:"amount"`
FilledAmount string `json:"filled_amount"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
HumanPrice *string `json:"human_price,omitempty"`
HumanAmount string `json:"human_amount"`
HumanFilledAmount string `json:"human_filled_amount"`
HumanRemaining string `json:"human_remaining"`
HumanTotal string `json:"human_total"`
}
OrderHistory matches a row in the GET /api/orders-history response.
type OrderStatus ¶
type OrderStatus string
OrderStatus represents the status of an order.
const ( OrderStatusPending OrderStatus = "pending" OrderStatusOpen OrderStatus = "open" OrderStatusPartial OrderStatus = "partial" OrderStatusFilled OrderStatus = "filled" OrderStatusCancelled OrderStatus = "cancelled" OrderStatusRejected OrderStatus = "rejected" )
type OrdersHistoryResponse ¶
type OrdersHistoryResponse struct {
Orders []OrderHistory `json:"orders"`
Total int `json:"total"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
OrdersHistoryResponse is the response from GET /api/orders-history.
type OrdersService ¶
type OrdersService struct {
// contains filtered or unexported fields
}
OrdersService handles order placement, cancellation, and history.
func NewOrdersService ¶
func NewOrdersService(client *HTTPClient) *OrdersService
NewOrdersService creates a new orders service.
func (*OrdersService) CancelAllOrders ¶
func (s *OrdersService) CancelAllOrders(tradingPairID int) (*CancelAllOrdersResponse, error)
CancelAllOrders cancels every open order the caller has on the given pair.
POST /api/cancel-all-orders (API-key `trade` scope).
func (*OrdersService) CancelOrder ¶
func (s *OrdersService) CancelOrder(orderID string, tradingPairID int) (*CancelOrderResponse, error)
CancelOrder cancels a single order by ID.
POST /api/cancel-order (API-key `trade` scope).
func (*OrdersService) GetOpenOrders ¶
func (s *OrdersService) GetOpenOrders() ([]Order, error)
GetOpenOrders returns active orders (pending / open / partial) the caller has.
func (*OrdersService) GetOrder ¶
func (s *OrdersService) GetOrder(orderID string) (*Order, error)
GetOrder retrieves an order by ID (client-side filter over GetUserOrders).
func (*OrdersService) GetOrdersByMarket ¶
func (s *OrdersService) GetOrdersByMarket(tradingPairID int) ([]Order, error)
GetOrdersByMarket filters GetUserOrders to a single trading pair.
func (*OrdersService) GetOrdersHistory ¶
func (s *OrdersService) GetOrdersHistory(opts *GetOrdersHistoryOptions) (*OrdersHistoryResponse, error)
GetOrdersHistory retrieves the paginated order history.
GET /api/orders-history (API-key `read` scope).
func (*OrdersService) GetUserOrders ¶
func (s *OrdersService) GetUserOrders() ([]Order, error)
GetUserOrders retrieves the caller's orders.
GET /api/user-orders (API-key `read` scope). Returns up to `limit` rows from the wrapped {"orders": [...]} response.
func (*OrdersService) SubmitOrder ¶
func (s *OrdersService) SubmitOrder( symbol string, tradingPairID int, side OrderSide, quantity string, price string, rawValues bool, ) (*SubmitOrderResponse, error)
SubmitOrder submits a new limit order.
POST /api/submit-order (API-key `trade` scope). `price` is required by the backend even for market-like orders — pass "0" for a price-insensitive market order if your trading pair supports it.
`rawValues` indicates whether quantity and price are in base units (true) or human-readable form (false). Backend default is true; this SDK keeps the explicit boolean to remove ambiguity.
type PlaceOrderParams ¶
type PlaceOrderParams struct {
Symbol string `json:"symbol"`
TradingPairID int `json:"tradingPairId"`
Side string `json:"side"`
Quantity string `json:"quantity"`
Price string `json:"price"`
RawValues bool `json:"rawValues,omitempty"`
}
PlaceOrderParams contains parameters for placing an order via WebSocket.
type PoolDetail ¶
type PoolDetail struct {
PoolListItem
KValue string `json:"k_value"`
MinLiquidity string `json:"min_liquidity"`
OrderLevels int `json:"order_levels"`
ActiveOrders int `json:"active_orders"`
LPPositionCount int `json:"lp_position_count"`
}
PoolDetail is the full view of a single pool.
type PoolListItem ¶
type PoolListItem struct {
ID int `json:"id"`
BaseSymbol string `json:"base_symbol"`
QuoteSymbol string `json:"quote_symbol"`
BaseReserve string `json:"base_reserve"`
QuoteReserve string `json:"quote_reserve"`
BaseDecimals int `json:"base_decimals"`
QuoteDecimals int `json:"quote_decimals"`
TotalLPTokens string `json:"total_lp_tokens"`
PoolFeeRate string `json:"pool_fee_rate"`
SpotPrice string `json:"spot_price"`
IsPublic bool `json:"is_public"`
DepositsPaused bool `json:"deposits_paused"`
WithdrawalsPaused bool `json:"withdrawals_paused"`
}
PoolListItem is the public view of a pool for listing.
type PoolsService ¶
type PoolsService struct {
// contains filtered or unexported fields
}
PoolsService handles liquidity pool data and LP operations.
- List and Get are public (no auth).
- Positions and PositionHistory require an API key with the `read` scope.
- AddLiquidity and RemoveLiquidity require an API key with the `liquidity` scope.
func NewPoolsService ¶
func NewPoolsService(client *HTTPClient) *PoolsService
NewPoolsService creates a new pools service.
func (*PoolsService) AddLiquidity ¶
func (s *PoolsService) AddLiquidity(req AddLiquidityRequest) (*AddLiquidityResult, error)
AddLiquidity deposits liquidity into a pool. Requires `liquidity` scope.
POST /api/pools/add-liquidity
func (*PoolsService) Get ¶
func (s *PoolsService) Get(poolID int) (*PoolDetail, error)
Get returns details for a single pool by ID (no auth).
GET /api/pools/:id
func (*PoolsService) List ¶
func (s *PoolsService) List() ([]PoolListItem, error)
List returns all active, public pools (no auth).
GET /api/pools/list
func (*PoolsService) PositionHistory ¶
func (s *PoolsService) PositionHistory(poolID, days int) (*PositionHistoryResponse, error)
PositionHistory returns chart data for the user's position in a single pool. Requires an API key with the `read` scope.
GET /api/pools/positions/history
If the user has no recorded position history for the pool the backend returns 404; this method treats that case as a non-error and returns a zero-value response with an empty History slice.
func (*PoolsService) Positions ¶
func (s *PoolsService) Positions() ([]UserPosition, error)
Positions returns the authenticated user's LP positions across all pools. Requires an API key with the `read` scope.
GET /api/pools/positions
func (*PoolsService) RemoveLiquidity ¶
func (s *PoolsService) RemoveLiquidity(req RemoveLiquidityRequest) (*RemoveLiquidityResult, error)
RemoveLiquidity burns LP tokens and withdraws the underlying assets. Requires `liquidity` scope.
POST /api/pools/remove-liquidity
type PositionHistoryResponse ¶
type PositionHistoryResponse struct {
PoolID int `json:"pool_id"`
BaseSymbol string `json:"base_symbol"`
QuoteSymbol string `json:"quote_symbol"`
BaseDecimals int `json:"base_decimals"`
QuoteDecimals int `json:"quote_decimals"`
History []PositionHistorySnapshot `json:"history"`
}
PositionHistoryResponse is the LP chart history for a single pool.
type PositionHistorySnapshot ¶
type PositionHistorySnapshot struct {
Timestamp string `json:"timestamp"`
LPTokenBalance string `json:"lp_token_balance"`
BaseValue string `json:"base_value"`
QuoteValue string `json:"quote_value"`
TotalValueQuote string `json:"total_value_quote"`
NetEarnedQuote string `json:"net_earned_quote"`
SpotPrice string `json:"spot_price"`
}
PositionHistorySnapshot is a single LP position chart point.
type PublicInvoice ¶
type PublicInvoice struct {
InvoiceID string `json:"invoice_id"`
Status string `json:"status"`
Denomination InvoiceDenomination `json:"denomination"`
Description *string `json:"description,omitempty"`
MerchantName string `json:"merchant_name"`
ExpiresAt time.Time `json:"expires_at"`
TimeRemainingMs int64 `json:"time_remaining_ms"`
PaymentOptions []InvoicePaymentOption `json:"payment_options"`
PaymentsReceived []InvoicePayment `json:"payments_received,omitempty"`
TotalPaidPercent float64 `json:"total_paid_percent"`
}
PublicInvoice is the response body for the public payment-page endpoint GET /api/invoices/:invoiceId/pay.
type RateLimitError ¶
RateLimitError represents a rate limit exceeded error
func NewRateLimitError ¶
func NewRateLimitError(retryAfter int) *RateLimitError
NewRateLimitError creates a new rate limit error
func (*RateLimitError) Error ¶
func (e *RateLimitError) Error() string
type RemoveLiquidityRequest ¶
type RemoveLiquidityRequest struct {
PoolID int `json:"pool_id"`
LPTokens string `json:"lp_tokens"` // LP tokens to burn (smallest units)
MinBaseOut string `json:"min_base_out"` // slippage protection
MinQuoteOut string `json:"min_quote_out"` // slippage protection
}
RemoveLiquidityRequest is the user-facing request to remove liquidity.
type RemoveLiquidityResult ¶
type RemoveLiquidityResult struct {
PoolID int `json:"pool_id"`
LPTokensBurned string `json:"lp_tokens_burned"`
BaseOut string `json:"base_out"`
QuoteOut string `json:"quote_out"`
TotalLPSupply string `json:"total_lp_supply"`
}
RemoveLiquidityResult is returned after a successful remove-liquidity operation.
type SparklinePoint ¶
type SparklinePoint struct {
TimeBucket time.Time `json:"time_bucket"`
Price string `json:"price"`
}
SparklinePoint is one timestamped close-price for a market sparkline.
type SparklinesResponse ¶
type SparklinesResponse struct {
Timeframe string `json:"timeframe"`
Limit int `json:"limit"`
Sparklines map[string][]SparklinePoint `json:"sparklines"`
}
SparklinesResponse is the response from GET /api/markets/sparklines. Sparklines is keyed by ticker symbol (e.g. "BTC-USDT").
type StatusCounts ¶
type StatusCounts struct {
Active int `json:"active"`
Delayed int `json:"delayed"`
Stale int `json:"stale"`
NeverSynced int `json:"never_synced"`
}
StatusCounts counts assets by sync status.
type SubmitOrderResponse ¶
type SubmitOrderResponse struct {
Message string `json:"message"`
OrderID string `json:"order_id"`
}
SubmitOrderResponse is the response from POST /api/submit-order.
type SubmitWithdrawalRequest ¶
type SubmitWithdrawalRequest struct {
Symbol string `json:"symbol"`
AssetID int `json:"assetId"`
Amount string `json:"amount"`
Address string `json:"address"`
DestinationTag *uint32 `json:"destinationTag,omitempty"` // XRP-style uint32 destination tag
Memo string `json:"memo,omitempty"` // Graphene-style string memo
}
SubmitWithdrawalRequest is the on-chain withdrawal submission payload.
IMPORTANT: Amount is a RAW INTEGER in the asset's smallest base unit (e.g. satoshis for BTC, wei for ETH). Decimal points and scientific notation are rejected — convert from human-readable using the asset's decimals first.
type SubmitWithdrawalResponse ¶
type SubmitWithdrawalResponse struct {
Message string `json:"message"`
WithdrawalID string `json:"withdrawalId"`
}
SubmitWithdrawalResponse is the API-key response from a successful submission.
type Ticker ¶
type Ticker struct {
TickerID string `json:"ticker_id"`
BaseCurrency string `json:"base_currency"`
TargetCurrency string `json:"target_currency"`
LastPrice string `json:"last_price"`
BaseVolume string `json:"base_volume"`
TargetVolume string `json:"target_volume"`
Bid string `json:"bid"`
Ask string `json:"ask"`
High string `json:"high"`
Low string `json:"low"`
}
Ticker represents market ticker data (CMC format) from GET /api/tickers.
type Trade ¶
type Trade struct {
ID string `json:"id"`
TradingPairID int `json:"trading_pair_id"`
TakerOrderID string `json:"taker_order_id"`
MakerOrderID string `json:"maker_order_id"`
Price string `json:"price"`
Amount string `json:"amount"`
TakerFee string `json:"taker_fee"`
MakerFee string `json:"maker_fee"`
CreatedAt *time.Time `json:"created_at,omitempty"`
Side string `json:"side"`
}
Trade represents an executed trade from GET /api/trades.
type UserBalance ¶
type UserBalance struct {
Balance string `json:"balance"`
LockedBalance string `json:"locked_balance"`
WalletID *string `json:"wallet_id,omitempty"`
DepositAddress *string `json:"deposit_address,omitempty"`
PaymentID *string `json:"payment_id,omitempty"`
ID int `json:"id"`
Symbol string `json:"symbol"`
Name string `json:"name"`
IsCrypto bool `json:"is_crypto"`
ChainType *string `json:"chain_type,omitempty"`
Decimals int `json:"decimals"`
MinDeposit string `json:"min_deposit"`
MinWithdrawal string `json:"min_withdrawal"`
WithdrawalFee string `json:"withdrawal_fee"`
DepositFee string `json:"deposit_fee"`
DepositFeeThreshold string `json:"deposit_fee_threshold"`
DepositConfirmsRequired int `json:"deposit_confirms_required"`
ContractAddress *string `json:"contract_address,omitempty"`
ChainID *int `json:"chain_id,omitempty"`
EVMNetwork *string `json:"evm_network,omitempty"`
ParentAssetID *int `json:"parent_asset_id,omitempty"`
USDTValue string `json:"usdt_value"`
DepositsEnabled bool `json:"deposits_enabled"`
WithdrawalEnabled bool `json:"withdrawal_enabled"`
SupportsShielded bool `json:"supports_shielded"`
ShieldedAddressMode string `json:"shielded_address_mode"`
ShieldedDepositAddress *string `json:"shielded_deposit_address,omitempty"`
}
UserBalance represents a wallet/asset row from GET /api/user-balances. Fields that can be missing or null in the backend response are pointers.
type UserOrdersResponse ¶
type UserOrdersResponse struct {
Orders []Order `json:"orders"`
}
UserOrdersResponse wraps the GET /api/user-orders payload.
type UserPosition ¶
type UserPosition struct {
PoolID int `json:"pool_id"`
BaseSymbol string `json:"base_symbol"`
QuoteSymbol string `json:"quote_symbol"`
LPTokenBalance string `json:"lp_token_balance"`
BaseDeposited string `json:"base_deposited"`
QuoteDeposited string `json:"quote_deposited"`
BaseDecimals int `json:"base_decimals"`
QuoteDecimals int `json:"quote_decimals"`
BaseValue string `json:"base_value"`
QuoteValue string `json:"quote_value"`
BaseEarned string `json:"base_earned"`
QuoteEarned string `json:"quote_earned"`
NetEarnedQuote string `json:"net_earned_quote"`
ApproxFeesEarned string `json:"approx_fees_earned"`
}
UserPosition is a user's LP position in a pool.
type ValidationError ¶
ValidationError represents a request validation failure
func NewValidationError ¶
func NewValidationError(message string) *ValidationError
NewValidationError creates a new validation error
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
type WalletAssetSync ¶
type WalletAssetSync struct {
AssetID int `json:"asset_id"`
Symbol string `json:"symbol"`
Name string `json:"name"`
NetworkName string `json:"network_name"`
ChainID *int `json:"chain_id,omitempty"`
BlockNumber *int64 `json:"block_number,omitempty"`
ProcessedAt *time.Time `json:"processed_at,omitempty"`
SyncStatus string `json:"sync_status"`
SecondsSinceLastSync *float64 `json:"seconds_since_last_sync,omitempty"`
ExplorerURL *string `json:"explorer_url,omitempty"`
DepositsEnabled bool `json:"deposits_enabled"`
WithdrawalsEnabled bool `json:"withdrawals_enabled"`
}
WalletAssetSync is the per-asset sync status row.
type WalletChainGroup ¶
type WalletChainGroup struct {
NetworkName string `json:"network_name"`
ChainID *int `json:"chain_id,omitempty"`
Assets []WalletAssetSync `json:"assets"`
}
WalletChainGroup groups per-asset sync status by chain network.
type WalletService ¶
type WalletService struct {
// contains filtered or unexported fields
}
WalletService handles user balance / deposit-address API calls.
The endpoints in this file all require an authenticated session (API key with the `read` scope or a logged-in JWT user). Withdrawals are handled by WithdrawalsService; deposit/withdrawal history routes are JWT-only and intentionally not exposed in the SDK.
func NewWalletService ¶
func NewWalletService(client *HTTPClient) *WalletService
NewWalletService creates a new wallet service.
func (*WalletService) GetBalance ¶
func (s *WalletService) GetBalance(symbol string) (*UserBalance, error)
GetBalance retrieves the balance for a specific asset by symbol (client-side filter over GetUserBalances).
func (*WalletService) GetBalanceByID ¶
func (s *WalletService) GetBalanceByID(assetID int) (*UserBalance, error)
GetBalanceByID retrieves the balance for a specific asset by numeric ID.
func (*WalletService) GetDepositAddress ¶
func (s *WalletService) GetDepositAddress(symbol string) (string, error)
GetDepositAddress returns the on-chain deposit address for the given symbol. The deposit address is embedded in the UserBalance response; returns an empty string if no address has been generated for the asset yet.
func (*WalletService) GetUserBalances ¶
func (s *WalletService) GetUserBalances() ([]UserBalance, error)
GetUserBalances retrieves all user balances.
GET /api/user-balances (API-key `read` scope)
type WalletStatus ¶
type WalletStatus struct {
OverallStatus string `json:"overall_status"`
SystemHealthPercentage int `json:"system_health_percentage"`
LastUpdated time.Time `json:"last_updated"`
StatusCounts StatusCounts `json:"status_counts"`
TotalAssets int `json:"total_assets"`
ChainGroups []WalletChainGroup `json:"chain_groups"`
}
WalletStatus is the response from GET /api/wallets/status.
type WalletSyncInfo ¶
type WalletSyncInfo struct {
CurrentBlock *int64 `json:"current_block,omitempty"`
LastProcessedAt *time.Time `json:"last_processed_at,omitempty"`
SyncStatus string `json:"sync_status"`
SecondsSinceLastSync *float64 `json:"seconds_since_last_sync,omitempty"`
}
WalletSyncInfo describes the latest processed block per asset.
type WalletsService ¶
type WalletsService struct {
// contains filtered or unexported fields
}
WalletsService exposes the public wallet-status endpoints that report per-chain deposit/withdrawal sync health. No authentication required.
func NewWalletsService ¶
func NewWalletsService(client *HTTPClient) *WalletsService
NewWalletsService creates a new wallets-status service.
func (*WalletsService) GetWalletStatus ¶
func (s *WalletsService) GetWalletStatus(assetID int) (*AssetStatusDetail, error)
GetWalletStatus returns sync status for a single asset by ID.
GET /api/wallets/status/:assetId (public)
func (*WalletsService) GetWalletStatuses ¶
func (s *WalletsService) GetWalletStatuses() (*WalletStatus, error)
GetWalletStatuses returns the overall wallet system status grouped by chain.
GET /api/wallets/status (public)
type WebSocket ¶
type WebSocket struct {
// contains filtered or unexported fields
}
WebSocket is a managed connection to the KlingEx WebSocket server.
API-key authentication is performed post-connect with a {"type":"auth", "apiKey":"..."} message; user-channel subscriptions are queued until the server replies with {"type":"auth_result","success":true}.
func NewWebSocket ¶
func NewWebSocket(apiKey string, opts ...WebSocketOption) *WebSocket
NewWebSocket creates a new WebSocket client. Provide an empty apiKey for public-only access.
func (*WebSocket) CancelOrder ¶
func (ws *WebSocket) CancelOrder(ctx context.Context, params CancelOrderParams) (*WsCancelResult, error)
CancelOrder cancels an order via the WebSocket connection.
func (*WebSocket) Connect ¶
Connect establishes the WebSocket connection. If an API key is configured the auth handshake is performed before this returns and any previously queued subscriptions are re-sent.
func (*WebSocket) Done ¶
func (ws *WebSocket) Done() <-chan struct{}
Done returns a channel that's closed when the connection is permanently terminated (after Close()).
func (*WebSocket) On ¶
func (ws *WebSocket) On(channel string, handler MessageHandler)
On registers a handler for an arbitrary channel key (use "*" to receive every message). Useful when you want to drive your own routing off msg.Type / msg.Raw rather than the SDK's channel derivation.
func (*WebSocket) Ping ¶
Ping sends an application-level ping; the server replies with {"type":"pong"} which is delivered to handlers registered for "pong".
func (*WebSocket) PlaceOrder ¶
func (ws *WebSocket) PlaceOrder(ctx context.Context, params PlaceOrderParams) (*WsOrderResult, error)
PlaceOrder places an order via the WebSocket connection.
func (*WebSocket) SubscribeAccountEvents ¶
func (ws *WebSocket) SubscribeAccountEvents(handler MessageHandler) error
SubscribeAccountEvents subscribes to the authenticated account-security event channel (login alerts, password changes, API key creation/revocation, 2FA changes).
func (*WebSocket) SubscribeInvoice ¶
func (ws *WebSocket) SubscribeInvoice(invoiceID string, handler MessageHandler) error
SubscribeInvoice subscribes to live updates for one invoice's payment status. No authentication required.
func (*WebSocket) SubscribeMarket ¶
func (ws *WebSocket) SubscribeMarket(market string, handler MessageHandler) error
SubscribeMarket subscribes to all real-time updates for a single market (ticker, orderbook, trades). Use MarketChannelMarkets to subscribe to the markets-list update channel.
handler is invoked on every message tagged with that market symbol. To distinguish ticker vs orderbook vs trade updates inspect msg.Type ("ticker" / "orderbook" / "trade", etc.).
func (*WebSocket) SubscribeOHLCV ¶
func (ws *WebSocket) SubscribeOHLCV(marketID int, timeframe string, handler MessageHandler) error
SubscribeOHLCV subscribes to OHLCV candlestick updates for a market / timeframe pair. The server requires the numeric market_id (trading pair ID), not the symbol.
func (*WebSocket) SubscribeOrderBook ¶
func (ws *WebSocket) SubscribeOrderBook(market string, handler MessageHandler) error
SubscribeOrderBook is an alias for SubscribeMarket (see SubscribeTicker).
func (*WebSocket) SubscribeQR ¶
func (ws *WebSocket) SubscribeQR(sessionToken string, handler MessageHandler) error
SubscribeQR subscribes to live updates for a QR-login session (used by the web UI's mobile QR auth flow). No authentication required.
func (*WebSocket) SubscribeTicker ¶
func (ws *WebSocket) SubscribeTicker(market string, handler MessageHandler) error
SubscribeTicker is a thin alias over SubscribeMarket — the server broadcasts ticker, trade, and orderbook updates over the same market subscription, so callers should filter on msg.Type.
func (*WebSocket) SubscribeTrades ¶
func (ws *WebSocket) SubscribeTrades(market string, handler MessageHandler) error
SubscribeTrades is an alias for SubscribeMarket (see SubscribeTicker). For the AUTHENTICATED user-trade channel use SubscribeUserChannel(UserChannelTrades, ...).
func (*WebSocket) SubscribeUserBalance ¶
func (ws *WebSocket) SubscribeUserBalance(handler MessageHandler) error
SubscribeUserBalance subscribes to the authenticated balance channel. (Server channel name is singular "balance".)
func (*WebSocket) SubscribeUserChannel ¶
func (ws *WebSocket) SubscribeUserChannel(channel string, handler MessageHandler) error
SubscribeUserChannel subscribes to one of the authenticated user-data channels (UserChannel* constants). The connection must be authenticated (NewWebSocket called with an API key); this call blocks the send until auth_result has been received.
func (*WebSocket) SubscribeUserDeposits ¶
func (ws *WebSocket) SubscribeUserDeposits(handler MessageHandler) error
SubscribeUserDeposits subscribes to the authenticated deposits channel.
func (*WebSocket) SubscribeUserNotifications ¶
func (ws *WebSocket) SubscribeUserNotifications(handler MessageHandler) error
SubscribeUserNotifications subscribes to the authenticated notifications channel.
func (*WebSocket) SubscribeUserOrders ¶
func (ws *WebSocket) SubscribeUserOrders(handler MessageHandler) error
SubscribeUserOrders subscribes to the authenticated orders channel.
func (*WebSocket) SubscribeUserTrades ¶
func (ws *WebSocket) SubscribeUserTrades(handler MessageHandler) error
SubscribeUserTrades subscribes to the authenticated trades channel.
func (*WebSocket) SubscribeUserTransfers ¶
func (ws *WebSocket) SubscribeUserTransfers(handler MessageHandler) error
SubscribeUserTransfers subscribes to the authenticated transfer channel.
func (*WebSocket) SubscribeUserWithdrawals ¶
func (ws *WebSocket) SubscribeUserWithdrawals(handler MessageHandler) error
SubscribeUserWithdrawals subscribes to the authenticated withdrawals channel.
func (*WebSocket) UnsubscribeInvoice ¶
UnsubscribeInvoice cancels an invoice subscription.
func (*WebSocket) UnsubscribeMarket ¶
UnsubscribeMarket cancels a market subscription and clears its handlers.
func (*WebSocket) UnsubscribeOHLCV ¶
UnsubscribeOHLCV cancels an OHLCV subscription.
func (*WebSocket) UnsubscribeQR ¶
UnsubscribeQR cancels a QR-login subscription.
func (*WebSocket) UnsubscribeUserChannel ¶
UnsubscribeUserChannel cancels a user-channel subscription.
type WebSocketMessage ¶
type WebSocketMessage struct {
Type string `json:"type"`
Channel string `json:"-"`
Data json.RawMessage `json:"-"`
Raw json.RawMessage `json:"-"` // full message bytes
RequestID string `json:"requestId,omitempty"`
Success bool `json:"success,omitempty"`
Error string `json:"error,omitempty"`
OrderID string `json:"orderId,omitempty"`
}
WebSocketMessage is the decoded envelope of every incoming server message. Channel is a synthetic field this SDK derives from the server message (server messages do not carry an explicit "channel" key; we use Type plus any "market", "market_id"/"timeframe", "invoice_id", or "session_token" field as the routing key when dispatching to handlers).
type WebSocketOption ¶
type WebSocketOption func(*WebSocket)
WebSocketOption configures the WebSocket client.
type WithdrawalsService ¶
type WithdrawalsService struct {
// contains filtered or unexported fields
}
WithdrawalsService handles on-chain withdrawal submission via API key.
Only the submission endpoint accepts API keys (with the `withdraw` scope). Validate-address, history, 2FA, and email-confirmation routes are JWT-only and intentionally not exposed in the SDK.
func NewWithdrawalsService ¶
func NewWithdrawalsService(client *HTTPClient) *WithdrawalsService
NewWithdrawalsService creates a new withdrawals service.
func (*WithdrawalsService) Submit ¶
func (s *WithdrawalsService) Submit(req SubmitWithdrawalRequest) (*SubmitWithdrawalResponse, error)
Submit posts an on-chain withdrawal.
API keys with the `withdraw` scope skip interactive 2FA and email confirmation; the 2FA gate was enforced when the scope was granted.
POST /api/submit-withdraw
Amount must be a raw integer in base units (see SubmitWithdrawalRequest).
type WsAuthResult ¶
type WsAuthResult struct {
Type string `json:"type"`
Success bool `json:"success"`
Error string `json:"error,omitempty"`
UserID string `json:"user_id,omitempty"`
}
WsAuthResult mirrors the {"type":"auth_result", ...} message.
type WsCancelResult ¶
type WsCancelResult struct {
Success bool `json:"success"`
Error string `json:"error,omitempty"`
RequestID string `json:"requestId"`
}
WsCancelResult is the response to a WebSocket cancel_order request.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
basic_trading
command
basic_trading shows the public market-data calls and a print-only walk through the authenticated endpoints.
|
basic_trading shows the public market-data calls and a print-only walk through the authenticated endpoints. |
|
mining_pool_example
command
mining_pool_example shows the public mining-pool endpoints (configs, blocks, stats, leaderboard) and — with an API key with the `read` scope — the caller's workers / rewards / payouts.
|
mining_pool_example shows the public mining-pool endpoints (configs, blocks, stats, leaderboard) and — with an API key with the `read` scope — the caller's workers / rewards / payouts. |
|
pools_example
command
pools_example lists liquidity pools and (with an authenticated key) the caller's LP positions and position history.
|
pools_example lists liquidity pools and (with an authenticated key) the caller's LP positions and position history. |
|
websocket_stream
command
websocket_stream subscribes to a market's real-time updates plus (when KLINGEX_API_KEY is set) the authenticated balance + orders channels.
|
websocket_stream subscribes to a market's real-time updates plus (when KLINGEX_API_KEY is set) the authenticated balance + orders channels. |
|
withdrawals_example
command
withdrawals_example demonstrates submitting an on-chain withdrawal via API key.
|
withdrawals_example demonstrates submitting an on-chain withdrawal via API key. |