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.
@@ -0,0 +1,3194 @@
1
+ // src/MCPLocal.ts
2
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
3
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
+ import { z } from "zod";
5
+
6
+ // src/MCPBase.ts
7
+ var MCPBase = class {
8
+ /**
9
+ * Optional logger instance for diagnostics and output.
10
+ * @protected
11
+ */
12
+ logger;
13
+ /**
14
+ * FIXParser instance, set during plugin register().
15
+ * @protected
16
+ */
17
+ parser;
18
+ /**
19
+ * Called when server is setup and listening.
20
+ * @protected
21
+ */
22
+ onReady = void 0;
23
+ /**
24
+ * Map to store verified orders before execution
25
+ * @protected
26
+ */
27
+ verifiedOrders = /* @__PURE__ */ new Map();
28
+ /**
29
+ * Map to store pending market data requests
30
+ * @protected
31
+ */
32
+ pendingRequests = /* @__PURE__ */ new Map();
33
+ /**
34
+ * Map to store market data prices
35
+ * @protected
36
+ */
37
+ marketDataPrices = /* @__PURE__ */ new Map();
38
+ /**
39
+ * Maximum number of price history entries to keep per symbol
40
+ * @protected
41
+ */
42
+ MAX_PRICE_HISTORY = 1e5;
43
+ constructor({ logger, onReady }) {
44
+ this.logger = logger;
45
+ this.onReady = onReady;
46
+ }
47
+ };
48
+
49
+ // src/schemas/schemas.ts
50
+ var toolSchemas = {
51
+ parse: {
52
+ description: "Parses a FIX message and describes it in plain language",
53
+ schema: {
54
+ type: "object",
55
+ properties: {
56
+ fixString: { type: "string" }
57
+ },
58
+ required: ["fixString"]
59
+ }
60
+ },
61
+ parseToJSON: {
62
+ description: "Parses a FIX message into JSON",
63
+ schema: {
64
+ type: "object",
65
+ properties: {
66
+ fixString: { type: "string" }
67
+ },
68
+ required: ["fixString"]
69
+ }
70
+ },
71
+ verifyOrder: {
72
+ description: "Verifies order parameters before execution. verifyOrder must be called before executeOrder.",
73
+ schema: {
74
+ type: "object",
75
+ properties: {
76
+ clOrdID: { type: "string" },
77
+ handlInst: {
78
+ type: "string",
79
+ enum: ["1", "2", "3"],
80
+ description: "Handling Instructions: 1=Automated Execution No Intervention, 2=Automated Execution Intervention OK, 3=Manual Order"
81
+ },
82
+ quantity: { type: "string" },
83
+ price: { type: "string" },
84
+ ordType: {
85
+ type: "string",
86
+ enum: [
87
+ "1",
88
+ "2",
89
+ "3",
90
+ "4",
91
+ "5",
92
+ "6",
93
+ "7",
94
+ "8",
95
+ "9",
96
+ "A",
97
+ "B",
98
+ "C",
99
+ "D",
100
+ "E",
101
+ "F",
102
+ "G",
103
+ "H",
104
+ "I",
105
+ "J",
106
+ "K",
107
+ "L",
108
+ "M",
109
+ "P",
110
+ "Q",
111
+ "R",
112
+ "S"
113
+ ],
114
+ description: "Order Type: 1=Market, 2=Limit, 3=Stop, 4=StopLimit, 5=MarketOnClose, 6=WithOrWithout, 7=LimitOrBetter, 8=LimitWithOrWithout, 9=OnBasis, A=OnClose, B=LimitOnClose, C=ForexMarket, D=PreviouslyQuoted, E=PreviouslyIndicated, F=ForexLimit, G=ForexSwap, H=ForexPreviouslyQuoted, I=Funari, J=MarketIfTouched, K=MarketWithLeftOverAsLimit, L=PreviousFundValuationPoint, M=NextFundValuationPoint, P=Pegged, Q=CounterOrderSelection, R=StopOnBidOrOffer, S=StopLimitOnBidOrOffer"
115
+ },
116
+ side: {
117
+ type: "string",
118
+ enum: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H"],
119
+ description: "Side: 1=Buy, 2=Sell, 3=BuyMinus, 4=SellPlus, 5=SellShort, 6=SellShortExempt, 7=Undisclosed, 8=Cross, 9=CrossShort, A=CrossShortExempt, B=AsDefined, C=Opposite, D=Subscribe, E=Redeem, F=Lend, G=Borrow, H=SellUndisclosed"
120
+ },
121
+ symbol: { type: "string" },
122
+ timeInForce: {
123
+ type: "string",
124
+ enum: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C"],
125
+ description: "Time In Force: 0=Day, 1=GoodTillCancel, 2=AtTheOpening, 3=ImmediateOrCancel, 4=FillOrKill, 5=GoodTillCrossing, 6=GoodTillDate, 7=AtTheClose, 8=GoodThroughCrossing, 9=AtCrossing, A=GoodForTime, B=GoodForAuction, C=GoodForMonth"
126
+ }
127
+ },
128
+ required: ["clOrdID", "handlInst", "quantity", "price", "ordType", "side", "symbol", "timeInForce"]
129
+ }
130
+ },
131
+ executeOrder: {
132
+ description: "Executes a verified order. verifyOrder must be called before executeOrder.",
133
+ schema: {
134
+ type: "object",
135
+ properties: {
136
+ clOrdID: { type: "string" },
137
+ handlInst: {
138
+ type: "string",
139
+ enum: ["1", "2", "3"],
140
+ description: "Handling Instructions: 1=Automated Execution No Intervention, 2=Automated Execution Intervention OK, 3=Manual Order"
141
+ },
142
+ quantity: { type: "string" },
143
+ price: { type: "string" },
144
+ ordType: {
145
+ type: "string",
146
+ enum: [
147
+ "1",
148
+ "2",
149
+ "3",
150
+ "4",
151
+ "5",
152
+ "6",
153
+ "7",
154
+ "8",
155
+ "9",
156
+ "A",
157
+ "B",
158
+ "C",
159
+ "D",
160
+ "E",
161
+ "F",
162
+ "G",
163
+ "H",
164
+ "I",
165
+ "J",
166
+ "K",
167
+ "L",
168
+ "M",
169
+ "P",
170
+ "Q",
171
+ "R",
172
+ "S"
173
+ ],
174
+ description: "Order Type: 1=Market, 2=Limit, 3=Stop, 4=StopLimit, 5=MarketOnClose, 6=WithOrWithout, 7=LimitOrBetter, 8=LimitWithOrWithout, 9=OnBasis, A=OnClose, B=LimitOnClose, C=ForexMarket, D=PreviouslyQuoted, E=PreviouslyIndicated, F=ForexLimit, G=ForexSwap, H=ForexPreviouslyQuoted, I=Funari, J=MarketIfTouched, K=MarketWithLeftOverAsLimit, L=PreviousFundValuationPoint, M=NextFundValuationPoint, P=Pegged, Q=CounterOrderSelection, R=StopOnBidOrOffer, S=StopLimitOnBidOrOffer"
175
+ },
176
+ side: {
177
+ type: "string",
178
+ enum: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H"],
179
+ description: "Side: 1=Buy, 2=Sell, 3=BuyMinus, 4=SellPlus, 5=SellShort, 6=SellShortExempt, 7=Undisclosed, 8=Cross, 9=CrossShort, A=CrossShortExempt, B=AsDefined, C=Opposite, D=Subscribe, E=Redeem, F=Lend, G=Borrow, H=SellUndisclosed"
180
+ },
181
+ symbol: { type: "string" },
182
+ timeInForce: {
183
+ type: "string",
184
+ enum: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C"],
185
+ description: "Time In Force: 0=Day, 1=GoodTillCancel, 2=AtTheOpening, 3=ImmediateOrCancel, 4=FillOrKill, 5=GoodTillCrossing, 6=GoodTillDate, 7=AtTheClose, 8=GoodThroughCrossing, 9=AtCrossing, A=GoodForTime, B=GoodForAuction, C=GoodForMonth"
186
+ }
187
+ },
188
+ required: ["clOrdID", "handlInst", "quantity", "price", "ordType", "side", "symbol", "timeInForce"]
189
+ }
190
+ },
191
+ marketDataRequest: {
192
+ description: "Requests market data for specified symbols",
193
+ schema: {
194
+ type: "object",
195
+ properties: {
196
+ mdUpdateType: {
197
+ type: "string",
198
+ enum: ["0", "1"],
199
+ description: "Market Data Update Type: 0=Full Refresh, 1=Incremental Refresh"
200
+ },
201
+ symbols: { type: "array", items: { type: "string" } },
202
+ mdReqID: { type: "string" },
203
+ subscriptionRequestType: {
204
+ type: "string",
205
+ enum: ["0", "1", "2"],
206
+ description: "Subscription Request Type: 0=Snapshot, 1=Snapshot + Updates, 2=Disable Previous Snapshot + Update Request"
207
+ },
208
+ mdEntryTypes: {
209
+ type: "array",
210
+ items: {
211
+ type: "string",
212
+ enum: [
213
+ "0",
214
+ "1",
215
+ "2",
216
+ "3",
217
+ "4",
218
+ "5",
219
+ "6",
220
+ "7",
221
+ "8",
222
+ "9",
223
+ "A",
224
+ "B",
225
+ "C",
226
+ "D",
227
+ "E",
228
+ "F",
229
+ "G",
230
+ "H",
231
+ "I",
232
+ "J",
233
+ "K",
234
+ "L",
235
+ "M",
236
+ "N",
237
+ "O",
238
+ "P",
239
+ "Q",
240
+ "R",
241
+ "S",
242
+ "T",
243
+ "U",
244
+ "V",
245
+ "W",
246
+ "X",
247
+ "Y",
248
+ "Z"
249
+ ]
250
+ },
251
+ description: "Market Data Entry Types: 0=Bid, 1=Offer, 2=Trade, 3=Index Value, 4=Opening Price, 5=Closing Price, 6=Settlement Price, 7=High Price, 8=Low Price, 9=Trade Volume, A=Open Interest, B=Simulated Sell Price, C=Simulated Buy Price, D=Empty Book, E=Session High Bid, F=Session Low Offer, G=Fixing Price, H=Electronic Volume, I=Threshold Limits and Price Band Variation, J=Clearing Price, K=Open Interest Change, L=Last Trade Price, M=Last Trade Volume, N=Last Trade Time, O=Last Trade Tick, P=Last Trade Exchange, Q=Last Trade ID, R=Last Trade Side, S=Last Trade Price Change, T=Last Trade Price Change Percent, U=Last Trade Price Change Basis Points, V=Last Trade Price Change Points, W=Last Trade Price Change Ticks, X=Last Trade Price Change Ticks Percent, Y=Last Trade Price Change Ticks Basis Points, Z=Last Trade Price Change Ticks Points"
252
+ }
253
+ },
254
+ required: ["mdUpdateType", "symbols", "mdReqID", "subscriptionRequestType"]
255
+ }
256
+ },
257
+ getStockGraph: {
258
+ description: "Generates a price chart for a given symbol",
259
+ schema: {
260
+ type: "object",
261
+ properties: {
262
+ symbol: { type: "string" }
263
+ },
264
+ required: ["symbol"]
265
+ }
266
+ },
267
+ getStockPriceHistory: {
268
+ description: "Returns price history for a given symbol",
269
+ schema: {
270
+ type: "object",
271
+ properties: {
272
+ symbol: { type: "string" }
273
+ },
274
+ required: ["symbol"]
275
+ }
276
+ },
277
+ technicalAnalysis: {
278
+ description: "Performs comprehensive technical analysis on market data for a given symbol, including indicators like SMA, EMA, RSI, Bollinger Bands, and trading signals",
279
+ schema: {
280
+ type: "object",
281
+ properties: {
282
+ symbol: {
283
+ type: "string",
284
+ description: "The trading symbol to analyze (e.g., AAPL, MSFT, EURUSD)"
285
+ }
286
+ },
287
+ required: ["symbol"]
288
+ }
289
+ }
290
+ };
291
+
292
+ // src/tools/analytics.ts
293
+ function sum(numbers) {
294
+ return numbers.reduce((acc, val) => acc + val, 0);
295
+ }
296
+ var TechnicalAnalyzer = class {
297
+ prices;
298
+ volumes;
299
+ highs;
300
+ lows;
301
+ constructor(data) {
302
+ this.prices = data.map((d) => d.trade > 0 ? d.trade : d.midPrice);
303
+ this.volumes = data.map((d) => d.volume);
304
+ this.highs = data.map((d) => d.tradingSessionHighPrice > 0 ? d.tradingSessionHighPrice : d.trade);
305
+ this.lows = data.map((d) => d.tradingSessionLowPrice > 0 ? d.tradingSessionLowPrice : d.trade);
306
+ }
307
+ // Calculate Simple Moving Average
308
+ calculateSMA(data, period) {
309
+ const sma = [];
310
+ for (let i = period - 1; i < data.length; i++) {
311
+ const sum2 = data.slice(i - period + 1, i + 1).reduce((a, b) => a + b, 0);
312
+ sma.push(sum2 / period);
313
+ }
314
+ return sma;
315
+ }
316
+ // Calculate Exponential Moving Average
317
+ calculateEMA(data, period) {
318
+ const multiplier = 2 / (period + 1);
319
+ const ema = [data[0]];
320
+ for (let i = 1; i < data.length; i++) {
321
+ ema.push(data[i] * multiplier + ema[i - 1] * (1 - multiplier));
322
+ }
323
+ return ema;
324
+ }
325
+ // Calculate RSI
326
+ calculateRSI(data, period = 14) {
327
+ if (data.length < period + 1) return [];
328
+ const changes = [];
329
+ for (let i = 1; i < data.length; i++) {
330
+ changes.push(data[i] - data[i - 1]);
331
+ }
332
+ const gains = changes.map((change) => change > 0 ? change : 0);
333
+ const losses = changes.map((change) => change < 0 ? Math.abs(change) : 0);
334
+ let avgGain = gains.slice(0, period).reduce((a, b) => a + b, 0) / period;
335
+ let avgLoss = losses.slice(0, period).reduce((a, b) => a + b, 0) / period;
336
+ const rsi = [];
337
+ for (let i = period; i < changes.length; i++) {
338
+ const rs = avgGain / avgLoss;
339
+ rsi.push(100 - 100 / (1 + rs));
340
+ avgGain = (avgGain * (period - 1) + gains[i]) / period;
341
+ avgLoss = (avgLoss * (period - 1) + losses[i]) / period;
342
+ }
343
+ return rsi;
344
+ }
345
+ // Calculate Bollinger Bands
346
+ calculateBollingerBands(data, period = 20, stdDev = 2) {
347
+ if (data.length < period) return [];
348
+ const sma = this.calculateSMA(data, period);
349
+ const bands = [];
350
+ for (let i = 0; i < sma.length; i++) {
351
+ const dataSlice = data.slice(i, i + period);
352
+ const mean = sma[i];
353
+ const variance = dataSlice.reduce((sum2, price) => sum2 + (price - mean) ** 2, 0) / period;
354
+ const standardDeviation = Math.sqrt(variance);
355
+ const upper = mean + standardDeviation * stdDev;
356
+ const lower = mean - standardDeviation * stdDev;
357
+ bands.push({
358
+ upper,
359
+ middle: mean,
360
+ lower,
361
+ bandwidth: (upper - lower) / mean * 100,
362
+ percentB: (data[i] - lower) / (upper - lower) * 100
363
+ });
364
+ }
365
+ return bands;
366
+ }
367
+ // Calculate maximum drawdown
368
+ calculateMaxDrawdown(prices) {
369
+ let maxPrice = prices[0];
370
+ let maxDrawdown = 0;
371
+ for (let i = 1; i < prices.length; i++) {
372
+ if (prices[i] > maxPrice) {
373
+ maxPrice = prices[i];
374
+ }
375
+ const drawdown = (maxPrice - prices[i]) / maxPrice;
376
+ if (drawdown > maxDrawdown) {
377
+ maxDrawdown = drawdown;
378
+ }
379
+ }
380
+ return maxDrawdown;
381
+ }
382
+ // Calculate Average True Range (ATR)
383
+ calculateAtr(prices, highs, lows) {
384
+ if (prices.length < 2) return [];
385
+ const trueRanges = [];
386
+ for (let i = 1; i < prices.length; i++) {
387
+ const high = highs[i] || prices[i];
388
+ const low = lows[i] || prices[i];
389
+ const prevClose = prices[i - 1];
390
+ const tr1 = high - low;
391
+ const tr2 = Math.abs(high - prevClose);
392
+ const tr3 = Math.abs(low - prevClose);
393
+ trueRanges.push(Math.max(tr1, tr2, tr3));
394
+ }
395
+ const atr = [];
396
+ if (trueRanges.length >= 14) {
397
+ let sum2 = trueRanges.slice(0, 14).reduce((a, b) => a + b, 0);
398
+ atr.push(sum2 / 14);
399
+ for (let i = 14; i < trueRanges.length; i++) {
400
+ sum2 = sum2 - trueRanges[i - 14] + trueRanges[i];
401
+ atr.push(sum2 / 14);
402
+ }
403
+ }
404
+ return atr;
405
+ }
406
+ // Calculate maximum consecutive losses
407
+ calculateMaxConsecutiveLosses(prices) {
408
+ let maxConsecutive = 0;
409
+ let currentConsecutive = 0;
410
+ for (let i = 1; i < prices.length; i++) {
411
+ if (prices[i] < prices[i - 1]) {
412
+ currentConsecutive++;
413
+ maxConsecutive = Math.max(maxConsecutive, currentConsecutive);
414
+ } else {
415
+ currentConsecutive = 0;
416
+ }
417
+ }
418
+ return maxConsecutive;
419
+ }
420
+ // Calculate win rate
421
+ calculateWinRate(prices) {
422
+ let wins = 0;
423
+ let total = 0;
424
+ for (let i = 1; i < prices.length; i++) {
425
+ if (prices[i] !== prices[i - 1]) {
426
+ total++;
427
+ if (prices[i] > prices[i - 1]) {
428
+ wins++;
429
+ }
430
+ }
431
+ }
432
+ return total > 0 ? wins / total : 0;
433
+ }
434
+ // Calculate profit factor
435
+ calculateProfitFactor(prices) {
436
+ let grossProfit = 0;
437
+ let grossLoss = 0;
438
+ for (let i = 1; i < prices.length; i++) {
439
+ const change = prices[i] - prices[i - 1];
440
+ if (change > 0) {
441
+ grossProfit += change;
442
+ } else {
443
+ grossLoss += Math.abs(change);
444
+ }
445
+ }
446
+ return grossLoss > 0 ? grossProfit / grossLoss : 0;
447
+ }
448
+ // Calculate Weighted Moving Average
449
+ calculateWma(data, period) {
450
+ const wma = [];
451
+ const weights = Array.from({ length: period }, (_, i) => i + 1);
452
+ const weightSum = weights.reduce((a, b) => a + b, 0);
453
+ for (let i = period - 1; i < data.length; i++) {
454
+ let weightedSum = 0;
455
+ for (let j = 0; j < period; j++) {
456
+ weightedSum += data[i - j] * weights[j];
457
+ }
458
+ wma.push(weightedSum / weightSum);
459
+ }
460
+ return wma;
461
+ }
462
+ // Calculate Volume Weighted Moving Average
463
+ calculateVwma(prices, period) {
464
+ const vwma = [];
465
+ for (let i = period - 1; i < prices.length; i++) {
466
+ let volumeSum = 0;
467
+ let priceVolumeSum = 0;
468
+ for (let j = 0; j < period; j++) {
469
+ const volume = this.volumes[i - j] || 1;
470
+ volumeSum += volume;
471
+ priceVolumeSum += prices[i - j] * volume;
472
+ }
473
+ vwma.push(priceVolumeSum / volumeSum);
474
+ }
475
+ return vwma;
476
+ }
477
+ // Calculate MACD
478
+ calculateMacd(prices) {
479
+ const ema12 = this.calculateEMA(prices, 12);
480
+ const ema26 = this.calculateEMA(prices, 26);
481
+ const macd = [];
482
+ const macdLine = [];
483
+ for (let i = 0; i < Math.min(ema12.length, ema26.length); i++) {
484
+ macdLine.push(ema12[i] - ema26[i]);
485
+ }
486
+ const signalLine = this.calculateEMA(macdLine, 9);
487
+ for (let i = 0; i < Math.min(macdLine.length, signalLine.length); i++) {
488
+ macd.push({
489
+ macd: macdLine[i],
490
+ signal: signalLine[i],
491
+ histogram: macdLine[i] - signalLine[i]
492
+ });
493
+ }
494
+ return macd;
495
+ }
496
+ // Calculate ADX (Average Directional Index)
497
+ calculateAdx(prices, highs, lows) {
498
+ if (prices.length < 14) return [];
499
+ const period = 14;
500
+ const adx = [];
501
+ const trueRanges = [];
502
+ const plusDM = [];
503
+ const minusDM = [];
504
+ trueRanges.push(highs[0] - lows[0]);
505
+ plusDM.push(0);
506
+ minusDM.push(0);
507
+ for (let i = 1; i < prices.length; i++) {
508
+ const high = highs[i] || prices[i];
509
+ const low = lows[i] || prices[i];
510
+ const prevHigh = highs[i - 1] || prices[i - 1];
511
+ const prevLow = lows[i - 1] || prices[i - 1];
512
+ const prevClose = prices[i - 1];
513
+ const tr1 = high - low;
514
+ const tr2 = Math.abs(high - prevClose);
515
+ const tr3 = Math.abs(low - prevClose);
516
+ trueRanges.push(Math.max(tr1, tr2, tr3));
517
+ const upMove = high - prevHigh;
518
+ const downMove = prevLow - low;
519
+ if (upMove > downMove && upMove > 0) {
520
+ plusDM.push(upMove);
521
+ minusDM.push(0);
522
+ } else if (downMove > upMove && downMove > 0) {
523
+ plusDM.push(0);
524
+ minusDM.push(downMove);
525
+ } else {
526
+ plusDM.push(0);
527
+ minusDM.push(0);
528
+ }
529
+ }
530
+ const smoothedTR = [];
531
+ const smoothedPlusDM = [];
532
+ const smoothedMinusDM = [];
533
+ let sumTR = 0;
534
+ let sumPlusDM = 0;
535
+ let sumMinusDM = 0;
536
+ for (let i = 0; i < period; i++) {
537
+ sumTR += trueRanges[i];
538
+ sumPlusDM += plusDM[i];
539
+ sumMinusDM += minusDM[i];
540
+ }
541
+ smoothedTR.push(sumTR);
542
+ smoothedPlusDM.push(sumPlusDM);
543
+ smoothedMinusDM.push(sumMinusDM);
544
+ for (let i = period; i < trueRanges.length; i++) {
545
+ const newTR = smoothedTR[smoothedTR.length - 1] - smoothedTR[smoothedTR.length - 1] / period + trueRanges[i];
546
+ const newPlusDM = smoothedPlusDM[smoothedPlusDM.length - 1] - smoothedPlusDM[smoothedPlusDM.length - 1] / period + plusDM[i];
547
+ const newMinusDM = smoothedMinusDM[smoothedMinusDM.length - 1] - smoothedMinusDM[smoothedMinusDM.length - 1] / period + minusDM[i];
548
+ smoothedTR.push(newTR);
549
+ smoothedPlusDM.push(newPlusDM);
550
+ smoothedMinusDM.push(newMinusDM);
551
+ }
552
+ const plusDI = [];
553
+ const minusDI = [];
554
+ for (let i = 0; i < smoothedTR.length; i++) {
555
+ plusDI.push(smoothedPlusDM[i] / smoothedTR[i] * 100);
556
+ minusDI.push(smoothedMinusDM[i] / smoothedTR[i] * 100);
557
+ }
558
+ const dx = [];
559
+ for (let i = 0; i < plusDI.length; i++) {
560
+ const diSum = plusDI[i] + minusDI[i];
561
+ const diDiff = Math.abs(plusDI[i] - minusDI[i]);
562
+ dx.push(diSum > 0 ? diDiff / diSum * 100 : 0);
563
+ }
564
+ if (dx.length < period) return [];
565
+ let sumDX = 0;
566
+ for (let i = 0; i < period; i++) {
567
+ sumDX += dx[i];
568
+ }
569
+ adx.push(sumDX / period);
570
+ for (let i = period; i < dx.length; i++) {
571
+ const newADX = adx[adx.length - 1] - adx[adx.length - 1] / period + dx[i];
572
+ adx.push(newADX);
573
+ }
574
+ return adx;
575
+ }
576
+ // Calculate DMI (Directional Movement Index)
577
+ calculateDmi(prices, highs, lows) {
578
+ if (prices.length < 14) return [];
579
+ const period = 14;
580
+ const dmi = [];
581
+ const trueRanges = [];
582
+ const plusDM = [];
583
+ const minusDM = [];
584
+ trueRanges.push(highs[0] - lows[0]);
585
+ plusDM.push(0);
586
+ minusDM.push(0);
587
+ for (let i = 1; i < prices.length; i++) {
588
+ const high = highs[i] || prices[i];
589
+ const low = lows[i] || prices[i];
590
+ const prevHigh = highs[i - 1] || prices[i - 1];
591
+ const prevLow = lows[i - 1] || prices[i - 1];
592
+ const prevClose = prices[i - 1];
593
+ const tr1 = high - low;
594
+ const tr2 = Math.abs(high - prevClose);
595
+ const tr3 = Math.abs(low - prevClose);
596
+ trueRanges.push(Math.max(tr1, tr2, tr3));
597
+ const upMove = high - prevHigh;
598
+ const downMove = prevLow - low;
599
+ if (upMove > downMove && upMove > 0) {
600
+ plusDM.push(upMove);
601
+ minusDM.push(0);
602
+ } else if (downMove > upMove && downMove > 0) {
603
+ plusDM.push(0);
604
+ minusDM.push(downMove);
605
+ } else {
606
+ plusDM.push(0);
607
+ minusDM.push(0);
608
+ }
609
+ }
610
+ const smoothedTR = [];
611
+ const smoothedPlusDM = [];
612
+ const smoothedMinusDM = [];
613
+ let sumTR = 0;
614
+ let sumPlusDM = 0;
615
+ let sumMinusDM = 0;
616
+ for (let i = 0; i < period; i++) {
617
+ sumTR += trueRanges[i];
618
+ sumPlusDM += plusDM[i];
619
+ sumMinusDM += minusDM[i];
620
+ }
621
+ smoothedTR.push(sumTR);
622
+ smoothedPlusDM.push(sumPlusDM);
623
+ smoothedMinusDM.push(sumMinusDM);
624
+ for (let i = period; i < trueRanges.length; i++) {
625
+ const newTR = smoothedTR[smoothedTR.length - 1] - smoothedTR[smoothedTR.length - 1] / period + trueRanges[i];
626
+ const newPlusDM = smoothedPlusDM[smoothedPlusDM.length - 1] - smoothedPlusDM[smoothedPlusDM.length - 1] / period + plusDM[i];
627
+ const newMinusDM = smoothedMinusDM[smoothedMinusDM.length - 1] - smoothedMinusDM[smoothedMinusDM.length - 1] / period + minusDM[i];
628
+ smoothedTR.push(newTR);
629
+ smoothedPlusDM.push(newPlusDM);
630
+ smoothedMinusDM.push(newMinusDM);
631
+ }
632
+ const plusDI = [];
633
+ const minusDI = [];
634
+ for (let i = 0; i < smoothedTR.length; i++) {
635
+ plusDI.push(smoothedPlusDM[i] / smoothedTR[i] * 100);
636
+ minusDI.push(smoothedMinusDM[i] / smoothedTR[i] * 100);
637
+ }
638
+ const dx = [];
639
+ for (let i = 0; i < plusDI.length; i++) {
640
+ const diSum = plusDI[i] + minusDI[i];
641
+ const diDiff = Math.abs(plusDI[i] - minusDI[i]);
642
+ dx.push(diSum > 0 ? diDiff / diSum * 100 : 0);
643
+ }
644
+ if (dx.length < period) return [];
645
+ const adx = [];
646
+ let sumDX = 0;
647
+ for (let i = 0; i < period; i++) {
648
+ sumDX += dx[i];
649
+ }
650
+ adx.push(sumDX / period);
651
+ for (let i = period; i < dx.length; i++) {
652
+ const newADX = adx[adx.length - 1] - adx[adx.length - 1] / period + dx[i];
653
+ adx.push(newADX);
654
+ }
655
+ for (let i = 0; i < adx.length; i++) {
656
+ dmi.push({
657
+ plusDI: plusDI[i + period - 1] || 0,
658
+ minusDI: minusDI[i + period - 1] || 0,
659
+ adx: adx[i]
660
+ });
661
+ }
662
+ return dmi;
663
+ }
664
+ // Calculate Ichimoku Cloud
665
+ calculateIchimoku(prices, highs, lows) {
666
+ if (prices.length < 52) return [];
667
+ const ichimoku = [];
668
+ const tenkanSen = [];
669
+ for (let i = 8; i < prices.length; i++) {
670
+ const periodHigh = Math.max(...highs.slice(i - 8, i + 1));
671
+ const periodLow = Math.min(...lows.slice(i - 8, i + 1));
672
+ tenkanSen.push((periodHigh + periodLow) / 2);
673
+ }
674
+ const kijunSen = [];
675
+ for (let i = 25; i < prices.length; i++) {
676
+ const periodHigh = Math.max(...highs.slice(i - 25, i + 1));
677
+ const periodLow = Math.min(...lows.slice(i - 25, i + 1));
678
+ kijunSen.push((periodHigh + periodLow) / 2);
679
+ }
680
+ const senkouSpanA = [];
681
+ for (let i = 0; i < Math.min(tenkanSen.length, kijunSen.length); i++) {
682
+ senkouSpanA.push((tenkanSen[i] + kijunSen[i]) / 2);
683
+ }
684
+ const senkouSpanB = [];
685
+ for (let i = 51; i < prices.length; i++) {
686
+ const periodHigh = Math.max(...highs.slice(i - 51, i + 1));
687
+ const periodLow = Math.min(...lows.slice(i - 51, i + 1));
688
+ senkouSpanB.push((periodHigh + periodLow) / 2);
689
+ }
690
+ const chikouSpan = [];
691
+ for (let i = 26; i < prices.length; i++) {
692
+ chikouSpan.push(prices[i - 26]);
693
+ }
694
+ const minLength = Math.min(
695
+ tenkanSen.length,
696
+ kijunSen.length,
697
+ senkouSpanA.length,
698
+ senkouSpanB.length,
699
+ chikouSpan.length
700
+ );
701
+ for (let i = 0; i < minLength; i++) {
702
+ ichimoku.push({
703
+ tenkan: tenkanSen[i],
704
+ kijun: kijunSen[i],
705
+ senkouA: senkouSpanA[i],
706
+ senkouB: senkouSpanB[i],
707
+ chikou: chikouSpan[i]
708
+ });
709
+ }
710
+ return ichimoku;
711
+ }
712
+ // Calculate Parabolic SAR
713
+ calculateParabolicSAR(prices, highs, lows) {
714
+ if (prices.length < 2) return [];
715
+ const sar = [];
716
+ const accelerationFactor = 0.02;
717
+ const maximumAcceleration = 0.2;
718
+ let currentSAR = lows[0];
719
+ let isLong = true;
720
+ let af = accelerationFactor;
721
+ let ep = highs[0];
722
+ sar.push(currentSAR);
723
+ for (let i = 1; i < prices.length; i++) {
724
+ const high = highs[i] || prices[i];
725
+ const low = lows[i] || prices[i];
726
+ if (isLong) {
727
+ if (low < currentSAR) {
728
+ isLong = false;
729
+ currentSAR = ep;
730
+ ep = low;
731
+ af = accelerationFactor;
732
+ } else {
733
+ if (high > ep) {
734
+ ep = high;
735
+ af = Math.min(af + accelerationFactor, maximumAcceleration);
736
+ }
737
+ currentSAR = currentSAR + af * (ep - currentSAR);
738
+ if (i > 0) {
739
+ const prevLow = lows[i - 1] || prices[i - 1];
740
+ currentSAR = Math.min(currentSAR, prevLow);
741
+ }
742
+ }
743
+ } else {
744
+ if (high > currentSAR) {
745
+ isLong = true;
746
+ currentSAR = ep;
747
+ ep = high;
748
+ af = accelerationFactor;
749
+ } else {
750
+ if (low < ep) {
751
+ ep = low;
752
+ af = Math.min(af + accelerationFactor, maximumAcceleration);
753
+ }
754
+ currentSAR = currentSAR + af * (ep - currentSAR);
755
+ if (i > 0) {
756
+ const prevHigh = highs[i - 1] || prices[i - 1];
757
+ currentSAR = Math.max(currentSAR, prevHigh);
758
+ }
759
+ }
760
+ }
761
+ sar.push(currentSAR);
762
+ }
763
+ return sar;
764
+ }
765
+ // Calculate Stochastic
766
+ calculateStochastic(prices, highs, lows) {
767
+ const stochastic = [];
768
+ const period = 14;
769
+ const smoothK = 3;
770
+ const smoothD = 3;
771
+ if (prices.length < period) return [];
772
+ const percentK = [];
773
+ for (let i = period - 1; i < prices.length; i++) {
774
+ const high = Math.max(...highs.slice(i - period + 1, i + 1));
775
+ const low = Math.min(...lows.slice(i - period + 1, i + 1));
776
+ const close = prices[i];
777
+ const k = (close - low) / (high - low) * 100;
778
+ percentK.push(k);
779
+ }
780
+ const smoothedK = [];
781
+ for (let i = smoothK - 1; i < percentK.length; i++) {
782
+ const sum2 = percentK.slice(i - smoothK + 1, i + 1).reduce((a, b) => a + b, 0);
783
+ smoothedK.push(sum2 / smoothK);
784
+ }
785
+ for (let i = smoothD - 1; i < smoothedK.length; i++) {
786
+ const sum2 = smoothedK.slice(i - smoothD + 1, i + 1).reduce((a, b) => a + b, 0);
787
+ const d = sum2 / smoothD;
788
+ stochastic.push({
789
+ k: smoothedK[i],
790
+ d
791
+ });
792
+ }
793
+ return stochastic;
794
+ }
795
+ // Calculate CCI
796
+ calculateCci(prices, highs, lows) {
797
+ const cci = [];
798
+ const period = 20;
799
+ if (prices.length < period) return [];
800
+ for (let i = period - 1; i < prices.length; i++) {
801
+ const slice = prices.slice(i - period + 1, i + 1);
802
+ const typicalPrices = slice.map((price, idx) => {
803
+ const high = highs[i - period + 1 + idx] || price;
804
+ const low = lows[i - period + 1 + idx] || price;
805
+ return (high + low + price) / 3;
806
+ });
807
+ const sma = typicalPrices.reduce((a, b) => a + b, 0) / period;
808
+ const meanDeviation = typicalPrices.reduce((sum2, tp) => sum2 + Math.abs(tp - sma), 0) / period;
809
+ const currentTP = (highs[i] + lows[i] + prices[i]) / 3;
810
+ const cciValue = meanDeviation !== 0 ? (currentTP - sma) / (0.015 * meanDeviation) : 0;
811
+ cci.push(cciValue);
812
+ }
813
+ return cci;
814
+ }
815
+ // Calculate Rate of Change
816
+ calculateRoc(prices) {
817
+ const roc = [];
818
+ for (let i = 10; i < prices.length; i++) {
819
+ roc.push((prices[i] - prices[i - 10]) / prices[i - 10] * 100);
820
+ }
821
+ return roc;
822
+ }
823
+ // Calculate Williams %R
824
+ calculateWilliamsR(prices) {
825
+ const williamsR = [];
826
+ const period = 14;
827
+ if (prices.length < period) return [];
828
+ for (let i = period - 1; i < prices.length; i++) {
829
+ const slice = prices.slice(i - period + 1, i + 1);
830
+ const high = Math.max(...slice);
831
+ const low = Math.min(...slice);
832
+ const close = prices[i];
833
+ const wr = (high - close) / (high - low) * -100;
834
+ williamsR.push(wr);
835
+ }
836
+ return williamsR;
837
+ }
838
+ // Calculate Momentum
839
+ calculateMomentum(prices) {
840
+ const momentum = [];
841
+ for (let i = 10; i < prices.length; i++) {
842
+ momentum.push(prices[i] - prices[i - 10]);
843
+ }
844
+ return momentum;
845
+ }
846
+ // Calculate Keltner Channels
847
+ calculateKeltnerChannels(prices, highs, lows) {
848
+ const keltner = [];
849
+ const period = 20;
850
+ const multiplier = 2;
851
+ if (prices.length < period) return [];
852
+ const ema = this.calculateEMA(prices, period);
853
+ const atr = this.calculateAtr(prices, highs, lows);
854
+ for (let i = 0; i < Math.min(ema.length, atr.length); i++) {
855
+ const middle = ema[i];
856
+ const atrValue = atr[i];
857
+ keltner.push({
858
+ upper: middle + multiplier * atrValue,
859
+ middle,
860
+ lower: middle - multiplier * atrValue
861
+ });
862
+ }
863
+ return keltner;
864
+ }
865
+ // Calculate Donchian Channels
866
+ calculateDonchianChannels(prices) {
867
+ const donchian = [];
868
+ for (let i = 20; i < prices.length; i++) {
869
+ const slice = prices.slice(i - 20, i);
870
+ donchian.push({
871
+ upper: Math.max(...slice),
872
+ middle: (Math.max(...slice) + Math.min(...slice)) / 2,
873
+ lower: Math.min(...slice)
874
+ });
875
+ }
876
+ return donchian;
877
+ }
878
+ // Calculate Chaikin Volatility
879
+ calculateChaikinVolatility(prices, highs, lows) {
880
+ const volatility = [];
881
+ const period = 10;
882
+ if (prices.length < period * 2) return [];
883
+ const highLowRange = [];
884
+ for (let i = 0; i < prices.length; i++) {
885
+ const high = highs[i] || prices[i];
886
+ const low = lows[i] || prices[i];
887
+ highLowRange.push(high - low);
888
+ }
889
+ const emaRange = this.calculateEMA(highLowRange, period);
890
+ for (let i = period; i < emaRange.length; i++) {
891
+ const currentEMA = emaRange[i];
892
+ const pastEMA = emaRange[i - period];
893
+ const volatilityValue = pastEMA !== 0 ? (currentEMA - pastEMA) / pastEMA * 100 : 0;
894
+ volatility.push(volatilityValue);
895
+ }
896
+ return volatility;
897
+ }
898
+ // Calculate On Balance Volume
899
+ calculateObv(volumes) {
900
+ const obv = [volumes[0]];
901
+ for (let i = 1; i < volumes.length; i++) {
902
+ obv.push(obv[i - 1] + volumes[i]);
903
+ }
904
+ return obv;
905
+ }
906
+ // Calculate Chaikin Money Flow
907
+ calculateCmf(prices, highs, lows, volumes) {
908
+ const cmf = [];
909
+ const period = 20;
910
+ if (prices.length < period) return [];
911
+ for (let i = period - 1; i < prices.length; i++) {
912
+ let totalMoneyFlowVolume = 0;
913
+ let totalVolume = 0;
914
+ for (let j = i - period + 1; j <= i; j++) {
915
+ const high = highs[j] || prices[j];
916
+ const low = lows[j] || prices[j];
917
+ const close = prices[j];
918
+ const volume = volumes[j] || 1;
919
+ const moneyFlowMultiplier = (close - low - (high - close)) / (high - low);
920
+ const moneyFlowVolume = moneyFlowMultiplier * volume;
921
+ totalMoneyFlowVolume += moneyFlowVolume;
922
+ totalVolume += volume;
923
+ }
924
+ const cmfValue = totalVolume !== 0 ? totalMoneyFlowVolume / totalVolume : 0;
925
+ cmf.push(cmfValue);
926
+ }
927
+ return cmf;
928
+ }
929
+ // Calculate Accumulation/Distribution Line
930
+ calculateAdl(prices) {
931
+ const adl = [0];
932
+ for (let i = 1; i < prices.length; i++) {
933
+ const high = this.highs[i] || prices[i];
934
+ const low = this.lows[i] || prices[i];
935
+ const close = prices[i];
936
+ const volume = this.volumes[i] || 1;
937
+ const moneyFlowMultiplier = (close - low - (high - close)) / (high - low);
938
+ const moneyFlowVolume = moneyFlowMultiplier * volume;
939
+ adl.push(adl[i - 1] + moneyFlowVolume);
940
+ }
941
+ return adl;
942
+ }
943
+ // Calculate Volume Rate of Change
944
+ calculateVolumeROC() {
945
+ const volumeROC = [];
946
+ for (let i = 10; i < this.volumes.length; i++) {
947
+ volumeROC.push((this.volumes[i] - this.volumes[i - 10]) / this.volumes[i - 10] * 100);
948
+ }
949
+ return volumeROC;
950
+ }
951
+ // Calculate Money Flow Index
952
+ calculateMfi(prices, highs, lows, volumes) {
953
+ const mfi = [];
954
+ const period = 14;
955
+ if (prices.length < period + 1) return [];
956
+ for (let i = period; i < prices.length; i++) {
957
+ let positiveMoneyFlow = 0;
958
+ let negativeMoneyFlow = 0;
959
+ for (let j = i - period + 1; j <= i; j++) {
960
+ const high = highs[j] || prices[j];
961
+ const low = lows[j] || prices[j];
962
+ const close = prices[j];
963
+ const volume = volumes[j] || 1;
964
+ const typicalPrice = (high + low + close) / 3;
965
+ const moneyFlow = typicalPrice * volume;
966
+ if (j > i - period + 1) {
967
+ const prevHigh = highs[j - 1] || prices[j - 1];
968
+ const prevLow = lows[j - 1] || prices[j - 1];
969
+ const prevClose = prices[j - 1];
970
+ const prevTypicalPrice = (prevHigh + prevLow + prevClose) / 3;
971
+ if (typicalPrice > prevTypicalPrice) {
972
+ positiveMoneyFlow += moneyFlow;
973
+ } else if (typicalPrice < prevTypicalPrice) {
974
+ negativeMoneyFlow += moneyFlow;
975
+ }
976
+ }
977
+ }
978
+ const moneyRatio = negativeMoneyFlow !== 0 ? positiveMoneyFlow / negativeMoneyFlow : 0;
979
+ const mfiValue = 100 - 100 / (1 + moneyRatio);
980
+ mfi.push(mfiValue);
981
+ }
982
+ return mfi;
983
+ }
984
+ // Calculate VWAP
985
+ calculateVwap(prices, volumes) {
986
+ const vwap = [];
987
+ let cumulativePV = 0;
988
+ let cumulativeVolume = 0;
989
+ for (let i = 0; i < prices.length; i++) {
990
+ cumulativePV += prices[i] * (volumes[i] || 1);
991
+ cumulativeVolume += volumes[i] || 1;
992
+ vwap.push(cumulativePV / cumulativeVolume);
993
+ }
994
+ return vwap;
995
+ }
996
+ // Calculate Pivot Points
997
+ calculatePivotPoints(prices) {
998
+ const pivotPoints = [];
999
+ for (let i = 0; i < prices.length; i++) {
1000
+ const high = this.highs[i] || prices[i];
1001
+ const low = this.lows[i] || prices[i];
1002
+ const close = prices[i];
1003
+ const pp = (high + low + close) / 3;
1004
+ const r1 = 2 * pp - low;
1005
+ const s1 = 2 * pp - high;
1006
+ const r2 = pp + (high - low);
1007
+ const s2 = pp - (high - low);
1008
+ const r3 = high + 2 * (pp - low);
1009
+ const s3 = low - 2 * (high - pp);
1010
+ pivotPoints.push({
1011
+ pp,
1012
+ r1,
1013
+ r2,
1014
+ r3,
1015
+ s1,
1016
+ s2,
1017
+ s3
1018
+ });
1019
+ }
1020
+ return pivotPoints;
1021
+ }
1022
+ // Calculate Fibonacci Levels
1023
+ calculateFibonacciLevels(prices) {
1024
+ const fibonacci = [];
1025
+ for (let i = 0; i < prices.length; i++) {
1026
+ const price = prices[i];
1027
+ fibonacci.push({
1028
+ retracement: {
1029
+ level0: price,
1030
+ level236: price * 0.764,
1031
+ level382: price * 0.618,
1032
+ level500: price * 0.5,
1033
+ level618: price * 0.382,
1034
+ level786: price * 0.214,
1035
+ level100: price * 0
1036
+ },
1037
+ extension: {
1038
+ level1272: price * 1.272,
1039
+ level1618: price * 1.618,
1040
+ level2618: price * 2.618,
1041
+ level4236: price * 4.236
1042
+ }
1043
+ });
1044
+ }
1045
+ return fibonacci;
1046
+ }
1047
+ // Calculate Gann Levels
1048
+ calculateGannLevels(prices) {
1049
+ const gannLevels = [];
1050
+ for (let i = 0; i < prices.length; i++) {
1051
+ gannLevels.push(prices[i] * (1 + i * 0.01));
1052
+ }
1053
+ return gannLevels;
1054
+ }
1055
+ // Calculate Elliott Wave
1056
+ calculateElliottWave(prices) {
1057
+ const elliottWave = [];
1058
+ if (prices.length < 10) return [];
1059
+ for (let i = 0; i < prices.length; i++) {
1060
+ const waves = [];
1061
+ let currentWave = 1;
1062
+ let wavePosition = 0.5;
1063
+ if (i >= 4) {
1064
+ const recentPrices = prices.slice(i - 4, i + 1);
1065
+ const swings = this.detectPriceSwings(recentPrices);
1066
+ if (swings.length >= 3) {
1067
+ waves.push(...swings.slice(0, 3));
1068
+ currentWave = Math.min(swings.length, 5);
1069
+ wavePosition = this.calculateWavePosition(recentPrices);
1070
+ }
1071
+ }
1072
+ elliottWave.push({
1073
+ waves: waves.length > 0 ? waves : [prices[i]],
1074
+ currentWave,
1075
+ wavePosition
1076
+ });
1077
+ }
1078
+ return elliottWave;
1079
+ }
1080
+ // Helper method to detect price swings
1081
+ detectPriceSwings(prices) {
1082
+ const swings = [];
1083
+ for (let i = 1; i < prices.length - 1; i++) {
1084
+ const prev = prices[i - 1];
1085
+ const curr = prices[i];
1086
+ const next = prices[i + 1];
1087
+ if (curr > prev && curr > next) {
1088
+ swings.push(curr);
1089
+ } else if (curr < prev && curr < next) {
1090
+ swings.push(curr);
1091
+ }
1092
+ }
1093
+ return swings;
1094
+ }
1095
+ // Helper method to calculate wave position
1096
+ calculateWavePosition(prices) {
1097
+ if (prices.length < 2) return 0.5;
1098
+ const current = prices[prices.length - 1];
1099
+ const min = Math.min(...prices);
1100
+ const max = Math.max(...prices);
1101
+ return max !== min ? (current - min) / (max - min) : 0.5;
1102
+ }
1103
+ // Calculate Harmonic Patterns
1104
+ calculateHarmonicPatterns(prices) {
1105
+ const harmonicPatterns = [];
1106
+ if (prices.length < 5) return [];
1107
+ for (let i = 4; i < prices.length; i++) {
1108
+ const recentPrices = prices.slice(i - 4, i + 1);
1109
+ const pattern = this.detectHarmonicPattern(recentPrices);
1110
+ harmonicPatterns.push(pattern);
1111
+ }
1112
+ return harmonicPatterns;
1113
+ }
1114
+ // Helper method to detect harmonic patterns
1115
+ detectHarmonicPattern(prices) {
1116
+ if (prices.length < 5) {
1117
+ return {
1118
+ type: "Unknown",
1119
+ completion: 0,
1120
+ target: prices[prices.length - 1] * 1.1,
1121
+ stopLoss: prices[prices.length - 1] * 0.9
1122
+ };
1123
+ }
1124
+ const swings = this.detectPriceSwings(prices);
1125
+ if (swings.length < 4) {
1126
+ return {
1127
+ type: "Unknown",
1128
+ completion: 0,
1129
+ target: prices[prices.length - 1] * 1.1,
1130
+ stopLoss: prices[prices.length - 1] * 0.9
1131
+ };
1132
+ }
1133
+ const [A, B, C, D] = swings.slice(-4);
1134
+ const X = prices[0];
1135
+ const abRatio = Math.abs((B - A) / (X - A));
1136
+ const bcRatio = Math.abs((C - B) / (A - B));
1137
+ const cdRatio = Math.abs((D - C) / (B - C));
1138
+ const adRatio = Math.abs((D - A) / (X - A));
1139
+ 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;
1140
+ if (isGartley) {
1141
+ const completion = this.calculatePatternCompletion(prices);
1142
+ const target = D + (D - C) * 0.618;
1143
+ const stopLoss = D - (D - C) * 0.382;
1144
+ return {
1145
+ type: "Gartley",
1146
+ completion,
1147
+ target,
1148
+ stopLoss
1149
+ };
1150
+ }
1151
+ 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;
1152
+ if (isButterfly) {
1153
+ const completion = this.calculatePatternCompletion(prices);
1154
+ const target = D + (D - C) * 1.27;
1155
+ const stopLoss = D - (D - C) * 0.5;
1156
+ return {
1157
+ type: "Butterfly",
1158
+ completion,
1159
+ target,
1160
+ stopLoss
1161
+ };
1162
+ }
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
+ // Helper method to calculate pattern completion
1171
+ calculatePatternCompletion(prices) {
1172
+ if (prices.length < 2) return 0;
1173
+ const current = prices[prices.length - 1];
1174
+ const min = Math.min(...prices);
1175
+ const max = Math.max(...prices);
1176
+ return max !== min ? (current - min) / (max - min) : 0;
1177
+ }
1178
+ // Calculate Position Size
1179
+ calculatePositionSize(currentPrice, targetEntry, stopLoss) {
1180
+ void currentPrice;
1181
+ const riskPerShare = Math.abs(targetEntry - stopLoss);
1182
+ return riskPerShare > 0 ? 100 / riskPerShare : 1;
1183
+ }
1184
+ // Calculate Confidence
1185
+ calculateConfidence(signals) {
1186
+ return Math.min(signals.length * 10, 100);
1187
+ }
1188
+ // Calculate Risk Level
1189
+ calculateRiskLevel(volatility) {
1190
+ if (volatility < 20) return "LOW";
1191
+ if (volatility < 40) return "MEDIUM";
1192
+ return "HIGH";
1193
+ }
1194
+ // Calculate Z-Score
1195
+ calculateZScore(currentPrice, startPrice) {
1196
+ return (currentPrice - startPrice) / (startPrice * 0.1);
1197
+ }
1198
+ // Calculate Ornstein-Uhlenbeck
1199
+ calculateOrnsteinUhlenbeck(currentPrice, startPrice, avgVolume) {
1200
+ const priceChanges = this.calculatePriceChanges();
1201
+ const mean = startPrice;
1202
+ let speed = 0.1;
1203
+ if (priceChanges.length > 1) {
1204
+ const variance = priceChanges.reduce((sum2, change) => sum2 + change * change, 0) / priceChanges.length;
1205
+ speed = Math.max(0.01, Math.min(1, variance * 10));
1206
+ }
1207
+ const volatility = avgVolume * 0.01;
1208
+ return {
1209
+ mean,
1210
+ speed,
1211
+ volatility,
1212
+ currentValue: currentPrice
1213
+ };
1214
+ }
1215
+ // Calculate Kalman Filter
1216
+ calculateKalmanFilter(currentPrice, startPrice, avgVolume) {
1217
+ const measurementNoise = avgVolume * 1e-3;
1218
+ const processNoise = avgVolume * 1e-4;
1219
+ let state = startPrice;
1220
+ let covariance = measurementNoise;
1221
+ const priceChanges = this.calculatePriceChanges();
1222
+ if (priceChanges.length > 0) {
1223
+ const predictedState = state;
1224
+ const predictedCovariance = covariance + processNoise;
1225
+ const kalmanGain = predictedCovariance / (predictedCovariance + measurementNoise);
1226
+ state = predictedState + kalmanGain * (currentPrice - predictedState);
1227
+ covariance = (1 - kalmanGain) * predictedCovariance;
1228
+ return {
1229
+ state,
1230
+ covariance,
1231
+ gain: kalmanGain
1232
+ };
1233
+ }
1234
+ return {
1235
+ state: currentPrice,
1236
+ covariance,
1237
+ gain: 0.5
1238
+ };
1239
+ }
1240
+ // Calculate ARIMA
1241
+ calculateArima(currentPrice) {
1242
+ const priceChanges = this.calculatePriceChanges();
1243
+ if (priceChanges.length < 3) {
1244
+ return {
1245
+ forecast: [currentPrice * 1.01, currentPrice * 1.02],
1246
+ residuals: [0, 0],
1247
+ aic: 100
1248
+ };
1249
+ }
1250
+ const n = priceChanges.length;
1251
+ let sumY = 0;
1252
+ let sumY1 = 0;
1253
+ let sumYY1 = 0;
1254
+ let sumY1Sq = 0;
1255
+ for (let i = 1; i < n; i++) {
1256
+ const y = priceChanges[i];
1257
+ const y1 = priceChanges[i - 1];
1258
+ sumY += y;
1259
+ sumY1 += y1;
1260
+ sumYY1 += y * y1;
1261
+ sumY1Sq += y1 * y1;
1262
+ }
1263
+ const phi = (n * sumYY1 - sumY * sumY1) / (n * sumY1Sq - sumY1 * sumY1);
1264
+ const c = (sumY - phi * sumY1) / n;
1265
+ const residuals = [];
1266
+ for (let i = 1; i < n; i++) {
1267
+ const predicted = c + phi * priceChanges[i - 1];
1268
+ residuals.push(priceChanges[i] - predicted);
1269
+ }
1270
+ const rss = residuals.reduce((sum2, r) => sum2 + r * r, 0);
1271
+ const aic = n * Math.log(rss / n) + 2 * 2;
1272
+ const lastChange = priceChanges[priceChanges.length - 1];
1273
+ const forecast1 = currentPrice + (c + phi * lastChange);
1274
+ const forecast2 = forecast1 + (c + phi * (c + phi * lastChange));
1275
+ return {
1276
+ forecast: [forecast1, forecast2],
1277
+ residuals,
1278
+ aic
1279
+ };
1280
+ }
1281
+ // Calculate GARCH
1282
+ calculateGarch(avgVolume) {
1283
+ const priceChanges = this.calculatePriceChanges();
1284
+ if (priceChanges.length < 5) {
1285
+ return {
1286
+ volatility: avgVolume * 0.01,
1287
+ persistence: 0.9,
1288
+ meanReversion: 0.1
1289
+ };
1290
+ }
1291
+ const squaredReturns = priceChanges.map((change) => change * change);
1292
+ const meanSquaredReturn = squaredReturns.reduce((sum2, sq) => sum2 + sq, 0) / squaredReturns.length;
1293
+ let persistence = 0.9;
1294
+ if (squaredReturns.length > 1) {
1295
+ const variance = squaredReturns.reduce((sum2, sq) => sum2 + sq, 0) / squaredReturns.length;
1296
+ persistence = Math.min(0.99, Math.max(0.5, variance / meanSquaredReturn));
1297
+ }
1298
+ const meanReversion = meanSquaredReturn * (1 - persistence);
1299
+ const volatility = Math.sqrt(meanSquaredReturn);
1300
+ return {
1301
+ volatility,
1302
+ persistence,
1303
+ meanReversion
1304
+ };
1305
+ }
1306
+ // Calculate Hilbert Transform
1307
+ calculateHilbertTransform(currentPrice) {
1308
+ const priceChanges = this.calculatePriceChanges();
1309
+ if (priceChanges.length < 3) {
1310
+ return {
1311
+ analytic: [currentPrice],
1312
+ phase: [0],
1313
+ amplitude: [currentPrice]
1314
+ };
1315
+ }
1316
+ const n = priceChanges.length;
1317
+ const analytic = [];
1318
+ const phase = [];
1319
+ const amplitude = [];
1320
+ for (let i = 0; i < n; i++) {
1321
+ let hilbertValue = 0;
1322
+ for (let j = 0; j < n; j++) {
1323
+ if (i !== j) {
1324
+ hilbertValue += priceChanges[j] / (Math.PI * (i - j));
1325
+ }
1326
+ }
1327
+ const realPart = priceChanges[i];
1328
+ const imagPart = hilbertValue;
1329
+ const analyticValue = Math.sqrt(realPart * realPart + imagPart * imagPart);
1330
+ analytic.push(analyticValue);
1331
+ const phaseValue = Math.atan2(imagPart, realPart);
1332
+ phase.push(phaseValue);
1333
+ amplitude.push(analyticValue);
1334
+ }
1335
+ return {
1336
+ analytic,
1337
+ phase,
1338
+ amplitude
1339
+ };
1340
+ }
1341
+ // Calculate Wavelet Transform
1342
+ calculateWaveletTransform(currentPrice) {
1343
+ const priceChanges = this.calculatePriceChanges();
1344
+ if (priceChanges.length < 4) {
1345
+ return {
1346
+ coefficients: [currentPrice],
1347
+ scales: [1]
1348
+ };
1349
+ }
1350
+ const coefficients = [];
1351
+ const scales = [];
1352
+ const n = priceChanges.length;
1353
+ const maxLevel = Math.floor(Math.log2(n));
1354
+ for (let level = 1; level <= maxLevel; level++) {
1355
+ const step = 2 ** (level - 1);
1356
+ const scale = step;
1357
+ for (let i = 0; i < n - step; i += step * 2) {
1358
+ if (i + step < n) {
1359
+ const coefficient = (priceChanges[i] - priceChanges[i + step]) / Math.sqrt(2);
1360
+ coefficients.push(coefficient);
1361
+ scales.push(scale);
1362
+ }
1363
+ }
1364
+ }
1365
+ if (coefficients.length === 0) {
1366
+ coefficients.push(currentPrice);
1367
+ scales.push(1);
1368
+ }
1369
+ return {
1370
+ coefficients,
1371
+ scales
1372
+ };
1373
+ }
1374
+ // Calculate Black-Scholes
1375
+ calculateBlackScholes(currentPrice, startPrice, avgVolume) {
1376
+ const S = currentPrice;
1377
+ const K = startPrice;
1378
+ const T = 1;
1379
+ const r = 0.05;
1380
+ const sigma = avgVolume * 0.01;
1381
+ const d1 = (Math.log(S / K) + (r + sigma * sigma / 2) * T) / (sigma * Math.sqrt(T));
1382
+ const d2 = d1 - sigma * Math.sqrt(T);
1383
+ const callPrice = S * this.normalCDF(d1) - K * Math.exp(-r * T) * this.normalCDF(d2);
1384
+ const putPrice = K * Math.exp(-r * T) * this.normalCDF(-d2) - S * this.normalCDF(-d1);
1385
+ return {
1386
+ callPrice,
1387
+ putPrice,
1388
+ delta: this.normalCDF(d1),
1389
+ gamma: this.normalPDF(d1) / (S * sigma * Math.sqrt(T)),
1390
+ theta: -S * this.normalPDF(d1) * sigma / (2 * Math.sqrt(T)) - r * K * Math.exp(-r * T) * this.normalCDF(d2),
1391
+ vega: S * Math.sqrt(T) * this.normalPDF(d1),
1392
+ rho: K * T * Math.exp(-r * T) * this.normalCDF(d2)
1393
+ };
1394
+ }
1395
+ // Normal CDF approximation
1396
+ normalCDF(x) {
1397
+ return 0.5 * (1 + this.erf(x / Math.sqrt(2)));
1398
+ }
1399
+ // Normal PDF
1400
+ normalPDF(x) {
1401
+ return Math.exp(-x * x / 2) / Math.sqrt(2 * Math.PI);
1402
+ }
1403
+ // Error function approximation
1404
+ erf(x) {
1405
+ const a1 = 0.254829592;
1406
+ const a2 = -0.284496736;
1407
+ const a3 = 1.421413741;
1408
+ const a4 = -1.453152027;
1409
+ const a5 = 1.061405429;
1410
+ const p = 0.3275911;
1411
+ const sign = x >= 0 ? 1 : -1;
1412
+ const absX = Math.abs(x);
1413
+ const t = 1 / (1 + p * absX);
1414
+ const y = 1 - ((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t * Math.exp(-absX * absX);
1415
+ return sign * y;
1416
+ }
1417
+ // Calculate price changes for volatility
1418
+ calculatePriceChanges() {
1419
+ const changes = [];
1420
+ for (let i = 1; i < this.prices.length; i++) {
1421
+ changes.push((this.prices[i] - this.prices[i - 1]) / this.prices[i - 1]);
1422
+ }
1423
+ return changes;
1424
+ }
1425
+ // Generate comprehensive market analysis
1426
+ analyze() {
1427
+ const currentPrice = this.prices[this.prices.length - 1];
1428
+ const startPrice = this.prices[0];
1429
+ const sessionHigh = Math.max(...this.highs);
1430
+ const sessionLow = Math.min(...this.lows);
1431
+ const totalVolume = sum(this.volumes);
1432
+ const avgVolume = totalVolume / this.volumes.length;
1433
+ const priceChanges = this.calculatePriceChanges();
1434
+ const volatility = priceChanges.length > 0 ? Math.sqrt(
1435
+ priceChanges.reduce((sum2, change) => sum2 + change ** 2, 0) / priceChanges.length
1436
+ ) * Math.sqrt(252) * 100 : 0;
1437
+ const sessionReturn = (currentPrice - startPrice) / startPrice * 100;
1438
+ const pricePosition = (currentPrice - sessionLow) / (sessionHigh - sessionLow) * 100;
1439
+ const trueVWAP = this.prices.reduce((sum2, price, i) => sum2 + price * this.volumes[i], 0) / totalVolume;
1440
+ 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;
1441
+ 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;
1442
+ const maxDrawdown = this.calculateMaxDrawdown(this.prices);
1443
+ const atrValues = this.calculateAtr(this.prices, this.highs, this.lows);
1444
+ const atr = atrValues.length > 0 ? atrValues[atrValues.length - 1] : 0;
1445
+ const impliedVolatility = volatility;
1446
+ const realizedVolatility = volatility;
1447
+ const sharpeRatio = sessionReturn / volatility;
1448
+ const sortinoRatio = sessionReturn / realizedVolatility;
1449
+ const calmarRatio = sessionReturn / maxDrawdown;
1450
+ const maxConsecutiveLosses = this.calculateMaxConsecutiveLosses(this.prices);
1451
+ const winRate = this.calculateWinRate(this.prices);
1452
+ const profitFactor = this.calculateProfitFactor(this.prices);
1453
+ return {
1454
+ currentPrice,
1455
+ startPrice,
1456
+ sessionHigh,
1457
+ sessionLow,
1458
+ totalVolume,
1459
+ avgVolume,
1460
+ volatility,
1461
+ sessionReturn,
1462
+ pricePosition,
1463
+ trueVWAP,
1464
+ momentum5,
1465
+ momentum10,
1466
+ maxDrawdown,
1467
+ atr,
1468
+ impliedVolatility,
1469
+ realizedVolatility,
1470
+ sharpeRatio,
1471
+ sortinoRatio,
1472
+ calmarRatio,
1473
+ maxConsecutiveLosses,
1474
+ winRate,
1475
+ profitFactor
1476
+ };
1477
+ }
1478
+ // Generate technical indicators
1479
+ getTechnicalIndicators() {
1480
+ return {
1481
+ sma5: this.calculateSMA(this.prices, 5),
1482
+ sma10: this.calculateSMA(this.prices, 10),
1483
+ sma20: this.calculateSMA(this.prices, 20),
1484
+ sma50: this.calculateSMA(this.prices, 50),
1485
+ sma200: this.calculateSMA(this.prices, 200),
1486
+ ema8: this.calculateEMA(this.prices, 8),
1487
+ ema12: this.calculateEMA(this.prices, 12),
1488
+ ema21: this.calculateEMA(this.prices, 21),
1489
+ ema26: this.calculateEMA(this.prices, 26),
1490
+ wma20: this.calculateWma(this.prices, 20),
1491
+ vwma20: this.calculateVwma(this.prices, 20),
1492
+ macd: this.calculateMacd(this.prices),
1493
+ adx: this.calculateAdx(this.prices, this.highs, this.lows),
1494
+ dmi: this.calculateDmi(this.prices, this.highs, this.lows),
1495
+ ichimoku: this.calculateIchimoku(this.prices, this.highs, this.lows),
1496
+ parabolicSAR: this.calculateParabolicSAR(this.prices, this.highs, this.lows),
1497
+ rsi: this.calculateRSI(this.prices, 14),
1498
+ stochastic: this.calculateStochastic(this.prices, this.highs, this.lows),
1499
+ cci: this.calculateCci(this.prices, this.highs, this.lows),
1500
+ roc: this.calculateRoc(this.prices),
1501
+ williamsR: this.calculateWilliamsR(this.prices),
1502
+ momentum: this.calculateMomentum(this.prices),
1503
+ bollinger: this.calculateBollingerBands(this.prices, 20, 2),
1504
+ atr: this.calculateAtr(this.prices, this.highs, this.lows),
1505
+ keltner: this.calculateKeltnerChannels(this.prices, this.highs, this.lows),
1506
+ donchian: this.calculateDonchianChannels(this.prices),
1507
+ chaikinVolatility: this.calculateChaikinVolatility(this.prices, this.highs, this.lows),
1508
+ obv: this.calculateObv(this.volumes),
1509
+ cmf: this.calculateCmf(this.prices, this.highs, this.lows, this.volumes),
1510
+ adl: this.calculateAdl(this.prices),
1511
+ volumeROC: this.calculateVolumeROC(),
1512
+ mfi: this.calculateMfi(this.prices, this.highs, this.lows, this.volumes),
1513
+ vwap: this.calculateVwap(this.prices, this.volumes),
1514
+ pivotPoints: this.calculatePivotPoints(this.prices),
1515
+ fibonacci: this.calculateFibonacciLevels(this.prices),
1516
+ gannLevels: this.calculateGannLevels(this.prices),
1517
+ elliottWave: this.calculateElliottWave(this.prices),
1518
+ harmonicPatterns: this.calculateHarmonicPatterns(this.prices)
1519
+ };
1520
+ }
1521
+ // Generate trading signals
1522
+ generateSignals() {
1523
+ const analysis = this.analyze();
1524
+ let bullishSignals = 0;
1525
+ let bearishSignals = 0;
1526
+ const signals = [];
1527
+ if (analysis.currentPrice > analysis.trueVWAP) {
1528
+ signals.push(
1529
+ `\u2713 BULLISH: Price above VWAP (+${((analysis.currentPrice - analysis.trueVWAP) / analysis.trueVWAP * 100).toFixed(2)}%)`
1530
+ );
1531
+ bullishSignals++;
1532
+ } else {
1533
+ signals.push(
1534
+ `\u2717 BEARISH: Price below VWAP (${((analysis.currentPrice - analysis.trueVWAP) / analysis.trueVWAP * 100).toFixed(2)}%)`
1535
+ );
1536
+ bearishSignals++;
1537
+ }
1538
+ if (analysis.momentum5 > 0 && analysis.momentum10 > 0) {
1539
+ signals.push("\u2713 BULLISH: Positive momentum on both timeframes");
1540
+ bullishSignals++;
1541
+ } else if (analysis.momentum5 < 0 && analysis.momentum10 < 0) {
1542
+ signals.push("\u2717 BEARISH: Negative momentum on both timeframes");
1543
+ bearishSignals++;
1544
+ } else {
1545
+ signals.push("\u25D0 MIXED: Conflicting momentum signals");
1546
+ }
1547
+ const currentVolume = this.volumes[this.volumes.length - 1];
1548
+ const volumeRatio = currentVolume / analysis.avgVolume;
1549
+ if (volumeRatio > 1.2 && analysis.sessionReturn > 0) {
1550
+ signals.push("\u2713 BULLISH: Above-average volume supporting upward move");
1551
+ bullishSignals++;
1552
+ } else if (volumeRatio > 1.2 && analysis.sessionReturn < 0) {
1553
+ signals.push("\u2717 BEARISH: Above-average volume supporting downward move");
1554
+ bearishSignals++;
1555
+ } else {
1556
+ signals.push("\u25D0 NEUTRAL: Volume not providing clear direction");
1557
+ }
1558
+ if (analysis.pricePosition > 65 && analysis.volatility > 30) {
1559
+ signals.push("\u2717 BEARISH: High in range with elevated volatility - reversal risk");
1560
+ bearishSignals++;
1561
+ } else if (analysis.pricePosition < 35 && analysis.volatility > 30) {
1562
+ signals.push("\u2713 BULLISH: Low in range with volatility - potential bounce");
1563
+ bullishSignals++;
1564
+ } else {
1565
+ signals.push("\u25D0 NEUTRAL: Price position and volatility not extreme");
1566
+ }
1567
+ return { bullishSignals, bearishSignals, signals };
1568
+ }
1569
+ // Generate comprehensive JSON analysis
1570
+ generateJSONAnalysis(symbol) {
1571
+ const analysis = this.analyze();
1572
+ const indicators = this.getTechnicalIndicators();
1573
+ const signals = this.generateSignals();
1574
+ const currentSMA5 = indicators.sma5.length > 0 ? indicators.sma5[indicators.sma5.length - 1] : null;
1575
+ const currentSMA10 = indicators.sma10.length > 0 ? indicators.sma10[indicators.sma10.length - 1] : null;
1576
+ const currentSMA20 = indicators.sma20.length > 0 ? indicators.sma20[indicators.sma20.length - 1] : null;
1577
+ const currentSMA50 = indicators.sma50.length > 0 ? indicators.sma50[indicators.sma50.length - 1] : null;
1578
+ const currentSMA200 = indicators.sma200.length > 0 ? indicators.sma200[indicators.sma200.length - 1] : null;
1579
+ const currentEMA8 = indicators.ema8[indicators.ema8.length - 1];
1580
+ const currentEMA12 = indicators.ema12[indicators.ema12.length - 1];
1581
+ const currentEMA21 = indicators.ema21[indicators.ema21.length - 1];
1582
+ const currentEMA26 = indicators.ema26[indicators.ema26.length - 1];
1583
+ const currentWMA20 = indicators.wma20.length > 0 ? indicators.wma20[indicators.wma20.length - 1] : null;
1584
+ const currentVWMA20 = indicators.vwma20.length > 0 ? indicators.vwma20[indicators.vwma20.length - 1] : null;
1585
+ const currentMACD = indicators.macd.length > 0 ? indicators.macd[indicators.macd.length - 1] : null;
1586
+ const currentADX = indicators.adx.length > 0 ? indicators.adx[indicators.adx.length - 1] : null;
1587
+ const currentDMI = indicators.dmi.length > 0 ? indicators.dmi[indicators.dmi.length - 1] : null;
1588
+ const currentIchimoku = indicators.ichimoku.length > 0 ? indicators.ichimoku[indicators.ichimoku.length - 1] : null;
1589
+ const currentParabolicSAR = indicators.parabolicSAR.length > 0 ? indicators.parabolicSAR[indicators.parabolicSAR.length - 1] : null;
1590
+ const currentRSI = indicators.rsi.length > 0 ? indicators.rsi[indicators.rsi.length - 1] : null;
1591
+ const currentStochastic = indicators.stochastic.length > 0 ? indicators.stochastic[indicators.stochastic.length - 1] : null;
1592
+ const currentCCI = indicators.cci.length > 0 ? indicators.cci[indicators.cci.length - 1] : null;
1593
+ const currentROC = indicators.roc.length > 0 ? indicators.roc[indicators.roc.length - 1] : null;
1594
+ const currentWilliamsR = indicators.williamsR.length > 0 ? indicators.williamsR[indicators.williamsR.length - 1] : null;
1595
+ const currentMomentum = indicators.momentum.length > 0 ? indicators.momentum[indicators.momentum.length - 1] : null;
1596
+ const currentBB = indicators.bollinger.length > 0 ? indicators.bollinger[indicators.bollinger.length - 1] : null;
1597
+ const currentAtr = indicators.atr.length > 0 ? indicators.atr[indicators.atr.length - 1] : null;
1598
+ const currentKeltner = indicators.keltner.length > 0 ? indicators.keltner[indicators.keltner.length - 1] : null;
1599
+ const currentDonchian = indicators.donchian.length > 0 ? indicators.donchian[indicators.donchian.length - 1] : null;
1600
+ const currentChaikinVolatility = indicators.chaikinVolatility.length > 0 ? indicators.chaikinVolatility[indicators.chaikinVolatility.length - 1] : null;
1601
+ const currentObv = indicators.obv.length > 0 ? indicators.obv[indicators.obv.length - 1] : null;
1602
+ const currentCmf = indicators.cmf.length > 0 ? indicators.cmf[indicators.cmf.length - 1] : null;
1603
+ const currentAdl = indicators.adl.length > 0 ? indicators.adl[indicators.adl.length - 1] : null;
1604
+ const currentVolumeROC = indicators.volumeROC.length > 0 ? indicators.volumeROC[indicators.volumeROC.length - 1] : null;
1605
+ const currentMfi = indicators.mfi.length > 0 ? indicators.mfi[indicators.mfi.length - 1] : null;
1606
+ const currentVwap = indicators.vwap.length > 0 ? indicators.vwap[indicators.vwap.length - 1] : null;
1607
+ const currentPivotPoints = indicators.pivotPoints.length > 0 ? indicators.pivotPoints[indicators.pivotPoints.length - 1] : null;
1608
+ const currentFibonacci = indicators.fibonacci.length > 0 ? indicators.fibonacci[indicators.fibonacci.length - 1] : null;
1609
+ const currentGannLevels = indicators.gannLevels.length > 0 ? indicators.gannLevels : [];
1610
+ const currentElliottWave = indicators.elliottWave.length > 0 ? indicators.elliottWave[indicators.elliottWave.length - 1] : null;
1611
+ const currentHarmonicPatterns = indicators.harmonicPatterns.length > 0 ? indicators.harmonicPatterns : [];
1612
+ const currentVolume = this.volumes[this.volumes.length - 1];
1613
+ const volumeRatio = currentVolume / analysis.avgVolume;
1614
+ const currentDrawdown = (analysis.sessionHigh - analysis.currentPrice) / analysis.sessionHigh * 100;
1615
+ const rangeWidth = (analysis.sessionHigh - analysis.sessionLow) / analysis.sessionLow * 100;
1616
+ const priceVsVWAP = (analysis.currentPrice - analysis.trueVWAP) / analysis.trueVWAP * 100;
1617
+ const totalScore = signals.bullishSignals - signals.bearishSignals;
1618
+ const overallSignal = totalScore > 0 ? "BULLISH_BIAS" : totalScore < 0 ? "BEARISH_BIAS" : "NEUTRAL";
1619
+ const targetEntry = Math.max(analysis.sessionLow * 1.005, analysis.trueVWAP * 0.998);
1620
+ const stopLoss = analysis.sessionLow * 0.995;
1621
+ const profitTarget = analysis.sessionHigh * 0.995;
1622
+ const riskRewardRatio = (profitTarget - analysis.currentPrice) / (analysis.currentPrice - stopLoss);
1623
+ const positionSize = this.calculatePositionSize(analysis.currentPrice, targetEntry, stopLoss);
1624
+ const maxRisk = positionSize * (targetEntry - stopLoss);
1625
+ return {
1626
+ symbol,
1627
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1628
+ marketStructure: {
1629
+ currentPrice: analysis.currentPrice,
1630
+ startPrice: analysis.startPrice,
1631
+ sessionHigh: analysis.sessionHigh,
1632
+ sessionLow: analysis.sessionLow,
1633
+ rangeWidth,
1634
+ totalVolume: analysis.totalVolume,
1635
+ sessionPerformance: analysis.sessionReturn,
1636
+ positionInRange: analysis.pricePosition
1637
+ },
1638
+ volatility: {
1639
+ impliedVolatility: analysis.impliedVolatility,
1640
+ realizedVolatility: analysis.realizedVolatility,
1641
+ atr: analysis.atr,
1642
+ maxDrawdown: analysis.maxDrawdown * 100,
1643
+ currentDrawdown
1644
+ },
1645
+ technicalIndicators: {
1646
+ sma5: currentSMA5,
1647
+ sma10: currentSMA10,
1648
+ sma20: currentSMA20,
1649
+ sma50: currentSMA50,
1650
+ sma200: currentSMA200,
1651
+ ema8: currentEMA8,
1652
+ ema12: currentEMA12,
1653
+ ema21: currentEMA21,
1654
+ ema26: currentEMA26,
1655
+ wma20: currentWMA20,
1656
+ vwma20: currentVWMA20,
1657
+ macd: currentMACD,
1658
+ adx: currentADX,
1659
+ dmi: currentDMI,
1660
+ ichimoku: currentIchimoku,
1661
+ parabolicSAR: currentParabolicSAR,
1662
+ rsi: currentRSI,
1663
+ stochastic: currentStochastic,
1664
+ cci: currentCCI,
1665
+ roc: currentROC,
1666
+ williamsR: currentWilliamsR,
1667
+ momentum: currentMomentum,
1668
+ bollingerBands: currentBB ? {
1669
+ upper: currentBB.upper,
1670
+ middle: currentBB.middle,
1671
+ lower: currentBB.lower,
1672
+ bandwidth: currentBB.bandwidth,
1673
+ percentB: currentBB.percentB
1674
+ } : null,
1675
+ atr: currentAtr,
1676
+ keltnerChannels: currentKeltner ? {
1677
+ upper: currentKeltner.upper,
1678
+ middle: currentKeltner.middle,
1679
+ lower: currentKeltner.lower
1680
+ } : null,
1681
+ donchianChannels: currentDonchian ? {
1682
+ upper: currentDonchian.upper,
1683
+ middle: currentDonchian.middle,
1684
+ lower: currentDonchian.lower
1685
+ } : null,
1686
+ chaikinVolatility: currentChaikinVolatility,
1687
+ obv: currentObv,
1688
+ cmf: currentCmf,
1689
+ adl: currentAdl,
1690
+ volumeROC: currentVolumeROC,
1691
+ mfi: currentMfi,
1692
+ vwap: currentVwap
1693
+ },
1694
+ volumeAnalysis: {
1695
+ currentVolume,
1696
+ averageVolume: Math.round(analysis.avgVolume),
1697
+ volumeRatio,
1698
+ trueVWAP: analysis.trueVWAP,
1699
+ priceVsVWAP,
1700
+ obv: currentObv,
1701
+ cmf: currentCmf,
1702
+ mfi: currentMfi
1703
+ },
1704
+ momentum: {
1705
+ momentum5: analysis.momentum5,
1706
+ momentum10: analysis.momentum10,
1707
+ sessionROC: analysis.sessionReturn,
1708
+ rsi: currentRSI,
1709
+ stochastic: currentStochastic,
1710
+ cci: currentCCI
1711
+ },
1712
+ supportResistance: {
1713
+ pivotPoints: currentPivotPoints,
1714
+ fibonacci: currentFibonacci,
1715
+ gannLevels: currentGannLevels,
1716
+ elliottWave: currentElliottWave,
1717
+ harmonicPatterns: currentHarmonicPatterns
1718
+ },
1719
+ tradingSignals: {
1720
+ ...signals,
1721
+ overallSignal,
1722
+ signalScore: totalScore,
1723
+ confidence: this.calculateConfidence(signals.signals),
1724
+ riskLevel: this.calculateRiskLevel(analysis.volatility)
1725
+ },
1726
+ statisticalModels: {
1727
+ zScore: this.calculateZScore(analysis.currentPrice, analysis.startPrice),
1728
+ ornsteinUhlenbeck: this.calculateOrnsteinUhlenbeck(
1729
+ analysis.currentPrice,
1730
+ analysis.startPrice,
1731
+ analysis.avgVolume
1732
+ ),
1733
+ kalmanFilter: this.calculateKalmanFilter(
1734
+ analysis.currentPrice,
1735
+ analysis.startPrice,
1736
+ analysis.avgVolume
1737
+ ),
1738
+ arima: this.calculateArima(analysis.currentPrice),
1739
+ garch: this.calculateGarch(analysis.avgVolume),
1740
+ hilbertTransform: this.calculateHilbertTransform(analysis.currentPrice),
1741
+ waveletTransform: this.calculateWaveletTransform(analysis.currentPrice)
1742
+ },
1743
+ optionsAnalysis: (() => {
1744
+ const blackScholes = this.calculateBlackScholes(
1745
+ analysis.currentPrice,
1746
+ analysis.startPrice,
1747
+ analysis.avgVolume
1748
+ );
1749
+ if (!blackScholes) return null;
1750
+ return {
1751
+ blackScholes,
1752
+ impliedVolatility: analysis.impliedVolatility,
1753
+ delta: blackScholes.delta,
1754
+ gamma: blackScholes.gamma,
1755
+ theta: blackScholes.theta,
1756
+ vega: blackScholes.vega,
1757
+ rho: blackScholes.rho,
1758
+ greeks: {
1759
+ delta: blackScholes.delta,
1760
+ gamma: blackScholes.gamma,
1761
+ theta: blackScholes.theta,
1762
+ vega: blackScholes.vega,
1763
+ rho: blackScholes.rho
1764
+ }
1765
+ };
1766
+ })(),
1767
+ riskManagement: {
1768
+ targetEntry,
1769
+ stopLoss,
1770
+ profitTarget,
1771
+ riskRewardRatio,
1772
+ positionSize,
1773
+ maxRisk
1774
+ },
1775
+ performance: {
1776
+ sharpeRatio: analysis.sharpeRatio,
1777
+ sortinoRatio: analysis.sortinoRatio,
1778
+ calmarRatio: analysis.calmarRatio,
1779
+ maxDrawdown: analysis.maxDrawdown * 100,
1780
+ winRate: analysis.winRate,
1781
+ profitFactor: analysis.profitFactor,
1782
+ totalReturn: analysis.sessionReturn,
1783
+ volatility: analysis.volatility
1784
+ }
1785
+ };
1786
+ }
1787
+ };
1788
+ var createTechnicalAnalysisHandler = (marketDataPrices) => {
1789
+ return async (args) => {
1790
+ try {
1791
+ const symbol = args.symbol;
1792
+ const priceHistory = marketDataPrices.get(symbol) || [];
1793
+ if (priceHistory.length === 0) {
1794
+ return {
1795
+ content: [
1796
+ {
1797
+ type: "text",
1798
+ text: `No price data available for ${symbol}. Please request market data first.`,
1799
+ uri: "technicalAnalysis"
1800
+ }
1801
+ ]
1802
+ };
1803
+ }
1804
+ const hasValidData = priceHistory.every(
1805
+ (entry) => typeof entry.trade === "number" && !Number.isNaN(entry.trade) && typeof entry.midPrice === "number" && !Number.isNaN(entry.midPrice)
1806
+ );
1807
+ if (!hasValidData) {
1808
+ throw new Error("Invalid market data");
1809
+ }
1810
+ const analyzer = new TechnicalAnalyzer(priceHistory);
1811
+ const analysis = analyzer.generateJSONAnalysis(symbol);
1812
+ return {
1813
+ content: [
1814
+ {
1815
+ type: "text",
1816
+ text: `Technical Analysis for ${symbol}:
1817
+
1818
+ ${JSON.stringify(analysis, null, 2)}`,
1819
+ uri: "technicalAnalysis"
1820
+ }
1821
+ ]
1822
+ };
1823
+ } catch (error) {
1824
+ return {
1825
+ content: [
1826
+ {
1827
+ type: "text",
1828
+ text: `Error performing technical analysis: ${error instanceof Error ? error.message : "Unknown error"}`,
1829
+ uri: "technicalAnalysis"
1830
+ }
1831
+ ],
1832
+ isError: true
1833
+ };
1834
+ }
1835
+ };
1836
+ };
1837
+
1838
+ // src/tools/marketData.ts
1839
+ import { Field, Fields, MDEntryType, Messages } from "fixparser";
1840
+ import QuickChart from "quickchart-js";
1841
+ var createMarketDataRequestHandler = (parser, pendingRequests) => {
1842
+ return async (args) => {
1843
+ try {
1844
+ parser.logger.log({
1845
+ level: "info",
1846
+ message: `Sending market data request for symbols: ${args.symbols.join(", ")}`
1847
+ });
1848
+ const response = new Promise((resolve) => {
1849
+ pendingRequests.set(args.mdReqID, resolve);
1850
+ parser.logger.log({
1851
+ level: "info",
1852
+ message: `Registered callback for market data request ID: ${args.mdReqID}`
1853
+ });
1854
+ });
1855
+ const entryTypes = args.mdEntryTypes || [
1856
+ MDEntryType.Bid,
1857
+ MDEntryType.Offer,
1858
+ MDEntryType.Trade,
1859
+ MDEntryType.IndexValue,
1860
+ MDEntryType.OpeningPrice,
1861
+ MDEntryType.ClosingPrice,
1862
+ MDEntryType.SettlementPrice,
1863
+ MDEntryType.TradingSessionHighPrice,
1864
+ MDEntryType.TradingSessionLowPrice,
1865
+ MDEntryType.VWAP,
1866
+ MDEntryType.Imbalance,
1867
+ MDEntryType.TradeVolume,
1868
+ MDEntryType.OpenInterest,
1869
+ MDEntryType.CompositeUnderlyingPrice,
1870
+ MDEntryType.SimulatedSellPrice,
1871
+ MDEntryType.SimulatedBuyPrice,
1872
+ MDEntryType.MarginRate,
1873
+ MDEntryType.MidPrice,
1874
+ MDEntryType.EmptyBook,
1875
+ MDEntryType.SettleHighPrice,
1876
+ MDEntryType.SettleLowPrice,
1877
+ MDEntryType.PriorSettlePrice,
1878
+ MDEntryType.SessionHighBid,
1879
+ MDEntryType.SessionLowOffer,
1880
+ MDEntryType.EarlyPrices,
1881
+ MDEntryType.AuctionClearingPrice,
1882
+ MDEntryType.SwapValueFactor,
1883
+ MDEntryType.DailyValueAdjustmentForLongPositions,
1884
+ MDEntryType.CumulativeValueAdjustmentForLongPositions,
1885
+ MDEntryType.DailyValueAdjustmentForShortPositions,
1886
+ MDEntryType.CumulativeValueAdjustmentForShortPositions,
1887
+ MDEntryType.FixingPrice,
1888
+ MDEntryType.CashRate,
1889
+ MDEntryType.RecoveryRate,
1890
+ MDEntryType.RecoveryRateForLong,
1891
+ MDEntryType.RecoveryRateForShort,
1892
+ MDEntryType.MarketBid,
1893
+ MDEntryType.MarketOffer,
1894
+ MDEntryType.ShortSaleMinPrice,
1895
+ MDEntryType.PreviousClosingPrice,
1896
+ MDEntryType.ThresholdLimitPriceBanding,
1897
+ MDEntryType.DailyFinancingValue,
1898
+ MDEntryType.AccruedFinancingValue,
1899
+ MDEntryType.TWAP
1900
+ ];
1901
+ const messageFields = [
1902
+ new Field(Fields.MsgType, Messages.MarketDataRequest),
1903
+ new Field(Fields.SenderCompID, parser.sender),
1904
+ new Field(Fields.MsgSeqNum, parser.getNextTargetMsgSeqNum()),
1905
+ new Field(Fields.TargetCompID, parser.target),
1906
+ new Field(Fields.SendingTime, parser.getTimestamp()),
1907
+ new Field(Fields.MDReqID, args.mdReqID),
1908
+ new Field(Fields.SubscriptionRequestType, args.subscriptionRequestType),
1909
+ new Field(Fields.MarketDepth, 0),
1910
+ new Field(Fields.MDUpdateType, args.mdUpdateType)
1911
+ ];
1912
+ messageFields.push(new Field(Fields.NoRelatedSym, args.symbols.length));
1913
+ args.symbols.forEach((symbol) => {
1914
+ messageFields.push(new Field(Fields.Symbol, symbol));
1915
+ });
1916
+ messageFields.push(new Field(Fields.NoMDEntryTypes, entryTypes.length));
1917
+ entryTypes.forEach((entryType) => {
1918
+ messageFields.push(new Field(Fields.MDEntryType, entryType));
1919
+ });
1920
+ const mdr = parser.createMessage(...messageFields);
1921
+ if (!parser.connected) {
1922
+ parser.logger.log({
1923
+ level: "error",
1924
+ message: "Not connected. Cannot send market data request."
1925
+ });
1926
+ return {
1927
+ content: [
1928
+ {
1929
+ type: "text",
1930
+ text: "Error: Not connected. Ignoring message.",
1931
+ uri: "marketDataRequest"
1932
+ }
1933
+ ],
1934
+ isError: true
1935
+ };
1936
+ }
1937
+ parser.logger.log({
1938
+ level: "info",
1939
+ message: `Sending market data request message: ${JSON.stringify(mdr?.toFIXJSON())}`
1940
+ });
1941
+ parser.send(mdr);
1942
+ const fixData = await response;
1943
+ parser.logger.log({
1944
+ level: "info",
1945
+ message: `Received market data response for request ID: ${args.mdReqID}`
1946
+ });
1947
+ return {
1948
+ content: [
1949
+ {
1950
+ type: "text",
1951
+ text: `Market data for ${args.symbols.join(", ")}: ${JSON.stringify(fixData.toFIXJSON())}`,
1952
+ uri: "marketDataRequest"
1953
+ }
1954
+ ]
1955
+ };
1956
+ } catch (error) {
1957
+ return {
1958
+ content: [
1959
+ {
1960
+ type: "text",
1961
+ text: `Error: ${error instanceof Error ? error.message : "Failed to request market data"}`,
1962
+ uri: "marketDataRequest"
1963
+ }
1964
+ ],
1965
+ isError: true
1966
+ };
1967
+ }
1968
+ };
1969
+ };
1970
+ var aggregateMarketData = (priceHistory, maxPoints = 490) => {
1971
+ if (priceHistory.length <= maxPoints) {
1972
+ return priceHistory;
1973
+ }
1974
+ const result = [];
1975
+ const step = priceHistory.length / maxPoints;
1976
+ result.push(priceHistory[0]);
1977
+ for (let i = 1; i < maxPoints - 1; i++) {
1978
+ const startIndex = Math.floor(i * step);
1979
+ const endIndex = Math.floor((i + 1) * step);
1980
+ const segment = priceHistory.slice(startIndex, endIndex);
1981
+ if (segment.length === 0) continue;
1982
+ const aggregatedPoint = {
1983
+ timestamp: segment[0].timestamp,
1984
+ // Use timestamp of first point in segment
1985
+ bid: segment.reduce((sum2, p) => sum2 + p.bid, 0) / segment.length,
1986
+ offer: segment.reduce((sum2, p) => sum2 + p.offer, 0) / segment.length,
1987
+ spread: segment.reduce((sum2, p) => sum2 + p.spread, 0) / segment.length,
1988
+ volume: segment.reduce((sum2, p) => sum2 + p.volume, 0) / segment.length,
1989
+ trade: segment.reduce((sum2, p) => sum2 + p.trade, 0) / segment.length,
1990
+ indexValue: segment.reduce((sum2, p) => sum2 + p.indexValue, 0) / segment.length,
1991
+ openingPrice: segment.reduce((sum2, p) => sum2 + p.openingPrice, 0) / segment.length,
1992
+ closingPrice: segment.reduce((sum2, p) => sum2 + p.closingPrice, 0) / segment.length,
1993
+ settlementPrice: segment.reduce((sum2, p) => sum2 + p.settlementPrice, 0) / segment.length,
1994
+ tradingSessionHighPrice: segment.reduce((sum2, p) => sum2 + p.tradingSessionHighPrice, 0) / segment.length,
1995
+ tradingSessionLowPrice: segment.reduce((sum2, p) => sum2 + p.tradingSessionLowPrice, 0) / segment.length,
1996
+ vwap: segment.reduce((sum2, p) => sum2 + p.vwap, 0) / segment.length,
1997
+ imbalance: segment.reduce((sum2, p) => sum2 + p.imbalance, 0) / segment.length,
1998
+ openInterest: segment.reduce((sum2, p) => sum2 + p.openInterest, 0) / segment.length,
1999
+ compositeUnderlyingPrice: segment.reduce((sum2, p) => sum2 + p.compositeUnderlyingPrice, 0) / segment.length,
2000
+ simulatedSellPrice: segment.reduce((sum2, p) => sum2 + p.simulatedSellPrice, 0) / segment.length,
2001
+ simulatedBuyPrice: segment.reduce((sum2, p) => sum2 + p.simulatedBuyPrice, 0) / segment.length,
2002
+ marginRate: segment.reduce((sum2, p) => sum2 + p.marginRate, 0) / segment.length,
2003
+ midPrice: segment.reduce((sum2, p) => sum2 + p.midPrice, 0) / segment.length,
2004
+ emptyBook: segment.reduce((sum2, p) => sum2 + p.emptyBook, 0) / segment.length,
2005
+ settleHighPrice: segment.reduce((sum2, p) => sum2 + p.settleHighPrice, 0) / segment.length,
2006
+ settleLowPrice: segment.reduce((sum2, p) => sum2 + p.settleLowPrice, 0) / segment.length,
2007
+ priorSettlePrice: segment.reduce((sum2, p) => sum2 + p.priorSettlePrice, 0) / segment.length,
2008
+ sessionHighBid: segment.reduce((sum2, p) => sum2 + p.sessionHighBid, 0) / segment.length,
2009
+ sessionLowOffer: segment.reduce((sum2, p) => sum2 + p.sessionLowOffer, 0) / segment.length,
2010
+ earlyPrices: segment.reduce((sum2, p) => sum2 + p.earlyPrices, 0) / segment.length,
2011
+ auctionClearingPrice: segment.reduce((sum2, p) => sum2 + p.auctionClearingPrice, 0) / segment.length,
2012
+ swapValueFactor: segment.reduce((sum2, p) => sum2 + p.swapValueFactor, 0) / segment.length,
2013
+ dailyValueAdjustmentForLongPositions: segment.reduce((sum2, p) => sum2 + p.dailyValueAdjustmentForLongPositions, 0) / segment.length,
2014
+ cumulativeValueAdjustmentForLongPositions: segment.reduce((sum2, p) => sum2 + p.cumulativeValueAdjustmentForLongPositions, 0) / segment.length,
2015
+ dailyValueAdjustmentForShortPositions: segment.reduce((sum2, p) => sum2 + p.dailyValueAdjustmentForShortPositions, 0) / segment.length,
2016
+ cumulativeValueAdjustmentForShortPositions: segment.reduce((sum2, p) => sum2 + p.cumulativeValueAdjustmentForShortPositions, 0) / segment.length,
2017
+ fixingPrice: segment.reduce((sum2, p) => sum2 + p.fixingPrice, 0) / segment.length,
2018
+ cashRate: segment.reduce((sum2, p) => sum2 + p.cashRate, 0) / segment.length,
2019
+ recoveryRate: segment.reduce((sum2, p) => sum2 + p.recoveryRate, 0) / segment.length,
2020
+ recoveryRateForLong: segment.reduce((sum2, p) => sum2 + p.recoveryRateForLong, 0) / segment.length,
2021
+ recoveryRateForShort: segment.reduce((sum2, p) => sum2 + p.recoveryRateForShort, 0) / segment.length,
2022
+ marketBid: segment.reduce((sum2, p) => sum2 + p.marketBid, 0) / segment.length,
2023
+ marketOffer: segment.reduce((sum2, p) => sum2 + p.marketOffer, 0) / segment.length,
2024
+ shortSaleMinPrice: segment.reduce((sum2, p) => sum2 + p.shortSaleMinPrice, 0) / segment.length,
2025
+ previousClosingPrice: segment.reduce((sum2, p) => sum2 + p.previousClosingPrice, 0) / segment.length,
2026
+ thresholdLimitPriceBanding: segment.reduce((sum2, p) => sum2 + p.thresholdLimitPriceBanding, 0) / segment.length,
2027
+ dailyFinancingValue: segment.reduce((sum2, p) => sum2 + p.dailyFinancingValue, 0) / segment.length,
2028
+ accruedFinancingValue: segment.reduce((sum2, p) => sum2 + p.accruedFinancingValue, 0) / segment.length,
2029
+ twap: segment.reduce((sum2, p) => sum2 + p.twap, 0) / segment.length
2030
+ };
2031
+ result.push(aggregatedPoint);
2032
+ }
2033
+ result.push(priceHistory[priceHistory.length - 1]);
2034
+ return result;
2035
+ };
2036
+ var createGetStockGraphHandler = (marketDataPrices) => {
2037
+ return async (args) => {
2038
+ try {
2039
+ const symbol = args.symbol;
2040
+ const priceHistory = marketDataPrices.get(symbol) || [];
2041
+ if (priceHistory.length === 0) {
2042
+ return {
2043
+ content: [
2044
+ {
2045
+ type: "text",
2046
+ text: `No price data available for ${symbol}`,
2047
+ uri: "getStockGraph"
2048
+ }
2049
+ ]
2050
+ };
2051
+ }
2052
+ const aggregatedData = aggregateMarketData(priceHistory, 500);
2053
+ const chart = new QuickChart();
2054
+ chart.setWidth(1200);
2055
+ chart.setHeight(600);
2056
+ chart.setBackgroundColor("transparent");
2057
+ const labels = aggregatedData.map((point) => new Date(point.timestamp).toLocaleTimeString());
2058
+ const bidData = aggregatedData.map((point) => point.bid);
2059
+ const offerData = aggregatedData.map((point) => point.offer);
2060
+ const spreadData = aggregatedData.map((point) => point.spread);
2061
+ const volumeData = aggregatedData.map((point) => point.volume);
2062
+ const tradeData = aggregatedData.map((point) => point.trade);
2063
+ const vwapData = aggregatedData.map((point) => point.vwap);
2064
+ const twapData = aggregatedData.map((point) => point.twap);
2065
+ const maxVolume = Math.max(...volumeData.filter((v) => v > 0));
2066
+ const maxPrice = Math.max(...bidData, ...offerData, ...tradeData, ...vwapData, ...twapData);
2067
+ const normalizedVolumeData = volumeData.map((v) => v / maxVolume * maxPrice * 0.3);
2068
+ const config = {
2069
+ type: "line",
2070
+ data: {
2071
+ labels,
2072
+ datasets: [
2073
+ {
2074
+ label: "Bid",
2075
+ data: bidData,
2076
+ borderColor: "#28a745",
2077
+ backgroundColor: "rgba(40, 167, 69, 0.1)",
2078
+ fill: false,
2079
+ tension: 0.4
2080
+ },
2081
+ {
2082
+ label: "Offer",
2083
+ data: offerData,
2084
+ borderColor: "#dc3545",
2085
+ backgroundColor: "rgba(220, 53, 69, 0.1)",
2086
+ fill: false,
2087
+ tension: 0.4
2088
+ },
2089
+ {
2090
+ label: "Spread",
2091
+ data: spreadData,
2092
+ borderColor: "#6c757d",
2093
+ backgroundColor: "rgba(108, 117, 125, 0.1)",
2094
+ fill: false,
2095
+ tension: 0.4
2096
+ },
2097
+ {
2098
+ label: "Trade",
2099
+ data: tradeData,
2100
+ borderColor: "#ffc107",
2101
+ backgroundColor: "rgba(255, 193, 7, 0.1)",
2102
+ fill: false,
2103
+ tension: 0.4
2104
+ },
2105
+ {
2106
+ label: "VWAP",
2107
+ data: vwapData,
2108
+ borderColor: "#17a2b8",
2109
+ backgroundColor: "rgba(23, 162, 184, 0.1)",
2110
+ fill: false,
2111
+ tension: 0.4
2112
+ },
2113
+ {
2114
+ label: "TWAP",
2115
+ data: twapData,
2116
+ borderColor: "#6610f2",
2117
+ backgroundColor: "rgba(102, 16, 242, 0.1)",
2118
+ fill: false,
2119
+ tension: 0.4
2120
+ },
2121
+ {
2122
+ label: "Volume (Normalized)",
2123
+ data: normalizedVolumeData,
2124
+ borderColor: "#007bff",
2125
+ backgroundColor: "rgba(0, 123, 255, 0.1)",
2126
+ fill: true,
2127
+ tension: 0.4
2128
+ }
2129
+ ]
2130
+ },
2131
+ options: {
2132
+ responsive: true,
2133
+ plugins: {
2134
+ title: {
2135
+ display: true,
2136
+ text: `${symbol} Market Data (Volume normalized to 30% of max price)`
2137
+ }
2138
+ },
2139
+ scales: {
2140
+ y: {
2141
+ beginAtZero: false,
2142
+ title: {
2143
+ display: true,
2144
+ text: "Price / Normalized Volume"
2145
+ }
2146
+ }
2147
+ }
2148
+ }
2149
+ };
2150
+ chart.setConfig(config);
2151
+ const imageBuffer = await chart.toBinary();
2152
+ const base64 = imageBuffer.toString("base64");
2153
+ return {
2154
+ content: [
2155
+ {
2156
+ type: "resource",
2157
+ resource: {
2158
+ uri: "resource://graph",
2159
+ mimeType: "image/png",
2160
+ blob: base64
2161
+ }
2162
+ }
2163
+ ]
2164
+ };
2165
+ } catch (error) {
2166
+ return {
2167
+ content: [
2168
+ {
2169
+ type: "text",
2170
+ text: `Error: ${error instanceof Error ? error.message : "Failed to generate graph"}`,
2171
+ uri: "getStockGraph"
2172
+ }
2173
+ ],
2174
+ isError: true
2175
+ };
2176
+ }
2177
+ };
2178
+ };
2179
+ var createGetStockPriceHistoryHandler = (marketDataPrices) => {
2180
+ return async (args) => {
2181
+ try {
2182
+ const symbol = args.symbol;
2183
+ const priceHistory = marketDataPrices.get(symbol) || [];
2184
+ if (priceHistory.length === 0) {
2185
+ return {
2186
+ content: [
2187
+ {
2188
+ type: "text",
2189
+ text: `No price data available for ${symbol}`,
2190
+ uri: "getStockPriceHistory"
2191
+ }
2192
+ ]
2193
+ };
2194
+ }
2195
+ const aggregatedData = aggregateMarketData(priceHistory, 500);
2196
+ return {
2197
+ content: [
2198
+ {
2199
+ type: "text",
2200
+ text: JSON.stringify(
2201
+ {
2202
+ symbol,
2203
+ count: aggregatedData.length,
2204
+ originalCount: priceHistory.length,
2205
+ data: aggregatedData.map((point) => ({
2206
+ timestamp: new Date(point.timestamp).toISOString(),
2207
+ bid: point.bid,
2208
+ offer: point.offer,
2209
+ spread: point.spread,
2210
+ volume: point.volume,
2211
+ trade: point.trade,
2212
+ indexValue: point.indexValue,
2213
+ openingPrice: point.openingPrice,
2214
+ closingPrice: point.closingPrice,
2215
+ settlementPrice: point.settlementPrice,
2216
+ tradingSessionHighPrice: point.tradingSessionHighPrice,
2217
+ tradingSessionLowPrice: point.tradingSessionLowPrice,
2218
+ vwap: point.vwap,
2219
+ imbalance: point.imbalance,
2220
+ openInterest: point.openInterest,
2221
+ compositeUnderlyingPrice: point.compositeUnderlyingPrice,
2222
+ simulatedSellPrice: point.simulatedSellPrice,
2223
+ simulatedBuyPrice: point.simulatedBuyPrice,
2224
+ marginRate: point.marginRate,
2225
+ midPrice: point.midPrice,
2226
+ emptyBook: point.emptyBook,
2227
+ settleHighPrice: point.settleHighPrice,
2228
+ settleLowPrice: point.settleLowPrice,
2229
+ priorSettlePrice: point.priorSettlePrice,
2230
+ sessionHighBid: point.sessionHighBid,
2231
+ sessionLowOffer: point.sessionLowOffer,
2232
+ earlyPrices: point.earlyPrices,
2233
+ auctionClearingPrice: point.auctionClearingPrice,
2234
+ swapValueFactor: point.swapValueFactor,
2235
+ dailyValueAdjustmentForLongPositions: point.dailyValueAdjustmentForLongPositions,
2236
+ cumulativeValueAdjustmentForLongPositions: point.cumulativeValueAdjustmentForLongPositions,
2237
+ dailyValueAdjustmentForShortPositions: point.dailyValueAdjustmentForShortPositions,
2238
+ cumulativeValueAdjustmentForShortPositions: point.cumulativeValueAdjustmentForShortPositions,
2239
+ fixingPrice: point.fixingPrice,
2240
+ cashRate: point.cashRate,
2241
+ recoveryRate: point.recoveryRate,
2242
+ recoveryRateForLong: point.recoveryRateForLong,
2243
+ recoveryRateForShort: point.recoveryRateForShort,
2244
+ marketBid: point.marketBid,
2245
+ marketOffer: point.marketOffer,
2246
+ shortSaleMinPrice: point.shortSaleMinPrice,
2247
+ previousClosingPrice: point.previousClosingPrice,
2248
+ thresholdLimitPriceBanding: point.thresholdLimitPriceBanding,
2249
+ dailyFinancingValue: point.dailyFinancingValue,
2250
+ accruedFinancingValue: point.accruedFinancingValue,
2251
+ twap: point.twap
2252
+ }))
2253
+ },
2254
+ null,
2255
+ 2
2256
+ ),
2257
+ uri: "getStockPriceHistory"
2258
+ }
2259
+ ]
2260
+ };
2261
+ } catch (error) {
2262
+ return {
2263
+ content: [
2264
+ {
2265
+ type: "text",
2266
+ text: `Error: ${error instanceof Error ? error.message : "Failed to get price history"}`,
2267
+ uri: "getStockPriceHistory"
2268
+ }
2269
+ ],
2270
+ isError: true
2271
+ };
2272
+ }
2273
+ };
2274
+ };
2275
+
2276
+ // src/tools/order.ts
2277
+ import { Field as Field2, Fields as Fields2, Messages as Messages2 } from "fixparser";
2278
+ var ordTypeNames = {
2279
+ "1": "Market",
2280
+ "2": "Limit",
2281
+ "3": "Stop",
2282
+ "4": "StopLimit",
2283
+ "5": "MarketOnClose",
2284
+ "6": "WithOrWithout",
2285
+ "7": "LimitOrBetter",
2286
+ "8": "LimitWithOrWithout",
2287
+ "9": "OnBasis",
2288
+ A: "OnClose",
2289
+ B: "LimitOnClose",
2290
+ C: "ForexMarket",
2291
+ D: "PreviouslyQuoted",
2292
+ E: "PreviouslyIndicated",
2293
+ F: "ForexLimit",
2294
+ G: "ForexSwap",
2295
+ H: "ForexPreviouslyQuoted",
2296
+ I: "Funari",
2297
+ J: "MarketIfTouched",
2298
+ K: "MarketWithLeftOverAsLimit",
2299
+ L: "PreviousFundValuationPoint",
2300
+ M: "NextFundValuationPoint",
2301
+ P: "Pegged",
2302
+ Q: "CounterOrderSelection",
2303
+ R: "StopOnBidOrOffer",
2304
+ S: "StopLimitOnBidOrOffer"
2305
+ };
2306
+ var sideNames = {
2307
+ "1": "Buy",
2308
+ "2": "Sell",
2309
+ "3": "BuyMinus",
2310
+ "4": "SellPlus",
2311
+ "5": "SellShort",
2312
+ "6": "SellShortExempt",
2313
+ "7": "Undisclosed",
2314
+ "8": "Cross",
2315
+ "9": "CrossShort",
2316
+ A: "CrossShortExempt",
2317
+ B: "AsDefined",
2318
+ C: "Opposite",
2319
+ D: "Subscribe",
2320
+ E: "Redeem",
2321
+ F: "Lend",
2322
+ G: "Borrow",
2323
+ H: "SellUndisclosed"
2324
+ };
2325
+ var timeInForceNames = {
2326
+ "0": "Day",
2327
+ "1": "GoodTillCancel",
2328
+ "2": "AtTheOpening",
2329
+ "3": "ImmediateOrCancel",
2330
+ "4": "FillOrKill",
2331
+ "5": "GoodTillCrossing",
2332
+ "6": "GoodTillDate",
2333
+ "7": "AtTheClose",
2334
+ "8": "GoodThroughCrossing",
2335
+ "9": "AtCrossing",
2336
+ A: "GoodForTime",
2337
+ B: "GoodForAuction",
2338
+ C: "GoodForMonth"
2339
+ };
2340
+ var handlInstNames = {
2341
+ "1": "AutomatedExecutionNoIntervention",
2342
+ "2": "AutomatedExecutionInterventionOK",
2343
+ "3": "ManualOrder"
2344
+ };
2345
+ var createVerifyOrderHandler = (parser, verifiedOrders) => {
2346
+ return async (args) => {
2347
+ void parser;
2348
+ try {
2349
+ verifiedOrders.set(args.clOrdID, {
2350
+ clOrdID: args.clOrdID,
2351
+ handlInst: args.handlInst,
2352
+ quantity: Number.parseFloat(String(args.quantity)),
2353
+ price: Number.parseFloat(String(args.price)),
2354
+ ordType: args.ordType,
2355
+ side: args.side,
2356
+ symbol: args.symbol,
2357
+ timeInForce: args.timeInForce
2358
+ });
2359
+ return {
2360
+ content: [
2361
+ {
2362
+ type: "text",
2363
+ text: `VERIFICATION: All parameters valid. Ready to proceed with order execution.
2364
+
2365
+ Parameters verified:
2366
+ - ClOrdID: ${args.clOrdID}
2367
+ - HandlInst: ${args.handlInst} (${handlInstNames[args.handlInst]})
2368
+ - Quantity: ${args.quantity}
2369
+ - Price: ${args.price}
2370
+ - OrdType: ${args.ordType} (${ordTypeNames[args.ordType]})
2371
+ - Side: ${args.side} (${sideNames[args.side]})
2372
+ - Symbol: ${args.symbol}
2373
+ - TimeInForce: ${args.timeInForce} (${timeInForceNames[args.timeInForce]})
2374
+
2375
+ To execute this order, call the executeOrder tool with these exact same parameters. Important: The user has to explicitly confirm before executeOrder is called!`,
2376
+ uri: "verifyOrder"
2377
+ }
2378
+ ]
2379
+ };
2380
+ } catch (error) {
2381
+ return {
2382
+ content: [
2383
+ {
2384
+ type: "text",
2385
+ text: `Error: ${error instanceof Error ? error.message : "Failed to verify order parameters"}`,
2386
+ uri: "verifyOrder"
2387
+ }
2388
+ ],
2389
+ isError: true
2390
+ };
2391
+ }
2392
+ };
2393
+ };
2394
+ var createExecuteOrderHandler = (parser, verifiedOrders, pendingRequests) => {
2395
+ return async (args) => {
2396
+ try {
2397
+ const verifiedOrder = verifiedOrders.get(args.clOrdID);
2398
+ if (!verifiedOrder) {
2399
+ return {
2400
+ content: [
2401
+ {
2402
+ type: "text",
2403
+ text: `Error: Order ${args.clOrdID} has not been verified. Please call verifyOrder first.`,
2404
+ uri: "executeOrder"
2405
+ }
2406
+ ],
2407
+ isError: true
2408
+ };
2409
+ }
2410
+ if (verifiedOrder.handlInst !== args.handlInst || verifiedOrder.quantity !== Number.parseFloat(String(args.quantity)) || verifiedOrder.price !== Number.parseFloat(String(args.price)) || verifiedOrder.ordType !== args.ordType || verifiedOrder.side !== args.side || verifiedOrder.symbol !== args.symbol || verifiedOrder.timeInForce !== args.timeInForce) {
2411
+ return {
2412
+ content: [
2413
+ {
2414
+ type: "text",
2415
+ text: "Error: Order parameters do not match the verified order. Please use the exact same parameters that were verified.",
2416
+ uri: "executeOrder"
2417
+ }
2418
+ ],
2419
+ isError: true
2420
+ };
2421
+ }
2422
+ const response = new Promise((resolve) => {
2423
+ pendingRequests.set(args.clOrdID, resolve);
2424
+ });
2425
+ const order = parser.createMessage(
2426
+ new Field2(Fields2.MsgType, Messages2.NewOrderSingle),
2427
+ new Field2(Fields2.MsgSeqNum, parser.getNextTargetMsgSeqNum()),
2428
+ new Field2(Fields2.SenderCompID, parser.sender),
2429
+ new Field2(Fields2.TargetCompID, parser.target),
2430
+ new Field2(Fields2.SendingTime, parser.getTimestamp()),
2431
+ new Field2(Fields2.ClOrdID, args.clOrdID),
2432
+ new Field2(Fields2.Side, args.side),
2433
+ new Field2(Fields2.Symbol, args.symbol),
2434
+ new Field2(Fields2.OrderQty, Number.parseFloat(String(args.quantity))),
2435
+ new Field2(Fields2.Price, Number.parseFloat(String(args.price))),
2436
+ new Field2(Fields2.OrdType, args.ordType),
2437
+ new Field2(Fields2.HandlInst, args.handlInst),
2438
+ new Field2(Fields2.TimeInForce, args.timeInForce),
2439
+ new Field2(Fields2.TransactTime, parser.getTimestamp())
2440
+ );
2441
+ if (!parser.connected) {
2442
+ return {
2443
+ content: [
2444
+ {
2445
+ type: "text",
2446
+ text: "Error: Not connected. Ignoring message.",
2447
+ uri: "executeOrder"
2448
+ }
2449
+ ],
2450
+ isError: true
2451
+ };
2452
+ }
2453
+ parser.send(order);
2454
+ const fixData = await response;
2455
+ verifiedOrders.delete(args.clOrdID);
2456
+ return {
2457
+ content: [
2458
+ {
2459
+ type: "text",
2460
+ text: fixData.messageType === Messages2.Reject ? `Reject message for order ${args.clOrdID}: ${JSON.stringify(fixData.toFIXJSON())}` : `Execution Report for order ${args.clOrdID}: ${JSON.stringify(fixData.toFIXJSON())}`,
2461
+ uri: "executeOrder"
2462
+ }
2463
+ ]
2464
+ };
2465
+ } catch (error) {
2466
+ return {
2467
+ content: [
2468
+ {
2469
+ type: "text",
2470
+ text: `Error: ${error instanceof Error ? error.message : "Failed to execute order"}`,
2471
+ uri: "executeOrder"
2472
+ }
2473
+ ],
2474
+ isError: true
2475
+ };
2476
+ }
2477
+ };
2478
+ };
2479
+
2480
+ // src/tools/parse.ts
2481
+ var createParseHandler = (parser) => {
2482
+ return async (args) => {
2483
+ try {
2484
+ const parsedMessage = parser.parse(args.fixString);
2485
+ if (!parsedMessage || parsedMessage.length === 0) {
2486
+ return {
2487
+ content: [
2488
+ {
2489
+ type: "text",
2490
+ text: "Error: Failed to parse FIX string",
2491
+ uri: "parse"
2492
+ }
2493
+ ],
2494
+ isError: true
2495
+ };
2496
+ }
2497
+ return {
2498
+ content: [
2499
+ {
2500
+ type: "text",
2501
+ text: `${parsedMessage[0].description}
2502
+ ${parsedMessage[0].messageTypeDescription}`,
2503
+ uri: "parse"
2504
+ }
2505
+ ]
2506
+ };
2507
+ } catch (error) {
2508
+ return {
2509
+ content: [
2510
+ {
2511
+ type: "text",
2512
+ text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`,
2513
+ uri: "parse"
2514
+ }
2515
+ ],
2516
+ isError: true
2517
+ };
2518
+ }
2519
+ };
2520
+ };
2521
+
2522
+ // src/tools/parseToJSON.ts
2523
+ var createParseToJSONHandler = (parser) => {
2524
+ return async (args) => {
2525
+ try {
2526
+ const parsedMessage = parser.parse(args.fixString);
2527
+ if (!parsedMessage || parsedMessage.length === 0) {
2528
+ return {
2529
+ content: [
2530
+ {
2531
+ type: "text",
2532
+ text: "Error: Failed to parse FIX string",
2533
+ uri: "parseToJSON"
2534
+ }
2535
+ ],
2536
+ isError: true
2537
+ };
2538
+ }
2539
+ return {
2540
+ content: [
2541
+ {
2542
+ type: "text",
2543
+ text: `${parsedMessage[0].toFIXJSON()}`,
2544
+ uri: "parseToJSON"
2545
+ }
2546
+ ]
2547
+ };
2548
+ } catch (error) {
2549
+ return {
2550
+ content: [
2551
+ {
2552
+ type: "text",
2553
+ text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`,
2554
+ uri: "parseToJSON"
2555
+ }
2556
+ ],
2557
+ isError: true
2558
+ };
2559
+ }
2560
+ };
2561
+ };
2562
+
2563
+ // src/tools/index.ts
2564
+ var createToolHandlers = (parser, verifiedOrders, pendingRequests, marketDataPrices) => ({
2565
+ parse: createParseHandler(parser),
2566
+ parseToJSON: createParseToJSONHandler(parser),
2567
+ verifyOrder: createVerifyOrderHandler(parser, verifiedOrders),
2568
+ executeOrder: createExecuteOrderHandler(parser, verifiedOrders, pendingRequests),
2569
+ marketDataRequest: createMarketDataRequestHandler(parser, pendingRequests),
2570
+ getStockGraph: createGetStockGraphHandler(marketDataPrices),
2571
+ getStockPriceHistory: createGetStockPriceHistoryHandler(marketDataPrices),
2572
+ technicalAnalysis: createTechnicalAnalysisHandler(marketDataPrices)
2573
+ });
2574
+
2575
+ // src/utils/messageHandler.ts
2576
+ import { Fields as Fields3, MDEntryType as MDEntryType2, Messages as Messages3 } from "fixparser";
2577
+ function getEnumValue(enumObj, name) {
2578
+ return enumObj[name] || name;
2579
+ }
2580
+ function handleMessage(message, parser, pendingRequests, marketDataPrices, maxPriceHistory, onPriceUpdate) {
2581
+ void parser;
2582
+ const msgType = message.messageType;
2583
+ if (msgType === Messages3.MarketDataSnapshotFullRefresh || msgType === Messages3.MarketDataIncrementalRefresh) {
2584
+ const symbol = message.getField(Fields3.Symbol)?.value;
2585
+ const fixJson = message.toFIXJSON();
2586
+ const entries = fixJson.Body?.NoMDEntries || [];
2587
+ const data = {
2588
+ timestamp: Date.now(),
2589
+ bid: 0,
2590
+ offer: 0,
2591
+ spread: 0,
2592
+ volume: 0,
2593
+ trade: 0,
2594
+ indexValue: 0,
2595
+ openingPrice: 0,
2596
+ closingPrice: 0,
2597
+ settlementPrice: 0,
2598
+ tradingSessionHighPrice: 0,
2599
+ tradingSessionLowPrice: 0,
2600
+ vwap: 0,
2601
+ imbalance: 0,
2602
+ openInterest: 0,
2603
+ compositeUnderlyingPrice: 0,
2604
+ simulatedSellPrice: 0,
2605
+ simulatedBuyPrice: 0,
2606
+ marginRate: 0,
2607
+ midPrice: 0,
2608
+ emptyBook: 0,
2609
+ settleHighPrice: 0,
2610
+ settleLowPrice: 0,
2611
+ priorSettlePrice: 0,
2612
+ sessionHighBid: 0,
2613
+ sessionLowOffer: 0,
2614
+ earlyPrices: 0,
2615
+ auctionClearingPrice: 0,
2616
+ swapValueFactor: 0,
2617
+ dailyValueAdjustmentForLongPositions: 0,
2618
+ cumulativeValueAdjustmentForLongPositions: 0,
2619
+ dailyValueAdjustmentForShortPositions: 0,
2620
+ cumulativeValueAdjustmentForShortPositions: 0,
2621
+ fixingPrice: 0,
2622
+ cashRate: 0,
2623
+ recoveryRate: 0,
2624
+ recoveryRateForLong: 0,
2625
+ recoveryRateForShort: 0,
2626
+ marketBid: 0,
2627
+ marketOffer: 0,
2628
+ shortSaleMinPrice: 0,
2629
+ previousClosingPrice: 0,
2630
+ thresholdLimitPriceBanding: 0,
2631
+ dailyFinancingValue: 0,
2632
+ accruedFinancingValue: 0,
2633
+ twap: 0
2634
+ };
2635
+ for (const entry of entries) {
2636
+ const entryType = entry.MDEntryType;
2637
+ const price = entry.MDEntryPx ? Number.parseFloat(entry.MDEntryPx) : 0;
2638
+ const size = entry.MDEntrySize ? Number.parseFloat(entry.MDEntrySize) : 0;
2639
+ const enumValue = getEnumValue(MDEntryType2, entryType);
2640
+ switch (enumValue) {
2641
+ case MDEntryType2.Bid:
2642
+ data.bid = price;
2643
+ break;
2644
+ case MDEntryType2.Offer:
2645
+ data.offer = price;
2646
+ break;
2647
+ case MDEntryType2.Trade:
2648
+ data.trade = price;
2649
+ break;
2650
+ case MDEntryType2.IndexValue:
2651
+ data.indexValue = price;
2652
+ break;
2653
+ case MDEntryType2.OpeningPrice:
2654
+ data.openingPrice = price;
2655
+ break;
2656
+ case MDEntryType2.ClosingPrice:
2657
+ data.closingPrice = price;
2658
+ break;
2659
+ case MDEntryType2.SettlementPrice:
2660
+ data.settlementPrice = price;
2661
+ break;
2662
+ case MDEntryType2.TradingSessionHighPrice:
2663
+ data.tradingSessionHighPrice = price;
2664
+ break;
2665
+ case MDEntryType2.TradingSessionLowPrice:
2666
+ data.tradingSessionLowPrice = price;
2667
+ break;
2668
+ case MDEntryType2.VWAP:
2669
+ data.vwap = price;
2670
+ break;
2671
+ case MDEntryType2.Imbalance:
2672
+ data.imbalance = size;
2673
+ break;
2674
+ case MDEntryType2.TradeVolume:
2675
+ data.volume = size;
2676
+ break;
2677
+ case MDEntryType2.OpenInterest:
2678
+ data.openInterest = size;
2679
+ break;
2680
+ case MDEntryType2.CompositeUnderlyingPrice:
2681
+ data.compositeUnderlyingPrice = price;
2682
+ break;
2683
+ case MDEntryType2.SimulatedSellPrice:
2684
+ data.simulatedSellPrice = price;
2685
+ break;
2686
+ case MDEntryType2.SimulatedBuyPrice:
2687
+ data.simulatedBuyPrice = price;
2688
+ break;
2689
+ case MDEntryType2.MarginRate:
2690
+ data.marginRate = price;
2691
+ break;
2692
+ case MDEntryType2.MidPrice:
2693
+ data.midPrice = price;
2694
+ break;
2695
+ case MDEntryType2.EmptyBook:
2696
+ data.emptyBook = 1;
2697
+ break;
2698
+ case MDEntryType2.SettleHighPrice:
2699
+ data.settleHighPrice = price;
2700
+ break;
2701
+ case MDEntryType2.SettleLowPrice:
2702
+ data.settleLowPrice = price;
2703
+ break;
2704
+ case MDEntryType2.PriorSettlePrice:
2705
+ data.priorSettlePrice = price;
2706
+ break;
2707
+ case MDEntryType2.SessionHighBid:
2708
+ data.sessionHighBid = price;
2709
+ break;
2710
+ case MDEntryType2.SessionLowOffer:
2711
+ data.sessionLowOffer = price;
2712
+ break;
2713
+ case MDEntryType2.EarlyPrices:
2714
+ data.earlyPrices = price;
2715
+ break;
2716
+ case MDEntryType2.AuctionClearingPrice:
2717
+ data.auctionClearingPrice = price;
2718
+ break;
2719
+ case MDEntryType2.SwapValueFactor:
2720
+ data.swapValueFactor = price;
2721
+ break;
2722
+ case MDEntryType2.DailyValueAdjustmentForLongPositions:
2723
+ data.dailyValueAdjustmentForLongPositions = price;
2724
+ break;
2725
+ case MDEntryType2.CumulativeValueAdjustmentForLongPositions:
2726
+ data.cumulativeValueAdjustmentForLongPositions = price;
2727
+ break;
2728
+ case MDEntryType2.DailyValueAdjustmentForShortPositions:
2729
+ data.dailyValueAdjustmentForShortPositions = price;
2730
+ break;
2731
+ case MDEntryType2.CumulativeValueAdjustmentForShortPositions:
2732
+ data.cumulativeValueAdjustmentForShortPositions = price;
2733
+ break;
2734
+ case MDEntryType2.FixingPrice:
2735
+ data.fixingPrice = price;
2736
+ break;
2737
+ case MDEntryType2.CashRate:
2738
+ data.cashRate = price;
2739
+ break;
2740
+ case MDEntryType2.RecoveryRate:
2741
+ data.recoveryRate = price;
2742
+ break;
2743
+ case MDEntryType2.RecoveryRateForLong:
2744
+ data.recoveryRateForLong = price;
2745
+ break;
2746
+ case MDEntryType2.RecoveryRateForShort:
2747
+ data.recoveryRateForShort = price;
2748
+ break;
2749
+ case MDEntryType2.MarketBid:
2750
+ data.marketBid = price;
2751
+ break;
2752
+ case MDEntryType2.MarketOffer:
2753
+ data.marketOffer = price;
2754
+ break;
2755
+ case MDEntryType2.ShortSaleMinPrice:
2756
+ data.shortSaleMinPrice = price;
2757
+ break;
2758
+ case MDEntryType2.PreviousClosingPrice:
2759
+ data.previousClosingPrice = price;
2760
+ break;
2761
+ case MDEntryType2.ThresholdLimitPriceBanding:
2762
+ data.thresholdLimitPriceBanding = price;
2763
+ break;
2764
+ case MDEntryType2.DailyFinancingValue:
2765
+ data.dailyFinancingValue = price;
2766
+ break;
2767
+ case MDEntryType2.AccruedFinancingValue:
2768
+ data.accruedFinancingValue = price;
2769
+ break;
2770
+ case MDEntryType2.TWAP:
2771
+ data.twap = price;
2772
+ break;
2773
+ }
2774
+ }
2775
+ data.spread = data.offer - data.bid;
2776
+ if (!marketDataPrices.has(symbol)) {
2777
+ marketDataPrices.set(symbol, []);
2778
+ }
2779
+ const prices = marketDataPrices.get(symbol);
2780
+ prices.push(data);
2781
+ if (prices.length > maxPriceHistory) {
2782
+ prices.splice(0, prices.length - maxPriceHistory);
2783
+ }
2784
+ onPriceUpdate?.(symbol, data);
2785
+ const mdReqID = message.getField(Fields3.MDReqID)?.value;
2786
+ if (mdReqID) {
2787
+ const callback = pendingRequests.get(mdReqID);
2788
+ if (callback) {
2789
+ callback(message);
2790
+ pendingRequests.delete(mdReqID);
2791
+ }
2792
+ }
2793
+ } else if (msgType === Messages3.ExecutionReport) {
2794
+ const reqId = message.getField(Fields3.ClOrdID)?.value;
2795
+ const callback = pendingRequests.get(reqId);
2796
+ if (callback) {
2797
+ callback(message);
2798
+ pendingRequests.delete(reqId);
2799
+ }
2800
+ }
2801
+ }
2802
+
2803
+ // src/MCPLocal.ts
2804
+ var MCPLocal = class extends MCPBase {
2805
+ /**
2806
+ * Map to store verified orders before execution
2807
+ * @private
2808
+ */
2809
+ verifiedOrders = /* @__PURE__ */ new Map();
2810
+ /**
2811
+ * Map to store pending requests and their callbacks
2812
+ * @private
2813
+ */
2814
+ pendingRequests = /* @__PURE__ */ new Map();
2815
+ /**
2816
+ * Map to store market data prices for each symbol
2817
+ * @private
2818
+ */
2819
+ marketDataPrices = /* @__PURE__ */ new Map();
2820
+ /**
2821
+ * Maximum number of price history entries to keep per symbol
2822
+ * @private
2823
+ */
2824
+ MAX_PRICE_HISTORY = 1e5;
2825
+ server = new Server(
2826
+ {
2827
+ name: "fixparser",
2828
+ version: "1.0.0"
2829
+ },
2830
+ {
2831
+ capabilities: {
2832
+ tools: Object.entries(toolSchemas).reduce(
2833
+ (acc, [name, { description, schema }]) => {
2834
+ acc[name] = {
2835
+ description,
2836
+ parameters: schema
2837
+ };
2838
+ return acc;
2839
+ },
2840
+ {}
2841
+ )
2842
+ }
2843
+ }
2844
+ );
2845
+ transport = new StdioServerTransport();
2846
+ constructor({ logger, onReady }) {
2847
+ super({ logger, onReady });
2848
+ }
2849
+ async register(parser) {
2850
+ this.parser = parser;
2851
+ this.parser.addOnMessageCallback((message) => {
2852
+ handleMessage(message, this.parser, this.pendingRequests, this.marketDataPrices, this.MAX_PRICE_HISTORY);
2853
+ });
2854
+ this.addWorkflows();
2855
+ await this.server.connect(this.transport);
2856
+ if (this.onReady) {
2857
+ this.onReady();
2858
+ }
2859
+ }
2860
+ addWorkflows() {
2861
+ if (!this.parser) {
2862
+ return;
2863
+ }
2864
+ if (!this.server) {
2865
+ return;
2866
+ }
2867
+ this.server.setRequestHandler(z.object({ method: z.literal("tools/list") }), async () => {
2868
+ return {
2869
+ tools: Object.entries(toolSchemas).map(([name, { description, schema }]) => ({
2870
+ name,
2871
+ description,
2872
+ inputSchema: schema
2873
+ }))
2874
+ };
2875
+ });
2876
+ this.server.setRequestHandler(
2877
+ z.object({
2878
+ method: z.literal("tools/call"),
2879
+ params: z.object({
2880
+ name: z.string(),
2881
+ arguments: z.any(),
2882
+ _meta: z.object({
2883
+ progressToken: z.number()
2884
+ }).optional()
2885
+ })
2886
+ }),
2887
+ async (request) => {
2888
+ const { name, arguments: args } = request.params;
2889
+ const toolHandlers = createToolHandlers(
2890
+ this.parser,
2891
+ this.verifiedOrders,
2892
+ this.pendingRequests,
2893
+ this.marketDataPrices
2894
+ );
2895
+ const handler = toolHandlers[name];
2896
+ if (!handler) {
2897
+ return {
2898
+ content: [
2899
+ {
2900
+ type: "text",
2901
+ text: `Tool not found: ${name}`,
2902
+ uri: name
2903
+ }
2904
+ ],
2905
+ isError: true
2906
+ };
2907
+ }
2908
+ const result = await handler(args);
2909
+ return {
2910
+ content: result.content,
2911
+ isError: result.isError
2912
+ };
2913
+ }
2914
+ );
2915
+ process.on("SIGINT", async () => {
2916
+ await this.server.close();
2917
+ process.exit(0);
2918
+ });
2919
+ }
2920
+ };
2921
+
2922
+ // src/MCPRemote.ts
2923
+ import { randomUUID } from "node:crypto";
2924
+ import { createServer } from "node:http";
2925
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2926
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
2927
+ import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
2928
+ import { z as z2 } from "zod";
2929
+ var transports = {};
2930
+ function jsonSchemaToZod(schema) {
2931
+ if (schema.type === "object") {
2932
+ const shape = {};
2933
+ for (const [key, prop] of Object.entries(schema.properties || {})) {
2934
+ const propSchema = prop;
2935
+ if (propSchema.type === "string") {
2936
+ if (propSchema.enum) {
2937
+ shape[key] = z2.enum(propSchema.enum);
2938
+ } else {
2939
+ shape[key] = z2.string();
2940
+ }
2941
+ } else if (propSchema.type === "number") {
2942
+ shape[key] = z2.number();
2943
+ } else if (propSchema.type === "boolean") {
2944
+ shape[key] = z2.boolean();
2945
+ } else if (propSchema.type === "array") {
2946
+ if (propSchema.items.type === "string") {
2947
+ shape[key] = z2.array(z2.string());
2948
+ } else if (propSchema.items.type === "number") {
2949
+ shape[key] = z2.array(z2.number());
2950
+ } else if (propSchema.items.type === "boolean") {
2951
+ shape[key] = z2.array(z2.boolean());
2952
+ } else {
2953
+ shape[key] = z2.array(z2.any());
2954
+ }
2955
+ } else {
2956
+ shape[key] = z2.any();
2957
+ }
2958
+ }
2959
+ return shape;
2960
+ }
2961
+ return {};
2962
+ }
2963
+ var MCPRemote = class extends MCPBase {
2964
+ /**
2965
+ * Port number the server will listen on.
2966
+ * @private
2967
+ */
2968
+ port;
2969
+ /**
2970
+ * Node.js HTTP server instance created internally.
2971
+ * @private
2972
+ */
2973
+ httpServer;
2974
+ /**
2975
+ * MCP server instance handling MCP protocol logic.
2976
+ * @private
2977
+ */
2978
+ mcpServer;
2979
+ /**
2980
+ * Optional name of the plugin/server instance.
2981
+ * @private
2982
+ */
2983
+ serverName;
2984
+ /**
2985
+ * Optional version string of the plugin/server.
2986
+ * @private
2987
+ */
2988
+ serverVersion;
2989
+ /**
2990
+ * Map to store verified orders before execution
2991
+ * @private
2992
+ */
2993
+ verifiedOrders = /* @__PURE__ */ new Map();
2994
+ /**
2995
+ * Map to store pending requests and their callbacks
2996
+ * @private
2997
+ */
2998
+ pendingRequests = /* @__PURE__ */ new Map();
2999
+ /**
3000
+ * Map to store market data prices for each symbol
3001
+ * @private
3002
+ */
3003
+ marketDataPrices = /* @__PURE__ */ new Map();
3004
+ /**
3005
+ * Maximum number of price history entries to keep per symbol
3006
+ * @private
3007
+ */
3008
+ MAX_PRICE_HISTORY = 1e5;
3009
+ constructor({ port, logger, onReady }) {
3010
+ super({ logger, onReady });
3011
+ this.port = port;
3012
+ }
3013
+ async register(parser) {
3014
+ this.parser = parser;
3015
+ this.logger = parser.logger;
3016
+ this.logger?.log({
3017
+ level: "info",
3018
+ message: `FIXParser (MCP): -- Plugin registered. Creating MCP server on port ${this.port}...`
3019
+ });
3020
+ this.parser.addOnMessageCallback((message) => {
3021
+ if (this.parser) {
3022
+ handleMessage(
3023
+ message,
3024
+ this.parser,
3025
+ this.pendingRequests,
3026
+ this.marketDataPrices,
3027
+ this.MAX_PRICE_HISTORY
3028
+ );
3029
+ }
3030
+ });
3031
+ this.httpServer = createServer(async (req, res) => {
3032
+ if (!req.url || !req.method) {
3033
+ res.writeHead(400);
3034
+ res.end("Bad Request");
3035
+ return;
3036
+ }
3037
+ if (req.url === "/mcp") {
3038
+ const sessionId = req.headers["mcp-session-id"];
3039
+ if (req.method === "POST") {
3040
+ const bodyChunks = [];
3041
+ req.on("data", (chunk) => {
3042
+ bodyChunks.push(chunk);
3043
+ });
3044
+ req.on("end", async () => {
3045
+ let parsed;
3046
+ const body = Buffer.concat(bodyChunks).toString();
3047
+ try {
3048
+ parsed = JSON.parse(body);
3049
+ } catch (error) {
3050
+ void error;
3051
+ res.writeHead(400);
3052
+ res.end(JSON.stringify({ error: "Invalid JSON" }));
3053
+ return;
3054
+ }
3055
+ let transport;
3056
+ if (sessionId && transports[sessionId]) {
3057
+ transport = transports[sessionId];
3058
+ } else if (!sessionId && req.method === "POST" && isInitializeRequest(parsed)) {
3059
+ transport = new StreamableHTTPServerTransport({
3060
+ sessionIdGenerator: () => randomUUID(),
3061
+ onsessioninitialized: (sessionId2) => {
3062
+ transports[sessionId2] = transport;
3063
+ }
3064
+ });
3065
+ transport.onclose = () => {
3066
+ if (transport.sessionId) {
3067
+ delete transports[transport.sessionId];
3068
+ }
3069
+ };
3070
+ this.mcpServer = new McpServer({
3071
+ name: this.serverName || "FIXParser",
3072
+ version: this.serverVersion || "1.0.0"
3073
+ });
3074
+ this.setupTools();
3075
+ await this.mcpServer.connect(transport);
3076
+ } else {
3077
+ res.writeHead(400, { "Content-Type": "application/json" });
3078
+ res.end(
3079
+ JSON.stringify({
3080
+ jsonrpc: "2.0",
3081
+ error: {
3082
+ code: -32e3,
3083
+ message: "Bad Request: No valid session ID provided"
3084
+ },
3085
+ id: null
3086
+ })
3087
+ );
3088
+ return;
3089
+ }
3090
+ try {
3091
+ await transport.handleRequest(req, res, parsed);
3092
+ } catch (error) {
3093
+ this.logger?.log({
3094
+ level: "error",
3095
+ message: `Error handling request: ${error}`
3096
+ });
3097
+ throw error;
3098
+ }
3099
+ });
3100
+ } else if (req.method === "GET" || req.method === "DELETE") {
3101
+ if (!sessionId || !transports[sessionId]) {
3102
+ res.writeHead(400);
3103
+ res.end("Invalid or missing session ID");
3104
+ return;
3105
+ }
3106
+ const transport = transports[sessionId];
3107
+ try {
3108
+ await transport.handleRequest(req, res);
3109
+ } catch (error) {
3110
+ this.logger?.log({
3111
+ level: "error",
3112
+ message: `Error handling ${req.method} request: ${error}`
3113
+ });
3114
+ throw error;
3115
+ }
3116
+ } else {
3117
+ this.logger?.log({
3118
+ level: "error",
3119
+ message: `Method not allowed: ${req.method}`
3120
+ });
3121
+ res.writeHead(405);
3122
+ res.end("Method Not Allowed");
3123
+ }
3124
+ } else {
3125
+ res.writeHead(404);
3126
+ res.end("Not Found");
3127
+ }
3128
+ });
3129
+ this.httpServer.listen(this.port, () => {
3130
+ this.logger?.log({
3131
+ level: "info",
3132
+ message: `FIXParser (MCP): -- Server listening on http://localhost:${this.port}...`
3133
+ });
3134
+ });
3135
+ if (this.onReady) {
3136
+ this.onReady();
3137
+ }
3138
+ }
3139
+ setupTools() {
3140
+ if (!this.parser) {
3141
+ this.logger?.log({
3142
+ level: "error",
3143
+ message: "FIXParser (MCP): -- FIXParser instance not initialized. Ignoring setup of tools..."
3144
+ });
3145
+ return;
3146
+ }
3147
+ if (!this.mcpServer) {
3148
+ this.logger?.log({
3149
+ level: "error",
3150
+ message: "FIXParser (MCP): -- MCP Server not initialized. Ignoring setup of tools..."
3151
+ });
3152
+ return;
3153
+ }
3154
+ const toolHandlers = createToolHandlers(
3155
+ this.parser,
3156
+ this.verifiedOrders,
3157
+ this.pendingRequests,
3158
+ this.marketDataPrices
3159
+ );
3160
+ Object.entries(toolSchemas).forEach(([name, { description, schema }]) => {
3161
+ this.mcpServer?.registerTool(
3162
+ name,
3163
+ {
3164
+ description,
3165
+ inputSchema: jsonSchemaToZod(schema)
3166
+ },
3167
+ async (args) => {
3168
+ const handler = toolHandlers[name];
3169
+ if (!handler) {
3170
+ return {
3171
+ content: [
3172
+ {
3173
+ type: "text",
3174
+ text: `Tool not found: ${name}`
3175
+ }
3176
+ ],
3177
+ isError: true
3178
+ };
3179
+ }
3180
+ const result = await handler(args);
3181
+ return {
3182
+ content: result.content,
3183
+ isError: result.isError
3184
+ };
3185
+ }
3186
+ );
3187
+ });
3188
+ }
3189
+ };
3190
+ export {
3191
+ MCPLocal,
3192
+ MCPRemote
3193
+ };
3194
+ //# sourceMappingURL=index.mjs.map