Watch how to download trading robots for free
Find us on Twitter!
Join our fan page
Interesting script?
So post a link to it -
let others appraise it
You liked the script? Try it in the MetaTrader 5 terminal
Indicators

Trend or Chop? A Variance-Ratio Scoreboard That Shows Whether Your Symbol Trends or Mean-Reverts on Each Horizon - indicator for MetaTrader 5

Views:
24
Published:
MQL5 Freelance Need a robot or indicator based on this code? Order it on Freelance Go to Freelance

Trend or Chop? A Variance-Ratio Scoreboard That Shows Whether Your Symbol Trends or Mean-Reverts on Each Horizon

The idea behind it

"This pair trends", "this one just chops": almost every trader has an opinion, and the opinion decides which strategies they try. Trend following needs moves that continue, and fading needs moves that reverse. The opinion can be measured, and the measure is old and simple: the variance ratio.

Take the price changes over one bar and over q bars, both as logarithms of the close. If price moves were completely independent from bar to bar (a random walk), the variance of the q-bar change would be q times the variance of the one-bar change. So the ratio

VR(q) = variance of q-bar changes / (q x variance of one-bar changes)

is close to 1 for a random walk. If moves tend to continue, the q-bar changes get larger than that and VR is above 1. If moves tend to reverse, they get smaller and VR is below 1. The two cases are very different markets, and they can exist on the same symbol at different horizons: a symbol can reverse over 2 bars and still trend over 32.

The details of the calculation:

  • Returns. The one-bar return is the natural logarithm of the close divided by the previous close. The q-bar return is the same over q bars. The q-bar returns overlap, which uses the data well but means that neighboring values are not independent.
  • Variance. Both variances are taken around their own mean, so a steady drift does not count as movement.
  • Horizons. Five horizons, InpHorizon1 to InpHorizon5 . They are raised, if needed, to rise strictly from one to the next.
  • Two sets of figures. "All" is every bar that was analysed. "Now" is a rolling window of the last InpWindowBars bars. Markets change character, so the two can disagree, and the disagreement is often the interesting part.
  • z-score. How far the ratio is from 1 in standard errors: z = (VR - 1) / sqrt(2 (2q - 1) (q - 1) / (3 q n)) , where n is the number of one-bar returns. The verdict is TREND when z is at least InpZLimit , CHOP when it is at most minus InpZLimit , and NOISE in between.

The z-score is the textbook value for independent returns with the same variance. Real prices have volatility that comes in waves and have fat tails, and for such data the true standard error is larger, so the z-score tends to be too big. Treat the verdict as a rough guide, keep InpZLimit well above 2, and trust figures that are strong, that agree between horizons and that agree between the window and the whole history.

There is no look-ahead and no repainting of closed bars. Only closed bars enter the statistics. The newest bar, which is still forming, has no value on the lines. The calculation is incremental: the indicator keeps running sums of the returns and of their squares for each horizon, adds the returns of each new bar and subtracts the ones that leave the window. A call on a new tick costs a few dozen operations, and the history is never rescanned.

How to interpret it

  • Lines (indicator window). One line for each horizon, the ratio over the rolling window at each closed bar. The shortest horizon is the darkest gray and the longest the white, thicker line. The dotted line at 1 is the random walk. Lines above it mean trending, below it mean reversal. The lines start one full window after the first analysed bar, because a partial window is not comparable.
  • Reading the lines. All lines above 1 means trending on every horizon. All below 1 means chop. Lines on both sides of 1 mean a mixed market, for example reversal over a few bars and trend over many. Lines that fall or rise together show a change of regime.
  • Data Window. The five ratios of the bar, named by their horizon in bars.
  • Panel (top left of the chart).
    • Line 1: symbol, timeframe, the number of returns analysed, the window length and the z limit of the verdict.
    • Line 2: the column names.
    • Lines 3-7: one row per horizon with the ratio, the z-score and the verdict, first for the whole history ("all") and then for the rolling window ("now"). A figure shows "--" until there are enough returns: InpMinReturns for "all" and one full window for "now".
    • Line 8: how many of the five horizons trend, chop or are noise, for the window and for the whole history.
    • Line 9: a reminder of how to read a ratio, and of the assumption behind the z-score.
    • Line 10: one line with symbol, timeframe, the number of bars, the five ratios of the whole history and the verdict letters (T trend, C chop, N noise) for the whole history and for the window, ready to be copied into a comment.


Fig. 1. The last 700 bars of a simulated H1 series that trends for 4,300 bars and then chops. The five lines start above the dotted line at 1 and fall below it as the window fills with the choppy part, the longest horizon last. The panel counts all 5,000 returns: the whole history reads TREND on every horizon, and the last 1,000 bars read CHOP on the short horizons. The numbers come from simulated data and say nothing about any real market. Black and white screenshot, per the Code Base image guidelines.

External variables (inputs)

