#TSBuild26
STA (Structural Trajectory Analyzer) is a multi-scale market structure indicator developed primarily for SPY and QQQ. It tracks how short-, medium-, and long-term price dynamics interact to help identify emerging trend changes, momentum shifts, exhaustion, and regime transitions.
Its structure and signal behavior have been tuned mainly around SPY/QQQ, where it is intended to be most reliable. Other liquid instruments may also benefit from the framework, but signal quality and timing can vary and should be independently validated.
By combining several structural components into one framework, STA helps distinguish short-term noise from more meaningful market moves and provides a clearer view of when market conditions are strengthening, weakening, or beginning to turn.** STA can be useful for recognizing early trend transitions, exhaustion points, reversals, and strengthening or weakening market structure**. Its main advantage is that it provides a unified view of market behavior across multiple time scales, helping distinguish temporary price fluctuations from more meaningful structural moves.
- Cyan dots: Start of an upward curvature phase—structural momentum is improving.
- Magenta dots: Start of a downward curvature phase—structural momentum is weakening.
- ▲ / ▼ triangles: First matching W1 momentum turn within five bars of the curvature-phase change.
- Small cyan ▲: Potential local bottom; the MACD histogram turns upward while MACD and STA remain negative.
- Magenta CAP label: Recovery from an extreme negative STA reading, confirmed by W1 momentum.
For SPY/QQQ, W1 triangle colors indicate the STA zone: green = bullish, gray = neutral, and yellow → red → magenta = progressively deeper weakness.
Signals on the current candle can change until it closes.
describe_indicator('STA — Structural Trajectory Analyzer', 'price');
const showPriceDots = input('Show curvature dots', 'Yes', ['Yes', 'No']) === 'Yes';
const showStatus = input('Show latest STA status', 'Yes', ['Yes', 'No']) === 'Yes';
const regimeMode = input('Regime', 'Auto', ['Auto', 'SPY', 'QQQ', 'Other']);
const ticker = String(constants.ticker || '').toUpperCase();
const regime = regimeMode === 'Auto' ? ticker : regimeMode;
const isSPY = regime === 'SPY';
const isQQQ = regime === 'QQQ';
const isRegimeSymbol = isSPY || isQQQ;
const bullDrive = isSPY ? 20 : isQQQ ? 25 : NaN;
const bullExtreme = isSPY ? 50 : isQQQ ? 100 : NaN;
const bearDrive = -bullDrive;
const bearExtreme = isSPY ? -60 : isQQQ ? -100 : NaN;
const bearCrash = isSPY ? -120 : isQQQ ? -200 : NaN;
const n = close.length;
const blank = () => Array(n).fill(NaN);
const finite = Number.isFinite;
function staAverage(a, length) {
const out = blank();
for (let i = length - 1; i < n; i++) {
let staTotal = 0, valid = true;
for (let j = 0; j < length; j++) {
if (!finite(a[i - j])) { valid = false; break; }
staTotal += a[i - j];
}
if (valid) out[i] = staTotal / length;
}
return out;
}
function staExponential(a, length) {
const out = blank(), alpha = 2 / (length + 1);
let previous = NaN;
for (let i = 0; i < n; i++) {
if (!finite(a[i])) { previous = NaN; continue; }
previous = finite(previous) ? alpha * a[i] + (1 - alpha) * previous : a[i];
out[i] = previous;
}
return out;
}
function staDifference(a) {
return a.map((v, i) => i > 0 ? v - a[i - 1] : NaN);
}
// ThinkScript Inertia: fitted least-squares line at the newest sample.
function staInertia(a, length) {
const out = blank();
const sx = length * (length - 1) / 2;
const sxx = length * (length - 1) * (2 * length - 1) / 6;
for (let i = length - 1; i < n; i++) {
let sy = 0, sxy = 0, valid = true;
for (let x = 0; x < length; x++) {
const y = a[i - length + 1 + x];
if (!finite(y)) { valid = false; break; }
sy += y; sxy += x * y;
}
if (valid) {
const slope = (length * sxy - sx * sy) / (length * sxx - sx * sx);
out[i] = (sy - slope * sx) / length + slope * (length - 1);
}
}
return out;
}
function staDeviation(a, length) {
const means = staAverage(a, length), out = blank();
for (let i = length - 1; i < n; i++) {
if (!finite(means[i])) continue;
let staSquaredTotal = 0;
for (let j = 0; j < length; j++) staSquaredTotal += (a[i - j] - means[i]) ** 2;
out[i] = Math.sqrt(staSquaredTotal / length); // population StDev, as in TOS
}
return out;
}
function staDistance(length) {
const ma = staAverage(close, length);
return close.map((p, i) => p === 0 ? 0 : 100 * (p - ma[i]) / p);
}
const weights = [1, 1, 3, 3, 4, 4, 3, 3, 1, 1];
const distances = weights.map((_, k) => staDistance(13 * (k + 1)));
const rawSTA = close.map((_, i) => (5 / 12) *
distances.reduce((staWeightedTotal, d, k) => staWeightedTotal + weights[k] * d[i], 0));
const d2 = staDistance(2), d5 = staDistance(5), d6 = staDistance(6);
const d9 = staDistance(9), d10 = staDistance(10);
const w1 = close.map((_, i) => (5 / 6) * (2 * d5[i] + 2 * d6[i] - d2[i] - d9[i] - d10[i]));
const staReg = staInertia(rawSTA, 5);
const staSlope = staDifference(staReg);
const curvature = staDifference(staSlope);
const sigma = staDeviation(curvature, 30);
const e5 = staExponential(staReg, 5), e10 = staExponential(staReg, 10);
const e21 = staExponential(staReg, 21);
const e5Slope = staDifference(e5);
const spread = e5.map((v, i) => v - e10[i]);
const ignition = e5.map((_, i) => i > 0 && e5Slope[i] > 0 && spread[i] > spread[i - 1]);
const w1Slope = staDifference(w1);
const macdFast = staExponential(close, 12), macdSlow = staExponential(close, 26);
const staMacdLine = macdFast.map((v, i) => v - macdSlow[i]);
const macdSignal = staExponential(staMacdLine, 9);
const hist = staMacdLine.map((v, i) => v - macdSignal[i]);
const turnUp = Array(n).fill(false), turnDown = Array(n).fill(false);
const firstUp = Array(n).fill(false), firstDown = Array(n).fill(false);
const recovery1 = Array(n).fill(false), majorRecovery = Array(n).fill(false);
const cap = Array(n).fill(false), localBottom = Array(n).fill(false);
const states = Array(n).fill(0);
let held = 0, previousState = 0, episodeBar = 0, triggered = 1;
let recoveryAge = 12, storedTrough = NaN;
for (let i = 0; i < n; i++) {
const threshold = finite(sigma[i]) ? 0.25 * Math.max(sigma[i], 0.000001) : NaN;
// CompoundValue(1,...,initial) uses the initial value on the first bar.
if (i > 0) {
if (held === 0) held = curvature[i] > threshold ? 4 : curvature[i] < -threshold ? -4 : 0;
else if (held > 1) held--;
else if (held < -1) held++;
else if (held === 1 && curvature[i] < -threshold) held = -4;
else if (held === -1 && curvature[i] > threshold) held = 4;
}
const state = Math.sign(held);
states[i] = state;
turnUp[i] = state === 1 && previousState !== 1;
turnDown[i] = state === -1 && previousState !== -1;
const newEpisode = turnUp[i] || turnDown[i];
const wUp = i > 0 && w1Slope[i] > 0 && w1Slope[i - 1] <= 0;
const wDown = i > 0 && w1Slope[i] < 0 && w1Slope[i - 1] >= 0;
if (i > 0 && newEpisode) episodeBar = i + 1;
const age = i + 1 - episodeBar;
firstUp[i] = state === 1 && wUp && age <= 5 && (newEpisode || triggered === 0);
firstDown[i] = state === -1 && wDown && age <= 5 && (newEpisode || triggered === 0);
const matching = (state === 1 && wUp) || (state === -1 && wDown);
if (i > 0) {
if (newEpisode) triggered = matching ? 1 : 0;
else if (triggered === 0 && age <= 5 && matching) triggered = 1;
else if (age > 5) triggered = 1;
}
const trough1 = i >= 1 ? staReg[i - 1] : NaN;
const trough2 = i >= 2 ? staReg[i - 2] : NaN;
const pct1 = trough1 < 0 ? 100 * (staReg[i] - trough1) / Math.max(Math.abs(trough1), 0.000001) : 0;
const pct2 = trough2 < 0 ? 100 * (staReg[i] - trough2) / Math.max(Math.abs(trough2), 0.000001) : 0;
recovery1[i] = isRegimeSymbol && i >= 2 && trough1 <= staReg[i - 2] &&
staReg[i] > trough1 && trough1 <= bearDrive &&
pct1 >= (trough1 <= bearExtreme ? 20 : 25) && staSlope[i] > 0;
const recovery2 = isRegimeSymbol && i >= 3 && trough2 <= staReg[i - 3] &&
staReg[i - 1] > trough2 && staReg[i] > staReg[i - 1] && trough2 <= bearDrive &&
pct2 >= (trough2 <= bearExtreme ? 30 : 35) && !recovery1[i - 1] && !recovery1[i];
const origin = recovery1[i] ? trough1 : recovery2 ? trough2 : NaN;
majorRecovery[i] = (recovery1[i] || recovery2) && (ignition[i] || (i > 0 && ignition[i - 1]));
if (i > 0) {
const oldAge = recoveryAge;
recoveryAge = majorRecovery[i] ? 0 : oldAge < 2 ? oldAge + 1 : 12;
storedTrough = majorRecovery[i] ? origin : oldAge < 2 ? storedTrough : NaN;
}
const bullRecent = firstUp[i] || (i > 0 && firstUp[i - 1]) || (i > 1 && firstUp[i - 2]);
const pairOnRecovery = majorRecovery[i] && bullRecent;
const pairOnW1 = firstUp[i] && recoveryAge <= 2;
const bottomOrigin = pairOnRecovery ? origin : pairOnW1 ? storedTrough : NaN;
cap[i] = (pairOnRecovery || pairOnW1) && bottomOrigin <= bearCrash;
localBottom[i] = i >= 2 && staMacdLine[i] < 0 && hist[i - 1] < 0 &&
hist[i] > hist[i - 1] && hist[i - 1] <= hist[i - 2] && staReg[i] < 0;
previousState = state;
}
const C = { lightGreen: '#90EE90', green: '#00A000', gray: '#D3D3D3',
orange: '#FFA500', red: '#FF0000', magenta: '#FF00FF', cyan: '#00FFFF', yellow: '#FFFF00' };
function candleColor(v) {
if (!isRegimeSymbol || !finite(v)) return null;
return v >= bullExtreme ? C.lightGreen : v >= bullDrive ? C.green :
v > bearDrive ? C.gray : v > bearExtreme ? C.orange : v > bearCrash ? C.red : C.magenta;
}
function arrowColor(v, up) {
if (!isRegimeSymbol) return up ? C.green : C.gray;
return v >= bullDrive ? C.green : v > bearDrive ? C.gray :
v > bearExtreme ? C.yellow : v > bearCrash ? C.red : C.magenta;
}
color_candles(e21.map(candleColor));
function labels(signal, text, name, style, color, markerOptions = {}) {
paint(signal.map(hit => hit ? text : null), { name, style, color, ...markerOptions });
}
// Always paint the same named series in the same order, including when hidden.
// Match the earlier version: circular points anchored to the candle's price.
const staUpDotMarker = {
enabled: true, radius: 4, symbol: 'circle',
fillColor: C.cyan, lineColor: C.cyan, lineWidth: 1
};
const staDownDotMarker = {
enabled: true, radius: 4, symbol: 'circle',
fillColor: C.magenta, lineColor: C.magenta, lineWidth: 1
};
paint(turnUp.map((hit, i) => showPriceDots && hit && finite(low[i])
? { y: low[i], marker: staUpDotMarker } : null),
{ name: 'Curvature up', color: 'transparent' });
paint(turnDown.map((hit, i) => showPriceDots && hit && finite(high[i])
? { y: high[i], marker: staDownDotMarker } : null),
{ name: 'Curvature down', color: 'transparent' });
// Separate fixed-color plots avoid relying on dynamic label color support.
for (const colorName of ['Green', 'Gray', 'Yellow', 'Red', 'Magenta']) {
const color = C[colorName.toLowerCase()];
labels(firstUp.map((hit, i) => hit && arrowColor(staReg[i], true) === color),
'▲', 'W1 up (' + colorName + ')', 'labels_below', color,
{ fontSize: 12, verticalOffset: 2 });
labels(firstDown.map((hit, i) => hit && arrowColor(staReg[i], false) === color),
'▼', 'W1 down (' + colorName + ')', 'labels_above', color,
{ fontSize: 12, verticalOffset: 2 });
}
labels(localBottom, '▲', 'Local bottom', 'labels_below', C.cyan,
{ fontSize: 10, verticalOffset: 8 });
labels(cap, 'CAP', 'CAP', 'labels_below', '#000000', {
backgroundColor: C.magenta, backgroundOpacity: 1,
backgroundBorderRadius: 3, fontSize: 9, verticalOffset: 14
});
// TOS AddLabel is represented by a status label on the latest candle.
const status = Array(n).fill(null);
if (showStatus && n > 0) {
const i = n - 1, v = staReg[i], state = states[i];
const phase = !finite(v) ? 'WARMUP' : v >= 0 && state === 1 ? 'BULL ACCEL' :
v >= 0 && state === -1 ? 'BULL ROLLOVER' : v < 0 && state === 1 ? 'BEAR RECOVERY' :
v < 0 && state === -1 ? 'BEAR ACCEL' : 'NEUTRAL';
status[i] = (isRegimeSymbol ? regime + ' ' : '') + 'STA ' + phase +
' R ' + (finite(v) ? v.toFixed(1) : 'N/A') +
' E21 ' + (finite(e21[i]) ? e21[i].toFixed(1) : 'N/A');
}
paint(status, { name: 'STA status', style: 'labels_above',
color: candleColor(e21[n - 1]) || '#808080' });
// Keep registered signal names distinct from every paint() name,
// including case-insensitive matches such as "Local bottom" / "Local Bottom".
register_signal(turnUp, 'STA Curvature Turn Up Signal');
register_signal(turnDown, 'STA Curvature Turn Down Signal');
register_signal(firstUp, 'STA First W1 Up Signal');
register_signal(firstDown, 'STA First W1 Down Signal');
register_signal(localBottom, 'STA Local Bottom Signal');
register_signal(cap, 'STA CAP Signal');
register_signal(majorRecovery, 'STA Major Recovery Signal');