Skip to content

About

A cli-tool agent-friendly to backtest trading strategies or ideas fast and easilly

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Backtest Engine

A small, deterministic Python CLI for checking trading-strategy ideas against historical OHLCV candles. It is designed for scripts and LLM-generated strategies (agents can use this tool), while keeping the simulation rules explicit and testable.

The engine is reliable for the bar-based model described below. It is not an exchange simulator or investment advice.

What it does

  • Loads validated chronological OHLCV CSV data and optionally resamples it.
  • Runs one custom Python Strategy against each completed candle.
  • Queues strategy orders at candle close and fills them at the next candle's open.
  • Simulates one net long or short position with configurable commission and slippage.
  • Reports net P&L, win rate, rejected orders, and maximum drawdown from marked-to-market equity.
  • Exports a versioned JSON result containing the report, equity curve, fills, positions, and rejected orders.

Dashboard

alt text

alt text

alt text

Quick start

Python 3.10 or newer is required.

python -m venv .venv
source .venv/bin/activate
python -m pip install -e .

backtest-engine \
  --data examples/sample_ohlcv_m1.csv \
  --strategy scripts/test_strategy.py \
  --timeframe M1 \
  --output results/sample_result.json

The example signals a long after the second candle and a close after the fifth; those orders fill at the following candle opens. If you do not install the console command, replace backtest-engine with python main.py.

To create a separate local fixture, run python generate_test_data.py; it creates dat/test_data.csv.

CSV contract

The CSV must contain one of timestamp, date, time, or datetime, plus these required numeric columns:

timestamp,open,high,low,close

volume is optional and defaults to zero. Data is converted to UTC and must have strictly increasing, unique timestamps. OHLC values must be finite and positive, with low <= open/close <= high.

Timestamps represent the start of each source candle. For example, a row timestamped 00:05 is the candle that opens at 00:05. A strategy receives that completed candle after its close; an order submitted from it fills at the next row's open.

Timeframes

--timeframe is optional. Without it, the supplied candles are used as-is. Named options are M1, M5, M15, M30, H1, H4, and D1; fixed pandas offsets such as 15min and 1h also work.

The target must be a whole multiple of the source interval. The loader checks grid alignment and drops bins with missing candles. Set source_timeframe in the JSON config to declare the input cadence. Otherwise the loader uses the most frequent observed spacing, taking the shortest in a tie. A single as-is row needs an explicit cadence for a distinct close time. Numeric Unix timestamps require timestamp_unit set to s, ms, us, or ns.

For session-based instruments, set session_calendar to a CSV path and request D1. Supply sorted, non-overlapping open,close timestamp pairs, one continuous interval per trading session. Use UTC or explicit offsets, including holiday and DST adjustments. The loader includes candles from session open up to the scheduled close, excludes outside rows, and drops incomplete sessions. Convert close-labeled vendor candles to start labels before loading.

Configuration

config.json is used by default. Pass --config path/to/config.json to use another file.

{
  "initial_balance": 100000.0,
  "leverage": 500.0,
  "slippage": 0.0001,
  "commission": 0.0002
}
  • initial_balance: starting account equity; must be greater than zero.
  • leverage: used for the entry affordability check: notional / leverage + entry_fee <= cash.
  • slippage: decimal adverse price adjustment per fill. 0.0001 is 1 basis point (0.01%).
  • commission: decimal fee charged on each fill. 0.0002 is 2 basis points (0.02%).

Commission and slippage range from zero inclusive to one exclusive. Two optional config fields control sizing and risk.

  • entry_equity_fraction sizes quantity-free buy() and sell() calls at the fill price. For example, 0.5 targets notional equal to half the cash remaining after entry commission. Explicit quantities take precedence. The default is one unit. The report's peak_entry_leverage is the highest filled entry notional divided by pre-entry equity.

  • maintenance_margin_rate enables liquidation when estimated exit equity is at or below the configured fraction of marked notional. For example, 0.05 sets a 5% threshold. Checks occur at each open before pending orders, immediately after a fill, and at each close. A breach cancels any pending order and closes at the observed price with normal costs. Gaps can leave debt and an insolvent account cannot fund another entry. Omit the field for the original entry-only margin model.

  • funding_rates charges perpetual-futures funding. Set it to a CSV with timestamp and rate columns, one row per settlement in UTC, with the rate as a decimal (0.0001 is 0.01%). At each candle open the engine settles every row dated after the previous open and up to this one, before filling a queued order. A long pays size * open * rate and a short receives it, so a negative rate pays the long. A position opened at a settlement time is not charged for it, and one closed there is. Positions report fundingPaid, their pnl is net of it, and the report totals it in funding_paid. Strategies can read the latest settled rate as broker.last_funding_rate. scripts/download_binance_futures.py writes this file for Binance USDT-margined perpetuals.

Strategy contract

The strategy path must be a Python module exposing a Strategy class. It receives the broker in its constructor and implements update(current_candle). Inheriting BaseStrategy is recommended but not required.

from strategies.base import BaseStrategy


