> For the complete documentation index, see [llms.txt](https://docs.opinion.trade/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.opinion.trade/developer-guide/opinion-clob-typescript-sdk/api-references/methods.md).

# Methods

Complete API reference for the TypeScript SDK (`@opinion-labs/opinion-clob-sdk` v0.5.2). All methods are async and use camelCase naming.

***

## Market Data Methods

### getMarkets

Get a paginated list of markets available for trading.

```typescript
import { TopicType, TopicStatusFilter, TopicSortType } from '@opinion-labs/opinion-clob-sdk';

const result = await client.getMarkets({
  topicType: TopicType.ALL,               // Optional: BINARY, CATEGORICAL, ALL (default: ALL)
  page: 1,                                 // Optional: page number (default: 1)
  limit: 20,                               // Optional: items per page (default: 20, max: 20)
  status: TopicStatusFilter.ACTIVATED,      // Optional: ALL, ACTIVATED, RESOLVED
  sortBy: TopicSortType.BY_VOLUME_DESC,     // Optional: sorting method (default: BY_TIME_DESC)
});

console.log(result.result.total);           // Total number of matching markets
console.log(result.result.list);            // Array of market objects
```

Parameters:

| Parameter   | Type              | Required | Description                              |
| ----------- | ----------------- | -------- | ---------------------------------------- |
| `topicType` | TopicType         | No       | Filter by market type (default: `ALL`)   |
| `page`      | number            | No       | Page number, must be >= 1 (default: 1)   |
| `limit`     | number            | No       | Items per page, 1-20 (default: 20)       |
| `status`    | TopicStatusFilter | No       | Filter by market status                  |
| `sortBy`    | TopicSortType     | No       | Sorting method (default: `BY_TIME_DESC`) |

Response: `ApiResponse<MarketListResult>` containing `{ total, list }`.

***

### getMarket

Get detailed information about a binary market.

```typescript
const result = await client.getMarket(67);          // market_id as number
const resultNoCache = await client.getMarket(67, false);  // bypass cache

console.log(result.result.data.marketTitle);
console.log(result.result.data.yesTokenId);
console.log(result.result.data.noTokenId);
console.log(result.result.data.conditionId);
```

Parameters:

| Parameter  | Type    | Required | Description                                  |
| ---------- | ------- | -------- | -------------------------------------------- |
| `marketId` | number  | Yes      | Market ID                                    |
| `useCache` | boolean | No       | Use cached data if available (default: true) |

Response: `ApiResponse<MarketDetailResult>` containing `{ data }` with market details.

***

### getCategoricalMarket

Get detailed information about a categorical market, including all child markets.

```typescript
const result = await client.getCategoricalMarket(10);

console.log(result.result.data.marketTitle);
console.log(result.result.data.childMarkets);  // Array of child market objects
```

Parameters:

| Parameter  | Type   | Required | Description           |
| ---------- | ------ | -------- | --------------------- |
| `marketId` | number | Yes      | Categorical market ID |

Response: `ApiResponse<MarketDetailResult>` containing `{ data }` with market details and `childMarkets` array.

***

### getQuoteTokens

Retrieve the list of supported quote tokens (currencies) on the platform.

```typescript
const result = await client.getQuoteTokens();          // with cache
const resultNoCache = await client.getQuoteTokens(false);  // bypass cache

for (const token of result.result.list) {
  console.log(token.quoteTokenName);       // e.g., "Base USDC"
  console.log(token.quoteTokenAddress);    // Contract address
  console.log(token.ctfExchangeAddress);   // Exchange contract address
  console.log(token.decimal);              // Token decimals (e.g., 6)
  console.log(token.symbol);              // e.g., "USDC"
}
```

Parameters:

| Parameter  | Type    | Required | Description                                  |
| ---------- | ------- | -------- | -------------------------------------------- |
| `useCache` | boolean | No       | Use cached data if available (default: true) |

Response: `ApiResponse<QuoteTokenListResult>` containing `{ total, list }`.

***

### getOrderbook

Get the orderbook (market depth) for a specific token.

```typescript
const result = await client.getOrderbook('34780524119202758863327378805823157249587136341915838311361711249158835002904');

console.log(result.result.bids);       // Array of [price, shares] buy orders
console.log(result.result.asks);       // Array of [price, shares] sell orders
console.log(result.result.lastPrice);  // Latest trade price
```

Parameters:

| Parameter | Type   | Required | Description                           |
| --------- | ------ | -------- | ------------------------------------- |
| `tokenId` | string | Yes      | Token ID (the outcome token to query) |

Response: `ApiResponse<OrderbookResponse>` with `bids`, `asks`, and `lastPrice`.

Response fields:

| Field       | Description                                |
| ----------- | ------------------------------------------ |
| `symbol`    | Token ID                                   |
| `ts`        | Timestamp in milliseconds                  |
| `bids`      | Array of `[price, shares]` for buy orders  |
| `asks`      | Array of `[price, shares]` for sell orders |
| `lastPrice` | Latest price from the last trade           |

***

### getLatestPrice

Get the latest price for a specific token.

```typescript
const result = await client.getLatestPrice('YOUR_TOKEN_ID');

console.log(result.result);  // Latest price data
```

Parameters:

| Parameter | Type   | Required | Description |
| --------- | ------ | -------- | ----------- |
| `tokenId` | string | Yes      | Token ID    |

Response: `ApiResponse<LatestPriceResponse>`.

***

### getPriceHistory

Get price history for a specific token.

```typescript
const result = await client.getPriceHistory('YOUR_TOKEN_ID', {
  interval: '1h',     // '1m', '1h', '1d', '1w', or 'max'
  startAt: 1700000000,  // Optional: start timestamp (Unix)
  endAt: 1700100000,    // Optional: end timestamp (Unix)
});

console.log(result.result);  // Array of price history data points
```

Parameters:

| Parameter  | Type   | Required | Description                                                              |
| ---------- | ------ | -------- | ------------------------------------------------------------------------ |
| `tokenId`  | string | Yes      | Token ID                                                                 |
| `interval` | string | No       | Time interval: `'1m'`, `'1h'`, `'1d'`, `'1w'`, `'max'` (default: `'1h'`) |
| `startAt`  | number | No       | Start timestamp (Unix seconds)                                           |
| `endAt`    | number | No       | End timestamp (Unix seconds)                                             |

Response: `ApiResponse<PriceHistoryResponse>`.

***

### getFeeRates

Get fee rates from the on-chain FeeManager contract for a specific token.

```typescript
const feeRates = await client.getFeeRates('YOUR_TOKEN_ID');

console.log(feeRates);  // FeeRateSettings object
```

Parameters:

| Parameter | Type   | Required | Description |
| --------- | ------ | -------- | ----------- |
| `tokenId` | string | Yes      | Token ID    |

Response: `FeeRateSettings` object (not wrapped in ApiResponse since this is an on-chain call).

***

## Trading Methods

### placeOrder

Place a market or limit order.

Limit Buy Order (by quote token amount):

```typescript
import { OrderSide, OrderType } from '@opinion-labs/opinion-clob-sdk';
import type { PlaceOrderDataInput } from '@opinion-labs/opinion-clob-sdk';

const orderData: PlaceOrderDataInput = {
  marketId: 57,
  tokenId: 'YOUR_TOKEN_ID',
  makerAmountInQuoteToken: '100',  // 100 USDT
  price: '0.6',
  orderType: OrderType.LIMIT_ORDER,
  side: OrderSide.BUY,
};

const result = await client.placeOrder(orderData, false);
console.log(result);
```

Limit Buy Order (by shares):

```typescript
const orderData: PlaceOrderDataInput = {
  marketId: 57,
  tokenId: 'YOUR_TOKEN_ID',
  makerAmountInBaseToken: '50',  // 50 Yes tokens
  price: '0.6',
  orderType: OrderType.LIMIT_ORDER,
  side: OrderSide.BUY,
};

const result = await client.placeOrder(orderData, false);
```

Market Buy Order:

```typescript
const orderData: PlaceOrderDataInput = {
  marketId: 57,
  tokenId: 'YOUR_TOKEN_ID',
  makerAmountInQuoteToken: '100',  // 100 USDT worth
  orderType: OrderType.MARKET_ORDER,
  side: OrderSide.BUY,
  price: '0',  // Price is ignored for market orders
};

const result = await client.placeOrder(orderData, false);
```

Limit Sell Order:

```typescript
const orderData: PlaceOrderDataInput = {
  marketId: 57,
  tokenId: 'YOUR_TOKEN_ID',
  makerAmountInBaseToken: '10',  // 10 Yes tokens
  price: '0.6',
  orderType: OrderType.LIMIT_ORDER,
  side: OrderSide.SELL,
};

const result = await client.placeOrder(orderData, false);
```

Parameters:

| Parameter       | Type                | Required | Description                                                                           |
| --------------- | ------------------- | -------- | ------------------------------------------------------------------------------------- |
| `data`          | PlaceOrderDataInput | Yes      | Order details (see [Models](broken://pages/f02726b8147af96802941231fb941b729461a2ea)) |
| `checkApproval` | boolean             | No       | Check and enable trading first (default: false)                                       |

Response: `ApiResponse<CreateOrderResponse>` with order data including `trans_no` (order ID).

Successful response example:

```json
{
  "errno": 0,
  "errmsg": "",
  "result": {
    "order_data": {
      "trans_no": "504d7580-cd59-11ef-887f-0a58a9feac02",
      "topic_title": "example",
      "side": 1,
      "outcome": "Yes",
      "price": "0.60000002400000096",
      "filled": "0/0.05",
      "status": 1
    }
  }
}
```

***

### placeOrdersBatch

Place multiple orders in batch. Orders are submitted sequentially. If one fails, the rest continue.

```typescript
const orders: PlaceOrderDataInput[] = [
  {
    marketId: 57,
    tokenId: 'TOKEN_1',
    makerAmountInQuoteToken: '100',
    price: '0.5',
    orderType: OrderType.LIMIT_ORDER,
    side: OrderSide.BUY,
  },
  {
    marketId: 57,
    tokenId: 'TOKEN_2',
    makerAmountInQuoteToken: '100',
    price: '0.6',
    orderType: OrderType.LIMIT_ORDER,
    side: OrderSide.BUY,
  },
];

const results = await client.placeOrdersBatch(orders, true);

for (const r of results) {
  if (r.success) {
    console.log(`Order ${r.index} placed:`, r.result);
  } else {
    console.log(`Order ${r.index} failed:`, r.error);
  }
}
```

Parameters:

| Parameter       | Type                   | Required | Description                                     |
| --------------- | ---------------------- | -------- | ----------------------------------------------- |
| `orders`        | PlaceOrderDataInput\[] | Yes      | Array of order inputs                           |
| `checkApproval` | boolean                | No       | Check and enable trading first (default: false) |

Response: `Array<{ index: number; success: boolean; result?: unknown; error?: string }>`.

***

### cancelOrder

Cancel a single pending order.

```typescript
const result = await client.cancelOrder('504d7580-cd59-11ef-887f-0a58a9feac02');
console.log(result);
```

Parameters:

| Parameter | Type   | Required | Description                                     |
| --------- | ------ | -------- | ----------------------------------------------- |
| `orderId` | string | Yes      | Order ID (`trans_no` from place order response) |

Response: `ApiResponse<CancelOrderResponse>`.

***

### cancelOrdersBatch

Cancel multiple orders at once.

```typescript
const orderIds = ['order_id_1', 'order_id_2', 'order_id_3'];
const results = await client.cancelOrdersBatch(orderIds);

for (const r of results) {
  if (r.success) {
    console.log(`Order ${r.index} cancelled`);
  } else {
    console.log(`Order ${r.index} failed:`, r.error);
  }
}
```

Parameters:

| Parameter  | Type      | Required | Description                  |
| ---------- | --------- | -------- | ---------------------------- |
| `orderIds` | string\[] | Yes      | Array of order IDs to cancel |

Response: `Array<{ index: number; success: boolean; result?: unknown; error?: string }>`.

***

### cancelAllOrders

Cancel all open orders, optionally filtered by market and/or side. Automatically paginates through all open orders.

```typescript
import { OrderSide } from '@opinion-labs/opinion-clob-sdk';

// Cancel all open orders
const result = await client.cancelAllOrders();

// Cancel all open orders for a specific market
const result2 = await client.cancelAllOrders({ marketId: 57 });

// Cancel all open BUY orders
const result3 = await client.cancelAllOrders({ side: OrderSide.BUY });

// Cancel all open SELL orders for a specific market
const result4 = await client.cancelAllOrders({ marketId: 57, side: OrderSide.SELL });

console.log(result.totalOrders);   // Total orders found
console.log(result.cancelled);     // Successfully cancelled
console.log(result.failed);        // Failed to cancel
console.log(result.results);       // Detailed results for each order
```

Parameters:

| Parameter  | Type      | Required | Description                        |
| ---------- | --------- | -------- | ---------------------------------- |
| `marketId` | number    | No       | Filter by market ID                |
| `side`     | OrderSide | No       | Filter by order side (BUY or SELL) |

Response:

```typescript
{
  totalOrders: number;
  cancelled: number;
  failed: number;
  results: Array<{ index: number; success: boolean; result?: unknown; error?: string }>;
}
```

***

## User Data Methods

### getMyOrders

Query your orders with optional filters.

```typescript
// Get all orders
const result = await client.getMyOrders();

// Filter by market_id and status
const result2 = await client.getMyOrders({
  marketId: 57,
  status: '1',    // 1=pending, 2=filled, 3=canceled, 4=expired, 5=failed, 6=on chain failed
  page: 1,
  limit: 10,
});

console.log(result.result.total);
console.log(result.result.list);
```

Parameters:

| Parameter  | Type   | Required | Description                                                                                                       |
| ---------- | ------ | -------- | ----------------------------------------------------------------------------------------------------------------- |
| `marketId` | number | No       | Filter by market ID                                                                                               |
| `status`   | string | No       | Filter by status: `'1'`=pending, `'2'`=filled, `'3'`=canceled, `'4'`=expired, `'5'`=failed, `'6'`=on chain failed |
| `page`     | number | No       | Page number (default: 1)                                                                                          |
| `limit`    | number | No       | Items per page (default: 10)                                                                                      |

Response: `ApiResponse<OrderListResponse>` with `{ total, list }`.

Response fields per order:

| Field            | Description                                                              |
| ---------------- | ------------------------------------------------------------------------ |
| `trans_no`       | Order ID (use to cancel)                                                 |
| `side`           | 0 = buy, 1 = sell                                                        |
| `status`         | 1=pending, 2=filled, 3=cancelled, 4=expired, 5=failed, 6=on chain failed |
| `trading_method` | 1=market order, 2=limit order                                            |
| `filled`         | Amount filled / Total amount                                             |
| `total_price`    | Total value of the order                                                 |

***

### getOrderById

Get detailed information about a specific order.

```typescript
const result = await client.getOrderById('504d7580-cd59-11ef-887f-0a58a9feac02');
console.log(result.result);
```

Parameters:

| Parameter | Type   | Required | Description           |
| --------- | ------ | -------- | --------------------- |
| `orderId` | string | Yes      | Order ID (`trans_no`) |

Response: `ApiResponse<OrderDetailResponse>`.

***

### getMyBalances

Get ERC20 balances for the authenticated user.

```typescript
const result = await client.getMyBalances();

for (const balance of result.result) {
  console.log(balance.totalBalance);       // Total in-app balance
  console.log(balance.balance);            // Available balance
  console.log(balance.netWorth);           // Total net worth
  console.log(balance.currencyAddress);    // Token contract address
}
```

Parameters: None.

Response: `ApiResponse<UserBalanceResponse>` (array of balance objects).

Response fields per balance:

| Field             | Description                  |
| ----------------- | ---------------------------- |
| `totalBalance`    | All in-app balance           |
| `balance`         | Current available balance    |
| `netWorth`        | Total net worth              |
| `currencyAddress` | ERC20 token contract address |

***

### getMyPositions

Query your positions.

```typescript
// Get all positions
const result = await client.getMyPositions();

// With pagination and market filter
const result2 = await client.getMyPositions({
  marketId: 23,
  page: 1,
  limit: 10,
});

console.log(result.result.total);
console.log(result.result.list);
```

Parameters:

| Parameter  | Type   | Required | Description                  |
| ---------- | ------ | -------- | ---------------------------- |
| `marketId` | number | No       | Filter by market ID          |
| `page`     | number | No       | Page number (default: 1)     |
| `limit`    | number | No       | Items per page (default: 10) |

Response: `ApiResponse<PositionsResponse>` with `{ total, list }`.

Response fields per position:

| Field               | Description                                |
| ------------------- | ------------------------------------------ |
| `topicId`           | Market ID                                  |
| `tokenId`           | Token ID of the position                   |
| `outcome`           | Position outcome label (e.g., "Yes", "No") |
| `tokenAmount`       | Amount of tokens held                      |
| `tokenFrozenAmount` | Amount frozen in open orders               |
| `profit`            | Unrealized profit                          |
| `positionAvgPrice`  | Average price of the position              |

***

### getMyTrades

Query your trade history (matched orders become trades).

```typescript
// Get all trades
const result = await client.getMyTrades();

// Filter by market with pagination
const result2 = await client.getMyTrades({
  marketId: 57,
  page: 1,
  limit: 10,
});

console.log(result.result.total);
console.log(result.result.list);
```

Parameters:

| Parameter  | Type   | Required | Description                  |
| ---------- | ------ | -------- | ---------------------------- |
| `marketId` | number | No       | Filter by market ID          |
| `page`     | number | No       | Page number (default: 1)     |
| `limit`    | number | No       | Items per page (default: 10) |

Response: `ApiResponse<TradeListResponse>` with `{ total, list }`.

Response fields per trade:

| Field         | Description                                                             |
| ------------- | ----------------------------------------------------------------------- |
| `transNo`     | Trade ID                                                                |
| `txHash`      | Blockchain transaction hash                                             |
| `side`        | "Buy" or "Sell"                                                         |
| `outcome`     | Outcome label (e.g., "Yes", "No")                                       |
| `shares`      | Number of tokens traded                                                 |
| `amount`      | Quote token amount                                                      |
| `profit`      | Realized profit from the trade                                          |
| `status`      | 1=pending, 2=filled, 3=canceled, 4=expired, 5=failed, 6=on chain failed |
| `outcomeSide` | 1=yes token, 2=no token                                                 |
| `tradeType`   | 1=taker, 2=maker                                                        |
| `fee`         | Trading fee                                                             |

***

### getUserAuth

Get authenticated user information.

```typescript
const result = await client.getUserAuth();
console.log(result.result);
```

Parameters: None.

Response: `ApiResponse<UserAuthResponse>`.

***

## Smart Contract Methods

These methods interact directly with the blockchain and require gas (BNB on BNB Chain).

### enableTrading

Authorize the O.LAB operator to process your orders on chain. You only need to call this once per trading account.

```typescript
const result = await client.enableTrading();

console.log(result.success);   // true if successful
console.log(result.txHash);    // Transaction hash (undefined if already enabled)
```

Parameters: None.

Response: `TransactionResult` with `{ txHash?, success }`.

Notes:

* Must be called before your first order can be filled.
* If trading is already enabled, the method returns successfully without submitting a transaction.
* Requires BNB in the signer wallet for gas.

***

### split

Convert collateral (e.g., USDC) into equal amounts of Yes and No outcome tokens.

```typescript
const result = await client.split(
  57,                          // marketId
  BigInt(100 * 10**18),        // amount in wei (100 tokens with 18 decimals)
  true                         // checkApproval (default: true)
);

// For USDC with 6 decimals:
const result2 = await client.split(57, BigInt(100 * 10**6));

console.log(result.success);
console.log(result.txHash);
```

Parameters:

| Parameter       | Type    | Required | Description                                    |
| --------------- | ------- | -------- | ---------------------------------------------- |
| `marketId`      | number  | Yes      | Market ID                                      |
| `amount`        | bigint  | Yes      | Amount of collateral to split (in wei)         |
| `checkApproval` | boolean | No       | Check and enable trading first (default: true) |

Response: `TransactionResult` with `{ txHash, success }`.

Notes:

* Requires gas (BNB).
* After splitting, you receive equal amounts of Yes and No tokens.
* Market must be in ACTIVATED, RESOLVING, or RESOLVED status.

***

### merge

Merge outcome tokens (Yes + No) back into collateral.

```typescript
const result = await client.merge(
  23,                          // marketId
  BigInt(100 * 10**18),        // amount in wei
  true                         // checkApproval (default: true)
);

console.log(result.success);
console.log(result.txHash);
```

Parameters:

| Parameter       | Type    | Required | Description                                    |
| --------------- | ------- | -------- | ---------------------------------------------- |
| `marketId`      | number  | Yes      | Market ID                                      |
| `amount`        | bigint  | Yes      | Amount of outcome tokens to merge (in wei)     |
| `checkApproval` | boolean | No       | Check and enable trading first (default: true) |

Response: `TransactionResult` with `{ txHash, success }`.

Notes:

* Requires gas (BNB).
* You need equal amounts of Yes and No tokens to merge.
* Market must be in ACTIVATED, RESOLVING, or RESOLVED status.
* After merging, you receive the original collateral tokens back.

***

### redeem

Claim collateral from a resolved market by redeeming winning outcome tokens.

```typescript
const result = await client.redeem(23);      // marketId
const result2 = await client.redeem(23, false);  // skip approval check

console.log(result.success);
console.log(result.txHash);
```

Parameters:

| Parameter       | Type    | Required | Description                                    |
| --------------- | ------- | -------- | ---------------------------------------------- |
| `marketId`      | number  | Yes      | Market ID                                      |
| `checkApproval` | boolean | No       | Check and enable trading first (default: true) |

Response: `TransactionResult` with `{ txHash, success }`.

Notes:

* Requires gas (BNB).
* Market must be in RESOLVED status.
* Only winning outcome tokens can be redeemed.
* Losing tokens have no redemption value.

***

## WebSocket

### createWebSocketClient

Create a WebSocket client for real-time market data. The client is pre-configured with the API key and wallet address from the `Client` instance.

```typescript
const wsClient = client.createWebSocketClient({
  heartbeatInterval: 30,   // Seconds between heartbeats (default: 30)
  onMessage: (msg) => console.log('Received:', msg),
  onOpen: () => console.log('Connected'),
  onClose: () => console.log('Disconnected'),
  onError: (error) => console.error('Error:', error),
});

// Connect
await wsClient.connect();

// Check connection status
console.log(wsClient.isConnected);
```

Configuration options:

| Parameter           | Type     | Required | Description                                              |
| ------------------- | -------- | -------- | -------------------------------------------------------- |
| `heartbeatInterval` | number   | No       | Seconds between heartbeat messages (default: 30)         |
| `wsUrl`             | string   | No       | WebSocket server URL (default: `wss://ws.opinion.trade`) |
| `onMessage`         | function | No       | Callback for all incoming messages                       |
| `onOpen`            | function | No       | Callback when connection opens                           |
| `onClose`           | function | No       | Callback when connection closes                          |
| `onError`           | function | No       | Callback on connection error                             |

### Subscription Channels

#### subscribeMarketDepthDiff

Subscribe to real-time orderbook depth updates for a specific market.

```typescript
wsClient.subscribeMarketDepthDiff(1274, (msg) => {
  console.log(`Market ${msg.marketId}: ${msg.side} ${msg.price} @ ${msg.size}`);
  console.log(`Token: ${msg.tokenId}, Outcome: ${msg.outcomeSide}`);
});

// Unsubscribe
wsClient.unsubscribeMarketDepthDiff(1274);
```

Message fields:

| Field          | Type   | Description                              |
| -------------- | ------ | ---------------------------------------- |
| `marketId`     | number | Market ID                                |
| `rootMarketId` | number | Root market ID (for categorical markets) |
| `tokenId`      | string | Token ID of the updated token            |
| `outcomeSide`  | number | 1 = yes, 2 = no                          |
| `side`         | string | `"bids"` or `"asks"`                     |
| `price`        | string | Price level                              |
| `size`         | string | Size in shares                           |

#### subscribeMarketLastPrice

Subscribe to last price updates.

```typescript
// For binary market
wsClient.subscribeMarketLastPrice({ marketId: 1274 }, (msg) => {
  console.log(`Market ${msg.marketId}: Last price ${msg.price}`);
});

// For categorical market
wsClient.subscribeMarketLastPrice({ rootMarketId: 61 }, (msg) => {
  console.log(`Market ${msg.marketId}: Last price ${msg.price}`);
});

// Unsubscribe
wsClient.unsubscribeMarketLastPrice({ marketId: 1274 });
```

#### subscribeMarketLastTrade

Subscribe to last trade updates.

```typescript
wsClient.subscribeMarketLastTrade({ marketId: 1274 }, (msg) => {
  console.log(`Market ${msg.marketId}: ${msg.side} ${msg.shares} shares @ ${msg.price}`);
});

// Unsubscribe
wsClient.unsubscribeMarketLastTrade({ marketId: 1274 });
```

#### subscribeTradeOrderUpdate

Subscribe to order status updates for your account.

```typescript
wsClient.subscribeTradeOrderUpdate({ marketId: 1274 }, (msg) => {
  console.log(`Order ${msg.orderId}: ${msg.orderUpdateType}, Status: ${msg.status}`);
  console.log(`Filled: ${msg.filledShares} shares, ${msg.filledAmount} amount`);
});

// Unsubscribe
wsClient.unsubscribeTradeOrderUpdate({ marketId: 1274 });
```

Message fields:

| Field             | Type   | Description                                                    |
| ----------------- | ------ | -------------------------------------------------------------- |
| `orderUpdateType` | string | `"orderNew"`, `"orderFill"`, `"orderCancel"`, `"orderConfirm"` |
| `orderId`         | string | Order ID                                                       |
| `side`            | number | 1 = buy, 2 = sell                                              |
| `status`          | number | 1=pending, 2=finished, 3=canceled, 4=expired, 5=failed         |
| `tradingMethod`   | number | 1 = market, 2 = limit                                          |
| `filledShares`    | string | Filled shares (updated after orderConfirm)                     |
| `filledAmount`    | string | Filled amount (updated after orderConfirm)                     |

#### subscribeTradeRecordNew

Subscribe to new trade record notifications.

```typescript
wsClient.subscribeTradeRecordNew({ marketId: 1274 }, (msg) => {
  console.log(`Trade ${msg.tradeNo}: ${msg.side} ${msg.shares} shares @ ${msg.price}`);
  console.log(`Fee: ${msg.fee}, Profit: ${msg.profit}`);
});

// Unsubscribe
wsClient.unsubscribeTradeRecordNew({ marketId: 1274 });
```

### Close Connection

```typescript
wsClient.close();
```

### Full WebSocket Example

```typescript
import { Client, CHAIN_ID_BNB_MAINNET, DEFAULT_API_HOST } from '@opinion-labs/opinion-clob-sdk';

const client = new Client({
  host: DEFAULT_API_HOST,
  apiKey: 'YOUR_API_KEY',
  chainId: CHAIN_ID_BNB_MAINNET,
  rpcUrl: 'YOUR_RPC_URL',
  privateKey: '0xYOUR_PRIVATE_KEY',
  multiSigAddress: '0xYOUR_MULTI_SIG_ADDRESS',
});

const wsClient = client.createWebSocketClient({
  onOpen: () => console.log('WebSocket connected'),
  onClose: () => console.log('WebSocket disconnected'),
  onError: (error) => console.error('WebSocket error:', error),
});

await wsClient.connect();

// Subscribe to depth updates
wsClient.subscribeMarketDepthDiff(1274, (msg) => {
  console.log(`Depth: ${msg.side} ${msg.price} @ ${msg.size}`);
});

// Subscribe to order updates
wsClient.subscribeTradeOrderUpdate({ marketId: 1274 }, (msg) => {
  console.log(`Order update: ${msg.orderUpdateType} - ${msg.orderId}`);
});

// Keep running...
// When done:
// wsClient.close();
```

***


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.opinion.trade/developer-guide/opinion-clob-typescript-sdk/api-references/methods.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
