fixparser-plugin-mcp 9.1.7-74db6dbc → 9.1.7-75ded9c1

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