fixparser-plugin-mcp 9.1.7-71fc8a2b → 9.1.7-74db6dbc

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,1285 +1,2494 @@
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 {
5
- CallToolRequestSchema,
6
- GetPromptRequestSchema,
7
- ListPromptsRequestSchema,
8
- ListResourcesRequestSchema,
9
- ListToolsRequestSchema
10
- } from "@modelcontextprotocol/sdk/types.js";
11
4
  import { z } from "zod";
12
5
 
13
- // ../../node_modules/zod-to-json-schema/dist/esm/Options.js
14
- var ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");
15
- var defaultOptions = {
16
- name: void 0,
17
- $refStrategy: "root",
18
- basePath: ["#"],
19
- effectStrategy: "input",
20
- pipeStrategy: "all",
21
- dateStrategy: "format:date-time",
22
- mapStrategy: "entries",
23
- removeAdditionalStrategy: "passthrough",
24
- allowedAdditionalProperties: true,
25
- rejectedAdditionalProperties: false,
26
- definitionPath: "definitions",
27
- target: "jsonSchema7",
28
- strictUnions: false,
29
- definitions: {},
30
- errorMessages: false,
31
- markdownDescription: false,
32
- patternStrategy: "escape",
33
- applyRegexFlags: false,
34
- emailStrategy: "format:email",
35
- base64Strategy: "contentEncoding:base64",
36
- nameStrategy: "ref"
37
- };
38
- var getDefaultOptions = (options) => typeof options === "string" ? {
39
- ...defaultOptions,
40
- name: options
41
- } : {
42
- ...defaultOptions,
43
- ...options
44
- };
45
-
46
- // ../../node_modules/zod-to-json-schema/dist/esm/Refs.js
47
- var getRefs = (options) => {
48
- const _options = getDefaultOptions(options);
49
- const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
50
- return {
51
- ..._options,
52
- currentPath,
53
- propertyPath: void 0,
54
- seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [
55
- def._def,
56
- {
57
- def: def._def,
58
- path: [..._options.basePath, _options.definitionPath, name],
59
- // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
60
- jsonSchema: void 0
61
- }
62
- ]))
63
- };
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
+ */
17
+ 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
+ }
64
47
  };
65
48
 
66
- // ../../node_modules/zod-to-json-schema/dist/esm/errorMessages.js
67
- function addErrorMessage(res, key, errorMessage, refs) {
68
- if (!refs?.errorMessages)
69
- return;
70
- if (errorMessage) {
71
- res.errorMessage = {
72
- ...res.errorMessage,
73
- [key]: errorMessage
74
- };
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"
207
+ },
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
+ ]
250
+ },
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
+ }
75
289
  }
76
- }
77
- function setResponseValueAndErrors(res, key, value, errorMessage, refs) {
78
- res[key] = value;
79
- addErrorMessage(res, key, errorMessage, refs);
80
- }
81
-
82
- // ../../node_modules/zod-to-json-schema/dist/esm/selectParser.js
83
- import { ZodFirstPartyTypeKind as ZodFirstPartyTypeKind3 } from "zod";
290
+ };
84
291
 
85
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/any.js
86
- function parseAnyDef() {
87
- return {};
292
+ // src/tools/analytics.ts
293
+ function sum(numbers) {
294
+ return numbers.reduce((acc, val) => acc + val, 0);
88
295
  }
89
-
90
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/array.js
91
- import { ZodFirstPartyTypeKind } from "zod";
92
- function parseArrayDef(def, refs) {
93
- const res = {
94
- type: "array"
95
- };
96
- if (def.type?._def && def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) {
97
- res.items = parseDef(def.type._def, {
98
- ...refs,
99
- currentPath: [...refs.currentPath, "items"]
100
- });
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);
101
306
  }
102
- if (def.minLength) {
103
- setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs);
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;
104
315
  }
105
- if (def.maxLength) {
106
- setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs);
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;
107
324
  }
108
- if (def.exactLength) {
109
- setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs);
110
- setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs);
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;
111
344
  }
112
- return res;
113
- }
114
-
115
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js
116
- function parseBigintDef(def, refs) {
117
- const res = {
118
- type: "integer",
119
- format: "int64"
120
- };
121
- if (!def.checks)
122
- return res;
123
- for (const check of def.checks) {
124
- switch (check.kind) {
125
- case "min":
126
- if (refs.target === "jsonSchema7") {
127
- if (check.inclusive) {
128
- setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
129
- } else {
130
- setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs);
131
- }
132
- } else {
133
- if (!check.inclusive) {
134
- res.exclusiveMinimum = true;
135
- }
136
- setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
137
- }
138
- break;
139
- case "max":
140
- if (refs.target === "jsonSchema7") {
141
- if (check.inclusive) {
142
- setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
143
- } else {
144
- setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs);
145
- }
146
- } else {
147
- if (!check.inclusive) {
148
- res.exclusiveMaximum = true;
149
- }
150
- setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
151
- }
152
- break;
153
- case "multipleOf":
154
- setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs);
155
- break;
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
+ });
156
364
  }
365
+ return bands;
157
366
  }
158
- return res;
159
- }
160
-
161
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js
162
- function parseBooleanDef() {
163
- return {
164
- type: "boolean"
165
- };
166
- }
167
-
168
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/branded.js
169
- function parseBrandedDef(_def, refs) {
170
- return parseDef(_def.type._def, refs);
171
- }
172
-
173
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/catch.js
174
- var parseCatchDef = (def, refs) => {
175
- return parseDef(def.innerType._def, refs);
176
- };
177
-
178
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/date.js
179
- function parseDateDef(def, refs, overrideDateStrategy) {
180
- const strategy = overrideDateStrategy ?? refs.dateStrategy;
181
- if (Array.isArray(strategy)) {
182
- return {
183
- anyOf: strategy.map((item, i) => parseDateDef(def, refs, item))
184
- };
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;
185
381
  }
186
- switch (strategy) {
187
- case "string":
188
- case "format:date-time":
189
- return {
190
- type: "string",
191
- format: "date-time"
192
- };
193
- case "format:date":
194
- return {
195
- type: "string",
196
- format: "date"
197
- };
198
- case "integer":
199
- return integerDateParser(def, refs);
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;
200
405
  }
201
- }
202
- var integerDateParser = (def, refs) => {
203
- const res = {
204
- type: "integer",
205
- format: "unix-time"
206
- };
207
- if (refs.target === "openApi3") {
208
- return res;
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;
209
419
  }
210
- for (const check of def.checks) {
211
- switch (check.kind) {
212
- case "min":
213
- setResponseValueAndErrors(
214
- res,
215
- "minimum",
216
- check.value,
217
- // This is in milliseconds
218
- check.message,
219
- refs
220
- );
221
- break;
222
- case "max":
223
- setResponseValueAndErrors(
224
- res,
225
- "maximum",
226
- check.value,
227
- // This is in milliseconds
228
- check.message,
229
- refs
230
- );
231
- break;
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++;
429
+ }
430
+ }
232
431
  }
432
+ return total > 0 ? wins / total : 0;
233
433
  }
234
- return res;
235
- };
236
-
237
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/default.js
238
- function parseDefaultDef(_def, refs) {
239
- return {
240
- ...parseDef(_def.innerType._def, refs),
241
- default: _def.defaultValue()
242
- };
243
- }
244
-
245
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/effects.js
246
- function parseEffectsDef(_def, refs) {
247
- return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : {};
248
- }
249
-
250
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/enum.js
251
- function parseEnumDef(def) {
252
- return {
253
- type: "string",
254
- enum: Array.from(def.values)
255
- };
256
- }
257
-
258
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js
259
- var isJsonSchema7AllOfType = (type) => {
260
- if ("type" in type && type.type === "string")
261
- return false;
262
- return "allOf" in type;
263
- };
264
- function parseIntersectionDef(def, refs) {
265
- const allOf = [
266
- parseDef(def.left._def, {
267
- ...refs,
268
- currentPath: [...refs.currentPath, "allOf", "0"]
269
- }),
270
- parseDef(def.right._def, {
271
- ...refs,
272
- currentPath: [...refs.currentPath, "allOf", "1"]
273
- })
274
- ].filter((x) => !!x);
275
- let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0;
276
- const mergedAllOf = [];
277
- allOf.forEach((schema) => {
278
- if (isJsonSchema7AllOfType(schema)) {
279
- mergedAllOf.push(...schema.allOf);
280
- if (schema.unevaluatedProperties === void 0) {
281
- unevaluatedProperties = void 0;
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);
282
444
  }
283
- } else {
284
- let nestedSchema = schema;
285
- if ("additionalProperties" in schema && schema.additionalProperties === false) {
286
- const { additionalProperties, ...rest } = schema;
287
- nestedSchema = rest;
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);
288
523
  } else {
289
- unevaluatedProperties = void 0;
524
+ plusDM.push(0);
525
+ minusDM.push(0);
290
526
  }
291
- mergedAllOf.push(nestedSchema);
292
527
  }
293
- });
294
- return mergedAllOf.length ? {
295
- allOf: mergedAllOf,
296
- ...unevaluatedProperties
297
- } : void 0;
298
- }
299
-
300
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/literal.js
301
- function parseLiteralDef(def, refs) {
302
- const parsedType = typeof def.value;
303
- if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
304
- return {
305
- type: Array.isArray(def.value) ? "array" : "object"
306
- };
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;
307
573
  }
