Trading System Audit Trail: What to Log for Every Trade
An audit trail lets you reconstruct, for every order, why the system sent it, what it knew at that moment and what the broker answered. That takes one structured record per decision step: the signal with its input data and their timestamps, the active configuration, the risk decision with the limits it checked, your own order ID next to the broker’s IDs, every broker response, and every exchange rate used, with its source and time. This article lists the fields worth logging, recommends a format (JSON Lines with UTC timestamps), shows a tested Python logger that makes later edits detectable, and covers retention and analysis, for Python bots on Interactive Brokers as well as MQL5 Expert Advisors, as of November 2026.
What is an audit trail in a trading system?
Debug logs help a developer find a bug. An audit trail answers a different question, possibly months later and for someone who never saw the code: why did the system place this order, with this size, at this time, and what happened to it? To answer that, every step of the chain from market data to position has to leave a record that can be linked to the others:
- input data arrives,
- a rule produces a signal,
- risk checks allow or block it,
- an order is sent,
- the broker answers,
- fills arrive,
- the position is reconciled with the broker.
The OWASP Logging Cheat Sheet asks applications to record when, where, who and what for each event, and describes an interaction identifier that links all events belonging to one interaction. In a trading system that identifier is the signal ID, carried from the signal through risk check and order to the fills. Without it, a log is a pile of lines; with it, each order can be traced from the data that triggered it to the position it created.
What to log: the fields for each decision step
The table lists a minimum per step. Field names are examples; using the same names everywhere matters more than the names themselves.
| Step | Fields | Why |
|---|---|---|
| Startup | Code commit, configuration ID and full configuration, paper or live, account alias, software versions | Ties every later event to code and settings |
| Input data | Instrument, values used, timestamp at the source, time received | Shows what the system knew and how fresh it was |
| Signal | Signal ID, rule, inputs, result, blocking filter if any | Explains why a trade was or was not attempted |
| Risk decision | Each check with its limit and current value, allow or block, resulting size | Shows that the limits were applied before the order |
| Order | Own order ID, type, side, quantity, price, time in force, time sent | The intent, recorded before it leaves the system |
| Broker response | Broker IDs, status, return codes, message text, time received | What the broker actually did with the request |
| Fill | Execution ID, quantity, price, fees, broker timestamp | The basis for P&L and slippage analysis |
| Exchange rate | Pair, rate, bid, ask or mid, source, as-of time, time fetched | Makes conversions of sizes, limits and P&L reproducible |
| Reconciliation | Expected and broker position, open orders, result | Detects drift between system and account |
| Errors and alerts | Error, context, action taken, alert sent | Shows how failures were handled |
Two principles keep the trail honest. Record the order intent before sending it, so that a crash between sending and logging still leaves evidence. And log blocked signals as well as executed ones: a risk check that never blocks anything is either never needed or not running, and only a record of every check, allowed or blocked, can tell which. When a size or limit is converted into another currency, the record names the pair, the rate, its source and the time it was valid; which rate suits which purpose, and how old it may be, is covered in the guide on stale market data in trading bots. The configuration ID ties each record to the settings in force; how to compute it is part of the article on trading bot configuration.
Timestamps and clocks: event time, receive time and log time
One timestamp per record is not enough. The OWASP cheat sheet points out that the event timestamp may differ from the time of logging, and in trading the gap is information: a signal computed on a bar that closed two minutes earlier, or a quote that was already stale when the order went out, only becomes visible if both times are recorded.
- Source time: the timestamp that the data provider or broker attached, logged as received. In the TWS API, for example, the time of an execution is the execution’s server time.
- Receive time: when your process received the data or the response.
- Log time: when the record was written.
Write your own timestamps in UTC in RFC 3339 format, for example 2026-11-19T14:30:01.250Z, where the Z suffix denotes a UTC offset of 00:00. Convert broker timestamps to UTC in a separate field and keep the original, because a wrong time zone assumption is easy to correct later only if the raw value survives. OWASP also recommends synchronizing time across all servers and devices, so run time synchronization on every machine that writes records. For latencies, measure durations with a monotonic clock instead of subtracting wall-clock times.
Order IDs and broker responses: Interactive Brokers and MetaTrader 5
Create your own order ID before sending, derived from the signal ID, and log every ID the broker returns next to it. Broker IDs alone are not enough, and their meaning differs by platform.
Interactive Brokers (TWS API): according to the reference of the Execution object, orderId is the API client’s order ID and may not be unique to an account; permId is the TWS order identifier and can be 0 for trades originating outside IB; execId identifies an execution, each partial fill has its own, and a correction appears as an execId that differs from a previous one only in the digits after the final period. Log all three together with clientId, and treat a corrected execution as a new record that references the old one instead of overwriting it. The Execution object also carries orderRef, a user-customizable string that stays associated with the order for its lifetime, which makes it a convenient place for your own order ID.
MetaTrader 5 (MQL5): the result of a trade request arrives in MqlTradeResult: the retcode of the trade server, the deal ticket if a deal was performed, the order ticket if an order was placed, the volume and price confirmed by the broker, the current bid and ask, the broker’s comment, the request_id set by the terminal and retcode_external, whose use depends on the broker and the external trading system. The request_id associates a request with the results passed to OnTradeTransaction(). Log the full structure for every request, including rejected ones, together with the magic number and your own order ID.
On both platforms, log the broker’s message text verbatim next to the code. It costs a few bytes and saves guessing when a code alone is ambiguous.
Format and a tested logger: JSON Lines with a hash chain
The Python logging cookbook notes that most log messages are written for humans and shows how to emit JSON when a program needs to parse them. For an audit trail, go one step further and make every record a JSON object on a line of its own. JSON Lines requires UTF-8, one valid JSON value per line and \n as the line terminator, suggests the extension .jsonl and describes itself as a great format for log files. Give every record the same base fields: log time, event type, run ID, configuration ID, signal or order ID and, if the layout may change, a schema version.
OWASP recommends building in tamper detection, so that you know whether a record has been modified or deleted. A hash chain is a simple way to do that: each record contains the SHA-256 hash of the previous one. The logger below writes such a chain and verifies it. It was tested with Python 3.9 and 3.12, standard library only, against edited, deleted, reordered and malformed lines and against rotation into a new file; it writes a local file and connects to nothing.
# audit_log.py: append-only audit trail as JSON Lines. Each record carries the
# hash of the previous one, so edited, deleted or reordered lines are detectable.
# Standard library only; writes a local file, connects to nothing.
import hashlib
import json
import os
import sys
from datetime import datetime, timezone
START = "0" * 64
def utc_now():
return datetime.now(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
def digest(record):
body = json.dumps(record, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
return hashlib.sha256(body.encode("utf-8")).hexdigest()
class AuditLog:
def __init__(self, path, prev=START):
"""prev: last hash of the previous file, if logs are rotated."""
self.path, self.prev = path, prev
if os.path.exists(path):
with open(path, encoding="utf-8") as f:
for line in f:
if line.strip():
self.prev = json.loads(line)["hash"]
def write(self, event, **fields):
record = {"log_time": utc_now(), "event": event, **fields, "prev": self.prev}
record["hash"] = digest(record)
with open(self.path, "a", encoding="utf-8") as f:
f.write(json.dumps(record, sort_keys=True, ensure_ascii=False) + "\n")
f.flush()
os.fsync(f.fileno()) # on disk before the order goes out
self.prev = record["hash"]
return record["hash"]
def verify(path, prev=START):
"""Returns the numbers of the lines that break the chain (empty = intact)."""
broken = []
with open(path, encoding="utf-8") as f:
for n, line in enumerate(f, 1):
try:
record = json.loads(line)
claimed = record.pop("hash")
except (ValueError, KeyError, AttributeError, TypeError):
broken.append(n)
continue
if record.get("prev") != prev or digest(record) != claimed:
broken.append(n)
prev = claimed
return broken
if __name__ == "__main__":
broken = verify(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else START)
print("chain intact" if not broken else f"chain broken at lines {broken}")
sys.exit(1 if broken else 0)Typical use, with invented values:
# Typical example with invented values: one signal, from input data to fill.
from audit_log import AuditLog
log = AuditLog("audit.jsonl")
ctx = {"run_id": "2026-11-19-a", "config_id": "e826f20fdc91", "commit": "4f2c9e1"}
log.write("signal", **ctx, signal_id="S-1041", symbol="XYZ", side="buy", rule="entry_1",
inputs={"close": 101.25, "level": 101.10}, data_time="2026-11-19T14:30:00Z")
log.write("risk_check", **ctx, signal_id="S-1041", decision="allow", qty=1,
limits={"max_position": [0, 2], "daily_loss_eur": [-180.0, -500.0]}, # [value, limit]
fx={"pair": "EURUSD", "rate": 1.0842, "side": "mid", "source": "broker",
"as_of": "2026-11-19T14:30:01.250Z"})
log.write("order_submit", **ctx, signal_id="S-1041", client_order_id="S-1041-1",
order_type="LMT", limit=101.25, qty=1, tif="DAY")
log.write("broker_response", **ctx, client_order_id="S-1041-1", order_id=58,
perm_id=1734567890, status="Submitted")
log.write("fill", **ctx, client_order_id="S-1041-1", exec_id="0001f2a3.01", qty=1, price=101.25)python3 audit_log.py audit.jsonl reports whether the chain is intact and exits with code 1 if it is not. Two limits are worth knowing: the chain cannot detect that the newest lines were cut off or that the whole file was rewritten with fresh hashes. Copy the latest hash regularly to a place the trading system cannot write to, for example a separate server. The fsync call asks the operating system to write each record to disk before the order goes out; for high-volume debug logging, the cookbook’s advice to attach only a QueueHandler to loggers used in performance-critical threads keeps slow handlers out of the trading path.
Retention, protection and analysis
How long to keep the records is not a technical question. Regulated firms have record-keeping duties set by their regulator, private traders may be subject to tax-related retention periods, and contracts can add their own. Ask your compliance officer or tax adviser and write the answer down. The OWASP principle applies either way: log data and its copies must not be destroyed before the required retention period ends, and must not be kept beyond it.
- Protection: copy records to read-only storage as soon as possible, as OWASP suggests, and keep the latest chain hashes elsewhere.
- Exclusions: session identifiers, access tokens, passwords and encryption keys do not belong in the log; OWASP recommends removing, masking, hashing or encrypting such values. Log an account alias instead of the account number.
- Rotation: one file per day or per run keeps files manageable; start each new file with the last hash of the previous one, as the
prevargument of the logger above allows, so the chain continues across files.
For analysis, JSON Lines needs no database import. DuckDB, for example, reads newline-delimited JSON with read_json and can read many files at once through a glob pattern. Useful standing queries: orders without a final status, signals blocked per risk check, slippage between signal price and fill price, latency between signal and broker acknowledgement, and differences between your fills and the broker’s statement.
An audit trail makes errors visible; it does not prevent them. Logs that nobody reads catch nothing, clocks can drift despite synchronization, and a trail is only as complete as the code paths that write to it. Trading involves a risk of loss up to total loss, whatever the quality of the logs.
What to do next
- Draw the chain from input data to position for your system and give each step an event type.
- Introduce a signal ID and your own order ID, and log every broker ID next to them.
- Add source time, receive time and log time in UTC to every record, including the exchange rates used.
- Log every risk check with its limit and value, including the blocked signals.
- Switch to JSON Lines, add the configuration ID to every record and protect the file with a hash chain and an external copy of the latest hash.
- Agree on a retention period and set up read-only archiving.
- Write the first standing queries and run them after every trading day.
To have an existing system’s logging, order handling and reconciliation checked, see the trading system code review.
Frequently asked questions
What should a trading bot log?
At minimum: startup details with code version and configuration, the input data behind each signal with its timestamps, the signal itself, every risk check with limit and value, each order with your own ID, every broker response and fill with the broker’s IDs, the exchange rates used with source and time, and the result of each position reconciliation. Errors and alerts belong in the same trail.
What is the best log format for a trading system?
For an audit trail, a structured format that programs can parse: one JSON object per line (JSON Lines) in UTF-8, with timestamps in UTC in RFC 3339 format and the same base fields in every record. It stays readable for people, appends cheaply and can be queried directly, for example with DuckDB, without importing it into a database first.
How long should trading logs be kept?
That depends on your obligations, not on technology. Regulated firms follow the record-keeping rules of their regulator, private traders may be subject to tax-related retention periods, and contracts can add requirements. Clarify the period with your compliance officer or tax adviser, keep the records read-only until it ends and do not keep them beyond it, as the OWASP Logging Cheat Sheet recommends.
How can I tell whether a log file was changed afterwards?
Chain the records: each line stores the SHA-256 hash of the previous line, so an edited, deleted or reordered line breaks the chain when it is verified. A chain alone cannot detect that the newest lines were cut off or that the whole file was rewritten, so copy the latest hash regularly to a separate place that the trading system cannot write to.
Sources and status
- Logging Cheat Sheet — OWASP Cheat Sheet Series (retrieved November 19, 2026)
- Logging Cookbook (implementing structured logging; dealing with handlers that block) — Python documentation (Python Software Foundation) (retrieved November 19, 2026)
- RFC 3339: Date and Time on the Internet: Timestamps — IETF (RFC Editor) (retrieved November 19, 2026)
- JSON Lines — jsonlines.org (retrieved November 19, 2026)
- TWS API reference: Execution (orderId, execId, time, permId, clientId, orderRef) — Interactive Brokers (retrieved November 19, 2026)
- The Structure of a Trade Request Result (MqlTradeResult) — MQL5 Reference (MetaQuotes) (retrieved November 19, 2026)
- Loading JSON, DuckDB 2.0 documentation (read_json, newline-delimited format, multiple files) — DuckDB documentation (retrieved November 19, 2026)
As of November 2026. Third-party rules, prices and APIs may have changed since; the providers' current documentation and the official texts are authoritative.
This article is also available in German: Logging und Audit-Trail: Handelsentscheidungen nachvollziehen.
Want to know whether your trading system logs enough to explain every trade? Get in touch — a free intro call clarifies what a review of logging, order handling and reconciliation covers. More: Trading system code review and audit.