Online Trend Change Detector [MarkitTick]

918

More exclusive indicators from MarkitTick

Subscribe to MarkitTick for $43.75/month to get exclusive indicators by this author. You pay right on TradingView and can use them on your charts straight away.

Explore MarkitTick
💡 This script watches a price series against a straight trend line fitted to its own recent past, and reports when the series leaves that line by more than random noise would explain. Each stretch of the chart is treated as a segment: the first bars of the segment are used to fit a least-squares line and to measure how noisy price is around it, and every bar after that is judged by how far it sits from the extended line, in units of that measured noise. When the departure is a sustained level shift, the script records a jump; when it is a growing tilt away from the line, it records a kink. Both are compared with thresholds that the script calibrates itself from simulated no-change data, so the sensitivity is tied to a stated false alarm target instead of a hand-picked number.

✨ Originality and Utility
Most trend tools answer "which way is price moving right now". This script asks a different question: "has the trend I fitted stopped describing price". That is a change-point question, and it is answered with a statistic that has a known reference distribution rather than with a crossover or a fixed percentage move.
  • The fitted line is not a rolling average. It is a single least-squares line that is frozen after the burn-in and then projected forward, so the later bars are measured against a fixed yardstick instead of one that bends toward them.
  • The distance from the line is not measured in price or percent. It is measured in multiples of the noise found during the burn-in, so the same statistic is comparable on a quiet instrument and on a wild one.
  • The detection thresholds are not typed in by the user. They are produced by running simulated no-change series through the exact same fit, residual and statistic pipeline, then choosing levels that keep the joint false alarm rate at or below the False Alarm % input over the Horizon Bars input.
  • Two statistics run side by side. The jump statistic reacts to a shift in the average level; the kink statistic reacts to a change in slope. A trend can end by a gap away from the line or by slowly bending away, and each case is handled by its own measure.
  • A dashboard shows every number behind a decision: the statistic, its threshold and how close the statistic is to that threshold, so a detection can be read, not just trusted.

● What it does not do
The script does not forecast price, does not give entries, stops or targets, and does not claim that a detected change is the start of a profitable move. It reports a statistical departure from a fitted line, nothing more.

🔬 Methodology and Concepts
• Segments and the burn-in
The script works in segments. A segment starts at the first bar available (or, after a detection, on the next bar). During the first Burn-In Bars bars of the segment, nothing is monitored; the bars are collected and a straight line is fitted to them by ordinary least squares, with the bar number inside the segment as the horizontal axis.
  • From the fit the script keeps the intercept, the slope per bar and the noise level. The noise level is the residual standard deviation of the burn-in, computed with the usual two degrees of freedom removed for the two fitted parameters.
  • If the burn-in data is so flat that the noise level cannot be estimated, the burn-in is discarded and a new one starts on the next bar.
  • Once the fit is complete, the segment enters monitoring and the line is extended forward without refitting.

• Residuals in noise units
For every monitored bar the script takes the source value, subtracts the projected line value for that bar, and divides by the burn-in noise level. The result is the residual in units of sigma. A residual of 2 means price sits two burn-in noise levels above the projected line.

• Bins and the sliding window
Residuals are added into bins of Bin Size bars. The statistics read the last two full bins plus the bin currently being filled, so the window is never shorter than two bins and never longer than three bins minus one bar. Nothing is evaluated until two full bins exist.
  • Smaller bins make the window short and the statistics quick to react to a large move, at the cost of more noise in the statistics.
  • Larger bins make the window long and let the statistics see a smaller, steadier change, at the cost of a slower reaction.

• The jump statistic
The jump statistic is the absolute value of the average residual over the window. It is large when the recent bars sit consistently on one side of the projected line, which is what a level shift looks like. It is expressed in sigma.

• The kink statistic
The kink statistic weights each residual in the window by its position, with the newest bar weighted most, adds them up, and divides by the sum of the squared weights. This is the slope of the residuals against position through the origin, expressed in sigma per bar. It is large when residuals are drifting steadily away from the line, which is what a change of slope looks like. If the jump statistic and the kink statistic are both above their thresholds on one bar, the event is recorded as a jump.

• Calibrating the thresholds
The thresholds come from simulation. One simulated no-change run is computed per bar from the first bar of the chart. A run draws random Gaussian noise for Burn-In Bars bars, fits a line to it, estimates the noise level, then draws Horizon Bars more noise values, measures them against the extended line and records the highest jump statistic and the highest kink statistic reached.
  • After Simulations runs are done, the script sorts the recorded maxima and searches for the lowest pair of thresholds at which the share of runs exceeding either one is no more than the False Alarm %.
  • Because both statistics are tested together, the false alarm target applies to the pair jointly, not to each one alone.
  • The same Seed gives the same thresholds every time, so a chart reloads to the same numbers.
  • No detection can occur until all Simulations runs have been computed, which means detection starts only after that many bars from the first bar of the chart.

• Statistical limits to keep in mind
  • The simulation assumes independent random noise around a straight line. Real price series are often autocorrelated and fat-tailed, so the stated false alarm rate describes the simulated world and is a guide, not a promise, on live markets.
  • The false alarm target holds over Horizon Bars of monitoring. A segment that is monitored for longer than that has a higher chance of a false detection.
  • The line is straight. A series that curves will drift away from any straight line and can produce detections even without a regime change.

• Extreme Anchor
With Extreme Anchor off, a detection ends the segment and a new segment starts on the next bar. With it on, a detection is registered only after an extra reversal check: the script finds the highest high since the segment started if the fitted slope rises, or the lowest low if it falls, fits a least-squares line from that extreme to the detection bar, and requires that line to slope against the segment's fitted slope over at least Min New Bars bars. When the check passes, the new segment starts at that extreme and the bars from the extreme up to the detection bar already count toward its burn-in.
  • A detection is rejected as Too Few Bars when the extreme is closer than Min New Bars.
  • A detection is rejected as Out of Reach when the extreme is more than 5,000 bars back.
  • A detection is rejected as Same Direction when the line from the extreme slopes the segment's own way.
  • These conditions only remove detections the statistics would otherwise register. The thresholds are not recalibrated for them.


🎨 Visual Guide
● On the price chart
  • Solid fit line over the burn-in bars: the least-squares line of the segment. It is drawn in the Rising Line colour (teal by default) when its slope is zero or positive and in the Falling Line colour (red by default) when its slope is negative.
  • Dashed line after the burn-in: the same fitted line extended forward over the monitoring bars. This is the line the residuals are measured from.
  • Upper and lower band lines: two lines placed Band Width times the burn-in noise above and below the fit line. They are solid over the burn-in bars and dashed after them, in the segment's colour.
  • Dotted, faded lines: the provisional channel. While a segment is still in its burn-in, a fit line and its bands are drawn over the bars gathered so far, from the third bar on, in the segment's colour made 50 points more transparent. It is a preview of the channel being built and disappears when the burn-in ends, so the confirmed channel can differ from it.
  • Segment ends: when a change is registered, the old segment's lines stop at that bar and a new segment begins.

● The bands are display only
Detection never uses the bands. Price can close outside a band without any change being detected, and a change can be detected with price inside the bands.

● The dashboard
The panel sits in the corner chosen in the Position input and has a header showing the symbol and timeframe.
  • Phase: Burn-In or Monitoring.
  • Burn-In: a ten-block progress bar with a percentage of the burn-in completed.
  • Segment Start and Segment Bars: when the current segment started and how many bars it has.
  • Fit Direction and Slope / Bar: Rising or Falling, and the fitted slope per bar, in the line's colour.
  • Noise (Sigma): the burn-in noise level in price units.
  • Projection, Upper Band and Lower Band: the projected line and band values for the current bar.
  • Residual: the current residual in sigma.
  • Window: the number of bars in the statistics window.
  • Jump Stat, Jump Threshold and Jump Load: the jump statistic in sigma, its calibrated threshold, and a progress bar showing the statistic as a share of the threshold.
  • Kink Stat, Kink Threshold and Kink Load: the same three rows for the kink statistic, in sigma per bar.
  • Calibration: progress of the simulation runs. The thresholds show a dash until all runs are done.
  • Last Change and Changes Detected: the type (Jump or Kink), the side (Above or Below) and the date of the last detection, plus a running count. Above is shown in the Rising Line colour and Below in the Falling Line colour.
  • Reversal Check and Segment Extreme: shown only with Extreme Anchor on. The first gives the result of the last reversal check (Passed, Too Few Bars, Out of Reach or Same Direction); the second gives the current segment's high or low.

● Chart type notice
On Heikin Ashi, Renko, Kagi, Point and Figure, Range and Line Break charts, the script shows a red notice in the middle of the chart and does not run, because those charts display synthetic prices. Use standard candles.

📖 How to Use
  1. Add the script to a standard candle chart and wait for calibration. The Calibration row on the dashboard must be complete before any detection can occur.
  2. Let the first segment finish its burn-in. Read the Fit Direction row to see whether the fitted line rises or falls, and use the dashed projection and bands as the reference path.
  3. Watch the Jump Load and Kink Load bars. A bar that fills toward 100 percent shows the statistic approaching its threshold; it is a gauge of departure from the line, not an instruction.
  4. A detection is recorded as Jump or Kink with the side Above or Below. Above means residuals moved to the upside of the projected line; Below means they moved to the downside.
  5. Read the type together with the side. A Jump Below on a rising fit means price has settled under the line the trend was following. A Kink Above on a falling fit means price is bending upward away from a falling line.
  6. After a detection, the next segment must complete its own burn-in before monitoring resumes, so the script is deliberately quiet for a stretch after every change.
  7. Use the result as a statistical context layer next to your own analysis of structure, volume and risk. It describes departure from a fitted line and says nothing about what price does next.

● Choosing the timeframe
A longer burn-in describes the trend over a longer span and gives a steadier noise estimate. A shorter burn-in follows local behaviour but its noise estimate is rougher. The Horizon Bars input should be close to the number of bars you normally expect a segment to last.

⚙️ Inputs and Settings
● Core Settings
  • Source: the series the line is fitted to and watched. The default is close.
  • Burn-In Bars (default 100): bars at the start of each segment used for the fit and the noise estimate. No change can be detected during them.
  • Bin Size (default 5): bars per bin. It sets the window length as described above.
  • Extreme Anchor (default off): turns on the reversal check and the extreme-based start of the next segment.
  • Min New Bars (default 10): with Extreme Anchor on, the fewest bars from the extreme to the detection bar.

● Calibration
  • False Alarm % (default 5): target chance of a false detection over Horizon Bars with no real change. Lower values raise the thresholds and mean fewer detections.
  • Horizon Bars (default 300): monitoring bars each simulated run covers.
  • Simulations (default 200): number of simulated runs. More runs make the thresholds steadier but delay the start of detection.
  • Seed (default 42): seed of the simulated noise.

● Visuals
  • Show Fit Lines, Show Projection and Show Bands switch each drawing on or off. With all three off, segments are not kept for drawing.
  • Band Width (default 2.0 sigma): distance of the bands from the fit line. Display only.
  • Show Provisional Channel: the dotted preview during burn-in.
  • Max Segments Displayed (default 50): removes the oldest segments' drawings beyond this count. Lines are drawn only over the last 5,000 bars.
  • Line Width: width of the fit and projection lines.

● Dashboard, Alerts and Colors
  • Show Dashboard and Position: show the panel and choose its corner.
  • Alert: Change Point and Change Point Action: switch the alert on or off and set the action word carried in the alert message. The message holds the action, symbol, timeframe, price, type (jump or kink), side (above or below), the statistic and its threshold.
  • Colour inputs: Rising Line, Falling Line, dashboard background, header and text, and the two ends of the progress bar gradient.


🔍 Deconstruction of the Underlying Scientific and Academic Framework
• Change-point detection
A change point is the moment at which the statistical behaviour of a series changes. Detecting it as data arrives, with a model fitted beforehand and a rule applied to each new observation, is called online or sequential detection, in contrast with offline methods that look at a whole finished series. This script uses the online form: a training stretch defines the reference behaviour, and a monitoring stretch is tested against it.

• Ordinary least squares and the noise estimate
The reference model is a straight line fitted by ordinary least squares, which minimises the sum of squared vertical distances between the data and the line. The noise level is the square root of the residual sum of squares divided by the number of observations minus two, the standard unbiased estimate of the residual variance for a two-parameter line.

• Studentised residuals
Dividing each new deviation by the estimated noise level puts all residuals on a common scale. Under the model's assumptions, the residuals of a no-change series have mean zero and a spread near one, so sums and averages of them have known behaviour.

• Level and slope contrasts
The jump statistic is the sample mean of the window's residuals, a direct test for a shift of level. The kink statistic is a position-weighted sum divided by the sum of squared weights, which is the least-squares slope of the residuals on position through the origin and is the natural test for a drifting trend. Using weights that are constant for one and linear for the other is the standard way to build sensitivity to level changes and slope changes from the same residual stream.

• Monitoring over a horizon
Testing every new bar is repeated testing, so the chance that at least one test exceeds a fixed cut-off grows with time. Controlling that error needs a threshold tied to the maximum of the statistic over the whole monitoring horizon, not to a single bar. The script records exactly that maximum in each simulated run.

• Monte Carlo calibration
Because the maximum of a running statistic over a horizon has no simple closed form once the fit is estimated from a finite training stretch, the script uses Monte Carlo simulation. It draws no-change series with Gaussian noise using the Box-Muller transform, sends them through the same fit, residual and statistic steps, and reads the thresholds from the empirical distribution of the maxima. Selecting the pair so that the share of runs exceeding either statistic is no more than the target gives a joint control of the false alarm rate.

• Assumptions and their consequences
The theory assumes independent, identically distributed noise and a truly linear reference. Market data departs from both, so thresholds calibrated on simulated noise are a statistical reference scale rather than a guarantee of the rate on live data. Treat the output as a measured departure from a fitted line.

⚠️ Disclaimer
All provided scripts and indicators are strictly for educational exploration and must not be interpreted as financial advice or a recommendation to execute trades. We expressly disclaim all liability for any financial losses or damages that may result, directly or indirectly, from the reliance on or application of these tools. Market participation carries inherent risk where past performance never guarantees future returns, leaving all investment decisions and due diligence solely at your own discretion.

Feragatname

Bilgiler ve yayınlar, TradingView tarafından sağlanan veya onaylanan finansal, yatırım, alım satım veya diğer türden tavsiye veya öneriler anlamına gelmez ve teşkil etmez. Kullanım Koşulları bölümünde daha fazlasını okuyun.