Matana Labs engine vs an independent reference implementation
We wrote a second backtester from scratch, in plain Python and sharing no code with the Matana Labs engine, and ran three strategies on both with the same rules and costs: 2,765 trades on 457 sessions of QQQ second-level data. Every trade matched to the second; the totals agree to the cent.
Summary
| Metric | SMA cross with stop and target: engine | reference | Donchian breakout: engine | reference | RSI(2) mean reversion: engine | reference |
|---|---|---|---|---|---|---|
| Trades | 689 | 689 | 380 | 380 | 1,696 | 1,696 |
| Net profit | −$9,822.71 | −$9,822.71 | −$506.67 | −$506.67 | −$17,259.64 | −$17,259.64 |
| Max drawdown | $11,621 (11.57%) | $11,621 (11.57%) | $7,237 (7.16%) | $7,237 (7.16%) | $20,134 (19.99%) | $20,134 (19.99%) |
| Win rate | 38.17% | 38.17% | 46.84% | 46.84% | 59.26% | 59.26% |
| Profit factor | 0.844 | 0.844 | 0.991 | 0.991 | 0.825 | 0.825 |
| Average trade | −$14.26 | −$14.26 | −$1.33 | −$1.33 | −$10.18 | −$10.18 |
| Strategy | Matched trades | Only in engine | Only in reference | Largest price difference | Largest P&L difference |
|---|---|---|---|---|---|
| SMA cross with stop and target | 689 of 689 (100%) | 0 | 0 | below $0.000000001 | below $0.000001 |
| Donchian breakout | 380 of 380 (100%) | 0 | 0 | below $0.000000001 | below $0.000001 |
| RSI(2) mean reversion | 1,696 of 1,696 (100%) | 0 | 0 | below $0.000000001 | below $0.000001 |
The strategies are test cases, not recommendations: all three lose money on this period after costs, which is common for simple rules and makes no difference to the comparison. Data: QQQ, January 2, 2025 to October 28, 2026, regular sessions; validated November 24, 2026.
Where the numbers differ, and why
Trades, entry and exit seconds, prices, net profit and drawdown are identical. The only differences are in the last digits of sums: the profit factor and average trade differ after about the twelfth significant digit, because the two programs add the same numbers in a different order (the reference uses exact summation). No trade differs.
Does the comparison notice a real difference? We changed one rule in the reference: stops filled at the stop level instead of the second’s price. In “SMA cross with stop and target”, 98 trades then differ and net profit moves by $436.51; in “RSI(2) mean reversion”, 56 trades then differ and net profit moves by $248.72. The comparison is sensitive to a single fill rule.
The results, trade by trade
The rules both implementations follow
- QQQ second-level data, January 2, 2025 to October 28, 2026, regular session 09:30 to 16:00 New York time; seconds without trades carry the price and nothing fills in them.
- $100,000 account, no leverage, 100 shares per trade, long only, one position at a time.
- Commission $0.0035 per share, at least $0.35 and at most 1% of the trade value; slippage 0.01% against every fill; no volume limits, so the test is about prices and timing, not liquidity.
- Intraday: any position is sold 5 minutes before the session’s last second; no new entries after that.
- Rules fire when their condition turns true; market orders fill at the price of that second; stops and targets are checked from the next second at each second’s price.
SMA cross with stop and target
strategy "Validation 1: SMA cross with stop and target"
capital 100000
leverage 1
session intraday
close_before 5m
execution
volumeCap off
slippagePct 0.01
commission.perShare 0.0035
commission.min 0.35
rule "Entry"
when
SMA(10)[5m] crosses_above SMA(30)[5m]
and pos.qty == 0
do
buy 100 shares
stop 0.5%
target 1%
rule "Exit on cross down"
when
SMA(10)[5m] crosses_below SMA(30)[5m]
and pos.qty > 0
do
sellDonchian breakout
strategy "Validation 2: Donchian breakout"
capital 100000
leverage 1
session intraday
close_before 5m
execution
volumeCap off
slippagePct 0.01
commission.perShare 0.0035
commission.min 0.35
rule "Breakout"
when
price > DC(20).u[15m]
and pos.qty == 0
do
buy 100 shares
rule "Exit below the 10-bar low"
when
price < DC(10).l[15m]
and pos.qty > 0
do
sellRSI(2) mean reversion
strategy "Validation 3: RSI(2) mean reversion"
capital 100000
leverage 1
session intraday
close_before 5m
execution
volumeCap off
slippagePct 0.01
commission.perShare 0.0035
commission.min 0.35
rule "Oversold"
when
RSI(2)[5m] < 10
and pos.qty == 0
do
buy 100 shares
stop 1%
rule "Exit on bounce"
when
RSI(2)[5m] > 70
and pos.qty > 0
do
sellThis is the strategy language of Strategy Lab’s Code view; the engine received exactly what the app’s parser makes of this text.
The reference implementation
About 300 lines of Python 3, standard library only. It reads the data file on its own, builds the bars, computes SMA, RSI and Donchian channels in the textbook way, walks every second and applies the rules above. It shares no code with the engine (C++).
Show the full source (ref_backtest.py)
#!/usr/bin/env python3
"""Independent reference backtester for the Matana Labs engine validation.
This file is deliberately separate from the Matana Labs engine: it shares no code with it. It reads the
second-level tape file directly (its documented layout), builds bars, computes its own indicators and walks
every second with the written rules below. Plain Python 3, standard library only, about 300 lines.
Run: python3 ref_backtest.py <tape.mt> [strategy-id …] → one JSON object per strategy on stdout
Rules shared by all three strategies (the same rules the Matana Labs strategies state in their code):
• data: one price and one volume per second, regular session (09:30–16:00 New York); a second without
trades carries the previous price and is flagged; no trade can fill in such a second.
• bars: 5- or 15-minute bars from the session open, built from the second prices; a bar is "closed"
from the first second after its last second. Indicators continue across days.
• signal: conditions read only closed bars (and, where written, the price of the current second).
A rule fires when its whole condition turns from false to true ("edge"); every morning
starts with all rules "false".
• order: a market order fills at the price of the second the rule fired in; if that second had no
trades, at the next second with trades.
• exits: a stop or target is checked from the second after the entry, at each second's price,
before the rules of that second; it fills at that second's price.
• day end: 300 seconds before the session's last second the position is sold at that second's price
and no rule runs until the next session.
• costs: 100 shares per trade; commission $0.0035 per share, at least $0.35 and at most 1 % of the
trade value; slippage 0.01 % against the trade on every fill; no volume limits.
• account: $100,000, no leverage. Equity = cash + position × price, measured every second.
"""
import json
import math
import struct
import sys
import zlib
# ── costs and session ───────────────────────────────────────────────────────────────────────────────
CAPITAL = 100000.0
QTY = 100
COMM_PER_SHARE, COMM_MIN, COMM_CAP_PCT = 0.0035, 0.35, 1.0
SLIPPAGE_PCT = 0.01
EOD_SEC = 300
SESSION_OPEN = 34200 # 09:30 New York, seconds from midnight
STOP_FILL = "second" # "second": a stop fills at the price of the second; "level": at the stop level (the
# optimistic bar-backtest habit; used only to show how much that choice changes)
FLAG_FILLED = 2 # tape flag: no trades in this second, price carried forward
# ── tape reader (layout: 4096-byte header, 48-byte day records, per-day packed blocks) ─────────────
def _varints(buf, pos):
out = []
n = len(buf)
while pos < n:
r = sh = 0
while True:
b = buf[pos]; pos += 1
r |= (b & 0x7F) << sh
if b < 0x80:
break
sh += 7
out.append(r)
return out
def read_tape(path):
"""→ list of days: {date, sod0, price [float], volume [int], filled [bool]}."""
raw = open(path, "rb").read()
if raw[:8] != b"MATANATP":
raise ValueError("not a tape file")
version, _flags = struct.unpack_from("<II", raw, 8)
scale, ndays = struct.unpack_from("<II", raw, 32)
_samples, off_days, off_blocks = struct.unpack_from("<QQQ", raw, 40)
if version != 2:
raise ValueError("this reader handles the packed tape (version 2) only")
tick = 1.0 / scale
days = []
for k in range(ndays):
date, _first, count, sod0 = struct.unpack_from("<IIIi", raw, off_days + 48 * k)
off, ln = struct.unpack_from("<QI", raw, off_blocks + 16 * k)
blk = raw[off:off + ln]
body = zlib.decompress(blk[5:]) if blk[0] == 1 else blk[1:]
v = _varints(body, 0)
# the flags section is (run, byte) pairs; varints of a byte < 128 are the byte itself
assert v[0] == count
j = 1
zz = lambda z: (z >> 1) ^ -(z & 1)
price, cur = [0] * count, zz(v[j]); price[0] = cur; j += 1; i = 1
while i < count:
z = v[j]; j += 1
if z == 0:
run = v[j]; j += 1
for _ in range(run):
price[i] = cur; i += 1
else:
cur += zz(z); price[i] = cur; i += 1
volume, i = [0] * count, 0
while i < count: # volume: value, or 0 + run of zero seconds
x = v[j]; j += 1
if x == 0:
i += v[j]; j += 1
else:
volume[i] = x; i += 1
filled, i = [False] * count, 0
while i < count:
run, f = v[j], v[j + 1]; j += 2
if f & FLAG_FILLED:
for q in range(i, i + run):
filled[q] = True
i += run
days.append({"date": date, "sod0": sod0, "price": [p * tick for p in price], "volume": volume, "filled": filled})
return days
# ── bars and indicators ────────────────────────────────────────────────────────────────────────────
def bar_start(sod, tf):
"""A second is labelled by its end (34201 = 09:30:00–09:30:01); bars run from the session open."""
off = SESSION_OPEN % tf
x = max(sod - 1, 0) - off
return (x // tf) * tf + off
def build_bars(days, tf):
"""Continuous bar list over all days, plus for each day/second the index of the last closed bar."""
bars, closed_at = [], []
for d in days:
idx, cur = [], None
for i, p in enumerate(d["price"]):
b = bar_start(d["sod0"] + i, tf)
if b != cur:
cur = b
bars.append([p, p, p, p]) # open, high, low, close
else:
br = bars[-1]
br[1] = max(br[1], p); br[2] = min(br[2], p); br[3] = p
idx.append(len(bars) - 2) # the bar before the current one is the last closed bar
closed_at.append(idx)
return bars, closed_at
def sma(vals, n):
out = [math.nan] * len(vals)
for i in range(n - 1, len(vals)):
out[i] = math.fsum(vals[i - n + 1:i + 1]) / n
return out
def rsi(vals, n):
"""Wilder's RSI: the first average is the simple mean of the first n changes."""
out = [math.nan] * len(vals)
up = dn = 0.0
for i in range(1, len(vals)):
d = vals[i] - vals[i - 1]
u, w = max(d, 0.0), max(-d, 0.0)
if i < n:
up += u; dn += w
continue
if i == n:
up = (up + u) / n; dn = (dn + w) / n
else:
up = (up * (n - 1) + u) / n; dn = (dn * (n - 1) + w) / n
out[i] = 100.0 if dn == 0 else 100.0 - 100.0 / (1.0 + up / dn)
return out
def highest(vals, n):
return [max(vals[i - n + 1:i + 1]) if i >= n - 1 else math.nan for i in range(len(vals))]
def lowest(vals, n):
return [min(vals[i - n + 1:i + 1]) if i >= n - 1 else math.nan for i in range(len(vals))]
# ── the three strategies: series on closed bars, entry and exit conditions ─────────────────────────
class SmaCross:
id, tf, stop_pct, target_pct = "sma-cross", 300, 0.5, 1.0
def series(self, bars):
c = [b[3] for b in bars]
return {"fast": sma(c, 10), "slow": sma(c, 30)}
def conditions(self, s, b, price, prev):
f, sl = s["fast"][b] if b >= 0 else math.nan, s["slow"][b] if b >= 0 else math.nan
ok = not (math.isnan(f) or math.isnan(sl))
up = ok and prev is not None and prev[0] <= prev[1] and f > sl
down = ok and prev is not None and prev[0] >= prev[1] and f < sl
return up, down, ((f, sl) if ok else None)
class Donchian:
id, tf, stop_pct, target_pct = "donchian-breakout", 900, None, None
def series(self, bars):
return {"upper": highest([b[1] for b in bars], 20), "lower": lowest([b[2] for b in bars], 10)}
def conditions(self, s, b, price, prev):
up, lo = (s["upper"][b], s["lower"][b]) if b >= 0 else (math.nan, math.nan)
return (not math.isnan(up) and price > up), (not math.isnan(lo) and price < lo), None
class Rsi2:
id, tf, stop_pct, target_pct = "rsi2-reversion", 300, 1.0, None
def series(self, bars):
return {"rsi": rsi([b[3] for b in bars], 2)}
def conditions(self, s, b, price, prev):
r = s["rsi"][b] if b >= 0 else math.nan
return (not math.isnan(r) and r < 10), (not math.isnan(r) and r > 70), None
STRATEGIES = {k.id: k for k in (SmaCross, Donchian, Rsi2)}
# ── the second-by-second walk ──────────────────────────────────────────────────────────────────────
def commission(price, qty):
return min(max(COMM_MIN, COMM_PER_SHARE * qty), price * qty * COMM_CAP_PCT / 100.0)
def run(days, strat):
bars, closed_at = build_bars(days, strat.tf)
s = strat.series(bars)
cash, qty, avg, stop, target = CAPITAL, 0, 0.0, None, None
entry = None
trades, peak, max_dd, max_dd_pct = [], CAPITAL, 0.0, 0.0
prev_vals = None # cross memory: the sides seen at the previous evaluated second
def buy(price, date, sod):
nonlocal cash, qty, avg, stop, target, entry
fill = price * (1 + SLIPPAGE_PCT / 100.0)
c = commission(fill, QTY)
cash -= QTY * fill + c
qty, avg = QTY, fill
stop = avg * (1 - strat.stop_pct / 100.0) if strat.stop_pct else None
target = avg * (1 + strat.target_pct / 100.0) if strat.target_pct else None
entry = {"dateIn": date, "sodIn": sod, "entry": fill, "commIn": c}
def sell(price, date, sod, why):
nonlocal cash, qty, stop, target, entry
fill = price * (1 - SLIPPAGE_PCT / 100.0)
c = commission(fill, qty)
cash += qty * fill - c
pnl = (fill - avg) * qty - entry["commIn"] - c
trades.append({**{k: entry[k] for k in ("dateIn", "sodIn", "entry")}, "dateOut": date, "sodOut": sod,
"exit": fill, "qty": qty, "pnl": pnl, "commission": entry["commIn"] + c, "why": why})
qty, stop, target, entry = 0, None, None, None
for di, d in enumerate(days):
prev_true = [False, False] # every session starts with both rules "false"
deferred = None # a market order from a second without trades
n = len(d["price"])
eod = d["sod0"] + n - 1 - EOD_SEC
for i in range(n):
sod, price, filled = d["sod0"] + i, d["price"][i], d["filled"][i]
if sod >= eod: # day end: sell, no rules until tomorrow
if qty:
sell(price, d["date"], sod, "day end")
deferred = None
else:
if qty and not filled: # 1. stop and target of the open position
if stop is not None and price <= stop:
sell(stop if STOP_FILL == "level" else price, d["date"], sod, "stop")
elif target is not None and price >= target:
sell(price, d["date"], sod, "target")
if deferred and not filled: # 2. an order that waited for a second with trades
(buy(price, d["date"], sod) if deferred == "buy" else sell(price, d["date"], sod, "rule"))
deferred = None
b = closed_at[di][i] # 3. rules on the state at this point of the second
up, down, prev_vals = strat.conditions(s, b, price, prev_vals)
want = [up and qty == 0, down and qty > 0]
fire = [want[k] and not prev_true[k] for k in (0, 1)]
prev_true = want
for k, side in ((0, "buy"), (1, "sell")):
if not fire[k]:
continue
if filled:
deferred = side
elif side == "buy":
buy(price, d["date"], sod)
else:
sell(price, d["date"], sod, "rule")
eq = cash + qty * price
peak = max(peak, eq)
max_dd = max(max_dd, peak - eq)
max_dd_pct = max(max_dd_pct, (peak - eq) / peak * 100.0)
return {"strategy": strat.id, "trades": trades, "equityEnd": cash, "netProfit": cash - CAPITAL,
"maxDrawdown": max_dd, "maxDrawdownPct": max_dd_pct, "first": days[0]["date"], "last": days[-1]["date"]}
def metrics(trades):
wins = [t["pnl"] for t in trades if t["pnl"] > 0]
losses = [t["pnl"] for t in trades if t["pnl"] < 0]
return {"tradeCount": len(trades), "winRate": 100.0 * len(wins) / len(trades) if trades else 0.0,
"profitFactor": math.fsum(wins) / -math.fsum(losses) if losses else None}
if __name__ == "__main__":
tape = read_tape(sys.argv[1])
for sid in sys.argv[2:] or list(STRATEGIES):
r = run(tape, STRATEGIES[sid]())
r.update(metrics(r["trades"]))
print(json.dumps(r))
Reproduce it in Matana Labs
- Open Strategy Lab (sign in or create a free account).
- Create a new strategy, open the Code view and paste one of the strategies above.
- Choose QQQ and the date range January 2, 2025 to October 28, 2026, and run it. The trades, net profit and drawdown match the table above; the run’s trade list shows each entry and exit second.
Data history on the free plan is limited; paid plans run the whole period. The validation is rerun when the engine’s fill rules change, and a smaller version runs on every change of the engine.