Skip to main content

Event-Driven Trading System

CI Python Coverage Docs mypy Ruff License: MIT

A causal, event-driven backtesting and paper-trading engine in Python. Market data, signals, orders, risk checks, fills and portfolio snapshots are typed, immutable events on a publish/subscribe bus. No component calls another directly, so any of them can be swapped, tested in isolation, or recorded. The pipeline that runs a backtest also trades an Alpaca paper account; only the execution component changes.

The goal is results you can trust: no look-ahead, correct long/short accounting, mark-to-market metrics on every bar, and deterministic, reproducible runs, each property enforced by tests.

Backtest chart: price with fills, equity vs. buy-and-hold, and drawdown

Two years of synthetic daily bars, 5/20 SMA crossover, long-only. Reproduce it with make demo.

Highlights

  • No look-ahead bias. Strategies see bar t after it closes; orders trade on bar t + 1 at the earliest, with adverse slippage and commission.
  • Strictly causal event loop. Each time slice's full event cascade settles before the next one is read.
  • Portfolios. One account trades many symbols, with per-symbol strategies or cross-sectional ones such as momentum rotation and pairs trading.
  • Realistic orders. Market, limit and stop orders, day or good-till-cancelled, partial fills capped by bar volume, and minimum commissions.
  • Sizing and exits. Fixed, percent-of-equity or ATR-risk position sizing, and a stop-loss and take-profit kept on every open position.
  • Pre-trade risk. Limits on position size, position value, gross leverage and drawdown that always let you reduce risk.
  • Correct accounting. Average-cost P&L for longs, shorts and flips, checked by property-based tests.
  • Research tools. Parallel parameter sweeps, and walk-forward validation that reports out-of-sample results.
  • Paper trading. Any strategy runs on live Alpaca bars against a paper account, or on simulated fills with --dry-run, and a daily report compares it with a backtest over the same bars.
  • Run store. Every event of every backtest and paper session goes to SQLite, alongside sweep and walk-forward results.
  • Engineering. Strict mypy, ruff, 500+ tests at 98% branch coverage, CI on Linux, macOS and Windows across Python 3.11–3.14.

Quick start

pip install "event-trading-system[all]"   # core needs only PyYAML; [all] adds Yahoo data, charts
trading                                   # synthetic data, MA crossover

To work on the code, install from a clone instead:

git clone https://github.com/Space-Paragon1/Event-Driven-Trading-System.git
cd Event-Driven-Trading-System
python -m venv .venv && source .venv/bin/activate   # Windows: .venv\Scripts\activate
pip install -e ".[dev]"
trading --strategy rsi --bars 1000                      # another strategy, longer run
trading --symbols SPY --from 2020-01-01 --to 2025-01-01  # real data (Yahoo Finance)
trading --symbols AAPL,MSFT,NVDA,AMZN \
        --strategy momentum_rotation --sizing percent --percent 50  # a portfolio
trading --csv prices.csv --symbol SPY                   # your own data
trading --allow-short --stop-loss 5 --take-profit 10    # long/short with exits
trading --save-chart run.png                            # chart to file (--chart: window)
trading --json | jq .metrics.sharpe_ratio               # machine-readable output
trading --config my.yaml -v                             # full config, log every event
Command What it does
trading [run] One backtest (the default command)
trading sweep Backtest every combination of a parameter grid and rank them
trading walk-forward Tune on one window, test on the next unseen one, repeat
trading paper Paper-trade on live Alpaca bars
trading runs List stored runs, sweeps and paper sessions
trading health Check a paper trader's heartbeat, for container health checks
trading compare Compare a paper session with a backtest over the same bars
trading study Walk every strategy of a study forward and write up the results

python -m trading works too, as does python main.py from a checkout. trading-backtest, the command's name before 0.3.0, still works. Run trading COMMAND --help for every option.

Sample output
19:58:59  [Signal]     AAPL 2024-03-15 00:00  BUY strength=0.0076
19:58:59  [Order]      AAPL 2024-03-15 00:00  O000001 BUY 400 MARKET @ ref 181.90  (signal)
19:58:59  [Approved]   AAPL 2024-03-15 00:00  O000001
19:58:59  [Fill]       AAPL 2024-03-18 00:00  O000001 BUY 400 @ 182.9983  comm=4.00
...

Backtest  AAPL | ma_crossover | synthetic data | 504 bars (2024-01-02 to 2026-01-05)

==============================================
  PERFORMANCE REPORT
==============================================
  Final equity                      $92,052.56
  Total return                         -7.95 %
  Buy & hold                          -19.82 %
  CAGR                                 -4.06 %
  Volatility (ann.)                     9.31 %
  Sharpe ratio                          -0.398
  Sortino ratio                         -0.561
  Max drawdown             12.77 %  (452 bars)
  Calmar ratio                          -0.318
----------------------------------------------
  Alpha (ann.)                         -1.85 %
  Beta                                   0.239
  Information ratio                      0.194
  Tracking error                       20.77 %
----------------------------------------------
  Round trips                               14
  Win rate                              35.7 %
  Profit factor                          0.332
  Avg trade P&L                       $-841.65
  Fills                                     29
  Commission                           $116.00
  Exposure                              40.3 %
  Turnover                              15.47x
  Risk vetoes                                0
==============================================

The order is placed on the signal bar's close (Friday 03-15) and filled at the next bar's open (Monday 03-18). Logs go to stderr and results to stdout.

How it works

Components

