Most spread filters in Expert Advisors look like if(spread > 20) return;. That works on one broker and one symbol, then breaks the moment the EA runs on an account with different typical spreads, a different symbol, or a quieter session. A filter that compares the current spread with what this symbol has recently been doing travels much better.
The idea: keep a rolling window of spread samples, take the median, and block new entries when the current spread is more than a chosen multiple of that median.
Why the median
Spread spikes are exactly what we want to detect, so they should not drag the baseline up. An average gets pulled by every rollover spike. The median barely moves.
Collecting samples
Sampling on every tick biases the window toward busy moments, so this records at most one sample per second.
input int InpSamples = 300; // about five minutes of seconds
input double InpMaxRatio = 2.0; // block when spread exceeds 2x the median
int g_spreads[];
int g_count = 0;
int g_pos = 0;
void RecordSpread()
{
static datetime last = 0;
datetime now = TimeCurrent();
if(now == last) return;
last = now;
if(ArraySize(g_spreads) != InpSamples)
ArrayResize(g_spreads, InpSamples);
g_spreads[g_pos] = (int)SymbolInfoInteger(_Symbol, SYMBOL_SPREAD);
g_pos = (g_pos + 1) % InpSamples;
if(g_count < InpSamples) g_count++;
}
The median and the check
double MedianSpread()
{
if(g_count == 0) return 0;
int tmp[];
ArrayResize(tmp, g_count);
ArrayCopy(tmp, g_spreads, 0, 0, g_count);
ArraySort(tmp);
int mid = g_count / 2;
if(g_count % 2 == 1) return tmp[mid];
return (tmp[mid - 1] + tmp[mid]) / 2.0;
}
bool SpreadOk()
{
double med = MedianSpread();
if(g_count < InpSamples / 4 || med <= 0)
return false; // not enough history yet
double cur = (double)SymbolInfoInteger(_Symbol, SYMBOL_SPREAD);
return (cur / med) <= InpMaxRatio;
}
void OnTick()
{
RecordSpread();
if(!SpreadOk()) return;
// entry logic here
}
Copying and sorting a few hundred ints once per tick is cheap, but if your EA is sensitive to OnTick time you can recompute the median only when a new sample is added.
Things to decide for your own strategy
- Block entries only, never exits. A stop loss should not wait for the spread to calm down.
- Keep a hard ceiling as well. If the median itself drifts very high, for example on a thin holiday session, a ratio check alone will happily allow trading at awful spreads. A simple absolute maximum on top covers that.
- Start in a waiting state. The filter returns false until a quarter of the window is filled, so the EA does not trade on the first tick after a restart with no baseline.
- In the Strategy Tester, use real ticks. With generated ticks the spread is fixed or simplified and the filter will look either useless or perfect.
A ratio of about two is a reasonable starting point for liquid FX pairs. For metals and indices, check the hourly spread profile first, because their normal range is much wider.
Top comments (0)