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

# Trading quickstart

> Place your first order with the Trading API: list your accounts and what their connector supports, read the instrument's rules, place a limit order, watch it on the events stream, amend it and cancel it.

This guide places a limit order far from the market, watches it on the events stream, moves it and cancels it, so nothing fills. It needs a [trading key and its private key](https://takeprofit.com/docs/platform-api/trading/api-keys.md), and an exchange account [connected to TakeProfit](https://takeprofit.com/docs/guide/trading/brokers).

These are real orders on your real account. Keep the price far from the market and the quantity at the minimum while you try things out.

## Setup

The examples are in Python with three packages:

```bash theme={null}
pip install requests websocket-client cryptography
export TAKEPROFIT_TRADING_KEY="tpk_..."
```

Every request is signed (see [Sign every request](https://takeprofit.com/docs/platform-api/trading/api-keys.md#sign-every-request)). This helper signs a query string or a body and returns the headers:

```python theme={null}
import json, os, time, uuid
from urllib.parse import urlencode

import requests
import websocket
from cryptography.hazmat.primitives.serialization import load_pem_private_key

BASE = "https://public-api.charting.com/api/v1/trading"
API_KEY = os.environ["TAKEPROFIT_TRADING_KEY"]
with open("trading-key.pem", "rb") as f:
    PRIVATE_KEY = load_pem_private_key(f.read(), password=None)

def signed_headers(payload: str) -> dict:
    timestamp = str(int(time.time() * 1000))
    message = (timestamp + API_KEY + payload).encode()
    return {
        "X-API-KEY": API_KEY,
        "X-API-TIMESTAMP": timestamp,
        "X-API-SIGNATURE": PRIVATE_KEY.sign(message).hex(),
    }

def get(path: str, params: dict | None = None) -> dict:
    query = urlencode(params or {})
    url = f"{BASE}{path}" + (f"?{query}" if query else "")
    response = requests.get(url, headers=signed_headers(query))
    response.raise_for_status()
    return response.json()

def post(path: str, payload: dict, idempotency_key: str | None = None) -> dict:
    body = json.dumps(payload)
    headers = {"Content-Type": "application/json", **signed_headers(body)}
    if idempotency_key:
        headers["Idempotency-Key"] = idempotency_key
    response = requests.post(f"{BASE}{path}", data=body, headers=headers)
    response.raise_for_status()
    return response.json()

def stream(path: str, params: dict) -> websocket.WebSocket:
    query = urlencode(params)
    headers = [f"{name}: {value}" for name, value in signed_headers(query).items()]
    return websocket.create_connection(f"wss://public-api.charting.com/api/v1/trading{path}?{query}", header=headers)
```

## 1. Find your account

```python theme={null}
accounts = get("/account/list")["accounts"]
for account in accounts:
    print(account["accountId"], account["title"], account["connectorCodes"], account["status"])
```

```json theme={null}
{
  "accounts": [
    {
      "accountId": "4b8e2f6a-91c3-4d57-a0e8-3f1c7b9d2e45",
      "title": "Main Binance",
      "connectorCodes": ["binance_spot", "binance_usdm"],
      "exchanges": ["CXBNCE"],
      "status": "active",
      "isDeleted": false
    }
  ]
}
```

Pick an account with `status` `active` and one of its `connectorCodes`. The rest of this guide uses Binance USD-M futures:

```python theme={null}
ACCOUNT = {"accountId": "4b8e2f6a-91c3-4d57-a0e8-3f1c7b9d2e45", "connectorCode": "binance_usdm"}
INSTRUMENT = {"exchange": "CXBNCE", "symbol": "BTC/USDT"}
```

Then check what the connector accepts. The answer is the same for every user, so read it once and keep it:

```python theme={null}
capabilities = get("/connector/capabilities", {"connectorCode": "binance_usdm"})
print(capabilities["markets"]["derivatives"]["placeOrder"]["limit"]["timeInForce"])  # ['gtc', 'ioc', 'fok']
```

A field the connector doesn't list is rejected, so check here before using stop orders, trailing stops or take-profit/stop-loss.

## 2. Read the instrument's rules

The order data stream sends the instrument's price and quantity steps in its first frame. Read it and close the stream:

```python theme={null}
ws = stream("/order/data/stream", {**ACCOUNT, **INSTRUMENT})
snapshot = json.loads(ws.recv())
ws.close()

info = snapshot["instrumentInfo"]
print(info["price"]["step"], info["quantity"]["min"], info["quantity"]["step"], info["quantityUnit"])
```

Round every price to `price.step` and keep every quantity at or above `quantity.min`, in steps of `quantity.step`. `quantityUnit` says what the quantity counts: the base asset (BTC here), lots or the quote asset.

## 3. Open the events stream

Open it before placing the order, so you see every change. The first frame is a `snapshot` of the account: balances, working orders and open positions.

```python theme={null}
events = stream("/events/stream", {**ACCOUNT, "label": "quickstart"})
print(json.loads(events.recv())["type"])  # snapshot
```

`label` limits the order and execution frames to orders tagged `quickstart`, so your other orders stay out of this script's view.

## 4. Place a limit order

Place a buy far below the market. `Idempotency-Key` makes the request safe to retry: a repeat with the same key returns the first order instead of placing a second.

```python theme={null}
placed = post("/order/create", {
    **ACCOUNT,
    "instrument": INSTRUMENT,
    "label": "quickstart",
    "order": {"side": "buy", "quantity": "0.001", "limit": {"price": "30000", "timeInForce": "gtc"}},
}, idempotency_key=str(uuid.uuid4()))
print(placed)
```

```json theme={null}
{ "orderId": "1f2e3d4c-5b6a-4798-8a9b-0c1d2e3f4a5b", "requestId": "9a8b7c6d-5e4f-4321-8765-0fedcba98765" }
```

The answer is `202 Accepted`: the order was taken for processing, not yet placed. The events stream tells you what the exchange did:

```python theme={null}
while True:
    frame = json.loads(events.recv())
    if frame["type"] == "order" and frame["order"]["orderId"] == placed["orderId"]:
        print(frame["order"]["status"])  # placed
        break
    if frame["type"] == "commandError" and frame.get("orderId") == placed["orderId"]:
        print(frame["code"], frame["message"])
        break
```

An `order` frame with a working status, such as `placed`, means the order is on the book. A `commandError` frame means the request failed, and says why.

## 5. Move it

An amend sends the order's full desired state, not a change: repeat the quantity and the time in force, with the new price.

```python theme={null}
order_id = placed["orderId"]
post("/order/amend", {
    **ACCOUNT,
    "orderId": order_id,
    "order": {"quantity": "0.001", "limit": {"price": "29000", "timeInForce": "gtc"}},
})

while True:
    frame = json.loads(events.recv())
    if frame["type"] == "notification" and "order" in frame["notification"]:
        outcome = frame["notification"]["order"]
        if outcome.get("orderId") == order_id:
            print(outcome["kind"])  # updated, or replaced
            order_id = outcome.get("replacementOrderId", order_id)
            break
```

Some connectors can't amend in place: they cancel the order and place a new one, and the notification's `kind` is `replaced`. From then on the order lives under `replacementOrderId`. Unlike placing, an amend isn't safe to retry: check the events stream before sending it again.

## 6. Cancel it

```python theme={null}
post("/order/cancel", {**ACCOUNT, "orderId": order_id})
```

The events stream sends an `order` frame with `order.status` `canceled`. Close the stream when you're done:

```python theme={null}
events.close()
```

## Next steps

* [Events stream](https://takeprofit.com/docs/platform-api/trading/events-stream.md) and [Order data stream](https://takeprofit.com/docs/platform-api/trading/order-data-stream.md) list every frame.
* [Credits and limits](https://takeprofit.com/docs/platform-api/limits.md) covers what each request and stream costs.


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