From an idea to an operating system
A trading idea begins as a hypothesis about recurring market behavior. Algorithmic trading makes that hypothesis explicit: the data to observe, the conditions that matter, the action to take, the amount of exposure to accept and the conditions that terminate the position.
Once those rules are encoded, the system can apply them consistently. Consistency is useful, but it is not the same as correctness. If the hypothesis is weak, the data is poor or the execution model is unrealistic, automation only repeats the problem more efficiently.
01Data
Prices, spreads, time, volume and external events available to the model.
02Signal
The conditions that transform observations into a potential action.
03Sizing
The rule that converts a decision into a defined amount of exposure.
04Execution
How requests become orders and how orders become actual fills.
05Controls
Operational limits, validation checks and conditions that suspend activity.
06Monitoring
Detection of failures, deviations and changes in the operating environment.
Rule-based does not mean simplistic
A rule can be a direct price condition, a relationship between several variables or the output of a statistical model. What makes the process algorithmic is that the decision path is defined precisely enough to be executed by software.
Automation does not remove uncertainty
The code controls the procedure, not the market. Prices can gap, liquidity can change, a broker can reject an order and relationships found in historical data can weaken or disappear.
Three layers should be evaluated separately
LogicDoes the market hypothesis make sense?
The entry and exit rules should connect to an explainable behavior rather than exist only because a historical optimization selected them.
PortfolioHow does a signal become exposure?
Position sizing, simultaneous positions, correlation and exit interaction can change the risk profile even when entry logic stays unchanged.
OperationsCan the system execute as designed?
Symbol specifications, order validation, latency, connectivity and error recovery determine whether intended behavior reaches the account.
Deterministic, statistical and adaptive systems
A deterministic system produces the same decision whenever the same inputs occur. A statistical system estimates a probability, expected value or relationship and applies rules to that estimate. An adaptive system changes some behavior as new observations arrive. These categories can overlap: an adaptive statistical model can still have deterministic rules for sizing and execution.
Complexity does not automatically improve a system. Every additional parameter, data source and conditional branch creates another assumption to test and another possible failure point to monitor.
Key distinctionAn algorithm is the decision procedure. An Expert Advisor is one software format that can implement such a procedure inside MetaTrader. The platform, broker and account remain separate parts of the operating environment.
The mechanism
In its classic form, each new position is larger than the previous one after an unfavorable outcome. If the starting size is V₀, the multiplier is m and the number of consecutive increases is n, the next size follows an exponential relationship.
With a multiplier of two, each step doubles. The important number is not only the latest position, but the cumulative exposure already created by the sequence.
Illustrative sequence using abstract units and a multiplier of 2| Step | New position | Cumulative units | Growth versus start |
|---|
| 0 | 1 | 1 | 1× |
| 1 | 2 | 3 | 3× |
| 2 | 4 | 7 | 7× |
| 3 | 8 | 15 | 15× |
| 4 | 16 | 31 | 31× |
| 5 | 32 | 63 | 63× |
Why a high win rate can coexist with tail risk
Many completed sequences may end positively because one later position offsets several smaller losses. This can produce frequent small gains while leaving a much less frequent but much larger adverse sequence. Win rate alone does not show the distribution or magnitude of those outcomes.
Finite capital meets an unbounded sequence
The theoretical progression assumes that another step can always be placed. Real accounts have finite capital, margin requirements, volume limits and broker constraints. When a sequence reaches that boundary, the next order may be rejected, existing positions may be forcibly closed and a substantial part—or all—of the account can be lost.
Market frictions change the arithmetic
The simplified progression often ignores spread, commission, swap, slippage and the possibility that positions are filled at different prices. These costs accumulate as the number or size of positions grows. Gaps and rapid movements can also bypass intended exit levels.
ClassicFixed multiplier after each loss
Exposure grows geometrically until a winning event or an external limit ends the sequence.
SoftenedMultiplier between one and two
Growth is slower but remains exponential while the progression continues.
CappedMaximum steps or maximum size
A cap bounds the progression, but it also removes the assumption that one later event necessarily recovers the full sequence.
Martingale is not the same as anti-Martingale
Anti-Martingale increases size after favorable outcomes and reduces or resets it after losses. Both methods make exposure depend on the preceding sequence, but they concentrate risk in different conditions. Neither label describes entries, exits or the underlying market hypothesis.
Questions for evaluating a progression
- What triggers an increase in size?
- Is the multiplier fixed or variable?
- How many increases are allowed?
- What is the cumulative exposure at the maximum step?
- What closes the sequence if recovery does not occur?
- Are spread, swap, commission and gaps included in the analysis?
A price lattice, not a complete strategy
The word “grid” describes a structure: multiple levels distributed above, below or around a reference price. It does not specify why positions are opened, whether the system follows or opposes a trend, or how accumulated exposure is resolved.
A mean-reversion grid may add positions as price moves away from a reference and expect a retracement. A breakout grid may place orders in the direction of movement. A market-making style grid can quote on both sides. Each version has a different exposure path.
01Spacing
Fixed price distance, volatility-adjusted distance or a nonlinear series. Narrow spacing creates more frequent interaction and faster inventory accumulation.
02Direction
Long-only, short-only, directional with a trend, counter-trend or two-sided. Direction determines which market paths add inventory.
03Sizing
Constant size, decreasing size, increasing size or a formula linked to volatility and existing exposure.
04Exit logic
Individual take-profits, basket average price, time-based exits, a global loss limit or another portfolio-level condition.
05Boundaries
Maximum positions, total volume, price range, duration and conditions that prevent the grid from extending indefinitely.
06State
The reference price may remain fixed, recenter after fills or move with the market. This changes the entire geometry of the system.
Grid and Martingale are related concepts, but not synonyms
Structural comparison| Question | Grid | Martingale |
|---|
| What defines it? | Multiple price levels or entries | Increasing size after losses |
| Must size increase? | No | Yes, by definition |
| Can it use one position? | Usually no; the structure involves levels | Yes; progression can occur across separate trades |
| Main risk driver | Inventory accumulation and exit structure | Geometric growth in position size |
| Can both coexist? | Yes. A grid can also increase size at successive levels, combining both mechanisms. |
When price remains inside a range
Repeated movement between levels can allow individual positions or baskets to close frequently. This favorable path can make the system appear stable while directional exposure remains limited.
When price trends or gaps
A counter-trend grid can accumulate positions against the move until every planned level is occupied. Distance from the average entry expands, financing costs continue and margin is consumed. If the move persists, losses can exceed the intended boundary or positions can be forcibly closed. A gap may also cross several levels without producing their modeled fills.
Core ideaThe key question is not “Does the system use a grid?” but “How much inventory can it accumulate, under which market path, and what rule ends that accumulation?”
Questions for evaluating a grid
- How are levels spaced and recentered?
- Does size remain constant across levels?
- What is the maximum number of open positions?
- Is there a basket-level exit and a separate loss boundary?
- How are gaps, spread expansion and trading pauses modeled?
- What happens if price never returns to the basket average?
What the engine is actually doing
At each historical step, the engine updates available information, evaluates the strategy, generates any order requests, applies its fill assumptions and updates positions, costs and account state. The result is a simulated path, not direct evidence of what a future live account will do.
Historical data→Strategy rules→Fill model→Simulated account→Analysis
Five sources of false confidence
Look-aheadUsing information before it existed
A signal may accidentally access the final value of a bar or another field that would not have been known at decision time.
OverfittingFitting historical noise
Too many parameters and repeated optimization can create a model specialized to one sample rather than a durable relationship.
Data qualityTesting on an incomplete market
Missing ticks, generated ticks, incorrect timezones and simplified spread histories can change the sequence of events.
SelectionShowing only the favorable run
Trying many instruments, periods or variants and reporting only the strongest result hides the number of failed attempts.
ExecutionAssuming fills that were unavailable
Instant execution at requested prices can materially overstate a strategy that trades during fast movement or thin liquidity.
RegimeConfusing one environment with all environments
A period dominated by one volatility or trend regime may not represent the conditions encountered later.
A more defensible validation sequence
- 01
Define before optimizing
Record the market hypothesis, variables and expected failure conditions before searching for parameters.
- 02
Separate development and evaluation
Use an in-sample segment to build the model and preserve unseen data for evaluation.
- 03
Stress the assumptions
Increase costs, delay entries, perturb parameters and shift start dates to measure sensitivity.
- 04
Walk forward through time
Repeat development and evaluation in chronological windows rather than mixing future and past information.
- 05
Compare with a live observation phase
Check whether order behavior, costs and frequency resemble the model before drawing broader conclusions.
Metrics should answer different questions
Return pathHow gains and losses accumulate through time rather than only the final result.
DrawdownDepth, duration and recovery of adverse periods.
Trade distributionAverage outcomes, extremes, skew and dependence on a small number of events.
ExposureTime in market, simultaneous positions and concentration by direction or regime.
SensitivityHow results change after modest variations in parameters, costs and timing.
CapacityWhether assumed volume and fills remain plausible as size increases.
What a backtest cannot proveIt cannot establish that a relationship will persist, guarantee a future result or reproduce liquidity that was never recorded in the historical dataset.
The path from condition to position
- 01
Signal event
The strategy observes a completed condition using the data available at that moment.
- 02
Order construction
The software selects direction, order type, volume, price levels and identifiers.
- 03
Local validation
The terminal checks permissions, symbol rules, available margin and request format.
- 04
Transmission
The request crosses the local machine, network and broker infrastructure.
- 05
Broker response
The request can be filled, partially filled, rejected, requoted or delayed depending on the environment.
- 06
State reconciliation
The EA must read the actual result and update its internal state from what occurred, not from what it intended.
Four costs that are not the same thing
SpreadBid–ask difference
The entry and exit sides of the quote create an immediate cost that can vary through the session.
CommissionExplicit transaction charge
A fixed or volume-based fee can have greater impact on systems with frequent or small expected moves.
SwapFinancing over time
Positions held across rollover can receive or pay financing that varies by symbol, direction and broker.
SlippageRequested versus filled price
Slippage can be negative or positive. Its distribution depends on order type, timing, liquidity and execution policy.
Market orders prioritize execution
A market order requests execution at the available market, so the final price can differ from the price observed when the request was created. The difference can grow during rapid movement or limited liquidity.
Limit orders prioritize price
A limit order sets a price boundary but may remain unfilled or receive only part of the requested quantity. Avoiding adverse price does not guarantee participation.
Why brokers can produce different outcomes
Two brokers can use different liquidity sources, spreads, commissions, trading sessions, contract sizes, tick values, minimum distances, execution policies and historical price feeds. Even when the strategy code is identical, these differences can change whether a condition occurs and how the resulting order is handled.
Examples of environment differences| Variable | What can differ | Possible effect |
|---|
| Price feed | Ticks, spikes, bar construction | Different signal timing |
| Spread | Typical level and expansion | Different entry cost or blocked trades |
| Symbol specification | Contract size, digits, volume step | Different sizing and order validation |
| Execution policy | Fill modes and rejection rules | Different fill rate and state |
| Trading session | Open periods and maintenance | Orders available at different times |
Operational reliability is part of system design
ConnectivityDetect interruptions
The system should distinguish between no signal and an inability to receive data or transmit orders.
IdempotenceAvoid duplicate actions
Retries and terminal restarts should not create repeated orders for the same intended event.
LoggingKeep an audit trail
Signals, requests, broker responses and state changes make later diagnosis possible.
RecoveryRebuild state safely
After a restart, the system should reconcile open positions and pending orders before taking new action.
TimeUse consistent clocks
Server time, local time and daylight-saving changes can affect sessions and scheduled behavior.
MonitoringSeparate strategy and technical alerts
An adverse market outcome and a failed order are different events and should be identified separately.
Execution principleA live system should treat the broker response as the source of truth. The requested order is only an instruction; the confirmed fill defines the actual position.