Crash-Guard Trend (#TSBuild26)
Crash-Guard Trend is a long-only trend and volatility indicator designed for Dow 30 stocks on the 2-hour timeframe. Its goal is to stay invested during healthy uptrends and ordinary pullbacks while stepping aside when market conditions begin to resemble a sharp sell-off.
The indicator combines a 60-period EMA with a volatility regime filter that compares short-term (20-bar) volatility with long-term (200-bar) volatility. A BUY signal occurs when price is above the EMA and volatility is calm. A SELL signal occurs only when price falls below the EMA and short-term volatility spikes above 1.5× its longer-term level.
Unlike a traditional trend-following system that may exit on every break below a moving average, Crash-Guard is designed to filter out normal market noise and remain invested through ordinary dips, while reacting to trend deterioration accompanied by abnormal volatility.
The indicator is non-repainting, uses completed candles only, and enforces alternating BUY and SELL signals. A built-in dashboard displays the current market regime, position status, volatility conditions, next potential signal, and strategy performance versus buy-and-hold.
Core concept: Stay invested through the noise. Step aside when trend weakness and abnormal volatility appear together. #TSBuild26
// =====================================================================
// Crash-Guard Trend — long-only BUY / SELL signals + dashboard
// Designed for: Dow 30 stocks, 2-HOUR candles, regular trading hours
// =====================================================================
// Idea: stay invested while the short-term trend is up (buy-and-hold core),
// and step aside only when a trend break arrives TOGETHER with a volatility
// spike — the signature of a sharp sell-off. Ordinary dips below the trend
// line are held through, because in research they usually recovered.
// After a SELL, buy back only once the trend is up AND the spike has calmed,
// which avoids whipsaw SELL-BUY-SELL clusters during turbulent periods.
//
// Volatility ratio = stdev(log returns, 20 bars) / stdev(log returns, 200 bars)
// ( 5 trading days vs 50 trading days on 2h candles)
//
// BUY : close > EMA(60) AND volatility ratio < 1.5 (EMA 60 = 15 trading days)
// SELL : close < EMA(60) AND volatility ratio > 1.5
//
// Non-repainting:
// * every value at candle i uses only candles 0..i (no future data)
// * signals are never placed on the candle that is still forming
// * BUY and SELL strictly alternate (position-aware loop), long only
//
// Chart legend (EMA line colour):
// green = above EMA, volatility calm -> uptrend: BUY allowed / holding
// purple = above EMA, volatility elevated -> uptrend but turbulent: no new BUY yet
// amber = below EMA, volatility normal -> ordinary dip: holding
// red = below EMA, volatility spike -> crash conditions: SELL
//
// Dashboard: current state, the two signal conditions with live values, what
// would trigger the next signal, and how the signals performed on the loaded
// chart versus buy-and-hold (close-to-close, no costs — for orientation only).
// =====================================================================
// warmup 800: the 200-bar volatility window plus time for EMA(60) to forget its starting value,
// so the chart and the Strategy Tester compute identical values in the visible range
describe_indicator('Crash-Guard Trend Final', 'price', { shortName: 'CGT', warmup: 800 });
// ---- inputs (defaults = the researched settings for 2h candles) ----
const TREND_LEN = input.number('Trend EMA length (bars)', 60, { min: 2, max: 1000 });
const VOL_SHORT_LEN = input.number('Short volatility', 20, { min: 2, max: 1000 });
const VOL_LONG_LEN = input.number('Long volatility', 200, { min: 3, max: 2000 });
const VOL_RATIO = input.number('Volatility spike ratio', 1.5, { min: 1, max: 5 });
const SHOW_LABELS = input.boolean('Show BUY / SELL labels', true);
const SHOW_DASHBOARD = input.boolean('Show dashboard', true);
const SHOW_EQUITY_CHART = input.boolean('Show equity chart in dashboard', true);
const DASHBOARD_POSITION = input.select('Dashboard position', 'top_right',
['top_left', 'top_right', 'bottom_left', 'bottom_right']);
// Strategy Tester (Trade By = Open) decides at a candle's close and fills at the NEXT candle's open.
// 'Fill candle' moves only the labels one candle right so they sit on the tester's entry/exit arrows.
// The registered BUY/SELL signals always stay on the candle where the condition was met.
const LABEL_PLACEMENT = input.select('Label placement', 'Signal candle', ['Signal candle', 'Fill candle (next open)']);
assert(VOL_SHORT_LEN < VOL_LONG_LEN, 'Short volatility window must be shorter than the long one');
const candleCount = close.length;
// ---- EMA seeded with the first close (identical to the research code) ----
function exponentialMovingAverage(values, windowLength) {
const alpha = 2 / (windowLength + 1);
const result = series_of(null);
for (let i = 0; i < values.length; i += 1) {
result[i] = i === 0 ? values[0] : alpha * values[i] + (1 - alpha) * result[i - 1];
}
return result;
}
// ---- rolling SAMPLE standard deviation; null until the window is full ----
function rollingSampleStdev(values, windowLength) {
const result = series_of(null);
for (let i = windowLength - 1; i < values.length; i += 1) {
let windowSum = 0;
let valid = true;
for (let k = i - windowLength + 1; k <= i; k += 1) {
if (values[k] === null) { valid = false; break; }
windowSum += values[k];
}
if (!valid) continue;
const windowMean = windowSum / windowLength;
let squares = 0;
for (let k = i - windowLength + 1; k <= i; k += 1) {
squares += (values[k] - windowMean) ** 2;
}
result[i] = Math.sqrt(squares / (windowLength - 1));
}
return result;
}
const trendLine = exponentialMovingAverage(close, TREND_LEN);
const logReturns = close.map((c, i) => (i === 0 ? null : Math.log(c / close[i - 1])));
const volShort = rollingSampleStdev(logReturns, VOL_SHORT_LEN);
const volLong = rollingSampleStdev(logReturns, VOL_LONG_LEN);
const volatilityRatio = volShort.map((vs, i) =>
vs === null || volLong[i] === null || volLong[i] === 0 ? null : vs / volLong[i]);
const isAboveTrend = close.map((c, i) => c > trendLine[i]);
const isVolatilityCalm = volatilityRatio.map(v => v !== null && v < VOL_RATIO);
const isVolatilitySpike = volatilityRatio.map(v => v !== null && v > VOL_RATIO);
const isBuyCondition = close.map((c, i) => isAboveTrend[i] && isVolatilityCalm[i]);
const isCrashCondition = close.map((c, i) => c < trendLine[i] && isVolatilitySpike[i]);
// ---- do not signal on the candle that is still forming ----
function resolutionSeconds() {
const res = String(current.resolution);
if (/^d+$/.test(res)) return Number(res) * 60;
if (res.startsWith('D')) return 24 * 3600;
if (res.startsWith('W')) return 7 * 24 * 3600;
return 31 * 24 * 3600;
}
const toSeconds = t => (t > 1e12 ? t / 1000 : t);
const lastIndex = candleCount - 1;
const lastCandleComplete = lastIndex < 0 ||
toSeconds(current.now) >= toSeconds(time[lastIndex]) + resolutionSeconds();
const lastUsableIndex = lastCandleComplete ? lastIndex : lastIndex - 1;
// ---- position-aware signal loop: strict BUY -> SELL -> BUY alternation ----
const buySignals = series_of(null);
const sellSignals = series_of(null);
const buyLabels = series_of(null);
const sellLabels = series_of(null);
const isHolding = series_of(false); // true on candles whose close-to-close return the position earns
let inPosition = false;
for (let i = 0; i <= lastUsableIndex; i += 1) {
if (inPosition) isHolding[i] = true; // held into this candle (includes the SELL candle)
if (!inPosition && isBuyCondition[i]) {
inPosition = true;
buySignals[i] = true;
buyLabels[i] = '▲ BUY';
} else if (inPosition && isCrashCondition[i]) {
inPosition = false;
sellSignals[i] = true;
sellLabels[i] = '▼ SELL';
}
}
// ---- exactly one BUY and one SELL signal for the Strategy Tester ----
register_signal(buySignals, 'BUY');
register_signal(sellSignals, 'SELL');
// ---- optionally draw the labels on the Strategy Tester's fill candle (display only) ----
const labelOffset = LABEL_PLACEMENT === 'Signal candle' ? 0 : 1;
const buyLabelsShown = series_of(null);
const sellLabelsShown = series_of(null);
for (let i = 0; i + labelOffset < candleCount; i += 1) {
if (buyLabels[i] !== null) buyLabelsShown[i + labelOffset] = buyLabels[i];
if (sellLabels[i] !== null) sellLabelsShown[i + labelOffset] = sellLabels[i];
}
// ---- chart visuals ----
const COLOR_CALM_UP = '#26a69a';
const COLOR_TURBULENT_UP = '#9c6ade';
const COLOR_DIP = '#f5a623';
const COLOR_CRASH = '#ef5350';
const COLOR_BUY = '#1b8a3a';
const COLOR_SELL = '#c62828';
const trendColors = close.map((c, i) => {
if (isBuyCondition[i]) return COLOR_CALM_UP;
if (isAboveTrend[i]) return COLOR_TURBULENT_UP;
if (isCrashCondition[i]) return COLOR_CRASH;
return COLOR_DIP;
});
paint(trendLine, { name: 'Trend EMA', color: trendColors, thickness: 2 });
paint(volatilityRatio, { name: 'Volatility ratio', hidden: true });
paint(SHOW_LABELS ? buyLabelsShown : constants.empty_series, {
name: 'Buy label', style: 'labels_below', color: 'white', backgroundColor: COLOR_BUY,
backgroundBorderRadius: 3, fontSize: 11,
});
paint(SHOW_LABELS ? sellLabelsShown : constants.empty_series, {
name: 'Sell label', style: 'labels_above', color: 'white', backgroundColor: COLOR_SELL,
backgroundBorderRadius: 3, fontSize: 11,
});
// =====================================================================
// Dashboard (display only — nothing below changes the signals)
// =====================================================================
const COLOR_PANEL = '#131722';
const COLOR_ROW = '#1a1e2b';
const COLOR_TEXT = '#d1d4dc';
const COLOR_MUTED = '#787b86';
const COLOR_GOOD = '#26a69a';
const COLOR_BAD = '#ef5350';
const statsStart = Math.min(VOL_LONG_LEN, Math.max(lastUsableIndex, 0));
const priceDecimals = current.decimals != null && isFinite(current.decimals)
? Math.min(Math.max(Math.round(current.decimals), 0), 6) : 2;
const formatPrice = value => (value == null ? '—' : Number(value).toFixed(priceDecimals));
const formatPercent = (value, digits = 1) => (value == null || !isFinite(value) ? '—'
: `${value >= 0 ? '+' : ''}${(value * 100).toFixed(digits)}%`);
// ---- replay the signals on the loaded chart: equity, drawdown, trades ----
let strategyEquity = 1;
let buyHoldEquity = 1;
let strategyPeak = 1;
let buyHoldPeak = 1;
let strategyMaxDrawdown = 0;
let buyHoldMaxDrawdown = 0;
let candlesHeld = 0;
const strategyCurve = [];
const buyHoldCurve = [];
const closedTradeReturns = [];
let openEntryPrice = null;
let lastSignalIndex = null;
let lastSignalType = null;
for (let i = statsStart; i <= lastUsableIndex; i += 1) {
if (i > statsStart) {
const candleReturn = close[i] / close[i - 1] - 1;
buyHoldEquity *= 1 + candleReturn;
if (isHolding[i]) {
strategyEquity *= 1 + candleReturn;
candlesHeld += 1;
}
}
strategyPeak = Math.max(strategyPeak, strategyEquity);
buyHoldPeak = Math.max(buyHoldPeak, buyHoldEquity);
strategyMaxDrawdown = Math.min(strategyMaxDrawdown, strategyEquity / strategyPeak - 1);
buyHoldMaxDrawdown = Math.min(buyHoldMaxDrawdown, buyHoldEquity / buyHoldPeak - 1);
if (buySignals[i]) {
openEntryPrice = close[i];
lastSignalIndex = i;
lastSignalType = 'BUY';
} else if (sellSignals[i]) {
if (openEntryPrice !== null) closedTradeReturns.push(close[i] / openEntryPrice - 1);
openEntryPrice = null;
lastSignalIndex = i;
lastSignalType = 'SELL';
}
strategyCurve.push(strategyEquity);
buyHoldCurve.push(buyHoldEquity);
}
const statsCandles = Math.max(lastUsableIndex - statsStart, 1);
const winningTrades = closedTradeReturns.filter(r => r > 0).length;
const winRate = closedTradeReturns.length ? winningTrades / closedTradeReturns.length : null;
const timeInMarket = candlesHeld / statsCandles;
const openTradeReturn = openEntryPrice !== null ? close[lastUsableIndex] / openEntryPrice - 1 : null;
const barsSinceSignal = lastSignalIndex !== null ? lastUsableIndex - lastSignalIndex : null;
// ---- downsample equity curves to at most ~120 points for the mini chart ----
const curveStep = Math.max(1, Math.ceil(strategyCurve.length / 120));
const pickEvery = values => values.filter((v, i) => i % curveStep === 0 || i === values.length - 1)
.map(v => Number(((v - 1) * 100).toFixed(2)));
const strategyPoints = pickEvery(strategyCurve);
const buyHoldPoints = pickEvery(buyHoldCurve);
const chartLabels = strategyPoints.map(() => '');
// ---- current state (last completed candle) ----
const nowIndex = Math.max(lastUsableIndex, 0);
const nowClose = close[nowIndex];
const nowTrend = trendLine[nowIndex];
const nowRatio = volatilityRatio[nowIndex];
const distanceToTrend = nowTrend ? nowClose / nowTrend - 1 : null;
let stateText = 'Warming up';
let stateColor = COLOR_MUTED;
if (nowRatio !== null) {
if (isBuyCondition[nowIndex]) { stateText = 'Uptrend · calm'; stateColor = COLOR_CALM_UP; }
else if (isAboveTrend[nowIndex]) { stateText = 'Uptrend · turbulent'; stateColor = COLOR_TURBULENT_UP; }
else if (isCrashCondition[nowIndex]) { stateText = 'Crash conditions'; stateColor = COLOR_CRASH; }
else { stateText = 'Dip · volatility normal'; stateColor = COLOR_DIP; }
}
const positionText = inPosition ? 'LONG' : 'FLAT';
const positionColor = inPosition ? COLOR_GOOD : COLOR_MUTED;
let nextActionText = 'Waiting for data';
if (nowRatio !== null) {
nextActionText = inPosition
? `SELL if close < ${formatPrice(nowTrend)} and vol ratio > ${VOL_RATIO.toFixed(2)}`
: `BUY if close > ${formatPrice(nowTrend)} and vol ratio < ${VOL_RATIO.toFixed(2)}`;
}
const ratioText = nowRatio === null ? '—' : `${nowRatio.toFixed(2)} / ${VOL_RATIO.toFixed(2)}`;
const ratioColor = nowRatio === null ? COLOR_MUTED : (nowRatio > VOL_RATIO ? COLOR_CRASH : COLOR_CALM_UP);
const trendText = distanceToTrend === null ? '—'
: `${isAboveTrend[nowIndex] ? 'Above' : 'Below'} ${formatPercent(distanceToTrend)}`;
const trendColor = isAboveTrend[nowIndex] ? COLOR_CALM_UP : COLOR_DIP;
const lastSignalText = lastSignalType === null ? '—'
: `${lastSignalType} · ${barsSinceSignal} bars ago @ ${formatPrice(close[lastSignalIndex])}`;
const lastSignalColor = lastSignalType === 'BUY' ? COLOR_GOOD : (lastSignalType === 'SELL' ? COLOR_BAD : COLOR_MUTED);
// ---- volatility gauge: 10 cells, the white divider marks the spike threshold ----
const GAUGE_CELLS = 10;
const gaugeFill = nowRatio === null ? 0 : Math.min(GAUGE_CELLS, Math.round(nowRatio / (2 * VOL_RATIO) * GAUGE_CELLS));
const gaugeCells = [];
for (let g = 0; g < GAUGE_CELLS; g += 1) {
const filled = g < gaugeFill;
const beyondThreshold = g >= GAUGE_CELLS / 2;
gaugeCells.push({
text: ' ', width: '7px', height: '8px', padding: '0', fontSize: '1px', borderRadius: '1px',
background: filled ? (beyondThreshold ? COLOR_CRASH : COLOR_CALM_UP) : 'rgba(120, 123, 134, 0.3)',
borderRight: g === GAUGE_CELLS / 2 - 1 ? '2px solid #d1d4dc' : 'none',
});
}
// ---- table helpers ----
const labelCell = text => ({
text, color: COLOR_MUTED, background: COLOR_ROW, padding: '3px 8px', fontSize: '10px',
fontWeight: '600', whiteSpace: 'nowrap',
});
const valueCell = (text, color) => ({
text, color, background: COLOR_ROW, padding: '3px 8px', fontSize: '10px', fontWeight: '700',
textAlign: 'right', whiteSpace: 'nowrap',
});
const sectionRow = text => ({
cells: [{
text, colspan: 2, color: COLOR_MUTED, background: COLOR_PANEL, padding: '5px 8px 2px 8px',
fontSize: '9px', fontWeight: '700', letterSpacing: '0.08em',
}],
});
const pairRow = (label, value, color) => ({ cells: [labelCell(label), valueCell(value, color)] });
const compareText = (strategyValue, buyHoldValue) => `${formatPercent(strategyValue)} vs ${formatPercent(buyHoldValue)}`;
const betterOrEqual = (strategyValue, buyHoldValue) => (strategyValue >= buyHoldValue ? COLOR_GOOD : COLOR_TEXT);
const isTwoHourChart = String(current.resolution) === '120';
const isExtendedHours = current.is_ext_hours === true;
const chartType = String(current.chart_type || 'candles');
const isStandardCandles = ['candles', 'bars', 'hollowcandles', 'line'].indexOf(chartType) !== -1;
const setupText = `${isTwoHourChart ? '2h' : `${current.resolution} (not 2h)`} · ${isExtendedHours ? 'EXTENDED hours' : 'regular hours'} · ${isStandardCandles ? chartType : `${chartType} ⚠`}`;
const setupIsStandard = isTwoHourChart && !isExtendedHours && isStandardCandles;
const setupColor = setupIsStandard ? COLOR_MUTED : COLOR_DIP;
const dashboardRows = [
{
cells: [{
text: 'CRASH-GUARD TREND', colspan: 2, color: COLOR_TEXT, background: COLOR_PANEL,
padding: '6px 8px 1px 8px', fontSize: '11px', fontWeight: '700', letterSpacing: '0.06em',
}],
},
{
cells: [{
text: 'Long-only · stay in uptrends, exit on crash signature', colspan: 2, color: COLOR_MUTED,
background: COLOR_PANEL, padding: '0 8px 5px 8px', fontSize: '9px',
borderBottom: '1px solid rgba(120, 123, 134, 0.35)',
}],
},
pairRow('Chart setup', setupText, setupColor),
sectionRow('STATUS'),
pairRow('Position', positionText, positionColor),
pairRow('Regime', stateText, stateColor),
pairRow('Last signal', lastSignalText, lastSignalColor),
pairRow('Open trade', openTradeReturn === null ? '—' : formatPercent(openTradeReturn),
openTradeReturn === null ? COLOR_MUTED : (openTradeReturn >= 0 ? COLOR_GOOD : COLOR_BAD)),
sectionRow('SIGNAL CHECK'),
pairRow(`Close vs EMA(${TREND_LEN})`, trendText, trendColor),
pairRow('Volatility ratio', ratioText, ratioColor),
{
cells: [
labelCell('Calm | spike'),
{
background: COLOR_ROW, padding: '3px 8px', textAlign: 'right',
table: { cellSpacing: 1, marginLeft: 'auto', rows: [{ cells: gaugeCells }] },
},
],
},
{
cells: [{
text: `Next: ${nextActionText}`, colspan: 2, color: COLOR_TEXT, background: COLOR_ROW,
padding: '3px 8px 5px 8px', fontSize: '10px', fontStyle: 'italic', whiteSpace: 'nowrap',
}],
},
sectionRow(`ON THIS CHART · ${statsCandles} CANDLES · STRATEGY vs BUY & HOLD`),
pairRow('Return', compareText(strategyEquity - 1, buyHoldEquity - 1),
betterOrEqual(strategyEquity, buyHoldEquity)),
pairRow('Max drawdown', compareText(strategyMaxDrawdown, buyHoldMaxDrawdown),
betterOrEqual(strategyMaxDrawdown, buyHoldMaxDrawdown)),
pairRow('Closed trades · win rate',
`${closedTradeReturns.length} · ${winRate === null ? '—' : `${Math.round(winRate * 100)}%`}`, COLOR_TEXT),
pairRow('Time in market', `${Math.round(timeInMarket * 100)}%`, COLOR_TEXT),
];
if (SHOW_EQUITY_CHART && strategyPoints.length > 2) {
dashboardRows.push({
cells: [{
colspan: 2, background: COLOR_ROW, padding: '2px 4px 4px 4px',
chart: {
width: '250px',
height: '90px',
type: 'line',
data: {
labels: chartLabels,
datasets: [
{ label: 'Strategy %', data: strategyPoints, borderColor: COLOR_CALM_UP, borderWidth: 1.5, pointRadius: 0, fill: false },
{ label: 'Buy & hold %', data: buyHoldPoints, borderColor: COLOR_MUTED, borderWidth: 1, pointRadius: 0, fill: false },
],
},
options: {
plugins: { legend: { display: true, labels: { color: COLOR_TEXT, boxWidth: 8, font: { size: 9 } } } },
scales: {
x: { display: false },
y: { position: 'right', ticks: { color: COLOR_MUTED, font: { size: 8 } }, grid: { color: 'rgba(120, 123, 134, 0.15)' } },
},
},
},
}],
});
}
dashboardRows.push({
cells: [{
text: setupIsStandard
? 'Signal on candle close · Strategy Tester fills next open · no repainting'
: '⚠ Use 2h, regular hours, normal candles (not Heikin Ashi) — same as the Strategy Tester',
colspan: 2, color: setupIsStandard ? COLOR_MUTED : COLOR_DIP, background: COLOR_PANEL,
padding: '4px 8px 6px 8px', fontSize: '8px', borderTop: '1px solid rgba(120, 123, 134, 0.35)',
}],
});
if (SHOW_DASHBOARD) {
const onRightSide = DASHBOARD_POSITION.endsWith('right');
paint_overlay('Crash-Guard Dashboard', { position: DASHBOARD_POSITION, offset_x: onRightSide ? -62 : 10, offset_y: 10 }, {
background: COLOR_PANEL,
border: '1px solid rgba(120, 123, 134, 0.45)',
borderRadius: '3px',
cellSpacing: 0,
overflow: 'hidden',
rows: dashboardRows,
});
}