// This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not // distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. // © jdehorty: "Machine Learning: Lorentzian Classification", https://www.tradingview.com/script/WhBzgfDu/ // Modified by ProEA, 2026: a reduced TypeScript model of its features, its Lorentzian-distance neighbour search // (with a sorted k-NN to compare) and its kernel filter, for a drill on simulated candles. // Source of this file: https://proea.app/open-source/lorentzian.ts.txt, listed at https://proea.app/en/legal/open-source // // Deterministic simulation engine for /en/blog/lorentzian-classification-indicator-settings: // models jdehorty's 665-line Machine Learning: Lorentzian Classification v2.0 (WhBzgfDu, 37,602 boosts) // across 88 simulated 15-minute candles (28 warm-up + 60 visible bars), including a simulated FOMC // volatility spike at visible bar 18 where Euclidean squared distance gets hijacked by the outlier // while Lorentzian log(1 + |dx|) distance compresses it, plus the Rational Quadratic Kernel (h=8, r=8, x=25) // and jdehorty's lines 403–411 ANN ratchet loop vs sorted minimum-k nearest neighbors. export type LorentzianBar = readonly [ index: number, open: number, high: number, low: number, close: number, isOutlierSpike: boolean, ]; export type DistanceMetric = "lorentzian" | "euclidean"; export type NeighborSearchMode = "ann-ratchet" | "sorted-knn"; export interface LorentzianSettings { neighborsCount: number; // 4..20 (default 8, line 206) featureCount: 2 | 3 | 4 | 5; // 2..5 (default 5, line 208) metric: DistanceMetric; // Lorentzian log(1+|dx|) vs Euclidean sqrt(sum(dx^2)) searchMode: NeighborSearchMode; // lines 403-411 ANN ratchet vs true sorted k-NN useKernelFilter: boolean; // Trade with Kernel (default true, line 313) kernelLookback: number; // Lookback Window h (default 8, line 316) } export const LDC_DEFAULTS: LorentzianSettings = { neighborsCount: 8, featureCount: 5, metric: "lorentzian", searchMode: "ann-ratchet", useKernelFilter: true, kernelLookback: 8, }; export const LDC_WARM = 28; export const LDC_SHOWN_COUNT = 60; export const FOMC_SPIKE_SHOWN_INDEX = 18; function buildSimulatedBars(): LorentzianBar[] { const total = LDC_WARM + LDC_SHOWN_COUNT; const bars: LorentzianBar[] = []; let prevClose = 100.0; for (let i = 0; i < total; i++) { // Deterministic multi-wave cycle + balanced bull/bear warmup + FOMC shock at shown bar 18 (i = 46) const shownIdx = i - LDC_WARM; const wave1 = Math.sin(i * 0.32) * 1.45; const wave2 = Math.cos(i * 0.17) * 0.75; let drift = 0; if (shownIdx < 0) { drift = i < 14 ? 0.46 : -0.48; } else if (shownIdx >= 3 && shownIdx <= 14) drift = 0.48; else if (shownIdx >= 15 && shownIdx <= 26) drift = -0.52; else if (shownIdx >= 27 && shownIdx <= 40) drift = 0.54; else if (shownIdx >= 41 && shownIdx <= 51) drift = -0.55; else if (shownIdx >= 52) drift = 0.46; const isFomc = shownIdx === FOMC_SPIKE_SHOWN_INDEX || shownIdx === FOMC_SPIKE_SHOWN_INDEX + 1; const shock = shownIdx === FOMC_SPIKE_SHOWN_INDEX ? 6.4 : shownIdx === FOMC_SPIKE_SHOWN_INDEX + 1 ? -5.9 : 0; const open = Number(prevClose.toFixed(2)); const rawClose = open + drift + (wave1 - Math.sin((i - 1) * 0.32) * 1.45) * 0.65 + wave2 * 0.16 + shock; const close = Number(rawClose.toFixed(2)); const wickUp = isFomc ? 3.4 : 0.45 + ((i * 7) % 5) * 0.14; const wickDn = isFomc ? 3.1 : 0.42 + ((i * 11) % 5) * 0.13; const high = Number((Math.max(open, close) + wickUp).toFixed(2)); const low = Number((Math.min(open, close) - wickDn).toFixed(2)); bars.push([i, open, high, low, close, isFomc]); prevClose = close; } return bars; } export const LDC_BARS: readonly LorentzianBar[] = buildSimulatedBars(); function ema(values: readonly number[], period: number): number[] { const out: number[] = []; const k = 2 / (period + 1); let prev = values[0] ?? 0; for (let i = 0; i < values.length; i++) { const v = values[i]!; prev = i === 0 ? v : v * k + prev * (1 - k); out.push(prev); } return out; } function rsi(closes: readonly number[], period: number, smooth: number): number[] { const raw: number[] = [50]; let avgGain = 0.5; let avgLoss = 0.5; for (let i = 1; i < closes.length; i++) { const diff = closes[i]! - closes[i - 1]!; const gain = diff > 0 ? diff : 0; const loss = diff < 0 ? -diff : 0; avgGain = (avgGain * (period - 1) + gain) / period; avgLoss = (avgLoss * (period - 1) + loss) / period; const rs = avgLoss <= 1e-9 ? 100 : avgGain / avgLoss; raw.push(100 - 100 / (1 + rs)); } return smooth > 1 ? ema(raw, smooth) : raw; } function cciNormalized(closes: readonly number[], period: number): number[] { const out: number[] = []; for (let i = 0; i < closes.length; i++) { const start = Math.max(0, i - period + 1); const slice = closes.slice(start, i + 1); const mean = slice.reduce((a, b) => a + b, 0) / slice.length; const mad = slice.reduce((a, b) => a + Math.abs(b - mean), 0) / slice.length; const cci = mad <= 1e-9 ? 0 : (closes[i]! - mean) / (0.015 * mad); // Rescale smoothly into 0..100 feature space like ml.n_cci out.push(50 + 50 * Math.tanh(cci / 150)); } return out; } function waveTrendNormalized(bars: readonly LorentzianBar[], n1: number, n2: number): number[] { const hlc3 = bars.map((b) => (b[2] + b[3] + b[4]) / 3); const esa = ema(hlc3, n1); const absDiff = hlc3.map((v, i) => Math.abs(v - esa[i]!)); const d = ema(absDiff, n1); const ci = hlc3.map((v, i) => (d[i]! <= 1e-9 ? 0 : (v - esa[i]!) / (0.015 * d[i]!))); const wt1 = ema(ci, n2); return wt1.map((v) => 50 + 50 * Math.tanh(v / 100)); } function adxNormalized(bars: readonly LorentzianBar[], period: number): number[] { const out: number[] = [25]; let smoothTr = 1; let smoothPlus = 0.3; let smoothMinus = 0.3; let adxVal = 25; for (let i = 1; i < bars.length; i++) { const [, , h, l] = bars[i]!; const [, , ph, pl, pc] = bars[i - 1]!; const up = h - ph; const dn = pl - l; const plusDm = up > dn && up > 0 ? up : 0; const minusDm = dn > up && dn > 0 ? dn : 0; const tr = Math.max(h - l, Math.abs(h - pc), Math.abs(l - pc)); smoothTr = (smoothTr * (period - 1) + tr) / period; smoothPlus = (smoothPlus * (period - 1) + plusDm) / period; smoothMinus = (smoothMinus * (period - 1) + minusDm) / period; const pdi = smoothTr <= 1e-9 ? 0 : (100 * smoothPlus) / smoothTr; const mdi = smoothTr <= 1e-9 ? 0 : (100 * smoothMinus) / smoothTr; const dx = pdi + mdi <= 1e-9 ? 0 : (100 * Math.abs(pdi - mdi)) / (pdi + mdi); adxVal = (adxVal * (period - 1) + dx) / period; out.push(Math.max(0, Math.min(100, adxVal))); } return out; } /** Rational Quadratic Kernel regression (jdehorty lines 316-318 & 508: h=8, r=8.0, x=25). */ export function rationalQuadraticKernel( closes: readonly number[], lookbackWindow: number, relativeWeight = 8.0, startAtBar = 25 ): number[] { const h = Math.max(2, lookbackWindow); const out: number[] = []; for (let t = 0; t < closes.length; t++) { let currentWeight = 0; let cumulativeWeight = 0; const maxLag = Math.min(t, startAtBar + 24); for (let i = 0; i <= maxLag; i++) { const y = closes[t - i]!; const w = Math.pow(1 + (i * i) / (2 * relativeWeight * h * h), -relativeWeight); currentWeight += y * w; cumulativeWeight += w; } out.push(cumulativeWeight > 0 ? currentWeight / cumulativeWeight : closes[t]!); } return out; } export interface LorentzianPoint { shownIndex: number; close: number; kernelYhat: number; kernelBullish: boolean; lorentzianPred: number; euclideanPred: number; activePred: number; signal: -1 | 0 | 1; buySignal: boolean; sellSignal: boolean; earlyFlip: boolean; differsFromSortedKnn: boolean; } export interface LorentzianSummary { shown: LorentzianPoint[]; buyCount: number; sellCount: number; earlyFlipCount: number; kernelBlockedCount: number; ratchetDiffBars: number; fomcLorentzianDist: number; fomcEuclideanDist: number; outlierCompressionRatio: number; } function calcDistance( a: readonly number[], b: readonly number[], featureCount: number, metric: DistanceMetric ): number { if (metric === "lorentzian") { let sum = 0; for (let f = 0; f < featureCount; f++) { sum += Math.log(1 + Math.abs(a[f]! - b[f]!)); } return sum; } let sq = 0; for (let f = 0; f < featureCount; f++) { const d = a[f]! - b[f]!; sq += d * d; } return Math.sqrt(sq); } function predictBar( barIdx: number, features: readonly (readonly number[])[], labels: readonly number[], k: number, featureCount: number, metric: DistanceMetric, searchMode: NeighborSearchMode ): number { if (barIdx < 12) return 0; const cur = features[barIdx]!; if (searchMode === "ann-ratchet") { // Mirrors WhBzgfDu lines 395-414: // lastDistance = -1.0, i % 4 != 0, d >= lastDistance, 75th percentile reset let lastDistance = -1.0; const distances: number[] = []; const preds: number[] = []; for (let i = 4; i <= barIdx - 4; i++) { const d = calcDistance(cur, features[i]!, featureCount, metric); if (d >= lastDistance && i % 4 !== 0) { lastDistance = d; distances.push(d); preds.push(labels[i]!); if (preds.length > k) { const qIdx = Math.min(distances.length - 1, Math.round((k * 3) / 4)); lastDistance = distances[qIdx]!; distances.shift(); preds.shift(); } } } return preds.reduce((acc, v) => acc + v, 0); } // True sorted k-Nearest Neighbors (minimum distance, spaced at least 4 bars) const candidates: { d: number; y: number }[] = []; for (let i = 4; i <= barIdx - 4; i++) { if (i % 4 !== 0) { candidates.push({ d: calcDistance(cur, features[i]!, featureCount, metric), y: labels[i]!, }); } } candidates.sort((x, y) => x.d - y.d); return candidates.slice(0, k).reduce((acc, item) => acc + item.y, 0); } export function summarizeLorentzian(s: LorentzianSettings): LorentzianSummary { const closes = LDC_BARS.map((b) => b[4]); // Default 5 features from WhBzgfDu lines 242-256: RSI(14,1), WT(10,11), CCI(20,1), ADX(20,2), RSI(9,1) const f1 = rsi(closes, 14, 1); const f2 = waveTrendNormalized(LDC_BARS, 10, 11); const f3 = cciNormalized(closes, 20); const f4 = adxNormalized(LDC_BARS, 20); const f5 = rsi(closes, 9, 1); const features = LDC_BARS.map((_, i) => [f1[i]!, f2[i]!, f3[i]!, f4[i]!, f5[i]!] as const); // WhBzgfDu line 336 training label for ANN ratchet: src[4] < src[0] ? -1 : src[4] > src[0] ? +1 : 0 // (double-negative with d >= lastDistance furthest-neighbor ratchet!) const ratchetLabels: number[] = LDC_BARS.map((_, i) => { const prev4 = closes[Math.max(0, i - 4)]!; return prev4 < closes[i]! ? -1 : prev4 > closes[i]! ? 1 : 0; }); // Forward 4-bar directional outcome for true sorted minimum-distance k-NN (i <= barIdx - 4, zero lookahead) const sortedKnnLabels: number[] = LDC_BARS.map((_, i) => { const targetIdx = Math.min(LDC_BARS.length - 1, i + 4); const diff = closes[targetIdx]! - closes[i]!; return diff > 0.05 ? 1 : diff < -0.05 ? -1 : 0; }); const kernel = rationalQuadraticKernel(closes, s.kernelLookback, 8.0, 25); const shown: LorentzianPoint[] = []; let prevSignal: -1 | 0 | 1 = 0; let barsHeld = 0; let buyCount = 0; let sellCount = 0; let earlyFlipCount = 0; let kernelBlockedCount = 0; let ratchetDiffBars = 0; for (let k = 0; k < LDC_SHOWN_COUNT; k++) { const idx = LDC_WARM + k; const kernelBullish = kernel[idx]! > kernel[idx - 1]!; const kernelBearish = kernel[idx]! < kernel[idx - 1]!; const activeLabels = s.searchMode === "ann-ratchet" ? ratchetLabels : sortedKnnLabels; const altLabels = s.searchMode === "ann-ratchet" ? sortedKnnLabels : ratchetLabels; const lorPred = predictBar(idx, features, activeLabels, s.neighborsCount, s.featureCount, "lorentzian", s.searchMode); const eucPred = predictBar(idx, features, activeLabels, s.neighborsCount, s.featureCount, "euclidean", s.searchMode); const altSearchPred = predictBar( idx, features, altLabels, s.neighborsCount, s.featureCount, s.metric, s.searchMode === "ann-ratchet" ? "sorted-knn" : "ann-ratchet" ); const activePred = s.metric === "lorentzian" ? lorPred : eucPred; const differsFromSortedKnn = Math.sign(activePred) !== Math.sign(altSearchPred); if (differsFromSortedKnn) ratchetDiffBars++; const rawSignal: -1 | 0 | 1 = activePred > 0 ? 1 : activePred < 0 ? -1 : prevSignal; const flipped = rawSignal !== prevSignal && prevSignal !== 0; const earlyFlip = flipped && barsHeld > 0 && barsHeld < 4; if (earlyFlip) earlyFlipCount++; let buySignal = false; let sellSignal = false; if (rawSignal !== prevSignal) { if (rawSignal === 1) { if (!s.useKernelFilter || kernelBullish) { buySignal = true; buyCount++; } else { kernelBlockedCount++; } } else if (rawSignal === -1) { if (!s.useKernelFilter || kernelBearish) { sellSignal = true; sellCount++; } else { kernelBlockedCount++; } } barsHeld = 0; } else { barsHeld++; } prevSignal = rawSignal; shown.push({ shownIndex: k, close: closes[idx]!, kernelYhat: Number(kernel[idx]!.toFixed(2)), kernelBullish, lorentzianPred: lorPred, euclideanPred: eucPred, activePred, signal: rawSignal, buySignal, sellSignal, earlyFlip, differsFromSortedKnn, }); } const fomcBarIdx = LDC_WARM + FOMC_SPIKE_SHOWN_INDEX; const neutralOrigin = [50, 50, 50, 25, 50] as const; const fomcLorentzianDist = Number( calcDistance(features[fomcBarIdx]!, neutralOrigin, s.featureCount, "lorentzian").toFixed(2) ); const fomcEuclideanDist = Number( calcDistance(features[fomcBarIdx]!, neutralOrigin, s.featureCount, "euclidean").toFixed(2) ); const outlierCompressionRatio = Number( (fomcEuclideanDist / Math.max(0.1, fomcLorentzianDist)).toFixed(1) ); return { shown, buyCount, sellCount, earlyFlipCount, kernelBlockedCount, ratchetDiffBars, fomcLorentzianDist, fomcEuclideanDist, outlierCompressionRatio, }; }