Documentation
¶
Index ¶
- Constants
- type APIError
- type Client
- func (c *Client) ApiRequest(method, endpoint string, version string, auth bool, otpRequired bool, ...) error
- func (c *Client) Authenticate(Username, Password string) (*t.AuthenticationResponse, error)
- func (c *Client) CancelOrder(params t.CancelOrderParams) (*t.CancelOrderResponse, error)
- func (c *Client) CancelOrderBulk(params t.CancelOrderBulkParams) (*t.CancelOrderResponse, error)
- func (c *Client) CreateOrder(params t.CreateOrderParams) (*t.OrderStatus, error)
- func (c *Client) GetNobitexConfig() (*t.Config, error)
- func (c *Client) GetOpenOrders(params t.GetOrdersListParams) (*t.OrdersListResponse, error)
- func (c *Client) GetOrderBook(symbol string) (*t.OrderBook, error)
- func (c *Client) GetOrderStatus(params t.GetOrderStatusParams) (*t.OrderStatus, error)
- func (c *Client) GetOrdersHistory(params t.GetOrdersListParams) (*t.OrdersListResponse, error)
- func (c *Client) GetRecentTrades(symbol string) (*t.Trades, error)
- func (c *Client) GetTickers(params t.GetTickersParams) (*t.Tickers, error)
- func (c *Client) GetUserTrades(params t.GetUserTradesParams) (*t.UserTrades, error)
- func (c *Client) GetWallets(params t.GetWalletParams) (*t.Wallets, error)
- func (c *Client) Request(method string, url string, auth bool, otpRequired bool, body interface{}, ...) error
- type ClientOptions
- type GoNobitexError
- type RequestError
Constants ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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.