Appearance
Auto Fib Extension
Trend-based fib extension from the last two swings.
Kind indicator · Drawn on the price pane
Try it
On the chart, press / and choose Auto Fib Extension under Support & resistance. To change it, copy the source below into the AlphaScript editor.
Inputs
| Input | Type | Default |
|---|---|---|
| Deviation (x ATR %) | float | 3 |
| Extend right | bool | true |
| Prices | bool | true |
| Levels | bool | true |
Source
From packages/alphascript/indicators/autofibext.as.js.
js
indicator({ name: "Auto Fib Extension", shortTitle: "Auto Fib Ext", overlay: true });
const devMult = input.float("Deviation (x ATR %)", 3, { min: 0.1, step: 0.5 });
const extendRight = input.bool("Extend right", true), showPrices = input.bool("Prices", true), showLevels = input.bool("Levels", true);
const atrPct = ta.calc([ta.atr(10), candle.close], (a, c) => (a / c) * 100);
/** @param {number} p */
const fmt = (p) => { const d = p > 0 ? math.max(2, 4 - math.floor(math.log(p) / math.log(10))) : 2; return String(math.round(p, d)); };
/** @type {{ t: number, p: number }[]} */
const pivots = [];
let dir = 0, extT = NaN, extP = NaN;
/** @type {number[]} */
let ids = [];
/** @param {number} bar */
function swing(bar) {
const h = candle.high.value, l = candle.low.value, dev = devMult * atrPct.value;
if (dir === 0) { if (dev === dev) { dir = 1; extT = bar; extP = h; pivots.push({ t: bar, p: l }); } return; }
if (dir === 1 ? h >= extP : l <= extP) { extT = bar; extP = dir === 1 ? h : l; return; }
const back = dir === 1 ? l : h;
if (dev === dev && (math.abs(back - extP) / extP) * 100 >= dev) { pivots.push({ t: extT, p: extP }); dir = -dir; extT = bar; extP = back; }
}
/** @param {number} x1 @param {number} x2 @param {[number, string][]} levels @param {(v: number) => number} priceOf */
function drawLevels(x1, x2, levels, priceOf) {
for (const id of ids) draw.remove(id);
ids = [];
for (const [v, color] of levels) {
const y = priceOf(v);
ids.push(draw.line({ x1, y1: y, x2, y2: y, color, width: 1, extend: extendRight ? "right" : "none" }));
const text = [showLevels ? String(v) : "", showPrices ? `(${fmt(y)})` : ""].filter(Boolean).join(" ");
if (text) ids.push(draw.label({ x: x1, y, text, style: "right", color: "rgba(0,0,0,0)", textColor: color, size: "small" }));
}
}
/** @type {[number, string][]} */
const LEVELS = [[0, "#787B86"], [0.382, "#F23645"], [0.618, "#009688"], [1, "#787B86"], [1.272, "#81C784"], [1.618, "#2962FF"], [2.618, "#9C27B0"]];
event.onCandle((bar) => {
swing(bar.time);
if (pivots.length < 2) return;
const a = pivots[pivots.length - 2], b = pivots[pivots.length - 1];
drawLevels(extT, bar.time, LEVELS, (v) => extP + (b.p - a.p) * v);
});