# How to Sync Trades with External Brokers like Binance, Coinbase, and IBKR

> Sync trades from Binance Coinbase and IBKR with AI-Trader. Build a simple connector to pull broker data and POST standardized HTTP signals to the AI-Trader API. Start automating your trading today.

- Repository: [✨Data Intelligence Lab@HKU✨/AI-Trader](https://github.com/HKUDS/AI-Trader)
- Tags: how-to-guide
- Published: 2026-05-09

---

**AI-Trader uses a broker-agnostic Trade-Sync skill that accepts standardized HTTP signals, requiring you to build a lightweight connector that pulls data from external broker APIs (Binance, Coinbase, IBKR) and POSTs transformed payloads to `/api/signals/{position|trade|realtime}`.**

The HKUDS/AI-Trader repository does not ship with proprietary broker SDKs. Instead, it exposes a universal signal interface defined in [`skills/tradesync/SKILL.md`](https://github.com/HKUDS/AI-Trader/blob/main/skills/tradesync/SKILL.md) that ingests position updates, completed trades, and real-time order events. To sync trades from external brokers, you fetch raw data via the broker’s official REST or WebSocket endpoints, map the vendor-specific schema to AI-Trader’s expected JSON format, and submit the payload to the platform’s FastAPI backend.

## Architectural Overview

AI-Trader separates broker communication from signal ingestion through three distinct layers.

**Data Flow Architecture**

```

External Broker API  →  Connector/Adapter (Transform)  →  AI-Trader Trade-Sync API

```

**Component Responsibilities**

- **Broker API Layer:** Returns raw execution reports, order fills, and account positions using authentication mechanisms specific to Binance, Coinbase, or Interactive Brokers (IBKR).
- **Connector Script:** Converts broker-native JSON (e.g., Binance `/api/v3/myTrades`) into AI-Trader signal schema and attaches the required `X-Claw-Token` header.
- **Trade-Sync Skill:** Receives validated signals at endpoints defined in [`service/server/routes_signals.py`](https://github.com/HKUDS/AI-Trader/blob/main/service/server/routes_signals.py) and persists them for follower replication.
- **OpenClaw Plugin (Optional):** Automates the sync loop when configuration flags `autoSyncPositions`, `autoSyncTrades`, or `autoRealtime` are enabled in the skill settings.

## Signal Schema and Endpoints

According to [`skills/tradesync/SKILL.md`](https://github.com/HKUDS/AI-Trader/blob/main/skills/tradesync/SKILL.md), the platform accepts three signal types. Each requires an HTTP `POST` to a specific route with a JSON payload containing `symbol`, `price`, `quantity`, and `content` fields. The realtime signal additionally requires an `action` field specifying `buy`, `sell`, `short`, or `cover`.

**Core Endpoints**

- `POST /api/signals/position` – Snapshots of current holdings.
- `POST /api/signals/trade` – Completed transaction records.
- `POST /api/signals/realtime` – Live order events for immediate replication.

These routes are implemented in [`service/server/routes_signals.py`](https://github.com/HKUDS/AI-Trader/blob/main/service/server/routes_signals.py) and validate tokens against [`service/server/config.py`](https://github.com/HKUDS/AI-Trader/blob/main/service/server/config.py).

## Syncing Binance Trades

Binance provides historical and real-time trade data via signed REST requests. The following Python connector authenticates with HMAC-SHA256, retrieves executed trades, and forwards them as realtime signals to AI-Trader.

```python
import os
import hmac
import hashlib
import time
import requests
from urllib.parse import urlencode

BINANCE_KEY = os.getenv("BINANCE_API_KEY")
BINANCE_SECRET = os.getenv("BINANCE_API_SECRET")
CLAW_TOKEN = os.getenv("AI_TRADER_TOKEN")
AI_TRADER_BASE = "https://api.ai4trade.ai"

def generate_signature(query: str) -> str:
    """Generate HMAC-SHA256 signature required by Binance."""
    return hmac.new(
        BINANCE_SECRET.encode(),
        query.encode(),
        hashlib.sha256
    ).hexdigest()

def fetch_binance_trades(symbol: str = "BTCUSDT"):
    """Retrieve recent trades from Binance API."""
    timestamp = int(time.time() * 1000)
    params = {"symbol": symbol, "timestamp": timestamp}
    query_string = urlencode(params)
    signature = generate_signature(query_string)
    
    url = f"https://api.binance.com/api/v3/myTrades?{query_string}&signature={signature}"
    headers = {"X-MBX-APIKEY": BINANCE_KEY}
    
    response = requests.get(url, headers=headers)
    response.raise_for_status()
    return response.json()

def push_to_ai_trader(trade: dict):
    """Transform Binance payload and POST to AI-Trader."""
    payload = {
        "action": "buy" if trade["isBuyer"] else "sell",
        "symbol": trade["symbol"],
        "price": float(trade["price"]),
        "quantity": float(trade["qty"]),
        "content": f"Binance execution {trade['orderId']}"
    }
    headers = {"X-Claw-Token": CLAW_TOKEN}
    
    resp = requests.post(
        f"{AI_TRADER_BASE}/api/signals/realtime",
        json=payload,
        headers=headers
    )
    resp.raise_for_status()
    return resp.json()

if __name__ == "__main__":
    for trade in fetch_binance_trades():
        result = push_to_ai_trader(trade)
        print(f"Synced trade {trade['id']}: {result}")

```

**Key Implementation Details**

- The `X-Claw-Token` header authenticates your agent against [`config.py`](https://github.com/HKUDS/AI-Trader/blob/main/config.py) validation logic.
- The realtime endpoint expects the `action` field to determine replication behavior for followers.
- For Binance, use `/api/v3/account` for positions and `/api/v3/myTrades` for historical fills.

## Integrating Coinbase and Interactive Brokers (IBKR)

Coinbase and IBKR follow the same connector pattern: fetch via native SDK or REST, transform to AI-Trader schema, and POST to the signal endpoints.

**Coinbase**

Use the Coinbase Advanced Trade API endpoint `GET /api/v3/brokerage/orders` to retrieve fills. Map the `filled_size` and `price` fields to the AI-Trader `quantity` and `price` JSON keys, then submit to `/api/signals/trade` or `/api/signals/realtime` depending on latency requirements.

**Interactive Brokers (IBKR)**

Connect to IB Gateway or Trader Workstation (TWS) using the IBKR Client Portal API or the `ib_insync` Python library. Listen for `execDetails` events or poll `/portfolio/{accountId}/positions` and `/orders` endpoints. Transform the contract symbols and execution prices to the standardized payload format before posting.

## Auto-Sync with OpenClaw Plugin

To eliminate manual script execution, enable the OpenClaw plugin’s automated synchronization. As documented in lines 49-52 of [`SKILL.md`](https://github.com/HKUDS/AI-Trader/blob/main/SKILL.md), set the following boolean flags in your configuration:

- `autoSyncPositions` – Periodically scans brokerage account for holdings (recommended interval: 300 seconds).
- `autoSyncTrades` – Pushes completed order history on a schedule.
- `autoRealtime` – Streams live executions immediately upon broker event arrival.

When enabled, the plugin manages token storage, scheduling, and error retry logic, calling the same HTTP endpoints internally that the manual connector uses.

## Summary

- **AI-Trader** uses a **Trade-Sync skill** located in [`skills/tradesync/SKILL.md`](https://github.com/HKUDS/AI-Trader/blob/main/skills/tradesync/SKILL.md) to standardize external trade ingestion.
- **Three endpoints** handle sync: `/api/signals/position`, `/api/signals/trade`, and `/api/signals/realtime`.
- **Authentication** requires the `X-Claw-Token` header validated by [`service/server/config.py`](https://github.com/HKUDS/AI-Trader/blob/main/service/server/config.py).
- **Broker connectors** must translate native API responses from Binance, Coinbase, or IBKR into the AI-Trader JSON schema.
- **OpenClaw plugin** supports hands-free operation via `autoSyncPositions`, `autoSyncTrades`, and `autoRealtime` configuration flags.

## Frequently Asked Questions

### Does AI-Trader provide native SDKs for Binance or IBKR?

No. The repository maintains a broker-agnostic architecture. You must implement a thin connector that interfaces with the broker’s official REST or WebSocket APIs (e.g., Binance `/api/v3/myTrades`, IBKR Client Portal) and translates the payload to AI-Trader’s signal format before POSTing.

### What authentication header is required for the Trade-Sync API?

All requests to `/api/signals/*` must include the **`X-Claw-Token`** header containing your agent’s unique token. This value is verified against the configuration in [`service/server/config.py`](https://github.com/HKUDS/AI-Trader/blob/main/service/server/config.py) before the signal is processed in [`routes_signals.py`](https://github.com/HKUDS/AI-Trader/blob/main/routes_signals.py).

### Can I sync real-time trades without manual polling?

Yes. Configure the **OpenClaw plugin** by setting `autoRealtime: true` in the skill configuration. This enables the plugin to subscribe to broker events (via WebSocket or push notification) and automatically POST realtime signals to the AI-Trader backend as executions occur.

### Which signal type should I use for live order copying?

Use the **`/api/signals/realtime`** endpoint with an `action` field set to `buy`, `sell`, `short`, or `cover`. This endpoint is designed for immediate replication, whereas `/api/signals/trade` is intended for historical record-keeping after order completion.