308
- if (refs.target === "openApi3") {
309
- return {
310
- type: parsedType === "bigint" ? "integer" : parsedType,
311
- enum: [def.value]
312
- };
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;
313
661
  }
314
- return {
315
- type: parsedType === "bigint" ? "integer" : parsedType,
316
- const: def.value
317
- };
318
- }
319
-
320
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/record.js
321
- import { ZodFirstPartyTypeKind as ZodFirstPartyTypeKind2 } from "zod";
322
-
323
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/string.js
324
- var emojiRegex = void 0;
325
- var zodPatterns = {
326
- /**
327
- * `c` was changed to `[cC]` to replicate /i flag
328
- */
329
- cuid: /^[cC][^\s-]{8,}$/,
330
- cuid2: /^[0-9a-z]+$/,
331
- ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
332
- /**
333
- * `a-z` was added to replicate /i flag
334
- */
335
- email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
336
- /**
337
- * Constructed a valid Unicode RegExp
338
- *
339
- * Lazily instantiate since this type of regex isn't supported
340
- * in all envs (e.g. React Native).
341
- *
342
- * See:
343
- * https://github.com/colinhacks/zod/issues/2433
344
- * Fix in Zod:
345
- * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
346
- */
347
- emoji: () => {
348
- if (emojiRegex === void 0) {
349
- emojiRegex = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u");
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);
350
671
  }
351
- return emojiRegex;
352
- },
353
- /**
354
- * Unused
355
- */
356
- uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,
357
- /**
358
- * Unused
359
- */
360
- ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,
361
- ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,
362
- /**
363
- * Unused
364
- */
365
- ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
366
- ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,
367
- base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
368
- base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
369
- nanoid: /^[a-zA-Z0-9_-]{21}$/,
370
- jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
371
- };
372
- function parseStringDef(def, refs) {
373
- const res = {
374
- type: "string"
375
- };
376
- if (def.checks) {
377
- for (const check of def.checks) {
378
- switch (check.kind) {
379
- case "min":
380
- setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
381
- break;
382
- case "max":
383
- setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
384
- break;
385
- case "email":
386
- switch (refs.emailStrategy) {
387
- case "format:email":
388
- addFormat(res, "email", check.message, refs);
389
- break;
390
- case "format:idn-email":
391
- addFormat(res, "idn-email", check.message, refs);
392
- break;
393
- case "pattern:zod":
394
- addPattern(res, zodPatterns.email, check.message, refs);
395
- break;
396
- }
397
- break;
398
- case "url":
399
- addFormat(res, "uri", check.message, refs);
400
- break;
401
- case "uuid":
402
- addFormat(res, "uuid", check.message, refs);
403
- break;
404
- case "regex":
405
- addPattern(res, check.regex, check.message, refs);
406
- break;
407
- case "cuid":
408
- addPattern(res, zodPatterns.cuid, check.message, refs);
409
- break;
410
- case "cuid2":
411
- addPattern(res, zodPatterns.cuid2, check.message, refs);
412
- break;
413
- case "startsWith":
414
- addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs);
415
- break;
416
- case "endsWith":
417
- addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs);
418
- break;
419
- case "datetime":
420
- addFormat(res, "date-time", check.message, refs);
421
- break;
422
- case "date":
423
- addFormat(res, "date", check.message, refs);
424
- break;
425
- case "time":
426
- addFormat(res, "time", check.message, refs);
427
- break;
428
- case "duration":
429
- addFormat(res, "duration", check.message, refs);
430
- break;
431
- case "length":
432
- setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
433
- setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
434
- break;
435
- case "includes": {
436
- addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs);
437
- break;
438
- }
439
- case "ip": {
440
- if (check.version !== "v6") {
441
- addFormat(res, "ipv4", check.message, refs);
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]
706
+ });
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);
442
734
  }
443
- if (check.version !== "v4") {
444
- addFormat(res, "ipv6", check.message, refs);
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);
445
739
  }
446
- break;
447
740
  }
448
- case "base64url":
449
- addPattern(res, zodPatterns.base64url, check.message, refs);
450
- break;
451
- case "jwt":
452
- addPattern(res, zodPatterns.jwt, check.message, refs);
453
- break;
454
- case "cidr": {
455
- if (check.version !== "v6") {
456
- addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
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);
457
751
  }
458
- if (check.version !== "v4") {
459
- addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
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);
460
756
  }
461
- break;
462
757
  }
463
- case "emoji":
464
- addPattern(res, zodPatterns.emoji(), check.message, refs);
465
- break;
466
- case "ulid": {
467
- addPattern(res, zodPatterns.ulid, check.message, refs);
468
- break;
469
- }
470
- case "base64": {
471
- switch (refs.base64Strategy) {
472
- case "format:binary": {
473
- addFormat(res, "binary", check.message, refs);
474
- break;
475
- }
476
- case "contentEncoding:base64": {
477
- setResponseValueAndErrors(res, "contentEncoding", "base64", check.message, refs);
478
- break;
479
- }
480
- case "pattern:zod": {
481
- addPattern(res, zodPatterns.base64, check.message, refs);
482
- break;
483
- }
484
- }
485
- break;
486
- }
487
- case "nanoid": {
488
- addPattern(res, zodPatterns.nanoid, check.message, refs);
489
- }
490
- case "toLowerCase":
491
- case "toUpperCase":
492
- case "trim":
493
- break;
494
- default:
495
- /* @__PURE__ */ ((_) => {
496
- })(check);
497
758
  }
759
+ sar.push(currentSAR);
498
760
  }
761
+ return sar;
499
762
  }
500
- return res;
501
- }
502
- function escapeLiteralCheckValue(literal, refs) {
503
- return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
504
- }
505
- var ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
506
- function escapeNonAlphaNumeric(source) {
507
- let result = "";
508
- for (let i = 0; i < source.length; i++) {
509
- if (!ALPHA_NUMERIC.has(source[i])) {
510
- result += "\\";
511
- }
512
- result += source[i];
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;
513
773
  }
514
- return result;
515
- }
516
- function addFormat(schema, value, message, refs) {
517
- if (schema.format || schema.anyOf?.some((x) => x.format)) {
518
- if (!schema.anyOf) {
519
- schema.anyOf = [];
520
- }
521
- if (schema.format) {
522
- schema.anyOf.push({
523
- format: schema.format,
524
- ...schema.errorMessage && refs.errorMessages && {
525
- errorMessage: { format: schema.errorMessage.format }
526
- }
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
527
814
  });
528
- delete schema.format;
529
- if (schema.errorMessage) {
530
- delete schema.errorMessage.format;
531
- if (Object.keys(schema.errorMessage).length === 0) {
532
- delete schema.errorMessage;
533
- }
534
- }
535
815
  }
536
- schema.anyOf.push({
537
- format: value,
538
- ...message && refs.errorMessages && { errorMessage: { format: message } }
539
- });
540
- } else {
541
- setResponseValueAndErrors(schema, "format", value, message, refs);
816
+ return keltner;
542
817
  }
543
- }
544
- function addPattern(schema, regex, message, refs) {
545
- if (schema.pattern || schema.allOf?.some((x) => x.pattern)) {
546
- if (!schema.allOf) {
547
- schema.allOf = [];
548
- }
549
- if (schema.pattern) {
550
- schema.allOf.push({
551
- pattern: schema.pattern,
552
- ...schema.errorMessage && refs.errorMessages && {
553
- errorMessage: { pattern: schema.errorMessage.pattern }
554
- }
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)
555
827
  });
556
- delete schema.pattern;
557
- if (schema.errorMessage) {
558
- delete schema.errorMessage.pattern;
559
- if (Object.keys(schema.errorMessage).length === 0) {
560
- delete schema.errorMessage;
561
- }
562
- }
563
828
  }
564
- schema.allOf.push({
565
- pattern: stringifyRegExpWithFlags(regex, refs),
566
- ...message && refs.errorMessages && { errorMessage: { pattern: message } }
567
- });
568
- } else {
569
- setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs);
829
+ return donchian;
570
830
  }
