DEV Community

James Wilson
James Wilson

Posted on

Building an Event-Driven Trading Application With Python and QATS API

In my previous articles, I explored how to monitor trading positions, send Telegram notifications, and store execution history in SQLite.

Those examples relied on polling the REST API.

Polling is easy to implement, but a position can be opened and closed between two requests without the application noticing.

For this project, I want to explore a different approach using Server-Sent Events (SSE), available through the QATS Trader API.

1. Moving from polling to events

SSE maintains an HTTP connection through which the server sends updates to the client.

Unlike WebSockets, communication is unidirectional. For a trading application that submits commands through REST and receives account updates separately, this is a useful architecture.

QATS provides four private trading event types:

  • order.updated
  • position.updated
  • execution.created
  • execution.updated

Our application will receive these events, store them in SQLite, and maintain a persistent checkpoint for reconnecting.

workflow diagram

2. Connecting to the event stream

We'll use httpx and httpx-sse to avoid writing our own SSE parser.

pip install httpx httpx-sse
Enter fullscreen mode Exit fullscreen mode

Create a read-only API key in the QATS Sandbox.

import os
import httpx
from httpx_sse import connect_sse

BASE = "https://prop.qats.us/api/sandbox/v1"

headers = {
    "Authorization": f"Bearer {os.environ['QATS_TOKEN']}"
}

client = httpx.Client(
    headers=headers,
    timeout=httpx.Timeout(60.0, connect=10.0)
)

account = client.get(BASE + "/trading/account")
account.raise_for_status()

account_id = account.json()["account"]["id"]
Enter fullscreen mode Exit fullscreen mode

The private event stream is available at:

GET /trading/events/stream
Enter fullscreen mode Exit fullscreen mode

Unlike browser-based EventSource, this Python client allows us to include the Bearer authorization header.

3. Persisting events in SQLite

A reliable event consumer needs to remember what it has already processed.

QATS identifies private events using the format accountId:sequence.

We can use that identifier as a primary key.

import sqlite3
import json

db = sqlite3.connect("events.sqlite")

db.execute("""
    CREATE TABLE IF NOT EXISTS events (
        id TEXT PRIMARY KEY,
        account_id TEXT NOT NULL,
        sequence INTEGER NOT NULL,
        event_type TEXT NOT NULL,
        payload TEXT NOT NULL
    )
""")
db.commit()


def last_sequence():
    row = db.execute("""
        SELECT COALESCE(MAX(sequence), 0)
        FROM events
        WHERE account_id = ?
    """, (account_id,)).fetchone()

    return row[0]


def save_event(event):
    if event["accountId"] != account_id:
        raise RuntimeError("Unexpected account")

    sequence = event["sequence"]
    previous = last_sequence()

    if sequence <= previous:
        return

    if sequence != previous + 1:
        raise RuntimeError("Event sequence gap")

    with db:
        db.execute("""
            INSERT INTO events VALUES (?, ?, ?, ?, ?)
        """, (
            event["id"],
            account_id,
            sequence,
            event["event"],
            json.dumps(event)
        ))

    print("Received:", event["event"], event["id"])
Enter fullscreen mode Exit fullscreen mode

The database acts as both an event log and a checkpoint.

After a restart, the application can continue from the last committed sequence rather than starting from scratch.

This example assumes a single event consumer per database and account.

4. Handling reconnects

Network connections will eventually fail. The interesting part is how the application recovers afterward.

The QATS API supports the Last-Event-ID header for recovering missed events.

import time

delay = 2

while True:
    checkpoint = last_sequence()

    try:
        with connect_sse(
            client,
            "GET",
            BASE + "/trading/events/stream",
            headers={
                "Last-Event-ID": f"{account_id}:{checkpoint}"
            }
        ) as stream:

            stream.response.raise_for_status()

            for event in stream.iter_sse():
                if event.event == "status":
                    continue

                save_event(event.json())
                delay = 2

    except httpx.HTTPStatusError as error:
        print("HTTP status:", error.response.status_code)
        break

    except httpx.RequestError:
        print("Connection interrupted")

    time.sleep(delay)
    delay = min(delay * 2, 60)
Enter fullscreen mode Exit fullscreen mode

The stream may also deliver status frames and heartbeat comments. Those aren't trading records.

If a sequence gap is detected, stop processing and investigate the missing events. QATS also provides a REST recovery endpoint:

GET /trading/events
Enter fullscreen mode Exit fullscreen mode

The REST endpoint and SSE stream expose the same committed event history.

This is one of the aspects of the QATS API I find particularly interesting. Reconnection is part of the documented API contract rather than something every developer needs to invent independently.

5. Building something useful on top of events

Once events are stored locally, several applications become possible:

  • An automatically updated trading journal.
  • Position change notifications.
  • Order execution analytics.
  • Synchronization between manual trading and automated scripts.

For external notifications, I'd add a persistent outbox table. Sending a Telegram message directly inside an event handler can create duplicate or missed notifications if the application crashes at the wrong moment.

I'd also periodically reconcile local data against the REST API. An event log alone shouldn't be treated as a guaranteed complete history of every account operation before the stream became available.

What's next?

What I like about working with the QATS trading ecosystem is that it provides opportunities to explore real software engineering problems through trading integrations.

The next step in this series is building a risk management module that checks account restrictions and calculates position sizes before sending trading commands.

Top comments (0)