> For the complete documentation index, see [llms.txt](https://docs.sodex.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.sodex.com/for-developers/developers/trading/quickstart.md).

# Quickstart

Use curl to [query market data without an account](#try-market-data-without-an-account), or follow the Python SDK example to [place your first testnet order](#place-your-first-testnet-order).

For a frontend, delegated trading service, or read-only application, start with [Choose Your Integration](https://docs.sodex.com/for-developers/developers/trading/choose-your-integration.md). For a custom TypeScript client, use [Manual REST Signing](https://docs.sodex.com/for-developers/developers/trading/authentication-and-signing/manual-rest-signing.md).

## Try market data without an account

Use curl to query the BTC-USD perpetual market on Mainnet.

```bash
curl -fsS 'https://mainnet-gw.sodex.dev/api/v1/perps/markets/symbols?symbol=BTC-USD'
```

Look for `code: 0` and a `data` entry with `name: "BTC-USD"`. The entry's `status` shows whether the market is trading. Its `tickSize` and `stepSize` give the increments for limit price and quantity. For a limit order, check that quantity is within `minQuantity` and `maxQuantity` and that price × quantity is within `minNotional` and `maxNotional`. Omit `symbol` to retrieve [all Mainnet markets](https://mainnet-gw.sodex.dev/api/v1/perps/markets/symbols).

For a market-data app, continue with [public Perps market endpoints](https://docs.sodex.com/for-developers/api-reference/trading-api/rest-v1/sodex-rest-perps-api.md) or the [L2 book subscription](https://docs.sodex.com/for-developers/api-reference/trading-api/websocket-v1/l2book.md). For a first signed order, continue below.

## Place your first testnet order

The example places a Perps limit order, requests cancellation, and checks the final order state. It uses the primary account, its current leverage and margin settings, and the `BOTH` position side.

### 1. Prepare your testnet account

| Environment | REST base URL                  | Perps WebSocket                       | Chain ID                                | What it covers                               |
| ----------- | ------------------------------ | ------------------------------------- | --------------------------------------- | -------------------------------------------- |
| Testnet     | `https://testnet-gw.sodex.dev` | `wss://testnet-gw.sodex.dev/ws/perps` | Selected by the SDK with `testnet=True` | Order placement and account APIs.            |
| Mainnet     | `https://mainnet-gw.sodex.dev` | `wss://mainnet-gw.sodex.dev/ws/perps` | `286623`                                | Orders plus the deposit and withdrawal loop. |

Spot endpoints use `/api/v1/spot`; Perps endpoints use `/api/v1/perps`.

Use an otherwise idle Testnet wallet and claim test funds from the [faucet](https://testnet.sodex.com/faucet). See [Testnet Onboarding Steps](https://docs.sodex.com/resources/testnet-onboarding-steps.md) for the web flow. Confirm the funds you intend to trade are available in Perps before placing a Perps order.

### 2. Install the SDK and prepare your trading key

Use Python 3.9 or later. Install the same reviewed `0.2.1` source revision as the [Python SDK Guide](https://docs.sodex.com/for-developers/sdks/python-sdk-guide.md#installation):

```bash
python3 -m venv .venv
source .venv/bin/activate
python -m pip install 'git+https://github.com/sodex-tech/sodex-python-sdk-public.git@732ac02c0297e2b8ce65d23780cdab246c659d63'
```

Already have a registered Testnet trading key? [Confirm its registration](https://docs.sodex.com/for-developers/developers/trading/api-keys-and-nonces.md#confirm-registration) and continue below. For a new key, follow [Register a trading API key](https://docs.sodex.com/for-developers/developers/trading/api-keys-and-nonces.md#register-a-trading-api-key).

### 3. Configure the example

| Variable                                  | Value                                                                       |
| ----------------------------------------- | --------------------------------------------------------------------------- |
| `SODEX_ACCOUNT_ADDRESS`                   | The master wallet address that owns the funded testnet account.             |
| `SODEX_API_KEY_NAME`                      | The registered trading key's name.                                          |
| `SODEX_PRIVATE_KEY`                       | That API key's private key, supplied through your local secret environment. |
| `SODEX_DEMO_SYMBOL`                       | The selected market's `name`.                                               |
| `SODEX_DEMO_PRICE`, `SODEX_DEMO_QUANTITY` | Your chosen limit price and base-asset quantity as decimal strings.         |

Set the non-secret inputs, replacing the placeholders:

```bash
export SODEX_ACCOUNT_ADDRESS='YOUR_MASTER_WALLET_ADDRESS'
export SODEX_API_KEY_NAME='YOUR_REGISTERED_KEY_NAME'
export SODEX_DEMO_SYMBOL='NAME_FROM_THE_SYMBOLS_RESPONSE'
export SODEX_DEMO_PRICE='YOUR_LIMIT_PRICE'
export SODEX_DEMO_QUANTITY='YOUR_BASE_ASSET_QUANTITY'
# Supply SODEX_PRIVATE_KEY securely in the local environment.
```

The TypeScript registration example calls the trading secret `SODEX_API_KEY_PRIVATE_KEY`; the Python SDK reads it as `SODEX_PRIVATE_KEY`. Use the same API key secret. The script explicitly selects Testnet even if `SODEX_NETWORK` is unset or set to Mainnet.

If you just claimed faucet funds, transfer a portion of the credited Spot vUSDC to Perps. This step requires a key with `WITHDRAW` enabled. If you registered a [trading-only key](https://docs.sodex.com/for-developers/developers/trading/api-keys-and-nonces.md#permissioned-api-keys) (`permissions: 14`), fund Perps separately from the owning wallet and skip the transfer command. See [Spot transfer requirements](https://docs.sodex.com/for-developers/api-reference/trading-api/rest-v1/sodex-rest-spot-api.md#transfer-asset-to-evm-or-perps). This example moves 30 test vUSDC.

```bash
python -c 'from decimal import Decimal; from sodex.client import Client; Client.from_env(testnet=True).transfer_spot_to_perps("vUSDC", Decimal("30"))'
curl -fsS "https://testnet-gw.sodex.dev/api/v1/perps/accounts/$SODEX_ACCOUNT_ADDRESS/state"
```

Check `code == 0` and the available margin in `data.am` before placing the order. If the transfer response is lost, check both engine balances before initiating another transfer.

### 4. Place, cancel, and confirm one order

Save the following as `quickstart.py`. Running it submits a real testnet limit buy and a cancellation. The order can fill before cancellation, so use a quantity you intend to trade. Every run creates a new client order ID: if a run is interrupted after that ID is printed, [reconcile the original order](https://docs.sodex.com/for-developers/api-reference/trading-api/rest-v1/sodex-rest-perps-api.md#query-order-history) before running it again.

```python
import os
import time
from decimal import Decimal
from uuid import uuid4

from requests.exceptions import Timeout, ConnectionError as HTTPConnectionError

from sodex.client import APIError, Client, HistoryFilter
from sodex.ws import Client as WebSocketClient

for name in ("SODEX_ACCOUNT_ADDRESS", "SODEX_API_KEY_NAME", "SODEX_PRIVATE_KEY"):
    if not os.environ.get(name):
        raise ValueError(f"Set {name}")

client = Client.from_env(testnet=True)
owner = os.environ["SODEX_ACCOUNT_ADDRESS"]
symbol = os.environ["SODEX_DEMO_SYMBOL"]
price = Decimal(os.environ["SODEX_DEMO_PRICE"])
quantity = Decimal(os.environ["SODEX_DEMO_QUANTITY"])
market, = client.perps_symbols(symbol)
if price <= 0 or quantity <= 0:
    raise ValueError("Price and quantity must be positive")
if price % Decimal(market.tick_size) or quantity % Decimal(market.step_size):
    raise ValueError("Price or quantity does not match the market's tick/step size")

account_id = client.primary_account_id()
print("Testnet account:", account_id, "market:", market.symbol)
print("Rules: tick", market.tick_size, "step", market.step_size,
      "min quantity", market.min_quantity, "min notional", market.min_notional)
cl_ord_id = "qs-" + uuid4().hex
print("Client order ID:", cl_ord_id, flush=True)


def on_order(order):
    if order.cl_ord_id == cl_ord_id:
        print("Order event:", order.order_id, order.status, order.filled_qty)


def on_trade(fill):
    if fill.cl_ord_id == cl_ord_id:
        print("Fill:", fill.order_id, fill.trade_id, fill.price, fill.quantity)


ws = WebSocketClient.from_base_url(client.base_url, engine="perps")
subscription = ws.subscribe_account(
    owner, symbols=[symbol], on_order_update=on_order, on_trade=on_trade,
)
try:
    ws.connect()
    subscription.wait_ready(timeout=10)
    print("Account subscriptions acknowledged")
    receipt = client.perps_order(
        symbol, True, quantity, limit_price=price,
        account_id=account_id, cl_ord_id=cl_ord_id,
    )
    print("Order receipt:", receipt.order_id, flush=True)
    if receipt.order_id <= 0:
        raise RuntimeError("No usable order ID; reconcile the saved client order ID")

    try:
        client.cancel_perps_order(symbol, order_id=receipt.order_id, account_id=account_id)
        print("Cancel response received; checking final state")
    except (APIError, Timeout, HTTPConnectionError) as error:
        print("Cancel not confirmed:", error, "Checking final state")

    history_filter = HistoryFilter(symbol=symbol, account_id=account_id, limit=100)
    terminal = {"FILLED", "CANCELED", "EXPIRED", "REJECTED"}
    for _ in range(10):
        records = client.perps_orders(owner, symbol=symbol, account_id=account_id)
        records += client.perps_orders_history(owner, history_filter)
        order = next((item for item in records if item.order_id == receipt.order_id), None)
        if order is not None and order.status in terminal:
            print("Final order:", order.status, "executed quantity:", order.executed_qty)
            break
        time.sleep(1)
    else:
        raise TimeoutError("Final state unconfirmed; reconcile the saved order identifiers")
finally:
    ws.close()
```

Run it:

```bash
python quickstart.py
```

A cancellation without fills produces output with this shape. IDs, market rules, and event ordering vary:

```
Testnet account: <account ID> market: <symbol>
Rules: tick <tick size> step <step size> min quantity <minimum> min notional <minimum>
Client order ID: qs-<unique ID>
Account subscriptions acknowledged
Order receipt: <order ID>
Cancel response received; checking final state
Final order: CANCELED executed quantity: 0
```

### 5. Interpret the result

| Result                                               | What it establishes                                                                                                                                                                     |
| ---------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Subscription acknowledgement                         | The server accepted the account subscriptions. This is not a full state reconciliation.                                                                                                 |
| Placement receipt                                    | An order identifier was returned. Confirm the order's state and actual fills.                                                                                                           |
| Cancel response                                      | A response was received for cancellation. The script still queries open orders and history for the final state.                                                                         |
| `CANCELED` or `EXPIRED`                              | The order is terminal; check executed quantity and trades for partial fills.                                                                                                            |
| `FILLED`                                             | The order filled before cancellation. Reconcile the resulting position and fees.                                                                                                        |
| `REJECTED`, an exception, or unconfirmed final state | Inspect the reported cause and follow [Trading Troubleshooting](https://docs.sodex.com/for-developers/developers/trading/troubleshooting.md). Do not automatically place a replacement. |

The pinned SDK can return order ID zero when an individual order is rejected, even though the HTTP envelope succeeded. Inspect the raw response item’s `code` and `error`. For example, `open interest cap reached` can reject a new position on a market whose status is still `TRADING`.

The Python client handles the HTTP envelope; raw REST clients must inspect the top-level `code` and each batch item's `code` and `error`. This example also requires a usable order ID and confirms terminal state through REST.

Use [Account Trades](https://docs.sodex.com/for-developers/api-reference/trading-api/websocket-v1/account-trades.md) and [REST recovery queries](https://docs.sodex.com/for-developers/api-reference/trading-api/rest-v1/sodex-rest-perps-api.md#query-trades) to reconcile fills and fees. The script reads the most recent 100 historical orders on an otherwise idle test account; a production client must cover longer gaps with the documented history filters and pagination. Resubscription does not recover missed events by itself.

## Mainnet funding and next steps

On Mainnet, complete a USDC deposit of **at least 5 USDC in one transaction** before API-key registration, wait for credit, and [retrieve the account ID](https://docs.sodex.com/for-developers/api-reference/trading-api.md#get-account-id). There is no Testnet Mirror API. The Mainnet funding routes are:

1. [Custody Deposits](https://docs.sodex.com/for-developers/developers/mirror-protocol/lifecycle/custody-deposits.md) or [Bridge Deposits](https://docs.sodex.com/for-developers/developers/mirror-protocol/lifecycle/deposits.md) from external networks.
2. [ValueChain to Spot or Perps](https://docs.sodex.com/for-developers/developers/mirror-protocol/lifecycle/valuechain-transfers.md) for assets already on ValueChain. If the trading account does not exist, the first credit must be USDC or SOSO; activation costs 1 unit.
3. [Withdrawals](https://docs.sodex.com/for-developers/developers/mirror-protocol/lifecycle/withdrawals.md) for the Perps → Spot → ValueChain → external route. Trading transfers stop at EVM.

Before adapting the example to Mainnet, follow [Production Integration Guide](https://docs.sodex.com/for-developers/developers/trading/production-guide.md). Continue with [Spot Trading](https://docs.sodex.com/for-developers/developers/trading/spot-trading.md), [Perp Trading](https://docs.sodex.com/for-developers/developers/trading/perp-trading.md), or the [SDK guides](https://docs.sodex.com/for-developers/sdks.md) for your integration.

## API Reference

{% content-ref url="/pages/JhkOXmaIr0osLMjp2DfF" %}
[REST API](https://docs.sodex.com/for-developers/api-reference/trading-api/rest-v1.md)
{% endcontent-ref %}

{% content-ref url="/pages/U25Aeh8OoqsoN02ofoj4" %}
[WebSocket Streams](https://docs.sodex.com/for-developers/api-reference/trading-api/websocket-v1.md)
{% endcontent-ref %}

{% content-ref url="/pages/HWeWqIzQUTNao2smQ2pp" %}
[Rate Limits](https://docs.sodex.com/for-developers/developers/trading/api-rate-limits.md)
{% endcontent-ref %}
