---
title: Formal Candle-Based Backtesting Models
url: https://www.emergentmind.com/topics/formal-candle-based-backtesting-models
type: topic
---

# Formal Candle-Based Backtesting Models

Formal candle-based backtesting models constitute a rigorous framework for evaluating trading systems using only discretely sampled candlestick data. These models specify not only the mathematical structure of candle data and its relation to the underlying continuous-time price evolution but also algorithmic strategies for ambiguity resolution, correctness proofs, and finite, constructive verification procedures. The paradigm enables robust, reproducible comparisons of trading strategy performance on historical data streams by making order execution, position sizing, and outcomes mathematically explicit and formally verifiable.

## 1. Mathematical Definition of Candle Data and Order-Signal Mapping

A candle, or bar, for a time interval $[a,b]$ is defined as the 4-tuple $C = (\mathrm{open},\mathrm{close},\mathrm{high},\mathrm{low}) \in (\mathbb{R}^+)^4$ such that
$$
\mathrm{low} \leq \min\{\mathrm{open}, \mathrm{close}\} \leq \max\{\mathrm{open}, \mathrm{close}\} \leq \mathrm{high}
$$
[1509.08248][1412.5558]. Every continuous intra-period price function $f \in C([a,b], \mathbb{R}^+)$ induces a candle
$$
C(f) = (f(a), f(b), \max_{t \in [a,b]} f(t), \min_{t \in [a,b]} f(t))
$$
This formalism posits continuity of intra-period price paths and absence of jumps, an assumption adopted for the unambiguous generation of candles from price trajectories.

Order signals are generated from past information sets $I_t$ by deterministic or indicator-driven functions:
- **Entry-signal**: $E_t = E(I_{t-1})$, representing market, limit, stop, or composite orders.
- **Exit-signal**: $X_t = X(I_{t-1})$, encoding market exits, stop-loss, or take-profit conditions.

The backtest result for a path $f$ is a tuple $R(f) = (\text{entry}_f, \text{exit}_f) \in (\mathbb{R}^+ \cup \{ -1 \})^2$ representing realized execution prices or indicating no trade, and the full candle-result pair is $CR(f) = (C(f), R(f))$ [1509.08248].

## 2. Intra-Period Price Models and Execution Semantics

Within the resolution interval, the intra-period price is modeled as a continuous function $f: [a, b] \to \mathbb{R}^+$, precluding intra-period gaps, with liquidity being perfect (i.e., orders are always filled when touched, with no partial or missed executions) [1412.5558]. The execution semantics for standard order types are as follows:
- **Market order**: executed at open price $O_t$ of candle $t$.
- **Limit buy at $\ell^*$**: filled if $L_t \leq \ell^* \leq H_t$, at price $\ell^*$.
- **Stop buy at $b^*$**: activated if $L_t \leq b^* \leq H_t$, with fill at $b^*$.
- **Stop-limit buy $(b^*, \ell^*)$**: order activates at first $P_t(u) = b^*$, then fills limit at first $P_t(u) = \ell^*$.

Positions, P&L, and position sizing are handled as follows:
$$
\Pi = Q \cdot (p_{\rm exit} - p_{\rm entry}), \quad Q = \frac{R\,C_{\rm current}}{p_{\rm entry} - s^*}
$$
where $Q$ is the size determined by risk $R$, current equity $C_{\rm current}$, and stop-loss $s^*$ [1412.5558].

## 3. Model Candles, IPMS, and the Reduction to Finite Verification

To rigorously verify backtest engines, the infinite space of possible intra-period price paths is discretized via **model candles** and **Intra-Period Model Price Series (IPMS)** constructions [1509.08248]:
- **Order levels**: Given $m$ user-defined price levels $L_1 < \cdots < L_m$, construct an extended grid $\{l_0, ..., l_{2m}\}$ by inserting intermediate points between order levels.
- **Model candles**: All 4-tuples $(o, c, h, l)$ where each component is a grid point and the tuple respects candle ordering.
- **IPMS**: Finite sequences $s = (l_{i_1}, ..., l_{i_k})$ with adjacent indices differing by $\pm1$, interpreted as piecewise-linear interpolations.

