No connection — showing the last data Kvants received
← All posts

Trading Strategy Rules: How to Write a Testable Specification

October 28, 2026·11 min·strategy rules
MBMarco BianchiTrading Systems Analyst · Europe
Trading Strategy Rules: How to Write a Testable Specification
Share

Learn how to write trading strategy rules for market selection, entries, exits, risk, order handling, and edge cases—then check whether the specification is ready to test.

Quick Answer

Effective trading strategy rules specify exactly what can be known at the decision time, what conditions create a signal, which order is submitted, how risk is sized, and what closes the position. They must also cover timing, costs, overlapping signals, and ambiguous situations.

A useful test is whether another trader could implement the strategy without asking what you meant. Clear rules do not make a strategy effective by themselves; they make it possible to test whether it has merit.

Key Takeaways

  • Separate the market idea from its implementation and performance.
  • Define every indicator, threshold, timeframe, and decision time explicitly.
  • Distinguish a signal from the order and fill that follow it.
  • Set position sizing and exit rules before examining results.
  • Resolve missing data, price gaps, conflicting exits, and repeated signals in advance.
  • Treat the first backtest as a specification audit, not proof of an edge.

What Complete Trading Strategy Rules Must Define

A statement such as “buy strong breakouts with high volume” describes an idea, not a complete strategy. “Strong,” “breakout,” and “high volume” can each be interpreted several ways.

A testable specification needs six components:

  1. Research universe: The instruments, exchanges, sessions, and data frequency included.
  2. Setup: The market state that makes a trade eligible.
  3. Trigger: The observable event that generates a signal.
  4. Execution: The order type, submission time, fill assumptions, and cancellation rules.
  5. Risk and exits: Position size, initial risk, profit-taking, trailing logic, and time exits.
  6. Portfolio constraints: Limits on simultaneous positions, total exposure, and repeated entries.

These components should be written without relying on phrases such as “near resistance,” “healthy trend,” or “enough confirmation.” If judgment remains part of the method, identify the judgment explicitly rather than disguising it as an objective rule.

The Deploy dialog for a strategy: you choose a venue from thirteen options, pick paper or live mode, set paper capital, and cap max leverage, max drawdown percent and max positions before deploying. A note explains live mode runs through the validation gate first and refuses deployment with reasons surfaced if any gate fails.

Deploying a strategy to paper or live with a pre-flight gate.

A Step-by-Step Strategy Specification Workflow

1. Freeze the market scope

Start by defining where the strategy is allowed to operate:

  • Asset class and eligible symbols
  • Chart interval and required data fields
  • Trading session and time zone
  • Long, short, or both directions
  • Liquidity or price filters
  • Dates or events that are excluded

Session boundaries matter. A rule based on the “daily high” can produce different signals depending on whether a day means a calendar day, an exchange session, or regular trading hours.

Avoid designing rules around today’s list of successful instruments. A historical universe that includes only current constituents can introduce survivorship bias.

2. Define indicators mathematically

Document the input and calculation for every indicator. “Price above the moving average” is incomplete without the following details:

  • Moving-average type
  • Lookback length
  • Price input
  • Chart interval
  • Whether the current or previous completed value is used

For example:

The trend filter is true when the previous completed hourly close is above the 50-period exponential moving average calculated from hourly closing prices.

This wording fixes the data, lookback, timing, and comparison.

3. Separate the setup from the trigger

A setup describes eligibility. A trigger creates the signal.

For a breakout system, the setup might require an established range and above-average liquidity. The trigger might be the first completed close above the range high.

This separation prevents a common implementation error: entering merely because the setup exists. It also makes diagnostics more useful because you can investigate whether a problem comes from market selection, setup quality, or entry timing.

4. State when information becomes available

A strategy cannot act on a bar’s closing value before that bar closes. If a signal requires the closing price, the earliest ordinary execution opportunity is after the close has been observed.

Write the sequence explicitly:

  1. Evaluate the condition when the bar closes.
  2. Generate the signal if all conditions are true.
  3. Submit the order at the next permitted event.
  4. Apply the defined fill model.

