# Quick Start

Get up and running with the Opinion CLOB TypeScript SDK in minutes. This guide will walk you through your first integration.

### Prerequisites

Before starting, ensure you have:

* Node.js 18+ installed
* Opinion CLOB TypeScript SDK installed ([Installation Guide](/developer-guide/opinion-clob-typescript-sdk/getting-started/installation.md))
* API credentials from Opinion Labs:
  * API Key
  * Private Key (for signing orders)
  * Multi-sig wallet address (create on [https://app.opinion.trade](https://app.opinion.trade/))
  * RPC URL (BNB Chain mainnet)

{% hint style="info" %}
**Need credentials?** Fill out this [short application form](https://docs.google.com/forms/d/1h7gp8UffZeXzYQ-lv4jcou9PoRNOqMAQhyW4IwZDnII) to get your API key.
{% endhint %}

### 5-Minute Quickstart

{% stepper %}
{% step %}

### Set Up Environment

Create a `.env` file in your project directory:

{% code title=".env" %}

```bash
# .env file
API_KEY=your_api_key_here
RPC_URL=https://bsc-dataseed.binance.org
PRIVATE_KEY=0x1234567890abcdef...
MULTI_SIG_ADDRESS=0xYourWalletAddress...
```

{% endcode %}
{% endstep %}

{% step %}

### Initialize the Client

Create a new TypeScript file (`my_first_app.ts`):

{% code title="my\_first\_app.ts (initialization)" %}

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

const client = new Client({
  host: DEFAULT_API_HOST,
  apiKey: process.env.API_KEY!,
  chainId: CHAIN_ID_BNB_MAINNET, // 56
  rpcUrl: process.env.RPC_URL!,
  privateKey: process.env.PRIVATE_KEY! as `0x${string}`,
  multiSigAddress: process.env.MULTI_SIG_ADDRESS! as `0x${string}`,
});

console.log('Client initialized successfully!');
```

{% endcode %}
{% endstep %}

{% step %}

### Fetch Market Data

Add market data fetching:

{% code title="fetch-markets.ts" %}

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

// Get all active markets
const marketsResponse = await client.getMarkets({
  status: TopicStatusFilter.ACTIVATED,
  page: 1,
  limit: 10,
});

// Parse the response
if (marketsResponse.errno === 0) {
  const markets = marketsResponse.result.list;
  console.log(`\nFound ${markets.length} active markets:`);

  for (const market of markets.slice(0, 3)) {
    console.log(`  - Market #${market.market_id}: ${market.market_title}`);
    console.log(`    Status: ${market.status}`);
  }
} else {
  console.error(`Error: ${marketsResponse.errmsg}`);
}
```

{% endcode %}
{% endstep %}

{% step %}

### Get Market Details

```typescript
// Get details for a specific market
const marketId = markets[0].market_id;

const marketDetail = await client.getMarket(marketId);
if (marketDetail.errno === 0) {
  const market = marketDetail.result.data;
  console.log(`\nMarket Details for #${marketId}:`);
  console.log(`  Title: ${market.market_title}`);
  console.log(`  Question ID: ${market.question_id}`);
  console.log(`  Quote Token: ${market.quote_token}`);
  console.log(`  Chain ID: ${market.chain_id}`);
}
```

{% endstep %}

{% step %}

### Check Orderbook

```typescript
const tokenId = 'your_token_id_here'; // Replace with actual token ID

try {
  const orderbook = await client.getOrderbook(tokenId);
  if (orderbook.errno === 0) {
    console.log(`\nOrderbook for token ${tokenId}:`);
    console.log('Orderbook:', JSON.stringify(orderbook.result, null, 2));
  }
} catch (e) {
  console.log(`  (Skip if token_id not set: ${e})`);
}
```

{% endstep %}

{% step %}

### Complete Example

Here is the full `my_first_app.ts` combining all the steps above:

{% code title="my\_first\_app.ts" %}

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

async function main() {
  // Initialize client
  const client = new Client({
    host: DEFAULT_API_HOST,
    apiKey: process.env.API_KEY!,
    chainId: CHAIN_ID_BNB_MAINNET,
    rpcUrl: process.env.RPC_URL!,
    privateKey: process.env.PRIVATE_KEY! as `0x${string}`,
    multiSigAddress: process.env.MULTI_SIG_ADDRESS! as `0x${string}`,
  });
  console.log('Client initialized successfully!');

  // Get active markets
  const marketsResponse = await client.getMarkets({
    status: TopicStatusFilter.ACTIVATED,
    limit: 5,
  });

  if (marketsResponse.errno === 0) {
    const markets = marketsResponse.result.list;
    console.log(`\nFound ${markets.length} active markets\n`);

    // Display markets
    markets.forEach((market, i) => {
      console.log(`${i + 1}. ${market.market_title}`);
      console.log(`   Market ID: ${market.market_id}`);
      console.log();
    });

    // Get details for first market
    if (markets.length > 0) {
      const firstMarket = markets[0];
      const detail = await client.getCategoricalMarket(firstMarket.market_id);

      if (detail.errno === 0) {
        const m = detail.result.data;
        console.log(`Details for '${m.market_title}':`);
        console.log(`  Status: ${m.status}`);
        console.log(`  Question ID: ${m.question_id}`);
        console.log(`  Quote Token: ${m.quote_token}`);
      }
    }
  } else {
    console.error(`Error fetching markets: ${marketsResponse.errmsg}`);
  }
}

main();
```

{% endcode %}
{% endstep %}
{% endstepper %}

### Run Your App

```bash
# Install dotenv if not already installed
npm install dotenv

# Run the script
npx tsx my_first_app.ts
```

**Expected Output:**

```
Client initialized successfully!

Found 5 active markets

1. Will Bitcoin reach $100k by end of 2025?
   Market ID: 1

2. Will AI surpass human intelligence by 2030?
   Market ID: 2

...

Details for 'Will Bitcoin reach $100k by end of 2025?':
  Status: 2
  Condition ID: 0xabc123...
  Quote Token: 0xdef456...
```

### Next Steps

Now that you've fetched market data, explore more advanced features:

#### Trading

Learn how to place orders:

{% code title="place-order.ts" %}

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

// Enable trading (required once before placing orders)
await client.enableTrading();

// Place a buy order of "No" token
const orderData: PlaceOrderDataInput = {
  marketId: 813,
  tokenId: '33095770954068818933468604332582424490740136703838404213332258128147961949614',
  side: OrderSide.BUY,
  orderType: OrderType.LIMIT_ORDER,
  price: '0.55',
  makerAmountInQuoteToken: '10', // 10 USDT
};

const result = await client.placeOrder(orderData);
console.log('Order placed:', result);
```

{% endcode %}

See Placing Orders for detailed examples.

#### Position Management

Track your positions:

{% code title="positions.ts" %}

```typescript
// Get balances
const balances = await client.getMyBalances();

// Get positions
const positions = await client.getMyPositions({ limit: 20 });

// Get trade history
const trades = await client.getMyTrades({ marketId: 813 });
```

{% endcode %}

See Managing Positions for more.

#### Smart Contract Operations

Interact with blockchain:

{% code title="contract-ops.ts" %}

```typescript
// Split USDT into outcome tokens
const splitResult = await client.split(813, BigInt('1000000000000000000')); // 1 USDT

// Merge outcome tokens back to USDT
const mergeResult = await client.merge(813, BigInt('1000000000000000000'));

// Redeem winnings after market resolves
const redeemResult = await client.redeem(813);
```

{% endcode %}

See Contract Operations for details.

### Common Patterns

#### Error Handling

Always check response status:

{% code title="error-handling.ts" %}

```typescript
const response = await client.getMarkets();

if (response.errno === 0) {
  // Success
  const markets = response.result.list;
} else {
  // Error
  console.error(`Error ${response.errno}: ${response.errmsg}`);
}
```

{% endcode %}

#### Using Try-Catch

{% code title="try-catch.ts" %}

```typescript
import { InvalidParamError, OpenApiError } from '@opinion-labs/opinion-clob-sdk';

try {
  const market = await client.getMarket(123);
} catch (e) {
  if (e instanceof InvalidParamError) {
    console.error(`Invalid parameter: ${e.message}`);
  } else if (e instanceof OpenApiError) {
    console.error(`API error: ${e.message}`);
  } else {
    console.error(`Unexpected error: ${e}`);
  }
}
```

{% endcode %}

#### Pagination

For large datasets:

{% code title="pagination.ts" %}

```typescript
let page = 1;
const allMarkets: any[] = [];

while (true) {
  const response = await client.getMarkets({ page, limit: 20 });
  if (response.errno !== 0) break;

  const markets = response.result.list;
  allMarkets.push(...markets);

  if (markets.length < 20) break;
  page++;
}

console.log(`Total markets: ${allMarkets.length}`);
```

{% endcode %}

### Configuration Tips

#### Cache Settings

Optimize performance with caching:

{% code title="cache-config.ts" %}

```typescript
const client = new Client({
  // ... other params ...
  marketCacheTtl: 300,              // Cache markets for 5 minutes
  quoteTokensCacheTtl: 3600,        // Cache quote tokens for 1 hour
  enableTradingCheckInterval: 3600,  // Check trading status hourly
});
```

{% endcode %}

Set to `0` to disable caching:

{% code title="disable-cache.ts" %}

```typescript
const client = new Client({
  // ... other params ...
  marketCacheTtl: 0,  // Disable market caching
});
```

{% endcode %}

#### Chain Selection

For production deployment, ensure you're using the correct configuration:

{% code title="chain-selection.ts" %}

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

const client = new Client({
  host: DEFAULT_API_HOST,
  chainId: CHAIN_ID_BNB_MAINNET, // 56
  rpcUrl: 'https://bsc-dataseed.binance.org',
  // ... other params ...
});
```

{% endcode %}

### Resources

* [**API Reference**](/developer-guide/opinion-clob-typescript-sdk/api-references.md): All Supported Methods
* [**Configuration Guide**](/developer-guide/opinion-clob-typescript-sdk/getting-started/configuration.md): Configuration
* [**Core Concepts**](/developer-guide/opinion-clob-typescript-sdk/core-concepts.md): Architecture
* [**Troubleshooting**](/developer-guide/opinion-clob-typescript-sdk/support/troubleshooting.md): Common Issues

***

Ready to build? Explore the API Reference to see all available methods!


---

# Agent Instructions: 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:

```
GET https://docs.opinion.trade/developer-guide/opinion-clob-typescript-sdk/getting-started/quick-start.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