flowchart LR
    Feed[(Market data<br/>synthetic · CSV · Yahoo · Alpaca)] -->|MarketDataEvent| Strategy
    Strategy -->|SignalEvent| OM[Order Manager]
    OM -->|OrderEvent| Risk[Risk Manager]
    Exits[Exit Manager] -->|OrderEvent: stop, take-profit| Risk
    Risk -->|ApprovedOrderEvent| Exec[Execution<br/>simulator or broker]
    Risk -.->|RiskVetoEvent| OM
    OM -.->|CancelOrderEvent| Exec
    Exec -->|FillEvent| Portfolio
    Exec -->|FillEvent| OM & Exits & Risk & Metrics
    Exec -.->|OrderCancelledEvent| OM
    Portfolio -->|PortfolioUpdateEvent| Metrics
    Portfolio -->|PortfolioUpdateEvent| Risk
    Bus{{Event bus}} -.- Logger & SQLite[(SQLite)]

Every arrow is an event on the bus. The logger and SQLite writer subscribe to everything.

Event Published by Meaning
MarketDataEvent engine (from a feed) one OHLCV bar
SignalEvent strategy BUY / SELL / EXIT / HOLD plus strength in [0, 1]
OrderEvent order manager, exit manager an order sized to reach a target, or a protective exit
ApprovedOrderEvent risk manager order passed every check
RiskVetoEvent risk manager order rejected, with reason
CancelOrderEvent order manager, exit manager request to cancel a working order
OrderCancelledEvent execution order ended with shares unfilled (cancelled, expired, rejected)
FillEvent execution shares traded, with price and commission
PortfolioUpdateEvent portfolio mark-to-market snapshot, once per time slice
EndOfBarEvent engine clock tick: the slice's cascade has settled

Events are frozen, slotted, keyword-only dataclasses.

One bar, step by step

sequenceDiagram
    autonumber
    participant E as Engine
    participant X as Execution
    participant P as Portfolio
    participant S as Strategy
    participant O as Order Mgr
    participant R as Risk
    E->>X: MarketDataEvent (bar t)
    X->>P: FillEvent: orders from bar t-1 fill at open(t)
    E->>S: MarketDataEvent (bar t)
    S->>O: SignalEvent (decided on close(t))
    O->>R: OrderEvent
    R->>X: ApprovedOrderEvent: queued until bar t+1
    Note over E: bus drained, cascade settled
    E->>P: EndOfBarEvent
    P->>R: PortfolioUpdateEvent: equity marked at close(t)

The engine is the clock. Feeds are merged into time slices, one bar per symbol:

for timestamp, bars in merge_feeds(feeds):
    for bar in bars:
        bus.publish(bar)
    bus.run()  # fills, signals, orders, risk decisions
    bus.publish(EndOfBarEvent(timestamp=timestamp))
    bus.run()  # mark-to-market snapshot, cross-sectional strategies

Design decisions

Decision Why
Drain the bus after every slice Queuing all bars first (a common mistake) makes every signal run after the whole dataset is processed, so every order is priced off the final bar. A regression test pins this.
Fill on the next bar A decision made on bar t's close cannot trade at that close. Slippage is adverse, never symmetric noise that averages to zero.
Assume the worst within a bar OHLC bars don't say what traded first. When a bar touches both a stop and a take-profit, the stop is assumed to fill first.
Target positions, not order sizes BUY means "be long N". The order manager orders the delta against the filled position plus working orders, so a strategy can emit BUY every bar without stacking exposure.
Risk checks only constrain new exposure Reducing or closing a position is always allowed, even with the drawdown breaker tripped. Getting out must never be blocked.
Explicit end-of-bar clock event The portfolio snapshot has to include fills that happened during the slice, which only the engine can know have settled.
One pipeline for backtests and paper trading Both build the same strategy, order manager, exits, risk, portfolio and metrics. Only execution differs, so a paper session runs exactly the code a backtest validated.
Sequential IDs and seeded randomness Two runs with the same config produce identical events, fills and reports.
Fail fast Handler exceptions propagate, and invalid config, unknown keys and malformed data raise precise errors. A strategy name that doesn't exist won't silently become random.

Portfolios, orders and risk

Several symbols

--symbols AAPL,MSFT (or simulation.symbols) trades one account across every symbol. Feeds are merged into time slices, and a symbol missing from a slice keeps its last price. Synthetic feeds can share a market factor (simulation.correlation), CSV takes a path template such as data/{symbol}.csv, and Yahoo Finance downloads each symbol.

Synthetic bars fall on the New York Stock Exchange's trading days: none on its holidays, and a 3.5-hour session on its early-close days, with proportionally less drift, variance and volume. The calendar is worked out from the exchange's rules and matches its published calendar from 2000 on. simulation.calendar: weekdays puts a full session on every weekday instead, as earlier versions did, and reproduces their bars.

Caching downloads

--cache-dir DIR (or simulation.cache_dir) keeps each Yahoo Finance download as a CSV file in DIR, and later runs with the same symbol, interval and dates read it from there, with no network at all:

trading --symbols SPY,QQQ --from 2015-01-01 --to 2025-01-01 --cache-dir data/cache

Each file has a checksum beside it, SPY_1d_2015-01-01_2025-01-01.csv.sha256, in the format sha256sum writes, so shasum -a 256 -c *.sha256 checks the cache. A file that no longer matches its checksum stops the run instead of being downloaded again: Yahoo revises its adjusted history after every dividend, and a study's data changing under it should be noticed. Delete the file to download it afresh. A range that has not ended yet in New York is not cached, since its last bars could still change.

Orders and fills

