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