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