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