fixparser-plugin-mcp 9.1.7-14636c8f → 9.1.7-1736d80f

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