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.

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.

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.

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.

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.

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.

Parameters:

Parameter
Type
Required
Description

tokenId

string

Yes

Token ID

Response: ApiResponse<LatestPriceResponse>.


getPriceHistory

Get price history for a specific token.

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.

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):

Limit Buy Order (by shares):

Market Buy Order:

Limit Sell Order:

Parameters:

Parameter
Type
Required
Description

data

PlaceOrderDataInput

Yes

Order details (see Models)

checkApproval

boolean

No

Check and enable trading first (default: false)

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

Successful response example:


placeOrdersBatch

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

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.

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.

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.

Parameters:

Parameter
Type
Required
Description

marketId

number

No

Filter by market ID

side

OrderSide

No

Filter by order side (BUY or SELL)

Response:


User Data Methods

getMyOrders

Query your orders with optional filters.

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.

Parameters:

Parameter
Type
Required
Description

orderId

string

Yes

Order ID (trans_no)

Response: ApiResponse<OrderDetailResponse>.


getMyBalances

Get ERC20 balances for the authenticated user.

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.

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).

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.

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.

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.

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.

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.

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.

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.

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.

subscribeMarketLastTrade

Subscribe to last trade updates.

subscribeTradeOrderUpdate

Subscribe to order status updates for your account.

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.

Close Connection

Full WebSocket Example