fixparser-plugin-mcp 9.1.7-148b599b → 9.1.7-1818bee7
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.
- package/build/cjs/MCPLocal.js +3090 -778
- package/build/cjs/MCPLocal.js.map +4 -4
- package/build/cjs/MCPRemote.js +3152 -437
- package/build/cjs/MCPRemote.js.map +4 -4
- package/build/cjs/index.js +3449 -0
- package/build/cjs/index.js.map +7 -0
- package/build/esm/MCPLocal.mjs +3081 -785
- package/build/esm/MCPLocal.mjs.map +4 -4
- package/build/esm/MCPRemote.mjs +3143 -447
- package/build/esm/MCPRemote.mjs.map +4 -4
- package/build/esm/index.mjs +3411 -0
- package/build/esm/index.mjs.map +7 -0
- package/build-examples/cjs/example_mcp_local.js +14 -15
- package/build-examples/cjs/example_mcp_local.js.map +4 -4
- package/build-examples/cjs/example_mcp_remote.js +18 -0
- package/build-examples/cjs/example_mcp_remote.js.map +7 -0
- package/build-examples/esm/example_mcp_local.mjs +14 -15
- package/build-examples/esm/example_mcp_local.mjs.map +4 -4
- package/build-examples/esm/example_mcp_remote.mjs +18 -0
- package/build-examples/esm/example_mcp_remote.mjs.map +7 -0
- package/package.json +11 -11
- package/types/MCPLocal.d.ts +0 -14
- package/types/MCPRemote.d.ts +0 -60
- package/types/PluginOptions.d.ts +0 -6
- package/types/index.d.ts +0 -3
package/build/cjs/MCPLocal.js
CHANGED
|
@@ -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,174 +35,3044 @@ __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
|
|
38
|
+
var import_zod = require("zod");
|
|
39
|
+
|
|
40
|
+
// src/MCPBase.ts
|
|
41
|
+
var MCPBase = class {
|
|
42
|
+
/**
|
|
43
|
+
* Optional logger instance for diagnostics and output.
|
|
44
|
+
* @protected
|
|
45
|
+
*/
|
|
46
|
+
logger;
|
|
47
|
+
/**
|
|
48
|
+
* FIXParser instance, set during plugin register().
|
|
49
|
+
* @protected
|
|
50
|
+
*/
|
|
51
|
+
parser;
|
|
52
|
+
/**
|
|
53
|
+
* Called when server is setup and listening.
|
|
54
|
+
* @protected
|
|
55
|
+
*/
|
|
56
|
+
onReady = void 0;
|
|
57
|
+
/**
|
|
58
|
+
* Map to store verified orders before execution
|
|
59
|
+
* @protected
|
|
60
|
+
*/
|
|
61
|
+
verifiedOrders = /* @__PURE__ */ new Map();
|
|
62
|
+
/**
|
|
63
|
+
* Map to store pending market data requests
|
|
64
|
+
* @protected
|
|
65
|
+
*/
|
|
66
|
+
pendingRequests = /* @__PURE__ */ new Map();
|
|
67
|
+
/**
|
|
68
|
+
* Map to store market data prices
|
|
69
|
+
* @protected
|
|
70
|
+
*/
|
|
71
|
+
marketDataPrices = /* @__PURE__ */ new Map();
|
|
72
|
+
/**
|
|
73
|
+
* Maximum number of price history entries to keep per symbol
|
|
74
|
+
* @protected
|
|
75
|
+
*/
|
|
76
|
+
MAX_PRICE_HISTORY = 1e5;
|
|
77
|
+
constructor({ logger, onReady }) {
|
|
78
|
+
this.logger = logger;
|
|
79
|
+
this.onReady = onReady;
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
// src/schemas/schemas.ts
|
|
84
|
+
var toolSchemas = {
|
|
85
|
+
parse: {
|
|
86
|
+
description: "Parses a FIX message and describes it in plain language",
|
|
87
|
+
schema: {
|
|
88
|
+
type: "object",
|
|
89
|
+
properties: {
|
|
90
|
+
fixString: { type: "string" }
|
|
91
|
+
},
|
|
92
|
+
required: ["fixString"]
|
|
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
|
+
}
|
|
323
|
+
}
|
|
324
|
+
};
|
|
325
|
+
|
|
326
|
+
// src/tools/indicators/momentum.ts
|
|
327
|
+
var MomentumIndicators = class {
|
|
328
|
+
/**
|
|
329
|
+
* Calculate RSI (Relative Strength Index)
|
|
330
|
+
*/
|
|
331
|
+
static calculateRSI(data, period = 14) {
|
|
332
|
+
if (data.length < period + 1) return [];
|
|
333
|
+
const changes = [];
|
|
334
|
+
for (let i = 1; i < data.length; i++) {
|
|
335
|
+
changes.push(data[i] - data[i - 1]);
|
|
336
|
+
}
|
|
337
|
+
const gains = changes.map((change) => change > 0 ? change : 0);
|
|
338
|
+
const losses = changes.map((change) => change < 0 ? Math.abs(change) : 0);
|
|
339
|
+
let avgGain = gains.slice(0, period).reduce((a, b) => a + b, 0) / period;
|
|
340
|
+
let avgLoss = losses.slice(0, period).reduce((a, b) => a + b, 0) / period;
|
|
341
|
+
const rsi = [];
|
|
342
|
+
for (let i = period; i < changes.length; i++) {
|
|
343
|
+
const rs = avgGain / avgLoss;
|
|
344
|
+
rsi.push(100 - 100 / (1 + rs));
|
|
345
|
+
avgGain = (avgGain * (period - 1) + gains[i]) / period;
|
|
346
|
+
avgLoss = (avgLoss * (period - 1) + losses[i]) / period;
|
|
347
|
+
}
|
|
348
|
+
return rsi;
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* Calculate Stochastic Oscillator
|
|
352
|
+
*/
|
|
353
|
+
static calculateStochastic(prices, highs, lows) {
|
|
354
|
+
const stochastic = [];
|
|
355
|
+
const period = 14;
|
|
356
|
+
const smoothK = 3;
|
|
357
|
+
const smoothD = 3;
|
|
358
|
+
if (prices.length < period) return [];
|
|
359
|
+
const percentK = [];
|
|
360
|
+
for (let i = period - 1; i < prices.length; i++) {
|
|
361
|
+
const high = Math.max(...highs.slice(i - period + 1, i + 1));
|
|
362
|
+
const low = Math.min(...lows.slice(i - period + 1, i + 1));
|
|
363
|
+
const close = prices[i];
|
|
364
|
+
const k = (close - low) / (high - low) * 100;
|
|
365
|
+
percentK.push(k);
|
|
366
|
+
}
|
|
367
|
+
const smoothedK = [];
|
|
368
|
+
for (let i = smoothK - 1; i < percentK.length; i++) {
|
|
369
|
+
const sum2 = percentK.slice(i - smoothK + 1, i + 1).reduce((a, b) => a + b, 0);
|
|
370
|
+
smoothedK.push(sum2 / smoothK);
|
|
371
|
+
}
|
|
372
|
+
for (let i = smoothD - 1; i < smoothedK.length; i++) {
|
|
373
|
+
const sum2 = smoothedK.slice(i - smoothD + 1, i + 1).reduce((a, b) => a + b, 0);
|
|
374
|
+
const d = sum2 / smoothD;
|
|
375
|
+
stochastic.push({
|
|
376
|
+
k: smoothedK[i],
|
|
377
|
+
d
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
return stochastic;
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
383
|
+
* Calculate CCI (Commodity Channel Index)
|
|
384
|
+
*/
|
|
385
|
+
static calculateCCI(prices, highs, lows) {
|
|
386
|
+
const cci = [];
|
|
387
|
+
const period = 20;
|
|
388
|
+
if (prices.length < period) return [];
|
|
389
|
+
for (let i = period - 1; i < prices.length; i++) {
|
|
390
|
+
const slice = prices.slice(i - period + 1, i + 1);
|
|
391
|
+
const typicalPrices = slice.map((price, idx) => {
|
|
392
|
+
const high = highs[i - period + 1 + idx] || price;
|
|
393
|
+
const low = lows[i - period + 1 + idx] || price;
|
|
394
|
+
return (high + low + price) / 3;
|
|
395
|
+
});
|
|
396
|
+
const sma = typicalPrices.reduce((a, b) => a + b, 0) / period;
|
|
397
|
+
const meanDeviation = typicalPrices.reduce((sum2, tp) => sum2 + Math.abs(tp - sma), 0) / period;
|
|
398
|
+
const currentTP = (highs[i] + lows[i] + prices[i]) / 3;
|
|
399
|
+
const cciValue = meanDeviation !== 0 ? (currentTP - sma) / (0.015 * meanDeviation) : 0;
|
|
400
|
+
cci.push(cciValue);
|
|
401
|
+
}
|
|
402
|
+
return cci;
|
|
403
|
+
}
|
|
404
|
+
/**
|
|
405
|
+
* Calculate Rate of Change
|
|
406
|
+
*/
|
|
407
|
+
static calculateROC(prices) {
|
|
408
|
+
const roc = [];
|
|
409
|
+
for (let i = 10; i < prices.length; i++) {
|
|
410
|
+
roc.push((prices[i] - prices[i - 10]) / prices[i - 10] * 100);
|
|
411
|
+
}
|
|
412
|
+
return roc;
|
|
413
|
+
}
|
|
414
|
+
/**
|
|
415
|
+
* Calculate Williams %R
|
|
416
|
+
*/
|
|
417
|
+
static calculateWilliamsR(prices) {
|
|
418
|
+
const williamsR = [];
|
|
419
|
+
const period = 14;
|
|
420
|
+
if (prices.length < period) return [];
|
|
421
|
+
for (let i = period - 1; i < prices.length; i++) {
|
|
422
|
+
const slice = prices.slice(i - period + 1, i + 1);
|
|
423
|
+
const high = Math.max(...slice);
|
|
424
|
+
const low = Math.min(...slice);
|
|
425
|
+
const close = prices[i];
|
|
426
|
+
const wr = (high - close) / (high - low) * -100;
|
|
427
|
+
williamsR.push(wr);
|
|
428
|
+
}
|
|
429
|
+
return williamsR;
|
|
430
|
+
}
|
|
431
|
+
/**
|
|
432
|
+
* Calculate Momentum
|
|
433
|
+
*/
|
|
434
|
+
static calculateMomentum(prices) {
|
|
435
|
+
const momentum = [];
|
|
436
|
+
for (let i = 10; i < prices.length; i++) {
|
|
437
|
+
momentum.push(prices[i] - prices[i - 10]);
|
|
438
|
+
}
|
|
439
|
+
return momentum;
|
|
440
|
+
}
|
|
441
|
+
};
|
|
442
|
+
|
|
443
|
+
// src/tools/indicators/movingAverages.ts
|
|
444
|
+
var MovingAverages = class {
|
|
445
|
+
/**
|
|
446
|
+
* Calculate Simple Moving Average
|
|
447
|
+
*/
|
|
448
|
+
static calculateSMA(data, period) {
|
|
449
|
+
const sma = [];
|
|
450
|
+
for (let i = period - 1; i < data.length; i++) {
|
|
451
|
+
const sum2 = data.slice(i - period + 1, i + 1).reduce((a, b) => a + b, 0);
|
|
452
|
+
sma.push(sum2 / period);
|
|
453
|
+
}
|
|
454
|
+
return sma;
|
|
455
|
+
}
|
|
456
|
+
/**
|
|
457
|
+
* Calculate Exponential Moving Average
|
|
458
|
+
*/
|
|
459
|
+
static calculateEMA(data, period) {
|
|
460
|
+
const multiplier = 2 / (period + 1);
|
|
461
|
+
const ema = [data[0]];
|
|
462
|
+
for (let i = 1; i < data.length; i++) {
|
|
463
|
+
ema.push(data[i] * multiplier + ema[i - 1] * (1 - multiplier));
|
|
464
|
+
}
|
|
465
|
+
return ema;
|
|
466
|
+
}
|
|
467
|
+
/**
|
|
468
|
+
* Calculate Weighted Moving Average
|
|
469
|
+
*/
|
|
470
|
+
static calculateWMA(data, period) {
|
|
471
|
+
const wma = [];
|
|
472
|
+
const weights = Array.from({ length: period }, (_, i) => i + 1);
|
|
473
|
+
const weightSum = weights.reduce((a, b) => a + b, 0);
|
|
474
|
+
for (let i = period - 1; i < data.length; i++) {
|
|
475
|
+
let weightedSum = 0;
|
|
476
|
+
for (let j = 0; j < period; j++) {
|
|
477
|
+
weightedSum += data[i - j] * weights[j];
|
|
478
|
+
}
|
|
479
|
+
wma.push(weightedSum / weightSum);
|
|
480
|
+
}
|
|
481
|
+
return wma;
|
|
482
|
+
}
|
|
483
|
+
/**
|
|
484
|
+
* Calculate Volume Weighted Moving Average
|
|
485
|
+
*/
|
|
486
|
+
static calculateVWMA(prices, volumes, period) {
|
|
487
|
+
const vwma = [];
|
|
488
|
+
for (let i = period - 1; i < prices.length; i++) {
|
|
489
|
+
let volumeSum = 0;
|
|
490
|
+
let priceVolumeSum = 0;
|
|
491
|
+
for (let j = 0; j < period; j++) {
|
|
492
|
+
const volume = volumes[i - j] || 1;
|
|
493
|
+
volumeSum += volume;
|
|
494
|
+
priceVolumeSum += prices[i - j] * volume;
|
|
495
|
+
}
|
|
496
|
+
vwma.push(priceVolumeSum / volumeSum);
|
|
497
|
+
}
|
|
498
|
+
return vwma;
|
|
499
|
+
}
|
|
500
|
+
};
|
|
501
|
+
|
|
502
|
+
// src/tools/indicators/options.ts
|
|
503
|
+
var OptionsAnalysis = class _OptionsAnalysis {
|
|
504
|
+
/**
|
|
505
|
+
* Calculate Black-Scholes Option Pricing
|
|
506
|
+
*/
|
|
507
|
+
static calculateBlackScholes(currentPrice, startPrice, avgVolume) {
|
|
508
|
+
const S = currentPrice;
|
|
509
|
+
const K = startPrice;
|
|
510
|
+
const T = 1;
|
|
511
|
+
const r = 0.05;
|
|
512
|
+
const sigma = avgVolume * 0.01;
|
|
513
|
+
const d1 = (Math.log(S / K) + (r + sigma * sigma / 2) * T) / (sigma * Math.sqrt(T));
|
|
514
|
+
const d2 = d1 - sigma * Math.sqrt(T);
|
|
515
|
+
const callPrice = S * _OptionsAnalysis.normalCDF(d1) - K * Math.exp(-r * T) * _OptionsAnalysis.normalCDF(d2);
|
|
516
|
+
const putPrice = K * Math.exp(-r * T) * _OptionsAnalysis.normalCDF(-d2) - S * _OptionsAnalysis.normalCDF(-d1);
|
|
517
|
+
return {
|
|
518
|
+
callPrice,
|
|
519
|
+
putPrice,
|
|
520
|
+
delta: _OptionsAnalysis.normalCDF(d1),
|
|
521
|
+
gamma: _OptionsAnalysis.normalPDF(d1) / (S * sigma * Math.sqrt(T)),
|
|
522
|
+
theta: -S * _OptionsAnalysis.normalPDF(d1) * sigma / (2 * Math.sqrt(T)) - r * K * Math.exp(-r * T) * _OptionsAnalysis.normalCDF(d2),
|
|
523
|
+
vega: S * Math.sqrt(T) * _OptionsAnalysis.normalPDF(d1),
|
|
524
|
+
rho: K * T * Math.exp(-r * T) * _OptionsAnalysis.normalCDF(d2)
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
/**
|
|
528
|
+
* Normal CDF approximation
|
|
529
|
+
*/
|
|
530
|
+
static normalCDF(x) {
|
|
531
|
+
return 0.5 * (1 + _OptionsAnalysis.erf(x / Math.sqrt(2)));
|
|
532
|
+
}
|
|
533
|
+
/**
|
|
534
|
+
* Normal PDF
|
|
535
|
+
*/
|
|
536
|
+
static normalPDF(x) {
|
|
537
|
+
return Math.exp(-x * x / 2) / Math.sqrt(2 * Math.PI);
|
|
538
|
+
}
|
|
539
|
+
/**
|
|
540
|
+
* Error function approximation
|
|
541
|
+
*/
|
|
542
|
+
static erf(x) {
|
|
543
|
+
const a1 = 0.254829592;
|
|
544
|
+
const a2 = -0.284496736;
|
|
545
|
+
const a3 = 1.421413741;
|
|
546
|
+
const a4 = -1.453152027;
|
|
547
|
+
const a5 = 1.061405429;
|
|
548
|
+
const p = 0.3275911;
|
|
549
|
+
const sign = x >= 0 ? 1 : -1;
|
|
550
|
+
const absX = Math.abs(x);
|
|
551
|
+
const t = 1 / (1 + p * absX);
|
|
552
|
+
const y = 1 - ((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t * Math.exp(-absX * absX);
|
|
553
|
+
return sign * y;
|
|
554
|
+
}
|
|
555
|
+
};
|
|
556
|
+
|
|
557
|
+
// src/tools/indicators/performance.ts
|
|
558
|
+
var PerformanceAnalysis = class {
|
|
559
|
+
/**
|
|
560
|
+
* Calculate maximum drawdown
|
|
561
|
+
*/
|
|
562
|
+
static calculateMaxDrawdown(prices) {
|
|
563
|
+
let maxPrice = prices[0];
|
|
564
|
+
let maxDrawdown = 0;
|
|
565
|
+
for (let i = 1; i < prices.length; i++) {
|
|
566
|
+
if (prices[i] > maxPrice) {
|
|
567
|
+
maxPrice = prices[i];
|
|
568
|
+
}
|
|
569
|
+
const drawdown = (maxPrice - prices[i]) / maxPrice;
|
|
570
|
+
if (drawdown > maxDrawdown) {
|
|
571
|
+
maxDrawdown = drawdown;
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
return maxDrawdown;
|
|
575
|
+
}
|
|
576
|
+
/**
|
|
577
|
+
* Calculate maximum consecutive losses
|
|
578
|
+
*/
|
|
579
|
+
static calculateMaxConsecutiveLosses(prices) {
|
|
580
|
+
let maxConsecutive = 0;
|
|
581
|
+
let currentConsecutive = 0;
|
|
582
|
+
for (let i = 1; i < prices.length; i++) {
|
|
583
|
+
if (prices[i] < prices[i - 1]) {
|
|
584
|
+
currentConsecutive++;
|
|
585
|
+
maxConsecutive = Math.max(maxConsecutive, currentConsecutive);
|
|
586
|
+
} else {
|
|
587
|
+
currentConsecutive = 0;
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
return maxConsecutive;
|
|
591
|
+
}
|
|
592
|
+
/**
|
|
593
|
+
* Calculate win rate
|
|
594
|
+
*/
|
|
595
|
+
static calculateWinRate(prices) {
|
|
596
|
+
let wins = 0;
|
|
597
|
+
let total = 0;
|
|
598
|
+
for (let i = 1; i < prices.length; i++) {
|
|
599
|
+
if (prices[i] !== prices[i - 1]) {
|
|
600
|
+
total++;
|
|
601
|
+
if (prices[i] > prices[i - 1]) {
|
|
602
|
+
wins++;
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
return total > 0 ? wins / total : 0;
|
|
607
|
+
}
|
|
608
|
+
/**
|
|
609
|
+
* Calculate profit factor
|
|
610
|
+
*/
|
|
611
|
+
static calculateProfitFactor(prices) {
|
|
612
|
+
let grossProfit = 0;
|
|
613
|
+
let grossLoss = 0;
|
|
614
|
+
for (let i = 1; i < prices.length; i++) {
|
|
615
|
+
const change = prices[i] - prices[i - 1];
|
|
616
|
+
if (change > 0) {
|
|
617
|
+
grossProfit += change;
|
|
618
|
+
} else {
|
|
619
|
+
grossLoss += Math.abs(change);
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
return grossLoss > 0 ? grossProfit / grossLoss : 0;
|
|
623
|
+
}
|
|
624
|
+
/**
|
|
625
|
+
* Calculate Sharpe Ratio
|
|
626
|
+
*/
|
|
627
|
+
static calculateSharpeRatio(returns, riskFreeRate = 0.02) {
|
|
628
|
+
if (returns.length === 0) return 0;
|
|
629
|
+
const meanReturn = returns.reduce((sum2, ret) => sum2 + ret, 0) / returns.length;
|
|
630
|
+
const excessReturn = meanReturn - riskFreeRate;
|
|
631
|
+
const variance = returns.reduce((sum2, ret) => sum2 + (ret - meanReturn) ** 2, 0) / returns.length;
|
|
632
|
+
const volatility = Math.sqrt(variance);
|
|
633
|
+
return volatility > 0 ? excessReturn / volatility : 0;
|
|
634
|
+
}
|
|
635
|
+
/**
|
|
636
|
+
* Calculate Sortino Ratio
|
|
637
|
+
*/
|
|
638
|
+
static calculateSortinoRatio(returns, riskFreeRate = 0.02) {
|
|
639
|
+
if (returns.length === 0) return 0;
|
|
640
|
+
const meanReturn = returns.reduce((sum2, ret) => sum2 + ret, 0) / returns.length;
|
|
641
|
+
const excessReturn = meanReturn - riskFreeRate;
|
|
642
|
+
const negativeReturns = returns.filter((ret) => ret < meanReturn);
|
|
643
|
+
const downsideVariance = negativeReturns.reduce((sum2, ret) => sum2 + (ret - meanReturn) ** 2, 0) / returns.length;
|
|
644
|
+
const downsideDeviation = Math.sqrt(downsideVariance);
|
|
645
|
+
return downsideDeviation > 0 ? excessReturn / downsideDeviation : 0;
|
|
646
|
+
}
|
|
647
|
+
/**
|
|
648
|
+
* Calculate Calmar Ratio
|
|
649
|
+
*/
|
|
650
|
+
static calculateCalmarRatio(returns, maxDrawdown) {
|
|
651
|
+
if (maxDrawdown === 0) return 0;
|
|
652
|
+
const meanReturn = returns.reduce((sum2, ret) => sum2 + ret, 0) / returns.length;
|
|
653
|
+
return meanReturn / maxDrawdown;
|
|
654
|
+
}
|
|
655
|
+
/**
|
|
656
|
+
* Calculate Position Size
|
|
657
|
+
*/
|
|
658
|
+
static calculatePositionSize(targetEntry, stopLoss) {
|
|
659
|
+
const riskPerShare = Math.abs(targetEntry - stopLoss);
|
|
660
|
+
return riskPerShare > 0 ? 100 / riskPerShare : 1;
|
|
661
|
+
}
|
|
662
|
+
/**
|
|
663
|
+
* Calculate Confidence
|
|
664
|
+
*/
|
|
665
|
+
static calculateConfidence(signals) {
|
|
666
|
+
return Math.min(signals.length * 10, 100);
|
|
667
|
+
}
|
|
668
|
+
/**
|
|
669
|
+
* Calculate Risk Level
|
|
670
|
+
*/
|
|
671
|
+
static calculateRiskLevel(volatility) {
|
|
672
|
+
if (volatility < 20) return "LOW";
|
|
673
|
+
if (volatility < 40) return "MEDIUM";
|
|
674
|
+
return "HIGH";
|
|
675
|
+
}
|
|
676
|
+
};
|
|
677
|
+
|
|
678
|
+
// src/tools/indicators/signals.ts
|
|
679
|
+
var TradingSignalsGenerator = class _TradingSignalsGenerator {
|
|
680
|
+
/**
|
|
681
|
+
* Generate trading signals based on market analysis
|
|
682
|
+
*/
|
|
683
|
+
static generateSignals(currentPrice, trueVWAP, momentum5, momentum10, sessionReturn, currentVolume, avgVolume, pricePosition, volatility) {
|
|
684
|
+
let bullishSignals = 0;
|
|
685
|
+
let bearishSignals = 0;
|
|
686
|
+
const signals = [];
|
|
687
|
+
if (currentPrice > trueVWAP) {
|
|
688
|
+
signals.push(
|
|
689
|
+
`\u2713 BULLISH: Price above VWAP (+${((currentPrice - trueVWAP) / trueVWAP * 100).toFixed(2)}%)`
|
|
690
|
+
);
|
|
691
|
+
bullishSignals++;
|
|
692
|
+
} else {
|
|
693
|
+
signals.push(`\u2717 BEARISH: Price below VWAP (${((currentPrice - trueVWAP) / trueVWAP * 100).toFixed(2)}%)`);
|
|
694
|
+
bearishSignals++;
|
|
695
|
+
}
|
|
696
|
+
if (momentum5 > 0 && momentum10 > 0) {
|
|
697
|
+
signals.push("\u2713 BULLISH: Positive momentum on both timeframes");
|
|
698
|
+
bullishSignals++;
|
|
699
|
+
} else if (momentum5 < 0 && momentum10 < 0) {
|
|
700
|
+
signals.push("\u2717 BEARISH: Negative momentum on both timeframes");
|
|
701
|
+
bearishSignals++;
|
|
702
|
+
} else {
|
|
703
|
+
signals.push("\u25D0 MIXED: Conflicting momentum signals");
|
|
704
|
+
}
|
|
705
|
+
const volumeRatio = currentVolume / avgVolume;
|
|
706
|
+
if (volumeRatio > 1.2 && sessionReturn > 0) {
|
|
707
|
+
signals.push("\u2713 BULLISH: Above-average volume supporting upward move");
|
|
708
|
+
bullishSignals++;
|
|
709
|
+
} else if (volumeRatio > 1.2 && sessionReturn < 0) {
|
|
710
|
+
signals.push("\u2717 BEARISH: Above-average volume supporting downward move");
|
|
711
|
+
bearishSignals++;
|
|
712
|
+
} else {
|
|
713
|
+
signals.push("\u25D0 NEUTRAL: Volume not providing clear direction");
|
|
714
|
+
}
|
|
715
|
+
if (pricePosition > 65 && volatility > 30) {
|
|
716
|
+
signals.push("\u2717 BEARISH: High in range with elevated volatility - reversal risk");
|
|
717
|
+
bearishSignals++;
|
|
718
|
+
} else if (pricePosition < 35 && volatility > 30) {
|
|
719
|
+
signals.push("\u2713 BULLISH: Low in range with volatility - potential bounce");
|
|
720
|
+
bullishSignals++;
|
|
721
|
+
} else {
|
|
722
|
+
signals.push("\u25D0 NEUTRAL: Price position and volatility not extreme");
|
|
723
|
+
}
|
|
724
|
+
return { bullishSignals, bearishSignals, signals };
|
|
725
|
+
}
|
|
726
|
+
/**
|
|
727
|
+
* Calculate overall signal and confidence
|
|
728
|
+
*/
|
|
729
|
+
static calculateOverallSignal(bullishSignals, bearishSignals, signals, volatility) {
|
|
730
|
+
const totalScore = bullishSignals - bearishSignals;
|
|
731
|
+
const overallSignal = totalScore > 0 ? "BULLISH_BIAS" : totalScore < 0 ? "BEARISH_BIAS" : "NEUTRAL";
|
|
732
|
+
const confidence = _TradingSignalsGenerator.calculateConfidence(signals);
|
|
733
|
+
const riskLevel = _TradingSignalsGenerator.calculateRiskLevel(volatility);
|
|
734
|
+
return {
|
|
735
|
+
bullishSignals,
|
|
736
|
+
bearishSignals,
|
|
737
|
+
signals,
|
|
738
|
+
overallSignal,
|
|
739
|
+
signalScore: totalScore,
|
|
740
|
+
confidence,
|
|
741
|
+
riskLevel
|
|
742
|
+
};
|
|
743
|
+
}
|
|
744
|
+
/**
|
|
745
|
+
* Calculate confidence based on number of signals
|
|
746
|
+
*/
|
|
747
|
+
static calculateConfidence(signals) {
|
|
748
|
+
return Math.min(signals.length * 10, 100);
|
|
749
|
+
}
|
|
750
|
+
/**
|
|
751
|
+
* Calculate risk level based on volatility
|
|
752
|
+
*/
|
|
753
|
+
static calculateRiskLevel(volatility) {
|
|
754
|
+
if (volatility < 20) return "LOW";
|
|
755
|
+
if (volatility < 40) return "MEDIUM";
|
|
756
|
+
return "HIGH";
|
|
757
|
+
}
|
|
758
|
+
};
|
|
759
|
+
|
|
760
|
+
// src/tools/indicators/statistical.ts
|
|
761
|
+
var StatisticalModels = class {
|
|
762
|
+
/**
|
|
763
|
+
* Calculate Z-Score
|
|
764
|
+
*/
|
|
765
|
+
static calculateZScore(currentPrice, startPrice) {
|
|
766
|
+
return (currentPrice - startPrice) / (startPrice * 0.1);
|
|
767
|
+
}
|
|
768
|
+
/**
|
|
769
|
+
* Calculate Ornstein-Uhlenbeck
|
|
770
|
+
*/
|
|
771
|
+
static calculateOrnsteinUhlenbeck(currentPrice, startPrice, avgVolume, priceChanges) {
|
|
772
|
+
const mean = startPrice;
|
|
773
|
+
let speed = 0.1;
|
|
774
|
+
if (priceChanges.length > 1) {
|
|
775
|
+
const variance = priceChanges.reduce((sum2, change) => sum2 + change * change, 0) / priceChanges.length;
|
|
776
|
+
speed = Math.max(0.01, Math.min(1, variance * 10));
|
|
777
|
+
}
|
|
778
|
+
const volatility = avgVolume * 0.01;
|
|
779
|
+
return {
|
|
780
|
+
mean,
|
|
781
|
+
speed,
|
|
782
|
+
volatility,
|
|
783
|
+
currentValue: currentPrice
|
|
784
|
+
};
|
|
785
|
+
}
|
|
786
|
+
/**
|
|
787
|
+
* Calculate Kalman Filter
|
|
788
|
+
*/
|
|
789
|
+
static calculateKalmanFilter(currentPrice, startPrice, avgVolume, priceChanges) {
|
|
790
|
+
const measurementNoise = avgVolume * 1e-3;
|
|
791
|
+
const processNoise = avgVolume * 1e-4;
|
|
792
|
+
let state = startPrice;
|
|
793
|
+
let covariance = measurementNoise;
|
|
794
|
+
if (priceChanges.length > 0) {
|
|
795
|
+
const predictedState = state;
|
|
796
|
+
const predictedCovariance = covariance + processNoise;
|
|
797
|
+
const kalmanGain = predictedCovariance / (predictedCovariance + measurementNoise);
|
|
798
|
+
state = predictedState + kalmanGain * (currentPrice - predictedState);
|
|
799
|
+
covariance = (1 - kalmanGain) * predictedCovariance;
|
|
800
|
+
return {
|
|
801
|
+
state,
|
|
802
|
+
covariance,
|
|
803
|
+
gain: kalmanGain
|
|
804
|
+
};
|
|
805
|
+
}
|
|
806
|
+
return {
|
|
807
|
+
state: currentPrice,
|
|
808
|
+
covariance,
|
|
809
|
+
gain: 0.5
|
|
810
|
+
};
|
|
811
|
+
}
|
|
812
|
+
/**
|
|
813
|
+
* Calculate ARIMA
|
|
814
|
+
*/
|
|
815
|
+
static calculateARIMA(currentPrice, priceChanges) {
|
|
816
|
+
if (priceChanges.length < 3) {
|
|
817
|
+
return {
|
|
818
|
+
forecast: [currentPrice * 1.01, currentPrice * 1.02],
|
|
819
|
+
residuals: [0, 0],
|
|
820
|
+
aic: 100
|
|
821
|
+
};
|
|
822
|
+
}
|
|
823
|
+
const n = priceChanges.length;
|
|
824
|
+
let sumY = 0;
|
|
825
|
+
let sumY1 = 0;
|
|
826
|
+
let sumYY1 = 0;
|
|
827
|
+
let sumY1Sq = 0;
|
|
828
|
+
for (let i = 1; i < n; i++) {
|
|
829
|
+
const y = priceChanges[i];
|
|
830
|
+
const y1 = priceChanges[i - 1];
|
|
831
|
+
sumY += y;
|
|
832
|
+
sumY1 += y1;
|
|
833
|
+
sumYY1 += y * y1;
|
|
834
|
+
sumY1Sq += y1 * y1;
|
|
835
|
+
}
|
|
836
|
+
const phi = (n * sumYY1 - sumY * sumY1) / (n * sumY1Sq - sumY1 * sumY1);
|
|
837
|
+
const c = (sumY - phi * sumY1) / n;
|
|
838
|
+
const residuals = [];
|
|
839
|
+
for (let i = 1; i < n; i++) {
|
|
840
|
+
const predicted = c + phi * priceChanges[i - 1];
|
|
841
|
+
residuals.push(priceChanges[i] - predicted);
|
|
842
|
+
}
|
|
843
|
+
const rss = residuals.reduce((sum2, r) => sum2 + r * r, 0);
|
|
844
|
+
const aic = n * Math.log(rss / n) + 2 * 2;
|
|
845
|
+
const lastChange = priceChanges[priceChanges.length - 1];
|
|
846
|
+
const forecast1 = currentPrice + (c + phi * lastChange);
|
|
847
|
+
const forecast2 = forecast1 + (c + phi * (c + phi * lastChange));
|
|
848
|
+
return {
|
|
849
|
+
forecast: [forecast1, forecast2],
|
|
850
|
+
residuals,
|
|
851
|
+
aic
|
|
852
|
+
};
|
|
853
|
+
}
|
|
854
|
+
/**
|
|
855
|
+
* Calculate GARCH
|
|
856
|
+
*/
|
|
857
|
+
static calculateGARCH(avgVolume, priceChanges) {
|
|
858
|
+
if (priceChanges.length < 5) {
|
|
859
|
+
return {
|
|
860
|
+
volatility: avgVolume * 0.01,
|
|
861
|
+
persistence: 0.9,
|
|
862
|
+
meanReversion: 0.1
|
|
863
|
+
};
|
|
864
|
+
}
|
|
865
|
+
const squaredReturns = priceChanges.map((change) => change * change);
|
|
866
|
+
const meanSquaredReturn = squaredReturns.reduce((sum2, sq) => sum2 + sq, 0) / squaredReturns.length;
|
|
867
|
+
let persistence = 0.9;
|
|
868
|
+
if (squaredReturns.length > 1) {
|
|
869
|
+
const variance = squaredReturns.reduce((sum2, sq) => sum2 + sq, 0) / squaredReturns.length;
|
|
870
|
+
persistence = Math.min(0.99, Math.max(0.5, variance / meanSquaredReturn));
|
|
871
|
+
}
|
|
872
|
+
const meanReversion = meanSquaredReturn * (1 - persistence);
|
|
873
|
+
const volatility = Math.sqrt(meanSquaredReturn);
|
|
874
|
+
return {
|
|
875
|
+
volatility,
|
|
876
|
+
persistence,
|
|
877
|
+
meanReversion
|
|
878
|
+
};
|
|
879
|
+
}
|
|
880
|
+
/**
|
|
881
|
+
* Calculate Hilbert Transform
|
|
882
|
+
*/
|
|
883
|
+
static calculateHilbertTransform(currentPrice, priceChanges) {
|
|
884
|
+
if (priceChanges.length < 3) {
|
|
885
|
+
return {
|
|
886
|
+
analytic: [currentPrice],
|
|
887
|
+
phase: [0],
|
|
888
|
+
amplitude: [currentPrice]
|
|
889
|
+
};
|
|
890
|
+
}
|
|
891
|
+
const n = priceChanges.length;
|
|
892
|
+
const analytic = [];
|
|
893
|
+
const phase = [];
|
|
894
|
+
const amplitude = [];
|
|
895
|
+
for (let i = 0; i < n; i++) {
|
|
896
|
+
let hilbertValue = 0;
|
|
897
|
+
for (let j = 0; j < n; j++) {
|
|
898
|
+
if (i !== j) {
|
|
899
|
+
hilbertValue += priceChanges[j] / (Math.PI * (i - j));
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
const realPart = priceChanges[i];
|
|
903
|
+
const imagPart = hilbertValue;
|
|
904
|
+
const analyticValue = Math.sqrt(realPart * realPart + imagPart * imagPart);
|
|
905
|
+
analytic.push(analyticValue);
|
|
906
|
+
const phaseValue = Math.atan2(imagPart, realPart);
|
|
907
|
+
phase.push(phaseValue);
|
|
908
|
+
amplitude.push(analyticValue);
|
|
909
|
+
}
|
|
910
|
+
return {
|
|
911
|
+
analytic,
|
|
912
|
+
phase,
|
|
913
|
+
amplitude
|
|
914
|
+
};
|
|
915
|
+
}
|
|
916
|
+
/**
|
|
917
|
+
* Calculate Wavelet Transform
|
|
918
|
+
*/
|
|
919
|
+
static calculateWaveletTransform(currentPrice, priceChanges) {
|
|
920
|
+
if (priceChanges.length < 4) {
|
|
921
|
+
return {
|
|
922
|
+
coefficients: [currentPrice],
|
|
923
|
+
scales: [1]
|
|
924
|
+
};
|
|
925
|
+
}
|
|
926
|
+
const coefficients = [];
|
|
927
|
+
const scales = [];
|
|
928
|
+
const n = priceChanges.length;
|
|
929
|
+
const maxLevel = Math.floor(Math.log2(n));
|
|
930
|
+
for (let level = 1; level <= maxLevel; level++) {
|
|
931
|
+
const step = 2 ** (level - 1);
|
|
932
|
+
const scale = step;
|
|
933
|
+
for (let i = 0; i < n - step; i += step * 2) {
|
|
934
|
+
if (i + step < n) {
|
|
935
|
+
const coefficient = (priceChanges[i] - priceChanges[i + step]) / Math.sqrt(2);
|
|
936
|
+
coefficients.push(coefficient);
|
|
937
|
+
scales.push(scale);
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
if (coefficients.length === 0) {
|
|
942
|
+
coefficients.push(currentPrice);
|
|
943
|
+
scales.push(1);
|
|
944
|
+
}
|
|
945
|
+
return {
|
|
946
|
+
coefficients,
|
|
947
|
+
scales
|
|
948
|
+
};
|
|
949
|
+
}
|
|
950
|
+
};
|
|
951
|
+
|
|
952
|
+
// src/tools/indicators/supportResistance.ts
|
|
953
|
+
var SupportResistanceIndicators = class _SupportResistanceIndicators {
|
|
954
|
+
/**
|
|
955
|
+
* Calculate Pivot Points
|
|
956
|
+
*/
|
|
957
|
+
static calculatePivotPoints(prices, highs, lows) {
|
|
958
|
+
const pivotPoints = [];
|
|
959
|
+
for (let i = 0; i < prices.length; i++) {
|
|
960
|
+
const high = highs[i] || prices[i];
|
|
961
|
+
const low = lows[i] || prices[i];
|
|
962
|
+
const close = prices[i];
|
|
963
|
+
const pp = (high + low + close) / 3;
|
|
964
|
+
const r1 = 2 * pp - low;
|
|
965
|
+
const s1 = 2 * pp - high;
|
|
966
|
+
const r2 = pp + (high - low);
|
|
967
|
+
const s2 = pp - (high - low);
|
|
968
|
+
const r3 = high + 2 * (pp - low);
|
|
969
|
+
const s3 = low - 2 * (high - pp);
|
|
970
|
+
pivotPoints.push({
|
|
971
|
+
pp,
|
|
972
|
+
r1,
|
|
973
|
+
r2,
|
|
974
|
+
r3,
|
|
975
|
+
s1,
|
|
976
|
+
s2,
|
|
977
|
+
s3
|
|
978
|
+
});
|
|
979
|
+
}
|
|
980
|
+
return pivotPoints;
|
|
981
|
+
}
|
|
982
|
+
/**
|
|
983
|
+
* Calculate Fibonacci Levels
|
|
984
|
+
*/
|
|
985
|
+
static calculateFibonacciLevels(prices) {
|
|
986
|
+
const fibonacci = [];
|
|
987
|
+
for (let i = 0; i < prices.length; i++) {
|
|
988
|
+
const price = prices[i];
|
|
989
|
+
fibonacci.push({
|
|
990
|
+
retracement: {
|
|
991
|
+
level0: price,
|
|
992
|
+
level236: price * 0.764,
|
|
993
|
+
level382: price * 0.618,
|
|
994
|
+
level500: price * 0.5,
|
|
995
|
+
level618: price * 0.382,
|
|
996
|
+
level786: price * 0.214,
|
|
997
|
+
level100: price * 0
|
|
998
|
+
},
|
|
999
|
+
extension: {
|
|
1000
|
+
level1272: price * 1.272,
|
|
1001
|
+
level1618: price * 1.618,
|
|
1002
|
+
level2618: price * 2.618,
|
|
1003
|
+
level4236: price * 4.236
|
|
1004
|
+
}
|
|
1005
|
+
});
|
|
1006
|
+
}
|
|
1007
|
+
return fibonacci;
|
|
1008
|
+
}
|
|
1009
|
+
/**
|
|
1010
|
+
* Calculate Gann Levels
|
|
1011
|
+
*/
|
|
1012
|
+
static calculateGannLevels(prices) {
|
|
1013
|
+
const gannLevels = [];
|
|
1014
|
+
for (let i = 0; i < prices.length; i++) {
|
|
1015
|
+
gannLevels.push(prices[i] * (1 + i * 0.01));
|
|
1016
|
+
}
|
|
1017
|
+
return gannLevels;
|
|
1018
|
+
}
|
|
1019
|
+
/**
|
|
1020
|
+
* Calculate Elliott Wave
|
|
1021
|
+
*/
|
|
1022
|
+
static calculateElliottWave(prices) {
|
|
1023
|
+
const elliottWave = [];
|
|
1024
|
+
if (prices.length < 10) return [];
|
|
1025
|
+
for (let i = 0; i < prices.length; i++) {
|
|
1026
|
+
const waves = [];
|
|
1027
|
+
let currentWave = 1;
|
|
1028
|
+
let wavePosition = 0.5;
|
|
1029
|
+
if (i >= 4) {
|
|
1030
|
+
const recentPrices = prices.slice(i - 4, i + 1);
|
|
1031
|
+
const swings = _SupportResistanceIndicators.detectPriceSwings(recentPrices);
|
|
1032
|
+
if (swings.length >= 3) {
|
|
1033
|
+
waves.push(...swings.slice(0, 3));
|
|
1034
|
+
currentWave = Math.min(swings.length, 5);
|
|
1035
|
+
wavePosition = _SupportResistanceIndicators.calculateWavePosition(recentPrices);
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
elliottWave.push({
|
|
1039
|
+
waves: waves.length > 0 ? waves : [prices[i]],
|
|
1040
|
+
currentWave,
|
|
1041
|
+
wavePosition
|
|
1042
|
+
});
|
|
1043
|
+
}
|
|
1044
|
+
return elliottWave;
|
|
1045
|
+
}
|
|
1046
|
+
/**
|
|
1047
|
+
* Helper method to detect price swings
|
|
1048
|
+
*/
|
|
1049
|
+
static detectPriceSwings(prices) {
|
|
1050
|
+
const swings = [];
|
|
1051
|
+
for (let i = 1; i < prices.length - 1; i++) {
|
|
1052
|
+
const prev = prices[i - 1];
|
|
1053
|
+
const curr = prices[i];
|
|
1054
|
+
const next = prices[i + 1];
|
|
1055
|
+
if (curr > prev && curr > next) {
|
|
1056
|
+
swings.push(curr);
|
|
1057
|
+
} else if (curr < prev && curr < next) {
|
|
1058
|
+
swings.push(curr);
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
return swings;
|
|
1062
|
+
}
|
|
1063
|
+
/**
|
|
1064
|
+
* Helper method to calculate wave position
|
|
1065
|
+
*/
|
|
1066
|
+
static calculateWavePosition(prices) {
|
|
1067
|
+
if (prices.length < 2) return 0.5;
|
|
1068
|
+
const current = prices[prices.length - 1];
|
|
1069
|
+
const min = Math.min(...prices);
|
|
1070
|
+
const max = Math.max(...prices);
|
|
1071
|
+
return max !== min ? (current - min) / (max - min) : 0.5;
|
|
1072
|
+
}
|
|
1073
|
+
/**
|
|
1074
|
+
* Calculate Harmonic Patterns
|
|
1075
|
+
*/
|
|
1076
|
+
static calculateHarmonicPatterns(prices) {
|
|
1077
|
+
const harmonicPatterns = [];
|
|
1078
|
+
if (prices.length < 5) return [];
|
|
1079
|
+
for (let i = 4; i < prices.length; i++) {
|
|
1080
|
+
const recentPrices = prices.slice(i - 4, i + 1);
|
|
1081
|
+
const pattern = _SupportResistanceIndicators.detectHarmonicPattern(recentPrices);
|
|
1082
|
+
harmonicPatterns.push(pattern);
|
|
1083
|
+
}
|
|
1084
|
+
return harmonicPatterns;
|
|
1085
|
+
}
|
|
1086
|
+
/**
|
|
1087
|
+
* Helper method to detect harmonic patterns
|
|
1088
|
+
*/
|
|
1089
|
+
static detectHarmonicPattern(prices) {
|
|
1090
|
+
if (prices.length < 5) {
|
|
1091
|
+
return {
|
|
1092
|
+
type: "Unknown",
|
|
1093
|
+
completion: 0,
|
|
1094
|
+
target: prices[prices.length - 1] * 1.1,
|
|
1095
|
+
stopLoss: prices[prices.length - 1] * 0.9
|
|
1096
|
+
};
|
|
1097
|
+
}
|
|
1098
|
+
const swings = _SupportResistanceIndicators.detectPriceSwings(prices);
|
|
1099
|
+
if (swings.length < 4) {
|
|
1100
|
+
return {
|
|
1101
|
+
type: "Unknown",
|
|
1102
|
+
completion: 0,
|
|
1103
|
+
target: prices[prices.length - 1] * 1.1,
|
|
1104
|
+
stopLoss: prices[prices.length - 1] * 0.9
|
|
1105
|
+
};
|
|
1106
|
+
}
|
|
1107
|
+
const [A, B, C, D] = swings.slice(-4);
|
|
1108
|
+
const X = prices[0];
|
|
1109
|
+
const abRatio = Math.abs((B - A) / (X - A));
|
|
1110
|
+
const bcRatio = Math.abs((C - B) / (A - B));
|
|
1111
|
+
const cdRatio = Math.abs((D - C) / (B - C));
|
|
1112
|
+
const adRatio = Math.abs((D - A) / (X - A));
|
|
1113
|
+
const isGartley = Math.abs(abRatio - 0.618) < 0.1 && bcRatio >= 0.382 && bcRatio <= 0.886 && cdRatio >= 1.13 && cdRatio <= 1.618 && Math.abs(adRatio - 0.786) < 0.1;
|
|
1114
|
+
if (isGartley) {
|
|
1115
|
+
const completion = _SupportResistanceIndicators.calculatePatternCompletion(prices);
|
|
1116
|
+
const target = D + (D - C) * 0.618;
|
|
1117
|
+
const stopLoss = D - (D - C) * 0.382;
|
|
1118
|
+
return {
|
|
1119
|
+
type: "Gartley",
|
|
1120
|
+
completion,
|
|
1121
|
+
target,
|
|
1122
|
+
stopLoss
|
|
1123
|
+
};
|
|
1124
|
+
}
|
|
1125
|
+
const isButterfly = Math.abs(abRatio - 0.786) < 0.1 && bcRatio >= 0.382 && bcRatio <= 0.886 && cdRatio >= 1.618 && cdRatio <= 2.618 && Math.abs(adRatio - 1.27) < 0.1;
|
|
1126
|
+
if (isButterfly) {
|
|
1127
|
+
const completion = _SupportResistanceIndicators.calculatePatternCompletion(prices);
|
|
1128
|
+
const target = D + (D - C) * 1.27;
|
|
1129
|
+
const stopLoss = D - (D - C) * 0.5;
|
|
1130
|
+
return {
|
|
1131
|
+
type: "Butterfly",
|
|
1132
|
+
completion,
|
|
1133
|
+
target,
|
|
1134
|
+
stopLoss
|
|
1135
|
+
};
|
|
1136
|
+
}
|
|
1137
|
+
return {
|
|
1138
|
+
type: "Unknown",
|
|
1139
|
+
completion: 0,
|
|
1140
|
+
target: prices[prices.length - 1] * 1.1,
|
|
1141
|
+
stopLoss: prices[prices.length - 1] * 0.9
|
|
1142
|
+
};
|
|
1143
|
+
}
|
|
1144
|
+
/**
|
|
1145
|
+
* Helper method to calculate pattern completion
|
|
1146
|
+
*/
|
|
1147
|
+
static calculatePatternCompletion(prices) {
|
|
1148
|
+
if (prices.length < 2) return 0;
|
|
1149
|
+
const current = prices[prices.length - 1];
|
|
1150
|
+
const min = Math.min(...prices);
|
|
1151
|
+
const max = Math.max(...prices);
|
|
1152
|
+
return max !== min ? (current - min) / (max - min) : 0;
|
|
1153
|
+
}
|
|
1154
|
+
};
|
|
1155
|
+
|
|
1156
|
+
// src/tools/indicators/trend.ts
|
|
1157
|
+
var TrendIndicators = class {
|
|
1158
|
+
/**
|
|
1159
|
+
* Calculate MACD (Moving Average Convergence Divergence)
|
|
1160
|
+
*/
|
|
1161
|
+
static calculateMACD(prices) {
|
|
1162
|
+
const ema12 = MovingAverages.calculateEMA(prices, 12);
|
|
1163
|
+
const ema26 = MovingAverages.calculateEMA(prices, 26);
|
|
1164
|
+
const macd = [];
|
|
1165
|
+
const macdLine = [];
|
|
1166
|
+
for (let i = 0; i < Math.min(ema12.length, ema26.length); i++) {
|
|
1167
|
+
macdLine.push(ema12[i] - ema26[i]);
|
|
1168
|
+
}
|
|
1169
|
+
const signalLine = MovingAverages.calculateEMA(macdLine, 9);
|
|
1170
|
+
for (let i = 0; i < Math.min(macdLine.length, signalLine.length); i++) {
|
|
1171
|
+
macd.push({
|
|
1172
|
+
macd: macdLine[i],
|
|
1173
|
+
signal: signalLine[i],
|
|
1174
|
+
histogram: macdLine[i] - signalLine[i]
|
|
1175
|
+
});
|
|
1176
|
+
}
|
|
1177
|
+
return macd;
|
|
1178
|
+
}
|
|
1179
|
+
/**
|
|
1180
|
+
* Calculate ADX (Average Directional Index)
|
|
1181
|
+
*/
|
|
1182
|
+
static calculateADX(prices, highs, lows) {
|
|
1183
|
+
if (prices.length < 14) return [];
|
|
1184
|
+
const period = 14;
|
|
1185
|
+
const adx = [];
|
|
1186
|
+
const trueRanges = [];
|
|
1187
|
+
const plusDM = [];
|
|
1188
|
+
const minusDM = [];
|
|
1189
|
+
trueRanges.push(highs[0] - lows[0]);
|
|
1190
|
+
plusDM.push(0);
|
|
1191
|
+
minusDM.push(0);
|
|
1192
|
+
for (let i = 1; i < prices.length; i++) {
|
|
1193
|
+
const high = highs[i] || prices[i];
|
|
1194
|
+
const low = lows[i] || prices[i];
|
|
1195
|
+
const prevHigh = highs[i - 1] || prices[i - 1];
|
|
1196
|
+
const prevLow = lows[i - 1] || prices[i - 1];
|
|
1197
|
+
const prevClose = prices[i - 1];
|
|
1198
|
+
const tr1 = high - low;
|
|
1199
|
+
const tr2 = Math.abs(high - prevClose);
|
|
1200
|
+
const tr3 = Math.abs(low - prevClose);
|
|
1201
|
+
trueRanges.push(Math.max(tr1, tr2, tr3));
|
|
1202
|
+
const upMove = high - prevHigh;
|
|
1203
|
+
const downMove = prevLow - low;
|
|
1204
|
+
if (upMove > downMove && upMove > 0) {
|
|
1205
|
+
plusDM.push(upMove);
|
|
1206
|
+
minusDM.push(0);
|
|
1207
|
+
} else if (downMove > upMove && downMove > 0) {
|
|
1208
|
+
plusDM.push(0);
|
|
1209
|
+
minusDM.push(downMove);
|
|
1210
|
+
} else {
|
|
1211
|
+
plusDM.push(0);
|
|
1212
|
+
minusDM.push(0);
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
const smoothedTR = [];
|
|
1216
|
+
const smoothedPlusDM = [];
|
|
1217
|
+
const smoothedMinusDM = [];
|
|
1218
|
+
let sumTR = 0;
|
|
1219
|
+
let sumPlusDM = 0;
|
|
1220
|
+
let sumMinusDM = 0;
|
|
1221
|
+
for (let i = 0; i < period; i++) {
|
|
1222
|
+
sumTR += trueRanges[i];
|
|
1223
|
+
sumPlusDM += plusDM[i];
|
|
1224
|
+
sumMinusDM += minusDM[i];
|
|
1225
|
+
}
|
|
1226
|
+
smoothedTR.push(sumTR);
|
|
1227
|
+
smoothedPlusDM.push(sumPlusDM);
|
|
1228
|
+
smoothedMinusDM.push(sumMinusDM);
|
|
1229
|
+
for (let i = period; i < trueRanges.length; i++) {
|
|
1230
|
+
const newTR = smoothedTR[smoothedTR.length - 1] - smoothedTR[smoothedTR.length - 1] / period + trueRanges[i];
|
|
1231
|
+
const newPlusDM = smoothedPlusDM[smoothedPlusDM.length - 1] - smoothedPlusDM[smoothedPlusDM.length - 1] / period + plusDM[i];
|
|
1232
|
+
const newMinusDM = smoothedMinusDM[smoothedMinusDM.length - 1] - smoothedMinusDM[smoothedMinusDM.length - 1] / period + minusDM[i];
|
|
1233
|
+
smoothedTR.push(newTR);
|
|
1234
|
+
smoothedPlusDM.push(newPlusDM);
|
|
1235
|
+
smoothedMinusDM.push(newMinusDM);
|
|
1236
|
+
}
|
|
1237
|
+
const plusDI = [];
|
|
1238
|
+
const minusDI = [];
|
|
1239
|
+
for (let i = 0; i < smoothedTR.length; i++) {
|
|
1240
|
+
plusDI.push(smoothedPlusDM[i] / smoothedTR[i] * 100);
|
|
1241
|
+
minusDI.push(smoothedMinusDM[i] / smoothedTR[i] * 100);
|
|
1242
|
+
}
|
|
1243
|
+
const dx = [];
|
|
1244
|
+
for (let i = 0; i < plusDI.length; i++) {
|
|
1245
|
+
const diSum = plusDI[i] + minusDI[i];
|
|
1246
|
+
const diDiff = Math.abs(plusDI[i] - minusDI[i]);
|
|
1247
|
+
dx.push(diSum > 0 ? diDiff / diSum * 100 : 0);
|
|
1248
|
+
}
|
|
1249
|
+
if (dx.length < period) return [];
|
|
1250
|
+
let sumDX = 0;
|
|
1251
|
+
for (let i = 0; i < period; i++) {
|
|
1252
|
+
sumDX += dx[i];
|
|
1253
|
+
}
|
|
1254
|
+
adx.push(sumDX / period);
|
|
1255
|
+
for (let i = period; i < dx.length; i++) {
|
|
1256
|
+
const newADX = adx[adx.length - 1] - adx[adx.length - 1] / period + dx[i];
|
|
1257
|
+
adx.push(newADX);
|
|
1258
|
+
}
|
|
1259
|
+
return adx;
|
|
1260
|
+
}
|
|
1261
|
+
/**
|
|
1262
|
+
* Calculate DMI (Directional Movement Index)
|
|
1263
|
+
*/
|
|
1264
|
+
static calculateDMI(prices, highs, lows) {
|
|
1265
|
+
if (prices.length < 14) return [];
|
|
1266
|
+
const period = 14;
|
|
1267
|
+
const dmi = [];
|
|
1268
|
+
const trueRanges = [];
|
|
1269
|
+
const plusDM = [];
|
|
1270
|
+
const minusDM = [];
|
|
1271
|
+
trueRanges.push(highs[0] - lows[0]);
|
|
1272
|
+
plusDM.push(0);
|
|
1273
|
+
minusDM.push(0);
|
|
1274
|
+
for (let i = 1; i < prices.length; i++) {
|
|
1275
|
+
const high = highs[i] || prices[i];
|
|
1276
|
+
const low = lows[i] || prices[i];
|
|
1277
|
+
const prevHigh = highs[i - 1] || prices[i - 1];
|
|
1278
|
+
const prevLow = lows[i - 1] || prices[i - 1];
|
|
1279
|
+
const prevClose = prices[i - 1];
|
|
1280
|
+
const tr1 = high - low;
|
|
1281
|
+
const tr2 = Math.abs(high - prevClose);
|
|
1282
|
+
const tr3 = Math.abs(low - prevClose);
|
|
1283
|
+
trueRanges.push(Math.max(tr1, tr2, tr3));
|
|
1284
|
+
const upMove = high - prevHigh;
|
|
1285
|
+
const downMove = prevLow - low;
|
|
1286
|
+
if (upMove > downMove && upMove > 0) {
|
|
1287
|
+
plusDM.push(upMove);
|
|
1288
|
+
minusDM.push(0);
|
|
1289
|
+
} else if (downMove > upMove && downMove > 0) {
|
|
1290
|
+
plusDM.push(0);
|
|
1291
|
+
minusDM.push(downMove);
|
|
1292
|
+
} else {
|
|
1293
|
+
plusDM.push(0);
|
|
1294
|
+
minusDM.push(0);
|
|
1295
|
+
}
|
|
1296
|
+
}
|
|
1297
|
+
const smoothedTR = [];
|
|
1298
|
+
const smoothedPlusDM = [];
|
|
1299
|
+
const smoothedMinusDM = [];
|
|
1300
|
+
let sumTR = 0;
|
|
1301
|
+
let sumPlusDM = 0;
|
|
1302
|
+
let sumMinusDM = 0;
|
|
1303
|
+
for (let i = 0; i < period; i++) {
|
|
1304
|
+
sumTR += trueRanges[i];
|
|
1305
|
+
sumPlusDM += plusDM[i];
|
|
1306
|
+
sumMinusDM += minusDM[i];
|
|
1307
|
+
}
|
|
1308
|
+
smoothedTR.push(sumTR);
|
|
1309
|
+
smoothedPlusDM.push(sumPlusDM);
|
|
1310
|
+
smoothedMinusDM.push(sumMinusDM);
|
|
1311
|
+
for (let i = period; i < trueRanges.length; i++) {
|
|
1312
|
+
const newTR = smoothedTR[smoothedTR.length - 1] - smoothedTR[smoothedTR.length - 1] / period + trueRanges[i];
|
|
1313
|
+
const newPlusDM = smoothedPlusDM[smoothedPlusDM.length - 1] - smoothedPlusDM[smoothedPlusDM.length - 1] / period + plusDM[i];
|
|
1314
|
+
const newMinusDM = smoothedMinusDM[smoothedMinusDM.length - 1] - smoothedMinusDM[smoothedMinusDM.length - 1] / period + minusDM[i];
|
|
1315
|
+
smoothedTR.push(newTR);
|
|
1316
|
+
smoothedPlusDM.push(newPlusDM);
|
|
1317
|
+
smoothedMinusDM.push(newMinusDM);
|
|
1318
|
+
}
|
|
1319
|
+
const plusDI = [];
|
|
1320
|
+
const minusDI = [];
|
|
1321
|
+
for (let i = 0; i < smoothedTR.length; i++) {
|
|
1322
|
+
plusDI.push(smoothedPlusDM[i] / smoothedTR[i] * 100);
|
|
1323
|
+
minusDI.push(smoothedMinusDM[i] / smoothedTR[i] * 100);
|
|
1324
|
+
}
|
|
1325
|
+
const dx = [];
|
|
1326
|
+
for (let i = 0; i < plusDI.length; i++) {
|
|
1327
|
+
const diSum = plusDI[i] + minusDI[i];
|
|
1328
|
+
const diDiff = Math.abs(plusDI[i] - minusDI[i]);
|
|
1329
|
+
dx.push(diSum > 0 ? diDiff / diSum * 100 : 0);
|
|
1330
|
+
}
|
|
1331
|
+
if (dx.length < period) return [];
|
|
1332
|
+
const adx = [];
|
|
1333
|
+
let sumDX = 0;
|
|
1334
|
+
for (let i = 0; i < period; i++) {
|
|
1335
|
+
sumDX += dx[i];
|
|
1336
|
+
}
|
|
1337
|
+
adx.push(sumDX / period);
|
|
1338
|
+
for (let i = period; i < dx.length; i++) {
|
|
1339
|
+
const newADX = adx[adx.length - 1] - adx[adx.length - 1] / period + dx[i];
|
|
1340
|
+
adx.push(newADX);
|
|
1341
|
+
}
|
|
1342
|
+
for (let i = 0; i < adx.length; i++) {
|
|
1343
|
+
dmi.push({
|
|
1344
|
+
plusDI: plusDI[i + period - 1] || 0,
|
|
1345
|
+
minusDI: minusDI[i + period - 1] || 0,
|
|
1346
|
+
adx: adx[i]
|
|
1347
|
+
});
|
|
1348
|
+
}
|
|
1349
|
+
return dmi;
|
|
1350
|
+
}
|
|
1351
|
+
/**
|
|
1352
|
+
* Calculate Ichimoku Cloud
|
|
1353
|
+
*/
|
|
1354
|
+
static calculateIchimoku(prices, highs, lows) {
|
|
1355
|
+
if (prices.length < 52) return [];
|
|
1356
|
+
const ichimoku = [];
|
|
1357
|
+
const tenkanSen = [];
|
|
1358
|
+
for (let i = 8; i < prices.length; i++) {
|
|
1359
|
+
const periodHigh = Math.max(...highs.slice(i - 8, i + 1));
|
|
1360
|
+
const periodLow = Math.min(...lows.slice(i - 8, i + 1));
|
|
1361
|
+
tenkanSen.push((periodHigh + periodLow) / 2);
|
|
1362
|
+
}
|
|
1363
|
+
const kijunSen = [];
|
|
1364
|
+
for (let i = 25; i < prices.length; i++) {
|
|
1365
|
+
const periodHigh = Math.max(...highs.slice(i - 25, i + 1));
|
|
1366
|
+
const periodLow = Math.min(...lows.slice(i - 25, i + 1));
|
|
1367
|
+
kijunSen.push((periodHigh + periodLow) / 2);
|
|
1368
|
+
}
|
|
1369
|
+
const senkouSpanA = [];
|
|
1370
|
+
for (let i = 0; i < Math.min(tenkanSen.length, kijunSen.length); i++) {
|
|
1371
|
+
senkouSpanA.push((tenkanSen[i] + kijunSen[i]) / 2);
|
|
1372
|
+
}
|
|
1373
|
+
const senkouSpanB = [];
|
|
1374
|
+
for (let i = 51; i < prices.length; i++) {
|
|
1375
|
+
const periodHigh = Math.max(...highs.slice(i - 51, i + 1));
|
|
1376
|
+
const periodLow = Math.min(...lows.slice(i - 51, i + 1));
|
|
1377
|
+
senkouSpanB.push((periodHigh + periodLow) / 2);
|
|
1378
|
+
}
|
|
1379
|
+
const chikouSpan = [];
|
|
1380
|
+
for (let i = 26; i < prices.length; i++) {
|
|
1381
|
+
chikouSpan.push(prices[i - 26]);
|
|
1382
|
+
}
|
|
1383
|
+
const minLength = Math.min(
|
|
1384
|
+
tenkanSen.length,
|
|
1385
|
+
kijunSen.length,
|
|
1386
|
+
senkouSpanA.length,
|
|
1387
|
+
senkouSpanB.length,
|
|
1388
|
+
chikouSpan.length
|
|
1389
|
+
);
|
|
1390
|
+
for (let i = 0; i < minLength; i++) {
|
|
1391
|
+
ichimoku.push({
|
|
1392
|
+
tenkan: tenkanSen[i],
|
|
1393
|
+
kijun: kijunSen[i],
|
|
1394
|
+
senkouA: senkouSpanA[i],
|
|
1395
|
+
senkouB: senkouSpanB[i],
|
|
1396
|
+
chikou: chikouSpan[i]
|
|
1397
|
+
});
|
|
1398
|
+
}
|
|
1399
|
+
return ichimoku;
|
|
1400
|
+
}
|
|
1401
|
+
/**
|
|
1402
|
+
* Calculate Parabolic SAR
|
|
1403
|
+
*/
|
|
1404
|
+
static calculateParabolicSAR(prices, highs, lows) {
|
|
1405
|
+
if (prices.length < 2) return [];
|
|
1406
|
+
const sar = [];
|
|
1407
|
+
const accelerationFactor = 0.02;
|
|
1408
|
+
const maximumAcceleration = 0.2;
|
|
1409
|
+
let currentSAR = lows[0];
|
|
1410
|
+
let isLong = true;
|
|
1411
|
+
let af = accelerationFactor;
|
|
1412
|
+
let ep = highs[0];
|
|
1413
|
+
sar.push(currentSAR);
|
|
1414
|
+
for (let i = 1; i < prices.length; i++) {
|
|
1415
|
+
const high = highs[i] || prices[i];
|
|
1416
|
+
const low = lows[i] || prices[i];
|
|
1417
|
+
if (isLong) {
|
|
1418
|
+
if (low < currentSAR) {
|
|
1419
|
+
isLong = false;
|
|
1420
|
+
currentSAR = ep;
|
|
1421
|
+
ep = low;
|
|
1422
|
+
af = accelerationFactor;
|
|
1423
|
+
} else {
|
|
1424
|
+
if (high > ep) {
|
|
1425
|
+
ep = high;
|
|
1426
|
+
af = Math.min(af + accelerationFactor, maximumAcceleration);
|
|
1427
|
+
}
|
|
1428
|
+
currentSAR = currentSAR + af * (ep - currentSAR);
|
|
1429
|
+
if (i > 0) {
|
|
1430
|
+
const prevLow = lows[i - 1] || prices[i - 1];
|
|
1431
|
+
currentSAR = Math.min(currentSAR, prevLow);
|
|
1432
|
+
}
|
|
1433
|
+
}
|
|
1434
|
+
} else {
|
|
1435
|
+
if (high > currentSAR) {
|
|
1436
|
+
isLong = true;
|
|
1437
|
+
currentSAR = ep;
|
|
1438
|
+
ep = high;
|
|
1439
|
+
af = accelerationFactor;
|
|
1440
|
+
} else {
|
|
1441
|
+
if (low < ep) {
|
|
1442
|
+
ep = low;
|
|
1443
|
+
af = Math.min(af + accelerationFactor, maximumAcceleration);
|
|
1444
|
+
}
|
|
1445
|
+
currentSAR = currentSAR + af * (ep - currentSAR);
|
|
1446
|
+
if (i > 0) {
|
|
1447
|
+
const prevHigh = highs[i - 1] || prices[i - 1];
|
|
1448
|
+
currentSAR = Math.max(currentSAR, prevHigh);
|
|
1449
|
+
}
|
|
1450
|
+
}
|
|
1451
|
+
}
|
|
1452
|
+
sar.push(currentSAR);
|
|
1453
|
+
}
|
|
1454
|
+
return sar;
|
|
1455
|
+
}
|
|
1456
|
+
};
|
|
1457
|
+
|
|
1458
|
+
// src/tools/indicators/volatility.ts
|
|
1459
|
+
var VolatilityIndicators = class _VolatilityIndicators {
|
|
1460
|
+
/**
|
|
1461
|
+
* Calculate Bollinger Bands
|
|
1462
|
+
*/
|
|
1463
|
+
static calculateBollingerBands(data, period = 20, stdDev = 2) {
|
|
1464
|
+
if (data.length < period) return [];
|
|
1465
|
+
const sma = MovingAverages.calculateSMA(data, period);
|
|
1466
|
+
const bands = [];
|
|
1467
|
+
for (let i = 0; i < sma.length; i++) {
|
|
1468
|
+
const dataSlice = data.slice(i, i + period);
|
|
1469
|
+
const mean = sma[i];
|
|
1470
|
+
const variance = dataSlice.reduce((sum2, price) => sum2 + (price - mean) ** 2, 0) / period;
|
|
1471
|
+
const standardDeviation = Math.sqrt(variance);
|
|
1472
|
+
const upper = mean + standardDeviation * stdDev;
|
|
1473
|
+
const lower = mean - standardDeviation * stdDev;
|
|
1474
|
+
bands.push({
|
|
1475
|
+
upper,
|
|
1476
|
+
middle: mean,
|
|
1477
|
+
lower,
|
|
1478
|
+
bandwidth: (upper - lower) / mean * 100,
|
|
1479
|
+
percentB: (data[i] - lower) / (upper - lower) * 100
|
|
1480
|
+
});
|
|
1481
|
+
}
|
|
1482
|
+
return bands;
|
|
1483
|
+
}
|
|
1484
|
+
/**
|
|
1485
|
+
* Calculate Average True Range (ATR)
|
|
1486
|
+
*/
|
|
1487
|
+
static calculateATR(prices, highs, lows) {
|
|
1488
|
+
if (prices.length < 2) return [];
|
|
1489
|
+
const trueRanges = [];
|
|
1490
|
+
for (let i = 1; i < prices.length; i++) {
|
|
1491
|
+
const high = highs[i] || prices[i];
|
|
1492
|
+
const low = lows[i] || prices[i];
|
|
1493
|
+
const prevClose = prices[i - 1];
|
|
1494
|
+
const tr1 = high - low;
|
|
1495
|
+
const tr2 = Math.abs(high - prevClose);
|
|
1496
|
+
const tr3 = Math.abs(low - prevClose);
|
|
1497
|
+
trueRanges.push(Math.max(tr1, tr2, tr3));
|
|
1498
|
+
}
|
|
1499
|
+
const atr = [];
|
|
1500
|
+
if (trueRanges.length >= 14) {
|
|
1501
|
+
let sum2 = trueRanges.slice(0, 14).reduce((a, b) => a + b, 0);
|
|
1502
|
+
atr.push(sum2 / 14);
|
|
1503
|
+
for (let i = 14; i < trueRanges.length; i++) {
|
|
1504
|
+
sum2 = sum2 - trueRanges[i - 14] + trueRanges[i];
|
|
1505
|
+
atr.push(sum2 / 14);
|
|
1506
|
+
}
|
|
1507
|
+
}
|
|
1508
|
+
return atr;
|
|
1509
|
+
}
|
|
1510
|
+
/**
|
|
1511
|
+
* Calculate Keltner Channels
|
|
1512
|
+
*/
|
|
1513
|
+
static calculateKeltnerChannels(prices, highs, lows) {
|
|
1514
|
+
const keltner = [];
|
|
1515
|
+
const period = 20;
|
|
1516
|
+
const multiplier = 2;
|
|
1517
|
+
if (prices.length < period) return [];
|
|
1518
|
+
const ema = MovingAverages.calculateEMA(prices, period);
|
|
1519
|
+
const atr = _VolatilityIndicators.calculateATR(prices, highs, lows);
|
|
1520
|
+
for (let i = 0; i < Math.min(ema.length, atr.length); i++) {
|
|
1521
|
+
const middle = ema[i];
|
|
1522
|
+
const atrValue = atr[i];
|
|
1523
|
+
keltner.push({
|
|
1524
|
+
upper: middle + multiplier * atrValue,
|
|
1525
|
+
middle,
|
|
1526
|
+
lower: middle - multiplier * atrValue
|
|
1527
|
+
});
|
|
1528
|
+
}
|
|
1529
|
+
return keltner;
|
|
1530
|
+
}
|
|
1531
|
+
/**
|
|
1532
|
+
* Calculate Donchian Channels
|
|
1533
|
+
*/
|
|
1534
|
+
static calculateDonchianChannels(prices) {
|
|
1535
|
+
const donchian = [];
|
|
1536
|
+
for (let i = 20; i < prices.length; i++) {
|
|
1537
|
+
const slice = prices.slice(i - 20, i);
|
|
1538
|
+
donchian.push({
|
|
1539
|
+
upper: Math.max(...slice),
|
|
1540
|
+
middle: (Math.max(...slice) + Math.min(...slice)) / 2,
|
|
1541
|
+
lower: Math.min(...slice)
|
|
1542
|
+
});
|
|
1543
|
+
}
|
|
1544
|
+
return donchian;
|
|
1545
|
+
}
|
|
1546
|
+
/**
|
|
1547
|
+
* Calculate Chaikin Volatility
|
|
1548
|
+
*/
|
|
1549
|
+
static calculateChaikinVolatility(prices, highs, lows) {
|
|
1550
|
+
const volatility = [];
|
|
1551
|
+
const period = 10;
|
|
1552
|
+
if (prices.length < period * 2) return [];
|
|
1553
|
+
const highLowRange = [];
|
|
1554
|
+
for (let i = 0; i < prices.length; i++) {
|
|
1555
|
+
const high = highs[i] || prices[i];
|
|
1556
|
+
const low = lows[i] || prices[i];
|
|
1557
|
+
highLowRange.push(high - low);
|
|
1558
|
+
}
|
|
1559
|
+
const emaRange = MovingAverages.calculateEMA(highLowRange, period);
|
|
1560
|
+
for (let i = period; i < emaRange.length; i++) {
|
|
1561
|
+
const currentEMA = emaRange[i];
|
|
1562
|
+
const pastEMA = emaRange[i - period];
|
|
1563
|
+
const volatilityValue = pastEMA !== 0 ? (currentEMA - pastEMA) / pastEMA * 100 : 0;
|
|
1564
|
+
volatility.push(volatilityValue);
|
|
1565
|
+
}
|
|
1566
|
+
return volatility;
|
|
1567
|
+
}
|
|
1568
|
+
};
|
|
1569
|
+
|
|
1570
|
+
// src/tools/indicators/volume.ts
|
|
1571
|
+
var VolumeIndicators = class {
|
|
1572
|
+
/**
|
|
1573
|
+
* Calculate On Balance Volume (OBV)
|
|
1574
|
+
*/
|
|
1575
|
+
static calculateOBV(prices, volumes) {
|
|
1576
|
+
const obv = [volumes[0]];
|
|
1577
|
+
for (let i = 1; i < prices.length; i++) {
|
|
1578
|
+
if (prices[i] > prices[i - 1]) {
|
|
1579
|
+
obv.push(obv[i - 1] + volumes[i]);
|
|
1580
|
+
} else if (prices[i] < prices[i - 1]) {
|
|
1581
|
+
obv.push(obv[i - 1] - volumes[i]);
|
|
1582
|
+
} else {
|
|
1583
|
+
obv.push(obv[i - 1]);
|
|
1584
|
+
}
|
|
1585
|
+
}
|
|
1586
|
+
return obv;
|
|
1587
|
+
}
|
|
1588
|
+
/**
|
|
1589
|
+
* Calculate Chaikin Money Flow (CMF)
|
|
1590
|
+
*/
|
|
1591
|
+
static calculateCMF(prices, highs, lows, volumes) {
|
|
1592
|
+
const cmf = [];
|
|
1593
|
+
const period = 20;
|
|
1594
|
+
if (prices.length < period) return [];
|
|
1595
|
+
for (let i = period - 1; i < prices.length; i++) {
|
|
1596
|
+
let totalMoneyFlowVolume = 0;
|
|
1597
|
+
let totalVolume = 0;
|
|
1598
|
+
for (let j = i - period + 1; j <= i; j++) {
|
|
1599
|
+
const high = highs[j] || prices[j];
|
|
1600
|
+
const low = lows[j] || prices[j];
|
|
1601
|
+
const close = prices[j];
|
|
1602
|
+
const volume = volumes[j] || 1;
|
|
1603
|
+
const moneyFlowMultiplier = (close - low - (high - close)) / (high - low);
|
|
1604
|
+
const moneyFlowVolume = moneyFlowMultiplier * volume;
|
|
1605
|
+
totalMoneyFlowVolume += moneyFlowVolume;
|
|
1606
|
+
totalVolume += volume;
|
|
1607
|
+
}
|
|
1608
|
+
const cmfValue = totalVolume !== 0 ? totalMoneyFlowVolume / totalVolume : 0;
|
|
1609
|
+
cmf.push(cmfValue);
|
|
1610
|
+
}
|
|
1611
|
+
return cmf;
|
|
1612
|
+
}
|
|
1613
|
+
/**
|
|
1614
|
+
* Calculate Accumulation/Distribution Line (ADL)
|
|
1615
|
+
*/
|
|
1616
|
+
static calculateADL(prices, highs, lows, volumes) {
|
|
1617
|
+
const adl = [0];
|
|
1618
|
+
for (let i = 1; i < prices.length; i++) {
|
|
1619
|
+
const high = highs[i] || prices[i];
|
|
1620
|
+
const low = lows[i] || prices[i];
|
|
1621
|
+
const close = prices[i];
|
|
1622
|
+
const volume = volumes[i] || 1;
|
|
1623
|
+
const moneyFlowMultiplier = (close - low - (high - close)) / (high - low);
|
|
1624
|
+
const moneyFlowVolume = moneyFlowMultiplier * volume;
|
|
1625
|
+
adl.push(adl[i - 1] + moneyFlowVolume);
|
|
1626
|
+
}
|
|
1627
|
+
return adl;
|
|
1628
|
+
}
|
|
1629
|
+
/**
|
|
1630
|
+
* Calculate Volume Rate of Change
|
|
1631
|
+
*/
|
|
1632
|
+
static calculateVolumeROC(volumes) {
|
|
1633
|
+
const volumeROC = [];
|
|
1634
|
+
for (let i = 10; i < volumes.length; i++) {
|
|
1635
|
+
volumeROC.push((volumes[i] - volumes[i - 10]) / volumes[i - 10] * 100);
|
|
1636
|
+
}
|
|
1637
|
+
return volumeROC;
|
|
1638
|
+
}
|
|
1639
|
+
/**
|
|
1640
|
+
* Calculate Money Flow Index (MFI)
|
|
1641
|
+
*/
|
|
1642
|
+
static calculateMFI(prices, highs, lows, volumes) {
|
|
1643
|
+
const mfi = [];
|
|
1644
|
+
const period = 14;
|
|
1645
|
+
if (prices.length < period + 1) return [];
|
|
1646
|
+
for (let i = period; i < prices.length; i++) {
|
|
1647
|
+
let positiveMoneyFlow = 0;
|
|
1648
|
+
let negativeMoneyFlow = 0;
|
|
1649
|
+
for (let j = i - period + 1; j <= i; j++) {
|
|
1650
|
+
const high = highs[j] || prices[j];
|
|
1651
|
+
const low = lows[j] || prices[j];
|
|
1652
|
+
const close = prices[j];
|
|
1653
|
+
const volume = volumes[j] || 1;
|
|
1654
|
+
const typicalPrice = (high + low + close) / 3;
|
|
1655
|
+
const moneyFlow = typicalPrice * volume;
|
|
1656
|
+
if (j > i - period + 1) {
|
|
1657
|
+
const prevHigh = highs[j - 1] || prices[j - 1];
|
|
1658
|
+
const prevLow = lows[j - 1] || prices[j - 1];
|
|
1659
|
+
const prevClose = prices[j - 1];
|
|
1660
|
+
const prevTypicalPrice = (prevHigh + prevLow + prevClose) / 3;
|
|
1661
|
+
if (typicalPrice > prevTypicalPrice) {
|
|
1662
|
+
positiveMoneyFlow += moneyFlow;
|
|
1663
|
+
} else if (typicalPrice < prevTypicalPrice) {
|
|
1664
|
+
negativeMoneyFlow += moneyFlow;
|
|
1665
|
+
}
|
|
1666
|
+
}
|
|
1667
|
+
}
|
|
1668
|
+
const moneyRatio = negativeMoneyFlow !== 0 ? positiveMoneyFlow / negativeMoneyFlow : 0;
|
|
1669
|
+
const mfiValue = 100 - 100 / (1 + moneyRatio);
|
|
1670
|
+
mfi.push(mfiValue);
|
|
1671
|
+
}
|
|
1672
|
+
return mfi;
|
|
1673
|
+
}
|
|
1674
|
+
/**
|
|
1675
|
+
* Calculate Volume Weighted Average Price (VWAP)
|
|
1676
|
+
*/
|
|
1677
|
+
static calculateVWAP(prices, volumes) {
|
|
1678
|
+
const vwap = [];
|
|
1679
|
+
let cumulativePV = 0;
|
|
1680
|
+
let cumulativeVolume = 0;
|
|
1681
|
+
for (let i = 0; i < prices.length; i++) {
|
|
1682
|
+
cumulativePV += prices[i] * (volumes[i] || 1);
|
|
1683
|
+
cumulativeVolume += volumes[i] || 1;
|
|
1684
|
+
vwap.push(cumulativePV / cumulativeVolume);
|
|
1685
|
+
}
|
|
1686
|
+
return vwap;
|
|
1687
|
+
}
|
|
1688
|
+
};
|
|
1689
|
+
|
|
1690
|
+
// src/tools/analytics.ts
|
|
1691
|
+
function sum(numbers) {
|
|
1692
|
+
return numbers.reduce((acc, val) => acc + val, 0);
|
|
1693
|
+
}
|
|
1694
|
+
var TechnicalAnalyzer = class {
|
|
1695
|
+
prices;
|
|
1696
|
+
volumes;
|
|
1697
|
+
highs;
|
|
1698
|
+
lows;
|
|
1699
|
+
constructor(data) {
|
|
1700
|
+
this.prices = data.map((d) => d.trade > 0 ? d.trade : d.midPrice);
|
|
1701
|
+
this.volumes = data.map((d) => d.volume);
|
|
1702
|
+
this.highs = data.map((d) => d.tradingSessionHighPrice > 0 ? d.tradingSessionHighPrice : d.trade);
|
|
1703
|
+
this.lows = data.map((d) => d.tradingSessionLowPrice > 0 ? d.tradingSessionLowPrice : d.trade);
|
|
1704
|
+
}
|
|
1705
|
+
// Calculate price changes for volatility
|
|
1706
|
+
calculatePriceChanges() {
|
|
1707
|
+
const changes = [];
|
|
1708
|
+
for (let i = 1; i < this.prices.length; i++) {
|
|
1709
|
+
changes.push((this.prices[i] - this.prices[i - 1]) / this.prices[i - 1]);
|
|
1710
|
+
}
|
|
1711
|
+
return changes;
|
|
1712
|
+
}
|
|
1713
|
+
// Generate comprehensive market analysis
|
|
1714
|
+
analyze() {
|
|
1715
|
+
const currentPrice = this.prices[this.prices.length - 1];
|
|
1716
|
+
const startPrice = this.prices[0];
|
|
1717
|
+
const sessionHigh = Math.max(...this.highs);
|
|
1718
|
+
const sessionLow = Math.min(...this.lows);
|
|
1719
|
+
const totalVolume = sum(this.volumes);
|
|
1720
|
+
const avgVolume = totalVolume / this.volumes.length;
|
|
1721
|
+
const priceChanges = this.calculatePriceChanges();
|
|
1722
|
+
const volatility = priceChanges.length > 0 ? Math.sqrt(
|
|
1723
|
+
priceChanges.reduce((sum2, change) => sum2 + change ** 2, 0) / priceChanges.length
|
|
1724
|
+
) * Math.sqrt(252) * 100 : 0;
|
|
1725
|
+
const sessionReturn = (currentPrice - startPrice) / startPrice * 100;
|
|
1726
|
+
const pricePosition = (currentPrice - sessionLow) / (sessionHigh - sessionLow) * 100;
|
|
1727
|
+
const trueVWAP = this.prices.reduce((sum2, price, i) => sum2 + price * this.volumes[i], 0) / totalVolume;
|
|
1728
|
+
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;
|
|
1729
|
+
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;
|
|
1730
|
+
const maxDrawdown = PerformanceAnalysis.calculateMaxDrawdown(this.prices);
|
|
1731
|
+
const atrValues = VolatilityIndicators.calculateATR(this.prices, this.highs, this.lows);
|
|
1732
|
+
const atr = atrValues.length > 0 ? atrValues[atrValues.length - 1] : 0;
|
|
1733
|
+
const impliedVolatility = volatility;
|
|
1734
|
+
const realizedVolatility = volatility;
|
|
1735
|
+
const sharpeRatio = sessionReturn / volatility;
|
|
1736
|
+
const sortinoRatio = sessionReturn / realizedVolatility;
|
|
1737
|
+
const calmarRatio = sessionReturn / maxDrawdown;
|
|
1738
|
+
const maxConsecutiveLosses = PerformanceAnalysis.calculateMaxConsecutiveLosses(this.prices);
|
|
1739
|
+
const winRate = PerformanceAnalysis.calculateWinRate(this.prices);
|
|
1740
|
+
const profitFactor = PerformanceAnalysis.calculateProfitFactor(this.prices);
|
|
1741
|
+
return {
|
|
1742
|
+
currentPrice,
|
|
1743
|
+
startPrice,
|
|
1744
|
+
sessionHigh,
|
|
1745
|
+
sessionLow,
|
|
1746
|
+
totalVolume,
|
|
1747
|
+
avgVolume,
|
|
1748
|
+
volatility,
|
|
1749
|
+
sessionReturn,
|
|
1750
|
+
pricePosition,
|
|
1751
|
+
trueVWAP,
|
|
1752
|
+
momentum5,
|
|
1753
|
+
momentum10,
|
|
1754
|
+
maxDrawdown,
|
|
1755
|
+
atr,
|
|
1756
|
+
impliedVolatility,
|
|
1757
|
+
realizedVolatility,
|
|
1758
|
+
sharpeRatio,
|
|
1759
|
+
sortinoRatio,
|
|
1760
|
+
calmarRatio,
|
|
1761
|
+
maxConsecutiveLosses,
|
|
1762
|
+
winRate,
|
|
1763
|
+
profitFactor
|
|
1764
|
+
};
|
|
1765
|
+
}
|
|
1766
|
+
// Generate technical indicators
|
|
1767
|
+
getTechnicalIndicators() {
|
|
1768
|
+
return {
|
|
1769
|
+
sma5: MovingAverages.calculateSMA(this.prices, 5),
|
|
1770
|
+
sma10: MovingAverages.calculateSMA(this.prices, 10),
|
|
1771
|
+
sma20: MovingAverages.calculateSMA(this.prices, 20),
|
|
1772
|
+
sma50: MovingAverages.calculateSMA(this.prices, 50),
|
|
1773
|
+
sma200: MovingAverages.calculateSMA(this.prices, 200),
|
|
1774
|
+
ema8: MovingAverages.calculateEMA(this.prices, 8),
|
|
1775
|
+
ema12: MovingAverages.calculateEMA(this.prices, 12),
|
|
1776
|
+
ema21: MovingAverages.calculateEMA(this.prices, 21),
|
|
1777
|
+
ema26: MovingAverages.calculateEMA(this.prices, 26),
|
|
1778
|
+
wma20: MovingAverages.calculateWMA(this.prices, 20),
|
|
1779
|
+
vwma20: MovingAverages.calculateVWMA(this.prices, this.volumes, 20),
|
|
1780
|
+
macd: TrendIndicators.calculateMACD(this.prices),
|
|
1781
|
+
adx: TrendIndicators.calculateADX(this.prices, this.highs, this.lows),
|
|
1782
|
+
dmi: TrendIndicators.calculateDMI(this.prices, this.highs, this.lows),
|
|
1783
|
+
ichimoku: TrendIndicators.calculateIchimoku(this.prices, this.highs, this.lows),
|
|
1784
|
+
parabolicSAR: TrendIndicators.calculateParabolicSAR(this.prices, this.highs, this.lows),
|
|
1785
|
+
rsi: MomentumIndicators.calculateRSI(this.prices, 14),
|
|
1786
|
+
stochastic: MomentumIndicators.calculateStochastic(this.prices, this.highs, this.lows),
|
|
1787
|
+
cci: MomentumIndicators.calculateCCI(this.prices, this.highs, this.lows),
|
|
1788
|
+
roc: MomentumIndicators.calculateROC(this.prices),
|
|
1789
|
+
williamsR: MomentumIndicators.calculateWilliamsR(this.prices),
|
|
1790
|
+
momentum: MomentumIndicators.calculateMomentum(this.prices),
|
|
1791
|
+
bollinger: VolatilityIndicators.calculateBollingerBands(this.prices, 20, 2),
|
|
1792
|
+
atr: VolatilityIndicators.calculateATR(this.prices, this.highs, this.lows),
|
|
1793
|
+
keltner: VolatilityIndicators.calculateKeltnerChannels(this.prices, this.highs, this.lows),
|
|
1794
|
+
donchian: VolatilityIndicators.calculateDonchianChannels(this.prices),
|
|
1795
|
+
chaikinVolatility: VolatilityIndicators.calculateChaikinVolatility(this.prices, this.highs, this.lows),
|
|
1796
|
+
obv: VolumeIndicators.calculateOBV(this.prices, this.volumes),
|
|
1797
|
+
cmf: VolumeIndicators.calculateCMF(this.prices, this.highs, this.lows, this.volumes),
|
|
1798
|
+
adl: VolumeIndicators.calculateADL(this.prices, this.highs, this.lows, this.volumes),
|
|
1799
|
+
volumeROC: VolumeIndicators.calculateVolumeROC(this.volumes),
|
|
1800
|
+
mfi: VolumeIndicators.calculateMFI(this.prices, this.highs, this.lows, this.volumes),
|
|
1801
|
+
vwap: VolumeIndicators.calculateVWAP(this.prices, this.volumes),
|
|
1802
|
+
pivotPoints: SupportResistanceIndicators.calculatePivotPoints(this.prices, this.highs, this.lows),
|
|
1803
|
+
fibonacci: SupportResistanceIndicators.calculateFibonacciLevels(this.prices),
|
|
1804
|
+
gannLevels: SupportResistanceIndicators.calculateGannLevels(this.prices),
|
|
1805
|
+
elliottWave: SupportResistanceIndicators.calculateElliottWave(this.prices),
|
|
1806
|
+
harmonicPatterns: SupportResistanceIndicators.calculateHarmonicPatterns(this.prices)
|
|
1807
|
+
};
|
|
1808
|
+
}
|
|
1809
|
+
// Generate comprehensive JSON analysis
|
|
1810
|
+
generateJSONAnalysis(symbol) {
|
|
1811
|
+
const analysis = this.analyze();
|
|
1812
|
+
const indicators = this.getTechnicalIndicators();
|
|
1813
|
+
const priceChanges = this.calculatePriceChanges();
|
|
1814
|
+
const currentSMA5 = indicators.sma5.length > 0 ? indicators.sma5[indicators.sma5.length - 1] : null;
|
|
1815
|
+
const currentSMA10 = indicators.sma10.length > 0 ? indicators.sma10[indicators.sma10.length - 1] : null;
|
|
1816
|
+
const currentSMA20 = indicators.sma20.length > 0 ? indicators.sma20[indicators.sma20.length - 1] : null;
|
|
1817
|
+
const currentSMA50 = indicators.sma50.length > 0 ? indicators.sma50[indicators.sma50.length - 1] : null;
|
|
1818
|
+
const currentSMA200 = indicators.sma200.length > 0 ? indicators.sma200[indicators.sma200.length - 1] : null;
|
|
1819
|
+
const currentEMA8 = indicators.ema8[indicators.ema8.length - 1];
|
|
1820
|
+
const currentEMA12 = indicators.ema12[indicators.ema12.length - 1];
|
|
1821
|
+
const currentEMA21 = indicators.ema21[indicators.ema21.length - 1];
|
|
1822
|
+
const currentEMA26 = indicators.ema26[indicators.ema26.length - 1];
|
|
1823
|
+
const currentWMA20 = indicators.wma20.length > 0 ? indicators.wma20[indicators.wma20.length - 1] : null;
|
|
1824
|
+
const currentVWMA20 = indicators.vwma20.length > 0 ? indicators.vwma20[indicators.vwma20.length - 1] : null;
|
|
1825
|
+
const currentMACD = indicators.macd.length > 0 ? indicators.macd[indicators.macd.length - 1] : null;
|
|
1826
|
+
const currentADX = indicators.adx.length > 0 ? indicators.adx[indicators.adx.length - 1] : null;
|
|
1827
|
+
const currentDMI = indicators.dmi.length > 0 ? indicators.dmi[indicators.dmi.length - 1] : null;
|
|
1828
|
+
const currentIchimoku = indicators.ichimoku.length > 0 ? indicators.ichimoku[indicators.ichimoku.length - 1] : null;
|
|
1829
|
+
const currentParabolicSAR = indicators.parabolicSAR.length > 0 ? indicators.parabolicSAR[indicators.parabolicSAR.length - 1] : null;
|
|
1830
|
+
const currentRSI = indicators.rsi.length > 0 ? indicators.rsi[indicators.rsi.length - 1] : null;
|
|
1831
|
+
const currentStochastic = indicators.stochastic.length > 0 ? indicators.stochastic[indicators.stochastic.length - 1] : null;
|
|
1832
|
+
const currentCCI = indicators.cci.length > 0 ? indicators.cci[indicators.cci.length - 1] : null;
|
|
1833
|
+
const currentROC = indicators.roc.length > 0 ? indicators.roc[indicators.roc.length - 1] : null;
|
|
1834
|
+
const currentWilliamsR = indicators.williamsR.length > 0 ? indicators.williamsR[indicators.williamsR.length - 1] : null;
|
|
1835
|
+
const currentMomentum = indicators.momentum.length > 0 ? indicators.momentum[indicators.momentum.length - 1] : null;
|
|
1836
|
+
const currentBB = indicators.bollinger.length > 0 ? indicators.bollinger[indicators.bollinger.length - 1] : null;
|
|
1837
|
+
const currentAtr = indicators.atr.length > 0 ? indicators.atr[indicators.atr.length - 1] : null;
|
|
1838
|
+
const currentKeltner = indicators.keltner.length > 0 ? indicators.keltner[indicators.keltner.length - 1] : null;
|
|
1839
|
+
const currentDonchian = indicators.donchian.length > 0 ? indicators.donchian[indicators.donchian.length - 1] : null;
|
|
1840
|
+
const currentChaikinVolatility = indicators.chaikinVolatility.length > 0 ? indicators.chaikinVolatility[indicators.chaikinVolatility.length - 1] : null;
|
|
1841
|
+
const currentObv = indicators.obv.length > 0 ? indicators.obv[indicators.obv.length - 1] : null;
|
|
1842
|
+
const currentCmf = indicators.cmf.length > 0 ? indicators.cmf[indicators.cmf.length - 1] : null;
|
|
1843
|
+
const currentAdl = indicators.adl.length > 0 ? indicators.adl[indicators.adl.length - 1] : null;
|
|
1844
|
+
const currentVolumeROC = indicators.volumeROC.length > 0 ? indicators.volumeROC[indicators.volumeROC.length - 1] : null;
|
|
1845
|
+
const currentMfi = indicators.mfi.length > 0 ? indicators.mfi[indicators.mfi.length - 1] : null;
|
|
1846
|
+
const currentVwap = indicators.vwap.length > 0 ? indicators.vwap[indicators.vwap.length - 1] : null;
|
|
1847
|
+
const currentPivotPoints = indicators.pivotPoints.length > 0 ? indicators.pivotPoints[indicators.pivotPoints.length - 1] : null;
|
|
1848
|
+
const currentFibonacci = indicators.fibonacci.length > 0 ? indicators.fibonacci[indicators.fibonacci.length - 1] : null;
|
|
1849
|
+
const currentGannLevels = indicators.gannLevels.length > 0 ? indicators.gannLevels : [];
|
|
1850
|
+
const currentElliottWave = indicators.elliottWave.length > 0 ? indicators.elliottWave[indicators.elliottWave.length - 1] : null;
|
|
1851
|
+
const currentHarmonicPatterns = indicators.harmonicPatterns.length > 0 ? indicators.harmonicPatterns : [];
|
|
1852
|
+
const currentVolume = this.volumes[this.volumes.length - 1];
|
|
1853
|
+
const volumeRatio = currentVolume / analysis.avgVolume;
|
|
1854
|
+
const currentDrawdown = (analysis.sessionHigh - analysis.currentPrice) / analysis.sessionHigh * 100;
|
|
1855
|
+
const rangeWidth = (analysis.sessionHigh - analysis.sessionLow) / analysis.sessionLow * 100;
|
|
1856
|
+
const priceVsVWAP = (analysis.currentPrice - analysis.trueVWAP) / analysis.trueVWAP * 100;
|
|
1857
|
+
const signalData = TradingSignalsGenerator.generateSignals(
|
|
1858
|
+
analysis.currentPrice,
|
|
1859
|
+
analysis.trueVWAP,
|
|
1860
|
+
analysis.momentum5,
|
|
1861
|
+
analysis.momentum10,
|
|
1862
|
+
analysis.sessionReturn,
|
|
1863
|
+
currentVolume,
|
|
1864
|
+
analysis.avgVolume,
|
|
1865
|
+
analysis.pricePosition,
|
|
1866
|
+
analysis.volatility
|
|
1867
|
+
);
|
|
1868
|
+
const tradingSignals = TradingSignalsGenerator.calculateOverallSignal(
|
|
1869
|
+
signalData.bullishSignals,
|
|
1870
|
+
signalData.bearishSignals,
|
|
1871
|
+
signalData.signals,
|
|
1872
|
+
analysis.volatility
|
|
1873
|
+
);
|
|
1874
|
+
const targetEntry = Math.max(analysis.sessionLow * 1.005, analysis.trueVWAP * 0.998);
|
|
1875
|
+
const stopLoss = analysis.sessionLow * 0.995;
|
|
1876
|
+
const profitTarget = analysis.sessionHigh * 0.995;
|
|
1877
|
+
const riskRewardRatio = (profitTarget - analysis.currentPrice) / (analysis.currentPrice - stopLoss);
|
|
1878
|
+
const positionSize = PerformanceAnalysis.calculatePositionSize(targetEntry, stopLoss);
|
|
1879
|
+
const maxRisk = positionSize * (targetEntry - stopLoss);
|
|
1880
|
+
return {
|
|
1881
|
+
symbol,
|
|
1882
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1883
|
+
marketStructure: {
|
|
1884
|
+
currentPrice: analysis.currentPrice,
|
|
1885
|
+
startPrice: analysis.startPrice,
|
|
1886
|
+
sessionHigh: analysis.sessionHigh,
|
|
1887
|
+
sessionLow: analysis.sessionLow,
|
|
1888
|
+
rangeWidth,
|
|
1889
|
+
totalVolume: analysis.totalVolume,
|
|
1890
|
+
sessionPerformance: analysis.sessionReturn,
|
|
1891
|
+
positionInRange: analysis.pricePosition
|
|
1892
|
+
},
|
|
1893
|
+
volatility: {
|
|
1894
|
+
impliedVolatility: analysis.impliedVolatility,
|
|
1895
|
+
realizedVolatility: analysis.realizedVolatility,
|
|
1896
|
+
atr: analysis.atr,
|
|
1897
|
+
maxDrawdown: analysis.maxDrawdown * 100,
|
|
1898
|
+
currentDrawdown
|
|
1899
|
+
},
|
|
1900
|
+
technicalIndicators: {
|
|
1901
|
+
sma5: currentSMA5,
|
|
1902
|
+
sma10: currentSMA10,
|
|
1903
|
+
sma20: currentSMA20,
|
|
1904
|
+
sma50: currentSMA50,
|
|
1905
|
+
sma200: currentSMA200,
|
|
1906
|
+
ema8: currentEMA8,
|
|
1907
|
+
ema12: currentEMA12,
|
|
1908
|
+
ema21: currentEMA21,
|
|
1909
|
+
ema26: currentEMA26,
|
|
1910
|
+
wma20: currentWMA20,
|
|
1911
|
+
vwma20: currentVWMA20,
|
|
1912
|
+
macd: currentMACD,
|
|
1913
|
+
adx: currentADX,
|
|
1914
|
+
dmi: currentDMI,
|
|
1915
|
+
ichimoku: currentIchimoku,
|
|
1916
|
+
parabolicSAR: currentParabolicSAR,
|
|
1917
|
+
rsi: currentRSI,
|
|
1918
|
+
stochastic: currentStochastic,
|
|
1919
|
+
cci: currentCCI,
|
|
1920
|
+
roc: currentROC,
|
|
1921
|
+
williamsR: currentWilliamsR,
|
|
1922
|
+
momentum: currentMomentum,
|
|
1923
|
+
bollingerBands: currentBB ? {
|
|
1924
|
+
upper: currentBB.upper,
|
|
1925
|
+
middle: currentBB.middle,
|
|
1926
|
+
lower: currentBB.lower,
|
|
1927
|
+
bandwidth: currentBB.bandwidth,
|
|
1928
|
+
percentB: currentBB.percentB
|
|
1929
|
+
} : null,
|
|
1930
|
+
atr: currentAtr,
|
|
1931
|
+
keltnerChannels: currentKeltner ? {
|
|
1932
|
+
upper: currentKeltner.upper,
|
|
1933
|
+
middle: currentKeltner.middle,
|
|
1934
|
+
lower: currentKeltner.lower
|
|
1935
|
+
} : null,
|
|
1936
|
+
donchianChannels: currentDonchian ? {
|
|
1937
|
+
upper: currentDonchian.upper,
|
|
1938
|
+
middle: currentDonchian.middle,
|
|
1939
|
+
lower: currentDonchian.lower
|
|
1940
|
+
} : null,
|
|
1941
|
+
chaikinVolatility: currentChaikinVolatility,
|
|
1942
|
+
obv: currentObv,
|
|
1943
|
+
cmf: currentCmf,
|
|
1944
|
+
adl: currentAdl,
|
|
1945
|
+
volumeROC: currentVolumeROC,
|
|
1946
|
+
mfi: currentMfi,
|
|
1947
|
+
vwap: currentVwap
|
|
1948
|
+
},
|
|
1949
|
+
volumeAnalysis: {
|
|
1950
|
+
currentVolume,
|
|
1951
|
+
averageVolume: Math.round(analysis.avgVolume),
|
|
1952
|
+
volumeRatio,
|
|
1953
|
+
trueVWAP: analysis.trueVWAP,
|
|
1954
|
+
priceVsVWAP,
|
|
1955
|
+
obv: currentObv,
|
|
1956
|
+
cmf: currentCmf,
|
|
1957
|
+
mfi: currentMfi
|
|
1958
|
+
},
|
|
1959
|
+
momentum: {
|
|
1960
|
+
momentum5: analysis.momentum5,
|
|
1961
|
+
momentum10: analysis.momentum10,
|
|
1962
|
+
sessionROC: analysis.sessionReturn,
|
|
1963
|
+
rsi: currentRSI,
|
|
1964
|
+
stochastic: currentStochastic,
|
|
1965
|
+
cci: currentCCI
|
|
1966
|
+
},
|
|
1967
|
+
supportResistance: {
|
|
1968
|
+
pivotPoints: currentPivotPoints,
|
|
1969
|
+
fibonacci: currentFibonacci,
|
|
1970
|
+
gannLevels: currentGannLevels,
|
|
1971
|
+
elliottWave: currentElliottWave,
|
|
1972
|
+
harmonicPatterns: currentHarmonicPatterns
|
|
1973
|
+
},
|
|
1974
|
+
tradingSignals,
|
|
1975
|
+
statisticalModels: {
|
|
1976
|
+
zScore: StatisticalModels.calculateZScore(analysis.currentPrice, analysis.startPrice),
|
|
1977
|
+
ornsteinUhlenbeck: StatisticalModels.calculateOrnsteinUhlenbeck(
|
|
1978
|
+
analysis.currentPrice,
|
|
1979
|
+
analysis.startPrice,
|
|
1980
|
+
analysis.avgVolume,
|
|
1981
|
+
priceChanges
|
|
1982
|
+
),
|
|
1983
|
+
kalmanFilter: StatisticalModels.calculateKalmanFilter(
|
|
1984
|
+
analysis.currentPrice,
|
|
1985
|
+
analysis.startPrice,
|
|
1986
|
+
analysis.avgVolume,
|
|
1987
|
+
priceChanges
|
|
1988
|
+
),
|
|
1989
|
+
arima: StatisticalModels.calculateARIMA(analysis.currentPrice, priceChanges),
|
|
1990
|
+
garch: StatisticalModels.calculateGARCH(analysis.avgVolume, priceChanges),
|
|
1991
|
+
hilbertTransform: StatisticalModels.calculateHilbertTransform(analysis.currentPrice, priceChanges),
|
|
1992
|
+
waveletTransform: StatisticalModels.calculateWaveletTransform(analysis.currentPrice, priceChanges)
|
|
1993
|
+
},
|
|
1994
|
+
optionsAnalysis: (() => {
|
|
1995
|
+
const blackScholes = OptionsAnalysis.calculateBlackScholes(
|
|
1996
|
+
analysis.currentPrice,
|
|
1997
|
+
analysis.startPrice,
|
|
1998
|
+
analysis.avgVolume
|
|
1999
|
+
);
|
|
2000
|
+
if (!blackScholes) return null;
|
|
2001
|
+
return {
|
|
2002
|
+
blackScholes,
|
|
2003
|
+
impliedVolatility: analysis.impliedVolatility,
|
|
2004
|
+
delta: blackScholes.delta,
|
|
2005
|
+
gamma: blackScholes.gamma,
|
|
2006
|
+
theta: blackScholes.theta,
|
|
2007
|
+
vega: blackScholes.vega,
|
|
2008
|
+
rho: blackScholes.rho,
|
|
2009
|
+
greeks: {
|
|
2010
|
+
delta: blackScholes.delta,
|
|
2011
|
+
gamma: blackScholes.gamma,
|
|
2012
|
+
theta: blackScholes.theta,
|
|
2013
|
+
vega: blackScholes.vega,
|
|
2014
|
+
rho: blackScholes.rho
|
|
2015
|
+
}
|
|
2016
|
+
};
|
|
2017
|
+
})(),
|
|
2018
|
+
riskManagement: {
|
|
2019
|
+
targetEntry,
|
|
2020
|
+
stopLoss,
|
|
2021
|
+
profitTarget,
|
|
2022
|
+
riskRewardRatio,
|
|
2023
|
+
positionSize,
|
|
2024
|
+
maxRisk
|
|
2025
|
+
},
|
|
2026
|
+
performance: {
|
|
2027
|
+
sharpeRatio: analysis.sharpeRatio,
|
|
2028
|
+
sortinoRatio: analysis.sortinoRatio,
|
|
2029
|
+
calmarRatio: analysis.calmarRatio,
|
|
2030
|
+
maxDrawdown: analysis.maxDrawdown * 100,
|
|
2031
|
+
winRate: analysis.winRate,
|
|
2032
|
+
profitFactor: analysis.profitFactor,
|
|
2033
|
+
totalReturn: analysis.sessionReturn,
|
|
2034
|
+
volatility: analysis.volatility
|
|
2035
|
+
}
|
|
2036
|
+
};
|
|
2037
|
+
}
|
|
2038
|
+
};
|
|
2039
|
+
var createTechnicalAnalysisHandler = (marketDataPrices) => {
|
|
2040
|
+
return async (args) => {
|
|
2041
|
+
try {
|
|
2042
|
+
const symbol = args.symbol;
|
|
2043
|
+
const priceHistory = marketDataPrices.get(symbol) || [];
|
|
2044
|
+
if (priceHistory.length === 0) {
|
|
2045
|
+
return {
|
|
2046
|
+
content: [
|
|
2047
|
+
{
|
|
2048
|
+
type: "text",
|
|
2049
|
+
text: `No price data available for ${symbol}. Please request market data first.`,
|
|
2050
|
+
uri: "technicalAnalysis"
|
|
2051
|
+
}
|
|
2052
|
+
]
|
|
2053
|
+
};
|
|
2054
|
+
}
|
|
2055
|
+
const hasValidData = priceHistory.every(
|
|
2056
|
+
(entry) => typeof entry.trade === "number" && !Number.isNaN(entry.trade) && typeof entry.midPrice === "number" && !Number.isNaN(entry.midPrice)
|
|
2057
|
+
);
|
|
2058
|
+
if (!hasValidData) {
|
|
2059
|
+
throw new Error("Invalid market data");
|
|
2060
|
+
}
|
|
2061
|
+
const analyzer = new TechnicalAnalyzer(priceHistory);
|
|
2062
|
+
const analysis = analyzer.generateJSONAnalysis(symbol);
|
|
2063
|
+
return {
|
|
2064
|
+
content: [
|
|
2065
|
+
{
|
|
2066
|
+
type: "text",
|
|
2067
|
+
text: `Technical Analysis for ${symbol}:
|
|
2068
|
+
|
|
2069
|
+
${JSON.stringify(analysis, null, 2)}`,
|
|
2070
|
+
uri: "technicalAnalysis"
|
|
2071
|
+
}
|
|
2072
|
+
]
|
|
2073
|
+
};
|
|
2074
|
+
} catch (error) {
|
|
2075
|
+
return {
|
|
2076
|
+
content: [
|
|
2077
|
+
{
|
|
2078
|
+
type: "text",
|
|
2079
|
+
text: `Error performing technical analysis: ${error instanceof Error ? error.message : "Unknown error"}`,
|
|
2080
|
+
uri: "technicalAnalysis"
|
|
2081
|
+
}
|
|
2082
|
+
],
|
|
2083
|
+
isError: true
|
|
2084
|
+
};
|
|
2085
|
+
}
|
|
2086
|
+
};
|
|
2087
|
+
};
|
|
2088
|
+
|
|
2089
|
+
// src/tools/marketData.ts
|
|
29
2090
|
var import_fixparser = require("fixparser");
|
|
30
|
-
var
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
2091
|
+
var import_quickchart_js = __toESM(require("quickchart-js"), 1);
|
|
2092
|
+
var createMarketDataRequestHandler = (parser, pendingRequests) => {
|
|
2093
|
+
return async (args) => {
|
|
2094
|
+
try {
|
|
2095
|
+
parser.logger.log({
|
|
2096
|
+
level: "info",
|
|
2097
|
+
message: `Sending market data request for symbols: ${args.symbols.join(", ")}`
|
|
2098
|
+
});
|
|
2099
|
+
const response = new Promise((resolve) => {
|
|
2100
|
+
pendingRequests.set(args.mdReqID, resolve);
|
|
2101
|
+
parser.logger.log({
|
|
2102
|
+
level: "info",
|
|
2103
|
+
message: `Registered callback for market data request ID: ${args.mdReqID}`
|
|
2104
|
+
});
|
|
2105
|
+
});
|
|
2106
|
+
const entryTypes = args.mdEntryTypes || [
|
|
2107
|
+
import_fixparser.MDEntryType.Bid,
|
|
2108
|
+
import_fixparser.MDEntryType.Offer,
|
|
2109
|
+
import_fixparser.MDEntryType.Trade,
|
|
2110
|
+
import_fixparser.MDEntryType.IndexValue,
|
|
2111
|
+
import_fixparser.MDEntryType.OpeningPrice,
|
|
2112
|
+
import_fixparser.MDEntryType.ClosingPrice,
|
|
2113
|
+
import_fixparser.MDEntryType.SettlementPrice,
|
|
2114
|
+
import_fixparser.MDEntryType.TradingSessionHighPrice,
|
|
2115
|
+
import_fixparser.MDEntryType.TradingSessionLowPrice,
|
|
2116
|
+
import_fixparser.MDEntryType.VWAP,
|
|
2117
|
+
import_fixparser.MDEntryType.Imbalance,
|
|
2118
|
+
import_fixparser.MDEntryType.TradeVolume,
|
|
2119
|
+
import_fixparser.MDEntryType.OpenInterest,
|
|
2120
|
+
import_fixparser.MDEntryType.CompositeUnderlyingPrice,
|
|
2121
|
+
import_fixparser.MDEntryType.SimulatedSellPrice,
|
|
2122
|
+
import_fixparser.MDEntryType.SimulatedBuyPrice,
|
|
2123
|
+
import_fixparser.MDEntryType.MarginRate,
|
|
2124
|
+
import_fixparser.MDEntryType.MidPrice,
|
|
2125
|
+
import_fixparser.MDEntryType.EmptyBook,
|
|
2126
|
+
import_fixparser.MDEntryType.SettleHighPrice,
|
|
2127
|
+
import_fixparser.MDEntryType.SettleLowPrice,
|
|
2128
|
+
import_fixparser.MDEntryType.PriorSettlePrice,
|
|
2129
|
+
import_fixparser.MDEntryType.SessionHighBid,
|
|
2130
|
+
import_fixparser.MDEntryType.SessionLowOffer,
|
|
2131
|
+
import_fixparser.MDEntryType.EarlyPrices,
|
|
2132
|
+
import_fixparser.MDEntryType.AuctionClearingPrice,
|
|
2133
|
+
import_fixparser.MDEntryType.SwapValueFactor,
|
|
2134
|
+
import_fixparser.MDEntryType.DailyValueAdjustmentForLongPositions,
|
|
2135
|
+
import_fixparser.MDEntryType.CumulativeValueAdjustmentForLongPositions,
|
|
2136
|
+
import_fixparser.MDEntryType.DailyValueAdjustmentForShortPositions,
|
|
2137
|
+
import_fixparser.MDEntryType.CumulativeValueAdjustmentForShortPositions,
|
|
2138
|
+
import_fixparser.MDEntryType.FixingPrice,
|
|
2139
|
+
import_fixparser.MDEntryType.CashRate,
|
|
2140
|
+
import_fixparser.MDEntryType.RecoveryRate,
|
|
2141
|
+
import_fixparser.MDEntryType.RecoveryRateForLong,
|
|
2142
|
+
import_fixparser.MDEntryType.RecoveryRateForShort,
|
|
2143
|
+
import_fixparser.MDEntryType.MarketBid,
|
|
2144
|
+
import_fixparser.MDEntryType.MarketOffer,
|
|
2145
|
+
import_fixparser.MDEntryType.ShortSaleMinPrice,
|
|
2146
|
+
import_fixparser.MDEntryType.PreviousClosingPrice,
|
|
2147
|
+
import_fixparser.MDEntryType.ThresholdLimitPriceBanding,
|
|
2148
|
+
import_fixparser.MDEntryType.DailyFinancingValue,
|
|
2149
|
+
import_fixparser.MDEntryType.AccruedFinancingValue,
|
|
2150
|
+
import_fixparser.MDEntryType.TWAP
|
|
2151
|
+
];
|
|
2152
|
+
const messageFields = [
|
|
2153
|
+
new import_fixparser.Field(import_fixparser.Fields.MsgType, import_fixparser.Messages.MarketDataRequest),
|
|
2154
|
+
new import_fixparser.Field(import_fixparser.Fields.SenderCompID, parser.sender),
|
|
2155
|
+
new import_fixparser.Field(import_fixparser.Fields.MsgSeqNum, parser.getNextTargetMsgSeqNum()),
|
|
2156
|
+
new import_fixparser.Field(import_fixparser.Fields.TargetCompID, parser.target),
|
|
2157
|
+
new import_fixparser.Field(import_fixparser.Fields.SendingTime, parser.getTimestamp()),
|
|
2158
|
+
new import_fixparser.Field(import_fixparser.Fields.MDReqID, args.mdReqID),
|
|
2159
|
+
new import_fixparser.Field(import_fixparser.Fields.SubscriptionRequestType, args.subscriptionRequestType),
|
|
2160
|
+
new import_fixparser.Field(import_fixparser.Fields.MarketDepth, 0),
|
|
2161
|
+
new import_fixparser.Field(import_fixparser.Fields.MDUpdateType, args.mdUpdateType)
|
|
2162
|
+
];
|
|
2163
|
+
messageFields.push(new import_fixparser.Field(import_fixparser.Fields.NoRelatedSym, args.symbols.length));
|
|
2164
|
+
args.symbols.forEach((symbol) => {
|
|
2165
|
+
messageFields.push(new import_fixparser.Field(import_fixparser.Fields.Symbol, symbol));
|
|
2166
|
+
});
|
|
2167
|
+
messageFields.push(new import_fixparser.Field(import_fixparser.Fields.NoMDEntryTypes, entryTypes.length));
|
|
2168
|
+
entryTypes.forEach((entryType) => {
|
|
2169
|
+
messageFields.push(new import_fixparser.Field(import_fixparser.Fields.MDEntryType, entryType));
|
|
2170
|
+
});
|
|
2171
|
+
const mdr = parser.createMessage(...messageFields);
|
|
2172
|
+
if (!parser.connected) {
|
|
2173
|
+
parser.logger.log({
|
|
2174
|
+
level: "error",
|
|
2175
|
+
message: "Not connected. Cannot send market data request."
|
|
2176
|
+
});
|
|
2177
|
+
return {
|
|
2178
|
+
content: [
|
|
2179
|
+
{
|
|
2180
|
+
type: "text",
|
|
2181
|
+
text: "Error: Not connected. Ignoring message.",
|
|
2182
|
+
uri: "marketDataRequest"
|
|
2183
|
+
}
|
|
2184
|
+
],
|
|
2185
|
+
isError: true
|
|
2186
|
+
};
|
|
2187
|
+
}
|
|
2188
|
+
parser.logger.log({
|
|
2189
|
+
level: "info",
|
|
2190
|
+
message: `Sending market data request message: ${JSON.stringify(mdr?.toFIXJSON())}`
|
|
2191
|
+
});
|
|
2192
|
+
parser.send(mdr);
|
|
2193
|
+
const fixData = await response;
|
|
2194
|
+
parser.logger.log({
|
|
2195
|
+
level: "info",
|
|
2196
|
+
message: `Received market data response for request ID: ${args.mdReqID}`
|
|
2197
|
+
});
|
|
2198
|
+
return {
|
|
2199
|
+
content: [
|
|
2200
|
+
{
|
|
2201
|
+
type: "text",
|
|
2202
|
+
text: `Market data for ${args.symbols.join(", ")}: ${JSON.stringify(fixData.toFIXJSON())}`,
|
|
2203
|
+
uri: "marketDataRequest"
|
|
2204
|
+
}
|
|
2205
|
+
]
|
|
2206
|
+
};
|
|
2207
|
+
} catch (error) {
|
|
2208
|
+
return {
|
|
2209
|
+
content: [
|
|
2210
|
+
{
|
|
2211
|
+
type: "text",
|
|
2212
|
+
text: `Error: ${error instanceof Error ? error.message : "Failed to request market data"}`,
|
|
2213
|
+
uri: "marketDataRequest"
|
|
2214
|
+
}
|
|
2215
|
+
],
|
|
2216
|
+
isError: true
|
|
2217
|
+
};
|
|
2218
|
+
}
|
|
2219
|
+
};
|
|
2220
|
+
};
|
|
2221
|
+
var aggregateMarketData = (priceHistory, maxPoints = 490) => {
|
|
2222
|
+
if (priceHistory.length <= maxPoints) {
|
|
2223
|
+
return priceHistory;
|
|
2224
|
+
}
|
|
2225
|
+
const result = [];
|
|
2226
|
+
const step = priceHistory.length / maxPoints;
|
|
2227
|
+
result.push(priceHistory[0]);
|
|
2228
|
+
for (let i = 1; i < maxPoints - 1; i++) {
|
|
2229
|
+
const startIndex = Math.floor(i * step);
|
|
2230
|
+
const endIndex = Math.floor((i + 1) * step);
|
|
2231
|
+
const segment = priceHistory.slice(startIndex, endIndex);
|
|
2232
|
+
if (segment.length === 0) continue;
|
|
2233
|
+
const aggregatedPoint = {
|
|
2234
|
+
timestamp: segment[0].timestamp,
|
|
2235
|
+
// Use timestamp of first point in segment
|
|
2236
|
+
bid: segment.reduce((sum2, p) => sum2 + p.bid, 0) / segment.length,
|
|
2237
|
+
offer: segment.reduce((sum2, p) => sum2 + p.offer, 0) / segment.length,
|
|
2238
|
+
spread: segment.reduce((sum2, p) => sum2 + p.spread, 0) / segment.length,
|
|
2239
|
+
volume: segment.reduce((sum2, p) => sum2 + p.volume, 0) / segment.length,
|
|
2240
|
+
trade: segment.reduce((sum2, p) => sum2 + p.trade, 0) / segment.length,
|
|
2241
|
+
indexValue: segment.reduce((sum2, p) => sum2 + p.indexValue, 0) / segment.length,
|
|
2242
|
+
openingPrice: segment.reduce((sum2, p) => sum2 + p.openingPrice, 0) / segment.length,
|
|
2243
|
+
closingPrice: segment.reduce((sum2, p) => sum2 + p.closingPrice, 0) / segment.length,
|
|
2244
|
+
settlementPrice: segment.reduce((sum2, p) => sum2 + p.settlementPrice, 0) / segment.length,
|
|
2245
|
+
tradingSessionHighPrice: segment.reduce((sum2, p) => sum2 + p.tradingSessionHighPrice, 0) / segment.length,
|
|
2246
|
+
tradingSessionLowPrice: segment.reduce((sum2, p) => sum2 + p.tradingSessionLowPrice, 0) / segment.length,
|
|
2247
|
+
vwap: segment.reduce((sum2, p) => sum2 + p.vwap, 0) / segment.length,
|
|
2248
|
+
imbalance: segment.reduce((sum2, p) => sum2 + p.imbalance, 0) / segment.length,
|
|
2249
|
+
openInterest: segment.reduce((sum2, p) => sum2 + p.openInterest, 0) / segment.length,
|
|
2250
|
+
compositeUnderlyingPrice: segment.reduce((sum2, p) => sum2 + p.compositeUnderlyingPrice, 0) / segment.length,
|
|
2251
|
+
simulatedSellPrice: segment.reduce((sum2, p) => sum2 + p.simulatedSellPrice, 0) / segment.length,
|
|
2252
|
+
simulatedBuyPrice: segment.reduce((sum2, p) => sum2 + p.simulatedBuyPrice, 0) / segment.length,
|
|
2253
|
+
marginRate: segment.reduce((sum2, p) => sum2 + p.marginRate, 0) / segment.length,
|
|
2254
|
+
midPrice: segment.reduce((sum2, p) => sum2 + p.midPrice, 0) / segment.length,
|
|
2255
|
+
emptyBook: segment.reduce((sum2, p) => sum2 + p.emptyBook, 0) / segment.length,
|
|
2256
|
+
settleHighPrice: segment.reduce((sum2, p) => sum2 + p.settleHighPrice, 0) / segment.length,
|
|
2257
|
+
settleLowPrice: segment.reduce((sum2, p) => sum2 + p.settleLowPrice, 0) / segment.length,
|
|
2258
|
+
priorSettlePrice: segment.reduce((sum2, p) => sum2 + p.priorSettlePrice, 0) / segment.length,
|
|
2259
|
+
sessionHighBid: segment.reduce((sum2, p) => sum2 + p.sessionHighBid, 0) / segment.length,
|
|
2260
|
+
sessionLowOffer: segment.reduce((sum2, p) => sum2 + p.sessionLowOffer, 0) / segment.length,
|
|
2261
|
+
earlyPrices: segment.reduce((sum2, p) => sum2 + p.earlyPrices, 0) / segment.length,
|
|
2262
|
+
auctionClearingPrice: segment.reduce((sum2, p) => sum2 + p.auctionClearingPrice, 0) / segment.length,
|
|
2263
|
+
swapValueFactor: segment.reduce((sum2, p) => sum2 + p.swapValueFactor, 0) / segment.length,
|
|
2264
|
+
dailyValueAdjustmentForLongPositions: segment.reduce((sum2, p) => sum2 + p.dailyValueAdjustmentForLongPositions, 0) / segment.length,
|
|
2265
|
+
cumulativeValueAdjustmentForLongPositions: segment.reduce((sum2, p) => sum2 + p.cumulativeValueAdjustmentForLongPositions, 0) / segment.length,
|
|
2266
|
+
dailyValueAdjustmentForShortPositions: segment.reduce((sum2, p) => sum2 + p.dailyValueAdjustmentForShortPositions, 0) / segment.length,
|
|
2267
|
+
cumulativeValueAdjustmentForShortPositions: segment.reduce((sum2, p) => sum2 + p.cumulativeValueAdjustmentForShortPositions, 0) / segment.length,
|
|
2268
|
+
fixingPrice: segment.reduce((sum2, p) => sum2 + p.fixingPrice, 0) / segment.length,
|
|
2269
|
+
cashRate: segment.reduce((sum2, p) => sum2 + p.cashRate, 0) / segment.length,
|
|
2270
|
+
recoveryRate: segment.reduce((sum2, p) => sum2 + p.recoveryRate, 0) / segment.length,
|
|
2271
|
+
recoveryRateForLong: segment.reduce((sum2, p) => sum2 + p.recoveryRateForLong, 0) / segment.length,
|
|
2272
|
+
recoveryRateForShort: segment.reduce((sum2, p) => sum2 + p.recoveryRateForShort, 0) / segment.length,
|
|
2273
|
+
marketBid: segment.reduce((sum2, p) => sum2 + p.marketBid, 0) / segment.length,
|
|
2274
|
+
marketOffer: segment.reduce((sum2, p) => sum2 + p.marketOffer, 0) / segment.length,
|
|
2275
|
+
shortSaleMinPrice: segment.reduce((sum2, p) => sum2 + p.shortSaleMinPrice, 0) / segment.length,
|
|
2276
|
+
previousClosingPrice: segment.reduce((sum2, p) => sum2 + p.previousClosingPrice, 0) / segment.length,
|
|
2277
|
+
thresholdLimitPriceBanding: segment.reduce((sum2, p) => sum2 + p.thresholdLimitPriceBanding, 0) / segment.length,
|
|
2278
|
+
dailyFinancingValue: segment.reduce((sum2, p) => sum2 + p.dailyFinancingValue, 0) / segment.length,
|
|
2279
|
+
accruedFinancingValue: segment.reduce((sum2, p) => sum2 + p.accruedFinancingValue, 0) / segment.length,
|
|
2280
|
+
twap: segment.reduce((sum2, p) => sum2 + p.twap, 0) / segment.length
|
|
2281
|
+
};
|
|
2282
|
+
result.push(aggregatedPoint);
|
|
2283
|
+
}
|
|
2284
|
+
result.push(priceHistory[priceHistory.length - 1]);
|
|
2285
|
+
return result;
|
|
2286
|
+
};
|
|
2287
|
+
var createGetStockGraphHandler = (marketDataPrices) => {
|
|
2288
|
+
return async (args) => {
|
|
2289
|
+
try {
|
|
2290
|
+
const symbol = args.symbol;
|
|
2291
|
+
const priceHistory = marketDataPrices.get(symbol) || [];
|
|
2292
|
+
if (priceHistory.length === 0) {
|
|
2293
|
+
return {
|
|
2294
|
+
content: [
|
|
2295
|
+
{
|
|
2296
|
+
type: "text",
|
|
2297
|
+
text: `No price data available for ${symbol}`,
|
|
2298
|
+
uri: "getStockGraph"
|
|
2299
|
+
}
|
|
2300
|
+
]
|
|
2301
|
+
};
|
|
2302
|
+
}
|
|
2303
|
+
const aggregatedData = aggregateMarketData(priceHistory, 500);
|
|
2304
|
+
const chart = new import_quickchart_js.default();
|
|
2305
|
+
chart.setWidth(1200);
|
|
2306
|
+
chart.setHeight(600);
|
|
2307
|
+
chart.setBackgroundColor("transparent");
|
|
2308
|
+
const labels = aggregatedData.map((point) => new Date(point.timestamp).toLocaleTimeString());
|
|
2309
|
+
const bidData = aggregatedData.map((point) => point.bid);
|
|
2310
|
+
const offerData = aggregatedData.map((point) => point.offer);
|
|
2311
|
+
const spreadData = aggregatedData.map((point) => point.spread);
|
|
2312
|
+
const volumeData = aggregatedData.map((point) => point.volume);
|
|
2313
|
+
const tradeData = aggregatedData.map((point) => point.trade);
|
|
2314
|
+
const vwapData = aggregatedData.map((point) => point.vwap);
|
|
2315
|
+
const twapData = aggregatedData.map((point) => point.twap);
|
|
2316
|
+
const maxVolume = Math.max(...volumeData.filter((v) => v > 0));
|
|
2317
|
+
const maxPrice = Math.max(...bidData, ...offerData, ...tradeData, ...vwapData, ...twapData);
|
|
2318
|
+
const normalizedVolumeData = volumeData.map((v) => v / maxVolume * maxPrice * 0.3);
|
|
2319
|
+
const config = {
|
|
2320
|
+
type: "line",
|
|
2321
|
+
data: {
|
|
2322
|
+
labels,
|
|
2323
|
+
datasets: [
|
|
2324
|
+
{
|
|
2325
|
+
label: "Bid",
|
|
2326
|
+
data: bidData,
|
|
2327
|
+
borderColor: "#28a745",
|
|
2328
|
+
backgroundColor: "rgba(40, 167, 69, 0.1)",
|
|
2329
|
+
fill: false,
|
|
2330
|
+
tension: 0.4
|
|
2331
|
+
},
|
|
2332
|
+
{
|
|
2333
|
+
label: "Offer",
|
|
2334
|
+
data: offerData,
|
|
2335
|
+
borderColor: "#dc3545",
|
|
2336
|
+
backgroundColor: "rgba(220, 53, 69, 0.1)",
|
|
2337
|
+
fill: false,
|
|
2338
|
+
tension: 0.4
|
|
2339
|
+
},
|
|
2340
|
+
{
|
|
2341
|
+
label: "Spread",
|
|
2342
|
+
data: spreadData,
|
|
2343
|
+
borderColor: "#6c757d",
|
|
2344
|
+
backgroundColor: "rgba(108, 117, 125, 0.1)",
|
|
2345
|
+
fill: false,
|
|
2346
|
+
tension: 0.4
|
|
2347
|
+
},
|
|
2348
|
+
{
|
|
2349
|
+
label: "Trade",
|
|
2350
|
+
data: tradeData,
|
|
2351
|
+
borderColor: "#ffc107",
|
|
2352
|
+
backgroundColor: "rgba(255, 193, 7, 0.1)",
|
|
2353
|
+
fill: false,
|
|
2354
|
+
tension: 0.4
|
|
2355
|
+
},
|
|
2356
|
+
{
|
|
2357
|
+
label: "VWAP",
|
|
2358
|
+
data: vwapData,
|
|
2359
|
+
borderColor: "#17a2b8",
|
|
2360
|
+
backgroundColor: "rgba(23, 162, 184, 0.1)",
|
|
2361
|
+
fill: false,
|
|
2362
|
+
tension: 0.4
|
|
2363
|
+
},
|
|
2364
|
+
{
|
|
2365
|
+
label: "TWAP",
|
|
2366
|
+
data: twapData,
|
|
2367
|
+
borderColor: "#6610f2",
|
|
2368
|
+
backgroundColor: "rgba(102, 16, 242, 0.1)",
|
|
2369
|
+
fill: false,
|
|
2370
|
+
tension: 0.4
|
|
2371
|
+
},
|
|
2372
|
+
{
|
|
2373
|
+
label: "Volume (Normalized)",
|
|
2374
|
+
data: normalizedVolumeData,
|
|
2375
|
+
borderColor: "#007bff",
|
|
2376
|
+
backgroundColor: "rgba(0, 123, 255, 0.1)",
|
|
2377
|
+
fill: true,
|
|
2378
|
+
tension: 0.4
|
|
2379
|
+
}
|
|
2380
|
+
]
|
|
2381
|
+
},
|
|
2382
|
+
options: {
|
|
2383
|
+
responsive: true,
|
|
2384
|
+
plugins: {
|
|
2385
|
+
title: {
|
|
2386
|
+
display: true,
|
|
2387
|
+
text: `${symbol} Market Data (Volume normalized to 30% of max price)`
|
|
2388
|
+
}
|
|
2389
|
+
},
|
|
2390
|
+
scales: {
|
|
2391
|
+
y: {
|
|
2392
|
+
beginAtZero: false,
|
|
2393
|
+
title: {
|
|
2394
|
+
display: true,
|
|
2395
|
+
text: "Price / Normalized Volume"
|
|
2396
|
+
}
|
|
2397
|
+
}
|
|
2398
|
+
}
|
|
2399
|
+
}
|
|
2400
|
+
};
|
|
2401
|
+
chart.setConfig(config);
|
|
2402
|
+
const imageBuffer = await chart.toBinary();
|
|
2403
|
+
const base64 = imageBuffer.toString("base64");
|
|
2404
|
+
return {
|
|
2405
|
+
content: [
|
|
2406
|
+
{
|
|
2407
|
+
type: "resource",
|
|
2408
|
+
resource: {
|
|
2409
|
+
uri: "resource://graph",
|
|
2410
|
+
mimeType: "image/png",
|
|
2411
|
+
blob: base64
|
|
2412
|
+
}
|
|
2413
|
+
}
|
|
2414
|
+
]
|
|
2415
|
+
};
|
|
2416
|
+
} catch (error) {
|
|
2417
|
+
return {
|
|
2418
|
+
content: [
|
|
2419
|
+
{
|
|
2420
|
+
type: "text",
|
|
2421
|
+
text: `Error: ${error instanceof Error ? error.message : "Failed to generate graph"}`,
|
|
2422
|
+
uri: "getStockGraph"
|
|
2423
|
+
}
|
|
2424
|
+
],
|
|
2425
|
+
isError: true
|
|
2426
|
+
};
|
|
36
2427
|
}
|
|
37
|
-
}
|
|
38
|
-
required: ["fixString"]
|
|
2428
|
+
};
|
|
39
2429
|
};
|
|
40
|
-
var
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
2430
|
+
var createGetStockPriceHistoryHandler = (marketDataPrices) => {
|
|
2431
|
+
return async (args) => {
|
|
2432
|
+
try {
|
|
2433
|
+
const symbol = args.symbol;
|
|
2434
|
+
const priceHistory = marketDataPrices.get(symbol) || [];
|
|
2435
|
+
if (priceHistory.length === 0) {
|
|
2436
|
+
return {
|
|
2437
|
+
content: [
|
|
2438
|
+
{
|
|
2439
|
+
type: "text",
|
|
2440
|
+
text: `No price data available for ${symbol}`,
|
|
2441
|
+
uri: "getStockPriceHistory"
|
|
2442
|
+
}
|
|
2443
|
+
]
|
|
2444
|
+
};
|
|
2445
|
+
}
|
|
2446
|
+
const aggregatedData = aggregateMarketData(priceHistory, 500);
|
|
2447
|
+
return {
|
|
2448
|
+
content: [
|
|
2449
|
+
{
|
|
2450
|
+
type: "text",
|
|
2451
|
+
text: JSON.stringify(
|
|
2452
|
+
{
|
|
2453
|
+
symbol,
|
|
2454
|
+
count: aggregatedData.length,
|
|
2455
|
+
originalCount: priceHistory.length,
|
|
2456
|
+
data: aggregatedData.map((point) => ({
|
|
2457
|
+
timestamp: new Date(point.timestamp).toISOString(),
|
|
2458
|
+
bid: point.bid,
|
|
2459
|
+
offer: point.offer,
|
|
2460
|
+
spread: point.spread,
|
|
2461
|
+
volume: point.volume,
|
|
2462
|
+
trade: point.trade,
|
|
2463
|
+
indexValue: point.indexValue,
|
|
2464
|
+
openingPrice: point.openingPrice,
|
|
2465
|
+
closingPrice: point.closingPrice,
|
|
2466
|
+
settlementPrice: point.settlementPrice,
|
|
2467
|
+
tradingSessionHighPrice: point.tradingSessionHighPrice,
|
|
2468
|
+
tradingSessionLowPrice: point.tradingSessionLowPrice,
|
|
2469
|
+
vwap: point.vwap,
|
|
2470
|
+
imbalance: point.imbalance,
|
|
2471
|
+
openInterest: point.openInterest,
|
|
2472
|
+
compositeUnderlyingPrice: point.compositeUnderlyingPrice,
|
|
2473
|
+
simulatedSellPrice: point.simulatedSellPrice,
|
|
2474
|
+
simulatedBuyPrice: point.simulatedBuyPrice,
|
|
2475
|
+
marginRate: point.marginRate,
|
|
2476
|
+
midPrice: point.midPrice,
|
|
2477
|
+
emptyBook: point.emptyBook,
|
|
2478
|
+
settleHighPrice: point.settleHighPrice,
|
|
2479
|
+
settleLowPrice: point.settleLowPrice,
|
|
2480
|
+
priorSettlePrice: point.priorSettlePrice,
|
|
2481
|
+
sessionHighBid: point.sessionHighBid,
|
|
2482
|
+
sessionLowOffer: point.sessionLowOffer,
|
|
2483
|
+
earlyPrices: point.earlyPrices,
|
|
2484
|
+
auctionClearingPrice: point.auctionClearingPrice,
|
|
2485
|
+
swapValueFactor: point.swapValueFactor,
|
|
2486
|
+
dailyValueAdjustmentForLongPositions: point.dailyValueAdjustmentForLongPositions,
|
|
2487
|
+
cumulativeValueAdjustmentForLongPositions: point.cumulativeValueAdjustmentForLongPositions,
|
|
2488
|
+
dailyValueAdjustmentForShortPositions: point.dailyValueAdjustmentForShortPositions,
|
|
2489
|
+
cumulativeValueAdjustmentForShortPositions: point.cumulativeValueAdjustmentForShortPositions,
|
|
2490
|
+
fixingPrice: point.fixingPrice,
|
|
2491
|
+
cashRate: point.cashRate,
|
|
2492
|
+
recoveryRate: point.recoveryRate,
|
|
2493
|
+
recoveryRateForLong: point.recoveryRateForLong,
|
|
2494
|
+
recoveryRateForShort: point.recoveryRateForShort,
|
|
2495
|
+
marketBid: point.marketBid,
|
|
2496
|
+
marketOffer: point.marketOffer,
|
|
2497
|
+
shortSaleMinPrice: point.shortSaleMinPrice,
|
|
2498
|
+
previousClosingPrice: point.previousClosingPrice,
|
|
2499
|
+
thresholdLimitPriceBanding: point.thresholdLimitPriceBanding,
|
|
2500
|
+
dailyFinancingValue: point.dailyFinancingValue,
|
|
2501
|
+
accruedFinancingValue: point.accruedFinancingValue,
|
|
2502
|
+
twap: point.twap
|
|
2503
|
+
}))
|
|
2504
|
+
},
|
|
2505
|
+
null,
|
|
2506
|
+
2
|
|
2507
|
+
),
|
|
2508
|
+
uri: "getStockPriceHistory"
|
|
2509
|
+
}
|
|
2510
|
+
]
|
|
2511
|
+
};
|
|
2512
|
+
} catch (error) {
|
|
2513
|
+
return {
|
|
2514
|
+
content: [
|
|
2515
|
+
{
|
|
2516
|
+
type: "text",
|
|
2517
|
+
text: `Error: ${error instanceof Error ? error.message : "Failed to get price history"}`,
|
|
2518
|
+
uri: "getStockPriceHistory"
|
|
2519
|
+
}
|
|
2520
|
+
],
|
|
2521
|
+
isError: true
|
|
2522
|
+
};
|
|
46
2523
|
}
|
|
47
|
-
}
|
|
48
|
-
required: ["fixString"]
|
|
2524
|
+
};
|
|
49
2525
|
};
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
2526
|
+
|
|
2527
|
+
// src/tools/order.ts
|
|
2528
|
+
var import_fixparser2 = require("fixparser");
|
|
2529
|
+
var ordTypeNames = {
|
|
2530
|
+
"1": "Market",
|
|
2531
|
+
"2": "Limit",
|
|
2532
|
+
"3": "Stop",
|
|
2533
|
+
"4": "StopLimit",
|
|
2534
|
+
"5": "MarketOnClose",
|
|
2535
|
+
"6": "WithOrWithout",
|
|
2536
|
+
"7": "LimitOrBetter",
|
|
2537
|
+
"8": "LimitWithOrWithout",
|
|
2538
|
+
"9": "OnBasis",
|
|
2539
|
+
A: "OnClose",
|
|
2540
|
+
B: "LimitOnClose",
|
|
2541
|
+
C: "ForexMarket",
|
|
2542
|
+
D: "PreviouslyQuoted",
|
|
2543
|
+
E: "PreviouslyIndicated",
|
|
2544
|
+
F: "ForexLimit",
|
|
2545
|
+
G: "ForexSwap",
|
|
2546
|
+
H: "ForexPreviouslyQuoted",
|
|
2547
|
+
I: "Funari",
|
|
2548
|
+
J: "MarketIfTouched",
|
|
2549
|
+
K: "MarketWithLeftOverAsLimit",
|
|
2550
|
+
L: "PreviousFundValuationPoint",
|
|
2551
|
+
M: "NextFundValuationPoint",
|
|
2552
|
+
P: "Pegged",
|
|
2553
|
+
Q: "CounterOrderSelection",
|
|
2554
|
+
R: "StopOnBidOrOffer",
|
|
2555
|
+
S: "StopLimitOnBidOrOffer"
|
|
2556
|
+
};
|
|
2557
|
+
var sideNames = {
|
|
2558
|
+
"1": "Buy",
|
|
2559
|
+
"2": "Sell",
|
|
2560
|
+
"3": "BuyMinus",
|
|
2561
|
+
"4": "SellPlus",
|
|
2562
|
+
"5": "SellShort",
|
|
2563
|
+
"6": "SellShortExempt",
|
|
2564
|
+
"7": "Undisclosed",
|
|
2565
|
+
"8": "Cross",
|
|
2566
|
+
"9": "CrossShort",
|
|
2567
|
+
A: "CrossShortExempt",
|
|
2568
|
+
B: "AsDefined",
|
|
2569
|
+
C: "Opposite",
|
|
2570
|
+
D: "Subscribe",
|
|
2571
|
+
E: "Redeem",
|
|
2572
|
+
F: "Lend",
|
|
2573
|
+
G: "Borrow",
|
|
2574
|
+
H: "SellUndisclosed"
|
|
2575
|
+
};
|
|
2576
|
+
var timeInForceNames = {
|
|
2577
|
+
"0": "Day",
|
|
2578
|
+
"1": "GoodTillCancel",
|
|
2579
|
+
"2": "AtTheOpening",
|
|
2580
|
+
"3": "ImmediateOrCancel",
|
|
2581
|
+
"4": "FillOrKill",
|
|
2582
|
+
"5": "GoodTillCrossing",
|
|
2583
|
+
"6": "GoodTillDate",
|
|
2584
|
+
"7": "AtTheClose",
|
|
2585
|
+
"8": "GoodThroughCrossing",
|
|
2586
|
+
"9": "AtCrossing",
|
|
2587
|
+
A: "GoodForTime",
|
|
2588
|
+
B: "GoodForAuction",
|
|
2589
|
+
C: "GoodForMonth"
|
|
2590
|
+
};
|
|
2591
|
+
var handlInstNames = {
|
|
2592
|
+
"1": "AutomatedExecutionNoIntervention",
|
|
2593
|
+
"2": "AutomatedExecutionInterventionOK",
|
|
2594
|
+
"3": "ManualOrder"
|
|
2595
|
+
};
|
|
2596
|
+
var createVerifyOrderHandler = (parser, verifiedOrders) => {
|
|
2597
|
+
return async (args) => {
|
|
2598
|
+
void parser;
|
|
2599
|
+
try {
|
|
2600
|
+
verifiedOrders.set(args.clOrdID, {
|
|
2601
|
+
clOrdID: args.clOrdID,
|
|
2602
|
+
handlInst: args.handlInst,
|
|
2603
|
+
quantity: Number.parseFloat(String(args.quantity)),
|
|
2604
|
+
price: Number.parseFloat(String(args.price)),
|
|
2605
|
+
ordType: args.ordType,
|
|
2606
|
+
side: args.side,
|
|
2607
|
+
symbol: args.symbol,
|
|
2608
|
+
timeInForce: args.timeInForce
|
|
2609
|
+
});
|
|
2610
|
+
return {
|
|
2611
|
+
content: [
|
|
2612
|
+
{
|
|
2613
|
+
type: "text",
|
|
2614
|
+
text: `VERIFICATION: All parameters valid. Ready to proceed with order execution.
|
|
2615
|
+
|
|
2616
|
+
Parameters verified:
|
|
2617
|
+
- ClOrdID: ${args.clOrdID}
|
|
2618
|
+
- HandlInst: ${args.handlInst} (${handlInstNames[args.handlInst]})
|
|
2619
|
+
- Quantity: ${args.quantity}
|
|
2620
|
+
- Price: ${args.price}
|
|
2621
|
+
- OrdType: ${args.ordType} (${ordTypeNames[args.ordType]})
|
|
2622
|
+
- Side: ${args.side} (${sideNames[args.side]})
|
|
2623
|
+
- Symbol: ${args.symbol}
|
|
2624
|
+
- TimeInForce: ${args.timeInForce} (${timeInForceNames[args.timeInForce]})
|
|
2625
|
+
|
|
2626
|
+
To execute this order, call the executeOrder tool with these exact same parameters. Important: The user has to explicitly confirm before executeOrder is called!`,
|
|
2627
|
+
uri: "verifyOrder"
|
|
2628
|
+
}
|
|
2629
|
+
]
|
|
2630
|
+
};
|
|
2631
|
+
} catch (error) {
|
|
2632
|
+
return {
|
|
2633
|
+
content: [
|
|
2634
|
+
{
|
|
2635
|
+
type: "text",
|
|
2636
|
+
text: `Error: ${error instanceof Error ? error.message : "Failed to verify order parameters"}`,
|
|
2637
|
+
uri: "verifyOrder"
|
|
2638
|
+
}
|
|
2639
|
+
],
|
|
2640
|
+
isError: true
|
|
2641
|
+
};
|
|
115
2642
|
}
|
|
116
|
-
}
|
|
117
|
-
required: ["clOrdID", "handlInst", "quantity", "price", "ordType", "side", "symbol", "timeInForce"]
|
|
2643
|
+
};
|
|
118
2644
|
};
|
|
119
|
-
var
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
2645
|
+
var createExecuteOrderHandler = (parser, verifiedOrders, pendingRequests) => {
|
|
2646
|
+
return async (args) => {
|
|
2647
|
+
try {
|
|
2648
|
+
const verifiedOrder = verifiedOrders.get(args.clOrdID);
|
|
2649
|
+
if (!verifiedOrder) {
|
|
2650
|
+
return {
|
|
2651
|
+
content: [
|
|
2652
|
+
{
|
|
2653
|
+
type: "text",
|
|
2654
|
+
text: `Error: Order ${args.clOrdID} has not been verified. Please call verifyOrder first.`,
|
|
2655
|
+
uri: "executeOrder"
|
|
2656
|
+
}
|
|
2657
|
+
],
|
|
2658
|
+
isError: true
|
|
2659
|
+
};
|
|
2660
|
+
}
|
|
2661
|
+
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) {
|
|
2662
|
+
return {
|
|
2663
|
+
content: [
|
|
2664
|
+
{
|
|
2665
|
+
type: "text",
|
|
2666
|
+
text: "Error: Order parameters do not match the verified order. Please use the exact same parameters that were verified.",
|
|
2667
|
+
uri: "executeOrder"
|
|
2668
|
+
}
|
|
2669
|
+
],
|
|
2670
|
+
isError: true
|
|
2671
|
+
};
|
|
2672
|
+
}
|
|
2673
|
+
const response = new Promise((resolve) => {
|
|
2674
|
+
pendingRequests.set(args.clOrdID, resolve);
|
|
2675
|
+
});
|
|
2676
|
+
const order = parser.createMessage(
|
|
2677
|
+
new import_fixparser2.Field(import_fixparser2.Fields.MsgType, import_fixparser2.Messages.NewOrderSingle),
|
|
2678
|
+
new import_fixparser2.Field(import_fixparser2.Fields.MsgSeqNum, parser.getNextTargetMsgSeqNum()),
|
|
2679
|
+
new import_fixparser2.Field(import_fixparser2.Fields.SenderCompID, parser.sender),
|
|
2680
|
+
new import_fixparser2.Field(import_fixparser2.Fields.TargetCompID, parser.target),
|
|
2681
|
+
new import_fixparser2.Field(import_fixparser2.Fields.SendingTime, parser.getTimestamp()),
|
|
2682
|
+
new import_fixparser2.Field(import_fixparser2.Fields.ClOrdID, args.clOrdID),
|
|
2683
|
+
new import_fixparser2.Field(import_fixparser2.Fields.Side, args.side),
|
|
2684
|
+
new import_fixparser2.Field(import_fixparser2.Fields.Symbol, args.symbol),
|
|
2685
|
+
new import_fixparser2.Field(import_fixparser2.Fields.OrderQty, Number.parseFloat(String(args.quantity))),
|
|
2686
|
+
new import_fixparser2.Field(import_fixparser2.Fields.Price, Number.parseFloat(String(args.price))),
|
|
2687
|
+
new import_fixparser2.Field(import_fixparser2.Fields.OrdType, args.ordType),
|
|
2688
|
+
new import_fixparser2.Field(import_fixparser2.Fields.HandlInst, args.handlInst),
|
|
2689
|
+
new import_fixparser2.Field(import_fixparser2.Fields.TimeInForce, args.timeInForce),
|
|
2690
|
+
new import_fixparser2.Field(import_fixparser2.Fields.TransactTime, parser.getTimestamp())
|
|
2691
|
+
);
|
|
2692
|
+
if (!parser.connected) {
|
|
2693
|
+
return {
|
|
2694
|
+
content: [
|
|
2695
|
+
{
|
|
2696
|
+
type: "text",
|
|
2697
|
+
text: "Error: Not connected. Ignoring message.",
|
|
2698
|
+
uri: "executeOrder"
|
|
2699
|
+
}
|
|
2700
|
+
],
|
|
2701
|
+
isError: true
|
|
2702
|
+
};
|
|
2703
|
+
}
|
|
2704
|
+
parser.send(order);
|
|
2705
|
+
const fixData = await response;
|
|
2706
|
+
verifiedOrders.delete(args.clOrdID);
|
|
2707
|
+
return {
|
|
2708
|
+
content: [
|
|
2709
|
+
{
|
|
2710
|
+
type: "text",
|
|
2711
|
+
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())}`,
|
|
2712
|
+
uri: "executeOrder"
|
|
2713
|
+
}
|
|
2714
|
+
]
|
|
2715
|
+
};
|
|
2716
|
+
} catch (error) {
|
|
2717
|
+
return {
|
|
2718
|
+
content: [
|
|
2719
|
+
{
|
|
2720
|
+
type: "text",
|
|
2721
|
+
text: `Error: ${error instanceof Error ? error.message : "Failed to execute order"}`,
|
|
2722
|
+
uri: "executeOrder"
|
|
2723
|
+
}
|
|
2724
|
+
],
|
|
2725
|
+
isError: true
|
|
2726
|
+
};
|
|
189
2727
|
}
|
|
190
|
-
}
|
|
191
|
-
required: ["symbol", "mdReqID"]
|
|
2728
|
+
};
|
|
192
2729
|
};
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
2730
|
+
|
|
2731
|
+
// src/tools/parse.ts
|
|
2732
|
+
var createParseHandler = (parser) => {
|
|
2733
|
+
return async (args) => {
|
|
2734
|
+
try {
|
|
2735
|
+
const parsedMessage = parser.parse(args.fixString);
|
|
2736
|
+
if (!parsedMessage || parsedMessage.length === 0) {
|
|
2737
|
+
return {
|
|
2738
|
+
content: [
|
|
2739
|
+
{
|
|
2740
|
+
type: "text",
|
|
2741
|
+
text: "Error: Failed to parse FIX string",
|
|
2742
|
+
uri: "parse"
|
|
2743
|
+
}
|
|
2744
|
+
],
|
|
2745
|
+
isError: true
|
|
2746
|
+
};
|
|
2747
|
+
}
|
|
2748
|
+
return {
|
|
2749
|
+
content: [
|
|
2750
|
+
{
|
|
2751
|
+
type: "text",
|
|
2752
|
+
text: `${parsedMessage[0].description}
|
|
2753
|
+
${parsedMessage[0].messageTypeDescription}`,
|
|
2754
|
+
uri: "parse"
|
|
2755
|
+
}
|
|
2756
|
+
]
|
|
2757
|
+
};
|
|
2758
|
+
} catch (error) {
|
|
2759
|
+
return {
|
|
2760
|
+
content: [
|
|
2761
|
+
{
|
|
2762
|
+
type: "text",
|
|
2763
|
+
text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`,
|
|
2764
|
+
uri: "parse"
|
|
2765
|
+
}
|
|
2766
|
+
],
|
|
2767
|
+
isError: true
|
|
2768
|
+
};
|
|
2769
|
+
}
|
|
2770
|
+
};
|
|
2771
|
+
};
|
|
2772
|
+
|
|
2773
|
+
// src/tools/parseToJSON.ts
|
|
2774
|
+
var createParseToJSONHandler = (parser) => {
|
|
2775
|
+
return async (args) => {
|
|
2776
|
+
try {
|
|
2777
|
+
const parsedMessage = parser.parse(args.fixString);
|
|
2778
|
+
if (!parsedMessage || parsedMessage.length === 0) {
|
|
2779
|
+
return {
|
|
2780
|
+
content: [
|
|
2781
|
+
{
|
|
2782
|
+
type: "text",
|
|
2783
|
+
text: "Error: Failed to parse FIX string",
|
|
2784
|
+
uri: "parseToJSON"
|
|
2785
|
+
}
|
|
2786
|
+
],
|
|
2787
|
+
isError: true
|
|
2788
|
+
};
|
|
2789
|
+
}
|
|
2790
|
+
return {
|
|
2791
|
+
content: [
|
|
2792
|
+
{
|
|
2793
|
+
type: "text",
|
|
2794
|
+
text: `${parsedMessage[0].toFIXJSON()}`,
|
|
2795
|
+
uri: "parseToJSON"
|
|
2796
|
+
}
|
|
2797
|
+
]
|
|
2798
|
+
};
|
|
2799
|
+
} catch (error) {
|
|
2800
|
+
return {
|
|
2801
|
+
content: [
|
|
2802
|
+
{
|
|
2803
|
+
type: "text",
|
|
2804
|
+
text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`,
|
|
2805
|
+
uri: "parseToJSON"
|
|
2806
|
+
}
|
|
2807
|
+
],
|
|
2808
|
+
isError: true
|
|
2809
|
+
};
|
|
2810
|
+
}
|
|
2811
|
+
};
|
|
2812
|
+
};
|
|
2813
|
+
|
|
2814
|
+
// src/tools/index.ts
|
|
2815
|
+
var createToolHandlers = (parser, verifiedOrders, pendingRequests, marketDataPrices) => ({
|
|
2816
|
+
parse: createParseHandler(parser),
|
|
2817
|
+
parseToJSON: createParseToJSONHandler(parser),
|
|
2818
|
+
verifyOrder: createVerifyOrderHandler(parser, verifiedOrders),
|
|
2819
|
+
executeOrder: createExecuteOrderHandler(parser, verifiedOrders, pendingRequests),
|
|
2820
|
+
marketDataRequest: createMarketDataRequestHandler(parser, pendingRequests),
|
|
2821
|
+
getStockGraph: createGetStockGraphHandler(marketDataPrices),
|
|
2822
|
+
getStockPriceHistory: createGetStockPriceHistoryHandler(marketDataPrices),
|
|
2823
|
+
technicalAnalysis: createTechnicalAnalysisHandler(marketDataPrices)
|
|
2824
|
+
});
|
|
2825
|
+
|
|
2826
|
+
// src/utils/messageHandler.ts
|
|
2827
|
+
var import_fixparser3 = require("fixparser");
|
|
2828
|
+
function getEnumValue(enumObj, name) {
|
|
2829
|
+
return enumObj[name] || name;
|
|
2830
|
+
}
|
|
2831
|
+
function handleMessage(message, parser, pendingRequests, marketDataPrices, maxPriceHistory, onPriceUpdate) {
|
|
2832
|
+
void parser;
|
|
2833
|
+
const msgType = message.messageType;
|
|
2834
|
+
if (msgType === import_fixparser3.Messages.MarketDataSnapshotFullRefresh || msgType === import_fixparser3.Messages.MarketDataIncrementalRefresh) {
|
|
2835
|
+
const symbol = message.getField(import_fixparser3.Fields.Symbol)?.value;
|
|
2836
|
+
const fixJson = message.toFIXJSON();
|
|
2837
|
+
const entries = fixJson.Body?.NoMDEntries || [];
|
|
2838
|
+
const data = {
|
|
2839
|
+
timestamp: Date.now(),
|
|
2840
|
+
bid: 0,
|
|
2841
|
+
offer: 0,
|
|
2842
|
+
spread: 0,
|
|
2843
|
+
volume: 0,
|
|
2844
|
+
trade: 0,
|
|
2845
|
+
indexValue: 0,
|
|
2846
|
+
openingPrice: 0,
|
|
2847
|
+
closingPrice: 0,
|
|
2848
|
+
settlementPrice: 0,
|
|
2849
|
+
tradingSessionHighPrice: 0,
|
|
2850
|
+
tradingSessionLowPrice: 0,
|
|
2851
|
+
vwap: 0,
|
|
2852
|
+
imbalance: 0,
|
|
2853
|
+
openInterest: 0,
|
|
2854
|
+
compositeUnderlyingPrice: 0,
|
|
2855
|
+
simulatedSellPrice: 0,
|
|
2856
|
+
simulatedBuyPrice: 0,
|
|
2857
|
+
marginRate: 0,
|
|
2858
|
+
midPrice: 0,
|
|
2859
|
+
emptyBook: 0,
|
|
2860
|
+
settleHighPrice: 0,
|
|
2861
|
+
settleLowPrice: 0,
|
|
2862
|
+
priorSettlePrice: 0,
|
|
2863
|
+
sessionHighBid: 0,
|
|
2864
|
+
sessionLowOffer: 0,
|
|
2865
|
+
earlyPrices: 0,
|
|
2866
|
+
auctionClearingPrice: 0,
|
|
2867
|
+
swapValueFactor: 0,
|
|
2868
|
+
dailyValueAdjustmentForLongPositions: 0,
|
|
2869
|
+
cumulativeValueAdjustmentForLongPositions: 0,
|
|
2870
|
+
dailyValueAdjustmentForShortPositions: 0,
|
|
2871
|
+
cumulativeValueAdjustmentForShortPositions: 0,
|
|
2872
|
+
fixingPrice: 0,
|
|
2873
|
+
cashRate: 0,
|
|
2874
|
+
recoveryRate: 0,
|
|
2875
|
+
recoveryRateForLong: 0,
|
|
2876
|
+
recoveryRateForShort: 0,
|
|
2877
|
+
marketBid: 0,
|
|
2878
|
+
marketOffer: 0,
|
|
2879
|
+
shortSaleMinPrice: 0,
|
|
2880
|
+
previousClosingPrice: 0,
|
|
2881
|
+
thresholdLimitPriceBanding: 0,
|
|
2882
|
+
dailyFinancingValue: 0,
|
|
2883
|
+
accruedFinancingValue: 0,
|
|
2884
|
+
twap: 0
|
|
2885
|
+
};
|
|
2886
|
+
for (const entry of entries) {
|
|
2887
|
+
const entryType = entry.MDEntryType;
|
|
2888
|
+
const price = entry.MDEntryPx ? Number.parseFloat(entry.MDEntryPx) : 0;
|
|
2889
|
+
const size = entry.MDEntrySize ? Number.parseFloat(entry.MDEntrySize) : 0;
|
|
2890
|
+
const enumValue = getEnumValue(import_fixparser3.MDEntryType, entryType);
|
|
2891
|
+
switch (enumValue) {
|
|
2892
|
+
case import_fixparser3.MDEntryType.Bid:
|
|
2893
|
+
data.bid = price;
|
|
2894
|
+
break;
|
|
2895
|
+
case import_fixparser3.MDEntryType.Offer:
|
|
2896
|
+
data.offer = price;
|
|
2897
|
+
break;
|
|
2898
|
+
case import_fixparser3.MDEntryType.Trade:
|
|
2899
|
+
data.trade = price;
|
|
2900
|
+
break;
|
|
2901
|
+
case import_fixparser3.MDEntryType.IndexValue:
|
|
2902
|
+
data.indexValue = price;
|
|
2903
|
+
break;
|
|
2904
|
+
case import_fixparser3.MDEntryType.OpeningPrice:
|
|
2905
|
+
data.openingPrice = price;
|
|
2906
|
+
break;
|
|
2907
|
+
case import_fixparser3.MDEntryType.ClosingPrice:
|
|
2908
|
+
data.closingPrice = price;
|
|
2909
|
+
break;
|
|
2910
|
+
case import_fixparser3.MDEntryType.SettlementPrice:
|
|
2911
|
+
data.settlementPrice = price;
|
|
2912
|
+
break;
|
|
2913
|
+
case import_fixparser3.MDEntryType.TradingSessionHighPrice:
|
|
2914
|
+
data.tradingSessionHighPrice = price;
|
|
2915
|
+
break;
|
|
2916
|
+
case import_fixparser3.MDEntryType.TradingSessionLowPrice:
|
|
2917
|
+
data.tradingSessionLowPrice = price;
|
|
2918
|
+
break;
|
|
2919
|
+
case import_fixparser3.MDEntryType.VWAP:
|
|
2920
|
+
data.vwap = price;
|
|
2921
|
+
break;
|
|
2922
|
+
case import_fixparser3.MDEntryType.Imbalance:
|
|
2923
|
+
data.imbalance = size;
|
|
2924
|
+
break;
|
|
2925
|
+
case import_fixparser3.MDEntryType.TradeVolume:
|
|
2926
|
+
data.volume = size;
|
|
2927
|
+
break;
|
|
2928
|
+
case import_fixparser3.MDEntryType.OpenInterest:
|
|
2929
|
+
data.openInterest = size;
|
|
2930
|
+
break;
|
|
2931
|
+
case import_fixparser3.MDEntryType.CompositeUnderlyingPrice:
|
|
2932
|
+
data.compositeUnderlyingPrice = price;
|
|
2933
|
+
break;
|
|
2934
|
+
case import_fixparser3.MDEntryType.SimulatedSellPrice:
|
|
2935
|
+
data.simulatedSellPrice = price;
|
|
2936
|
+
break;
|
|
2937
|
+
case import_fixparser3.MDEntryType.SimulatedBuyPrice:
|
|
2938
|
+
data.simulatedBuyPrice = price;
|
|
2939
|
+
break;
|
|
2940
|
+
case import_fixparser3.MDEntryType.MarginRate:
|
|
2941
|
+
data.marginRate = price;
|
|
2942
|
+
break;
|
|
2943
|
+
case import_fixparser3.MDEntryType.MidPrice:
|
|
2944
|
+
data.midPrice = price;
|
|
2945
|
+
break;
|
|
2946
|
+
case import_fixparser3.MDEntryType.EmptyBook:
|
|
2947
|
+
data.emptyBook = 1;
|
|
2948
|
+
break;
|
|
2949
|
+
case import_fixparser3.MDEntryType.SettleHighPrice:
|
|
2950
|
+
data.settleHighPrice = price;
|
|
2951
|
+
break;
|
|
2952
|
+
case import_fixparser3.MDEntryType.SettleLowPrice:
|
|
2953
|
+
data.settleLowPrice = price;
|
|
2954
|
+
break;
|
|
2955
|
+
case import_fixparser3.MDEntryType.PriorSettlePrice:
|
|
2956
|
+
data.priorSettlePrice = price;
|
|
2957
|
+
break;
|
|
2958
|
+
case import_fixparser3.MDEntryType.SessionHighBid:
|
|
2959
|
+
data.sessionHighBid = price;
|
|
2960
|
+
break;
|
|
2961
|
+
case import_fixparser3.MDEntryType.SessionLowOffer:
|
|
2962
|
+
data.sessionLowOffer = price;
|
|
2963
|
+
break;
|
|
2964
|
+
case import_fixparser3.MDEntryType.EarlyPrices:
|
|
2965
|
+
data.earlyPrices = price;
|
|
2966
|
+
break;
|
|
2967
|
+
case import_fixparser3.MDEntryType.AuctionClearingPrice:
|
|
2968
|
+
data.auctionClearingPrice = price;
|
|
2969
|
+
break;
|
|
2970
|
+
case import_fixparser3.MDEntryType.SwapValueFactor:
|
|
2971
|
+
data.swapValueFactor = price;
|
|
2972
|
+
break;
|
|
2973
|
+
case import_fixparser3.MDEntryType.DailyValueAdjustmentForLongPositions:
|
|
2974
|
+
data.dailyValueAdjustmentForLongPositions = price;
|
|
2975
|
+
break;
|
|
2976
|
+
case import_fixparser3.MDEntryType.CumulativeValueAdjustmentForLongPositions:
|
|
2977
|
+
data.cumulativeValueAdjustmentForLongPositions = price;
|
|
2978
|
+
break;
|
|
2979
|
+
case import_fixparser3.MDEntryType.DailyValueAdjustmentForShortPositions:
|
|
2980
|
+
data.dailyValueAdjustmentForShortPositions = price;
|
|
2981
|
+
break;
|
|
2982
|
+
case import_fixparser3.MDEntryType.CumulativeValueAdjustmentForShortPositions:
|
|
2983
|
+
data.cumulativeValueAdjustmentForShortPositions = price;
|
|
2984
|
+
break;
|
|
2985
|
+
case import_fixparser3.MDEntryType.FixingPrice:
|
|
2986
|
+
data.fixingPrice = price;
|
|
2987
|
+
break;
|
|
2988
|
+
case import_fixparser3.MDEntryType.CashRate:
|
|
2989
|
+
data.cashRate = price;
|
|
2990
|
+
break;
|
|
2991
|
+
case import_fixparser3.MDEntryType.RecoveryRate:
|
|
2992
|
+
data.recoveryRate = price;
|
|
2993
|
+
break;
|
|
2994
|
+
case import_fixparser3.MDEntryType.RecoveryRateForLong:
|
|
2995
|
+
data.recoveryRateForLong = price;
|
|
2996
|
+
break;
|
|
2997
|
+
case import_fixparser3.MDEntryType.RecoveryRateForShort:
|
|
2998
|
+
data.recoveryRateForShort = price;
|
|
2999
|
+
break;
|
|
3000
|
+
case import_fixparser3.MDEntryType.MarketBid:
|
|
3001
|
+
data.marketBid = price;
|
|
3002
|
+
break;
|
|
3003
|
+
case import_fixparser3.MDEntryType.MarketOffer:
|
|
3004
|
+
data.marketOffer = price;
|
|
3005
|
+
break;
|
|
3006
|
+
case import_fixparser3.MDEntryType.ShortSaleMinPrice:
|
|
3007
|
+
data.shortSaleMinPrice = price;
|
|
3008
|
+
break;
|
|
3009
|
+
case import_fixparser3.MDEntryType.PreviousClosingPrice:
|
|
3010
|
+
data.previousClosingPrice = price;
|
|
3011
|
+
break;
|
|
3012
|
+
case import_fixparser3.MDEntryType.ThresholdLimitPriceBanding:
|
|
3013
|
+
data.thresholdLimitPriceBanding = price;
|
|
3014
|
+
break;
|
|
3015
|
+
case import_fixparser3.MDEntryType.DailyFinancingValue:
|
|
3016
|
+
data.dailyFinancingValue = price;
|
|
3017
|
+
break;
|
|
3018
|
+
case import_fixparser3.MDEntryType.AccruedFinancingValue:
|
|
3019
|
+
data.accruedFinancingValue = price;
|
|
3020
|
+
break;
|
|
3021
|
+
case import_fixparser3.MDEntryType.TWAP:
|
|
3022
|
+
data.twap = price;
|
|
3023
|
+
break;
|
|
3024
|
+
}
|
|
3025
|
+
}
|
|
3026
|
+
data.spread = data.offer - data.bid;
|
|
3027
|
+
if (!marketDataPrices.has(symbol)) {
|
|
3028
|
+
marketDataPrices.set(symbol, []);
|
|
3029
|
+
}
|
|
3030
|
+
const prices = marketDataPrices.get(symbol);
|
|
3031
|
+
prices.push(data);
|
|
3032
|
+
if (prices.length > maxPriceHistory) {
|
|
3033
|
+
prices.splice(0, prices.length - maxPriceHistory);
|
|
3034
|
+
}
|
|
3035
|
+
onPriceUpdate?.(symbol, data);
|
|
3036
|
+
const mdReqID = message.getField(import_fixparser3.Fields.MDReqID)?.value;
|
|
3037
|
+
if (mdReqID) {
|
|
3038
|
+
const callback = pendingRequests.get(mdReqID);
|
|
3039
|
+
if (callback) {
|
|
3040
|
+
callback(message);
|
|
3041
|
+
pendingRequests.delete(mdReqID);
|
|
3042
|
+
}
|
|
3043
|
+
}
|
|
3044
|
+
} else if (msgType === import_fixparser3.Messages.ExecutionReport) {
|
|
3045
|
+
const reqId = message.getField(import_fixparser3.Fields.ClOrdID)?.value;
|
|
3046
|
+
const callback = pendingRequests.get(reqId);
|
|
3047
|
+
if (callback) {
|
|
3048
|
+
callback(message);
|
|
3049
|
+
pendingRequests.delete(reqId);
|
|
3050
|
+
}
|
|
3051
|
+
}
|
|
3052
|
+
}
|
|
3053
|
+
|
|
3054
|
+
// src/MCPLocal.ts
|
|
3055
|
+
var MCPLocal = class extends MCPBase {
|
|
3056
|
+
/**
|
|
3057
|
+
* Map to store verified orders before execution
|
|
3058
|
+
* @private
|
|
3059
|
+
*/
|
|
3060
|
+
verifiedOrders = /* @__PURE__ */ new Map();
|
|
3061
|
+
/**
|
|
3062
|
+
* Map to store pending requests and their callbacks
|
|
3063
|
+
* @private
|
|
3064
|
+
*/
|
|
3065
|
+
pendingRequests = /* @__PURE__ */ new Map();
|
|
3066
|
+
/**
|
|
3067
|
+
* Map to store market data prices for each symbol
|
|
3068
|
+
* @private
|
|
3069
|
+
*/
|
|
3070
|
+
marketDataPrices = /* @__PURE__ */ new Map();
|
|
3071
|
+
/**
|
|
3072
|
+
* Maximum number of price history entries to keep per symbol
|
|
3073
|
+
* @private
|
|
3074
|
+
*/
|
|
3075
|
+
MAX_PRICE_HISTORY = 1e5;
|
|
196
3076
|
server = new import_server.Server(
|
|
197
3077
|
{
|
|
198
3078
|
name: "fixparser",
|
|
@@ -200,43 +3080,27 @@ var MCPLocal = class {
|
|
|
200
3080
|
},
|
|
201
3081
|
{
|
|
202
3082
|
capabilities: {
|
|
203
|
-
tools:
|
|
204
|
-
|
|
205
|
-
|
|
3083
|
+
tools: Object.entries(toolSchemas).reduce(
|
|
3084
|
+
(acc, [name, { description, schema }]) => {
|
|
3085
|
+
acc[name] = {
|
|
3086
|
+
description,
|
|
3087
|
+
parameters: schema
|
|
3088
|
+
};
|
|
3089
|
+
return acc;
|
|
3090
|
+
},
|
|
3091
|
+
{}
|
|
3092
|
+
)
|
|
206
3093
|
}
|
|
207
3094
|
}
|
|
208
3095
|
);
|
|
209
3096
|
transport = new import_stdio.StdioServerTransport();
|
|
210
|
-
onReady = void 0;
|
|
211
|
-
pendingRequests = /* @__PURE__ */ new Map();
|
|
212
|
-
verifiedOrders = /* @__PURE__ */ new Map();
|
|
213
3097
|
constructor({ logger, onReady }) {
|
|
214
|
-
|
|
3098
|
+
super({ logger, onReady });
|
|
215
3099
|
}
|
|
216
3100
|
async register(parser) {
|
|
217
3101
|
this.parser = parser;
|
|
218
3102
|
this.parser.addOnMessageCallback((message) => {
|
|
219
|
-
|
|
220
|
-
if (msgType === import_fixparser.Messages.MarketDataSnapshotFullRefresh || msgType === import_fixparser.Messages.ExecutionReport || msgType === import_fixparser.Messages.Reject) {
|
|
221
|
-
let id;
|
|
222
|
-
if (msgType === import_fixparser.Messages.MarketDataSnapshotFullRefresh) {
|
|
223
|
-
const mdReqID = message.getField(import_fixparser.Fields.MDReqID);
|
|
224
|
-
if (mdReqID) id = String(mdReqID.value);
|
|
225
|
-
} else if (msgType === import_fixparser.Messages.ExecutionReport) {
|
|
226
|
-
const clOrdID = message.getField(import_fixparser.Fields.ClOrdID);
|
|
227
|
-
if (clOrdID) id = String(clOrdID.value);
|
|
228
|
-
} else if (msgType === import_fixparser.Messages.Reject) {
|
|
229
|
-
const refSeqNum = message.getField(import_fixparser.Fields.RefSeqNum);
|
|
230
|
-
if (refSeqNum) id = String(refSeqNum.value);
|
|
231
|
-
}
|
|
232
|
-
if (id) {
|
|
233
|
-
const callback = this.pendingRequests.get(id);
|
|
234
|
-
if (callback) {
|
|
235
|
-
callback(message);
|
|
236
|
-
this.pendingRequests.delete(id);
|
|
237
|
-
}
|
|
238
|
-
}
|
|
239
|
-
}
|
|
3103
|
+
handleMessage(message, this.parser, this.pendingRequests, this.marketDataPrices, this.MAX_PRICE_HISTORY);
|
|
240
3104
|
});
|
|
241
3105
|
this.addWorkflows();
|
|
242
3106
|
await this.server.connect(this.transport);
|
|
@@ -251,606 +3115,54 @@ var MCPLocal = class {
|
|
|
251
3115
|
if (!this.server) {
|
|
252
3116
|
return;
|
|
253
3117
|
}
|
|
254
|
-
|
|
255
|
-
const result = {};
|
|
256
|
-
for (const [key, propSchema] of Object.entries(schema.properties || {})) {
|
|
257
|
-
const prop = propSchema;
|
|
258
|
-
const value = args?.[key];
|
|
259
|
-
if (prop.required && (value === void 0 || value === null)) {
|
|
260
|
-
throw new Error(`Required property '${key}' is missing`);
|
|
261
|
-
}
|
|
262
|
-
if (value !== void 0) {
|
|
263
|
-
result[key] = value;
|
|
264
|
-
} else if (prop.default !== void 0) {
|
|
265
|
-
result[key] = prop.default;
|
|
266
|
-
}
|
|
267
|
-
}
|
|
268
|
-
return result;
|
|
269
|
-
};
|
|
270
|
-
this.server.setRequestHandler(import_types.ListResourcesRequestSchema, async () => {
|
|
271
|
-
return {
|
|
272
|
-
resources: []
|
|
273
|
-
};
|
|
274
|
-
});
|
|
275
|
-
this.server.setRequestHandler(import_types.ListToolsRequestSchema, async () => {
|
|
276
|
-
return {
|
|
277
|
-
tools: [
|
|
278
|
-
{
|
|
279
|
-
name: "parse",
|
|
280
|
-
description: "Parses a FIX message and describes it in plain language",
|
|
281
|
-
inputSchema: parseInputSchema
|
|
282
|
-
},
|
|
283
|
-
{
|
|
284
|
-
name: "parseToJSON",
|
|
285
|
-
description: "Parses a FIX message into JSON",
|
|
286
|
-
inputSchema: parseToJSONInputSchema
|
|
287
|
-
},
|
|
288
|
-
{
|
|
289
|
-
name: "verifyOrder",
|
|
290
|
-
description: "Verifies all parameters for a New Order Single. This is the first step - verification only, no order is sent.",
|
|
291
|
-
inputSchema: orderSchema
|
|
292
|
-
},
|
|
293
|
-
{
|
|
294
|
-
name: "executeOrder",
|
|
295
|
-
description: "Executes a New Order Single after verification. This is the second step - only call after successful verification.",
|
|
296
|
-
inputSchema: orderSchema
|
|
297
|
-
},
|
|
298
|
-
{
|
|
299
|
-
name: "marketDataRequest",
|
|
300
|
-
description: "Sends a request for Market Data with the given symbol. IMPORTANT: All parameters must be explicitly provided by the user - no assumptions will be made.",
|
|
301
|
-
inputSchema: marketDataRequestInputSchema
|
|
302
|
-
}
|
|
303
|
-
]
|
|
304
|
-
};
|
|
305
|
-
});
|
|
306
|
-
this.server.setRequestHandler(import_types.CallToolRequestSchema, async (request) => {
|
|
307
|
-
const { name, arguments: args } = request.params;
|
|
308
|
-
switch (name) {
|
|
309
|
-
case "parse": {
|
|
310
|
-
try {
|
|
311
|
-
const { fixString } = validateArgs(args, parseInputSchema);
|
|
312
|
-
const parsedMessage = this.parser?.parse(fixString);
|
|
313
|
-
if (!parsedMessage || parsedMessage.length === 0) {
|
|
314
|
-
return {
|
|
315
|
-
isError: true,
|
|
316
|
-
content: [{ type: "text", text: "Error: Failed to parse FIX string" }]
|
|
317
|
-
};
|
|
318
|
-
}
|
|
319
|
-
return {
|
|
320
|
-
content: [
|
|
321
|
-
{
|
|
322
|
-
type: "text",
|
|
323
|
-
text: `${parsedMessage[0].description}
|
|
324
|
-
${parsedMessage[0].messageTypeDescription}`
|
|
325
|
-
}
|
|
326
|
-
]
|
|
327
|
-
};
|
|
328
|
-
} catch (error) {
|
|
329
|
-
return {
|
|
330
|
-
isError: true,
|
|
331
|
-
content: [
|
|
332
|
-
{
|
|
333
|
-
type: "text",
|
|
334
|
-
text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`
|
|
335
|
-
}
|
|
336
|
-
]
|
|
337
|
-
};
|
|
338
|
-
}
|
|
339
|
-
}
|
|
340
|
-
case "parseToJSON": {
|
|
341
|
-
try {
|
|
342
|
-
const { fixString } = validateArgs(args, parseToJSONInputSchema);
|
|
343
|
-
const parsedMessage = this.parser?.parse(fixString);
|
|
344
|
-
if (!parsedMessage || parsedMessage.length === 0) {
|
|
345
|
-
return {
|
|
346
|
-
isError: true,
|
|
347
|
-
content: [{ type: "text", text: "Error: Failed to parse FIX string" }]
|
|
348
|
-
};
|
|
349
|
-
}
|
|
350
|
-
return {
|
|
351
|
-
content: [
|
|
352
|
-
{
|
|
353
|
-
type: "text",
|
|
354
|
-
text: `${parsedMessage[0].toFIXJSON()}`
|
|
355
|
-
}
|
|
356
|
-
]
|
|
357
|
-
};
|
|
358
|
-
} catch (error) {
|
|
359
|
-
return {
|
|
360
|
-
isError: true,
|
|
361
|
-
content: [
|
|
362
|
-
{
|
|
363
|
-
type: "text",
|
|
364
|
-
text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`
|
|
365
|
-
}
|
|
366
|
-
]
|
|
367
|
-
};
|
|
368
|
-
}
|
|
369
|
-
}
|
|
370
|
-
case "verifyOrder": {
|
|
371
|
-
try {
|
|
372
|
-
const { clOrdID, handlInst, quantity, price, ordType, side, symbol, timeInForce } = validateArgs(args, orderSchema);
|
|
373
|
-
this.verifiedOrders.set(clOrdID, {
|
|
374
|
-
clOrdID,
|
|
375
|
-
handlInst,
|
|
376
|
-
quantity,
|
|
377
|
-
price,
|
|
378
|
-
ordType,
|
|
379
|
-
side,
|
|
380
|
-
symbol,
|
|
381
|
-
timeInForce
|
|
382
|
-
});
|
|
383
|
-
return {
|
|
384
|
-
content: [
|
|
385
|
-
{
|
|
386
|
-
type: "text",
|
|
387
|
-
text: `VERIFICATION: All parameters valid. Ready to proceed with order execution.
|
|
388
|
-
|
|
389
|
-
Parameters verified:
|
|
390
|
-
- ClOrdID: ${clOrdID}
|
|
391
|
-
- HandlInst: ${handlInst}
|
|
392
|
-
- Quantity: ${quantity}
|
|
393
|
-
- Price: ${price}
|
|
394
|
-
- OrdType: ${ordType}
|
|
395
|
-
- Side: ${side}
|
|
396
|
-
- Symbol: ${symbol}
|
|
397
|
-
- TimeInForce: ${timeInForce}
|
|
398
|
-
|
|
399
|
-
To execute this order, call the executeOrder tool with these exact same parameters.`
|
|
400
|
-
}
|
|
401
|
-
]
|
|
402
|
-
};
|
|
403
|
-
} catch (error) {
|
|
404
|
-
return {
|
|
405
|
-
isError: true,
|
|
406
|
-
content: [
|
|
407
|
-
{
|
|
408
|
-
type: "text",
|
|
409
|
-
text: `Error: ${error instanceof Error ? error.message : "Failed to verify order parameters"}`
|
|
410
|
-
}
|
|
411
|
-
]
|
|
412
|
-
};
|
|
413
|
-
}
|
|
414
|
-
}
|
|
415
|
-
case "executeOrder": {
|
|
416
|
-
try {
|
|
417
|
-
const { clOrdID, handlInst, quantity, price, ordType, side, symbol, timeInForce } = validateArgs(args, orderSchema);
|
|
418
|
-
const verifiedOrder = this.verifiedOrders.get(clOrdID);
|
|
419
|
-
if (!verifiedOrder) {
|
|
420
|
-
return {
|
|
421
|
-
isError: true,
|
|
422
|
-
content: [
|
|
423
|
-
{
|
|
424
|
-
type: "text",
|
|
425
|
-
text: `Error: Order ${clOrdID} has not been verified. Please call verifyOrder first.`
|
|
426
|
-
}
|
|
427
|
-
]
|
|
428
|
-
};
|
|
429
|
-
}
|
|
430
|
-
if (verifiedOrder.handlInst !== handlInst || verifiedOrder.quantity !== quantity || verifiedOrder.price !== price || verifiedOrder.ordType !== ordType || verifiedOrder.side !== side || verifiedOrder.symbol !== symbol || verifiedOrder.timeInForce !== timeInForce) {
|
|
431
|
-
return {
|
|
432
|
-
isError: true,
|
|
433
|
-
content: [
|
|
434
|
-
{
|
|
435
|
-
type: "text",
|
|
436
|
-
text: "Error: Order parameters do not match the verified order. Please use the exact same parameters that were verified."
|
|
437
|
-
}
|
|
438
|
-
]
|
|
439
|
-
};
|
|
440
|
-
}
|
|
441
|
-
const response = new Promise((resolve) => {
|
|
442
|
-
this.pendingRequests.set(clOrdID, resolve);
|
|
443
|
-
});
|
|
444
|
-
const order = this.parser?.createMessage(
|
|
445
|
-
new import_fixparser.Field(import_fixparser.Fields.MsgType, import_fixparser.Messages.NewOrderSingle),
|
|
446
|
-
new import_fixparser.Field(import_fixparser.Fields.MsgSeqNum, this.parser?.getNextTargetMsgSeqNum()),
|
|
447
|
-
new import_fixparser.Field(import_fixparser.Fields.SenderCompID, this.parser?.sender),
|
|
448
|
-
new import_fixparser.Field(import_fixparser.Fields.TargetCompID, this.parser?.target),
|
|
449
|
-
new import_fixparser.Field(import_fixparser.Fields.SendingTime, this.parser?.getTimestamp()),
|
|
450
|
-
new import_fixparser.Field(import_fixparser.Fields.ClOrdID, clOrdID),
|
|
451
|
-
new import_fixparser.Field(import_fixparser.Fields.Side, side),
|
|
452
|
-
new import_fixparser.Field(import_fixparser.Fields.Symbol, symbol),
|
|
453
|
-
new import_fixparser.Field(import_fixparser.Fields.OrderQty, quantity),
|
|
454
|
-
new import_fixparser.Field(import_fixparser.Fields.Price, price),
|
|
455
|
-
new import_fixparser.Field(import_fixparser.Fields.OrdType, ordType),
|
|
456
|
-
new import_fixparser.Field(import_fixparser.Fields.HandlInst, handlInst),
|
|
457
|
-
new import_fixparser.Field(import_fixparser.Fields.TimeInForce, timeInForce),
|
|
458
|
-
new import_fixparser.Field(import_fixparser.Fields.TransactTime, this.parser?.getTimestamp())
|
|
459
|
-
);
|
|
460
|
-
if (!this.parser?.connected) {
|
|
461
|
-
return {
|
|
462
|
-
isError: true,
|
|
463
|
-
content: [
|
|
464
|
-
{
|
|
465
|
-
type: "text",
|
|
466
|
-
text: "Error: Not connected. Ignoring message."
|
|
467
|
-
}
|
|
468
|
-
]
|
|
469
|
-
};
|
|
470
|
-
}
|
|
471
|
-
this.parser?.send(order);
|
|
472
|
-
const fixData = await response;
|
|
473
|
-
this.verifiedOrders.delete(clOrdID);
|
|
474
|
-
return {
|
|
475
|
-
content: [
|
|
476
|
-
{
|
|
477
|
-
type: "text",
|
|
478
|
-
text: fixData.messageType === import_fixparser.Messages.Reject ? `Reject message for order ${clOrdID}: ${JSON.stringify(fixData.toFIXJSON())}` : `Execution Report for order ${clOrdID}: ${JSON.stringify(fixData.toFIXJSON())}`
|
|
479
|
-
}
|
|
480
|
-
]
|
|
481
|
-
};
|
|
482
|
-
} catch (error) {
|
|
483
|
-
return {
|
|
484
|
-
isError: true,
|
|
485
|
-
content: [
|
|
486
|
-
{
|
|
487
|
-
type: "text",
|
|
488
|
-
text: `Error: ${error instanceof Error ? error.message : "Failed to execute order"}`
|
|
489
|
-
}
|
|
490
|
-
]
|
|
491
|
-
};
|
|
492
|
-
}
|
|
493
|
-
}
|
|
494
|
-
case "marketDataRequest": {
|
|
495
|
-
try {
|
|
496
|
-
const { mdUpdateType, symbol, mdReqID, subscriptionRequestType, mdEntryType } = validateArgs(
|
|
497
|
-
args,
|
|
498
|
-
marketDataRequestInputSchema
|
|
499
|
-
);
|
|
500
|
-
const response = new Promise((resolve) => {
|
|
501
|
-
this.pendingRequests.set(mdReqID, resolve);
|
|
502
|
-
});
|
|
503
|
-
const marketDataRequest = this.parser?.createMessage(
|
|
504
|
-
new import_fixparser.Field(import_fixparser.Fields.MsgType, import_fixparser.Messages.MarketDataRequest),
|
|
505
|
-
new import_fixparser.Field(import_fixparser.Fields.SenderCompID, this.parser?.sender),
|
|
506
|
-
new import_fixparser.Field(import_fixparser.Fields.MsgSeqNum, this.parser?.getNextTargetMsgSeqNum()),
|
|
507
|
-
new import_fixparser.Field(import_fixparser.Fields.TargetCompID, this.parser?.target),
|
|
508
|
-
new import_fixparser.Field(import_fixparser.Fields.SendingTime, this.parser?.getTimestamp()),
|
|
509
|
-
new import_fixparser.Field(import_fixparser.Fields.MarketDepth, 0),
|
|
510
|
-
new import_fixparser.Field(import_fixparser.Fields.MDUpdateType, mdUpdateType),
|
|
511
|
-
new import_fixparser.Field(import_fixparser.Fields.NoRelatedSym, 1),
|
|
512
|
-
new import_fixparser.Field(import_fixparser.Fields.Symbol, symbol),
|
|
513
|
-
new import_fixparser.Field(import_fixparser.Fields.MDReqID, mdReqID),
|
|
514
|
-
new import_fixparser.Field(import_fixparser.Fields.SubscriptionRequestType, subscriptionRequestType),
|
|
515
|
-
new import_fixparser.Field(import_fixparser.Fields.NoMDEntryTypes, 1),
|
|
516
|
-
new import_fixparser.Field(import_fixparser.Fields.MDEntryType, mdEntryType)
|
|
517
|
-
);
|
|
518
|
-
if (!this.parser?.connected) {
|
|
519
|
-
return {
|
|
520
|
-
isError: true,
|
|
521
|
-
content: [
|
|
522
|
-
{
|
|
523
|
-
type: "text",
|
|
524
|
-
text: "Error: Not connected. Ignoring message."
|
|
525
|
-
}
|
|
526
|
-
]
|
|
527
|
-
};
|
|
528
|
-
}
|
|
529
|
-
this.parser?.send(marketDataRequest);
|
|
530
|
-
const fixData = await response;
|
|
531
|
-
return {
|
|
532
|
-
content: [
|
|
533
|
-
{
|
|
534
|
-
type: "text",
|
|
535
|
-
text: `Market data for ${symbol}: ${JSON.stringify(fixData.toFIXJSON())}`
|
|
536
|
-
}
|
|
537
|
-
]
|
|
538
|
-
};
|
|
539
|
-
} catch (error) {
|
|
540
|
-
return {
|
|
541
|
-
isError: true,
|
|
542
|
-
content: [
|
|
543
|
-
{
|
|
544
|
-
type: "text",
|
|
545
|
-
text: `Error: ${error instanceof Error ? error.message : "Failed to request market data"}`
|
|
546
|
-
}
|
|
547
|
-
]
|
|
548
|
-
};
|
|
549
|
-
}
|
|
550
|
-
}
|
|
551
|
-
default:
|
|
552
|
-
throw new Error(`Unknown tool: ${name}`);
|
|
553
|
-
}
|
|
554
|
-
});
|
|
555
|
-
this.server.setRequestHandler(import_types.ListPromptsRequestSchema, async () => {
|
|
3118
|
+
this.server.setRequestHandler(import_zod.z.object({ method: import_zod.z.literal("tools/list") }), async () => {
|
|
556
3119
|
return {
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
{
|
|
563
|
-
name: "fixString",
|
|
564
|
-
description: "FIX message string to parse",
|
|
565
|
-
required: true
|
|
566
|
-
}
|
|
567
|
-
]
|
|
568
|
-
},
|
|
569
|
-
{
|
|
570
|
-
name: "parseToJSON",
|
|
571
|
-
description: "Parses a FIX message into JSON",
|
|
572
|
-
arguments: [
|
|
573
|
-
{
|
|
574
|
-
name: "fixString",
|
|
575
|
-
description: "FIX message string to parse",
|
|
576
|
-
required: true
|
|
577
|
-
}
|
|
578
|
-
]
|
|
579
|
-
},
|
|
580
|
-
{
|
|
581
|
-
name: "verifyOrder",
|
|
582
|
-
description: "Verifies all parameters for a New Order Single. This is the first step - verification only, no order is sent.",
|
|
583
|
-
arguments: [
|
|
584
|
-
{
|
|
585
|
-
name: "clOrdID",
|
|
586
|
-
description: "Client Order ID",
|
|
587
|
-
required: true
|
|
588
|
-
},
|
|
589
|
-
{
|
|
590
|
-
name: "handlInst",
|
|
591
|
-
description: "Handling instruction (1=Manual, 2=Automated, 3=AutomatedNoIntervention)",
|
|
592
|
-
required: true
|
|
593
|
-
},
|
|
594
|
-
{
|
|
595
|
-
name: "quantity",
|
|
596
|
-
description: "Order quantity",
|
|
597
|
-
required: true
|
|
598
|
-
},
|
|
599
|
-
{
|
|
600
|
-
name: "price",
|
|
601
|
-
description: "Order price",
|
|
602
|
-
required: true
|
|
603
|
-
},
|
|
604
|
-
{
|
|
605
|
-
name: "ordType",
|
|
606
|
-
description: "Order type (1=Market, 2=Limit, 3=Stop)",
|
|
607
|
-
required: true
|
|
608
|
-
},
|
|
609
|
-
{
|
|
610
|
-
name: "side",
|
|
611
|
-
description: "Order 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)",
|
|
612
|
-
required: true
|
|
613
|
-
},
|
|
614
|
-
{
|
|
615
|
-
name: "symbol",
|
|
616
|
-
description: "Trading symbol",
|
|
617
|
-
required: true
|
|
618
|
-
},
|
|
619
|
-
{
|
|
620
|
-
name: "timeInForce",
|
|
621
|
-
description: "Time in force (0=Day, 1=Good Till Cancel, 2=At Opening, 3=Immediate or Cancel, 4=Fill or Kill, 5=Good Till Crossing, 6=Good Till Date)",
|
|
622
|
-
required: true
|
|
623
|
-
}
|
|
624
|
-
]
|
|
625
|
-
},
|
|
626
|
-
{
|
|
627
|
-
name: "executeOrder",
|
|
628
|
-
description: "Executes a New Order Single after verification. This is the second step - only call after successful verification.",
|
|
629
|
-
arguments: [
|
|
630
|
-
{
|
|
631
|
-
name: "clOrdID",
|
|
632
|
-
description: "Client Order ID",
|
|
633
|
-
required: true
|
|
634
|
-
},
|
|
635
|
-
{
|
|
636
|
-
name: "handlInst",
|
|
637
|
-
description: "Handling instruction (1=Manual, 2=Automated, 3=AutomatedNoIntervention)",
|
|
638
|
-
required: true
|
|
639
|
-
},
|
|
640
|
-
{
|
|
641
|
-
name: "quantity",
|
|
642
|
-
description: "Order quantity",
|
|
643
|
-
required: true
|
|
644
|
-
},
|
|
645
|
-
{
|
|
646
|
-
name: "price",
|
|
647
|
-
description: "Order price",
|
|
648
|
-
required: true
|
|
649
|
-
},
|
|
650
|
-
{
|
|
651
|
-
name: "ordType",
|
|
652
|
-
description: "Order type (1=Market, 2=Limit, 3=Stop)",
|
|
653
|
-
required: true
|
|
654
|
-
},
|
|
655
|
-
{
|
|
656
|
-
name: "side",
|
|
657
|
-
description: "Order 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)",
|
|
658
|
-
required: true
|
|
659
|
-
},
|
|
660
|
-
{
|
|
661
|
-
name: "symbol",
|
|
662
|
-
description: "Trading symbol",
|
|
663
|
-
required: true
|
|
664
|
-
},
|
|
665
|
-
{
|
|
666
|
-
name: "timeInForce",
|
|
667
|
-
description: "Time in force (0=Day, 1=Good Till Cancel, 2=At Opening, 3=Immediate or Cancel, 4=Fill or Kill, 5=Good Till Crossing, 6=Good Till Date)",
|
|
668
|
-
required: true
|
|
669
|
-
}
|
|
670
|
-
]
|
|
671
|
-
},
|
|
672
|
-
{
|
|
673
|
-
name: "marketDataRequest",
|
|
674
|
-
description: "Sends a request for Market Data with the given symbol. IMPORTANT: All parameters must be explicitly provided by the user - no assumptions will be made.",
|
|
675
|
-
arguments: [
|
|
676
|
-
{
|
|
677
|
-
name: "mdUpdateType",
|
|
678
|
-
description: "Market data update type (0=FullRefresh, 1=IncrementalRefresh)",
|
|
679
|
-
required: true
|
|
680
|
-
},
|
|
681
|
-
{
|
|
682
|
-
name: "symbol",
|
|
683
|
-
description: "Trading symbol",
|
|
684
|
-
required: true
|
|
685
|
-
},
|
|
686
|
-
{
|
|
687
|
-
name: "mdReqID",
|
|
688
|
-
description: "Market data request ID",
|
|
689
|
-
required: true
|
|
690
|
-
},
|
|
691
|
-
{
|
|
692
|
-
name: "subscriptionRequestType",
|
|
693
|
-
description: "Subscription request type (0=Snapshot + Updates, 1=Snapshot, 2=Unsubscribe)",
|
|
694
|
-
required: true
|
|
695
|
-
},
|
|
696
|
-
{
|
|
697
|
-
name: "mdEntryType",
|
|
698
|
-
description: "Market data entry type (0=Bid, 1=Offer, 2=Trade, 3=Index Value, 4=Opening Price)",
|
|
699
|
-
required: true
|
|
700
|
-
}
|
|
701
|
-
]
|
|
702
|
-
}
|
|
703
|
-
]
|
|
3120
|
+
tools: Object.entries(toolSchemas).map(([name, { description, schema }]) => ({
|
|
3121
|
+
name,
|
|
3122
|
+
description,
|
|
3123
|
+
inputSchema: schema
|
|
3124
|
+
}))
|
|
704
3125
|
};
|
|
705
3126
|
});
|
|
706
|
-
this.server.setRequestHandler(
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
{
|
|
728
|
-
role: "user",
|
|
729
|
-
content: {
|
|
730
|
-
type: "text",
|
|
731
|
-
text: `Please parse the FIX message to JSON: ${fixString}`
|
|
732
|
-
}
|
|
733
|
-
}
|
|
734
|
-
]
|
|
735
|
-
};
|
|
736
|
-
}
|
|
737
|
-
case "verifyOrder": {
|
|
738
|
-
const { clOrdID, handlInst, quantity, price, ordType, side, symbol, timeInForce } = args || {};
|
|
739
|
-
return {
|
|
740
|
-
messages: [
|
|
741
|
-
{
|
|
742
|
-
role: "user",
|
|
743
|
-
content: {
|
|
744
|
-
type: "text",
|
|
745
|
-
text: [
|
|
746
|
-
"You are an AI assistant that helps users verify FIX New Order Single parameters.",
|
|
747
|
-
"This is STEP 1 of 2 - VERIFICATION ONLY. No order will be sent at this stage.",
|
|
748
|
-
"",
|
|
749
|
-
"You must verify that all required fields are provided and valid:",
|
|
750
|
-
"- ClOrdID (Client Order ID)",
|
|
751
|
-
"- HandlInst (1=Manual, 2=Automated, 3=AutomatedNoIntervention)",
|
|
752
|
-
"- Quantity (Order quantity)",
|
|
753
|
-
"- Price (Order price)",
|
|
754
|
-
"- OrdType (1=Market, 2=Limit, 3=Stop)",
|
|
755
|
-
"- 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)",
|
|
756
|
-
"- Symbol (Trading symbol)",
|
|
757
|
-
"- TimeInForce (0=Day, 1=Good Till Cancel, 2=At Opening, 3=Immediate or Cancel, 4=Fill or Kill, 5=Good Till Crossing, 6=Good Till Date)",
|
|
758
|
-
"",
|
|
759
|
-
"Current parameters to verify:",
|
|
760
|
-
`- ClOrdID: ${clOrdID}`,
|
|
761
|
-
`- HandlInst: ${handlInst}`,
|
|
762
|
-
`- Quantity: ${quantity}`,
|
|
763
|
-
`- Price: ${price}`,
|
|
764
|
-
`- OrdType: ${ordType}`,
|
|
765
|
-
`- Side: ${side}`,
|
|
766
|
-
`- Symbol: ${symbol}`,
|
|
767
|
-
`- TimeInForce: ${timeInForce}`,
|
|
768
|
-
"",
|
|
769
|
-
"If all parameters are valid, respond with:",
|
|
770
|
-
"`VERIFICATION: All parameters valid. Ready to proceed.`",
|
|
771
|
-
"",
|
|
772
|
-
"Otherwise, list the missing or invalid ones.",
|
|
773
|
-
"",
|
|
774
|
-
"IMPORTANT: This is only verification. To actually send the order, the user must call the executeOrder tool with the same parameters."
|
|
775
|
-
].join("\n")
|
|
776
|
-
}
|
|
777
|
-
}
|
|
778
|
-
]
|
|
779
|
-
};
|
|
780
|
-
}
|
|
781
|
-
case "executeOrder": {
|
|
782
|
-
const { clOrdID, handlInst, quantity, price, ordType, side, symbol, timeInForce } = args || {};
|
|
3127
|
+
this.server.setRequestHandler(
|
|
3128
|
+
import_zod.z.object({
|
|
3129
|
+
method: import_zod.z.literal("tools/call"),
|
|
3130
|
+
params: import_zod.z.object({
|
|
3131
|
+
name: import_zod.z.string(),
|
|
3132
|
+
arguments: import_zod.z.any(),
|
|
3133
|
+
_meta: import_zod.z.object({
|
|
3134
|
+
progressToken: import_zod.z.number()
|
|
3135
|
+
}).optional()
|
|
3136
|
+
})
|
|
3137
|
+
}),
|
|
3138
|
+
async (request) => {
|
|
3139
|
+
const { name, arguments: args } = request.params;
|
|
3140
|
+
const toolHandlers = createToolHandlers(
|
|
3141
|
+
this.parser,
|
|
3142
|
+
this.verifiedOrders,
|
|
3143
|
+
this.pendingRequests,
|
|
3144
|
+
this.marketDataPrices
|
|
3145
|
+
);
|
|
3146
|
+
const handler = toolHandlers[name];
|
|
3147
|
+
if (!handler) {
|
|
783
3148
|
return {
|
|
784
|
-
|
|
3149
|
+
content: [
|
|
785
3150
|
{
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
text: [
|
|
790
|
-
"You are an AI assistant that helps users execute FIX New Order Single messages.",
|
|
791
|
-
"This is STEP 2 of 2 - EXECUTION. This will send the order to the market.",
|
|
792
|
-
"",
|
|
793
|
-
"IMPORTANT: This tool should only be called after successful verification of all parameters.",
|
|
794
|
-
"",
|
|
795
|
-
"Parameters to execute:",
|
|
796
|
-
`- ClOrdID: ${clOrdID}`,
|
|
797
|
-
`- HandlInst: ${handlInst}`,
|
|
798
|
-
`- Quantity: ${quantity}`,
|
|
799
|
-
`- Price: ${price}`,
|
|
800
|
-
`- OrdType: ${ordType}`,
|
|
801
|
-
`- Side: ${side}`,
|
|
802
|
-
`- Symbol: ${symbol}`,
|
|
803
|
-
`- TimeInForce: ${timeInForce}`,
|
|
804
|
-
"",
|
|
805
|
-
"IMPORTANT: The response will be either:",
|
|
806
|
-
"1. An Execution Report (MsgType=8) if the order was successfully placed",
|
|
807
|
-
"2. A Reject message (MsgType=3) if the order failed to execute (e.g., due to missing or invalid parameters)"
|
|
808
|
-
].join("\n")
|
|
809
|
-
}
|
|
3151
|
+
type: "text",
|
|
3152
|
+
text: `Tool not found: ${name}`,
|
|
3153
|
+
uri: name
|
|
810
3154
|
}
|
|
811
|
-
]
|
|
812
|
-
|
|
813
|
-
}
|
|
814
|
-
case "marketDataRequest": {
|
|
815
|
-
const { mdUpdateType, symbol, mdReqID, subscriptionRequestType, mdEntryType } = args || {};
|
|
816
|
-
return {
|
|
817
|
-
messages: [
|
|
818
|
-
{
|
|
819
|
-
role: "user",
|
|
820
|
-
content: {
|
|
821
|
-
type: "text",
|
|
822
|
-
text: [
|
|
823
|
-
"You are an AI assistant that helps users create FIX Market Data Request messages.",
|
|
824
|
-
"You must **first verify** that all required fields are provided:",
|
|
825
|
-
"- MDUpdateType (0=FullRefresh, 1=IncrementalRefresh)",
|
|
826
|
-
"- Symbol (Trading symbol)",
|
|
827
|
-
"- MDReqID (Market data request ID)",
|
|
828
|
-
"- SubscriptionRequestType (0=Snapshot + Updates, 1=Snapshot, 2=Unsubscribe)",
|
|
829
|
-
"- MDEntryType (0=Bid, 1=Offer, 2=Trade, 3=Index Value, 4=Opening Price)",
|
|
830
|
-
"",
|
|
831
|
-
"Only when all fields are present and valid, respond with:",
|
|
832
|
-
"`VERIFICATION: All parameters valid. Ready to proceed.`",
|
|
833
|
-
"",
|
|
834
|
-
"Otherwise, list the missing or invalid ones.",
|
|
835
|
-
"",
|
|
836
|
-
"Do not create the FIX message until verification is complete.",
|
|
837
|
-
"",
|
|
838
|
-
"Current parameters:",
|
|
839
|
-
`- MDUpdateType: ${mdUpdateType}`,
|
|
840
|
-
`- Symbol: ${symbol}`,
|
|
841
|
-
`- MDReqID: ${mdReqID}`,
|
|
842
|
-
`- SubscriptionRequestType: ${subscriptionRequestType}`,
|
|
843
|
-
`- MDEntryType: ${mdEntryType}`
|
|
844
|
-
].join("\n")
|
|
845
|
-
}
|
|
846
|
-
}
|
|
847
|
-
]
|
|
3155
|
+
],
|
|
3156
|
+
isError: true
|
|
848
3157
|
};
|
|
849
3158
|
}
|
|
850
|
-
|
|
851
|
-
|
|
3159
|
+
const result = await handler(args);
|
|
3160
|
+
return {
|
|
3161
|
+
content: result.content,
|
|
3162
|
+
isError: result.isError
|
|
3163
|
+
};
|
|
852
3164
|
}
|
|
853
|
-
|
|
3165
|
+
);
|
|
854
3166
|
process.on("SIGINT", async () => {
|
|
855
3167
|
await this.server.close();
|
|
856
3168
|
process.exit(0);
|