From job state to trading evidence
In Edition 6 we distinguished a known failure before an action from an uncertain result afterward. A trading agent needs that distinction at the execution boundary. If a buy request times out, did it fail, fill completely, or fill only part of the requested quantity? Sending another request before answering can increase exposure while the local worker still believes there is no position.
This edition asks a narrow research question: can a reconciliation pass distinguish duplicate evidence, conflicting evidence, missing evidence, and partial execution without treating uncertainty as permission to repeat a trade? We will reproduce those four cases with invented records. The outcome is an evidence classification, not a trading decision.
Time: about 35 minutes. Prerequisites: Python 3.12 or later and the concepts from Edition 6. The script uses the standard library, writes no files, and connects to no broker or wallet. Every identifier and amount below is fictional.
Step 1: Define what each identifier means
An intent identifies one requested economic action. A fill identifies one execution record. One intent can have several fills, and a feed can deliver the same fill more than once. Counting messages therefore overstates activity when a provider repeats a response.
We will store four buy intents. Each has a requested quantity and starts in unknown. This starting state means the local system has not established what happened. It does not mean a broker rejected the request. We intentionally supply no authoritative rejection events in this lab, so none of these intents can authorize a retry.
The fixture has six kinds of evidence: an intended side, an intended quantity, an execution identifier, an execution side, an execution quantity, and the relationship between execution and intent. Real adapters also need instrument identity, venue, source time, fee units, and settlement evidence. Keep those fields in a production contract rather than assuming a matching ticker is enough.
Step 2: Write the interpretation rules first
An identical repeat of the same fill identifier adds no quantity. A contradictory repeat marks the affected intent for review. A consistent fill matching the requested quantity establishes filled within this simulation. A smaller positive amount establishes partial. No matching record leaves the result unknown.
These rules preserve a useful asymmetry. Evidence can establish that some quantity executed, but absence from a response does not establish that nothing executed. A truncated page, delayed event, or unavailable adapter could hide a valid fill. A complete broker reconciliation has a stronger contract than our small list.
Conflict handling is equally important. Choosing the last of two contradictory quantities might make the output look settled while concealing the disagreement. We retain the first record as evidence and mark both referenced intents for review. We do not add the two quantities or choose whichever creates a favorable result.
Step 3: Run the reconciliation experiment
Save this complete script as lab_07.py and run python lab_07.py. Use the same interpreter as your earlier journal labs.
from decimal import Decimal
intents = {
"entry-a": {"status": "unknown", "side": "buy", "units": "2"},
"entry-b": {"status": "unknown", "side": "buy", "units": "1"},
"entry-c": {"status": "unknown", "side": "buy", "units": "1"},
"entry-d": {"status": "unknown", "side": "buy", "units": "3"},
}
events = [
{"intent": "entry-a", "fill": "demo-fill-a", "side": "buy", "units": "2"},
{"intent": "entry-a", "fill": "demo-fill-a", "side": "buy", "units": "2"},
{"intent": "entry-c", "fill": "demo-fill-c", "side": "buy", "units": "1"},
{"intent": "entry-c", "fill": "demo-fill-c", "side": "buy", "units": "9"},
{"intent": "entry-d", "fill": "demo-fill-d", "side": "buy", "units": "1"},
]
seen, conflicts = {}, set()
duplicates = 0
for event in events:
prior = seen.get(event["fill"])
if prior is not None:
if prior == event:
duplicates += 1
else:
conflicts.update((prior["intent"], event["intent"]))
continue
seen[event["fill"]] = event
for key, intent in intents.items():
matches = [row for row in seen.values() if row["intent"] == key]
if key in conflicts:
intent["status"] = "review"
elif not matches:
intent["status"] = "unknown"
elif any(row["side"] != intent["side"] for row in matches):
intent["status"] = "review"
else:
filled = sum((Decimal(row["units"]) for row in matches), Decimal("0"))
requested = Decimal(intent["units"])
intent["status"] = (
"filled" if filled == requested
else "partial" if Decimal("0") < filled < requested
else "review"
)
assert duplicates == 1
assert len(seen) == 3
assert [intents[key]["status"] for key in sorted(intents)] == [
"filled", "unknown", "review", "partial"
]
assert all(row["status"] != "retry" for row in intents.values())
for key in sorted(intents):
print(f"{key}={intents[key]['status']}")
print("unique_fill_records=3 identical_duplicates=1")
print("retry_authorizations=0 data=synthetic no_orders_submitted")
Expected output:
entry-a=filled
entry-b=unknown
entry-c=review
entry-d=partial
unique_fill_records=3 identical_duplicates=1
retry_authorizations=0 data=synthetic no_orders_submitted
Step 4: Interpret the four outcomes
entry-a has one fictional two-unit fill delivered twice. Its requested quantity is two, so its result is filled. Counting both messages would incorrectly report four units. The duplicate counter describes delivery, not additional execution.
entry-b has no matching record. It stays unknown. The fixture cannot distinguish an unsubmitted request from a filled request whose receipt has not arrived. This is the practical link to Edition 6: an uncertain external effect must be reconciled before another action is considered.
entry-c has conflicting versions of the same fill identifier. One says one unit and the other says nine. We know the records disagree; we do not know which quantity is authoritative. The review state records that limit explicitly.
entry-d requests three units and has one consistent one-unit fill. It is partial, with two units not established as filled by the available records. That does not authorize a new two-unit request. An original order could still be working, cancelled, or complete with delayed evidence. Order status and fills must be reconciled together.
Step 5: Test whether the result survives repeated evidence
Append another exact copy of the first event. Predict the change before running: identical duplicates should increase by one, while the classified states and unique fill count remain unchanged. Update the duplicate assertion for this intentional variation and keep the original script as the baseline.
Next, add a second, distinct two-unit fill to entry-d. Its total becomes three and its simulated state becomes filled. Add three units instead and the total exceeds the requested quantity, producing review. Both changes teach why reconciliation needs quantity accounting rather than a yes/no receipt flag.
Finally, change one execution side to sell while its intent remains buy. That disagreement must not confirm the buy. In a real system, also test a wrong chain, wrong instrument, reused provider identifier, delayed page, and a receipt arriving after a worker restart. Do not remove a check just to make the experiment pass.
Step 6: Connect reconciliation to the research denominator
A research ledger should distinguish intents, unique executions, independently completed round trips, open positions, and unresolved outcomes. A confirmed entry is not a completed trade, and neither an entry nor a partial fill supplies an exit price. Edition 3's cost accounting still applies only when the required quantities and costs are known.
Keep unresolved cases visible. Otherwise a strategy may appear to improve simply because missing or contradictory outcomes disappear from evaluation. A prospective comparison should give the baseline and challenger the same reconciliation rules and retain the same candidate stream.
Evidence limits and troubleshooting
The printed results prove the declared behavior on this fixture. They do not prove provider authenticity, durable recovery across crashes, concurrency safety, settlement finality, correct fee accounting, or profitable trading. Three unique fill records include a disputed record; they are not three verified market fills. This is an original teaching experiment, not a report of newly observed production trades.
If an assertion fails, compare the event identifiers, quantities, and sides with the unmodified fixture. Construct Decimal quantities from strings. The script assumes valid positive finite quantities; a real adapter must reject malformed, negative, infinite, or nonnumeric amounts before reconciliation. Keep execution evidence and operational validation as separate checks.
Completion check: Explain why the four states differ, why the identical duplicate adds no exposure, and why no intent authorizes a retry. Save the script and its output together so another reader can inspect the same cases.
Next edition: A fresh response can carry a stale quote. We will move from execution evidence to the time and identity of the observations an agent uses.
Primary technical reference
Python Decimal documentation describes the arithmetic used for quantities. The reconciliation policy and fictional fixture are original examples; they are not a broker-specific guarantee.