Event-driven engine, orders and accounting
Build an event-driven engine with a priority queue of market, signal, order, and execution events, a bar-based order simulator, and portfolio accounting with invariants. Compare it with the vectorized engine under ideal conditions and explore conditional orders and partial execution.
After this lesson you can
- Implement the event queue and main loop with strict temporal ordering.
- Model an order lifecycle and an execution simulator on daily bars.
- Maintain cash, positions, net asset value, and PnL with invariants checked at each step.
- Demonstrate equivalence with the vectorized engine without costs to machine precision.
Before you start
From matrix to event
The vectorized engine calculates a portfolio under rules expressible as aligned panel operations. Pending orders, partial fills, and cancellations require state. An event-driven engine represents discrete changes: market, signal, order, and execution. A queue determines processing order; a portfolio records each fill’s effect. This architecture helps study conditional decisions, although it does not automatically make a simulation realistic.
In this lesson the teaching engine processes market marks, signals, orders, bars, and dividends. A signal receives only marks already processed and creates orders in the next phase; the strategy must also respect its own data availability dates. A production implementation would need more events and connections, recovery guarantees, data validation, and risk controls. The figure shows a conceptual step-by-step walkthrough, not exchange data.
A priority queue uses key . The date orders sessions; the phase determines, for example, whether an order is active before a bar is processed; the sequence breaks ties in insertion order. Without the final number, two events at the same time and phase might change order between runs. Document the timing contract: a signal calculated at the close cannot receive that closing price unless submitted before the auction deadline using information then available.
A loop extracts the smallest event, updates state, and continues. The example supports pre-scheduled events and the signal inserts orders at a later phase of the same instant. A version dynamically generating other events should verify that no insertion precedes the event being processed. The queue provides reproducibility; causality also depends on the data entering each signal and when it was available.
Consider a cutoff at Monday’s end. The closing data arrives, the strategy decides, and leaves an order for Tuesday. On Tuesday an opening event gives the simulator an execution opportunity. Cash and position change only after a fill. A signal is not a trade, nor is an accepted order: recording the desired position directly on receiving the signal omits delays, rejections, and partial fills.
In the lab, the bar event receives open, high, low, and close together. This is a processing simplification: a consumer must not use the high or close to decide an order then assumed active at that same bar’s open. The execution function can inspect the low for an already pending order, but this does not make the low available in advance to the strategy. Keep the observation clock separate from the information each component uses.
Orders and bars
The order lifecycle moves from new to open, partially filled, and finally filled or canceled. A partial fill reduces the outstanding balance; canceling the remainder does not undo what has already filled. A buy limit accepts the limit or a better price; a sell limit accepts the limit or higher. The SEC explains that a limit order specifies a price condition and does not guarantee execution.
With open 101, low 98, and buy limit 99, our simulator permits a fill at 99 if the order was active before the bar. This is optimistic: the low indicates that some trade occurred at 98, but not our order’s queue position, available volume, or whether it filled. If the open were 97, the model would use 97 as hypothetical improvement. A sell limit is symmetric. We also do not know the intraday order of high and low; two conditional orders triggered in the same bar can produce incompatible outcomes depending on the real path.
The function applies maximum capacity shared by orders processed in a bar and visits them in insertion order. Capacity is an illustrative parameter, not a depth estimate; it does not replace order-book data, price-time priority, or impact. A market order fills at the open and a market-on-close order at that bar’s close. For causal use, both must be active before the relevant price and the close order must respect the actual submission deadline. Order-simulator commissions, slippage, rejection, expiry, and auction rules are excluded; the portfolio does accept explicit commissions on each fill.
For example, with two pending orders and capacity of five units, the first buys four and the second receives one unit. At the next bar the second can complete its balance. The test fixes this order explicitly and shares capacity between buys and sells; it does not match the user’s own orders against each other. With zero capacity both remain open. Canceling a partial order leaves the executed portion intact and removes only the possibility of future fills in this model.
The open can fall outside a limit order’s acceptable range. For a buy with open 101 and limit 99, the model waits for an intraday touch and uses 99; if the low were 100, it would not fill. With open 97 it permits improvement to 97. For a sell order the inequalities reverse. None of these conventions accounts for quotes jumping over the limit, insufficient counterparties, or an observed price from another trading venue.
Accounting and invariants
Portfolio accounting maintains cash , units , and average cost . For a signed fill at price and fee :
A buy has positive quantity and reduces cash; a sell has negative quantity. At the fill mark and without fees, value does not change merely by exchanging cash for the asset. With a fee it falls by exactly . A later mark can differ from the fill, changing unrealized PnL. The code permits short positions and negative cash, so it does not impose a cash-only account. That mode would require rejecting trades exceeding cash or inventory and defining margin policy.
In a long position, selling part realizes per unit closed. In a short position, buying back realizes per unit. Adding in the same direction updates weighted average cost; reducing without changing sign preserves it. If a trade crosses zero, the closing portion realizes PnL and the excess opens a position at the new price. Fees accumulate separately from average cost. A dividend of per share changes cash by : a short position pays the amount.
Starting with cash and no positions, and marking all positions, the tested invariant is
This is an accounting identity for the model, not a profitability claim. It excludes financing, interest, taxes, splits, and currencies. Value can fall below zero when losses or leverage are allowed; a real account has additional constraints.
Consider buying four shares at 99 with 1000 cash and no fee: 604 cash and four shares remain. At a mark of 100, value is 1004 and unrealized PnL is 4. If one share is then sold at 103, 4 is realized and three shares remain at average cost 99; if the new mark is 103, unrealized PnL is 12. Cash plus positions totals 1016, equal to initial capital plus 4 realized and 12 unrealized. Sale proceeds are not added again as profit: they are already cash.
A corporate distribution must be included once. Using dividend-adjusted prices and also crediting the dividend as cash can double-count it. Share-based accounting requires compatible prices and events, effective dates, and verified conventions. The portfolio example uses marks without automatic adjustments and explicit dividends. Preparing consistent data is the responsibility of the provider and engine user.
Equivalence and testing
Engine equivalence is a differential test: both receive the same lagged target positions and prices. Without costs, with fractional shares and ideal simultaneous rebalancing at a known price, the event engine buys units of each asset. Marking at the next price gives
Induction from the same initial capital establishes equality with the vectorized product. This equivalence does not show that an order can actually execute at that price, and need not hold if either model applies different costs, constraints, rounding, or timing rules. Floating-point operations accumulate in different orders, so a numerical tolerance is used.
The test uses 80 intervals and three synthetic assets. Before each interval it calculates total value, converts already-lagged target weights into fractional shares, and executes all differences at the same price. The portfolio is marked at the next price. The vectorized engine receives the same returns and signal sequence, with a one-row lag. Residual cash is assumed to earn zero. A convention change, such as marking at close in one engine and open in the other, requires redefining the experiment before attributing discrepancy to a defect.
Hypothesis generates sequences within defined ranges and checks the invariant after each fill and dividend. It is configured for 1000 valid examples of up to 30 trades, with positive and negative quantities and position crossings. Passing those samples does not prove every possible case: ranges, error handling, and assumptions remain part of the test. We also verify stable ordering, partial limit fills, cancellation, capacity, and dividends on a short position.
Local laboratory
Download p01events.py and test_p01events.py along with p01vector.py from the previous lesson. Install NumPy, pandas, pytest, and Hypothesis in your Python environment. The following code runs the actual implementation and its tests, not simulated output. P01_LIB_DIR points to the files’ directory; by default it is the current directory.
import os,sys
from pathlib import Path
import pytest
lib=Path(os.environ.get('P01_LIB_DIR','.')).resolve()
if not (lib/'p01events.py').exists(): raise FileNotFoundError('Descarga los módulos y pruebas en P01_LIB_DIR')
sys.path.insert(0,str(lib))
from p01events import Portfolio,Order,Engine
portfolio=Portfolio(1000)
engine=Engine(portfolio)
order=Order('A',10,'limit',99)
engine.schedule(0,0,'order',order)
engine.schedule(1,0,'bar',('A',{'open':101,'high':102,'low':98,'close':100},4))
engine.run()
print('Estado:',order.status,'| pendientes:',order.remaining,
'| efectivo:',portfolio.cash,'| acciones:',portfolio.positions['A'])
os.environ['PYTEST_DISABLE_PLUGIN_AUTOLOAD']='1'
status=pytest.main([str(lib/'test_p01events.py'),'-q','-s','-p','_hypothesis_pytestplugin',
'--hypothesis-show-statistics','-p','no:cacheprovider'])
assert status==0npm run lab and open the connection link.In the verified run, the order is partial with 6 shares pending, cash 604, and 4 shares. All six tests pass; Hypothesis records 1000 valid examples, and maximum capital difference between engines is approximately for the test’s seed and sample. This is a bounded synthetic check, not a result on real markets. Lesson files retain seed, ordering, and tolerance for reproduction.
Exercises
def apply_fill(cash,shares,quantity,price,fee):
raise NotImplementedError()Step 1 of 2. What is the value of the position in asset i after rebalancing?
What to remember
The next step can add more demanding cost and execution models on this basis, without confusing a bar touch with available liquidity.