nobitex

package module
v0.0.0-...-ff5fcfd Latest Latest
Warning

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

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

README

Go Nobitex

Go Reference Go Report Card Go Version

A comprehensive, type-safe, and fully documented Go SDK for interacting with the Nobitex cryptocurrency exchange API.
This SDK provides a clean and intuitive interface for authentication, wallet access, order execution, and real-time market data.

Disclaimer

This SDK is unofficial and not officially affiliated with Nobitex.
Use at your own risk — the author(s) assume no responsibility for any losses resulting from API usage or trading logic.

Features

  • Full implementation of public and private Nobitex endpoints
  • Strongly typed request/response models
  • Full OTP authentication support (TOTP, compatible with github.com/pquerna/otp)
  • Auto-refresh of API keys (4 hours or ~30 days depending on remember mode)
  • Real-time market data: tickers, order books, recent trades
  • Wallet management
  • Full order lifecycle: create, cancel, bulk-cancel, history, status
  • Structured error handling (APIError, RequestError)
  • Clean and maintainable Go codebase

Installation

go get github.com/darhelm/go-nobitex

Quick Start

package main

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

func main() {
    client, err := nobitex.NewClient(nobitex.ClientOptions{
        Username:    "user@example.com",
        Password:    "your-password",
        OtpCode:     "123456",
        Remember:    "yes",
        UserAgent:   "MyBot/1.0",
        AutoRefresh: true,
    })
    if err != nil {
        panic(err)
    }

    cfg, err := client.GetNobitexConfig()
    if err != nil {
        panic(err)
    }

    fmt.Println(cfg.Nobitex.ActiveCurrencies)
}

Documentation


Examples

Authentication

client, err := nobitex.NewClient(nobitex.ClientOptions{
    Username:  "user@example.com",
    Password:  "pass",
    OtpCode:   "123456",
    Remember:  "yes",
    UserAgent: "Bot/1.0",
})

Get Nobitex Config

cfg, err := client.GetNobitexConfig()
fmt.Println(cfg.Nobitex.AllCurrencies)

Get Tickers

tickers, err := client.GetTickers(types.GetTickersParams{
    SrcCurrency: "btc",
    DstCurrency: "usdt",
})
for symbol, t := range tickers.Stats {
    fmt.Println(symbol, t.Latest)
}

Get Order Book

orderBook, err := client.GetOrderBook("btc-usdt")
fmt.Println(ob.Asks[0], ob.Bids[0])

Get Recent Trades

recentTrades, err := client.GetRecentTrades("btc-usdt")

Get Wallets

balances, err := client.GetWallets(types.GetWalletParams{
    Currencies: []string{"BTC", "USDT"},
})

Create Order

createOrder, err := client.CreateOrder(types.CreateOrderParams{
    Execution:   "limit",
    Type:        "buy",
    SrcCurrency: "btc",
    DstCurrency: "usdt",
    Amount:      "0.01",
    Price:       "2000000000",
})

Cancel Order

cancel, err = client.CancelOrder(types.CancelOrderParams{
    Id: 123,
})

Bulk Cancel

bulkCancel, err = client.CancelOrderBulk(types.CancelOrderBulkParams{
    Hours:       1,
    Execution:   "limit",
    TradeType:   types.TradeTypeSpot,
    SrcCurrency: "btc",
    DstCurrency: "usdt",
})

Order History

orderHistory, _ := client.GetOrdersHistory(types.GetOrdersListParams{
    SrcCurrency: "btc",
    DstCurrency: "usdt",
})

Open Orders

openOrders, _ := client.GetOpenOrders(types.GetOrdersListParams{})

Order Status

orderStatus, _ := client.GetOrderStatus(types.GetOrderStatusParams{
    Id: 123456,
})

User Trades

userTrades, _ := client.GetUserTrades(types.GetUserTradesParams{
    SrcCurrency: "btc",
    DstCurrency: "usdt",
})

Error Handling

if err != nil {
    if apiErr, ok := err.(*nobitex.APIError); ok {
        fmt.Println(apiErr.Status, apiErr.Code, apiErr.Message, apiErr.Detail)
    }
}

Contributing

  1. Fork the repository
  2. Create a branch in this example feat/new-feature
  3. Commit changes
  4. Open Pull Request

Before pushing:

go vet ./...
golangci-lint run

License

MIT License.

Documentation

Index

Constants

View Source
const (
	// BaseUrl is the root URL for the Nobitex Market API.
	BaseUrl = "https://apiv2.nobitex.ir"
)

Constants defining the API base URL and version.

Variables

