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