Skip to Content
Usage ExamplesTrading Operations

Trading Operations

Learn how to perform trading operations using the NordUser class.

[!TIP] Check out the API Reference for a full breakdown of every method, including argument tables and expected responses.

[!NOTE] Other languages: See Python Trading for Python examples, or REST API for raw HTTP API usage.

Prerequisites

Ensure you have an initialized NordUser instance. See Creating a User for details.

import { Nord, NordUser, Side, FillMode, TriggerKind, Intent } from "@n1xyz/nord-ts"; import { PublicKey } from "@solana/web3.js"; // user is an initialized instance of NordUser

Placing Orders

Place various types of orders using the placeOrder method.

Method: nordUser.placeOrder(orderConfig)

Parameters

NameTypeRequiredDescription
marketIdnumberYesThe ID of the market (e.g., 0 for BTC/USDC).
sideSideYesOrder side: Side.Bid (Buy) or Side.Ask (Sell).
fillModeFillModeYesFillMode.Limit, FillMode.PostOnly, FillMode.ImmediateOrCancel, or FillMode.FillOrKill.
sizenumberYesThe size of the order in base asset units.
pricenumberNo*The limit price. Required if fillMode is Limit.
isReduceOnlybooleanNoIf true, the order will only reduce an existing position. Default false.

Return Value

Returns a Promise that resolves to an object containing the orderId.

