fixparser-plugin-mcp 9.1.7-57d70bb1 → 9.1.7-5d282a9e

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.
@@ -132,7 +132,7 @@ var toolSchemas = {
132
132
  }
133
133
  },
134
134
  executeOrder: {
135
- description: "Executes a verified order. verifyOrder must be called before executeOrder. user has to explicitly allow executeOrder.",
135
+ description: "Executes a verified order. verifyOrder must be called before executeOrder.",
136
136
  schema: {
137
137
  type: "object",
138
138
  properties: {
@@ -276,8 +276,1567 @@ var toolSchemas = {
276
276
  },
277
277
  required: ["symbol"]
278
278
  }
279
+ },
280
+ technicalAnalysis: {
281
+ description: "Performs comprehensive technical analysis on market data for a given symbol, including indicators like SMA, EMA, RSI, Bollinger Bands, and trading signals",
282
+ schema: {
283
+ type: "object",
284
+ properties: {
285
+ symbol: {
286
+ type: "string",
287
+ description: "The trading symbol to analyze (e.g., AAPL, MSFT, EURUSD)"
288
+ }
289
+ },
290
+ required: ["symbol"]
291
+ }
292
+ }
293
+ };
294
+
295
+ // src/tools/analytics.ts
296
+ function sum(numbers) {
297
+ return numbers.reduce((acc, val) => acc + val, 0);
298
+ }
299
+ var TechnicalAnalyzer = class {
300
+ prices;
301
+ volumes;
302
+ highs;
303
+ lows;
304
+ constructor(data) {
305
+ this.prices = data.map((d) => d.trade > 0 ? d.trade : d.midPrice);
306
+ this.volumes = data.map((d) => d.volume);
307
+ this.highs = data.map((d) => d.tradingSessionHighPrice > 0 ? d.tradingSessionHighPrice : d.trade);
308
+ this.lows = data.map((d) => d.tradingSessionLowPrice > 0 ? d.tradingSessionLowPrice : d.trade);
309
+ }
310
+ // Calculate Simple Moving Average
311
+ calculateSMA(data, period) {
312
+ const sma = [];
313
+ for (let i = period - 1; i < data.length; i++) {
314
+ const sum2 = data.slice(i - period + 1, i + 1).reduce((a, b) => a + b, 0);
315
+ sma.push(sum2 / period);
316
+ }
317
+ return sma;
318
+ }
319
+ // Calculate Exponential Moving Average
320
+ calculateEMA(data, period) {
321
+ const multiplier = 2 / (period + 1);
322
+ const ema = [data[0]];
323
+ for (let i = 1; i < data.length; i++) {
324
+ ema.push(data[i] * multiplier + ema[i - 1] * (1 - multiplier));
325
+ }
326
+ return ema;
327
+ }
328
+ // Calculate RSI
329
+ calculateRSI(data, period = 14) {
330
+ if (data.length < period + 1) return [];
331
+ const changes = [];
332
+ for (let i = 1; i < data.length; i++) {
333
+ changes.push(data[i] - data[i - 1]);
334
+ }
335
+ const gains = changes.map((change) => change > 0 ? change : 0);
336
+ const losses = changes.map((change) => change < 0 ? Math.abs(change) : 0);
337
+ let avgGain = gains.slice(0, period).reduce((a, b) => a + b, 0) / period;
338
+ let avgLoss = losses.slice(0, period).reduce((a, b) => a + b, 0) / period;
339
+ const rsi = [];
340
+ for (let i = period; i < changes.length; i++) {
341
+ const rs = avgGain / avgLoss;
342
+ rsi.push(100 - 100 / (1 + rs));
343
+ avgGain = (avgGain * (period - 1) + gains[i]) / period;
344
+ avgLoss = (avgLoss * (period - 1) + losses[i]) / period;
345
+ }
346
+ return rsi;
347
+ }
348
+ // Calculate Bollinger Bands
349
+ calculateBollingerBands(data, period = 20, stdDev = 2) {
350
+ if (data.length < period) return [];
351
+ const sma = this.calculateSMA(data, period);
352
+ const bands = [];
353
+ for (let i = 0; i < sma.length; i++) {
354
+ const dataSlice = data.slice(i, i + period);
355
+ const mean = sma[i];
356
+ const variance = dataSlice.reduce((sum2, price) => sum2 + (price - mean) ** 2, 0) / period;
357
+ const standardDeviation = Math.sqrt(variance);
358
+ const upper = mean + standardDeviation * stdDev;
359
+ const lower = mean - standardDeviation * stdDev;
360
+ bands.push({
361
+ upper,
362
+ middle: mean,
363
+ lower,
364
+ bandwidth: (upper - lower) / mean * 100,
365
+ percentB: (data[i] - lower) / (upper - lower) * 100
366
+ });
367
+ }
368
+ return bands;
369
+ }
370
+ // Calculate maximum drawdown
371
+ calculateMaxDrawdown(prices) {
372
+ let maxPrice = prices[0];
373
+ let maxDrawdown = 0;
374
+ for (let i = 1; i < prices.length; i++) {
375
+ if (prices[i] > maxPrice) {
376
+ maxPrice = prices[i];
377
+ }
378
+ const drawdown = (maxPrice - prices[i]) / maxPrice;
379
+ if (drawdown > maxDrawdown) {
380
+ maxDrawdown = drawdown;
381
+ }
382
+ }
383
+ return maxDrawdown;
384
+ }
385
+ // Calculate Average True Range (ATR)
386
+ calculateAtr(prices, highs, lows) {
387
+ if (prices.length < 2) return [];
388
+ const trueRanges = [];
389
+ for (let i = 1; i < prices.length; i++) {
390
+ const high = highs[i] || prices[i];
391
+ const low = lows[i] || prices[i];
392
+ const prevClose = prices[i - 1];
393
+ const tr1 = high - low;
394
+ const tr2 = Math.abs(high - prevClose);
395
+ const tr3 = Math.abs(low - prevClose);
396
+ trueRanges.push(Math.max(tr1, tr2, tr3));
397
+ }
398
+ const atr = [];
399
+ if (trueRanges.length >= 14) {
400
+ let sum2 = trueRanges.slice(0, 14).reduce((a, b) => a + b, 0);
401
+ atr.push(sum2 / 14);
402
+ for (let i = 14; i < trueRanges.length; i++) {
403
+ sum2 = sum2 - trueRanges[i - 14] + trueRanges[i];
404
+ atr.push(sum2 / 14);
405
+ }
406
+ }
407
+ return atr;
408
+ }
409
+ // Calculate maximum consecutive losses
410
+ calculateMaxConsecutiveLosses(prices) {
411
+ let maxConsecutive = 0;
412
+ let currentConsecutive = 0;
413
+ for (let i = 1; i < prices.length; i++) {
414
+ if (prices[i] < prices[i - 1]) {
415
+ currentConsecutive++;
416
+ maxConsecutive = Math.max(maxConsecutive, currentConsecutive);
417
+ } else {
418
+ currentConsecutive = 0;
419
+ }
420
+ }
421
+ return maxConsecutive;
422
+ }
423
+ // Calculate win rate
424
+ calculateWinRate(prices) {
425
+ let wins = 0;
426
+ let total = 0;
427
+ for (let i = 1; i < prices.length; i++) {
428
+ if (prices[i] !== prices[i - 1]) {
429
+ total++;
430
+ if (prices[i] > prices[i - 1]) {
431
+ wins++;
432
+ }
433
+ }
434
+ }
435
+ return total > 0 ? wins / total : 0;
436
+ }
437
+ // Calculate profit factor
438
+ calculateProfitFactor(prices) {
439
+ let grossProfit = 0;
440
+ let grossLoss = 0;
441
+ for (let i = 1; i < prices.length; i++) {
442
+ const change = prices[i] - prices[i - 1];
443
+ if (change > 0) {
444
+ grossProfit += change;
445
+ } else {
446
+ grossLoss += Math.abs(change);
447
+ }
448
+ }
449
+ return grossLoss > 0 ? grossProfit / grossLoss : 0;
450
+ }
451
+ // Calculate Weighted Moving Average
452
+ calculateWma(data, period) {
453
+ const wma = [];
454
+ const weights = Array.from({ length: period }, (_, i) => i + 1);
455
+ const weightSum = weights.reduce((a, b) => a + b, 0);
456
+ for (let i = period - 1; i < data.length; i++) {
457
+ let weightedSum = 0;
458
+ for (let j = 0; j < period; j++) {
459
+ weightedSum += data[i - j] * weights[j];
460
+ }
461
+ wma.push(weightedSum / weightSum);
462
+ }
463
+ return wma;
464
+ }
465
+ // Calculate Volume Weighted Moving Average
466
+ calculateVwma(prices, period) {
467
+ const vwma = [];
468
+ for (let i = period - 1; i < prices.length; i++) {
469
+ let volumeSum = 0;
470
+ let priceVolumeSum = 0;
471
+ for (let j = 0; j < period; j++) {
472
+ const volume = this.volumes[i - j] || 1;
473
+ volumeSum += volume;
474
+ priceVolumeSum += prices[i - j] * volume;
475
+ }
476
+ vwma.push(priceVolumeSum / volumeSum);
477
+ }
478
+ return vwma;
479
+ }
480
+ // Calculate MACD
481
+ calculateMacd(prices) {
482
+ const ema12 = this.calculateEMA(prices, 12);
483
+ const ema26 = this.calculateEMA(prices, 26);
484
+ const macd = [];
485
+ const macdLine = [];
486
+ for (let i = 0; i < Math.min(ema12.length, ema26.length); i++) {
487
+ macdLine.push(ema12[i] - ema26[i]);
488
+ }
489
+ const signalLine = this.calculateEMA(macdLine, 9);
490
+ for (let i = 0; i < Math.min(macdLine.length, signalLine.length); i++) {
491
+ macd.push({
492
+ macd: macdLine[i],
493
+ signal: signalLine[i],
494
+ histogram: macdLine[i] - signalLine[i]
495
+ });
496
+ }
497
+ return macd;
498
+ }
499
+ // Calculate ADX (Average Directional Index)
500
+ calculateAdx(prices, highs, lows) {
501
+ if (prices.length < 14) return [];
502
+ const period = 14;
503
+ const adx = [];
504
+ const trueRanges = [];
505
+ const plusDM = [];
506
+ const minusDM = [];
507
+ trueRanges.push(highs[0] - lows[0]);
508
+ plusDM.push(0);
509
+ minusDM.push(0);
510
+ for (let i = 1; i < prices.length; i++) {
511
+ const high = highs[i] || prices[i];
512
+ const low = lows[i] || prices[i];
513
+ const prevHigh = highs[i - 1] || prices[i - 1];
514
+ const prevLow = lows[i - 1] || prices[i - 1];
515
+ const prevClose = prices[i - 1];
516
+ const tr1 = high - low;
517
+ const tr2 = Math.abs(high - prevClose);
518
+ const tr3 = Math.abs(low - prevClose);
519
+ trueRanges.push(Math.max(tr1, tr2, tr3));
520
+ const upMove = high - prevHigh;
521
+ const downMove = prevLow - low;
522
+ if (upMove > downMove && upMove > 0) {
523
+ plusDM.push(upMove);
524
+ minusDM.push(0);
525
+ } else if (downMove > upMove && downMove > 0) {
526
+ plusDM.push(0);
527
+ minusDM.push(downMove);
528
+ } else {
529
+ plusDM.push(0);
530
+ minusDM.push(0);
531
+ }
532
+ }
533
+ const smoothedTR = [];
534
+ const smoothedPlusDM = [];
535
+ const smoothedMinusDM = [];
536
+ let sumTR = 0;
537
+ let sumPlusDM = 0;
538
+ let sumMinusDM = 0;
539
+ for (let i = 0; i < period; i++) {
540
+ sumTR += trueRanges[i];
541
+ sumPlusDM += plusDM[i];
542
+ sumMinusDM += minusDM[i];
543
+ }
544
+ smoothedTR.push(sumTR);
545
+ smoothedPlusDM.push(sumPlusDM);
546
+ smoothedMinusDM.push(sumMinusDM);
547
+ for (let i = period; i < trueRanges.length; i++) {
548
+ const newTR = smoothedTR[smoothedTR.length - 1] - smoothedTR[smoothedTR.length - 1] / period + trueRanges[i];
549
+ const newPlusDM = smoothedPlusDM[smoothedPlusDM.length - 1] - smoothedPlusDM[smoothedPlusDM.length - 1] / period + plusDM[i];
550
+ const newMinusDM = smoothedMinusDM[smoothedMinusDM.length - 1] - smoothedMinusDM[smoothedMinusDM.length - 1] / period + minusDM[i];
551
+ smoothedTR.push(newTR);
552
+ smoothedPlusDM.push(newPlusDM);
553
+ smoothedMinusDM.push(newMinusDM);
554
+ }
555
+ const plusDI = [];
556
+ const minusDI = [];
557
+ for (let i = 0; i < smoothedTR.length; i++) {
558
+ plusDI.push(smoothedPlusDM[i] / smoothedTR[i] * 100);
559
+ minusDI.push(smoothedMinusDM[i] / smoothedTR[i] * 100);
560
+ }
561
+ const dx = [];
562
+ for (let i = 0; i < plusDI.length; i++) {
563
+ const diSum = plusDI[i] + minusDI[i];
564
+ const diDiff = Math.abs(plusDI[i] - minusDI[i]);
565
+ dx.push(diSum > 0 ? diDiff / diSum * 100 : 0);
566
+ }
567
+ if (dx.length < period) return [];
568
+ let sumDX = 0;
569
+ for (let i = 0; i < period; i++) {
570
+ sumDX += dx[i];
571
+ }
572
+ adx.push(sumDX / period);
573
+ for (let i = period; i < dx.length; i++) {
574
+ const newADX = adx[adx.length - 1] - adx[adx.length - 1] / period + dx[i];
575
+ adx.push(newADX);
576
+ }
577
+ return adx;
578
+ }
579
+ // Calculate DMI (Directional Movement Index)
580
+ calculateDmi(prices, highs, lows) {
581
+ if (prices.length < 14) return [];
582
+ const period = 14;
583
+ const dmi = [];
584
+ const trueRanges = [];
585
+ const plusDM = [];
586
+ const minusDM = [];
587
+ trueRanges.push(highs[0] - lows[0]);
588
+ plusDM.push(0);
589
+ minusDM.push(0);
590
+ for (let i = 1; i < prices.length; i++) {
591
+ const high = highs[i] || prices[i];
592
+ const low = lows[i] || prices[i];
593
+ const prevHigh = highs[i - 1] || prices[i - 1];
594
+ const prevLow = lows[i - 1] || prices[i - 1];
595
+ const prevClose = prices[i - 1];
596
+ const tr1 = high - low;
597
+ const tr2 = Math.abs(high - prevClose);
598
+ const tr3 = Math.abs(low - prevClose);
599
+ trueRanges.push(Math.max(tr1, tr2, tr3));
600
+ const upMove = high - prevHigh;
601
+ const downMove = prevLow - low;
602
+ if (upMove > downMove && upMove > 0) {
603
+ plusDM.push(upMove);
604
+ minusDM.push(0);
605
+ } else if (downMove > upMove && downMove > 0) {
606
+ plusDM.push(0);
607
+ minusDM.push(downMove);
608
+ } else {
609
+ plusDM.push(0);
610
+ minusDM.push(0);
611
+ }
612
+ }
613
+ const smoothedTR = [];
614
+ const smoothedPlusDM = [];
615
+ const smoothedMinusDM = [];
616
+ let sumTR = 0;
617
+ let sumPlusDM = 0;
618
+ let sumMinusDM = 0;
619
+ for (let i = 0; i < period; i++) {
620
+ sumTR += trueRanges[i];
621
+ sumPlusDM += plusDM[i];
622
+ sumMinusDM += minusDM[i];
623
+ }
624
+ smoothedTR.push(sumTR);
625
+ smoothedPlusDM.push(sumPlusDM);
626
+ smoothedMinusDM.push(sumMinusDM);
627
+ for (let i = period; i < trueRanges.length; i++) {
628
+ const newTR = smoothedTR[smoothedTR.length - 1] - smoothedTR[smoothedTR.length - 1] / period + trueRanges[i];
629
+ const newPlusDM = smoothedPlusDM[smoothedPlusDM.length - 1] - smoothedPlusDM[smoothedPlusDM.length - 1] / period + plusDM[i];
630
+ const newMinusDM = smoothedMinusDM[smoothedMinusDM.length - 1] - smoothedMinusDM[smoothedMinusDM.length - 1] / period + minusDM[i];
631
+ smoothedTR.push(newTR);
632
+ smoothedPlusDM.push(newPlusDM);
633
+ smoothedMinusDM.push(newMinusDM);
634
+ }
635
+ const plusDI = [];
636
+ const minusDI = [];
637
+ for (let i = 0; i < smoothedTR.length; i++) {
638
+ plusDI.push(smoothedPlusDM[i] / smoothedTR[i] * 100);
639
+ minusDI.push(smoothedMinusDM[i] / smoothedTR[i] * 100);
640
+ }
641
+ const dx = [];
642
+ for (let i = 0; i < plusDI.length; i++) {
643
+ const diSum = plusDI[i] + minusDI[i];
644
+ const diDiff = Math.abs(plusDI[i] - minusDI[i]);
645
+ dx.push(diSum > 0 ? diDiff / diSum * 100 : 0);
646
+ }
647
+ if (dx.length < period) return [];
648
+ const adx = [];
649
+ let sumDX = 0;
650
+ for (let i = 0; i < period; i++) {
651
+ sumDX += dx[i];
652
+ }
653
+ adx.push(sumDX / period);
654
+ for (let i = period; i < dx.length; i++) {
655
+ const newADX = adx[adx.length - 1] - adx[adx.length - 1] / period + dx[i];
656
+ adx.push(newADX);
657
+ }
658
+ for (let i = 0; i < adx.length; i++) {
659
+ dmi.push({
660
+ plusDI: plusDI[i + period - 1] || 0,
661
+ minusDI: minusDI[i + period - 1] || 0,
662
+ adx: adx[i]
663
+ });
664
+ }
665
+ return dmi;
666
+ }
667
+ // Calculate Ichimoku Cloud
668
+ calculateIchimoku(prices, highs, lows) {
669
+ if (prices.length < 52) return [];
670
+ const ichimoku = [];
671
+ const tenkanSen = [];
672
+ for (let i = 8; i < prices.length; i++) {
673
+ const periodHigh = Math.max(...highs.slice(i - 8, i + 1));
674
+ const periodLow = Math.min(...lows.slice(i - 8, i + 1));
675
+ tenkanSen.push((periodHigh + periodLow) / 2);
676
+ }
677
+ const kijunSen = [];
678
+ for (let i = 25; i < prices.length; i++) {
679
+ const periodHigh = Math.max(...highs.slice(i - 25, i + 1));
680
+ const periodLow = Math.min(...lows.slice(i - 25, i + 1));
681
+ kijunSen.push((periodHigh + periodLow) / 2);
682
+ }
683
+ const senkouSpanA = [];
684
+ for (let i = 0; i < Math.min(tenkanSen.length, kijunSen.length); i++) {
685
+ senkouSpanA.push((tenkanSen[i] + kijunSen[i]) / 2);
686
+ }
687
+ const senkouSpanB = [];
688
+ for (let i = 51; i < prices.length; i++) {
689
+ const periodHigh = Math.max(...highs.slice(i - 51, i + 1));
690
+ const periodLow = Math.min(...lows.slice(i - 51, i + 1));
691
+ senkouSpanB.push((periodHigh + periodLow) / 2);
692
+ }
693
+ const chikouSpan = [];
694
+ for (let i = 26; i < prices.length; i++) {
695
+ chikouSpan.push(prices[i - 26]);
696
+ }
697
+ const minLength = Math.min(
698
+ tenkanSen.length,
699
+ kijunSen.length,
700
+ senkouSpanA.length,
701
+ senkouSpanB.length,
702
+ chikouSpan.length
703
+ );
704
+ for (let i = 0; i < minLength; i++) {
705
+ ichimoku.push({
706
+ tenkan: tenkanSen[i],
707
+ kijun: kijunSen[i],
708
+ senkouA: senkouSpanA[i],
709
+ senkouB: senkouSpanB[i],
710
+ chikou: chikouSpan[i]
711
+ });
712
+ }
713
+ return ichimoku;
714
+ }
715
+ // Calculate Parabolic SAR
716
+ calculateParabolicSAR(prices, highs, lows) {
717
+ if (prices.length < 2) return [];
718
+ const sar = [];
719
+ const accelerationFactor = 0.02;
720
+ const maximumAcceleration = 0.2;
721
+ let currentSAR = lows[0];
722
+ let isLong = true;
723
+ let af = accelerationFactor;
724
+ let ep = highs[0];
725
+ sar.push(currentSAR);
726
+ for (let i = 1; i < prices.length; i++) {
727
+ const high = highs[i] || prices[i];
728
+ const low = lows[i] || prices[i];
729
+ if (isLong) {
730
+ if (low < currentSAR) {
731
+ isLong = false;
732
+ currentSAR = ep;
733
+ ep = low;
734
+ af = accelerationFactor;
735
+ } else {
736
+ if (high > ep) {
737
+ ep = high;
738
+ af = Math.min(af + accelerationFactor, maximumAcceleration);
739
+ }
740
+ currentSAR = currentSAR + af * (ep - currentSAR);
741
+ if (i > 0) {
742
+ const prevLow = lows[i - 1] || prices[i - 1];
743
+ currentSAR = Math.min(currentSAR, prevLow);
744
+ }
745
+ }
746
+ } else {
747
+ if (high > currentSAR) {
748
+ isLong = true;
749
+ currentSAR = ep;
750
+ ep = high;
751
+ af = accelerationFactor;
752
+ } else {
753
+ if (low < ep) {
754
+ ep = low;
755
+ af = Math.min(af + accelerationFactor, maximumAcceleration);
756
+ }
757
+ currentSAR = currentSAR + af * (ep - currentSAR);
758
+ if (i > 0) {
759
+ const prevHigh = highs[i - 1] || prices[i - 1];
760
+ currentSAR = Math.max(currentSAR, prevHigh);
761
+ }
762
+ }
763
+ }
764
+ sar.push(currentSAR);
765
+ }
766
+ return sar;
767
+ }
768
+ // Calculate Stochastic
769
+ calculateStochastic(prices, highs, lows) {
770
+ const stochastic = [];
771
+ const period = 14;
772
+ const smoothK = 3;
773
+ const smoothD = 3;
774
+ if (prices.length < period) return [];
775
+ const percentK = [];
776
+ for (let i = period - 1; i < prices.length; i++) {
777
+ const high = Math.max(...highs.slice(i - period + 1, i + 1));
778
+ const low = Math.min(...lows.slice(i - period + 1, i + 1));
779
+ const close = prices[i];
780
+ const k = (close - low) / (high - low) * 100;
781
+ percentK.push(k);
782
+ }
783
+ const smoothedK = [];
784
+ for (let i = smoothK - 1; i < percentK.length; i++) {
785
+ const sum2 = percentK.slice(i - smoothK + 1, i + 1).reduce((a, b) => a + b, 0);
786
+ smoothedK.push(sum2 / smoothK);
787
+ }
788
+ for (let i = smoothD - 1; i < smoothedK.length; i++) {
789
+ const sum2 = smoothedK.slice(i - smoothD + 1, i + 1).reduce((a, b) => a + b, 0);
790
+ const d = sum2 / smoothD;
791
+ stochastic.push({
792
+ k: smoothedK[i],
793
+ d
794
+ });
795
+ }
796
+ return stochastic;
797
+ }
798
+ // Calculate CCI
799
+ calculateCci(prices, highs, lows) {
800
+ const cci = [];
801
+ const period = 20;
802
+ if (prices.length < period) return [];
803
+ for (let i = period - 1; i < prices.length; i++) {
804
+ const slice = prices.slice(i - period + 1, i + 1);
805
+ const typicalPrices = slice.map((price, idx) => {
806
+ const high = highs[i - period + 1 + idx] || price;
807
+ const low = lows[i - period + 1 + idx] || price;
808
+ return (high + low + price) / 3;
809
+ });
810
+ const sma = typicalPrices.reduce((a, b) => a + b, 0) / period;
811
+ const meanDeviation = typicalPrices.reduce((sum2, tp) => sum2 + Math.abs(tp - sma), 0) / period;
812
+ const currentTP = (highs[i] + lows[i] + prices[i]) / 3;
813
+ const cciValue = meanDeviation !== 0 ? (currentTP - sma) / (0.015 * meanDeviation) : 0;
814
+ cci.push(cciValue);
815
+ }
816
+ return cci;
817
+ }
818
+ // Calculate Rate of Change
819
+ calculateRoc(prices) {
820
+ const roc = [];
821
+ for (let i = 10; i < prices.length; i++) {
822
+ roc.push((prices[i] - prices[i - 10]) / prices[i - 10] * 100);
823
+ }
824
+ return roc;
825
+ }
826
+ // Calculate Williams %R
827
+ calculateWilliamsR(prices) {
828
+ const williamsR = [];
829
+ const period = 14;
830
+ if (prices.length < period) return [];
831
+ for (let i = period - 1; i < prices.length; i++) {
832
+ const slice = prices.slice(i - period + 1, i + 1);
833
+ const high = Math.max(...slice);
834
+ const low = Math.min(...slice);
835
+ const close = prices[i];
836
+ const wr = (high - close) / (high - low) * -100;
837
+ williamsR.push(wr);
838
+ }
839
+ return williamsR;
840
+ }
841
+ // Calculate Momentum
842
+ calculateMomentum(prices) {
843
+ const momentum = [];
844
+ for (let i = 10; i < prices.length; i++) {
845
+ momentum.push(prices[i] - prices[i - 10]);
846
+ }
847
+ return momentum;
848
+ }
849
+ // Calculate Keltner Channels
850
+ calculateKeltnerChannels(prices, highs, lows) {
851
+ const keltner = [];
852
+ const period = 20;
853
+ const multiplier = 2;
854
+ if (prices.length < period) return [];
855
+ const ema = this.calculateEMA(prices, period);
856
+ const atr = this.calculateAtr(prices, highs, lows);
857
+ for (let i = 0; i < Math.min(ema.length, atr.length); i++) {
858
+ const middle = ema[i];
859
+ const atrValue = atr[i];
860
+ keltner.push({
861
+ upper: middle + multiplier * atrValue,
862
+ middle,
863
+ lower: middle - multiplier * atrValue
864
+ });
865
+ }
866
+ return keltner;
867
+ }
868
+ // Calculate Donchian Channels
869
+ calculateDonchianChannels(prices) {
870
+ const donchian = [];
871
+ for (let i = 20; i < prices.length; i++) {
872
+ const slice = prices.slice(i - 20, i);
873
+ donchian.push({
874
+ upper: Math.max(...slice),
875
+ middle: (Math.max(...slice) + Math.min(...slice)) / 2,
876
+ lower: Math.min(...slice)
877
+ });
878
+ }
879
+ return donchian;
880
+ }
881
+ // Calculate Chaikin Volatility
882
+ calculateChaikinVolatility(prices, highs, lows) {
883
+ const volatility = [];
884
+ const period = 10;
885
+ if (prices.length < period * 2) return [];
886
+ const highLowRange = [];
887
+ for (let i = 0; i < prices.length; i++) {
888
+ const high = highs[i] || prices[i];
889
+ const low = lows[i] || prices[i];
890
+ highLowRange.push(high - low);
891
+ }
892
+ const emaRange = this.calculateEMA(highLowRange, period);
893
+ for (let i = period; i < emaRange.length; i++) {
894
+ const currentEMA = emaRange[i];
895
+ const pastEMA = emaRange[i - period];
896
+ const volatilityValue = pastEMA !== 0 ? (currentEMA - pastEMA) / pastEMA * 100 : 0;
897
+ volatility.push(volatilityValue);
898
+ }
899
+ return volatility;
900
+ }
901
+ // Calculate On Balance Volume
902
+ calculateObv(volumes) {
903
+ const obv = [volumes[0]];
904
+ for (let i = 1; i < volumes.length; i++) {
905
+ obv.push(obv[i - 1] + volumes[i]);
906
+ }
907
+ return obv;
908
+ }
909
+ // Calculate Chaikin Money Flow
910
+ calculateCmf(prices, highs, lows, volumes) {
911
+ const cmf = [];
912
+ const period = 20;
913
+ if (prices.length < period) return [];
914
+ for (let i = period - 1; i < prices.length; i++) {
915
+ let totalMoneyFlowVolume = 0;
916
+ let totalVolume = 0;
917
+ for (let j = i - period + 1; j <= i; j++) {
918
+ const high = highs[j] || prices[j];
919
+ const low = lows[j] || prices[j];
920
+ const close = prices[j];
921
+ const volume = volumes[j] || 1;
922
+ const moneyFlowMultiplier = (close - low - (high - close)) / (high - low);
923
+ const moneyFlowVolume = moneyFlowMultiplier * volume;
924
+ totalMoneyFlowVolume += moneyFlowVolume;
925
+ totalVolume += volume;
926
+ }
927
+ const cmfValue = totalVolume !== 0 ? totalMoneyFlowVolume / totalVolume : 0;
928
+ cmf.push(cmfValue);
929
+ }
930
+ return cmf;
931
+ }
932
+ // Calculate Accumulation/Distribution Line
933
+ calculateAdl(prices) {
934
+ const adl = [0];
935
+ for (let i = 1; i < prices.length; i++) {
936
+ const high = this.highs[i] || prices[i];
937
+ const low = this.lows[i] || prices[i];
938
+ const close = prices[i];
939
+ const volume = this.volumes[i] || 1;
940
+ const moneyFlowMultiplier = (close - low - (high - close)) / (high - low);
941
+ const moneyFlowVolume = moneyFlowMultiplier * volume;
942
+ adl.push(adl[i - 1] + moneyFlowVolume);
943
+ }
944
+ return adl;
945
+ }
946
+ // Calculate Volume Rate of Change
947
+ calculateVolumeROC() {
948
+ const volumeROC = [];
949
+ for (let i = 10; i < this.volumes.length; i++) {
950
+ volumeROC.push((this.volumes[i] - this.volumes[i - 10]) / this.volumes[i - 10] * 100);
951
+ }
952
+ return volumeROC;
953
+ }
954
+ // Calculate Money Flow Index
955
+ calculateMfi(prices, highs, lows, volumes) {
956
+ const mfi = [];
957
+ const period = 14;
958
+ if (prices.length < period + 1) return [];
959
+ for (let i = period; i < prices.length; i++) {
960
+ let positiveMoneyFlow = 0;
961
+ let negativeMoneyFlow = 0;
962
+ for (let j = i - period + 1; j <= i; j++) {
963
+ const high = highs[j] || prices[j];
964
+ const low = lows[j] || prices[j];
965
+ const close = prices[j];
966
+ const volume = volumes[j] || 1;
967
+ const typicalPrice = (high + low + close) / 3;
968
+ const moneyFlow = typicalPrice * volume;
969
+ if (j > i - period + 1) {
970
+ const prevHigh = highs[j - 1] || prices[j - 1];
971
+ const prevLow = lows[j - 1] || prices[j - 1];
972
+ const prevClose = prices[j - 1];
973
+ const prevTypicalPrice = (prevHigh + prevLow + prevClose) / 3;
974
+ if (typicalPrice > prevTypicalPrice) {
975
+ positiveMoneyFlow += moneyFlow;
976
+ } else if (typicalPrice < prevTypicalPrice) {
977
+ negativeMoneyFlow += moneyFlow;
978
+ }
979
+ }
980
+ }
981
+ const moneyRatio = negativeMoneyFlow !== 0 ? positiveMoneyFlow / negativeMoneyFlow : 0;
982
+ const mfiValue = 100 - 100 / (1 + moneyRatio);
983
+ mfi.push(mfiValue);
984
+ }
985
+ return mfi;
986
+ }
987
+ // Calculate VWAP
988
+ calculateVwap(prices, volumes) {
989
+ const vwap = [];
990
+ let cumulativePV = 0;
991
+ let cumulativeVolume = 0;
992
+ for (let i = 0; i < prices.length; i++) {
993
+ cumulativePV += prices[i] * (volumes[i] || 1);
994
+ cumulativeVolume += volumes[i] || 1;
995
+ vwap.push(cumulativePV / cumulativeVolume);
996
+ }
997
+ return vwap;
998
+ }
999
+ // Calculate Pivot Points
1000
+ calculatePivotPoints(prices) {
1001
+ const pivotPoints = [];
1002
+ for (let i = 0; i < prices.length; i++) {
1003
+ const high = this.highs[i] || prices[i];
1004
+ const low = this.lows[i] || prices[i];
1005
+ const close = prices[i];
1006
+ const pp = (high + low + close) / 3;
1007
+ const r1 = 2 * pp - low;
1008
+ const s1 = 2 * pp - high;
1009
+ const r2 = pp + (high - low);
1010
+ const s2 = pp - (high - low);
1011
+ const r3 = high + 2 * (pp - low);
1012
+ const s3 = low - 2 * (high - pp);
1013
+ pivotPoints.push({
1014
+ pp,
1015
+ r1,
1016
+ r2,
1017
+ r3,
1018
+ s1,
1019
+ s2,
1020
+ s3
1021
+ });
1022
+ }
1023
+ return pivotPoints;
1024
+ }
1025
+ // Calculate Fibonacci Levels
1026
+ calculateFibonacciLevels(prices) {
1027
+ const fibonacci = [];
1028
+ for (let i = 0; i < prices.length; i++) {
1029
+ const price = prices[i];
1030
+ fibonacci.push({
1031
+ retracement: {
1032
+ level0: price,
1033
+ level236: price * 0.764,
1034
+ level382: price * 0.618,
1035
+ level500: price * 0.5,
1036
+ level618: price * 0.382,
1037
+ level786: price * 0.214,
1038
+ level100: price * 0
1039
+ },
1040
+ extension: {
1041
+ level1272: price * 1.272,
1042
+ level1618: price * 1.618,
1043
+ level2618: price * 2.618,
1044
+ level4236: price * 4.236
1045
+ }
1046
+ });
1047
+ }
1048
+ return fibonacci;
1049
+ }
1050
+ // Calculate Gann Levels
1051
+ calculateGannLevels(prices) {
1052
+ const gannLevels = [];
1053
+ for (let i = 0; i < prices.length; i++) {
1054
+ gannLevels.push(prices[i] * (1 + i * 0.01));
1055
+ }
1056
+ return gannLevels;
1057
+ }
1058
+ // Calculate Elliott Wave
1059
+ calculateElliottWave(prices) {
1060
+ const elliottWave = [];
1061
+ if (prices.length < 10) return [];
1062
+ for (let i = 0; i < prices.length; i++) {
1063
+ const waves = [];
1064
+ let currentWave = 1;
1065
+ let wavePosition = 0.5;
1066
+ if (i >= 4) {
1067
+ const recentPrices = prices.slice(i - 4, i + 1);
1068
+ const swings = this.detectPriceSwings(recentPrices);
1069
+ if (swings.length >= 3) {
1070
+ waves.push(...swings.slice(0, 3));
1071
+ currentWave = Math.min(swings.length, 5);
1072
+ wavePosition = this.calculateWavePosition(recentPrices);
1073
+ }
1074
+ }
1075
+ elliottWave.push({
1076
+ waves: waves.length > 0 ? waves : [prices[i]],
1077
+ currentWave,
1078
+ wavePosition
1079
+ });
1080
+ }
1081
+ return elliottWave;
1082
+ }
1083
+ // Helper method to detect price swings
1084
+ detectPriceSwings(prices) {
1085
+ const swings = [];
1086
+ for (let i = 1; i < prices.length - 1; i++) {
1087
+ const prev = prices[i - 1];
1088
+ const curr = prices[i];
1089
+ const next = prices[i + 1];
1090
+ if (curr > prev && curr > next) {
1091
+ swings.push(curr);
1092
+ } else if (curr < prev && curr < next) {
1093
+ swings.push(curr);
1094
+ }
1095
+ }
1096
+ return swings;
1097
+ }
1098
+ // Helper method to calculate wave position
1099
+ calculateWavePosition(prices) {
1100
+ if (prices.length < 2) return 0.5;
1101
+ const current = prices[prices.length - 1];
1102
+ const min = Math.min(...prices);
1103
+ const max = Math.max(...prices);
1104
+ return max !== min ? (current - min) / (max - min) : 0.5;
1105
+ }
1106
+ // Calculate Harmonic Patterns
1107
+ calculateHarmonicPatterns(prices) {
1108
+ const harmonicPatterns = [];
1109
+ if (prices.length < 5) return [];
1110
+ for (let i = 4; i < prices.length; i++) {
1111
+ const recentPrices = prices.slice(i - 4, i + 1);
1112
+ const pattern = this.detectHarmonicPattern(recentPrices);
1113
+ harmonicPatterns.push(pattern);
1114
+ }
1115
+ return harmonicPatterns;
1116
+ }
1117
+ // Helper method to detect harmonic patterns
1118
+ detectHarmonicPattern(prices) {
1119
+ if (prices.length < 5) {
1120
+ return {
1121
+ type: "Unknown",
1122
+ completion: 0,
1123
+ target: prices[prices.length - 1] * 1.1,
1124
+ stopLoss: prices[prices.length - 1] * 0.9
1125
+ };
1126
+ }
1127
+ const swings = this.detectPriceSwings(prices);
1128
+ if (swings.length < 4) {
1129
+ return {
1130
+ type: "Unknown",
1131
+ completion: 0,
1132
+ target: prices[prices.length - 1] * 1.1,
1133
+ stopLoss: prices[prices.length - 1] * 0.9
1134
+ };
1135
+ }
1136
+ const [A, B, C, D] = swings.slice(-4);
1137
+ const X = prices[0];
1138
+ const abRatio = Math.abs((B - A) / (X - A));
1139
+ const bcRatio = Math.abs((C - B) / (A - B));
1140
+ const cdRatio = Math.abs((D - C) / (B - C));
1141
+ const adRatio = Math.abs((D - A) / (X - A));
1142
+ const isGartley = Math.abs(abRatio - 0.618) < 0.1 && bcRatio >= 0.382 && bcRatio <= 0.886 && cdRatio >= 1.13 && cdRatio <= 1.618 && Math.abs(adRatio - 0.786) < 0.1;
1143
+ if (isGartley) {
1144
+ const completion = this.calculatePatternCompletion(prices);
1145
+ const target = D + (D - C) * 0.618;
1146
+ const stopLoss = D - (D - C) * 0.382;
1147
+ return {
1148
+ type: "Gartley",
1149
+ completion,
1150
+ target,
1151
+ stopLoss
1152
+ };
1153
+ }
1154
+ const isButterfly = Math.abs(abRatio - 0.786) < 0.1 && bcRatio >= 0.382 && bcRatio <= 0.886 && cdRatio >= 1.618 && cdRatio <= 2.618 && Math.abs(adRatio - 1.27) < 0.1;
1155
+ if (isButterfly) {
1156
+ const completion = this.calculatePatternCompletion(prices);
1157
+ const target = D + (D - C) * 1.27;
1158
+ const stopLoss = D - (D - C) * 0.5;
1159
+ return {
1160
+ type: "Butterfly",
1161
+ completion,
1162
+ target,
1163
+ stopLoss
1164
+ };
1165
+ }
1166
+ return {
1167
+ type: "Unknown",
1168
+ completion: 0,
1169
+ target: prices[prices.length - 1] * 1.1,
1170
+ stopLoss: prices[prices.length - 1] * 0.9
1171
+ };
1172
+ }
1173
+ // Helper method to calculate pattern completion
1174
+ calculatePatternCompletion(prices) {
1175
+ if (prices.length < 2) return 0;
1176
+ const current = prices[prices.length - 1];
1177
+ const min = Math.min(...prices);
1178
+ const max = Math.max(...prices);
1179
+ return max !== min ? (current - min) / (max - min) : 0;
1180
+ }
1181
+ // Calculate Position Size
1182
+ calculatePositionSize(currentPrice, targetEntry, stopLoss) {
1183
+ void currentPrice;
1184
+ const riskPerShare = Math.abs(targetEntry - stopLoss);
1185
+ return riskPerShare > 0 ? 100 / riskPerShare : 1;
1186
+ }
1187
+ // Calculate Confidence
1188
+ calculateConfidence(signals) {
1189
+ return Math.min(signals.length * 10, 100);
1190
+ }
1191
+ // Calculate Risk Level
1192
+ calculateRiskLevel(volatility) {
1193
+ if (volatility < 20) return "LOW";
1194
+ if (volatility < 40) return "MEDIUM";
1195
+ return "HIGH";
1196
+ }
1197
+ // Calculate Z-Score
1198
+ calculateZScore(currentPrice, startPrice) {
1199
+ return (currentPrice - startPrice) / (startPrice * 0.1);
1200
+ }
1201
+ // Calculate Ornstein-Uhlenbeck
1202
+ calculateOrnsteinUhlenbeck(currentPrice, startPrice, avgVolume) {
1203
+ const priceChanges = this.calculatePriceChanges();
1204
+ const mean = startPrice;
1205
+ let speed = 0.1;
1206
+ if (priceChanges.length > 1) {
1207
+ const variance = priceChanges.reduce((sum2, change) => sum2 + change * change, 0) / priceChanges.length;
1208
+ speed = Math.max(0.01, Math.min(1, variance * 10));
1209
+ }
1210
+ const volatility = avgVolume * 0.01;
1211
+ return {
1212
+ mean,
1213
+ speed,
1214
+ volatility,
1215
+ currentValue: currentPrice
1216
+ };
1217
+ }
1218
+ // Calculate Kalman Filter
1219
+ calculateKalmanFilter(currentPrice, startPrice, avgVolume) {
1220
+ const measurementNoise = avgVolume * 1e-3;
1221
+ const processNoise = avgVolume * 1e-4;
1222
+ let state = startPrice;
1223
+ let covariance = measurementNoise;
1224
+ const priceChanges = this.calculatePriceChanges();
1225
+ if (priceChanges.length > 0) {
1226
+ const predictedState = state;
1227
+ const predictedCovariance = covariance + processNoise;
1228
+ const kalmanGain = predictedCovariance / (predictedCovariance + measurementNoise);
1229
+ state = predictedState + kalmanGain * (currentPrice - predictedState);
1230
+ covariance = (1 - kalmanGain) * predictedCovariance;
1231
+ return {
1232
+ state,
1233
+ covariance,
1234
+ gain: kalmanGain
1235
+ };
1236
+ }
1237
+ return {
1238
+ state: currentPrice,
1239
+ covariance,
1240
+ gain: 0.5
1241
+ };
1242
+ }
1243
+ // Calculate ARIMA
1244
+ calculateArima(currentPrice) {
1245
+ const priceChanges = this.calculatePriceChanges();
1246
+ if (priceChanges.length < 3) {
1247
+ return {
1248
+ forecast: [currentPrice * 1.01, currentPrice * 1.02],
1249
+ residuals: [0, 0],
1250
+ aic: 100
1251
+ };
1252
+ }
1253
+ const n = priceChanges.length;
1254
+ let sumY = 0;
1255
+ let sumY1 = 0;
1256
+ let sumYY1 = 0;
1257
+ let sumY1Sq = 0;
1258
+ for (let i = 1; i < n; i++) {
1259
+ const y = priceChanges[i];
1260
+ const y1 = priceChanges[i - 1];
1261
+ sumY += y;
1262
+ sumY1 += y1;
1263
+ sumYY1 += y * y1;
1264
+ sumY1Sq += y1 * y1;
1265
+ }
1266
+ const phi = (n * sumYY1 - sumY * sumY1) / (n * sumY1Sq - sumY1 * sumY1);
1267
+ const c = (sumY - phi * sumY1) / n;
1268
+ const residuals = [];
1269
+ for (let i = 1; i < n; i++) {
1270
+ const predicted = c + phi * priceChanges[i - 1];
1271
+ residuals.push(priceChanges[i] - predicted);
1272
+ }
1273
+ const rss = residuals.reduce((sum2, r) => sum2 + r * r, 0);
1274
+ const aic = n * Math.log(rss / n) + 2 * 2;
1275
+ const lastChange = priceChanges[priceChanges.length - 1];
1276
+ const forecast1 = currentPrice + (c + phi * lastChange);
1277
+ const forecast2 = forecast1 + (c + phi * (c + phi * lastChange));
1278
+ return {
1279
+ forecast: [forecast1, forecast2],
1280
+ residuals,
1281
+ aic
1282
+ };
1283
+ }
1284
+ // Calculate GARCH
1285
+ calculateGarch(avgVolume) {
1286
+ const priceChanges = this.calculatePriceChanges();
1287
+ if (priceChanges.length < 5) {
1288
+ return {
1289
+ volatility: avgVolume * 0.01,
1290
+ persistence: 0.9,
1291
+ meanReversion: 0.1
1292
+ };
1293
+ }
1294
+ const squaredReturns = priceChanges.map((change) => change * change);
1295
+ const meanSquaredReturn = squaredReturns.reduce((sum2, sq) => sum2 + sq, 0) / squaredReturns.length;
1296
+ let persistence = 0.9;
1297
+ if (squaredReturns.length > 1) {
1298
+ const variance = squaredReturns.reduce((sum2, sq) => sum2 + sq, 0) / squaredReturns.length;
1299
+ persistence = Math.min(0.99, Math.max(0.5, variance / meanSquaredReturn));
1300
+ }
1301
+ const meanReversion = meanSquaredReturn * (1 - persistence);
1302
+ const volatility = Math.sqrt(meanSquaredReturn);
1303
+ return {
1304
+ volatility,
1305
+ persistence,
1306
+ meanReversion
1307
+ };
1308
+ }
1309
+ // Calculate Hilbert Transform
1310
+ calculateHilbertTransform(currentPrice) {
1311
+ const priceChanges = this.calculatePriceChanges();
1312
+ if (priceChanges.length < 3) {
1313
+ return {
1314
+ analytic: [currentPrice],
1315
+ phase: [0],
1316
+ amplitude: [currentPrice]
1317
+ };
1318
+ }
1319
+ const n = priceChanges.length;
1320
+ const analytic = [];
1321
+ const phase = [];
1322
+ const amplitude = [];
1323
+ for (let i = 0; i < n; i++) {
1324
+ let hilbertValue = 0;
1325
+ for (let j = 0; j < n; j++) {
1326
+ if (i !== j) {
1327
+ hilbertValue += priceChanges[j] / (Math.PI * (i - j));
1328
+ }
1329
+ }
1330
+ const realPart = priceChanges[i];
1331
+ const imagPart = hilbertValue;
1332
+ const analyticValue = Math.sqrt(realPart * realPart + imagPart * imagPart);
1333
+ analytic.push(analyticValue);
1334
+ const phaseValue = Math.atan2(imagPart, realPart);
1335
+ phase.push(phaseValue);
1336
+ amplitude.push(analyticValue);
1337
+ }
1338
+ return {
1339
+ analytic,
1340
+ phase,
1341
+ amplitude
1342
+ };
1343
+ }
1344
+ // Calculate Wavelet Transform
1345
+ calculateWaveletTransform(currentPrice) {
1346
+ const priceChanges = this.calculatePriceChanges();
1347
+ if (priceChanges.length < 4) {
1348
+ return {
1349
+ coefficients: [currentPrice],
1350
+ scales: [1]
1351
+ };
1352
+ }
1353
+ const coefficients = [];
1354
+ const scales = [];
1355
+ const n = priceChanges.length;
1356
+ const maxLevel = Math.floor(Math.log2(n));
1357
+ for (let level = 1; level <= maxLevel; level++) {
1358
+ const step = 2 ** (level - 1);
1359
+ const scale = step;
1360
+ for (let i = 0; i < n - step; i += step * 2) {
1361
+ if (i + step < n) {
1362
+ const coefficient = (priceChanges[i] - priceChanges[i + step]) / Math.sqrt(2);
1363
+ coefficients.push(coefficient);
1364
+ scales.push(scale);
1365
+ }
1366
+ }
1367
+ }
1368
+ if (coefficients.length === 0) {
1369
+ coefficients.push(currentPrice);
1370
+ scales.push(1);
1371
+ }
1372
+ return {
1373
+ coefficients,
1374
+ scales
1375
+ };
1376
+ }
1377
+ // Calculate Black-Scholes
1378
+ calculateBlackScholes(currentPrice, startPrice, avgVolume) {
1379
+ const S = currentPrice;
1380
+ const K = startPrice;
1381
+ const T = 1;
1382
+ const r = 0.05;
1383
+ const sigma = avgVolume * 0.01;
1384
+ const d1 = (Math.log(S / K) + (r + sigma * sigma / 2) * T) / (sigma * Math.sqrt(T));
1385
+ const d2 = d1 - sigma * Math.sqrt(T);
1386
+ const callPrice = S * this.normalCDF(d1) - K * Math.exp(-r * T) * this.normalCDF(d2);
1387
+ const putPrice = K * Math.exp(-r * T) * this.normalCDF(-d2) - S * this.normalCDF(-d1);
1388
+ return {
1389
+ callPrice,
1390
+ putPrice,
1391
+ delta: this.normalCDF(d1),
1392
+ gamma: this.normalPDF(d1) / (S * sigma * Math.sqrt(T)),
1393
+ theta: -S * this.normalPDF(d1) * sigma / (2 * Math.sqrt(T)) - r * K * Math.exp(-r * T) * this.normalCDF(d2),
1394
+ vega: S * Math.sqrt(T) * this.normalPDF(d1),
1395
+ rho: K * T * Math.exp(-r * T) * this.normalCDF(d2)
1396
+ };
1397
+ }
1398
+ // Normal CDF approximation
1399
+ normalCDF(x) {
1400
+ return 0.5 * (1 + this.erf(x / Math.sqrt(2)));
1401
+ }
1402
+ // Normal PDF
1403
+ normalPDF(x) {
1404
+ return Math.exp(-x * x / 2) / Math.sqrt(2 * Math.PI);
1405
+ }
1406
+ // Error function approximation
1407
+ erf(x) {
1408
+ const a1 = 0.254829592;
1409
+ const a2 = -0.284496736;
1410
+ const a3 = 1.421413741;
1411
+ const a4 = -1.453152027;
1412
+ const a5 = 1.061405429;
1413
+ const p = 0.3275911;
1414
+ const sign = x >= 0 ? 1 : -1;
1415
+ const absX = Math.abs(x);
1416
+ const t = 1 / (1 + p * absX);
1417
+ const y = 1 - ((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t * Math.exp(-absX * absX);
1418
+ return sign * y;
1419
+ }
1420
+ // Calculate price changes for volatility
1421
+ calculatePriceChanges() {
1422
+ const changes = [];
1423
+ for (let i = 1; i < this.prices.length; i++) {
1424
+ changes.push((this.prices[i] - this.prices[i - 1]) / this.prices[i - 1]);
1425
+ }
1426
+ return changes;
1427
+ }
1428
+ // Generate comprehensive market analysis
1429
+ analyze() {
1430
+ const currentPrice = this.prices[this.prices.length - 1];
1431
+ const startPrice = this.prices[0];
1432
+ const sessionHigh = Math.max(...this.highs);
1433
+ const sessionLow = Math.min(...this.lows);
1434
+ const totalVolume = sum(this.volumes);
1435
+ const avgVolume = totalVolume / this.volumes.length;
1436
+ const priceChanges = this.calculatePriceChanges();
1437
+ const volatility = priceChanges.length > 0 ? Math.sqrt(
1438
+ priceChanges.reduce((sum2, change) => sum2 + change ** 2, 0) / priceChanges.length
1439
+ ) * Math.sqrt(252) * 100 : 0;
1440
+ const sessionReturn = (currentPrice - startPrice) / startPrice * 100;
1441
+ const pricePosition = (currentPrice - sessionLow) / (sessionHigh - sessionLow) * 100;
1442
+ const trueVWAP = this.prices.reduce((sum2, price, i) => sum2 + price * this.volumes[i], 0) / totalVolume;
1443
+ const momentum5 = this.prices.length > 5 ? (currentPrice - this.prices[Math.max(0, this.prices.length - 6)]) / this.prices[Math.max(0, this.prices.length - 6)] * 100 : 0;
1444
+ const momentum10 = this.prices.length > 10 ? (currentPrice - this.prices[Math.max(0, this.prices.length - 11)]) / this.prices[Math.max(0, this.prices.length - 11)] * 100 : 0;
1445
+ const maxDrawdown = this.calculateMaxDrawdown(this.prices);
1446
+ const atrValues = this.calculateAtr(this.prices, this.highs, this.lows);
1447
+ const atr = atrValues.length > 0 ? atrValues[atrValues.length - 1] : 0;
1448
+ const impliedVolatility = volatility;
1449
+ const realizedVolatility = volatility;
1450
+ const sharpeRatio = sessionReturn / volatility;
1451
+ const sortinoRatio = sessionReturn / realizedVolatility;
1452
+ const calmarRatio = sessionReturn / maxDrawdown;
1453
+ const maxConsecutiveLosses = this.calculateMaxConsecutiveLosses(this.prices);
1454
+ const winRate = this.calculateWinRate(this.prices);
1455
+ const profitFactor = this.calculateProfitFactor(this.prices);
1456
+ return {
1457
+ currentPrice,
1458
+ startPrice,
1459
+ sessionHigh,
1460
+ sessionLow,
1461
+ totalVolume,
1462
+ avgVolume,
1463
+ volatility,
1464
+ sessionReturn,
1465
+ pricePosition,
1466
+ trueVWAP,
1467
+ momentum5,
1468
+ momentum10,
1469
+ maxDrawdown,
1470
+ atr,
1471
+ impliedVolatility,
1472
+ realizedVolatility,
1473
+ sharpeRatio,
1474
+ sortinoRatio,
1475
+ calmarRatio,
1476
+ maxConsecutiveLosses,
1477
+ winRate,
1478
+ profitFactor
1479
+ };
1480
+ }
1481
+ // Generate technical indicators
1482
+ getTechnicalIndicators() {
1483
+ return {
1484
+ sma5: this.calculateSMA(this.prices, 5),
1485
+ sma10: this.calculateSMA(this.prices, 10),
1486
+ sma20: this.calculateSMA(this.prices, 20),
1487
+ sma50: this.calculateSMA(this.prices, 50),
1488
+ sma200: this.calculateSMA(this.prices, 200),
1489
+ ema8: this.calculateEMA(this.prices, 8),
1490
+ ema12: this.calculateEMA(this.prices, 12),
1491
+ ema21: this.calculateEMA(this.prices, 21),
1492
+ ema26: this.calculateEMA(this.prices, 26),
1493
+ wma20: this.calculateWma(this.prices, 20),
1494
+ vwma20: this.calculateVwma(this.prices, 20),
1495
+ macd: this.calculateMacd(this.prices),
1496
+ adx: this.calculateAdx(this.prices, this.highs, this.lows),
1497
+ dmi: this.calculateDmi(this.prices, this.highs, this.lows),
1498
+ ichimoku: this.calculateIchimoku(this.prices, this.highs, this.lows),
1499
+ parabolicSAR: this.calculateParabolicSAR(this.prices, this.highs, this.lows),
1500
+ rsi: this.calculateRSI(this.prices, 14),
1501
+ stochastic: this.calculateStochastic(this.prices, this.highs, this.lows),
1502
+ cci: this.calculateCci(this.prices, this.highs, this.lows),
1503
+ roc: this.calculateRoc(this.prices),
1504
+ williamsR: this.calculateWilliamsR(this.prices),
1505
+ momentum: this.calculateMomentum(this.prices),
1506
+ bollinger: this.calculateBollingerBands(this.prices, 20, 2),
1507
+ atr: this.calculateAtr(this.prices, this.highs, this.lows),
1508
+ keltner: this.calculateKeltnerChannels(this.prices, this.highs, this.lows),
1509
+ donchian: this.calculateDonchianChannels(this.prices),
1510
+ chaikinVolatility: this.calculateChaikinVolatility(this.prices, this.highs, this.lows),
1511
+ obv: this.calculateObv(this.volumes),
1512
+ cmf: this.calculateCmf(this.prices, this.highs, this.lows, this.volumes),
1513
+ adl: this.calculateAdl(this.prices),
1514
+ volumeROC: this.calculateVolumeROC(),
1515
+ mfi: this.calculateMfi(this.prices, this.highs, this.lows, this.volumes),
1516
+ vwap: this.calculateVwap(this.prices, this.volumes),
1517
+ pivotPoints: this.calculatePivotPoints(this.prices),
1518
+ fibonacci: this.calculateFibonacciLevels(this.prices),
1519
+ gannLevels: this.calculateGannLevels(this.prices),
1520
+ elliottWave: this.calculateElliottWave(this.prices),
1521
+ harmonicPatterns: this.calculateHarmonicPatterns(this.prices)
1522
+ };
1523
+ }
1524
+ // Generate trading signals
1525
+ generateSignals() {
1526
+ const analysis = this.analyze();
1527
+ let bullishSignals = 0;
1528
+ let bearishSignals = 0;
1529
+ const signals = [];
1530
+ if (analysis.currentPrice > analysis.trueVWAP) {
1531
+ signals.push(
1532
+ `\u2713 BULLISH: Price above VWAP (+${((analysis.currentPrice - analysis.trueVWAP) / analysis.trueVWAP * 100).toFixed(2)}%)`
1533
+ );
1534
+ bullishSignals++;
1535
+ } else {
1536
+ signals.push(
1537
+ `\u2717 BEARISH: Price below VWAP (${((analysis.currentPrice - analysis.trueVWAP) / analysis.trueVWAP * 100).toFixed(2)}%)`
1538
+ );
1539
+ bearishSignals++;
1540
+ }
1541
+ if (analysis.momentum5 > 0 && analysis.momentum10 > 0) {
1542
+ signals.push("\u2713 BULLISH: Positive momentum on both timeframes");
1543
+ bullishSignals++;
1544
+ } else if (analysis.momentum5 < 0 && analysis.momentum10 < 0) {
1545
+ signals.push("\u2717 BEARISH: Negative momentum on both timeframes");
1546
+ bearishSignals++;
1547
+ } else {
1548
+ signals.push("\u25D0 MIXED: Conflicting momentum signals");
1549
+ }
1550
+ const currentVolume = this.volumes[this.volumes.length - 1];
1551
+ const volumeRatio = currentVolume / analysis.avgVolume;
1552
+ if (volumeRatio > 1.2 && analysis.sessionReturn > 0) {
1553
+ signals.push("\u2713 BULLISH: Above-average volume supporting upward move");
1554
+ bullishSignals++;
1555
+ } else if (volumeRatio > 1.2 && analysis.sessionReturn < 0) {
1556
+ signals.push("\u2717 BEARISH: Above-average volume supporting downward move");
1557
+ bearishSignals++;
1558
+ } else {
1559
+ signals.push("\u25D0 NEUTRAL: Volume not providing clear direction");
1560
+ }
1561
+ if (analysis.pricePosition > 65 && analysis.volatility > 30) {
1562
+ signals.push("\u2717 BEARISH: High in range with elevated volatility - reversal risk");
1563
+ bearishSignals++;
1564
+ } else if (analysis.pricePosition < 35 && analysis.volatility > 30) {
1565
+ signals.push("\u2713 BULLISH: Low in range with volatility - potential bounce");
1566
+ bullishSignals++;
1567
+ } else {
1568
+ signals.push("\u25D0 NEUTRAL: Price position and volatility not extreme");
1569
+ }
1570
+ return { bullishSignals, bearishSignals, signals };
1571
+ }
1572
+ // Generate comprehensive JSON analysis
1573
+ generateJSONAnalysis(symbol) {
1574
+ const analysis = this.analyze();
1575
+ const indicators = this.getTechnicalIndicators();
1576
+ const signals = this.generateSignals();
1577
+ const currentSMA5 = indicators.sma5.length > 0 ? indicators.sma5[indicators.sma5.length - 1] : null;
1578
+ const currentSMA10 = indicators.sma10.length > 0 ? indicators.sma10[indicators.sma10.length - 1] : null;
1579
+ const currentSMA20 = indicators.sma20.length > 0 ? indicators.sma20[indicators.sma20.length - 1] : null;
1580
+ const currentSMA50 = indicators.sma50.length > 0 ? indicators.sma50[indicators.sma50.length - 1] : null;
1581
+ const currentSMA200 = indicators.sma200.length > 0 ? indicators.sma200[indicators.sma200.length - 1] : null;
1582
+ const currentEMA8 = indicators.ema8[indicators.ema8.length - 1];
1583
+ const currentEMA12 = indicators.ema12[indicators.ema12.length - 1];
1584
+ const currentEMA21 = indicators.ema21[indicators.ema21.length - 1];
1585
+ const currentEMA26 = indicators.ema26[indicators.ema26.length - 1];
1586
+ const currentWMA20 = indicators.wma20.length > 0 ? indicators.wma20[indicators.wma20.length - 1] : null;
1587
+ const currentVWMA20 = indicators.vwma20.length > 0 ? indicators.vwma20[indicators.vwma20.length - 1] : null;
1588
+ const currentMACD = indicators.macd.length > 0 ? indicators.macd[indicators.macd.length - 1] : null;
1589
+ const currentADX = indicators.adx.length > 0 ? indicators.adx[indicators.adx.length - 1] : null;
1590
+ const currentDMI = indicators.dmi.length > 0 ? indicators.dmi[indicators.dmi.length - 1] : null;
1591
+ const currentIchimoku = indicators.ichimoku.length > 0 ? indicators.ichimoku[indicators.ichimoku.length - 1] : null;
1592
+ const currentParabolicSAR = indicators.parabolicSAR.length > 0 ? indicators.parabolicSAR[indicators.parabolicSAR.length - 1] : null;
1593
+ const currentRSI = indicators.rsi.length > 0 ? indicators.rsi[indicators.rsi.length - 1] : null;
1594
+ const currentStochastic = indicators.stochastic.length > 0 ? indicators.stochastic[indicators.stochastic.length - 1] : null;
1595
+ const currentCCI = indicators.cci.length > 0 ? indicators.cci[indicators.cci.length - 1] : null;
1596
+ const currentROC = indicators.roc.length > 0 ? indicators.roc[indicators.roc.length - 1] : null;
1597
+ const currentWilliamsR = indicators.williamsR.length > 0 ? indicators.williamsR[indicators.williamsR.length - 1] : null;
1598
+ const currentMomentum = indicators.momentum.length > 0 ? indicators.momentum[indicators.momentum.length - 1] : null;
1599
+ const currentBB = indicators.bollinger.length > 0 ? indicators.bollinger[indicators.bollinger.length - 1] : null;
1600
+ const currentAtr = indicators.atr.length > 0 ? indicators.atr[indicators.atr.length - 1] : null;
1601
+ const currentKeltner = indicators.keltner.length > 0 ? indicators.keltner[indicators.keltner.length - 1] : null;
1602
+ const currentDonchian = indicators.donchian.length > 0 ? indicators.donchian[indicators.donchian.length - 1] : null;
1603
+ const currentChaikinVolatility = indicators.chaikinVolatility.length > 0 ? indicators.chaikinVolatility[indicators.chaikinVolatility.length - 1] : null;
1604
+ const currentObv = indicators.obv.length > 0 ? indicators.obv[indicators.obv.length - 1] : null;
1605
+ const currentCmf = indicators.cmf.length > 0 ? indicators.cmf[indicators.cmf.length - 1] : null;
1606
+ const currentAdl = indicators.adl.length > 0 ? indicators.adl[indicators.adl.length - 1] : null;
1607
+ const currentVolumeROC = indicators.volumeROC.length > 0 ? indicators.volumeROC[indicators.volumeROC.length - 1] : null;
1608
+ const currentMfi = indicators.mfi.length > 0 ? indicators.mfi[indicators.mfi.length - 1] : null;
1609
+ const currentVwap = indicators.vwap.length > 0 ? indicators.vwap[indicators.vwap.length - 1] : null;
1610
+ const currentPivotPoints = indicators.pivotPoints.length > 0 ? indicators.pivotPoints[indicators.pivotPoints.length - 1] : null;
1611
+ const currentFibonacci = indicators.fibonacci.length > 0 ? indicators.fibonacci[indicators.fibonacci.length - 1] : null;
1612
+ const currentGannLevels = indicators.gannLevels.length > 0 ? indicators.gannLevels : [];
1613
+ const currentElliottWave = indicators.elliottWave.length > 0 ? indicators.elliottWave[indicators.elliottWave.length - 1] : null;
1614
+ const currentHarmonicPatterns = indicators.harmonicPatterns.length > 0 ? indicators.harmonicPatterns : [];
1615
+ const currentVolume = this.volumes[this.volumes.length - 1];
1616
+ const volumeRatio = currentVolume / analysis.avgVolume;
1617
+ const currentDrawdown = (analysis.sessionHigh - analysis.currentPrice) / analysis.sessionHigh * 100;
1618
+ const rangeWidth = (analysis.sessionHigh - analysis.sessionLow) / analysis.sessionLow * 100;
1619
+ const priceVsVWAP = (analysis.currentPrice - analysis.trueVWAP) / analysis.trueVWAP * 100;
1620
+ const totalScore = signals.bullishSignals - signals.bearishSignals;
1621
+ const overallSignal = totalScore > 0 ? "BULLISH_BIAS" : totalScore < 0 ? "BEARISH_BIAS" : "NEUTRAL";
1622
+ const targetEntry = Math.max(analysis.sessionLow * 1.005, analysis.trueVWAP * 0.998);
1623
+ const stopLoss = analysis.sessionLow * 0.995;
1624
+ const profitTarget = analysis.sessionHigh * 0.995;
1625
+ const riskRewardRatio = (profitTarget - analysis.currentPrice) / (analysis.currentPrice - stopLoss);
1626
+ const positionSize = this.calculatePositionSize(analysis.currentPrice, targetEntry, stopLoss);
1627
+ const maxRisk = positionSize * (targetEntry - stopLoss);
1628
+ return {
1629
+ symbol,
1630
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1631
+ marketStructure: {
1632
+ currentPrice: analysis.currentPrice,
1633
+ startPrice: analysis.startPrice,
1634
+ sessionHigh: analysis.sessionHigh,
1635
+ sessionLow: analysis.sessionLow,
1636
+ rangeWidth,
1637
+ totalVolume: analysis.totalVolume,
1638
+ sessionPerformance: analysis.sessionReturn,
1639
+ positionInRange: analysis.pricePosition
1640
+ },
1641
+ volatility: {
1642
+ impliedVolatility: analysis.impliedVolatility,
1643
+ realizedVolatility: analysis.realizedVolatility,
1644
+ atr: analysis.atr,
1645
+ maxDrawdown: analysis.maxDrawdown * 100,
1646
+ currentDrawdown
1647
+ },
1648
+ technicalIndicators: {
1649
+ sma5: currentSMA5,
1650
+ sma10: currentSMA10,
1651
+ sma20: currentSMA20,
1652
+ sma50: currentSMA50,
1653
+ sma200: currentSMA200,
1654
+ ema8: currentEMA8,
1655
+ ema12: currentEMA12,
1656
+ ema21: currentEMA21,
1657
+ ema26: currentEMA26,
1658
+ wma20: currentWMA20,
1659
+ vwma20: currentVWMA20,
1660
+ macd: currentMACD,
1661
+ adx: currentADX,
1662
+ dmi: currentDMI,
1663
+ ichimoku: currentIchimoku,
1664
+ parabolicSAR: currentParabolicSAR,
1665
+ rsi: currentRSI,
1666
+ stochastic: currentStochastic,
1667
+ cci: currentCCI,
1668
+ roc: currentROC,
1669
+ williamsR: currentWilliamsR,
1670
+ momentum: currentMomentum,
1671
+ bollingerBands: currentBB ? {
1672
+ upper: currentBB.upper,
1673
+ middle: currentBB.middle,
1674
+ lower: currentBB.lower,
1675
+ bandwidth: currentBB.bandwidth,
1676
+ percentB: currentBB.percentB
1677
+ } : null,
1678
+ atr: currentAtr,
1679
+ keltnerChannels: currentKeltner ? {
1680
+ upper: currentKeltner.upper,
1681
+ middle: currentKeltner.middle,
1682
+ lower: currentKeltner.lower
1683
+ } : null,
1684
+ donchianChannels: currentDonchian ? {
1685
+ upper: currentDonchian.upper,
1686
+ middle: currentDonchian.middle,
1687
+ lower: currentDonchian.lower
1688
+ } : null,
1689
+ chaikinVolatility: currentChaikinVolatility,
1690
+ obv: currentObv,
1691
+ cmf: currentCmf,
1692
+ adl: currentAdl,
1693
+ volumeROC: currentVolumeROC,
1694
+ mfi: currentMfi,
1695
+ vwap: currentVwap
1696
+ },
1697
+ volumeAnalysis: {
1698
+ currentVolume,
1699
+ averageVolume: Math.round(analysis.avgVolume),
1700
+ volumeRatio,
1701
+ trueVWAP: analysis.trueVWAP,
1702
+ priceVsVWAP,
1703
+ obv: currentObv,
1704
+ cmf: currentCmf,
1705
+ mfi: currentMfi
1706
+ },
1707
+ momentum: {
1708
+ momentum5: analysis.momentum5,
1709
+ momentum10: analysis.momentum10,
1710
+ sessionROC: analysis.sessionReturn,
1711
+ rsi: currentRSI,
1712
+ stochastic: currentStochastic,
1713
+ cci: currentCCI
1714
+ },
1715
+ supportResistance: {
1716
+ pivotPoints: currentPivotPoints,
1717
+ fibonacci: currentFibonacci,
1718
+ gannLevels: currentGannLevels,
1719
+ elliottWave: currentElliottWave,
1720
+ harmonicPatterns: currentHarmonicPatterns
1721
+ },
1722
+ tradingSignals: {
1723
+ ...signals,
1724
+ overallSignal,
1725
+ signalScore: totalScore,
1726
+ confidence: this.calculateConfidence(signals.signals),
1727
+ riskLevel: this.calculateRiskLevel(analysis.volatility)
1728
+ },
1729
+ statisticalModels: {
1730
+ zScore: this.calculateZScore(analysis.currentPrice, analysis.startPrice),
1731
+ ornsteinUhlenbeck: this.calculateOrnsteinUhlenbeck(
1732
+ analysis.currentPrice,
1733
+ analysis.startPrice,
1734
+ analysis.avgVolume
1735
+ ),
1736
+ kalmanFilter: this.calculateKalmanFilter(
1737
+ analysis.currentPrice,
1738
+ analysis.startPrice,
1739
+ analysis.avgVolume
1740
+ ),
1741
+ arima: this.calculateArima(analysis.currentPrice),
1742
+ garch: this.calculateGarch(analysis.avgVolume),
1743
+ hilbertTransform: this.calculateHilbertTransform(analysis.currentPrice),
1744
+ waveletTransform: this.calculateWaveletTransform(analysis.currentPrice)
1745
+ },
1746
+ optionsAnalysis: (() => {
1747
+ const blackScholes = this.calculateBlackScholes(
1748
+ analysis.currentPrice,
1749
+ analysis.startPrice,
1750
+ analysis.avgVolume
1751
+ );
1752
+ if (!blackScholes) return null;
1753
+ return {
1754
+ blackScholes,
1755
+ impliedVolatility: analysis.impliedVolatility,
1756
+ delta: blackScholes.delta,
1757
+ gamma: blackScholes.gamma,
1758
+ theta: blackScholes.theta,
1759
+ vega: blackScholes.vega,
1760
+ rho: blackScholes.rho,
1761
+ greeks: {
1762
+ delta: blackScholes.delta,
1763
+ gamma: blackScholes.gamma,
1764
+ theta: blackScholes.theta,
1765
+ vega: blackScholes.vega,
1766
+ rho: blackScholes.rho
1767
+ }
1768
+ };
1769
+ })(),
1770
+ riskManagement: {
1771
+ targetEntry,
1772
+ stopLoss,
1773
+ profitTarget,
1774
+ riskRewardRatio,
1775
+ positionSize,
1776
+ maxRisk
1777
+ },
1778
+ performance: {
1779
+ sharpeRatio: analysis.sharpeRatio,
1780
+ sortinoRatio: analysis.sortinoRatio,
1781
+ calmarRatio: analysis.calmarRatio,
1782
+ maxDrawdown: analysis.maxDrawdown * 100,
1783
+ winRate: analysis.winRate,
1784
+ profitFactor: analysis.profitFactor,
1785
+ totalReturn: analysis.sessionReturn,
1786
+ volatility: analysis.volatility
1787
+ }
1788
+ };
279
1789
  }
280
1790
  };
1791
+ var createTechnicalAnalysisHandler = (marketDataPrices) => {
1792
+ return async (args) => {
1793
+ try {
1794
+ const symbol = args.symbol;
1795
+ const priceHistory = marketDataPrices.get(symbol) || [];
1796
+ if (priceHistory.length === 0) {
1797
+ return {
1798
+ content: [
1799
+ {
1800
+ type: "text",
1801
+ text: `No price data available for ${symbol}. Please request market data first.`,
1802
+ uri: "technicalAnalysis"
1803
+ }
1804
+ ]
1805
+ };
1806
+ }
1807
+ const hasValidData = priceHistory.every(
1808
+ (entry) => typeof entry.trade === "number" && !Number.isNaN(entry.trade) && typeof entry.midPrice === "number" && !Number.isNaN(entry.midPrice)
1809
+ );
1810
+ if (!hasValidData) {
1811
+ throw new Error("Invalid market data");
1812
+ }
1813
+ const analyzer = new TechnicalAnalyzer(priceHistory);
1814
+ const analysis = analyzer.generateJSONAnalysis(symbol);
1815
+ return {
1816
+ content: [
1817
+ {
1818
+ type: "text",
1819
+ text: `Technical Analysis for ${symbol}:
1820
+
1821
+ ${JSON.stringify(analysis, null, 2)}`,
1822
+ uri: "technicalAnalysis"
1823
+ }
1824
+ ]
1825
+ };
1826
+ } catch (error) {
1827
+ return {
1828
+ content: [
1829
+ {
1830
+ type: "text",
1831
+ text: `Error performing technical analysis: ${error instanceof Error ? error.message : "Unknown error"}`,
1832
+ uri: "technicalAnalysis"
1833
+ }
1834
+ ],
1835
+ isError: true
1836
+ };
1837
+ }
1838
+ };
1839
+ };
281
1840
 
282
1841
  // src/tools/marketData.ts
283
1842
  import { Field, Fields, MDEntryType, Messages } from "fixparser";
@@ -285,10 +1844,63 @@ import QuickChart from "quickchart-js";
285
1844
  var createMarketDataRequestHandler = (parser, pendingRequests) => {
286
1845
  return async (args) => {
287
1846
  try {
1847
+ parser.logger.log({
1848
+ level: "info",
1849
+ message: `Sending market data request for symbols: ${args.symbols.join(", ")}`
1850
+ });
288
1851
  const response = new Promise((resolve) => {
289
1852
  pendingRequests.set(args.mdReqID, resolve);
1853
+ parser.logger.log({
1854
+ level: "info",
1855
+ message: `Registered callback for market data request ID: ${args.mdReqID}`
1856
+ });
290
1857
  });
291
- const entryTypes = args.mdEntryTypes || [MDEntryType.Bid, MDEntryType.Offer, MDEntryType.TradeVolume];
1858
+ const entryTypes = args.mdEntryTypes || [
1859
+ MDEntryType.Bid,
1860
+ MDEntryType.Offer,
1861
+ MDEntryType.Trade,
1862
+ MDEntryType.IndexValue,
1863
+ MDEntryType.OpeningPrice,
1864
+ MDEntryType.ClosingPrice,
1865
+ MDEntryType.SettlementPrice,
1866
+ MDEntryType.TradingSessionHighPrice,
1867
+ MDEntryType.TradingSessionLowPrice,
1868
+ MDEntryType.VWAP,
1869
+ MDEntryType.Imbalance,
1870
+ MDEntryType.TradeVolume,
1871
+ MDEntryType.OpenInterest,
1872
+ MDEntryType.CompositeUnderlyingPrice,
1873
+ MDEntryType.SimulatedSellPrice,
1874
+ MDEntryType.SimulatedBuyPrice,
1875
+ MDEntryType.MarginRate,
1876
+ MDEntryType.MidPrice,
1877
+ MDEntryType.EmptyBook,
1878
+ MDEntryType.SettleHighPrice,
1879
+ MDEntryType.SettleLowPrice,
1880
+ MDEntryType.PriorSettlePrice,
1881
+ MDEntryType.SessionHighBid,
1882
+ MDEntryType.SessionLowOffer,
1883
+ MDEntryType.EarlyPrices,
1884
+ MDEntryType.AuctionClearingPrice,
1885
+ MDEntryType.SwapValueFactor,
1886
+ MDEntryType.DailyValueAdjustmentForLongPositions,
1887
+ MDEntryType.CumulativeValueAdjustmentForLongPositions,
1888
+ MDEntryType.DailyValueAdjustmentForShortPositions,
1889
+ MDEntryType.CumulativeValueAdjustmentForShortPositions,
1890
+ MDEntryType.FixingPrice,
1891
+ MDEntryType.CashRate,
1892
+ MDEntryType.RecoveryRate,
1893
+ MDEntryType.RecoveryRateForLong,
1894
+ MDEntryType.RecoveryRateForShort,
1895
+ MDEntryType.MarketBid,
1896
+ MDEntryType.MarketOffer,
1897
+ MDEntryType.ShortSaleMinPrice,
1898
+ MDEntryType.PreviousClosingPrice,
1899
+ MDEntryType.ThresholdLimitPriceBanding,
1900
+ MDEntryType.DailyFinancingValue,
1901
+ MDEntryType.AccruedFinancingValue,
1902
+ MDEntryType.TWAP
1903
+ ];
292
1904
  const messageFields = [
293
1905
  new Field(Fields.MsgType, Messages.MarketDataRequest),
294
1906
  new Field(Fields.SenderCompID, parser.sender),
@@ -310,6 +1922,10 @@ var createMarketDataRequestHandler = (parser, pendingRequests) => {
310
1922
  });
311
1923
  const mdr = parser.createMessage(...messageFields);
312
1924
  if (!parser.connected) {
1925
+ parser.logger.log({
1926
+ level: "error",
1927
+ message: "Not connected. Cannot send market data request."
1928
+ });
313
1929
  return {
314
1930
  content: [
315
1931
  {
@@ -321,8 +1937,16 @@ var createMarketDataRequestHandler = (parser, pendingRequests) => {
321
1937
  isError: true
322
1938
  };
323
1939
  }
1940
+ parser.logger.log({
1941
+ level: "info",
1942
+ message: `Sending market data request message: ${JSON.stringify(mdr?.toFIXJSON())}`
1943
+ });
324
1944
  parser.send(mdr);
325
1945
  const fixData = await response;
1946
+ parser.logger.log({
1947
+ level: "info",
1948
+ message: `Received market data response for request ID: ${args.mdReqID}`
1949
+ });
326
1950
  return {
327
1951
  content: [
328
1952
  {
@@ -346,6 +1970,72 @@ var createMarketDataRequestHandler = (parser, pendingRequests) => {
346
1970
  }
347
1971
  };
348
1972
  };
1973
+ var aggregateMarketData = (priceHistory, maxPoints = 490) => {
1974
+ if (priceHistory.length <= maxPoints) {
1975
+ return priceHistory;
1976
+ }
1977
+ const result = [];
1978
+ const step = priceHistory.length / maxPoints;
1979
+ result.push(priceHistory[0]);
1980
+ for (let i = 1; i < maxPoints - 1; i++) {
1981
+ const startIndex = Math.floor(i * step);
1982
+ const endIndex = Math.floor((i + 1) * step);
1983
+ const segment = priceHistory.slice(startIndex, endIndex);
1984
+ if (segment.length === 0) continue;
1985
+ const aggregatedPoint = {
1986
+ timestamp: segment[0].timestamp,
1987
+ // Use timestamp of first point in segment
1988
+ bid: segment.reduce((sum2, p) => sum2 + p.bid, 0) / segment.length,
1989
+ offer: segment.reduce((sum2, p) => sum2 + p.offer, 0) / segment.length,
1990
+ spread: segment.reduce((sum2, p) => sum2 + p.spread, 0) / segment.length,
1991
+ volume: segment.reduce((sum2, p) => sum2 + p.volume, 0) / segment.length,
1992
+ trade: segment.reduce((sum2, p) => sum2 + p.trade, 0) / segment.length,
1993
+ indexValue: segment.reduce((sum2, p) => sum2 + p.indexValue, 0) / segment.length,
1994
+ openingPrice: segment.reduce((sum2, p) => sum2 + p.openingPrice, 0) / segment.length,
1995
+ closingPrice: segment.reduce((sum2, p) => sum2 + p.closingPrice, 0) / segment.length,
1996
+ settlementPrice: segment.reduce((sum2, p) => sum2 + p.settlementPrice, 0) / segment.length,
1997
+ tradingSessionHighPrice: segment.reduce((sum2, p) => sum2 + p.tradingSessionHighPrice, 0) / segment.length,
1998
+ tradingSessionLowPrice: segment.reduce((sum2, p) => sum2 + p.tradingSessionLowPrice, 0) / segment.length,
1999
+ vwap: segment.reduce((sum2, p) => sum2 + p.vwap, 0) / segment.length,
2000
+ imbalance: segment.reduce((sum2, p) => sum2 + p.imbalance, 0) / segment.length,
2001
+ openInterest: segment.reduce((sum2, p) => sum2 + p.openInterest, 0) / segment.length,
2002
+ compositeUnderlyingPrice: segment.reduce((sum2, p) => sum2 + p.compositeUnderlyingPrice, 0) / segment.length,
2003
+ simulatedSellPrice: segment.reduce((sum2, p) => sum2 + p.simulatedSellPrice, 0) / segment.length,
2004
+ simulatedBuyPrice: segment.reduce((sum2, p) => sum2 + p.simulatedBuyPrice, 0) / segment.length,
2005
+ marginRate: segment.reduce((sum2, p) => sum2 + p.marginRate, 0) / segment.length,
2006
+ midPrice: segment.reduce((sum2, p) => sum2 + p.midPrice, 0) / segment.length,
2007
+ emptyBook: segment.reduce((sum2, p) => sum2 + p.emptyBook, 0) / segment.length,
2008
+ settleHighPrice: segment.reduce((sum2, p) => sum2 + p.settleHighPrice, 0) / segment.length,
2009
+ settleLowPrice: segment.reduce((sum2, p) => sum2 + p.settleLowPrice, 0) / segment.length,
2010
+ priorSettlePrice: segment.reduce((sum2, p) => sum2 + p.priorSettlePrice, 0) / segment.length,
2011
+ sessionHighBid: segment.reduce((sum2, p) => sum2 + p.sessionHighBid, 0) / segment.length,
2012
+ sessionLowOffer: segment.reduce((sum2, p) => sum2 + p.sessionLowOffer, 0) / segment.length,
2013
+ earlyPrices: segment.reduce((sum2, p) => sum2 + p.earlyPrices, 0) / segment.length,
2014
+ auctionClearingPrice: segment.reduce((sum2, p) => sum2 + p.auctionClearingPrice, 0) / segment.length,
2015
+ swapValueFactor: segment.reduce((sum2, p) => sum2 + p.swapValueFactor, 0) / segment.length,
2016
+ dailyValueAdjustmentForLongPositions: segment.reduce((sum2, p) => sum2 + p.dailyValueAdjustmentForLongPositions, 0) / segment.length,
2017
+ cumulativeValueAdjustmentForLongPositions: segment.reduce((sum2, p) => sum2 + p.cumulativeValueAdjustmentForLongPositions, 0) / segment.length,
2018
+ dailyValueAdjustmentForShortPositions: segment.reduce((sum2, p) => sum2 + p.dailyValueAdjustmentForShortPositions, 0) / segment.length,
2019
+ cumulativeValueAdjustmentForShortPositions: segment.reduce((sum2, p) => sum2 + p.cumulativeValueAdjustmentForShortPositions, 0) / segment.length,
2020
+ fixingPrice: segment.reduce((sum2, p) => sum2 + p.fixingPrice, 0) / segment.length,
2021
+ cashRate: segment.reduce((sum2, p) => sum2 + p.cashRate, 0) / segment.length,
2022
+ recoveryRate: segment.reduce((sum2, p) => sum2 + p.recoveryRate, 0) / segment.length,
2023
+ recoveryRateForLong: segment.reduce((sum2, p) => sum2 + p.recoveryRateForLong, 0) / segment.length,
2024
+ recoveryRateForShort: segment.reduce((sum2, p) => sum2 + p.recoveryRateForShort, 0) / segment.length,
2025
+ marketBid: segment.reduce((sum2, p) => sum2 + p.marketBid, 0) / segment.length,
2026
+ marketOffer: segment.reduce((sum2, p) => sum2 + p.marketOffer, 0) / segment.length,
2027
+ shortSaleMinPrice: segment.reduce((sum2, p) => sum2 + p.shortSaleMinPrice, 0) / segment.length,
2028
+ previousClosingPrice: segment.reduce((sum2, p) => sum2 + p.previousClosingPrice, 0) / segment.length,
2029
+ thresholdLimitPriceBanding: segment.reduce((sum2, p) => sum2 + p.thresholdLimitPriceBanding, 0) / segment.length,
2030
+ dailyFinancingValue: segment.reduce((sum2, p) => sum2 + p.dailyFinancingValue, 0) / segment.length,
2031
+ accruedFinancingValue: segment.reduce((sum2, p) => sum2 + p.accruedFinancingValue, 0) / segment.length,
2032
+ twap: segment.reduce((sum2, p) => sum2 + p.twap, 0) / segment.length
2033
+ };
2034
+ result.push(aggregatedPoint);
2035
+ }
2036
+ result.push(priceHistory[priceHistory.length - 1]);
2037
+ return result;
2038
+ };
349
2039
  var createGetStockGraphHandler = (marketDataPrices) => {
350
2040
  return async (args) => {
351
2041
  try {
@@ -362,15 +2052,22 @@ var createGetStockGraphHandler = (marketDataPrices) => {
362
2052
  ]
363
2053
  };
364
2054
  }
2055
+ const aggregatedData = aggregateMarketData(priceHistory, 500);
365
2056
  const chart = new QuickChart();
366
2057
  chart.setWidth(1200);
367
2058
  chart.setHeight(600);
368
2059
  chart.setBackgroundColor("transparent");
369
- const labels = priceHistory.map((point) => new Date(point.timestamp).toLocaleTimeString());
370
- const bidData = priceHistory.map((point) => point.bid);
371
- const offerData = priceHistory.map((point) => point.offer);
372
- const spreadData = priceHistory.map((point) => point.spread);
373
- const volumeData = priceHistory.map((point) => point.volume);
2060
+ const labels = aggregatedData.map((point) => new Date(point.timestamp).toLocaleTimeString());
2061
+ const bidData = aggregatedData.map((point) => point.bid);
2062
+ const offerData = aggregatedData.map((point) => point.offer);
2063
+ const spreadData = aggregatedData.map((point) => point.spread);
2064
+ const volumeData = aggregatedData.map((point) => point.volume);
2065
+ const tradeData = aggregatedData.map((point) => point.trade);
2066
+ const vwapData = aggregatedData.map((point) => point.vwap);
2067
+ const twapData = aggregatedData.map((point) => point.twap);
2068
+ const maxVolume = Math.max(...volumeData.filter((v) => v > 0));
2069
+ const maxPrice = Math.max(...bidData, ...offerData, ...tradeData, ...vwapData, ...twapData);
2070
+ const normalizedVolumeData = volumeData.map((v) => v / maxVolume * maxPrice * 0.3);
374
2071
  const config = {
375
2072
  type: "line",
376
2073
  data: {
@@ -401,8 +2098,32 @@ var createGetStockGraphHandler = (marketDataPrices) => {
401
2098
  tension: 0.4
402
2099
  },
403
2100
  {
404
- label: "Volume",
405
- data: volumeData,
2101
+ label: "Trade",
2102
+ data: tradeData,
2103
+ borderColor: "#ffc107",
2104
+ backgroundColor: "rgba(255, 193, 7, 0.1)",
2105
+ fill: false,
2106
+ tension: 0.4
2107
+ },
2108
+ {
2109
+ label: "VWAP",
2110
+ data: vwapData,
2111
+ borderColor: "#17a2b8",
2112
+ backgroundColor: "rgba(23, 162, 184, 0.1)",
2113
+ fill: false,
2114
+ tension: 0.4
2115
+ },
2116
+ {
2117
+ label: "TWAP",
2118
+ data: twapData,
2119
+ borderColor: "#6610f2",
2120
+ backgroundColor: "rgba(102, 16, 242, 0.1)",
2121
+ fill: false,
2122
+ tension: 0.4
2123
+ },
2124
+ {
2125
+ label: "Volume (Normalized)",
2126
+ data: normalizedVolumeData,
406
2127
  borderColor: "#007bff",
407
2128
  backgroundColor: "rgba(0, 123, 255, 0.1)",
408
2129
  fill: true,
@@ -415,12 +2136,16 @@ var createGetStockGraphHandler = (marketDataPrices) => {
415
2136
  plugins: {
416
2137
  title: {
417
2138
  display: true,
418
- text: `${symbol} Market Data`
2139
+ text: `${symbol} Market Data (Volume normalized to 30% of max price)`
419
2140
  }
420
2141
  },
421
2142
  scales: {
422
2143
  y: {
423
- beginAtZero: false
2144
+ beginAtZero: false,
2145
+ title: {
2146
+ display: true,
2147
+ text: "Price / Normalized Volume"
2148
+ }
424
2149
  }
425
2150
  }
426
2151
  }
@@ -445,7 +2170,7 @@ var createGetStockGraphHandler = (marketDataPrices) => {
445
2170
  content: [
446
2171
  {
447
2172
  type: "text",
448
- text: `Error: ${error instanceof Error ? error.message : "Failed to generate chart"}`,
2173
+ text: `Error: ${error instanceof Error ? error.message : "Failed to generate graph"}`,
449
2174
  uri: "getStockGraph"
450
2175
  }
451
2176
  ],
@@ -470,6 +2195,7 @@ var createGetStockPriceHistoryHandler = (marketDataPrices) => {
470
2195
  ]
471
2196
  };
472
2197
  }
2198
+ const aggregatedData = aggregateMarketData(priceHistory, 500);
473
2199
  return {
474
2200
  content: [
475
2201
  {
@@ -477,13 +2203,55 @@ var createGetStockPriceHistoryHandler = (marketDataPrices) => {
477
2203
  text: JSON.stringify(
478
2204
  {
479
2205
  symbol,
480
- count: priceHistory.length,
481
- data: priceHistory.map((point) => ({
2206
+ count: aggregatedData.length,
2207
+ originalCount: priceHistory.length,
2208
+ data: aggregatedData.map((point) => ({
482
2209
  timestamp: new Date(point.timestamp).toISOString(),
483
2210
  bid: point.bid,
484
2211
  offer: point.offer,
485
2212
  spread: point.spread,
486
- volume: point.volume
2213
+ volume: point.volume,
2214
+ trade: point.trade,
2215
+ indexValue: point.indexValue,
2216
+ openingPrice: point.openingPrice,
2217
+ closingPrice: point.closingPrice,
2218
+ settlementPrice: point.settlementPrice,
2219
+ tradingSessionHighPrice: point.tradingSessionHighPrice,
2220
+ tradingSessionLowPrice: point.tradingSessionLowPrice,
2221
+ vwap: point.vwap,
2222
+ imbalance: point.imbalance,
2223
+ openInterest: point.openInterest,
2224
+ compositeUnderlyingPrice: point.compositeUnderlyingPrice,
2225
+ simulatedSellPrice: point.simulatedSellPrice,
2226
+ simulatedBuyPrice: point.simulatedBuyPrice,
2227
+ marginRate: point.marginRate,
2228
+ midPrice: point.midPrice,
2229
+ emptyBook: point.emptyBook,
2230
+ settleHighPrice: point.settleHighPrice,
2231
+ settleLowPrice: point.settleLowPrice,
2232
+ priorSettlePrice: point.priorSettlePrice,
2233
+ sessionHighBid: point.sessionHighBid,
2234
+ sessionLowOffer: point.sessionLowOffer,
2235
+ earlyPrices: point.earlyPrices,
2236
+ auctionClearingPrice: point.auctionClearingPrice,
2237
+ swapValueFactor: point.swapValueFactor,
2238
+ dailyValueAdjustmentForLongPositions: point.dailyValueAdjustmentForLongPositions,
2239
+ cumulativeValueAdjustmentForLongPositions: point.cumulativeValueAdjustmentForLongPositions,
2240
+ dailyValueAdjustmentForShortPositions: point.dailyValueAdjustmentForShortPositions,
2241
+ cumulativeValueAdjustmentForShortPositions: point.cumulativeValueAdjustmentForShortPositions,
2242
+ fixingPrice: point.fixingPrice,
2243
+ cashRate: point.cashRate,
2244
+ recoveryRate: point.recoveryRate,
2245
+ recoveryRateForLong: point.recoveryRateForLong,
2246
+ recoveryRateForShort: point.recoveryRateForShort,
2247
+ marketBid: point.marketBid,
2248
+ marketOffer: point.marketOffer,
2249
+ shortSaleMinPrice: point.shortSaleMinPrice,
2250
+ previousClosingPrice: point.previousClosingPrice,
2251
+ thresholdLimitPriceBanding: point.thresholdLimitPriceBanding,
2252
+ dailyFinancingValue: point.dailyFinancingValue,
2253
+ accruedFinancingValue: point.accruedFinancingValue,
2254
+ twap: point.twap
487
2255
  }))
488
2256
  },
489
2257
  null,
@@ -498,7 +2266,7 @@ var createGetStockPriceHistoryHandler = (marketDataPrices) => {
498
2266
  content: [
499
2267
  {
500
2268
  type: "text",
501
- text: `Error: ${error instanceof Error ? error.message : "Failed to get stock price history"}`,
2269
+ text: `Error: ${error instanceof Error ? error.message : "Failed to get price history"}`,
502
2270
  uri: "getStockPriceHistory"
503
2271
  }
504
2272
  ],
@@ -579,6 +2347,7 @@ var handlInstNames = {
579
2347
  };
580
2348
  var createVerifyOrderHandler = (parser, verifiedOrders) => {
581
2349
  return async (args) => {
2350
+ void parser;
582
2351
  try {
583
2352
  verifiedOrders.set(args.clOrdID, {
584
2353
  clOrdID: args.clOrdID,
@@ -606,7 +2375,7 @@ Parameters verified:
606
2375
  - Symbol: ${args.symbol}
607
2376
  - TimeInForce: ${args.timeInForce} (${timeInForceNames[args.timeInForce]})
608
2377
 
609
- To execute this order, call the executeOrder tool with these exact same parameters.`,
2378
+ To execute this order, call the executeOrder tool with these exact same parameters. Important: The user has to explicitly confirm before executeOrder is called!`,
610
2379
  uri: "verifyOrder"
611
2380
  }
612
2381
  ]
@@ -802,48 +2571,211 @@ var createToolHandlers = (parser, verifiedOrders, pendingRequests, marketDataPri
802
2571
  executeOrder: createExecuteOrderHandler(parser, verifiedOrders, pendingRequests),
803
2572
  marketDataRequest: createMarketDataRequestHandler(parser, pendingRequests),
804
2573
  getStockGraph: createGetStockGraphHandler(marketDataPrices),
805
- getStockPriceHistory: createGetStockPriceHistoryHandler(marketDataPrices)
2574
+ getStockPriceHistory: createGetStockPriceHistoryHandler(marketDataPrices),
2575
+ technicalAnalysis: createTechnicalAnalysisHandler(marketDataPrices)
806
2576
  });
807
2577
 
808
2578
  // src/utils/messageHandler.ts
809
2579
  import { Fields as Fields3, MDEntryType as MDEntryType2, Messages as Messages3 } from "fixparser";
2580
+ function getEnumValue(enumObj, name) {
2581
+ return enumObj[name] || name;
2582
+ }
810
2583
  function handleMessage(message, parser, pendingRequests, marketDataPrices, maxPriceHistory, onPriceUpdate) {
811
- parser.logger.log({
812
- level: "info",
813
- message: `MCP Server received message: ${message.messageType}: ${message.description}`
814
- });
2584
+ void parser;
815
2585
  const msgType = message.messageType;
816
- if (msgType === Messages3.MarketDataSnapshotFullRefresh) {
2586
+ if (msgType === Messages3.MarketDataSnapshotFullRefresh || msgType === Messages3.MarketDataIncrementalRefresh) {
817
2587
  const symbol = message.getField(Fields3.Symbol)?.value;
818
- const entries = message.getField(Fields3.NoMDEntries)?.value;
819
- let bid = 0;
820
- let offer = 0;
821
- let volume = 0;
822
- const entryTypes = message.getFields(Fields3.MDEntryType);
823
- const entryPrices = message.getFields(Fields3.MDEntryPx);
824
- const entrySizes = message.getFields(Fields3.MDEntrySize);
825
- if (entryTypes && entryPrices && entrySizes) {
826
- for (let i = 0; i < entries; i++) {
827
- const entryType = entryTypes[i]?.value;
828
- const entryPrice = Number.parseFloat(entryPrices[i]?.value);
829
- const entrySize = Number.parseFloat(entrySizes[i]?.value);
830
- if (entryType === MDEntryType2.Bid) {
831
- bid = entryPrice;
832
- } else if (entryType === MDEntryType2.Offer) {
833
- offer = entryPrice;
834
- }
835
- volume += entrySize;
836
- }
837
- }
838
- const spread = offer - bid;
839
- const timestamp = Date.now();
2588
+ const fixJson = message.toFIXJSON();
2589
+ const entries = fixJson.Body?.NoMDEntries || [];
840
2590
  const data = {
841
- timestamp,
842
- bid,
843
- offer,
844
- spread,
845
- volume
2591
+ timestamp: Date.now(),
2592
+ bid: 0,
2593
+ offer: 0,
2594
+ spread: 0,
2595
+ volume: 0,
2596
+ trade: 0,
2597
+ indexValue: 0,
2598
+ openingPrice: 0,
2599
+ closingPrice: 0,
2600
+ settlementPrice: 0,
2601
+ tradingSessionHighPrice: 0,
2602
+ tradingSessionLowPrice: 0,
2603
+ vwap: 0,
2604
+ imbalance: 0,
2605
+ openInterest: 0,
2606
+ compositeUnderlyingPrice: 0,
2607
+ simulatedSellPrice: 0,
2608
+ simulatedBuyPrice: 0,
2609
+ marginRate: 0,
2610
+ midPrice: 0,
2611
+ emptyBook: 0,
2612
+ settleHighPrice: 0,
2613
+ settleLowPrice: 0,
2614
+ priorSettlePrice: 0,
2615
+ sessionHighBid: 0,
2616
+ sessionLowOffer: 0,
2617
+ earlyPrices: 0,
2618
+ auctionClearingPrice: 0,
2619
+ swapValueFactor: 0,
2620
+ dailyValueAdjustmentForLongPositions: 0,
2621
+ cumulativeValueAdjustmentForLongPositions: 0,
2622
+ dailyValueAdjustmentForShortPositions: 0,
2623
+ cumulativeValueAdjustmentForShortPositions: 0,
2624
+ fixingPrice: 0,
2625
+ cashRate: 0,
2626
+ recoveryRate: 0,
2627
+ recoveryRateForLong: 0,
2628
+ recoveryRateForShort: 0,
2629
+ marketBid: 0,
2630
+ marketOffer: 0,
2631
+ shortSaleMinPrice: 0,
2632
+ previousClosingPrice: 0,
2633
+ thresholdLimitPriceBanding: 0,
2634
+ dailyFinancingValue: 0,
2635
+ accruedFinancingValue: 0,
2636
+ twap: 0
846
2637
  };
2638
+ for (const entry of entries) {
2639
+ const entryType = entry.MDEntryType;
2640
+ const price = entry.MDEntryPx ? Number.parseFloat(entry.MDEntryPx) : 0;
2641
+ const size = entry.MDEntrySize ? Number.parseFloat(entry.MDEntrySize) : 0;
2642
+ const enumValue = getEnumValue(MDEntryType2, entryType);
2643
+ switch (enumValue) {
2644
+ case MDEntryType2.Bid:
2645
+ data.bid = price;
2646
+ break;
2647
+ case MDEntryType2.Offer:
2648
+ data.offer = price;
2649
+ break;
2650
+ case MDEntryType2.Trade:
2651
+ data.trade = price;
2652
+ break;
2653
+ case MDEntryType2.IndexValue:
2654
+ data.indexValue = price;
2655
+ break;
2656
+ case MDEntryType2.OpeningPrice:
2657
+ data.openingPrice = price;
2658
+ break;
2659
+ case MDEntryType2.ClosingPrice:
2660
+ data.closingPrice = price;
2661
+ break;
2662
+ case MDEntryType2.SettlementPrice:
2663
+ data.settlementPrice = price;
2664
+ break;
2665
+ case MDEntryType2.TradingSessionHighPrice:
2666
+ data.tradingSessionHighPrice = price;
2667
+ break;
2668
+ case MDEntryType2.TradingSessionLowPrice:
2669
+ data.tradingSessionLowPrice = price;
2670
+ break;
2671
+ case MDEntryType2.VWAP:
2672
+ data.vwap = price;
2673
+ break;
2674
+ case MDEntryType2.Imbalance:
2675
+ data.imbalance = size;
2676
+ break;
2677
+ case MDEntryType2.TradeVolume:
2678
+ data.volume = size;
2679
+ break;
2680
+ case MDEntryType2.OpenInterest:
2681
+ data.openInterest = size;
2682
+ break;
2683
+ case MDEntryType2.CompositeUnderlyingPrice:
2684
+ data.compositeUnderlyingPrice = price;
2685
+ break;
2686
+ case MDEntryType2.SimulatedSellPrice:
2687
+ data.simulatedSellPrice = price;
2688
+ break;
2689
+ case MDEntryType2.SimulatedBuyPrice:
2690
+ data.simulatedBuyPrice = price;
2691
+ break;
2692
+ case MDEntryType2.MarginRate:
2693
+ data.marginRate = price;
2694
+ break;
2695
+ case MDEntryType2.MidPrice:
2696
+ data.midPrice = price;
2697
+ break;
2698
+ case MDEntryType2.EmptyBook:
2699
+ data.emptyBook = 1;
2700
+ break;
2701
+ case MDEntryType2.SettleHighPrice:
2702
+ data.settleHighPrice = price;
2703
+ break;
2704
+ case MDEntryType2.SettleLowPrice:
2705
+ data.settleLowPrice = price;
2706
+ break;
2707
+ case MDEntryType2.PriorSettlePrice:
2708
+ data.priorSettlePrice = price;
2709
+ break;
2710
+ case MDEntryType2.SessionHighBid:
2711
+ data.sessionHighBid = price;
2712
+ break;
2713
+ case MDEntryType2.SessionLowOffer:
2714
+ data.sessionLowOffer = price;
2715
+ break;
2716
+ case MDEntryType2.EarlyPrices:
2717
+ data.earlyPrices = price;
2718
+ break;
2719
+ case MDEntryType2.AuctionClearingPrice:
2720
+ data.auctionClearingPrice = price;
2721
+ break;
2722
+ case MDEntryType2.SwapValueFactor:
2723
+ data.swapValueFactor = price;
2724
+ break;
2725
+ case MDEntryType2.DailyValueAdjustmentForLongPositions:
2726
+ data.dailyValueAdjustmentForLongPositions = price;
2727
+ break;
2728
+ case MDEntryType2.CumulativeValueAdjustmentForLongPositions:
2729
+ data.cumulativeValueAdjustmentForLongPositions = price;
2730
+ break;
2731
+ case MDEntryType2.DailyValueAdjustmentForShortPositions:
2732
+ data.dailyValueAdjustmentForShortPositions = price;
2733
+ break;
2734
+ case MDEntryType2.CumulativeValueAdjustmentForShortPositions:
2735
+ data.cumulativeValueAdjustmentForShortPositions = price;
2736
+ break;
2737
+ case MDEntryType2.FixingPrice:
2738
+ data.fixingPrice = price;
2739
+ break;
2740
+ case MDEntryType2.CashRate:
2741
+ data.cashRate = price;
2742
+ break;
2743
+ case MDEntryType2.RecoveryRate:
2744
+ data.recoveryRate = price;
2745
+ break;
2746
+ case MDEntryType2.RecoveryRateForLong:
2747
+ data.recoveryRateForLong = price;
2748
+ break;
2749
+ case MDEntryType2.RecoveryRateForShort:
2750
+ data.recoveryRateForShort = price;
2751
+ break;
2752
+ case MDEntryType2.MarketBid:
2753
+ data.marketBid = price;
2754
+ break;
2755
+ case MDEntryType2.MarketOffer:
2756
+ data.marketOffer = price;
2757
+ break;
2758
+ case MDEntryType2.ShortSaleMinPrice:
2759
+ data.shortSaleMinPrice = price;
2760
+ break;
2761
+ case MDEntryType2.PreviousClosingPrice:
2762
+ data.previousClosingPrice = price;
2763
+ break;
2764
+ case MDEntryType2.ThresholdLimitPriceBanding:
2765
+ data.thresholdLimitPriceBanding = price;
2766
+ break;
2767
+ case MDEntryType2.DailyFinancingValue:
2768
+ data.dailyFinancingValue = price;
2769
+ break;
2770
+ case MDEntryType2.AccruedFinancingValue:
2771
+ data.accruedFinancingValue = price;
2772
+ break;
2773
+ case MDEntryType2.TWAP:
2774
+ data.twap = price;
2775
+ break;
2776
+ }
2777
+ }
2778
+ data.spread = data.offer - data.bid;
847
2779
  if (!marketDataPrices.has(symbol)) {
848
2780
  marketDataPrices.set(symbol, []);
849
2781
  }
@@ -853,6 +2785,14 @@ function handleMessage(message, parser, pendingRequests, marketDataPrices, maxPr
853
2785
  prices.splice(0, prices.length - maxPriceHistory);
854
2786
  }
855
2787
  onPriceUpdate?.(symbol, data);
2788
+ const mdReqID = message.getField(Fields3.MDReqID)?.value;
2789
+ if (mdReqID) {
2790
+ const callback = pendingRequests.get(mdReqID);
2791
+ if (callback) {
2792
+ callback(message);
2793
+ pendingRequests.delete(mdReqID);
2794
+ }
2795
+ }
856
2796
  } else if (msgType === Messages3.ExecutionReport) {
857
2797
  const reqId = message.getField(Fields3.ClOrdID)?.value;
858
2798
  const callback = pendingRequests.get(reqId);
@@ -865,6 +2805,39 @@ function handleMessage(message, parser, pendingRequests, marketDataPrices, maxPr
865
2805
 
866
2806
  // src/MCPRemote.ts
867
2807
  var transports = {};
2808
+ function jsonSchemaToZod(schema) {
2809
+ if (schema.type === "object") {
2810
+ const shape = {};
2811
+ for (const [key, prop] of Object.entries(schema.properties || {})) {
2812
+ const propSchema = prop;
2813
+ if (propSchema.type === "string") {
2814
+ if (propSchema.enum) {
2815
+ shape[key] = z.enum(propSchema.enum);
2816
+ } else {
2817
+ shape[key] = z.string();
2818
+ }
2819
+ } else if (propSchema.type === "number") {
2820
+ shape[key] = z.number();
2821
+ } else if (propSchema.type === "boolean") {
2822
+ shape[key] = z.boolean();
2823
+ } else if (propSchema.type === "array") {
2824
+ if (propSchema.items.type === "string") {
2825
+ shape[key] = z.array(z.string());
2826
+ } else if (propSchema.items.type === "number") {
2827
+ shape[key] = z.array(z.number());
2828
+ } else if (propSchema.items.type === "boolean") {
2829
+ shape[key] = z.array(z.boolean());
2830
+ } else {
2831
+ shape[key] = z.array(z.any());
2832
+ }
2833
+ } else {
2834
+ shape[key] = z.any();
2835
+ }
2836
+ }
2837
+ return shape;
2838
+ }
2839
+ return {};
2840
+ }
868
2841
  var MCPRemote = class extends MCPBase {
869
2842
  /**
870
2843
  * Port number the server will listen on.
@@ -907,7 +2880,7 @@ var MCPRemote = class extends MCPBase {
907
2880
  */
908
2881
  marketDataPrices = /* @__PURE__ */ new Map();
909
2882
  /**
910
- * Maximum number of price points to store per symbol
2883
+ * Maximum number of price history entries to keep per symbol
911
2884
  * @private
912
2885
  */
913
2886
  MAX_PRICE_HISTORY = 1e5;
@@ -929,31 +2902,7 @@ var MCPRemote = class extends MCPBase {
929
2902
  this.parser,
930
2903
  this.pendingRequests,
931
2904
  this.marketDataPrices,
932
- this.MAX_PRICE_HISTORY,
933
- (symbol, data) => {
934
- this.mcpServer?.tool(
935
- "priceUpdate",
936
- {
937
- description: "Price update notification",
938
- schema: z.object({
939
- symbol: z.string(),
940
- timestamp: z.number(),
941
- bid: z.number(),
942
- offer: z.number(),
943
- spread: z.number(),
944
- volume: z.number()
945
- })
946
- },
947
- () => ({
948
- content: [
949
- {
950
- type: "text",
951
- text: JSON.stringify({ symbol, ...data })
952
- }
953
- ]
954
- })
955
- );
956
- }
2905
+ this.MAX_PRICE_HISTORY
957
2906
  );
958
2907
  }
959
2908
  });
@@ -975,7 +2924,8 @@ var MCPRemote = class extends MCPBase {
975
2924
  const body = Buffer.concat(bodyChunks).toString();
976
2925
  try {
977
2926
  parsed = JSON.parse(body);
978
- } catch (err) {
2927
+ } catch (error) {
2928
+ void error;
979
2929
  res.writeHead(400);
980
2930
  res.end(JSON.stringify({ error: "Invalid JSON" }));
981
2931
  return;
@@ -1015,7 +2965,15 @@ var MCPRemote = class extends MCPBase {
1015
2965
  );
1016
2966
  return;
1017
2967
  }
1018
- await transport.handleRequest(req, res, parsed);
2968
+ try {
2969
+ await transport.handleRequest(req, res, parsed);
2970
+ } catch (error) {
2971
+ this.logger?.log({
2972
+ level: "error",
2973
+ message: `Error handling request: ${error}`
2974
+ });
2975
+ throw error;
2976
+ }
1019
2977
  });
1020
2978
  } else if (req.method === "GET" || req.method === "DELETE") {
1021
2979
  if (!sessionId || !transports[sessionId]) {
@@ -1024,8 +2982,20 @@ var MCPRemote = class extends MCPBase {
1024
2982
  return;
1025
2983
  }
1026
2984
  const transport = transports[sessionId];
1027
- await transport.handleRequest(req, res);
2985
+ try {
2986
+ await transport.handleRequest(req, res);
2987
+ } catch (error) {
2988
+ this.logger?.log({
2989
+ level: "error",
2990
+ message: `Error handling ${req.method} request: ${error}`
2991
+ });
2992
+ throw error;
2993
+ }
1028
2994
  } else {
2995
+ this.logger?.log({
2996
+ level: "error",
2997
+ message: `Method not allowed: ${req.method}`
2998
+ });
1029
2999
  res.writeHead(405);
1030
3000
  res.end("Method Not Allowed");
1031
3001
  }
@@ -1059,69 +3029,40 @@ var MCPRemote = class extends MCPBase {
1059
3029
  });
1060
3030
  return;
1061
3031
  }
1062
- this.mcpServer.tool(
1063
- "tools/list",
1064
- {
1065
- description: "List available tools",
1066
- schema: z.object({})
1067
- },
1068
- async () => {
1069
- return {
1070
- content: [
1071
- {
1072
- type: "text",
1073
- text: JSON.stringify(
1074
- Object.entries(toolSchemas).map(([name, { description, schema }]) => ({
1075
- name,
1076
- description,
1077
- inputSchema: schema
1078
- }))
1079
- )
1080
- }
1081
- ]
1082
- };
1083
- }
3032
+ const toolHandlers = createToolHandlers(
3033
+ this.parser,
3034
+ this.verifiedOrders,
3035
+ this.pendingRequests,
3036
+ this.marketDataPrices
1084
3037
  );
1085
- this.mcpServer.tool(
1086
- "tools/call",
1087
- {
1088
- description: "Call a tool",
1089
- schema: z.object({
1090
- name: z.string(),
1091
- arguments: z.any(),
1092
- _meta: z.object({
1093
- progressToken: z.number()
1094
- }).optional()
1095
- })
1096
- },
1097
- async (request) => {
1098
- const { name, arguments: args } = request;
1099
- const toolHandlers = createToolHandlers(
1100
- this.parser,
1101
- this.verifiedOrders,
1102
- this.pendingRequests,
1103
- this.marketDataPrices
1104
- );
1105
- const handler = toolHandlers[name];
1106
- if (!handler) {
3038
+ Object.entries(toolSchemas).forEach(([name, { description, schema }]) => {
3039
+ this.mcpServer?.registerTool(
3040
+ name,
3041
+ {
3042
+ description,
3043
+ inputSchema: jsonSchemaToZod(schema)
3044
+ },
3045
+ async (args) => {
3046
+ const handler = toolHandlers[name];
3047
+ if (!handler) {
3048
+ return {
3049
+ content: [
3050
+ {
3051
+ type: "text",
3052
+ text: `Tool not found: ${name}`
3053
+ }
3054
+ ],
3055
+ isError: true
3056
+ };
3057
+ }
3058
+ const result = await handler(args);
1107
3059
  return {
1108
- content: [
1109
- {
1110
- type: "text",
1111
- text: `Tool not found: ${name}`,
1112
- uri: name
1113
- }
1114
- ],
1115
- isError: true
3060
+ content: result.content,
3061
+ isError: result.isError
1116
3062
  };
1117
3063
  }
1118
- const result = await handler(args);
1119
- return {
1120
- content: result.content,
1121
- isError: result.isError
1122
- };
1123
- }
1124
- );
3064
+ );
3065
+ });
1125
3066
  }
1126
3067
  };
1127
3068
  export {