fixparser-plugin-mcp 9.1.7-e80c38c2 → 9.1.7-eb1de32a

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,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";
5
- import sharp from "sharp";
4
+ import { Fields as Fields3, Messages as Messages3 } from "fixparser";
6
5
  import { z } from "zod";
6
+
7
+ // src/schemas/schemas.ts
7
8
  var toolSchemas = {
8
9
  parse: {
9
10
  description: "Parses a FIX message and describes it in plain language",
@@ -232,6 +233,516 @@ var toolSchemas = {
232
233
  }
233
234
  }
234
235
  };
236
+
237
+ // src/tools/marketData.ts
238
+ import { Field, Fields, 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 messageFields = [
247
+ new Field(Fields.MsgType, Messages.MarketDataRequest),
248
+ new Field(Fields.SenderCompID, parser.sender),
249
+ new Field(Fields.MsgSeqNum, parser.getNextTargetMsgSeqNum()),
250
+ new Field(Fields.TargetCompID, parser.target),
251
+ new Field(Fields.SendingTime, parser.getTimestamp()),
252
+ new Field(Fields.MDReqID, args.mdReqID),
253
+ new Field(Fields.SubscriptionRequestType, args.subscriptionRequestType),
254
+ new Field(Fields.MarketDepth, 0),
255
+ new Field(Fields.MDUpdateType, args.mdUpdateType)
256
+ ];
257
+ messageFields.push(new Field(Fields.NoRelatedSym, args.symbols.length));
258
+ args.symbols.forEach((symbol) => {
259
+ messageFields.push(new Field(Fields.Symbol, symbol));
260
+ });
261
+ messageFields.push(new Field(Fields.NoMDEntryTypes, args.mdEntryTypes.length));
262
+ args.mdEntryTypes.forEach((entryType) => {
263
+ messageFields.push(new Field(Fields.MDEntryType, entryType));
264
+ });
265
+ const mdr = parser.createMessage(...messageFields);
266
+ if (!parser.connected) {
267
+ return {
268
+ content: [
269
+ {
270
+ type: "text",
271
+ text: "Error: Not connected. Ignoring message.",
272
+ uri: "marketDataRequest"
273
+ }
274
+ ],
275
+ isError: true
276
+ };
277
+ }
278
+ parser.send(mdr);
279
+ const fixData = await response;
280
+ return {
281
+ content: [
282
+ {
283
+ type: "text",
284
+ text: `Market data for ${args.symbols.join(", ")}: ${JSON.stringify(fixData.toFIXJSON())}`,
285
+ uri: "marketDataRequest"
286
+ }
287
+ ]
288
+ };
289
+ } catch (error) {
290
+ return {
291
+ content: [
292
+ {
293
+ type: "text",
294
+ text: `Error: ${error instanceof Error ? error.message : "Failed to request market data"}`,
295
+ uri: "marketDataRequest"
296
+ }
297
+ ],
298
+ isError: true
299
+ };
300
+ }
301
+ };
302
+ };
303
+ var createGetStockGraphHandler = (marketDataPrices) => {
304
+ return async (args) => {
305
+ try {
306
+ const symbol = args.symbol;
307
+ const priceHistory = marketDataPrices.get(symbol) || [];
308
+ if (priceHistory.length === 0) {
309
+ return {
310
+ content: [
311
+ {
312
+ type: "text",
313
+ text: `No price data available for ${symbol}`,
314
+ uri: "getStockGraph"
315
+ }
316
+ ]
317
+ };
318
+ }
319
+ const chart = new QuickChart();
320
+ chart.setWidth(600);
321
+ chart.setHeight(300);
322
+ const labels = priceHistory.map((point) => new Date(point.timestamp).toLocaleTimeString());
323
+ const data = priceHistory.map((point) => point.price);
324
+ chart.setConfig({
325
+ type: "line",
326
+ data: {
327
+ labels,
328
+ datasets: [
329
+ {
330
+ label: symbol,
331
+ data,
332
+ borderColor: "#007bff",
333
+ backgroundColor: "rgba(0, 123, 255, 0.1)",
334
+ fill: true,
335
+ tension: 0.4
336
+ }
337
+ ]
338
+ },
339
+ options: {
340
+ plugins: {
341
+ title: {
342
+ display: true,
343
+ text: `${symbol} Price History`,
344
+ font: {
345
+ size: 16,
346
+ weight: "bold"
347
+ }
348
+ },
349
+ legend: {
350
+ display: true
351
+ }
352
+ },
353
+ scales: {
354
+ y: {
355
+ beginAtZero: false,
356
+ grid: {
357
+ color: "#e9ecef"
358
+ }
359
+ },
360
+ x: {
361
+ grid: {
362
+ display: false
363
+ }
364
+ }
365
+ }
366
+ }
367
+ });
368
+ const imageBuffer = await chart.toBinary();
369
+ const base64Image = imageBuffer.toString("base64");
370
+ return {
371
+ content: [
372
+ {
373
+ type: "image",
374
+ text: base64Image,
375
+ source: {
376
+ data: base64Image
377
+ },
378
+ uri: "getStockGraph",
379
+ mimeType: "image/png"
380
+ }
381
+ ]
382
+ };
383
+ } catch (error) {
384
+ return {
385
+ content: [
386
+ {
387
+ type: "text",
388
+ text: `Error: ${error instanceof Error ? error.message : "Failed to generate stock graph"}`,
389
+ uri: "getStockGraph"
390
+ }
391
+ ],
392
+ isError: true
393
+ };
394
+ }
395
+ };
396
+ };
397
+ var createGetStockPriceHistoryHandler = (marketDataPrices) => {
398
+ return async (args) => {
399
+ try {
400
+ const symbol = args.symbol;
401
+ const priceHistory = marketDataPrices.get(symbol) || [];
402
+ if (priceHistory.length === 0) {
403
+ return {
404
+ content: [
405
+ {
406
+ type: "text",
407
+ text: `No price data available for ${symbol}`,
408
+ uri: "getStockPriceHistory"
409
+ }
410
+ ]
411
+ };
412
+ }
413
+ return {
414
+ content: [
415
+ {
416
+ type: "text",
417
+ text: JSON.stringify(
418
+ {
419
+ symbol,
420
+ count: priceHistory.length,
421
+ prices: priceHistory.map((point) => ({
422
+ timestamp: new Date(point.timestamp).toISOString(),
423
+ price: point.price
424
+ }))
425
+ },
426
+ null,
427
+ 2
428
+ ),
429
+ uri: "getStockPriceHistory"
430
+ }
431
+ ]
432
+ };
433
+ } catch (error) {
434
+ return {
435
+ content: [
436
+ {
437
+ type: "text",
438
+ text: `Error: ${error instanceof Error ? error.message : "Failed to get stock price history"}`,
439
+ uri: "getStockPriceHistory"
440
+ }
441
+ ],
442
+ isError: true
443
+ };
444
+ }
445
+ };
446
+ };
447
+
448
+ // src/tools/order.ts
449
+ import { Field as Field2, Fields as Fields2, Messages as Messages2 } from "fixparser";
450
+ var ordTypeNames = {
451
+ "1": "Market",
452
+ "2": "Limit",
453
+ "3": "Stop",
454
+ "4": "StopLimit",
455
+ "5": "MarketOnClose",
456
+ "6": "WithOrWithout",
457
+ "7": "LimitOrBetter",
458
+ "8": "LimitWithOrWithout",
459
+ "9": "OnBasis",
460
+ A: "OnClose",
461
+ B: "LimitOnClose",
462
+ C: "ForexMarket",
463
+ D: "PreviouslyQuoted",
464
+ E: "PreviouslyIndicated",
465
+ F: "ForexLimit",
466
+ G: "ForexSwap",
467
+ H: "ForexPreviouslyQuoted",
468
+ I: "Funari",
469
+ J: "MarketIfTouched",
470
+ K: "MarketWithLeftOverAsLimit",
471
+ L: "PreviousFundValuationPoint",
472
+ M: "NextFundValuationPoint",
473
+ P: "Pegged",
474
+ Q: "CounterOrderSelection",
475
+ R: "StopOnBidOrOffer",
476
+ S: "StopLimitOnBidOrOffer"
477
+ };
478
+ var sideNames = {
479
+ "1": "Buy",
480
+ "2": "Sell",
481
+ "3": "BuyMinus",
482
+ "4": "SellPlus",
483
+ "5": "SellShort",
484
+ "6": "SellShortExempt",
485
+ "7": "Undisclosed",
486
+ "8": "Cross",
487
+ "9": "CrossShort",
488
+ A: "CrossShortExempt",
489
+ B: "AsDefined",
490
+ C: "Opposite",
491
+ D: "Subscribe",
492
+ E: "Redeem",
493
+ F: "Lend",
494
+ G: "Borrow",
495
+ H: "SellUndisclosed"
496
+ };
497
+ var timeInForceNames = {
498
+ "0": "Day",
499
+ "1": "GoodTillCancel",
500
+ "2": "AtTheOpening",
501
+ "3": "ImmediateOrCancel",
502
+ "4": "FillOrKill",
503
+ "5": "GoodTillCrossing",
504
+ "6": "GoodTillDate",
505
+ "7": "AtTheClose",
506
+ "8": "GoodThroughCrossing",
507
+ "9": "AtCrossing",
508
+ A: "GoodForTime",
509
+ B: "GoodForAuction",
510
+ C: "GoodForMonth"
511
+ };
512
+ var handlInstNames = {
513
+ "1": "AutomatedExecutionNoIntervention",
514
+ "2": "AutomatedExecutionInterventionOK",
515
+ "3": "ManualOrder"
516
+ };
517
+ var createVerifyOrderHandler = (parser, verifiedOrders) => {
518
+ return async (args) => {
519
+ try {
520
+ verifiedOrders.set(args.clOrdID, {
521
+ clOrdID: args.clOrdID,
522
+ handlInst: args.handlInst,
523
+ quantity: Number.parseFloat(String(args.quantity)),
524
+ price: Number.parseFloat(String(args.price)),
525
+ ordType: args.ordType,
526
+ side: args.side,
527
+ symbol: args.symbol,
528
+ timeInForce: args.timeInForce
529
+ });
530
+ return {
531
+ content: [
532
+ {
533
+ type: "text",
534
+ text: `VERIFICATION: All parameters valid. Ready to proceed with order execution.
535
+
536
+ Parameters verified:
537
+ - ClOrdID: ${args.clOrdID}
538
+ - HandlInst: ${args.handlInst} (${handlInstNames[args.handlInst]})
539
+ - Quantity: ${args.quantity}
540
+ - Price: ${args.price}
541
+ - OrdType: ${args.ordType} (${ordTypeNames[args.ordType]})
542
+ - Side: ${args.side} (${sideNames[args.side]})
543
+ - Symbol: ${args.symbol}
544
+ - TimeInForce: ${args.timeInForce} (${timeInForceNames[args.timeInForce]})
545
+
546
+ To execute this order, call the executeOrder tool with these exact same parameters.`,
547
+ uri: "verifyOrder"
548
+ }
549
+ ]
550
+ };
551
+ } catch (error) {
552
+ return {
553
+ content: [
554
+ {
555
+ type: "text",
556
+ text: `Error: ${error instanceof Error ? error.message : "Failed to verify order parameters"}`,
557
+ uri: "verifyOrder"
558
+ }
559
+ ],
560
+ isError: true
561
+ };
562
+ }
563
+ };
564
+ };
565
+ var createExecuteOrderHandler = (parser, verifiedOrders, pendingRequests) => {
566
+ return async (args) => {
567
+ try {
568
+ const verifiedOrder = verifiedOrders.get(args.clOrdID);
569
+ if (!verifiedOrder) {
570
+ return {
571
+ content: [
572
+ {
573
+ type: "text",
574
+ text: `Error: Order ${args.clOrdID} has not been verified. Please call verifyOrder first.`,
575
+ uri: "executeOrder"
576
+ }
577
+ ],
578
+ isError: true
579
+ };
580
+ }
581
+ 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) {
582
+ return {
583
+ content: [
584
+ {
585
+ type: "text",
586
+ text: "Error: Order parameters do not match the verified order. Please use the exact same parameters that were verified.",
587
+ uri: "executeOrder"
588
+ }
589
+ ],
590
+ isError: true
591
+ };
592
+ }
593
+ const response = new Promise((resolve) => {
594
+ pendingRequests.set(args.clOrdID, resolve);
595
+ });
596
+ const order = parser.createMessage(
597
+ new Field2(Fields2.MsgType, Messages2.NewOrderSingle),
598
+ new Field2(Fields2.MsgSeqNum, parser.getNextTargetMsgSeqNum()),
599
+ new Field2(Fields2.SenderCompID, parser.sender),
600
+ new Field2(Fields2.TargetCompID, parser.target),
601
+ new Field2(Fields2.SendingTime, parser.getTimestamp()),
602
+ new Field2(Fields2.ClOrdID, args.clOrdID),
603
+ new Field2(Fields2.Side, args.side),
604
+ new Field2(Fields2.Symbol, args.symbol),
605
+ new Field2(Fields2.OrderQty, Number.parseFloat(String(args.quantity))),
606
+ new Field2(Fields2.Price, Number.parseFloat(String(args.price))),
607
+ new Field2(Fields2.OrdType, args.ordType),
608
+ new Field2(Fields2.HandlInst, args.handlInst),
609
+ new Field2(Fields2.TimeInForce, args.timeInForce),
610
+ new Field2(Fields2.TransactTime, parser.getTimestamp())
611
+ );
612
+ if (!parser.connected) {
613
+ return {
614
+ content: [
615
+ {
616
+ type: "text",
617
+ text: "Error: Not connected. Ignoring message.",
618
+ uri: "executeOrder"
619
+ }
620
+ ],
621
+ isError: true
622
+ };
623
+ }
624
+ parser.send(order);
625
+ const fixData = await response;
626
+ verifiedOrders.delete(args.clOrdID);
627
+ return {
628
+ content: [
629
+ {
630
+ type: "text",
631
+ 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())}`,
632
+ uri: "executeOrder"
633
+ }
634
+ ]
635
+ };
636
+ } catch (error) {
637
+ return {
638
+ content: [
639
+ {
640
+ type: "text",
641
+ text: `Error: ${error instanceof Error ? error.message : "Failed to execute order"}`,
642
+ uri: "executeOrder"
643
+ }
644
+ ],
645
+ isError: true
646
+ };
647
+ }
648
+ };
649
+ };
650
+
651
+ // src/tools/parse.ts
652
+ var createParseHandler = (parser) => {
653
+ return async (args) => {
654
+ try {
655
+ const parsedMessage = parser.parse(args.fixString);
656
+ if (!parsedMessage || parsedMessage.length === 0) {
657
+ return {
658
+ content: [
659
+ {
660
+ type: "text",
661
+ text: "Error: Failed to parse FIX string",
662
+ uri: "parse"
663
+ }
664
+ ],
665
+ isError: true
666
+ };
667
+ }
668
+ return {
669
+ content: [
670
+ {
671
+ type: "text",
672
+ text: `${parsedMessage[0].description}
673
+ ${parsedMessage[0].messageTypeDescription}`,
674
+ uri: "parse"
675
+ }
676
+ ]
677
+ };
678
+ } catch (error) {
679
+ return {
680
+ content: [
681
+ {
682
+ type: "text",
683
+ text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`,
684
+ uri: "parse"
685
+ }
686
+ ],
687
+ isError: true
688
+ };
689
+ }
690
+ };
691
+ };
692
+
693
+ // src/tools/parseToJSON.ts
694
+ var createParseToJSONHandler = (parser) => {
695
+ return async (args) => {
696
+ try {
697
+ const parsedMessage = parser.parse(args.fixString);
698
+ if (!parsedMessage || parsedMessage.length === 0) {
699
+ return {
700
+ content: [
701
+ {
702
+ type: "text",
703
+ text: "Error: Failed to parse FIX string",
704
+ uri: "parseToJSON"
705
+ }
706
+ ],
707
+ isError: true
708
+ };
709
+ }
710
+ return {
711
+ content: [
712
+ {
713
+ type: "text",
714
+ text: `${parsedMessage[0].toFIXJSON()}`,
715
+ uri: "parseToJSON"
716
+ }
717
+ ]
718
+ };
719
+ } catch (error) {
720
+ return {
721
+ content: [
722
+ {
723
+ type: "text",
724
+ text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`,
725
+ uri: "parseToJSON"
726
+ }
727
+ ],
728
+ isError: true
729
+ };
730
+ }
731
+ };
732
+ };
733
+
734
+ // src/tools/index.ts
735
+ var createToolHandlers = (parser, verifiedOrders, pendingRequests, marketDataPrices) => ({
736
+ parse: createParseHandler(parser),
737
+ parseToJSON: createParseToJSONHandler(parser),
738
+ verifyOrder: createVerifyOrderHandler(parser, verifiedOrders),
739
+ executeOrder: createExecuteOrderHandler(parser, verifiedOrders, pendingRequests),
740
+ marketDataRequest: createMarketDataRequestHandler(parser, pendingRequests),
741
+ getStockGraph: createGetStockGraphHandler(marketDataPrices),
742
+ getStockPriceHistory: createGetStockPriceHistoryHandler(marketDataPrices)
743
+ });
744
+
745
+ // src/MCPLocal.ts
235
746
  var MCPLocal = class {
236
747
  parser;
237
748
  server = new Server(
@@ -258,7 +769,6 @@ var MCPLocal = class {
258
769
  onReady = void 0;
259
770
  pendingRequests = /* @__PURE__ */ new Map();
260
771
  verifiedOrders = /* @__PURE__ */ new Map();
261
- // Store market data prices with timestamps
262
772
  marketDataPrices = /* @__PURE__ */ new Map();
263
773
  MAX_PRICE_HISTORY = 1e5;
264
774
  // Maximum number of price points to store per symbol
@@ -273,16 +783,16 @@ var MCPLocal = class {
273
783
  message: `MCP Server received message: ${message.messageType}: ${message.description}`
274
784
  });
275
785
  const msgType = message.messageType;
276
- if (msgType === Messages.MarketDataSnapshotFullRefresh || msgType === Messages.ExecutionReport || msgType === Messages.Reject || msgType === Messages.MarketDataIncrementalRefresh) {
786
+ if (msgType === Messages3.MarketDataSnapshotFullRefresh || msgType === Messages3.ExecutionReport || msgType === Messages3.Reject || msgType === Messages3.MarketDataIncrementalRefresh) {
277
787
  this.parser?.logger.log({
278
788
  level: "info",
279
789
  message: `MCP Server handling message type: ${msgType}`
280
790
  });
281
791
  let id;
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();
792
+ if (msgType === Messages3.MarketDataIncrementalRefresh || msgType === Messages3.MarketDataSnapshotFullRefresh) {
793
+ const symbol = message.getField(Fields3.Symbol);
794
+ const price = message.getField(Fields3.MDEntryPx);
795
+ const timestamp = message.getField(Fields3.MDEntryTime)?.value || Date.now();
286
796
  if (symbol?.value && price?.value) {
287
797
  const symbolStr = String(symbol.value);
288
798
  const priceNum = Number(price.value);
@@ -309,14 +819,14 @@ var MCPLocal = class {
309
819
  });
310
820
  }
311
821
  }
312
- if (msgType === Messages.MarketDataSnapshotFullRefresh) {
313
- const mdReqID = message.getField(Fields.MDReqID);
822
+ if (msgType === Messages3.MarketDataSnapshotFullRefresh) {
823
+ const mdReqID = message.getField(Fields3.MDReqID);
314
824
  if (mdReqID) id = String(mdReqID.value);
315
- } else if (msgType === Messages.ExecutionReport) {
316
- const clOrdID = message.getField(Fields.ClOrdID);
825
+ } else if (msgType === Messages3.ExecutionReport) {
826
+ const clOrdID = message.getField(Fields3.ClOrdID);
317
827
  if (clOrdID) id = String(clOrdID.value);
318
- } else if (msgType === Messages.Reject) {
319
- const refSeqNum = message.getField(Fields.RefSeqNum);
828
+ } else if (msgType === Messages3.Reject) {
829
+ const refSeqNum = message.getField(Fields3.RefSeqNum);
320
830
  if (refSeqNum) id = String(refSeqNum.value);
321
831
  }
322
832
  if (id) {
@@ -366,492 +876,30 @@ var MCPLocal = class {
366
876
  }),
367
877
  async (request, extra) => {
368
878
  const { name, arguments: args } = request.params;
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
- };
384
- }
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
- };
879
+ const toolHandlers = createToolHandlers(
880
+ this.parser,
881
+ this.verifiedOrders,
882
+ this.pendingRequests,
883
+ this.marketDataPrices
884
+ );
885
+ const handler = toolHandlers[name];
886
+ if (!handler) {
887
+ return {
888
+ content: [
889
+ {
890
+ type: "text",
891
+ text: `Tool not found: ${name}`,
892
+ uri: name
581
893
  }
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
- };
894
+ ],
895
+ isError: true
896
+ };
854
897
  }
898
+ const result = await handler(args);
899
+ return {
900
+ content: result.content,
901
+ isError: result.isError
902
+ };
855
903
  }
856
904
  );
857
905
  process.on("SIGINT", async () => {