This section is empty.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	GoNobitexError

	Status     string
	Code       string
	Message    string
	Detail     string
	StatusCode int

	// Map of all parsed key->values for inspection (similar to go-bitpin)
	Fields map[string][]string
}

APIError represents *any* server-side error returned by Nobitex.

Nobitex usually returns one of:

{ "status": "failed", "code": "ErrCode", "message": "msg" }
{ "detail": "something went wrong" }
{ "status": "failed", "message": "msg", "detail": "extra" }
{ ... totally undocumented garbage ... }

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

	Username  string
	Password  string
	OtpSecret string
	OtpCode   string

	Remember  string
	UserAgent string

	AuthTime time.Time

	// ApiKey is the API key for authentication.
	ApiKey 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 Nobitex Market API. It manages authentication, base URL, and API requests.

func NewClient

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

NewClient initializes a new Nobitex API client using the provided configuration options. It prepares the HTTP client, authentication settings, TOTP handling, base URL, and automatic re-authentication behavior.

Parameters:

  • opts: A ClientOptions struct containing configuration fields such as:
  • HttpClient: optional custom HTTP client.
  • Timeout: request timeout used when no custom client is provided.
  • BaseUrl: optional override for the Nobitex base URL.
  • Username / Password: credentials for API login.
  • OtpSecret / OtpCode: TOTP configuration for X-TOTP header.
  • ApiKey: an already-issued Nobitex API key (optional).
  • Remember: long-lived ("yes") vs short-lived ("no") login sessions.
  • AutoAuth: whether to auto-authenticate if ApiKey is missing.
  • AutoRefresh: whether to re-authenticate when Remember expires.

Returns:

  • A pointer to an initialized Client.
  • An error if automatic authentication fails or TOTP generation fails.

Behavior:

  • If opts.BaseUrl is provided, it overrides the default base URL ("https://apiv2.nobitex.ir/").
  • If opts.HttpClient is nil, a new http.Client with opts.Timeout is created.
  • If opts.ApiKey is empty and username/password+TOTP are provided, NewClient performs an immediate login by calling Authenticate().
  • If opts.OtpSecret is provided, NewClient automatically generates a TOTP one-time password using utils.GenerateOtpCode.
  • Sets AuthTime to the time of successful authentication.
  • If AutoRefresh is enabled, immediately checks whether the API key must be refreshed based on Remember ("yes" = ~30 days, "no" = ~4 hours).

Dependencies:

  • utils.GenerateOtpCode for TOTP generation.
  • Authenticate() for obtaining a Nobitex API key.
  • handleAutoRefresh() for Remember-based token rotation.

Errors:

  • Returned directly from Authenticate() on login failure.
  • Returned if TOTP generation fails.
  • Returned from handleAutoRefresh() if refresh logic cannot proceed.

Example:

opts := ClientOptions{
    Username:   "user@example.com",
    Password:   "password",
    OtpSecret:  "AuthSecret",
    Remember:   "yes",
    AutoAuth:   true,
    AutoRefresh: true,
}
client, err := NewClient(opts)
if err != nil {
    log.Fatalf("failed to initialize client: %v", err)
}

func (*Client) ApiRequest

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

ApiRequest is a convenience wrapper that builds a Nobitex 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: Nobitex 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) Authenticate

func (c *Client) Authenticate(Username, Password string) (*t.AuthenticationResponse, error)

Authenticate logs in to Nobitex using username, password, captcha="api", and an X-TOTP code. It retrieves a session API key for authenticated endpoints.

Endpoint:

POST /auth/login/

Parameters:

  • Username: account email.
  • Password: account password.

The function automatically sends:

  • captcha="api"
  • remember=<client.Remember>
  • X-TOTP header (generated or provided)

Returns:

  • *AuthenticationResponse containing:
  • Status ("ok")
  • Key (API key used in Authorization: Token <key>)
  • Device (session device ID)
  • An error if login fails.

Behavior:

  • Constructs a JSON object with username, password, captcha, remember.
  • Sends X-TOTP via Request().
  • On success, updates c.ApiKey with response.Key.
  • Does NOT manage refresh tokens (Nobitex does not use them).

Errors:

  • "Username and/or password are empty"
  • APIError with status/code/message/detail

Example:

resp, err := client.Authenticate("me@example.com", "secret")
if err != nil {
    return err
}
fmt.Println("API key:", resp.Key)

func (*Client) CancelOrder

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

CancelOrder cancels a single existing order.

Endpoint:

POST /market/orders/update-status

Parameters:

  • params: t.CancelOrderParams Id or ClientOrderId Status="canceled"

Returns:

  • *t.CancelOrderResponse on success, always contains "status": "ok" on status code 200
  • APIError on failure