Input Default Purpose
InpHorizon1 2 Horizon 1 in bars (2-500).
InpHorizon2 4 Horizon 2 in bars. It is raised to be longer than horizon 1.
InpHorizon3 8 Horizon 3 in bars. It is raised to be longer than horizon 2.
InpHorizon4 16 Horizon 4 in bars. It is raised to be longer than horizon 3.
InpHorizon5 32 Horizon 5 in bars. It is raised to be longer than horizon 4.
InpWindowBars 1000 Rolling window in bars (100-20000). It is raised to at least 4 times the longest horizon, so that the long horizons have enough returns.
InpMinReturns 200 Fewest returns before the whole-history figures are shown (50-5000).
InpZLimit 2.5 The verdict is TREND or CHOP when the z-score is beyond this value (1-6).
InpHistoryBars 50000 Newest bars analysed when the indicator loads or is fully recalculated. 0 analyses all bars. New bars are added as they arrive.
InpShowPanel true Show the statistics panel.
InpColorShort clrDimGray Line color of horizon 1. The lines of horizons 2-4 are mixed between this color and the long color.
InpColorLong clrWhite Line color of horizon 5.
InpTextColor clrSilver Panel text color.
InpFontSize 8 Panel font size (Consolas). The line height follows the size.
InpPanelX , InpPanelY 8, 14 Panel offset from the upper left corner of the chart, in pixels.

Recommended use

  • Symbols and timeframes. Any symbol and any timeframe. The ratio describes one symbol on one timeframe, so H1 and M15 give different answers, and the horizons are counted in bars of the chart. 2 bars of M5 and 2 bars of D1 are not the same thing.
  • Compare symbols with the same inputs. The line at the end of the panel is made for that. Put the indicator with the same horizons, window and z limit on several symbols and compare the verdict letters and the ratios.
  • Look at the number of returns. A window of 1000 bars gives noisy ratios, especially for the long horizons: 1000 bars hold only about 31 separate, non-overlapping 32-bar changes. A line that moves a lot from bar to bar is noise before it is a regime. Increase InpWindowBars to smooth it.
  • Short-horizon ratios below 1 are common in bar data. Bid-ask bounce, rounding and thin trading push the shortest horizons below 1 on many symbols, and this effect says little about whether a strategy can use it. Look at the trend of the ratio over the horizons, not at one value.
  • The z-score is optimistic. It assumes independent returns with the same variance. Volatility clusters in real markets, and large moves are more frequent than the normal distribution allows. So a z of 3 on real data is weaker than it looks. Use InpZLimit of 3 or more if you want few false verdicts.
  • Five verdicts are not five tests. The horizons share the same data and the q-bar changes overlap, so the verdicts of neighboring horizons are strongly related. Two TREND marks next to each other are close to one finding.
  • Check both halves of the history. Change InpHistoryBars to see an older and a newer part. A ratio that is above 1 in one half and below 1 in the other is not a property of the symbol.
  • A ratio is not a profit. A ratio of 0.95 or 1.05 is hard to trade after spread and swap. The indicator does not include costs and does not tell you where to enter.
  • It describes the past. The table shows what was usual in the loaded history. It does not predict the next move.
  • The data is the broker's data. The closes depend on the feed and on its time zone, and holes in the history change the returns. A different broker can give slightly different figures.
  • Prices. The returns use the logarithm of the close, so symbols that can have a close of zero or below (for example some spreads) are not supported: such a bar is treated as a close with a logarithm of 0.
  • Performance and memory. Each bar is processed once, with about two dozen additions per bar. The state is a few dozen numbers. Later ticks only update the panel.
  • Chart objects. The only objects are the panel lines in the main chart window, named with the prefix VR_P . They are removed in OnDeinit() .
  • Account types. The indicator does not trade and does not depend on netting or hedging accounts.
  • Your turn: post your scoreboard. Attach the indicator to a chart you trade, copy the last line of the panel and post it in the comments with the name of your broker. This is only the format, and its numbers are made up: EURUSD H1 | 50000 bars | VR(all) 2:0.97 4:0.95 8:0.93 16:0.91 32:0.90 | profile all CCCNN now NNNNN . Which of your symbols trend, and which chop? Does your favorite symbol trend on a long horizon and reverse on a short one? Post your most surprising result.
PropFirm Consistency and Drawdown Monitor PropFirm Consistency and Drawdown Monitor

Read-only PropFirm daily drawdown, trailing total drawdown, and single-day consistency cap HUD monitor with four closed-bar iCustom buffers.

Breakout Follow-Through Statistics: Real Break or Fakeout After a New N-Bar High or Low? Breakout Follow-Through Statistics: Real Break or Fakeout After a New N-Bar High or Low?

Every new N-bar high or low gets tagged, timed, and scored — real breakout or fakeout — so the scorecard tells you what this symbol has actually done at its own extremes, not what you assume it does.

Accelerator Oscillator (AC) Accelerator Oscillator (AC)

The Acceleration/Deceleration Indicator (AC) measures acceleration and deceleration of the current driving force.

MACD Signals MACD Signals

Indicator edition for new platform.