fixparser-plugin-mcp 9.1.7-5d282a9e → 9.1.7-620b3399

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.
@@ -310,1567 +310,8 @@ 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
- };
1823
313
  }
1824
314
  };
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
- };
1874
315
 
1875
316
  // src/tools/marketData.ts
1876
317
  var import_fixparser = require("fixparser");
@@ -2004,72 +445,6 @@ var createMarketDataRequestHandler = (parser, pendingRequests) => {
2004
445
  }
2005
446
  };
2006
447
  };
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
- };
2073
448
  var createGetStockGraphHandler = (marketDataPrices) => {
2074
449
  return async (args) => {
2075
450
  try {
@@ -2086,22 +461,18 @@ var createGetStockGraphHandler = (marketDataPrices) => {
2086
461
  ]
2087
462
  };
2088
463
  }
2089
- const aggregatedData = aggregateMarketData(priceHistory, 500);
2090
464
  const chart = new import_quickchart_js.default();
2091
465
  chart.setWidth(1200);
2092
466
  chart.setHeight(600);
2093
467
  chart.setBackgroundColor("transparent");
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);
468
+ const labels = priceHistory.map((point) => new Date(point.timestamp).toLocaleTimeString());
469
+ const bidData = priceHistory.map((point) => point.bid);
470
+ const offerData = priceHistory.map((point) => point.offer);
471
+ const spreadData = priceHistory.map((point) => point.spread);
472
+ const volumeData = priceHistory.map((point) => point.volume);
473
+ const tradeData = priceHistory.map((point) => point.trade);
474
+ const vwapData = priceHistory.map((point) => point.vwap);
475
+ const twapData = priceHistory.map((point) => point.twap);
2105
476
  const config = {
2106
477
  type: "line",
2107
478
  data: {
@@ -2156,8 +527,8 @@ var createGetStockGraphHandler = (marketDataPrices) => {
2156
527
  tension: 0.4
2157
528
  },
2158
529
  {
2159
- label: "Volume (Normalized)",
2160
- data: normalizedVolumeData,
530
+ label: "Volume",
531
+ data: volumeData,
2161
532
  borderColor: "#007bff",
2162
533
  backgroundColor: "rgba(0, 123, 255, 0.1)",
2163
534
  fill: true,
@@ -2170,16 +541,12 @@ var createGetStockGraphHandler = (marketDataPrices) => {
2170
541
  plugins: {
2171
542
  title: {
2172
543
  display: true,
2173
- text: `${symbol} Market Data (Volume normalized to 30% of max price)`
544
+ text: `${symbol} Market Data`
2174
545
  }
2175
546
  },
2176
547
  scales: {
2177
548
  y: {
2178
- beginAtZero: false,
2179
- title: {
2180
- display: true,
2181
- text: "Price / Normalized Volume"
2182
- }
549
+ beginAtZero: false
2183
550
  }
2184
551
  }
2185
552
  }
@@ -2229,7 +596,6 @@ var createGetStockPriceHistoryHandler = (marketDataPrices) => {
2229
596
  ]
2230
597
  };
2231
598
  }
2232
- const aggregatedData = aggregateMarketData(priceHistory, 500);
2233
599
  return {
2234
600
  content: [
2235
601
  {
@@ -2237,9 +603,8 @@ var createGetStockPriceHistoryHandler = (marketDataPrices) => {
2237
603
  text: JSON.stringify(
2238
604
  {
2239
605
  symbol,
2240
- count: aggregatedData.length,
2241
- originalCount: priceHistory.length,
2242
- data: aggregatedData.map((point) => ({
606
+ count: priceHistory.length,
607
+ data: priceHistory.map((point) => ({
2243
608
  timestamp: new Date(point.timestamp).toISOString(),
2244
609
  bid: point.bid,
2245
610
  offer: point.offer,
@@ -2381,7 +746,6 @@ var handlInstNames = {
2381
746
  };
2382
747
  var createVerifyOrderHandler = (parser, verifiedOrders) => {
2383
748
  return async (args) => {
2384
- void parser;
2385
749
  try {
2386
750
  verifiedOrders.set(args.clOrdID, {
2387
751
  clOrdID: args.clOrdID,
@@ -2605,22 +969,29 @@ var createToolHandlers = (parser, verifiedOrders, pendingRequests, marketDataPri
2605
969
  executeOrder: createExecuteOrderHandler(parser, verifiedOrders, pendingRequests),
2606
970
  marketDataRequest: createMarketDataRequestHandler(parser, pendingRequests),
2607
971
  getStockGraph: createGetStockGraphHandler(marketDataPrices),
2608
- getStockPriceHistory: createGetStockPriceHistoryHandler(marketDataPrices),
2609
- technicalAnalysis: createTechnicalAnalysisHandler(marketDataPrices)
972
+ getStockPriceHistory: createGetStockPriceHistoryHandler(marketDataPrices)
2610
973
  });
2611
974
 
2612
975
  // src/utils/messageHandler.ts
2613
976
  var import_fixparser3 = require("fixparser");
2614
- function getEnumValue(enumObj, name) {
2615
- return enumObj[name] || name;
2616
- }
2617
977
  function handleMessage(message, parser, pendingRequests, marketDataPrices, maxPriceHistory, onPriceUpdate) {
2618
- void parser;
978
+ parser.logger.log({
979
+ level: "info",
980
+ message: `MCP Server received message: ${message.messageType}: ${message.description}`
981
+ });
2619
982
  const msgType = message.messageType;
2620
983
  if (msgType === import_fixparser3.Messages.MarketDataSnapshotFullRefresh || msgType === import_fixparser3.Messages.MarketDataIncrementalRefresh) {
2621
984
  const symbol = message.getField(import_fixparser3.Fields.Symbol)?.value;
985
+ parser.logger.log({
986
+ level: "info",
987
+ message: `Processing market data for symbol: ${symbol}`
988
+ });
2622
989
  const fixJson = message.toFIXJSON();
2623
990
  const entries = fixJson.Body?.NoMDEntries || [];
991
+ parser.logger.log({
992
+ level: "info",
993
+ message: `Found ${entries.length} market data entries`
994
+ });
2624
995
  const data = {
2625
996
  timestamp: Date.now(),
2626
997
  bid: 0,
@@ -2673,8 +1044,13 @@ function handleMessage(message, parser, pendingRequests, marketDataPrices, maxPr
2673
1044
  const entryType = entry.MDEntryType;
2674
1045
  const price = entry.MDEntryPx ? Number.parseFloat(entry.MDEntryPx) : 0;
2675
1046
  const size = entry.MDEntrySize ? Number.parseFloat(entry.MDEntrySize) : 0;
2676
- const enumValue = getEnumValue(import_fixparser3.MDEntryType, entryType);
2677
- switch (enumValue) {
1047
+ if (entryType === import_fixparser3.MDEntryType.Bid || entryType === import_fixparser3.MDEntryType.Offer || entryType === import_fixparser3.MDEntryType.TradeVolume) {
1048
+ parser.logger.log({
1049
+ level: "info",
1050
+ message: `Market Data Entry - Type: ${entryType}, Price: ${price}, Size: ${size}`
1051
+ });
1052
+ }
1053
+ switch (entryType) {
2678
1054
  case import_fixparser3.MDEntryType.Bid:
2679
1055
  data.bid = price;
2680
1056
  break;
@@ -2811,12 +1187,24 @@ function handleMessage(message, parser, pendingRequests, marketDataPrices, maxPr
2811
1187
  }
2812
1188
  data.spread = data.offer - data.bid;
2813
1189
  if (!marketDataPrices.has(symbol)) {
1190
+ parser.logger.log({
1191
+ level: "info",
1192
+ message: `Creating new price history array for symbol: ${symbol}`
1193
+ });
2814
1194
  marketDataPrices.set(symbol, []);
2815
1195
  }
2816
1196
  const prices = marketDataPrices.get(symbol);
2817
1197
  prices.push(data);
1198
+ parser.logger.log({
1199
+ level: "info",
1200
+ message: `Updated price history for ${symbol}. Current size: ${prices.length}`
1201
+ });
2818
1202
  if (prices.length > maxPriceHistory) {
2819
1203
  prices.splice(0, prices.length - maxPriceHistory);
1204
+ parser.logger.log({
1205
+ level: "info",
1206
+ message: `Trimmed price history for ${symbol} to ${maxPriceHistory} entries`
1207
+ });
2820
1208
  }
2821
1209
  onPriceUpdate?.(symbol, data);
2822
1210
  const mdReqID = message.getField(import_fixparser3.Fields.MDReqID)?.value;
@@ -2825,6 +1213,10 @@ function handleMessage(message, parser, pendingRequests, marketDataPrices, maxPr
2825
1213
  if (callback) {
2826
1214
  callback(message);
2827
1215
  pendingRequests.delete(mdReqID);
1216
+ parser.logger.log({
1217
+ level: "info",
1218
+ message: `Resolved market data request for ID: ${mdReqID}`
1219
+ });
2828
1220
  }
2829
1221
  }
2830
1222
  } else if (msgType === import_fixparser3.Messages.ExecutionReport) {
@@ -3063,6 +1455,10 @@ var MCPRemote = class extends MCPBase {
3063
1455
  this.marketDataPrices,
3064
1456
  this.MAX_PRICE_HISTORY
3065
1457
  );
1458
+ this.logger?.log({
1459
+ level: "info",
1460
+ message: `Market Data Prices TEST: ${JSON.stringify(this.marketDataPrices)}`
1461
+ });
3066
1462
  }
3067
1463
  });
3068
1464
  this.httpServer = (0, import_node_http.createServer)(async (req, res) => {
@@ -3083,8 +1479,7 @@ var MCPRemote = class extends MCPBase {
3083
1479
  const body = Buffer.concat(bodyChunks).toString();
3084
1480
  try {
3085
1481
  parsed = JSON.parse(body);
3086
- } catch (error) {
3087
- void error;
1482
+ } catch (err) {
3088
1483
  res.writeHead(400);
3089
1484
  res.end(JSON.stringify({ error: "Invalid JSON" }));
3090
1485
  return;