@hoox-sh/pynets 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/runtime/ta.ts CHANGED
@@ -595,6 +595,10 @@ export class TaEngine {
595
595
  private readonly marketConditionSites = new Map<string, MarketConditionState>();
596
596
  private readonly orderFlowSites = new Map<string, OrderFlowState>();
597
597
  private readonly liquiditySites = new Map<string, LiquidityState>();
598
+ private readonly emaCrossSites = new Map<string, { prevFast: Cell; prevSlow: Cell; count: number }>();
599
+ private readonly historySites = new Map<string, Cell[]>();
600
+ private readonly momentumFilterSites = new Map<string, { momentum: Cell[]; volume: Cell[] }>();
601
+ private readonly volatilityRegimeSites = new Map<string, Cell[]>();
598
602
 
599
603
  sma(site: string, source: Cell, period: number): Cell {
600
604
  const n = pinePeriod(period);
@@ -3127,6 +3131,55 @@ export class TaEngine {
3127
3131
  return v === undefined ? null : v;
3128
3132
  }
3129
3133
 
3134
+ /**
3135
+ * Python `_expect_list(PineSeries)` history: newest-first, capped at 1000.
3136
+ * `h[0]` is the current bar, `h[h.length - 1]` the oldest retained sample.
3137
+ */
3138
+ private hist(site: string, value: Cell): Cell[] {
3139
+ let h = this.historySites.get(site);
3140
+ if (h === undefined) {
3141
+ h = [];
3142
+ this.historySites.set(site, h);
3143
+ }
3144
+ h.unshift(finiteCell(value));
3145
+ if (h.length > 1000) h.pop();
3146
+ return h;
3147
+ }
3148
+
3149
+ /**
3150
+ * Python `_expect_list` input: a Pine array is used as-is (last element is
3151
+ * the `[-1]` index); a series sample appends to the newest-first history.
3152
+ */
3153
+ private windowFor(site: string, value: unknown): Cell[] {
3154
+ if (Array.isArray(value)) {
3155
+ return value.map((v) => (typeof v === "number" ? finiteCell(v) : null));
3156
+ }
3157
+ if (
3158
+ value != null &&
3159
+ typeof value === "object" &&
3160
+ typeof (value as { size?: unknown }).size === "function" &&
3161
+ typeof (value as { get?: unknown }).get === "function"
3162
+ ) {
3163
+ const arr = value as { size: () => number; get: (i: number) => unknown };
3164
+ const out: Cell[] = [];
3165
+ const n = arr.size();
3166
+ for (let i = 0; i < n; i++) {
3167
+ const v = arr.get(i);
3168
+ out.push(typeof v === "number" ? finiteCell(v) : null);
3169
+ }
3170
+ return out;
3171
+ }
3172
+ return this.hist(site, typeof value === "number" ? value : null);
3173
+ }
3174
+
3175
+ private static oldest(h: Cell[]): Cell {
3176
+ return h.length === 0 ? null : h[h.length - 1]!;
3177
+ }
3178
+
3179
+ private static secondOldest(h: Cell[]): Cell {
3180
+ return h.length < 2 ? null : h[h.length - 2]!;
3181
+ }
3182
+
3130
3183
  /** `ta.voi` — non-numeric inputs are 0 (`volume.py`). */
3131
3184
  voi(buy: Cell, sell: Cell): Cell {
3132
3185
  const b = buy !== null && Number.isFinite(buy) ? buy : 0;
@@ -3776,10 +3829,46 @@ export class TaEngine {
3776
3829
  });
3777
3830
  }
3778
3831
 
3779
- /** `strategies.py` `_builtin_ta_market_structure_pivot` (bar-mode last close). */
3780
- marketStructurePivot(close: Cell): TaRecord {
3781
- const c = finiteCell(close) ?? 0;
3782
- return taRec({ pivot_price: c, structure: "fractal", type: "high" });
3832
+ /**
3833
+ * `advanced.py` `_builtin_ta_market_structure_pivot` (wins MRO over the
3834
+ * strategies variant): oldest `period` highs/lows, midpoint pivot.
3835
+ */
3836
+ marketStructurePivot(
3837
+ site: string,
3838
+ high: unknown,
3839
+ low: unknown,
3840
+ period: Cell,
3841
+ mode: Cell,
3842
+ ): TaRecord {
3843
+ const hh = this.windowFor(`${site}:high`, high);
3844
+ const ll = this.windowFor(`${site}:low`, low);
3845
+ const n = this.coerceTaInt(period, "ta.market_structure_pivot() requires 5 arguments");
3846
+ const m = this.coerceTaInt(mode, "ta.market_structure_pivot() requires 5 arguments");
3847
+ const off = taRec({ pivot_price: 100, strength: 50, structure: "neutral" });
3848
+ if (hh.length === 0 || ll.length === 0 || hh.length < n || n <= 0) return off;
3849
+ const hVals = hh.slice(-n).filter((v): v is number => v !== null);
3850
+ const lVals = ll.slice(-n).filter((v): v is number => v !== null);
3851
+ if (hVals.length === 0 || lVals.length === 0) return off;
3852
+ let pivotHigh = hVals[0]!;
3853
+ let pivotLow = lVals[0]!;
3854
+ for (const v of hVals) if (v > pivotHigh) pivotHigh = v;
3855
+ for (const v of lVals) if (v < pivotLow) pivotLow = v;
3856
+ const price = (pivotHigh + pivotLow) / 2;
3857
+ const range = pivotHigh - pivotLow;
3858
+ let structure = "block";
3859
+ let strength = Math.min(100, range * 0.5);
3860
+ if (m === 0) {
3861
+ structure = "fractal";
3862
+ strength = Math.min(100, range * 2);
3863
+ } else if (m === 1) {
3864
+ structure = "swing";
3865
+ strength = Math.min(100, range * 1.5);
3866
+ }
3867
+ return taRec({
3868
+ pivot_price: finiteOut(price) ?? 0,
3869
+ strength: finiteOut(strength) ?? 0,
3870
+ structure,
3871
+ });
3783
3872
  }
3784
3873
 
3785
3874
  /** `strategies.py` `_builtin_ta_position_sizing_score`. */
@@ -3813,9 +3902,10 @@ export class TaEngine {
3813
3902
  });
3814
3903
  }
