DEV Community

James Wilson
James Wilson

Posted on

Building an Automated Trading Journal With Python, SQLite, and QATS API

In my previous article, I built a lightweight trading monitor that retrieves account data and sends notifications to Telegram.

This time, I want to explore something equally useful: automatically collecting trading history and calculating performance statistics.

A trading journal becomes much more interesting when you don't have to enter every trade manually.

I'll use Python, SQLite, and the QATS Trader API to build a small execution journal.

1. Retrieving execution history

One useful feature of QATS is that its API exposes individual executions, including prices, quantities, commissions, and realized P&L.

The endpoint is:

GET /trading/executions
Enter fullscreen mode Exit fullscreen mode

We'll use the QATS Sandbox with a read-only API key.

Install the dependency:

pip install requests
Enter fullscreen mode Exit fullscreen mode

Create a small API client that handles cursor pagination:

import os
import requests

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

session = requests.Session()
session.headers["Authorization"] = (
    f"Bearer {os.environ['QATS_TOKEN']}"
)


def get_executions():
    params = {"pageSize": 100}

    while True:
        response = session.get(
            BASE + "/trading/executions",
            params=params,
            timeout=15
        )
        response.raise_for_status()
        data = response.json()

        yield from data["executions"]

        cursor = data["pagination"]["nextCursor"]

        if not cursor:
            break

        if cursor == params.get("cursor"):
            raise RuntimeError("Pagination stopped progressing")

        params["cursor"] = cursor
Enter fullscreen mode Exit fullscreen mode

Cursor pagination is useful because multiple executions can share the same timestamp. Using timestamps alone as unique identifiers could cause missing records.

2. Storing executions in SQLite

SQLite is more than enough for a small personal trading journal.

Each execution has its own identifier, which makes it possible to synchronize trading history without creating duplicate records.

import sqlite3

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

db.execute("""
    CREATE TABLE IF NOT EXISTS executions (
        id TEXT PRIMARY KEY,
        symbol TEXT NOT NULL,
        executed_at TEXT NOT NULL,
        fees TEXT NOT NULL,
        realized_pnl TEXT NOT NULL,
        trade_net_pnl TEXT
    )
""")
Enter fullscreen mode Exit fullscreen mode

Now we can insert or update executions:

def sync_journal():
    for item in get_executions():
        trade_pnl = item.get("tradeNetPnl")

        with db:
            db.execute("""
                INSERT INTO executions
                VALUES (?, ?, ?, ?, ?, ?)
                ON CONFLICT(id) DO UPDATE SET
                    fees = excluded.fees,
                    realized_pnl = excluded.realized_pnl,
                    trade_net_pnl = excluded.trade_net_pnl
            """, (
                item["id"],
                item["symbol"],
                item["executedAt"],
                str(item["fees"]),
                str(item["realizedPnl"]),
                None if trade_pnl is None else str(trade_pnl)
            ))
Enter fullscreen mode Exit fullscreen mode

Use a separate database for each trading account. Run one synchronization process at a time.

I also prefer retaining decimal values as strings in SQLite and converting them to Decimal in Python rather than relying on floating-point arithmetic for financial calculations.

3. Calculating performance statistics

There is an interesting detail in the QATS API.

The realizedPnl field already includes the execution fee. Subtracting commissions from it again would produce an incorrect result.

The tradeNetPnl field represents the allocated result of closed exposure, including the relevant opening and closing fees.

Let's calculate some basic statistics:

from decimal import Decimal

rows = db.execute("""
    SELECT fees, realized_pnl, trade_net_pnl
    FROM executions
""").fetchall()

fees = sum((Decimal(r[0]) for r in rows), Decimal(0))
net_pnl = sum((Decimal(r[1]) for r in rows), Decimal(0))

closed = [
    Decimal(r[2])
    for r in rows
    if r[2] is not None
]

wins = [p for p in closed if p > 0]
losses = [p for p in closed if p < 0]

win_rate = len(wins) / len(closed) * 100 if closed else 0

gross_loss = abs(sum(losses))
profit_factor = (
    sum(wins) / gross_loss
    if gross_loss else None
)

print("Execution P&L:", net_pnl)
print("Fees:", fees)
print(f"Closing-fill win rate: {win_rate:.2f}%")
print("Closing-fill profit factor:", profit_factor)
Enter fullscreen mode Exit fullscreen mode

These are execution-level statistics. Partial position closures can produce multiple records, so calculating a conventional trade-level win rate requires additional grouping.

Funding payments and other account adjustments may also need to be accounted for separately.

4. Sending a daily report to Telegram

The Telegram integration from my previous article can be reused here.

def send_report(message):
    token = os.environ["TELEGRAM_TOKEN"]

    response = requests.post(
        f"https://api.telegram.org/bot{token}/sendMessage",
        json={
            "chat_id": os.environ["TELEGRAM_CHAT_ID"],
            "text": message
        },
        timeout=15
    )
    response.raise_for_status()
Enter fullscreen mode Exit fullscreen mode

For a daily report, filter the SQLite records by the reporting period before calculating the statistics.

You can schedule synchronization and reporting with cron or a small background service. Make sure the first synchronization finishes before generating the report.

What makes this integration interesting

What I appreciate about the QATS Prop ecosystem is the ability to access trading data independently of the platform's interface.

QATS already provides a built-in Trade Journal, but having programmatic access to execution history makes custom analytics possible.

A personal journal could eventually include performance by trading session, average execution costs, strategy-specific statistics, or comparisons between instruments.

The next step is replacing periodic synchronization with real-time account events.

That's where Server-Sent Events become useful.

Top comments (0)