Skip to main content

XXSim

Exchange Execution Simulator — simulates order execution against OHLCV candlebar data.

Disclaimer

Own risk warning — Execution prices are best estimations based on worst-case scenarios and statistics. There will be price differences between simulations and real-world execution. By using this package the user acknowledges consent and takes full responsibility for any implications caused by errors or misinterpretation of results.

The challenge

The golden standard of market data comes in OHLCV candlebars (1-min, 5-min, daily, etc.). Within each bar, the intra-bar price path is unknown. Fill prices depend on rules and order formations that are hard to simulate exactly.

The solution

XXSim reconstructs a plausible intra-bar price path from OHLC data and evaluates orders against it, producing realistic fill prices within statistical uncertainty.

Supported order types

  • MarketOrder
  • LimitOrder
  • StopOrder
  • StopLimitOrder
  • TrailingStopMarket
  • TrailingStopLimit
  • MarketOnCloseOrder (MOC) — fills at bar.close only on bars where BarData.is_close_bar=True

Not supported

  • Limit-on-Close (LOC)
  • Market-if-Touched (MIT)

Order modifiers

Fields that modify order behavior without changing the order type:

Field Description
tif Time-in-force: GTC (default), DAY (expires on date change), GTD (expires after goodTillDate)
goodTillDate Expiry datetime for GTD orders — format '%Y%m%d %H:%M:%S <timezone>'
goodAfterTime Order inactive until this datetime — format '%Y%m%d %H:%M:%S <timezone>', timezone is mandatory
ocaGroup One-Cancels-All group name — when one order in the group fills, the rest are cancelled

Execution algorithm assumptions

  • No partial fills — orders fill entirely or not at all
  • Aggressive approach — order fills if there is any plausible price path through the bar that would trigger it
  • Intra-bar price path for trailing stops:
    • Bullish bar (close > open): open → low → high → close
    • Bearish bar (close ≤ open): open → high → low → close
  • Optional fill drift — volatility-based normal distribution drift, configurable via SimulatorConfig:
    • fill_drift_model="none" (default): deterministic fills at exact price
    • fill_drift_model="normal": drift drawn from N(0, bar_range / std_divider)
    • Result always clamped to [bar.low, bar.high]
    • Use random_seed for reproducible backtests

Installation

pip install XXSim

Usage

Single-Bar Execution

from XXSim import ExecutionEngine
from xtrading_models import MarketOrder, BarData
from datetime import datetime

engine = ExecutionEngine()
bar = BarData(
    date=datetime(2025, 1, 1, 9, 30),
    open=100.00, high=105.00, low=95.00, close=102.00, volume=1000000,
)
order = MarketOrder(action='BUY', totalQuantity=100)
fills = engine.execute(order, bar)
print(fills)

Multi-Bar Simulation

from XXSim import Simulator, SimulatorConfig
from xtrading_models import MarketOrder, LimitOrder

sim = Simulator()

# Register callbacks
sim.on_fill(lambda trade, fill: print(f"Filled: {fill.execution.price}"))
sim.on_cancel(lambda trade: print(f"Cancelled: {trade.log[-1].message}"))

# Submit orders
sim.submit_order(MarketOrder(action='BUY', totalQuantity=100))
sim.submit_order(LimitOrder(action='SELL', totalQuantity=100, price=110.0))

# Process bars
for bar in historical_bars:
    fills = sim.process_bar(bar)

Bracket Orders

from xtrading_models import MarketOrder, StopOrder, LimitOrder

entry = MarketOrder(action='BUY', totalQuantity=100)
stop_loss = StopOrder(action='SELL', totalQuantity=100, price=95.0)
take_profit = LimitOrder(action='SELL', totalQuantity=100, price=110.0)

entry.add_child(stop_loss)
entry.add_child(take_profit)

trade = sim.submit_order(entry)

The Simulator supports:

  • Bracket orders: child orders activate when parent fills
  • Callbacks: on_fill, on_cancel, on_status, on_bar
  • SimulatorEvent: enum of all event names (fill, cancel, status, bar) — use instead of raw strings when subscribing via EventEmitter directly

Development

Running Tests

pytest tests/ -v

Visualizations

Stop-limit and trailing test cases can be visualized:

python docs/stop-limit-chart-generator.py test-data/stop-limit/<filename.csv>
python docs/trailing-stop-chart-generator.py test-data/trailing-stop/<filename.csv>

Contributing

Contributions are welcome! Please see the documentation in the docs folder for algorithm details and test specifications.

Metadata

Release files for XXSim 0.23.1

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

Source distribution (sdist)

Source distribution for XXSim 0.23.1
File Size Uploaded Provenance Actions
xxsim-0.23.1.tar.gz 47.7 kB Without provenance Details for xxsim-0.23.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for XXSim 0.23.1
File Interpreter ABI Platform Actions
xxsim-0.23.1-py3-none-any.whl Python 3 none any Details for xxsim-0.23.1-py3-none-any.whl

Total release size: 68.4 kB

Release files / xxsim-0.23.1.tar.gz

Download URL xxsim-0.23.1.tar.gz
Size 47.7 kB
Tags Source
SHA-256 checksum
How to use checksums
d423d4e0b86caa45fbb336828e7b4d1a446f0684b94c9bb735794908ba4372b4
BLAKE2b-256 checksum
How to use checksums
8e15219b3968e97ef90331b738e0b026f907f4ea533ab265e969570b63198714
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.13

Release files / xxsim-0.23.1-py3-none-any.whl

Download URL xxsim-0.23.1-py3-none-any.whl
Size 20.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
2c033a2ddc4d50f40f67f4a750844da0be6ee229e3ab871033129f0e2d927095
BLAKE2b-256 checksum
How to use checksums
36bcb883ac34fd5630ecbedca4dedb89c385b7c7a7ff63ec15c077e9427b6eb0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.13

Security for XXSim 0.23.1

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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

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

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