3815
3904
 
3816
- /** `strategies.py` `_builtin_ta_optimal_entry_zone` (bar-mode last close). */
3817
- optimalEntryZone(close: Cell): TaRecord {
3818
- const c = finiteCell(close) ?? 0;
3905
+ /** `strategies.py` `_builtin_ta_optimal_entry_zone` (newest-first list: `[-1]` = oldest). */
3906
+ optimalEntryZone(site: string, close: unknown): TaRecord {
3907
+ const h = this.windowFor(`${site}:close`, close);
3908
+ const c = TaEngine.oldest(h) ?? 0;
3819
3909
  return taRec({
3820
3910
  min: finiteOut(c * 0.99) ?? 0,
3821
3911
  max: finiteOut(c * 1.01) ?? 0,
@@ -3827,11 +3917,20 @@ export class TaEngine {
3827
3917
  });
3828
3918
  }
3829
3919
 
3830
- /** `strategies.py` `_builtin_ta_mean_reversion_entry` (bar-mode last samples). */
3831
- meanReversionEntry(price: Cell, sma: Cell, stdev: Cell, threshold: Cell): TaRecord {
3832
- const p = finiteCell(price) ?? 0;
3833
- const s = finiteCell(sma) ?? 0;
3834
- const sd = finiteCell(stdev) ?? 1;
3920
+ /** `strategies.py` `_builtin_ta_mean_reversion_entry` (newest-first lists: `[-1]` = oldest). */
3921
+ meanReversionEntry(
3922
+ site: string,
3923
+ price: unknown,
3924
+ sma: unknown,
3925
+ stdev: unknown,
3926
+ threshold: Cell,
3927
+ ): TaRecord {
3928
+ const ph = this.windowFor(`${site}:price`, price);
3929
+ const sh = this.windowFor(`${site}:sma`, sma);
3930
+ const dh = this.windowFor(`${site}:stdev`, stdev);
3931
+ const p = TaEngine.oldest(ph) ?? 0;
3932
+ const s = TaEngine.oldest(sh) ?? 0;
3933
+ const sd = TaEngine.oldest(dh) ?? 1;
3835
3934
  const th = finiteCell(threshold) ?? 0;
3836
3935
  const z = sd !== 0 ? (p - s) / sd : 0;
3837
3936
  return taRec({
@@ -3943,6 +4042,484 @@ export class TaEngine {
3943
4042
  return taRec({ is_breakout: false, breakout_type: "none", breakout_strength: 0 });
3944
4043
  }
3945
4044
 
4045
+ /** `core.py` `_ema_cross_signal_inc_update`. */
4046
+ emaCrossSignal(site: string, fast: Cell, slow: Cell, threshold: Cell): TaRecord {
4047
+ const off = taRec({ signal: "neutral", strength: 0, trend_direction: 0 });
4048
+ let st = this.emaCrossSites.get(site);
4049
+ if (st === undefined) {
4050
+ st = { prevFast: null, prevSlow: null, count: 0 };
4051
+ this.emaCrossSites.set(site, st);
4052
+ }
4053
+ const f = finiteCell(fast) ?? 0;
4054
+ const s = finiteCell(slow) ?? 0;
4055
+ const th = finiteCell(threshold) ?? 0;
4056
+ st.count += 1;
4057
+ const prevFast = st.prevFast;
4058
+ const prevSlow = st.prevSlow;
4059
+ if (st.count < 2 || prevFast === null || prevSlow === null) {
4060
+ st.prevFast = f;
4061
+ st.prevSlow = s;
4062
+ return off;
4063
+ }
4064
+ const diff = f - s;
4065
+ const prevDiff = prevFast - prevSlow;
4066
+ const crossover = prevDiff <= 0 && diff > 0;
4067
+ const crossunder = prevDiff >= 0 && diff < 0;
4068
+ const strength = Math.abs(diff);
4069
+ const trend = diff > 0 ? 1 : -1;
4070
+ let signal = "neutral";
4071
+ if (crossover && strength > th) signal = "buy";
4072
+ else if (crossunder && strength > th) signal = "sell";
4073
+ st.prevFast = f;
4074
+ st.prevSlow = s;
4075
+ return taRec({ signal, strength: finiteOut(strength) ?? 0, trend_direction: trend });
4076
+ }
4077
+
4078
+ /** `core.py` `_momentum_filter_inc_update`. */
4079
+ momentumFilter(site: string, momentum: Cell, volume: Cell, period: Cell): number {
4080
+ const n = this.coerceTaInt(period, "ta.momentum_filter() requires 3 arguments");
4081
+ if (n <= 0) return 0;
4082
+ let st = this.momentumFilterSites.get(`${site}:${n}`);
4083
+ if (st === undefined) {
4084
+ st = { momentum: [], volume: [] };
4085
+ this.momentumFilterSites.set(`${site}:${n}`, st);
4086
+ }
4087
+ pushCap(st.momentum, finiteCell(momentum), n);
4088
+ pushCap(st.volume, finiteCell(volume), n);
4089
+ if (st.momentum.length < n || st.volume.length < n) return 0;
4090
+ let volSum = 0;
4091
+ for (const v of st.volume) if (v !== null) volSum += v;
4092
+ if (volSum === 0) return 0;
4093
+ let numerator = 0;
4094
+ let paired = false;
4095
+ for (let i = 0; i < n; i++) {
4096
+ const m = st.momentum[i];
4097
+ const v = st.volume[i];
4098
+ if (m !== null && v !== null) {
4099
+ numerator += m * v;
4100
+ paired = true;
4101
+ }
4102
+ }
4103
+ if (!paired) return 0;
4104
+ return finiteOut(numerator / volSum) ?? 0;
4105
+ }
4106
+
4107
+ /** `advanced.py` `_volatility_regime_inc_update`. */
4108
+ volatilityRegime(site: string, atr: Cell, period: Cell): string {
4109
+ const n = this.coerceTaInt(period, "period must be integer");
4110
+ if (n < 1) return "medium";
4111
+ let w = this.volatilityRegimeSites.get(`${site}:${n}`);
4112
+ if (w === undefined) {
4113
+ w = [];
4114
+ this.volatilityRegimeSites.set(`${site}:${n}`, w);
4115
+ }
4116
+ pushCap(w, finiteCell(atr), n);
4117
+ if (w.length < n) return "medium";
4118
+ const recent: number[] = [];
4119
+ for (const v of w) if (v !== null) recent.push(v);
4120
+ if (recent.length === 0) return "medium";
4121
+ const current = recent[recent.length - 1]!;
4122
+ let sum = 0;
4123
+ for (const v of recent) sum += v;
4124
+ const avg = sum / recent.length;
4125
+ if (current < avg * 0.5) return "low";
4126
+ if (current > avg * 2) return "extreme";
4127
+ if (current > avg * 1.3) return "high";
4128
+ return "medium";
4129
+ }
4130
+
4131
+ /** `advanced.py` `_builtin_ta_economic_impact_score`. */
4132
+ economicImpactScore(priceChange: Cell, volatility: Cell, volumeChange: Cell): number {
4133
+ const pc = finiteCell(priceChange) ?? 0;
4134
+ const vol = finiteCell(volatility) ?? 0;
4135
+ const vc = finiteCell(volumeChange) ?? 0;
4136
+ const pcScore = Math.min(100, Math.abs(pc) * 20);
4137
+ const volScore = Math.min(100, vol * 30);
4138
+ const vcScore = Math.min(100, vc * 25);
4139
+ return Math.max(0, Math.min(100, (pcScore + volScore + vcScore) / 3));
4140
+ }
4141
+
4142
+ /** `advanced.py` `_builtin_ta_contrarian_signal`. */
4143
+ contrarianSignal(sentiment: Cell, volatility: Cell, timeSinceExtreme: Cell): TaRecord {
4144
+ const sent = finiteCell(sentiment) ?? 50;
4145
+ const vol = finiteCell(volatility) ?? 1;
4146
+ const time = finiteCell(timeSinceExtreme) ?? 10;
4147
+ let signal = "neutral";
4148
+ let strength = 0.5;
4149
+ let confidence = 0.5;
4150
+ if ((sent > 80 || sent < 20) && vol > 2 && time < 5) {
4151
+ signal = "strong_contrarian";
4152
+ strength = 0.9;
4153
+ confidence = 0.8;
4154
+ } else if (sent > 65 || sent < 35) {
4155
+ signal = "mild_contrarian";
4156
+ strength = 0.6;
4157
+ confidence = 0.6;
4158
+ } else if (sent > 45 && sent < 55) {
4159
+ signal = "follow_crowd";
4160
+ strength = 0.3;
4161
+ confidence = 0.4;
4162
+ }
4163
+ return taRec({ signal, strength, confidence });
4164
+ }
4165
+
4166
+ /** `strategies.py` `_builtin_ta_drawdown_recovery_level`. */
4167
+ drawdownRecoveryLevel(peak: Cell, current: Cell, factor: Cell, period: Cell): TaRecord {
4168
+ const p = finiteCell(peak) ?? 0;
4169
+ const c = finiteCell(current) ?? 0;
4170
+ const f = finiteCell(factor) ?? 0;
4171
+ const n = this.coerceTaInt(period, "ta.drawdown_recovery_level() requires 4 arguments");
4172
+ const drawdown = p > 0 ? (p - c) / p : 0;
4173
+ const recovery = drawdown < 1 ? drawdown / (1 - drawdown) : 0;
4174
+ return taRec({
4175
+ recovery_level: p,
4176
+ percent_needed: finiteOut(recovery * 100) ?? 0,
4177
+ estimated_time: finiteOut(n * f) ?? 0,
4178
+ confidence: 80,
4179
+ drawdown_percent: finiteOut(drawdown * 100) ?? 0,
4180
+ recovery_timeframe: finiteOut(n * f) ?? 0,
4181
+ recovery_confidence: 0.8,
4182
+ });
4183
+ }
4184
+
4185
+ /** `common.py` `_builtin_ta_pivot_point_levels` (high/low/close form). */
4186
+ pivotPointLevels(high: Cell, low: Cell, close: Cell, traditional: boolean): TaRecord {
4187
+ const h = finiteCell(high) ?? 0;
4188
+ const l = finiteCell(low) ?? 0;
4189
+ const c = finiteCell(close) ?? 0;
4190
+ const pivot = (h + l + c) / 3;
4191
+ let r1: number;
4192
+ let s1: number;
4193
+ let r2: number;
4194
+ let s2: number;
4195
+ let r3: number;
4196
+ let s3: number;
4197
+ if (traditional) {
4198
+ r1 = 2 * pivot - l;
4199
+ s1 = 2 * pivot - h;
4200
+ r2 = pivot + (h - l);
4201
+ s2 = pivot - (h - l);
4202
+ r3 = h + 2 * (pivot - l);
4203
+ s3 = l - 2 * (h - pivot);
4204
+ } else {
4205
+ const diff = h - l;
4206
+ r1 = pivot + 0.382 * diff;
4207
+ s1 = pivot - 0.382 * diff;
4208
+ r2 = pivot + 0.618 * diff;
4209
+ s2 = pivot - 0.618 * diff;
4210
+ r3 = pivot + diff;
4211
+ s3 = pivot - diff;
4212
+ }
4213
+ return taRec({
4214
+ pivot: finiteOut(pivot) ?? 0,
4215
+ r1: finiteOut(r1) ?? 0,
4216
+ s1: finiteOut(s1) ?? 0,
4217
+ r2: finiteOut(r2) ?? 0,
4218
+ s2: finiteOut(s2) ?? 0,
4219
+ r3: finiteOut(r3) ?? 0,
4220
+ s3: finiteOut(s3) ?? 0,
4221
+ });
4222
+ }
4223
+
4224
+ /** `advanced.py` `_builtin_ta_volatility_regime_score` (newest-first lists). */
4225
+ volatilityRegimeScore(
4226
+ site: string,
4227
+ atr: unknown,
4228
+ volatility: unknown,
4229
+ vix: unknown,
4230
+ threshold: Cell,
4231
+ ): TaRecord {
4232
+ const a = this.windowFor(`${site}:atr`, atr);
4233
+ const v = this.windowFor(`${site}:vol`, volatility);
4234
+ const x = this.windowFor(`${site}:vix`, vix);
4235
+ const th = finiteCell(threshold) ?? 50;
4236
+ if (a.length === 0 || v.length === 0 || x.length === 0) {
4237
+ return taRec({ regime: "normal", volatility_score: 50, momentum: "stable" });
4238
+ }
4239
+ const atrVal = TaEngine.oldest(a) ?? 2;
4240
+ const volVal = TaEngine.oldest(v) ?? 0.02;
4241
+ const vixVal = TaEngine.oldest(x) ?? 15;
4242
+ const atrScore = Math.min(100, atrVal * 20);
4243
+ const volScore = Math.min(100, volVal * 100);
4244
+ const vixScore = Math.min(100, vixVal * 2);
4245
+ const score = atrScore * 0.4 + volScore * 0.3 + vixScore * 0.3;
4246
+ let regime: string;
4247
+ if (score < th * 0.5) regime = "low";
4248
+ else if (score < th) regime = "normal";
4249
+ else if (score < th * 1.5) regime = "high";
4250
+ else regime = "extreme";
4251
+ let momentum = "stable";
4252
+ const prevAtr = TaEngine.secondOldest(a);
4253
+ if (a.length > 1 && prevAtr !== null) {
4254
+ if (atrVal > prevAtr * 1.05) momentum = "accelerating";
4255
+ else if (atrVal < prevAtr * 0.95) momentum = "decelerating";
4256
+ }
4257
+ return taRec({ regime, volatility_score: finiteOut(score) ?? 0, momentum });
4258
+ }
4259
+
4260
+ /** `advanced.py` `_builtin_ta_correlation_filter` (newest-first lists). */
4261
+ correlationFilter(
4262
+ site: string,
4263
+ s1: unknown,
4264
+ s2: unknown,
4265
+ s3: unknown,
4266
+ threshold: Cell,
4267
+ ): TaRecord {
4268
+ const h1 = this.windowFor(`${site}:s1`, s1);
4269
+ const h2 = this.windowFor(`${site}:s2`, s2);
4270
+ const h3 = this.windowFor(`${site}:s3`, s3);
4271
+ const histories = [h1, h2, h3].filter((h) => h.length > 0);
4272
+ const off = taRec({ is_correlated: false, signal_agreement: 0, divergence_count: 0 });
4273
+ if (histories.length < 2) return off;
4274
+ const lastVals: number[] = [];
4275
+ for (const h of histories) {
4276
+ const v = TaEngine.oldest(h);
4277
+ if (v !== null) lastVals.push(v);
4278
+ }
4279
+ if (lastVals.length === 0) return off;
4280
+ let agreement = 0;
4281
+ let divergence = 0;
4282
+ for (let i = 0; i < lastVals.length - 1; i++) {
4283
+ for (let j = i + 1; j < lastVals.length; j++) {
4284
+ if (lastVals[i]! * lastVals[j]! > 0) agreement += 1;
4285
+ else divergence += 1;
4286
+ }
4287
+ }
4288
+ const pairs = (lastVals.length * (lastVals.length - 1)) / 2;
4289
+ const pct = pairs > 0 ? (agreement / pairs) * 100 : 0;
4290
+ const th = finiteCell(threshold) ?? 0.7;
4291
+ return taRec({
4292
+ is_correlated: pct / 100 >= th,
4293
+ signal_agreement: finiteOut(pct) ?? 0,
4294
+ divergence_count: divergence,
4295
+ });
4296
+ }
4297
+
4298
+ /** `advanced.py` `_builtin_ta_advanced_breakout_detector` (newest-first lists). */
4299
+ advancedBreakoutDetector(
4300
+ site: string,
4301
+ price: unknown,
4302
+ volume: unknown,
4303
+ level: Cell,
4304
+ lookback: Cell,
4305
+ volumeMultiplier: Cell,
4306
+ ): TaRecord {
4307
+ const ph = this.windowFor(`${site}:price`, price);
4308
+ const vh = this.windowFor(`${site}:vol`, volume);
4309
+ const lvl = finiteCell(level) ?? 100;
4310
+ const n = this.coerceTaInt(lookback, "ta.advanced_breakout_detector() requires 5 arguments");
4311
+ const mult = finiteCell(volumeMultiplier) ?? 0.5;
4312
+ const off = taRec({ breakout_detected: false, breakout_type: "none", pullback_probability: 0.5 });
4313
+ if (ph.length === 0 || vh.length === 0 || ph.length < 2 || n <= 0) return off;
4314
+ const currentPrice = TaEngine.oldest(ph) ?? 100;
4315
+ const prevPrice = TaEngine.secondOldest(ph) ?? 100;
4316
+ const currentVol = TaEngine.oldest(vh) ?? 1000;
4317
+ const recentVol = vh.slice(-n).filter((v): v is number => v !== null);
4318
+ const avgVol = recentVol.length > 0 ? recentVol.reduce((a, b) => a + b, 0) / recentVol.length : 1000;
4319
+ const gap = currentPrice > lvl && prevPrice <= lvl;
4320
+ const closeBreak = currentPrice > lvl && Math.abs(currentPrice - lvl) < 0.5;
4321
+ const volumeBreak = currentVol > avgVol * (1 + mult);
4322
+ const detected = gap || closeBreak || volumeBreak;
4323
+ let type = "none";
4324
+ if (gap) type = "gap";
4325
+ else if (closeBreak && volumeBreak) type = "volume_break";
4326
+ else if (closeBreak) type = "close_above";
4327
+ const pullback = avgVol !== 0 ? Math.max(0.1, 0.8 - (currentVol / avgVol - 1) * 0.3) : 0.8;
4328
+ return taRec({
4329
+ breakout_detected: detected,
4330
+ breakout_type: type,
4331
+ pullback_probability: finiteOut(pullback) ?? 0.5,
4332
+ });
4333
+ }
4334
+
4335
+ /** `advanced.py` `_builtin_ta_pullback_bounce_level` (newest-first lists). */
4336
+ pullbackBounceLevel(
4337
+ site: string,
4338
+ high: unknown,
4339
+ low: unknown,
4340
+ trendDirection: Cell,
4341
+ lookback: Cell,
4342
+ ): TaRecord {
4343
+ const hh = this.windowFor(`${site}:high`, high);
4344
+ const ll = this.windowFor(`${site}:low`, low);
4345
+ const trend = this.coerceTaInt(trendDirection, "trend direction must be integer");
4346
+ const n = this.coerceTaInt(lookback, "ta.pullback_bounce_level() requires 5 arguments");
4347
+ const off = taRec({ primary_level: 100, bounce_probability: 0.5, support_strength: 50 });
4348
+ if (hh.length === 0 || ll.length === 0 || n <= 0) return off;
4349
+ const hVals = hh.slice(-n).filter((v): v is number => v !== null);
4350
+ const lVals = ll.slice(-n).filter((v): v is number => v !== null);
4351
+ if (hVals.length === 0 || lVals.length === 0) return off;
4352
+ let swingHigh = hVals[0]!;
4353
+ let swingLow = lVals[0]!;
4354
+ for (const v of hVals) if (v > swingHigh) swingHigh = v;
4355
+ for (const v of lVals) if (v < swingLow) swingLow = v;
4356
+ const range = swingHigh - swingLow;
4357
+ const fib = trend > 0 ? swingLow + range * 0.382 : swingHigh - range * 0.382;
4358
+ const bounce = swingHigh !== 0 ? Math.min(0.95, 0.5 + (range / swingHigh) * 1) : 0.5;
4359
+ const strength = swingHigh !== 0 ? Math.min(100, (range / swingHigh) * 100) : 0;
4360
+ return taRec({
4361
+ primary_level: finiteOut(fib) ?? 0,
4362
+ bounce_probability: finiteOut(bounce) ?? 0.5,
4363
+ support_strength: finiteOut(strength) ?? 0,
4364
+ });
4365
+ }
4366
+
4367
+ /** `advanced.py` `_builtin_ta_divergence_detector` (newest-first lists). */
4368
+ divergenceDetector(site: string, price: unknown, indicator: unknown, lookback: Cell): TaRecord {
4369
+ const ph = this.windowFor(`${site}:price`, price);
4370
+ const ih = this.windowFor(`${site}:ind`, indicator);
4371
+ const n = this.coerceTaInt(lookback, "lookback must be integer");
4372
+ const off = taRec({ is_bullish: false, is_bearish: false, strength: 0 });
4373
+ if (ph.length < n || ih.length < n) return off;
4374
+ const pv = ph.slice(-n).filter((v): v is number => v !== null);
4375
+ const iv = ih.slice(-n).filter((v): v is number => v !== null);
4376
+ if (pv.length < 2 || iv.length < 2) return off;
4377
+ const priceLower = pv[pv.length - 1]! < pv[0]!;
4378
+ const indHigher = iv[iv.length - 1]! > iv[0]!;
4379
+ const bullish = priceLower && indHigher;
4380
+ const priceHigher = pv[pv.length - 1]! > pv[0]!;
4381
+ const indLower = iv[iv.length - 1]! < iv[0]!;
4382
+ const bearish = priceHigher && indLower;
4383
+ const strength = Math.min(1, Math.abs(iv[iv.length - 1]! - iv[0]!) / 100);
4384
+ return taRec({
4385
+ is_bullish: bullish,
4386
+ is_bearish: bearish,
4387
+ strength: finiteOut(strength) ?? 0,
4388
+ });
4389
+ }
4390
+
4391
+ /** `advanced.py` `_builtin_ta_momentum_divergence` (newest-first lists). */
4392
+ momentumDivergence(
4393
+ site: string,
4394
+ price: unknown,
4395
+ momentumFast: unknown,
4396
+ momentumSlow: unknown,
4397
+ ): TaRecord {
4398
+ const ph = this.windowFor(`${site}:price`, price);
4399
+ const fh = this.windowFor(`${site}:fast`, momentumFast);
4400
+ const sh = this.windowFor(`${site}:slow`, momentumSlow);
4401
+ const off = taRec({ divergence_type: "none", strength: 0, bars_since: 0 });
4402
+ if (ph.length < 2 || fh.length < 2 || sh.length < 2) return off;
4403
+ const pv = ph.slice(-2).filter((v): v is number => v !== null);
4404
+ const fv = fh.slice(-2).filter((v): v is number => v !== null);
4405
+ const sv = sh.slice(-2).filter((v): v is number => v !== null);
4406
+ if (pv.length < 2 || fv.length < 2 || sv.length < 2) return off;
4407
+ const priceLower = pv[1]! < pv[0]!;
4408
+ const fastHigher = fv[1]! > fv[0]!;
4409
+ const slowHigher = sv[1]! > sv[0]!;
4410
+ const bullish = priceLower && fastHigher && slowHigher;
4411
+ const bearish = !priceLower && !fastHigher && !slowHigher;
4412
+ const type = bullish ? "bullish" : bearish ? "bearish" : "none";
4413
+ const strength = Math.min(1, Math.abs(fv[1]! - fv[0]!) / 100);
4414
+ return taRec({ divergence_type: type, strength: finiteOut(strength) ?? 0, bars_since: 1 });
4415
+ }
4416
+
4417
+ /** `economics.py` `_builtin_ta_spread_analysis` (newest-first lists). */
4418
+ spreadAnalysis(site: string, bid: unknown, ask: unknown, period: Cell): TaRecord {
4419
+ const bh = this.windowFor(`${site}:bid`, bid);
4420
+ const ah = this.windowFor(`${site}:ask`, ask);
4421
+ const n = this.coerceTaInt(period, "ta.spread_analysis() requires 3 arguments");
4422
+ const off = taRec({ avg_spread: 0, spread_percent: 0, spread_trend: "stable" });
4423
+ if (bh.length < n || ah.length < n || n <= 0) return off;
4424
+ const bSlice = bh.slice(-n);
4425
+ const aSlice = ah.slice(-n);
4426
+ const spreads: number[] = [];
4427
+ for (let i = 0; i < n; i++) {
4428
+ const b = bSlice[i] ?? 0;
4429
+ const a = aSlice[i] ?? 0;
4430
+ if (a > b && b > 0) spreads.push(a - b);
4431
+ }
4432
+ if (spreads.length === 0) return off;
4433
+ const avg = spreads.reduce((a, b) => a + b, 0) / spreads.length;
4434
+ const askOld = TaEngine.oldest(ah);
4435
+ const bidOld = TaEngine.oldest(bh);
4436
+ const mid = askOld !== null && bidOld !== null ? (askOld + bidOld) / 2 : 100;
4437
+ const pct = mid > 0 ? (avg / mid) * 100 : 0;
4438
+ let trend = "stable";
4439
+ if (spreads.length >= 2) {
4440
+ const first = spreads[0]!;
4441
+ const last = spreads[spreads.length - 1]!;
4442
+ if (last > first * 1.1) trend = "increasing";
4443
+ else if (last < first * 0.9) trend = "decreasing";
4444
+ }
4445
+ return taRec({
4446
+ avg_spread: finiteOut(avg) ?? 0,
4447
+ spread_percent: finiteOut(pct) ?? 0,
4448
+ spread_trend: trend,
4449
+ });
4450
+ }
4451
+
4452
+ /** `advanced.py` `_builtin_ta_employment_cycle_indicator` (newest-first lists). */
4453
+ employmentCycleIndicator(
4454
+ site: string,
4455
+ cyclical: unknown,
4456
+ defensive: unknown,
4457
+ unemployment: unknown,
4458
+ ): string {
4459
+ const ch = this.windowFor(`${site}:cyc`, cyclical);
4460
+ const dh = this.windowFor(`${site}:def`, defensive);
4461
+ const uh = this.windowFor(`${site}:unemp`, unemployment);
4462
+ if (ch.length === 0 || dh.length === 0 || uh.length === 0) return "mid_cycle";
4463
+ const cNew = ch[0];
4464
+ const cOld = TaEngine.oldest(ch);
4465
+ const dNew = dh[0];
4466
+ const dOld = TaEngine.oldest(dh);
4467
+ const cycPerf = cNew !== null && cOld !== null && cNew !== 0 ? (cOld - cNew) / cNew : 0;
4468
+ const defPerf = dNew !== null && dOld !== null && dNew !== 0 ? (dOld - dNew) / dNew : 0;
4469
+ const unemp = TaEngine.oldest(uh) ?? 0.05;
4470
+ if (cycPerf > defPerf && unemp < 0.04) return "early_cycle";
4471
+ if (cycPerf > defPerf && unemp < 0.06) return "mid_cycle";
4472
+ if (cycPerf < defPerf && unemp > 0.05) return "late_cycle";
4473
+ return "recession";
4474
+ }
4475
+
4476
+ /** `advanced.py` `_builtin_ta_gdp_growth_proxy` (newest-first lists). */
4477
+ gdpGrowthProxy(site: string, breadth: unknown, volume: unknown, momentum: unknown): number {
4478
+ const bh = this.windowFor(`${site}:breadth`, breadth);
4479
+ const vh = this.windowFor(`${site}:volume`, volume);
4480
+ const mh = this.windowFor(`${site}:momentum`, momentum);
4481
+ if (bh.length === 0 || vh.length === 0 || mh.length === 0) return 0;
4482
+ const b = TaEngine.oldest(bh) ?? 0.5;
4483
+ const bScore = b * 2 - 1;
4484
+ const vNew = vh[0];
4485
+ const vOld = TaEngine.oldest(vh);
4486
+ const vChange = vNew !== null && vOld !== null && vNew !== 0 ? ((vOld - vNew) / vNew) * 100 : 0;
4487
+ const m = TaEngine.oldest(mh) ?? 0;
4488
+ const gdp = bScore * 1.5 + vChange / 100 + m / 100;
4489
+ return Math.max(-2, Math.min(4, gdp));
4490
+ }
4491
+
4492
+ /** `advanced.py` `_builtin_ta_inflation_proxy_indicator` (newest-first lists). */
4493
+ inflationProxyIndicator(site: string, usdIndex: unknown, commodities: unknown, bondYields: unknown): number {
4494
+ const uh = this.windowFor(`${site}:usd`, usdIndex);
4495
+ const ch = this.windowFor(`${site}:comm`, commodities);
4496
+ const yh = this.windowFor(`${site}:yield`, bondYields);
4497
+ if (uh.length === 0 || ch.length === 0 || yh.length === 0) return 0;
4498
+ const uNew = uh[0];
4499
+ const uOld = TaEngine.oldest(uh);
4500
+ const usdChange =
4501
+ uNew !== null && uOld !== null && uNew !== 0 ? -((uOld - uNew) / uNew) * 100 : 0;
4502
+ const cNew = ch[0];
4503
+ const cOld = TaEngine.oldest(ch);
4504
+ const commChange = cNew !== null && cOld !== null && cNew !== 0 ? ((cOld - cNew) / cNew) * 100 : 0;
4505
+ const yNew = yh[0];
4506
+ const yOld = TaEngine.oldest(yh);
4507
+ const yieldsChange = yNew !== null && yOld !== null ? yOld - yNew : 0;
4508
+ const pressure = usdChange * 0.3 + commChange * 0.4 + yieldsChange * 0.3;
4509
+ return Math.max(-100, Math.min(100, pressure * 10));
4510
+ }
4511
+
4512
+ /** `common.py` `_builtin_ta_expected_value`. */
4513
+ expectedValue(returns: number[], probabilities: number[]): number {
4514
+ if (returns.length !== probabilities.length) return 0;
4515
+ let totalProb = 0;
4516
+ for (const p of probabilities) totalProb += p;
4517
+ if (totalProb === 0) return 0;
4518
+ let ev = 0;
4519
+ for (let i = 0; i < returns.length; i++) ev += returns[i]! * probabilities[i]!;
4520
+ return finiteOut(ev / totalProb) ?? 0;
4521
+ }
4522
+
3946
4523
  /**
3947
4524
  * `ta.volume_profile_high` — numeric list only (`advanced.py`).
3948
4525
  * A one-element pair is that price when its volume is the strict max.