Behavior:

  • Requires authentication.
  • The SDK enforces params.Status="canceled" automatically.

Example:

err := client.CancelOrder(t.CancelOrderParams{Id:12345})

func (*Client) CancelOrderBulk

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

CancelOrderBulk cancels multiple orders based on filter criteria.

Endpoint:

POST /market/orders/cancel-old

Parameters:

  • params: t.CancelOrderBulkParams Hours: cancel orders older than X hours Execution: limit/market/... TradeType: spot/margin SrcCurrency / DstCurrency

Returns:

  • *t.CancelOrderResponse on success, always contains "status": "ok" on status code 200
  • APIError on failure

Behavior:

  • Requires authentication.
  • Cancels all matching orders without returning per-order info.

Example:

err := client.CancelOrderBulk(t.CancelOrderBulkParams{Hours: 6})

func (*Client) CreateOrder

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

CreateOrder submits a new trading order (spot or margin) to Nobitex.

Endpoint:

POST /market/orders/add

Parameters:

  • params: t.CreateOrderParams containing: Execution ("limit","market","stop_limit","stop_market") SrcCurrency DstCurrency Type ("buy"/"sell") Amount (optional for some execution types) Price (required for limit orders) StopPrice / StopLimitPrice (for stop orders) ClientOrderId (optional)

Returns:

  • *t.OrderStatus containing the created order state:

    Status Order → OrderStatusResponse

Behavior:

  • Requires authentication.
  • No TOTP required for order placement (otpRequired=false).
  • Returns server-evaluated matched/unmatched amounts, fees, timestamps.

Example:

order, err := client.CreateOrder(t.CreateOrderParams{
    Execution:   "limit",
    SrcCurrency: "btc",
    DstCurrency: "usdt",
    Type:        "buy",
    Amount:      "0.01",
    Price:       "1500000000",
})

func (*Client) GetNobitexConfig

func (c *Client) GetNobitexConfig() (*t.Config, error)

GetNobitexConfig fetches global Nobitex configuration including:

  • allCurrencies
  • activeCurrencies
  • amountPrecisions[asset]
  • pricePrecisions[asset]

Endpoint:

GET /api/v2/options

Returns:

  • *t.Config containing t.Nobitex metadata.

Behavior:

  • No authentication required.
  • Calls ApiRequest("GET", "options", "v2").

Example:

cfg, err := client.GetNobitexConfig()
if err != nil {
    log.Fatal(err)
}
fmt.Println(cfg.Nobitex.ActiveCurrencies)

func (*Client) GetOpenOrders

func (c *Client) GetOpenOrders(params t.GetOrdersListParams) (*t.OrdersListResponse, error)

GetOpenOrders retrieves only active/open orders.

Endpoint:

GET /market/orders/list

Parameters:

  • params: t.GetOrdersListParams Status is overridden to "open" internally.

Returns:

  • *t.OrdersListResponse

Behavior:

  • Requires authentication.
  • Same filtering as GetOrdersHistory except Status="open".

Example:

openOrders, _ := client.GetOpenOrders(t.GetOrdersListParams{})

func (*Client) GetOrderBook

func (c *Client) GetOrderBook(symbol string) (*t.OrderBook, error)

GetOrderBook retrieves aggregated asks and bids for a specific market symbol.

Endpoint:

GET /api/v3/orderbook/{symbol}/

Parameters:

  • symbol: market pair in Nobitex format (e.g. "BTCUSDT" or "BTCIRT").

Returns:

  • *t.OrderBook containing: Status LastUpdate LastTradePrice Asks [][]string Bids [][]string

Behavior:

  • No authentication required.
  • Uses version "v3" (Nobitex newest orderbook specification).

Example:

ob, _ := client.GetOrderBook("BTCUSDT")
fmt.Println(ob.Asks[0], ob.Bids[0])

func (*Client) GetOrderStatus

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

GetOrderStatus retrieves detailed status for a specific order using either Id or ClientOrderId.

Endpoint:

POST /market/orders/status

Parameters:

  • params: t.GetOrderStatusParams

Returns:

  • *t.OrderStatus containing:

    Status Order → OrderStatusResponse

Behavior:

  • Requires authentication.
  • POST is used because Nobitex expects request body.

Example:

st, _ := client.GetOrderStatus(t.GetOrderStatusParams{Id: 12345})

func (*Client) GetOrdersHistory

func (c *Client) GetOrdersHistory(params t.GetOrdersListParams) (*t.OrdersListResponse, error)

GetOrdersHistory retrieves historical user orders using filter criteria.

Endpoint:

GET /market/orders/list

