Skip to Content
Usage ExamplesTrading Operations

Trading Operations

Learn how to perform trading operations using the NordUser class.

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 NordUser

Placing Orders

Place various types of orders using the placeOrder method.

Limit Order

A standard limit order specifies a price and size.

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

Market orders execute immediately at the best available price.

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

Reduce-Only Order

Reduce-only orders ensure you only decrease your current position size and will not open a new position in the opposite direction.

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.

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

Atomic Operations

Execute multiple actions (place, cancel) in a single atomic transaction. This guarantees that either all actions succeed or none do, which is critical for complex trading strategies like bracket orders or market making.

const atomicResult = await user.atomic([ // 1. Cancel an existing order { kind: "cancel", marketId: 0, orderId: existingOrderId, }, // 2. Place a new order replacement { 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.

Add Trigger

const trigger = await user.addTrigger({ marketId: 0, side: Side.Ask, // Trigger direction kind: TriggerKind.StopLoss, // or TriggerKind.TakeProfit triggerPrice: 45000, // Price that activates the trigger limitPrice: 44900, // Optional: limit price for the triggered order }); console.log("Added trigger:", trigger.actionId);

Remove Trigger

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

Fund Management

Manage your account balances on the exchange.

Deposit Tokens

Deposit SPL tokens from your Solana wallet to the Nord Protocol.

const depositResult = await user.deposit({ amount: 1000, tokenId: 1, // e.g., USDC token ID // recipient: optional recipient public key }); console.log("Deposit signature:", depositResult.signature);

Withdraw Tokens

Withdraw tokens from the exchange back to your wallet.

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

Transfer Operations

Transfer tokens between different accounts (sub-accounts) under your user session.

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