class Strategy(BaseStrategy):
    def __init__(self, broker):
        super().__init__(broker)
        self.candle_count = 0

    def update(self, current_candle):
        self.candle_count += 1

        if self.candle_count == 2:
            self.broker.buy(size=1.0)
        elif self.candle_count == 5:
            self.broker.close_position()

current_candle is a pandas Series containing open, high, low, close, and volume; its name is the UTC bar start. During update, broker.current_time is the decision time at the bar close. BTC V2–V5 use the signal bar's start hour, so a signal on the 21:55 M5 bar can fill at 22:00.

Broker API

  • buy(size): queue a long entry for the next candle open. If currently short, it closes the short and opens the requested long at that open.
  • sell(size): queue a short entry for the next candle open. If currently long, it closes the long and opens the requested short at that open.
  • close_position(): queue a close for the next candle open.
  • has_open_position(): whether a position is currently open.
  • has_pending_order(): whether an order is waiting for the next candle.
  • current_balance: marked-to-market account equity, including unrealized P&L and estimated exit fees. It is not cash alone.

Only one pending order is allowed. A final-candle signal is rejected because no subsequent candle open exists. Any already-open position is automatically closed at the final candle close so the final report is realized. size is quantity in the instrument's base units (for example, BTC for a BTC/USDT series).

Result JSON

--output writes a native, versioned Backtest Engine result. Parent directories are created automatically.

schemaVersion
backtest.metadata          # effective config, input and strategy source hashes, timeframe
backtest.report
backtest.equityCurve       # UTC Unix seconds and marked-to-market equity
trade.tradeHistory         # fills with execution time and, for queued orders, submission time and signal bar start
trade.finishedPositions    # net P&L includes entry and exit fees
trade.rejectedOrders

In new reports, strategySources contains the SHA-256 of the entry script bytes compiled for the run. baseFilesOnDisk records file snapshots for imported strategy classes. Python can reuse imported modules within a process.

This schema is intentionally documented as the engine's own format. It is not advertised as compatible with another tool unless an importer test is added for that tool's pinned schema version.

Simulation assumptions and limits

  • This is a bar-based market-order simulator. It does not model intrabar order priority, limit/stop orders, partial fills, spreads, or market impact.
  • Slippage is a fixed adverse percentage. Commission is charged on both entry and exit.
  • Drawdown is calculated from candle-close marked-to-market equity. It cannot show a path inside an OHLC candle; use finer-grained data when that matters.
  • Margin checks observe opens and closes. Venue-specific liquidation tiers, intrabar margin calls and contract multipliers require a separate instrument model. Funding is settled at the candle open with that open as the mark price, and only when funding_rates is set.

For strategy viability, use data and costs representative of the venue, test out-of-sample periods, and treat results as a research signal rather than a guarantee.

Frozen BTC pullback comparison

From the project root, run the frozen V5 parameters on contiguous full UTC days after the original selection period. This example uses the local BTC/USDT minute candles from Binance spot, May through October 2026.

python -m scripts.evaluate_pullback --data data/btcusdt_binance_m1_2026_05_to_10.csv --output results/pullback_forward_may_oct_2026.json

The comparison runs at 2 and 4 bp commission per fill, with 1 bp slippage. Each of 500 seeded controls randomizes entry times within the signal window while matching V5's realized trading dates, daily counts, holding period, and quantity. This tests timing conditional on trading those days. The JSON includes monthly net P&L, the control median, and the number of controls V5 beat.

Testing

python -m unittest discover -v

The regression suite covers next-open execution, fee-inclusive trade P&L, marked-to-market drawdown, CSV validation and resampling, JSON output, CLI failures, and fixture generation.

Safety for agent-generated strategies

Strategy modules are executed as normal Python code in the current process. Run only trusted strategies. If an LLM or another user generates code you have not reviewed, execute the engine in an isolated environment with no credentials or sensitive files.

Research dashboard

A private, dependency-free web dashboard ships in dashboard/. It binds only to the loopback interface.

.venv/bin/python -m dashboard            # http://127.0.0.1:8765/
.venv/bin/python -m dashboard --port 9000
  • Strategies lists every strategy file, its header, the hypothesis with its linked research note, and each class/version with effective parameters.
  • Results shows detailed statistics for any engine result under results/, including CAGR, Sharpe, Sortino, profit factor, exposure, streaks, and monthly returns. It also charts equity, drawdown, and price candles with trade markers, plus the position ledger.
  • Compare groups results by symbol and overlays normalized equity and drawdown. It flags runs whose period, timeframe, costs, or sizing differ.
  • Run launches backtests of any named class in a strategy file via python -m dashboard.runner, writing to results/dashboard/<SYMBOL>/, and runs the unittest suite with a live log.
  • Research renders the notes in trading-research-findings/.

Symbols come from the result metadata, a symbol CSV column, or the data filename. Results produced before metadata export show "no metadata"; choose their data file manually to draw the price chart.

About

A cli-tool agent-friendly to backtest trading strategies or ideas fast and easilly

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages