top of page

Lesson 2: From Trading Idea to Trading Algorithm

  • 2 days ago
  • 7 min read

How to Turn a Market Hypothesis into Clear, Testable and Automatable Rules


Every trading algorithm begins before any code is written. It starts with an observation about market behaviour and a question: can that observation be expressed clearly enough for the same decision to be made repeatedly?

This lesson focuses on the bridge between an informal trading idea and an algorithmic specification.

The objective is not to teach a particular profitable strategy, but to show how vague concepts can be converted into rules that can be tested, challenged and eventually implemented in software.


Original illustration: the research path from an observation to a monitored trading algorithm.
Original illustration: the research path from an observation to a monitored trading algorithm.
Do not start with code. Start with a hypothesis that can be described without ambiguity.

1. Begin With a Market Hypothesis

A market idea is usually expressed in ordinary language:

  • Trends may continue.

  • Unusually large moves may reverse.

  • Volatility may expand after quiet periods.

  • Price may react around a previous range.

These observations are useful starting points, but they are not yet strategies.

A hypothesis adds a relationship that can be investigated. For example:

“When short-term trend strength is positive and volatility is not unusually high, upward breakouts may have different follow-through from breakouts occurring in weak conditions.”

The next task is to define every important term.


2. Remove Ambiguity From the Idea


Original illustration: the difference between an intuitive trading statement and a rule that can be reproduced.
Original illustration: the difference between an intuitive trading statement and a rule that can be reproduced.

Words such as strong, weak, near, large, confirmation and trend can mean different things to different people.

A computer cannot interpret them unless they are converted into measurable conditions.

Instead of “buy when the market looks strong”, a specification might:

  • Define the market state using a fast moving average above a slow moving average.

  • Require price to close above a reference level.

  • Evaluate the condition only after a completed bar.

If two people cannot independently apply the rule and reach the same answer, the rule is probably not precise enough.

3. Define the Strategy Architecture

A trading algorithm needs more than an entry.

Before coding, write down the full lifecycle of the position:

  • What can be traded?

  • What creates a setup?

  • What triggers an entry?

  • How is exposure sized?

  • How is the position managed?

  • What forces the system to stop?


Original illustration: six components of a complete algorithmic trading specification.
Original illustration: six components of a complete algorithmic trading specification.

Component

Question to answer

Example specification

Market universe

Which instruments are eligible?

Only instruments meeting predefined liquidity and data requirements

Setup filter

When is the strategy allowed to look for a trade?

Trend and volatility conditions must be satisfied

Entry trigger

What exact event opens a position?

A completed bar closes beyond a defined reference level

Position size

How much exposure is allowed?

Size is calculated from a predefined risk budget

Exit logic

What closes or reduces the position?

Stop, target, time exit or opposite condition

Safety rules

When must the algorithm stop acting?

Daily loss, exposure, connection or data checks


4. Think in States, Not Just Signals

Many beginner strategies are written as a collection of independent signals.

A clearer algorithm often treats the strategy as a set of states. For example, the system may be:

  • Flat

  • Waiting for a valid setup

  • Holding an open position

  • Resetting after an exit

Original illustration: a simplified state-machine view of a trading strategy.
Original illustration: a simplified state-machine view of a trading strategy.

This matters because the same market condition can require different behaviour depending on whether a position already exists.

A breakout signal that opens a new position when flat should not necessarily open another position every time the condition remains true.


5. Convert Conditions Into Boolean Logic

At the algorithm level, many decisions become true-or-false questions:

  • Is the trend filter true?

  • Has the breakout occurred?

  • Is the spread within the permitted range?

  • Is there already an open position?

  • Has the maximum risk limit been reached?


Original illustration using synthetic market data: a trend concept expressed as a fast-average-above-slow-average condition.
Original illustration using synthetic market data: a trend concept expressed as a fast-average-above-slow-average condition.

Boolean logic makes the strategy easier to test because each condition can be inspected independently.

If a trade occurs unexpectedly, the researcher can examine which condition evaluated to true rather than relying on a vague interpretation of the chart.


6. Specify Timing Carefully

A rule is incomplete if it does not state when it is evaluated.

A condition checked on every tick can behave differently from the same condition checked only at the close of a one-hour bar.

  • Define the timeframe used by each input.

  • State whether calculations use completed bars or the currently forming bar.

  • Define the time zone and trading session where relevant.

  • Decide whether multiple signals can occur during the same bar.

  • Specify what happens around market close, gaps or unavailable data.

These details may appear minor during visual analysis, but they can materially change a backtest and live execution.


7. Write Entry Rules as a Checklist

A useful specification describes entry as a sequence of conditions rather than a single sentence.

For illustration only, a trend-following setup could require all of the following:

  • The selected instrument is eligible for the strategy.

  • No position is currently open under the strategy.

  • The trend filter is positive.

  • The volatility filter is within the permitted range.

  • A completed bar produces the defined entry trigger.

  • Current risk and exposure limits allow a new position.

The example is intentionally generic. Its purpose is to demonstrate structure, not to recommend a trading setup.


8. Define Exit Logic Before Testing

Exit rules deserve the same precision as entries.

