tabdeal

package module
v0.0.0-...-9e693b3 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2025 License: MIT Imports: 9 Imported by: 0

README

Go Tabdeal

Go Reference Go Report Card Go Version

A clean, strongly typed, and fully documented Go SDK for interacting with the Tabdeal exchange API.

This SDK provides strict typed models, request signing, public/private endpoints, and predictable behavior with minimal abstraction.

Disclaimer

This SDK is unofficial. Use at your own risk.

Features

  • Full support for Tabdeal public & authenticated endpoints
  • Strongly typed request/response structs
  • Simple API key + secret authentication
  • Request signing (HMAC-SHA256)
  • Order placement, cancellation, bulk cancellation
  • Wallets, trades, order history
  • Order book & recent trades
  • Fully structured error handling (APIError, RequestError)

Installation

go get github.com/darhelm/go-tabdeal

Quick Start

package main

import (
    "fmt"
    "time"
    tabdeal "github.com/darhelm/go-tabdeal"
)

func main() {
    client, err := tabdeal.NewClient(tabdeal.ClientOptions{
        ApiKey:    "YOUR_KEY",
        ApiSecret: "YOUR_SECRET",
        Timeout:   5 * time.Second,
    })
    if err != nil {
        panic(err)
    }

    info, err := client.GetMarketInformation()
    if err != nil {
        panic(err)
    }

    fmt.Println((*info)[0].Symbol)
}

Documentation


Examples

Create Client
client, err := tabdeal.NewClient(tabdeal.ClientOptions{
    ApiKey:    "KEY",
    ApiSecret: "SECRET",
    Timeout:   5 * time.Second,
})
Market Information
info, err := client.GetMarketInformation()
fmt.Println((*info)[0].Symbol)
Order Book
ob, err := client.GetOrderBook(types.GetOrderBookParams{
    Symbol: "BTCIRT",
})
fmt.Println(ob.Asks[0], ob.Bids[0])
Recent Trades
trades, err := client.GetRecentTrades(types.GetRecentTradesParams{
    Symbol: "BTCIRT",
})
Wallets
wallets, err := client.GetWallets(types.GetWalletParams{
    Asset: "USDT",
})
Create Order
resp, err := client.CreateOrder(types.CreateOrderParams{
    Symbol:   "BTCIRT",
    Side:     "BUY",
    Type:     "LIMIT",
    Quantity: 0.01,
    Price:    1500000000,
})
Cancel Order
cancel, err := client.CancelOrder(types.CancelOrderParams{
    Symbol:  "BTCIRT",
    OrderId: 1234,
})
Bulk Cancel
bulk, err := client.CancelOrderBulk(types.CancelOrderBulkParams{
    Symbol: "BTCIRT",
})
Order History
history, err := client.GetOrdersHistory(types.GetUserOrdersHistoryParams{
    Symbol: "BTCIRT",
})
Open Orders
open, err := client.GetOpenOrders(types.GetOpenOrdersParams{
    Symbol: "BTCIRT",
})
Order Status
st, err := client.GetOrderStatus(types.GetOrderStatusParams{
    OrderId: 1234,
})
User Trades
trades, err := client.GetUserTrades(types.GetUserTradesParams{
    Symbol: "BTCIRT",
})
Error Handling
if err != nil {
    if apiErr, ok := err.(*tabdeal.APIError); ok {
        fmt.Println(apiErr.Code, apiErr.Message, apiErr.Detail)
    }
}

License

MIT License.

Documentation

Index

Constants

View Source
const (
	// BaseUrl is the root URL for the Tabdeal Market API.
	BaseUrl = "https://api1.tabdeal.org"
	Version = "v1"
)

Constants defining the API base URL and version.

Variables

This section is empty.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	GoTabdealError

	Code       int16
	Msg        string
	Detail     string
	StatusCode int

	// Fields collects all key–value pairs extracted from the error payload,
	// including fields not explicitly modeled in this struct.
	Fields map[string][]string
}

APIError represents an error response returned by Tabdeal's REST API. Tabdeal does not enforce a uniform error schema across endpoints, but error payloads commonly include the following fields:

  • code: a short identifier describing the error category
  • msg: a human-readable error message
  • detail: optional additional context or validation information

Because different endpoints may return additional or undocumented fields, APIError retains a Fields map containing all parsed key–value pairs from the server's response body.

type Client