This prevents look-ahead bias and exposes whether the intended entry depends on information that was not yet available.

5. Convert the signal into an order

The signal does not determine the execution price. Define:

  • Market, limit, stop, or stop-limit order
  • Submission time
  • Limit or stop price
  • Time in force
  • Partial-fill treatment
  • Cancellation or expiration condition
  • Behavior when price gaps through the requested level

“Enter on the next bar” remains ambiguous. Does it mean the next open, a market order processed after the open, or a limit order available throughout the bar? Each choice can produce different trades.

6. Define risk and position sizing

Choose the invalidation rule before choosing position size. For fixed-risk sizing, a basic long-position calculation is:

Position size = Maximum planned trade risk / (Entry price − Stop price)

The practical calculation may also need to account for fees, expected slippage, contract multipliers, tick size, lot increments, and minimum order quantities.

Add portfolio-level constraints as well. A strategy can size each position conservatively while still accumulating excessive exposure through correlated or simultaneous trades.

7. Define every exit and its priority

Specify the initial stop, profit target, trailing rule, time exit, and any signal-based exit. Then state what happens when multiple exit conditions occur together.

Questions to resolve include:

  • Can the stop move, and if so, when?
  • Can a stop ever be widened?
  • Is the target based on entry price or actual average fill?
  • What happens if both stop and target are touched in one bar?
  • Are positions closed before the session ends?
  • Does an opposite signal close, reverse, or leave the position unchanged?

If the available data cannot reveal which intrabar event happened first, use finer data or a conservative assumption. Do not silently select the favorable outcome.

The Strategy Studio editor showing a compiled momentum-crossover strategy: a header names the strategy with Save, Templates, Deploy, Backtest, Competition and Import Pine actions and metric tiles for Sharpe, win rate, max drawdown and live status, while a structured readout lists the price feed, indicators (EMA 12, EMA 26, RSI 14), the crossover condition, AND logic, long entry and exit signals, position sizing, stop-loss and take-profit risk, and market execution with slippage.

A strategy laid out end to end in the Kvants editor.

Worked Example: From Vague Idea to Testable Rules

Consider this initial idea:

Buy a liquid stock when it breaks above its recent range on strong volume, then use a tight stop and hold until momentum fades.

A testable first draft could be:

  • Universe: Selected US stocks with complete daily and 30-minute OHLCV data.
  • Decision interval: 30-minute bars during regular trading hours, using the exchange time zone.
  • Trend filter: Previous daily close is above the previous day’s 50-day exponential moving average.
  • Range: Highest high of the previous 20 completed 30-minute bars, excluding the current bar.
  • Volume filter: Current completed bar volume exceeds 1.5 times the average volume of the previous 20 completed 30-minute bars.
  • Trigger: First 30-minute close above the defined range while the trend and volume filters are true.
  • Entry: Submit a market order after the signal bar closes, processed at the next available event.
  • Initial stop: Lowest low of the five completed bars preceding the signal bar.
  • Position size: Size the trade so the planned loss between the modeled entry and initial stop does not exceed the predefined risk budget, subject to buying-power and lot-size constraints.
  • Target: Exit at two times the initial per-share risk above the actual entry price.
  • Time exit: Close any remaining position at the end of the third trading session after entry.
  • Repeated signals: Ignore new long signals while a position in the symbol is open.
  • Costs: Deduct the chosen commission model and apply an explicit slippage assumption to entries and exits.

This is not a recommendation or a claim that the setup works. It is a specification that can be challenged. For example, the researcher can now test whether the volume threshold is useful, whether next-event execution erodes the apparent breakout advantage, and whether the stop produces impractical position sizes.

The Signal Library, a research catalog of single time-series signals, one instrument and one leg each: cards for signals like ADX Filtered Trend, Bollinger Mean Reversion, CCI Reversion, DEMA Crossover, Donchian Breakout, Dual Momentum, EMA Crossover, MACD Trend, RSI Mean Reversion and SMA Cross each carry a one-line description, a persistence status such as unproven, watch or persistent, and linked lessons and performance.

