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

# Trading & Orders

> Create and manage orders with the Rust SDK

## Overview

The Rust SDK provides `OrderClient` for order creation, EIP-712 signing, and order management. It supports:

* `OrderType::Gtc` for resting limit orders
* `OrderType::Fak` for fill-and-kill limit orders
* `OrderType::Fok` for fill-or-kill market orders

## Prerequisites

Before placing orders, you need:

* an authenticated `Client`
* a private key for EIP-712 signing
* market venue data (fetched via `get_market()` and cached automatically)

```rust theme={null}
use limitless_exchange_rust_sdk::Client;

let client = Client::new()?;
let private_key = std::env::var("PRIVATE_KEY")?;

let order_client = client.new_order_client(&private_key, None)?;
```

> [!NOTE]
>
> The `OrderClient` lazily fetches your profile on the first order to determine your `owner_id` and fee rate. `CHAIN_ID` defaults to `8453` (Base mainnet) unless you override it.

> [!WARNING]
>
> **Wallet-mode preflight.** Accepting the one-time "choose your trading wallet" prompt in the app enables 1-click (smart wallet) trading on your Limitless profile. Once that mode is set, self-signed orders are rejected with `Signer does not match - you should use embedded address for smart wallet`. Switch the profile to EOA trading mode first: see [Trading wallet mode](https://docs.limitless.exchange/developers/eip712-signing.md#trading-wallet-mode-whose-address-signs).

## Token approvals

Before your first trade on a given venue, you must approve the exchange contracts to spend your tokens. This is a **one-time on-chain setup** per venue.

> [tab] Standard CLOB
>
> Approve USDC and Conditional Tokens to the **exchange** contract:
>
> ```rust theme={null}
> let market = client.markets.get_market("your-market-slug").await?;
> let exchange = market
>     .venue
>     .as_ref()
>     .expect("venue")
>     .exchange
>     .clone();
>
> println!("approve USDC and CTF to {}", exchange);
> ```

> [tab] NegRisk
>
> NegRisk markets also require Conditional Token approval to the **adapter** contract:
>
> ```rust theme={null}
> let market = client.markets.get_market("your-negrisk-slug").await?;
> let venue = market.venue.as_ref().expect("venue");
>
> println!("exchange {}", venue.exchange);
> println!("adapter {}", venue.adapter.as_ref().expect("adapter"));
> ```

> [!WARNING]
>
> Approvals are on-chain transactions that cost gas. Use `venue.exchange` for both CLOB and NegRisk, and additionally `venue.adapter` for NegRisk markets.

> [!NOTE]
>
> **New trading venues.** If the market's venue has `feeModuleType` set to `"COLLATERAL"`, the signing wallet also needs a USDC approval to the venue's `feeModule` address (once per fee module), and orders must be signed with a fee rate of `0`. Updated SDK releases handle venue detection and the fee rate. See [New trading venues](https://docs.limitless.exchange/developers/venue-system.md#new-trading-venues).

## GTC orders

GTC orders remain on the book until filled or explicitly cancelled.

```rust theme={null}
use limitless_exchange_rust_sdk::{CreateOrderParams, GtcOrderArgs, OrderType, Side};

let market = client.markets.get_market("btc-above-100k-march-2025").await?;
let tokens = market.tokens.as_ref().expect("market tokens");

let result = order_client
    .create_order(CreateOrderParams {
        order_type: OrderType::Gtc,
        market_slug: market.slug.clone(),
        args: GtcOrderArgs {
            token_id: tokens.yes.clone(),
            side: Side::Buy,
            price: 0.65,
            size: 10.0,
            expiration: None,
            nonce: None,
            taker: None,
            post_only: false,
        }
        .into(),
    })
    .await?;

println!("order id {}", result.order.id);
```

### Post-only GTC order

Use `post_only: true` to ensure the order never crosses the spread as a taker:

```rust theme={null}
let result = order_client
    .create_order(CreateOrderParams {
        order_type: OrderType::Gtc,
        market_slug: market.slug.clone(),
        args: GtcOrderArgs {
            token_id: tokens.yes.clone(),
            side: Side::Buy,
            price: 0.65,
            size: 10.0,
            expiration: None,
            nonce: None,
            taker: None,
            post_only: true,
        }
        .into(),
    })
    .await?;
```

### `GtcOrderArgs`

| Field | Type | Description |
| - | - | - |
| `token_id` | `String` | Token ID from market data |
| `side` | `Side` | `Side::Buy` or `Side::Sell` |
| `price` | `f64` | Price between 0 and 1, tick-aligned to `0.001` |
| `size` | `f64` | Number of shares |
| `post_only` | `bool` | Optional. Rejects the order if it would immediately match |
| `expiration` | `Option<String>` | Must be `"0"` / `None` (the default). Non-zero expiration is not currently supported and the API rejects it. |
| `nonce` | `Option<i32>` | Must be `0` / `None` (the default). Non-zero nonce is not currently supported and the API rejects it. |
| `taker` | `Option<String>` | Optional taker address |

## Self-trade prevention

The published crate (1.1.0) does not expose `stp_policy` on `CreateOrderParams`; new orders use the server default, `cancel_maker`. `stp_policy` is available on `ReplacementOrderParams` for cancel-replace (see below).

```rust theme={null}
use limitless_exchange_rust_sdk::{CreateOrderParams, GtcOrderArgs, OrderType, Side};

let result = order_client
    .create_order(CreateOrderParams {
        order_type: OrderType::Gtc,
        market_slug: market.slug.clone(),
        args: GtcOrderArgs {
            token_id: tokens.yes.clone(),
            side: Side::Buy,
            price: 0.65,
            size: 10.0,
            expiration: None,
            nonce: None,
            taker: None,
            post_only: false,
        }
        .into(),
    })
    .await?;
```

Where it works today, on a cancel-replace replacement:

```rust theme={null}
        replacement: ReplacementOrderParams {
            order_type: OrderType::Gtc,
            market_slug: market.slug.clone(),
            args: GtcOrderArgs { token_id: tokens.yes.clone(), side: Side::Buy, price: 0.65, size: 10.0, expiration: None, nonce: None, taker: None, post_only: false }.into(),
            client_order_id: None,
            timestamp: None,
            recv_window: None,
            stp_policy: Some(StpPolicy::CancelMaker), // CancelMaker | CancelTaker | CancelBoth
        },
```

| Value | Result |
| - | - |
| `StpPolicy::CancelMaker` | Default. Cancels your conflicting resting order and continues with the incoming order. |
| `StpPolicy::CancelTaker` | Rejects the incoming order before it self-trades. |
| `StpPolicy::CancelBoth` | Cancels your conflicting resting order and rejects the incoming order. |

The create-order response carries an `execution: Option<OrderExecution>` field with the outcome:

```rust theme={null}
if let Some(execution) = result.execution.as_ref() {
    if execution.settlement_status == "CANCELED" && execution.reason.as_deref() == Some("STP_TAKER_REJECTED") {
        println!("order rejected by self-trade prevention");
    } else if let Some(cancels) = execution.stp_maker_cancels.as_deref().filter(|c| !c.is_empty()) {
        println!("cancelled own resting orders: {:?}", cancels);
    }
}
```

| `execution` field | Type | Description |
| - | - | - |
| `settlement_status` | `String` | `CANCELED` when a `cancel_taker` / `cancel_both` order is rejected. |
| `reason` | `Option<String>` | `STP_TAKER_REJECTED` when the incoming order was rejected. |
| `stp_maker_cancels` | `Option<Vec<String>>` | Resting order ids cancelled by `cancel_maker` / `cancel_both`. |

> [!NOTE]
>
> Self-trade prevention blocks same-profile matches on the **same token** only. Orders on a different token of the same profile are unaffected. The wire field is always `stpPolicy`, regardless of the SDK.

## FAK orders

FAK orders use the same `price` + `size` inputs as GTC, but any unmatched remainder is cancelled immediately.

```rust theme={null}
use limitless_exchange_rust_sdk::{CreateOrderParams, FakOrderArgs, OrderType, Side};

let response = order_client
    .create_order(CreateOrderParams {
        order_type: OrderType::Fak,
        market_slug: market.slug.clone(),
        args: FakOrderArgs {
            token_id: tokens.yes.clone(),
            side: Side::Buy,
            price: 0.45,
            size: 10.0,
            expiration: None,
            nonce: None,
            taker: None,
        }
        .into(),
    })
    .await?;

println!("order id {}", response.order.id);
println!("maker matches {}", response.maker_matches.len());
```

> [!NOTE]
>
> `post_only` is not supported for `FAK` orders.

## FOK orders

FOK orders execute immediately and fully, or are cancelled entirely. Instead of `price` and `size`, you pass `maker_amount`.

> [tab] FOK BUY
>
> For buys, `maker_amount` is the total USDC to spend:
>
> ```rust theme={null}
> use limitless_exchange_rust_sdk::{CreateOrderParams, FokOrderArgs, OrderType, Side};
>
> let response = order_client
>     .create_order(CreateOrderParams {
>         order_type: OrderType::Fok,
>         market_slug: market.slug.clone(),
>         args: FokOrderArgs {
>             token_id: tokens.yes.clone(),
>             side: Side::Buy,
>             maker_amount: 10.0,
>             expiration: None,
>             nonce: None,
>             taker: None,
>         }
>         .into(),
>     })
>     .await?;
>
> println!("order id {}", response.order.id);
> ```

> [tab] FOK SELL
>
> For sells, `maker_amount` is the number of shares to sell:
>
> ```rust theme={null}
> let response = order_client
>     .create_order(CreateOrderParams {
>         order_type: OrderType::Fok,
>         market_slug: market.slug.clone(),
>         args: FokOrderArgs {
>             token_id: tokens.yes.clone(),
>             side: Side::Sell,
>             maker_amount: 10.0,
>             expiration: None,
>             nonce: None,
>             taker: None,
>         }
>         .into(),
>     })
>     .await?;
> ```

### `FokOrderArgs`

| Field | Type | Description |
| - | - | - |
| `token_id` | `String` | Token ID from market data |
| `side` | `Side` | `Side::Buy` or `Side::Sell` |
| `maker_amount` | `f64` | BUY: USDC to spend. SELL: shares to sell. Max 6 decimals |
| `expiration` | `Option<String>` | Must be `"0"` / `None` (the default). Non-zero expiration is not currently supported and the API rejects it. |
| `nonce` | `Option<i32>` | Must be `0` / `None` (the default). Non-zero nonce is not currently supported and the API rejects it. |
| `taker` | `Option<String>` | Optional taker address |

## Build and sign separately

For advanced flows, build and sign orders without submitting them:

```rust theme={null}
use limitless_exchange_rust_sdk::{GtcOrderArgs, Side};

let unsigned = order_client
    .build_unsigned_order(
        GtcOrderArgs {
            token_id: tokens.yes.clone(),
            side: Side::Buy,
            price: 0.65,
            size: 10.0,
            expiration: None,
            nonce: None,
            taker: None,
            post_only: false,
        }
        .into(),
    )
    .await?;

let signature = order_client.sign_order_for_market(&market.slug, &unsigned).await?;
println!("{}", signature);
```

You can also override the signing config explicitly:

```rust theme={null}
use limitless_exchange_rust_sdk::OrderSigningConfig;

let signature = order_client.sign_order_with_config(
    &unsigned,
    OrderSigningConfig {
        chain_id: 8453,
        contract_address: "0xYourExchangeContract".to_string(),
    },
)?;
```

## AMM trading

CLOB orders trade against the orderbook. AMM (FPMM) markets trade against a pool, and the SDK exposes them through `sdk.amm`. The service calls `POST /amm/allowances/check`, `POST /amm/allowances/approve`, `POST /amm/buy`, and `POST /amm/sell` on behalf of a partner server wallet.

Use it when the market is an AMM market and you want the server to hold custody, sign the trade, and pay gas. See [AMM Trading (Server Wallets)](https://docs.limitless.exchange/developers/amm-trading.md) for the underlying endpoints and market model.

### Requirements

* Authenticate with an HMAC API token that holds **both** the `trading` and `delegated_signing` scopes, or call the `*_with_identity` variants with a Privy identity token. Legacy `x-api-key` credentials are rejected.
* The trade runs against a server-wallet sub-account. Set `on_behalf_of` to the sub-account profile ID (`1..=2147483647`), or leave it `None` to trade from the authenticated profile.
* Amounts are **positive integer strings** in the collateral token's base units (for USDC: `"1000000"` = 1 USDC). Never use floats.
* `slippage_bps` is `Option<i32>`. `None` uses the server default of `100` (1%); values range from `0` to `1000`.
* `outcome_index` is `0` for YES and `1` for NO.

### One-time approval per wallet and market

`BUY` and `SELL` approvals are independent and set up once per wallet and market. `buy` and `sell` do **not** preflight allowances themselves. Confirm the allowance first.

`ensure_allowance` runs `check_allowance`, submits `approve_allowance` at most once when missing, then polls the check until `confirmed` is true. Configure the poll via `AmmAllowancePollOptions` (default 2s interval, 30 attempts).

```rust theme={null}
use limitless_exchange_rust_sdk::{
    AmmAllowanceParams, AmmAllowanceSide, Client, HmacCredentials,
};

let sdk = Client::from_http_client(
    Client::builder()
        .hmac_credentials(HmacCredentials {
            token_id: std::env::var("LIMITLESS_API_TOKEN_ID")?,
            secret: std::env::var("LIMITLESS_API_TOKEN_SECRET")?,
        })
        .build()?,
)?;

let market = "btc-100k-weekly".to_string();

for side in [AmmAllowanceSide::Buy, AmmAllowanceSide::Sell] {
    sdk.amm
        .ensure_allowance(
            &AmmAllowanceParams {
                market: market.clone(),
                side,
                on_behalf_of: Some(12345),
            },
            None,
        )
        .await?;
}
```

> [!NOTE]
>
> A `submitted` response from `approve_allowance` (HTTP 202) is not confirmation. Either use `ensure_allowance`, or poll `check_allowance` until `confirmed` is true.

### Buy shares

`buy` spends an exact collateral amount on the chosen outcome. Pass a unique `idempotency_key` per trade. On a timeout retry, reuse the exact same params so the server replays the original submission rather than opening a second trade.

```rust theme={null}
use limitless_exchange_rust_sdk::AmmBuyParams;

let buy = sdk
    .amm
    .buy(&AmmBuyParams {
        market: market.clone(),
        outcome_index: 0,                       // 0 = YES, 1 = NO
        collateral_amount: "1000000".to_string(), // 1 USDC in base units
        slippage_bps: Some(100),                // optional, 0..1000
        idempotency_key: "buy-unique-key-001".to_string(),
        on_behalf_of: Some(12345),              // None for a direct profile
    })
    .await?;

println!("status={:?} expected={} min={}", buy.status, buy.expected_shares, buy.min_shares);
```

### Sell shares

`sell` requests an exact collateral return by selling outcome shares.

```rust theme={null}
use limitless_exchange_rust_sdk::AmmSellParams;

let sell = sdk
    .amm
    .sell(&AmmSellParams {
        market: market.clone(),
        outcome_index: 0,
        collateral_return_amount: "992015".to_string(),
        slippage_bps: None,
        idempotency_key: "sell-unique-key-001".to_string(),
        on_behalf_of: Some(12345),
    })
    .await?;

println!("status={:?} expected={} max={}", sell.status, sell.expected_shares, sell.max_shares);
```

> [!NOTE]
>
> Reusing an `idempotency_key` with different params returns `LimitlessError::Api` with `status == 409`. The four AMM routes share a rate limit of 10 requests / 10 seconds per actor. Every AMM method has a `*_with_raw` sibling (e.g. `sdk.amm.buy_with_raw`) that returns `SdkResponse<T>` with the HTTP status, headers, and body.

## Cancelling orders

Cancel a single order:

```rust theme={null}
let message = order_client.cancel("abc123-def456").await?;
println!("{}", message);
```

Cancel all orders in a market:

```rust theme={null}
let message = order_client.cancel_all(&market.slug).await?;
println!("{}", message);
```

## Cancel and replace

`cancel_replace` cancels one open order and submits a replacement in the same request. Use it to reprice or resize a resting order in one round-trip instead of separate cancel and create calls. `cancel_replace_batch` runs several of these operations in a single call.

The cancel and the replacement are **not atomic**: they report independent outcomes, and a successful cancel does not guarantee a successful replacement. Choose the failure mode with `CancelReplaceMode`:

| Mode | Cancellation fails | Replacement result |
| - | - | - |
| `CancelReplaceMode::StopOnFailure` | Stops the operation | `NOT_ATTEMPTED` |
| `CancelReplaceMode::AllowFailure` | Continues the operation | `SUCCESS`, `FAILURE`, or `UNKNOWN` independently |

Identify the order to cancel with `CancelTarget::OrderId` or `CancelTarget::ClientOrderId`. The replacement uses the same `OrderArgs` fields as `create_order`.

### Single cancel-replace

```rust theme={null}
use limitless_exchange_rust_sdk::{
    CancelReplaceCancelResult, CancelReplaceMode, CancelReplaceParams,
    CancelReplaceReplacementResult, CancelTarget, GtcOrderArgs, OrderType,
    ReplacementOrderParams, Side,
};

let tokens = market.tokens.as_ref().expect("CLOB market exposes tokens");

let result = order_client
    .cancel_replace(CancelReplaceParams {
        cancel: CancelTarget::OrderId { order_id: "order_abc123".to_string() },
        mode: CancelReplaceMode::StopOnFailure,
        on_behalf_of: None,
        replacement: ReplacementOrderParams {
            order_type: OrderType::Gtc,
            market_slug: market.slug.clone(),
            args: GtcOrderArgs {
                token_id: tokens.yes.clone(),
                side: Side::Buy,
                price: 0.62,
                size: 100.0,
                expiration: None,
                nonce: None,
                taker: None,
                post_only: false,
            }
            .into(),
            client_order_id: None,
            timestamp: None,
            recv_window: None,
            stp_policy: None,
        },
    })
    .await?;

if let CancelReplaceCancelResult::Success { order_id, .. } = &result.cancel {
    println!("Cancelled: {order_id}");
}
if let CancelReplaceReplacementResult::Success { data } = &result.replacement {
    println!("Replacement placed: {}", data.order.id);
}
```

### Batch cancel-replace

Each operation runs independently and its result is returned with the caller's `index`:

```rust theme={null}
let batch = order_client
    .cancel_replace_batch(vec![
        CancelReplaceParams {
            cancel: CancelTarget::OrderId { order_id: "order_abc123".to_string() },
            mode: CancelReplaceMode::AllowFailure,
            on_behalf_of: None,
            replacement: ReplacementOrderParams { /* ... */ },
        },
        CancelReplaceParams {
            cancel: CancelTarget::ClientOrderId { client_order_id: "my-tag-42".to_string() },
            mode: CancelReplaceMode::StopOnFailure,
            on_behalf_of: None,
            replacement: ReplacementOrderParams { /* ... */ },
        },
    ])
    .await?;

for item in &batch.results {
    println!("{} {:?} {:?}", item.index, item.cancel, item.replacement);
}
```

### Delegated cancel-replace

Partners with the `delegated_signing` scope call `delegated_orders.cancel_replace` and `delegated_orders.cancel_replace_batch`. The server signs the replacement using the sub-account's managed wallet, so no signing key is required. Set `on_behalf_of` (the sub-account profile ID) and `fee_rate_bps` on every operation:

```rust theme={null}
use limitless_exchange_rust_sdk::DelegatedCancelReplaceParams;

let tokens = market.tokens.as_ref().expect("CLOB market exposes tokens");

delegated_orders
    .cancel_replace(DelegatedCancelReplaceParams {
        cancel: CancelTarget::OrderId { order_id: "order_abc123".to_string() },
        mode: CancelReplaceMode::StopOnFailure,
        on_behalf_of: partner_account.profile_id,
        fee_rate_bps: 100,
        replacement: ReplacementOrderParams {
            order_type: OrderType::Gtc,
            market_slug: market.slug.clone(),
            args: GtcOrderArgs {
                token_id: tokens.yes.clone(),
                side: Side::Buy,
                price: 0.62,
                size: 100.0,
                expiration: None,
                nonce: None,
                taker: None,
                post_only: false,
            }
            .into(),
            client_order_id: None,
            timestamp: None,
            recv_window: None,
            stp_policy: None,
        },
    })
    .await?;
```

> [!NOTE]
>
> See [`POST /orders/cancel-replace`](https://docs.limitless.exchange/api-reference/trading/cancel-replace) and [`POST /orders/cancel-replace/batch`](https://docs.limitless.exchange/api-reference/trading/cancel-replace-batch) for the full request and response shapes, per-status fields, and failure semantics.


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