571
- }
572
- function stringifyRegExpWithFlags(regex, refs) {
573
- if (!refs.applyRegexFlags || !regex.flags) {
574
- return regex.source;
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;
575
838
  }
576
- const flags = {
577
- i: regex.flags.includes("i"),
578
- m: regex.flags.includes("m"),
579
- s: regex.flags.includes("s")
580
- // `.` matches newlines
581
- };
582
- const source = flags.i ? regex.source.toLowerCase() : regex.source;
583
- let pattern = "";
584
- let isEscaped = false;
585
- let inCharGroup = false;
586
- let inCharRange = false;
587
- for (let i = 0; i < source.length; i++) {
588
- if (isEscaped) {
589
- pattern += source[i];
590
- isEscaped = false;
591
- continue;
592
- }
593
- if (flags.i) {
594
- if (inCharGroup) {
595
- if (source[i].match(/[a-z]/)) {
596
- if (inCharRange) {
597
- pattern += source[i];
598
- pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
599
- inCharRange = false;
600
- } else if (source[i + 1] === "-" && source[i + 2]?.match(/[a-z]/)) {
601
- pattern += source[i];
602
- inCharRange = true;
603
- } else {
604
- pattern += `${source[i]}${source[i].toUpperCase()}`;
605
- }
606
- continue;
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
607
928
  }
608
- } else if (source[i].match(/[a-z]/)) {
609
- pattern += `[${source[i]}${source[i].toUpperCase()}]`;
610
- continue;
611
- }
929
+ });
612
930
  }
613
- if (flags.m) {
614
- if (source[i] === "^") {
615
- pattern += `(^|(?<=[\r
616
- ]))`;
617
- continue;
618
- } else if (source[i] === "$") {
619
- pattern += `($|(?=[\r
620
- ]))`;
621
- continue;
622
- }
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));
623
938
  }
624
- if (flags.s && source[i] === ".") {
625
- pattern += inCharGroup ? `${source[i]}\r
626
- ` : `[${source[i]}\r
627
- ]`;
628
- continue;
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
+ });
629
950
  }
630
- pattern += source[i];
631
- if (source[i] === "\\") {
632
- isEscaped = true;
633
- } else if (inCharGroup && source[i] === "]") {
634
- inCharGroup = false;
635
- } else if (!inCharGroup && source[i] === "[") {
636
- inCharGroup = true;
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
+ });
637
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;
638
970
  }
639
- try {
640
- new RegExp(pattern);
641
- } catch {
642
- console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`);
643
- return regex.source;
971
+ // Calculate Confidence
972
+ calculateConfidence(signals) {
973
+ return Math.min(signals.length * 10, 100);
644
974
  }
645
- return pattern;
646
- }
647
-
648
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/record.js
649
- function parseRecordDef(def, refs) {
650
- if (refs.target === "openAi") {
651
- console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");
975
+ // Calculate Risk Level
976
+ calculateRiskLevel(volatility) {
977
+ if (volatility < 20) return "LOW";
978
+ if (volatility < 40) return "MEDIUM";
979
+ return "HIGH";
652
980
  }
653
- if (refs.target === "openApi3" && def.keyType?._def.typeName === ZodFirstPartyTypeKind2.ZodEnum) {
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) {
654
987
  return {
655
- type: "object",
656
- required: def.keyType._def.values,
657
- properties: def.keyType._def.values.reduce((acc, key) => ({
658
- ...acc,
659
- [key]: parseDef(def.valueType._def, {
660
- ...refs,
661
- currentPath: [...refs.currentPath, "properties", key]
662
- }) ?? {}
663
- }), {}),
664
- additionalProperties: refs.rejectedAdditionalProperties
988
+ mean: startPrice,
989
+ speed: 0.1,
990
+ volatility: avgVolume * 0.01,
991
+ currentValue: currentPrice
665
992
  };
666
993
  }
667
- const schema = {
668
- type: "object",
669
- additionalProperties: parseDef(def.valueType._def, {
670
- ...refs,
671
- currentPath: [...refs.currentPath, "additionalProperties"]
672
- }) ?? refs.allowedAdditionalProperties
673
- };
674
- if (refs.target === "openApi3") {
675
- return schema;
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
+ };
676
1009
  }
677
- if (def.keyType?._def.typeName === ZodFirstPartyTypeKind2.ZodString && def.keyType._def.checks?.length) {
678
- const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
1010
+ // Calculate GARCH
1011
+ calculateGarch(currentPrice, startPrice, avgVolume) {
679
1012
  return {
680
- ...schema,
681
- propertyNames: keyType
1013
+ volatility: avgVolume * 0.01,
1014
+ persistence: 0.9,
1015
+ meanReversion: 0.1
682
1016
  };
683
- } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind2.ZodEnum) {
1017
+ }
1018
+ // Calculate Hilbert Transform
1019
+ calculateHilbertTransform(currentPrice, startPrice, avgVolume) {
684
1020
  return {
685
- ...schema,
686
- propertyNames: {
687
- enum: def.keyType._def.values
688
- }
1021
+ analytic: [currentPrice],
1022
+ phase: [0],
1023
+ amplitude: [currentPrice]
689
1024
  };
690
- } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind2.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind2.ZodString && def.keyType._def.type._def.checks?.length) {
691
- const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs);
1025
+ }
1026
+ // Calculate Wavelet Transform
1027
+ calculateWaveletTransform(currentPrice, startPrice, avgVolume) {
692
1028
  return {
693
- ...schema,
694
- propertyNames: keyType
1029
+ coefficients: [currentPrice],
1030
+ scales: [1]
695
1031
  };
696
1032
  }
697
- return schema;
698
- }
699
-
700
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/map.js
701
- function parseMapDef(def, refs) {
702
- if (refs.mapStrategy === "record") {
703
- return parseRecordDef(def, refs);
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;
704
1075
  }
705
- const keys = parseDef(def.keyType._def, {
706
- ...refs,
707
- currentPath: [...refs.currentPath, "items", "items", "0"]
708
- }) || {};
709
- const values = parseDef(def.valueType._def, {
710
- ...refs,
711
- currentPath: [...refs.currentPath, "items", "items", "1"]
712
- }) || {};
713
- return {
714
- type: "array",
715
- maxItems: 125,
716
- items: {
717
- type: "array",
718
- items: [keys, values],
719
- minItems: 2,
720
- maxItems: 2
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]);
721
1081
  }
722
- };
723
- }
724
-
725
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js
726
- function parseNativeEnumDef(def) {
727
- const object = def.values;
728
- const actualKeys = Object.keys(def.values).filter((key) => {
729
- return typeof object[object[key]] !== "number";
730
- });
731
- const actualValues = actualKeys.map((key) => object[key]);
732
- const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));
733
- return {
734
- type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
735
- enum: actualValues
736
- };
737
- }
738
-
739
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/never.js
740
- function parseNeverDef() {
741
- return {
742
- not: {}
743
- };
744
- }
745
-
746
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/null.js
747
- function parseNullDef(refs) {
748
- return refs.target === "openApi3" ? {
749
- enum: ["null"],
750
- nullable: true
751
- } : {
752
- type: "null"
753
- };
754
- }
755
-
756
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/union.js
757
- var primitiveMappings = {
758
- ZodString: "string",
759
- ZodNumber: "number",
760
- ZodBigInt: "integer",
761
- ZodBoolean: "boolean",
762
- ZodNull: "null"
763
- };
764
- function parseUnionDef(def, refs) {
765
- if (refs.target === "openApi3")
766
- return asAnyOf(def, refs);
767
- const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
768
- if (options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) {
769
- const types = options.reduce((types2, x) => {
770
- const type = primitiveMappings[x._def.typeName];
771
- return type && !types2.includes(type) ? [...types2, type] : types2;
772
- }, []);
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);
773
1112
  return {
774
- type: types.length > 1 ? types : types[0]
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
775
1135
  };
776
- } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
777
- const types = options.reduce((acc, x) => {
778
- const type = typeof x._def.value;
779
- switch (type) {
780
- case "string":
781
- case "number":
782
- case "boolean":
783
- return [...acc, type];
784
- case "bigint":
785
- return [...acc, "integer"];
786
- case "object":
787
- if (x._def.value === null)
788
- return [...acc, "null"];
789
- case "symbol":
790
- case "undefined":
791
- case "function":
792
- default:
793
- return acc;
794
- }
795
- }, []);
796
- if (types.length === options.length) {
797
- const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
798
- return {
799
- type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
800
- enum: options.reduce((acc, x) => {
801
- return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
802
- }, [])
803
- };
1136
+ }
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");
1216
+ }
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");
804
1225
  }
805
- } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
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);
806
1284
  return {
807
- type: "string",
808
- enum: options.reduce((acc, x) => [
809
- ...acc,
810
- ...x._def.values.filter((x2) => !acc.includes(x2))
811
- ], [])
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
+ }
812
1452
  };
813
1453
  }
814
- return asAnyOf(def, refs);
815
- }
816
- var asAnyOf = (def, refs) => {
817
- const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef(x._def, {
818
- ...refs,
819
- currentPath: [...refs.currentPath, "anyOf", `${i}`]
820
- })).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0));
821
- return anyOf.length ? { anyOf } : void 0;
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) {
1461
+ return {
1462
+ content: [
1463
+ {
1464
+ type: "text",
1465
+ text: `No price data available for ${symbol}. Please request market data first.`,
1466
+ uri: "technicalAnalysis"
1467
+ }
1468
+ ]
1469
+ };
1470
+ }
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
+ };
822
1503
  };
823
1504
 
824
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js
825
- function parseNullableDef(def, refs) {
826
- if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
827
- if (refs.target === "openApi3") {
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
+ });
1593
+ return {
1594
+ content: [
1595
+ {
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) {
828
1624
  return {
829
- type: primitiveMappings[def.innerType._def.typeName],
830
- nullable: true
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
831
1633
  };
832
1634
  }
833
- return {
834
- type: [
835
- primitiveMappings[def.innerType._def.typeName],
836
- "null"
837
- ]
838
- };
1635
+ };
1636
+ };
1637
+ var aggregateMarketData = (priceHistory, maxPoints = 490) => {
1638
+ if (priceHistory.length <= maxPoints) {
1639
+ return priceHistory;
839
1640
  }
840
- if (refs.target === "openApi3") {
841
- const base2 = parseDef(def.innerType._def, {
842
- ...refs,
843
- currentPath: [...refs.currentPath]
844
- });
845
- if (base2 && "$ref" in base2)
846
- return { allOf: [base2], nullable: true };
847
- return base2 && { ...base2, nullable: true };
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);
848
1699
  }
849
- const base = parseDef(def.innerType._def, {
850
- ...refs,
851
- currentPath: [...refs.currentPath, "anyOf", "0"]
852
- });
853
- return base && { anyOf: [base, { type: "null" }] };
854
- }
855
-
856
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/number.js
857
- function parseNumberDef(def, refs) {
858
- const res = {
859
- type: "number"
860
- };
861
- if (!def.checks)
862
- return res;
863
- for (const check of def.checks) {
864
- switch (check.kind) {
865
- case "int":
866
- res.type = "integer";
867
- addErrorMessage(res, "type", check.message, refs);
868
- break;
869
- case "min":
870
- if (refs.target === "jsonSchema7") {
871
- if (check.inclusive) {
872
- setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
873
- } else {
874
- setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs);
875
- }
876
- } else {
877
- if (!check.inclusive) {
878
- res.exclusiveMinimum = true;
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: [
1711
+ {
1712
+ type: "text",
1713
+ text: `No price data available for ${symbol}`,
1714
+ uri: "getStockGraph"
1715
+ }
1716
+ ]
1717
+ };
1718
+ }
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
+ },
1756
+ {
1757
+ label: "Spread",
1758
+ data: spreadData,
1759
+ borderColor: "#6c757d",
1760
+ backgroundColor: "rgba(108, 117, 125, 0.1)",
1761
+ fill: false,
1762
+ tension: 0.4
1763
+ },
1764
+ {
1765
+ label: "Trade",
1766
+ data: tradeData,
1767
+ borderColor: "#ffc107",
1768
+ backgroundColor: "rgba(255, 193, 7, 0.1)",
1769
+ fill: false,
1770
+ tension: 0.4
1771
+ },
1772
+ {
1773
+ label: "VWAP",
1774
+ data: vwapData,
1775
+ borderColor: "#17a2b8",
1776
+ backgroundColor: "rgba(23, 162, 184, 0.1)",
1777
+ fill: false,
1778
+ tension: 0.4
1779
+ },
1780
+ {
1781
+ label: "TWAP",
1782
+ data: twapData,
1783
+ borderColor: "#6610f2",
1784
+ backgroundColor: "rgba(102, 16, 242, 0.1)",
1785
+ fill: false,
1786
+ tension: 0.4
1787
+ },
1788
+ {
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
1795
+ }
1796
+ ]
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)`
1804
+ }
1805
+ },
1806
+ scales: {
1807
+ y: {
1808
+ beginAtZero: false,
1809
+ title: {
1810
+ display: true,
1811
+ text: "Price / Normalized Volume"
1812
+ }
1813
+ }
879
1814
  }
