fixparser-plugin-mcp 9.1.7-e7f944da → 9.1.7-e80c38c2

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,10 +1,9 @@
1
1
  // src/MCPLocal.ts
2
2
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
3
3
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
- import { Fields as Fields3, MDEntryType as MDEntryType2, Messages as Messages3 } from "fixparser";
4
+ import { Field, Fields, Messages } from "fixparser";
5
+ import sharp from "sharp";
5
6
  import { z } from "zod";
6
-
7
- // src/schemas/schemas.ts
8
7
  var toolSchemas = {
9
8
  parse: {
10
9
  description: "Parses a FIX message and describes it in plain language",
@@ -204,12 +203,12 @@ var toolSchemas = {
204
203
  "X",
205
204
  "Y",
206
205
  "Z"
207
- ]
208
- },
209
- 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"
206
+ ],
207
+ 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"
208
+ }
210
209
  }
211
210
  },
212
- required: ["mdUpdateType", "symbols", "mdReqID", "subscriptionRequestType"]
211
+ required: ["mdUpdateType", "symbols", "mdReqID", "subscriptionRequestType", "mdEntryTypes"]
213
212
  }
214
213
  },
215
214
  getStockGraph: {
@@ -233,534 +232,6 @@ var toolSchemas = {
233
232
  }
234
233
  }
235
234
  };
