Connect Trade API Cookbook

The Connect Trade API Cookbook provides ready-to-run code samples in Python for the most common integration tasks. All samples use the base URL https://api.connecttrade.com and authenticate via client-id, client-secret, user-id, and user-secret headers.

Setup

Configure credentials and create reusable HTTP helpers for GET, POST, PATCH, and DELETE requests.

import requests

BASE_URL = "https://api.connecttrade.com"

HEADERS = {
    "client-id": "YOUR_CLIENT_ID",
    "client-secret": "YOUR_CLIENT_SECRET",
    "user-id": "YOUR_USER_ID",
    "user-secret": "YOUR_USER_SECRET",
}

def get(path, params=None):
    r = requests.get(f"{BASE_URL}{path}", headers=HEADERS, params=params)
    r.raise_for_status()
    return r.json()

def post(path, body):
    r = requests.post(f"{BASE_URL}{path}", headers={**HEADERS, "Content-Type": "application/json"}, json=body)
    r.raise_for_status()
    return r.json()

def delete(path):
    r = requests.delete(f"{BASE_URL}{path}", headers=HEADERS)
    r.raise_for_status()
    return r.json()

def patch(path, body):
    r = requests.patch(f"{BASE_URL}{path}", headers={**HEADERS, "Content-Type": "application/json"}, json=body)
    r.raise_for_status()
    return r.json()

Get Account Balances

Retrieve cash, buying power, and margin information across all connected brokerage accounts using GET /balances.

balances = get("/balances")
for bal in balances:
    print(f"Account {bal['account_number']}: "
          f"cash={bal['cash']}, buying_power={bal['buying_power']}")

Get Positions

Retrieve current holdings including quantity, last price, and unrealized P&L for each position using GET /positions.

positions = get("/positions")
for pos in positions:
    print(f"{pos['symbol']}: {pos['quantity']} shares @ {pos['last_price']}, "
          f"unrealized P&L: {pos['unrealized_pl']}")

Get Open Orders

List all working orders filtered by status using GET /orders?status=open. Each order includes symbol, side, quantity, order type, and normalized status.

orders = get("/orders", params={"status": "open"})
for order in orders:
    print(f"{order['symbol']} {order['side']} {order['order_qty']} "
          f"({order['order_type']}) — {order['normalized_status']}")

Get Filled Orders

Retrieve recently filled orders sorted by execution time. Each order includes a fills array with per-execution quantity and price.

orders = get("/orders", params={"status": "filled", "sort": "last_exec_time:desc", "limit": "20"})
for order in orders:
    fills = order.get("fills", [])
    total_filled = sum(float(f["quantity"]) for f in fills)
    print(f"{order['symbol']} {order['side']} filled {total_filled} shares")

List Connected Accounts

List all brokerage accounts linked to the user, including institution name, account number, and account ID using GET /accounts.

accounts = get("/accounts")
for acct in accounts:
    print(f"{acct['institution_name']} — {acct['account_number']} (id: {acct['account_id']})")

Get Recent Transactions

Retrieve historical transaction activity filtered by date range using GET /transactions.

txns = get("/transactions", params={
    "start_date": "2025-06-01",
    "end_date": "2025-06-30"
})
for txn in txns:
    print(f"{txn['transaction_type']}: {txn.get('symbol', 'N/A')} — {txn.get('amount', 'N/A')}")

Place a Market Order

Submit a market order using POST /orders. Required fields include account_id, a unique cl_order_id, broker code, side, quantity, order type, time in force, instrument, and symbol.

import uuid

order = post("/orders", {
    "account_id": "YOUR_ACCOUNT_ID",
    "cl_order_id": str(uuid.uuid4())[:30],
    "broker": "ALPACA",
    "side": "BUY",
    "order_qty": "10",
    "order_type": "MKT",
    "order_tif": "DAY",
    "instrument": "STK",
    "symbol": "AAPL"
})
print(f"Order {order['order_id']} — status: {order['normalized_status']}")

Cancel All Open Orders

Fetch all open orders and cancel each one using DELETE /accounts/{account_id}/orders/{order_id}.

orders = get("/orders", params={"status": "open"})
for order in orders:
    result = delete(f"/accounts/{order['account_id']}/orders/{order['order_id']}")
    print(f"Cancelled {order['symbol']} {order['side']} — {result['message']}")