Orders fill on later bars of their symbol:

Order Fills
MARKET at the open
LIMIT at the open if it is already at or through the limit, else at the limit if the bar's range reaches it
STOP at the open if it gapped through the stop, else at the stop if the bar's range reaches it
  • Market and stop fills pay slippage against you, never past the bar's high or low. Limit fills never trade worse than the limit. Slippage is the sum of three parts, the last two off by default:

    Key Cost, as a share of the price
    slippage_bps a fixed number of basis points (1)
    spread_bps half the quoted bid-ask spread
    impact impact × σ × √(shares / ADV), the square-root law of market impact

    σ is the standard deviation of the symbol's log returns from close to close and ADV its average volume per bar, both over the volume_window (20) bars before the fill bar, never the bar being traded. A coefficient near 1 is the usual estimate, so a trade of 1 % of a day's volume in a stock moving 2 % a day costs about 0.2 %. Impact grows with size: four times the shares cost twice as much per share.

  • Commission per fill is max(commission_min, commission_per_share × shares).

  • With max_volume_pct set, at most that share of a bar's volume fills. The rest stays working (gtc) or is cancelled (day).

  • An order the account cannot fund is rejected when it arrives, as a broker would. With it added, positions and open orders may be worth at most portfolio.margin_multiplier times equity: 2 by default (Reg T margin), 1 for a cash account, null for no check. Positions are valued at their last close, the new order at its limit, stop or reference price. Orders that reduce exposure always go through. The rejection is an OrderCancelledEvent whose reason starts rejected: insufficient buying power. A dry run checks the same way; a paper session leaves it to the broker.

  • Orders that add exposure use order_manager.order_type: market, or limit priced limit_offset_bps better than the last close. Orders that reduce or flip a position are always market orders, so exits are never missed.

Position sizing

sizing Target position
fixed quantity shares
percent percent_equity % of equity, at the last close
atr the size that loses risk_pct % of equity on a move of atr_multiple × ATR(atr_period)

Sizes use the previous slice's equity, never the bar being traded.

Exits

--stop-loss PCT and --take-profit PCT (or exits.stop_loss_atr for a stop measured in ATRs) keep a reduce-only stop and take-profit on every open position, priced from its average cost and replaced after each fill. When one fills, the other is cancelled.

Risk limits

The risk manager checks these in order, and only for orders that increase exposure. Reducing or closing a position is always allowed, and protective exits are always approved.

  1. max_position: shares per symbol, counting approved orders not yet filled.
  2. max_position_pct: position value per symbol, as a percentage of equity.
  3. max_gross_leverage: gross exposure across all symbols, as a multiple of equity.
  4. max_drawdown_pct: once equity falls this far below its peak, no new exposure.
  5. max_daily_loss_pct: once equity falls this far below the previous trading day's close, no new exposure until the next trading day (New York time). Off by default.

Set any limit to null to disable it.

Interest and borrow fees

Three annual rates in the portfolio section, all 0 by default, are paid or charged whenever a bar closes, for the calendar time since the previous one (actual/360, the way Alpaca charges margin interest and borrow fees):

portfolio:
  interest_rate_pct: 4.0     # paid on cash
  margin_rate_pct: 7.0       # charged on borrowed cash, a negative balance
  borrow_rate_pct: 0.3       # charged on the value of short positions

They accrue on what was held at the previous close: the cash, and each short position's value at that close, so a Friday close accrues three days by Monday's. Each payment is a CashFlowEvent, stored in the cash_flows table. The report shows the totals as Interest (net of margin interest) and Borrow fees. A borrow fee also counts against the short trade that held the position, and against its symbol's net P&L.

Strategies

Key Kind Logic
ma_crossover per symbol BUY when SMA(fast) crosses above SMA(slow), SELL on the cross below
rsi per symbol Wilder's RSI: BUY on crossing into oversold, SELL on crossing into overbought (mean reversion)
buy_and_hold per symbol Buys every symbol on its first bar and never sells: a benchmark that pays the same costs
random per symbol Uniform random BUY/SELL/HOLD: a null baseline any real strategy should beat
momentum_rotation portfolio Every rebalance_every bars, holds the top_k symbols with the best lookback return and exits the rest. Leaders with a negative return are exited too, so a falling market means cash.
pairs portfolio Two symbols. Trades the z-score of the spread log(A) − β·log(B), with β from a rolling least-squares fit. Needs allow_short.

With allow_short: false (the default), SELL exits to flat. With true, it reverses to a short of the same size.

Writing your own

Subclass Strategy and implement on_bar. Wiring and publishing are handled for you:

from trading import BacktestConfig, BacktestEngine, Signal, Strategy
from trading.events.types import Direction, MarketDataEvent
from trading.signal.indicators import SMA


class TrendFilter(Strategy):
    """Long while the close is above its 50-bar average, flat otherwise."""

    name = "trend_filter"

    def __init__(self, period: int = 50) -> None:
        super().__init__()
        self.sma = SMA(period)

    def on_bar(self, bar: MarketDataEvent) -> Signal:
        avg = self.sma.update(bar.close)
        if avg is None:
            return Direction.HOLD, 0.0
        return (Direction.BUY if bar.close > avg else Direction.SELL), 1.0


result = BacktestEngine(BacktestConfig(), strategy=TrendFilter()).run()
print(result.report)

This emits BUY on every bar above the average, yet trades only when the regime flips. That comes from target-position sizing.

For decisions that compare symbols, subclass PortfolioStrategy and implement on_slice, which sees every symbol's bar for a time slice at once:

