Skip to Main Content

Fractal Trendline Detection Indicator

This indicator example identifies fractal highs and lows, then uses them to attempt to detect trendlines on the chart. It can be powerful at identifying both consolidation and broadening, and illustrates how to draw rays with JavaScript on the platform.

Fractal Trendline Detection Indicator
describe_indicator('Fractal Trendlines', 'price', { decimals: 'by_symbol_+1', shortName: 'Frac.Trends', mainColorInheritFrom: 'u_dots' });
 
const length = input('Length', 21, { min: 3, max: 31 });
const bandType = input('Band type', 'ATR', constants.band_types);
const bandLength = input('Band length', 10, { min: 2, max: 50 });
 
const multiplier = input('Band value', 0.33, { min: 0.01, max: 10 });
 
 
const paintLineAndBand = (fractalPoints, color, name, borderColor) => {
	const last2Points = indexed_points_of(fractalPoints).slice(-2);
	const fractalDots = series_of(null);
	let trendLine = series_of(null);
 
	// in some cases we might just not have last 2 fractals at all
	if (last2Points.length == 2) {
 
		fractalDots[last2Points[0].candleIndex] = last2Points[0].value;
		fractalDots[last2Points[1].candleIndex] = last2Points[1].value;
 
		trendLine = line(
			last2Points[0].candleIndex,
			last2Points[0].value,
 
			last2Points[1].candleIndex,
			last2Points[1].value
		);
 
	}
 
	paint(fractalDots, { name: `${name[0]}/Dots`, style: 'dotted', thickness: 3, color });
	paint(trendLine, { name, color });
 
	const { upper, lower } = compute_band(trendLine, bandType, multiplier, bandLength);
 
	fill(
		paint(upper, { name: `${name[0]}/Top`, color: borderColor }),
		paint(lower, { name: `${name[0]}/Bot`, color: borderColor }),
		color
	);
};
 
const fHighs = fractal_high(high, length);
const fLows = fractal_low(low, length);
 
paintLineAndBand(fHighs, '#2ca599', 'Upper', '#84cbc2');
paintLineAndBand(fLows, '#ee5451', 'Lower', '#f79790');