Sum Unrealized P&L

Calculate total unrealized profit and loss across all positions by summing the unrealized_pl field from GET /positions.

positions = get("/positions")
total_pl = sum(
    float(p["unrealized_pl"])
    for p in positions
    if p.get("unrealized_pl") is not None
)
print(f"Total unrealized P&L: ${total_pl:,.2f}")

Fills from Today

Retrieve all order fills from the current trading day by filtering orders by start time and flattening the fills array from each order.

from datetime import datetime, timezone

today = datetime.now(timezone.utc).strftime("%Y-%m-%dT00:00:00Z")
orders = get("/orders", params={
    "status": "all",
    "start_time": today,
    "sort": "last_exec_time:desc",
    "limit": "500"
})

fills = []
for order in orders:
    for fill in order.get("fills", []):
        fills.append({
            "symbol": order["symbol"],
            "side": order["side"],
            "price": fill["price"],
            "quantity": fill["quantity"],
            "time": fill["time"],
        })

print(f"Total fills today: {len(fills)}")
for f in fills[:10]:
    print(f"  {f['time']} {f['symbol']} {f['side']} {f['quantity']} @ {f['price']}")

Momentum Signal

Calculate a 20-day price momentum signal for a symbol using the Streaming Market Data API. Connect to wss://mdstream.connecttrade.com, authenticate with a short-lived access token, and subscribe to daily bars with historical backfill.

import asyncio, json, uuid
import websockets

async def spy_momentum():
    token_resp = get("/connections/YOUR_CONNECTION_ID/token")
    access_token = token_resp["access_token"]

    async with websockets.connect("wss://mdstream.connecttrade.com") as ws:
        await ws.send(json.dumps({
            "action": "authenticate",
            "access_token": access_token,
            "request_id": str(uuid.uuid4()),
            "version": "v1.0"
        }))
        auth = json.loads(await ws.recv())
        assert auth["type"] == "auth_success"

        await ws.send(json.dumps({
            "action": "subscribe",
            "channel": "bars",
            "symbol": "SPY",
            "interval": "1d",
            "session": "USEqCore",
            "request_id": str(uuid.uuid4()),
            "backfill_nbars": 20
        }))

        bars = []
        async for raw in ws:
            msg = json.loads(raw)
            if msg.get("type") == "subscribed":
                continue
            if "c" in msg:
                bars.append(float(msg["c"]))
                if len(bars) >= 20:
                    momentum = (bars[-1] / bars[0]) - 1
                    print(f"SPY 20-day momentum: {momentum:+.2%}")
                    return

asyncio.run(spy_momentum())

Calculate VWAP

Compute the volume-weighted average price (VWAP) for a symbol's fills from the current day. Fetches filled orders for a symbol and calculates the weighted average across all executions.

from datetime import datetime, timezone

orders = get("/orders", params={
    "status": "filled",
    "symbols": "AAPL",
    "start_time": datetime.now(timezone.utc).strftime("%Y-%m-%dT00:00:00Z"),
    "limit": "500"
})

total_qty = 0
total_cost = 0
for order in orders:
    for fill in order.get("fills", []):
        qty = float(fill["quantity"])
        px = float(fill["price"])
        total_qty += qty
        total_cost += qty * px

if total_qty > 0:
    vwap = total_cost / total_qty
    print(f"AAPL execution VWAP: ${vwap:.4f} ({total_qty:.0f} shares)")

Portfolio Concentration

Calculate each position's share of total portfolio market value, sorted from largest to smallest. Uses last_price and quantity from GET /positions.

positions = get("/positions")
values = []
for pos in positions:
    if pos.get("last_price") and pos.get("quantity"):
        mv = float(pos["last_price"]) * float(pos["quantity"])
        values.append((pos["symbol"], mv))

total = sum(v for _, v in values)
values.sort(key=lambda x: -x[1])
print("Portfolio concentration:")
for sym, mv in values:
    pct = mv / total * 100 if total else 0
    print(f"  {sym}: ${mv:,.0f} ({pct:.1f}%)")

Full API documentation | Interactive API reference (Redoc) | API documentation overview