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