fixparser-plugin-mcp 9.1.7-c5ae06ce → 9.1.7-c6228661

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,38 +5,1536 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
5
5
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
6
6
  import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
7
7
  import { z } from "zod";
8
- import {
9
- Field,
10
- Fields,
11
- HandlInst,
12
- MDEntryType,
13
- Messages,
14
- OrdType,
15
- SubscriptionRequestType,
16
- TimeInForce
17
- } from "fixparser";
18
- var transports = {};
19
- var MCPRemote = class {
20
- /**
21
- * Port number the server will listen on.
22
- * @private
23
- */
24
- port;
8
+
9
+ // src/MCPBase.ts
10
+ var MCPBase = class {
25
11
  /**
26
12
  * Optional logger instance for diagnostics and output.
27
- * @private
13
+ * @protected
28
14
  */
29
15
  logger;
30
16
  /**
31
17
  * FIXParser instance, set during plugin register().
32
- * @private
18
+ * @protected
33
19
  */
34
20
  parser;
21
+ /**
22
+ * Called when server is setup and listening.
23
+ * @protected
24
+ */
25
+ onReady = void 0;
26
+ /**
27
+ * Map to store verified orders before execution
28
+ * @protected
29
+ */
30
+ verifiedOrders = /* @__PURE__ */ new Map();
31
+ /**
32
+ * Map to store pending market data requests
33
+ * @protected
34
+ */
35
+ pendingRequests = /* @__PURE__ */ new Map();
36
+ /**
37
+ * Map to store market data prices
38
+ * @protected
39
+ */
40
+ marketDataPrices = /* @__PURE__ */ new Map();
41
+ /**
42
+ * Maximum number of price history entries to keep per symbol
43
+ * @protected
44
+ */
45
+ MAX_PRICE_HISTORY = 1e5;
46
+ constructor({ logger, onReady }) {
47
+ this.logger = logger;
48
+ this.onReady = onReady;
49
+ }
50
+ };
51
+
52
+ // src/schemas/schemas.ts
53
+ var toolSchemas = {
54
+ parse: {
55
+ description: "Parses a FIX message and describes it in plain language",
56
+ schema: {
57
+ type: "object",
58
+ properties: {
59
+ fixString: { type: "string" }
60
+ },
61
+ required: ["fixString"]
62
+ }
63
+ },
64
+ parseToJSON: {
65
+ description: "Parses a FIX message into JSON",
66
+ schema: {
67
+ type: "object",
68
+ properties: {
69
+ fixString: { type: "string" }
70
+ },
71
+ required: ["fixString"]
72
+ }
73
+ },
74
+ verifyOrder: {
75
+ description: "Verifies order parameters before execution. verifyOrder must be called before executeOrder.",
76
+ schema: {
77
+ type: "object",
78
+ properties: {
79
+ clOrdID: { type: "string" },
80
+ handlInst: {
81
+ type: "string",
82
+ enum: ["1", "2", "3"],
83
+ description: "Handling Instructions: 1=Automated Execution No Intervention, 2=Automated Execution Intervention OK, 3=Manual Order"
84
+ },
85
+ quantity: { type: "string" },
86
+ price: { type: "string" },
87
+ ordType: {
88
+ type: "string",
89
+ enum: [
90
+ "1",
91
+ "2",
92
+ "3",
93
+ "4",
94
+ "5",
95
+ "6",
96
+ "7",
97
+ "8",
98
+ "9",
99
+ "A",
100
+ "B",
101
+ "C",
102
+ "D",
103
+ "E",
104
+ "F",
105
+ "G",
106
+ "H",
107
+ "I",
108
+ "J",
109
+ "K",
110
+ "L",
111
+ "M",
112
+ "P",
113
+ "Q",
114
+ "R",
115
+ "S"
116
+ ],
117
+ description: "Order Type: 1=Market, 2=Limit, 3=Stop, 4=StopLimit, 5=MarketOnClose, 6=WithOrWithout, 7=LimitOrBetter, 8=LimitWithOrWithout, 9=OnBasis, A=OnClose, B=LimitOnClose, C=ForexMarket, D=PreviouslyQuoted, E=PreviouslyIndicated, F=ForexLimit, G=ForexSwap, H=ForexPreviouslyQuoted, I=Funari, J=MarketIfTouched, K=MarketWithLeftOverAsLimit, L=PreviousFundValuationPoint, M=NextFundValuationPoint, P=Pegged, Q=CounterOrderSelection, R=StopOnBidOrOffer, S=StopLimitOnBidOrOffer"
118
+ },
119
+ side: {
120
+ type: "string",
121
+ enum: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H"],
122
+ description: "Side: 1=Buy, 2=Sell, 3=BuyMinus, 4=SellPlus, 5=SellShort, 6=SellShortExempt, 7=Undisclosed, 8=Cross, 9=CrossShort, A=CrossShortExempt, B=AsDefined, C=Opposite, D=Subscribe, E=Redeem, F=Lend, G=Borrow, H=SellUndisclosed"
123
+ },
124
+ symbol: { type: "string" },
125
+ timeInForce: {
126
+ type: "string",
127
+ enum: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C"],
128
+ description: "Time In Force: 0=Day, 1=GoodTillCancel, 2=AtTheOpening, 3=ImmediateOrCancel, 4=FillOrKill, 5=GoodTillCrossing, 6=GoodTillDate, 7=AtTheClose, 8=GoodThroughCrossing, 9=AtCrossing, A=GoodForTime, B=GoodForAuction, C=GoodForMonth"
129
+ }
130
+ },
131
+ required: ["clOrdID", "handlInst", "quantity", "price", "ordType", "side", "symbol", "timeInForce"]
132
+ }
133
+ },
134
+ executeOrder: {
135
+ description: "Executes a verified order. verifyOrder must be called before executeOrder.",
136
+ schema: {
137
+ type: "object",
138
+ properties: {
139
+ clOrdID: { type: "string" },
140
+ handlInst: {
141
+ type: "string",
142
+ enum: ["1", "2", "3"],
143
+ description: "Handling Instructions: 1=Automated Execution No Intervention, 2=Automated Execution Intervention OK, 3=Manual Order"
144
+ },
145
+ quantity: { type: "string" },
146
+ price: { type: "string" },
147
+ ordType: {
148
+ type: "string",
149
+ enum: [
150
+ "1",
151
+ "2",
152
+ "3",
153
+ "4",
154
+ "5",
155
+ "6",
156
+ "7",
157
+ "8",
158
+ "9",
159
+ "A",
160
+ "B",
161
+ "C",
162
+ "D",
163
+ "E",
164
+ "F",
165
+ "G",
166
+ "H",
167
+ "I",
168
+ "J",
169
+ "K",
170
+ "L",
171
+ "M",
172
+ "P",
173
+ "Q",
174
+ "R",
175
+ "S"
176
+ ],
177
+ description: "Order Type: 1=Market, 2=Limit, 3=Stop, 4=StopLimit, 5=MarketOnClose, 6=WithOrWithout, 7=LimitOrBetter, 8=LimitWithOrWithout, 9=OnBasis, A=OnClose, B=LimitOnClose, C=ForexMarket, D=PreviouslyQuoted, E=PreviouslyIndicated, F=ForexLimit, G=ForexSwap, H=ForexPreviouslyQuoted, I=Funari, J=MarketIfTouched, K=MarketWithLeftOverAsLimit, L=PreviousFundValuationPoint, M=NextFundValuationPoint, P=Pegged, Q=CounterOrderSelection, R=StopOnBidOrOffer, S=StopLimitOnBidOrOffer"
178
+ },
179
+ side: {
180
+ type: "string",
181
+ enum: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H"],
182
+ description: "Side: 1=Buy, 2=Sell, 3=BuyMinus, 4=SellPlus, 5=SellShort, 6=SellShortExempt, 7=Undisclosed, 8=Cross, 9=CrossShort, A=CrossShortExempt, B=AsDefined, C=Opposite, D=Subscribe, E=Redeem, F=Lend, G=Borrow, H=SellUndisclosed"
183
+ },
184
+ symbol: { type: "string" },
185
+ timeInForce: {
186
+ type: "string",
187
+ enum: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C"],
188
+ description: "Time In Force: 0=Day, 1=GoodTillCancel, 2=AtTheOpening, 3=ImmediateOrCancel, 4=FillOrKill, 5=GoodTillCrossing, 6=GoodTillDate, 7=AtTheClose, 8=GoodThroughCrossing, 9=AtCrossing, A=GoodForTime, B=GoodForAuction, C=GoodForMonth"
189
+ }
190
+ },
191
+ required: ["clOrdID", "handlInst", "quantity", "price", "ordType", "side", "symbol", "timeInForce"]
192
+ }
193
+ },
194
+ marketDataRequest: {
195
+ description: "Requests market data for specified symbols",
196
+ schema: {
197
+ type: "object",
198
+ properties: {
199
+ mdUpdateType: {
200
+ type: "string",
201
+ enum: ["0", "1"],
202
+ description: "Market Data Update Type: 0=Full Refresh, 1=Incremental Refresh"
203
+ },
204
+ symbols: { type: "array", items: { type: "string" } },
205
+ mdReqID: { type: "string" },
206
+ subscriptionRequestType: {
207
+ type: "string",
208
+ enum: ["0", "1", "2"],
209
+ description: "Subscription Request Type: 0=Snapshot, 1=Snapshot + Updates, 2=Disable Previous Snapshot + Update Request"
210
+ },
211
+ mdEntryTypes: {
212
+ type: "array",
213
+ items: {
214
+ type: "string",
215
+ enum: [
216
+ "0",
217
+ "1",
218
+ "2",
219
+ "3",
220
+ "4",
221
+ "5",
222
+ "6",
223
+ "7",
224
+ "8",
225
+ "9",
226
+ "A",
227
+ "B",
228
+ "C",
229
+ "D",
230
+ "E",
231
+ "F",
232
+ "G",
233
+ "H",
234
+ "I",
235
+ "J",
236
+ "K",
237
+ "L",
238
+ "M",
239
+ "N",
240
+ "O",
241
+ "P",
242
+ "Q",
243
+ "R",
244
+ "S",
245
+ "T",
246
+ "U",
247
+ "V",
248
+ "W",
249
+ "X",
250
+ "Y",
251
+ "Z"
252
+ ]
253
+ },
254
+ description: "Market Data Entry Types: 0=Bid, 1=Offer, 2=Trade, 3=Index Value, 4=Opening Price, 5=Closing Price, 6=Settlement Price, 7=High Price, 8=Low Price, 9=Trade Volume, A=Open Interest, B=Simulated Sell Price, C=Simulated Buy Price, D=Empty Book, E=Session High Bid, F=Session Low Offer, G=Fixing Price, H=Electronic Volume, I=Threshold Limits and Price Band Variation, J=Clearing Price, K=Open Interest Change, L=Last Trade Price, M=Last Trade Volume, N=Last Trade Time, O=Last Trade Tick, P=Last Trade Exchange, Q=Last Trade ID, R=Last Trade Side, S=Last Trade Price Change, T=Last Trade Price Change Percent, U=Last Trade Price Change Basis Points, V=Last Trade Price Change Points, W=Last Trade Price Change Ticks, X=Last Trade Price Change Ticks Percent, Y=Last Trade Price Change Ticks Basis Points, Z=Last Trade Price Change Ticks Points"
255
+ }
256
+ },
257
+ required: ["mdUpdateType", "symbols", "mdReqID", "subscriptionRequestType"]
258
+ }
259
+ },
260
+ getStockGraph: {
261
+ description: "Generates a price chart for a given symbol",
262
+ schema: {
263
+ type: "object",
264
+ properties: {
265
+ symbol: { type: "string" }
266
+ },
267
+ required: ["symbol"]
268
+ }
269
+ },
270
+ getStockPriceHistory: {
271
+ description: "Returns price history for a given symbol",
272
+ schema: {
273
+ type: "object",
274
+ properties: {
275
+ symbol: { type: "string" }
276
+ },
277
+ required: ["symbol"]
278
+ }
279
+ },
280
+ technicalAnalysis: {
281
+ description: "Performs comprehensive technical analysis on market data for a given symbol, including indicators like SMA, EMA, RSI, Bollinger Bands, and trading signals",
282
+ schema: {
283
+ type: "object",
284
+ properties: {
285
+ symbol: {
286
+ type: "string",
287
+ description: "The trading symbol to analyze (e.g., AAPL, MSFT, EURUSD)"
288
+ }
289
+ },
290
+ required: ["symbol"]
291
+ }
292
+ }
293
+ };
294
+
295
+ // src/tools/analytics.ts
296
+ function sum(numbers) {
297
+ return numbers.reduce((acc, val) => acc + val, 0);
298
+ }
299
+ var TechnicalAnalyzer = class {
300
+ prices;
301
+ volumes;
302
+ highs;
303
+ lows;
304
+ constructor(data) {
305
+ this.prices = data.map((d) => d.trade > 0 ? d.trade : d.midPrice);
306
+ this.volumes = data.map((d) => d.volume);
307
+ this.highs = data.map((d) => d.tradingSessionHighPrice > 0 ? d.tradingSessionHighPrice : d.trade);
308
+ this.lows = data.map((d) => d.tradingSessionLowPrice > 0 ? d.tradingSessionLowPrice : d.trade);
309
+ }
310
+ // Calculate Simple Moving Average
311
+ calculateSMA(data, period) {
312
+ const sma = [];
313
+ for (let i = period - 1; i < data.length; i++) {
314
+ const sum2 = data.slice(i - period + 1, i + 1).reduce((a, b) => a + b, 0);
315
+ sma.push(sum2 / period);
316
+ }
317
+ return sma;
318
+ }
319
+ // Calculate Exponential Moving Average
320
+ calculateEMA(data, period) {
321
+ const multiplier = 2 / (period + 1);
322
+ const ema = [data[0]];
323
+ for (let i = 1; i < data.length; i++) {
324
+ ema.push(data[i] * multiplier + ema[i - 1] * (1 - multiplier));
325
+ }
326
+ return ema;
327
+ }
328
+ // Calculate RSI
329
+ calculateRSI(data, period = 14) {
330
+ if (data.length < period + 1) return [];
331
+ const changes = [];
332
+ for (let i = 1; i < data.length; i++) {
333
+ changes.push(data[i] - data[i - 1]);
334
+ }
335
+ const gains = changes.map((change) => change > 0 ? change : 0);
336
+ const losses = changes.map((change) => change < 0 ? Math.abs(change) : 0);
337
+ let avgGain = gains.slice(0, period).reduce((a, b) => a + b, 0) / period;
338
+ let avgLoss = losses.slice(0, period).reduce((a, b) => a + b, 0) / period;
339
+ const rsi = [];
340
+ for (let i = period; i < changes.length; i++) {
341
+ const rs = avgGain / avgLoss;
342
+ rsi.push(100 - 100 / (1 + rs));
343
+ avgGain = (avgGain * (period - 1) + gains[i]) / period;
344
+ avgLoss = (avgLoss * (period - 1) + losses[i]) / period;
345
+ }
346
+ return rsi;
347
+ }
348
+ // Calculate Bollinger Bands
349
+ calculateBollingerBands(data, period = 20, stdDev = 2) {
350
+ if (data.length < period) return [];
351
+ const sma = this.calculateSMA(data, period);
352
+ const bands = [];
353
+ for (let i = 0; i < sma.length; i++) {
354
+ const dataSlice = data.slice(i, i + period);
355
+ const mean = sma[i];
356
+ const variance = dataSlice.reduce((sum2, price) => sum2 + (price - mean) ** 2, 0) / period;
357
+ const standardDeviation = Math.sqrt(variance);
358
+ bands.push({
359
+ upper: mean + standardDeviation * stdDev,
360
+ middle: mean,
361
+ lower: mean - standardDeviation * stdDev
362
+ });
363
+ }
364
+ return bands;
365
+ }
366
+ // Calculate maximum drawdown
367
+ calculateMaxDrawdown(prices) {
368
+ let maxPrice = prices[0];
369
+ let maxDrawdown = 0;
370
+ for (let i = 1; i < prices.length; i++) {
371
+ if (prices[i] > maxPrice) {
372
+ maxPrice = prices[i];
373
+ }
374
+ const drawdown = (maxPrice - prices[i]) / maxPrice;
375
+ if (drawdown > maxDrawdown) {
376
+ maxDrawdown = drawdown;
377
+ }
378
+ }
379
+ return maxDrawdown;
380
+ }
381
+ // Calculate price changes for volatility
382
+ calculatePriceChanges() {
383
+ const changes = [];
384
+ for (let i = 1; i < this.prices.length; i++) {
385
+ changes.push((this.prices[i] - this.prices[i - 1]) / this.prices[i - 1]);
386
+ }
387
+ return changes;
388
+ }
389
+ // Generate comprehensive market analysis
390
+ analyze() {
391
+ const currentPrice = this.prices[this.prices.length - 1];
392
+ const startPrice = this.prices[0];
393
+ const sessionHigh = Math.max(...this.highs);
394
+ const sessionLow = Math.min(...this.lows);
395
+ const totalVolume = sum(this.volumes);
396
+ const avgVolume = totalVolume / this.volumes.length;
397
+ const priceChanges = this.calculatePriceChanges();
398
+ const volatility = priceChanges.length > 0 ? Math.sqrt(
399
+ priceChanges.reduce((sum2, change) => sum2 + change ** 2, 0) / priceChanges.length
400
+ ) * Math.sqrt(252) * 100 : 0;
401
+ const sessionReturn = (currentPrice - startPrice) / startPrice * 100;
402
+ const pricePosition = (currentPrice - sessionLow) / (sessionHigh - sessionLow) * 100;
403
+ const trueVWAP = this.prices.reduce((sum2, price, i) => sum2 + price * this.volumes[i], 0) / totalVolume;
404
+ 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;
405
+ 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;
406
+ const maxDrawdown = this.calculateMaxDrawdown(this.prices);
407
+ return {
408
+ currentPrice,
409
+ startPrice,
410
+ sessionHigh,
411
+ sessionLow,
412
+ totalVolume,
413
+ avgVolume,
414
+ volatility,
415
+ sessionReturn,
416
+ pricePosition,
417
+ trueVWAP,
418
+ momentum5,
419
+ momentum10,
420
+ maxDrawdown
421
+ };
422
+ }
423
+ // Generate technical indicators
424
+ getTechnicalIndicators() {
425
+ return {
426
+ sma5: this.calculateSMA(this.prices, 5),
427
+ sma10: this.calculateSMA(this.prices, 10),
428
+ ema8: this.calculateEMA(this.prices, 8),
429
+ ema21: this.calculateEMA(this.prices, 21),
430
+ rsi: this.calculateRSI(this.prices, 14),
431
+ bollinger: this.calculateBollingerBands(this.prices, 20, 2)
432
+ };
433
+ }
434
+ // Generate trading signals
435
+ generateSignals() {
436
+ const analysis = this.analyze();
437
+ let bullishSignals = 0;
438
+ let bearishSignals = 0;
439
+ const signals = [];
440
+ if (analysis.currentPrice > analysis.trueVWAP) {
441
+ signals.push(
442
+ `\u2713 BULLISH: Price above VWAP (+${((analysis.currentPrice - analysis.trueVWAP) / analysis.trueVWAP * 100).toFixed(2)}%)`
443
+ );
444
+ bullishSignals++;
445
+ } else {
446
+ signals.push(
447
+ `\u2717 BEARISH: Price below VWAP (${((analysis.currentPrice - analysis.trueVWAP) / analysis.trueVWAP * 100).toFixed(2)}%)`
448
+ );
449
+ bearishSignals++;
450
+ }
451
+ if (analysis.momentum5 > 0 && analysis.momentum10 > 0) {
452
+ signals.push("\u2713 BULLISH: Positive momentum on both timeframes");
453
+ bullishSignals++;
454
+ } else if (analysis.momentum5 < 0 && analysis.momentum10 < 0) {
455
+ signals.push("\u2717 BEARISH: Negative momentum on both timeframes");
456
+ bearishSignals++;
457
+ } else {
458
+ signals.push("\u25D0 MIXED: Conflicting momentum signals");
459
+ }
460
+ const currentVolume = this.volumes[this.volumes.length - 1];
461
+ const volumeRatio = currentVolume / analysis.avgVolume;
462
+ if (volumeRatio > 1.2 && analysis.sessionReturn > 0) {
463
+ signals.push("\u2713 BULLISH: Above-average volume supporting upward move");
464
+ bullishSignals++;
465
+ } else if (volumeRatio > 1.2 && analysis.sessionReturn < 0) {
466
+ signals.push("\u2717 BEARISH: Above-average volume supporting downward move");
467
+ bearishSignals++;
468
+ } else {
469
+ signals.push("\u25D0 NEUTRAL: Volume not providing clear direction");
470
+ }
471
+ if (analysis.pricePosition > 65 && analysis.volatility > 30) {
472
+ signals.push("\u2717 BEARISH: High in range with elevated volatility - reversal risk");
473
+ bearishSignals++;
474
+ } else if (analysis.pricePosition < 35 && analysis.volatility > 30) {
475
+ signals.push("\u2713 BULLISH: Low in range with volatility - potential bounce");
476
+ bullishSignals++;
477
+ } else {
478
+ signals.push("\u25D0 NEUTRAL: Price position and volatility not extreme");
479
+ }
480
+ return { bullishSignals, bearishSignals, signals };
481
+ }
482
+ // Generate comprehensive JSON analysis
483
+ generateJSONAnalysis(symbol) {
484
+ const analysis = this.analyze();
485
+ const indicators = this.getTechnicalIndicators();
486
+ const signals = this.generateSignals();
487
+ const currentSMA5 = indicators.sma5.length > 0 ? indicators.sma5[indicators.sma5.length - 1] : null;
488
+ const currentSMA10 = indicators.sma10.length > 0 ? indicators.sma10[indicators.sma10.length - 1] : null;
489
+ const currentEMA8 = indicators.ema8[indicators.ema8.length - 1];
490
+ const currentEMA21 = indicators.ema21[indicators.ema21.length - 1];
491
+ const currentRSI = indicators.rsi.length > 0 ? indicators.rsi[indicators.rsi.length - 1] : null;
492
+ const currentBB = indicators.bollinger.length > 0 ? indicators.bollinger[indicators.bollinger.length - 1] : null;
493
+ const currentVolume = this.volumes[this.volumes.length - 1];
494
+ const volumeRatio = currentVolume / analysis.avgVolume;
495
+ const currentDrawdown = (analysis.sessionHigh - analysis.currentPrice) / analysis.sessionHigh * 100;
496
+ const rangeWidth = (analysis.sessionHigh - analysis.sessionLow) / analysis.sessionLow * 100;
497
+ const priceVsVWAP = (analysis.currentPrice - analysis.trueVWAP) / analysis.trueVWAP * 100;
498
+ const totalScore = signals.bullishSignals - signals.bearishSignals;
499
+ const overallSignal = totalScore > 0 ? "BULLISH_BIAS" : totalScore < 0 ? "BEARISH_BIAS" : "NEUTRAL";
500
+ const targetEntry = Math.max(analysis.sessionLow * 1.005, analysis.trueVWAP * 0.998);
501
+ const stopLoss = analysis.sessionLow * 0.995;
502
+ const profitTarget = analysis.sessionHigh * 0.995;
503
+ const riskRewardRatio = (profitTarget - analysis.currentPrice) / (analysis.currentPrice - stopLoss);
504
+ return {
505
+ symbol,
506
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
507
+ marketStructure: {
508
+ currentPrice: analysis.currentPrice,
509
+ startPrice: analysis.startPrice,
510
+ sessionHigh: analysis.sessionHigh,
511
+ sessionLow: analysis.sessionLow,
512
+ rangeWidth,
513
+ totalVolume: analysis.totalVolume,
514
+ sessionPerformance: analysis.sessionReturn,
515
+ positionInRange: analysis.pricePosition
516
+ },
517
+ volatility: {
518
+ impliedVolatility: analysis.volatility,
519
+ maxDrawdown: analysis.maxDrawdown * 100,
520
+ currentDrawdown
521
+ },
522
+ technicalIndicators: {
523
+ sma5: currentSMA5,
524
+ sma10: currentSMA10,
525
+ ema8: currentEMA8,
526
+ ema21: currentEMA21,
527
+ rsi: currentRSI,
528
+ bollingerBands: currentBB ? {
529
+ upper: currentBB.upper,
530
+ middle: currentBB.middle,
531
+ lower: currentBB.lower,
532
+ position: (analysis.currentPrice - currentBB.lower) / (currentBB.upper - currentBB.lower) * 100
533
+ } : null
534
+ },
535
+ volumeAnalysis: {
536
+ currentVolume,
537
+ averageVolume: Math.round(analysis.avgVolume),
538
+ volumeRatio,
539
+ trueVWAP: analysis.trueVWAP,
540
+ priceVsVWAP
541
+ },
542
+ momentum: {
543
+ momentum5: analysis.momentum5,
544
+ momentum10: analysis.momentum10,
545
+ sessionROC: analysis.sessionReturn
546
+ },
547
+ tradingSignals: {
548
+ ...signals,
549
+ overallSignal,
550
+ signalScore: totalScore
551
+ },
552
+ riskManagement: {
553
+ targetEntry,
554
+ stopLoss,
555
+ profitTarget,
556
+ riskRewardRatio
557
+ }
558
+ };
559
+ }
560
+ };
561
+ var createTechnicalAnalysisHandler = (marketDataPrices) => {
562
+ return async (args) => {
563
+ try {
564
+ const symbol = args.symbol;
565
+ const priceHistory = marketDataPrices.get(symbol) || [];
566
+ if (priceHistory.length === 0) {
567
+ return {
568
+ content: [
569
+ {
570
+ type: "text",
571
+ text: `No price data available for ${symbol}. Please request market data first.`,
572
+ uri: "technicalAnalysis"
573
+ }
574
+ ]
575
+ };
576
+ }
577
+ const analyzer = new TechnicalAnalyzer(priceHistory);
578
+ const analysis = analyzer.generateJSONAnalysis(symbol);
579
+ return {
580
+ content: [
581
+ {
582
+ type: "text",
583
+ text: `Technical Analysis for ${symbol}:
584
+
585
+ ${JSON.stringify(analysis, null, 2)}`,
586
+ uri: "technicalAnalysis"
587
+ }
588
+ ]
589
+ };
590
+ } catch (error) {
591
+ return {
592
+ content: [
593
+ {
594
+ type: "text",
595
+ text: `Error performing technical analysis: ${error instanceof Error ? error.message : "Unknown error"}`,
596
+ uri: "technicalAnalysis"
597
+ }
598
+ ],
599
+ isError: true
600
+ };
601
+ }
602
+ };
603
+ };
604
+
605
+ // src/tools/marketData.ts
606
+ import { Field, Fields, MDEntryType, Messages } from "fixparser";
607
+ import QuickChart from "quickchart-js";
608
+ var createMarketDataRequestHandler = (parser, pendingRequests) => {
609
+ return async (args) => {
610
+ try {
611
+ parser.logger.log({
612
+ level: "info",
613
+ message: `Sending market data request for symbols: ${args.symbols.join(", ")}`
614
+ });
615
+ const response = new Promise((resolve) => {
616
+ pendingRequests.set(args.mdReqID, resolve);
617
+ parser.logger.log({
618
+ level: "info",
619
+ message: `Registered callback for market data request ID: ${args.mdReqID}`
620
+ });
621
+ });
622
+ const entryTypes = args.mdEntryTypes || [
623
+ MDEntryType.Bid,
624
+ MDEntryType.Offer,
625
+ MDEntryType.Trade,
626
+ MDEntryType.IndexValue,
627
+ MDEntryType.OpeningPrice,
628
+ MDEntryType.ClosingPrice,
629
+ MDEntryType.SettlementPrice,
630
+ MDEntryType.TradingSessionHighPrice,
631
+ MDEntryType.TradingSessionLowPrice,
632
+ MDEntryType.VWAP,
633
+ MDEntryType.Imbalance,
634
+ MDEntryType.TradeVolume,
635
+ MDEntryType.OpenInterest,
636
+ MDEntryType.CompositeUnderlyingPrice,
637
+ MDEntryType.SimulatedSellPrice,
638
+ MDEntryType.SimulatedBuyPrice,
639
+ MDEntryType.MarginRate,
640
+ MDEntryType.MidPrice,
641
+ MDEntryType.EmptyBook,
642
+ MDEntryType.SettleHighPrice,
643
+ MDEntryType.SettleLowPrice,
644
+ MDEntryType.PriorSettlePrice,
645
+ MDEntryType.SessionHighBid,
646
+ MDEntryType.SessionLowOffer,
647
+ MDEntryType.EarlyPrices,
648
+ MDEntryType.AuctionClearingPrice,
649
+ MDEntryType.SwapValueFactor,
650
+ MDEntryType.DailyValueAdjustmentForLongPositions,
651
+ MDEntryType.CumulativeValueAdjustmentForLongPositions,
652
+ MDEntryType.DailyValueAdjustmentForShortPositions,
653
+ MDEntryType.CumulativeValueAdjustmentForShortPositions,
654
+ MDEntryType.FixingPrice,
655
+ MDEntryType.CashRate,
656
+ MDEntryType.RecoveryRate,
657
+ MDEntryType.RecoveryRateForLong,
658
+ MDEntryType.RecoveryRateForShort,
659
+ MDEntryType.MarketBid,
660
+ MDEntryType.MarketOffer,
661
+ MDEntryType.ShortSaleMinPrice,
662
+ MDEntryType.PreviousClosingPrice,
663
+ MDEntryType.ThresholdLimitPriceBanding,
664
+ MDEntryType.DailyFinancingValue,
665
+ MDEntryType.AccruedFinancingValue,
666
+ MDEntryType.TWAP
667
+ ];
668
+ const messageFields = [
669
+ new Field(Fields.MsgType, Messages.MarketDataRequest),
670
+ new Field(Fields.SenderCompID, parser.sender),
671
+ new Field(Fields.MsgSeqNum, parser.getNextTargetMsgSeqNum()),
672
+ new Field(Fields.TargetCompID, parser.target),
673
+ new Field(Fields.SendingTime, parser.getTimestamp()),
674
+ new Field(Fields.MDReqID, args.mdReqID),
675
+ new Field(Fields.SubscriptionRequestType, args.subscriptionRequestType),
676
+ new Field(Fields.MarketDepth, 0),
677
+ new Field(Fields.MDUpdateType, args.mdUpdateType)
678
+ ];
679
+ messageFields.push(new Field(Fields.NoRelatedSym, args.symbols.length));
680
+ args.symbols.forEach((symbol) => {
681
+ messageFields.push(new Field(Fields.Symbol, symbol));
682
+ });
683
+ messageFields.push(new Field(Fields.NoMDEntryTypes, entryTypes.length));
684
+ entryTypes.forEach((entryType) => {
685
+ messageFields.push(new Field(Fields.MDEntryType, entryType));
686
+ });
687
+ const mdr = parser.createMessage(...messageFields);
688
+ if (!parser.connected) {
689
+ parser.logger.log({
690
+ level: "error",
691
+ message: "Not connected. Cannot send market data request."
692
+ });
693
+ return {
694
+ content: [
695
+ {
696
+ type: "text",
697
+ text: "Error: Not connected. Ignoring message.",
698
+ uri: "marketDataRequest"
699
+ }
700
+ ],
701
+ isError: true
702
+ };
703
+ }
704
+ parser.logger.log({
705
+ level: "info",
706
+ message: `Sending market data request message: ${JSON.stringify(mdr?.toFIXJSON())}`
707
+ });
708
+ parser.send(mdr);
709
+ const fixData = await response;
710
+ parser.logger.log({
711
+ level: "info",
712
+ message: `Received market data response for request ID: ${args.mdReqID}`
713
+ });
714
+ return {
715
+ content: [
716
+ {
717
+ type: "text",
718
+ text: `Market data for ${args.symbols.join(", ")}: ${JSON.stringify(fixData.toFIXJSON())}`,
719
+ uri: "marketDataRequest"
720
+ }
721
+ ]
722
+ };
723
+ } catch (error) {
724
+ return {
725
+ content: [
726
+ {
727
+ type: "text",
728
+ text: `Error: ${error instanceof Error ? error.message : "Failed to request market data"}`,
729
+ uri: "marketDataRequest"
730
+ }
731
+ ],
732
+ isError: true
733
+ };
734
+ }
735
+ };
736
+ };
737
+ var createGetStockGraphHandler = (marketDataPrices) => {
738
+ return async (args) => {
739
+ try {
740
+ const symbol = args.symbol;
741
+ const priceHistory = marketDataPrices.get(symbol) || [];
742
+ if (priceHistory.length === 0) {
743
+ return {
744
+ content: [
745
+ {
746
+ type: "text",
747
+ text: `No price data available for ${symbol}`,
748
+ uri: "getStockGraph"
749
+ }
750
+ ]
751
+ };
752
+ }
753
+ const chart = new QuickChart();
754
+ chart.setWidth(1200);
755
+ chart.setHeight(600);
756
+ chart.setBackgroundColor("transparent");
757
+ const labels = priceHistory.map((point) => new Date(point.timestamp).toLocaleTimeString());
758
+ const bidData = priceHistory.map((point) => point.bid);
759
+ const offerData = priceHistory.map((point) => point.offer);
760
+ const spreadData = priceHistory.map((point) => point.spread);
761
+ const volumeData = priceHistory.map((point) => point.volume);
762
+ const tradeData = priceHistory.map((point) => point.trade);
763
+ const vwapData = priceHistory.map((point) => point.vwap);
764
+ const twapData = priceHistory.map((point) => point.twap);
765
+ const config = {
766
+ type: "line",
767
+ data: {
768
+ labels,
769
+ datasets: [
770
+ {
771
+ label: "Bid",
772
+ data: bidData,
773
+ borderColor: "#28a745",
774
+ backgroundColor: "rgba(40, 167, 69, 0.1)",
775
+ fill: false,
776
+ tension: 0.4
777
+ },
778
+ {
779
+ label: "Offer",
780
+ data: offerData,
781
+ borderColor: "#dc3545",
782
+ backgroundColor: "rgba(220, 53, 69, 0.1)",
783
+ fill: false,
784
+ tension: 0.4
785
+ },
786
+ {
787
+ label: "Spread",
788
+ data: spreadData,
789
+ borderColor: "#6c757d",
790
+ backgroundColor: "rgba(108, 117, 125, 0.1)",
791
+ fill: false,
792
+ tension: 0.4
793
+ },
794
+ {
795
+ label: "Trade",
796
+ data: tradeData,
797
+ borderColor: "#ffc107",
798
+ backgroundColor: "rgba(255, 193, 7, 0.1)",
799
+ fill: false,
800
+ tension: 0.4
801
+ },
802
+ {
803
+ label: "VWAP",
804
+ data: vwapData,
805
+ borderColor: "#17a2b8",
806
+ backgroundColor: "rgba(23, 162, 184, 0.1)",
807
+ fill: false,
808
+ tension: 0.4
809
+ },
810
+ {
811
+ label: "TWAP",
812
+ data: twapData,
813
+ borderColor: "#6610f2",
814
+ backgroundColor: "rgba(102, 16, 242, 0.1)",
815
+ fill: false,
816
+ tension: 0.4
817
+ },
818
+ {
819
+ label: "Volume",
820
+ data: volumeData,
821
+ borderColor: "#007bff",
822
+ backgroundColor: "rgba(0, 123, 255, 0.1)",
823
+ fill: true,
824
+ tension: 0.4
825
+ }
826
+ ]
827
+ },
828
+ options: {
829
+ responsive: true,
830
+ plugins: {
831
+ title: {
832
+ display: true,
833
+ text: `${symbol} Market Data`
834
+ }
835
+ },
836
+ scales: {
837
+ y: {
838
+ beginAtZero: false
839
+ }
840
+ }
841
+ }
842
+ };
843
+ chart.setConfig(config);
844
+ const imageBuffer = await chart.toBinary();
845
+ const base64 = imageBuffer.toString("base64");
846
+ return {
847
+ content: [
848
+ {
849
+ type: "resource",
850
+ resource: {
851
+ uri: "resource://graph",
852
+ mimeType: "image/png",
853
+ blob: base64
854
+ }
855
+ }
856
+ ]
857
+ };
858
+ } catch (error) {
859
+ return {
860
+ content: [
861
+ {
862
+ type: "text",
863
+ text: `Error: ${error instanceof Error ? error.message : "Failed to generate graph"}`,
864
+ uri: "getStockGraph"
865
+ }
866
+ ],
867
+ isError: true
868
+ };
869
+ }
870
+ };
871
+ };
872
+ var createGetStockPriceHistoryHandler = (marketDataPrices) => {
873
+ return async (args) => {
874
+ try {
875
+ const symbol = args.symbol;
876
+ const priceHistory = marketDataPrices.get(symbol) || [];
877
+ if (priceHistory.length === 0) {
878
+ return {
879
+ content: [
880
+ {
881
+ type: "text",
882
+ text: `No price data available for ${symbol}`,
883
+ uri: "getStockPriceHistory"
884
+ }
885
+ ]
886
+ };
887
+ }
888
+ return {
889
+ content: [
890
+ {
891
+ type: "text",
892
+ text: JSON.stringify(
893
+ {
894
+ symbol,
895
+ count: priceHistory.length,
896
+ data: priceHistory.map((point) => ({
897
+ timestamp: new Date(point.timestamp).toISOString(),
898
+ bid: point.bid,
899
+ offer: point.offer,
900
+ spread: point.spread,
901
+ volume: point.volume,
902
+ trade: point.trade,
903
+ indexValue: point.indexValue,
904
+ openingPrice: point.openingPrice,
905
+ closingPrice: point.closingPrice,
906
+ settlementPrice: point.settlementPrice,
907
+ tradingSessionHighPrice: point.tradingSessionHighPrice,
908
+ tradingSessionLowPrice: point.tradingSessionLowPrice,
909
+ vwap: point.vwap,
910
+ imbalance: point.imbalance,
911
+ openInterest: point.openInterest,
912
+ compositeUnderlyingPrice: point.compositeUnderlyingPrice,
913
+ simulatedSellPrice: point.simulatedSellPrice,
914
+ simulatedBuyPrice: point.simulatedBuyPrice,
915
+ marginRate: point.marginRate,
916
+ midPrice: point.midPrice,
917
+ emptyBook: point.emptyBook,
918
+ settleHighPrice: point.settleHighPrice,
919
+ settleLowPrice: point.settleLowPrice,
920
+ priorSettlePrice: point.priorSettlePrice,
921
+ sessionHighBid: point.sessionHighBid,
922
+ sessionLowOffer: point.sessionLowOffer,
923
+ earlyPrices: point.earlyPrices,
924
+ auctionClearingPrice: point.auctionClearingPrice,
925
+ swapValueFactor: point.swapValueFactor,
926
+ dailyValueAdjustmentForLongPositions: point.dailyValueAdjustmentForLongPositions,
927
+ cumulativeValueAdjustmentForLongPositions: point.cumulativeValueAdjustmentForLongPositions,
928
+ dailyValueAdjustmentForShortPositions: point.dailyValueAdjustmentForShortPositions,
929
+ cumulativeValueAdjustmentForShortPositions: point.cumulativeValueAdjustmentForShortPositions,
930
+ fixingPrice: point.fixingPrice,
931
+ cashRate: point.cashRate,
932
+ recoveryRate: point.recoveryRate,
933
+ recoveryRateForLong: point.recoveryRateForLong,
934
+ recoveryRateForShort: point.recoveryRateForShort,
935
+ marketBid: point.marketBid,
936
+ marketOffer: point.marketOffer,
937
+ shortSaleMinPrice: point.shortSaleMinPrice,
938
+ previousClosingPrice: point.previousClosingPrice,
939
+ thresholdLimitPriceBanding: point.thresholdLimitPriceBanding,
940
+ dailyFinancingValue: point.dailyFinancingValue,
941
+ accruedFinancingValue: point.accruedFinancingValue,
942
+ twap: point.twap
943
+ }))
944
+ },
945
+ null,
946
+ 2
947
+ ),
948
+ uri: "getStockPriceHistory"
949
+ }
950
+ ]
951
+ };
952
+ } catch (error) {
953
+ return {
954
+ content: [
955
+ {
956
+ type: "text",
957
+ text: `Error: ${error instanceof Error ? error.message : "Failed to get price history"}`,
958
+ uri: "getStockPriceHistory"
959
+ }
960
+ ],
961
+ isError: true
962
+ };
963
+ }
964
+ };
965
+ };
966
+
967
+ // src/tools/order.ts
968
+ import { Field as Field2, Fields as Fields2, Messages as Messages2 } from "fixparser";
969
+ var ordTypeNames = {
970
+ "1": "Market",
971
+ "2": "Limit",
972
+ "3": "Stop",
973
+ "4": "StopLimit",
974
+ "5": "MarketOnClose",
975
+ "6": "WithOrWithout",
976
+ "7": "LimitOrBetter",
977
+ "8": "LimitWithOrWithout",
978
+ "9": "OnBasis",
979
+ A: "OnClose",
980
+ B: "LimitOnClose",
981
+ C: "ForexMarket",
982
+ D: "PreviouslyQuoted",
983
+ E: "PreviouslyIndicated",
984
+ F: "ForexLimit",
985
+ G: "ForexSwap",
986
+ H: "ForexPreviouslyQuoted",
987
+ I: "Funari",
988
+ J: "MarketIfTouched",
989
+ K: "MarketWithLeftOverAsLimit",
990
+ L: "PreviousFundValuationPoint",
991
+ M: "NextFundValuationPoint",
992
+ P: "Pegged",
993
+ Q: "CounterOrderSelection",
994
+ R: "StopOnBidOrOffer",
995
+ S: "StopLimitOnBidOrOffer"
996
+ };
997
+ var sideNames = {
998
+ "1": "Buy",
999
+ "2": "Sell",
1000
+ "3": "BuyMinus",
1001
+ "4": "SellPlus",
1002
+ "5": "SellShort",
1003
+ "6": "SellShortExempt",
1004
+ "7": "Undisclosed",
1005
+ "8": "Cross",
1006
+ "9": "CrossShort",
1007
+ A: "CrossShortExempt",
1008
+ B: "AsDefined",
1009
+ C: "Opposite",
1010
+ D: "Subscribe",
1011
+ E: "Redeem",
1012
+ F: "Lend",
1013
+ G: "Borrow",
1014
+ H: "SellUndisclosed"
1015
+ };
1016
+ var timeInForceNames = {
1017
+ "0": "Day",
1018
+ "1": "GoodTillCancel",
1019
+ "2": "AtTheOpening",
1020
+ "3": "ImmediateOrCancel",
1021
+ "4": "FillOrKill",
1022
+ "5": "GoodTillCrossing",
1023
+ "6": "GoodTillDate",
1024
+ "7": "AtTheClose",
1025
+ "8": "GoodThroughCrossing",
1026
+ "9": "AtCrossing",
1027
+ A: "GoodForTime",
1028
+ B: "GoodForAuction",
1029
+ C: "GoodForMonth"
1030
+ };
1031
+ var handlInstNames = {
1032
+ "1": "AutomatedExecutionNoIntervention",
1033
+ "2": "AutomatedExecutionInterventionOK",
1034
+ "3": "ManualOrder"
1035
+ };
1036
+ var createVerifyOrderHandler = (parser, verifiedOrders) => {
1037
+ return async (args) => {
1038
+ try {
1039
+ verifiedOrders.set(args.clOrdID, {
1040
+ clOrdID: args.clOrdID,
1041
+ handlInst: args.handlInst,
1042
+ quantity: Number.parseFloat(String(args.quantity)),
1043
+ price: Number.parseFloat(String(args.price)),
1044
+ ordType: args.ordType,
1045
+ side: args.side,
1046
+ symbol: args.symbol,
1047
+ timeInForce: args.timeInForce
1048
+ });
1049
+ return {
1050
+ content: [
1051
+ {
1052
+ type: "text",
1053
+ text: `VERIFICATION: All parameters valid. Ready to proceed with order execution.
1054
+
1055
+ Parameters verified:
1056
+ - ClOrdID: ${args.clOrdID}
1057
+ - HandlInst: ${args.handlInst} (${handlInstNames[args.handlInst]})
1058
+ - Quantity: ${args.quantity}
1059
+ - Price: ${args.price}
1060
+ - OrdType: ${args.ordType} (${ordTypeNames[args.ordType]})
1061
+ - Side: ${args.side} (${sideNames[args.side]})
1062
+ - Symbol: ${args.symbol}
1063
+ - TimeInForce: ${args.timeInForce} (${timeInForceNames[args.timeInForce]})
1064
+
1065
+ To execute this order, call the executeOrder tool with these exact same parameters. Important: The user has to explicitly confirm before executeOrder is called!`,
1066
+ uri: "verifyOrder"
1067
+ }
1068
+ ]
1069
+ };
1070
+ } catch (error) {
1071
+ return {
1072
+ content: [
1073
+ {
1074
+ type: "text",
1075
+ text: `Error: ${error instanceof Error ? error.message : "Failed to verify order parameters"}`,
1076
+ uri: "verifyOrder"
1077
+ }
1078
+ ],
1079
+ isError: true
1080
+ };
1081
+ }
1082
+ };
1083
+ };
1084
+ var createExecuteOrderHandler = (parser, verifiedOrders, pendingRequests) => {
1085
+ return async (args) => {
1086
+ try {
1087
+ const verifiedOrder = verifiedOrders.get(args.clOrdID);
1088
+ if (!verifiedOrder) {
1089
+ return {
1090
+ content: [
1091
+ {
1092
+ type: "text",
1093
+ text: `Error: Order ${args.clOrdID} has not been verified. Please call verifyOrder first.`,
1094
+ uri: "executeOrder"
1095
+ }
1096
+ ],
1097
+ isError: true
1098
+ };
1099
+ }
1100
+ 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) {
1101
+ return {
1102
+ content: [
1103
+ {
1104
+ type: "text",
1105
+ text: "Error: Order parameters do not match the verified order. Please use the exact same parameters that were verified.",
1106
+ uri: "executeOrder"
1107
+ }
1108
+ ],
1109
+ isError: true
1110
+ };
1111
+ }
1112
+ const response = new Promise((resolve) => {
1113
+ pendingRequests.set(args.clOrdID, resolve);
1114
+ });
1115
+ const order = parser.createMessage(
1116
+ new Field2(Fields2.MsgType, Messages2.NewOrderSingle),
1117
+ new Field2(Fields2.MsgSeqNum, parser.getNextTargetMsgSeqNum()),
1118
+ new Field2(Fields2.SenderCompID, parser.sender),
1119
+ new Field2(Fields2.TargetCompID, parser.target),
1120
+ new Field2(Fields2.SendingTime, parser.getTimestamp()),
1121
+ new Field2(Fields2.ClOrdID, args.clOrdID),
1122
+ new Field2(Fields2.Side, args.side),
1123
+ new Field2(Fields2.Symbol, args.symbol),
1124
+ new Field2(Fields2.OrderQty, Number.parseFloat(String(args.quantity))),
1125
+ new Field2(Fields2.Price, Number.parseFloat(String(args.price))),
1126
+ new Field2(Fields2.OrdType, args.ordType),
1127
+ new Field2(Fields2.HandlInst, args.handlInst),
1128
+ new Field2(Fields2.TimeInForce, args.timeInForce),
1129
+ new Field2(Fields2.TransactTime, parser.getTimestamp())
1130
+ );
1131
+ if (!parser.connected) {
1132
+ return {
1133
+ content: [
1134
+ {
1135
+ type: "text",
1136
+ text: "Error: Not connected. Ignoring message.",
1137
+ uri: "executeOrder"
1138
+ }
1139
+ ],
1140
+ isError: true
1141
+ };
1142
+ }
1143
+ parser.send(order);
1144
+ const fixData = await response;
1145
+ verifiedOrders.delete(args.clOrdID);
1146
+ return {
1147
+ content: [
1148
+ {
1149
+ type: "text",
1150
+ text: fixData.messageType === Messages2.Reject ? `Reject message for order ${args.clOrdID}: ${JSON.stringify(fixData.toFIXJSON())}` : `Execution Report for order ${args.clOrdID}: ${JSON.stringify(fixData.toFIXJSON())}`,
1151
+ uri: "executeOrder"
1152
+ }
1153
+ ]
1154
+ };
1155
+ } catch (error) {
1156
+ return {
1157
+ content: [
1158
+ {
1159
+ type: "text",
1160
+ text: `Error: ${error instanceof Error ? error.message : "Failed to execute order"}`,
1161
+ uri: "executeOrder"
1162
+ }
1163
+ ],
1164
+ isError: true
1165
+ };
1166
+ }
1167
+ };
1168
+ };
1169
+
1170
+ // src/tools/parse.ts
1171
+ var createParseHandler = (parser) => {
1172
+ return async (args) => {
1173
+ try {
1174
+ const parsedMessage = parser.parse(args.fixString);
1175
+ if (!parsedMessage || parsedMessage.length === 0) {
1176
+ return {
1177
+ content: [
1178
+ {
1179
+ type: "text",
1180
+ text: "Error: Failed to parse FIX string",
1181
+ uri: "parse"
1182
+ }
1183
+ ],
1184
+ isError: true
1185
+ };
1186
+ }
1187
+ return {
1188
+ content: [
1189
+ {
1190
+ type: "text",
1191
+ text: `${parsedMessage[0].description}
1192
+ ${parsedMessage[0].messageTypeDescription}`,
1193
+ uri: "parse"
1194
+ }
1195
+ ]
1196
+ };
1197
+ } catch (error) {
1198
+ return {
1199
+ content: [
1200
+ {
1201
+ type: "text",
1202
+ text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`,
1203
+ uri: "parse"
1204
+ }
1205
+ ],
1206
+ isError: true
1207
+ };
1208
+ }
1209
+ };
1210
+ };
1211
+
1212
+ // src/tools/parseToJSON.ts
1213
+ var createParseToJSONHandler = (parser) => {
1214
+ return async (args) => {
1215
+ try {
1216
+ const parsedMessage = parser.parse(args.fixString);
1217
+ if (!parsedMessage || parsedMessage.length === 0) {
1218
+ return {
1219
+ content: [
1220
+ {
1221
+ type: "text",
1222
+ text: "Error: Failed to parse FIX string",
1223
+ uri: "parseToJSON"
1224
+ }
1225
+ ],
1226
+ isError: true
1227
+ };
1228
+ }
1229
+ return {
1230
+ content: [
1231
+ {
1232
+ type: "text",
1233
+ text: `${parsedMessage[0].toFIXJSON()}`,
1234
+ uri: "parseToJSON"
1235
+ }
1236
+ ]
1237
+ };
1238
+ } catch (error) {
1239
+ return {
1240
+ content: [
1241
+ {
1242
+ type: "text",
1243
+ text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`,
1244
+ uri: "parseToJSON"
1245
+ }
1246
+ ],
1247
+ isError: true
1248
+ };
1249
+ }
1250
+ };
1251
+ };
1252
+
1253
+ // src/tools/index.ts
1254
+ var createToolHandlers = (parser, verifiedOrders, pendingRequests, marketDataPrices) => ({
1255
+ parse: createParseHandler(parser),
1256
+ parseToJSON: createParseToJSONHandler(parser),
1257
+ verifyOrder: createVerifyOrderHandler(parser, verifiedOrders),
1258
+ executeOrder: createExecuteOrderHandler(parser, verifiedOrders, pendingRequests),
1259
+ marketDataRequest: createMarketDataRequestHandler(parser, pendingRequests),
1260
+ getStockGraph: createGetStockGraphHandler(marketDataPrices),
1261
+ getStockPriceHistory: createGetStockPriceHistoryHandler(marketDataPrices),
1262
+ technicalAnalysis: createTechnicalAnalysisHandler(marketDataPrices)
1263
+ });
1264
+
1265
+ // src/utils/messageHandler.ts
1266
+ import { Fields as Fields3, MDEntryType as MDEntryType2, Messages as Messages3 } from "fixparser";
1267
+ function getEnumValue(enumObj, name) {
1268
+ return enumObj[name] || name;
1269
+ }
1270
+ function handleMessage(message, parser, pendingRequests, marketDataPrices, maxPriceHistory, onPriceUpdate) {
1271
+ const msgType = message.messageType;
1272
+ if (msgType === Messages3.MarketDataSnapshotFullRefresh || msgType === Messages3.MarketDataIncrementalRefresh) {
1273
+ const symbol = message.getField(Fields3.Symbol)?.value;
1274
+ const fixJson = message.toFIXJSON();
1275
+ const entries = fixJson.Body?.NoMDEntries || [];
1276
+ const data = {
1277
+ timestamp: Date.now(),
1278
+ bid: 0,
1279
+ offer: 0,
1280
+ spread: 0,
1281
+ volume: 0,
1282
+ trade: 0,
1283
+ indexValue: 0,
1284
+ openingPrice: 0,
1285
+ closingPrice: 0,
1286
+ settlementPrice: 0,
1287
+ tradingSessionHighPrice: 0,
1288
+ tradingSessionLowPrice: 0,
1289
+ vwap: 0,
1290
+ imbalance: 0,
1291
+ openInterest: 0,
1292
+ compositeUnderlyingPrice: 0,
1293
+ simulatedSellPrice: 0,
1294
+ simulatedBuyPrice: 0,
1295
+ marginRate: 0,
1296
+ midPrice: 0,
1297
+ emptyBook: 0,
1298
+ settleHighPrice: 0,
1299
+ settleLowPrice: 0,
1300
+ priorSettlePrice: 0,
1301
+ sessionHighBid: 0,
1302
+ sessionLowOffer: 0,
1303
+ earlyPrices: 0,
1304
+ auctionClearingPrice: 0,
1305
+ swapValueFactor: 0,
1306
+ dailyValueAdjustmentForLongPositions: 0,
1307
+ cumulativeValueAdjustmentForLongPositions: 0,
1308
+ dailyValueAdjustmentForShortPositions: 0,
1309
+ cumulativeValueAdjustmentForShortPositions: 0,
1310
+ fixingPrice: 0,
1311
+ cashRate: 0,
1312
+ recoveryRate: 0,
1313
+ recoveryRateForLong: 0,
1314
+ recoveryRateForShort: 0,
1315
+ marketBid: 0,
1316
+ marketOffer: 0,
1317
+ shortSaleMinPrice: 0,
1318
+ previousClosingPrice: 0,
1319
+ thresholdLimitPriceBanding: 0,
1320
+ dailyFinancingValue: 0,
1321
+ accruedFinancingValue: 0,
1322
+ twap: 0
1323
+ };
1324
+ for (const entry of entries) {
1325
+ const entryType = entry.MDEntryType;
1326
+ const price = entry.MDEntryPx ? Number.parseFloat(entry.MDEntryPx) : 0;
1327
+ const size = entry.MDEntrySize ? Number.parseFloat(entry.MDEntrySize) : 0;
1328
+ const enumValue = getEnumValue(MDEntryType2, entryType);
1329
+ switch (enumValue) {
1330
+ case MDEntryType2.Bid:
1331
+ data.bid = price;
1332
+ break;
1333
+ case MDEntryType2.Offer:
1334
+ data.offer = price;
1335
+ break;
1336
+ case MDEntryType2.Trade:
1337
+ data.trade = price;
1338
+ break;
1339
+ case MDEntryType2.IndexValue:
1340
+ data.indexValue = price;
1341
+ break;
1342
+ case MDEntryType2.OpeningPrice:
1343
+ data.openingPrice = price;
1344
+ break;
1345
+ case MDEntryType2.ClosingPrice:
1346
+ data.closingPrice = price;
1347
+ break;
1348
+ case MDEntryType2.SettlementPrice:
1349
+ data.settlementPrice = price;
1350
+ break;
1351
+ case MDEntryType2.TradingSessionHighPrice:
1352
+ data.tradingSessionHighPrice = price;
1353
+ break;
1354
+ case MDEntryType2.TradingSessionLowPrice:
1355
+ data.tradingSessionLowPrice = price;
1356
+ break;
1357
+ case MDEntryType2.VWAP:
1358
+ data.vwap = price;
1359
+ break;
1360
+ case MDEntryType2.Imbalance:
1361
+ data.imbalance = size;
1362
+ break;
1363
+ case MDEntryType2.TradeVolume:
1364
+ data.volume = size;
1365
+ break;
1366
+ case MDEntryType2.OpenInterest:
1367
+ data.openInterest = size;
1368
+ break;
1369
+ case MDEntryType2.CompositeUnderlyingPrice:
1370
+ data.compositeUnderlyingPrice = price;
1371
+ break;
1372
+ case MDEntryType2.SimulatedSellPrice:
1373
+ data.simulatedSellPrice = price;
1374
+ break;
1375
+ case MDEntryType2.SimulatedBuyPrice:
1376
+ data.simulatedBuyPrice = price;
1377
+ break;
1378
+ case MDEntryType2.MarginRate:
1379
+ data.marginRate = price;
1380
+ break;
1381
+ case MDEntryType2.MidPrice:
1382
+ data.midPrice = price;
1383
+ break;
1384
+ case MDEntryType2.EmptyBook:
1385
+ data.emptyBook = 1;
1386
+ break;
1387
+ case MDEntryType2.SettleHighPrice:
1388
+ data.settleHighPrice = price;
1389
+ break;
1390
+ case MDEntryType2.SettleLowPrice:
1391
+ data.settleLowPrice = price;
1392
+ break;
1393
+ case MDEntryType2.PriorSettlePrice:
1394
+ data.priorSettlePrice = price;
1395
+ break;
1396
+ case MDEntryType2.SessionHighBid:
1397
+ data.sessionHighBid = price;
1398
+ break;
1399
+ case MDEntryType2.SessionLowOffer:
1400
+ data.sessionLowOffer = price;
1401
+ break;
1402
+ case MDEntryType2.EarlyPrices:
1403
+ data.earlyPrices = price;
1404
+ break;
1405
+ case MDEntryType2.AuctionClearingPrice:
1406
+ data.auctionClearingPrice = price;
1407
+ break;
1408
+ case MDEntryType2.SwapValueFactor:
1409
+ data.swapValueFactor = price;
1410
+ break;
1411
+ case MDEntryType2.DailyValueAdjustmentForLongPositions:
1412
+ data.dailyValueAdjustmentForLongPositions = price;
1413
+ break;
1414
+ case MDEntryType2.CumulativeValueAdjustmentForLongPositions:
1415
+ data.cumulativeValueAdjustmentForLongPositions = price;
1416
+ break;
1417
+ case MDEntryType2.DailyValueAdjustmentForShortPositions:
1418
+ data.dailyValueAdjustmentForShortPositions = price;
1419
+ break;
1420
+ case MDEntryType2.CumulativeValueAdjustmentForShortPositions:
1421
+ data.cumulativeValueAdjustmentForShortPositions = price;
1422
+ break;
1423
+ case MDEntryType2.FixingPrice:
1424
+ data.fixingPrice = price;
1425
+ break;
1426
+ case MDEntryType2.CashRate:
1427
+ data.cashRate = price;
1428
+ break;
1429
+ case MDEntryType2.RecoveryRate:
1430
+ data.recoveryRate = price;
1431
+ break;
1432
+ case MDEntryType2.RecoveryRateForLong:
1433
+ data.recoveryRateForLong = price;
1434
+ break;
1435
+ case MDEntryType2.RecoveryRateForShort:
1436
+ data.recoveryRateForShort = price;
1437
+ break;
1438
+ case MDEntryType2.MarketBid:
1439
+ data.marketBid = price;
1440
+ break;
1441
+ case MDEntryType2.MarketOffer:
1442
+ data.marketOffer = price;
1443
+ break;
1444
+ case MDEntryType2.ShortSaleMinPrice:
1445
+ data.shortSaleMinPrice = price;
1446
+ break;
1447
+ case MDEntryType2.PreviousClosingPrice:
1448
+ data.previousClosingPrice = price;
1449
+ break;
1450
+ case MDEntryType2.ThresholdLimitPriceBanding:
1451
+ data.thresholdLimitPriceBanding = price;
1452
+ break;
1453
+ case MDEntryType2.DailyFinancingValue:
1454
+ data.dailyFinancingValue = price;
1455
+ break;
1456
+ case MDEntryType2.AccruedFinancingValue:
1457
+ data.accruedFinancingValue = price;
1458
+ break;
1459
+ case MDEntryType2.TWAP:
1460
+ data.twap = price;
1461
+ break;
1462
+ }
1463
+ }
1464
+ data.spread = data.offer - data.bid;
1465
+ if (!marketDataPrices.has(symbol)) {
1466
+ marketDataPrices.set(symbol, []);
1467
+ }
1468
+ const prices = marketDataPrices.get(symbol);
1469
+ prices.push(data);
1470
+ if (prices.length > maxPriceHistory) {
1471
+ prices.splice(0, prices.length - maxPriceHistory);
1472
+ }
1473
+ onPriceUpdate?.(symbol, data);
1474
+ const mdReqID = message.getField(Fields3.MDReqID)?.value;
1475
+ if (mdReqID) {
1476
+ const callback = pendingRequests.get(mdReqID);
1477
+ if (callback) {
1478
+ callback(message);
1479
+ pendingRequests.delete(mdReqID);
1480
+ }
1481
+ }
1482
+ } else if (msgType === Messages3.ExecutionReport) {
1483
+ const reqId = message.getField(Fields3.ClOrdID)?.value;
1484
+ const callback = pendingRequests.get(reqId);
1485
+ if (callback) {
1486
+ callback(message);
1487
+ pendingRequests.delete(reqId);
1488
+ }
1489
+ }
1490
+ }
1491
+
1492
+ // src/MCPRemote.ts
1493
+ var transports = {};
1494
+ function jsonSchemaToZod(schema) {
1495
+ if (schema.type === "object") {
1496
+ const shape = {};
1497
+ for (const [key, prop] of Object.entries(schema.properties || {})) {
1498
+ const propSchema = prop;
1499
+ if (propSchema.type === "string") {
1500
+ if (propSchema.enum) {
1501
+ shape[key] = z.enum(propSchema.enum);
1502
+ } else {
1503
+ shape[key] = z.string();
1504
+ }
1505
+ } else if (propSchema.type === "number") {
1506
+ shape[key] = z.number();
1507
+ } else if (propSchema.type === "boolean") {
1508
+ shape[key] = z.boolean();
1509
+ } else if (propSchema.type === "array") {
1510
+ if (propSchema.items.type === "string") {
1511
+ shape[key] = z.array(z.string());
1512
+ } else if (propSchema.items.type === "number") {
1513
+ shape[key] = z.array(z.number());
1514
+ } else if (propSchema.items.type === "boolean") {
1515
+ shape[key] = z.array(z.boolean());
1516
+ } else {
1517
+ shape[key] = z.array(z.any());
1518
+ }
1519
+ } else {
1520
+ shape[key] = z.any();
1521
+ }
1522
+ }
1523
+ return shape;
1524
+ }
1525
+ return {};
1526
+ }
1527
+ var MCPRemote = class extends MCPBase {
1528
+ /**
1529
+ * Port number the server will listen on.
1530
+ * @private
1531
+ */
1532
+ port;
35
1533
  /**
36
1534
  * Node.js HTTP server instance created internally.
37
1535
  * @private
38
1536
  */
39
- server;
1537
+ httpServer;
40
1538
  /**
41
1539
  * MCP server instance handling MCP protocol logic.
42
1540
  * @private
@@ -46,89 +1544,61 @@ var MCPRemote = class {
46
1544
  * Optional name of the plugin/server instance.
47
1545
  * @private
48
1546
  */
49
- name;
1547
+ serverName;
50
1548
  /**
51
1549
  * Optional version string of the plugin/server.
52
1550
  * @private
53
1551
  */
54
- version;
1552
+ serverVersion;
55
1553
  /**
56
- * Called when server is setup and listening.
1554
+ * Map to store verified orders before execution
57
1555
  * @private
58
1556
  */
59
- onReady = void 0;
1557
+ verifiedOrders = /* @__PURE__ */ new Map();
60
1558
  /**
61
- * A map of pending market data requests, keyed by MDReqID.
62
- * Each entry contains a resolver function that is called when the corresponding
63
- * FIX Message is received.
1559
+ * Map to store pending requests and their callbacks
64
1560
  * @private
65
- * @type {Map<string, (data: Message) => void>}
66
1561
  */
67
1562
  pendingRequests = /* @__PURE__ */ new Map();
1563
+ /**
1564
+ * Map to store market data prices for each symbol
1565
+ * @private
1566
+ */
1567
+ marketDataPrices = /* @__PURE__ */ new Map();
1568
+ /**
1569
+ * Maximum number of price history entries to keep per symbol
1570
+ * @private
1571
+ */
1572
+ MAX_PRICE_HISTORY = 1e5;
68
1573
  constructor({ port, logger, onReady }) {
1574
+ super({ logger, onReady });
69
1575
  this.port = port;
70
- if (logger) this.logger = logger;
71
- if (onReady) this.onReady = onReady;
72
1576
  }
73
1577
  async register(parser) {
74
1578
  this.parser = parser;
75
- this.parser.addOnMessageCallback((message) => {
76
- this.logger?.log({
77
- level: "info",
78
- message: `FIXParser (MCP): (${parser.protocol?.toUpperCase()}): << received ${message.description}`
79
- });
80
- const msgType = message.messageType;
81
- if (msgType === Messages.MarketDataSnapshotFullRefresh || msgType === Messages.ExecutionReport) {
82
- const idField = msgType === Messages.MarketDataSnapshotFullRefresh ? message.getField(Fields.MDReqID) : message.getField(Fields.ClOrdID);
83
- if (idField) {
84
- const id = idField.value;
85
- if (typeof id === "string" || typeof id === "number") {
86
- const callback = this.pendingRequests.get(String(id));
87
- if (callback) {
88
- callback(message);
89
- this.pendingRequests.delete(String(id));
90
- }
91
- }
92
- }
93
- }
94
- });
95
1579
  this.logger = parser.logger;
96
1580
  this.logger?.log({
97
1581
  level: "info",
98
1582
  message: `FIXParser (MCP): -- Plugin registered. Creating MCP server on port ${this.port}...`
99
1583
  });
100
- this.server = createServer(async (req, res) => {
1584
+ this.parser.addOnMessageCallback((message) => {
1585
+ if (this.parser) {
1586
+ handleMessage(
1587
+ message,
1588
+ this.parser,
1589
+ this.pendingRequests,
1590
+ this.marketDataPrices,
1591
+ this.MAX_PRICE_HISTORY
1592
+ );
1593
+ }
1594
+ });
1595
+ this.httpServer = createServer(async (req, res) => {
101
1596
  if (!req.url || !req.method) {
102
1597
  res.writeHead(400);
103
1598
  res.end("Bad Request");
104
1599
  return;
105
1600
  }
106
- const url = new URL(req.url, `http://${req.headers.host}`);
107
- if (url.pathname === "/.well-known/oauth-authorization-server") {
108
- const config = {
109
- issuer: "https://accounts.google.com",
110
- authorization_endpoint: "https://accounts.google.com/o/oauth2/v2/auth",
111
- token_endpoint: "https://oauth2.googleapis.com/token",
112
- jwks_uri: "https://www.googleapis.com/oauth2/v3/certs",
113
- response_types_supported: [
114
- "code",
115
- "token",
116
- "id_token",
117
- "code token",
118
- "code id_token",
119
- "token id_token",
120
- "code token id_token"
121
- ],
122
- subject_types_supported: ["public"],
123
- id_token_signing_alg_values_supported: ["RS256"],
124
- scopes_supported: ["openid", "email", "profile"],
125
- token_endpoint_auth_methods_supported: ["client_secret_basic", "client_secret_post"]
126
- };
127
- res.writeHead(200, { "Content-Type": "application/json" });
128
- res.end(JSON.stringify(config));
129
- return;
130
- }
131
- if (url.pathname === "/") {
1601
+ if (req.url === "/mcp") {
132
1602
  const sessionId = req.headers["mcp-session-id"];
133
1603
  if (req.method === "POST") {
134
1604
  const bodyChunks = [];
@@ -161,10 +1631,10 @@ var MCPRemote = class {
161
1631
  }
162
1632
  };
163
1633
  this.mcpServer = new McpServer({
164
- name: this.name || "FIXParser",
165
- version: this.version || "1.0.0"
1634
+ name: this.serverName || "FIXParser",
1635
+ version: this.serverVersion || "1.0.0"
166
1636
  });
167
- this.addWorkflows();
1637
+ this.setupTools();
168
1638
  await this.mcpServer.connect(transport);
169
1639
  } else {
170
1640
  res.writeHead(400, { "Content-Type": "application/json" });
@@ -180,7 +1650,15 @@ var MCPRemote = class {
180
1650
  );
181
1651
  return;
182
1652
  }
183
- await transport.handleRequest(req, res, parsed);
1653
+ try {
1654
+ await transport.handleRequest(req, res, parsed);
1655
+ } catch (error) {
1656
+ this.logger?.log({
1657
+ level: "error",
1658
+ message: `Error handling request: ${error}`
1659
+ });
1660
+ throw error;
1661
+ }
184
1662
  });
185
1663
  } else if (req.method === "GET" || req.method === "DELETE") {
186
1664
  if (!sessionId || !transports[sessionId]) {
@@ -189,17 +1667,29 @@ var MCPRemote = class {
189
1667
  return;
190
1668
  }
191
1669
  const transport = transports[sessionId];
192
- await transport.handleRequest(req, res);
1670
+ try {
1671
+ await transport.handleRequest(req, res);
1672
+ } catch (error) {
1673
+ this.logger?.log({
1674
+ level: "error",
1675
+ message: `Error handling ${req.method} request: ${error}`
1676
+ });
1677
+ throw error;
1678
+ }
193
1679
  } else {
1680
+ this.logger?.log({
1681
+ level: "error",
1682
+ message: `Method not allowed: ${req.method}`
1683
+ });
194
1684
  res.writeHead(405);
195
1685
  res.end("Method Not Allowed");
196
1686
  }
197
- return;
1687
+ } else {
1688
+ res.writeHead(404);
1689
+ res.end("Not Found");
198
1690
  }
199
- res.writeHead(404);
200
- res.end("Not Found");
201
1691
  });
202
- this.server.listen(this.port, () => {
1692
+ this.httpServer.listen(this.port, () => {
203
1693
  this.logger?.log({
204
1694
  level: "info",
205
1695
  message: `FIXParser (MCP): -- Server listening on http://localhost:${this.port}...`
@@ -209,381 +1699,55 @@ var MCPRemote = class {
209
1699
  this.onReady();
210
1700
  }
211
1701
  }
212
- addWorkflows() {
1702
+ setupTools() {
213
1703
  if (!this.parser) {
214
1704
  this.logger?.log({
215
1705
  level: "error",
216
- message: "FIXParser (MCP): -- FIXParser instance not initialized. Ignoring setup of workflows..."
1706
+ message: "FIXParser (MCP): -- FIXParser instance not initialized. Ignoring setup of tools..."
217
1707
  });
218
1708
  return;
219
1709
  }
220
1710
  if (!this.mcpServer) {
221
1711
  this.logger?.log({
222
1712
  level: "error",
223
- message: "FIXParser (MCP): -- MCP Server not initialized. Ignoring setup of workflows..."
1713
+ message: "FIXParser (MCP): -- MCP Server not initialized. Ignoring setup of tools..."
224
1714
  });
225
1715
  return;
226
1716
  }
227
- this.mcpServer.tool(
228
- "parse",
229
- "Parses a FIX message and describes it in plain language",
230
- { fixString: z.string() },
231
- async ({ fixString }) => {
232
- const parsedMessage = this.parser?.parse(fixString);
233
- if (!parsedMessage || parsedMessage.length === 0) {
234
- this.logger?.log({
235
- level: "error",
236
- message: "FIXParser (MCP): -- Failed to parse FIX string"
237
- });
238
- return {
239
- isError: true,
240
- content: [
241
- {
242
- type: "text",
243
- text: "Error: Failed to parse FIX string"
244
- }
245
- ]
246
- };
247
- }
248
- return {
249
- content: [
250
- {
251
- type: "text",
252
- text: parsedMessage ? `${parsedMessage[0].description} - ${parsedMessage[0].messageTypeDescription}` : ""
253
- }
254
- ]
255
- };
256
- }
257
- );
258
- this.mcpServer.prompt(
259
- "parse",
260
- "Parses a FIX message and describes it in plain language",
261
- { fixString: z.string() },
262
- ({ fixString }) => ({
263
- messages: [
264
- {
265
- role: "user",
266
- content: {
267
- type: "text",
268
- text: `Please parse and explain this FIX message: ${fixString}`
269
- }
270
- }
271
- ]
272
- })
273
- );
274
- this.mcpServer.tool(
275
- "parseToJSON",
276
- "Parses a FIX message into JSON",
277
- { fixString: z.string() },
278
- async ({ fixString }) => {
279
- const parsedMessage = this.parser?.parse(fixString);
280
- if (!parsedMessage || parsedMessage.length === 0) {
281
- this.logger?.log({
282
- level: "error",
283
- message: "FIXParser (MCP): -- Failed to parse FIX string"
284
- });
285
- return {
286
- isError: true,
287
- content: [
288
- {
289
- type: "text",
290
- text: "Error: Failed to parse FIX string"
291
- }
292
- ]
293
- };
294
- }
295
- return {
296
- content: [
297
- {
298
- type: "text",
299
- text: parsedMessage ? JSON.stringify(parsedMessage[0].toFIXJSON()) : ""
300
- }
301
- ]
302
- };
303
- }
1717
+ const toolHandlers = createToolHandlers(
1718
+ this.parser,
1719
+ this.verifiedOrders,
1720
+ this.pendingRequests,
1721
+ this.marketDataPrices
304
1722
  );
305
- this.mcpServer.prompt(
306
- "parseToJSON",
307
- "Parses a FIX message into JSON",
308
- { fixString: z.string() },
309
- ({ fixString }) => ({
310
- messages: [
311
- {
312
- role: "user",
313
- content: {
314
- type: "text",
315
- text: `Please parse the FIX message to JSON: ${fixString}`
316
- }
317
- }
318
- ]
319
- })
320
- );
321
- this.mcpServer.tool(
322
- "newOrderSingle",
323
- "Creates and sends a New Order Single",
324
- {
325
- clOrdID: z.string(),
326
- handlInst: z.enum(["1", "2", "3"]).default(HandlInst.AutomatedExecutionNoIntervention).optional(),
327
- quantity: z.number(),
328
- price: z.number(),
329
- ordType: z.enum([
330
- "1",
331
- "2",
332
- "3",
333
- "4",
334
- "5",
335
- "6",
336
- "7",
337
- "8",
338
- "9",
339
- "A",
340
- "B",
341
- "C",
342
- "D",
343
- "E",
344
- "F",
345
- "G",
346
- "H",
347
- "I",
348
- "J",
349
- "K",
350
- "L",
351
- "M",
352
- "P",
353
- "Q",
354
- "R",
355
- "S"
356
- ]).default(OrdType.Market).optional(),
357
- side: z.enum(["1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H"]),
358
- // 1 = Buy, 2 = Sell...
359
- symbol: z.string(),
360
- timeInForce: z.enum(["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C"]).default(TimeInForce.Day).optional()
361
- },
362
- async ({ clOrdID, handlInst, quantity, price, ordType, side, symbol, timeInForce }) => {
363
- const response = new Promise((resolve) => {
364
- this.pendingRequests.set(clOrdID, resolve);
365
- });
366
- const order = this.parser?.createMessage(
367
- new Field(Fields.MsgType, Messages.NewOrderSingle),
368
- new Field(Fields.MsgSeqNum, this.parser?.getNextTargetMsgSeqNum()),
369
- new Field(Fields.SenderCompID, this.parser?.sender),
370
- new Field(Fields.TargetCompID, this.parser?.target),
371
- new Field(Fields.SendingTime, this.parser?.getTimestamp()),
372
- new Field(Fields.ClOrdID, clOrdID),
373
- new Field(Fields.Side, side),
374
- new Field(Fields.Symbol, symbol),
375
- new Field(Fields.OrderQty, quantity),
376
- new Field(Fields.Price, price),
377
- new Field(Fields.OrdType, ordType),
378
- new Field(Fields.HandlInst, handlInst),
379
- new Field(Fields.TimeInForce, timeInForce),
380
- new Field(Fields.TransactTime, this.parser?.getTimestamp())
381
- );
382
- if (!this.parser?.connected) {
383
- this.logger?.log({
384
- level: "error",
385
- message: "FIXParser (MCP): -- Not connected. Ignoring message."
386
- });
387
- return {
388
- isError: true,
389
- content: [
390
- {
391
- type: "text",
392
- text: "Error: Not connected. Ignoring message."
393
- }
394
- ]
395
- };
396
- }
397
- this.parser?.send(order);
398
- this.logger?.log({
399
- level: "info",
400
- message: `FIXParser (MCP): (${this.parser?.protocol?.toUpperCase()}): >> sent ${order?.description}`
401
- });
402
- const fixData = await response;
403
- return {
404
- content: [
405
- {
406
- type: "text",
407
- text: `Execution Report for order ${clOrdID}: ${JSON.stringify(fixData.toFIXJSON())}`
408
- }
409
- ]
410
- };
411
- }
412
- );
413
- this.mcpServer.prompt(
414
- "newOrderSingle",
415
- "Creates and sends a New Order Single",
416
- {
417
- clOrdID: z.string(),
418
- handlInst: z.string(),
419
- quantity: z.string(),
420
- price: z.string(),
421
- ordType: z.string(),
422
- side: z.string(),
423
- symbol: z.string(),
424
- timeInForce: z.string()
425
- },
426
- ({ clOrdID, handlInst, quantity, price, ordType, side, symbol, timeInForce }) => ({
427
- messages: [
428
- {
429
- role: "user",
430
- content: {
431
- type: "text",
432
- text: [
433
- "Create a New Order Single FIX message with the following parameters:",
434
- `- ClOrdID: ${clOrdID}`,
435
- `- HandlInst: ${handlInst ?? "default"}`,
436
- `- Quantity: ${quantity}`,
437
- `- Price: ${price}`,
438
- `- OrdType: ${ordType ?? "default (Market)"}`,
439
- `- Side: ${side}`,
440
- `- Symbol: ${symbol}`,
441
- `- TimeInForce: ${timeInForce ?? "default (Day)"}`,
442
- "",
443
- "Format the response as a JSON object with FIX tag numbers as keys and their corresponding values."
444
- ].join("\n")
445
- }
1723
+ Object.entries(toolSchemas).forEach(([name, { description, schema }]) => {
1724
+ this.mcpServer?.registerTool(
1725
+ name,
1726
+ {
1727
+ description,
1728
+ inputSchema: jsonSchemaToZod(schema)
1729
+ },
1730
+ async (args) => {
1731
+ const handler = toolHandlers[name];
1732
+ if (!handler) {
1733
+ return {
1734
+ content: [
1735
+ {
1736
+ type: "text",
1737
+ text: `Tool not found: ${name}`
1738
+ }
1739
+ ],
1740
+ isError: true
1741
+ };
446
1742
  }
447
- ]
448
- })
449
- );
450
- this.mcpServer.tool(
451
- "marketDataRequest",
452
- "Sends a request for Market Data with the given symbol",
453
- {
454
- mdUpdateType: z.enum(["0", "1"]).default("0").optional(),
455
- // MDUpdateType.FullRefresh
456
- symbol: z.string(),
457
- mdReqID: z.string(),
458
- subscriptionRequestType: z.enum(["0", "1", "2"]).default(SubscriptionRequestType.SnapshotAndUpdates).optional(),
459
- mdEntryType: z.enum([
460
- "0",
461
- "1",
462
- "2",
463
- "3",
464
- "4",
465
- "5",
466
- "6",
467
- "7",
468
- "8",
469
- "9",
470
- "A",
471
- "B",
472
- "C",
473
- "D",
474
- "E",
475
- "F",
476
- "G",
477
- "H",
478
- "J",
479
- "K",
480
- "L",
481
- "M",
482
- "N",
483
- "O",
484
- "P",
485
- "Q",
486
- "S",
487
- "R",
488
- "T",
489
- "U",
490
- "V",
491
- "W",
492
- "X",
493
- "Y",
494
- "Z",
495
- "a",
496
- "b",
497
- "c",
498
- "d",
499
- "e",
500
- "g",
501
- "h",
502
- "i",
503
- "t"
504
- ]).default(MDEntryType.Bid).optional()
505
- },
506
- async ({ mdUpdateType, symbol, mdReqID, subscriptionRequestType, mdEntryType }) => {
507
- const response = new Promise((resolve) => {
508
- this.pendingRequests.set(mdReqID, resolve);
509
- });
510
- const marketDataRequest = this.parser?.createMessage(
511
- new Field(Fields.MsgType, Messages.MarketDataRequest),
512
- new Field(Fields.SenderCompID, this.parser?.sender),
513
- new Field(Fields.MsgSeqNum, this.parser?.getNextTargetMsgSeqNum()),
514
- new Field(Fields.TargetCompID, this.parser?.target),
515
- new Field(Fields.SendingTime, this.parser?.getTimestamp()),
516
- new Field(Fields.MarketDepth, 0),
517
- new Field(Fields.MDUpdateType, mdUpdateType),
518
- new Field(Fields.NoRelatedSym, 1),
519
- new Field(Fields.Symbol, symbol),
520
- new Field(Fields.MDReqID, mdReqID),
521
- new Field(Fields.SubscriptionRequestType, subscriptionRequestType),
522
- new Field(Fields.NoMDEntryTypes, 1),
523
- new Field(Fields.MDEntryType, mdEntryType)
524
- );
525
- if (!this.parser?.connected) {
526
- this.logger?.log({
527
- level: "error",
528
- message: "FIXParser (MCP): -- Not connected. Ignoring message."
529
- });
1743
+ const result = await handler(args);
530
1744
  return {
531
- isError: true,
532
- content: [
533
- {
534
- type: "text",
535
- text: "Error: Not connected. Ignoring message."
536
- }
537
- ]
1745
+ content: result.content,
1746
+ isError: result.isError
538
1747
  };
539
1748
  }
540
- this.parser?.send(marketDataRequest);
541
- this.logger?.log({
542
- level: "info",
543
- message: `FIXParser (MCP): (${this.parser?.protocol?.toUpperCase()}): >> sent ${marketDataRequest?.description}`
544
- });
545
- const fixData = await response;
546
- return {
547
- content: [
548
- {
549
- type: "text",
550
- text: `Market data for ${symbol}: ${JSON.stringify(fixData.toFIXJSON())}`
551
- }
552
- ]
553
- };
554
- }
555
- );
556
- this.mcpServer.prompt(
557
- "marketDataRequest",
558
- "Sends a request for Market Data with the given symbol",
559
- {
560
- mdUpdateType: z.string(),
561
- symbol: z.string(),
562
- mdReqID: z.string(),
563
- subscriptionRequestType: z.string(),
564
- mdEntryType: z.string()
565
- },
566
- ({ mdUpdateType, symbol, mdReqID, subscriptionRequestType, mdEntryType }) => ({
567
- messages: [
568
- {
569
- role: "user",
570
- content: {
571
- type: "text",
572
- text: [
573
- "Create a Market Data Request FIX message with the following parameters:",
574
- `- MDUpdateType: ${mdUpdateType ?? "default (0 = FullRefresh)"}`,
575
- `- Symbol: ${symbol}`,
576
- `- MDReqID: ${mdReqID}`,
577
- `- SubscriptionRequestType: ${subscriptionRequestType ?? "default (0 = Snapshot + Updates)"}`,
578
- `- MDEntryType: ${mdEntryType ?? "default (0 = Bid)"}`,
579
- "",
580
- "Format the response as a JSON object with FIX tag numbers as keys and their corresponding values."
581
- ].join("\n")
582
- }
583
- }
584
- ]
585
- })
586
- );
1749
+ );
1750
+ });
587
1751
  }
588
1752
  };
589
1753
  export {