type Client struct {
	// HttpClient is the HTTP client used for API requests.
	// Defaults to the Go standard library's http.DefaultClient.
	HttpClient *http.Client

	// BaseUrl is the base URL of the API used by this client.
	// Defaults to the constant BaseUrl.
	BaseUrl string

	// Version is the Api's current version
	Version string

	// ApiKey is the API key for authentication.
	ApiKey string

	// ApiSecret is the API Secret for authentication.
	ApiSecret string

	// AutoAuth enables automatic authentication if no valid tokens are provided.
	AutoAuth bool

	// AutoRefresh enables automatic refreshing of the access token when it expires.
	AutoRefresh bool
}

Client represents the API client for interacting with the Tabdeal Market API. It manages authentication, base URL, and API requests.

func NewClient

func NewClient(opts ClientOptions) (*Client, error)

NewClient initializes a new Tabdeal API client using the provided configuration options. It sets up the HTTP client, assigns API credentials, and applies any optional overrides such as custom base URLs or timeouts.

Parameters:

  • opts: ClientOptions with the following fields:
  • HttpClient: optional custom HTTP client. If nil, a new http.Client is created using opts.Timeout.
  • Timeout: request timeout used when creating a default HttpClient.
  • BaseUrl: optional override for the API base URL. Defaults to BaseUrl ("https://api1.tabdeal.org") if empty.
  • ApiKey: API key used for authenticated endpoints.
  • ApiSecret: API secret used for request signing.

Returns:

  • A pointer to an initialized Client.
  • Never returns an error, because no network operations or authentication are performed inside NewClient.

Behavior:

  • If opts.BaseUrl is provided, it overrides the default BaseUrl.
  • If opts.HttpClient is nil, a new http.Client is constructed using opts.Timeout.
  • ApiKey and ApiSecret are stored on the client for use in authenticated requests.
  • No authentication request is performed.
  • No token refresh logic is invoked.

Example:

opts := ClientOptions{
    ApiKey:    "your-api-key",
    ApiSecret: "your-secret",
    Timeout:   5 * time.Second,
}

client, err := NewClient(opts)
if err != nil {
    panic(err)
}

// The client is now ready to call API methods:
info, _ := client.GetMarketInformation()

func (*Client) ApiRequest

func (c *Client) ApiRequest(method, endpoint string, auth bool, body interface{}, result interface{}) error

ApiRequest is a convenience wrapper that builds a Tabdeal API URL using createApiURI() and delegates the actual HTTP call to Request().

Parameters:

  • method: HTTP method ("GET", "POST").
  • endpoint: The endpoint path, such as "/market/orders/add".
  • version: Tabdeal version string ("v2", "v3"). May be empty.
  • auth: Whether this call requires Authorization: Token <key>.
  • otpRequired: Whether this endpoint requires X-TOTP.
  • body: Struct for GET params or POST JSON body.
  • result: Destination struct for response JSON.

Returns:

  • nil on success.
  • See Request() for structured errors.

Behavior:

  • Constructs URL = BaseUrl + "/api/{version}/{endpoint}".
  • Passes all fields to Request() unchanged.

Example:

var stats t.Tickers
err := client.ApiRequest("GET", "/market/stats", "", false, false, params, &stats)

func (*Client) CancelOrder

func (c *Client) CancelOrder(params t.CancelOrderParams) (*t.CancelOrderResponse, error)

CancelOrder cancels a single active order.

Endpoint:

DELETE /api/v1/order?symbol=...&orderId=...

Params:

  • Symbol
  • OrderId OR OrigClientOrderId

Authentication:

  • Required. Signed request.

Returns:

  • *t.CancelOrderResponse containing BaseOrderResponse
  • error on API or network failure.

Example:

client.CancelOrder(t.CancelOrderParams{
    Symbol: "BTCUSDT",
    OrderId: 1234567,
})

func (*Client) CancelOrderBulk

func (c *Client) CancelOrderBulk(params t.CancelOrderBulkParams) (*[]*t.CancelOrderResponse, error)

CancelOrderBulk cancels all open orders for a symbol.

Endpoint:

DELETE /api/v1/openOrders?symbol=...

Params:

  • Symbol (from BaseSymbolParams)

Authentication:

  • Required.

Returns:

  • []*t.CancelOrderResponse for all canceled orders.
  • error on API or network failure.

Example:

resp, _ := client.CancelOrderBulk(t.CancelOrderBulkParams{
    Symbol: "BTCUSDT",
})

func (*Client) CreateOrder