Parameters:

  • params: t.GetOrdersListParams Status ("open","closed","canceled", etc.) Type ("buy"/"sell") Execution ("limit","market") TradeType ("spot","margin") SrcCurrency / DstCurrency Details, FromId, Order (sorting/id filters)

Returns:

  • *t.OrdersListResponse containing:

    Status Orders []OrdersListResponse

Behavior:

  • Requires authentication.
  • Filters determine scope and ordering.

Example:

resp, _ := client.GetOrdersHistory(t.GetOrdersListParams{
    Status:"closed",
    SrcCurrency:"btc",
    DstCurrency:"usdt",
})

func (*Client) GetRecentTrades

func (c *Client) GetRecentTrades(symbol string) (*t.Trades, error)

GetRecentTrades retrieves recent trade executions for a market.

Endpoint:

GET /api/v2/trades/{symbol}/

Parameters:

  • symbol: market pair ("BTCUSDT", "ETHIRT", etc.)

Returns:

  • *t.Trades where each Trade has: Time Price Volume Type ("buy"/"sell")

Behavior:

  • No authentication required.
  • Returns trades sorted newest-first.

Example:

trades, _ := client.GetRecentTrades("BTCUSDT")
fmt.Println(trades[0].Price, trades[0].Type)

func (*Client) GetTickers

func (c *Client) GetTickers(params t.GetTickersParams) (*t.Tickers, error)

GetTickers retrieves market statistics for one or more trading pairs. It delegates to the Nobitex market stats endpoint.

Endpoint:

GET /api/market/stats

Parameters:

  • params: t.GetTickersParams
  • SrcCurrency
  • DstCurrency

Returns:

  • *t.Tickers containing: Status Stats[market] → t.Ticker

Behavior:

  • No authentication required.
  • Serializes params as query string.

Example:

stats, err := client.GetTickers(t.GetTickersParams{SrcCurrency:"btc",DstCurrency:"usdt"})
if err != nil { ... }
fmt.Println(stats.Stats["BTCUSDT"].Latest)

func (*Client) GetUserTrades

func (c *Client) GetUserTrades(params t.GetUserTradesParams) (*t.UserTrades, error)

GetUserTrades retrieves the authenticated user's trade history.

Endpoint:

GET /market/trades/list

Parameters:

  • params: t.GetUserTradesParams SrcCurrency DstCurrency FromId (for pagination)

Returns:

  • *t.UserTrades containing: Status Trades []UserTradeResponse HasNext bool

Behavior:

  • Requires authentication.
  • Supports pagination via FromId.

Example:

trades, _ := client.GetUserTrades(t.GetUserTradesParams{
    SrcCurrency:"btc",
    DstCurrency:"usdt",
})

func (*Client) GetWallets

func (c *Client) GetWallets(params t.GetWalletParams) (*t.Wallets, error)

GetWallets retrieves a list of wallets for the authenticated user from the API. It sends a GET request to the `/wallets` endpoint and returns wallet information based on the provided parameters.

Parameters:

  • params: A `GetWalletParams` struct containing optional filters for querying specific wallets, such as by currency list or trade type ("spot"/"margin").

Returns:

  • A pointer to a `Wallets` struct containing the list of wallets with fields:
  • id
  • balance
  • blocked (frozen)
  • An error if the request fails, authentication is missing, or the response cannot be processed.

Behavior:

  • Sends a GET request to `/api/v2/wallets`
  • Requires authentication (`auth=true`)
  • Response JSON is unmarshalled into `t.Wallets`.

Example:

params := t.GetWalletParams{
    Currencies: []string{"BTC","USDT"},
    TradeType:  "spot",
}
wallets, err := client.GetWallets(params)
if err != nil { ... }
fmt.Println(wallets.Wallets["btc"].Balance)

Dependencies:

  • ApiRequest

Errors:

  • APIError (status, code, message, detail)
  • RequestError (network/JSON issues)

func (*Client) Request

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

Request sends an HTTP request to a full Nobitex 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 Nobitex 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 Nobitex 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

	Username  string
	Password  string
	OtpSecret string
	OtpCode   string

	Remember  string
	UserAgent string

	// ApiKey is the token used for authenticated API requests.
	ApiKey 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
}

ClientOptions represents the configuration options for creating a new API client. These options allow customization of the HTTP client, authentication tokens, API credentials, and automatic authentication/refresh behaviors.

type GoNobitexError

type GoNobitexError struct {
	Message string
	Err     error
}

func (*GoNobitexError) Error

func (e *GoNobitexError) Error() string

func (*GoNobitexError) Unwrap

func (e *GoNobitexError) Unwrap() error

type RequestError

type RequestError struct {
	GoNobitexError
	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