from collections.abc import Mapping
from datetime import datetime

from trading.signal.base import PortfolioStrategy


class LongTheLeader(PortfolioStrategy):
    """Holds whichever symbol gained the most since the previous slice."""

    name = "leader"

    def __init__(self) -> None:
        super().__init__()
        self.last: dict[str, float] = {}

    def on_slice(
        self, timestamp: datetime, bars: Mapping[str, MarketDataEvent]
    ) -> Mapping[str, Signal]:
        gains = {s: b.close / self.last.get(s, b.close) for s, b in bars.items()}
        self.last.update({s: b.close for s, b in bars.items()})
        best = max(gains, key=gains.__getitem__)
        return {s: (Direction.BUY if s == best else Direction.EXIT, 1.0) for s in bars}


config = BacktestConfig().with_overrides({"simulation.symbols": ["AAPL", "MSFT", "NVDA"]})
result = BacktestEngine(config, strategy=LongTheLeader()).run()

To make a strategy available from the CLI and config, add it to STRATEGIES in signal/registry.py.

examples/ has runnable scripts: a custom strategy against buy and hold, a sweep and its deflated Sharpe ratio, walk-forward validation, and a custom strategy paper trading. The tests run each of them.

Research

Parameter sweeps

trading sweep --bars 756 --param strategy.fast_period=5:20:5 \
                         --param strategy.slow_period=30,60,90

--param takes an inclusive range start:stop[:step] or a list a,b,c; repeat it to build a grid. Every combination runs on the same data, in parallel (--jobs), and is ranked by --metric (default sharpe_ratio, or any report field).

Sweep: 12 combinations, ranked by sharpe_ratio  (stored as e4004d89ee16)

fast_period  slow_period   return %     sharpe   max dd %     trades
--------------------------------------------------------------------
         15           60      +3.50      0.521       2.59          5
         20           60      +3.35      0.499       2.87          5
         20           90      +2.94      0.460       3.25          3
         15           90      +1.95      0.314       3.05          4
         10           90      +1.76      0.287       3.90          4

Best: --param strategy.fast_period=15 --param strategy.slow_period=60

Beware: the best of many backtests is optimistic. Validate it with walk-forward.

After the best run, a sweep prints its deflated Sharpe ratio (Bailey and López de Prado, 2014): the probability that its true Sharpe ratio is above zero, judged against the best Sharpe ratio that as many trials of a strategy with no skill would be expected to reach by luck, and allowing for the skew and fat tails of its returns. It counts every combination as a trial, which errs on the strict side when combinations are similar.

Walk-forward validation

The best of many backtests flatters the strategy. Walk-forward picks the best parameters on a training window, scores them on the unseen window that follows, and rolls forward (--anchored grows the training window instead). The test windows chain into one out-of-sample equity curve. Each test window is warmed up on the bars before it and starts in the position the strategy already holds, as it would had it been trading all along.

trading walk-forward --bars 1260 --train 504 --test 126 \
    --param strategy.fast_period=5:20:5 --param strategy.slow_period=30:90:30
Walk-forward: 6 folds (rolling, train 504 / test 126 bars), optimising sharpe_ratio

fold  test window               fast_period   slow_period  IS sharpe_ratio  OOS sharpe_ratio
--------------------------------------------------------------------------------------------
   0  2025-12-08..2026-06-01             10            30           -0.091             1.774
   1  2026-06-02..2026-11-24              5            30            0.968            -2.261
   2  2026-11-25..2027-05-19             20            60            0.944             0.089
   3  2027-05-20..2027-11-11             20            90            1.221            -0.452
   4  2027-11-12..2028-05-05             10            30            0.590             4.439
   5  2028-05-08..2028-10-30             10            30            1.451            -0.940

Out-of-sample (test windows chained):
  ... full performance report ...
Walk-forward efficiency (OOS CAGR / IS CAGR): 0.62

Walk-forward efficiency is out-of-sample CAGR over mean in-sample CAGR. Well below 1 means much of the in-sample result came from fitting noise. On synthetic random-walk data like this, all of it is noise, which is exactly what the check should reveal.

Confidence intervals

A Sharpe ratio from one backtest is a single draw. --bootstrap N (or metrics.bootstrap: N) resamples the per-bar returns N times and reports the range that holds the central 95 % (metrics.confidence) of the resampled Sharpe ratios and total returns, after a backtest or for walk-forward's chained out-of-sample period:

95 % confidence (stationary bootstrap, 2000 resamples, mean block 8 bars)
  Sharpe ratio         -1.772  to     0.782
  Total return        -28.12 %  to   +15.56 %

Returns are drawn in blocks of random length, averaging the cube root of the number of bars (metrics.bootstrap_block to choose), so the volatility clustering of real returns survives resampling. An interval that spans zero means the run cannot tell the strategy from luck. The resampling is seeded, so a rerun gives the same interval. Sweeps do not bootstrap each run.

trading runs lists stored backtests, paper sessions, sweeps and walk-forward runs, newest first.

The study

docs/research/ walks every built-in strategy forward over 15 years of eight liquid ETFs (pairs trades EWA against EWC), after commissions, spread, slippage and market impact. Out of sample, none beat buying and holding the same ETFs, and only buy and hold had a 95 % interval for its Sharpe ratio above zero:

Strategy CAGR Sharpe Sharpe 95 % CI
buy_and_hold +7.49 % 0.63 0.07 to 1.27
momentum_rotation +5.29 % 0.49 -0.03 to 1.07
rsi +4.44 % 0.45 -0.13 to 1.10
ma_crossover +3.22 % 0.41 -0.17 to 1.11
pairs +0.85 % 0.21 -0.23 to 0.71
random +0.58 % 0.12 -0.40 to 0.69

