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

# Rust SDK

> Call the Lean API from Rust, with a typed async method for every endpoint.

`lean-api-sdk` is the Lean API client for Rust. It is generated from the
[OpenAPI spec](https://lean.mintlify.site/api-reference/openapi.json), so every endpoint in the
[API reference](https://docs.lean.xyz/api-reference/markets/list-markets.md) is an async method on `lean_api::Client` with
typed requests and responses.

The crate uses the 2024 edition, so it needs a recent stable Rust. It runs on Tokio, and TLS uses
rustls, so there is no OpenSSL dependency.

## Install

The crate is on crates.io once 0.1.0 is published. Add it with Tokio to run it, and `uuid` for
order IDs:

```bash theme={"dark"}
cargo add lean-api-sdk uuid --features uuid/v4
cargo add tokio --features macros,rt-multi-thread
```

Or in `Cargo.toml`:

```toml Cargo.toml theme={"dark"}
[dependencies]
lean-api-sdk = "0.1"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
uuid = { version = "1", features = ["v4"] }
```

The package is `lean-api-sdk` and the library is `lean_api`.

## Create a client

The examples use the same two environment variables as the [quickstart](https://docs.lean.xyz/quickstart.md):

```bash theme={"dark"}
export LEAN_API_URL="https://api.lean.xyz"
export LEAN_API_KEY="lean_sk_test_..."
```

```rust theme={"dark"}
use lean_api::Client;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let lean = Client::from_env()?;
    Ok(())
}
```

`Client::from_env` reads `LEAN_API_KEY`, and `LEAN_API_URL` when it is set. The base URL defaults
to `https://api.lean.xyz`. Keep the key in the environment and never log it; the client leaves it
out of `Debug` output. [Authentication](https://docs.lean.xyz/authentication.md#create-a-key) shows how to create a key.

Each method returns a `Response`: the result is in `data` and the request ID in `meta.request_id`.

## Find a market

```rust theme={"dark"}
use lean_api::{ListMarketsQuery, ListMarketsQueryStatus};

let markets = lean
    .list_markets(&ListMarketsQuery {
        league: Some("nfl".into()),
        status: Some(ListMarketsQueryStatus::Open),
        limit: Some(20),
        ..Default::default()
    })
    .await?
    .data;
let market = markets
    .markets
    .iter()
    .find(|item| item.legs.iter().any(|leg| leg.tradable))
    .ok_or("No tradable market")?;

println!("{} {} {} {}", market.id, market.fixture.title, market.group.label, market.outcome);
```

Pick a market whose `legs` include one with `tradable: true`. [Markets and IDs](https://docs.lean.xyz/markets.md) explains
each field. `lean.get_market(id)` reads one market.

## Quote and preview

Check what an order would do before you place it. Neither call places or reserves anything.

```rust theme={"dark"}
use lean_api::{Action, CreateOrderRequest, QuoteMarketQuery, TimeInForce};

let quote = lean
    .quote_market(
        &market.id,
        &QuoteMarketQuery {
            action: Some(Action::Buy),
            notional: Some("25".into()),
            ..Default::default()
        },
    )
    .await?
    .data;
println!("{} {} {}", quote.executable_quantity, quote.expected_total_usd, quote.expires_at);

// A new ID for each new order. Reuse it only to retry this same order.
let client_order_id = format!("bot-{}", uuid::Uuid::new_v4().simple());
let order = CreateOrderRequest {
    notional: Some("25".into()),
    time_in_force: Some(TimeInForce::Ioc),
    ..CreateOrderRequest::new(client_order_id, &market.id, Action::Buy)
};

let preview = lean.preview_order(&order).await?.data;
println!("{} {:?}", preview.would_submit, preview.warnings);
```

`CreateOrderRequest::new` sets the required fields and leaves the rest unset. Quote again after
`expires_at`. A blocking warning means the order would be refused. See [Preview](https://docs.lean.xyz/preview.md).

## Place an order

This buys 25 USD of the outcome at once and cancels whatever can't fill:

```rust theme={"dark"}
if !preview.would_submit {
    return Err("The preview says this order would be refused".into());
}

let placed = lean.create_order(&order).await?.data;
println!("{} {} {} {}", placed.id, placed.status, placed.filled_quantity, placed.livemode);
```

`notional` is the dollars to spend, in place of `quantity`. Polymarket takes `ioc` buys by dollar
amount only, so size an immediate buy with `notional` when it should fill there. To buy a number of
shares instead, set `quantity` and `limit_price`. See
[Buying a dollar amount](https://docs.lean.xyz/orders.md#buying-a-dollar-amount).

Save `client_order_id` before you send the order, and reuse it on every retry of the same order.
Sending it again returns the original order, never a second one.

> [!WARNING]
>
> An accepted response is not a fill. Read `status` and `filled_quantity`, and confirm them by
> reading the order back.

Prices, quantities and amounts are decimal strings exactly as the API sends them, so nothing is
rounded through `f64`. Parse them with the decimal type your program already uses.

## Read an order

```rust theme={"dark"}
let read = lean.get_order(&placed.id).await?.data;
println!("{} {} {:?}", read.status, read.filled_quantity, read.avg_fill_price);
```

If the response to `create_order` never arrived, look the order up by its `client_order_id`:

```rust theme={"dark"}
use lean_api::ListOrdersQuery;

let found = lean
    .list_orders(&ListOrdersQuery {
        client_order_id: Some(order.client_order_id.clone()),
        ..Default::default()
    })
    .await?
    .data;
for item in &found.orders {
    println!("{} {}", item.id, item.status);
}
```

Then reconcile with `lean.get_positions(&Default::default())` and `lean.get_balances()`. See
[Orders and idempotency](https://docs.lean.xyz/orders.md#reconcile).

## Errors, timeouts and retries

A response that isn't a success returns `Error::Api`, and `error.api()` gives you its fields: the
HTTP `status()`, the error `code()`, the `request_id()` to quote when you report a problem, and
`details()` with structured details such as validation issues:

```rust theme={"dark"}
let placed = match lean.create_order(&order).await {
    Ok(placed) => placed.data,
    Err(error) => {
        if let Some(api) = error.api() {
            eprintln!("{} {:?} {:?} {:?}", api.status(), api.code(), api.request_id(), api.details());
        }
        return Err(error.into());
    }
};
```

[Errors](https://docs.lean.xyz/errors.md) lists every code. `Error::Transport` means the request did not complete: the
connection failed or it timed out. A POST that fails this way may still have reached the API.

Each request times out after 30 seconds. Build the client with `Client::builder()` to change it:

```rust theme={"dark"}
use std::time::Duration;

let lean = Client::builder()
    .api_key(std::env::var("LEAN_API_KEY")?)
    .timeout(Duration::from_secs(10))
    .max_read_retries(2)
    .build()?;
```

GET requests are retried twice on connection errors, 429 and 5xx responses, with jittered backoff
that follows `Retry-After`. Set `max_read_retries(0)` to turn that off. POST, PATCH and DELETE
requests are never retried. After a timeout on `create_order`, look the order up with
`list_orders` and its `client_order_id` before you send it again, and resend only with the same
`client_order_id` and body.

## Test mode

The key decides the mode, as it does for every call. With a `lean_sk_test_` key, orders and fills
are simulated and no money moves. Switch to a live key by changing `LEAN_API_KEY`; the code stays the
same.

Every successful response has `data.livemode`, which is `false` for a test key. Check it where
your program would act on money:

```rust theme={"dark"}
let balances = lean.get_balances().await?.data;
if balances.livemode {
    return Err("This program expects a test key".into());
}
```

To start over with a test key, `lean.reset_test_mode()` clears the simulated orders, positions,
withdrawals, transfers, stop losses and limit chases and returns test balances to the starting
amount. See [Test mode and live mode](https://docs.lean.xyz/test-mode.md).

## Stream updates

`Client::stream` keeps a WebSocket open. It reconnects with a new ticket after a drop and reads
every page of orders again over REST after each reconnect:

```rust theme={"dark"}
use lean_api::{StreamChannel, StreamEvent, StreamOptions, StreamStatus};

let (stream, mut events) = lean.stream(StreamOptions {
    channels: vec![StreamChannel::Orders, StreamChannel::Positions],
    ..Default::default()
})?;
stream.subscribe([StreamChannel::book(market.id.clone())]);

while let Some(event) = events.recv().await {
    match event {
        StreamEvent::Order(order) => println!("{} {}", order.id, order.status),
        StreamEvent::OrdersResync(orders) => println!("{} orders after a reconnect", orders.len()),
        StreamEvent::Stale { channel, stale } => println!("{channel:?} stale: {stale}"),
        StreamEvent::Status(StreamStatus::Disconnected(reason)) => println!("stopped: {reason:?}"),
        _ => {}
    }
}
```

`OrdersResync` replaces the order state you hold. A channel reports `Stale { stale: true }` from a
drop until its first update on the next connection. A refused key stops the stream instead of
retrying.

Events queue up to `StreamOptions::event_buffer`, 1024 by default. Past that the stream stops
reading the socket until you catch up. Call `stream.close()` when you are done; dropping every
handle or the event receiver also stops it. See [Streaming](https://docs.lean.xyz/streaming.md) for each channel.

## Types

Every request and response type is exported from `lean_api` by name, such as
`CreateOrderRequest`, `OrderPreview`, `Order` and `Market`. Enums such as `Action`, `TimeInForce`
and `OrderStatus` print as the API's strings:

```rust theme={"dark"}
use lean_api::{Order, OrderStatus};

fn is_resting(order: &Order) -> bool {
    matches!(order.status, OrderStatus::Open | OrderStatus::PartiallyFilled)
}
```

## Methods

Method names follow the [API reference](https://docs.lean.xyz/api-reference/markets/list-markets.md). The ones used most:

| Method | Endpoint |
| - | - |
| `list_markets`, `get_market` | `GET /v1/markets`, `GET /v1/markets/{id}` |
| `quote_market` | `GET /v1/markets/{id}/quote` |
| `preview_order` | `POST /v1/orders/preview` |
| `create_order` | `POST /v1/orders` |
| `get_order`, `list_orders` | `GET /v1/orders/{id}`, `GET /v1/orders` |
| `cancel_order` | `POST /v1/orders/{id}/cancel` |
| `list_fills` | `GET /v1/fills` |
| `get_positions`, `get_balances` | `GET /v1/positions`, `GET /v1/balances` |
| `reset_test_mode` | `POST /v1/test/reset` |

Changes to the crate are listed in the [changelog](https://docs.lean.xyz/changelog.md).


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