A backtest can look very different depending on whether a position uses:

  • A fixed stop

  • A volatility-based stop

  • A time exit

  • A profit target

  • A trailing mechanism

  • An opposite signal

An algorithm should also define what happens when several exit conditions occur together.

For example, if a stop and a strategy exit are both triggered within the same bar, the simulation needs a consistent execution assumption.


9. Position Sizing and Risk Rules

Once entry and exit logic exist, the strategy still needs a rule for exposure.

Fixed position size is simple, but it can create different monetary risk when volatility changes.

Other approaches link size to:

  • Stop distance

  • Account equity

  • Volatility

  • Portfolio exposure

Risk rules can also sit above individual trades. Examples include:

  • Maximum simultaneous positions

  • Maximum exposure to one market group

  • A daily loss threshold

  • A rule preventing new entries when required market data is unavailable


10. Translate the Specification Into Pseudocode

Before writing MQL5, Python or another programming language, pseudocode can expose gaps in the strategy logic.

It describes the algorithm in structured language without requiring exact programming syntax.


Original illustration: a simplified decision tree showing how entry and exit logic can be separated.
Original illustration: a simplified decision tree showing how entry and exit logic can be separated.

A simple conceptual structure might be:

  1. Receive a new evaluation event.

  2. Validate market data and trading permissions.

  3. If no position is open, evaluate setup and entry conditions.

  4. If entry conditions are true, calculate the permitted position size and submit the intended order.

  5. If a position is open, update risk controls and evaluate exit conditions.

  6. Record the decision and relevant strategy state for later review.


11. Separate Strategy Logic From Execution Logic

One useful design principle is to separate two questions:

Should the strategy want a position?

and

How should the platform execute that decision?

Strategy logic contains the hypothesis, filters and signals.

Execution logic handles operational details such as:

  • Order type

  • Permitted volume

  • Spread checks

  • Duplicate-order prevention

  • Rejected orders

  • Position status

Keeping the two layers conceptually separate makes testing and troubleshooting easier.


12. Test in Layers

A strategy should not move directly from an idea to live automated execution.

Each stage should challenge a different part of the process.


Original illustration: five testing layers between strategy logic and controlled deployment.
Original illustration: five testing layers between strategy logic and controlled deployment.


Logic Test

Confirm that the implementation matches the written specification.


Historical Backtest

Evaluate how the rules behave across historical data and different conditions.


Out-of-Sample Evaluation

Use data not relied upon during development to challenge the strategy’s robustness.


Demo or Paper Execution

Observe whether orders, timing and platform behaviour match expectations in a live-data environment without relying on real capital.


Controlled Deployment

If a system is eventually used live, monitor assumptions, execution quality and risk rather than assuming the research stage is finished.


13. Common Mistakes When Turning Ideas Into Algorithms


Original illustration: research and implementation weaknesses that coding alone cannot solve.
Original illustration: research and implementation weaknesses that coding alone cannot solve.

Ambiguous Rules

If the written specification contains subjective language, the implementation may not match the original intention.


Look-Ahead Bias

A rule must never use information that would not have been available at the moment of the historical decision.


Too Many Parameters

Adding many adjustable thresholds can make it easier to fit historical noise rather than a durable relationship.


Unrealistic Execution Assumptions

Ignoring spreads, commissions, slippage, gaps or order constraints can make simulated results misleading.


No Fail-Safe Behaviour

The algorithm should define what happens when data, connectivity, permissions or account conditions are abnormal.


14. Documentation Is Part of the Strategy

A well-documented strategy is easier to test, maintain and revise.

Keep a written record of:

  • The hypothesis

  • Rule definitions

  • Parameter meanings

  • Data assumptions

  • Risk limits

  • Version changes

This is especially important when an algorithm evolves.

Without version control or documentation, it becomes difficult to know whether a change improved the original idea or simply changed the strategy into something else.


15. A Practical Pre-Coding Checklist

  • Can the market hypothesis be stated in one or two clear sentences?

  • Is every subjective term replaced by a measurable definition?

  • Are the market universe and timeframe specified?

  • Are setup, entry and exit rules separate and explicit?

  • Is position sizing defined?

  • Are account-level and strategy-level risk limits defined?

  • Is the evaluation timing clear?

  • Are abnormal conditions and fail-safe behaviour specified?

  • Can the complete process be written as pseudocode?

  • Is there a plan for backtesting and out-of-sample evaluation?


Key Takeaways

  • A trading algorithm begins with a testable hypothesis, not with code.

  • Vague market language must be converted into objective conditions.

  • A complete strategy specifies entries, exits, sizing, filters and safety rules.

  • State-based thinking helps prevent repeated or contradictory actions.

  • Timing and data availability must be defined explicitly.

  • Pseudocode can reveal logical gaps before implementation.

  • Strategy logic and execution logic should be distinguished.

  • Testing should progress through multiple layers before any controlled deployment.

  • Coding cannot rescue a poorly specified or overfitted trading idea.


Educational Notice: This material is provided for educational purposes only. Examples are simplified illustrations of quantitative research and algorithm design and do not constitute investment advice, a personal recommendation, or a guarantee of trading performance. Historical, simulated and backtested results do not guarantee future outcomes. Automated and leveraged trading can result in significant losses.

Comments


bottom of page