### Install Opinion CLOB SDK Source: https://github.com/yuandiaodiaodiao/opinion-js-sdk/blob/master/README.md Installs the unofficial Opinion CLOB SDK using npm. This command is used to add the SDK as a dependency to your Node.js project. ```bash npm install unofficial-opinion-clob-sdk ``` -------------------------------- ### Get User Account Balances Source: https://context7.com/yuandiaodiaodiao/opinion-js-sdk/llms.txt Check a user's token balances across all quote tokens, including wallet and multi-sig addresses. Provides details on total, available, and frozen balances for each token, with an example calculation for USD value. ```typescript const balances = await client.getMyBalances(); console.log('Account Balances:'); console.log(` Wallet: ${balances.walletAddress}`); console.log(` Multi-sig: ${balances.multiSignAddress}`); console.log(` Chain: ${balances.chainId}`); console.log('\nToken Balances:'); balances.balances.forEach(bal => { console.log(`\n ${bal.quoteToken}:`); console.log(` Decimals: ${bal.tokenDecimals}`); console.log(` Total: ${bal.totalBalance}`); console.log(` Available: ${bal.availableBalance}`); console.log(` Frozen: ${bal.frozenBalance}`); // Calculate USD value (if quote token is USDC) const totalUSD = parseFloat(bal.totalBalance); const availableUSD = parseFloat(bal.availableBalance); const frozenUSD = parseFloat(bal.frozenBalance); console.log(` Total USD: $${totalUSD.toFixed(2)}`); console.log(` Available USD: $${availableUSD.toFixed(2)}`); console.log(` Frozen USD: $${frozenUSD.toFixed(2)}`); }); ``` -------------------------------- ### Place Limit Order (TypeScript) Source: https://github.com/yuandiaodiaodiao/opinion-js-sdk/blob/master/README.md Places a limit order on the CLOB. This example shows how to place both buy and sell limit orders, specifying price, amount, side, and order type. It also demonstrates the use of `checkApproval`. ```typescript // Limit buy order const buyOrder = await client.placeOrder({ marketId: 123, tokenId: '0x...', // Replace with actual token ID price: '0.65', makerAmountInQuoteToken: '100', // 100 USDC side: OrderSide.BUY, orderType: OrderType.LIMIT_ORDER, }, true); // checkApproval = true // Limit sell order const sellOrder = await client.placeOrder({ marketId: 123, tokenId: '0x...', // Replace with actual token ID price: '0.70', makerAmountInBaseToken: '150', // 150 YES tokens side: OrderSide.SELL, orderType: OrderType.LIMIT_ORDER, }); ``` -------------------------------- ### Fetch Markets Data (TypeScript) Source: https://github.com/yuandiaodiaodiao/opinion-js-sdk/blob/master/README.md Retrieves a list of available markets using the SDK client. This example shows how to specify pagination, limits, and filtering by topic type and status. ```typescript const markets = await client.getMarkets({ topicType: TopicType.BINARY, // Assuming TopicType is imported or defined page: 1, limit: 20, status: 'activated', }); ``` -------------------------------- ### Get User Positions Source: https://github.com/yuandiaodiaodiao/opinion-js-sdk/blob/master/docs/api/classes/Client.html Retrieves the current open positions for the authenticated user, with options for pagination and filtering by market. ```APIDOC ## GET /api/v1/me/positions ### Description Get user's positions. ### Method GET ### Endpoint /api/v1/me/positions ### Parameters #### Query Parameters - **limit** (number) - Optional - Maximum number of positions to return. - **marketId** (number) - Optional - Filter positions by market ID. - **page** (number) - Optional - Page number for pagination. ### Response #### Success Response (200) - **list** ([Position](../interfaces/Position.html)[]) - Array of position objects. - **total** (number) - Total number of positions available. #### Response Example ```json { "list": [ { "id": 1, "marketId": 1, "size": "10.0" } ], "total": 20 } ``` ``` -------------------------------- ### Running Unit Tests with npm (Bash) Source: https://github.com/yuandiaodiaodiao/opinion-js-sdk/blob/master/test/README.md Commands to execute unit tests for the Opinion JS SDK using npm scripts. These include options for running all tests, enabling watch mode for continuous testing, generating code coverage reports, and running integration tests which require environment setup. ```bash # Run all tests npm test # Watch mode (auto-run on file changes) npm run test:watch # Run with coverage report npm run test:coverage # Run integration tests (requires .env configuration) npm run test:integration ``` -------------------------------- ### Retrieve Market Data using Opinion CLOB SDK Source: https://github.com/yuandiaodiaodiao/opinion-js-sdk/blob/master/docs/api/index.html Shows how to fetch market data using the Opinion CLOB SDK. This includes retrieving a list of markets with filtering options, getting details for a specific market, fetching the order book for a token, and retrieving historical price data. ```typescript const markets = await client.getMarkets({ topicType: TopicType.BINARY, page: 1, limit: 20, status: 'activated', }); const market = await client.getMarket(marketId); console.log('Market:', market.title); console.log('Status:', market.status); const orderbook = await client.getOrderbook(tokenId); console.log('Bids:', orderbook.bids); console.log('Asks:', orderbook.asks); const history = await client.getPriceHistory({ tokenId: '0x...', interval: '1h', // 1m, 1h, 1d, 1w, max startAt: Math.floor(Date.now() / 1000) - 86400, // last 24h }); ``` -------------------------------- ### Get Markets with Pagination Source: https://github.com/yuandiaodiaodiao/opinion-js-sdk/blob/master/docs/api/classes/Client.html Fetches a list of markets with support for pagination and filtering. This endpoint is used to browse and discover available markets. ```APIDOC ## GET /api/v1/markets ### Description Get markets with pagination. ### Method GET ### Endpoint /api/v1/markets ### Parameters #### Query Parameters - **limit** (number) - Optional - Maximum number of markets to return. - **page** (number) - Optional - Page number for pagination. - **status** (string) - Optional - Filter markets by status. - **topicType** ([TopicType](../enums/TopicType.html)) - Optional - Filter markets by topic type. ### Response #### Success Response (200) - **list** ([Market](../interfaces/Market.html)[]) - Array of market objects. - **total** (number) - Total number of markets available. #### Response Example ```json { "list": [ { "id": 1, "name": "Example Market" } ], "total": 100 } ``` ``` -------------------------------- ### User Account: Get Balances using Opinion JS SDK Source: https://github.com/yuandiaodiaodiao/opinion-js-sdk/blob/master/docs/api/index.html Demonstrates how to retrieve the user's token balances. The output provides the symbol and balance for each token. ```javascript const balances = await client.getMyBalances();alances.forEach(b => { console.log(`${b.symbol}: ${b.balance}`); }); ``` -------------------------------- ### Get User Orders Source: https://github.com/yuandiaodiaodiao/opinion-js-sdk/blob/master/docs/api/classes/Client.html Fetches the order history for the authenticated user, with support for pagination and filtering by market and status. ```APIDOC ## GET /api/v1/me/orders ### Description Get user's orders. ### Method GET ### Endpoint /api/v1/me/orders ### Parameters #### Query Parameters - **limit** (number) - Optional - Maximum number of orders to return. - **marketId** (number) - Optional - Filter orders by market ID. - **page** (number) - Optional - Page number for pagination. - **status** (string) - Optional - Filter orders by status. ### Response #### Success Response (200) - **list** ([Order](../interfaces/Order.html)[]) - Array of order objects. - **total** (number) - Total number of orders available. #### Response Example ```json { "list": [ { "id": 1, "marketId": 1, "status": "filled" } ], "total": 50 } ``` ``` -------------------------------- ### Fetch Maker and Taker Fee Rates (TypeScript) Source: https://context7.com/yuandiaodiaodiao/opinion-js-sdk/llms.txt Retrieves the maker and taker fee rates for a specific token. It also includes an example of calculating the fees for a trade based on these rates. Dependencies: opinion-js-sdk. Input: tokenId. Output: feeRates object with makerFeeBps and takerFeeBps. ```typescript const tokenId = '0x1234567890abcdef...'; const feeRates = await client.getFeeRates(tokenId); console.log('Fee Rates:'); console.log(` Token: ${feeRates.tokenId}`); console.log(` Maker Fee: ${feeRates.makerFeeBps} bps (${parseFloat(feeRates.makerFeeBps) / 100}%)`); console.log(` Taker Fee: ${feeRates.takerFeeBps} bps (${parseFloat(feeRates.takerFeeBps) / 100}%)`); // Calculate fees for a trade const tradeAmount = 1000; // 1000 USDC const makerFee = tradeAmount * parseFloat(feeRates.makerFeeBps) / 10000; const takerFee = tradeAmount * parseFloat(feeRates.takerFeeBps) / 10000; console.log(`\nFees on ${tradeAmount} USDC trade:`); console.log(` As maker: $${makerFee.toFixed(2)}`); console.log(` As taker: $${takerFee.toFixed(2)}`); ``` -------------------------------- ### Get User Orders with Filtering and Pagination Source: https://context7.com/yuandiaodiaodiao/opinion-js-sdk/llms.txt Retrieve a user's order history with options to filter by status (pending, filled, cancelled) or market ID, and paginate results. Requires a client instance and provides total order count and a list of orders. ```typescript // Get all open orders const openOrders = await client.getMyOrders({ status: '1', // 1 = pending/open page: 1, limit: 20, }); console.log(`Open Orders (${openOrders.total} total):`); openOrders.list.forEach(order => { console.log(` ${order.orderId}:`); console.log(` Market: ${order.marketTitle}`); console.log(` Side: ${order.sideEnum}`); console.log(` Price: ${order.price}`); console.log(` Size: ${order.orderShares} (${order.filledShares} filled)`); console.log(` Status: ${order.statusEnum}`); }); // Get orders for specific market const marketOrders = await client.getMyOrders({ marketId: 12345, page: 1, limit: 50, }); // Get filled orders const filledOrders = await client.getMyOrders({ status: '2', // 2 = filled page: 1, limit: 10, }); // Get cancelled orders const cancelledOrders = await client.getMyOrders({ status: '3', // 3 = cancelled page: 1, limit: 10, }); ``` -------------------------------- ### Get User Trade History Source: https://github.com/yuandiaodiaodiao/opinion-js-sdk/blob/master/docs/api/classes/Client.html Fetches the trade history for the authenticated user, with support for pagination and filtering by market. ```APIDOC ## GET /api/v1/me/trades ### Description Get user's trade history. ### Method GET ### Endpoint /api/v1/me/trades ### Parameters #### Query Parameters - **limit** (number) - Optional - Maximum number of trades to return. - **marketId** (number) - Optional - Filter trades by market ID. - **page** (number) - Optional - Page number for pagination. ### Response #### Success Response (200) - **list** ([Trade](../interfaces/Trade.html)[]) - Array of trade objects. - **total** (number) - Total number of trades available. #### Response Example ```json { "list": [ { "id": 1, "marketId": 1, "price": "120.00" } ], "total": 100 } ``` ``` -------------------------------- ### User Account: Get My Positions (TypeScript) Source: https://github.com/yuandiaodiaodiao/opinion-js-sdk/blob/master/README.md Fetch the current user's positions, with optional filtering by market ID and pagination parameters (page and limit). ```typescript const positions = await client.getMyPositions({ marketId: 123, page: 1, limit: 10, }); ``` -------------------------------- ### Batch Operations with Opinion JS SDK Source: https://github.com/yuandiaodiaodiao/opinion-js-sdk/blob/master/docs/api/index.html Provides examples for performing multiple order-related operations in batches. This includes placing multiple orders, canceling multiple specific orders by ID, and canceling all open orders, optionally with filters. ```javascript // Place multiple orders const orders = [ { marketId: 1, tokenId: '0x...', price: '0.5', ... }, { marketId: 2, tokenId: '0x...', price: '0.6', ... }, ]; const results = await client.placeOrdersBatch(orders, true); // Cancel multiple orders const cancelResults = await client.cancelOrdersBatch(['id1', 'id2']); // Cancel all open orders (with optional filters) const summary = await client.cancelAllOrders({ marketId: 123, // optional side: OrderSide.BUY, // optional }); console.log(`Cancelled ${summary.cancelled} orders`); ``` -------------------------------- ### Get Latest Price Source: https://github.com/yuandiaodiaodiao/opinion-js-sdk/blob/master/docs/api/classes/Client.html Fetches the latest price for a given token. This endpoint is crucial for real-time market monitoring and trading decisions. ```APIDOC ## GET /api/v1/latestPrice ### Description Get latest price for a token. ### Method GET ### Endpoint /api/v1/latestPrice ### Parameters #### Query Parameters - **tokenId** (string) - Required - Token ID ### Response #### Success Response (200) - **price** (string) - The latest price of the token. #### Response Example ```json { "price": "123.45" } ``` ``` -------------------------------- ### User Account: Get My Balances (TypeScript) Source: https://github.com/yuandiaodiaodiao/opinion-js-sdk/blob/master/README.md Retrieve the user's current token balances. The result is an array of objects, each containing the symbol and balance of a token. ```typescript const balances = await client.getMyBalances(); balances.forEach(b => { console.log(`${b.symbol}: ${b.balance}`); }); ``` -------------------------------- ### User Account: Get My Orders (TypeScript) Source: https://github.com/yuandiaodiaodiao/opinion-js-sdk/blob/master/README.md Retrieve a list of the current user's orders, with optional filtering by market ID, status, and pagination parameters (page and limit). ```typescript const myOrders = await client.getMyOrders({ marketId: 123, // optional filter status: '1', // 1 = pending page: 1, limit: 10, }); ``` -------------------------------- ### Get Fee Rates Source: https://github.com/yuandiaodiaodiao/opinion-js-sdk/blob/master/docs/api/classes/Client.html Retrieves the fee rates for a specific token. This endpoint is useful for understanding the cost associated with token transactions. ```APIDOC ## GET /api/v1/feeRates ### Description Get fee rates for a token. ### Method GET ### Endpoint /api/v1/feeRates ### Parameters #### Query Parameters - **tokenId** (string) - Required - Token ID ### Response #### Success Response (200) - **FeeRates** ([FeeRates](../interfaces/FeeRates.html)[]) - Array of fee rate objects. #### Response Example ```json [ { "fee": "0.001" } ] ``` ``` -------------------------------- ### Market Data API Source: https://github.com/yuandiaodiaodiao/opinion-js-sdk/blob/master/docs/api/index.html This section details endpoints for retrieving market data, including listing markets, getting market details, fetching orderbooks, and accessing historical price data. ```APIDOC ## GET /api/markets ### Description Retrieves a list of available prediction markets. ### Method GET ### Endpoint `/api/markets` ### Parameters #### Query Parameters - **topicType** (TopicType) - Optional - The type of topic to filter markets by (e.g., BINARY). - **page** (number) - Optional - The page number for pagination. - **limit** (number) - Optional - The number of markets to return per page. - **status** (string) - Optional - The status of the markets to filter by (e.g., 'activated'). ### Response #### Success Response (200) - **list** (array) - An array of market objects. #### Response Example ```json { "list": [ { "id": 123, "title": "Will ETH price be above $2000 tomorrow?", "status": "activated" } ] } ``` ``` ```APIDOC ## GET /api/markets/{marketId} ### Description Retrieves detailed information for a specific prediction market. ### Method GET ### Endpoint `/api/markets/{marketId}` ### Parameters #### Path Parameters - **marketId** (number) - Required - The ID of the market to retrieve. ### Response #### Success Response (200) - **id** (number) - The market ID. - **title** (string) - The title of the market. - **status** (string) - The current status of the market. #### Response Example ```json { "id": 123, "title": "Will ETH price be above $2000 tomorrow?", "status": "activated" } ``` ``` ```APIDOC ## GET /api/orderbook/{tokenId} ### Description Retrieves the orderbook for a specific market's token. ### Method GET ### Endpoint `/api/orderbook/{tokenId}` ### Parameters #### Path Parameters - **tokenId** (string) - Required - The token ID of the market. ### Response #### Success Response (200) - **bids** (array) - An array of bid orders. - **asks** (array) - An array of ask orders. #### Response Example ```json { "bids": [ { "price": "0.55", "amount": "10" } ], "asks": [ { "price": "0.60", "amount": "5" } ] } ``` ``` ```APIDOC ## GET /api/price-history/{tokenId} ### Description Retrieves the historical price data for a specific market token. ### Method GET ### Endpoint `/api/price-history/{tokenId}` ### Parameters #### Path Parameters - **tokenId** (string) - Required - The token ID of the market. #### Query Parameters - **interval** (string) - Optional - The interval for the price data (e.g., '1m', '1h', '1d', '1w', 'max'). Defaults to '1h'. - **startAt** (number) - Optional - The start timestamp (Unix epoch seconds) for the historical data. ### Response #### Success Response (200) - **history** (array) - An array of price data points. #### Response Example ```json { "history": [ { "time": 1678886400, "price": "0.58" } ] } ``` ``` -------------------------------- ### Get User Positions with Filtering and Pagination Source: https://context7.com/yuandiaodiaodiao/opinion-js-sdk/llms.txt Retrieve a user's current holdings across different markets, with options to paginate results or filter by a specific market ID. Displays key position metrics like shares owned, average entry price, and P&L. ```typescript // Get all positions const positions = await client.getMyPositions({ page: 1, limit: 20, }); console.log(`Active Positions (${positions.total} total):`); positions.list.forEach(pos => { console.log(`\n${pos.marketTitle} (${pos.marketId}):`); console.log(` Outcome: ${pos.outcome} (${pos.outcomeSideEnum})`); console.log(` Shares Owned: ${pos.sharesOwned}`); console.log(` Shares Frozen: ${pos.sharesFrozen}`); console.log(` Avg Entry: ${pos.avgEntryPrice}`); console.log(` Current Value: ${pos.currentValueInQuoteToken} USDC`); console.log(` Unrealized P&L: ${pos.unrealizedPnl} (${pos.unrealizedPnlPercent}%)`); console.log(` Daily Change: ${pos.dailyPnlChange} (${pos.dailyPnlChangePercent}%)`); console.log(` Status: ${pos.marketStatusEnum}`); console.log(` Claim Status: ${pos.claimStatusEnum}`); }); // Get positions for specific market const marketPositions = await client.getMyPositions({ marketId: 12345, page: 1, limit: 10, }); console.log(`\nPositions in market 12345: ${marketPositions.list.length}`); ``` -------------------------------- ### Get User Balances Source: https://github.com/yuandiaodiaodiao/opinion-js-sdk/blob/master/docs/api/classes/Client.html Retrieves the current balances for the authenticated user across various assets. This is essential for managing user's funds. ```APIDOC ## GET /api/v1/me/balances ### Description Get user's balances. ### Method GET ### Endpoint /api/v1/me/balances ### Response #### Success Response (200) - **Balance** ([Balance](../interfaces/Balance.html)[]) - Array of balance objects for each asset. #### Response Example ```json [ { "asset": "USD", "amount": "1000.00" } ] ``` ``` -------------------------------- ### Handle SDK Errors with TypeScript Source: https://context7.com/yuandiaodiaodiao/opinion-js-sdk/llms.txt This example demonstrates comprehensive error handling for SDK operations using TypeScript. It differentiates between client-side validation errors, API errors, insufficient gas balances, and insufficient token balances, providing specific feedback for each case. It relies on imported error types from the 'unofficial-opinion-clob-sdk'. ```typescript import { InvalidParamError, OpenApiError, InsufficientGasBalance, BalanceNotEnough, } from 'unofficial-opinion-clob-sdk'; // Complete error handling example async function placeOrderWithErrorHandling() { try { const order = await client.placeOrder({ marketId: 12345, tokenId: '0xabc...', price: '0.55', makerAmountInQuoteToken: '100', side: OrderSide.BUY, orderType: OrderType.LIMIT_ORDER, }, true); console.log('Order placed successfully:', order.orderId); return order; } catch (error) { if (error instanceof InvalidParamError) { // Client-side validation error console.error('Invalid parameters:', error.message); console.error('Please check: price range, amount, market ID'); } else if (error instanceof OpenApiError) { // API error (4xx/5xx response) console.error('API error:', error.message); console.error('Status:', error.statusCode); console.error('Response:', error.response); } else if (error instanceof InsufficientGasBalance) { // Not enough BNB for gas console.error('Insufficient gas balance:', error.message); console.error('Address:', error.address); console.error('Required:', error.required, 'wei'); console.error('Available:', error.available, 'wei'); console.error('Please add BNB to your wallet'); } else if (error instanceof BalanceNotEnough) { // Not enough token balance console.error('Insufficient token balance:', error.message); console.error('Please deposit more tokens'); } else { // Unknown error console.error('Unexpected error:', error); } throw error; } } // Error handling for blockchain operations async function splitWithErrorHandling(marketId: number, amount: bigint) { try { const result = await client.split(marketId, amount, true); console.log('Split successful:', result.txHash); } catch (error) { if (error instanceof BalanceNotEnough) { console.error('Not enough USDC to split'); } else if (error instanceof InsufficientGasBalance) { console.error('Not enough BNB for gas fees'); } else if (error instanceof OpenApiError) { console.error('Market not in correct state:', error.message); } else { console.error('Transaction failed:', error); } } } // Execute with error handling await placeOrderWithErrorHandling(); ``` -------------------------------- ### Get Categorical Market Details Source: https://github.com/yuandiaodiaodiao/opinion-js-sdk/blob/master/docs/api/classes/Client.html Retrieves detailed information about a specific categorical market. Requires the market ID as a number parameter. Returns a promise that resolves with the market data. ```typescript async function getCategoricalMarketDetails(client: Client, marketId: number) { try { const marketData = await client.getCategoricalMarket(marketId); console.log(`Details for market ${marketId}:`, marketData); return marketData; } catch (error) { console.error(`Error fetching details for market ${marketId}:`, error); throw error; } } ``` -------------------------------- ### Cancel Multiple Orders in Batch - TypeScript Source: https://context7.com/yuandiaodiaodiao/opinion-js-sdk/llms.txt Provides an example of cancelling multiple open orders simultaneously using the Opinion JS SDK. This batch operation streamlines the process of managing and closing multiple positions efficiently. It iterates through the results to report success or failure for each cancellation. ```typescript const orderIds = [ 'order-id-1', 'order-id-2', 'order-id-3', 'order-id-4', 'order-id-5', ]; // Cancel all orders const cancelResults = await client.cancelOrdersBatch(orderIds); // Process results cancelResults.forEach(result => { if (result.success) { console.log(`✓ Cancelled order: ${result.orderId}`); } else { console.log(`✗ Failed to cancel ${result.orderId}: ${result.error}`); } }); const cancelled = cancelResults.filter(r => r.success).length; console.log(` Cancelled ${cancelled} out of ${orderIds.length} orders`); ``` -------------------------------- ### Validate Prices with Opinion SDK Source: https://context7.com/yuandiaodiaodiao/opinion-js-sdk/llms.txt Shows how to use the validatePrice function to ensure prices adhere to market constraints (between 0.001 and 0.999 with a maximum of 6 decimal places). The example includes valid price checks and demonstrates how invalid prices trigger errors, preventing invalid order placements. Requires importing 'validatePrice' from 'unofficial-opinion-clob-sdk' and using an initialized 'client' object. ```typescript import { validatePrice } from 'unofficial-opinion-clob-sdk'; // Valid prices (between 0.001 and 0.999, max 6 decimals) const validPrice1 = validatePrice('0.550000'); // "0.550000" const validPrice2 = validatePrice(0.75); // "0.75" const validPrice3 = validatePrice('0.001'); // "0.001" (minimum) const validPrice4 = validatePrice('0.999'); // "0.999" (maximum) console.log('Valid prices:', validPrice1, validPrice2, validPrice3, validPrice4); // Invalid prices throw InvalidParamError try { validatePrice('1.5'); // Too high (> 0.999) } catch (error) { console.error('Error:', error.message); // "Price 1.5 is out of valid range. Price must be between 0.001 and 0.999." } try { validatePrice('0.0005'); // Too low (< 0.001) } catch (error) { console.error('Error:', error.message); } try { validatePrice('0.5555555'); // Too many decimals (> 6) } catch (error) { console.error('Error:', error.message); // "Price precision exceeds 6 decimal places: 0.5555555..." } // Use in order placement try { await client.placeOrder({ marketId: 12345, tokenId: '0xabc...', price: validatePrice('0.65'), // Validated makerAmountInQuoteToken: '100', side: OrderSide.BUY, orderType: OrderType.LIMIT_ORDER, }); } catch (error) { console.error('Order failed:', error.message); } ``` -------------------------------- ### Initialize Opinion CLOB SDK Client and Place Limit Buy Order Source: https://github.com/yuandiaodiaodiao/opinion-js-sdk/blob/master/docs/api/index.html Demonstrates initializing the Opinion CLOB SDK client with configuration options and placing a limit buy order on a market. Requires market ID, token ID, price, and amount. The client configuration includes API host, API key, RPC URL, private key, wallet address, and chain ID. ```typescript import { Client, OrderSide, OrderType } from 'unofficial-opinion-clob-sdk'; // Initialize the client const client = new Client({ host: 'https://api.opinion.com', apiKey: 'your-api-key', rpcUrl: 'https://bsc-dataseed.binance.org/', privateKey: '0x...', walletAddress: '0x...', chainId: 56, // BNB Chain }); // Get markets const markets = await client.getMarkets({ page: 1, limit: 20 }); console.log('Available markets:', markets.list); // Place a limit buy order const order = await client.placeOrder({ marketId: 123, tokenId: '0x...', price: '0.55', makerAmountInQuoteToken: '100', // 100 USDC side: OrderSide.BUY, orderType: OrderType.LIMIT_ORDER, }); console.log('Order placed:', order); ``` -------------------------------- ### Initialize Opinion CLOB SDK Client Source: https://github.com/yuandiaodiaodiao/opinion-js-sdk/blob/master/docs/api/classes/Client.html Initializes a new Opinion CLOB SDK client with the provided configuration. This is the primary entry point for interacting with the SDK. ```typescript import { Client } from "@opinions-clob/js-sdk"; const config = { // ... client configuration details }; const client = new Client(config); ``` -------------------------------- ### Get Trade History API Source: https://context7.com/yuandiaodiaodiao/opinion-js-sdk/llms.txt Retrieves a list of completed trades for the authenticated user. Supports pagination and filtering by market. ```APIDOC ## GET /trades ### Description Retrieve your completed trades with details. ### Method GET ### Endpoint /trades ### Parameters #### Query Parameters - **page** (number) - Optional - The page number for pagination. - **limit** (number) - Optional - The number of trades to retrieve per page. - **marketId** (number) - Optional - Filter trades by a specific market ID. ### Request Example ```typescript // Get recent trades const trades = await client.getMyTrades({ page: 1, limit: 20, }); // Get trades for specific market const marketTrades = await client.getMyTrades({ marketId: 12345, page: 1, limit: 50, }); ``` ### Response #### Success Response (200) - **total** (number) - The total number of trades available. - **list** (array) - An array of trade objects. - **tradeNo** (string) - The unique identifier for the trade. - **marketTitle** (string) - The title of the market. - **marketId** (number) - The ID of the market. - **orderNo** (string) - The order number associated with the trade. - **txHash** (string) - The transaction hash on the blockchain. - **side** (string) - The side of the trade (e.g., BUY, SELL). - **outcome** (string) - The outcome of the trade. - **outcomeSideEnum** (string) - The enum for the outcome side. - **price** (string) - The price at which the trade was executed. - **shares** (string) - The number of shares traded. - **amount** (string) - The amount traded in the base currency. - **usdAmount** (string) - The equivalent amount in USD. - **fee** (string) - The trading fee. - **profit** (string) - The profit or loss from the trade. - **statusEnum** (string) - The status of the trade. - **createdAt** (number) - The timestamp when the trade was created (Unix epoch time). #### Response Example ```json { "total": 100, "list": [ { "tradeNo": "T12345", "marketTitle": "BTC/USDC", "marketId": 12345, "orderNo": "O67890", "txHash": "0xabc...", "side": "BUY", "outcome": "FILLED", "outcomeSideEnum": "FILLED", "price": "0.550000", "shares": "10", "amount": "5.500000", "usdAmount": "5.50", "fee": "0.001", "profit": "0.1", "statusEnum": "FILLED", "createdAt": 1678886400 } ] } ``` ``` -------------------------------- ### Initialize Theme and Display for Opinion CLOB SDK Source: https://github.com/yuandiaodiaodiao/opinion-js-sdk/blob/master/docs/api/classes/CouldNotPayGasWithEther.html This JavaScript snippet initializes the theme based on local storage or OS preference and controls the initial display of the application body. It uses setTimeout to ensure the application is shown after a delay or when available. ```javascript document.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### Initialize Opinion CLOB SDK Client (TypeScript) Source: https://github.com/yuandiaodiaodiao/opinion-js-sdk/blob/master/README.md Demonstrates how to initialize the Opinion CLOB SDK client with necessary configuration options. This includes API host, API key, RPC URL, private key, vault address, and chain ID. ```typescript import { Client, OrderSide, OrderType } from 'unofficial-opinion-clob-sdk'; // Initialize the client const client = new Client({ host: 'https://api.opinion.com', apiKey: 'your-api-key', rpcUrl: 'https://bsc-dataseed.binance.org/', privateKey: '0x...', // Replace with your private key vaultAddress: '0x...', // Replace with your vault address chainId: 56, // BNB Chain }); // Get markets const markets = await client.getMarkets({ page: 1, limit: 20 }); console.log('Available markets:', markets.list); // Place a limit buy order const order = await client.placeOrder({ marketId: 123, tokenId: '0x...', // Replace with actual token ID price: '0.55', makerAmountInQuoteToken: '100', // 100 USDC side: OrderSide.BUY, orderType: OrderType.LIMIT_ORDER, }); console.log('Order placed:', order); ``` -------------------------------- ### placeOrder Source: https://github.com/yuandiaodiaodiao/opinion-js-sdk/blob/master/docs/api/classes/Client.html Places a single order on the platform. ```APIDOC ## POST /placeOrder ### Description Place an order. ### Method POST ### Endpoint /placeOrder ### Parameters #### Request Body - **data** (PlaceOrderDataInput) - Required - The data required to place the order. - **checkApproval** (boolean) - Optional - Whether to check and enable trading first. Defaults to false. ### Response #### Success Response (200) - **any** - The result of the order placement. ``` -------------------------------- ### User Account: Get My Trades (TypeScript) Source: https://github.com/yuandiaodiaodiao/opinion-js-sdk/blob/master/README.md Fetch the user's trade history, with optional filtering by market ID and pagination parameters (page and limit). ```typescript const trades = await client.getMyTrades({ marketId: 123, page: 1, limit: 20, }); ``` -------------------------------- ### Development: Build Script (Bash) Source: https://github.com/yuandiaodiaodiao/opinion-js-sdk/blob/master/README.md Execute the build script for the project using npm. This command compiles the source code and prepares the package for distribution. ```bash npm run build ``` -------------------------------- ### Initialize SDK Theme from Local Storage Source: https://github.com/yuandiaodiaodiao/opinion-js-sdk/blob/master/docs/api/interfaces/OrderbookLevel.html Initializes the SDK's theme by reading the 'tsd-theme' value from local storage. If no theme is found, it defaults to 'os'. This script snippet is typically used for client-side theme management. ```javascript document.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; ``` -------------------------------- ### Generate Documentation Commands Source: https://github.com/yuandiaodiaodiao/opinion-js-sdk/blob/master/CLAUDE.md Bash commands to generate TypeDoc documentation for the SDK, with options for watch mode and serving the documentation locally. ```bash npm run docs # Generate TypeDoc documentation npm run docs:watch # Generate docs in watch mode npm run docs:serve # Serve docs at http://localhost:8080 ``` -------------------------------- ### placeOrdersBatch Source: https://github.com/yuandiaodiaodiao/opinion-js-sdk/blob/master/docs/api/classes/Client.html Places multiple orders in a single batch request. ```APIDOC ## POST /placeOrdersBatch ### Description Place multiple orders in batch. ### Method POST ### Endpoint /placeOrdersBatch ### Parameters #### Request Body - **orders** (PlaceOrderDataInput[]) - Required - A list of orders to place. - **checkApproval** (boolean) - Optional - Whether to check and enable trading first. Defaults to false. ### Response #### Success Response (200) - **any[]** - An array of results for each order placed in the batch. ``` -------------------------------- ### Best Practices: Approval Management (TypeScript) Source: https://github.com/yuandiaodiaodiao/opinion-js-sdk/blob/master/README.md Optimize trading by enabling trading once using `enableTrading()`. Subsequent order placements can then be made without re-checking approvals, improving efficiency for multiple operations. ```typescript // Approve tokens once await client.enableTrading(); // Then place multiple orders without re-checking await client.placeOrder(order1, false); await client.placeOrder(order2, false); await client.placeOrder(order3, false); ``` -------------------------------- ### Get Market by ID Source: https://github.com/yuandiaodiaodiao/opinion-js-sdk/blob/master/docs/api/classes/Client.html Retrieves detailed information about a specific market using its unique ID. Optionally, it can utilize cached data for faster retrieval. ```APIDOC ## GET /api/v1/markets/{marketId} ### Description Get specific market by ID. ### Method GET ### Endpoint /api/v1/markets/{marketId} ### Parameters #### Path Parameters - **marketId** (number) - Required - Market ID #### Query Parameters - **useCache** (boolean) - Optional - Whether to use cached data (defaults to true) ### Response #### Success Response (200) - **Market** ([Market](../interfaces/Market.html)) - Object containing market details. #### Response Example ```json { "id": 1, "name": "Example Market" } ``` ``` -------------------------------- ### Run Testing Commands Source: https://github.com/yuandiaodiaodiao/opinion-js-sdk/blob/master/CLAUDE.md A set of bash commands to execute tests for the SDK, including running all tests, watch mode, coverage reports, and integration tests. ```bash npm run test # Run all tests npm run test:watch # Run tests in watch mode npm run test:coverage # Run tests with coverage report npm run test:integration # Run integration tests (requires .env) ``` -------------------------------- ### Execute Complete Trading Workflow with Opinion JS SDK (TypeScript) Source: https://context7.com/yuandiaodiaodiao/opinion-js-sdk/llms.txt This TypeScript code demonstrates a complete trading workflow using the unofficial Opinion CLOB SDK. It initializes a client, interacts with markets, places and cancels orders, checks balances and positions, and merges tokens. It requires environment variables for API key, RPC URL, private key, and vault address. ```typescript import { Client, OrderSide, OrderType, safeAmountToWei, weiToAmount } from 'unofficial-opinion-clob-sdk'; import type { Hex, Address } from 'viem'; async function completeTradingWorkflow() { // 1. Initialize client const client = new Client({ host: 'https://api.opinion.com', apiKey: process.env.OPINION_API_KEY!, rpcUrl: 'https://bsc-dataseed.binance.org/', privateKey: process.env.PRIVATE_KEY! as Hex, vaultAddress: process.env.VAULT_ADDRESS! as Address, chainId: 56, }); console.log('✓ Client initialized\n'); // 2. Find an active market const markets = await client.getMarkets({ status: 'activated', page: 1, limit: 10, }); const market = markets.list[0]; console.log(`✓ Selected market: ${market.marketTitle} (${market.marketId})\n`); // 3. Check market details and orderbook const marketDetails = await client.getMarket(market.marketId); const yesTokenId = marketDetails.yesTokenId!; const orderbook = await client.getOrderbook(yesTokenId); console.log(`✓ Current market: Best bid: ${orderbook.bids[0]?.price || 'N/A'} Best ask: ${orderbook.asks[0]?.price || 'N/A'}\n`); // 4. Check balances const balances = await client.getMyBalances(); const usdcBalance = balances.balances.find(b => b.quoteToken.toLowerCase() === marketDetails.quoteToken?.toLowerCase() ); console.log(`✓ USDC Balance: ${usdcBalance?.availableBalance || '0'}\n`); // 5. Enable trading (approve tokens) console.log('Enabling trading...'); await client.enableTrading(); console.log('✓ Trading enabled\n'); // 6. Split collateral into outcome tokens console.log('Splitting 100 USDC into outcome tokens...'); const splitAmount = safeAmountToWei(100, 6); const splitTx = await client.split(market.marketId, splitAmount, false); console.log(`✓ Split completed: ${splitTx.txHash}\n`); // 7. Place a limit buy order console.log('Placing limit buy order...'); const buyOrder = await client.placeOrder({ marketId: market.marketId, tokenId: yesTokenId, price: '0.45', makerAmountInQuoteToken: '50', side: OrderSide.BUY, orderType: OrderType.LIMIT_ORDER, }, false); console.log(`✓ Buy order placed: ${buyOrder.orderId}\n`); // 8. Place a limit sell order console.log('Placing limit sell order...'); const sellOrder = await client.placeOrder({ marketId: market.marketId, tokenId: yesTokenId, price: '0.75', makerAmountInBaseToken: '50', side: OrderSide.SELL, orderType: OrderType.LIMIT_ORDER, }, false); console.log(`✓ Sell order placed: ${sellOrder.orderId}\n`); // 9. Check open orders const openOrders = await client.getMyOrders({ marketId: market.marketId, status: '1', }); console.log(`✓ Open orders: ${openOrders.list.length}\n`); // 10. Check positions const positions = await client.getMyPositions({ marketId: market.marketId, }); positions.list.forEach(pos => { console.log(`Position: ${pos.outcome} Shares: ${pos.sharesOwned} Value: ${pos.currentValueInQuoteToken} USDC P&L: ${pos.unrealizedPnl} (${pos.unrealizedPnlPercent}%)\n`); }); // 11. Cancel an order console.log(`Cancelling order ${buyOrder.orderId}...`); await client.cancelOrder(buyOrder.orderId); console.log('✓ Order cancelled\n'); // 12. Check trade history const trades = await client.getMyTrades({ marketId: market.marketId, limit: 5, }); console.log(`✓ Recent trades: ${trades.list.length}\n`); // 13. Merge tokens back (if needed) const mergeAmount = safeAmountToWei(25, 6); console.log('Merging 25 outcome tokens back to USDC...'); const mergeTx = await client.merge(market.marketId, mergeAmount, false); console.log(`✓ Merge completed: ${mergeTx.txHash}\n`); console.log('✓ Trading workflow completed successfully!'); } // Execute workflow completeTradingWorkflow().catch(error => { console.error('Workflow failed:', error); process.exit(1); }); ``` -------------------------------- ### Amount Conversion Utilities Source: https://context7.com/yuandiaodiaodiao/opinion-js-sdk/llms.txt Provides functions to convert human-readable amounts to blockchain wei format and vice versa. ```APIDOC ## Amount Conversion Utilities ### Description Convert between human-readable amounts and blockchain wei format. ### Functions - **safeAmountToWei(amount: number | string, decimals: number): bigint** Converts a human-readable amount to wei format. Handles potential errors like negative amounts or amounts exceeding uint256. - **weiToAmount(wei: bigint, decimals: number): string** Converts an amount in wei format back to a human-readable string. ### Request Example ```typescript import { safeAmountToWei, weiToAmount } from 'unofficial-opinion-clob-sdk'; // Convert human-readable to wei const usdcAmount = safeAmountToWei(100.5, 6); // USDC has 6 decimals console.log(`100.5 USDC = ${usdcAmount}n wei`); // Convert wei back to human-readable const readableUSDC = weiToAmount(100500000n, 6); console.log(`100500000 wei = ${readableUSDC} USDC`); // Error handling try { safeAmountToWei(-100, 6); } catch (error) { console.error(error.message); } ``` ### Response (No direct response, these are utility functions.) ```