interface ReducedOrder { orderId: bigint; // The order that was reduced remainingSize: bigint; // Size remaining after reduction (0 if fully cancelled) cancelledSize: bigint; // Size that was removed price: bigint; // Order price } { orderId: bigint, actionId: bigint, fills: Receipt_Trade[], reducedOrders: ReducedOrder[], // Orders shrunk/cancelled by reduce-only maintenance }

[!NOTE] The reducedOrders array contains any resting reduce-only orders that were automatically shrunk or cancelled as a result of this action. See the Reduce-Only Orders section for details.

Examples

Limit Order

const limitOrder = await user.placeOrder({ marketId: 0, // e.g., BTC/USDC market side: Side.Bid, // Buy fillMode: FillMode.Limit, isReduceOnly: false, size: 0.1, // Quantity price: 50000, // Limit Price }); console.log("Placed limit order:", limitOrder.orderId);

Market Order

const marketOrder = await user.placeOrder({ marketId: 0, side: Side.Ask, fillMode: FillMode.FillOrKill, // FOK for market orders isReduceOnly: false, size: 0.5, }); console.log("Placed market order:", marketOrder.actionId);

Reduce-Only Order

For perpetual markets, reduce-only orders support all fill modes: Limit, PostOnly, ImmediateOrCancel, and FillOrKill. Reduce-only orders require an existing non-zero perp position and must be on the contra side.

[!IMPORTANT] In-engine reduce-only maintenance:

  • If the total contra exposure (reduce-only orders) exceeds the remaining position capacity, the engine automatically shrinks or cancels resting reduce-only orders, starting from the worst price.
  • IOC oversize is clamped to position size; FOK oversize is rejected.
  • Limit and PostOnly reduce-only orders may rest on the book.
  • Non-reduce contra orders are never auto-evicted.
  • Affected orders are reported via the reducedOrders field in the response and the reduced_orders field in account WebSocket updates.
const reduceOnlyOrder = await user.placeOrder({ marketId: 0, side: Side.Ask, fillMode: FillMode.Limit, isReduceOnly: true, size: 0.1, price: 55000, }); // Check if any existing reduce-only orders were shrunk/cancelled if (reduceOnlyOrder.reducedOrders?.length) { console.log("Reduced orders:", reduceOnlyOrder.reducedOrders); }

Canceling Orders

Cancel an existing order using its orderId.

Method: nordUser.cancelOrder(orderId)

Parameters

NameTypeRequiredDescription
orderIdbigint | stringYesThe unique identifier of the order to cancel.

Return Value

Returns a Promise containing the canceled order details.

{ orderId: bigint, // ... other order details }

Example

const cancelResult = await user.cancelOrder(existingOrderId); console.log("Cancelled order:", cancelResult.orderId);

Cancel by Client Order ID

Cancel an order using the client-provided identifier instead of the exchange-assigned order ID.

Method: nordUser.cancelOrderByClientId(clientOrderId)

Parameters

NameTypeRequiredDescription
clientOrderIdbigint | stringYesThe client-specified order identifier set when placing the order.
accountIdnumberNoThe sub-account ID that placed the order.

Return Value

Returns a Promise containing the canceled order details.

{ orderId: bigint, clientOrderId: bigint, accountId: number, }

Example

const cancelResult = await user.cancelOrderByClientId(42n); console.log("Cancelled order:", cancelResult.orderId);

Atomic Operations

Execute multiple actions (place, cancel) in a single atomic transaction.

[!IMPORTANT] Constraints:

  • Maximum 4 operations per atomic transaction
  • Ordering per market: Cancels → Trades → Places (cancels must come first, placements last)
  • Across different markets, order can be any

Method: nordUser.atomic(actions)

Parameters

NameTypeRequiredDescription
actionsUserAtomicSubaction[]YesAn array of actions (place or cancel). Max 4.

UserAtomicSubaction Structure:

For place: same fields as placeOrder plus kind: "place". For cancel: kind: "cancel", marketId, and orderId. For cancelByClientId: kind: "cancelByClientId", marketId, and clientOrderId.

Return Value

Returns a Promise resolving to the atomic action result.

{ actionId: bigint, // ... result details }

Example

const atomicResult = await user.atomic([ { kind: "cancel", marketId: 0, orderId: existingOrderId, }, { kind: "cancelByClientId", marketId: 0, clientOrderId: 42n, }, { kind: "place", marketId: 0, side: Side.Bid, fillMode: FillMode.Limit, isReduceOnly: false, size: 0.2, price: 49500, }, ]); console.log("Atomic action ID:", atomicResult.actionId);

Trigger Orders

Manage stop-loss and take-profit triggers.

[!CAUTION] Experimental Feature: Trigger orders (TP/SL) are currently unstable and may change. Use with caution in production.

[!INFO] Auto-Close on Position Changes: Triggers automatically close when your position is closed or flipped. This prevents triggers from executing unexpectedly after position state changes.

Add Trigger

Method: nordUser.addTrigger(triggerConfig)

Parameters

NameTypeRequiredDescription
marketIdnumberYesThe ID of the market.
sideSideYesSide.Bid or Side.Ask.
kindTriggerKindYesTriggerKind.StopLoss or TriggerKind.TakeProfit.
triggerPricenumberYesThe price that activates the trigger.
limitPricenumberNoThe price for the triggered limit order.
intentIntentYesIntent.Decrease (close/reduce position) or Intent.Increase (add to position).

Example

const trigger = await user.addTrigger({ marketId: 0, side: Side.Ask, kind: TriggerKind.StopLoss, triggerPrice: 45000, limitPrice: 44900, intent: Intent.Decrease, }); console.log("Added trigger:", trigger.actionId);

Remove Trigger

Method: nordUser.removeTrigger(triggerConfig)

Parameters

NameTypeRequiredDescription
marketIdnumberYesThe ID of the market.
sideSideYesSide.Bid or Side.Ask.
kindTriggerKindYesTriggerKind.StopLoss or TriggerKind.TakeProfit.
intentIntentYesIntent.Decrease or Intent.Increase. Must match the intent used when adding.
triggerPricenumberNoThe trigger price for exact-match removal.
limitsobjectNoThe same { price, size } limits used on add-trigger for exact-match removal.

[!NOTE] For exact-match removal, pass the same triggerPrice and limits fields used when adding the trigger. If the trigger was added without size limits, keep them omitted here too.

Example

await user.removeTrigger({ marketId: 0, side: Side.Ask, kind: TriggerKind.StopLoss, intent: Intent.Decrease, });

Fund Management

Manage your account balances on the exchange.

Deposit Tokens

Method: nordUser.deposit(depositConfig)

Parameters

NameTypeRequiredDescription
amountnumberYesAmount to deposit.
tokenIdnumberYesThe ID of the token (e.g., 1 for USDC).
recipientPublicKeyNoOptional recipient public key.

Return Value

{ signature: string }

Example

const depositResult = await user.deposit({ amount: 1000, tokenId: 1, }); console.log("Deposit signature:", depositResult.signature);

Withdraw Tokens

Method: nordUser.withdraw(withdrawConfig)

Parameters

NameTypeRequiredDescription
amountnumberYesAmount to withdraw.
tokenIdnumberYesThe ID of the token.

Return Value

{ actionId: bigint }

Example

const withdrawResult = await user.withdraw({ amount: 500, tokenId: 1, }); console.log("Withdrawal action ID:", withdrawResult.actionId);

Transfer to Account

Transfer tokens between different accounts.

Method: nordUser.transferToAccount(transferConfig)

Parameters

NameTypeRequiredDescription
tokenIdnumberYesThe ID of the token.
amountnumberYesAmount to transfer.
fromAccountIdnumberYesSource account ID.
toAccountIdnumberYesDestination account ID.

Example

const transferResult = await user.transferToAccount({ tokenId: 1, amount: 100, fromAccountId: 0, toAccountId: 1, }); console.log("Transfer action ID:", transferResult.actionId);

Information & Balances

Fetch User Info

Refresh the local state of the user, including balances and orders.

await user.fetchInfo(); console.log("Balances:", user.balances); console.log("Orders:", user.orders);

Get Solana Balances

Check token balances in your Solana wallet context.

const solBalances = await user.getSolanaBalances({ includeZeroBalances: false, }); console.log("Solana Balances:", solBalances);

Trade History

To retrieve trade history, you can manually fetch it from the Nord API. This is done by making a GET request to the /trades endpoint.

Endpoint

The URL is constructed as follows:

GET {NORD_API_URL}/trades?makerId={makerId}&pageSize={pageSize}
  • makerId: (Required) The ID of the maker (user) whose trade history you want to fetch.
  • pageSize: (Optional) The number of trades to retrieve per page.

Usage Example

Here is an example of how to fetch trade history using the native fetch API:

// Define the Nord API URL (e.g., for Mainnet) const NORD_URL = "https://zo-mainnet.n1.xyz"; async function fetchTradeHistory(makerId: string, pageSize: number = 50) { try { const response = await fetch( `${NORD_URL}/trades?makerId=${makerId}&pageSize=${pageSize}` ); if (!response.ok) { throw new Error(`Error fetching trades: ${response.statusText}`); } const trades = await response.json(); console.log("Trade History:", trades); return trades; } catch (error) { console.error("Failed to fetch trade history:", error); } } // Example usage // Replace 'YOUR_MAKER_ID' with the actual maker ID fetchTradeHistory("YOUR_MAKER_ID");
Last updated on