Automation and screening in technical analysis — tools, workflow and pitfalls
A screener should apply the same rule to the entire recorded list of instruments. The key question after a scan is therefore: does an empty result mean there is no setup, or no data? This chapter takes you from defining a setup to complete pseudocode, an alert register and a test outside the sample used to select parameters. We separate identifying a candidate from submitting an order. Automation can save work, but it can also repeat an error quickly and consistently.

Write a rule that can return “unavailable”
Automation starts with a complete definition of what should happen for each instrument. A screener evaluates a condition and returns a candidate; an execution system also manages requests, fills, rejections and account state. Keep those responsibilities explicit. If an instrument has missing records, reporting “no candidate” hides a different outcome: the condition could not be evaluated.
Use this hypothetical EUR/USD screening model, not an investment recommendation. Its higher-timeframe gate requires the last completed D1 Close above its EMA(20). Its H1 test requires the newly completed Close strictly above the highest High of the preceding 20 completed H1 records, plus 0.1×the preceding ATR(14). Exclude the candidate candle from both reference calculations. Declare the ATR formula, seed, time zone, price side and gap policy in the saved specification; “ATR(14)” alone is incomplete.
All model candles use one Bid feed and aligned UTC boundaries.
For the numerical checkpoint, assume the preceding history has already produced a valid Wilder ATR of 0.0010 USD per EUR, or 10 pips. The prior 20-bar high is 1.2500. The buffer is 0.0001, so the strict boundary is 1.2501. A completed H1 Close of 1.2502 passes; 1.2501 does not. This is a selected teaching condition, with no claimed optimal multiplier or measured edge.
| Record available | Value known then | Effect on this scan |
|---|---|---|
| 00:00:02 UTC | D1 ending 00:00:00: Close 1.2495; EMA20 1.2490 | The D1 gate passes |
| Before 01:00:00 UTC | H1 reference high 1.2500; prior ATR14 0.0010 | Boundary fixed at 1.2501 |
| 01:00:02 UTC | H1 ending 01:00:00: Close 1.2502 | Candidate can first be recorded |
A candidate, a request and a fill are different events
The table uses a hypothetical calendar day whose D1 boundary is explicitly 00:00 UTC. These labels do not describe every broker’s daily candles. At 00:59:59, the H1 close in the final row is unavailable. In a replay, revealing that row early changes the information set and creates look-ahead. The following forming D1 candle is also excluded from the higher-timeframe gate.
Give each candidate a stable identity, such as instrument, timeframe, bar end and rule version. A repeated data delivery should update or repeat the same record according to a written policy, rather than create another order. Track valid, missing, stale and revised inputs separately. When late corrections arrive, keep both the original decision and the later revision; do not rewrite what was known at the first scan.
After 01:00:02 a separate execution procedure might authorise a request. It must still check its risk and spread limits, available size, permissions and existing positions. The request can be rejected or only partly filled. Confirmation needs the broker’s actual response. The MQL5 testing documentation describes simulation modes and their limits; a test mode’s generated prices are not a historical promise of execution.
Calculate costs from the same price convention
For a second, separate hypothetical accounting model, assume a later confirmed purchase of EUR 20,000 at Ask 1.2504 and sale of the same quantity at Bid 1.2500. Gross realised P&L is 20,000×(1.2500−1.2504)=−USD 8. With commission of USD 0.80 on each execution, net P&L is −USD 9.60. Assume no financing or other charge in this short accounting example. These chosen fills already incorporate their Bid/Ask sides: subtracting another spread would count that component again.
The fill record must state quantity and price for each execution, fees, timestamps and any unfilled remainder. The screening close of 1.2502 is neither the entry fill nor the exit fill. Our arithmetic measures a specified round trip; it is not a backtest result, position-sizing rule or evidence that the screen makes money.
Common failure modes include using the current candle inside its own breakout reference, reading the forming D1 close, treating missing input as false, and choosing parameters after seeing the test outcome. Freeze the definition, retain rejected cases and separate development data from later evaluation. A successful chart or one accounting example does not assess the whole procedure. Platform features, alert limits and programme contracts can change; check the current documentation for the specific account rather than assuming universal automation permissions.
Three exercises with worked answers
The exercise data are hypothetical. Choose an answer, then check the calculation.
Extend the rule into a complete workflow
Continue with platform tools, the full screening specification, real-data examples and the final workshop. Keep signal availability, execution and evaluation as separate records while you compare alert states and test assumptions.
1. Why automate – and what exactly are you automating
The eight currencies USD, EUR, GBP, JPY, CHF, AUD, NZD and CAD form 8 × 7 / 2 = 28 unordered pairs. This is a selected universe, not the whole Forex market or a measurement of the “most widely followed” instruments. A broker may offer a different list. Record the symbols, quotation direction and list version before scanning. We assess moving-average, oscillator and S/R-zone filters under the same data contract.
A screener applies a recorded condition across a list. Its output is a set of candidates and a coverage report. A later manual or automatic decision may reject a candidate; retain that result separately.
A screener performs a repeatable review without selecting favourite charts, but only within its configuration. A list of 28 pairs in the settings does not prove that all received current data. The report must also contain a record for a pair without a signal and for a pair that could not be assessed.
RSI below 30 is the result of a condition, not a buy instruction. If additional price action or contextual analysis determines entry, record rejections as well. Otherwise, the screener test will cover only conveniently selected trades.
2. The automation spectrum: from alert to algorithm
The five levels below organise the scope of functions. They are a course convention, not a ranking of the optimal path for most traders. A higher level requires additional checks, but is not necessarily better for a particular task.
| Level | What the Machine Does | What the Trader Does | Examples |
|---|---|---|---|
| 1. Price alert | Notifies when price reaches a level | Analyses, decides, executes | Alert on EUR/USD = 1.0700 |
| 2. Indicator alert | Notifies when an indicator meets a condition | Analyses context, decides | RSI(14) < 30 on D1 |
| 3. Screener | Filters the instrument list by criteria | Reviews results, analyses, decides | TradingView Screener |
| 4. Semi-auto system | Generates a signal + suggested parameters | Approves or rejects, manages position | Custom indicator + Pine Script alert |
| 5. Full automation | Analyses, opens, manages, closes | Monitors, intervenes in emergencies | Expert Advisor (EA) in MT4/MT5 |
A ready-made filter or alert does not always require programming. It still requires configuration, a data source and an operational test. Semi-automatic and automatic execution introduce a separate problem: a correctly identified condition may receive a different execution or no execution at all.
This article focuses on levels 1 to 4. Full automation (EAs) appears here mainly in the context of pitfalls – because that is where people end up when they reach for a robot too early.
3. Screening criteria in practice
Start with the observation you want to find, then translate it into conditions. A selective filter is useful only if it finds the intended cases and reports what it could not assess. Result count alone cannot tell you whether it is good.
A checklist for making a rule objective
Before any condition reaches the scanner, it has to move from the language of intuition to the language of a machine. Every element below that you do not settle explicitly, the scanner will settle for you – usually differently from what you assume:
| Element | Control question |
|---|---|
| Universe | Which instruments am I scanning (a closed list, not "everything")? |
| Data source | Whose feed and which prices (bid, ask, mid)? The same one I trade on? |
| Timeframe and moment of evaluation | Which candles – closed only? When exactly is the condition computed? |
| Indicator with implementation | Which parameters and whose implementation (Wilder's RSI ≠ RSI on an SMA)? |
| Operator and threshold | A crossover through the threshold, or a state below/above it? With what tolerance? |
| Scan frequency | Once per closed candle, once a day at a fixed hour, or continuously? |
| Missing data | What does the rule do with a missing candle, a gap, a symbol change? |
| Deduplication | How many alerts when the condition holds for six candles in a row – six or one? |
| Reset condition | What invalidates the signal and lets the rule fire again? |
Three separate measures. Scan duration and data coverage measure convenience and reliability. Agreement with an independently labelled reference pattern measures condition detection. Financial results require the entire strategy, including rejected candidates, response prices and costs. Hitting TP is not, by itself, the definition of a “correct” screener result, and no improvement in win rate does not negate time savings. Compare against the unfiltered variant on the same sample set aside in advance.
Trend filters
- Price relative to EMA/SMA. Price above a rising 200 EMA on D1 can define a directional filter. It rejects candidates that fail this condition, rather than all “countertrend” trades under every market definition. Price equal to the average, or a flat slope, requires an explicit decision.
- Moving-average crossover. The condition EMA 50 previously ≤ EMA 200 and now > EMA 200 detects a transition. It is neither a cross rate nor proof of a change in future price direction. Both values must come from complete candles in the same series.
- ADX above a threshold. Example thresholds from established convention: ADX(14) > 25 is treated as a trending market, < 20 as consolidation – bearing in mind that ADX measures the strength of a move, not its direction. Useful mainly as a negative filter: below the threshold, a trend rule rejects the instrument in line with the chosen parameter.
Momentum and oscillator filters
- RSI in extreme zones. Example thresholds for RSI(14) are 30 and 70. Their frequency depends on the instrument, timeframe, period and initialisation method. Oversold is not a standalone buy signal, nor overbought a sell signal. Without research, we do not attribute greater information value to D1 extremes than to H1 extremes.
- Divergence. You need to define swings, the pairing of price and oscillator extremes, and the confirmation time. With those definitions, even a complex pattern can be calculated. A manual assessment of “multi-wave” divergence without rules leaves discretionary selection that is difficult to reproduce fairly in a test.
- MACD histogram – sign change. The histogram crosses zero from below – in this implementation that means a change in the relationship between the MACD line and the signal line, not proof of a change in price direction. Easy to code, frequently used as a preliminary filter for further analysis.
Price and structural filters
- Proximity to S/R. Define the zone and tolerance in the same unit as price. An alert at a manually marked zone may simplify review, but its effectiveness must be tested; it does not follow from ease of configuration.
- Breakout of an N-candle range. For example, the close of a completed candle > the highest high of the previous 20 complete candles. The tested candle is excluded from the maximum window; equality is not a breakout in the strict variant. This is one Donchian convention, not an automatic promise of profit.
- Fibonacci. Define confirmed swing endpoints and tolerance around a retracement. Delayed confirmation is described in article 5.11. Calculating a level does not prove that price will react to it.
Work one candle before reading the full contract
Use support S=1.1000 and frozen ATR A=0.0040. The zone is [1.0992;1.1008]; invalidation requires C < 1.0980; rearming requires C ≥ 1.1040 and L > 1.1008. Assume the stated EMA conditions hold when a signal is tested.
- Missing or invalid data: record that state and suspend new alerts.
- A close below the invalidation boundary retires this context.
- If disarmed, test rearming for the next candle. Do not alert on this candle.
- If armed, a range intersection with the zone and C > S can produce a candidate if the EMA filter passes.
The trace below supplies the numbers. These are model inputs, not reconstructed market history. The later contract adds controls that preserve this meaning when data or requests repeat.
Replay the alert state without seeing the next candle
Keep the same S, frozen A, branch order and context. The first six decisions use the published trace, including its retry. The final gap is separate. Make a choice before revealing the check; answers remain accessible without entering notes.
Step 1. Armed. L=1.1007,H=1.1015,C=1.1010.
Optional note. Keep a copy if browser storage is unavailable.
Check this step and reveal the next
SIGNAL. The range intersects the zone, C > S, and the assumed EMA filter passes. Disarm this context.
Step 1 — retry. The same key and input hash arrive again.
Optional note. Keep a copy if browser storage is unavailable.
Check this step and reveal the next
Return the existing SIGNAL. Do not assess it against the now-disarmed state or send another notification.
Step 2. Disarmed. L=1.1010,H=1.1042,C=1.1040.
Optional note. Keep a copy if browser storage is unavailable.
Check this step and reveal the next
REARM for the next candle. C equals the permitted threshold and L is above 1.1008. No alert now.
Step 3. Armed. L=1.1007,H=1.1025,C=1.1010; the EMA filter passes.
Optional note. Keep a copy if browser storage is unavailable.
Check this step and reveal the next
SIGNAL on this new candle key, then disarm.
Step 4. Disarmed. L=1.0975,H=1.1014,C=1.0980.
Optional note. Keep a copy if browser storage is unavailable.
Check this step and reveal the next
DISARMED. Equality does not satisfy C < 1.0980. Rearming also fails.
Step 5. Disarmed. L=1.0974,H=1.0982,C=1.0979.
Optional note. Keep a copy if browser storage is unavailable.
Check this step and reveal the next
INVALIDATED. Retire the old centre; a new confirmed fractal is needed.
Step separate gap. Instead of a complete record, a data error prevents assessment.
Optional note. Keep a copy if browser storage is unavailable.
Check this step and reveal the next
NO_DATA. Do not invent NO_SIGNAL or infer rearming or invalidation inside the gap. Suspend alerts until context is rebuilt.
Read the complete worked trace
The same level, successive alert states
Let us work through the rule without changing thresholds after seeing the outcome. Support S = 1.1000 comes from a fractal confirmed before the first tested day. ATR A = 0.0040, or 40 pips, frozen at that time, defines the zone [1.0992; 1.1008], invalidation at C < 1.0980 and rearming at C ≥ 1.1040 and L > 1.1008. These are model parameters, not recommended values for EUR/USD. The fractal centre and A remain the same throughout the example.
| Step | L / H / C | State before | Outcome |
|---|---|---|---|
| 1 | 1.1007 / 1.1015 / 1.1010 | Armed | Range intersects the zone, C > S: alert and disarm |
| 1 — retry | Same key and input hash as in 1 | Existing SIGNAL record | Return the previous outcome; no new assessment, state change or notification |
| 2 | 1.1010 / 1.1042 / 1.1040 | Disarmed | C equals the rearm threshold, L is above the zone: arm for the next step, no alert |
| 3 | 1.1007 / 1.1025 / 1.1010 | Armed | New test: second alert, a different candle end and key |
| 4 | 1.0975 / 1.1014 / 1.0980 | Disarmed | Equality does not invalidate under the strict rule; no rearm and no alert |
| 5 | 1.0974 / 1.0982 / 1.0979 | Disarmed | C < 1.0980: context invalidated |
In steps 1 and 3, the declared EMA filter is satisfied: close is above EMA, and the current EMA is above its value 20 candles earlier. The table does not reconstruct 500 warm-up candles; these two conditions are inputs to a logical model, not documented market readings. Retrying step 1 must return the same SIGNAL; it must not be recalculated using the now-disarmed state and overwritten as DISARMED. On revision, we separately reconstruct the state before that candle and subsequent dependent states, preserving the original run. Step 2 cannot both arm and issue an alert, because its state at the start of assessment was disarmed. Branch order is part of the definition, not a technical detail.
After step 5, the old fractal remains archived as invalidated. The next day's scan cannot rename it “latest support” and create a new alert from the same centre. A new confirmed fractal is needed. Expiry after 60 candles is a separate state: it occurs even without crossing the invalidation level. If data are missing between steps, we do not know whether rearming or invalidation occurred in the gap; report the interruption and suspend new alerts until the context is rebuilt.
A high/low revision may change fractal qualification. Keep the original snapshot, the outcome available then, and the subsequent correction linked to it. Assessing “how the rule worked on final data” and “what it could actually have sent at the time” are two different experiments. You may run both, but must not mix their records. The attached state CSV provides material for checking an implementation without placing orders.
From intuition to condition – the full rule and what gets lost in translation
Intuition: "buy bounces off support in an uptrend on D1." The same thought written so that a scanner can execute it:
The full version has four responsibilities: obtain a versioned snapshot; freeze context; assess the candle from its original state; commit the outcome and deliver a deduplicated notification. Read its branches in order. A retry is not a new candle, and a correction is not an original alert.
Read the full data, state and delivery contract
PSEUDOCODE: “SUPPORT TEST” CANDIDATE, NOT AN ORDER
Frozen configuration: version, 28 pairs, BID feed, D1, calendar,
EMA: α=2/201, seeded with SMA of the first 200 C; Wilder ATR(14):
seed = mean of the first 14 TR with previous C, then α=1/14;
warm-up of at least 500 complete candles is a model choice, not a convergence guarantee.
Symbol state: level S, ATR A, identification interval, armed/disarmed.
At the start of t, record an immutable context snapshot from data known before start_t:
this records inputs for t without changing the working armed state; a retry uses this snapshot.
State before t and the centre archive come from the last previously processed candle.
select the last strict lower fractal with 2 candles on each side,
confirmed and received before start_t, no more than 60 candles old;
equal lows do not form a strict fractal; none = NO_LEVEL.
Identify new context by feed and fractal centre. Keep invalidated centres
in the register; do not recreate context from the same centre.
For new context A := ATR known before start_t; retain it unchanged
until expiry, invalidation or a new confirmed centre.
After 60 candles from the centre, record EXPIRED; issue no alert.
If A ≤ 0 or its value is missing: NO_VALUE, without a signal.
Record zone [S − 0.2A; S + 0.2A] and invalidation C < S − 0.5A.
A new confirmed fractal creates new context, armed before the test.
After the end of t, for EVERY symbol in the full universe:
Key := (version, feed, symbol, D1, end_UTC).
Retrieve complete OHLC t and known_at, and the saved context snapshot before start_t.
The input hash covers OHLC, indicator history, context, configuration and data versions.
If this key and hash exist: return the earlier outcome without assessment or state change.
If the key exists but the hash differs: append a revision and run a separate replay
from the frozen state before t; do not assess t using state already changed by t.
Correcting history before t requires replay from the first changed input.
Preserve the original outcome/known_at; mark the replay outcome as a later correction.
Do not send the correction as a new original alert; finish the symbol.
On first assessment, use a copy of state before t and the context snapshot;
validate L ≤ min(O,C) ≤ max(O,C) ≤ H.
Check session continuity, feed, component, price increments and warm-up.
Data error: record NO_DATA; retain state; issue no alert.
If C_t < S − 0.5A: record INVALIDATED, remove context; finish the symbol.
If the state was disarmed:
if C_t ≥ S + A AND L_t > S + 0.2A: arm for the NEXT candle;
record REARM or DISARMED; issue no alert on the same candle.
If the state was armed:
trend := C_t > EMA200_t AND EMA200_t > EMA200_(t−20).
test := H_t ≥ S − 0.2A AND L_t ≤ S + 0.2A AND C_t > S.
signal := trend AND test.
Record SIGNAL or NO_SIGNAL with the complete operands.
On a signal, disarm context; a new alert only after a future REARM.
Every terminating branch records outcome, inputs, state before and state after t.
Commit the record and state once in one transaction with a unique key;
on a retry conflict, return the existing record without a second mutation.
Identify the notification by this key, including when resuming delivery.
Process candle ends chronologically; a data gap blocks subsequent alerts
until context is rebuilt; it cannot be converted into NO_SIGNAL.
After scanning, report expected/evaluated/missing/candidates, including when candidates = 0.
The alert includes end_t, known_at, version, S, A and conditions; no execution function.The translation makes choices visible. Support means a confirmed fractal, the zone is ±0.2 × frozen ATR, and a test requires the recorded range intersection and close. W1 context and discretionary candle quality are outside this rule. Rearming an alert and invalidating support remain separate events. Another definition needs another version.
Macro context and cost filters – what no screener will show you on its own
A calendar, spread or rollover filter is a separate rule. A 30- or 60-minute window has no established optimality here. Record which events it covers, where their dates came from, and whether it blocks new candidates, new orders, or also changes the handling of existing positions.
- Calendar filter. An example procedure may reject new candidates two hours before a selected event. This is a parameter to test, not a universal requirement. Verify the date with the publisher and distinguish scheduled time from actual publication; “High impact” is the calendar provider's classification.
- Spread filter. The threshold is explicit, with its unit and comparison basis. Twice a previously measured level for the pair and time of day may block a new instruction. It does not explain why the spread widened or protect an existing position.
- ATR filter. ATR > 1.2 × the mean of the previous N values describes a selected threshold being exceeded. A reading below the threshold does not automatically mean a “thin market”. Changing SL, TP and volume requires a recorded rule; it does not necessarily follow from ATR alone.
Keep later assessment of patterns, context and risk as separate rules. If one changes whether action is taken, retain its inputs and rejection reason.
Filters may return different numbers of results in different regimes. If you switch between trend and range sets, the switching rule must be recorded before the test and use data available at that time. Selecting the best filter retrospectively for each historical segment is another optimisation. An empty week with complete data is a valid result, not a reason to loosen thresholds on the fly.
node reproduce-real-examples.cjs in that folder. Read the instructions or inspect the expected values. The checker verifies 50 assertions and writes checks to ./reproduced. All source dependencies are included; the related H1/H4 and three-symbol examples share the checker.Actual H1 scan: a rejected wick and a new candidate
A separate, simpler experiment covers EURUSD, GBPUSD and USDJPY from the same ICMarketsSC-Demo export. Each complete H1 is assessed after its end, using Bid. Hours remain in original MT5 time, with no verified offset. Threshold R is the High of the latest strict pivot with two lower High values to its left and two to its right; equality creates no pivot. Centre i becomes known only after i+2 closes and is used only from the next bar. Tolerance is zero.
A candidate requires both Ct > R and Ct−1 ≤ R. Each pivot produces at most one candidate, and the key includes rule version, feed, symbol, H1 and the evaluated bar’s start. A retry returns the recorded outcome. After 24 subsequent bars from the centre the level expires; any non-hourly interruption resets context and requires a new contiguous pivot. We do not infer the interruption’s cause. This is a candidate filter, not an entry-and-exit strategy.
EUR/USD: the pivot at 21:00 on 13 October has High = 1.12037. Its two right-hand H1 bars end at 00:00 on 14 October, so R cannot be known earlier. H1 [03:00, 04:00) has H = 1.12044 but C = 1.12034: the wick-only breach is rejected, without inventing a “trap” narrative. Only H1 [04:00, 05:00) closes at 1.12064, while previous C remains ≤ R. A candidate arises after that close is received, no earlier than 05:00.
| Symbol | R | C | Scan outcome |
|---|---|---|---|
| EURUSD | 1.12037 | 1.12064 | New candidate |
| GBPUSD | 1.32593 | 1.32669 | This pivot already reported — no repeat |
| USDJPY | 158.466 | 158.392 | Rejected: C ≤ R |
All 3 of 3 symbols were assessed; one new candidate does not mean one trade. Rejections and all earlier outcomes from 1 October are recorded too. We selected the first EURUSD candidate after that date with an earlier rejected breach of the same R within the prior 12 H1 bars, not by a subsequent profit. The export has no live receipt times, Ask, fills or complete revision history. We show causal ordering on frozen data, not the notifications actually sent at the time.
For verification: chart-source H1 bars, successive example states, the full three-symbol register, metadata and SHA-256, and the reproduction script. Prefix checks compare an outcome computed using only history up to that point with the same portion of the full replay. Appending future bars must not alter an earlier outcome.
4. TradingView – Screener, alerts, Pine Script
Built-in screener
TradingView provides currency filters and alerts, but the precise scope depends on the current tool and plan. Check columns, timeframe and source. “Volume” in spot FX is not a centralised transaction record: it may mean the number of updates to a particular feed. Two sources can produce different results; comparison is still possible, but requires identified data and a method.
For a first implementation, use one intent: find oversold candidates within this D1 downtrend filter. Evaluate complete, available candles from the recorded universe and feed. The rule is C < EMA(200) AND RSI(14) < 35 AND ADX(14) > 20. Equality fails each strict comparison. Indicator implementations and initialisation follow the declared data contract. This returns candidates for review; it does not prescribe a short or a long.
| Model row | Close / EMA200 | RSI14 / ADX14 | Outcome |
|---|---|---|---|
| A | 1.0900 / 1.1000 | 32 / 24 | Candidate: all three comparisons pass |
| B | 1.1100 / 1.1000 | 32 / 24 | Rejected: close is not below EMA |
| C | 1.0900 / 1.1000 | 68 / 24 | Rejected: RSI is not below 35 |
These inputs check logic without reconstructing indicator history. A five-session return would be a separate condition: 100 × (C_t / C_(t−5) − 1) is signed; its absolute value is not. Specify sign, threshold and series before adding it. Report expected, evaluated, missing and candidates instead of promising a typical daily count.
Alerts in TradingView
An alert notifies you of a condition: it may require a close or an intrabar response. In either case, record the data time, detection time and message receipt time. We do not assume that every other algorithm has already traded or that every notification has the same delay.
Alert limits depend on the current TradingView plan, alert type and duration. Check these before choosing a universe. Limits on active alerts and on symbols assessed are separate constraints.
Pine Script – custom indicators and strategies
Pine Script supports indicators, alerts and simulated strategies. Start with a small condition you can check by hand, then verify its behaviour on complete and forming bars. The official documentation defines the execution model.
- A custom indicator can combine RSI, a confirmed Fibonacci zone and an EMA relationship. Each input needs its calculation, source and availability time; a drawn arrow does not supply those definitions.
- An alert based on a custom indicator – the script generates an alert automatically when the conditions converge. You get a phone notification and open a chart ready for analysis.
- A strategy backtest – Pine Script has a built-in
strategy()module that lets you test logic on historical data. Results are visible in the "Strategy Tester" tab: equity curve, drawdown, win rate, profit factor.
Pine Script calculates indicators, alerts and simulated orders in TradingView's emulator. Native broker integration for order handling does not mean that a strategy script sends its own trades to a broker. Automatic execution following a webhook requires a separate, correctly configured layer. It must identify duplicates, acknowledgements and errors. The environment depends on data and requirements; without measurement, we do not establish any platform as a guarantee of lower slippage.
An RSI event in pseudocode. This describes logic, not paste-ready code or an order-submitting system. The implementation must retain the completeness and timing contract and the initialisation rule specified in article 5.8.
PSEUDOCODE — ALERT ONLY, NO ORDERS
Configuration: rule version, universe, BID feed, D1 timeframe,
daily boundaries, RSI(14) and EMA(200) implementations, at least 500 historical candles.
After each expected D1 end, for EVERY symbol:
Check completeness, OHLC, calendar continuity and availability time.
If data are missing: record NO_DATA; retain threshold state; finish the symbol.
Calculate RSI and EMA with the same declared method on two consecutive complete D1 candles.
If the result is undefined: record NO_VALUE; finish the symbol.
Event := previous RSI ≥ 30 AND new RSI < 30 AND new C < new EMA.
Key := (version, feed, symbol, D1, end_UTC).
Record the outcome even when event = FALSE, with data time and hash.
If event and key not yet sent: record an alert, send the notification.
Rerunning with the same key does not send a new alert.
History correction: append a correction version; do not replace the original decision.
If there is a data gap between candles: do not pretend there was a continuous crossover.
The next event requires a new pair of consecutive complete candles.
RSI = 30 on the previous candle permits the transition, while equality on the current candle does not satisfy it. This is an explicit choice of operators. Another candle still below 30 is not a new transition. Separately, we deduplicate an identical result after rerunning the scan. A data gap does not permit inventing the missing RSI or accepting an unobserved crossover.
Detection and response. Close is available once the candle is completed and received. An alert, a decision and any execution attempt follow. TradingView's default emulator fills a new order no earlier than the next tick; it also offers options for modelling execution at close. Such an option does not prove that this price was achievable after receiving the alert. Using a future HTF close before its interval ends is look-ahead, regardless of the setting's name. The timeline is shown in article 5.11.
5. MT4/MT5 – Scanners, indicators, EAs
MetaTrader supports local indicators and Expert Advisors written in MQL4/MQL5. An EA can submit and manage orders if the platform, account and provider permit it. A scanner that only reports conditions has a narrower responsibility.
Custom indicators and scanners
A dashboard may report trend state, RSI and distance from a moving average for Market Watch symbols. Check the tool’s rule, version, coverage and data handling. A product name or review does not settle those questions.
A local MT4/MT5 scanner needs its platform process to keep running, on a computer or VPS. TradingView alerts use its server infrastructure. Check data freshness, service errors and message receipt in either environment; notification is separate from detection.
Expert Advisors – full automation
EAs are programmes that can trade on their own. The range of possibilities is enormous – from a simple "buy when the 50 EMA crosses above the 200 EMA" to complex systems with dynamic position management, trailing stops, and multi-timeframe analysis.
Assessing a ready-made EA requires documented rules, a change history, data, costs and results that include weak periods. A smooth chart alone establishes neither fraud nor fitting, but without this information it cannot rule them out. The rest of the chapter shows what to check.
MT5 vs MT4
MT5 has a multi-symbol tester, while the standard MT4 tester works on a selected symbol. This matters for portfolio strategies, but does not determine data or execution-model quality. Check the supported instruments, testing modes and the specific broker's terms; the platform's name alone is no assessment of execution.
6. Workflow: From scan to watchlist
The process below separates scanning, verification and response. It is an organisational example for swing trading, not the findings of an effectiveness study. Every stage leaves a record, including rejection.
- W1 after the week completes. Review the context and previously confirmed S/R zones. Assessment can be manual or automated if formally defined. Record the identification time and zone boundaries; do not move them later to fit the outcome.
- D1 scan after the specified close. Assess every symbol under the frozen rule. Review candidates against the recorded weekly context; retain manual rejections and missing-data states.
- Watchlist and exposure. The number of pairs depends on review capacity, not an “ideal” range of 2–5. Long EUR/USD, long GBP/USD and short USD/CHF share a short USD leg and have different other currencies; they are not one identical position. Measure correlation on aligned returns, specifying the period and window. DXY partly duplicates these rates. COT has separate position and publication dates. Position sizing belongs only in the trade plan.
- Alerts and waiting. On watchlist pairs you set alerts: price-based (price reaches a zone), indicator-based (RSI enters an extreme zone), or on drawn objects (a trendline touch). You do not sit and stare at the chart – you wait for the notification.
- Alert → review → decision. Inspect the recorded candidate and the separate activation, risk and execution conditions. A notification does not itself authorise an order. Record why no action is taken.
Record the actual review time and coverage. An alert does not guarantee correct contextual assessment or a complete list. A data change after an intervention or announcement may change the rule's outcome; checking that change requires a new record rather than replacing the previous reading.
The number of candidates should fit your review capacity. Treat an empty result as no setups only after checking universe coverage and data freshness. Failure, an incomplete candle and insufficient history have separate states. “Not today” is an interpretation, not a diagnostic message.
7. Monday morning – What screening 28 pairs looks like
Illustrative Monday review: the source uses days ending at 17:00 America/New_York and five full D1 candles in a normal week. Assessment uses the last received complete D1. With UTC, a short Sunday candle may already exist by Monday, so we do not universally assume that no new D1 forms over the weekend.
8:15. In the TradingView screener, D1 filters (data from Friday's session close): RSI(14) < 35, price below the 200 EMA, ADX(14) > 20. Goal: pairs in oversold territory within a downtrend.
The model filter returns four pairs with complete data for all 28. The review uses the same source, D1 end time and indicator initialisation:
- AUD/USD. A hypothetical RSI of 28 and price below the 200 EMA satisfy the filter. With a previously recorded W1 zone, the candidate proceeds to further analysis; proximity to support alone is no buy instruction.
- NZD/USD. The filter is satisfied, but an additional rule requires proximity to a W1 zone, which is absent here. Record: rejected in validation, not a “false signal” labelled after a loss.
- EUR/GBP. In the model, the scanner reports ADX 21 and a second feed 18 against a threshold > 20. This is not one consistent measurement. Record sources and suspend the comparison until OHLC, daily boundaries and initialisation are checked. Do not attribute the entire three-point ADX difference to the feed alone without recalculating.
- GBP/CHF. Hypothetical RSI 31 and ADX 27 satisfy the filter. Proximity to a 61.8% retracement requires a previously known swing and a specified tolerance; a price alert and RSI remain separate conditions.
Model: 4/28 = 14.2857% of instruments pass the filter, and 2/28 = 7.1429% remain on the watchlist. Working time was not measured. With two missing datasets, the correct report would say “4 candidates out of 26 assessed, coverage 26/28 = 92.8571%”, rather than “4 out of 28”; the outcomes for the missing two are unknown.
8. Alerts – How not to miss without watching
An alert separates waiting for a condition from reviewing a chart. Its effect on working time can be calculated. This does not establish a guarantee of fewer impulsive trades; the notification still requires following the plan.
Market vs limit order – a short rule
A market order guarantees neither price nor execution under every condition. A limit constrains price under the product's rules, but may remain unfilled. Without data, we do not assume that a limit “usually wins” on D1. Order-type choice and bid/ask activation are discussed in article 2.7.
Types of alerts
- Price. "Notify me when EUR/USD reaches 1.0700." You set these at S/R levels, Fibonacci retracements, and zones of interest. Zero coding.
- Indicator. "RSI(14) < 30 on D1" or "the MACD histogram changed sign." In TradingView: click the indicator → Create Alert. In MT4/MT5: through a custom indicator with an alert function (note – an MT4 alert requires an open platform or a VPS, because it runs locally).
- On a drawing object. TradingView lets you set alerts on drawn trendlines and zones – price touched your weekly line, you get a push on your phone. It combines manually drawn analysis with an automatic notification.
- A composite condition. A multi-condition alert: "price below the 200 EMA AND RSI < 35 AND ADX > 25." It requires Pine Script or MQL, but you set it once.
How to combine alerts in practice
Zone-based + indicator-based. At the weekend you draw zones on W1/D1 and set price alerts on them. In parallel you set indicator alerts (RSI < 30) on the watchlist pairs. When both fire at around the same time you have a more selective condition, though not necessarily an independent confirmation: both criteria are computed from the same price. The zone-based approach pairs well with support and resistance analysis, the indicator-based one with oscillator-driven strategies.
Reduce unnecessary repeats and expired conditions. The number of active alerts depends on the review process: you can scan the entire universe and send only deduplicated new events. You need not omit instruments to reduce notifications.
A state such as RSI < 30 can remain true for several candles. Previous RSI ≥ 30 and current RSI < 30 is an event at a transition. Evaluate the chosen condition once per specified complete candle, then deduplicate repeat processing of that candle. These are separate controls.
Align source, price side, daily boundaries and indicator initialisation before comparing scanners. Different OHLC can change threshold results. Server-zone labels alone do not establish the size or direction of a difference. Lesson 5.11 works through the time mapping.
In the hypothetical model, the W1 zone [1.0680; 1.0720] was defined before the test. Separately, an RSI(14) cross below 30 was defined on a complete D1. Their combined condition needs a specified time window, such as both events in the same day, rather than any “similar time” chosen retrospectively. Once satisfied, a complete H4 is reviewed under the pattern rule. This is a more selective filter, but both signals derive from price and are not automatically independent.
9. Backtesting – What to test and how to interpret results
A backtest applies a model to historical inputs. It can expose inconsistent rules and estimate outcomes under stated assumptions. It cannot establish the exact prices available after a live decision or guarantee results on new observations.
What is worth testing
A historical test requires reproducible rules and data available at each point in time. Even a simple inequality is incomplete without a source, timeframe, initialisation and response price.
- Indicator conditions. RSI(14) < 30 becomes reproducible only after the source, boundaries, calculation and assessment time are fixed.
- Exit rules and SL/TP. A fixed 50-pip SL, a 100-pip TP. Or a 2× ATR trailing stop. Measurable, comparable.
- Comparing variants. Measure the same procedure under a different threshold or stop rule. Record all variants examined and retain data not used to choose them.
What lends itself poorly to backtesting is anything that requires human judgement:
- Price action. Candle geometry, a zone and confirmation time can be defined numerically. A discretionary “looks convincing” requires a separate, recorded assessment protocol; we do not assume the eye contributes a proven edge over the rule.
- Structural context. Manually labelling wave 2 requires rules, a labelling version and its creation time. Later relabelling cannot improve an earlier test result.
- Discretionary decisions. Candidate rejections can be recorded prospectively. Without that record, we do not know whether discretion improved the outcome or only successful cases were selected. There is no basis for claiming that context invisible to the algorithm alone explains profitability.
Data quality – a topic few people talk about
A backtest result is only as reliable as the data you run it on. On Forex that is a serious issue. The market is decentralised – data from your broker may differ from another's (different spreads, small differences in OHLC). OHLC data loses the information about price movement inside the candle: if SL and TP were tight, there is no way to know which came first – the SL or the TP touch.
MT5's “Every tick based on real ticks” mode uses available ticks, but does not guarantee their presence everywhere. MetaQuotes describes generating ticks where data are missing and rejecting ticks inconsistent with minute data. Check the data report. Historical spread is separate from execution delay. A fixed “current” spread used in another mode is a scenario, not always a lower estimate: the current spread may be high or low relative to the history being tested.
Bid/ask, mid and provider prices. Do not infer price type from an API being free. Metadata must specify bid, ask, mid, a transaction or another series. For a long model calculated against mid, spread cost in pips is (entry spread + exit spread)/2. With both spreads equal to 1 pip and 200 round trips, the difference is 200 pips before additional costs. With actual entry ask and exit bid, that difference is already in the prices. Dukascopy and TrueFX are example sources to check; a provider's name does not remove the need to check columns, coverage and gaps.
Bar close and intrabar are different rules. A touch can occur and disappear before the candle ends. A close-based event waits for completion and receipt. OHLC cannot reconstruct all movement order within the interval, so it cannot substantiate a claimed percentage advantage for either rule.
Financing has a sign and a unit. Swap may be negative or positive depending on the product and position side; we do not infer its sign for short USD/MXN or long USD/TRY from currency names alone. Testing needs historical specifications and day multipliers, not just the current table. For example, a price result of +80 USD, commissions of −7 USD and financing of −18 USD give +55 USD; with financing of +18 USD the result is +91 USD. Spread embedded in actual prices is not charged again. Detailed units and conversions are described in article 2.8.
One candle, two possible outcomes
The long model is already open at a fill of 1.1000. The next candle's bid OHLC: O = 1.1000, H = 1.1030, L = 1.0980, C = 1.1010. TP = 1.1020, ordinary SL = 1.0990; assume gap-free execution exactly at the level, without additional costs. Path O→H→L→C reaches TP first: +20 pips. Path O→L→H→C reaches SL first: −10 pips. Both have identical OHLC.
At a notional of 10,000 EUR, results are +20 or −10 USD. These are not two possible outcomes of the same actual trade: they show two paths consistent with incomplete data. Entry and exit fill prices already include the market side, so we do not add spread again. A tester that assumes an order from OHLC chooses a convention; the report must disclose it. A lower timeframe or ticks can resolve more cases, but missing data remain missing.
Mid and fill — two calculations for the same round trip
EUR/USD model: entry mid 1.1000, entry spread 2 pips, hence ask 1.1001; long fill 1.1002. Exit mid 1.1020, exit spread 4 pips, hence bid 1.1018; sell fill 1.1017. Notional 10,000 EUR. Mid profit is 20 USD. Spread halves cost 1 + 2 = 3 USD; slippage relative to ask/bid is 1 + 1 = 2 USD. The fill-price result is (1.1017 − 1.1002) × 10,000 = 15 USD — consistent with 20 − 3 − 2.
Round-trip commission of 2 USD and signed financing of −1 USD give 12 USD net. At illustrative reference rates of 0.92 EUR/USD and 0.79 GBP/USD, that equals EUR 11.04 or GBP 9.48; an actual register should use the exchange rates and booking times for the individual amounts. We do not calculate 15 − 3 − 2 again. The CSV separates the reference point from actual prices.
How to interpret the results
The key backtesting metrics:
| Metric | What it tells you | What to watch out for |
|---|---|---|
| Profit Factor (PF) | Sum of positive NET results / absolute sum of negative results | Zero counts towards neither sum. With no losses the ratio is undefined, not evidence of an infinite edge. PF 1.5 is not a universal threshold. |
| Max Drawdown | Largest equity fall from a previous peak | In currency or as a percentage of the peak; depends on sampling frequency. Closed-trade results alone may miss open-position risk. |
| Win Rate | Share of positive outcomes in a defined sample | 30% of outcomes at +3R and 70% at −1R give +0.2R gross per trade. A cost of 0.25R per round trip changes expectancy to −0.05R. R:R and win rate alone do not prove future profitability. |
| Number of trades | Sample count and effective diversity | 100 trades in the same USD move ≠ 100 independent observations. Examine clusters, regimes and uncertainty; there is no magic minimum. |
| Sharpe Ratio | Mean excess return over a benchmark / return standard deviation | Frequency, benchmark, annualisation and temporal dependence matter. > 1 or > 2 is neither a quality test nor proof of overfitting. |
Example: a badly done backtest and how to fix it
Optimisation model: an RSI threshold from 10 to 30 in steps of 1, SL from 30 to 80 pips in steps of 1, and TP from 80 to 200 pips in steps of 1. The grid contains 21 × 51 × 121 = 129,591 combinations, not a few dozen. Count abandoned attempts and manual rule changes too. An example best PF of 2.8 on 2020–2025 data is a selection result on that dataset, not proof that the chosen combination RSI 22 / SL 43 / TP 167 has an edge.
A sharp performance peak around one combination is a signal to check sensitivity. It does not prove overfitting by itself: costs, a small sample and a regime change may matter. Report the whole grid and the selection rule, not only the best point.
After selecting parameters on the whole 2020–2025 period, you cannot rename 2024–2025 as a holdout. You need fresh future observations or a different plan specified in advance. Training, validation and test have separate functions; after using the test, do not optimise on it again.
Differences between testing and operation may come from the cost model, data, execution or changing conditions. Not every weaker live trial proves overfitting, and not every backtest is optimistic by definition. Comparison requires the same rules and a journal of signals, orders and actual fills.
A forward test checks operation on new observations. Duration does not establish representativeness: a few months may cover few events and a single regime. Demo allows you to check logic and availability, but its execution need not match a real account. Break down a poorer result into differences in data, execution, costs and the event distribution itself.
Reshuffling closed outcomes, for example 1,000 permutations of 150 trades, shows conditional equity paths for the same sample and fixed position-sizing rules. It does not create new shocks or a distribution change, and may remove temporal dependence. With percentage risk or simultaneous positions, their structure must be preserved. The 95th percentile of such a simulation is not a guaranteed limit on future drawdown. A tool for this exercise is the Monte Carlo simulator.
10. Python in screening and backtesting
Python can support your own data register and tests. Cost and difficulty depend on source quality, scope and maintenance. A custom scanner requires error handling, dependency versions and monitoring; this article presents a logical contract, not production code or a promise of a cheap system ready to run.
A custom environment offers control over several parts of the process:
- Source integration. Broker APIs and data libraries expose different instruments and metadata. Check access, coverage and revisions before combining their series.
- Statistical analysis. Libraries calculate tests and distributions. The question, reference distribution, dependence assumptions and family of attempts still need to be chosen correctly.
- Backtesting flexibility. The backtrader and vectorbt libraries let you test portfolio strategies (many pairs at once), strategies with dynamic capital allocation, and strategies with correlations between instruments. Pine Script and MQL have limits here.
- A connected workflow. Retrieval, screening and notifications can share a register. Execution requires a separate instruction and acknowledgement layer, with its own retry handling.
- Sentiment analysis. Some traders experiment with automated sentiment analysis of news and economic reports, feeding that signal into the screening pipeline. Tools for this exist (from simple scripts to language-model APIs), but in retail practice it is still more of an experiment than a finished solution.
A pipeline in pseudocode — data, scanning and archive. It contains no API tokens or order-execution functions. The same logic can be implemented in any environment.
PIPELINE PSEUDOCODE — NO ORDER-SUBMISSION FUNCTION
Load the frozen configuration and complete versioned symbol list.
Determine expected candle ends from the source calendar, not the computer clock.
For each symbol, retrieve data with component, start, end, complete,
received_at, revision and source identifier.
Retain an immutable data snapshot and checksum.
Validate OHLC, price unit, session continuity and indicator warm-up.
On error, record NO_DATA with its cause; do not create NO_SIGNAL.
On a valid snapshot, calculate the complete criteria rule.
Record an outcome for each symbol, including those failing the condition.
Deduplicate alerts by version, feed, symbol, timeframe and end_UTC.
On a correction, append a new record linked to the previous snapshot.
Summarise: expected, evaluated, missing, candidates and scan duration.
Archive the manual decision and its time separately, without overwriting the filter outcome.
Report process failure and missing symbols, even when there are zero candidates.
Before choosing a source, check its licence, instrument coverage, price side, timestamps, completeness, revisions and available bid/ask. We do not apply one blanket label to all Yahoo data or free APIs. A data-reading library neither improves data quality automatically nor provides execution prices.
Retrying a data request is a different operation from retrying order submission. A scan can safely recreate the same key and return its earlier outcome. The execution layer requires a separate instruction identifier and a status check before retrying; it is outside the screener shown here.
11. Automation pitfalls
Automation repeats a specified process. Measure whether it saves review time, preserves coverage or changes operational mistakes. It can also repeat an error consistently; the following checks make errors easier to identify.
| Pitfall | Mechanism | How to limit it |
|---|---|---|
| Mid model | For two fills, the difference is half the entry spread plus half the exit spread | Check price type; do not add spread again to actual ask/bid fills |
| Fixed spread | An assumed scenario that may be too low or too high | Bid/ask history and a missing-data report; “real ticks” mode alone does not guarantee completeness |
| Omitted slippage and commission | Net result lower than gross, especially on low timeframes | Model slippage conservatively; count commission in R |
| Look-ahead | The signal uses data unavailable at the moment of decision (the close of a forming candle, a swing from the future) | Inputs available at the decision, including confirmation and delivery delays; response at a later available quote |
| Overfitting | Parameters fitted to the noise of one specific history | Few parameters; out-of-sample; walk-forward |
| Multiple attempts | Selecting the best variant increases the risk of a false discovery | Register all attempts, use an appropriate correction and a previously unused test |
| Survivorship bias | You only see the systems that survived | Evaluate the process, not pre-selected results |
| Repainting | The indicator redraws closed history | Forward test the indicator; avoid ZigZag-like tools in rules |
| Omitted swap | The cost of holding a position eats into swing results | Include swap points; test on data with costs |
Overfitting (fitting to the past)
Overfitting means fitting choices to properties of a particular sample that do not persist outside it. It is not a synonym for every loss on the first day. Parameter sensitivity, the number of attempts and new observations help assess the problem.
Warning signs of overfitting:[5]
- The strategy has many free parameters relative to the number of trades and the available history.
- A small change of a parameter (RSI 14 → RSI 15) drastically changes the results – so-called fragility.
- A backtest over one period gives excellent results, over another – a loss.
- A high PF or Sharpe requires assessing uncertainty, the number of variants examined and dependence between outcomes. Neither a sample below 100 nor above 500 trades alone determines whether an edge exists. Also check observation length, rare large losses and performance on data not used to choose the rule.
Out-of-sample testing is meaningful only if the sample was not involved in rule selection. In walk-forward testing, fitting on an earlier window is followed by assessment on a later one; all thresholds, updates and result aggregation are recorded beforehand. Requiring a positive result in every window is not a universal statistical rule.
Data snooping
With 50 independent tests of true null hypotheses at a 5% level, the probability of at least one false rejection is 1 − 0.95^50 = 92.3055%, and the expected number is 2.5. This is high risk, not certainty. Variants on the same data are usually dependent, so the independence calculation cannot be treated as their measured probability.
Record the family of attempts before choosing a winner. With 50 tests and a 5% family level, Bonferroni gives a threshold of 0.05/50 = 0.001 for each valid p-value. It controls the risk of at least one false rejection without requiring independent tests. FDR answers a different question; the example below shows the distinction. No p-value correction establishes a strategy's profitability.
Bonferroni, FDR and the limit of the inference
A model of five valid tests in one previously defined family: ordered p-values 0.0004; 0.008; 0.019; 0.021; 0.070. Bonferroni at α = 0.05 gives 0.01 and rejects the first two. The Benjamini–Hochberg procedure at q = 0.05 compares values against i × q / 5: 0.01; 0.02; 0.03; 0.04; 0.05. The largest satisfying index is 4, so it rejects the first four.
FWER controls the probability of at least one false rejection; FDR controls the expected proportion of false rejections among all rejections, with that proportion zero when there are none. Classical BH requires appropriate dependence assumptions, such as independence or a specified positive dependence; we do not apply it to arbitrarily correlated FX variants without checking. q = 5% does not mean each selected strategy has a 95% chance of working. The authors' paper (1995) and method documentation describe the procedures' scope. A valid test needs a question, data, reference distribution and statistic specified in advance; the p-values here are hypothetical inputs.
Sample splitting includes label time
In a hypothetical plan frozen before analysis, training covers 2018–2022, validation 2023, and the unseen test 2024–2025. If a label has a horizon of up to five sessions, a late-December 2022 training observation whose outcome is determined in January 2023 does not belong to training ending on 31 December. Remove labels crossing the boundary or move the cut according to their actual end times. Separating entry dates alone is insufficient.
Historical prices before the boundary may warm up an indicator at the test's start if they were known then. A scaler, thresholds or instrument selection must not be fitted on the future data segment. Validation is for selection, the test for a one-time assessment; once you change a rule based on the test, it is already consumed. Walk-forward requires the same principles for every window and an update method recorded in advance. Probability calibration also needs a separate segment: eight events out of ten forecasts of 0.8 in a small group prove neither universal calibration nor profitability.
Precision, recall and the costs of omission
A model with 100 independently labelled cases: the reference pattern is positive in 20 and negative in 80. The screener issues 15 alerts: 12 match the reference and 3 are false; it misses 8 positives. Precision = 12/15 = 80%, recall = 12/20 = 60%, specificity = 77/80 = 96.25%. Financial performance does not follow from these three measures. Reference labels must be independent of the filter; we do not label every manually selected subsequent profit as positive.
If the reference uses a future outcome, its label is available only at the end of its horizon. It cannot influence an earlier signal or enter training prematurely. Download the recalculated models; all numbers in this block are hypothetical.
Survivorship bias in ready-made EAs
Looking only at systems still sold and published omits withdrawn attempts. Comparison requires a known population and a register of unsuccessful versions too. We do not know the number of “thousands” of withdrawn EAs or influencers' example results — we do not use these numbers as evidence.
The illusion of control
Automation requires monitoring process state, data freshness and unhandled errors. Operating at night alone determines neither slippage nor the number of losses. Alarms should report missing data or a halted scan as well as a satisfied setup.
The black box
Missing documentation makes it difficult to determine whether changed results come from data, the rule or execution. A system may stop performing as expected; you need a stopping condition and an assessment procedure. “It has worked so far” is insufficient.
Repainting indicators
Distinguish a changing reading on an open candle, delayed swing confirmation, a data correction and rewriting an earlier signal. Retain a value snapshot with its assessment time and compare it against later history. An indicator being named ZigZag does not determine every use; the problem is using a point before confirmation or hiding changes.
Prop firms and automation
Prop-firm rules are contractual and vary between programmes and stages. We do not claim that many firms prohibit all automation. For example, FTMO describes permitting algorithms and EAs subject to programme restrictions. Check the current rules, the account's nature (including simulated accounts), limits and prohibited practices; acceptance of a screener does not automatically mean acceptance of every execution method.
12. What not to automate early on
Before automating execution, you must also describe activities beyond the signal itself. The list below identifies tasks requiring a separate rule and test; we do not assume that manual execution is always more effective.
- Position management. Define sizing, stop amendments and partial closes before automating them. Practice can expose unclear decisions, but manual execution is not evidence that a rule is superior.
- Macro calendar. A screener can account for NFP if it has received a correct schedule and blocking rule. It cannot predict the spread or content of an unpublished announcement. No calendar is an explicit limitation, not a property of every automated system.
- Universe selection. Define and version the list before testing. Excluding poorly performing pairs after examining results is another selection attempt. Measure pair characteristics on specified data instead of assigning them fixed properties.
- Weekends and breaks. A spread filter may suspend new orders, but does not limit an existing position's gap loss. Reducing notional exposure reduces price sensitivity; an ordinary stop does not guarantee price. An option hedge requires a separate agreement and account, not merely a “hedge” label. Break risk is discussed in article 4.4.
- Account state. Check the product, hedging/netting mode, margin for a new instruction and rules for closing positions due to insufficient collateral. Liquidation order depends on the provider; we do not assume closing the largest loss is universal. Margin and client protection are discussed separately in article 2.6. Capacity to accept an order at one moment does not guarantee maintaining the position later.
Automate clearly defined, repeatable activities and retain their trail. Scanning, alerts, decisions and execution are successive stages with separate errors and limits. Repeating a rule faster does not improve its quality; it only allows consistent implementation and testing.
13. Tools — comparison
| Tool | Scripting language | Screening | Alerts | Backtesting | Auto-execution | Cost (indicative) |
|---|---|---|---|---|---|---|
| TradingView — basic plan | Pine Script | Platform filters | According to the current plan | Strategy emulator | The strategy script itself does not send native broker orders | Check plan and data |
| TradingView — paid plans | Pine Script | Scope depends on the tool | According to the current plan | Strategy emulator | A webhook needs a separate execution layer; broker integration does not automatically turn a script into an EA | Current pricing |
| MT4 | MQL4 | Custom indicators | Yes (popup, push, email) | Strategy Tester (1 symbol) | Expert Advisors | USD 0 (from the broker) |
| MT5 | MQL5 | Custom indicators | Yes (popup, push, email) | Strategy Tester (multi-currency) | Expert Advisors | USD 0 (from the broker) |
| cTrader | C# / platform tools | According to configuration | According to configuration | cBot tests | cBot — separate execution logic | Platform and provider terms |
| Custom environment | For example, Python | Author-defined rule | Custom infrastructure | Author's model / libraries | Separate API layer | Data, maintenance and infrastructure |
The table describes function scope, not a quality ranking. Tool licensing, data access, VPS and transaction costs are separate items. Check plan limits and prices in current documentation.
- Primary timeframe: D1 – that is where you screen and analyse. You take context from W1.
- Watchlist: choose a versioned universe you can review and monitor. The number reaching the active list is an output of the rule, not a target to force.
- Two filters. For example, EMA 200 and RSI 14 as explicitly defined price transformations. Their thresholds are conventions to assess, not proven removal of most noise.
- 1 alert type to start with: price alerts on S/R zones from the weekly chart. You will add indicator alerts later.
- Begin with a process you can audit. A scanner and one alert rule can be a manageable first exercise. Add execution after its account-state and error-handling rules are specified.
- Process practice and forward testing. Two or three months on demo may serve as an assumed practice period for operation, recording and rule compliance; they are not a sufficient validation minimum. The number and period of observations depend on event frequency, outcome dependence and variability. Demo does not automatically reproduce real-account execution conditions, and the passage of a chosen time guarantees neither representativeness nor profitability.
Position size – outside the scope of this article
Selecting a setup without the right position size is half the job – but the formulas, the treatment of costs within the risk budget, and worked numerical examples belong to section 9. The interactive position size calculator and the Monte Carlo simulator are in the Tools section.
A fixed rule on real data: close beyond the range or wick only?
A candle can breach an earlier high and finish above it, or return inside the range. Does that distinction describe different later price changes in these records? We fixed one comparison before calculating its summary. This is a retrospective description of one provider’s history. Some periods had already appeared in our educational examples; neither the plan timestamp nor the date split creates an unseen holdout.
The input is 6,000 unchanged Bid H1 records for each of EUR/USD, GBP/USD and USD/JPY from ICMarketsSC-Demo / MT5. Within the candidate dates, the ledger contains 17,995 records and 3,140 single-side candidates. The cooldown selects 1,086; 1,039 have a continuous six-record outcome and 47 cross a future timestamp gap. Those 47 remain counted rather than being silently discarded.
| Direction · category | Available / selected | Mean | Median | Fraction > 0 |
|---|---|---|---|---|
| UP · close | 271 / 280 | -0.0689 | -0.1433 | 0.4613 |
| UP · wick | 258 / 273 | 0.2077 | 0.0577 | 0.5078 |
| DOWN · close | 226 / 236 | 0.0934 | -0.1256 | 0.4823 |
| DOWN · wick | 284 / 297 | -0.0152 | -0.2569 | 0.4472 |
A positive signed change follows the breach direction; a negative one moves against it. Mean, median and fraction above zero answer different questions. For DOWN · close, the mean is positive while the median is negative and fewer than half the observations are positive. None of these figures is a win rate after costs.
Exact rule and limits of the comparison
For candidate t, freeze the highest High and lowest Low of the previous 20 completed H1 records. Require hourly continuity from t−21 through t; the oldest record supplies previous Close for True Range. A breach of both boundaries is excluded first. Otherwise classify a Close strictly outside as CLOSE, or a High/Low breach with Close inside, including equality, as WICK. Equality of the extreme alone is not a breach.
Take the first candidate per symbol, then suppress the next six indices regardless of its later outcome availability. Only after selection, check the next six records for exact hourly steps. Measure direction × (C at t+6 − C at t), in pips and divided by the arithmetic mean TR of the 20 preceding records. The candidate contributes neither to its reference range nor to that denominator.
The figure pools events, so symbols with more available events carry more weight. Outcome windows do not overlap within a symbol, but 808 adjacent event pairs share earlier history, and available windows across pairs overlap in clock time 950 times. The July groups use the candidate’s date; one outcome crosses that boundary. These dependencies and time-structured gaps prevent an independence or causal interpretation. There are no fills, spread assumptions, account returns or statistical edge claims here.
All 48 summary rows (CSV) · Full classification ledger (CSV) · Selected events and missing outcomes (CSV) · Method and reproduction instructions · Sources, frozen plan, code and outputs (ZIP).
Capstone: keep the decision separate from the next six candles
This is the first selected EUR/USD UP_CLOSE on or after 1 September 2026 with an available outcome: the H1 bar opening on 3 September at 19:00. Earlier UP_CLOSE candidates at 2 September 16:00 and 3 September 15:00 were rejected by the existing cooldown. The case was chosen by chronology and availability, not by the sign or size of its later move. Call the qualifying H1 candle P.
At the decision, the previous 20-record range is 1.15826–1.16302 and their mean True Range is 9.325 pips. P closes at 1.16368, above that frozen upper edge. The latest eligible H4 bar opens at 16:00 and ends at 20:00, alongside P’s H1 close. It provides a wider view of the same Bid history, not an independent confirming vote. Both final records still require receipt after their intervals end.
Before revealing another bar: record what qualifies, the earliest assessment time, and what remains unknown. For this exercise, stop monitoring on the first subsequent H1 Close at or below 1.16302. Keep that boundary fixed. This is an analytical stopping condition; it specifies no order, stop-loss fill or position size.
Frame 0: through the 2026-09-03 19:00 H1 bar
P qualifies as UP_CLOSE only after its final record arrives, no earlier than 20:00. The subsequent path is still hidden. Qualification alone supplies no executable Ask or cost.
EUR/USD Bid H1/H4. Original MT5 time; only this prefix is visible. H4 context stays fixed. Reveal record 1 of 6
Frame 1: through the 2026-09-03 20:00 H1 bar
The revealed Close is 1.16328, above 1.16302. The monitoring condition has not occurred; this does not predict the next Close.
EUR/USD Bid H1/H4. Original MT5 time; only this prefix is visible. H4 context stays fixed. Reveal record 2 of 6
Frame 2: through the 2026-09-03 21:00 H1 bar
The revealed Close is 1.16346, above 1.16302. The monitoring condition has not occurred; this does not predict the next Close.
EUR/USD Bid H1/H4. Original MT5 time; only this prefix is visible. H4 context stays fixed. Reveal record 3 of 6
Frame 3: through the 2026-09-03 22:00 H1 bar
Close 1.16286 is at or below 1.16302. Monitoring ends after this 22:00 bar closes, no earlier than 23:00. The earlier UP_CLOSE classification remains correct.
EUR/USD Bid H1/H4. Original MT5 time; only this prefix is visible. H4 context stays fixed. Reveal record 4 of 6
Frame 4: through the 2026-09-03 23:00 H1 bar
Close is now 1.16257. Monitoring already ended on the 22:00 bar; the new record does not change when that condition became known.
EUR/USD Bid H1/H4. Original MT5 time; only this prefix is visible. H4 context stays fixed. Reveal record 5 of 6
Frame 5: through the 2026-09-04 00:00 H1 bar
Close is now 1.16229. Monitoring already ended on the 22:00 bar; the new record does not change when that condition became known.
EUR/USD Bid H1/H4. Original MT5 time; only this prefix is visible. H4 context stays fixed. Reveal record 6 of 6
Frame 6: through the 2026-09-04 01:00 H1 bar
The sixth Close is 1.16232: −13.6 pips from P, or −544/373 (about −1.4584) prior mean-TR20 units. That is an observed Bid-price change, not a reconstructed trade loss.
EUR/USD Bid H1/H4. Original MT5 time; only this prefix is visible. H4 context stays fixed.
Each frame rescales from its own visible prices; no future extreme sets the initial axes. H4 remains frozen at the decision. Original MT5 bar-opening labels are retained, the broker offset is unverified, and actual receipt times were not measured. A later quote would still be needed to model any executable response.
Capstone data and timing notes · All 28 H1 records, including the revealed path (CSV). The complete ledger and ZIP above retain the exclusions and calculation trail.
FAQ – Automation and screening in technical analysis
Do I need to be able to programme in order to use screening?
No. The built-in TradingView screeners and MT4/MT5 dashboards work on the principle of "click the filters, set the thresholds, get a list." Pine Script and MQL add capabilities (custom conditions, composite alerts), but basic screening does not require writing code.
Is it worth buying a ready-made Expert Advisor (EA)?
Assessment requires documented rules, a complete history of attempts and changes, a cost model and new observations. Even a verified account history guarantees neither representativeness nor future results. An attractive backtest or review alone does not replace these checks.
How many alerts should I have set at once?
There is no universal number. Record review capacity and condition expiry, and reduce repeats with deduplication. You can scan the whole universe without notifying after every candle that still satisfies the same state.
How reliable is a backtest on Forex?
It depends on data, rules and the execution model. OHLC does not establish SL/TP order within the same candle. A real-tick mode may fill gaps with generated data. A backtest does not forecast results; a forward test checks new observations subject to limits on sample length and diversity.
TradingView or MT4/MT5 for screening?
Compare the source and candle boundaries, available filters, alert operation and tester scope. TradingView alerts run on the server; a local MT indicator needs a running platform or VPS. A TradingView strategy script alone is not a native broker-trading system.
Is Python better for backtesting than Pine Script?
A custom environment gives control over data and the model, but transfers responsibility for their correctness to the author. A platform tester has defined conventions and limitations. The choice does not remove look-ahead, unit errors or omitted costs.
Do I have to run the screener every day?
If the rule evaluates every D1 close, scanning should cover every such close. Reviewing only on Monday and Thursday misses new conditions from other days unless an automated system still records them. Separate manual-review frequency from full-scan frequency.
Sources
Primary sources
- Robert Pardo, The Evaluation and Optimization of Trading Strategies, 2nd ed., Wiley, 2008 – backtesting methodology, walk-forward analysis, recognising overfitting; a key work in the context of validating automated strategies.
- Ernest P. Chan, Quantitative Trading: How to Build Your Own Algorithmic Trading Business, 2nd ed., Wiley, 2021 – a practical guide to building quantitative strategies: from screening to algorithmic execution.
- Perry J. Kaufman, Trading Systems and Methods, 6th ed., Wiley, 2020 – an encyclopaedic review of trading systems: trend filters, screening, testing, and strategy optimisation.
- Andreas F. Clenow, Following the Trend, Wiley, 2013 – a systematic approach to trend trading: instrument screening, portfolio backtesting, position management; practical aspects of automation.
Further reading
- David Aronson, Evidence-Based Technical Analysis, Wiley, 2007 – statistical validation of TA methods: data-mining bias, significance tests, the multiple comparisons problem (data snooping); essential reading for anyone testing strategies.
- Marcos Lopez de Prado, Advances in Financial Machine Learning, Wiley, 2018 — further reading; unread chapters are not attributed as evidence for rules.
- Alexander Elder, The New Trading for a Living, Wiley, 2014 — further reading; unread chapters are not attributed as evidence for rules.
- Kathy Lien, Day Trading and Swing Trading the Currency Market, 3rd ed., Wiley, 2016 — further reading; unread chapters are not attributed as evidence for rules.
- Lukas Menkhoff, Mark P. Taylor, "The Obstinate Passion of Foreign Exchange Professionals: Technical Analysis," Journal of Economic Literature, Vol. 45, No. 4, 2007 – a review of TA usage in Forex; context for the discussion on the role of automation among professional currency traders.
- Andrew W. Lo, Adaptive Markets: Financial Evolution at the Speed of Thought, Princeton University Press, 2017 – the adaptive markets hypothesis: why strategies that worked in the past may stop working; implications for automation and backtesting.
Institutional sources and documentation
- Swiss National Bank (2015), "Swiss National Bank discontinues minimum exchange rate and lowers interest rate to −0.75%", press release, 15 January 2015.
- FCA (2015), "News for customers of Alpari (UK) Limited" – Alpari (UK) entering the special administration regime.
- BIS Markets Committee (2017), “The sterling ‘flash event’ of 7 October 2016”, January 2017 — analysis of the event: thin liquidity, orders, algorithmic responses and platform discrepancies.
- TradingView, Pine Script Docs – official language documentation: script behaviour on the current and closed candle (barstate), alerts, strategy().
- MetaQuotes, MQL5 Reference – official MQL5 documentation: indicators, Expert Advisors, Strategy Tester.
- ESMA (2018), "ESMA agrees to prohibit binary options and restrict CFDs to protect retail investors", 27 March 2018 – the product intervention package: leverage limits, negative balance protection, risk warnings; supervisory analyses indicated 74–89% of retail CFD accounts were loss-making.