fixparser-plugin-mcp 9.1.7-74db6dbc → 9.1.7-81ea0211

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