The **main correctness theorem** (Theorem 3.8 in [1509.08248]) asserts that if a backtest engine $E$ is stable under strictly increasing bijections $T: \mathbb{R}^+ \to \mathbb{R}^+$ (i.e., transformation of price scale), then if $E$ yields correct results on all model candles, $E$ is correct for all continuous intra-period price functions and underlying candles for a given order setup. The proof leverages the transform-invariant reduction to a finite test set.

## 4. Ambiguities and Systematic Resolution Strategies

Ambiguous situations, termed **SNUs** (Situations Not Uniquely decidable), arise due to the loss of intra-candle sequencing information:
- E.g., Limit buy and target violated in same candle: was the target reached after fill or before order activation?
- Situations where stop-loss and target are both touched within the bar.

Resolution strategies, selectable per backtest execution, include [1412.5558]:
- **Worst-case (wc)**: Assign the least favorable execution or sequence.
- **Best-case (bc)**: Assign the most favorable outcome.
- **Ignore (ig)**: Discard the ambiguous trade.
- **Exact (ex)**: Consult tick-level data for unique disambiguation (when available).

Resolution is codified:
```python
function resolve_SNU(situation, mode):
    if mode == "ex":
        load_tick_data()
        return determine_exactly()
    if mode == "ig":
        return SKIP_TRADE
    outcomes = enumerate_possible_fill_sequences(situation)
    if mode == "wc":
        return worst_outcome(outcomes)
    else:  # bc
        return best_outcome(outcomes)
```
This parametrization enables both conservative and aggressive backtest statistics.

## 5. Algorithmic Implementation and Complexity Considerations

A formal algorithmic implementation iteratively processes candles, evaluating signals, resolving ambiguities, and updating capital per trade [1412.5558]. For engines seeking proof of correctness, the process is as follows [1509.08248]:
- Initialize a mapping from candle-result pairs to IPMS.
- For each IPMS sequence of increasing length, simulate the reference engine and store novel CR pairs.
- Stopping criterion: When $\mathcal{M}_n = \mathcal{M}_{n+1}$, all additional sequences yield only previously observed candle-results.

This algorithm reduces an infinite verification problem to a finite suite, with worst-case complexity $O((2m)^4)$ for combinatorial model candles, but practical runtime is reduced by equivalence pruning (Remark 4.11 in [1509.08248]).

## 6. Representative Examples and Edge Cases

The framework captures and systematically resolves challenging cases:
- **Limit Buy + Stop-Loss + Target**: When both exit levels are touched in the same candle, the realized outcome is determined by the user-selected ambiguity resolution mode.
- **Stop-Limit Entry + Target**: For concurrent activation and limit fill conditions overlapping with exit criteria, possible outcomes are enumerated and the most or least favorable selected as required.
- **Market Order at Open**: When stop condition lies below open, fill is immediate at open, with no ambiguity.

All such cases demonstrate the formal approach's capacity to manage the full range of ambiguous candlestick scenarios, providing explicit formulas for profit/loss and position management [1412.5558].

## 7. Significance, Applications, and Extensions

The formal models developed in [1509.08248] and [1412.5558] provide a theoretically closed method to validate backtest engines operating on candlestick data. By proving that correct operation on all model candles ensures correctness on all real data, they establish a finite, constructive route to engine verification under the assumptions of continuity, local decision-making, and transformation-stability.

Applications include trading platform engine validation, systematic trading system prototyping, and regulatory audits. Although current results address the one-entry, one-exit scenario per period, the underlying methodology (grid discretization, IPMS, transformation-stability, finite termination) directly suggests plausible extensions to more complex order configurations and multi-instrument setups.

Key insights include the reduction of an analytically intractable infinite path space to a demonstrably finite and algorithmically accessible problem, transforming platform validation from an empirical to a rigorously provable process [1509.08248].

Source: https://www.emergentmind.com/topics/formal-candle-based-backtesting-models