fixparser-plugin-mcp 9.1.7-148b599b → 9.1.7-1818bee7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/cjs/MCPLocal.js +3090 -778
- package/build/cjs/MCPLocal.js.map +4 -4
- package/build/cjs/MCPRemote.js +3152 -437
- package/build/cjs/MCPRemote.js.map +4 -4
- package/build/cjs/index.js +3449 -0
- package/build/cjs/index.js.map +7 -0
- package/build/esm/MCPLocal.mjs +3081 -785
- package/build/esm/MCPLocal.mjs.map +4 -4
- package/build/esm/MCPRemote.mjs +3143 -447
- package/build/esm/MCPRemote.mjs.map +4 -4
- package/build/esm/index.mjs +3411 -0
- package/build/esm/index.mjs.map +7 -0
- package/build-examples/cjs/example_mcp_local.js +14 -15
- package/build-examples/cjs/example_mcp_local.js.map +4 -4
- package/build-examples/cjs/example_mcp_remote.js +18 -0
- package/build-examples/cjs/example_mcp_remote.js.map +7 -0
- package/build-examples/esm/example_mcp_local.mjs +14 -15
- package/build-examples/esm/example_mcp_local.mjs.map +4 -4
- package/build-examples/esm/example_mcp_remote.mjs +18 -0
- package/build-examples/esm/example_mcp_remote.mjs.map +7 -0
- package/package.json +11 -11
- package/types/MCPLocal.d.ts +0 -14
- package/types/MCPRemote.d.ts +0 -60
- package/types/PluginOptions.d.ts +0 -6
- package/types/index.d.ts +0 -3
|
@@ -1,19 +1,18 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{EncryptMethod as $,FIXParser as X,Field as h,Fields as S,LicenseManager as k,Messages as U,ResetSeqNumFlag as B}from"fixparser";import{Server as F}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as b}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as M,GetPromptRequestSchema as N,ListPromptsRequestSchema as C,ListResourcesRequestSchema as A,ListToolsRequestSchema as P}from"@modelcontextprotocol/sdk/types.js";import{Field as t,Fields as r,Messages as g}from"fixparser";var T={type:"object",properties:{fixString:{type:"string",description:"FIX message string to parse"}},required:["fixString"]},O={type:"object",properties:{fixString:{type:"string",description:"FIX message string to parse"}},required:["fixString"]},f={type:"object",properties:{clOrdID:{type:"string",description:"Client Order ID"},handlInst:{type:"string",enum:["1","2","3"],description:"Handling instruction (1=Manual, 2=Automated, 3=AutomatedNoIntervention)"},quantity:{type:"number",description:"Order quantity"},price:{type:"number",description:"Order price"},ordType:{type:"string",enum:["1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","P","Q","R","S"],description:"Order type (1=Market, 2=Limit, 3=Stop)"},side:{type:"string",enum:["1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H"],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)"},symbol:{type:"string",description:"Trading symbol"},timeInForce:{type:"string",enum:["0","1","2","3","4","5","6","7","8","9","A","B","C"],description:"Time in force (0=Day, 1=Good Till Cancel, 2=At Opening, 3=Immediate or Cancel, 4=Fill or Kill, 5=Good Till Crossing, 6=Good Till Date)"}},required:["clOrdID","handlInst","quantity","price","ordType","side","symbol","timeInForce"]},R={type:"object",properties:{mdUpdateType:{type:"string",enum:["0","1"],description:'Market data update type (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use "0" for FullRefresh, "1" for IncrementalRefresh)'},symbol:{type:"string",description:"Trading symbol"},mdReqID:{type:"string",description:"Market data request ID"},subscriptionRequestType:{type:"string",enum:["0","1","2"],description:'Subscription request type (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use "0" for Snapshot + Updates, "1" for Snapshot, "2" for Unsubscribe)'},mdEntryType:{type:"string",enum:["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","J","K","L","M","N","O","P","Q","S","R","T","U","V","W","X","Y","Z","a","b","c","d","e","g","h","i","t"],description:'Market data entry type (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)'}},required:["symbol","mdReqID"]},x=class{parser;server=new F({name:"fixparser",version:"1.0.0"},{capabilities:{tools:{},prompts:{},resources:{}}});transport=new b;onReady=void 0;pendingRequests=new Map;verifiedOrders=new Map;constructor({logger:o,onReady:p}){p&&(this.onReady=p)}async register(o){this.parser=o,this.parser.addOnMessageCallback(p=>{let d=p.messageType;if(d===g.MarketDataSnapshotFullRefresh||d===g.ExecutionReport||d===g.Reject){let s;if(d===g.MarketDataSnapshotFullRefresh){let e=p.getField(r.MDReqID);e&&(s=String(e.value))}else if(d===g.ExecutionReport){let e=p.getField(r.ClOrdID);e&&(s=String(e.value))}else if(d===g.Reject){let e=p.getField(r.RefSeqNum);e&&(s=String(e.value))}if(s){let e=this.pendingRequests.get(s);e&&(e(p),this.pendingRequests.delete(s))}}}),this.addWorkflows(),await this.server.connect(this.transport),this.onReady&&this.onReady()}addWorkflows(){if(!this.parser||!this.server)return;let o=(p,d)=>{let s={};for(let[e,i]of Object.entries(d.properties||{})){let n=i,a=p?.[e];if(n.required&&a==null)throw new Error(`Required property '${e}' is missing`);a!==void 0?s[e]=a:n.default!==void 0&&(s[e]=n.default)}return s};this.server.setRequestHandler(A,async()=>({resources:[]})),this.server.setRequestHandler(P,async()=>({tools:[{name:"parse",description:"Parses a FIX message and describes it in plain language",inputSchema:T},{name:"parseToJSON",description:"Parses a FIX message into JSON",inputSchema:O},{name:"verifyOrder",description:"Verifies all parameters for a New Order Single. This is the first step - verification only, no order is sent.",inputSchema:f},{name:"executeOrder",description:"Executes a New Order Single after verification. This is the second step - only call after successful verification.",inputSchema:f},{name:"marketDataRequest",description:"Sends a request for Market Data with the given symbol. IMPORTANT: All parameters must be explicitly provided by the user - no assumptions will be made.",inputSchema:R}]})),this.server.setRequestHandler(M,async p=>{let{name:d,arguments:s}=p.params;switch(d){case"parse":try{let{fixString:e}=o(s,T),i=this.parser?.parse(e);return!i||i.length===0?{isError:!0,content:[{type:"text",text:"Error: Failed to parse FIX string"}]}:{content:[{type:"text",text:`${i[0].description}
|
|
3
|
-
|
|
4
|
-
|
|
2
|
+
import{EncryptMethod as et,FIXParser as tt,Field as q,Fields as j,LicenseManager as rt,Messages as nt,ResetSeqNumFlag as st}from"fixparser";var le=class{format;useStderr;constructor({format:n="json",useStderr:t=!1}){this.format=n,this.useStderr=t}configure(n){this.format=n.format||"json",n.useStderr!==void 0&&(this.useStderr=n.useStderr)}async send(n){let t=this.useStderr?console.error:console.log;if(this.format==="json")t(JSON.stringify(n));else if(this.format==="jsonrpc"){let{message:e,...s}=n,l={jsonrpc:"2.0",method:n.level,params:{message:e,...s},id:n.id||Date.now()};t(JSON.stringify(l))}else{let{name:e,id:s,message:l,level:a,...c}=n,o=Object.entries(c).map(([i,r])=>`${i}: ${r}`),u="";e&&(u+=`${e} `),u+=`${s}: ${l}`,t(u,o.join(", "))}}async flush(){}async close(){}status(){return"connected"}};import{Server as Te}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as Ce}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as B}from"zod";import{Field as A,Fields as x,MDEntryType as v,Messages as He}from"fixparser";import Ne from"quickchart-js";import{Field as I,Fields as O,Messages as he}from"fixparser";import{Fields as ee,MDEntryType as P,Messages as te}from"fixparser";import{McpServer as ft}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as Pt}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{isInitializeRequest as St}from"@modelcontextprotocol/sdk/types.js";import{z as wt}from"zod";var De=class{logger;parser;onReady=void 0;verifiedOrders=new Map;pendingRequests=new Map;marketDataPrices=new Map;MAX_PRICE_HISTORY=1e5;constructor({logger:n,onReady:t}){this.logger=n,this.onReady=t}},ce={parse:{description:"Parses a FIX message and describes it in plain language",schema:{type:"object",properties:{fixString:{type:"string"}},required:["fixString"]}},parseToJSON:{description:"Parses a FIX message into JSON",schema:{type:"object",properties:{fixString:{type:"string"}},required:["fixString"]}},verifyOrder:{description:"Verifies order parameters before execution. verifyOrder must be called before executeOrder.",schema:{type:"object",properties:{clOrdID:{type:"string"},handlInst:{type:"string",enum:["1","2","3"],description:"Handling Instructions: 1=Automated Execution No Intervention, 2=Automated Execution Intervention OK, 3=Manual Order"},quantity:{type:"string"},price:{type:"string"},ordType:{type:"string",enum:["1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","P","Q","R","S"],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"},side:{type:"string",enum:["1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H"],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"},symbol:{type:"string"},timeInForce:{type:"string",enum:["0","1","2","3","4","5","6","7","8","9","A","B","C"],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"}},required:["clOrdID","handlInst","quantity","price","ordType","side","symbol","timeInForce"]}},executeOrder:{description:"Executes a verified order. verifyOrder must be called before executeOrder.",schema:{type:"object",properties:{clOrdID:{type:"string"},handlInst:{type:"string",enum:["1","2","3"],description:"Handling Instructions: 1=Automated Execution No Intervention, 2=Automated Execution Intervention OK, 3=Manual Order"},quantity:{type:"string"},price:{type:"string"},ordType:{type:"string",enum:["1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","P","Q","R","S"],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"},side:{type:"string",enum:["1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H"],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"},symbol:{type:"string"},timeInForce:{type:"string",enum:["0","1","2","3","4","5","6","7","8","9","A","B","C"],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"}},required:["clOrdID","handlInst","quantity","price","ordType","side","symbol","timeInForce"]}},marketDataRequest:{description:"Requests market data for specified symbols",schema:{type:"object",properties:{mdUpdateType:{type:"string",enum:["0","1"],description:"Market Data Update Type: 0=Full Refresh, 1=Incremental Refresh"},symbols:{type:"array",items:{type:"string"}},mdReqID:{type:"string"},subscriptionRequestType:{type:"string",enum:["0","1","2"],description:"Subscription Request Type: 0=Snapshot, 1=Snapshot + Updates, 2=Disable Previous Snapshot + Update Request"},mdEntryTypes:{type:"array",items:{type:"string",enum:["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]},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"}},required:["mdUpdateType","symbols","mdReqID","subscriptionRequestType"]}},getStockGraph:{description:"Generates a price chart for a given symbol",schema:{type:"object",properties:{symbol:{type:"string"}},required:["symbol"]}},getStockPriceHistory:{description:"Returns price history for a given symbol",schema:{type:"object",properties:{symbol:{type:"string"}},required:["symbol"]}},technicalAnalysis:{description:"Performs comprehensive technical analysis on market data for a given symbol, including indicators like SMA, EMA, RSI, Bollinger Bands, and trading signals",schema:{type:"object",properties:{symbol:{type:"string",description:"The trading symbol to analyze (e.g., AAPL, MSFT, EURUSD)"}},required:["symbol"]}}},$=class{static calculateRSI(n,t=14){if(n.length<t+1)return[];let e=[];for(let u=1;u<n.length;u++)e.push(n[u]-n[u-1]);let s=e.map(u=>u>0?u:0),l=e.map(u=>u<0?Math.abs(u):0),a=s.slice(0,t).reduce((u,i)=>u+i,0)/t,c=l.slice(0,t).reduce((u,i)=>u+i,0)/t,o=[];for(let u=t;u<e.length;u++){let i=a/c;o.push(100-100/(1+i)),a=(a*(t-1)+s[u])/t,c=(c*(t-1)+l[u])/t}return o}static calculateStochastic(n,t,e){let s=[];if(n.length<14)return[];let o=[];for(let i=13;i<n.length;i++){let r=Math.max(...t.slice(i-14+1,i+1)),h=Math.min(...e.slice(i-14+1,i+1)),f=(n[i]-h)/(r-h)*100;o.push(f)}let u=[];for(let i=2;i<o.length;i++){let r=o.slice(i-3+1,i+1).reduce((h,m)=>h+m,0);u.push(r/3)}for(let i=2;i<u.length;i++){let h=u.slice(i-3+1,i+1).reduce((m,f)=>m+f,0)/3;s.push({k:u[i],d:h})}return s}static calculateCCI(n,t,e){let s=[];if(n.length<20)return[];for(let a=19;a<n.length;a++){let o=n.slice(a-20+1,a+1).map((m,f)=>{let M=t[a-20+1+f]||m,d=e[a-20+1+f]||m;return(M+d+m)/3}),u=o.reduce((m,f)=>m+f,0)/20,i=o.reduce((m,f)=>m+Math.abs(f-u),0)/20,r=(t[a]+e[a]+n[a])/3,h=i!==0?(r-u)/(.015*i):0;s.push(h)}return s}static calculateROC(n){let t=[];for(let e=10;e<n.length;e++)t.push((n[e]-n[e-10])/n[e-10]*100);return t}static calculateWilliamsR(n){let t=[];if(n.length<14)return[];for(let s=13;s<n.length;s++){let l=n.slice(s-14+1,s+1),a=Math.max(...l),c=Math.min(...l),o=n[s],u=(a-o)/(a-c)*-100;t.push(u)}return t}static calculateMomentum(n){let t=[];for(let e=10;e<n.length;e++)t.push(n[e]-n[e-10]);return t}},R=class{static calculateSMA(n,t){let e=[];for(let s=t-1;s<n.length;s++){let l=n.slice(s-t+1,s+1).reduce((a,c)=>a+c,0);e.push(l/t)}return e}static calculateEMA(n,t){let e=2/(t+1),s=[n[0]];for(let l=1;l<n.length;l++)s.push(n[l]*e+s[l-1]*(1-e));return s}static calculateWMA(n,t){let e=[],s=Array.from({length:t},(a,c)=>c+1),l=s.reduce((a,c)=>a+c,0);for(let a=t-1;a<n.length;a++){let c=0;for(let o=0;o<t;o++)c+=n[a-o]*s[o];e.push(c/l)}return e}static calculateVWMA(n,t,e){let s=[];for(let l=e-1;l<n.length;l++){let a=0,c=0;for(let o=0;o<e;o++){let u=t[l-o]||1;a+=u,c+=n[l-o]*u}s.push(c/a)}return s}},Le=class C{static calculateBlackScholes(t,e,s){let l=t,a=e,c=1,o=.05,u=s*.01,i=(Math.log(l/a)+(o+u*u/2)*c)/(u*Math.sqrt(c)),r=i-u*Math.sqrt(c),h=l*C.normalCDF(i)-a*Math.exp(-o*c)*C.normalCDF(r),m=a*Math.exp(-o*c)*C.normalCDF(-r)-l*C.normalCDF(-i);return{callPrice:h,putPrice:m,delta:C.normalCDF(i),gamma:C.normalPDF(i)/(l*u*Math.sqrt(c)),theta:-l*C.normalPDF(i)*u/(2*Math.sqrt(c))-o*a*Math.exp(-o*c)*C.normalCDF(r),vega:l*Math.sqrt(c)*C.normalPDF(i),rho:a*c*Math.exp(-o*c)*C.normalCDF(r)}}static normalCDF(t){return .5*(1+C.erf(t/Math.sqrt(2)))}static normalPDF(t){return Math.exp(-t*t/2)/Math.sqrt(2*Math.PI)}static erf(t){let e=.254829592,s=-.284496736,l=1.421413741,a=-1.453152027,c=1.061405429,o=.3275911,u=t>=0?1:-1,i=Math.abs(t),r=1/(1+o*i),h=1-((((c*r+a)*r+l)*r+s)*r+e)*r*Math.exp(-i*i);return u*h}},J=class{static calculateMaxDrawdown(n){let t=n[0],e=0;for(let s=1;s<n.length;s++){n[s]>t&&(t=n[s]);let l=(t-n[s])/t;l>e&&(e=l)}return e}static calculateMaxConsecutiveLosses(n){let t=0,e=0;for(let s=1;s<n.length;s++)n[s]<n[s-1]?(e++,t=Math.max(t,e)):e=0;return t}static calculateWinRate(n){let t=0,e=0;for(let s=1;s<n.length;s++)n[s]!==n[s-1]&&(e++,n[s]>n[s-1]&&t++);return e>0?t/e:0}static calculateProfitFactor(n){let t=0,e=0;for(let s=1;s<n.length;s++){let l=n[s]-n[s-1];l>0?t+=l:e+=Math.abs(l)}return e>0?t/e:0}static calculateSharpeRatio(n,t=.02){if(n.length===0)return 0;let e=n.reduce((c,o)=>c+o,0)/n.length,s=e-t,l=n.reduce((c,o)=>c+(o-e)**2,0)/n.length,a=Math.sqrt(l);return a>0?s/a:0}static calculateSortinoRatio(n,t=.02){if(n.length===0)return 0;let e=n.reduce((o,u)=>o+u,0)/n.length,s=e-t,a=n.filter(o=>o<e).reduce((o,u)=>o+(u-e)**2,0)/n.length,c=Math.sqrt(a);return c>0?s/c:0}static calculateCalmarRatio(n,t){return t===0?0:n.reduce((s,l)=>s+l,0)/n.length/t}static calculatePositionSize(n,t){let e=Math.abs(n-t);return e>0?100/e:1}static calculateConfidence(n){return Math.min(n.length*10,100)}static calculateRiskLevel(n){return n<20?"LOW":n<40?"MEDIUM":"HIGH"}},ue=class re{static generateSignals(t,e,s,l,a,c,o,u,i){let r=0,h=0,m=[];t>e?(m.push(`\u2713 BULLISH: Price above VWAP (+${((t-e)/e*100).toFixed(2)}%)`),r++):(m.push(`\u2717 BEARISH: Price below VWAP (${((t-e)/e*100).toFixed(2)}%)`),h++),s>0&&l>0?(m.push("\u2713 BULLISH: Positive momentum on both timeframes"),r++):s<0&&l<0?(m.push("\u2717 BEARISH: Negative momentum on both timeframes"),h++):m.push("\u25D0 MIXED: Conflicting momentum signals");let f=c/o;return f>1.2&&a>0?(m.push("\u2713 BULLISH: Above-average volume supporting upward move"),r++):f>1.2&&a<0?(m.push("\u2717 BEARISH: Above-average volume supporting downward move"),h++):m.push("\u25D0 NEUTRAL: Volume not providing clear direction"),u>65&&i>30?(m.push("\u2717 BEARISH: High in range with elevated volatility - reversal risk"),h++):u<35&&i>30?(m.push("\u2713 BULLISH: Low in range with volatility - potential bounce"),r++):m.push("\u25D0 NEUTRAL: Price position and volatility not extreme"),{bullishSignals:r,bearishSignals:h,signals:m}}static calculateOverallSignal(t,e,s,l){let a=t-e,c=a>0?"BULLISH_BIAS":a<0?"BEARISH_BIAS":"NEUTRAL",o=re.calculateConfidence(s),u=re.calculateRiskLevel(l);return{bullishSignals:t,bearishSignals:e,signals:s,overallSignal:c,signalScore:a,confidence:o,riskLevel:u}}static calculateConfidence(t){return Math.min(t.length*10,100)}static calculateRiskLevel(t){return t<20?"LOW":t<40?"MEDIUM":"HIGH"}},W=class{static calculateZScore(n,t){return(n-t)/(t*.1)}static calculateOrnsteinUhlenbeck(n,t,e,s){let l=t,a=.1;if(s.length>1){let o=s.reduce((u,i)=>u+i*i,0)/s.length;a=Math.max(.01,Math.min(1,o*10))}let c=e*.01;return{mean:l,speed:a,volatility:c,currentValue:n}}static calculateKalmanFilter(n,t,e,s){let l=e*.001,a=e*1e-4,c=t,o=l;if(s.length>0){let u=c,i=o+a,r=i/(i+l);return c=u+r*(n-u),o=(1-r)*i,{state:c,covariance:o,gain:r}}return{state:n,covariance:o,gain:.5}}static calculateARIMA(n,t){if(t.length<3)return{forecast:[n*1.01,n*1.02],residuals:[0,0],aic:100};let e=t.length,s=0,l=0,a=0,c=0;for(let d=1;d<e;d++){let S=t[d],w=t[d-1];s+=S,l+=w,a+=S*w,c+=w*w}let o=(e*a-s*l)/(e*c-l*l),u=(s-o*l)/e,i=[];for(let d=1;d<e;d++){let S=u+o*t[d-1];i.push(t[d]-S)}let r=i.reduce((d,S)=>d+S*S,0),h=e*Math.log(r/e)+2*2,m=t[t.length-1],f=n+(u+o*m),M=f+(u+o*(u+o*m));return{forecast:[f,M],residuals:i,aic:h}}static calculateGARCH(n,t){if(t.length<5)return{volatility:n*.01,persistence:.9,meanReversion:.1};let e=t.map(o=>o*o),s=e.reduce((o,u)=>o+u,0)/e.length,l=.9;if(e.length>1){let o=e.reduce((u,i)=>u+i,0)/e.length;l=Math.min(.99,Math.max(.5,o/s))}let a=s*(1-l);return{volatility:Math.sqrt(s),persistence:l,meanReversion:a}}static calculateHilbertTransform(n,t){if(t.length<3)return{analytic:[n],phase:[0],amplitude:[n]};let e=t.length,s=[],l=[],a=[];for(let c=0;c<e;c++){let o=0;for(let m=0;m<e;m++)c!==m&&(o+=t[m]/(Math.PI*(c-m)));let u=t[c],i=o,r=Math.sqrt(u*u+i*i);s.push(r);let h=Math.atan2(i,u);l.push(h),a.push(r)}return{analytic:s,phase:l,amplitude:a}}static calculateWaveletTransform(n,t){if(t.length<4)return{coefficients:[n],scales:[1]};let e=[],s=[],l=t.length,a=Math.floor(Math.log2(l));for(let c=1;c<=a;c++){let o=2**(c-1),u=o;for(let i=0;i<l-o;i+=o*2)if(i+o<l){let r=(t[i]-t[i+o])/Math.sqrt(2);e.push(r),s.push(u)}}return e.length===0&&(e.push(n),s.push(1)),{coefficients:e,scales:s}}},z=class G{static calculatePivotPoints(t,e,s){let l=[];for(let a=0;a<t.length;a++){let c=e[a]||t[a],o=s[a]||t[a],u=t[a],i=(c+o+u)/3,r=2*i-o,h=2*i-c,m=i+(c-o),f=i-(c-o),M=c+2*(i-o),d=o-2*(c-i);l.push({pp:i,r1:r,r2:m,r3:M,s1:h,s2:f,s3:d})}return l}static calculateFibonacciLevels(t){let e=[];for(let s=0;s<t.length;s++){let l=t[s];e.push({retracement:{level0:l,level236:l*.764,level382:l*.618,level500:l*.5,level618:l*.382,level786:l*.214,level100:l*0},extension:{level1272:l*1.272,level1618:l*1.618,level2618:l*2.618,level4236:l*4.236}})}return e}static calculateGannLevels(t){let e=[];for(let s=0;s<t.length;s++)e.push(t[s]*(1+s*.01));return e}static calculateElliottWave(t){let e=[];if(t.length<10)return[];for(let s=0;s<t.length;s++){let l=[],a=1,c=.5;if(s>=4){let o=t.slice(s-4,s+1),u=G.detectPriceSwings(o);u.length>=3&&(l.push(...u.slice(0,3)),a=Math.min(u.length,5),c=G.calculateWavePosition(o))}e.push({waves:l.length>0?l:[t[s]],currentWave:a,wavePosition:c})}return e}static detectPriceSwings(t){let e=[];for(let s=1;s<t.length-1;s++){let l=t[s-1],a=t[s],c=t[s+1];(a>l&&a>c||a<l&&a<c)&&e.push(a)}return e}static calculateWavePosition(t){if(t.length<2)return .5;let e=t[t.length-1],s=Math.min(...t),l=Math.max(...t);return l!==s?(e-s)/(l-s):.5}static calculateHarmonicPatterns(t){let e=[];if(t.length<5)return[];for(let s=4;s<t.length;s++){let l=t.slice(s-4,s+1),a=G.detectHarmonicPattern(l);e.push(a)}return e}static detectHarmonicPattern(t){if(t.length<5)return{type:"Unknown",completion:0,target:t[t.length-1]*1.1,stopLoss:t[t.length-1]*.9};let e=G.detectPriceSwings(t);if(e.length<4)return{type:"Unknown",completion:0,target:t[t.length-1]*1.1,stopLoss:t[t.length-1]*.9};let[s,l,a,c]=e.slice(-4),o=t[0],u=Math.abs((l-s)/(o-s)),i=Math.abs((a-l)/(s-l)),r=Math.abs((c-a)/(l-a)),h=Math.abs((c-s)/(o-s));if(Math.abs(u-.618)<.1&&i>=.382&&i<=.886&&r>=1.13&&r<=1.618&&Math.abs(h-.786)<.1){let M=G.calculatePatternCompletion(t),d=c+(c-a)*.618,S=c-(c-a)*.382;return{type:"Gartley",completion:M,target:d,stopLoss:S}}if(Math.abs(u-.786)<.1&&i>=.382&&i<=.886&&r>=1.618&&r<=2.618&&Math.abs(h-1.27)<.1){let M=G.calculatePatternCompletion(t),d=c+(c-a)*1.27,S=c-(c-a)*.5;return{type:"Butterfly",completion:M,target:d,stopLoss:S}}return{type:"Unknown",completion:0,target:t[t.length-1]*1.1,stopLoss:t[t.length-1]*.9}}static calculatePatternCompletion(t){if(t.length<2)return 0;let e=t[t.length-1],s=Math.min(...t),l=Math.max(...t);return l!==s?(e-s)/(l-s):0}},K=class{static calculateMACD(n){let t=R.calculateEMA(n,12),e=R.calculateEMA(n,26),s=[],l=[];for(let c=0;c<Math.min(t.length,e.length);c++)l.push(t[c]-e[c]);let a=R.calculateEMA(l,9);for(let c=0;c<Math.min(l.length,a.length);c++)s.push({macd:l[c],signal:a[c],histogram:l[c]-a[c]});return s}static calculateADX(n,t,e){if(n.length<14)return[];let s=14,l=[],a=[],c=[],o=[];a.push(t[0]-e[0]),c.push(0),o.push(0);for(let p=1;p<n.length;p++){let g=t[p]||n[p],y=e[p]||n[p],b=t[p-1]||n[p-1],D=e[p-1]||n[p-1],H=n[p-1],L=g-y,V=Math.abs(g-H),k=Math.abs(y-H);a.push(Math.max(L,V,k));let N=g-b,F=D-y;N>F&&N>0?(c.push(N),o.push(0)):F>N&&F>0?(c.push(0),o.push(F)):(c.push(0),o.push(0))}let u=[],i=[],r=[],h=0,m=0,f=0;for(let p=0;p<s;p++)h+=a[p],m+=c[p],f+=o[p];u.push(h),i.push(m),r.push(f);for(let p=s;p<a.length;p++){let g=u[u.length-1]-u[u.length-1]/s+a[p],y=i[i.length-1]-i[i.length-1]/s+c[p],b=r[r.length-1]-r[r.length-1]/s+o[p];u.push(g),i.push(y),r.push(b)}let M=[],d=[];for(let p=0;p<u.length;p++)M.push(i[p]/u[p]*100),d.push(r[p]/u[p]*100);let S=[];for(let p=0;p<M.length;p++){let g=M[p]+d[p],y=Math.abs(M[p]-d[p]);S.push(g>0?y/g*100:0)}if(S.length<s)return[];let w=0;for(let p=0;p<s;p++)w+=S[p];l.push(w/s);for(let p=s;p<S.length;p++){let g=l[l.length-1]-l[l.length-1]/s+S[p];l.push(g)}return l}static calculateDMI(n,t,e){if(n.length<14)return[];let s=14,l=[],a=[],c=[],o=[];a.push(t[0]-e[0]),c.push(0),o.push(0);for(let g=1;g<n.length;g++){let y=t[g]||n[g],b=e[g]||n[g],D=t[g-1]||n[g-1],H=e[g-1]||n[g-1],L=n[g-1],V=y-b,k=Math.abs(y-L),N=Math.abs(b-L);a.push(Math.max(V,k,N));let F=y-D,E=H-b;F>E&&F>0?(c.push(F),o.push(0)):E>F&&E>0?(c.push(0),o.push(E)):(c.push(0),o.push(0))}let u=[],i=[],r=[],h=0,m=0,f=0;for(let g=0;g<s;g++)h+=a[g],m+=c[g],f+=o[g];u.push(h),i.push(m),r.push(f);for(let g=s;g<a.length;g++){let y=u[u.length-1]-u[u.length-1]/s+a[g],b=i[i.length-1]-i[i.length-1]/s+c[g],D=r[r.length-1]-r[r.length-1]/s+o[g];u.push(y),i.push(b),r.push(D)}let M=[],d=[];for(let g=0;g<u.length;g++)M.push(i[g]/u[g]*100),d.push(r[g]/u[g]*100);let S=[];for(let g=0;g<M.length;g++){let y=M[g]+d[g],b=Math.abs(M[g]-d[g]);S.push(y>0?b/y*100:0)}if(S.length<s)return[];let w=[],p=0;for(let g=0;g<s;g++)p+=S[g];w.push(p/s);for(let g=s;g<S.length;g++){let y=w[w.length-1]-w[w.length-1]/s+S[g];w.push(y)}for(let g=0;g<w.length;g++)l.push({plusDI:M[g+s-1]||0,minusDI:d[g+s-1]||0,adx:w[g]});return l}static calculateIchimoku(n,t,e){if(n.length<52)return[];let s=[],l=[];for(let r=8;r<n.length;r++){let h=Math.max(...t.slice(r-8,r+1)),m=Math.min(...e.slice(r-8,r+1));l.push((h+m)/2)}let a=[];for(let r=25;r<n.length;r++){let h=Math.max(...t.slice(r-25,r+1)),m=Math.min(...e.slice(r-25,r+1));a.push((h+m)/2)}let c=[];for(let r=0;r<Math.min(l.length,a.length);r++)c.push((l[r]+a[r])/2);let o=[];for(let r=51;r<n.length;r++){let h=Math.max(...t.slice(r-51,r+1)),m=Math.min(...e.slice(r-51,r+1));o.push((h+m)/2)}let u=[];for(let r=26;r<n.length;r++)u.push(n[r-26]);let i=Math.min(l.length,a.length,c.length,o.length,u.length);for(let r=0;r<i;r++)s.push({tenkan:l[r],kijun:a[r],senkouA:c[r],senkouB:o[r],chikou:u[r]});return s}static calculateParabolicSAR(n,t,e){if(n.length<2)return[];let s=[],l=.02,a=.2,c=e[0],o=!0,u=l,i=t[0];s.push(c);for(let r=1;r<n.length;r++){let h=t[r]||n[r],m=e[r]||n[r];if(o){if(m<c)o=!1,c=i,i=m,u=l;else if(h>i&&(i=h,u=Math.min(u+l,a)),c=c+u*(i-c),r>0){let f=e[r-1]||n[r-1];c=Math.min(c,f)}}else if(h>c)o=!0,c=i,i=h,u=l;else if(m<i&&(i=m,u=Math.min(u+l,a)),c=c+u*(i-c),r>0){let f=t[r-1]||n[r-1];c=Math.max(c,f)}s.push(c)}return s}},X=class me{static calculateBollingerBands(t,e=20,s=2){if(t.length<e)return[];let l=R.calculateSMA(t,e),a=[];for(let c=0;c<l.length;c++){let o=t.slice(c,c+e),u=l[c],i=o.reduce((f,M)=>f+(M-u)**2,0)/e,r=Math.sqrt(i),h=u+r*s,m=u-r*s;a.push({upper:h,middle:u,lower:m,bandwidth:(h-m)/u*100,percentB:(t[c]-m)/(h-m)*100})}return a}static calculateATR(t,e,s){if(t.length<2)return[];let l=[];for(let c=1;c<t.length;c++){let o=e[c]||t[c],u=s[c]||t[c],i=t[c-1],r=o-u,h=Math.abs(o-i),m=Math.abs(u-i);l.push(Math.max(r,h,m))}let a=[];if(l.length>=14){let c=l.slice(0,14).reduce((o,u)=>o+u,0);a.push(c/14);for(let o=14;o<l.length;o++)c=c-l[o-14]+l[o],a.push(c/14)}return a}static calculateKeltnerChannels(t,e,s){let l=[];if(t.length<20)return[];let o=R.calculateEMA(t,20),u=me.calculateATR(t,e,s);for(let i=0;i<Math.min(o.length,u.length);i++){let r=o[i],h=u[i];l.push({upper:r+2*h,middle:r,lower:r-2*h})}return l}static calculateDonchianChannels(t){let e=[];for(let s=20;s<t.length;s++){let l=t.slice(s-20,s);e.push({upper:Math.max(...l),middle:(Math.max(...l)+Math.min(...l))/2,lower:Math.min(...l)})}return e}static calculateChaikinVolatility(t,e,s){let l=[];if(t.length<10*2)return[];let c=[];for(let u=0;u<t.length;u++){let i=e[u]||t[u],r=s[u]||t[u];c.push(i-r)}let o=R.calculateEMA(c,10);for(let u=10;u<o.length;u++){let i=o[u],r=o[u-10],h=r!==0?(i-r)/r*100:0;l.push(h)}return l}},U=class{static calculateOBV(n,t){let e=[t[0]];for(let s=1;s<n.length;s++)n[s]>n[s-1]?e.push(e[s-1]+t[s]):n[s]<n[s-1]?e.push(e[s-1]-t[s]):e.push(e[s-1]);return e}static calculateCMF(n,t,e,s){let l=[];if(n.length<20)return[];for(let c=19;c<n.length;c++){let o=0,u=0;for(let r=c-20+1;r<=c;r++){let h=t[r]||n[r],m=e[r]||n[r],f=n[r],M=s[r]||1,S=(f-m-(h-f))/(h-m)*M;o+=S,u+=M}let i=u!==0?o/u:0;l.push(i)}return l}static calculateADL(n,t,e,s){let l=[0];for(let a=1;a<n.length;a++){let c=t[a]||n[a],o=e[a]||n[a],u=n[a],i=s[a]||1,h=(u-o-(c-u))/(c-o)*i;l.push(l[a-1]+h)}return l}static calculateVolumeROC(n){let t=[];for(let e=10;e<n.length;e++)t.push((n[e]-n[e-10])/n[e-10]*100);return t}static calculateMFI(n,t,e,s){let l=[];if(n.length<15)return[];for(let c=14;c<n.length;c++){let o=0,u=0;for(let h=c-14+1;h<=c;h++){let m=t[h]||n[h],f=e[h]||n[h],M=n[h],d=s[h]||1,S=(m+f+M)/3,w=S*d;if(h>c-14+1){let p=t[h-1]||n[h-1],g=e[h-1]||n[h-1],y=n[h-1],b=(p+g+y)/3;S>b?o+=w:S<b&&(u+=w)}}let r=100-100/(1+(u!==0?o/u:0));l.push(r)}return l}static calculateVWAP(n,t){let e=[],s=0,l=0;for(let a=0;a<n.length;a++)s+=n[a]*(t[a]||1),l+=t[a]||1,e.push(s/l);return e}};function Ve(n){return n.reduce((t,e)=>t+e,0)}var Ee=class{prices;volumes;highs;lows;constructor(n){this.prices=n.map(t=>t.trade>0?t.trade:t.midPrice),this.volumes=n.map(t=>t.volume),this.highs=n.map(t=>t.tradingSessionHighPrice>0?t.tradingSessionHighPrice:t.trade),this.lows=n.map(t=>t.tradingSessionLowPrice>0?t.tradingSessionLowPrice:t.trade)}calculatePriceChanges(){let n=[];for(let t=1;t<this.prices.length;t++)n.push((this.prices[t]-this.prices[t-1])/this.prices[t-1]);return n}analyze(){let n=this.prices[this.prices.length-1],t=this.prices[0],e=Math.max(...this.highs),s=Math.min(...this.lows),l=Ve(this.volumes),a=l/this.volumes.length,c=this.calculatePriceChanges(),o=c.length>0?Math.sqrt(c.reduce((L,V)=>L+V**2,0)/c.length)*Math.sqrt(252)*100:0,u=(n-t)/t*100,i=(n-s)/(e-s)*100,r=this.prices.reduce((L,V,k)=>L+V*this.volumes[k],0)/l,h=this.prices.length>5?(n-this.prices[Math.max(0,this.prices.length-6)])/this.prices[Math.max(0,this.prices.length-6)]*100:0,m=this.prices.length>10?(n-this.prices[Math.max(0,this.prices.length-11)])/this.prices[Math.max(0,this.prices.length-11)]*100:0,f=J.calculateMaxDrawdown(this.prices),M=X.calculateATR(this.prices,this.highs,this.lows),d=M.length>0?M[M.length-1]:0,S=o,w=o,p=u/o,g=u/w,y=u/f,b=J.calculateMaxConsecutiveLosses(this.prices),D=J.calculateWinRate(this.prices),H=J.calculateProfitFactor(this.prices);return{currentPrice:n,startPrice:t,sessionHigh:e,sessionLow:s,totalVolume:l,avgVolume:a,volatility:o,sessionReturn:u,pricePosition:i,trueVWAP:r,momentum5:h,momentum10:m,maxDrawdown:f,atr:d,impliedVolatility:S,realizedVolatility:w,sharpeRatio:p,sortinoRatio:g,calmarRatio:y,maxConsecutiveLosses:b,winRate:D,profitFactor:H}}getTechnicalIndicators(){return{sma5:R.calculateSMA(this.prices,5),sma10:R.calculateSMA(this.prices,10),sma20:R.calculateSMA(this.prices,20),sma50:R.calculateSMA(this.prices,50),sma200:R.calculateSMA(this.prices,200),ema8:R.calculateEMA(this.prices,8),ema12:R.calculateEMA(this.prices,12),ema21:R.calculateEMA(this.prices,21),ema26:R.calculateEMA(this.prices,26),wma20:R.calculateWMA(this.prices,20),vwma20:R.calculateVWMA(this.prices,this.volumes,20),macd:K.calculateMACD(this.prices),adx:K.calculateADX(this.prices,this.highs,this.lows),dmi:K.calculateDMI(this.prices,this.highs,this.lows),ichimoku:K.calculateIchimoku(this.prices,this.highs,this.lows),parabolicSAR:K.calculateParabolicSAR(this.prices,this.highs,this.lows),rsi:$.calculateRSI(this.prices,14),stochastic:$.calculateStochastic(this.prices,this.highs,this.lows),cci:$.calculateCCI(this.prices,this.highs,this.lows),roc:$.calculateROC(this.prices),williamsR:$.calculateWilliamsR(this.prices),momentum:$.calculateMomentum(this.prices),bollinger:X.calculateBollingerBands(this.prices,20,2),atr:X.calculateATR(this.prices,this.highs,this.lows),keltner:X.calculateKeltnerChannels(this.prices,this.highs,this.lows),donchian:X.calculateDonchianChannels(this.prices),chaikinVolatility:X.calculateChaikinVolatility(this.prices,this.highs,this.lows),obv:U.calculateOBV(this.prices,this.volumes),cmf:U.calculateCMF(this.prices,this.highs,this.lows,this.volumes),adl:U.calculateADL(this.prices,this.highs,this.lows,this.volumes),volumeROC:U.calculateVolumeROC(this.volumes),mfi:U.calculateMFI(this.prices,this.highs,this.lows,this.volumes),vwap:U.calculateVWAP(this.prices,this.volumes),pivotPoints:z.calculatePivotPoints(this.prices,this.highs,this.lows),fibonacci:z.calculateFibonacciLevels(this.prices),gannLevels:z.calculateGannLevels(this.prices),elliottWave:z.calculateElliottWave(this.prices),harmonicPatterns:z.calculateHarmonicPatterns(this.prices)}}generateJSONAnalysis(n){let t=this.analyze(),e=this.getTechnicalIndicators(),s=this.calculatePriceChanges(),l=e.sma5.length>0?e.sma5[e.sma5.length-1]:null,a=e.sma10.length>0?e.sma10[e.sma10.length-1]:null,c=e.sma20.length>0?e.sma20[e.sma20.length-1]:null,o=e.sma50.length>0?e.sma50[e.sma50.length-1]:null,u=e.sma200.length>0?e.sma200[e.sma200.length-1]:null,i=e.ema8[e.ema8.length-1],r=e.ema12[e.ema12.length-1],h=e.ema21[e.ema21.length-1],m=e.ema26[e.ema26.length-1],f=e.wma20.length>0?e.wma20[e.wma20.length-1]:null,M=e.vwma20.length>0?e.vwma20[e.vwma20.length-1]:null,d=e.macd.length>0?e.macd[e.macd.length-1]:null,S=e.adx.length>0?e.adx[e.adx.length-1]:null,w=e.dmi.length>0?e.dmi[e.dmi.length-1]:null,p=e.ichimoku.length>0?e.ichimoku[e.ichimoku.length-1]:null,g=e.parabolicSAR.length>0?e.parabolicSAR[e.parabolicSAR.length-1]:null,y=e.rsi.length>0?e.rsi[e.rsi.length-1]:null,b=e.stochastic.length>0?e.stochastic[e.stochastic.length-1]:null,D=e.cci.length>0?e.cci[e.cci.length-1]:null,H=e.roc.length>0?e.roc[e.roc.length-1]:null,L=e.williamsR.length>0?e.williamsR[e.williamsR.length-1]:null,V=e.momentum.length>0?e.momentum[e.momentum.length-1]:null,k=e.bollinger.length>0?e.bollinger[e.bollinger.length-1]:null,N=e.atr.length>0?e.atr[e.atr.length-1]:null,F=e.keltner.length>0?e.keltner[e.keltner.length-1]:null,E=e.donchian.length>0?e.donchian[e.donchian.length-1]:null,pe=e.chaikinVolatility.length>0?e.chaikinVolatility[e.chaikinVolatility.length-1]:null,ne=e.obv.length>0?e.obv[e.obv.length-1]:null,se=e.cmf.length>0?e.cmf[e.cmf.length-1]:null,fe=e.adl.length>0?e.adl[e.adl.length-1]:null,ye=e.volumeROC.length>0?e.volumeROC[e.volumeROC.length-1]:null,oe=e.mfi.length>0?e.mfi[e.mfi.length-1]:null,Pe=e.vwap.length>0?e.vwap[e.vwap.length-1]:null,ve=e.pivotPoints.length>0?e.pivotPoints[e.pivotPoints.length-1]:null,Se=e.fibonacci.length>0?e.fibonacci[e.fibonacci.length-1]:null,Me=e.gannLevels.length>0?e.gannLevels:[],we=e.elliottWave.length>0?e.elliottWave[e.elliottWave.length-1]:null,be=e.harmonicPatterns.length>0?e.harmonicPatterns:[],Y=this.volumes[this.volumes.length-1],Re=Y/t.avgVolume,Fe=(t.sessionHigh-t.currentPrice)/t.sessionHigh*100,Ie=(t.sessionHigh-t.sessionLow)/t.sessionLow*100,Oe=(t.currentPrice-t.trueVWAP)/t.trueVWAP*100,Z=ue.generateSignals(t.currentPrice,t.trueVWAP,t.momentum5,t.momentum10,t.sessionReturn,Y,t.avgVolume,t.pricePosition,t.volatility),Ae=ue.calculateOverallSignal(Z.bullishSignals,Z.bearishSignals,Z.signals,t.volatility),_=Math.max(t.sessionLow*1.005,t.trueVWAP*.998),Q=t.sessionLow*.995,ie=t.sessionHigh*.995,xe=(ie-t.currentPrice)/(t.currentPrice-Q),ae=J.calculatePositionSize(_,Q),ke=ae*(_-Q);return{symbol:n,timestamp:new Date().toISOString(),marketStructure:{currentPrice:t.currentPrice,startPrice:t.startPrice,sessionHigh:t.sessionHigh,sessionLow:t.sessionLow,rangeWidth:Ie,totalVolume:t.totalVolume,sessionPerformance:t.sessionReturn,positionInRange:t.pricePosition},volatility:{impliedVolatility:t.impliedVolatility,realizedVolatility:t.realizedVolatility,atr:t.atr,maxDrawdown:t.maxDrawdown*100,currentDrawdown:Fe},technicalIndicators:{sma5:l,sma10:a,sma20:c,sma50:o,sma200:u,ema8:i,ema12:r,ema21:h,ema26:m,wma20:f,vwma20:M,macd:d,adx:S,dmi:w,ichimoku:p,parabolicSAR:g,rsi:y,stochastic:b,cci:D,roc:H,williamsR:L,momentum:V,bollingerBands:k?{upper:k.upper,middle:k.middle,lower:k.lower,bandwidth:k.bandwidth,percentB:k.percentB}:null,atr:N,keltnerChannels:F?{upper:F.upper,middle:F.middle,lower:F.lower}:null,donchianChannels:E?{upper:E.upper,middle:E.middle,lower:E.lower}:null,chaikinVolatility:pe,obv:ne,cmf:se,adl:fe,volumeROC:ye,mfi:oe,vwap:Pe},volumeAnalysis:{currentVolume:Y,averageVolume:Math.round(t.avgVolume),volumeRatio:Re,trueVWAP:t.trueVWAP,priceVsVWAP:Oe,obv:ne,cmf:se,mfi:oe},momentum:{momentum5:t.momentum5,momentum10:t.momentum10,sessionROC:t.sessionReturn,rsi:y,stochastic:b,cci:D},supportResistance:{pivotPoints:ve,fibonacci:Se,gannLevels:Me,elliottWave:we,harmonicPatterns:be},tradingSignals:Ae,statisticalModels:{zScore:W.calculateZScore(t.currentPrice,t.startPrice),ornsteinUhlenbeck:W.calculateOrnsteinUhlenbeck(t.currentPrice,t.startPrice,t.avgVolume,s),kalmanFilter:W.calculateKalmanFilter(t.currentPrice,t.startPrice,t.avgVolume,s),arima:W.calculateARIMA(t.currentPrice,s),garch:W.calculateGARCH(t.avgVolume,s),hilbertTransform:W.calculateHilbertTransform(t.currentPrice,s),waveletTransform:W.calculateWaveletTransform(t.currentPrice,s)},optionsAnalysis:(()=>{let T=Le.calculateBlackScholes(t.currentPrice,t.startPrice,t.avgVolume);return T?{blackScholes:T,impliedVolatility:t.impliedVolatility,delta:T.delta,gamma:T.gamma,theta:T.theta,vega:T.vega,rho:T.rho,greeks:{delta:T.delta,gamma:T.gamma,theta:T.theta,vega:T.vega,rho:T.rho}}:null})(),riskManagement:{targetEntry:_,stopLoss:Q,profitTarget:ie,riskRewardRatio:xe,positionSize:ae,maxRisk:ke},performance:{sharpeRatio:t.sharpeRatio,sortinoRatio:t.sortinoRatio,calmarRatio:t.calmarRatio,maxDrawdown:t.maxDrawdown*100,winRate:t.winRate,profitFactor:t.profitFactor,totalReturn:t.sessionReturn,volatility:t.volatility}}}},Be=n=>async t=>{try{let e=t.symbol,s=n.get(e)||[];if(s.length===0)return{content:[{type:"text",text:`No price data available for ${e}. Please request market data first.`,uri:"technicalAnalysis"}]};if(!s.every(o=>typeof o.trade=="number"&&!Number.isNaN(o.trade)&&typeof o.midPrice=="number"&&!Number.isNaN(o.midPrice)))throw new Error("Invalid market data");let c=new Ee(s).generateJSONAnalysis(e);return{content:[{type:"text",text:`Technical Analysis for ${e}:
|
|
3
|
+
|
|
4
|
+
${JSON.stringify(c,null,2)}`,uri:"technicalAnalysis"}]}}catch(e){return{content:[{type:"text",text:`Error performing technical analysis: ${e instanceof Error?e.message:"Unknown error"}`,uri:"technicalAnalysis"}],isError:!0}}},qe=(n,t)=>async e=>{try{n.logger.log({level:"info",message:`Sending market data request for symbols: ${e.symbols.join(", ")}`});let s=new Promise(u=>{t.set(e.mdReqID,u),n.logger.log({level:"info",message:`Registered callback for market data request ID: ${e.mdReqID}`})}),l=e.mdEntryTypes||[v.Bid,v.Offer,v.Trade,v.IndexValue,v.OpeningPrice,v.ClosingPrice,v.SettlementPrice,v.TradingSessionHighPrice,v.TradingSessionLowPrice,v.VWAP,v.Imbalance,v.TradeVolume,v.OpenInterest,v.CompositeUnderlyingPrice,v.SimulatedSellPrice,v.SimulatedBuyPrice,v.MarginRate,v.MidPrice,v.EmptyBook,v.SettleHighPrice,v.SettleLowPrice,v.PriorSettlePrice,v.SessionHighBid,v.SessionLowOffer,v.EarlyPrices,v.AuctionClearingPrice,v.SwapValueFactor,v.DailyValueAdjustmentForLongPositions,v.CumulativeValueAdjustmentForLongPositions,v.DailyValueAdjustmentForShortPositions,v.CumulativeValueAdjustmentForShortPositions,v.FixingPrice,v.CashRate,v.RecoveryRate,v.RecoveryRateForLong,v.RecoveryRateForShort,v.MarketBid,v.MarketOffer,v.ShortSaleMinPrice,v.PreviousClosingPrice,v.ThresholdLimitPriceBanding,v.DailyFinancingValue,v.AccruedFinancingValue,v.TWAP],a=[new A(x.MsgType,He.MarketDataRequest),new A(x.SenderCompID,n.sender),new A(x.MsgSeqNum,n.getNextTargetMsgSeqNum()),new A(x.TargetCompID,n.target),new A(x.SendingTime,n.getTimestamp()),new A(x.MDReqID,e.mdReqID),new A(x.SubscriptionRequestType,e.subscriptionRequestType),new A(x.MarketDepth,0),new A(x.MDUpdateType,e.mdUpdateType)];a.push(new A(x.NoRelatedSym,e.symbols.length)),e.symbols.forEach(u=>{a.push(new A(x.Symbol,u))}),a.push(new A(x.NoMDEntryTypes,l.length)),l.forEach(u=>{a.push(new A(x.MDEntryType,u))});let c=n.createMessage(...a);if(!n.connected)return n.logger.log({level:"error",message:"Not connected. Cannot send market data request."}),{content:[{type:"text",text:"Error: Not connected. Ignoring message.",uri:"marketDataRequest"}],isError:!0};n.logger.log({level:"info",message:`Sending market data request message: ${JSON.stringify(c?.toFIXJSON())}`}),n.send(c);let o=await s;return n.logger.log({level:"info",message:`Received market data response for request ID: ${e.mdReqID}`}),{content:[{type:"text",text:`Market data for ${e.symbols.join(", ")}: ${JSON.stringify(o.toFIXJSON())}`,uri:"marketDataRequest"}]}}catch(s){return{content:[{type:"text",text:`Error: ${s instanceof Error?s.message:"Failed to request market data"}`,uri:"marketDataRequest"}],isError:!0}}},de=(n,t=490)=>{if(n.length<=t)return n;let e=[],s=n.length/t;e.push(n[0]);for(let l=1;l<t-1;l++){let a=Math.floor(l*s),c=Math.floor((l+1)*s),o=n.slice(a,c);if(o.length===0)continue;let u={timestamp:o[0].timestamp,bid:o.reduce((i,r)=>i+r.bid,0)/o.length,offer:o.reduce((i,r)=>i+r.offer,0)/o.length,spread:o.reduce((i,r)=>i+r.spread,0)/o.length,volume:o.reduce((i,r)=>i+r.volume,0)/o.length,trade:o.reduce((i,r)=>i+r.trade,0)/o.length,indexValue:o.reduce((i,r)=>i+r.indexValue,0)/o.length,openingPrice:o.reduce((i,r)=>i+r.openingPrice,0)/o.length,closingPrice:o.reduce((i,r)=>i+r.closingPrice,0)/o.length,settlementPrice:o.reduce((i,r)=>i+r.settlementPrice,0)/o.length,tradingSessionHighPrice:o.reduce((i,r)=>i+r.tradingSessionHighPrice,0)/o.length,tradingSessionLowPrice:o.reduce((i,r)=>i+r.tradingSessionLowPrice,0)/o.length,vwap:o.reduce((i,r)=>i+r.vwap,0)/o.length,imbalance:o.reduce((i,r)=>i+r.imbalance,0)/o.length,openInterest:o.reduce((i,r)=>i+r.openInterest,0)/o.length,compositeUnderlyingPrice:o.reduce((i,r)=>i+r.compositeUnderlyingPrice,0)/o.length,simulatedSellPrice:o.reduce((i,r)=>i+r.simulatedSellPrice,0)/o.length,simulatedBuyPrice:o.reduce((i,r)=>i+r.simulatedBuyPrice,0)/o.length,marginRate:o.reduce((i,r)=>i+r.marginRate,0)/o.length,midPrice:o.reduce((i,r)=>i+r.midPrice,0)/o.length,emptyBook:o.reduce((i,r)=>i+r.emptyBook,0)/o.length,settleHighPrice:o.reduce((i,r)=>i+r.settleHighPrice,0)/o.length,settleLowPrice:o.reduce((i,r)=>i+r.settleLowPrice,0)/o.length,priorSettlePrice:o.reduce((i,r)=>i+r.priorSettlePrice,0)/o.length,sessionHighBid:o.reduce((i,r)=>i+r.sessionHighBid,0)/o.length,sessionLowOffer:o.reduce((i,r)=>i+r.sessionLowOffer,0)/o.length,earlyPrices:o.reduce((i,r)=>i+r.earlyPrices,0)/o.length,auctionClearingPrice:o.reduce((i,r)=>i+r.auctionClearingPrice,0)/o.length,swapValueFactor:o.reduce((i,r)=>i+r.swapValueFactor,0)/o.length,dailyValueAdjustmentForLongPositions:o.reduce((i,r)=>i+r.dailyValueAdjustmentForLongPositions,0)/o.length,cumulativeValueAdjustmentForLongPositions:o.reduce((i,r)=>i+r.cumulativeValueAdjustmentForLongPositions,0)/o.length,dailyValueAdjustmentForShortPositions:o.reduce((i,r)=>i+r.dailyValueAdjustmentForShortPositions,0)/o.length,cumulativeValueAdjustmentForShortPositions:o.reduce((i,r)=>i+r.cumulativeValueAdjustmentForShortPositions,0)/o.length,fixingPrice:o.reduce((i,r)=>i+r.fixingPrice,0)/o.length,cashRate:o.reduce((i,r)=>i+r.cashRate,0)/o.length,recoveryRate:o.reduce((i,r)=>i+r.recoveryRate,0)/o.length,recoveryRateForLong:o.reduce((i,r)=>i+r.recoveryRateForLong,0)/o.length,recoveryRateForShort:o.reduce((i,r)=>i+r.recoveryRateForShort,0)/o.length,marketBid:o.reduce((i,r)=>i+r.marketBid,0)/o.length,marketOffer:o.reduce((i,r)=>i+r.marketOffer,0)/o.length,shortSaleMinPrice:o.reduce((i,r)=>i+r.shortSaleMinPrice,0)/o.length,previousClosingPrice:o.reduce((i,r)=>i+r.previousClosingPrice,0)/o.length,thresholdLimitPriceBanding:o.reduce((i,r)=>i+r.thresholdLimitPriceBanding,0)/o.length,dailyFinancingValue:o.reduce((i,r)=>i+r.dailyFinancingValue,0)/o.length,accruedFinancingValue:o.reduce((i,r)=>i+r.accruedFinancingValue,0)/o.length,twap:o.reduce((i,r)=>i+r.twap,0)/o.length};e.push(u)}return e.push(n[n.length-1]),e},je=n=>async t=>{try{let e=t.symbol,s=n.get(e)||[];if(s.length===0)return{content:[{type:"text",text:`No price data available for ${e}`,uri:"getStockGraph"}]};let l=de(s,500),a=new Ne;a.setWidth(1200),a.setHeight(600),a.setBackgroundColor("transparent");let c=l.map(y=>new Date(y.timestamp).toLocaleTimeString()),o=l.map(y=>y.bid),u=l.map(y=>y.offer),i=l.map(y=>y.spread),r=l.map(y=>y.volume),h=l.map(y=>y.trade),m=l.map(y=>y.vwap),f=l.map(y=>y.twap),M=Math.max(...r.filter(y=>y>0)),d=Math.max(...o,...u,...h,...m,...f),S=r.map(y=>y/M*d*.3),w={type:"line",data:{labels:c,datasets:[{label:"Bid",data:o,borderColor:"#28a745",backgroundColor:"rgba(40, 167, 69, 0.1)",fill:!1,tension:.4},{label:"Offer",data:u,borderColor:"#dc3545",backgroundColor:"rgba(220, 53, 69, 0.1)",fill:!1,tension:.4},{label:"Spread",data:i,borderColor:"#6c757d",backgroundColor:"rgba(108, 117, 125, 0.1)",fill:!1,tension:.4},{label:"Trade",data:h,borderColor:"#ffc107",backgroundColor:"rgba(255, 193, 7, 0.1)",fill:!1,tension:.4},{label:"VWAP",data:m,borderColor:"#17a2b8",backgroundColor:"rgba(23, 162, 184, 0.1)",fill:!1,tension:.4},{label:"TWAP",data:f,borderColor:"#6610f2",backgroundColor:"rgba(102, 16, 242, 0.1)",fill:!1,tension:.4},{label:"Volume (Normalized)",data:S,borderColor:"#007bff",backgroundColor:"rgba(0, 123, 255, 0.1)",fill:!0,tension:.4}]},options:{responsive:!0,plugins:{title:{display:!0,text:`${e} Market Data (Volume normalized to 30% of max price)`}},scales:{y:{beginAtZero:!1,title:{display:!0,text:"Price / Normalized Volume"}}}}};return a.setConfig(w),{content:[{type:"resource",resource:{uri:"resource://graph",mimeType:"image/png",blob:(await a.toBinary()).toString("base64")}}]}}catch(e){return{content:[{type:"text",text:`Error: ${e instanceof Error?e.message:"Failed to generate graph"}`,uri:"getStockGraph"}],isError:!0}}},We=n=>async t=>{try{let e=t.symbol,s=n.get(e)||[];if(s.length===0)return{content:[{type:"text",text:`No price data available for ${e}`,uri:"getStockPriceHistory"}]};let l=de(s,500);return{content:[{type:"text",text:JSON.stringify({symbol:e,count:l.length,originalCount:s.length,data:l.map(a=>({timestamp:new Date(a.timestamp).toISOString(),bid:a.bid,offer:a.offer,spread:a.spread,volume:a.volume,trade:a.trade,indexValue:a.indexValue,openingPrice:a.openingPrice,closingPrice:a.closingPrice,settlementPrice:a.settlementPrice,tradingSessionHighPrice:a.tradingSessionHighPrice,tradingSessionLowPrice:a.tradingSessionLowPrice,vwap:a.vwap,imbalance:a.imbalance,openInterest:a.openInterest,compositeUnderlyingPrice:a.compositeUnderlyingPrice,simulatedSellPrice:a.simulatedSellPrice,simulatedBuyPrice:a.simulatedBuyPrice,marginRate:a.marginRate,midPrice:a.midPrice,emptyBook:a.emptyBook,settleHighPrice:a.settleHighPrice,settleLowPrice:a.settleLowPrice,priorSettlePrice:a.priorSettlePrice,sessionHighBid:a.sessionHighBid,sessionLowOffer:a.sessionLowOffer,earlyPrices:a.earlyPrices,auctionClearingPrice:a.auctionClearingPrice,swapValueFactor:a.swapValueFactor,dailyValueAdjustmentForLongPositions:a.dailyValueAdjustmentForLongPositions,cumulativeValueAdjustmentForLongPositions:a.cumulativeValueAdjustmentForLongPositions,dailyValueAdjustmentForShortPositions:a.dailyValueAdjustmentForShortPositions,cumulativeValueAdjustmentForShortPositions:a.cumulativeValueAdjustmentForShortPositions,fixingPrice:a.fixingPrice,cashRate:a.cashRate,recoveryRate:a.recoveryRate,recoveryRateForLong:a.recoveryRateForLong,recoveryRateForShort:a.recoveryRateForShort,marketBid:a.marketBid,marketOffer:a.marketOffer,shortSaleMinPrice:a.shortSaleMinPrice,previousClosingPrice:a.previousClosingPrice,thresholdLimitPriceBanding:a.thresholdLimitPriceBanding,dailyFinancingValue:a.dailyFinancingValue,accruedFinancingValue:a.accruedFinancingValue,twap:a.twap}))},null,2),uri:"getStockPriceHistory"}]}}catch(e){return{content:[{type:"text",text:`Error: ${e instanceof Error?e.message:"Failed to get price history"}`,uri:"getStockPriceHistory"}],isError:!0}}},Ge={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"},$e={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"},Xe={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"},Ue={1:"AutomatedExecutionNoIntervention",2:"AutomatedExecutionInterventionOK",3:"ManualOrder"},Je=(n,t)=>async e=>{try{return t.set(e.clOrdID,{clOrdID:e.clOrdID,handlInst:e.handlInst,quantity:Number.parseFloat(String(e.quantity)),price:Number.parseFloat(String(e.price)),ordType:e.ordType,side:e.side,symbol:e.symbol,timeInForce:e.timeInForce}),{content:[{type:"text",text:`VERIFICATION: All parameters valid. Ready to proceed with order execution.
|
|
5
|
+
|
|
5
6
|
Parameters verified:
|
|
6
|
-
- ClOrdID: ${e}
|
|
7
|
-
- HandlInst: ${
|
|
8
|
-
- Quantity: ${
|
|
9
|
-
- Price: ${
|
|
10
|
-
- OrdType: ${
|
|
11
|
-
- Side: ${
|
|
12
|
-
- Symbol: ${
|
|
13
|
-
- TimeInForce: ${
|
|
7
|
+
- ClOrdID: ${e.clOrdID}
|
|
8
|
+
- HandlInst: ${e.handlInst} (${Ue[e.handlInst]})
|
|
9
|
+
- Quantity: ${e.quantity}
|
|
10
|
+
- Price: ${e.price}
|
|
11
|
+
- OrdType: ${e.ordType} (${Ge[e.ordType]})
|
|
12
|
+
- Side: ${e.side} (${$e[e.side]})
|
|
13
|
+
- Symbol: ${e.symbol}
|
|
14
|
+
- TimeInForce: ${e.timeInForce} (${Xe[e.timeInForce]})
|
|
14
15
|
|
|
15
|
-
To execute this order, call the executeOrder tool with these exact same parameters
|
|
16
|
-
|
|
17
|
-
`)}}]}}case"marketDataRequest":{let{mdUpdateType:e,symbol:i,mdReqID:n,subscriptionRequestType:a,mdEntryType:l}=s||{};return{messages:[{role:"user",content:{type:"text",text:["You are an AI assistant that helps users create FIX Market Data Request messages.","You must **first verify** that all required fields are provided:","- MDUpdateType (0=FullRefresh, 1=IncrementalRefresh)","- Symbol (Trading symbol)","- MDReqID (Market data request ID)","- SubscriptionRequestType (0=Snapshot + Updates, 1=Snapshot, 2=Unsubscribe)","- MDEntryType (0=Bid, 1=Offer, 2=Trade, 3=Index Value, 4=Opening Price)","","Only when all fields are present and valid, respond with:","`VERIFICATION: All parameters valid. Ready to proceed.`","","Otherwise, list the missing or invalid ones.","","Do not create the FIX message until verification is complete.","","Current parameters:",`- MDUpdateType: ${e}`,`- Symbol: ${i}`,`- MDReqID: ${n}`,`- SubscriptionRequestType: ${a}`,`- MDEntryType: ${l}`].join(`
|
|
18
|
-
`)}}]}}default:throw new Error(`Unknown prompt: ${d}`)}}),process.on("SIGINT",async()=>{await this.server.close(),process.exit(0)})}};var q="CLIENT2",E="EXECUTOR",G=async()=>{await k.setLicenseKey(process.env.FIXPARSER_LICENSE_KEY);let o=new X({logging:!1,plugins:[new x({port:3099,onReady:()=>{}})]}),p=()=>{let s=o.createMessage(new h(S.MsgType,U.Logon),new h(S.MsgSeqNum,o.getNextTargetMsgSeqNum()),new h(S.SenderCompID,q),new h(S.SendingTime,o.getTimestamp()),new h(S.TargetCompID,E),new h(S.ResetSeqNumFlag,B.Yes),new h(S.EncryptMethod,$.None),new h(S.HeartBtInt,10));o.send(s)},d={host:process.env.FIXPARSER_HOST||"10.0.1.42",port:process.env.FIXPARSER_PORT?Number.parseInt(process.env.FIXPARSER_PORT,10):5001,protocol:"tcp",sender:process.env.FIXPARSER_SENDER||q,target:process.env.FIXPARSER_TARGET||E,fixVersion:process.env.FIXPARSER_TARGET||"FIX.4.4",onOpen:()=>{p()},onMessage:s=>{},onClose:()=>{setTimeout(()=>{o.connect(d)},1e3)}};o.connect(d)};G().catch(o=>console.error("Error initializing server:",o));
|
|
16
|
+
To execute this order, call the executeOrder tool with these exact same parameters. Important: The user has to explicitly confirm before executeOrder is called!`,uri:"verifyOrder"}]}}catch(s){return{content:[{type:"text",text:`Error: ${s instanceof Error?s.message:"Failed to verify order parameters"}`,uri:"verifyOrder"}],isError:!0}}},ze=(n,t,e)=>async s=>{try{let l=t.get(s.clOrdID);if(!l)return{content:[{type:"text",text:`Error: Order ${s.clOrdID} has not been verified. Please call verifyOrder first.`,uri:"executeOrder"}],isError:!0};if(l.handlInst!==s.handlInst||l.quantity!==Number.parseFloat(String(s.quantity))||l.price!==Number.parseFloat(String(s.price))||l.ordType!==s.ordType||l.side!==s.side||l.symbol!==s.symbol||l.timeInForce!==s.timeInForce)return{content:[{type:"text",text:"Error: Order parameters do not match the verified order. Please use the exact same parameters that were verified.",uri:"executeOrder"}],isError:!0};let a=new Promise(u=>{e.set(s.clOrdID,u)}),c=n.createMessage(new I(O.MsgType,he.NewOrderSingle),new I(O.MsgSeqNum,n.getNextTargetMsgSeqNum()),new I(O.SenderCompID,n.sender),new I(O.TargetCompID,n.target),new I(O.SendingTime,n.getTimestamp()),new I(O.ClOrdID,s.clOrdID),new I(O.Side,s.side),new I(O.Symbol,s.symbol),new I(O.OrderQty,Number.parseFloat(String(s.quantity))),new I(O.Price,Number.parseFloat(String(s.price))),new I(O.OrdType,s.ordType),new I(O.HandlInst,s.handlInst),new I(O.TimeInForce,s.timeInForce),new I(O.TransactTime,n.getTimestamp()));if(!n.connected)return{content:[{type:"text",text:"Error: Not connected. Ignoring message.",uri:"executeOrder"}],isError:!0};n.send(c);let o=await a;return t.delete(s.clOrdID),{content:[{type:"text",text:o.messageType===he.Reject?`Reject message for order ${s.clOrdID}: ${JSON.stringify(o.toFIXJSON())}`:`Execution Report for order ${s.clOrdID}: ${JSON.stringify(o.toFIXJSON())}`,uri:"executeOrder"}]}}catch(l){return{content:[{type:"text",text:`Error: ${l instanceof Error?l.message:"Failed to execute order"}`,uri:"executeOrder"}],isError:!0}}},Ke=n=>async t=>{try{let e=n.parse(t.fixString);return!e||e.length===0?{content:[{type:"text",text:"Error: Failed to parse FIX string",uri:"parse"}],isError:!0}:{content:[{type:"text",text:`${e[0].description}
|
|
17
|
+
${e[0].messageTypeDescription}`,uri:"parse"}]}}catch(e){return{content:[{type:"text",text:`Error: ${e instanceof Error?e.message:"Failed to parse FIX string"}`,uri:"parse"}],isError:!0}}},Qe=n=>async t=>{try{let e=n.parse(t.fixString);return!e||e.length===0?{content:[{type:"text",text:"Error: Failed to parse FIX string",uri:"parseToJSON"}],isError:!0}:{content:[{type:"text",text:`${e[0].toFIXJSON()}`,uri:"parseToJSON"}]}}catch(e){return{content:[{type:"text",text:`Error: ${e instanceof Error?e.message:"Failed to parse FIX string"}`,uri:"parseToJSON"}],isError:!0}}},Ye=(n,t,e,s)=>({parse:Ke(n),parseToJSON:Qe(n),verifyOrder:Je(n,t),executeOrder:ze(n,t,e),marketDataRequest:qe(n,e),getStockGraph:je(s),getStockPriceHistory:We(s),technicalAnalysis:Be(s)});function Ze(n,t){return n[t]||t}function _e(n,t,e,s,l,a){let c=n.messageType;if(c===te.MarketDataSnapshotFullRefresh||c===te.MarketDataIncrementalRefresh){let o=n.getField(ee.Symbol)?.value,i=n.toFIXJSON().Body?.NoMDEntries||[],r={timestamp:Date.now(),bid:0,offer:0,spread:0,volume:0,trade:0,indexValue:0,openingPrice:0,closingPrice:0,settlementPrice:0,tradingSessionHighPrice:0,tradingSessionLowPrice:0,vwap:0,imbalance:0,openInterest:0,compositeUnderlyingPrice:0,simulatedSellPrice:0,simulatedBuyPrice:0,marginRate:0,midPrice:0,emptyBook:0,settleHighPrice:0,settleLowPrice:0,priorSettlePrice:0,sessionHighBid:0,sessionLowOffer:0,earlyPrices:0,auctionClearingPrice:0,swapValueFactor:0,dailyValueAdjustmentForLongPositions:0,cumulativeValueAdjustmentForLongPositions:0,dailyValueAdjustmentForShortPositions:0,cumulativeValueAdjustmentForShortPositions:0,fixingPrice:0,cashRate:0,recoveryRate:0,recoveryRateForLong:0,recoveryRateForShort:0,marketBid:0,marketOffer:0,shortSaleMinPrice:0,previousClosingPrice:0,thresholdLimitPriceBanding:0,dailyFinancingValue:0,accruedFinancingValue:0,twap:0};for(let f of i){let M=f.MDEntryType,d=f.MDEntryPx?Number.parseFloat(f.MDEntryPx):0,S=f.MDEntrySize?Number.parseFloat(f.MDEntrySize):0;switch(Ze(P,M)){case P.Bid:r.bid=d;break;case P.Offer:r.offer=d;break;case P.Trade:r.trade=d;break;case P.IndexValue:r.indexValue=d;break;case P.OpeningPrice:r.openingPrice=d;break;case P.ClosingPrice:r.closingPrice=d;break;case P.SettlementPrice:r.settlementPrice=d;break;case P.TradingSessionHighPrice:r.tradingSessionHighPrice=d;break;case P.TradingSessionLowPrice:r.tradingSessionLowPrice=d;break;case P.VWAP:r.vwap=d;break;case P.Imbalance:r.imbalance=S;break;case P.TradeVolume:r.volume=S;break;case P.OpenInterest:r.openInterest=S;break;case P.CompositeUnderlyingPrice:r.compositeUnderlyingPrice=d;break;case P.SimulatedSellPrice:r.simulatedSellPrice=d;break;case P.SimulatedBuyPrice:r.simulatedBuyPrice=d;break;case P.MarginRate:r.marginRate=d;break;case P.MidPrice:r.midPrice=d;break;case P.EmptyBook:r.emptyBook=1;break;case P.SettleHighPrice:r.settleHighPrice=d;break;case P.SettleLowPrice:r.settleLowPrice=d;break;case P.PriorSettlePrice:r.priorSettlePrice=d;break;case P.SessionHighBid:r.sessionHighBid=d;break;case P.SessionLowOffer:r.sessionLowOffer=d;break;case P.EarlyPrices:r.earlyPrices=d;break;case P.AuctionClearingPrice:r.auctionClearingPrice=d;break;case P.SwapValueFactor:r.swapValueFactor=d;break;case P.DailyValueAdjustmentForLongPositions:r.dailyValueAdjustmentForLongPositions=d;break;case P.CumulativeValueAdjustmentForLongPositions:r.cumulativeValueAdjustmentForLongPositions=d;break;case P.DailyValueAdjustmentForShortPositions:r.dailyValueAdjustmentForShortPositions=d;break;case P.CumulativeValueAdjustmentForShortPositions:r.cumulativeValueAdjustmentForShortPositions=d;break;case P.FixingPrice:r.fixingPrice=d;break;case P.CashRate:r.cashRate=d;break;case P.RecoveryRate:r.recoveryRate=d;break;case P.RecoveryRateForLong:r.recoveryRateForLong=d;break;case P.RecoveryRateForShort:r.recoveryRateForShort=d;break;case P.MarketBid:r.marketBid=d;break;case P.MarketOffer:r.marketOffer=d;break;case P.ShortSaleMinPrice:r.shortSaleMinPrice=d;break;case P.PreviousClosingPrice:r.previousClosingPrice=d;break;case P.ThresholdLimitPriceBanding:r.thresholdLimitPriceBanding=d;break;case P.DailyFinancingValue:r.dailyFinancingValue=d;break;case P.AccruedFinancingValue:r.accruedFinancingValue=d;break;case P.TWAP:r.twap=d;break}}r.spread=r.offer-r.bid,s.has(o)||s.set(o,[]);let h=s.get(o);h.push(r),h.length>l&&h.splice(0,h.length-l),a?.(o,r);let m=n.getField(ee.MDReqID)?.value;if(m){let f=e.get(m);f&&(f(n),e.delete(m))}}else if(c===te.ExecutionReport){let o=n.getField(ee.ClOrdID)?.value,u=e.get(o);u&&(u(n),e.delete(o))}}var ge=class extends De{verifiedOrders=new Map;pendingRequests=new Map;marketDataPrices=new Map;MAX_PRICE_HISTORY=1e5;server=new Te({name:"fixparser",version:"1.0.0"},{capabilities:{tools:Object.entries(ce).reduce((n,[t,{description:e,schema:s}])=>(n[t]={description:e,parameters:s},n),{})}});transport=new Ce;constructor({logger:n,onReady:t}){super({logger:n,onReady:t})}async register(n){this.parser=n,this.parser.addOnMessageCallback(t=>{_e(t,this.parser,this.pendingRequests,this.marketDataPrices,this.MAX_PRICE_HISTORY)}),this.addWorkflows(),await this.server.connect(this.transport),this.onReady&&this.onReady()}addWorkflows(){this.parser&&this.server&&(this.server.setRequestHandler(B.object({method:B.literal("tools/list")}),async()=>({tools:Object.entries(ce).map(([n,{description:t,schema:e}])=>({name:n,description:t,inputSchema:e}))})),this.server.setRequestHandler(B.object({method:B.literal("tools/call"),params:B.object({name:B.string(),arguments:B.any(),_meta:B.object({progressToken:B.number()}).optional()})}),async n=>{let{name:t,arguments:e}=n.params,l=Ye(this.parser,this.verifiedOrders,this.pendingRequests,this.marketDataPrices)[t];if(!l)return{content:[{type:"text",text:`Tool not found: ${t}`,uri:t}],isError:!0};let a=await l(e);return{content:a.content,isError:a.isError}}),process.on("SIGINT",async()=>{await this.server.close(),process.exit(0)}))}};var ot=async()=>{await rt.setLicenseKey(process.env.FIXPARSER_LICENSE_KEY);let n=process.env.FIXPARSER_SENDER||"SENDER",t=process.env.FIXPARSER_TARGET||"TARGET",e=new tt({logging:!0,logOptions:{level:"info",format:"jsonrpc",transport:new le({format:"jsonrpc"})},plugins:[new ge({port:3099,onReady:()=>{}})]}),s=()=>{let a=e.createMessage(new q(j.MsgType,nt.Logon),new q(j.MsgSeqNum,e.getNextTargetMsgSeqNum()),new q(j.SenderCompID,n),new q(j.SendingTime,e.getTimestamp()),new q(j.TargetCompID,t),new q(j.ResetSeqNumFlag,st.Yes),new q(j.EncryptMethod,et.None),new q(j.HeartBtInt,10));e.send(a)},l={host:process.env.FIXPARSER_HOST||"10.0.1.42",port:process.env.FIXPARSER_PORT?Number.parseInt(process.env.FIXPARSER_PORT,10):5001,protocol:"tcp",sender:n,target:t,fixVersion:"FIX.4.4",onOpen:()=>{e.logger.log({level:"info",message:"FIXParser logging in..."}),s()},onClose:()=>{e.logger.log({level:"info",message:"FIXParser disconnected. Reconnecting in 1 second..."}),setTimeout(()=>{e.connect(l)},1e3)}};e.connect(l)};ot().catch(n=>console.error("Error initializing server:",n));
|
|
19
18
|
//# sourceMappingURL=example_mcp_local.mjs.map
|