> ## Documentation Index
> Fetch the complete documentation index at: https://docs.orica.markets/llms.txt
> Use this file to discover all available pages before exploring further.

# Trading

> Execute buy, sell, and redeem operations with the SDK.

The SDK provides transaction builders for all trading operations. You build instructions, add them to a transaction, and sign with your wallet.

***

## Prerequisites

Before trading, ensure you have:

1. An initialized SDK instance
2. A connected wallet
3. A USDC token account with sufficient balance

> [tab] TypeScript
>
> ```typescript theme={"dark"}
> import { getAssociatedTokenAddress } from "@solana/spl-token";
>
> // Get global state for USDC mint
> const globalState = await sdk.orica.fetchGlobalState();
>
> // Get user's USDC account
> const userUsdc = await getAssociatedTokenAddress(
>   globalState.usdcMint,
>   wallet.publicKey
> );
> ```

> [tab] Python
>
> ```python theme={"dark"}
> from spl.token.instructions import get_associated_token_address
>
> # Get global state for USDC mint
> global_state = await sdk.orica.fetch_global_state()
>
> # Get user's USDC account
> user_usdc = get_associated_token_address(
>     wallet.pubkey(),
>     global_state.usdc_mint
> )
> ```

***

## Buying Shares

Purchase shares of a specific outcome:

> [tab] TypeScript
>
> ```typescript theme={"dark"}
> import { BN } from "@coral-xyz/anchor";
> import { Transaction, sendAndConfirmTransaction } from "@solana/web3.js";
>
> const marketAddress = new PublicKey("ABC123...");
> const amount = new BN(10_000_000); // 10 USDC (6 decimals)
> const outcomeIndex = 0; // 0 = first outcome (e.g., "Yes")
>
> // Build instructions
> const instructions = await sdk.orica.buildBuy(
>   wallet.publicKey,
>   userUsdc,
>   marketAddress,
>   amount,
>   outcomeIndex
> );
>
> // Instructions include compute budget + buy instruction
> const tx = new Transaction().add(...instructions);
>
> // Sign and send
> const signature = await sendAndConfirmTransaction(connection, tx, [wallet]);
> console.log("Buy executed:", signature);
> ```

> [tab] Python
>
> ```python theme={"dark"}
> from solana.transaction import Transaction
>
> market_address = Pubkey.from_string("ABC123...")
> amount = 10_000_000  # 10 USDC (6 decimals)
> outcome_index = 0  # 0 = first outcome (e.g., "Yes")
>
> # Build instructions
> instructions = await sdk.orica.build_buy(
>     user=wallet.pubkey(),
>     user_usdc=user_usdc,
>     market_address=market_address,
>     amount=amount,
>     outcome_index=outcome_index,
> )
>
> # Instructions include compute budget + buy instruction
> tx = Transaction()
> tx.add(*instructions)
>
> # Sign and send
> signature = await connection.send_transaction(tx, wallet)
> print(f"Buy executed: {signature}")
> ```

***

## Selling Shares

Sell shares back to the pool:

> [tab] TypeScript
>
> ```typescript theme={"dark"}
> const sharesToSell = new BN(5000); // Number of shares
> const outcomeIndex = 0;
>
> const instructions = await sdk.orica.buildSell(
>   wallet.publicKey,
>   userUsdc,
>   marketAddress,
>   sharesToSell,
>   outcomeIndex
> );
>
> const tx = new Transaction().add(...instructions);
> const signature = await sendAndConfirmTransaction(connection, tx, [wallet]);
> console.log("Sell executed:", signature);
> ```

> [tab] Python
>
> ```python theme={"dark"}
> shares_to_sell = 5000  # Number of shares
> outcome_index = 0
>
> instructions = await sdk.orica.build_sell(
>     user=wallet.pubkey(),
>     user_usdc=user_usdc,
>     market_address=market_address,
>     shares=shares_to_sell,
>     outcome_index=outcome_index,
> )
>
> tx = Transaction()
> tx.add(*instructions)
> signature = await connection.send_transaction(tx, wallet)
> print(f"Sell executed: {signature}")
> ```

> [!WARNING]
>
> You cannot sell more shares than you own. Fetch your position first to check balances.

***

## Redeeming Winnings

After a market resolves, redeem winning shares:

> [tab] TypeScript
>
> ```typescript theme={"dark"}
> // Only works on resolved markets with winning position
> const instruction = await sdk.orica.buildRedeem(
>   wallet.publicKey,
>   userUsdc,
>   marketAddress
> );
>
> const tx = new Transaction().add(instruction);
> const signature = await sendAndConfirmTransaction(connection, tx, [wallet]);
> console.log("Redeemed:", signature);
> ```

> [tab] Python
>
> ```python theme={"dark"}
> # Only works on resolved markets with winning position
> instruction = await sdk.orica.build_redeem(
>     user=wallet.pubkey(),
>     user_usdc=user_usdc,
>     market_address=market_address,
> )
>
> tx = Transaction()
> tx.add(instruction)
> signature = await connection.send_transaction(tx, wallet)
> print(f"Redeemed: {signature}")
> ```

***

## Compute Units

Complex bonding curve calculations require additional compute units. The SDK handles this automatically:

> [tab] TypeScript
>
> ```typescript theme={"dark"}
> // Default: 1,400,000 compute units
> const instructions = await sdk.orica.buildBuy(...);
>
> // Custom compute units
> const instructions = await sdk.orica.buildBuy(
>   wallet.publicKey,
>   userUsdc,
>   marketAddress,
>   amount,
>   outcomeIndex,
>   { computeUnits: 500_000 }
> );
> ```

> [tab] Python
>
> ```python theme={"dark"}
> # Default: 1,400,000 compute units
> instructions = await sdk.orica.build_buy(...)
>
> # Custom compute units
> instructions = await sdk.orica.build_buy(
>     user=wallet.pubkey(),
>     user_usdc=user_usdc,
>     market_address=market_address,
>     amount=amount,
>     outcome_index=outcome_index,
>     compute_units=500_000,
> )
> ```

***

## Error Handling

> [tab] TypeScript
>
> ```typescript theme={"dark"}
> try {
>   const tx = new Transaction().add(...instructions);
>   await sendAndConfirmTransaction(connection, tx, [wallet]);
> } catch (error) {
>   if (error.message.includes("insufficient funds")) {
>     console.error("Not enough USDC balance");
>   } else if (error.message.includes("MarketClosed")) {
>     console.error("Market is no longer accepting trades");
>   } else if (error.message.includes("InsufficientShares")) {
>     console.error("Not enough shares to sell");
>   } else {
>     throw error;
>   }
> }
> ```

> [tab] Python
>
> ```python theme={"dark"}
> try:
>     tx = Transaction()
>     tx.add(*instructions)
>     await connection.send_transaction(tx, wallet)
> except Exception as error:
>     if "insufficient funds" in str(error):
>         print("Not enough USDC balance")
>     elif "MarketClosed" in str(error):
>         print("Market is no longer accepting trades")
>     elif "InsufficientShares" in str(error):
>         print("Not enough shares to sell")
>     else:
>         raise
> ```

***

## Complete Trading Flow

> [tab] TypeScript
>
> ```typescript theme={"dark"}
> import { Connection, PublicKey, Transaction, sendAndConfirmTransaction } from "@solana/web3.js";
> import { getAssociatedTokenAddress } from "@solana/spl-token";
> import { BN } from "@coral-xyz/anchor";
> import { OricaSDK } from "@neko/orica-sdk";
>
> async function tradingExample(wallet: Keypair) {
>   // 1. Initialize
>   const connection = new Connection("https://api.mainnet-beta.solana.com");
>   const sdk = await OricaSDK.createFromChain(connection);
>
>   // 2. Get USDC account
>   const globalState = await sdk.orica.fetchGlobalState();
>   const userUsdc = await getAssociatedTokenAddress(globalState.usdcMint, wallet.publicKey);
>
>   // 3. Choose market and check prices
>   const marketAddress = new PublicKey("...");
>   const market = await sdk.orica.fetchMarket(marketAddress);
>   const prices = sdk.orica.calculatePrices(market);
>
>   console.log("Prices:", prices);
>
>   // 4. Buy shares
>   const buyIxs = await sdk.orica.buildBuy(
>     wallet.publicKey,
>     userUsdc,
>     marketAddress,
>     new BN(5_000_000), // 5 USDC
>     0 // Outcome 0
>   );
>
>   const buyTx = new Transaction().add(...buyIxs);
>   const buySig = await sendAndConfirmTransaction(connection, buyTx, [wallet]);
>   console.log("Bought shares:", buySig);
>
>   // 5. Check position
>   const position = await sdk.orica.fetchPosition(marketAddress, wallet.publicKey);
>   console.log("Shares held:", position?.outcomeAmounts[0].toString());
> }
> ```

> [tab] Python
>
> ```python theme={"dark"}
> from solana.rpc.async_api import AsyncClient
> from solders.pubkey import Pubkey
> from solana.transaction import Transaction
> from spl.token.instructions import get_associated_token_address
> from orica_sdk import OricaSDK
>
> async def trading_example(wallet):
>     # 1. Initialize
>     connection = AsyncClient("https://api.mainnet-beta.solana.com")
>     sdk = await OricaSDK.create(connection)
>
>     # 2. Get USDC account
>     global_state = await sdk.orica.fetch_global_state()
>     user_usdc = get_associated_token_address(wallet.pubkey(), global_state.usdc_mint)
>
>     # 3. Choose market and check prices
>     market_address = Pubkey.from_string("...")
>     market = await sdk.orica.fetch_market(market_address)
>     prices = sdk.orica.calculate_prices(market)
>
>     print(f"Prices: {prices}")
>
>     # 4. Buy shares
>     buy_ixs = await sdk.orica.build_buy(
>         user=wallet.pubkey(),
>         user_usdc=user_usdc,
>         market_address=market_address,
>         amount=5_000_000,  # 5 USDC
>         outcome_index=0,
>     )
>
>     buy_tx = Transaction()
>     buy_tx.add(*buy_ixs)
>     buy_sig = await connection.send_transaction(buy_tx, wallet)
>     print(f"Bought shares: {buy_sig}")
>
>     # 5. Check position
>     position = await sdk.orica.fetch_position(market_address, wallet.pubkey())
>     print(f"Shares held: {position.outcome_amounts[0] if position else 0}")
> ```

***

## Next Steps

> [card] [Positions](https://docs.orica.markets/sdk/positions.md)
>
> Track and manage user positions.

> [card] [Disputes](https://docs.orica.markets/sdk/disputes.md)
>
> Participate in dispute resolution.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.