fixparser-plugin-mcp 9.1.7-abf6e45c → 9.1.7-ad8cf02b

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