|
| 1 | +/** |
| 2 | + * Commodity Channel Index (CCI) Indicator |
| 3 | + * |
| 4 | + * Hand-optimized implementation using oakscriptjs. |
| 5 | + * Measures the variation of a security's price from its statistical mean. |
| 6 | + * High values show the price is unusually high compared to average, low values show it's unusually low. |
| 7 | + */ |
| 8 | + |
| 9 | +import { Series, ta, type IndicatorResult, type InputConfig, type PlotConfig, type Bar } from 'oakscriptjs'; |
| 10 | + |
| 11 | +export interface CCIInputs { |
| 12 | + length: number; |
| 13 | + src: 'open' | 'high' | 'low' | 'close' | 'hl2' | 'hlc3' | 'ohlc4' | 'hlcc4'; |
| 14 | +} |
| 15 | + |
| 16 | +export const defaultInputs: CCIInputs = { |
| 17 | + length: 20, |
| 18 | + src: 'hlc3', |
| 19 | +}; |
| 20 | + |
| 21 | +export const inputConfig: InputConfig[] = [ |
| 22 | + { id: 'length', type: 'int', title: 'Length', defval: 20, min: 1 }, |
| 23 | + { id: 'src', type: 'source', title: 'Source', defval: 'hlc3' }, |
| 24 | +]; |
| 25 | + |
| 26 | +export const plotConfig: PlotConfig[] = [ |
| 27 | + { id: 'plot0', title: 'CCI', color: '#2962FF', lineWidth: 2 }, |
| 28 | +]; |
| 29 | + |
| 30 | +export const metadata = { |
| 31 | + title: 'Commodity Channel Index', |
| 32 | + shortTitle: 'CCI', |
| 33 | + overlay: false, |
| 34 | +}; |
| 35 | + |
| 36 | +function getSourceSeries(bars: Bar[], src: CCIInputs['src']): Series { |
| 37 | + const open = new Series(bars, (bar) => bar.open); |
| 38 | + const high = new Series(bars, (bar) => bar.high); |
| 39 | + const low = new Series(bars, (bar) => bar.low); |
| 40 | + const close = new Series(bars, (bar) => bar.close); |
| 41 | + |
| 42 | + switch (src) { |
| 43 | + case 'open': return open; |
| 44 | + case 'high': return high; |
| 45 | + case 'low': return low; |
| 46 | + case 'close': return close; |
| 47 | + case 'hl2': return high.add(low).div(2); |
| 48 | + case 'hlc3': return high.add(low).add(close).div(3); |
| 49 | + case 'ohlc4': return open.add(high).add(low).add(close).div(4); |
| 50 | + case 'hlcc4': return high.add(low).add(close).add(close).div(4); |
| 51 | + default: return close; |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +export function calculate(bars: Bar[], inputs: Partial<CCIInputs> = {}): IndicatorResult { |
| 56 | + const { length, src } = { ...defaultInputs, ...inputs }; |
| 57 | + const source = getSourceSeries(bars, src); |
| 58 | + const cci = ta.cci(source, length); |
| 59 | + |
| 60 | + const plotData = cci.toArray().map((value: number | undefined, i: number) => ({ |
| 61 | + time: bars[i].time, |
| 62 | + value: value ?? NaN, |
| 63 | + })); |
| 64 | + |
| 65 | + return { |
| 66 | + metadata: { title: metadata.title, shorttitle: metadata.shortTitle, overlay: metadata.overlay }, |
| 67 | + plots: { 'plot0': plotData }, |
| 68 | + }; |
| 69 | +} |
| 70 | + |
| 71 | +export const CCI = { calculate, metadata, defaultInputs, inputConfig, plotConfig }; |
0 commit comments