The built-in strategies are examples of the engine, not edges. The report is generated, so make research rebuilds it, and the bars it read are cached with checksums so the rebuild runs offline. trading study SPEC runs any study described the same way: a base config, the walk-forward windows, and the strategies with their grids (docs/research/study.yaml).

Paper trading

export APCA_API_KEY_ID=...       # paper keys from the Alpaca dashboard
export APCA_API_SECRET_KEY=...

trading paper --symbols SPY --dry-run           # live bars, simulated fills
trading paper --symbols SPY,QQQ --strategy momentum_rotation --sizing percent --percent 50
trading paper --config my.yaml --timeframe 15Min --warmup 200
trading paper --config my.yaml --resume         # continue after a stop or a crash

The client only talks to Alpaca's paper endpoint. There is no way to point it at a live-money account.

Session settings live in the config file's paper section, so a deployed trader is described by one file. Options override it:

paper:
  timeframe: 15Min       # 1Min | 5Min | 15Min | 30Min | 1Hour | 1Day (--timeframe)
  warmup_bars: 200       # --warmup
  poll_seconds: null     # null = a quarter of a bar, between 5 and 60 s (--poll)
  settle_seconds: 5.0    # wait after a bar ends before treating it as complete
  feed: iex              # iex (free) | sip (subscription) (--feed)
  resume: false          # continue the latest session on the same symbols (--resume)

A session runs in four steps:

  1. Pre-flight. The paper account must be active. A new session must find no positions or open orders in the traded symbols, because the strategy starts flat with a virtual account of portfolio.starting_cash. A resumed session starts where the last one stopped instead (see below).
  2. Warm-up. The last --warmup completed bars go to the strategy and indicators only, never to the portfolio. Each symbol's last warm-up signal is then traded straight away, so the strategy starts in its current position: buy-and-hold buys at once, and a moving-average crossover above its slow average goes long without waiting for the next cross.
  3. Loop. Every --poll seconds it collects fills for working orders, then runs the bars that completed since the last loop through the pipeline, exactly as a backtest would. It follows Alpaca's market calendar. Only bars in regular trading hours are traded, so pre- and post-market bars and anything after an early close are skipped, as are weekends and holidays. Once the market has closed and its last bar is in, the trader sleeps until a minute before the next open.
  4. Stop. On SIGTERM or Ctrl-C, the trader finishes the step it is on, or wakes from its sleep, and stops; a second signal stops it at once. It also stops after --iterations loops. It then cancels its open orders and prints the session report, including what stopped it. Positions are left as they are, and so are their stop-losses and take-profits resting at the broker, which keep protecting them while the trader is down. docker stop and systemctl stop send SIGTERM, so give the trader a stop timeout of 30 seconds or more: resuming a session can take that long to cancel orders.

How orders reach the broker:

  • Each order carries a client order ID, so a retried request never places it twice.
  • One order per symbol is in flight at a time. A waiting order is resized for fills that arrived meanwhile, and never grows past what risk approved.
  • If a cancelled order fills further before the cancel takes effect, the order manager orders the difference back to the target once its replacement has finished, through the usual risk checks.
  • Stop-losses and take-profits rest at Alpaca, so they act within a bar and while the trader is down. A stop and a take-profit for one position go as a single one-cancels-other (OCO) order: when one fills, Alpaca cancels the other.
  • Alpaca holds the shares behind a resting exit, so while another order for the symbol is working, its exits come off the broker and are checked against each completed bar instead (once crossed, they exit at market). They rest again once the symbol is quiet. Exits Alpaca refuses are checked on completed bars for the rest of the session.
  • With daily bars, a bar completes at midnight New York time. The trader trades it a minute before the next open and Alpaca queues the order for the open, matching the backtest's next-open fills.
  • --dry-run runs the backtest's execution simulator on the live bars and sends nothing. --feed picks Alpaca's free iex data (the default) or paid sip data.

Each session is stored in SQLite as a run of kind paper (dry-run for dry runs).

Resuming a session

A trader that runs unattended gets restarted: after a deploy, a crash or a reboot. --resume (or paper.resume: true) continues the latest session stored for the same symbols instead of starting flat:

  1. Rebuild. The previous session's virtual cash and positions are rebuilt from where it started, plus every fill of its orders as the broker reports them. That includes fills the run store never saw, such as a stop that filled while the trader was down.
  2. Check. The rebuilt positions must match the paper account's, and every open order in the symbols must be the previous session's. If not, it refuses to start and changes nothing.
  3. Take over. The previous session's open orders are cancelled. The new session starts holding its positions at their average cost, and places their stop-losses and take-profits again. An ATR stop keeps its level, since the ATR it was set with is gone. The exits are back at the broker within a loop, usually a second or two.
  4. Carry on. The order manager takes up the targets the previous session was still working towards. A position already at its target sends nothing, so nothing is bought twice. An entry that a stop or a crash interrupted is completed. A position closed by a protective exit stays closed until the next signal, as in a backtest. Of the warm-up signals, only those from bars the previous session never saw are acted on.

With no earlier session it starts a new one, so a deployed trader can always run with --resume. Sessions chain through the resumed_from column of the runs table. Only one trader should work a given account and set of symbols at a time.

Safety limits

