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 } from "@n1xyz/nord-ts";
import { PublicKey } from "@solana/web3.js";
// user is an initialized instance of NordUserPlacing Orders
Place various types of orders using the placeOrder method.
Method: nordUser.placeOrder(orderConfig)
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
marketId | number | Yes | The ID of the market (e.g., 0 for BTC/USDC). |
side | Side | Yes | Order side: Side.Bid (Buy) or Side.Ask (Sell). |
fillMode | FillMode | Yes | FillMode.Limit, FillMode.PostOnly, FillMode.ImmediateOrCancel, or FillMode.FillOrKill. |
size | number | Yes | The size of the order in base asset units. |
price | number | No* | The limit price. Required if fillMode is Limit. |
isReduceOnly | boolean | No | If true, the order will only reduce an existing position. Default false. |
Return Value
Returns a Promise that resolves to an object containing the orderId.
{
orderId: bigint
}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
const reduceOnlyOrder = await user.placeOrder({
marketId: 0,
side: Side.Ask,
fillMode: FillMode.Limit,
isReduceOnly: true,
size: 0.1,
price: 55000,
});Canceling Orders
Cancel an existing order using its orderId.
Method: nordUser.cancelOrder(orderId)
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
orderId | bigint | string | Yes | The 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);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
| Name | Type | Required | Description |
|---|---|---|---|
actions | UserAtomicSubaction[] | Yes | An 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.
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: "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.
Add Trigger
Method: nordUser.addTrigger(triggerConfig)
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
marketId | number | Yes | The ID of the market. |
side | Side | Yes | Side.Bid or Side.Ask. |
kind | TriggerKind | Yes | TriggerKind.StopLoss or TriggerKind.TakeProfit. |
triggerPrice | number | Yes | The price that activates the trigger. |
limitPrice | number | No | The price for the triggered limit order. |
Example
const trigger = await user.addTrigger({
marketId: 0,
side: Side.Ask,
kind: TriggerKind.StopLoss,
triggerPrice: 45000,
limitPrice: 44900,
});
console.log("Added trigger:", trigger.actionId);Remove Trigger
Method: nordUser.removeTrigger(triggerConfig)
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
marketId | number | Yes | The ID of the market. |
side | Side | Yes | Side.Bid or Side.Ask. |
kind | TriggerKind | Yes | TriggerKind.StopLoss or TriggerKind.TakeProfit. |
Example
await user.removeTrigger({
marketId: 0,
side: Side.Ask,
kind: TriggerKind.StopLoss,
});Fund Management
Manage your account balances on the exchange.
Deposit Tokens
Method: nordUser.deposit(depositConfig)
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
amount | number | Yes | Amount to deposit. |
tokenId | number | Yes | The ID of the token (e.g., 1 for USDC). |
recipient | PublicKey | No | Optional 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
| Name | Type | Required | Description |
|---|---|---|---|
amount | number | Yes | Amount to withdraw. |
tokenId | number | Yes | The 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
| Name | Type | Required | Description |
|---|---|---|---|
tokenId | number | Yes | The ID of the token. |
amount | number | Yes | Amount to transfer. |
fromAccountId | number | Yes | Source account ID. |
toAccountId | number | Yes | Destination 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");