880
- setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
881
1815
  }
882
- break;
883
- case "max":
884
- if (refs.target === "jsonSchema7") {
885
- if (check.inclusive) {
886
- setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
887
- } else {
888
- setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs);
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
+ }
889
1829
  }
890
- } else {
891
- if (!check.inclusive) {
892
- res.exclusiveMaximum = true;
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"
893
1839
  }
894
- setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
895
- }
896
- break;
897
- case "multipleOf":
898
- setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs);
899
- break;
1840
+ ],
1841
+ isError: true
1842
+ };
900
1843
  }
901
- }
902
- return res;
903
- }
904
-
905
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/object.js
906
- import { ZodOptional } from "zod";
907
- function parseObjectDef(def, refs) {
908
- const forceOptionalIntoNullable = refs.target === "openAi";
909
- const result = {
910
- type: "object",
911
- properties: {}
912
1844
  };
913
- const required = [];
914
- const shape = def.shape();
915
- for (const propName in shape) {
916
- let propDef = shape[propName];
917
- if (propDef === void 0 || propDef._def === void 0) {
918
- continue;
919
- }
920
- let propOptional = safeIsOptional(propDef);
921
- if (propOptional && forceOptionalIntoNullable) {
922
- if (propDef instanceof ZodOptional) {
923
- propDef = propDef._def.innerType;
924
- }
925
- if (!propDef.isNullable()) {
926
- propDef = propDef.nullable();
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
+ };
927
1861
  }
928
- propOptional = false;
929
- }
930
- const parsedDef = parseDef(propDef._def, {
931
- ...refs,
932
- currentPath: [...refs.currentPath, "properties", propName],
933
- propertyPath: [...refs.currentPath, "properties", propName]
934
- });
935
- if (parsedDef === void 0) {
936
- continue;
937
- }
938
- result.properties[propName] = parsedDef;
939
- if (!propOptional) {
940
- required.push(propName);
1862
+ const aggregatedData = aggregateMarketData(priceHistory, 500);
1863
+ return {
1864
+ content: [
1865
+ {
1866
+ type: "text",
1867
+ text: JSON.stringify(
1868
+ {
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
+ };
941
1939
  }
942
- }
943
- if (required.length) {
944
- result.required = required;
945
- }
946
- const additionalProperties = decideAdditionalProperties(def, refs);
947
- if (additionalProperties !== void 0) {
948
- result.additionalProperties = additionalProperties;
949
- }
950
- return result;
951
- }
952
- function decideAdditionalProperties(def, refs) {
953
- if (def.catchall._def.typeName !== "ZodNever") {
954
- return parseDef(def.catchall._def, {
955
- ...refs,
956
- currentPath: [...refs.currentPath, "additionalProperties"]
957
- });
958
- }
959
- switch (def.unknownKeys) {
960
- case "passthrough":
961
- return refs.allowedAdditionalProperties;
962
- case "strict":
963
- return refs.rejectedAdditionalProperties;
964
- case "strip":
965
- return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
966
- }
967
- }
968
- function safeIsOptional(schema) {
969
- try {
970
- return schema.isOptional();
971
- } catch {
972
- return true;
973
- }
974
- }
1940
+ };
1941
+ };
975
1942
 
976
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/optional.js
977
- var parseOptionalDef = (def, refs) => {
978
- if (refs.currentPath.toString() === refs.propertyPath?.toString()) {
979
- return parseDef(def.innerType._def, refs);
980
- }
981
- const innerSchema = parseDef(def.innerType._def, {
982
- ...refs,
983
- currentPath: [...refs.currentPath, "anyOf", "1"]
984
- });
985
- return innerSchema ? {
986
- anyOf: [
987
- {
988
- not: {}
989
- },
990
- innerSchema
991
- ]
992
- } : {};
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"
993
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
+
2032
+ Parameters verified:
2033
+ - ClOrdID: ${args.clOrdID}
2034
+ - HandlInst: ${args.handlInst} (${handlInstNames[args.handlInst]})
2035
+ - Quantity: ${args.quantity}
2036
+ - Price: ${args.price}
2037
+ - OrdType: ${args.ordType} (${ordTypeNames[args.ordType]})
2038
+ - Side: ${args.side} (${sideNames[args.side]})
2039
+ - Symbol: ${args.symbol}
2040
+ - TimeInForce: ${args.timeInForce} (${timeInForceNames[args.timeInForce]})
994
2041
 
995
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js
996
- var parsePipelineDef = (def, refs) => {
997
- if (refs.pipeStrategy === "input") {
998
- return parseDef(def.in._def, refs);
999
- } else if (refs.pipeStrategy === "output") {
1000
- return parseDef(def.out._def, refs);
1001
- }
1002
- const a = parseDef(def.in._def, {
1003
- ...refs,
1004
- currentPath: [...refs.currentPath, "allOf", "0"]
1005
- });
1006
- const b = parseDef(def.out._def, {
1007
- ...refs,
1008
- currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
1009
- });
1010
- return {
1011
- allOf: [a, b].filter((x) => x !== void 0)
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
+ }
1012
2059
  };
1013
2060
  };
1014
-
1015
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/promise.js
1016
- function parsePromiseDef(def, refs) {
1017
- return parseDef(def.type._def, refs);
1018
- }
1019
-
1020
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/set.js
1021
- function parseSetDef(def, refs) {
1022
- const items = parseDef(def.valueType._def, {
1023
- ...refs,
1024
- currentPath: [...refs.currentPath, "items"]
1025
- });
1026
- const schema = {
1027
- type: "array",
1028
- uniqueItems: true,
1029
- items
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
+ }
1030
2144
  };
1031
- if (def.minSize) {
1032
- setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs);
1033
- }
1034
- if (def.maxSize) {
1035
- setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs);
1036
- }
1037
- return schema;
1038
- }
1039
-
1040
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js
1041
- function parseTupleDef(def, refs) {
1042
- if (def.rest) {
1043
- return {
1044
- type: "array",
1045
- minItems: def.items.length,
1046
- items: def.items.map((x, i) => parseDef(x._def, {
1047
- ...refs,
1048
- currentPath: [...refs.currentPath, "items", `${i}`]
1049
- })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []),
1050
- additionalItems: parseDef(def.rest._def, {
1051
- ...refs,
1052
- currentPath: [...refs.currentPath, "additionalItems"]
1053
- })
1054
- };
1055
- } else {
1056
- return {
1057
- type: "array",
1058
- minItems: def.items.length,
1059
- maxItems: def.items.length,
1060
- items: def.items.map((x, i) => parseDef(x._def, {
1061
- ...refs,
1062
- currentPath: [...refs.currentPath, "items", `${i}`]
1063
- })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], [])
1064
- };
1065
- }
1066
- }
2145
+ };
1067
2146
 