Browsing tradeable signals in the research library.

Common Specification Failure Modes

Using adjectives instead of thresholds

Words such as “strong,” “clean,” and “significant” hide discretion. Replace them with calculations, or label the decision as discretionary and use a manual review protocol.

Optimizing before the base case is stable

Changing several thresholds immediately after an unattractive result encourages data fitting. First confirm that the implementation matches the written rules and that the trades are economically plausible.

Ignoring trades that cannot be filled realistically

A chart may show that a price traded, but that does not prove the entire order would have filled there. This is particularly important in thin markets, around gaps, and when the strategy’s order is large relative to available liquidity.

Leaving edge cases to the software

Different platforms may handle missing bars, simultaneous exits, order priority, and session boundaries differently. Unstated behavior becomes accidental strategy logic.

Adding exceptions after losses

A rule introduced because it removes a known historical loss is a hypothesis, not an established improvement. Record it as a new version and validate it on untouched data.

How to Check Whether the Rules Are Ready to Backtest

Before running a large test, perform a specification audit:

  1. Highlight subjective terms. Define or remove each one.
  2. Mark every data dependency. Confirm that each value existed at the decision time.
  3. Trace several timestamps manually. Follow setup, signal, order, fill, sizing, and exit in sequence.
  4. List exceptional events. Include gaps, missing data, conflicting orders, repeated signals, and position limits.
  5. Verify units and rounding. Check percentages, price distances, ticks, contract values, and lot sizes.
  6. Inspect initial trades. Confirm that the first backtest produces the trades the written rules require.
  7. Freeze a version. Save the specification, parameters, data scope, and cost assumptions before evaluating alternatives.

Only after this audit should you compare parameter values or examine performance across different periods. Reserve data for out-of-sample or walk-forward evaluation so strategy development and validation do not use exactly the same observations.

Implementing the Specification in Kvants

Once the written rules are complete, Kvants Studio can turn the plain-English idea into editable, auditable strategy logic. Review that generated logic against the specification rather than assuming the translation is automatically correct.

Backtests run on NautilusTrader’s event-driven engine, which helps represent orders and market events in sequence. Kvants also supports parameter sweeps, walk-forward analysis, crisis-stress validation, and Pine Script v6 export for supported research workflows.

The practical sequence is specification first, implementation second, trade-level verification third, and broader validation last. The Kvants documentation provides guidance on prompting, strategy logic, and exports. Kvants is a research tool, not a substitute for execution judgment or risk controls.

Frequently Asked Questions

How detailed should trading strategy rules be?

They should be detailed enough that an independent person can determine whether a trade is valid and reproduce the intended order sequence. Every input, timeframe, threshold, decision time, order, sizing rule, exit, and exception should have one interpretation.

Can a discretionary strategy have testable rules?

Yes, but the discretionary component must be isolated. Objective rules can define the universe, setup, risk, and exits, while a documented review rubric handles the judgment-based entry. Screenshots and consistent labels can support review, although results will remain less reproducible than a fully systematic test.

Should I include fees and slippage in the written rules?

Yes. They are part of the research specification, even if they are not signal conditions. Record the commission schedule, spread treatment, slippage model, and any assumptions about liquidity or market impact.

What should I do if a rule cannot be coded?

First determine whether the rule is merely vague or genuinely visual. A vague rule may become measurable once its underlying judgment is identified. A genuinely discretionary rule can be tested through structured replay or manual labeling, provided the rubric is fixed before reviewing outcomes.

When should I optimize strategy parameters?

Optimize only after verifying the base implementation trade by trade. Use economically plausible ranges, preserve validation data, and examine whether results are stable across nearby values rather than relying on one isolated optimum.

Risk Note

This article is educational and is not investment advice. Trading involves risk, and clearly written rules cannot eliminate losses or guarantee that a strategy has an edge. Backtested performance does not guarantee future results. Historical tests can be distorted by data quality, bias, costs, liquidity assumptions, and changes in market behavior.

Read more