Two limits halt the trader. It winds down as it does on SIGTERM, reports halted, and exits with status 1:

  • Kill switch. Set paper.kill_switch to a file path. While that file exists, the trader refuses to start, and a running trader halts before its next step, which is at most poll_seconds away during market hours. Write a reason into the file and it is logged: echo "bad fills on the open" > data/KILL. Delete the file to trade again.
  • Daily order limit. paper.max_orders_per_day (default 200) caps the orders sent to the broker per trading day in the traded symbols, protective orders included; an OCO pair counts once. Orders sent earlier that day count too, read from the broker, so a restart does not reset the count. Once the cap is reached, new entry orders are refused and the trader halts, but stop-losses and take-profits are still placed. It refuses to start again until the next trading day.

risk.max_daily_loss_pct (see Risk limits) does not halt the trader: it refuses new exposure for the rest of the day, and backtests apply it too. A dry run sends no orders, so it ignores the kill switch and the order limit.

Logs and heartbeat

Logs go to stderr as text. With --log-format json, or TRADING_LOG_FORMAT=json in the environment (handy in a container), each line is a JSON object instead, ready for a log collector. Every line has time (UTC), level, logger and message. Lines from a paper session add its run_id. Lines about an event add event (fill, order, risk_veto, halt, heartbeat and so on) and the event's fields. A fill, shown here over several lines:

{"time": "2024-06-03T13:30:41.512+00:00", "level": "INFO", "logger": "trading.events",
 "message": "[Fill]       SPY 2024-05-31 04:00+00:00  O000001 BUY 100 @ 527.3700  comm=1.00",
 "run_id": "3f9c1e2a7b4d", "event": "fill", "timestamp": "2024-05-31T04:00:00+00:00",
 "symbol": "SPY", "fill_id": "F000001", "order_id": "O000001", "direction": "BUY",
 "quantity": 100, "fill_price": 527.37, "commission": 1.0}

Every paper.heartbeat_seconds (default 300), while trading and while asleep, the trader logs a heartbeat. It says whether the market is open, the bars traded and the last one, the virtual account's equity and positions, working orders, orders sent today, and broker requests that failed in a row. Set paper.heartbeat_file and each heartbeat also rewrites that file with the status as JSON. A last heartbeat records how the session ended: state is running while it runs, then stopped, halted or failed.

paper:
  heartbeat_seconds: 300               # null turns the heartbeat off
  heartbeat_file: data/heartbeat.json

The file's age tells a working trader from a stuck or dead one, overnight too. A health check can call the trader unhealthy once the file is older than twice heartbeat_seconds plus poll_seconds, or once state is no longer running:

find data/heartbeat.json -mmin -12 | grep -q . && grep -q '"state": "running"' data/heartbeat.json

Alerts

Set TRADING_ALERT_WEBHOOK to a webhook URL and the paper trader posts alerts to it:

  • fill: every fill, such as [paper 3f9c1e2a7b4d] Fill: BUY 100 SPY @ 527.37 (order O000001).
  • error: whatever it logs at ERROR, such as a halt, and the error that ended a session or stopped it from starting.
  • session: when a session starts trading, and when it ends, with its final status.
  • report: the daily comparison with a backtest, from trading compare --alert (see Paper against backtest).

paper.alert_on picks which to send (default: all four):

paper:
  alert_on: [error, session]   # no fill alerts

The URL is read from the environment only, never from the config file: it holds a secret, and the config is stored with every run. Each alert is a JSON POST. Its text field is what Slack-style incoming webhooks display (Discord offers one too: the webhook URL with /slack appended). kind, run_id, time and data (the fill's or the log line's fields) are there for anything else.

Alerts go out from a background thread, so a slow or broken webhook never holds up trading. A request that times out or gets a 429 or 5xx answer is tried twice more, and an alert that still fails is logged as a warning and dropped. When a session ends, the trader waits up to 10 seconds for queued alerts to go out. A dry run sends alerts too, labelled [dry run ...], so trading paper --dry-run --iterations 1 tests the webhook.

Paper against backtest