1068
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js
1069
- function parseUndefinedDef() {
1070
- return {
1071
- not: {}
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
+ }
1072
2186
  };
1073
- }
1074
-
1075
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js
1076
- function parseUnknownDef() {
1077
- return {};
1078
- }
1079
-
1080
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js
1081
- var parseReadonlyDef = (def, refs) => {
1082
- return parseDef(def.innerType._def, refs);
1083
2187
  };
1084
2188
 
1085
- // ../../node_modules/zod-to-json-schema/dist/esm/selectParser.js
1086
- var selectParser = (def, typeName, refs) => {
1087
- switch (typeName) {
1088
- case ZodFirstPartyTypeKind3.ZodString:
1089
- return parseStringDef(def, refs);
1090
- case ZodFirstPartyTypeKind3.ZodNumber:
1091
- return parseNumberDef(def, refs);
1092
- case ZodFirstPartyTypeKind3.ZodObject:
1093
- return parseObjectDef(def, refs);
1094
- case ZodFirstPartyTypeKind3.ZodBigInt:
1095
- return parseBigintDef(def, refs);
1096
- case ZodFirstPartyTypeKind3.ZodBoolean:
1097
- return parseBooleanDef();
1098
- case ZodFirstPartyTypeKind3.ZodDate:
1099
- return parseDateDef(def, refs);
1100
- case ZodFirstPartyTypeKind3.ZodUndefined:
1101
- return parseUndefinedDef();
1102
- case ZodFirstPartyTypeKind3.ZodNull:
1103
- return parseNullDef(refs);
1104
- case ZodFirstPartyTypeKind3.ZodArray:
1105
- return parseArrayDef(def, refs);
1106
- case ZodFirstPartyTypeKind3.ZodUnion:
1107
- case ZodFirstPartyTypeKind3.ZodDiscriminatedUnion:
1108
- return parseUnionDef(def, refs);
1109
- case ZodFirstPartyTypeKind3.ZodIntersection:
1110
- return parseIntersectionDef(def, refs);
1111
- case ZodFirstPartyTypeKind3.ZodTuple:
1112
- return parseTupleDef(def, refs);
1113
- case ZodFirstPartyTypeKind3.ZodRecord:
1114
- return parseRecordDef(def, refs);
1115
- case ZodFirstPartyTypeKind3.ZodLiteral:
1116
- return parseLiteralDef(def, refs);
1117
- case ZodFirstPartyTypeKind3.ZodEnum:
1118
- return parseEnumDef(def);
1119
- case ZodFirstPartyTypeKind3.ZodNativeEnum:
1120
- return parseNativeEnumDef(def);
1121
- case ZodFirstPartyTypeKind3.ZodNullable:
1122
- return parseNullableDef(def, refs);
1123
- case ZodFirstPartyTypeKind3.ZodOptional:
1124
- return parseOptionalDef(def, refs);
1125
- case ZodFirstPartyTypeKind3.ZodMap:
1126
- return parseMapDef(def, refs);
1127
- case ZodFirstPartyTypeKind3.ZodSet:
1128
- return parseSetDef(def, refs);
1129
- case ZodFirstPartyTypeKind3.ZodLazy:
1130
- return () => def.getter()._def;
1131
- case ZodFirstPartyTypeKind3.ZodPromise:
1132
- return parsePromiseDef(def, refs);
1133
- case ZodFirstPartyTypeKind3.ZodNaN:
1134
- case ZodFirstPartyTypeKind3.ZodNever:
1135
- return parseNeverDef();
1136
- case ZodFirstPartyTypeKind3.ZodEffects:
1137
- return parseEffectsDef(def, refs);
1138
- case ZodFirstPartyTypeKind3.ZodAny:
1139
- return parseAnyDef();
1140
- case ZodFirstPartyTypeKind3.ZodUnknown:
1141
- return parseUnknownDef();
1142
- case ZodFirstPartyTypeKind3.ZodDefault:
1143
- return parseDefaultDef(def, refs);
1144
- case ZodFirstPartyTypeKind3.ZodBranded:
1145
- return parseBrandedDef(def, refs);
1146
- case ZodFirstPartyTypeKind3.ZodReadonly:
1147
- return parseReadonlyDef(def, refs);
1148
- case ZodFirstPartyTypeKind3.ZodCatch:
1149
- return parseCatchDef(def, refs);
1150
- case ZodFirstPartyTypeKind3.ZodPipeline:
1151
- return parsePipelineDef(def, refs);
1152
- case ZodFirstPartyTypeKind3.ZodFunction:
1153
- case ZodFirstPartyTypeKind3.ZodVoid:
1154
- case ZodFirstPartyTypeKind3.ZodSymbol:
1155
- return void 0;
1156
- default:
1157
- return /* @__PURE__ */ ((_) => void 0)(typeName);
1158
- }
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
+ };
2205
+ }
2206
+ return {
2207
+ content: [
2208
+ {
2209
+ type: "text",
2210
+ text: `${parsedMessage[0].toFIXJSON()}`,
2211
+ uri: "parseToJSON"
2212
+ }
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"
2222
+ }
2223
+ ],
2224
+ isError: true
2225
+ };
2226
+ }
2227
+ };
1159
2228
  };
1160
2229
 
