fixparser-plugin-mcp 9.1.7-52ccb1d5 → 9.1.7-537ecaee

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,9 +1,7 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
2
  var __defProp = Object.defineProperty;
4
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
6
  var __export = (target, all) => {
9
7
  for (var name in all)
@@ -17,14 +15,6 @@ var __copyProps = (to, from, except, desc) => {
17
15
  }
18
16
  return to;
19
17
  };
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
- ));
28
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
19
 
30
20
  // src/MCPLocal.ts
@@ -35,52 +25,8 @@ __export(MCPLocal_exports, {
35
25
  module.exports = __toCommonJS(MCPLocal_exports);
36
26
  var import_server = require("@modelcontextprotocol/sdk/server/index.js");
37
27
  var import_stdio = require("@modelcontextprotocol/sdk/server/stdio.js");
28
+ var import_fixparser = require("fixparser");
38
29
  var import_zod = require("zod");
39
-
40
- // src/MCPBase.ts
41
- var MCPBase = class {
42
- /**
43
- * Optional logger instance for diagnostics and output.
44
- * @protected
45
- */
46
- logger;
47
- /**
48
- * FIXParser instance, set during plugin register().
49
- * @protected
50
- */
51
- parser;
52
- /**
53
- * Called when server is setup and listening.
54
- * @protected
55
- */
56
- onReady = void 0;
57
- /**
58
- * Map to store verified orders before execution
59
- * @protected
60
- */
61
- verifiedOrders = /* @__PURE__ */ new Map();
62
- /**
63
- * Map to store pending market data requests
64
- * @protected
65
- */
66
- pendingRequests = /* @__PURE__ */ new Map();
67
- /**
68
- * Map to store market data prices
69
- * @protected
70
- */
71
- marketDataPrices = /* @__PURE__ */ new Map();
72
- /**
73
- * Maximum number of price history entries to keep per symbol
74
- * @protected
75
- */
76
- MAX_PRICE_HISTORY = 1e5;
77
- constructor({ logger, onReady }) {
78
- this.logger = logger;
79
- this.onReady = onReady;
80
- }
81
- };
82
-
83
- // src/schemas/schemas.ts
84
30
  var toolSchemas = {
85
31
  parse: {
86
32
  description: "Parses a FIX message and describes it in plain language",
@@ -163,7 +109,7 @@ var toolSchemas = {
163
109
  }
164
110
  },
165
111
  executeOrder: {
166
- description: "Executes a verified order. verifyOrder must be called before executeOrder.",
112
+ description: "Executes a verified order. verifyOrder must be called before executeOrder. user has to explicitly allow executeOrder.",
167
113
  schema: {
168
114
  type: "object",
169
115
  properties: {
@@ -280,12 +226,12 @@ var toolSchemas = {
280
226
  "X",
281
227
  "Y",
282
228
  "Z"
283
- ]
284
- },
285
- 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"
229
+ ],
230
+ 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"
231
+ }
286
232
  }
287
233
  },
288
- required: ["mdUpdateType", "symbols", "mdReqID", "subscriptionRequestType"]
234
+ required: ["mdUpdateType", "symbols", "mdReqID", "subscriptionRequestType", "mdEntryTypes"]
289
235
  }
290
236
  },
291
237
  getStockGraph: {
@@ -309,895 +255,8 @@ var toolSchemas = {
309
255
  }
310
256
  }
311
257
  };
