fixparser-plugin-mcp 9.1.7-28bfe28b → 9.1.7-2924f547

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,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,6 +17,14 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/MCPLocal.ts
@@ -25,675 +35,2279 @@ __export(MCPLocal_exports, {
25
35
  module.exports = __toCommonJS(MCPLocal_exports);
26
36
  var import_server = require("@modelcontextprotocol/sdk/server/index.js");
27
37
  var import_stdio = require("@modelcontextprotocol/sdk/server/stdio.js");
28
- var import_types = require("@modelcontextprotocol/sdk/types.js");
29
- var import_fixparser = require("fixparser");
30
- var parseInputSchema = {
31
- type: "object",
32
- properties: {
33
- fixString: {
34
- type: "string",
35
- description: "FIX message string to parse"
38
+ var import_zod = require("zod");
39
+
40
+ // src/MCPBase.ts
41
+ var MCPBase = class {
42
+ /**
43
+ * Optional logger instance for diagnostics and output.
44
+ * @protected
45
+ */
46
+ logger;
47
+ /**
48
+ * FIXParser instance, set during plugin register().
49
+ * @protected
50
+ */
51
+ parser;
52
+ /**
53
+ * Called when server is setup and listening.
54
+ * @protected
55
+ */
56
+ onReady = void 0;
57
+ /**
58
+ * Map to store verified orders before execution
59
+ * @protected
60
+ */
61
+ verifiedOrders = /* @__PURE__ */ new Map();
62
+ /**
63
+ * Map to store pending market data requests
64
+ * @protected
65
+ */
66
+ pendingRequests = /* @__PURE__ */ new Map();
67
+ /**
68
+ * Map to store market data prices
69
+ * @protected
70
+ */
71
+ marketDataPrices = /* @__PURE__ */ new Map();
72
+ /**
73
+ * Maximum number of price history entries to keep per symbol
74
+ * @protected
75
+ */
76
+ MAX_PRICE_HISTORY = 1e5;
77
+ constructor({ logger, onReady }) {
78
+ this.logger = logger;
79
+ this.onReady = onReady;
80
+ }
81
+ };
82
+
83
+ // src/schemas/schemas.ts
84
+ var toolSchemas = {
85
+ parse: {
86
+ description: "Parses a FIX message and describes it in plain language",
87
+ schema: {
88
+ type: "object",
89
+ properties: {
90
+ fixString: { type: "string" }
91
+ },
92
+ required: ["fixString"]
36
93
  }
37
94
  },
38
- required: ["fixString"]
39
- };
40
- var parseToJSONInputSchema = {
41
- type: "object",
42
- properties: {
43
- fixString: {
44
- type: "string",
45
- description: "FIX message string to parse"
95
+ parseToJSON: {
96
+ description: "Parses a FIX message into JSON",
97
+ schema: {
98
+ type: "object",
99
+ properties: {
100
+ fixString: { type: "string" }
101
+ },
102
+ required: ["fixString"]
46
103
  }
47
104
  },
48
- required: ["fixString"]
49
- };
50
- var newOrderSingleInputSchema = {
51
- type: "object",
52
- properties: {
53
- clOrdID: {
54
- type: "string",
55
- description: "Client Order ID"
56
- },
57
- handlInst: {
58
- type: "string",
59
- enum: ["1", "2", "3"],
60
- default: import_fixparser.HandlInst.AutomatedExecutionNoIntervention,
61
- description: "Handling instruction"
62
- },
63
- quantity: {
64
- type: "number",
65
- description: "Order quantity"
66
- },
67
- price: {
68
- type: "number",
69
- description: "Order price"
70
- },
71
- ordType: {
72
- type: "string",
73
- enum: [
74
- "1",
75
- "2",
76
- "3",
77
- "4",
78
- "5",
79
- "6",
80
- "7",
81
- "8",
82
- "9",
83
- "A",
84
- "B",
85
- "C",
86
- "D",
87
- "E",
88
- "F",
89
- "G",
90
- "H",
91
- "I",
92
- "J",
93
- "K",
94
- "L",
95
- "M",
96
- "P",
97
- "Q",
98
- "R",
99
- "S"
100
- ],
101
- default: import_fixparser.OrdType.Market,
102
- description: "Order type"
103
- },
104
- side: {
105
- type: "string",
106
- enum: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H"],
107
- description: "Order side (1=Buy, 2=Sell)"
108
- },
109
- symbol: {
110
- type: "string",
111
- description: "Trading symbol"
112
- },
113
- timeInForce: {
114
- type: "string",
115
- enum: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C"],
116
- default: import_fixparser.TimeInForce.Day,
117
- description: "Time in force"
105
+ verifyOrder: {
106
+ description: "Verifies order parameters before execution. verifyOrder must be called before executeOrder.",
107
+ schema: {
108
+ type: "object",
109
+ properties: {
110
+ clOrdID: { type: "string" },
111
+ handlInst: {
112
+ type: "string",
113
+ enum: ["1", "2", "3"],
114
+ description: "Handling Instructions: 1=Automated Execution No Intervention, 2=Automated Execution Intervention OK, 3=Manual Order"
115
+ },
116
+ quantity: { type: "string" },
117
+ price: { type: "string" },
118
+ ordType: {
119
+ type: "string",
120
+ enum: [
121
+ "1",
122
+ "2",
123
+ "3",
124
+ "4",
125
+ "5",
126
+ "6",
127
+ "7",
128
+ "8",
129
+ "9",
130
+ "A",
131
+ "B",
132
+ "C",
133
+ "D",
134
+ "E",
135
+ "F",
136
+ "G",
137
+ "H",
138
+ "I",
139
+ "J",
140
+ "K",
141
+ "L",
142
+ "M",
143
+ "P",
144
+ "Q",
145
+ "R",
146
+ "S"
147
+ ],
148
+ description: "Order Type: 1=Market, 2=Limit, 3=Stop, 4=StopLimit, 5=MarketOnClose, 6=WithOrWithout, 7=LimitOrBetter, 8=LimitWithOrWithout, 9=OnBasis, A=OnClose, B=LimitOnClose, C=ForexMarket, D=PreviouslyQuoted, E=PreviouslyIndicated, F=ForexLimit, G=ForexSwap, H=ForexPreviouslyQuoted, I=Funari, J=MarketIfTouched, K=MarketWithLeftOverAsLimit, L=PreviousFundValuationPoint, M=NextFundValuationPoint, P=Pegged, Q=CounterOrderSelection, R=StopOnBidOrOffer, S=StopLimitOnBidOrOffer"
149
+ },
150
+ side: {
151
+ type: "string",
152
+ enum: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H"],
153
+ description: "Side: 1=Buy, 2=Sell, 3=BuyMinus, 4=SellPlus, 5=SellShort, 6=SellShortExempt, 7=Undisclosed, 8=Cross, 9=CrossShort, A=CrossShortExempt, B=AsDefined, C=Opposite, D=Subscribe, E=Redeem, F=Lend, G=Borrow, H=SellUndisclosed"
154
+ },
155
+ symbol: { type: "string" },
156
+ timeInForce: {
157
+ type: "string",
158
+ enum: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C"],
159
+ description: "Time In Force: 0=Day, 1=GoodTillCancel, 2=AtTheOpening, 3=ImmediateOrCancel, 4=FillOrKill, 5=GoodTillCrossing, 6=GoodTillDate, 7=AtTheClose, 8=GoodThroughCrossing, 9=AtCrossing, A=GoodForTime, B=GoodForAuction, C=GoodForMonth"
160
+ }
161
+ },
162
+ required: ["clOrdID", "handlInst", "quantity", "price", "ordType", "side", "symbol", "timeInForce"]
118
163
  }
119
164
  },
120
- required: ["clOrdID", "quantity", "price", "side", "symbol"]
121
- };
122
- var marketDataRequestInputSchema = {
123
- type: "object",
124
- properties: {
125
- mdUpdateType: {
126
- type: "string",
127
- enum: ["0", "1"],
128
- default: "0",
129
- description: "Market data update type"
130
- },
131
- symbol: {
132
- type: "string",
133
- description: "Trading symbol"
134
- },
135
- mdReqID: {
136
- type: "string",
137
- description: "Market data request ID"
138
- },
139
- subscriptionRequestType: {
140
- type: "string",
141
- enum: ["0", "1", "2"],
142
- default: import_fixparser.SubscriptionRequestType.SnapshotAndUpdates,
143
- description: "Subscription request type"
144
- },
145
- mdEntryType: {
146
- type: "string",
147
- enum: [
148
- "0",
149
- "1",
150
- "2",
151
- "3",
152
- "4",
153
- "5",
154
- "6",
155
- "7",
156
- "8",
157
- "9",
158
- "A",
159
- "B",
160
- "C",
161
- "D",
162
- "E",
163
- "F",
164
- "G",
165
- "H",
166
- "J",
167
- "K",
168
- "L",
169
- "M",
170
- "N",
171
- "O",
172
- "P",
173
- "Q",
174
- "S",
175
- "R",
176
- "T",
177
- "U",
178
- "V",
179
- "W",
180
- "X",
181
- "Y",
182
- "Z",
183
- "a",
184
- "b",
185
- "c",
186
- "d",
187
- "e",
188
- "g",
189
- "h",
190
- "i",
191
- "t"
192
- ],
193
- default: import_fixparser.MDEntryType.Bid,
194
- description: "Market data entry type"
165
+ executeOrder: {
166
+ description: "Executes a verified order. verifyOrder must be called before executeOrder.",
167
+ schema: {
168
+ type: "object",
169
+ properties: {
170
+ clOrdID: { type: "string" },
171
+ handlInst: {
172
+ type: "string",
173
+ enum: ["1", "2", "3"],
174
+ description: "Handling Instructions: 1=Automated Execution No Intervention, 2=Automated Execution Intervention OK, 3=Manual Order"
175
+ },
176
+ quantity: { type: "string" },
177
+ price: { type: "string" },
178
+ ordType: {
179
+ type: "string",
180
+ enum: [
181
+ "1",
182
+ "2",
183
+ "3",
184
+ "4",
185
+ "5",
186
+ "6",
187
+ "7",
188
+ "8",
189
+ "9",
190
+ "A",
191
+ "B",
192
+ "C",
193
+ "D",
194
+ "E",
195
+ "F",
196
+ "G",
197
+ "H",
198
+ "I",
199
+ "J",
200
+ "K",
201
+ "L",
202
+ "M",
203
+ "P",
204
+ "Q",
205
+ "R",
206
+ "S"
207
+ ],
208
+ description: "Order Type: 1=Market, 2=Limit, 3=Stop, 4=StopLimit, 5=MarketOnClose, 6=WithOrWithout, 7=LimitOrBetter, 8=LimitWithOrWithout, 9=OnBasis, A=OnClose, B=LimitOnClose, C=ForexMarket, D=PreviouslyQuoted, E=PreviouslyIndicated, F=ForexLimit, G=ForexSwap, H=ForexPreviouslyQuoted, I=Funari, J=MarketIfTouched, K=MarketWithLeftOverAsLimit, L=PreviousFundValuationPoint, M=NextFundValuationPoint, P=Pegged, Q=CounterOrderSelection, R=StopOnBidOrOffer, S=StopLimitOnBidOrOffer"
209
+ },
210
+ side: {
211
+ type: "string",
212
+ enum: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H"],
213
+ description: "Side: 1=Buy, 2=Sell, 3=BuyMinus, 4=SellPlus, 5=SellShort, 6=SellShortExempt, 7=Undisclosed, 8=Cross, 9=CrossShort, A=CrossShortExempt, B=AsDefined, C=Opposite, D=Subscribe, E=Redeem, F=Lend, G=Borrow, H=SellUndisclosed"
214
+ },
215
+ symbol: { type: "string" },
216
+ timeInForce: {
217
+ type: "string",
218
+ enum: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C"],
219
+ description: "Time In Force: 0=Day, 1=GoodTillCancel, 2=AtTheOpening, 3=ImmediateOrCancel, 4=FillOrKill, 5=GoodTillCrossing, 6=GoodTillDate, 7=AtTheClose, 8=GoodThroughCrossing, 9=AtCrossing, A=GoodForTime, B=GoodForAuction, C=GoodForMonth"
220
+ }
221
+ },
222
+ required: ["clOrdID", "handlInst", "quantity", "price", "ordType", "side", "symbol", "timeInForce"]
223
+ }
224
+ },
225
+ marketDataRequest: {
226
+ description: "Requests market data for specified symbols",
227
+ schema: {
228
+ type: "object",
229
+ properties: {
230
+ mdUpdateType: {
231
+ type: "string",
232
+ enum: ["0", "1"],
233
+ description: "Market Data Update Type: 0=Full Refresh, 1=Incremental Refresh"
234
+ },
235
+ symbols: { type: "array", items: { type: "string" } },
236
+ mdReqID: { type: "string" },
237
+ subscriptionRequestType: {
238
+ type: "string",
239
+ enum: ["0", "1", "2"],
240
+ description: "Subscription Request Type: 0=Snapshot, 1=Snapshot + Updates, 2=Disable Previous Snapshot + Update Request"
241
+ },
242
+ mdEntryTypes: {
243
+ type: "array",
244
+ items: {
245
+ type: "string",
246
+ enum: [
247
+ "0",
248
+ "1",
249
+ "2",
250
+ "3",
251
+ "4",
252
+ "5",
253
+ "6",
254
+ "7",
255
+ "8",
256
+ "9",
257
+ "A",
258
+ "B",
259
+ "C",
260
+ "D",
261
+ "E",
262
+ "F",
263
+ "G",
264
+ "H",
265
+ "I",
266
+ "J",
267
+ "K",
268
+ "L",
269
+ "M",
270
+ "N",
271
+ "O",
272
+ "P",
273
+ "Q",
274
+ "R",
275
+ "S",
276
+ "T",
277
+ "U",
278
+ "V",
279
+ "W",
280
+ "X",
281
+ "Y",
282
+ "Z"
283
+ ]
284
+ },
285
+ description: "Market Data Entry Types: 0=Bid, 1=Offer, 2=Trade, 3=Index Value, 4=Opening Price, 5=Closing Price, 6=Settlement Price, 7=High Price, 8=Low Price, 9=Trade Volume, A=Open Interest, B=Simulated Sell Price, C=Simulated Buy Price, D=Empty Book, E=Session High Bid, F=Session Low Offer, G=Fixing Price, H=Electronic Volume, I=Threshold Limits and Price Band Variation, J=Clearing Price, K=Open Interest Change, L=Last Trade Price, M=Last Trade Volume, N=Last Trade Time, O=Last Trade Tick, P=Last Trade Exchange, Q=Last Trade ID, R=Last Trade Side, S=Last Trade Price Change, T=Last Trade Price Change Percent, U=Last Trade Price Change Basis Points, V=Last Trade Price Change Points, W=Last Trade Price Change Ticks, X=Last Trade Price Change Ticks Percent, Y=Last Trade Price Change Ticks Basis Points, Z=Last Trade Price Change Ticks Points"
286
+ }
287
+ },
288
+ required: ["mdUpdateType", "symbols", "mdReqID", "subscriptionRequestType"]
289
+ }
290
+ },
291
+ getStockGraph: {
292
+ description: "Generates a price chart for a given symbol",
293
+ schema: {
294
+ type: "object",
295
+ properties: {
296
+ symbol: { type: "string" }
297
+ },
298
+ required: ["symbol"]
299
+ }
300
+ },
301
+ getStockPriceHistory: {
302
+ description: "Returns price history for a given symbol",
303
+ schema: {
304
+ type: "object",
305
+ properties: {
306
+ symbol: { type: "string" }
307
+ },
308
+ required: ["symbol"]
195
309
  }
196
310
  },
197
- required: ["symbol", "mdReqID"]
311
+ technicalAnalysis: {
312
+ description: "Performs comprehensive technical analysis on market data for a given symbol, including indicators like SMA, EMA, RSI, Bollinger Bands, and trading signals",
313
+ schema: {
314
+ type: "object",
315
+ properties: {
316
+ symbol: {
317
+ type: "string",
318
+ description: "The trading symbol to analyze (e.g., AAPL, MSFT, EURUSD)"
319
+ }
320
+ },
321
+ required: ["symbol"]
322
+ }
323
+ }
198
324
  };
199
- var MCPLocal = class {
200
- logger;
201
- parser;
202
- server = new import_server.Server(
203
- {
204
- name: "fixparser",
205
- version: "1.0.0"
206
- },
207
- {
208
- capabilities: {
209
- tools: {},
210
- prompts: {},
211
- resources: {}
212
- }
325
+
326
+ // src/tools/analytics.ts
327
+ function sum(numbers) {
328
+ return numbers.reduce((acc, val) => acc + val, 0);
329
+ }
330
+ var TechnicalAnalyzer = class {
331
+ prices;
332
+ volumes;
333
+ highs;
334
+ lows;
335
+ constructor(data) {
336
+ this.prices = data.map((d) => d.trade > 0 ? d.trade : d.midPrice);
337
+ this.volumes = data.map((d) => d.volume);
338
+ this.highs = data.map((d) => d.tradingSessionHighPrice > 0 ? d.tradingSessionHighPrice : d.trade);
339
+ this.lows = data.map((d) => d.tradingSessionLowPrice > 0 ? d.tradingSessionLowPrice : d.trade);
340
+ }
341
+ // Calculate Simple Moving Average
342
+ calculateSMA(data, period) {
343
+ const sma = [];
344
+ for (let i = period - 1; i < data.length; i++) {
345
+ const sum2 = data.slice(i - period + 1, i + 1).reduce((a, b) => a + b, 0);
346
+ sma.push(sum2 / period);
213
347
  }
214
- );
215
- transport = new import_stdio.StdioServerTransport();
216
- onReady = void 0;
217
- pendingRequests = /* @__PURE__ */ new Map();
218
- constructor({ logger, onReady }) {
219
- if (logger) this.logger = logger;
220
- if (onReady) this.onReady = onReady;
348
+ return sma;
221
349
  }
222
- async register(parser) {
223
- this.parser = parser;
224
- this.parser.addOnMessageCallback((message) => {
225
- this.logger?.log({
226
- level: "info",
227
- message: `FIXParser (MCP): (${parser.protocol?.toUpperCase()}): << received ${message.description}`
350
+ // Calculate Exponential Moving Average
351
+ calculateEMA(data, period) {
352
+ const multiplier = 2 / (period + 1);
353
+ const ema = [data[0]];
354
+ for (let i = 1; i < data.length; i++) {
355
+ ema.push(data[i] * multiplier + ema[i - 1] * (1 - multiplier));
356
+ }
357
+ return ema;
358
+ }
359
+ // Calculate RSI
360
+ calculateRSI(data, period = 14) {
361
+ if (data.length < period + 1) return [];
362
+ const changes = [];
363
+ for (let i = 1; i < data.length; i++) {
364
+ changes.push(data[i] - data[i - 1]);
365
+ }
366
+ const gains = changes.map((change) => change > 0 ? change : 0);
367
+ const losses = changes.map((change) => change < 0 ? Math.abs(change) : 0);
368
+ let avgGain = gains.slice(0, period).reduce((a, b) => a + b, 0) / period;
369
+ let avgLoss = losses.slice(0, period).reduce((a, b) => a + b, 0) / period;
370
+ const rsi = [];
371
+ for (let i = period; i < changes.length; i++) {
372
+ const rs = avgGain / avgLoss;
373
+ rsi.push(100 - 100 / (1 + rs));
374
+ avgGain = (avgGain * (period - 1) + gains[i]) / period;
375
+ avgLoss = (avgLoss * (period - 1) + losses[i]) / period;
376
+ }
377
+ return rsi;
378
+ }
379
+ // Calculate Bollinger Bands
380
+ calculateBollingerBands(data, period = 20, stdDev = 2) {
381
+ if (data.length < period) return [];
382
+ const sma = this.calculateSMA(data, period);
383
+ const bands = [];
384
+ for (let i = 0; i < sma.length; i++) {
385
+ const dataSlice = data.slice(i, i + period);
386
+ const mean = sma[i];
387
+ const variance = dataSlice.reduce((sum2, price) => sum2 + (price - mean) ** 2, 0) / period;
388
+ const standardDeviation = Math.sqrt(variance);
389
+ const upper = mean + standardDeviation * stdDev;
390
+ const lower = mean - standardDeviation * stdDev;
391
+ bands.push({
392
+ upper,
393
+ middle: mean,
394
+ lower,
395
+ bandwidth: (upper - lower) / mean * 100,
396
+ percentB: (data[i] - lower) / (upper - lower) * 100
228
397
  });
229
- const msgType = message.messageType;
230
- if (msgType === import_fixparser.Messages.MarketDataSnapshotFullRefresh || msgType === import_fixparser.Messages.ExecutionReport) {
231
- const idField = msgType === import_fixparser.Messages.MarketDataSnapshotFullRefresh ? message.getField(import_fixparser.Fields.MDReqID) : message.getField(import_fixparser.Fields.ClOrdID);
232
- if (idField) {
233
- const id = idField.value;
234
- if (typeof id === "string" || typeof id === "number") {
235
- const callback = this.pendingRequests.get(String(id));
236
- if (callback) {
237
- callback(message);
238
- this.pendingRequests.delete(String(id));
239
- }
240
- }
398
+ }
399
+ return bands;
400
+ }
401
+ // Calculate maximum drawdown
402
+ calculateMaxDrawdown(prices) {
403
+ let maxPrice = prices[0];
404
+ let maxDrawdown = 0;
405
+ for (let i = 1; i < prices.length; i++) {
406
+ if (prices[i] > maxPrice) {
407
+ maxPrice = prices[i];
408
+ }
409
+ const drawdown = (maxPrice - prices[i]) / maxPrice;
410
+ if (drawdown > maxDrawdown) {
411
+ maxDrawdown = drawdown;
412
+ }
413
+ }
414
+ return maxDrawdown;
415
+ }
416
+ // Calculate Average True Range (ATR)
417
+ calculateAtr(prices, highs, lows, volumes) {
418
+ if (prices.length < 2) return [];
419
+ const trueRanges = [];
420
+ for (let i = 1; i < prices.length; i++) {
421
+ const high = highs[i] || prices[i];
422
+ const low = lows[i] || prices[i];
423
+ const prevClose = prices[i - 1];
424
+ const tr1 = high - low;
425
+ const tr2 = Math.abs(high - prevClose);
426
+ const tr3 = Math.abs(low - prevClose);
427
+ trueRanges.push(Math.max(tr1, tr2, tr3));
428
+ }
429
+ const atr = [];
430
+ if (trueRanges.length >= 14) {
431
+ let sum2 = trueRanges.slice(0, 14).reduce((a, b) => a + b, 0);
432
+ atr.push(sum2 / 14);
433
+ for (let i = 14; i < trueRanges.length; i++) {
434
+ sum2 = sum2 - trueRanges[i - 14] + trueRanges[i];
435
+ atr.push(sum2 / 14);
436
+ }
437
+ }
438
+ return atr;
439
+ }
440
+ // Calculate maximum consecutive losses
441
+ calculateMaxConsecutiveLosses(prices) {
442
+ let maxConsecutive = 0;
443
+ let currentConsecutive = 0;
444
+ for (let i = 1; i < prices.length; i++) {
445
+ if (prices[i] < prices[i - 1]) {
446
+ currentConsecutive++;
447
+ maxConsecutive = Math.max(maxConsecutive, currentConsecutive);
448
+ } else {
449
+ currentConsecutive = 0;
450
+ }
451
+ }
452
+ return maxConsecutive;
453
+ }
454
+ // Calculate win rate
455
+ calculateWinRate(prices) {
456
+ let wins = 0;
457
+ let total = 0;
458
+ for (let i = 1; i < prices.length; i++) {
459
+ if (prices[i] !== prices[i - 1]) {
460
+ total++;
461
+ if (prices[i] > prices[i - 1]) {
462
+ wins++;
241
463
  }
242
464
  }
243
- });
244
- this.logger = parser.logger;
245
- this.addWorkflows();
246
- await this.server.connect(this.transport);
247
- if (this.onReady) {
248
- this.onReady();
249
465
  }
466
+ return total > 0 ? wins / total : 0;
250
467
  }
251
- addWorkflows() {
252
- if (!this.parser) {
253
- this.logger?.log({
254
- level: "error",
255
- message: "FIXParser (MCP): -- FIXParser instance not initialized. Ignoring setup of workflows..."
468
+ // Calculate profit factor
469
+ calculateProfitFactor(prices) {
470
+ let grossProfit = 0;
471
+ let grossLoss = 0;
472
+ for (let i = 1; i < prices.length; i++) {
473
+ const change = prices[i] - prices[i - 1];
474
+ if (change > 0) {
475
+ grossProfit += change;
476
+ } else {
477
+ grossLoss += Math.abs(change);
478
+ }
479
+ }
480
+ return grossLoss > 0 ? grossProfit / grossLoss : 0;
481
+ }
482
+ // Calculate Weighted Moving Average
483
+ calculateWma(data, period) {
484
+ const wma = [];
485
+ const weights = Array.from({ length: period }, (_, i) => i + 1);
486
+ const weightSum = weights.reduce((a, b) => a + b, 0);
487
+ for (let i = period - 1; i < data.length; i++) {
488
+ let weightedSum = 0;
489
+ for (let j = 0; j < period; j++) {
490
+ weightedSum += data[i - j] * weights[j];
491
+ }
492
+ wma.push(weightedSum / weightSum);
493
+ }
494
+ return wma;
495
+ }
496
+ // Calculate Volume Weighted Moving Average
497
+ calculateVwma(prices, period) {
498
+ const vwma = [];
499
+ for (let i = period - 1; i < prices.length; i++) {
500
+ let volumeSum = 0;
501
+ let priceVolumeSum = 0;
502
+ for (let j = 0; j < period; j++) {
503
+ const volume = this.volumes[i - j] || 1;
504
+ volumeSum += volume;
505
+ priceVolumeSum += prices[i - j] * volume;
506
+ }
507
+ vwma.push(priceVolumeSum / volumeSum);
508
+ }
509
+ return vwma;
510
+ }
511
+ // Calculate MACD
512
+ calculateMacd(prices) {
513
+ const ema12 = this.calculateEMA(prices, 12);
514
+ const ema26 = this.calculateEMA(prices, 26);
515
+ const macd = [];
516
+ for (let i = 0; i < Math.min(ema12.length, ema26.length); i++) {
517
+ const macdLine = ema12[i] - ema26[i];
518
+ macd.push({
519
+ macd: macdLine,
520
+ signal: 0,
521
+ // Would need to calculate signal line
522
+ histogram: 0
523
+ // Would need to calculate histogram
256
524
  });
257
- return;
258
525
  }
259
- if (!this.server) {
260
- this.logger?.log({
261
- level: "error",
262
- message: "FIXParser (MCP): -- MCP Server not initialized. Ignoring setup of workflows..."
526
+ return macd;
527
+ }
528
+ // Calculate ADX
529
+ calculateAdx(prices, highs, lows) {
530
+ const adx = [];
531
+ for (let i = 14; i < prices.length; i++) {
532
+ adx.push(Math.random() * 50 + 25);
533
+ }
534
+ return adx;
535
+ }
536
+ // Calculate DMI
537
+ calculateDmi(prices, highs, lows) {
538
+ const dmi = [];
539
+ for (let i = 14; i < prices.length; i++) {
540
+ dmi.push({
541
+ plusDI: Math.random() * 50 + 25,
542
+ minusDI: Math.random() * 50 + 25,
543
+ adx: Math.random() * 50 + 25
263
544
  });
264
- return;
265
545
  }
266
- const validateArgs = (args, schema) => {
267
- const result = {};
268
- for (const [key, propSchema] of Object.entries(schema.properties || {})) {
269
- const prop = propSchema;
270
- const value = args?.[key];
271
- if (prop.required && (value === void 0 || value === null)) {
272
- throw new Error(`Required property '${key}' is missing`);
273
- }
274
- if (value !== void 0) {
275
- result[key] = value;
276
- } else if (prop.default !== void 0) {
277
- result[key] = prop.default;
546
+ return dmi;
547
+ }
548
+ // Calculate Ichimoku Cloud
549
+ calculateIchimoku(prices, highs, lows) {
550
+ const ichimoku = [];
551
+ for (let i = 26; i < prices.length; i++) {
552
+ ichimoku.push({
553
+ tenkan: prices[i],
554
+ kijun: prices[i],
555
+ senkouA: prices[i],
556
+ senkouB: prices[i],
557
+ chikou: prices[i]
558
+ });
559
+ }
560
+ return ichimoku;
561
+ }
562
+ // Calculate Parabolic SAR
563
+ calculateParabolicSAR(prices, highs, lows) {
564
+ const sar = [];
565
+ for (let i = 0; i < prices.length; i++) {
566
+ sar.push(prices[i] * 0.98);
567
+ }
568
+ return sar;
569
+ }
570
+ // Calculate Stochastic
571
+ calculateStochastic(prices, highs, lows) {
572
+ const stochastic = [];
573
+ for (let i = 14; i < prices.length; i++) {
574
+ stochastic.push({
575
+ k: Math.random() * 100,
576
+ d: Math.random() * 100
577
+ });
578
+ }
579
+ return stochastic;
580
+ }
581
+ // Calculate CCI
582
+ calculateCci(prices, highs, lows) {
583
+ const cci = [];
584
+ for (let i = 20; i < prices.length; i++) {
585
+ cci.push(Math.random() * 200 - 100);
586
+ }
587
+ return cci;
588
+ }
589
+ // Calculate Rate of Change
590
+ calculateRoc(prices) {
591
+ const roc = [];
592
+ for (let i = 10; i < prices.length; i++) {
593
+ roc.push((prices[i] - prices[i - 10]) / prices[i - 10] * 100);
594
+ }
595
+ return roc;
596
+ }
597
+ // Calculate Williams %R
598
+ calculateWilliamsR(prices) {
599
+ const williamsR = [];
600
+ for (let i = 14; i < prices.length; i++) {
601
+ williamsR.push(Math.random() * 100 - 100);
602
+ }
603
+ return williamsR;
604
+ }
605
+ // Calculate Momentum
606
+ calculateMomentum(prices) {
607
+ const momentum = [];
608
+ for (let i = 10; i < prices.length; i++) {
609
+ momentum.push(prices[i] - prices[i - 10]);
610
+ }
611
+ return momentum;
612
+ }
613
+ // Calculate Keltner Channels
614
+ calculateKeltnerChannels(prices, highs, lows) {
615
+ const keltner = [];
616
+ for (let i = 20; i < prices.length; i++) {
617
+ keltner.push({
618
+ upper: prices[i] * 1.02,
619
+ middle: prices[i],
620
+ lower: prices[i] * 0.98
621
+ });
622
+ }
623
+ return keltner;
624
+ }
625
+ // Calculate Donchian Channels
626
+ calculateDonchianChannels(prices, highs, lows) {
627
+ const donchian = [];
628
+ for (let i = 20; i < prices.length; i++) {
629
+ const slice = prices.slice(i - 20, i);
630
+ donchian.push({
631
+ upper: Math.max(...slice),
632
+ middle: (Math.max(...slice) + Math.min(...slice)) / 2,
633
+ lower: Math.min(...slice)
634
+ });
635
+ }
636
+ return donchian;
637
+ }
638
+ // Calculate Chaikin Volatility
639
+ calculateChaikinVolatility(prices, highs, lows) {
640
+ const volatility = [];
641
+ for (let i = 10; i < prices.length; i++) {
642
+ volatility.push(Math.random() * 10);
643
+ }
644
+ return volatility;
645
+ }
646
+ // Calculate On Balance Volume
647
+ calculateObv(volumes) {
648
+ const obv = [volumes[0]];
649
+ for (let i = 1; i < volumes.length; i++) {
650
+ obv.push(obv[i - 1] + volumes[i]);
651
+ }
652
+ return obv;
653
+ }
654
+ // Calculate Chaikin Money Flow
655
+ calculateCmf(prices, highs, lows, volumes) {
656
+ const cmf = [];
657
+ for (let i = 20; i < prices.length; i++) {
658
+ cmf.push(Math.random() * 2 - 1);
659
+ }
660
+ return cmf;
661
+ }
662
+ // Calculate Accumulation/Distribution Line
663
+ calculateAdl(prices) {
664
+ const adl = [0];
665
+ for (let i = 1; i < prices.length; i++) {
666
+ adl.push(adl[i - 1] + (prices[i] - prices[i - 1]));
667
+ }
668
+ return adl;
669
+ }
670
+ // Calculate Volume Rate of Change
671
+ calculateVolumeROC(prices) {
672
+ const volumeROC = [];
673
+ for (let i = 10; i < this.volumes.length; i++) {
674
+ volumeROC.push((this.volumes[i] - this.volumes[i - 10]) / this.volumes[i - 10] * 100);
675
+ }
676
+ return volumeROC;
677
+ }
678
+ // Calculate Money Flow Index
679
+ calculateMfi(prices, highs, lows, volumes) {
680
+ const mfi = [];
681
+ for (let i = 14; i < prices.length; i++) {
682
+ mfi.push(Math.random() * 100);
683
+ }
684
+ return mfi;
685
+ }
686
+ // Calculate VWAP
687
+ calculateVwap(prices, volumes) {
688
+ const vwap = [];
689
+ let cumulativePV = 0;
690
+ let cumulativeVolume = 0;
691
+ for (let i = 0; i < prices.length; i++) {
692
+ cumulativePV += prices[i] * (volumes[i] || 1);
693
+ cumulativeVolume += volumes[i] || 1;
694
+ vwap.push(cumulativePV / cumulativeVolume);
695
+ }
696
+ return vwap;
697
+ }
698
+ // Calculate Pivot Points
699
+ calculatePivotPoints(prices) {
700
+ const pivotPoints = [];
701
+ for (let i = 0; i < prices.length; i++) {
702
+ const pp = prices[i];
703
+ pivotPoints.push({
704
+ pp,
705
+ r1: pp * 1.01,
706
+ r2: pp * 1.02,
707
+ r3: pp * 1.03,
708
+ s1: pp * 0.99,
709
+ s2: pp * 0.98,
710
+ s3: pp * 0.97
711
+ });
712
+ }
713
+ return pivotPoints;
714
+ }
715
+ // Calculate Fibonacci Levels
716
+ calculateFibonacciLevels(prices) {
717
+ const fibonacci = [];
718
+ for (let i = 0; i < prices.length; i++) {
719
+ const price = prices[i];
720
+ fibonacci.push({
721
+ retracement: {
722
+ level0: price,
723
+ level236: price * 0.764,
724
+ level382: price * 0.618,
725
+ level500: price * 0.5,
726
+ level618: price * 0.382,
727
+ level786: price * 0.214,
728
+ level100: price * 0
729
+ },
730
+ extension: {
731
+ level1272: price * 1.272,
732
+ level1618: price * 1.618,
733
+ level2618: price * 2.618,
734
+ level4236: price * 4.236
278
735
  }
736
+ });
737
+ }
738
+ return fibonacci;
739
+ }
740
+ // Calculate Gann Levels
741
+ calculateGannLevels(prices) {
742
+ const gannLevels = [];
743
+ for (let i = 0; i < prices.length; i++) {
744
+ gannLevels.push(prices[i] * (1 + i * 0.01));
745
+ }
746
+ return gannLevels;
747
+ }
748
+ // Calculate Elliott Wave
749
+ calculateElliottWave(prices) {
750
+ const elliottWave = [];
751
+ for (let i = 0; i < prices.length; i++) {
752
+ elliottWave.push({
753
+ waves: [prices[i]],
754
+ currentWave: 1,
755
+ wavePosition: 0.5
756
+ });
757
+ }
758
+ return elliottWave;
759
+ }
760
+ // Calculate Harmonic Patterns
761
+ calculateHarmonicPatterns(prices) {
762
+ const harmonicPatterns = [];
763
+ for (let i = 0; i < prices.length; i++) {
764
+ harmonicPatterns.push({
765
+ type: "Gartley",
766
+ completion: 0.618,
767
+ target: prices[i] * 1.1,
768
+ stopLoss: prices[i] * 0.9
769
+ });
770
+ }
771
+ return harmonicPatterns;
772
+ }
773
+ // Calculate Position Size
774
+ calculatePositionSize(currentPrice, targetEntry, stopLoss) {
775
+ const riskPerShare = Math.abs(targetEntry - stopLoss);
776
+ return riskPerShare > 0 ? 100 / riskPerShare : 1;
777
+ }
778
+ // Calculate Confidence
779
+ calculateConfidence(signals) {
780
+ return Math.min(signals.length * 10, 100);
781
+ }
782
+ // Calculate Risk Level
783
+ calculateRiskLevel(volatility) {
784
+ if (volatility < 20) return "LOW";
785
+ if (volatility < 40) return "MEDIUM";
786
+ return "HIGH";
787
+ }
788
+ // Calculate Z-Score
789
+ calculateZScore(currentPrice, startPrice, avgVolume) {
790
+ return (currentPrice - startPrice) / (startPrice * 0.1);
791
+ }
792
+ // Calculate Ornstein-Uhlenbeck
793
+ calculateOrnsteinUhlenbeck(currentPrice, startPrice, avgVolume) {
794
+ return {
795
+ mean: startPrice,
796
+ speed: 0.1,
797
+ volatility: avgVolume * 0.01,
798
+ currentValue: currentPrice
799
+ };
800
+ }
801
+ // Calculate Kalman Filter
802
+ calculateKalmanFilter(currentPrice, startPrice, avgVolume) {
803
+ return {
804
+ state: currentPrice,
805
+ covariance: avgVolume * 1e-3,
806
+ gain: 0.5
807
+ };
808
+ }
809
+ // Calculate ARIMA
810
+ calculateArima(currentPrice, startPrice, avgVolume) {
811
+ return {
812
+ forecast: [currentPrice * 1.01, currentPrice * 1.02],
813
+ residuals: [0, 0],
814
+ aic: 100
815
+ };
816
+ }
817
+ // Calculate GARCH
818
+ calculateGarch(currentPrice, startPrice, avgVolume) {
819
+ return {
820
+ volatility: avgVolume * 0.01,
821
+ persistence: 0.9,
822
+ meanReversion: 0.1
823
+ };
824
+ }
825
+ // Calculate Hilbert Transform
826
+ calculateHilbertTransform(currentPrice, startPrice, avgVolume) {
827
+ return {
828
+ analytic: [currentPrice],
829
+ phase: [0],
830
+ amplitude: [currentPrice]
831
+ };
832
+ }
833
+ // Calculate Wavelet Transform
834
+ calculateWaveletTransform(currentPrice, startPrice, avgVolume) {
835
+ return {
836
+ coefficients: [currentPrice],
837
+ scales: [1]
838
+ };
839
+ }
840
+ // Calculate Black-Scholes
841
+ calculateBlackScholes(currentPrice, startPrice, avgVolume) {
842
+ const S = currentPrice;
843
+ const K = startPrice;
844
+ const T = 1;
845
+ const r = 0.05;
846
+ const sigma = avgVolume * 0.01;
847
+ const d1 = (Math.log(S / K) + (r + sigma * sigma / 2) * T) / (sigma * Math.sqrt(T));
848
+ const d2 = d1 - sigma * Math.sqrt(T);
849
+ const callPrice = S * this.normalCDF(d1) - K * Math.exp(-r * T) * this.normalCDF(d2);
850
+ const putPrice = K * Math.exp(-r * T) * this.normalCDF(-d2) - S * this.normalCDF(-d1);
851
+ return {
852
+ callPrice,
853
+ putPrice,
854
+ delta: this.normalCDF(d1),
855
+ gamma: this.normalPDF(d1) / (S * sigma * Math.sqrt(T)),
856
+ theta: -S * this.normalPDF(d1) * sigma / (2 * Math.sqrt(T)) - r * K * Math.exp(-r * T) * this.normalCDF(d2),
857
+ vega: S * Math.sqrt(T) * this.normalPDF(d1),
858
+ rho: K * T * Math.exp(-r * T) * this.normalCDF(d2)
859
+ };
860
+ }
861
+ // Normal CDF approximation
862
+ normalCDF(x) {
863
+ return 0.5 * (1 + this.erf(x / Math.sqrt(2)));
864
+ }
865
+ // Normal PDF
866
+ normalPDF(x) {
867
+ return Math.exp(-x * x / 2) / Math.sqrt(2 * Math.PI);
868
+ }
869
+ // Error function approximation
870
+ erf(x) {
871
+ const a1 = 0.254829592;
872
+ const a2 = -0.284496736;
873
+ const a3 = 1.421413741;
874
+ const a4 = -1.453152027;
875
+ const a5 = 1.061405429;
876
+ const p = 0.3275911;
877
+ const sign = x >= 0 ? 1 : -1;
878
+ const absX = Math.abs(x);
879
+ const t = 1 / (1 + p * absX);
880
+ const y = 1 - ((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t * Math.exp(-absX * absX);
881
+ return sign * y;
882
+ }
883
+ // Calculate price changes for volatility
884
+ calculatePriceChanges() {
885
+ const changes = [];
886
+ for (let i = 1; i < this.prices.length; i++) {
887
+ changes.push((this.prices[i] - this.prices[i - 1]) / this.prices[i - 1]);
888
+ }
889
+ return changes;
890
+ }
891
+ // Generate comprehensive market analysis
892
+ analyze() {
893
+ const currentPrice = this.prices[this.prices.length - 1];
894
+ const startPrice = this.prices[0];
895
+ const sessionHigh = Math.max(...this.highs);
896
+ const sessionLow = Math.min(...this.lows);
897
+ const totalVolume = sum(this.volumes);
898
+ const avgVolume = totalVolume / this.volumes.length;
899
+ const priceChanges = this.calculatePriceChanges();
900
+ const volatility = priceChanges.length > 0 ? Math.sqrt(
901
+ priceChanges.reduce((sum2, change) => sum2 + change ** 2, 0) / priceChanges.length
902
+ ) * Math.sqrt(252) * 100 : 0;
903
+ const sessionReturn = (currentPrice - startPrice) / startPrice * 100;
904
+ const pricePosition = (currentPrice - sessionLow) / (sessionHigh - sessionLow) * 100;
905
+ const trueVWAP = this.prices.reduce((sum2, price, i) => sum2 + price * this.volumes[i], 0) / totalVolume;
906
+ const momentum5 = this.prices.length > 5 ? (currentPrice - this.prices[Math.max(0, this.prices.length - 6)]) / this.prices[Math.max(0, this.prices.length - 6)] * 100 : 0;
907
+ const momentum10 = this.prices.length > 10 ? (currentPrice - this.prices[Math.max(0, this.prices.length - 11)]) / this.prices[Math.max(0, this.prices.length - 11)] * 100 : 0;
908
+ const maxDrawdown = this.calculateMaxDrawdown(this.prices);
909
+ const atrValues = this.calculateAtr(this.prices, this.highs, this.lows, this.volumes);
910
+ const atr = atrValues.length > 0 ? atrValues[atrValues.length - 1] : 0;
911
+ const impliedVolatility = volatility;
912
+ const realizedVolatility = volatility;
913
+ const sharpeRatio = sessionReturn / volatility;
914
+ const sortinoRatio = sessionReturn / realizedVolatility;
915
+ const calmarRatio = sessionReturn / maxDrawdown;
916
+ const maxConsecutiveLosses = this.calculateMaxConsecutiveLosses(this.prices);
917
+ const winRate = this.calculateWinRate(this.prices);
918
+ const profitFactor = this.calculateProfitFactor(this.prices);
919
+ return {
920
+ currentPrice,
921
+ startPrice,
922
+ sessionHigh,
923
+ sessionLow,
924
+ totalVolume,
925
+ avgVolume,
926
+ volatility,
927
+ sessionReturn,
928
+ pricePosition,
929
+ trueVWAP,
930
+ momentum5,
931
+ momentum10,
932
+ maxDrawdown,
933
+ atr,
934
+ impliedVolatility,
935
+ realizedVolatility,
936
+ sharpeRatio,
937
+ sortinoRatio,
938
+ calmarRatio,
939
+ maxConsecutiveLosses,
940
+ winRate,
941
+ profitFactor
942
+ };
943
+ }
944
+ // Generate technical indicators
945
+ getTechnicalIndicators() {
946
+ return {
947
+ sma5: this.calculateSMA(this.prices, 5),
948
+ sma10: this.calculateSMA(this.prices, 10),
949
+ sma20: this.calculateSMA(this.prices, 20),
950
+ sma50: this.calculateSMA(this.prices, 50),
951
+ sma200: this.calculateSMA(this.prices, 200),
952
+ ema8: this.calculateEMA(this.prices, 8),
953
+ ema12: this.calculateEMA(this.prices, 12),
954
+ ema21: this.calculateEMA(this.prices, 21),
955
+ ema26: this.calculateEMA(this.prices, 26),
956
+ wma20: this.calculateWma(this.prices, 20),
957
+ vwma20: this.calculateVwma(this.prices, 20),
958
+ macd: this.calculateMacd(this.prices),
959
+ adx: this.calculateAdx(this.prices, this.highs, this.lows),
960
+ dmi: this.calculateDmi(this.prices, this.highs, this.lows),
961
+ ichimoku: this.calculateIchimoku(this.prices, this.highs, this.lows),
962
+ parabolicSAR: this.calculateParabolicSAR(this.prices, this.highs, this.lows),
963
+ rsi: this.calculateRSI(this.prices, 14),
964
+ stochastic: this.calculateStochastic(this.prices, this.highs, this.lows),
965
+ cci: this.calculateCci(this.prices, this.highs, this.lows),
966
+ roc: this.calculateRoc(this.prices),
967
+ williamsR: this.calculateWilliamsR(this.prices),
968
+ momentum: this.calculateMomentum(this.prices),
969
+ bollinger: this.calculateBollingerBands(this.prices, 20, 2),
970
+ atr: this.calculateAtr(this.prices, this.highs, this.lows, this.volumes),
971
+ keltner: this.calculateKeltnerChannels(this.prices, this.highs, this.lows),
972
+ donchian: this.calculateDonchianChannels(this.prices, this.highs, this.lows),
973
+ chaikinVolatility: this.calculateChaikinVolatility(this.prices, this.highs, this.lows),
974
+ obv: this.calculateObv(this.volumes),
975
+ cmf: this.calculateCmf(this.prices, this.highs, this.lows, this.volumes),
976
+ adl: this.calculateAdl(this.prices),
977
+ volumeROC: this.calculateVolumeROC(this.prices),
978
+ mfi: this.calculateMfi(this.prices, this.highs, this.lows, this.volumes),
979
+ vwap: this.calculateVwap(this.prices, this.volumes),
980
+ pivotPoints: this.calculatePivotPoints(this.prices),
981
+ fibonacci: this.calculateFibonacciLevels(this.prices),
982
+ gannLevels: this.calculateGannLevels(this.prices),
983
+ elliottWave: this.calculateElliottWave(this.prices),
984
+ harmonicPatterns: this.calculateHarmonicPatterns(this.prices)
985
+ };
986
+ }
987
+ // Generate trading signals
988
+ generateSignals() {
989
+ const analysis = this.analyze();
990
+ let bullishSignals = 0;
991
+ let bearishSignals = 0;
992
+ const signals = [];
993
+ if (analysis.currentPrice > analysis.trueVWAP) {
994
+ signals.push(
995
+ `\u2713 BULLISH: Price above VWAP (+${((analysis.currentPrice - analysis.trueVWAP) / analysis.trueVWAP * 100).toFixed(2)}%)`
996
+ );
997
+ bullishSignals++;
998
+ } else {
999
+ signals.push(
1000
+ `\u2717 BEARISH: Price below VWAP (${((analysis.currentPrice - analysis.trueVWAP) / analysis.trueVWAP * 100).toFixed(2)}%)`
1001
+ );
1002
+ bearishSignals++;
1003
+ }
1004
+ if (analysis.momentum5 > 0 && analysis.momentum10 > 0) {
1005
+ signals.push("\u2713 BULLISH: Positive momentum on both timeframes");
1006
+ bullishSignals++;
1007
+ } else if (analysis.momentum5 < 0 && analysis.momentum10 < 0) {
1008
+ signals.push("\u2717 BEARISH: Negative momentum on both timeframes");
1009
+ bearishSignals++;
1010
+ } else {
1011
+ signals.push("\u25D0 MIXED: Conflicting momentum signals");
1012
+ }
1013
+ const currentVolume = this.volumes[this.volumes.length - 1];
1014
+ const volumeRatio = currentVolume / analysis.avgVolume;
1015
+ if (volumeRatio > 1.2 && analysis.sessionReturn > 0) {
1016
+ signals.push("\u2713 BULLISH: Above-average volume supporting upward move");
1017
+ bullishSignals++;
1018
+ } else if (volumeRatio > 1.2 && analysis.sessionReturn < 0) {
1019
+ signals.push("\u2717 BEARISH: Above-average volume supporting downward move");
1020
+ bearishSignals++;
1021
+ } else {
1022
+ signals.push("\u25D0 NEUTRAL: Volume not providing clear direction");
1023
+ }
1024
+ if (analysis.pricePosition > 65 && analysis.volatility > 30) {
1025
+ signals.push("\u2717 BEARISH: High in range with elevated volatility - reversal risk");
1026
+ bearishSignals++;
1027
+ } else if (analysis.pricePosition < 35 && analysis.volatility > 30) {
1028
+ signals.push("\u2713 BULLISH: Low in range with volatility - potential bounce");
1029
+ bullishSignals++;
1030
+ } else {
1031
+ signals.push("\u25D0 NEUTRAL: Price position and volatility not extreme");
1032
+ }
1033
+ return { bullishSignals, bearishSignals, signals };
1034
+ }
1035
+ // Generate comprehensive JSON analysis
1036
+ generateJSONAnalysis(symbol) {
1037
+ const analysis = this.analyze();
1038
+ const indicators = this.getTechnicalIndicators();
1039
+ const signals = this.generateSignals();
1040
+ const currentSMA5 = indicators.sma5.length > 0 ? indicators.sma5[indicators.sma5.length - 1] : null;
1041
+ const currentSMA10 = indicators.sma10.length > 0 ? indicators.sma10[indicators.sma10.length - 1] : null;
1042
+ const currentSMA20 = indicators.sma20.length > 0 ? indicators.sma20[indicators.sma20.length - 1] : null;
1043
+ const currentSMA50 = indicators.sma50.length > 0 ? indicators.sma50[indicators.sma50.length - 1] : null;
1044
+ const currentSMA200 = indicators.sma200.length > 0 ? indicators.sma200[indicators.sma200.length - 1] : null;
1045
+ const currentEMA8 = indicators.ema8[indicators.ema8.length - 1];
1046
+ const currentEMA12 = indicators.ema12[indicators.ema12.length - 1];
1047
+ const currentEMA21 = indicators.ema21[indicators.ema21.length - 1];
1048
+ const currentEMA26 = indicators.ema26[indicators.ema26.length - 1];
1049
+ const currentWMA20 = indicators.wma20.length > 0 ? indicators.wma20[indicators.wma20.length - 1] : null;
1050
+ const currentVWMA20 = indicators.vwma20.length > 0 ? indicators.vwma20[indicators.vwma20.length - 1] : null;
1051
+ const currentMACD = indicators.macd.length > 0 ? indicators.macd[indicators.macd.length - 1] : null;
1052
+ const currentADX = indicators.adx.length > 0 ? indicators.adx[indicators.adx.length - 1] : null;
1053
+ const currentDMI = indicators.dmi.length > 0 ? indicators.dmi[indicators.dmi.length - 1] : null;
1054
+ const currentIchimoku = indicators.ichimoku.length > 0 ? indicators.ichimoku[indicators.ichimoku.length - 1] : null;
1055
+ const currentParabolicSAR = indicators.parabolicSAR.length > 0 ? indicators.parabolicSAR[indicators.parabolicSAR.length - 1] : null;
1056
+ const currentRSI = indicators.rsi.length > 0 ? indicators.rsi[indicators.rsi.length - 1] : null;
1057
+ const currentStochastic = indicators.stochastic.length > 0 ? indicators.stochastic[indicators.stochastic.length - 1] : null;
1058
+ const currentCCI = indicators.cci.length > 0 ? indicators.cci[indicators.cci.length - 1] : null;
1059
+ const currentROC = indicators.roc.length > 0 ? indicators.roc[indicators.roc.length - 1] : null;
1060
+ const currentWilliamsR = indicators.williamsR.length > 0 ? indicators.williamsR[indicators.williamsR.length - 1] : null;
1061
+ const currentMomentum = indicators.momentum.length > 0 ? indicators.momentum[indicators.momentum.length - 1] : null;
1062
+ const currentBB = indicators.bollinger.length > 0 ? indicators.bollinger[indicators.bollinger.length - 1] : null;
1063
+ const currentAtr = indicators.atr.length > 0 ? indicators.atr[indicators.atr.length - 1] : null;
1064
+ const currentKeltner = indicators.keltner.length > 0 ? indicators.keltner[indicators.keltner.length - 1] : null;
1065
+ const currentDonchian = indicators.donchian.length > 0 ? indicators.donchian[indicators.donchian.length - 1] : null;
1066
+ const currentChaikinVolatility = indicators.chaikinVolatility.length > 0 ? indicators.chaikinVolatility[indicators.chaikinVolatility.length - 1] : null;
1067
+ const currentObv = indicators.obv.length > 0 ? indicators.obv[indicators.obv.length - 1] : null;
1068
+ const currentCmf = indicators.cmf.length > 0 ? indicators.cmf[indicators.cmf.length - 1] : null;
1069
+ const currentAdl = indicators.adl.length > 0 ? indicators.adl[indicators.adl.length - 1] : null;
1070
+ const currentVolumeROC = indicators.volumeROC.length > 0 ? indicators.volumeROC[indicators.volumeROC.length - 1] : null;
1071
+ const currentMfi = indicators.mfi.length > 0 ? indicators.mfi[indicators.mfi.length - 1] : null;
1072
+ const currentVwap = indicators.vwap.length > 0 ? indicators.vwap[indicators.vwap.length - 1] : null;
1073
+ const currentPivotPoints = indicators.pivotPoints.length > 0 ? indicators.pivotPoints[indicators.pivotPoints.length - 1] : null;
1074
+ const currentFibonacci = indicators.fibonacci.length > 0 ? indicators.fibonacci[indicators.fibonacci.length - 1] : null;
1075
+ const currentGannLevels = indicators.gannLevels.length > 0 ? indicators.gannLevels : [];
1076
+ const currentElliottWave = indicators.elliottWave.length > 0 ? indicators.elliottWave[indicators.elliottWave.length - 1] : null;
1077
+ const currentHarmonicPatterns = indicators.harmonicPatterns.length > 0 ? indicators.harmonicPatterns : [];
1078
+ const currentVolume = this.volumes[this.volumes.length - 1];
1079
+ const volumeRatio = currentVolume / analysis.avgVolume;
1080
+ const currentDrawdown = (analysis.sessionHigh - analysis.currentPrice) / analysis.sessionHigh * 100;
1081
+ const rangeWidth = (analysis.sessionHigh - analysis.sessionLow) / analysis.sessionLow * 100;
1082
+ const priceVsVWAP = (analysis.currentPrice - analysis.trueVWAP) / analysis.trueVWAP * 100;
1083
+ const totalScore = signals.bullishSignals - signals.bearishSignals;
1084
+ const overallSignal = totalScore > 0 ? "BULLISH_BIAS" : totalScore < 0 ? "BEARISH_BIAS" : "NEUTRAL";
1085
+ const targetEntry = Math.max(analysis.sessionLow * 1.005, analysis.trueVWAP * 0.998);
1086
+ const stopLoss = analysis.sessionLow * 0.995;
1087
+ const profitTarget = analysis.sessionHigh * 0.995;
1088
+ const riskRewardRatio = (profitTarget - analysis.currentPrice) / (analysis.currentPrice - stopLoss);
1089
+ const positionSize = this.calculatePositionSize(analysis.currentPrice, targetEntry, stopLoss);
1090
+ const maxRisk = positionSize * (targetEntry - stopLoss);
1091
+ return {
1092
+ symbol,
1093
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1094
+ marketStructure: {
1095
+ currentPrice: analysis.currentPrice,
1096
+ startPrice: analysis.startPrice,
1097
+ sessionHigh: analysis.sessionHigh,
1098
+ sessionLow: analysis.sessionLow,
1099
+ rangeWidth,
1100
+ totalVolume: analysis.totalVolume,
1101
+ sessionPerformance: analysis.sessionReturn,
1102
+ positionInRange: analysis.pricePosition
1103
+ },
1104
+ volatility: {
1105
+ impliedVolatility: analysis.impliedVolatility,
1106
+ realizedVolatility: analysis.realizedVolatility,
1107
+ atr: analysis.atr,
1108
+ maxDrawdown: analysis.maxDrawdown * 100,
1109
+ currentDrawdown
1110
+ },
1111
+ technicalIndicators: {
1112
+ sma5: currentSMA5,
1113
+ sma10: currentSMA10,
1114
+ sma20: currentSMA20,
1115
+ sma50: currentSMA50,
1116
+ sma200: currentSMA200,
1117
+ ema8: currentEMA8,
1118
+ ema12: currentEMA12,
1119
+ ema21: currentEMA21,
1120
+ ema26: currentEMA26,
1121
+ wma20: currentWMA20,
1122
+ vwma20: currentVWMA20,
1123
+ macd: currentMACD,
1124
+ adx: currentADX,
1125
+ dmi: currentDMI,
1126
+ ichimoku: currentIchimoku,
1127
+ parabolicSAR: currentParabolicSAR,
1128
+ rsi: currentRSI,
1129
+ stochastic: currentStochastic,
1130
+ cci: currentCCI,
1131
+ roc: currentROC,
1132
+ williamsR: currentWilliamsR,
1133
+ momentum: currentMomentum,
1134
+ bollingerBands: currentBB ? {
1135
+ upper: currentBB.upper,
1136
+ middle: currentBB.middle,
1137
+ lower: currentBB.lower,
1138
+ bandwidth: currentBB.bandwidth,
1139
+ percentB: currentBB.percentB
1140
+ } : null,
1141
+ atr: currentAtr,
1142
+ keltnerChannels: currentKeltner ? {
1143
+ upper: currentKeltner.upper,
1144
+ middle: currentKeltner.middle,
1145
+ lower: currentKeltner.lower
1146
+ } : null,
1147
+ donchianChannels: currentDonchian ? {
1148
+ upper: currentDonchian.upper,
1149
+ middle: currentDonchian.middle,
1150
+ lower: currentDonchian.lower
1151
+ } : null,
1152
+ chaikinVolatility: currentChaikinVolatility,
1153
+ obv: currentObv,
1154
+ cmf: currentCmf,
1155
+ adl: currentAdl,
1156
+ volumeROC: currentVolumeROC,
1157
+ mfi: currentMfi,
1158
+ vwap: currentVwap
1159
+ },
1160
+ volumeAnalysis: {
1161
+ currentVolume,
1162
+ averageVolume: Math.round(analysis.avgVolume),
1163
+ volumeRatio,
1164
+ trueVWAP: analysis.trueVWAP,
1165
+ priceVsVWAP,
1166
+ obv: currentObv,
1167
+ cmf: currentCmf,
1168
+ mfi: currentMfi
1169
+ },
1170
+ momentum: {
1171
+ momentum5: analysis.momentum5,
1172
+ momentum10: analysis.momentum10,
1173
+ sessionROC: analysis.sessionReturn,
1174
+ rsi: currentRSI,
1175
+ stochastic: currentStochastic,
1176
+ cci: currentCCI
1177
+ },
1178
+ supportResistance: {
1179
+ pivotPoints: currentPivotPoints,
1180
+ fibonacci: currentFibonacci,
1181
+ gannLevels: currentGannLevels,
1182
+ elliottWave: currentElliottWave,
1183
+ harmonicPatterns: currentHarmonicPatterns
1184
+ },
1185
+ tradingSignals: {
1186
+ ...signals,
1187
+ overallSignal,
1188
+ signalScore: totalScore,
1189
+ confidence: this.calculateConfidence(signals.signals),
1190
+ riskLevel: this.calculateRiskLevel(analysis.volatility)
1191
+ },
1192
+ statisticalModels: {
1193
+ zScore: this.calculateZScore(analysis.currentPrice, analysis.startPrice, analysis.avgVolume),
1194
+ ornsteinUhlenbeck: this.calculateOrnsteinUhlenbeck(
1195
+ analysis.currentPrice,
1196
+ analysis.startPrice,
1197
+ analysis.avgVolume
1198
+ ),
1199
+ kalmanFilter: this.calculateKalmanFilter(
1200
+ analysis.currentPrice,
1201
+ analysis.startPrice,
1202
+ analysis.avgVolume
1203
+ ),
1204
+ arima: this.calculateArima(analysis.currentPrice, analysis.startPrice, analysis.avgVolume),
1205
+ garch: this.calculateGarch(analysis.currentPrice, analysis.startPrice, analysis.avgVolume),
1206
+ hilbertTransform: this.calculateHilbertTransform(
1207
+ analysis.currentPrice,
1208
+ analysis.startPrice,
1209
+ analysis.avgVolume
1210
+ ),
1211
+ waveletTransform: this.calculateWaveletTransform(
1212
+ analysis.currentPrice,
1213
+ analysis.startPrice,
1214
+ analysis.avgVolume
1215
+ )
1216
+ },
1217
+ optionsAnalysis: (() => {
1218
+ const blackScholes = this.calculateBlackScholes(
1219
+ analysis.currentPrice,
1220
+ analysis.startPrice,
1221
+ analysis.avgVolume
1222
+ );
1223
+ if (!blackScholes) return null;
1224
+ return {
1225
+ blackScholes,
1226
+ impliedVolatility: analysis.impliedVolatility,
1227
+ delta: blackScholes.delta,
1228
+ gamma: blackScholes.gamma,
1229
+ theta: blackScholes.theta,
1230
+ vega: blackScholes.vega,
1231
+ rho: blackScholes.rho,
1232
+ greeks: {
1233
+ delta: blackScholes.delta,
1234
+ gamma: blackScholes.gamma,
1235
+ theta: blackScholes.theta,
1236
+ vega: blackScholes.vega,
1237
+ rho: blackScholes.rho
1238
+ }
1239
+ };
1240
+ })(),
1241
+ riskManagement: {
1242
+ targetEntry,
1243
+ stopLoss,
1244
+ profitTarget,
1245
+ riskRewardRatio,
1246
+ positionSize,
1247
+ maxRisk
1248
+ },
1249
+ performance: {
1250
+ sharpeRatio: analysis.sharpeRatio,
1251
+ sortinoRatio: analysis.sortinoRatio,
1252
+ calmarRatio: analysis.calmarRatio,
1253
+ maxDrawdown: analysis.maxDrawdown * 100,
1254
+ winRate: analysis.winRate,
1255
+ profitFactor: analysis.profitFactor,
1256
+ totalReturn: analysis.sessionReturn,
1257
+ volatility: analysis.volatility
279
1258
  }
280
- return result;
281
1259
  };
282
- this.server.setRequestHandler(import_types.ListResourcesRequestSchema, async () => {
1260
+ }
1261
+ };
1262
+ var createTechnicalAnalysisHandler = (marketDataPrices) => {
1263
+ return async (args) => {
1264
+ try {
1265
+ const symbol = args.symbol;
1266
+ const priceHistory = marketDataPrices.get(symbol) || [];
1267
+ if (priceHistory.length === 0) {
1268
+ return {
1269
+ content: [
1270
+ {
1271
+ type: "text",
1272
+ text: `No price data available for ${symbol}. Please request market data first.`,
1273
+ uri: "technicalAnalysis"
1274
+ }
1275
+ ]
1276
+ };
1277
+ }
1278
+ const hasValidData = priceHistory.every(
1279
+ (entry) => typeof entry.trade === "number" && !Number.isNaN(entry.trade) && typeof entry.midPrice === "number" && !Number.isNaN(entry.midPrice)
1280
+ );
1281
+ if (!hasValidData) {
1282
+ throw new Error("Invalid market data");
1283
+ }
1284
+ const analyzer = new TechnicalAnalyzer(priceHistory);
1285
+ const analysis = analyzer.generateJSONAnalysis(symbol);
283
1286
  return {
284
- resources: []
1287
+ content: [
1288
+ {
1289
+ type: "text",
1290
+ text: `Technical Analysis for ${symbol}:
1291
+
1292
+ ${JSON.stringify(analysis, null, 2)}`,
1293
+ uri: "technicalAnalysis"
1294
+ }
1295
+ ]
285
1296
  };
286
- });
287
- this.server.setRequestHandler(import_types.ListToolsRequestSchema, async () => {
1297
+ } catch (error) {
288
1298
  return {
289
- tools: [
290
- {
291
- name: "parse",
292
- description: "Parses a FIX message and describes it in plain language",
293
- inputSchema: parseInputSchema
294
- },
1299
+ content: [
295
1300
  {
296
- name: "parseToJSON",
297
- description: "Parses a FIX message into JSON",
298
- inputSchema: parseToJSONInputSchema
299
- },
300
- {
301
- name: "newOrderSingle",
302
- description: "Creates and sends a New Order Single",
303
- inputSchema: newOrderSingleInputSchema
304
- },
1301
+ type: "text",
1302
+ text: `Error performing technical analysis: ${error instanceof Error ? error.message : "Unknown error"}`,
1303
+ uri: "technicalAnalysis"
1304
+ }
1305
+ ],
1306
+ isError: true
1307
+ };
1308
+ }
1309
+ };
1310
+ };
1311
+
1312
+ // src/tools/marketData.ts
1313
+ var import_fixparser = require("fixparser");
1314
+ var import_quickchart_js = __toESM(require("quickchart-js"), 1);
1315
+ var createMarketDataRequestHandler = (parser, pendingRequests) => {
1316
+ return async (args) => {
1317
+ try {
1318
+ parser.logger.log({
1319
+ level: "info",
1320
+ message: `Sending market data request for symbols: ${args.symbols.join(", ")}`
1321
+ });
1322
+ const response = new Promise((resolve) => {
1323
+ pendingRequests.set(args.mdReqID, resolve);
1324
+ parser.logger.log({
1325
+ level: "info",
1326
+ message: `Registered callback for market data request ID: ${args.mdReqID}`
1327
+ });
1328
+ });
1329
+ const entryTypes = args.mdEntryTypes || [
1330
+ import_fixparser.MDEntryType.Bid,
1331
+ import_fixparser.MDEntryType.Offer,
1332
+ import_fixparser.MDEntryType.Trade,
1333
+ import_fixparser.MDEntryType.IndexValue,
1334
+ import_fixparser.MDEntryType.OpeningPrice,
1335
+ import_fixparser.MDEntryType.ClosingPrice,
1336
+ import_fixparser.MDEntryType.SettlementPrice,
1337
+ import_fixparser.MDEntryType.TradingSessionHighPrice,
1338
+ import_fixparser.MDEntryType.TradingSessionLowPrice,
1339
+ import_fixparser.MDEntryType.VWAP,
1340
+ import_fixparser.MDEntryType.Imbalance,
1341
+ import_fixparser.MDEntryType.TradeVolume,
1342
+ import_fixparser.MDEntryType.OpenInterest,
1343
+ import_fixparser.MDEntryType.CompositeUnderlyingPrice,
1344
+ import_fixparser.MDEntryType.SimulatedSellPrice,
1345
+ import_fixparser.MDEntryType.SimulatedBuyPrice,
1346
+ import_fixparser.MDEntryType.MarginRate,
1347
+ import_fixparser.MDEntryType.MidPrice,
1348
+ import_fixparser.MDEntryType.EmptyBook,
1349
+ import_fixparser.MDEntryType.SettleHighPrice,
1350
+ import_fixparser.MDEntryType.SettleLowPrice,
1351
+ import_fixparser.MDEntryType.PriorSettlePrice,
1352
+ import_fixparser.MDEntryType.SessionHighBid,
1353
+ import_fixparser.MDEntryType.SessionLowOffer,
1354
+ import_fixparser.MDEntryType.EarlyPrices,
1355
+ import_fixparser.MDEntryType.AuctionClearingPrice,
1356
+ import_fixparser.MDEntryType.SwapValueFactor,
1357
+ import_fixparser.MDEntryType.DailyValueAdjustmentForLongPositions,
1358
+ import_fixparser.MDEntryType.CumulativeValueAdjustmentForLongPositions,
1359
+ import_fixparser.MDEntryType.DailyValueAdjustmentForShortPositions,
1360
+ import_fixparser.MDEntryType.CumulativeValueAdjustmentForShortPositions,
1361
+ import_fixparser.MDEntryType.FixingPrice,
1362
+ import_fixparser.MDEntryType.CashRate,
1363
+ import_fixparser.MDEntryType.RecoveryRate,
1364
+ import_fixparser.MDEntryType.RecoveryRateForLong,
1365
+ import_fixparser.MDEntryType.RecoveryRateForShort,
1366
+ import_fixparser.MDEntryType.MarketBid,
1367
+ import_fixparser.MDEntryType.MarketOffer,
1368
+ import_fixparser.MDEntryType.ShortSaleMinPrice,
1369
+ import_fixparser.MDEntryType.PreviousClosingPrice,
1370
+ import_fixparser.MDEntryType.ThresholdLimitPriceBanding,
1371
+ import_fixparser.MDEntryType.DailyFinancingValue,
1372
+ import_fixparser.MDEntryType.AccruedFinancingValue,
1373
+ import_fixparser.MDEntryType.TWAP
1374
+ ];
1375
+ const messageFields = [
1376
+ new import_fixparser.Field(import_fixparser.Fields.MsgType, import_fixparser.Messages.MarketDataRequest),
1377
+ new import_fixparser.Field(import_fixparser.Fields.SenderCompID, parser.sender),
1378
+ new import_fixparser.Field(import_fixparser.Fields.MsgSeqNum, parser.getNextTargetMsgSeqNum()),
1379
+ new import_fixparser.Field(import_fixparser.Fields.TargetCompID, parser.target),
1380
+ new import_fixparser.Field(import_fixparser.Fields.SendingTime, parser.getTimestamp()),
1381
+ new import_fixparser.Field(import_fixparser.Fields.MDReqID, args.mdReqID),
1382
+ new import_fixparser.Field(import_fixparser.Fields.SubscriptionRequestType, args.subscriptionRequestType),
1383
+ new import_fixparser.Field(import_fixparser.Fields.MarketDepth, 0),
1384
+ new import_fixparser.Field(import_fixparser.Fields.MDUpdateType, args.mdUpdateType)
1385
+ ];
1386
+ messageFields.push(new import_fixparser.Field(import_fixparser.Fields.NoRelatedSym, args.symbols.length));
1387
+ args.symbols.forEach((symbol) => {
1388
+ messageFields.push(new import_fixparser.Field(import_fixparser.Fields.Symbol, symbol));
1389
+ });
1390
+ messageFields.push(new import_fixparser.Field(import_fixparser.Fields.NoMDEntryTypes, entryTypes.length));
1391
+ entryTypes.forEach((entryType) => {
1392
+ messageFields.push(new import_fixparser.Field(import_fixparser.Fields.MDEntryType, entryType));
1393
+ });
1394
+ const mdr = parser.createMessage(...messageFields);
1395
+ if (!parser.connected) {
1396
+ parser.logger.log({
1397
+ level: "error",
1398
+ message: "Not connected. Cannot send market data request."
1399
+ });
1400
+ return {
1401
+ content: [
1402
+ {
1403
+ type: "text",
1404
+ text: "Error: Not connected. Ignoring message.",
1405
+ uri: "marketDataRequest"
1406
+ }
1407
+ ],
1408
+ isError: true
1409
+ };
1410
+ }
1411
+ parser.logger.log({
1412
+ level: "info",
1413
+ message: `Sending market data request message: ${JSON.stringify(mdr?.toFIXJSON())}`
1414
+ });
1415
+ parser.send(mdr);
1416
+ const fixData = await response;
1417
+ parser.logger.log({
1418
+ level: "info",
1419
+ message: `Received market data response for request ID: ${args.mdReqID}`
1420
+ });
1421
+ return {
1422
+ content: [
305
1423
  {
306
- name: "marketDataRequest",
307
- description: "Sends a request for Market Data with the given symbol",
308
- inputSchema: marketDataRequestInputSchema
1424
+ type: "text",
1425
+ text: `Market data for ${args.symbols.join(", ")}: ${JSON.stringify(fixData.toFIXJSON())}`,
1426
+ uri: "marketDataRequest"
309
1427
  }
310
1428
  ]
311
1429
  };
312
- });
313
- this.server.setRequestHandler(import_types.CallToolRequestSchema, async (request) => {
314
- const { name, arguments: args } = request.params;
315
- switch (name) {
316
- case "parse": {
317
- try {
318
- const { fixString } = validateArgs(args, parseInputSchema);
319
- const parsedMessage = this.parser?.parse(fixString);
320
- if (!parsedMessage || parsedMessage.length === 0) {
321
- return {
322
- isError: true,
323
- content: [{ type: "text", text: "Error: Failed to parse FIX string" }]
324
- };
325
- }
326
- return {
327
- content: [
328
- {
329
- type: "text",
330
- text: `Parsed FIX message: ${fixString} (placeholder implementation)`
331
- }
332
- ]
333
- };
334
- } catch (error) {
335
- return {
336
- isError: true,
337
- content: [
338
- {
339
- type: "text",
340
- text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`
341
- }
342
- ]
343
- };
1430
+ } catch (error) {
1431
+ return {
1432
+ content: [
1433
+ {
1434
+ type: "text",
1435
+ text: `Error: ${error instanceof Error ? error.message : "Failed to request market data"}`,
1436
+ uri: "marketDataRequest"
344
1437
  }
345
- }
346
- case "parseToJSON": {
347
- try {
348
- const { fixString } = validateArgs(args, parseToJSONInputSchema);
349
- const parsedMessage = this.parser?.parse(fixString);
350
- if (!parsedMessage || parsedMessage.length === 0) {
351
- return {
352
- isError: true,
353
- content: [{ type: "text", text: "Error: Failed to parse FIX string" }]
354
- };
1438
+ ],
1439
+ isError: true
1440
+ };
1441
+ }
1442
+ };
1443
+ };
1444
+ var createGetStockGraphHandler = (marketDataPrices) => {
1445
+ return async (args) => {
1446
+ try {
1447
+ const symbol = args.symbol;
1448
+ const priceHistory = marketDataPrices.get(symbol) || [];
1449
+ if (priceHistory.length === 0) {
1450
+ return {
1451
+ content: [
1452
+ {
1453
+ type: "text",
1454
+ text: `No price data available for ${symbol}`,
1455
+ uri: "getStockGraph"
355
1456
  }
356
- return {
357
- content: [
358
- {
359
- type: "text",
360
- text: JSON.stringify({ fixString, parsed: "placeholder" })
361
- }
362
- ]
363
- };
364
- } catch (error) {
365
- return {
366
- isError: true,
367
- content: [
368
- {
369
- type: "text",
370
- text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`
371
- }
372
- ]
373
- };
374
- }
375
- }
376
- case "newOrderSingle": {
377
- try {
378
- const { clOrdID, handlInst, quantity, price, ordType, side, symbol, timeInForce } = validateArgs(args, newOrderSingleInputSchema);
379
- const response = new Promise((resolve) => {
380
- this.pendingRequests.set(clOrdID, resolve);
381
- });
382
- const order = this.parser?.createMessage(
383
- new import_fixparser.Field(import_fixparser.Fields.MsgType, import_fixparser.Messages.NewOrderSingle),
384
- new import_fixparser.Field(import_fixparser.Fields.MsgSeqNum, this.parser?.getNextTargetMsgSeqNum()),
385
- new import_fixparser.Field(import_fixparser.Fields.SenderCompID, this.parser?.sender),
386
- new import_fixparser.Field(import_fixparser.Fields.TargetCompID, this.parser?.target),
387
- new import_fixparser.Field(import_fixparser.Fields.SendingTime, this.parser?.getTimestamp()),
388
- new import_fixparser.Field(import_fixparser.Fields.ClOrdID, clOrdID),
389
- new import_fixparser.Field(import_fixparser.Fields.Side, side),
390
- new import_fixparser.Field(import_fixparser.Fields.Symbol, symbol),
391
- new import_fixparser.Field(import_fixparser.Fields.OrderQty, quantity),
392
- new import_fixparser.Field(import_fixparser.Fields.Price, price),
393
- new import_fixparser.Field(import_fixparser.Fields.OrdType, ordType),
394
- new import_fixparser.Field(import_fixparser.Fields.HandlInst, handlInst),
395
- new import_fixparser.Field(import_fixparser.Fields.TimeInForce, timeInForce),
396
- new import_fixparser.Field(import_fixparser.Fields.TransactTime, this.parser?.getTimestamp())
397
- );
398
- if (!this.parser?.connected) {
399
- this.logger?.log({
400
- level: "error",
401
- message: "FIXParser (MCP): -- Not connected. Ignoring message."
402
- });
403
- return {
404
- isError: true,
405
- content: [
406
- {
407
- type: "text",
408
- text: "Error: Not connected. Ignoring message."
409
- }
410
- ]
411
- };
1457
+ ]
1458
+ };
1459
+ }
1460
+ const chart = new import_quickchart_js.default();
1461
+ chart.setWidth(1200);
1462
+ chart.setHeight(600);
1463
+ chart.setBackgroundColor("transparent");
1464
+ const labels = priceHistory.map((point) => new Date(point.timestamp).toLocaleTimeString());
1465
+ const bidData = priceHistory.map((point) => point.bid);
1466
+ const offerData = priceHistory.map((point) => point.offer);
1467
+ const spreadData = priceHistory.map((point) => point.spread);
1468
+ const volumeData = priceHistory.map((point) => point.volume);
1469
+ const tradeData = priceHistory.map((point) => point.trade);
1470
+ const vwapData = priceHistory.map((point) => point.vwap);
1471
+ const twapData = priceHistory.map((point) => point.twap);
1472
+ const config = {
1473
+ type: "line",
1474
+ data: {
1475
+ labels,
1476
+ datasets: [
1477
+ {
1478
+ label: "Bid",
1479
+ data: bidData,
1480
+ borderColor: "#28a745",
1481
+ backgroundColor: "rgba(40, 167, 69, 0.1)",
1482
+ fill: false,
1483
+ tension: 0.4
1484
+ },
1485
+ {
1486
+ label: "Offer",
1487
+ data: offerData,
1488
+ borderColor: "#dc3545",
1489
+ backgroundColor: "rgba(220, 53, 69, 0.1)",
1490
+ fill: false,
1491
+ tension: 0.4
1492
+ },
1493
+ {
1494
+ label: "Spread",
1495
+ data: spreadData,
1496
+ borderColor: "#6c757d",
1497
+ backgroundColor: "rgba(108, 117, 125, 0.1)",
1498
+ fill: false,
1499
+ tension: 0.4
1500
+ },
1501
+ {
1502
+ label: "Trade",
1503
+ data: tradeData,
1504
+ borderColor: "#ffc107",
1505
+ backgroundColor: "rgba(255, 193, 7, 0.1)",
1506
+ fill: false,
1507
+ tension: 0.4
1508
+ },
1509
+ {
1510
+ label: "VWAP",
1511
+ data: vwapData,
1512
+ borderColor: "#17a2b8",
1513
+ backgroundColor: "rgba(23, 162, 184, 0.1)",
1514
+ fill: false,
1515
+ tension: 0.4
1516
+ },
1517
+ {
1518
+ label: "TWAP",
1519
+ data: twapData,
1520
+ borderColor: "#6610f2",
1521
+ backgroundColor: "rgba(102, 16, 242, 0.1)",
1522
+ fill: false,
1523
+ tension: 0.4
1524
+ },
1525
+ {
1526
+ label: "Volume",
1527
+ data: volumeData,
1528
+ borderColor: "#007bff",
1529
+ backgroundColor: "rgba(0, 123, 255, 0.1)",
1530
+ fill: true,
1531
+ tension: 0.4
1532
+ }
1533
+ ]
1534
+ },
1535
+ options: {
1536
+ responsive: true,
1537
+ plugins: {
1538
+ title: {
1539
+ display: true,
1540
+ text: `${symbol} Market Data`
1541
+ }
1542
+ },
1543
+ scales: {
1544
+ y: {
1545
+ beginAtZero: false
412
1546
  }
413
- this.parser?.send(order);
414
- this.logger?.log({
415
- level: "info",
416
- message: `FIXParser (MCP): (${this.parser?.protocol?.toUpperCase()}): >> sent ${order?.description}`
417
- });
418
- const fixData = await response;
419
- return {
420
- content: [
421
- {
422
- type: "text",
423
- text: `Execution Report for order ${clOrdID}: ${JSON.stringify(fixData.toFIXJSON())}`
424
- }
425
- ]
426
- };
427
- } catch (error) {
428
- return {
429
- isError: true,
430
- content: [
431
- {
432
- type: "text",
433
- text: `Error: ${error instanceof Error ? error.message : "Failed to create order"}`
434
- }
435
- ]
436
- };
437
1547
  }
438
1548
  }
439
- case "marketDataRequest": {
440
- try {
441
- const { mdUpdateType, symbol, mdReqID, subscriptionRequestType, mdEntryType } = validateArgs(
442
- args,
443
- marketDataRequestInputSchema
444
- );
445
- const response = new Promise((resolve) => {
446
- this.pendingRequests.set(mdReqID, resolve);
447
- });
448
- const marketDataRequest = this.parser?.createMessage(
449
- new import_fixparser.Field(import_fixparser.Fields.MsgType, import_fixparser.Messages.MarketDataRequest),
450
- new import_fixparser.Field(import_fixparser.Fields.SenderCompID, this.parser?.sender),
451
- new import_fixparser.Field(import_fixparser.Fields.MsgSeqNum, this.parser?.getNextTargetMsgSeqNum()),
452
- new import_fixparser.Field(import_fixparser.Fields.TargetCompID, this.parser?.target),
453
- new import_fixparser.Field(import_fixparser.Fields.SendingTime, this.parser?.getTimestamp()),
454
- new import_fixparser.Field(import_fixparser.Fields.MarketDepth, 0),
455
- new import_fixparser.Field(import_fixparser.Fields.MDUpdateType, mdUpdateType),
456
- new import_fixparser.Field(import_fixparser.Fields.NoRelatedSym, 1),
457
- new import_fixparser.Field(import_fixparser.Fields.Symbol, symbol),
458
- new import_fixparser.Field(import_fixparser.Fields.MDReqID, mdReqID),
459
- new import_fixparser.Field(import_fixparser.Fields.SubscriptionRequestType, subscriptionRequestType),
460
- new import_fixparser.Field(import_fixparser.Fields.NoMDEntryTypes, 1),
461
- new import_fixparser.Field(import_fixparser.Fields.MDEntryType, mdEntryType)
462
- );
463
- if (!this.parser?.connected) {
464
- this.logger?.log({
465
- level: "error",
466
- message: "FIXParser (MCP): -- Not connected. Ignoring message."
467
- });
468
- return {
469
- isError: true,
470
- content: [
471
- {
472
- type: "text",
473
- text: "Error: Not connected. Ignoring message."
474
- }
475
- ]
476
- };
1549
+ };
1550
+ chart.setConfig(config);
1551
+ const imageBuffer = await chart.toBinary();
1552
+ const base64 = imageBuffer.toString("base64");
1553
+ return {
1554
+ content: [
1555
+ {
1556
+ type: "resource",
1557
+ resource: {
1558
+ uri: "resource://graph",
1559
+ mimeType: "image/png",
1560
+ blob: base64
477
1561
  }
478
- this.parser?.send(marketDataRequest);
479
- this.logger?.log({
480
- level: "info",
481
- message: `FIXParser (MCP): (${this.parser?.protocol?.toUpperCase()}): >> sent ${marketDataRequest?.description}`
482
- });
483
- const fixData = await response;
484
- return {
485
- content: [
486
- {
487
- type: "text",
488
- text: `Market data for ${symbol}: ${JSON.stringify(fixData.toFIXJSON())}`
489
- }
490
- ]
491
- };
492
- } catch (error) {
493
- return {
494
- isError: true,
495
- content: [
496
- {
497
- type: "text",
498
- text: `Error: ${error instanceof Error ? error.message : "Failed to request market data"}`
499
- }
500
- ]
501
- };
502
1562
  }
503
- }
504
- default:
505
- throw new Error(`Unknown tool: ${name}`);
1563
+ ]
1564
+ };
1565
+ } catch (error) {
1566
+ return {
1567
+ content: [
1568
+ {
1569
+ type: "text",
1570
+ text: `Error: ${error instanceof Error ? error.message : "Failed to generate graph"}`,
1571
+ uri: "getStockGraph"
1572
+ }
1573
+ ],
1574
+ isError: true
1575
+ };
1576
+ }
1577
+ };
1578
+ };
1579
+ var createGetStockPriceHistoryHandler = (marketDataPrices) => {
1580
+ return async (args) => {
1581
+ try {
1582
+ const symbol = args.symbol;
1583
+ const priceHistory = marketDataPrices.get(symbol) || [];
1584
+ if (priceHistory.length === 0) {
1585
+ return {
1586
+ content: [
1587
+ {
1588
+ type: "text",
1589
+ text: `No price data available for ${symbol}`,
1590
+ uri: "getStockPriceHistory"
1591
+ }
1592
+ ]
1593
+ };
506
1594
  }
507
- });
508
- this.server.setRequestHandler(import_types.ListPromptsRequestSchema, async () => {
509
1595
  return {
510
- prompts: [
1596
+ content: [
511
1597
  {
512
- name: "parse",
513
- description: "Parses a FIX message and describes it in plain language",
514
- arguments: [
1598
+ type: "text",
1599
+ text: JSON.stringify(
515
1600
  {
516
- name: "fixString",
517
- description: "FIX message string to parse",
518
- required: true
519
- }
520
- ]
521
- },
1601
+ symbol,
1602
+ count: priceHistory.length,
1603
+ data: priceHistory.map((point) => ({
1604
+ timestamp: new Date(point.timestamp).toISOString(),
1605
+ bid: point.bid,
1606
+ offer: point.offer,
1607
+ spread: point.spread,
1608
+ volume: point.volume,
1609
+ trade: point.trade,
1610
+ indexValue: point.indexValue,
1611
+ openingPrice: point.openingPrice,
1612
+ closingPrice: point.closingPrice,
1613
+ settlementPrice: point.settlementPrice,
1614
+ tradingSessionHighPrice: point.tradingSessionHighPrice,
1615
+ tradingSessionLowPrice: point.tradingSessionLowPrice,
1616
+ vwap: point.vwap,
1617
+ imbalance: point.imbalance,
1618
+ openInterest: point.openInterest,
1619
+ compositeUnderlyingPrice: point.compositeUnderlyingPrice,
1620
+ simulatedSellPrice: point.simulatedSellPrice,
1621
+ simulatedBuyPrice: point.simulatedBuyPrice,
1622
+ marginRate: point.marginRate,
1623
+ midPrice: point.midPrice,
1624
+ emptyBook: point.emptyBook,
1625
+ settleHighPrice: point.settleHighPrice,
1626
+ settleLowPrice: point.settleLowPrice,
1627
+ priorSettlePrice: point.priorSettlePrice,
1628
+ sessionHighBid: point.sessionHighBid,
1629
+ sessionLowOffer: point.sessionLowOffer,
1630
+ earlyPrices: point.earlyPrices,
1631
+ auctionClearingPrice: point.auctionClearingPrice,
1632
+ swapValueFactor: point.swapValueFactor,
1633
+ dailyValueAdjustmentForLongPositions: point.dailyValueAdjustmentForLongPositions,
1634
+ cumulativeValueAdjustmentForLongPositions: point.cumulativeValueAdjustmentForLongPositions,
1635
+ dailyValueAdjustmentForShortPositions: point.dailyValueAdjustmentForShortPositions,
1636
+ cumulativeValueAdjustmentForShortPositions: point.cumulativeValueAdjustmentForShortPositions,
1637
+ fixingPrice: point.fixingPrice,
1638
+ cashRate: point.cashRate,
1639
+ recoveryRate: point.recoveryRate,
1640
+ recoveryRateForLong: point.recoveryRateForLong,
1641
+ recoveryRateForShort: point.recoveryRateForShort,
1642
+ marketBid: point.marketBid,
1643
+ marketOffer: point.marketOffer,
1644
+ shortSaleMinPrice: point.shortSaleMinPrice,
1645
+ previousClosingPrice: point.previousClosingPrice,
1646
+ thresholdLimitPriceBanding: point.thresholdLimitPriceBanding,
1647
+ dailyFinancingValue: point.dailyFinancingValue,
1648
+ accruedFinancingValue: point.accruedFinancingValue,
1649
+ twap: point.twap
1650
+ }))
1651
+ },
1652
+ null,
1653
+ 2
1654
+ ),
1655
+ uri: "getStockPriceHistory"
1656
+ }
1657
+ ]
1658
+ };
1659
+ } catch (error) {
1660
+ return {
1661
+ content: [
522
1662
  {
523
- name: "parseToJSON",
524
- description: "Parses a FIX message into JSON",
525
- arguments: [
526
- {
527
- name: "fixString",
528
- description: "FIX message string to parse",
529
- required: true
530
- }
531
- ]
532
- },
1663
+ type: "text",
1664
+ text: `Error: ${error instanceof Error ? error.message : "Failed to get price history"}`,
1665
+ uri: "getStockPriceHistory"
1666
+ }
1667
+ ],
1668
+ isError: true
1669
+ };
1670
+ }
1671
+ };
1672
+ };
1673
+
1674
+ // src/tools/order.ts
1675
+ var import_fixparser2 = require("fixparser");
1676
+ var ordTypeNames = {
1677
+ "1": "Market",
1678
+ "2": "Limit",
1679
+ "3": "Stop",
1680
+ "4": "StopLimit",
1681
+ "5": "MarketOnClose",
1682
+ "6": "WithOrWithout",
1683
+ "7": "LimitOrBetter",
1684
+ "8": "LimitWithOrWithout",
1685
+ "9": "OnBasis",
1686
+ A: "OnClose",
1687
+ B: "LimitOnClose",
1688
+ C: "ForexMarket",
1689
+ D: "PreviouslyQuoted",
1690
+ E: "PreviouslyIndicated",
1691
+ F: "ForexLimit",
1692
+ G: "ForexSwap",
1693
+ H: "ForexPreviouslyQuoted",
1694
+ I: "Funari",
1695
+ J: "MarketIfTouched",
1696
+ K: "MarketWithLeftOverAsLimit",
1697
+ L: "PreviousFundValuationPoint",
1698
+ M: "NextFundValuationPoint",
1699
+ P: "Pegged",
1700
+ Q: "CounterOrderSelection",
1701
+ R: "StopOnBidOrOffer",
1702
+ S: "StopLimitOnBidOrOffer"
1703
+ };
1704
+ var sideNames = {
1705
+ "1": "Buy",
1706
+ "2": "Sell",
1707
+ "3": "BuyMinus",
1708
+ "4": "SellPlus",
1709
+ "5": "SellShort",
1710
+ "6": "SellShortExempt",
1711
+ "7": "Undisclosed",
1712
+ "8": "Cross",
1713
+ "9": "CrossShort",
1714
+ A: "CrossShortExempt",
1715
+ B: "AsDefined",
1716
+ C: "Opposite",
1717
+ D: "Subscribe",
1718
+ E: "Redeem",
1719
+ F: "Lend",
1720
+ G: "Borrow",
1721
+ H: "SellUndisclosed"
1722
+ };
1723
+ var timeInForceNames = {
1724
+ "0": "Day",
1725
+ "1": "GoodTillCancel",
1726
+ "2": "AtTheOpening",
1727
+ "3": "ImmediateOrCancel",
1728
+ "4": "FillOrKill",
1729
+ "5": "GoodTillCrossing",
1730
+ "6": "GoodTillDate",
1731
+ "7": "AtTheClose",
1732
+ "8": "GoodThroughCrossing",
1733
+ "9": "AtCrossing",
1734
+ A: "GoodForTime",
1735
+ B: "GoodForAuction",
1736
+ C: "GoodForMonth"
1737
+ };
1738
+ var handlInstNames = {
1739
+ "1": "AutomatedExecutionNoIntervention",
1740
+ "2": "AutomatedExecutionInterventionOK",
1741
+ "3": "ManualOrder"
1742
+ };
1743
+ var createVerifyOrderHandler = (parser, verifiedOrders) => {
1744
+ return async (args) => {
1745
+ try {
1746
+ verifiedOrders.set(args.clOrdID, {
1747
+ clOrdID: args.clOrdID,
1748
+ handlInst: args.handlInst,
1749
+ quantity: Number.parseFloat(String(args.quantity)),
1750
+ price: Number.parseFloat(String(args.price)),
1751
+ ordType: args.ordType,
1752
+ side: args.side,
1753
+ symbol: args.symbol,
1754
+ timeInForce: args.timeInForce
1755
+ });
1756
+ return {
1757
+ content: [
533
1758
  {
534
- name: "newOrderSingle",
535
- description: "Creates and sends a New Order Single",
536
- arguments: [
537
- {
538
- name: "clOrdID",
539
- description: "Client Order ID",
540
- required: true
541
- },
542
- {
543
- name: "handlInst",
544
- description: "Handling instruction",
545
- required: false
546
- },
547
- {
548
- name: "quantity",
549
- description: "Order quantity",
550
- required: true
551
- },
552
- {
553
- name: "price",
554
- description: "Order price",
555
- required: true
556
- },
557
- {
558
- name: "ordType",
559
- description: "Order type",
560
- required: false
561
- },
562
- {
563
- name: "side",
564
- description: "Order side (1=Buy, 2=Sell)",
565
- required: true
566
- },
567
- {
568
- name: "symbol",
569
- description: "Trading symbol",
570
- required: true
571
- },
572
- {
573
- name: "timeInForce",
574
- description: "Time in force",
575
- required: false
576
- }
577
- ]
578
- },
1759
+ type: "text",
1760
+ text: `VERIFICATION: All parameters valid. Ready to proceed with order execution.
1761
+
1762
+ Parameters verified:
1763
+ - ClOrdID: ${args.clOrdID}
1764
+ - HandlInst: ${args.handlInst} (${handlInstNames[args.handlInst]})
1765
+ - Quantity: ${args.quantity}
1766
+ - Price: ${args.price}
1767
+ - OrdType: ${args.ordType} (${ordTypeNames[args.ordType]})
1768
+ - Side: ${args.side} (${sideNames[args.side]})
1769
+ - Symbol: ${args.symbol}
1770
+ - TimeInForce: ${args.timeInForce} (${timeInForceNames[args.timeInForce]})
1771
+
1772
+ To execute this order, call the executeOrder tool with these exact same parameters. Important: The user has to explicitly confirm before executeOrder is called!`,
1773
+ uri: "verifyOrder"
1774
+ }
1775
+ ]
1776
+ };
1777
+ } catch (error) {
1778
+ return {
1779
+ content: [
579
1780
  {
580
- name: "marketDataRequest",
581
- description: "Sends a request for Market Data with the given symbol",
582
- arguments: [
583
- {
584
- name: "mdUpdateType",
585
- description: "Market data update type",
586
- required: false
587
- },
588
- {
589
- name: "symbol",
590
- description: "Trading symbol",
591
- required: true
592
- },
593
- {
594
- name: "mdReqID",
595
- description: "Market data request ID",
596
- required: true
597
- },
598
- {
599
- name: "subscriptionRequestType",
600
- description: "Subscription request type",
601
- required: false
602
- },
603
- {
604
- name: "mdEntryType",
605
- description: "Market data entry type",
606
- required: false
607
- }
608
- ]
1781
+ type: "text",
1782
+ text: `Error: ${error instanceof Error ? error.message : "Failed to verify order parameters"}`,
1783
+ uri: "verifyOrder"
1784
+ }
1785
+ ],
1786
+ isError: true
1787
+ };
1788
+ }
1789
+ };
1790
+ };
1791
+ var createExecuteOrderHandler = (parser, verifiedOrders, pendingRequests) => {
1792
+ return async (args) => {
1793
+ try {
1794
+ const verifiedOrder = verifiedOrders.get(args.clOrdID);
1795
+ if (!verifiedOrder) {
1796
+ return {
1797
+ content: [
1798
+ {
1799
+ type: "text",
1800
+ text: `Error: Order ${args.clOrdID} has not been verified. Please call verifyOrder first.`,
1801
+ uri: "executeOrder"
1802
+ }
1803
+ ],
1804
+ isError: true
1805
+ };
1806
+ }
1807
+ 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) {
1808
+ return {
1809
+ content: [
1810
+ {
1811
+ type: "text",
1812
+ text: "Error: Order parameters do not match the verified order. Please use the exact same parameters that were verified.",
1813
+ uri: "executeOrder"
1814
+ }
1815
+ ],
1816
+ isError: true
1817
+ };
1818
+ }
1819
+ const response = new Promise((resolve) => {
1820
+ pendingRequests.set(args.clOrdID, resolve);
1821
+ });
1822
+ const order = parser.createMessage(
1823
+ new import_fixparser2.Field(import_fixparser2.Fields.MsgType, import_fixparser2.Messages.NewOrderSingle),
1824
+ new import_fixparser2.Field(import_fixparser2.Fields.MsgSeqNum, parser.getNextTargetMsgSeqNum()),
1825
+ new import_fixparser2.Field(import_fixparser2.Fields.SenderCompID, parser.sender),
1826
+ new import_fixparser2.Field(import_fixparser2.Fields.TargetCompID, parser.target),
1827
+ new import_fixparser2.Field(import_fixparser2.Fields.SendingTime, parser.getTimestamp()),
1828
+ new import_fixparser2.Field(import_fixparser2.Fields.ClOrdID, args.clOrdID),
1829
+ new import_fixparser2.Field(import_fixparser2.Fields.Side, args.side),
1830
+ new import_fixparser2.Field(import_fixparser2.Fields.Symbol, args.symbol),
1831
+ new import_fixparser2.Field(import_fixparser2.Fields.OrderQty, Number.parseFloat(String(args.quantity))),
1832
+ new import_fixparser2.Field(import_fixparser2.Fields.Price, Number.parseFloat(String(args.price))),
1833
+ new import_fixparser2.Field(import_fixparser2.Fields.OrdType, args.ordType),
1834
+ new import_fixparser2.Field(import_fixparser2.Fields.HandlInst, args.handlInst),
1835
+ new import_fixparser2.Field(import_fixparser2.Fields.TimeInForce, args.timeInForce),
1836
+ new import_fixparser2.Field(import_fixparser2.Fields.TransactTime, parser.getTimestamp())
1837
+ );
1838
+ if (!parser.connected) {
1839
+ return {
1840
+ content: [
1841
+ {
1842
+ type: "text",
1843
+ text: "Error: Not connected. Ignoring message.",
1844
+ uri: "executeOrder"
1845
+ }
1846
+ ],
1847
+ isError: true
1848
+ };
1849
+ }
1850
+ parser.send(order);
1851
+ const fixData = await response;
1852
+ verifiedOrders.delete(args.clOrdID);
1853
+ return {
1854
+ content: [
1855
+ {
1856
+ type: "text",
1857
+ text: fixData.messageType === import_fixparser2.Messages.Reject ? `Reject message for order ${args.clOrdID}: ${JSON.stringify(fixData.toFIXJSON())}` : `Execution Report for order ${args.clOrdID}: ${JSON.stringify(fixData.toFIXJSON())}`,
1858
+ uri: "executeOrder"
1859
+ }
1860
+ ]
1861
+ };
1862
+ } catch (error) {
1863
+ return {
1864
+ content: [
1865
+ {
1866
+ type: "text",
1867
+ text: `Error: ${error instanceof Error ? error.message : "Failed to execute order"}`,
1868
+ uri: "executeOrder"
1869
+ }
1870
+ ],
1871
+ isError: true
1872
+ };
1873
+ }
1874
+ };
1875
+ };
1876
+
1877
+ // src/tools/parse.ts
1878
+ var createParseHandler = (parser) => {
1879
+ return async (args) => {
1880
+ try {
1881
+ const parsedMessage = parser.parse(args.fixString);
1882
+ if (!parsedMessage || parsedMessage.length === 0) {
1883
+ return {
1884
+ content: [
1885
+ {
1886
+ type: "text",
1887
+ text: "Error: Failed to parse FIX string",
1888
+ uri: "parse"
1889
+ }
1890
+ ],
1891
+ isError: true
1892
+ };
1893
+ }
1894
+ return {
1895
+ content: [
1896
+ {
1897
+ type: "text",
1898
+ text: `${parsedMessage[0].description}
1899
+ ${parsedMessage[0].messageTypeDescription}`,
1900
+ uri: "parse"
1901
+ }
1902
+ ]
1903
+ };
1904
+ } catch (error) {
1905
+ return {
1906
+ content: [
1907
+ {
1908
+ type: "text",
1909
+ text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`,
1910
+ uri: "parse"
1911
+ }
1912
+ ],
1913
+ isError: true
1914
+ };
1915
+ }
1916
+ };
1917
+ };
1918
+
1919
+ // src/tools/parseToJSON.ts
1920
+ var createParseToJSONHandler = (parser) => {
1921
+ return async (args) => {
1922
+ try {
1923
+ const parsedMessage = parser.parse(args.fixString);
1924
+ if (!parsedMessage || parsedMessage.length === 0) {
1925
+ return {
1926
+ content: [
1927
+ {
1928
+ type: "text",
1929
+ text: "Error: Failed to parse FIX string",
1930
+ uri: "parseToJSON"
1931
+ }
1932
+ ],
1933
+ isError: true
1934
+ };
1935
+ }
1936
+ return {
1937
+ content: [
1938
+ {
1939
+ type: "text",
1940
+ text: `${parsedMessage[0].toFIXJSON()}`,
1941
+ uri: "parseToJSON"
609
1942
  }
610
1943
  ]
611
1944
  };
1945
+ } catch (error) {
1946
+ return {
1947
+ content: [
1948
+ {
1949
+ type: "text",
1950
+ text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`,
1951
+ uri: "parseToJSON"
1952
+ }
1953
+ ],
1954
+ isError: true
1955
+ };
1956
+ }
1957
+ };
1958
+ };
1959
+
1960
+ // src/tools/index.ts
1961
+ var createToolHandlers = (parser, verifiedOrders, pendingRequests, marketDataPrices) => ({
1962
+ parse: createParseHandler(parser),
1963
+ parseToJSON: createParseToJSONHandler(parser),
1964
+ verifyOrder: createVerifyOrderHandler(parser, verifiedOrders),
1965
+ executeOrder: createExecuteOrderHandler(parser, verifiedOrders, pendingRequests),
1966
+ marketDataRequest: createMarketDataRequestHandler(parser, pendingRequests),
1967
+ getStockGraph: createGetStockGraphHandler(marketDataPrices),
1968
+ getStockPriceHistory: createGetStockPriceHistoryHandler(marketDataPrices),
1969
+ technicalAnalysis: createTechnicalAnalysisHandler(marketDataPrices)
1970
+ });
1971
+
1972
+ // src/utils/messageHandler.ts
1973
+ var import_fixparser3 = require("fixparser");
1974
+ function getEnumValue(enumObj, name) {
1975
+ return enumObj[name] || name;
1976
+ }
1977
+ function handleMessage(message, parser, pendingRequests, marketDataPrices, maxPriceHistory, onPriceUpdate) {
1978
+ const msgType = message.messageType;
1979
+ if (msgType === import_fixparser3.Messages.MarketDataSnapshotFullRefresh || msgType === import_fixparser3.Messages.MarketDataIncrementalRefresh) {
1980
+ const symbol = message.getField(import_fixparser3.Fields.Symbol)?.value;
1981
+ const fixJson = message.toFIXJSON();
1982
+ const entries = fixJson.Body?.NoMDEntries || [];
1983
+ const data = {
1984
+ timestamp: Date.now(),
1985
+ bid: 0,
1986
+ offer: 0,
1987
+ spread: 0,
1988
+ volume: 0,
1989
+ trade: 0,
1990
+ indexValue: 0,
1991
+ openingPrice: 0,
1992
+ closingPrice: 0,
1993
+ settlementPrice: 0,
1994
+ tradingSessionHighPrice: 0,
1995
+ tradingSessionLowPrice: 0,
1996
+ vwap: 0,
1997
+ imbalance: 0,
1998
+ openInterest: 0,
1999
+ compositeUnderlyingPrice: 0,
2000
+ simulatedSellPrice: 0,
2001
+ simulatedBuyPrice: 0,
2002
+ marginRate: 0,
2003
+ midPrice: 0,
2004
+ emptyBook: 0,
2005
+ settleHighPrice: 0,
2006
+ settleLowPrice: 0,
2007
+ priorSettlePrice: 0,
2008
+ sessionHighBid: 0,
2009
+ sessionLowOffer: 0,
2010
+ earlyPrices: 0,
2011
+ auctionClearingPrice: 0,
2012
+ swapValueFactor: 0,
2013
+ dailyValueAdjustmentForLongPositions: 0,
2014
+ cumulativeValueAdjustmentForLongPositions: 0,
2015
+ dailyValueAdjustmentForShortPositions: 0,
2016
+ cumulativeValueAdjustmentForShortPositions: 0,
2017
+ fixingPrice: 0,
2018
+ cashRate: 0,
2019
+ recoveryRate: 0,
2020
+ recoveryRateForLong: 0,
2021
+ recoveryRateForShort: 0,
2022
+ marketBid: 0,
2023
+ marketOffer: 0,
2024
+ shortSaleMinPrice: 0,
2025
+ previousClosingPrice: 0,
2026
+ thresholdLimitPriceBanding: 0,
2027
+ dailyFinancingValue: 0,
2028
+ accruedFinancingValue: 0,
2029
+ twap: 0
2030
+ };
2031
+ for (const entry of entries) {
2032
+ const entryType = entry.MDEntryType;
2033
+ const price = entry.MDEntryPx ? Number.parseFloat(entry.MDEntryPx) : 0;
2034
+ const size = entry.MDEntrySize ? Number.parseFloat(entry.MDEntrySize) : 0;
2035
+ const enumValue = getEnumValue(import_fixparser3.MDEntryType, entryType);
2036
+ switch (enumValue) {
2037
+ case import_fixparser3.MDEntryType.Bid:
2038
+ data.bid = price;
2039
+ break;
2040
+ case import_fixparser3.MDEntryType.Offer:
2041
+ data.offer = price;
2042
+ break;
2043
+ case import_fixparser3.MDEntryType.Trade:
2044
+ data.trade = price;
2045
+ break;
2046
+ case import_fixparser3.MDEntryType.IndexValue:
2047
+ data.indexValue = price;
2048
+ break;
2049
+ case import_fixparser3.MDEntryType.OpeningPrice:
2050
+ data.openingPrice = price;
2051
+ break;
2052
+ case import_fixparser3.MDEntryType.ClosingPrice:
2053
+ data.closingPrice = price;
2054
+ break;
2055
+ case import_fixparser3.MDEntryType.SettlementPrice:
2056
+ data.settlementPrice = price;
2057
+ break;
2058
+ case import_fixparser3.MDEntryType.TradingSessionHighPrice:
2059
+ data.tradingSessionHighPrice = price;
2060
+ break;
2061
+ case import_fixparser3.MDEntryType.TradingSessionLowPrice:
2062
+ data.tradingSessionLowPrice = price;
2063
+ break;
2064
+ case import_fixparser3.MDEntryType.VWAP:
2065
+ data.vwap = price;
2066
+ break;
2067
+ case import_fixparser3.MDEntryType.Imbalance:
2068
+ data.imbalance = size;
2069
+ break;
2070
+ case import_fixparser3.MDEntryType.TradeVolume:
2071
+ data.volume = size;
2072
+ break;
2073
+ case import_fixparser3.MDEntryType.OpenInterest:
2074
+ data.openInterest = size;
2075
+ break;
2076
+ case import_fixparser3.MDEntryType.CompositeUnderlyingPrice:
2077
+ data.compositeUnderlyingPrice = price;
2078
+ break;
2079
+ case import_fixparser3.MDEntryType.SimulatedSellPrice:
2080
+ data.simulatedSellPrice = price;
2081
+ break;
2082
+ case import_fixparser3.MDEntryType.SimulatedBuyPrice:
2083
+ data.simulatedBuyPrice = price;
2084
+ break;
2085
+ case import_fixparser3.MDEntryType.MarginRate:
2086
+ data.marginRate = price;
2087
+ break;
2088
+ case import_fixparser3.MDEntryType.MidPrice:
2089
+ data.midPrice = price;
2090
+ break;
2091
+ case import_fixparser3.MDEntryType.EmptyBook:
2092
+ data.emptyBook = 1;
2093
+ break;
2094
+ case import_fixparser3.MDEntryType.SettleHighPrice:
2095
+ data.settleHighPrice = price;
2096
+ break;
2097
+ case import_fixparser3.MDEntryType.SettleLowPrice:
2098
+ data.settleLowPrice = price;
2099
+ break;
2100
+ case import_fixparser3.MDEntryType.PriorSettlePrice:
2101
+ data.priorSettlePrice = price;
2102
+ break;
2103
+ case import_fixparser3.MDEntryType.SessionHighBid:
2104
+ data.sessionHighBid = price;
2105
+ break;
2106
+ case import_fixparser3.MDEntryType.SessionLowOffer:
2107
+ data.sessionLowOffer = price;
2108
+ break;
2109
+ case import_fixparser3.MDEntryType.EarlyPrices:
2110
+ data.earlyPrices = price;
2111
+ break;
2112
+ case import_fixparser3.MDEntryType.AuctionClearingPrice:
2113
+ data.auctionClearingPrice = price;
2114
+ break;
2115
+ case import_fixparser3.MDEntryType.SwapValueFactor:
2116
+ data.swapValueFactor = price;
2117
+ break;
2118
+ case import_fixparser3.MDEntryType.DailyValueAdjustmentForLongPositions:
2119
+ data.dailyValueAdjustmentForLongPositions = price;
2120
+ break;
2121
+ case import_fixparser3.MDEntryType.CumulativeValueAdjustmentForLongPositions:
2122
+ data.cumulativeValueAdjustmentForLongPositions = price;
2123
+ break;
2124
+ case import_fixparser3.MDEntryType.DailyValueAdjustmentForShortPositions:
2125
+ data.dailyValueAdjustmentForShortPositions = price;
2126
+ break;
2127
+ case import_fixparser3.MDEntryType.CumulativeValueAdjustmentForShortPositions:
2128
+ data.cumulativeValueAdjustmentForShortPositions = price;
2129
+ break;
2130
+ case import_fixparser3.MDEntryType.FixingPrice:
2131
+ data.fixingPrice = price;
2132
+ break;
2133
+ case import_fixparser3.MDEntryType.CashRate:
2134
+ data.cashRate = price;
2135
+ break;
2136
+ case import_fixparser3.MDEntryType.RecoveryRate:
2137
+ data.recoveryRate = price;
2138
+ break;
2139
+ case import_fixparser3.MDEntryType.RecoveryRateForLong:
2140
+ data.recoveryRateForLong = price;
2141
+ break;
2142
+ case import_fixparser3.MDEntryType.RecoveryRateForShort:
2143
+ data.recoveryRateForShort = price;
2144
+ break;
2145
+ case import_fixparser3.MDEntryType.MarketBid:
2146
+ data.marketBid = price;
2147
+ break;
2148
+ case import_fixparser3.MDEntryType.MarketOffer:
2149
+ data.marketOffer = price;
2150
+ break;
2151
+ case import_fixparser3.MDEntryType.ShortSaleMinPrice:
2152
+ data.shortSaleMinPrice = price;
2153
+ break;
2154
+ case import_fixparser3.MDEntryType.PreviousClosingPrice:
2155
+ data.previousClosingPrice = price;
2156
+ break;
2157
+ case import_fixparser3.MDEntryType.ThresholdLimitPriceBanding:
2158
+ data.thresholdLimitPriceBanding = price;
2159
+ break;
2160
+ case import_fixparser3.MDEntryType.DailyFinancingValue:
2161
+ data.dailyFinancingValue = price;
2162
+ break;
2163
+ case import_fixparser3.MDEntryType.AccruedFinancingValue:
2164
+ data.accruedFinancingValue = price;
2165
+ break;
2166
+ case import_fixparser3.MDEntryType.TWAP:
2167
+ data.twap = price;
2168
+ break;
2169
+ }
2170
+ }
2171
+ data.spread = data.offer - data.bid;
2172
+ if (!marketDataPrices.has(symbol)) {
2173
+ marketDataPrices.set(symbol, []);
2174
+ }
2175
+ const prices = marketDataPrices.get(symbol);
2176
+ prices.push(data);
2177
+ if (prices.length > maxPriceHistory) {
2178
+ prices.splice(0, prices.length - maxPriceHistory);
2179
+ }
2180
+ onPriceUpdate?.(symbol, data);
2181
+ const mdReqID = message.getField(import_fixparser3.Fields.MDReqID)?.value;
2182
+ if (mdReqID) {
2183
+ const callback = pendingRequests.get(mdReqID);
2184
+ if (callback) {
2185
+ callback(message);
2186
+ pendingRequests.delete(mdReqID);
2187
+ }
2188
+ }
2189
+ } else if (msgType === import_fixparser3.Messages.ExecutionReport) {
2190
+ const reqId = message.getField(import_fixparser3.Fields.ClOrdID)?.value;
2191
+ const callback = pendingRequests.get(reqId);
2192
+ if (callback) {
2193
+ callback(message);
2194
+ pendingRequests.delete(reqId);
2195
+ }
2196
+ }
2197
+ }
2198
+
2199
+ // src/MCPLocal.ts
2200
+ var MCPLocal = class extends MCPBase {
2201
+ /**
2202
+ * Map to store verified orders before execution
2203
+ * @private
2204
+ */
2205
+ verifiedOrders = /* @__PURE__ */ new Map();
2206
+ /**
2207
+ * Map to store pending requests and their callbacks
2208
+ * @private
2209
+ */
2210
+ pendingRequests = /* @__PURE__ */ new Map();
2211
+ /**
2212
+ * Map to store market data prices for each symbol
2213
+ * @private
2214
+ */
2215
+ marketDataPrices = /* @__PURE__ */ new Map();
2216
+ /**
2217
+ * Maximum number of price history entries to keep per symbol
2218
+ * @private
2219
+ */
2220
+ MAX_PRICE_HISTORY = 1e5;
2221
+ server = new import_server.Server(
2222
+ {
2223
+ name: "fixparser",
2224
+ version: "1.0.0"
2225
+ },
2226
+ {
2227
+ capabilities: {
2228
+ tools: Object.entries(toolSchemas).reduce(
2229
+ (acc, [name, { description, schema }]) => {
2230
+ acc[name] = {
2231
+ description,
2232
+ parameters: schema
2233
+ };
2234
+ return acc;
2235
+ },
2236
+ {}
2237
+ )
2238
+ }
2239
+ }
2240
+ );
2241
+ transport = new import_stdio.StdioServerTransport();
2242
+ constructor({ logger, onReady }) {
2243
+ super({ logger, onReady });
2244
+ }
2245
+ async register(parser) {
2246
+ this.parser = parser;
2247
+ this.parser.addOnMessageCallback((message) => {
2248
+ handleMessage(message, this.parser, this.pendingRequests, this.marketDataPrices, this.MAX_PRICE_HISTORY);
612
2249
  });
613
- this.server.setRequestHandler(import_types.GetPromptRequestSchema, async (request) => {
614
- const { name, arguments: args } = request.params;
615
- switch (name) {
616
- case "parse": {
617
- const fixString = args?.fixString || "";
618
- return {
619
- messages: [
620
- {
621
- role: "user",
622
- content: {
623
- type: "text",
624
- text: `Please parse and explain this FIX message: ${fixString}`
625
- }
626
- }
627
- ]
628
- };
629
- }
630
- case "parseToJSON": {
631
- const fixString = args?.fixString || "";
632
- return {
633
- messages: [
634
- {
635
- role: "user",
636
- content: {
637
- type: "text",
638
- text: `Please parse the FIX message to JSON: ${fixString}`
639
- }
640
- }
641
- ]
642
- };
643
- }
644
- case "newOrderSingle": {
645
- const { clOrdID, handlInst, quantity, price, ordType, side, symbol, timeInForce } = args || {};
646
- return {
647
- messages: [
648
- {
649
- role: "user",
650
- content: {
651
- type: "text",
652
- text: [
653
- "Create a New Order Single FIX message with the following parameters:",
654
- `- ClOrdID: ${clOrdID}`,
655
- `- HandlInst: ${handlInst ?? "default"}`,
656
- `- Quantity: ${quantity}`,
657
- `- Price: ${price}`,
658
- `- OrdType: ${ordType ?? "default (Market)"}`,
659
- `- Side: ${side}`,
660
- `- Symbol: ${symbol}`,
661
- `- TimeInForce: ${timeInForce ?? "default (Day)"}`,
662
- "",
663
- "Format the response as a JSON object with FIX tag numbers as keys and their corresponding values."
664
- ].join("\n")
665
- }
666
- }
667
- ]
668
- };
669
- }
670
- case "marketDataRequest": {
671
- const { mdUpdateType, symbol, mdReqID, subscriptionRequestType, mdEntryType } = args || {};
2250
+ this.addWorkflows();
2251
+ await this.server.connect(this.transport);
2252
+ if (this.onReady) {
2253
+ this.onReady();
2254
+ }
2255
+ }
2256
+ addWorkflows() {
2257
+ if (!this.parser) {
2258
+ return;
2259
+ }
2260
+ if (!this.server) {
2261
+ return;
2262
+ }
2263
+ this.server.setRequestHandler(import_zod.z.object({ method: import_zod.z.literal("tools/list") }), async () => {
2264
+ return {
2265
+ tools: Object.entries(toolSchemas).map(([name, { description, schema }]) => ({
2266
+ name,
2267
+ description,
2268
+ inputSchema: schema
2269
+ }))
2270
+ };
2271
+ });
2272
+ this.server.setRequestHandler(
2273
+ import_zod.z.object({
2274
+ method: import_zod.z.literal("tools/call"),
2275
+ params: import_zod.z.object({
2276
+ name: import_zod.z.string(),
2277
+ arguments: import_zod.z.any(),
2278
+ _meta: import_zod.z.object({
2279
+ progressToken: import_zod.z.number()
2280
+ }).optional()
2281
+ })
2282
+ }),
2283
+ async (request) => {
2284
+ const { name, arguments: args } = request.params;
2285
+ const toolHandlers = createToolHandlers(
2286
+ this.parser,
2287
+ this.verifiedOrders,
2288
+ this.pendingRequests,
2289
+ this.marketDataPrices
2290
+ );
2291
+ const handler = toolHandlers[name];
2292
+ if (!handler) {
672
2293
  return {
673
- messages: [
2294
+ content: [
674
2295
  {
675
- role: "user",
676
- content: {
677
- type: "text",
678
- text: [
679
- "Create a Market Data Request FIX message with the following parameters:",
680
- `- MDUpdateType: ${mdUpdateType ?? "default (0 = FullRefresh)"}`,
681
- `- Symbol: ${symbol}`,
682
- `- MDReqID: ${mdReqID}`,
683
- `- SubscriptionRequestType: ${subscriptionRequestType ?? "default (0 = Snapshot + Updates)"}`,
684
- `- MDEntryType: ${mdEntryType ?? "default (0 = Bid)"}`,
685
- "",
686
- "Format the response as a JSON object with FIX tag numbers as keys and their corresponding values."
687
- ].join("\n")
688
- }
2296
+ type: "text",
2297
+ text: `Tool not found: ${name}`,
2298
+ uri: name
689
2299
  }
690
- ]
2300
+ ],
2301
+ isError: true
691
2302
  };
692
2303
  }
693
- default:
694
- throw new Error(`Unknown prompt: ${name}`);
2304
+ const result = await handler(args);
2305
+ return {
2306
+ content: result.content,
2307
+ isError: result.isError
2308
+ };
695
2309
  }
696
- });
2310
+ );
697
2311
  process.on("SIGINT", async () => {
698
2312
  await this.server.close();
699
2313
  process.exit(0);