func (c *Client) CreateOrder(params t.CreateOrderParams) (*t.CreateOrderResponse, error)

CreateOrder submits a new spot order to Tabdeal.

Endpoint:

POST /api/v1/order

Params (t.CreateOrderParams):

  • Side ("BUY"/"SELL")
  • Type ("LIMIT", "MARKET")
  • Quantity (required)
  • Price (for limit orders)
  • StopPrice (for stop orders)
  • Symbol/TabdealSymbol (from BaseSymbolParams)

Authentication:

  • Required. Signs parameters using API secret.

Returns:

  • *t.CreateOrderResponse with full order details and fills.
  • error on failure.

Example:

resp, _ := client.CreateOrder(t.CreateOrderParams{
    Symbol: "BTCUSDT",
    Side: "BUY",
    Type: "LIMIT",
    Quantity: 0.01,
    Price: 950000000,
})

func (*Client) GetMarketInformation

func (c *Client) GetMarketInformation() (*[]*t.MarketInformation, error)

GetMarketInformation retrieves full market metadata from Tabdeal, including symbol configurations, precision rules, filters, and trading permissions.

Endpoint:

GET /r/api/v1/exchangeInfo

Returns:

  • []*t.MarketInformation: list of market definitions provided by Tabdeal.
  • error on network or API failure.

Behavior:

  • No authentication required.
  • Returns exchange-wide configuration for all markets.

Example:

info, err := client.GetMarketInformation()
if err != nil { panic(err) }
fmt.Println(info[0].Symbol)

func (*Client) GetOpenOrders

func (c *Client) GetOpenOrders(params t.GetOpenOrdersParams) (*[]*t.BaseOrderResponse, error)

GetOpenOrders retrieves all currently-open orders for a market.

Endpoint:

GET /api/v1/openOrders?symbol=...

Params:

  • Symbol (from BaseSymbolParams)

Authentication:

  • Required.

Returns:

  • []*t.BaseOrderResponse

Example:

open, _ := client.GetOpenOrders(t.GetOpenOrdersParams{Symbol: "BTCUSDT"})

func (*Client) GetOrderBook

func (c *Client) GetOrderBook(params t.GetOrderBookParams) (*t.OrderBook, error)

GetOrderBook returns the current depth (order book) for a specific market.

Endpoint:

GET /r/api/v1/depth?symbol=SYMBOL

Params:

  • params.Symbol: market symbol (BTCUSDT, BTCIRT, etc.)

Returns:

  • *t.OrderBook including raw bids and asks.
  • error on failure.

Behavior:

  • No authentication required.
  • Depth is returned in aggregated form: [][]string.

Example:

book, _ := client.GetOrderBook(t.GetOrderBookParams{Symbol: "BTCUSDT"})
fmt.Println(book.Bids[0])

func (*Client) GetOrderStatus

func (c *Client) GetOrderStatus(params t.GetOrderStatusParams) (*t.OrderStatusResponse, error)

GetOrderStatus retrieves the full status of a specific order.

Endpoint:

GET /api/v1/order?symbol=...&orderId=... OR &origClientOrderId=...

Params:

  • OrderId or OrigClientOrderId

Authentication:

  • Required.

Returns:

  • *t.OrderStatusResponse

Example:

st, _ := client.GetOrderStatus(t.GetOrderStatusParams{OrderId: 1234})

func (*Client) GetOrdersHistory

func (c *Client) GetOrdersHistory(params t.GetUserOrdersHistoryParams) (*[]*t.BaseOrderResponse, error)

GetOrdersHistory retrieves historical orders for the authenticated user.

Endpoint:

GET /api/v1/allOrders?symbol=...&startTime=...&endTime=...&limit=...

Params:

  • Symbol
  • StartTime / EndTime (optional)
  • Limit (optional)

Authentication:

  • Required.

Returns:

  • []*t.BaseOrderResponse
  • error

Example:

history, _ := client.GetOrdersHistory(t.GetUserOrdersHistoryParams{
    Symbol: "BTCUSDT",
    Limit: 50,
})

func (*Client) GetRecentTrades

func (c *Client) GetRecentTrades(params t.GetRecentTradesParams) (*[]*t.Trade, error)

GetRecentTrades retrieves most recent trades for a market.

Endpoint:

GET /r/api/v1/trades?symbol=SYMBOL&limit=...

Params:

  • Symbol (required)
  • Limit (optional)

