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