236
-
237
- // src/tools/marketData.ts
238
- import { Field, Fields, MDEntryType, Messages } from "fixparser";
239
- import QuickChart from "quickchart-js";
240
- var createMarketDataRequestHandler = (parser, pendingRequests) => {
241
- return async (args) => {
242
- try {
243
- const response = new Promise((resolve) => {
244
- pendingRequests.set(args.mdReqID, resolve);
245
- });
246
- const entryTypes = args.mdEntryTypes || [MDEntryType.Bid, MDEntryType.Offer, MDEntryType.TradeVolume];
247
- const messageFields = [
248
- new Field(Fields.MsgType, Messages.MarketDataRequest),
249
- new Field(Fields.SenderCompID, parser.sender),
250
- new Field(Fields.MsgSeqNum, parser.getNextTargetMsgSeqNum()),
251
- new Field(Fields.TargetCompID, parser.target),
252
- new Field(Fields.SendingTime, parser.getTimestamp()),
253
- new Field(Fields.MDReqID, args.mdReqID),
254
- new Field(Fields.SubscriptionRequestType, args.subscriptionRequestType),
255
- new Field(Fields.MarketDepth, 0),
256
- new Field(Fields.MDUpdateType, args.mdUpdateType)
257
- ];
258
- messageFields.push(new Field(Fields.NoRelatedSym, args.symbols.length));
259
- args.symbols.forEach((symbol) => {
260
- messageFields.push(new Field(Fields.Symbol, symbol));
261
- });
262
- messageFields.push(new Field(Fields.NoMDEntryTypes, entryTypes.length));
263
- entryTypes.forEach((entryType) => {
264
- messageFields.push(new Field(Fields.MDEntryType, entryType));
265
- });
266
- const mdr = parser.createMessage(...messageFields);
267
- if (!parser.connected) {
268
- return {
269
- content: [
270
- {
271
- type: "text",
272
- text: "Error: Not connected. Ignoring message.",
273
- uri: "marketDataRequest"
274
- }
275
- ],
276
- isError: true
277
- };
278
- }
279
- parser.send(mdr);
280
- const fixData = await response;
281
- return {
282
- content: [
283
- {
284
- type: "text",
285
- text: `Market data for ${args.symbols.join(", ")}: ${JSON.stringify(fixData.toFIXJSON())}`,
286
- uri: "marketDataRequest"
287
- }
288
- ]
289
- };
290
- } catch (error) {
291
- return {
292
- content: [
293
- {
294
- type: "text",
295
- text: `Error: ${error instanceof Error ? error.message : "Failed to request market data"}`,
296
- uri: "marketDataRequest"
297
- }
298
- ],
299
- isError: true
300
- };
301
- }
302
- };
303
- };
304
- var createGetStockGraphHandler = (marketDataPrices) => {
305
- return async (args) => {
306
- try {
307
- const symbol = args.symbol;
308
- const priceHistory = marketDataPrices.get(symbol) || [];
309
- if (priceHistory.length === 0) {
310
- return {
311
- content: [
312
- {
313
- type: "text",
314
- text: `No price data available for ${symbol}`,
315
- uri: "getStockGraph"
316
- }
317
- ]
318
- };
319
- }
320
- const chart = new QuickChart();
321
- chart.setWidth(300);
322
- chart.setHeight(150);
323
- chart.setBackgroundColor("transparent");
324
- const labels = priceHistory.map((point) => new Date(point.timestamp).toLocaleTimeString());
325
- const bidData = priceHistory.map((point) => point.bid);
326
- const offerData = priceHistory.map((point) => point.offer);
327
- const spreadData = priceHistory.map((point) => point.spread);
328
- const volumeData = priceHistory.map((point) => point.volume);
329
- const config = {
330
- type: "line",
331
- data: {
332
- labels,
333
- datasets: [
334
- {
335
- label: "Bid",
336
- data: bidData,
337
- borderColor: "#28a745",
338
- backgroundColor: "rgba(40, 167, 69, 0.1)",
339
- fill: false,
340
- tension: 0.4
341
- },
342
- {
343
- label: "Offer",
344
- data: offerData,
345
- borderColor: "#dc3545",
346
- backgroundColor: "rgba(220, 53, 69, 0.1)",
347
- fill: false,
348
- tension: 0.4
349
- },
350
- {
351
- label: "Spread",
352
- data: spreadData,
353
- borderColor: "#6c757d",
354
- backgroundColor: "rgba(108, 117, 125, 0.1)",
355
- fill: false,
356
- tension: 0.4
357
- },
358
- {
359
- label: "Volume",
360
- data: volumeData,
361
- borderColor: "#007bff",
362
- backgroundColor: "rgba(0, 123, 255, 0.1)",
363
- fill: true,
364
- tension: 0.4
365
- }
366
- ]
367
- },
368
- options: {
369
- responsive: true,
370
- plugins: {
371
- title: {
372
- display: true,
373
- text: `${symbol} Market Data`
374
- }
375
- },
376
- scales: {
377
- y: {
378
- beginAtZero: false
379
- }
380
- }
381
- }
382
- };
383
- chart.setConfig(config);
384
- const imageBuffer = await chart.toBinary();
385
- const base64 = Buffer.from(imageBuffer).toString("base64");
386
- return {
387
- content: [
388
- {
389
- type: "resource",
390
- resource: {
391
- uri: "resource://graph",
392
- mimeType: "image/png",
393
- blob: base64
394
- }
395
- }
396
- ]
397
- };
398
- } catch (error) {
399
- return {
400
- content: [
401
- {
402
- type: "text",
403
- text: `Error: ${error instanceof Error ? error.message : "Failed to generate chart"}`,
404
- uri: "getStockGraph"
405
- }
406
- ],
407
- isError: true
408
- };
409
- }
410
- };
411
- };
412
- var createGetStockPriceHistoryHandler = (marketDataPrices) => {
413
- return async (args) => {
414
- try {
415
- const symbol = args.symbol;
416
- const priceHistory = marketDataPrices.get(symbol) || [];
417
- if (priceHistory.length === 0) {
418
- return {
419
- content: [
420
- {
421
- type: "text",
422
- text: `No price data available for ${symbol}`,
423
- uri: "getStockPriceHistory"
424
- }
425
- ]
426
- };
427
- }
428
- return {
429
- content: [
430
- {
431
- type: "text",
432
- text: JSON.stringify(
433
- {
434
- symbol,
435
- count: priceHistory.length,
436
- data: priceHistory.map((point) => ({
437
- timestamp: new Date(point.timestamp).toISOString(),
438
- bid: point.bid,
439
- offer: point.offer,
440
- spread: point.spread,
441
- volume: point.volume
442
- }))
443
- },
444
- null,
445
- 2
446
- ),
447
- uri: "getStockPriceHistory"
448
- }
449
- ]
450
- };
451
- } catch (error) {
452
- return {
453
- content: [
454
- {
455
- type: "text",
456
- text: `Error: ${error instanceof Error ? error.message : "Failed to get stock price history"}`,
457
- uri: "getStockPriceHistory"
458
- }
459
- ],
460
- isError: true
461
- };
462
- }
463
- };
464
- };
465
-
466
- // src/tools/order.ts
467
- import { Field as Field2, Fields as Fields2, Messages as Messages2 } from "fixparser";
468
- var ordTypeNames = {
469
- "1": "Market",
470
- "2": "Limit",
471
- "3": "Stop",
472
- "4": "StopLimit",
473
- "5": "MarketOnClose",
474
- "6": "WithOrWithout",
475
- "7": "LimitOrBetter",
476
- "8": "LimitWithOrWithout",
477
- "9": "OnBasis",
478
- A: "OnClose",
479
- B: "LimitOnClose",
480
- C: "ForexMarket",
481
- D: "PreviouslyQuoted",
482
- E: "PreviouslyIndicated",
483
- F: "ForexLimit",
484
- G: "ForexSwap",
485
- H: "ForexPreviouslyQuoted",
486
- I: "Funari",
487
- J: "MarketIfTouched",
488
- K: "MarketWithLeftOverAsLimit",
489
- L: "PreviousFundValuationPoint",
490
- M: "NextFundValuationPoint",
491
- P: "Pegged",
492
- Q: "CounterOrderSelection",
493
- R: "StopOnBidOrOffer",
494
- S: "StopLimitOnBidOrOffer"
495
- };
496
- var sideNames = {
497
- "1": "Buy",
498
- "2": "Sell",
499
- "3": "BuyMinus",
500
- "4": "SellPlus",
501
- "5": "SellShort",
502
- "6": "SellShortExempt",
503
- "7": "Undisclosed",
504
- "8": "Cross",
505
- "9": "CrossShort",
506
- A: "CrossShortExempt",
507
- B: "AsDefined",
508
- C: "Opposite",
509
- D: "Subscribe",
510
- E: "Redeem",
511
- F: "Lend",
512
- G: "Borrow",
513
- H: "SellUndisclosed"
514
- };
515
- var timeInForceNames = {
516
- "0": "Day",
517
- "1": "GoodTillCancel",
518
- "2": "AtTheOpening",
519
- "3": "ImmediateOrCancel",
520
- "4": "FillOrKill",
521
- "5": "GoodTillCrossing",
522
- "6": "GoodTillDate",
523
- "7": "AtTheClose",
524
- "8": "GoodThroughCrossing",
525
- "9": "AtCrossing",
526
- A: "GoodForTime",
527
- B: "GoodForAuction",
528
- C: "GoodForMonth"
529
- };
530
- var handlInstNames = {
531
- "1": "AutomatedExecutionNoIntervention",
532
- "2": "AutomatedExecutionInterventionOK",
533
- "3": "ManualOrder"
534
- };
535
- var createVerifyOrderHandler = (parser, verifiedOrders) => {
536
- return async (args) => {
537
- try {
538
- verifiedOrders.set(args.clOrdID, {
539
- clOrdID: args.clOrdID,
540
- handlInst: args.handlInst,
541
- quantity: Number.parseFloat(String(args.quantity)),
542
- price: Number.parseFloat(String(args.price)),
543
- ordType: args.ordType,
544
- side: args.side,
545
- symbol: args.symbol,
546
- timeInForce: args.timeInForce
547
- });
548
- return {
549
- content: [
550
- {
551
- type: "text",
552
- text: `VERIFICATION: All parameters valid. Ready to proceed with order execution.
553
-
554
- Parameters verified:
555
- - ClOrdID: ${args.clOrdID}
556
- - HandlInst: ${args.handlInst} (${handlInstNames[args.handlInst]})
557
- - Quantity: ${args.quantity}
558
- - Price: ${args.price}
559
- - OrdType: ${args.ordType} (${ordTypeNames[args.ordType]})
560
- - Side: ${args.side} (${sideNames[args.side]})
561
- - Symbol: ${args.symbol}
562
- - TimeInForce: ${args.timeInForce} (${timeInForceNames[args.timeInForce]})
563
-
564
- To execute this order, call the executeOrder tool with these exact same parameters.`,
565
- uri: "verifyOrder"
566
- }
567
- ]
568
- };
569
- } catch (error) {
570
- return {
571
- content: [
572
- {
573
- type: "text",
574
- text: `Error: ${error instanceof Error ? error.message : "Failed to verify order parameters"}`,
575
- uri: "verifyOrder"
576
- }
577
- ],
578
- isError: true
579
- };
580
- }
581
- };
582
- };
583
- var createExecuteOrderHandler = (parser, verifiedOrders, pendingRequests) => {
584
- return async (args) => {
585
- try {
586
- const verifiedOrder = verifiedOrders.get(args.clOrdID);
587
- if (!verifiedOrder) {
588
- return {
589
- content: [
590
- {
591
- type: "text",
592
- text: `Error: Order ${args.clOrdID} has not been verified. Please call verifyOrder first.`,
593
- uri: "executeOrder"
594
- }
595
- ],
596
- isError: true
597
- };
598
- }
599
- 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) {
600
- return {
601
- content: [
602
- {
603
- type: "text",
604
- text: "Error: Order parameters do not match the verified order. Please use the exact same parameters that were verified.",
605
- uri: "executeOrder"
606
- }
607
- ],
608
- isError: true
609
- };
610
- }
611
- const response = new Promise((resolve) => {
612
- pendingRequests.set(args.clOrdID, resolve);
613
- });
614
- const order = parser.createMessage(
615
- new Field2(Fields2.MsgType, Messages2.NewOrderSingle),
616
- new Field2(Fields2.MsgSeqNum, parser.getNextTargetMsgSeqNum()),
617
- new Field2(Fields2.SenderCompID, parser.sender),
618
- new Field2(Fields2.TargetCompID, parser.target),
619
- new Field2(Fields2.SendingTime, parser.getTimestamp()),
620
- new Field2(Fields2.ClOrdID, args.clOrdID),
621
- new Field2(Fields2.Side, args.side),
622
- new Field2(Fields2.Symbol, args.symbol),
623
- new Field2(Fields2.OrderQty, Number.parseFloat(String(args.quantity))),
624
- new Field2(Fields2.Price, Number.parseFloat(String(args.price))),
625
- new Field2(Fields2.OrdType, args.ordType),
626
- new Field2(Fields2.HandlInst, args.handlInst),
627
- new Field2(Fields2.TimeInForce, args.timeInForce),
628
- new Field2(Fields2.TransactTime, parser.getTimestamp())
629
- );
630
- if (!parser.connected) {
631
- return {
632
- content: [
633
- {
634
- type: "text",
635
- text: "Error: Not connected. Ignoring message.",
636
- uri: "executeOrder"
637
- }
638
- ],
639
- isError: true
640
- };
641
- }
642
- parser.send(order);
643
- const fixData = await response;
644
- verifiedOrders.delete(args.clOrdID);
645
- return {
646
- content: [
647
- {
648
- type: "text",
649
- 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())}`,
650
- uri: "executeOrder"
651
- }
652
- ]
653
- };
654
- } catch (error) {
655
- return {
656
- content: [
657
- {
658
- type: "text",
659
- text: `Error: ${error instanceof Error ? error.message : "Failed to execute order"}`,
660
- uri: "executeOrder"
661
- }
662
- ],
663
- isError: true
664
- };
665
- }
666
- };
667
- };
668
-
669
- // src/tools/parse.ts
670
- var createParseHandler = (parser) => {
671
- return async (args) => {
672
- try {
673
- const parsedMessage = parser.parse(args.fixString);
674
- if (!parsedMessage || parsedMessage.length === 0) {
675
- return {
676
- content: [
677
- {
678
- type: "text",
679
- text: "Error: Failed to parse FIX string",
680
- uri: "parse"
681
- }
682
- ],
683
- isError: true
684
- };
685
- }
686
- return {
687
- content: [
688
- {
689
- type: "text",
690
- text: `${parsedMessage[0].description}
691
- ${parsedMessage[0].messageTypeDescription}`,
692
- uri: "parse"
693
- }
694
- ]
695
- };
696
- } catch (error) {
697
- return {
698
- content: [
699
- {
700
- type: "text",
701
- text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`,
702
- uri: "parse"
703
- }
704
- ],
705
- isError: true
706
- };
707
- }
708
- };
709
- };
710
-
711
- // src/tools/parseToJSON.ts
712
- var createParseToJSONHandler = (parser) => {
713
- return async (args) => {
714
- try {
715
- const parsedMessage = parser.parse(args.fixString);
716
- if (!parsedMessage || parsedMessage.length === 0) {
717
- return {
718
- content: [
719
- {
720
- type: "text",
721
- text: "Error: Failed to parse FIX string",
722
- uri: "parseToJSON"
723
- }
724
- ],
725
- isError: true
726
- };
727
- }
728
- return {
729
- content: [
730
- {
731
- type: "text",
732
- text: `${parsedMessage[0].toFIXJSON()}`,
733
- uri: "parseToJSON"
734
- }
735
- ]
736
- };
737
- } catch (error) {
738
- return {
739
- content: [
740
- {
741
- type: "text",
742
- text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`,
743
- uri: "parseToJSON"
744
- }
745
- ],
746
- isError: true
747
- };
748
- }
749
- };
750
- };
751
-
752
- // src/tools/index.ts
753
- var createToolHandlers = (parser, verifiedOrders, pendingRequests, marketDataPrices) => ({
754
- parse: createParseHandler(parser),
755
- parseToJSON: createParseToJSONHandler(parser),
756
- verifyOrder: createVerifyOrderHandler(parser, verifiedOrders),
757
- executeOrder: createExecuteOrderHandler(parser, verifiedOrders, pendingRequests),
758
- marketDataRequest: createMarketDataRequestHandler(parser, pendingRequests),
759
- getStockGraph: createGetStockGraphHandler(marketDataPrices),
760
- getStockPriceHistory: createGetStockPriceHistoryHandler(marketDataPrices)
761
- });
762
-
763
- // src/MCPLocal.ts
764
235
  var MCPLocal = class {
765
236
  parser;
766
237
  server = new Server(
@@ -787,6 +258,7 @@ var MCPLocal = class {
787
258
  onReady = void 0;
788
259
  pendingRequests = /* @__PURE__ */ new Map();
789
260
  verifiedOrders = /* @__PURE__ */ new Map();
261
+ // Store market data prices with timestamps
790
262
  marketDataPrices = /* @__PURE__ */ new Map();
791
263
  MAX_PRICE_HISTORY = 1e5;
792
264
  // Maximum number of price points to store per symbol
@@ -801,63 +273,50 @@ var MCPLocal = class {
801
273
  message: `MCP Server received message: ${message.messageType}: ${message.description}`
802
274
  });
803
275
  const msgType = message.messageType;
804
- if (msgType === Messages3.MarketDataSnapshotFullRefresh || msgType === Messages3.ExecutionReport || msgType === Messages3.Reject || msgType === Messages3.MarketDataIncrementalRefresh) {
276
+ if (msgType === Messages.MarketDataSnapshotFullRefresh || msgType === Messages.ExecutionReport || msgType === Messages.Reject || msgType === Messages.MarketDataIncrementalRefresh) {
805
277
  this.parser?.logger.log({
806
278
  level: "info",
807
279
  message: `MCP Server handling message type: ${msgType}`
808
280
  });
809
281
  let id;
810
- if (msgType === Messages3.MarketDataIncrementalRefresh || msgType === Messages3.MarketDataSnapshotFullRefresh) {
811
- const symbol = message.getField(Fields3.Symbol);
812
- const entryType = message.getField(Fields3.MDEntryType);
813
- const price = message.getField(Fields3.MDEntryPx);
814
- const size = message.getField(Fields3.MDEntrySize);
815
- const timestamp = message.getField(Fields3.MDEntryTime)?.value || Date.now();
282
+ if (msgType === Messages.MarketDataIncrementalRefresh || msgType === Messages.MarketDataSnapshotFullRefresh) {
283
+ const symbol = message.getField(Fields.Symbol);
284
+ const price = message.getField(Fields.MDEntryPx);
285
+ const timestamp = message.getField(Fields.MDEntryTime)?.value || Date.now();
816
286
  if (symbol?.value && price?.value) {
817
287
  const symbolStr = String(symbol.value);
818
288
  const priceNum = Number(price.value);
819
- const sizeNum = size?.value ? Number(size.value) : 0;
820
289
  const priceHistory = this.marketDataPrices.get(symbolStr) || [];
821
- const lastEntry = priceHistory[priceHistory.length - 1] || {
822
- timestamp: 0,
823
- bid: 0,
824
- offer: 0,
825
- spread: 0,
826
- volume: 0
827
- };
828
- const newEntry = {
290
+ priceHistory.push({
829
291
  timestamp: Number(timestamp),
830
- bid: entryType?.value === MDEntryType2.Bid ? priceNum : lastEntry.bid,
831
- offer: entryType?.value === MDEntryType2.Offer ? priceNum : lastEntry.offer,
832
- spread: entryType?.value === MDEntryType2.Offer ? priceNum - lastEntry.bid : entryType?.value === MDEntryType2.Bid ? lastEntry.offer - priceNum : lastEntry.spread,
833
- volume: entryType?.value === MDEntryType2.TradeVolume ? sizeNum : lastEntry.volume
834
- };
835
- priceHistory.push(newEntry);
292
+ price: priceNum
293
+ });
836
294
  if (priceHistory.length > this.MAX_PRICE_HISTORY) {
837
295
  priceHistory.shift();
838
296
  }
839
297
  this.marketDataPrices.set(symbolStr, priceHistory);
840
298
  this.parser?.logger.log({
841
299
  level: "info",
842
- message: `MCP Server added ${symbol}: ${JSON.stringify(newEntry)}`
300
+ message: `MCP Server added ${symbol}: ${priceNum}`
843
301
  });
844
302
  this.server.notification({
845
303
  method: "priceUpdate",
846
304
  params: {
847
305
  symbol: symbolStr,
848
- ...newEntry
306
+ price: priceNum,
307
+ timestamp: Number(timestamp)
849
308
  }
850
309
  });
851
310
  }
852
311
  }
853
- if (msgType === Messages3.MarketDataSnapshotFullRefresh) {
854
- const mdReqID = message.getField(Fields3.MDReqID);
312
+ if (msgType === Messages.MarketDataSnapshotFullRefresh) {
313
+ const mdReqID = message.getField(Fields.MDReqID);
855
314
  if (mdReqID) id = String(mdReqID.value);
856
- } else if (msgType === Messages3.ExecutionReport) {
857
- const clOrdID = message.getField(Fields3.ClOrdID);
315
+ } else if (msgType === Messages.ExecutionReport) {
316
+ const clOrdID = message.getField(Fields.ClOrdID);
858
317
  if (clOrdID) id = String(clOrdID.value);
859
- } else if (msgType === Messages3.Reject) {
860
- const refSeqNum = message.getField(Fields3.RefSeqNum);
318
+ } else if (msgType === Messages.Reject) {
319
+ const refSeqNum = message.getField(Fields.RefSeqNum);
861
320
  if (refSeqNum) id = String(refSeqNum.value);
862
321
  }
863
322
  if (id) {
@@ -907,30 +366,492 @@ var MCPLocal = class {
907
366
  }),
908
367
  async (request, extra) => {
909
368
  const { name, arguments: args } = request.params;
910
- const toolHandlers = createToolHandlers(
911
- this.parser,
912
- this.verifiedOrders,
913
- this.pendingRequests,
914
- this.marketDataPrices
915
- );
916
- const handler = toolHandlers[name];
917
- if (!handler) {
918
- return {
919
- content: [
920
- {
921
- type: "text",
922
- text: `Tool not found: ${name}`,
923
- uri: name
369
+ switch (name) {
370
+ case "parse":
371
+ try {
372
+ const parsedMessage = this.parser?.parse(args.fixString);
373
+ if (!parsedMessage || parsedMessage.length === 0) {
374
+ return {
375
+ content: [
376
+ {
377
+ type: "text",
378
+ text: "Error: Failed to parse FIX string",
379
+ uri: "parse"
380
+ }
381
+ ],
382
+ isError: true
383
+ };
924
384
  }
925
- ],
926
- isError: true
927
- };
385
+ return {
386
+ content: [
387
+ {
388
+ type: "text",
389
+ text: `${parsedMessage[0].description}
390
+ ${parsedMessage[0].messageTypeDescription}`,
391
+ uri: "parse"
392
+ }
393
+ ]
394
+ };
395
+ } catch (error) {
396
+ return {
397
+ content: [
398
+ {
399
+ type: "text",
400
+ text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`,
401
+ uri: "parse"
402
+ }
403
+ ],
404
+ isError: true
405
+ };
406
+ }
407
+ case "parseToJSON":
408
+ try {
409
+ const parsedMessage = this.parser?.parse(args.fixString);
410
+ if (!parsedMessage || parsedMessage.length === 0) {
411
+ return {
412
+ content: [
413
+ {
414
+ type: "text",
415
+ text: "Error: Failed to parse FIX string",
416
+ uri: "parseToJSON"
417
+ }
418
+ ],
419
+ isError: true
420
+ };
421
+ }
422
+ return {
423
+ content: [
424
+ {
425
+ type: "text",
426
+ text: `${parsedMessage[0].toFIXJSON()}`,
427
+ uri: "parseToJSON"
428
+ }
429
+ ]
430
+ };
431
+ } catch (error) {
432
+ return {
433
+ content: [
434
+ {
435
+ type: "text",
436
+ text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`,
437
+ uri: "parseToJSON"
438
+ }
439
+ ],
440
+ isError: true
441
+ };
442
+ }
443
+ case "verifyOrder":
444
+ try {
445
+ this.verifiedOrders.set(args.clOrdID, {
446
+ clOrdID: args.clOrdID,
447
+ handlInst: args.handlInst,
448
+ quantity: Number.parseFloat(args.quantity),
449
+ price: Number.parseFloat(args.price),
450
+ ordType: args.ordType,
451
+ side: args.side,
452
+ symbol: args.symbol,
453
+ timeInForce: args.timeInForce
454
+ });
455
+ const ordTypeNames = {
456
+ "1": "Market",
457
+ "2": "Limit",
458
+ "3": "Stop",
459
+ "4": "StopLimit",
460
+ "5": "MarketOnClose",
461
+ "6": "WithOrWithout",
462
+ "7": "LimitOrBetter",
463
+ "8": "LimitWithOrWithout",
464
+ "9": "OnBasis",
465
+ A: "OnClose",
466
+ B: "LimitOnClose",
467
+ C: "ForexMarket",
468
+ D: "PreviouslyQuoted",
469
+ E: "PreviouslyIndicated",
470
+ F: "ForexLimit",
471
+ G: "ForexSwap",
472
+ H: "ForexPreviouslyQuoted",
473
+ I: "Funari",
474
+ J: "MarketIfTouched",
475
+ K: "MarketWithLeftOverAsLimit",
476
+ L: "PreviousFundValuationPoint",
477
+ M: "NextFundValuationPoint",
478
+ P: "Pegged",
479
+ Q: "CounterOrderSelection",
480
+ R: "StopOnBidOrOffer",
481
+ S: "StopLimitOnBidOrOffer"
482
+ };
483
+ const sideNames = {
484
+ "1": "Buy",
485
+ "2": "Sell",
486
+ "3": "BuyMinus",
487
+ "4": "SellPlus",
488
+ "5": "SellShort",
489
+ "6": "SellShortExempt",
490
+ "7": "Undisclosed",
491
+ "8": "Cross",
492
+ "9": "CrossShort",
493
+ A: "CrossShortExempt",
494
+ B: "AsDefined",
495
+ C: "Opposite",
496
+ D: "Subscribe",
497
+ E: "Redeem",
498
+ F: "Lend",
499
+ G: "Borrow",
500
+ H: "SellUndisclosed"
501
+ };
502
+ const timeInForceNames = {
503
+ "0": "Day",
504
+ "1": "GoodTillCancel",
505
+ "2": "AtTheOpening",
506
+ "3": "ImmediateOrCancel",
507
+ "4": "FillOrKill",
508
+ "5": "GoodTillCrossing",
509
+ "6": "GoodTillDate",
510
+ "7": "AtTheClose",
511
+ "8": "GoodThroughCrossing",
512
+ "9": "AtCrossing",
513
+ A: "GoodForTime",
514
+ B: "GoodForAuction",
515
+ C: "GoodForMonth"
516
+ };
517
+ const handlInstNames = {
518
+ "1": "AutomatedExecutionNoIntervention",
519
+ "2": "AutomatedExecutionInterventionOK",
520
+ "3": "ManualOrder"
521
+ };
522
+ return {
523
+ content: [
524
+ {
525
+ type: "text",
526
+ text: `VERIFICATION: All parameters valid. Ready to proceed with order execution.
527
+
528
+ Parameters verified:
529
+ - ClOrdID: ${args.clOrdID}
530
+ - HandlInst: ${args.handlInst} (${handlInstNames[args.handlInst]})
531
+ - Quantity: ${args.quantity}
532
+ - Price: ${args.price}
533
+ - OrdType: ${args.ordType} (${ordTypeNames[args.ordType]})
534
+ - Side: ${args.side} (${sideNames[args.side]})
535
+ - Symbol: ${args.symbol}
536
+ - TimeInForce: ${args.timeInForce} (${timeInForceNames[args.timeInForce]})
537
+
538
+ To execute this order, call the executeOrder tool with these exact same parameters.`,
539
+ uri: "verifyOrder"
540
+ }
541
+ ]
542
+ };
543
+ } catch (error) {
544
+ return {
545
+ content: [
546
+ {
547
+ type: "text",
548
+ text: `Error: ${error instanceof Error ? error.message : "Failed to verify order parameters"}`,
549
+ uri: "verifyOrder"
550
+ }
551
+ ],
552
+ isError: true
553
+ };
554
+ }
555
+ case "executeOrder":
556
+ try {
557
+ const verifiedOrder = this.verifiedOrders.get(args.clOrdID);
558
+ if (!verifiedOrder) {
559
+ return {
560
+ content: [
561
+ {
562
+ type: "text",
563
+ text: `Error: Order ${args.clOrdID} has not been verified. Please call verifyOrder first.`,
564
+ uri: "executeOrder"
565
+ }
566
+ ],
567
+ isError: true
568
+ };
569
+ }
570
+ 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) {
571
+ return {
572
+ content: [
573
+ {
574
+ type: "text",
575
+ text: "Error: Order parameters do not match the verified order. Please use the exact same parameters that were verified.",
576
+ uri: "executeOrder"
577
+ }
578
+ ],
579
+ isError: true
580
+ };
581
+ }
582
+ const response = new Promise((resolve) => {
583
+ this.pendingRequests.set(args.clOrdID, resolve);
584
+ });
585
+ const order = this.parser?.createMessage(
586
+ new Field(Fields.MsgType, Messages.NewOrderSingle),
587
+ new Field(Fields.MsgSeqNum, this.parser?.getNextTargetMsgSeqNum()),
588
+ new Field(Fields.SenderCompID, this.parser?.sender),
589
+ new Field(Fields.TargetCompID, this.parser?.target),
590
+ new Field(Fields.SendingTime, this.parser?.getTimestamp()),
591
+ new Field(Fields.ClOrdID, args.clOrdID),
592
+ new Field(Fields.Side, args.side),
593
+ new Field(Fields.Symbol, args.symbol),
594
+ new Field(Fields.OrderQty, Number.parseFloat(args.quantity)),
595
+ new Field(Fields.Price, Number.parseFloat(args.price)),
596
+ new Field(Fields.OrdType, args.ordType),
597
+ new Field(Fields.HandlInst, args.handlInst),
598
+ new Field(Fields.TimeInForce, args.timeInForce),
599
+ new Field(Fields.TransactTime, this.parser?.getTimestamp())
600
+ );
601
+ if (!this.parser?.connected) {
602
+ return {
603
+ content: [
604
+ {
605
+ type: "text",
606
+ text: "Error: Not connected. Ignoring message.",
607
+ uri: "executeOrder"
608
+ }
609
+ ],
610
+ isError: true
611
+ };
612
+ }
613
+ this.parser?.send(order);
614
+ const fixData = await response;
615
+ this.verifiedOrders.delete(args.clOrdID);
616
+ return {
617
+ content: [
618
+ {
619
+ type: "text",
620
+ text: fixData.messageType === Messages.Reject ? `Reject message for order ${args.clOrdID}: ${JSON.stringify(fixData.toFIXJSON())}` : `Execution Report for order ${args.clOrdID}: ${JSON.stringify(fixData.toFIXJSON())}`,
621
+ uri: "executeOrder"
622
+ }
623
+ ]
624
+ };
625
+ } catch (error) {
626
+ return {
627
+ content: [
628
+ {
629
+ type: "text",
630
+ text: `Error: ${error instanceof Error ? error.message : "Failed to execute order"}`,
631
+ uri: "executeOrder"
632
+ }
633
+ ],
634
+ isError: true
635
+ };
636
+ }
637
+ case "marketDataRequest":
638
+ try {
639
+ const response = new Promise((resolve) => {
640
+ this.pendingRequests.set(args.mdReqID, resolve);
641
+ });
642
+ const messageFields = [
643
+ new Field(Fields.MsgType, Messages.MarketDataRequest),
644
+ new Field(Fields.SenderCompID, this.parser?.sender),
645
+ new Field(Fields.MsgSeqNum, this.parser?.getNextTargetMsgSeqNum()),
646
+ new Field(Fields.TargetCompID, this.parser?.target),
647
+ new Field(Fields.SendingTime, this.parser?.getTimestamp()),
648
+ new Field(Fields.MDReqID, args.mdReqID),
649
+ new Field(Fields.SubscriptionRequestType, args.subscriptionRequestType),
650
+ new Field(Fields.MarketDepth, 0),
651
+ new Field(Fields.MDUpdateType, args.mdUpdateType)
652
+ ];
653
+ messageFields.push(new Field(Fields.NoRelatedSym, args.symbols.length));
654
+ args.symbols.forEach((symbol) => {
655
+ messageFields.push(new Field(Fields.Symbol, symbol));
656
+ });
657
+ messageFields.push(new Field(Fields.NoMDEntryTypes, args.mdEntryTypes.length));
658
+ args.mdEntryTypes.forEach((entryType) => {
659
+ messageFields.push(new Field(Fields.MDEntryType, entryType));
660
+ });
661
+ const mdr = this.parser?.createMessage(...messageFields);
662
+ if (!this.parser?.connected) {
663
+ return {
664
+ content: [
665
+ {
666
+ type: "text",
667
+ text: "Error: Not connected. Ignoring message.",
668
+ uri: "marketDataRequest"
669
+ }
670
+ ],
671
+ isError: true
672
+ };
673
+ }
674
+ this.parser?.send(mdr);
675
+ const fixData = await response;
676
+ return {
677
+ content: [
678
+ {
679
+ type: "text",
680
+ text: `Market data for ${args.symbols.join(", ")}: ${JSON.stringify(fixData.toFIXJSON())}`,
681
+ uri: "marketDataRequest"
682
+ }
683
+ ]
684
+ };
685
+ } catch (error) {
686
+ return {
687
+ content: [
688
+ {
689
+ type: "text",
690
+ text: `Error: ${error instanceof Error ? error.message : "Failed to request market data"}`,
691
+ uri: "marketDataRequest"
692
+ }
693
+ ],
694
+ isError: true
695
+ };
696
+ }
697
+ case "getStockGraph":
698
+ try {
699
+ const symbol = args.symbol;
700
+ const priceHistory = this.marketDataPrices.get(symbol) || [];
701
+ if (priceHistory.length === 0) {
702
+ return {
703
+ content: [
704
+ {
705
+ type: "text",
706
+ text: `No price data available for ${symbol}`,
707
+ uri: "getStockGraph"
708
+ }
709
+ ]
710
+ };
711
+ }
712
+ const width = 600;
713
+ const height = 300;
714
+ const padding = 40;
715
+ const xScale = (width - 2 * padding) / (priceHistory.length - 1);
716
+ const yMin = Math.min(...priceHistory.map((d) => d.price));
717
+ const yMax = Math.max(...priceHistory.map((d) => d.price));
718
+ const yScale = (height - 2 * padding) / (yMax - yMin);
719
+ const points = priceHistory.map((d, i) => {
720
+ const x = padding + i * xScale;
721
+ const y = height - padding - (d.price - yMin) * yScale;
722
+ return `${x},${y}`;
723
+ }).join(" L ");
724
+ const svg = `<?xml version="1.0" encoding="UTF-8"?>
725
+ <svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">
726
+ <!-- Background -->
727
+ <rect width="100%" height="100%" fill="#f8f9fa"/>
728
+
729
+ <!-- Grid lines -->
730
+ <g stroke="#e9ecef" stroke-width="1">
731
+ ${Array.from({ length: 5 }, (_, i) => {
732
+ const y = padding + (height - 2 * padding) * i / 4;
733
+ return `<line x1="${padding}" y1="${y}" x2="${width - padding}" y2="${y}"/>`;
734
+ }).join("\n")}
735
+ </g>
736
+
737
+ <!-- Price line -->
738
+ <path d="M ${points}"
739
+ fill="none"
740
+ stroke="#007bff"
741
+ stroke-width="2"/>
742
+
743
+ <!-- Data points -->
744
+ ${priceHistory.map((d, i) => {
745
+ const x = padding + i * xScale;
746
+ const y = height - padding - (d.price - yMin) * yScale;
747
+ return `<circle cx="${x}" cy="${y}" r="3" fill="#007bff"/>`;
748
+ }).join("\n")}
749
+
750
+ <!-- Labels -->
751
+ <g font-family="Arial" font-size="12" fill="#495057">
752
+ ${Array.from({ length: 5 }, (_, i) => {
753
+ const x = padding + (width - 2 * padding) * i / 4;
754
+ const index = Math.floor((priceHistory.length - 1) * i / 4);
755
+ const timestamp = new Date(priceHistory[index].timestamp).toLocaleTimeString();
756
+ return `<text x="${x + padding}" y="${height - padding + 20}" text-anchor="middle">${timestamp}</text>`;
757
+ }).join("\n")}
758
+ ${Array.from({ length: 5 }, (_, i) => {
759
+ const y = padding + (height - 2 * padding) * i / 4;
760
+ const price = yMax - (yMax - yMin) * i / 4;
761
+ return `<text x="${padding - 5}" y="${y + 4}" text-anchor="end">$${price.toFixed(2)}</text>`;
762
+ }).join("\n")}
763
+ </g>
764
+
765
+ <!-- Title -->
766
+ <text x="${width / 2}" y="${padding / 2}"
767
+ font-family="Arial" font-size="16" font-weight="bold"
768
+ text-anchor="middle" fill="#212529">
769
+ ${symbol} - Price Chart (${priceHistory.length} points)
770
+ </text>
771
+ </svg>`;
772
+ const pngBuffer = await sharp(Buffer.from(svg)).png().toBuffer();
773
+ const base64Png = pngBuffer.toString("base64");
774
+ return {
775
+ content: [
776
+ {
777
+ type: "image",
778
+ text: base64Png,
779
+ uri: "getStockGraph",
780
+ mimeType: "image/png"
781
+ }
782
+ ]
783
+ };
784
+ } catch (error) {
785
+ return {
786
+ content: [
787
+ {
788
+ type: "text",
789
+ text: `Error: ${error instanceof Error ? error.message : "Failed to generate stock graph"}`,
790
+ uri: "getStockGraph"
791
+ }
792
+ ],
793
+ isError: true
794
+ };
795
+ }
796
+ case "getStockPriceHistory":
797
+ try {
798
+ const symbol = args.symbol;
799
+ const priceHistory = this.marketDataPrices.get(symbol) || [];
800
+ if (priceHistory.length === 0) {
801
+ return {
802
+ content: [
803
+ {
804
+ type: "text",
805
+ text: `No price data available for ${symbol}`,
806
+ uri: "getStockPriceHistory"
807
+ }
808
+ ]
809
+ };
810
+ }
811
+ return {
812
+ content: [
813
+ {
814
+ type: "text",
815
+ text: JSON.stringify(
816
+ {
817
+ symbol,
818
+ count: priceHistory.length,
819
+ prices: priceHistory.map((point) => ({
820
+ timestamp: new Date(point.timestamp).toISOString(),
821
+ price: point.price
822
+ }))
823
+ },
824
+ null,
825
+ 2
826
+ ),
827
+ uri: "getStockPriceHistory"
828
+ }
829
+ ]
830
+ };
831
+ } catch (error) {
832
+ return {
833
+ content: [
834
+ {
835
+ type: "text",
836
+ text: `Error: ${error instanceof Error ? error.message : "Failed to get stock price history"}`,
837
+ uri: "getStockPriceHistory"
838
+ }
839
+ ],
840
+ isError: true
841
+ };
842
+ }
843
+ default:
844
+ return {
845
+ content: [
846
+ {
847
+ type: "text",
848
+ text: `Tool not found: ${name}`,
849
+ uri: name
850
+ }
851
+ ],
852
+ isError: true
853
+ };
928
854
  }
929
- const result = await handler(args);
930
- return {
931
- content: result.content,
932
- isError: result.isError
933
- };
934
855
  }
935
856
  );
936
857
  process.on("SIGINT", async () => {