API
View as Markdown

Python: idempotent client helper

import os
import uuid
import requests

API_KEY  = os.environ["TRADAVITY_API_KEY"]
BASE_URL = "https://app.tradavity.com/api/v1"
HEADERS  = {"Authorization": f"Bearer {API_KEY}"}

def write(method, path, body=None, idempotency_key=None, params=None, files=None):
    """POST / PATCH / PUT / DELETE with automatic Idempotency-Key."""
    h = dict(HEADERS)
    if idempotency_key is None:
        idempotency_key = str(uuid.uuid4())
    h["Idempotency-Key"] = idempotency_key
    if files is None and body is not None:
        h["Content-Type"] = "application/json"
    r = requests.request(
        method, f"{BASE_URL}{path}",
        headers=h, params=params or {},
        json=body if files is None else None,
        files=files, timeout=30,
    )
    resp = r.json() if r.headers.get("Content-Type", "").startswith("application/json") else None
    if not r.ok or (resp and not resp.get("ok")):
        err = resp["error"] if resp else {"code": "http_error", "message": r.text}
        raise RuntimeError(f"{r.status_code} {err.get('code')}: {err.get('message')}")
    return resp["data"] if resp else None

# Examples
trade = write("POST", "/trades", {
    "account_id": 192,
    "trade_date": "2026-05-10T14:32:00Z",
    "symbol": "MNQ", "direction": "long", "net_pnl": 50.0, "fees": 1.24,
    "trade_quality_grade": "A",
})
n = trade["trade"]["trade_number"]

write("PUT", f"/trades/{n}/tags", {"tag_ids": [19, 109]})

with open("chart.png", "rb") as f:
    write("POST", f"/trades/{n}/screenshots",
          files={"file": ("chart.png", f, "image/png"),
                 "label": (None, "Entry breakout")})

# Read it back to confirm it landed
r = requests.get(f"{BASE_URL}/trades/{n}", headers=HEADERS, timeout=30).json()
t = r["data"]["trade"]
print(f"Trade #{n}: {t['symbol']} {t['direction']} net_pnl={t['net_pnl']}")