1161
- // ../../node_modules/zod-to-json-schema/dist/esm/parseDef.js
1162
- function parseDef(def, refs, forceResolution = false) {
1163
- const seenItem = refs.seen.get(def);
1164
- if (refs.override) {
1165
- const overrideResult = refs.override?.(def, refs, seenItem, forceResolution);
1166
- if (overrideResult !== ignoreOverride) {
1167
- return overrideResult;
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
+ }
1168
2441
  }
1169
- }
1170
- if (seenItem && !forceResolution) {
1171
- const seenSchema = get$ref(seenItem, refs);
1172
- if (seenSchema !== void 0) {
1173
- return seenSchema;
2442
+ data.spread = data.offer - data.bid;
2443
+ if (!marketDataPrices.has(symbol)) {
2444
+ marketDataPrices.set(symbol, []);
1174
2445
  }
1175
- }
1176
- const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
1177
- refs.seen.set(def, newItem);
1178
- const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
1179
- const jsonSchema = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
1180
- if (jsonSchema) {
1181
- addMeta(def, refs, jsonSchema);
1182
- }
1183
- if (refs.postProcess) {
1184
- const postProcessResult = refs.postProcess(jsonSchema, def, refs);
1185
- newItem.jsonSchema = jsonSchema;
1186
- return postProcessResult;
1187
- }
1188
- newItem.jsonSchema = jsonSchema;
1189
- return jsonSchema;
1190
- }
1191
- var get$ref = (item, refs) => {
1192
- switch (refs.$refStrategy) {
1193
- case "root":
1194
- return { $ref: item.path.join("/") };
1195
- case "relative":
1196
- return { $ref: getRelativePath(refs.currentPath, item.path) };
1197
- case "none":
1198
- case "seen": {
1199
- if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
1200
- console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);
1201
- return {};
1202
- }
1203
- return refs.$refStrategy === "seen" ? {} : void 0;
2446
+ const prices = marketDataPrices.get(symbol);
2447
+ prices.push(data);
2448
+ if (prices.length > maxPriceHistory) {
2449
+ prices.splice(0, prices.length - maxPriceHistory);
1204
2450
  }
1205
- }
1206
- };
1207
- var getRelativePath = (pathA, pathB) => {
1208
- let i = 0;
1209
- for (; i < pathA.length && i < pathB.length; i++) {
1210
- if (pathA[i] !== pathB[i])
1211
- break;
1212
- }
1213
- return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
1214
- };
1215
- var addMeta = (def, refs, jsonSchema) => {
1216
- if (def.description) {
1217
- jsonSchema.description = def.description;
1218
- if (refs.markdownDescription) {
1219
- jsonSchema.markdownDescription = def.description;
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
+ }
1220
2459
  }
1221
- }
1222
- return jsonSchema;
1223
- };
1224
-
1225
- // ../../node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js
1226
- var zodToJsonSchema = (schema, options) => {
1227
- const refs = getRefs(options);
1228
- const definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name2, schema2]) => ({
1229
- ...acc,
1230
- [name2]: parseDef(schema2._def, {
1231
- ...refs,
1232
- currentPath: [...refs.basePath, refs.definitionPath, name2]
1233
- }, true) ?? {}
1234
- }), {}) : void 0;
1235
- const name = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name;
1236
- const main = parseDef(schema._def, name === void 0 ? refs : {
1237
- ...refs,
1238
- currentPath: [...refs.basePath, refs.definitionPath, name]
1239
- }, false) ?? {};
1240
- const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
1241
- if (title !== void 0) {
1242
- main.title = title;
1243
- }
1244
- const combined = name === void 0 ? definitions ? {
1245
- ...main,
1246
- [refs.definitionPath]: definitions
1247
- } : main : {
1248
- $ref: [
1249
- ...refs.$refStrategy === "relative" ? [] : refs.basePath,
1250
- refs.definitionPath,
1251
- name
1252
- ].join("/"),
1253
- [refs.definitionPath]: {
1254
- ...definitions,
1255
- [name]: main
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);
1256
2466
  }
1257
- };
1258
- if (refs.target === "jsonSchema7") {
1259
- combined.$schema = "http://json-schema.org/draft-07/schema#";
1260
- } else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") {
1261
- combined.$schema = "https://json-schema.org/draft/2019-09/schema#";
1262
2467
  }
1263
- if (refs.target === "openAi" && ("anyOf" in combined || "oneOf" in combined || "allOf" in combined || "type" in combined && Array.isArray(combined.type))) {
1264
- console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");
1265
- }
1266
- return combined;
1267
- };
2468
+ }
1268
2469
 
1269
2470
  // src/MCPLocal.ts