Returns:

  • []*t.Trade sorted newest → oldest.
  • error on API or network failure.

Behavior:

  • No authentication required.

Example:

trades, _ := client.GetRecentTrades(t.GetRecentTradesParams{Symbol: "BTCUSDT"})
fmt.Println(trades[0].Price)

func (*Client) GetServerTime

func (c *Client) GetServerTime() (*t.ServerTime, error)

func (*Client) GetUserTrades

func (c *Client) GetUserTrades(params t.GetUserTradesParams) (*[]*t.UserTradeResponse, error)

GetUserTrades returns the authenticated user's trade history for a symbol.

Endpoint:

GET /api/v1/myTrades?symbol=...&fromId=...

Params:

  • Symbol
  • FromId (pagination, optional)

Authentication:

  • Required.

Returns:

  • []*t.UserTradeResponse
  • error

Example:

trades, _ := client.GetUserTrades(t.GetUserTradesParams{
    Symbol: "BTCUSDT",
})

func (*Client) GetWallets

func (c *Client) GetWallets(params t.GetWalletParams) (*[]*t.Wallet, error)

GetWallets retrieves funding wallet balances for the authenticated user.

Endpoint:

GET /api/v1/get-funding-asset?asset=...

Params:

  • Asset (optional): filter by a specific asset.

Authentication:

  • Required. Uses X-MBX-APIKEY header.

Returns:

  • []*t.Wallet containing asset, free, and freeze amounts.
  • error if authentication is missing or API responds with error.

Example:

balances, _ := client.GetWallets(t.GetWalletParams{Asset: "USDT"})
fmt.Println(balances[0].Free)

func (*Client) Request

func (c *Client) Request(method string, url string, auth bool, body interface{}, result interface{}) error

Request sends an HTTP request to a full Tabdeal URL and handles:

  • optional authentication
  • automatic TOTP header placement
  • request serialization (JSON or query params)
  • response deserialization
  • structured API error handling

Parameters:

  • method: "GET" or "POST".
  • url: Fully constructed URL (already includes version when needed).
  • auth: Whether the request requires an Authorization header.
  • otpRequired: Whether X-TOTP should be sent for this specific request.
  • body: For GET, serialized into URL params; for POST, JSON-encoded.
  • result: Optional pointer to the output struct into which JSON is unmarshaled.

Returns:

  • nil on success.
  • *RequestError on network/encoding issues.
  • *APIError when Tabdeal returns status != 2xx.

Behavior:

  • GET: struct → ?a=b&c=d via StructToURLParams.
  • POST: struct → JSON in request body.
  • If auth=true:
  • handleAutoRefresh() is executed when AutoRefresh is enabled.
  • assertAuth() ensures ApiKey is set.
  • User-Agent and Authorization headers are required.
  • X-TOTP header is added when otpRequired=true.
  • On error HTTP status, parseErrorResponse() maps Tabdeal JSON error objects into APIError (fields: status, code, message, detail).

Dependencies:

  • StructToURLParams
  • assertAuth()
  • handleAutoRefresh()
  • parseErrorResponse()

Errors:

  • "failed to marshal request body"
  • "failed to convert struct to URL params"
  • "failed to send request"
  • "failed to unmarshal response"
  • APIError (status, code, message, detail)

Example:

var res t.OrderStatus
err := client.Request("POST", url, true, true, params, &res)
if err != nil {
    return err
}

type ClientOptions

type ClientOptions struct {
	// HttpClient is the custom HTTP client to be used for API requests.
	// If nil, the default HTTP client is used.
	HttpClient *http.Client

	// Timeout specifies the request timeout duration for the HTTP client.
	Timeout time.Duration

	// BaseUrl is the base URL of the API. Defaults to the constant BaseUrl
	// if not provided.
	BaseUrl string

	// ApiKey is the token used for authenticated API requests.
	ApiKey string

	// ApiSecret is the token used for authenticated API requests.
	ApiSecret string
}

ClientOptions represents the configuration options for creating a new API client. These options allow customization of the HTTP client, authentication tokens

type GoTabdealError

type GoTabdealError struct {
	Message string
	Err     error
}

func (*GoTabdealError) Error

func (e *GoTabdealError) Error() string

func (*GoTabdealError) Unwrap

func (e *GoTabdealError) Unwrap() error

type RequestError

type RequestError struct {
	GoTabdealError
	Operation string
}

RequestError Error returned when a request cannot be created/sent/read.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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