fixparser-plugin-mcp 9.1.7-71fc8a2b → 9.1.7-74db6dbc

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