312
-
313
- // src/tools/marketData.ts
314
- var import_fixparser = require("fixparser");
315
- var import_quickchart_js = __toESM(require("quickchart-js"), 1);
316
- var createMarketDataRequestHandler = (parser, pendingRequests) => {
317
- return async (args) => {
318
- try {
319
- const response = new Promise((resolve) => {
320
- pendingRequests.set(args.mdReqID, resolve);
321
- });
322
- const entryTypes = args.mdEntryTypes || [
323
- import_fixparser.MDEntryType.Bid,
324
- import_fixparser.MDEntryType.Offer,
325
- import_fixparser.MDEntryType.Trade,
326
- import_fixparser.MDEntryType.IndexValue,
327
- import_fixparser.MDEntryType.OpeningPrice,
328
- import_fixparser.MDEntryType.ClosingPrice,
329
- import_fixparser.MDEntryType.SettlementPrice,
330
- import_fixparser.MDEntryType.TradingSessionHighPrice,
331
- import_fixparser.MDEntryType.TradingSessionLowPrice,
332
- import_fixparser.MDEntryType.VWAP,
333
- import_fixparser.MDEntryType.Imbalance,
334
- import_fixparser.MDEntryType.TradeVolume,
335
- import_fixparser.MDEntryType.OpenInterest,
336
- import_fixparser.MDEntryType.CompositeUnderlyingPrice,
337
- import_fixparser.MDEntryType.SimulatedSellPrice,
338
- import_fixparser.MDEntryType.SimulatedBuyPrice,
339
- import_fixparser.MDEntryType.MarginRate,
340
- import_fixparser.MDEntryType.MidPrice,
341
- import_fixparser.MDEntryType.EmptyBook,
342
- import_fixparser.MDEntryType.SettleHighPrice,
343
- import_fixparser.MDEntryType.SettleLowPrice,
344
- import_fixparser.MDEntryType.PriorSettlePrice,
345
- import_fixparser.MDEntryType.SessionHighBid,
346
- import_fixparser.MDEntryType.SessionLowOffer,
347
- import_fixparser.MDEntryType.EarlyPrices,
348
- import_fixparser.MDEntryType.AuctionClearingPrice,
349
- import_fixparser.MDEntryType.SwapValueFactor,
350
- import_fixparser.MDEntryType.DailyValueAdjustmentForLongPositions,
351
- import_fixparser.MDEntryType.CumulativeValueAdjustmentForLongPositions,
352
- import_fixparser.MDEntryType.DailyValueAdjustmentForShortPositions,
353
- import_fixparser.MDEntryType.CumulativeValueAdjustmentForShortPositions,
354
- import_fixparser.MDEntryType.FixingPrice,
355
- import_fixparser.MDEntryType.CashRate,
356
- import_fixparser.MDEntryType.RecoveryRate,
357
- import_fixparser.MDEntryType.RecoveryRateForLong,
358
- import_fixparser.MDEntryType.RecoveryRateForShort,
359
- import_fixparser.MDEntryType.MarketBid,
360
- import_fixparser.MDEntryType.MarketOffer,
361
- import_fixparser.MDEntryType.ShortSaleMinPrice,
362
- import_fixparser.MDEntryType.PreviousClosingPrice,
363
- import_fixparser.MDEntryType.ThresholdLimitPriceBanding,
364
- import_fixparser.MDEntryType.DailyFinancingValue,
365
- import_fixparser.MDEntryType.AccruedFinancingValue,
366
- import_fixparser.MDEntryType.TWAP
367
- ];
368
- const messageFields = [
369
- new import_fixparser.Field(import_fixparser.Fields.MsgType, import_fixparser.Messages.MarketDataRequest),
370
- new import_fixparser.Field(import_fixparser.Fields.SenderCompID, parser.sender),
371
- new import_fixparser.Field(import_fixparser.Fields.MsgSeqNum, parser.getNextTargetMsgSeqNum()),
372
- new import_fixparser.Field(import_fixparser.Fields.TargetCompID, parser.target),
373
- new import_fixparser.Field(import_fixparser.Fields.SendingTime, parser.getTimestamp()),
374
- new import_fixparser.Field(import_fixparser.Fields.MDReqID, args.mdReqID),
375
- new import_fixparser.Field(import_fixparser.Fields.SubscriptionRequestType, args.subscriptionRequestType),
376
- new import_fixparser.Field(import_fixparser.Fields.MarketDepth, 0),
377
- new import_fixparser.Field(import_fixparser.Fields.MDUpdateType, args.mdUpdateType)
378
- ];
379
- messageFields.push(new import_fixparser.Field(import_fixparser.Fields.NoRelatedSym, args.symbols.length));
380
- args.symbols.forEach((symbol) => {
381
- messageFields.push(new import_fixparser.Field(import_fixparser.Fields.Symbol, symbol));
382
- });
383
- messageFields.push(new import_fixparser.Field(import_fixparser.Fields.NoMDEntryTypes, entryTypes.length));
384
- entryTypes.forEach((entryType) => {
385
- messageFields.push(new import_fixparser.Field(import_fixparser.Fields.MDEntryType, entryType));
386
- });
387
- const mdr = parser.createMessage(...messageFields);
388
- if (!parser.connected) {
389
- return {
390
- content: [
391
- {
392
- type: "text",
393
- text: "Error: Not connected. Ignoring message.",
394
- uri: "marketDataRequest"
395
- }
396
- ],
397
- isError: true
398
- };
399
- }
400
- parser.send(mdr);
401
- const fixData = await response;
402
- return {
403
- content: [
404
- {
405
- type: "text",
406
- text: `Market data for ${args.symbols.join(", ")}: ${JSON.stringify(fixData.toFIXJSON())}`,
407
- uri: "marketDataRequest"
408
- }
409
- ]
410
- };
411
- } catch (error) {
412
- return {
413
- content: [
414
- {
415
- type: "text",
416
- text: `Error: ${error instanceof Error ? error.message : "Failed to request market data"}`,
417
- uri: "marketDataRequest"
418
- }
419
- ],
420
- isError: true
421
- };
422
- }
423
- };
424
- };
425
- var createGetStockGraphHandler = (marketDataPrices) => {
426
- return async (args) => {
427
- try {
428
- const symbol = args.symbol;
429
- const priceHistory = marketDataPrices.get(symbol) || [];
430
- if (priceHistory.length === 0) {
431
- return {
432
- content: [
433
- {
434
- type: "text",
435
- text: `No price data available for ${symbol}`,
436
- uri: "getStockGraph"
437
- }
438
- ]
439
- };
440
- }
441
- const chart = new import_quickchart_js.default();
442
- chart.setWidth(1200);
443
- chart.setHeight(600);
444
- chart.setBackgroundColor("transparent");
445
- const labels = priceHistory.map((point) => new Date(point.timestamp).toLocaleTimeString());
446
- const bidData = priceHistory.map((point) => point.bid);
447
- const offerData = priceHistory.map((point) => point.offer);
448
- const spreadData = priceHistory.map((point) => point.spread);
449
- const volumeData = priceHistory.map((point) => point.volume);
450
- const tradeData = priceHistory.map((point) => point.trade);
451
- const vwapData = priceHistory.map((point) => point.vwap);
452
- const twapData = priceHistory.map((point) => point.twap);
453
- const config = {
454
- type: "line",
455
- data: {
456
- labels,
457
- datasets: [
458
- {
459
- label: "Bid",
460
- data: bidData,
461
- borderColor: "#28a745",
462
- backgroundColor: "rgba(40, 167, 69, 0.1)",
463
- fill: false,
464
- tension: 0.4
465
- },
466
- {
467
- label: "Offer",
468
- data: offerData,
469
- borderColor: "#dc3545",
470
- backgroundColor: "rgba(220, 53, 69, 0.1)",
471
- fill: false,
472
- tension: 0.4
473
- },
474
- {
475
- label: "Spread",
476
- data: spreadData,
477
- borderColor: "#6c757d",
478
- backgroundColor: "rgba(108, 117, 125, 0.1)",
479
- fill: false,
480
- tension: 0.4
481
- },
482
- {
483
- label: "Trade",
484
- data: tradeData,
485
- borderColor: "#ffc107",
486
- backgroundColor: "rgba(255, 193, 7, 0.1)",
487
- fill: false,
488
- tension: 0.4
489
- },
490
- {
491
- label: "VWAP",
492
- data: vwapData,
493
- borderColor: "#17a2b8",
494
- backgroundColor: "rgba(23, 162, 184, 0.1)",
495
- fill: false,
496
- tension: 0.4
497
- },
498
- {
499
- label: "TWAP",
500
- data: twapData,
501
- borderColor: "#6610f2",
502
- backgroundColor: "rgba(102, 16, 242, 0.1)",
503
- fill: false,
504
- tension: 0.4
505
- },
506
- {
507
- label: "Volume",
508
- data: volumeData,
509
- borderColor: "#007bff",
510
- backgroundColor: "rgba(0, 123, 255, 0.1)",
511
- fill: true,
512
- tension: 0.4
513
- }
514
- ]
515
- },
516
- options: {
517
- responsive: true,
518
- plugins: {
519
- title: {
520
- display: true,
521
- text: `${symbol} Market Data`
522
- }
523
- },
524
- scales: {
525
- y: {
526
- beginAtZero: false
527
- }
528
- }
529
- }
530
- };
531
- chart.setConfig(config);
532
- const imageBuffer = await chart.toBinary();
533
- const base64 = imageBuffer.toString("base64");
534
- return {
535
- content: [
536
- {
537
- type: "resource",
538
- resource: {
539
- uri: "resource://graph",
540
- mimeType: "image/png",
541
- blob: base64
542
- }
543
- }
544
- ]
545
- };
546
- } catch (error) {
547
- return {
548
- content: [
549
- {
550
- type: "text",
551
- text: `Error: ${error instanceof Error ? error.message : "Failed to generate graph"}`,
552
- uri: "getStockGraph"
553
- }
554
- ],
555
- isError: true
556
- };
557
- }
558
- };
559
- };
560
- var createGetStockPriceHistoryHandler = (marketDataPrices) => {
561
- return async (args) => {
562
- try {
563
- const symbol = args.symbol;
564
- const priceHistory = marketDataPrices.get(symbol) || [];
565
- if (priceHistory.length === 0) {
566
- return {
567
- content: [
568
- {
569
- type: "text",
570
- text: `No price data available for ${symbol}`,
571
- uri: "getStockPriceHistory"
572
- }
573
- ]
574
- };
575
- }
576
- return {
577
- content: [
578
- {
579
- type: "text",
580
- text: JSON.stringify(
581
- {
582
- symbol,
583
- count: priceHistory.length,
584
- data: priceHistory.map((point) => ({
585
- timestamp: new Date(point.timestamp).toISOString(),
586
- bid: point.bid,
587
- offer: point.offer,
588
- spread: point.spread,
589
- volume: point.volume,
590
- trade: point.trade,
591
- indexValue: point.indexValue,
592
- openingPrice: point.openingPrice,
593
- closingPrice: point.closingPrice,
594
- settlementPrice: point.settlementPrice,
595
- tradingSessionHighPrice: point.tradingSessionHighPrice,
596
- tradingSessionLowPrice: point.tradingSessionLowPrice,
597
- vwap: point.vwap,
598
- imbalance: point.imbalance,
599
- openInterest: point.openInterest,
600
- compositeUnderlyingPrice: point.compositeUnderlyingPrice,
601
- simulatedSellPrice: point.simulatedSellPrice,
602
- simulatedBuyPrice: point.simulatedBuyPrice,
603
- marginRate: point.marginRate,
604
- midPrice: point.midPrice,
605
- emptyBook: point.emptyBook,
606
- settleHighPrice: point.settleHighPrice,
607
- settleLowPrice: point.settleLowPrice,
608
- priorSettlePrice: point.priorSettlePrice,
609
- sessionHighBid: point.sessionHighBid,
610
- sessionLowOffer: point.sessionLowOffer,
611
- earlyPrices: point.earlyPrices,
612
- auctionClearingPrice: point.auctionClearingPrice,
613
- swapValueFactor: point.swapValueFactor,
614
- dailyValueAdjustmentForLongPositions: point.dailyValueAdjustmentForLongPositions,
615
- cumulativeValueAdjustmentForLongPositions: point.cumulativeValueAdjustmentForLongPositions,
616
- dailyValueAdjustmentForShortPositions: point.dailyValueAdjustmentForShortPositions,
617
- cumulativeValueAdjustmentForShortPositions: point.cumulativeValueAdjustmentForShortPositions,
618
- fixingPrice: point.fixingPrice,
619
- cashRate: point.cashRate,
620
- recoveryRate: point.recoveryRate,
621
- recoveryRateForLong: point.recoveryRateForLong,
622
- recoveryRateForShort: point.recoveryRateForShort,
623
- marketBid: point.marketBid,
624
- marketOffer: point.marketOffer,
625
- shortSaleMinPrice: point.shortSaleMinPrice,
626
- previousClosingPrice: point.previousClosingPrice,
627
- thresholdLimitPriceBanding: point.thresholdLimitPriceBanding,
628
- dailyFinancingValue: point.dailyFinancingValue,
629
- accruedFinancingValue: point.accruedFinancingValue,
630
- twap: point.twap
631
- }))
632
- },
633
- null,
634
- 2
635
- ),
636
- uri: "getStockPriceHistory"
637
- }
638
- ]
639
- };
640
- } catch (error) {
641
- return {
642
- content: [
643
- {
644
- type: "text",
645
- text: `Error: ${error instanceof Error ? error.message : "Failed to get price history"}`,
646
- uri: "getStockPriceHistory"
647
- }
648
- ],
649
- isError: true
650
- };
651
- }
652
- };
653
- };
654
-
655
- // src/tools/order.ts
656
- var import_fixparser2 = require("fixparser");
657
- var ordTypeNames = {
658
- "1": "Market",
659
- "2": "Limit",
660
- "3": "Stop",
661
- "4": "StopLimit",
662
- "5": "MarketOnClose",
663
- "6": "WithOrWithout",
664
- "7": "LimitOrBetter",
665
- "8": "LimitWithOrWithout",
666
- "9": "OnBasis",
667
- A: "OnClose",
668
- B: "LimitOnClose",
669
- C: "ForexMarket",
670
- D: "PreviouslyQuoted",
671
- E: "PreviouslyIndicated",
672
- F: "ForexLimit",
673
- G: "ForexSwap",
674
- H: "ForexPreviouslyQuoted",
675
- I: "Funari",
676
- J: "MarketIfTouched",
677
- K: "MarketWithLeftOverAsLimit",
678
- L: "PreviousFundValuationPoint",
679
- M: "NextFundValuationPoint",
680
- P: "Pegged",
681
- Q: "CounterOrderSelection",
682
- R: "StopOnBidOrOffer",
683
- S: "StopLimitOnBidOrOffer"
684
- };
685
- var sideNames = {
686
- "1": "Buy",
687
- "2": "Sell",
688
- "3": "BuyMinus",
689
- "4": "SellPlus",
690
- "5": "SellShort",
691
- "6": "SellShortExempt",
692
- "7": "Undisclosed",
693
- "8": "Cross",
694
- "9": "CrossShort",
695
- A: "CrossShortExempt",
696
- B: "AsDefined",
697
- C: "Opposite",
698
- D: "Subscribe",
699
- E: "Redeem",
700
- F: "Lend",
701
- G: "Borrow",
702
- H: "SellUndisclosed"
703
- };
704
- var timeInForceNames = {
705
- "0": "Day",
706
- "1": "GoodTillCancel",
707
- "2": "AtTheOpening",
708
- "3": "ImmediateOrCancel",
709
- "4": "FillOrKill",
710
- "5": "GoodTillCrossing",
711
- "6": "GoodTillDate",
712
- "7": "AtTheClose",
713
- "8": "GoodThroughCrossing",
714
- "9": "AtCrossing",
715
- A: "GoodForTime",
716
- B: "GoodForAuction",
717
- C: "GoodForMonth"
718
- };
719
- var handlInstNames = {
720
- "1": "AutomatedExecutionNoIntervention",
721
- "2": "AutomatedExecutionInterventionOK",
722
- "3": "ManualOrder"
723
- };
724
- var createVerifyOrderHandler = (parser, verifiedOrders) => {
725
- return async (args) => {
726
- try {
727
- verifiedOrders.set(args.clOrdID, {
728
- clOrdID: args.clOrdID,
729
- handlInst: args.handlInst,
730
- quantity: Number.parseFloat(String(args.quantity)),
731
- price: Number.parseFloat(String(args.price)),
732
- ordType: args.ordType,
733
- side: args.side,
734
- symbol: args.symbol,
735
- timeInForce: args.timeInForce
736
- });
737
- return {
738
- content: [
739
- {
740
- type: "text",
741
- text: `VERIFICATION: All parameters valid. Ready to proceed with order execution.
742
-
743
- Parameters verified:
744
- - ClOrdID: ${args.clOrdID}
745
- - HandlInst: ${args.handlInst} (${handlInstNames[args.handlInst]})
746
- - Quantity: ${args.quantity}
747
- - Price: ${args.price}
748
- - OrdType: ${args.ordType} (${ordTypeNames[args.ordType]})
749
- - Side: ${args.side} (${sideNames[args.side]})
750
- - Symbol: ${args.symbol}
751
- - TimeInForce: ${args.timeInForce} (${timeInForceNames[args.timeInForce]})
752
-
753
- To execute this order, call the executeOrder tool with these exact same parameters.`,
754
- uri: "verifyOrder"
755
- }
756
- ]
757
- };
758
- } catch (error) {
759
- return {
760
- content: [
761
- {
762
- type: "text",
763
- text: `Error: ${error instanceof Error ? error.message : "Failed to verify order parameters"}`,
764
- uri: "verifyOrder"
765
- }
766
- ],
767
- isError: true
768
- };
769
- }
770
- };
771
- };
772
- var createExecuteOrderHandler = (parser, verifiedOrders, pendingRequests) => {
773
- return async (args) => {
774
- try {
775
- const verifiedOrder = verifiedOrders.get(args.clOrdID);
776
- if (!verifiedOrder) {
777
- return {
778
- content: [
779
- {
780
- type: "text",
781
- text: `Error: Order ${args.clOrdID} has not been verified. Please call verifyOrder first.`,
782
- uri: "executeOrder"
783
- }
784
- ],
785
- isError: true
786
- };
787
- }
788
- 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) {
789
- return {
790
- content: [
791
- {
792
- type: "text",
793
- text: "Error: Order parameters do not match the verified order. Please use the exact same parameters that were verified.",
794
- uri: "executeOrder"
795
- }
796
- ],
797
- isError: true
798
- };
799
- }
800
- const response = new Promise((resolve) => {
801
- pendingRequests.set(args.clOrdID, resolve);
802
- });
803
- const order = parser.createMessage(
804
- new import_fixparser2.Field(import_fixparser2.Fields.MsgType, import_fixparser2.Messages.NewOrderSingle),
805
- new import_fixparser2.Field(import_fixparser2.Fields.MsgSeqNum, parser.getNextTargetMsgSeqNum()),
806
- new import_fixparser2.Field(import_fixparser2.Fields.SenderCompID, parser.sender),
807
- new import_fixparser2.Field(import_fixparser2.Fields.TargetCompID, parser.target),
808
- new import_fixparser2.Field(import_fixparser2.Fields.SendingTime, parser.getTimestamp()),
809
- new import_fixparser2.Field(import_fixparser2.Fields.ClOrdID, args.clOrdID),
810
- new import_fixparser2.Field(import_fixparser2.Fields.Side, args.side),
811
- new import_fixparser2.Field(import_fixparser2.Fields.Symbol, args.symbol),
812
- new import_fixparser2.Field(import_fixparser2.Fields.OrderQty, Number.parseFloat(String(args.quantity))),
813
- new import_fixparser2.Field(import_fixparser2.Fields.Price, Number.parseFloat(String(args.price))),
814
- new import_fixparser2.Field(import_fixparser2.Fields.OrdType, args.ordType),
815
- new import_fixparser2.Field(import_fixparser2.Fields.HandlInst, args.handlInst),
816
- new import_fixparser2.Field(import_fixparser2.Fields.TimeInForce, args.timeInForce),
817
- new import_fixparser2.Field(import_fixparser2.Fields.TransactTime, parser.getTimestamp())
818
- );
819
- if (!parser.connected) {
820
- return {
821
- content: [
822
- {
823
- type: "text",
824
- text: "Error: Not connected. Ignoring message.",
825
- uri: "executeOrder"
826
- }
827
- ],
828
- isError: true
829
- };
830
- }
831
- parser.send(order);
832
- const fixData = await response;
833
- verifiedOrders.delete(args.clOrdID);
834
- return {
835
- content: [
836
- {
837
- type: "text",
838
- 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())}`,
839
- uri: "executeOrder"
840
- }
841
- ]
842
- };
843
- } catch (error) {
844
- return {
845
- content: [
846
- {
847
- type: "text",
848
- text: `Error: ${error instanceof Error ? error.message : "Failed to execute order"}`,
849
- uri: "executeOrder"
850
- }
851
- ],
852
- isError: true
853
- };
854
- }
855
- };
856
- };
857
-
858
- // src/tools/parse.ts
859
- var createParseHandler = (parser) => {
860
- return async (args) => {
861
- try {
862
- const parsedMessage = parser.parse(args.fixString);
863
- if (!parsedMessage || parsedMessage.length === 0) {
864
- return {
865
- content: [
866
- {
867
- type: "text",
868
- text: "Error: Failed to parse FIX string",
869
- uri: "parse"
870
- }
871
- ],
872
- isError: true
873
- };
874
- }
875
- return {
876
- content: [
877
- {
878
- type: "text",
879
- text: `${parsedMessage[0].description}
880
- ${parsedMessage[0].messageTypeDescription}`,
881
- uri: "parse"
882
- }
883
- ]
884
- };
885
- } catch (error) {
886
- return {
887
- content: [
888
- {
889
- type: "text",
890
- text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`,
891
- uri: "parse"
892
- }
893
- ],
894
- isError: true
895
- };
896
- }
897
- };
898
- };
899
-
900
- // src/tools/parseToJSON.ts
901
- var createParseToJSONHandler = (parser) => {
902
- return async (args) => {
903
- try {
904
- const parsedMessage = parser.parse(args.fixString);
905
- if (!parsedMessage || parsedMessage.length === 0) {
906
- return {
907
- content: [
908
- {
909
- type: "text",
910
- text: "Error: Failed to parse FIX string",
911
- uri: "parseToJSON"
912
- }
913
- ],
914
- isError: true
915
- };
916
- }
917
- return {
918
- content: [
919
- {
920
- type: "text",
921
- text: `${parsedMessage[0].toFIXJSON()}`,
922
- uri: "parseToJSON"
923
- }
924
- ]
925
- };
926
- } catch (error) {
927
- return {
928
- content: [
929
- {
930
- type: "text",
931
- text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`,
932
- uri: "parseToJSON"
933
- }
934
- ],
935
- isError: true
936
- };
937
- }
938
- };
939
- };
940
-
941
- // src/tools/index.ts
942
- var createToolHandlers = (parser, verifiedOrders, pendingRequests, marketDataPrices) => ({
943
- parse: createParseHandler(parser),
944
- parseToJSON: createParseToJSONHandler(parser),
945
- verifyOrder: createVerifyOrderHandler(parser, verifiedOrders),
946
- executeOrder: createExecuteOrderHandler(parser, verifiedOrders, pendingRequests),
947
- marketDataRequest: createMarketDataRequestHandler(parser, pendingRequests),
948
- getStockGraph: createGetStockGraphHandler(marketDataPrices),
949
- getStockPriceHistory: createGetStockPriceHistoryHandler(marketDataPrices)
950
- });
951
-
952
- // src/utils/messageHandler.ts
953
- var import_fixparser3 = require("fixparser");
954
- function handleMessage(message, parser, pendingRequests, marketDataPrices, maxPriceHistory, onPriceUpdate) {
955
- parser.logger.log({
956
- level: "info",
957
- message: `MCP Server received message: ${message.messageType}: ${message.description}`
958
- });
959
- const msgType = message.messageType;
960
- if (msgType === import_fixparser3.Messages.MarketDataSnapshotFullRefresh || msgType === import_fixparser3.Messages.MarketDataIncrementalRefresh) {
961
- const symbol = message.getField(import_fixparser3.Fields.Symbol)?.value;
962
- const fixJson = message.toFIXJSON();
963
- const entries = fixJson.Body?.NoMDEntries || [];
964
- const data = {
965
- timestamp: Date.now(),
966
- bid: 0,
967
- offer: 0,
968
- spread: 0,
969
- volume: 0,
970
- trade: 0,
971
- indexValue: 0,
972
- openingPrice: 0,
973
- closingPrice: 0,
974
- settlementPrice: 0,
975
- tradingSessionHighPrice: 0,
976
- tradingSessionLowPrice: 0,
977
- vwap: 0,
978
- imbalance: 0,
979
- openInterest: 0,
980
- compositeUnderlyingPrice: 0,
981
- simulatedSellPrice: 0,
982
- simulatedBuyPrice: 0,
983
- marginRate: 0,
984
- midPrice: 0,
985
- emptyBook: 0,
986
- settleHighPrice: 0,
987
- settleLowPrice: 0,
988
- priorSettlePrice: 0,
989
- sessionHighBid: 0,
990
- sessionLowOffer: 0,
991
- earlyPrices: 0,
992
- auctionClearingPrice: 0,
993
- swapValueFactor: 0,
994
- dailyValueAdjustmentForLongPositions: 0,
995
- cumulativeValueAdjustmentForLongPositions: 0,
996
- dailyValueAdjustmentForShortPositions: 0,
997
- cumulativeValueAdjustmentForShortPositions: 0,
998
- fixingPrice: 0,
999
- cashRate: 0,
1000
- recoveryRate: 0,
1001
- recoveryRateForLong: 0,
1002
- recoveryRateForShort: 0,
1003
- marketBid: 0,
1004
- marketOffer: 0,
1005
- shortSaleMinPrice: 0,
1006
- previousClosingPrice: 0,
1007
- thresholdLimitPriceBanding: 0,
1008
- dailyFinancingValue: 0,
1009
- accruedFinancingValue: 0,
1010
- twap: 0
1011
- };
1012
- for (const entry of entries) {
1013
- const entryType = entry.MDEntryType;
1014
- const price = entry.MDEntryPx ? Number.parseFloat(entry.MDEntryPx) : 0;
1015
- const size = entry.MDEntrySize ? Number.parseFloat(entry.MDEntrySize) : 0;
1016
- switch (entryType) {
1017
- case import_fixparser3.MDEntryType.Bid:
1018
- data.bid = price;
1019
- break;
1020
- case import_fixparser3.MDEntryType.Offer:
1021
- data.offer = price;
1022
- break;
1023
- case import_fixparser3.MDEntryType.Trade:
1024
- data.trade = price;
1025
- break;
1026
- case import_fixparser3.MDEntryType.IndexValue:
1027
- data.indexValue = price;
1028
- break;
1029
- case import_fixparser3.MDEntryType.OpeningPrice:
1030
- data.openingPrice = price;
1031
- break;
1032
- case import_fixparser3.MDEntryType.ClosingPrice:
1033
- data.closingPrice = price;
1034
- break;
1035
- case import_fixparser3.MDEntryType.SettlementPrice:
1036
- data.settlementPrice = price;
1037
- break;
1038
- case import_fixparser3.MDEntryType.TradingSessionHighPrice:
1039
- data.tradingSessionHighPrice = price;
1040
- break;
1041
- case import_fixparser3.MDEntryType.TradingSessionLowPrice:
1042
- data.tradingSessionLowPrice = price;
1043
- break;
1044
- case import_fixparser3.MDEntryType.VWAP:
1045
- data.vwap = price;
1046
- break;
1047
- case import_fixparser3.MDEntryType.Imbalance:
1048
- data.imbalance = size;
1049
- break;
1050
- case import_fixparser3.MDEntryType.TradeVolume:
1051
- data.volume = size;
1052
- break;
1053
- case import_fixparser3.MDEntryType.OpenInterest:
1054
- data.openInterest = size;
1055
- break;
1056
- case import_fixparser3.MDEntryType.CompositeUnderlyingPrice:
1057
- data.compositeUnderlyingPrice = price;
1058
- break;
1059
- case import_fixparser3.MDEntryType.SimulatedSellPrice:
1060
- data.simulatedSellPrice = price;
1061
- break;
1062
- case import_fixparser3.MDEntryType.SimulatedBuyPrice:
1063
- data.simulatedBuyPrice = price;
1064
- break;
1065
- case import_fixparser3.MDEntryType.MarginRate:
1066
- data.marginRate = price;
1067
- break;
1068
- case import_fixparser3.MDEntryType.MidPrice:
1069
- data.midPrice = price;
1070
- break;
1071
- case import_fixparser3.MDEntryType.EmptyBook:
1072
- data.emptyBook = 1;
1073
- break;
1074
- case import_fixparser3.MDEntryType.SettleHighPrice:
1075
- data.settleHighPrice = price;
1076
- break;
1077
- case import_fixparser3.MDEntryType.SettleLowPrice:
1078
- data.settleLowPrice = price;
1079
- break;
1080
- case import_fixparser3.MDEntryType.PriorSettlePrice:
1081
- data.priorSettlePrice = price;
1082
- break;
1083
- case import_fixparser3.MDEntryType.SessionHighBid:
1084
- data.sessionHighBid = price;
1085
- break;
1086
- case import_fixparser3.MDEntryType.SessionLowOffer:
1087
- data.sessionLowOffer = price;
1088
- break;
1089
- case import_fixparser3.MDEntryType.EarlyPrices:
1090
- data.earlyPrices = price;
1091
- break;
1092
- case import_fixparser3.MDEntryType.AuctionClearingPrice:
1093
- data.auctionClearingPrice = price;
1094
- break;
1095
- case import_fixparser3.MDEntryType.SwapValueFactor:
1096
- data.swapValueFactor = price;
1097
- break;
1098
- case import_fixparser3.MDEntryType.DailyValueAdjustmentForLongPositions:
1099
- data.dailyValueAdjustmentForLongPositions = price;
1100
- break;
1101
- case import_fixparser3.MDEntryType.CumulativeValueAdjustmentForLongPositions:
1102
- data.cumulativeValueAdjustmentForLongPositions = price;
1103
- break;
1104
- case import_fixparser3.MDEntryType.DailyValueAdjustmentForShortPositions:
1105
- data.dailyValueAdjustmentForShortPositions = price;
1106
- break;
1107
- case import_fixparser3.MDEntryType.CumulativeValueAdjustmentForShortPositions:
1108
- data.cumulativeValueAdjustmentForShortPositions = price;
1109
- break;
1110
- case import_fixparser3.MDEntryType.FixingPrice:
1111
- data.fixingPrice = price;
1112
- break;
1113
- case import_fixparser3.MDEntryType.CashRate:
1114
- data.cashRate = price;
1115
- break;
1116
- case import_fixparser3.MDEntryType.RecoveryRate:
1117
- data.recoveryRate = price;
1118
- break;
1119
- case import_fixparser3.MDEntryType.RecoveryRateForLong:
1120
- data.recoveryRateForLong = price;
1121
- break;
1122
- case import_fixparser3.MDEntryType.RecoveryRateForShort:
1123
- data.recoveryRateForShort = price;
1124
- break;
1125
- case import_fixparser3.MDEntryType.MarketBid:
1126
- data.marketBid = price;
1127
- break;
1128
- case import_fixparser3.MDEntryType.MarketOffer:
1129
- data.marketOffer = price;
1130
- break;
1131
- case import_fixparser3.MDEntryType.ShortSaleMinPrice:
1132
- data.shortSaleMinPrice = price;
1133
- break;
1134
- case import_fixparser3.MDEntryType.PreviousClosingPrice:
1135
- data.previousClosingPrice = price;
1136
- break;
1137
- case import_fixparser3.MDEntryType.ThresholdLimitPriceBanding:
1138
- data.thresholdLimitPriceBanding = price;
1139
- break;
1140
- case import_fixparser3.MDEntryType.DailyFinancingValue:
1141
- data.dailyFinancingValue = price;
1142
- break;
1143
- case import_fixparser3.MDEntryType.AccruedFinancingValue:
1144
- data.accruedFinancingValue = price;
1145
- break;
1146
- case import_fixparser3.MDEntryType.TWAP:
1147
- data.twap = price;
1148
- break;
1149
- }
1150
- }
1151
- data.spread = data.offer - data.bid;
1152
- if (!marketDataPrices.has(symbol)) {
1153
- marketDataPrices.set(symbol, []);
1154
- }
1155
- const prices = marketDataPrices.get(symbol);
1156
- prices.push(data);
1157
- if (prices.length > maxPriceHistory) {
1158
- prices.splice(0, prices.length - maxPriceHistory);
1159
- }
1160
- onPriceUpdate?.(symbol, data);
1161
- const mdReqID = message.getField(import_fixparser3.Fields.MDReqID)?.value;
1162
- if (mdReqID) {
1163
- const callback = pendingRequests.get(mdReqID);
1164
- if (callback) {
1165
- callback(message);
1166
- pendingRequests.delete(mdReqID);
1167
- }
1168
- }
1169
- } else if (msgType === import_fixparser3.Messages.ExecutionReport) {
1170
- const reqId = message.getField(import_fixparser3.Fields.ClOrdID)?.value;
1171
- const callback = pendingRequests.get(reqId);
1172
- if (callback) {
1173
- callback(message);
1174
- pendingRequests.delete(reqId);
1175
- }
1176
- }
1177
- }
1178
-
1179
- // src/MCPLocal.ts
1180
- var MCPLocal = class extends MCPBase {
1181
- /**
1182
- * Map to store verified orders before execution
1183
- * @private
1184
- */
1185
- verifiedOrders = /* @__PURE__ */ new Map();
1186
- /**
1187
- * Map to store pending requests and their callbacks
1188
- * @private
1189
- */
1190
- pendingRequests = /* @__PURE__ */ new Map();
1191
- /**
1192
- * Map to store market data prices for each symbol
1193
- * @private
1194
- */
1195
- marketDataPrices = /* @__PURE__ */ new Map();
1196
- /**
1197
- * Maximum number of price history entries to keep per symbol
1198
- * @private
1199
- */
1200
- MAX_PRICE_HISTORY = 1e5;
258
+ var MCPLocal = class {
259
+ parser;
1201
260
  server = new import_server.Server(
1202
261
  {
1203
262
  name: "fixparser",
@@ -1219,13 +278,78 @@ var MCPLocal = class extends MCPBase {
1219
278
  }
1220
279
  );
1221
280
  transport = new import_stdio.StdioServerTransport();
281
+ onReady = void 0;
282
+ pendingRequests = /* @__PURE__ */ new Map();
283
+ verifiedOrders = /* @__PURE__ */ new Map();
284
+ // Store market data prices with timestamps
285
+ marketDataPrices = /* @__PURE__ */ new Map();
286
+ MAX_PRICE_HISTORY = 1e5;
287
+ // Maximum number of price points to store per symbol
1222
288
  constructor({ logger, onReady }) {
1223
- super({ logger, onReady });
289
+ if (onReady) this.onReady = onReady;
1224
290
  }
1225
291
  async register(parser) {
1226
292
  this.parser = parser;
1227
293
  this.parser.addOnMessageCallback((message) => {
1228
- handleMessage(message, this.parser, this.pendingRequests, this.marketDataPrices, this.MAX_PRICE_HISTORY);
294
+ this.parser?.logger.log({
295
+ level: "info",
296
+ message: `MCP Server received message: ${message.messageType}: ${message.description}`
297
+ });
298
+ const msgType = message.messageType;
299
+ if (msgType === import_fixparser.Messages.MarketDataSnapshotFullRefresh || msgType === import_fixparser.Messages.ExecutionReport || msgType === import_fixparser.Messages.Reject || msgType === import_fixparser.Messages.MarketDataIncrementalRefresh) {
300
+ this.parser?.logger.log({
301
+ level: "info",
302
+ message: `MCP Server handling message type: ${msgType}`
303
+ });
304
+ let id;
305
+ if (msgType === import_fixparser.Messages.MarketDataIncrementalRefresh || msgType === import_fixparser.Messages.MarketDataSnapshotFullRefresh) {
306
+ const symbol = message.getField(import_fixparser.Fields.Symbol);
307
+ const price = message.getField(import_fixparser.Fields.MDEntryPx);
308
+ const timestamp = message.getField(import_fixparser.Fields.MDEntryTime)?.value || Date.now();
309
+ if (symbol?.value && price?.value) {
310
+ const symbolStr = String(symbol.value);
311
+ const priceNum = Number(price.value);
312
+ const priceHistory = this.marketDataPrices.get(symbolStr) || [];
313
+ priceHistory.push({
314
+ timestamp: Number(timestamp),
315
+ price: priceNum
316
+ });
317
+ if (priceHistory.length > this.MAX_PRICE_HISTORY) {
318
+ priceHistory.shift();
319
+ }
320
+ this.marketDataPrices.set(symbolStr, priceHistory);
321
+ this.parser?.logger.log({
322
+ level: "info",
323
+ message: `MCP Server added ${symbol}: ${priceNum}`
324
+ });
325
+ this.server.notification({
326
+ method: "priceUpdate",
327
+ params: {
328
+ symbol: symbolStr,
329
+ price: priceNum,
330
+ timestamp: Number(timestamp)
331
+ }
332
+ });
333
+ }
334
+ }
335
+ if (msgType === import_fixparser.Messages.MarketDataSnapshotFullRefresh) {
336
+ const mdReqID = message.getField(import_fixparser.Fields.MDReqID);
337
+ if (mdReqID) id = String(mdReqID.value);
338
+ } else if (msgType === import_fixparser.Messages.ExecutionReport) {
339
+ const clOrdID = message.getField(import_fixparser.Fields.ClOrdID);
340
+ if (clOrdID) id = String(clOrdID.value);
341
+ } else if (msgType === import_fixparser.Messages.Reject) {
342
+ const refSeqNum = message.getField(import_fixparser.Fields.RefSeqNum);
343
+ if (refSeqNum) id = String(refSeqNum.value);
344
+ }
345
+ if (id) {
346
+ const callback = this.pendingRequests.get(id);
347
+ if (callback) {
348
+ callback(message);
349
+ this.pendingRequests.delete(id);
350
+ }
351
+ }
352
+ }
1229
353
  });
1230
354
  this.addWorkflows();
1231
355
  await this.server.connect(this.transport);
@@ -1240,15 +364,18 @@ var MCPLocal = class extends MCPBase {
1240
364
  if (!this.server) {
1241
365
  return;
1242
366
  }
1243
- this.server.setRequestHandler(import_zod.z.object({ method: import_zod.z.literal("tools/list") }), async () => {
1244
- return {
1245
- tools: Object.entries(toolSchemas).map(([name, { description, schema }]) => ({
1246
- name,
1247
- description,
1248
- inputSchema: schema
1249
- }))
1250
- };
1251
- });
367
+ this.server.setRequestHandler(
368
+ import_zod.z.object({ method: import_zod.z.literal("tools/list") }),
369
+ async (request, extra) => {
370
+ return {
371
+ tools: Object.entries(toolSchemas).map(([name, { description, schema }]) => ({
372
+ name,
373
+ description,
374
+ inputSchema: schema
375
+ }))
376
+ };
377
+ }
378
+ );
1252
379
  this.server.setRequestHandler(
1253
380
  import_zod.z.object({
1254
381
  method: import_zod.z.literal("tools/call"),
@@ -1260,32 +387,493 @@ var MCPLocal = class extends MCPBase {
1260
387
  }).optional()
1261
388
  })
1262
389
  }),
1263
- async (request) => {
390
+ async (request, extra) => {
1264
391
  const { name, arguments: args } = request.params;
1265
- const toolHandlers = createToolHandlers(
1266
- this.parser,
1267
- this.verifiedOrders,
1268
- this.pendingRequests,
1269
- this.marketDataPrices
1270
- );
1271
- const handler = toolHandlers[name];
1272
- if (!handler) {
1273
- return {
1274
- content: [
1275
- {
1276
- type: "text",
1277
- text: `Tool not found: ${name}`,
1278
- uri: name
392
+ switch (name) {
393
+ case "parse":
394
+ try {
395
+ const parsedMessage = this.parser?.parse(args.fixString);
396
+ if (!parsedMessage || parsedMessage.length === 0) {
397
+ return {
398
+ content: [
399
+ {
400
+ type: "text",
401
+ text: "Error: Failed to parse FIX string",
402
+ uri: "parse"
403
+ }
404
+ ],
405
+ isError: true
406
+ };
1279
407
  }
1280
- ],
1281
- isError: true
1282
- };
408
+ return {
409
+ content: [
410
+ {
411
+ type: "text",
412
+ text: `${parsedMessage[0].description}
413
+ ${parsedMessage[0].messageTypeDescription}`,
414
+ uri: "parse"
415
+ }
416
+ ]
417
+ };
418
+ } catch (error) {
419
+ return {
420
+ content: [
421
+ {
422
+ type: "text",
423
+ text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`,
424
+ uri: "parse"
425
+ }
426
+ ],
427
+ isError: true
428
+ };
429
+ }
430
+ case "parseToJSON":
431
+ try {
432
+ const parsedMessage = this.parser?.parse(args.fixString);
433
+ if (!parsedMessage || parsedMessage.length === 0) {
434
+ return {
435
+ content: [
436
+ {
437
+ type: "text",
438
+ text: "Error: Failed to parse FIX string",
439
+ uri: "parseToJSON"
440
+ }
441
+ ],
442
+ isError: true
443
+ };
444
+ }
445
+ return {
446
+ content: [
447
+ {
448
+ type: "text",
449
+ text: `${parsedMessage[0].toFIXJSON()}`,
450
+ uri: "parseToJSON"
451
+ }
452
+ ]
453
+ };
454
+ } catch (error) {
455
+ return {
456
+ content: [
457
+ {
458
+ type: "text",
459
+ text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`,
460
+ uri: "parseToJSON"
461
+ }
462
+ ],
463
+ isError: true
464
+ };
465
+ }
466
+ case "verifyOrder":
467
+ try {
468
+ this.verifiedOrders.set(args.clOrdID, {
469
+ clOrdID: args.clOrdID,
470
+ handlInst: args.handlInst,
471
+ quantity: Number.parseFloat(args.quantity),
472
+ price: Number.parseFloat(args.price),
473
+ ordType: args.ordType,
474
+ side: args.side,
475
+ symbol: args.symbol,
476
+ timeInForce: args.timeInForce
477
+ });
478
+ const ordTypeNames = {
479
+ "1": "Market",
480
+ "2": "Limit",
481
+ "3": "Stop",
482
+ "4": "StopLimit",
483
+ "5": "MarketOnClose",
484
+ "6": "WithOrWithout",
485
+ "7": "LimitOrBetter",
486
+ "8": "LimitWithOrWithout",
487
+ "9": "OnBasis",
488
+ A: "OnClose",
489
+ B: "LimitOnClose",
490
+ C: "ForexMarket",
491
+ D: "PreviouslyQuoted",
492
+ E: "PreviouslyIndicated",
493
+ F: "ForexLimit",
494
+ G: "ForexSwap",
495
+ H: "ForexPreviouslyQuoted",
496
+ I: "Funari",
497
+ J: "MarketIfTouched",
498
+ K: "MarketWithLeftOverAsLimit",
499
+ L: "PreviousFundValuationPoint",
500
+ M: "NextFundValuationPoint",
501
+ P: "Pegged",
502
+ Q: "CounterOrderSelection",
503
+ R: "StopOnBidOrOffer",
504
+ S: "StopLimitOnBidOrOffer"
505
+ };
506
+ const sideNames = {
507
+ "1": "Buy",
508
+ "2": "Sell",
509
+ "3": "BuyMinus",
510
+ "4": "SellPlus",
511
+ "5": "SellShort",
512
+ "6": "SellShortExempt",
513
+ "7": "Undisclosed",
514
+ "8": "Cross",
515
+ "9": "CrossShort",
516
+ A: "CrossShortExempt",
517
+ B: "AsDefined",
518
+ C: "Opposite",
519
+ D: "Subscribe",
520
+ E: "Redeem",
521
+ F: "Lend",
522
+ G: "Borrow",
523
+ H: "SellUndisclosed"
524
+ };
525
+ const timeInForceNames = {
526
+ "0": "Day",
527
+ "1": "GoodTillCancel",
528
+ "2": "AtTheOpening",
529
+ "3": "ImmediateOrCancel",
530
+ "4": "FillOrKill",
531
+ "5": "GoodTillCrossing",
532
+ "6": "GoodTillDate",
533
+ "7": "AtTheClose",
534
+ "8": "GoodThroughCrossing",
535
+ "9": "AtCrossing",
536
+ A: "GoodForTime",
537
+ B: "GoodForAuction",
538
+ C: "GoodForMonth"
539
+ };
540
+ const handlInstNames = {
541
+ "1": "AutomatedExecutionNoIntervention",
542
+ "2": "AutomatedExecutionInterventionOK",
543
+ "3": "ManualOrder"
544
+ };
545
+ return {
546
+ content: [
547
+ {
548
+ type: "text",
549
+ text: `VERIFICATION: All parameters valid. Ready to proceed with order execution.
550
+
551
+ Parameters verified:
552
+ - ClOrdID: ${args.clOrdID}
553
+ - HandlInst: ${args.handlInst} (${handlInstNames[args.handlInst]})
554
+ - Quantity: ${args.quantity}
555
+ - Price: ${args.price}
556
+ - OrdType: ${args.ordType} (${ordTypeNames[args.ordType]})
557
+ - Side: ${args.side} (${sideNames[args.side]})
558
+ - Symbol: ${args.symbol}
559
+ - TimeInForce: ${args.timeInForce} (${timeInForceNames[args.timeInForce]})
560
+
561
+ To execute this order, call the executeOrder tool with these exact same parameters.`,
562
+ uri: "verifyOrder"
563
+ }
564
+ ]
565
+ };
566
+ } catch (error) {
567
+ return {
568
+ content: [
569
+ {
570
+ type: "text",
571
+ text: `Error: ${error instanceof Error ? error.message : "Failed to verify order parameters"}`,
572
+ uri: "verifyOrder"
573
+ }
574
+ ],
575
+ isError: true
576
+ };
577
+ }
578
+ case "executeOrder":
579
+ try {
580
+ const verifiedOrder = this.verifiedOrders.get(args.clOrdID);
581
+ if (!verifiedOrder) {
582
+ return {
583
+ content: [
584
+ {
585
+ type: "text",
586
+ text: `Error: Order ${args.clOrdID} has not been verified. Please call verifyOrder first.`,
587
+ uri: "executeOrder"
588
+ }
589
+ ],
590
+ isError: true
591
+ };
592
+ }
593
+ if (verifiedOrder.handlInst !== args.handlInst || verifiedOrder.quantity !== Number.parseFloat(args.quantity) || verifiedOrder.price !== Number.parseFloat(args.price) || verifiedOrder.ordType !== args.ordType || verifiedOrder.side !== args.side || verifiedOrder.symbol !== args.symbol || verifiedOrder.timeInForce !== args.timeInForce) {
594
+ return {
595
+ content: [
596
+ {
597
+ type: "text",
598
+ text: "Error: Order parameters do not match the verified order. Please use the exact same parameters that were verified.",
599
+ uri: "executeOrder"
600
+ }
601
+ ],
602
+ isError: true
603
+ };
604
+ }
605
+ const response = new Promise((resolve) => {
606
+ this.pendingRequests.set(args.clOrdID, resolve);
607
+ });
608
+ const order = this.parser?.createMessage(
609
+ new import_fixparser.Field(import_fixparser.Fields.MsgType, import_fixparser.Messages.NewOrderSingle),
610
+ new import_fixparser.Field(import_fixparser.Fields.MsgSeqNum, this.parser?.getNextTargetMsgSeqNum()),
611
+ new import_fixparser.Field(import_fixparser.Fields.SenderCompID, this.parser?.sender),
612
+ new import_fixparser.Field(import_fixparser.Fields.TargetCompID, this.parser?.target),
613
+ new import_fixparser.Field(import_fixparser.Fields.SendingTime, this.parser?.getTimestamp()),
614
+ new import_fixparser.Field(import_fixparser.Fields.ClOrdID, args.clOrdID),
615
+ new import_fixparser.Field(import_fixparser.Fields.Side, args.side),
616
+ new import_fixparser.Field(import_fixparser.Fields.Symbol, args.symbol),
617
+ new import_fixparser.Field(import_fixparser.Fields.OrderQty, Number.parseFloat(args.quantity)),
618
+ new import_fixparser.Field(import_fixparser.Fields.Price, Number.parseFloat(args.price)),
619
+ new import_fixparser.Field(import_fixparser.Fields.OrdType, args.ordType),
620
+ new import_fixparser.Field(import_fixparser.Fields.HandlInst, args.handlInst),
621
+ new import_fixparser.Field(import_fixparser.Fields.TimeInForce, args.timeInForce),
622
+ new import_fixparser.Field(import_fixparser.Fields.TransactTime, this.parser?.getTimestamp())
623
+ );
624
+ if (!this.parser?.connected) {
625
+ return {
626
+ content: [
627
+ {
628
+ type: "text",
629
+ text: "Error: Not connected. Ignoring message.",
630
+ uri: "executeOrder"
631
+ }
632
+ ],
633
+ isError: true
634
+ };
635
+ }
636
+ this.parser?.send(order);
637
+ const fixData = await response;
638
+ this.verifiedOrders.delete(args.clOrdID);
639
+ return {
640
+ content: [
641
+ {
642
+ type: "text",
643
+ text: fixData.messageType === import_fixparser.Messages.Reject ? `Reject message for order ${args.clOrdID}: ${JSON.stringify(fixData.toFIXJSON())}` : `Execution Report for order ${args.clOrdID}: ${JSON.stringify(fixData.toFIXJSON())}`,
644
+ uri: "executeOrder"
645
+ }
646
+ ]
647
+ };
648
+ } catch (error) {
649
+ return {
650
+ content: [
651
+ {
652
+ type: "text",
653
+ text: `Error: ${error instanceof Error ? error.message : "Failed to execute order"}`,
654
+ uri: "executeOrder"
655
+ }
656
+ ],
657
+ isError: true
658
+ };
659
+ }
660
+ case "marketDataRequest":
661
+ try {
662
+ const response = new Promise((resolve) => {
663
+ this.pendingRequests.set(args.mdReqID, resolve);
664
+ });
665
+ const messageFields = [
666
+ new import_fixparser.Field(import_fixparser.Fields.MsgType, import_fixparser.Messages.MarketDataRequest),
667
+ new import_fixparser.Field(import_fixparser.Fields.SenderCompID, this.parser?.sender),
668
+ new import_fixparser.Field(import_fixparser.Fields.MsgSeqNum, this.parser?.getNextTargetMsgSeqNum()),
669
+ new import_fixparser.Field(import_fixparser.Fields.TargetCompID, this.parser?.target),
670
+ new import_fixparser.Field(import_fixparser.Fields.SendingTime, this.parser?.getTimestamp()),
671
+ new import_fixparser.Field(import_fixparser.Fields.MDReqID, args.mdReqID),
672
+ new import_fixparser.Field(import_fixparser.Fields.SubscriptionRequestType, args.subscriptionRequestType),
673
+ new import_fixparser.Field(import_fixparser.Fields.MarketDepth, 0),
674
+ new import_fixparser.Field(import_fixparser.Fields.MDUpdateType, args.mdUpdateType)
675
+ ];
676
+ messageFields.push(new import_fixparser.Field(import_fixparser.Fields.NoRelatedSym, args.symbols.length));
677
+ args.symbols.forEach((symbol) => {
678
+ messageFields.push(new import_fixparser.Field(import_fixparser.Fields.Symbol, symbol));
679
+ });
680
+ messageFields.push(new import_fixparser.Field(import_fixparser.Fields.NoMDEntryTypes, args.mdEntryTypes.length));
681
+ args.mdEntryTypes.forEach((entryType) => {
682
+ messageFields.push(new import_fixparser.Field(import_fixparser.Fields.MDEntryType, entryType));
683
+ });
684
+ const mdr = this.parser?.createMessage(...messageFields);
685
+ if (!this.parser?.connected) {
686
+ return {
687
+ content: [
688
+ {
689
+ type: "text",
690
+ text: "Error: Not connected. Ignoring message.",
691
+ uri: "marketDataRequest"
692
+ }
693
+ ],
694
+ isError: true
695
+ };
696
+ }
697
+ this.parser?.send(mdr);
698
+ const fixData = await response;
699
+ return {
700
+ content: [
701
+ {
702
+ type: "text",
703
+ text: `Market data for ${args.symbols.join(", ")}: ${JSON.stringify(fixData.toFIXJSON())}`,
704
+ uri: "marketDataRequest"
705
+ }
706
+ ]
707
+ };
708
+ } catch (error) {
709
+ return {
710
+ content: [
711
+ {
712
+ type: "text",
713
+ text: `Error: ${error instanceof Error ? error.message : "Failed to request market data"}`,
714
+ uri: "marketDataRequest"
715
+ }
716
+ ],
717
+ isError: true
718
+ };
719
+ }
720
+ case "getStockGraph":
721
+ try {
722
+ const symbol = args.symbol;
723
+ const priceHistory = this.marketDataPrices.get(symbol) || [];
724
+ if (priceHistory.length === 0) {
725
+ return {
726
+ content: [
727
+ {
728
+ type: "text",
729
+ text: `No price data available for ${symbol}`,
730
+ uri: "getStockGraph"
731
+ }
732
+ ]
733
+ };
734
+ }
735
+ const width = 600;
736
+ const height = 300;
737
+ const padding = 40;
738
+ const xScale = (width - 2 * padding) / (priceHistory.length - 1);
739
+ const yMin = Math.min(...priceHistory.map((d) => d.price));
740
+ const yMax = Math.max(...priceHistory.map((d) => d.price));
741
+ const yScale = (height - 2 * padding) / (yMax - yMin);
742
+ const points = priceHistory.map((d, i) => {
743
+ const x = padding + i * xScale;
744
+ const y = height - padding - (d.price - yMin) * yScale;
745
+ return `${x},${y}`;
746
+ }).join(" L ");
747
+ const svg = `<?xml version="1.0" encoding="UTF-8"?>
748
+ <svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">
749
+ <!-- Background -->
750
+ <rect width="100%" height="100%" fill="#f8f9fa"/>
751
+
752
+ <!-- Grid lines -->
753
+ <g stroke="#e9ecef" stroke-width="1">
754
+ ${Array.from({ length: 5 }, (_, i) => {
755
+ const y = padding + (height - 2 * padding) * i / 4;
756
+ return `<line x1="${padding}" y1="${y}" x2="${width - padding}" y2="${y}"/>`;
757
+ }).join("\n")}
758
+ </g>
759
+
760
+ <!-- Price line -->
761
+ <path d="M ${points}"
762
+ fill="none"
763
+ stroke="#007bff"
764
+ stroke-width="2"/>
765
+
766
+ <!-- Data points -->
767
+ ${priceHistory.map((d, i) => {
768
+ const x = padding + i * xScale;
769
+ const y = height - padding - (d.price - yMin) * yScale;
770
+ return `<circle cx="${x}" cy="${y}" r="3" fill="#007bff"/>`;
771
+ }).join("\n")}
772
+
773
+ <!-- Labels -->
774
+ <g font-family="Arial" font-size="12" fill="#495057">
775
+ ${Array.from({ length: 5 }, (_, i) => {
776
+ const x = padding + (width - 2 * padding) * i / 4;
777
+ const index = Math.floor((priceHistory.length - 1) * i / 4);
778
+ const timestamp = new Date(priceHistory[index].timestamp).toLocaleTimeString();
779
+ return `<text x="${x + padding}" y="${height - padding + 20}" text-anchor="middle">${timestamp}</text>`;
780
+ }).join("\n")}
781
+ ${Array.from({ length: 5 }, (_, i) => {
782
+ const y = padding + (height - 2 * padding) * i / 4;
783
+ const price = yMax - (yMax - yMin) * i / 4;
784
+ return `<text x="${padding - 5}" y="${y + 4}" text-anchor="end">$${price.toFixed(2)}</text>`;
785
+ }).join("\n")}
786
+ </g>
787
+
788
+ <!-- Title -->
789
+ <text x="${width / 2}" y="${padding / 2}"
790
+ font-family="Arial" font-size="16" font-weight="bold"
791
+ text-anchor="middle" fill="#212529">
792
+ ${symbol} - Price Chart (${priceHistory.length} points)
793
+ </text>
794
+ </svg>`;
795
+ const base64Svg = Buffer.from(svg).toString("base64");
796
+ return {
797
+ content: [
798
+ {
799
+ type: "image",
800
+ text: base64Svg,
801
+ uri: "getStockGraph",
802
+ mimeType: "image/svg+xml"
803
+ }
804
+ ]
805
+ };
806
+ } catch (error) {
807
+ return {
808
+ content: [
809
+ {
810
+ type: "text",
811
+ text: `Error: ${error instanceof Error ? error.message : "Failed to generate stock graph"}`,
812
+ uri: "getStockGraph"
813
+ }
814
+ ],
815
+ isError: true
816
+ };
817
+ }
818
+ case "getStockPriceHistory":
819
+ try {
820
+ const symbol = args.symbol;
821
+ const priceHistory = this.marketDataPrices.get(symbol) || [];
822
+ if (priceHistory.length === 0) {
823
+ return {
824
+ content: [
825
+ {
826
+ type: "text",
827
+ text: `No price data available for ${symbol}`,
828
+ uri: "getStockPriceHistory"
829
+ }
830
+ ]
831
+ };
832
+ }
833
+ return {
834
+ content: [
835
+ {
836
+ type: "text",
837
+ text: JSON.stringify(
838
+ {
839
+ symbol,
840
+ count: priceHistory.length,
841
+ prices: priceHistory.map((point) => ({
842
+ timestamp: new Date(point.timestamp).toISOString(),
843
+ price: point.price
844
+ }))
845
+ },
846
+ null,
847
+ 2
848
+ ),
849
+ uri: "getStockPriceHistory"
850
+ }
851
+ ]
852
+ };
853
+ } catch (error) {
854
+ return {
855
+ content: [
856
+ {
857
+ type: "text",
858
+ text: `Error: ${error instanceof Error ? error.message : "Failed to get stock price history"}`,
859
+ uri: "getStockPriceHistory"
860
+ }
861
+ ],
862
+ isError: true
863
+ };
864
+ }
865
+ default:
866
+ return {
867
+ content: [
868
+ {
869
+ type: "text",
870
+ text: `Tool not found: ${name}`,
871
+ uri: name
872
+ }
873
+ ],
874
+ isError: true
875
+ };
1283
876
  }
1284
- const result = await handler(args);
1285
- return {
1286
- content: result.content,
1287
- isError: result.isError
1288
- };
1289
877
  }
1290
878
  );
1291
879
  process.on("SIGINT", async () => {