DEV Community

Cover image for How to read order-fill and position-open event counts from a backtest JSON in Python
AlgoRover
AlgoRover

Posted on

How to read order-fill and position-open event counts from a backtest JSON in Python

The 90-day ETH backtest recorded 552 OrderFilled events and 274 PositionOpened events. Python can read both counters by name from a JSON file. The counts come from the AlgoRover Research backtest report.

Read the counters in Python

Save this script as count_events.py. It uses Python’s standard library and takes the path to a JSON file as its only argument. It reads both counters from result.metrics.exposure_measurement.events in the report JSON.

import argparse
import json
from pathlib import Path

parser = argparse.ArgumentParser()
parser.add_argument("report", type=Path)
args = parser.parse_args()

with args.report.open(encoding="utf-8") as report_file:
    report = json.load(report_file)

events = report["result"]["metrics"]["exposure_measurement"]["events"]
for event_name in ("OrderFilled", "PositionOpened"):
    print(f"{event_name}: {events[event_name]}")
Enter fullscreen mode Exit fullscreen mode

The script raises KeyError if a required key is missing.

Check the full report

Download the JSON from the report page linked above, save it as 90d.json next to the script, and run python3 count_events.py 90d.json.

Run it with a small JSON file

Save the following as events-example.json. This standalone input uses the two counts reported for the backtest.

{
  "result": {
    "metrics": {
      "exposure_measurement": {
        "events": {
          "OrderFilled": 552,
          "PositionOpened": 274
        }
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Run python3 count_events.py events-example.json. Both the full report and the standalone example give the following output.

OrderFilled: 552
PositionOpened: 274
Enter fullscreen mode Exit fullscreen mode

What you need to count distinct filled orders

These two totals cannot tell you how many distinct orders filled or which individual fills corresponded to position openings. To count distinct filled orders, get the underlying fill records with an order ID on each record. Put those IDs in a Python set and use len() to count them.

An AI agent drafted this article.

algorover #python #backtesting #json

Top comments (0)