1270
- import {
1271
- Field,
1272
- Fields,
1273
- HandlInst,
1274
- MDEntryType,
1275
- Messages,
1276
- OrdType,
1277
- SubscriptionRequestType,
1278
- TimeInForce
1279
- } from "fixparser";
1280
- var MCPLocal = class {
1281
- logger;
1282
- parser;
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;
1283
2492
  server = new Server(
1284
2493
  {
1285
2494
  name: "fixparser",
@@ -1287,42 +2496,28 @@ var MCPLocal = class {
1287
2496
  },
1288
2497
  {
1289
2498
  capabilities: {
1290
- tools: {},
1291
- prompts: {},
1292
- resources: {}
2499
+ tools: Object.entries(toolSchemas).reduce(
2500
+ (acc, [name, { description, schema }]) => {
2501
+ acc[name] = {
2502
+ description,
2503
+ parameters: schema
2504
+ };
2505
+ return acc;
2506
+ },
2507
+ {}
2508
+ )
1293
2509
  }
1294
2510
  }
1295
2511
  );
1296
2512
  transport = new StdioServerTransport();
1297
- onReady = void 0;
1298
- pendingRequests = /* @__PURE__ */ new Map();
1299
2513
  constructor({ logger, onReady }) {
1300
- if (logger) this.logger = logger;
1301
- if (onReady) this.onReady = onReady;
2514
+ super({ logger, onReady });
1302
2515
  }
1303
2516
  async register(parser) {
1304
2517
  this.parser = parser;
1305
2518
  this.parser.addOnMessageCallback((message) => {
1306
- this.logger?.log({
1307
- level: "info",
1308
- message: `FIXParser (MCP): (${parser.protocol?.toUpperCase()}): << received ${message.description}`
1309
- });
1310
- const msgType = message.messageType;
1311
- if (msgType === Messages.MarketDataSnapshotFullRefresh || msgType === Messages.ExecutionReport) {
1312
- const idField = msgType === Messages.MarketDataSnapshotFullRefresh ? message.getField(Fields.MDReqID) : message.getField(Fields.ClOrdID);
1313
- if (idField) {
1314
- const id = idField.value;
1315
- if (typeof id === "string" || typeof id === "number") {
1316
- const callback = this.pendingRequests.get(String(id));
1317
- if (callback) {
1318
- callback(message);
1319
- this.pendingRequests.delete(String(id));
1320
- }
1321
- }
1322
- }
1323
- }
2519
+ handleMessage(message, this.parser, this.pendingRequests, this.marketDataPrices, this.MAX_PRICE_HISTORY);
1324
2520
  });
1325
- this.logger = parser.logger;
1326
2521
  this.addWorkflows();
1327
2522
  await this.server.connect(this.transport);
1328
2523
  if (this.onReady) {
@@ -1331,637 +2526,59 @@ var MCPLocal = class {
1331
2526
  }
1332
2527
  addWorkflows() {
1333
2528
  if (!this.parser) {
1334
- this.logger?.log({
1335
- level: "error",
1336
- message: "FIXParser (MCP): -- FIXParser instance not initialized. Ignoring setup of workflows..."
1337
- });
1338
2529
  return;
1339
2530
  }
1340
2531
  if (!this.server) {
1341
- this.logger?.log({
1342
- level: "error",
1343
- message: "FIXParser (MCP): -- MCP Server not initialized. Ignoring setup of workflows..."
1344
- });
1345
2532
  return;
1346
2533
  }
1347
- this.server.setRequestHandler(ListResourcesRequestSchema, async () => {
2534
+ this.server.setRequestHandler(z.object({ method: z.literal("tools/list") }), async () => {
1348
2535
  return {
1349
- resources: []
1350
- };
1351
- });
1352
- this.server.setRequestHandler(ListToolsRequestSchema, async () => {
1353
- return {
1354
- tools: [
1355
- {
1356
- name: "parse",
1357
- description: "Parses a FIX message and describes it in plain language",
1358
- inputSchema: zodToJsonSchema(
1359
- z.object({
1360
- fixString: z.string().describe("FIX message string to parse")
1361
- }),
1362
- { name: "ParseInput" }
1363
- )
1364
- },
1365
- {
1366
- name: "parseToJSON",
1367
- description: "Parses a FIX message into JSON",
1368
- inputSchema: zodToJsonSchema(
1369
- z.object({
1370
- fixString: z.string().describe("FIX message string to parse")
1371
- }),
1372
- { name: "ParseToJSONInput" }
1373
- )
1374
- },
1375
- {
1376
- name: "newOrderSingle",
1377
- description: "Creates and sends a New Order Single",
1378
- inputSchema: zodToJsonSchema(
1379
- z.object({
1380
- clOrdID: z.string().describe("Client Order ID"),
1381
- handlInst: z.enum(["1", "2", "3"]).default(HandlInst.AutomatedExecutionNoIntervention).optional().describe("Handling instruction"),
1382
- quantity: z.number().describe("Order quantity"),
1383
- price: z.number().describe("Order price"),
1384
- ordType: z.enum([
1385
- "1",
1386
- "2",
1387
- "3",
1388
- "4",
1389
- "5",
1390
- "6",
1391
- "7",
1392
- "8",
1393
- "9",
1394
- "A",
1395
- "B",
1396
- "C",
1397
- "D",
1398
- "E",
1399
- "F",
1400
- "G",
1401
- "H",
1402
- "I",
1403
- "J",
1404
- "K",
1405
- "L",
1406
- "M",
1407
- "P",
1408
- "Q",
1409
- "R",
1410
- "S"
1411
- ]).default("1").optional().describe("Order type"),
1412
- side: z.enum([
1413
- "1",
1414
- "2",
1415
- "3",
1416
- "4",
1417
- "5",
1418
- "6",
1419
- "7",
1420
- "8",
1421
- "9",
1422
- "A",
1423
- "B",
1424
- "C",
1425
- "D",
1426
- "E",
1427
- "F",
1428
- "G",
1429
- "H"
1430
- ]).describe("Order side (1=Buy, 2=Sell)"),
1431
- symbol: z.string().describe("Trading symbol"),
1432
- timeInForce: z.enum(["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C"]).default(TimeInForce.Day).optional().describe("Time in force")
1433
- }),
1434
- { name: "NewOrderSingleInput" }
1435
- )
1436
- },
1437
- {
1438
- name: "marketDataRequest",
1439
- description: "Sends a request for Market Data with the given symbol",
1440
- inputSchema: zodToJsonSchema(
1441
- z.object({
1442
- mdUpdateType: z.enum(["0", "1"]).default("0").optional().describe("Market data update type"),
1443
- symbol: z.string().describe("Trading symbol"),
1444
- mdReqID: z.string().describe("Market data request ID"),
1445
- subscriptionRequestType: z.enum(["0", "1", "2"]).default(SubscriptionRequestType.SnapshotAndUpdates).optional().describe("Subscription request type"),
1446
- mdEntryType: z.enum([
1447
- "0",
1448
- "1",
1449
- "2",
1450
- "3",
1451
- "4",
1452
- "5",
1453
- "6",
1454
- "7",
1455
- "8",
1456
- "9",
1457
- "A",
1458
- "B",
1459
- "C",
1460
- "D",
1461
- "E",
1462
- "F",
1463
- "G",
1464
- "H",
1465
- "J",
1466
- "K",
1467
- "L",
1468
- "M",
1469
- "N",
1470
- "O",
1471
- "P",
1472
- "Q",
1473
- "S",
1474
- "R",
1475
- "T",
1476
- "U",
1477
- "V",
1478
- "W",
1479
- "X",
1480
- "Y",
1481
- "Z",
1482
- "a",
1483
- "b",
1484
- "c",
1485
- "d",
1486
- "e",
1487
- "g",
1488
- "h",
1489
- "i",
1490
- "t"
1491
- ]).default(MDEntryType.Bid).optional().describe("Market data entry type")
1492
- }),
1493
- { name: "MarketDataRequestInput" }
1494
- )
1495
- }
1496
- ]
2536
+ tools: Object.entries(toolSchemas).map(([name, { description, schema }]) => ({
2537
+ name,
2538
+ description,
2539
+ inputSchema: schema
2540
+ }))
1497
2541
  };
1498
2542
  });
1499
- this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
1500
- const { name, arguments: args } = request.params;
1501
- switch (name) {
1502
- case "parse": {
1503
- const { fixString } = z.object({
1504
- fixString: z.string().describe("FIX message string to parse")
1505
- }).parse(args || {});
1506
- try {
1507
- const parsedMessage = this.parser?.parse(fixString);
1508
- if (!parsedMessage || parsedMessage.length === 0) {
1509
- return {
1510
- isError: true,
1511
- content: [{ type: "text", text: "Error: Failed to parse FIX string" }]
1512
- };
1513
- }
1514
- return {
1515
- content: [
1516
- {
1517
- type: "text",
1518
- text: `Parsed FIX message: ${fixString} (placeholder implementation)`
1519
- }
1520
- ]
1521
- };
1522
- } catch (error) {
1523
- return {
1524
- isError: true,
1525
- content: [
1526
- {
1527
- type: "text",
1528
- text: "Error: Failed to parse FIX string"
1529
- }
1530
- ]
1531
- };
1532
- }
1533
- }
1534
- case "parseToJSON": {
1535
- const { fixString } = z.object({
1536
- fixString: z.string().describe("FIX message string to parse")
1537
- }).parse(args || {});
1538
- try {
1539
- const parsedMessage = this.parser?.parse(fixString);
1540
- if (!parsedMessage || parsedMessage.length === 0) {
1541
- return {
1542
- isError: true,
1543
- content: [{ type: "text", text: "Error: Failed to parse FIX string" }]
1544
- };
1545
- }
1546
- return {
1547
- content: [
1548
- {
1549
- type: "text",
1550
- text: JSON.stringify({ fixString, parsed: "placeholder" })
1551
- }
1552
- ]
1553
- };
1554
- } catch (error) {
1555
- return {
1556
- isError: true,
1557
- content: [
1558
- {
1559
- type: "text",
1560
- text: "Error: Failed to parse FIX string"
1561
- }
1562
- ]
1563
- };
1564
- }
1565
- }
1566
- case "newOrderSingle": {
1567
- const { clOrdID, handlInst, quantity, price, ordType, side, symbol, timeInForce } = z.object({
1568
- clOrdID: z.string().describe("Client Order ID"),
1569
- handlInst: z.enum(["1", "2", "3"]).default(HandlInst.AutomatedExecutionNoIntervention).optional().describe("Handling instruction"),
1570
- quantity: z.number().describe("Order quantity"),
1571
- price: z.number().describe("Order price"),
1572
- ordType: z.enum([
1573
- "1",
1574
- "2",
1575
- "3",
1576
- "4",
1577
- "5",
1578
- "6",
1579
- "7",
1580
- "8",
1581
- "9",
1582
- "A",
1583
- "B",
1584
- "C",
1585
- "D",
1586
- "E",
1587
- "F",
1588
- "G",
1589
- "H",
1590
- "I",
1591
- "J",
1592
- "K",
1593
- "L",
1594
- "M",
1595
- "P",
1596
- "Q",
1597
- "R",
1598
- "S"
1599
- ]).default(OrdType.Market).optional().describe("Order type"),
1600
- side: z.enum([
1601
- "1",
1602
- "2",
1603
- "3",
1604
- "4",
1605
- "5",
1606
- "6",
1607
- "7",
1608
- "8",
1609
- "9",
1610
- "A",
1611
- "B",
1612
- "C",
1613
- "D",
1614
- "E",
1615
- "F",
1616
- "G",
1617
- "H"
1618
- ]).describe("Order side (1=Buy, 2=Sell)"),
1619
- symbol: z.string().describe("Trading symbol"),
1620
- timeInForce: z.enum(["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C"]).default(TimeInForce.Day).optional().describe("Time in force")
1621
- }).parse(args || {});
1622
- const response = new Promise((resolve) => {
1623
- this.pendingRequests.set(clOrdID, resolve);
1624
- });
1625
- const order = this.parser?.createMessage(
1626
- new Field(Fields.MsgType, Messages.NewOrderSingle),
1627
- new Field(Fields.MsgSeqNum, this.parser?.getNextTargetMsgSeqNum()),
1628
- new Field(Fields.SenderCompID, this.parser?.sender),
1629
- new Field(Fields.TargetCompID, this.parser?.target),
1630
- new Field(Fields.SendingTime, this.parser?.getTimestamp()),
1631
- new Field(Fields.ClOrdID, clOrdID),
1632
- new Field(Fields.Side, side),
1633
- new Field(Fields.Symbol, symbol),
1634
- new Field(Fields.OrderQty, quantity),
1635
- new Field(Fields.Price, price),
1636
- new Field(Fields.OrdType, ordType),
1637
- new Field(Fields.HandlInst, handlInst),
1638
- new Field(Fields.TimeInForce, timeInForce),
1639
- new Field(Fields.TransactTime, this.parser?.getTimestamp())
1640
- );
1641
- if (!this.parser?.connected) {
1642
- this.logger?.log({
1643
- level: "error",
1644
- message: "FIXParser (MCP): -- Not connected. Ignoring message."
1645
- });
1646
- return {
1647
- isError: true,
1648
- content: [
1649
- {
1650
- type: "text",
1651
- text: "Error: Not connected. Ignoring message."
1652
- }
1653
- ]
1654
- };
1655
- }
1656
- this.parser?.send(order);
1657
- this.logger?.log({
1658
- level: "info",
1659
- message: `FIXParser (MCP): (${this.parser?.protocol?.toUpperCase()}): >> sent ${order?.description}`
1660
- });
1661
- const fixData = await response;
1662
- return {
1663
- content: [
1664
- {
1665
- type: "text",
1666
- text: `Execution Report for order ${clOrdID}: ${JSON.stringify(fixData.toFIXJSON())}`
1667
- }
1668
- ]
1669
- };
1670
- }
1671
- case "marketDataRequest": {
1672
- const { mdUpdateType, symbol, mdReqID, subscriptionRequestType, mdEntryType } = z.object({
1673
- mdUpdateType: z.enum(["0", "1"]).default("0").optional().describe("Market data update type"),
1674
- symbol: z.string().describe("Trading symbol"),
1675
- mdReqID: z.string().describe("Market data request ID"),
1676
- subscriptionRequestType: z.enum(["0", "1", "2"]).default(SubscriptionRequestType.SnapshotAndUpdates).optional().describe("Subscription request type"),
1677
- mdEntryType: z.enum([
1678
- "0",
1679
- "1",
1680
- "2",
1681
- "3",
1682
- "4",
1683
- "5",
1684
- "6",
1685
- "7",
1686
- "8",
1687
- "9",
1688
- "A",
1689
- "B",
1690
- "C",
1691
- "D",
1692
- "E",
1693
- "F",
1694
- "G",
1695
- "H",
1696
- "J",
1697
- "K",
1698
- "L",
1699
- "M",
1700
- "N",
1701
- "O",
1702
- "P",
1703
- "Q",
1704
- "S",
1705
- "R",
1706
- "T",
1707
- "U",
1708
- "V",
1709
- "W",
1710
- "X",
1711
- "Y",
1712
- "Z",
1713
- "a",
1714
- "b",
1715
- "c",
1716
- "d",
1717
- "e",
1718
- "g",
1719
- "h",
1720
- "i",
1721
- "t"
1722
- ]).default(MDEntryType.Bid).optional().describe("Market data entry type")
1723
- }).parse(args || {});
1724
- const response = new Promise((resolve) => {
1725
- this.pendingRequests.set(mdReqID, resolve);
1726
- });
1727
- const marketDataRequest = this.parser?.createMessage(
1728
- new Field(Fields.MsgType, Messages.MarketDataRequest),
1729
- new Field(Fields.SenderCompID, this.parser?.sender),
1730
- new Field(Fields.MsgSeqNum, this.parser?.getNextTargetMsgSeqNum()),
1731
- new Field(Fields.TargetCompID, this.parser?.target),
1732
- new Field(Fields.SendingTime, this.parser?.getTimestamp()),
1733
- new Field(Fields.MarketDepth, 0),
1734
- new Field(Fields.MDUpdateType, mdUpdateType),
1735
- new Field(Fields.NoRelatedSym, 1),
1736
- new Field(Fields.Symbol, symbol),
1737
- new Field(Fields.MDReqID, mdReqID),
1738
- new Field(Fields.SubscriptionRequestType, subscriptionRequestType),
1739
- new Field(Fields.NoMDEntryTypes, 1),
1740
- new Field(Fields.MDEntryType, mdEntryType)
1741
- );
1742
- if (!this.parser?.connected) {
1743
- this.logger?.log({
1744
- level: "error",
1745
- message: "FIXParser (MCP): -- Not connected. Ignoring message."
1746
- });
1747
- return {
1748
- isError: true,
1749
- content: [
1750
- {
1751
- type: "text",
1752
- text: "Error: Not connected. Ignoring message."
1753
- }
1754
- ]
1755
- };
1756
- }
1757
- this.parser?.send(marketDataRequest);
1758
- this.logger?.log({
1759
- level: "info",
1760
- message: `FIXParser (MCP): (${this.parser?.protocol?.toUpperCase()}): >> sent ${marketDataRequest?.description}`
1761
- });
1762
- const fixData = await response;
2543
+ this.server.setRequestHandler(
2544
+ 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
+ })
2553
+ }),
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) {
1763
2564
  return {
1764
2565
  content: [
1765
2566
  {
1766
2567
  type: "text",
1767
- text: `Market data for ${symbol}: ${JSON.stringify(fixData.toFIXJSON())}`
1768
- }
1769
- ]
1770
- };
1771
- }
1772
- default:
1773
- throw new Error(`Unknown tool: ${name}`);
1774
- }
1775
- });
1776
- this.server.setRequestHandler(ListPromptsRequestSchema, async () => {
1777
- return {
1778
- prompts: [
1779
- {
1780
- name: "parse",
1781
- description: "Parses a FIX message and describes it in plain language",
1782
- arguments: [
1783
- {
1784
- name: "fixString",
1785
- description: "FIX message string to parse",
1786
- required: true
1787
- }
1788
- ]
1789
- },
1790
- {
1791
- name: "parseToJSON",
1792
- description: "Parses a FIX message into JSON",
1793
- arguments: [
1794
- {
1795
- name: "fixString",
1796
- description: "FIX message string to parse",
1797
- required: true
1798
- }
1799
- ]
1800
- },
1801
- {
1802
- name: "newOrderSingle",
1803
- description: "Creates and sends a New Order Single",
1804
- arguments: [
1805
- {
1806
- name: "clOrdID",
1807
- description: "Client Order ID",
1808
- required: true
1809
- },
1810
- {
1811
- name: "handlInst",
1812
- description: "Handling instruction",
1813
- required: false
1814
- },
1815
- {
1816
- name: "quantity",
1817
- description: "Order quantity",
1818
- required: true
1819
- },
1820
- {
1821
- name: "price",
1822
- description: "Order price",
1823
- required: true
1824
- },
1825
- {
1826
- name: "ordType",
1827
- description: "Order type",
1828
- required: false
1829
- },
1830
- {
1831
- name: "side",
1832
- description: "Order side (1=Buy, 2=Sell)",
1833
- required: true
1834
- },
1835
- {
1836
- name: "symbol",
1837
- description: "Trading symbol",
1838
- required: true
1839
- },
1840
- {
1841
- name: "timeInForce",
1842
- description: "Time in force",
1843
- required: false
1844
- }
1845
- ]
1846
- },
1847
- {
1848
- name: "marketDataRequest",
1849
- description: "Sends a request for Market Data with the given symbol",
1850
- arguments: [
1851
- {
1852
- name: "mdUpdateType",
1853
- description: "Market data update type",
1854
- required: false
1855
- },
1856
- {
1857
- name: "symbol",
1858
- description: "Trading symbol",
1859
- required: true
1860
- },
1861
- {
1862
- name: "mdReqID",
1863
- description: "Market data request ID",
1864
- required: true
1865
- },
1866
- {
1867
- name: "subscriptionRequestType",
1868
- description: "Subscription request type",
1869
- required: false
1870
- },
1871
- {
1872
- name: "mdEntryType",
1873
- description: "Market data entry type",
1874
- required: false
1875
- }
1876
- ]
1877
- }
1878
- ]
1879
- };
1880
- });
1881
- this.server.setRequestHandler(GetPromptRequestSchema, async (request) => {
1882
- const { name, arguments: args } = request.params;
1883
- switch (name) {
1884
- case "parse": {
1885
- const fixString = args?.fixString || "";
1886
- return {
1887
- messages: [
1888
- {
1889
- role: "user",
1890
- content: {
1891
- type: "text",
1892
- text: `Please parse and explain this FIX message: ${fixString}`
1893
- }
1894
- }
1895
- ]
1896
- };
1897
- }
1898
- case "parseToJSON": {
1899
- const fixString = args?.fixString || "";
1900
- return {
1901
- messages: [
1902
- {
1903
- role: "user",
1904
- content: {
1905
- type: "text",
1906
- text: `Please parse the FIX message to JSON: ${fixString}`
1907
- }
1908
- }
1909
- ]
1910
- };
1911
- }
1912
- case "newOrderSingle": {
1913
- const { clOrdID, handlInst, quantity, price, ordType, side, symbol, timeInForce } = args || {};
1914
- return {
1915
- messages: [
1916
- {
1917
- role: "user",
1918
- content: {
1919
- type: "text",
1920
- text: [
1921
- "Create a New Order Single FIX message with the following parameters:",
1922
- `- ClOrdID: ${clOrdID}`,
1923
- `- HandlInst: ${handlInst ?? "default"}`,
1924
- `- Quantity: ${quantity}`,
1925
- `- Price: ${price}`,
1926
- `- OrdType: ${ordType ?? "default (Market)"}`,
1927
- `- Side: ${side}`,
1928
- `- Symbol: ${symbol}`,
1929
- `- TimeInForce: ${timeInForce ?? "default (Day)"}`,
1930
- "",
1931
- "Format the response as a JSON object with FIX tag numbers as keys and their corresponding values."
1932
- ].join("\n")
1933
- }
2568
+ text: `Tool not found: ${name}`,
2569
+ uri: name
1934
2570
  }
1935
- ]
1936
- };
1937
- }
1938
- case "marketDataRequest": {
1939
- const { mdUpdateType, symbol, mdReqID, subscriptionRequestType, mdEntryType } = args || {};
1940
- return {
1941
- messages: [
1942
- {
1943
- role: "user",
1944
- content: {
1945
- type: "text",
1946
- text: [
1947
- "Create a Market Data Request FIX message with the following parameters:",
1948
- `- MDUpdateType: ${mdUpdateType ?? "default (0 = FullRefresh)"}`,
1949
- `- Symbol: ${symbol}`,
1950
- `- MDReqID: ${mdReqID}`,
1951
- `- SubscriptionRequestType: ${subscriptionRequestType ?? "default (0 = Snapshot + Updates)"}`,
1952
- `- MDEntryType: ${mdEntryType ?? "default (0 = Bid)"}`,
1953
- "",
1954
- "Format the response as a JSON object with FIX tag numbers as keys and their corresponding values."
1955
- ].join("\n")
1956
- }
1957
- }
1958
- ]
2571
+ ],
2572
+ isError: true
1959
2573
  };
1960
2574
  }
1961
- default:
1962
- throw new Error(`Unknown prompt: ${name}`);
2575
+ const result = await handler(args);
2576
+ return {
2577
+ content: result.content,
2578
+ isError: result.isError
2579
+ };
1963
2580
  }
1964
- });
2581
+ );
1965
2582
  process.on("SIGINT", async () => {
1966
2583
  await this.server.close();
1967
2584
  process.exit(0);