trading compare replays a paper session's bars through a backtest of the same config and compares the two, day by day. The backtest warms up on the same bars and starts in the same position, so where the two differ, the difference comes from trading on a real account:

  • prices: Alpaca's fills against the simulator's (the next bar's open, plus the configured slippage), in basis points, where positive means paper did worse;
  • fills on one side only, or for another quantity: orders that filled late, partly or never, and stops that triggered on one side only;
  • commissions, which the simulator charges and Alpaca does not;
  • downtime: bars missed while the trader was down are traded when it is back.
trading compare --config my.yaml                 # the latest paper session, its last day
trading compare --config my.yaml --day 2026-03-02 --json
trading compare --config my.yaml --alert         # also post the day's report to the webhook
$ trading compare --config my.yaml --day 2026-03-09
Paper session 3f9c1e2a7b4d: ma_crossover on SPY, 1Day bars
Backtest: the same config over the same 21 bar(s), after 40 warm-up bar(s)

2026-03-09
  equity      paper 100,207.11   backtest 100,253.55   gap -0.05%
  fill        SPY BUY     paper 100 @ 595.89       backtest 100 @ 595.42       +8.0 bps

Session to date: 2026-03-01 to 2026-03-21, 21 day(s)
  return      paper +1.99%   backtest +2.04%
  fills       1 matched, 0 only on paper, 0 only in the backtest, 0 with another quantity
  prices      +8.0 bps against the backtest (positive is worse); worst +8.0 bps, SPY BUY on 2026-03-09
  commission  paper 0.00   backtest 1.00
  tracking    0.19% a year (daily returns, paper - backtest)

A table of every day's equity follows. A resumed session is compared as a whole. --run picks an earlier session by its last run, and --db reads another run store. A dry run fills on the simulator, so it matches its backtest exactly. Sessions stored by earlier versions did not keep their warm-up bars, and their backtest starts cold.

With daily bars, a day is complete once the trader has traded its bar, a minute before the next open. Fills that came after the last complete bar are listed as pending until its day is in.

Running in Docker

compose.yaml runs the paper trader as a service:

cp .env.example .env              # fill in your Alpaca paper keys, and a webhook if you like
docker compose up -d --build
docker compose logs -f trader
docker compose ps                 # shows whether the trader is healthy
  • Secrets come from .env. Git ignores it, and .dockerignore keeps it out of the image, so the keys are neither in the repository, the image nor the config.
  • Settings come from config/paper.yaml: SPY, a 10/50 moving-average crossover on daily bars and a 5% stop-loss, to start from. config/ is mounted read-only; after editing it, docker compose restart trader.
  • State lives in the data volume at /data: the run store, the heartbeat file and the kill switch. paper.resume is on, so a new container carries on the last session.
  • Logs are JSON lines, and Docker keeps the last 5 × 10 MB of them.
  • Health. Every minute Compose runs trading health, which reads the heartbeat file. The container is unhealthy if the trader has stopped, halted or failed, or has not beaten for twice heartbeat_seconds plus a loop. Docker only reports it; restarting an unhealthy container takes a watcher such as autoheal.
  • Restarts. restart: unless-stopped brings the trader back after a crash or a reboot. A halted trader exits as well, and Docker restarts it, but it refuses to start until the halt clears: the kill switch file is gone, or a new trading day began for the order limit. Docker keeps trying, waiting longer each time. These refusals are logged as warnings and not alerted, so a halt is alerted once.
  • Stopping. docker compose stop sends SIGTERM and allows 60 seconds to wind down. To halt trading but keep the container: docker compose exec trader touch /data/KILL. To trade again, remove it with a one-off container, since a halted trader keeps restarting: docker compose run --rm --entrypoint rm trader /data/KILL.

The image alone runs any command, for example a backtest: docker build -t event-trading-system . then docker run --rm event-trading-system --bars 500 --no-db. Outside Docker, trading health --config my.yaml exits 0 if the trader is healthy and 1 if not.

The deployment guide takes it from a fresh cloud VM to a trader that runs unattended, with monitoring, backups and updates.

Configuration

Settings come from built-in defaults, then an optional YAML file (--config), then CLI flags. config/default.yaml lists every key with its default and comments.

simulation:    { symbols: [AAPL], data_source: synthetic, n_bars: 252, seed: 42 }
strategy:      { type: ma_crossover, fast_period: 5, slow_period: 20 }
order_manager: { sizing: fixed, quantity: 100, allow_short: false, order_type: market }
execution:     { slippage_bps: 1.0, spread_bps: 0.0, impact: 0.0, commission_per_share: 0.01 }
risk:          { max_position: 500, max_gross_leverage: 2.0, max_drawdown_pct: 10.0 }
exits:         { stop_loss_pct: null, take_profit_pct: null }
portfolio:     { starting_cash: 100000.0, margin_multiplier: 2.0 }
metrics:       { periods_per_year: null, risk_free_rate: 0.0 }  # null = infer from interval
persistence:   { enabled: true, db_path: trading.db }
paper:         { timeframe: 1Day, warmup_bars: 100, feed: iex, max_orders_per_day: 200 }

The config is validated: unknown keys, wrong types and inconsistent values are rejected with their location and a suggestion:

$ trading --config bad.yaml
trading: error: strategy.type: unknown strategy 'rsii' (did you mean 'rsi'?) ...

Metrics

Metrics are computed on the per-bar equity curve, annualised with periods_per_year (inferred: 252 for daily bars, 52 for weekly, and so on). The benchmark is the buy and hold: equal amounts of every symbol bought at its first close (a symbol not trading yet counts as cash), valued at each bar's close. Excess returns are over metrics.risk_free_rate.

Metric Definition
Total return / CAGR Final over starting equity; CAGR compounds over bars / periods_per_year years
Buy & hold Equal-weight buy-and-hold of every symbol, first close to last close
Volatility Sample std. dev. of per-bar returns × √periods_per_year
Sharpe / Sortino Mean excess return over std. dev. (Sortino: downside deviation only), annualised
Max drawdown Deepest peak-to-trough fall, and the longest stretch spent below a prior peak
Calmar CAGR / max drawdown
Beta Covariance of per-bar returns with the buy-and-hold benchmark's, over its variance
Alpha Jensen's alpha, annualised: mean excess return minus beta × the benchmark's
Tracking error Std. dev. of per-bar returns minus the benchmark's, annualised
Information ratio Mean return in excess of the benchmark's, over the tracking error
Skewness / kurtosis Of per-bar returns, kurtosis not excess (JSON only)
Round trips / win rate Trades from flat to flat (flips split into two), net of commission
Profit factor Gross profit / gross loss over round trips
Exposure Share of bars with any open position
Turnover Traded notional / average equity
Risk vetoes Orders the risk manager refused

Portfolio runs add a per-symbol breakdown: net P&L, round trips, win rate, fills and the symbol's own buy-and-hold return.

Persistence

Each run writes to SQLite (--db PATH, --no-db to disable). The runs table holds the config and final report as JSON, and its kind column says whether the run was a backtest, a paper session or a dry-run; a resumed paper session names the one it continued in resumed_from. Every other event table is keyed by run_id, including targets, which records the order manager's target position for each symbol, cash_flows, the interest and borrow fees paid, and warmup_bars, the bars a paper session warmed up on. A backtest is a single transaction, so a crash leaves nothing behind; a paper session commits as it goes. Sweeps and walk-forward runs go to the sweeps and sweep_results tables.

-- Compare runs
SELECT run_id, kind, strategy, json_extract(report_json, '$.sharpe_ratio') AS sharpe
FROM runs ORDER BY started_at DESC;

-- Fills of the latest run
SELECT timestamp, symbol, direction, quantity, fill_price FROM fills
WHERE run_id = (SELECT run_id FROM runs ORDER BY started_at DESC LIMIT 1);

Development

make install     # pip install -e ".[dev]" and pre-commit hooks
make check       # ruff + strict mypy + tests with coverage (what CI runs)
make docs        # build the documentation site into site/ (make docs-serve to preview)
make bench       # backtest throughput, in bars a second
make demo        # regenerate docs/images/backtest.png

The documentation site adds a tutorial, an architecture guide, a reference of every config key and the API reference to this README. CI builds it on every pull request; on main it also measures coverage (the badge above) and throughput (Benchmarks), and deploys it. RELEASING.md explains how releases reach PyPI. What counts as public API, and how it is deprecated, is in Stability.

Without make: ruff check . && ruff format --check . && mypy && pytest --cov.

The tests aim at the properties a backtest must not violate, not just per-unit behaviour:

  • Causality. No fill is earlier than its order, orders fill on a later bar, and the strategy never sees future bars.
  • Accounting invariants. On every bar of every strategy (long-only and long/short), equity == cash + Σ position × close. Cash reconciles exactly with the fill history.
  • Property-based tests (Hypothesis). For random fill sequences, realized + unrealized P&L equals the cash-flow P&L.
  • Reference values. RSI matches Wilder's published worked example.
  • Paper trading end to end against a fake broker and a clock that moves only when the trader sleeps, so multi-day sessions run in milliseconds.
  • Regression tests for each bug fix listed in the changelog.

Layout

src/trading/
├── backtest/engine.py         # pipeline wiring and the slice-by-slice event loop
├── bus/event_bus.py           # FIFO, breadth-first pub/sub
├── events/types.py            # every event type
├── market_data/               # feeds, download cache, calendars, slice merging, state
├── signal/                    # strategy bases, indicators, built-in strategies, registry
├── order_manager/             # target-position sizing, protective exits
├── risk/manager.py            # pre-trade limits
├── execution/simulator.py     # fills from OHLCV bars: order types, slippage, volume caps
├── portfolio/                 # position accounting, PortfolioTracker
├── metrics/                   # pure stats, round-trip trades, report
├── research/                  # parameter grids, sweeps, walk-forward, studies
├── live/                      # Alpaca client, broker execution, paper trader, alerts
├── persistence/               # SQLite schema, run and sweep storage
├── visualization/chart.py
├── logger/                    # event log lines, JSON log format
├── config.py                  # typed, validated configuration
└── cli.py                     # the trading command

Limitations

These are deliberate scope limits, not oversights:

  • Bars only: no tick data or order book. Fills are inferred from OHLC bars, so the order of events within a bar is assumed (stops before take-profits).
  • No maintenance margin. Buying power is checked when an order arrives, but a position is never liquidated when equity falls.
  • Yahoo Finance data is split/dividend-adjusted and unofficial. Use CSV for data you control.
  • A resumed paper session cancels and replaces the previous session's exits, leaving its positions without them for a second or two. Its realized P&L and trade statistics start afresh, and its drawdown is measured from the equity it resumed with.
  • Alpaca bars are unadjusted, so a split during warm-up or a session distorts indicators.

The roadmap tracks what comes next.

Contributing

Issues and pull requests are welcome; CONTRIBUTING.md explains the setup and what a change needs. Report security problems privately, as SECURITY.md describes.

License

MIT. See LICENSE.

Metadata

Release files for event-trading-system 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for event-trading-system 1.0.0
File Size Uploaded Provenance Actions
event_trading_system-1.0.0.tar.gz 293.2 kB With provenance Details for event_trading_system-1.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for event-trading-system 1.0.0
File Interpreter ABI Platform Actions
event_trading_system-1.0.0-py3-none-any.whl Python 3 none any Details for event_trading_system-1.0.0-py3-none-any.whl

Total release size: 469.9 kB

Release files / event_trading_system-1.0.0.tar.gz

Download URL event_trading_system-1.0.0.tar.gz
Size 293.2 kB
Tags Source
SHA-256 checksum
How to use checksums
075d44582ab5364fa41f143a7432d22cbd510429e1d1014f9cd64a75e169c90d
BLAKE2b-256 checksum
How to use checksums
e0acae57b450e469031f118a4b55d402eeaabace9bbe5f80739592bbfdc93a47
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 6, 2026.

Transparency log

Release files / event_trading_system-1.0.0-py3-none-any.whl

Download URL event_trading_system-1.0.0-py3-none-any.whl
Size 176.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
56383a3a34161debcf5517d1e50b75c2a58a982d34b28898271df23428878aab
BLAKE2b-256 checksum
How to use checksums
84600be040ba3e4d715890ec67cbc497fa13788cdcb4d0a3e6f87b5568bd448e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 6, 2026.

Transparency log

Security for event-trading-system 1.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for event_trading_system-1.0.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 6, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.0.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page