UNPKG

fixparser-plugin-mcp

Version:

FIXParser MCP Plugin (Local/Remote)

4 lines (3 loc) 65.7 kB
#!/usr/bin/env node import{EncryptMethod as pt,FIXParser as ft,Field as K,Fields as Q,LicenseManager as bt,Messages as yt,ResetSeqNumFlag as Pt}from"fixparser";var de=class{format;useStderr;constructor({format:h="json",useStderr:t=!1}){this.format=h,this.useStderr=t}configure(h){this.format=h.format||"json",h.useStderr!==void 0&&(this.useStderr=h.useStderr)}async send(h){let t=this.useStderr?console.error:console.log;if(this.format==="json")t(JSON.stringify(h));else if(this.format==="jsonrpc"){let{message:e,...n}=h,s={jsonrpc:"2.0",method:h.level,params:{message:e,...n},id:h.id||Date.now()};t(JSON.stringify(s))}else{let{name:e,id:n,message:s,level:i,...l}=h,r=Object.entries(l).map(([a,o])=>`${a}: ${o}`),c="";e&&(c+=`${e} `),c+=`${n}: ${s}`,t(c,r.join(", "))}}async flush(){}async close(){}status(){return"connected"}};import{randomUUID as ct}from"node:crypto";import{createServer as ut}from"node:http";import{McpServer as mt}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as ht}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{isInitializeRequest as dt}from"@modelcontextprotocol/sdk/types.js";import{z as H}from"zod";var ee=class{logger;parser;onReady=void 0;verifiedOrders=new Map;pendingRequests=new Map;marketDataPrices=new Map;MAX_PRICE_HISTORY=1e5;constructor({logger:t,onReady:e}){this.logger=t,this.onReady=e}};var ge={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"]}}};var X=class{static calculateRSI(t,e=14){if(t.length<e+1)return[];let n=[];for(let a=1;a<t.length;a++)n.push(t[a]-t[a-1]);let s=n.map(a=>a>0?a:0),i=n.map(a=>a<0?Math.abs(a):0),l=s.slice(0,e).reduce((a,o)=>a+o,0)/e,r=i.slice(0,e).reduce((a,o)=>a+o,0)/e,c=[];for(let a=e;a<n.length;a++){let o=l/r;c.push(100-100/(1+o)),l=(l*(e-1)+s[a])/e,r=(r*(e-1)+i[a])/e}return c}static calculateStochastic(t,e,n){let s=[];if(t.length<14)return[];let c=[];for(let o=13;o<t.length;o++){let u=Math.max(...e.slice(o-14+1,o+1)),m=Math.min(...n.slice(o-14+1,o+1)),f=(t[o]-m)/(u-m)*100;c.push(f)}let a=[];for(let o=2;o<c.length;o++){let u=c.slice(o-3+1,o+1).reduce((m,d)=>m+d,0);a.push(u/3)}for(let o=2;o<a.length;o++){let m=a.slice(o-3+1,o+1).reduce((d,f)=>d+f,0)/3;s.push({k:a[o],d:m})}return s}static calculateCCI(t,e,n){let s=[];if(t.length<20)return[];for(let l=19;l<t.length;l++){let c=t.slice(l-20+1,l+1).map((d,f)=>{let g=e[l-20+1+f]||d,b=n[l-20+1+f]||d;return(g+b+d)/3}),a=c.reduce((d,f)=>d+f,0)/20,o=c.reduce((d,f)=>d+Math.abs(f-a),0)/20,u=(e[l]+n[l]+t[l])/3,m=o!==0?(u-a)/(.015*o):0;s.push(m)}return s}static calculateROC(t){let e=[];for(let n=10;n<t.length;n++)e.push((t[n]-t[n-10])/t[n-10]*100);return e}static calculateWilliamsR(t){let e=[];if(t.length<14)return[];for(let s=13;s<t.length;s++){let i=t.slice(s-14+1,s+1),l=Math.max(...i),r=Math.min(...i),c=t[s],a=(l-c)/(l-r)*-100;e.push(a)}return e}static calculateMomentum(t){let e=[];for(let n=10;n<t.length;n++)e.push(t[n]-t[n-10]);return e}};var T=class{static calculateSMA(t,e){let n=[];for(let s=e-1;s<t.length;s++){let i=t.slice(s-e+1,s+1).reduce((l,r)=>l+r,0);n.push(i/e)}return n}static calculateEMA(t,e){let n=2/(e+1),s=[t[0]];for(let i=1;i<t.length;i++)s.push(t[i]*n+s[i-1]*(1-n));return s}static calculateWMA(t,e){let n=[],s=Array.from({length:e},(l,r)=>r+1),i=s.reduce((l,r)=>l+r,0);for(let l=e-1;l<t.length;l++){let r=0;for(let c=0;c<e;c++)r+=t[l-c]*s[c];n.push(r/i)}return n}static calculateVWMA(t,e,n){let s=[];for(let i=n-1;i<t.length;i++){let l=0,r=0;for(let c=0;c<n;c++){let a=e[i-c]||1;l+=a,r+=t[i-c]*a}s.push(r/l)}return s}};var j=class h{static calculateBlackScholes(t,e,n){let s=t,i=e,l=1,r=.05,c=n*.01,a=(Math.log(s/i)+(r+c*c/2)*l)/(c*Math.sqrt(l)),o=a-c*Math.sqrt(l),u=s*h.normalCDF(a)-i*Math.exp(-r*l)*h.normalCDF(o),m=i*Math.exp(-r*l)*h.normalCDF(-o)-s*h.normalCDF(-a);return{callPrice:u,putPrice:m,delta:h.normalCDF(a),gamma:h.normalPDF(a)/(s*c*Math.sqrt(l)),theta:-s*h.normalPDF(a)*c/(2*Math.sqrt(l))-r*i*Math.exp(-r*l)*h.normalCDF(o),vega:s*Math.sqrt(l)*h.normalPDF(a),rho:i*l*Math.exp(-r*l)*h.normalCDF(o)}}static calculateBinomialTree(t,e,n=1,s=.05,i=.2,l=100){let r=n/l,c=Math.exp(i*Math.sqrt(r)),a=1/c,o=(Math.exp(s*r)-a)/(c-a),u=[];for(let P=0;P<=l;P++){u[P]=[];for(let v=0;v<=P;v++)u[P][v]=t*c**v*a**(P-v)}let m=[];m[l]=[];for(let P=0;P<=l;P++){let v=Math.max(0,u[l][P]-e);m[l][P]=v}let d=[];d[l]=[];for(let P=0;P<=l;P++){let v=Math.max(0,e-u[l][P]);d[l][P]=v}for(let P=l-1;P>=0;P--){m[P]=[];for(let v=0;v<=P;v++){let S=m[P+1][v+1],x=m[P+1][v],F=Math.exp(-s*r)*(o*S+(1-o)*x);m[P][v]=Math.max(F,u[P][v]-e)}}for(let P=l-1;P>=0;P--){d[P]=[];for(let v=0;v<=P;v++){let S=d[P+1][v+1],x=d[P+1][v],F=Math.exp(-s*r)*(o*S+(1-o)*x);d[P][v]=Math.max(F,e-u[P][v])}}let f=m[0][0],g=d[0][0],b=(m[1][1]-m[1][0])/(u[1][1]-u[1][0]),y=((m[1][1]-m[1][0])/(u[1][1]-u[1][0])-(m[1][0]-m[1][0])/(u[1][0]-u[1][0]))/(u[1][1]-u[1][0]),I=(m[1][0]-m[0][0])/r,M=(f-f*1.01)/(i*.01),p=(f-f*1.01)/(s*.01);return{callPrice:f,putPrice:g,delta:b,gamma:y,theta:I,vega:M,rho:p}}static calculateTrinomialTree(t,e,n=1,s=.05,i=.2,l=50){let r=n/l,c=i*Math.sqrt(3*r),a=Math.exp(c),o=.5*((s-.5*i*i)*r/c+i*i*r/(c*c)),u=.5*((s-.5*i*i)*r/c-i*i*r/(c*c)),m=1-o-u,d=[];for(let S=0;S<=l;S++){d[S]=[];for(let x=0;x<=2*S+1;x++){let F=x-S;d[S][x]=t*a**F}}let f=[];f[l]=[];for(let S=0;S<=2*l;S++){let x=Math.max(0,d[l][S]-e);f[l][S]=x}let g=[];g[l]=[];for(let S=0;S<=2*l;S++){let x=Math.max(0,e-d[l][S]);g[l][S]=x}for(let S=l-1;S>=0;S--){f[S]=[];for(let x=0;x<=2*S;x++){let F=f[S+1][x+2],L=f[S+1][x+1],D=f[S+1][x],N=Math.exp(-s*r)*(o*F+m*L+u*D);f[S][x]=Math.max(N,d[S][x]-e)}}for(let S=l-1;S>=0;S--){g[S]=[];for(let x=0;x<=2*S;x++){let F=g[S+1][x+2],L=g[S+1][x+1],D=g[S+1][x],N=Math.exp(-s*r)*(o*F+m*L+u*D);g[S][x]=Math.max(N,e-d[S][x])}}let b=f[0][0],y=g[0][0],I=(f[1][2]-f[1][0])/(d[1][2]-d[1][0]),M=((f[1][2]-f[1][1])/(d[1][2]-d[1][1])-(f[1][1]-f[1][0])/(d[1][1]-d[1][0]))/(d[1][2]-d[1][0]),p=(f[1][1]-f[0][0])/r,P=(b-b*1.01)/(i*.01),v=(b-b*1.01)/(s*.01);return{callPrice:b,putPrice:y,delta:I,gamma:M,theta:p,vega:P,rho:v}}static calculateMonteCarlo(t,e,n=1,s=.05,i=.2,l=1e4){let r=0,c=0,a=0,o=0;for(let P=0;P<l;P++){let v=h.boxMuller(),S=t*Math.exp((s-.5*i*i)*n+i*Math.sqrt(n)*v),x=Math.max(0,S-e),F=Math.max(0,e-S);r+=x,c+=F,S>e&&(a+=1,o+=0)}let u=Math.exp(-s*n),m=r/l*u,d=c/l*u,f=a/l*u,g=o/l*u,b=-(m*s),y=(m-m*1.01)/(i*.01),I=(m-m*1.01)/(s*.01),M=Math.sqrt(m*(1-m)/l),p={lower:m-1.96*M,upper:m+1.96*M};return{callPrice:m,putPrice:d,delta:f,gamma:g,theta:b,vega:y,rho:I,confidenceInterval:p}}static calculateHestonModel(t,e,n=1,s=.05,i=.2,l=.2,r=2,c=.3,a=-.5){let o=t*.6-e*Math.exp(-s*n)*.4,u=o-t+e*Math.exp(-s*n),m=Math.sqrt(2*Math.PI/n)*(o/t)*(1+.5*(o/t)),d=.6,f=.01/t,g=-(o*s),b=o*Math.sqrt(n),y=e*n*Math.exp(-s*n)*.4;return{callPrice:o,putPrice:u,impliedVolatility:m,delta:d,gamma:f,theta:g,vega:b,rho:y}}static calculateSABRModel(t,e,n=1,s=.05,i=.2,l=.5,r=-.5,c=.3){let a=t,o=e,u=n,m=c/i*Math.log(a/o),d=Math.log((Math.sqrt(1-2*r*m+m*m)+m-r)/(1-r)),f;Math.abs(a-o)<1e-8?f=i/a**(1-l)*(1+((1-l)**2/24*i**2/a**(2-2*l)+r*l*i*c/(4*a**(1-l))+(2-3*r**2)*c**2/24)*u):f=i/(a*o)**((1-l)/2)*(1+((1-l)**2/24*i**2/(a*o)**(1-l)+r*l*i*c/(4*(a*o)**((1-l)/2))+(2-3*r**2)*c**2/24)*u)*m/d;let g=(Math.log(a/o)+(s+f*f/2)*u)/(f*Math.sqrt(u)),b=g-f*Math.sqrt(u),y=a*h.normalCDF(g)-o*Math.exp(-s*u)*h.normalCDF(b),I=o*Math.exp(-s*u)*h.normalCDF(-b)-a*h.normalCDF(-g),M=h.normalCDF(g),p=h.normalPDF(g)/(a*f*Math.sqrt(u)),P=-a*h.normalPDF(g)*f/(2*Math.sqrt(u))-s*o*Math.exp(-s*u)*h.normalCDF(b),v=a*Math.sqrt(u)*h.normalPDF(g),S=o*u*Math.exp(-s*u)*h.normalCDF(b);return{callPrice:y,putPrice:I,impliedVolatility:f,delta:M,gamma:p,theta:P,vega:v,rho:S}}static calculateVarianceGamma(t,e,n=1,s=.05,i=.2,l=-.1,r=.3){let c=t,a=e,o=n,u=s,m=c*.55-a*Math.exp(-u*o)*.45,d=m-c+a*Math.exp(-u*o),f=Math.sqrt(2*Math.PI/o)*(m/c)*(1+.5*(m/c)),g=.55,b=.01/c,y=-(m*u),I=m*Math.sqrt(o),M=a*o*Math.exp(-u*o)*.45;return{callPrice:m,putPrice:d,impliedVolatility:f,delta:g,gamma:b,theta:y,vega:I,rho:M}}static normalCDF(t){return .5*(1+h.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,n=-.284496736,s=1.421413741,i=-1.453152027,l=1.061405429,r=.3275911,c=t>=0?1:-1,a=Math.abs(t),o=1/(1+r*a),u=1-((((l*o+i)*o+s)*o+n)*o+e)*o*Math.exp(-a*a);return c*u}static boxMuller(){let t=Math.random(),e=Math.random();return Math.sqrt(-2*Math.log(t))*Math.cos(2*Math.PI*e)}};var U=class{static calculateMaxDrawdown(t){let e=t[0],n=0;for(let s=1;s<t.length;s++){t[s]>e&&(e=t[s]);let i=(e-t[s])/e;i>n&&(n=i)}return n}static calculateMaxConsecutiveLosses(t){let e=0,n=0;for(let s=1;s<t.length;s++)t[s]<t[s-1]?(n++,e=Math.max(e,n)):n=0;return e}static calculateWinRate(t){let e=0,n=0;for(let s=1;s<t.length;s++)t[s]!==t[s-1]&&(n++,t[s]>t[s-1]&&e++);return n>0?e/n:0}static calculateProfitFactor(t){let e=0,n=0;for(let s=1;s<t.length;s++){let i=t[s]-t[s-1];i>0?e+=i:n+=Math.abs(i)}return n>0?e/n:0}static calculateSharpeRatio(t,e=.02){if(t.length===0)return 0;let n=t.reduce((r,c)=>r+c,0)/t.length,s=n-e,i=t.reduce((r,c)=>r+(c-n)**2,0)/t.length,l=Math.sqrt(i);return l>0?s/l:0}static calculateSortinoRatio(t,e=.02){if(t.length===0)return 0;let n=t.reduce((c,a)=>c+a,0)/t.length,s=n-e,l=t.filter(c=>c<n).reduce((c,a)=>c+(a-n)**2,0)/t.length,r=Math.sqrt(l);return r>0?s/r:0}static calculateCalmarRatio(t,e){return e===0?0:t.reduce((s,i)=>s+i,0)/t.length/e}static calculatePositionSize(t,e){let n=Math.abs(t-e);return n>0?100/n:1}static calculateConfidence(t){return Math.min(t.length*10,100)}static calculateRiskLevel(t){return t<20?"LOW":t<40?"MEDIUM":"HIGH"}};var Y=class h{static generateSignals(t,e,n,s,i,l,r,c,a){let o=0,u=0,m=[];t>e?(m.push(`\u2713 BULLISH: Price above VWAP (+${((t-e)/e*100).toFixed(2)}%)`),o++):(m.push(`\u2717 BEARISH: Price below VWAP (${((t-e)/e*100).toFixed(2)}%)`),u++),n>0&&s>0?(m.push("\u2713 BULLISH: Positive momentum on both timeframes"),o++):n<0&&s<0?(m.push("\u2717 BEARISH: Negative momentum on both timeframes"),u++):m.push("\u25D0 MIXED: Conflicting momentum signals");let d=l/r;return d>1.2&&i>0?(m.push("\u2713 BULLISH: Above-average volume supporting upward move"),o++):d>1.2&&i<0?(m.push("\u2717 BEARISH: Above-average volume supporting downward move"),u++):m.push("\u25D0 NEUTRAL: Volume not providing clear direction"),c>65&&a>30?(m.push("\u2717 BEARISH: High in range with elevated volatility - reversal risk"),u++):c<35&&a>30?(m.push("\u2713 BULLISH: Low in range with volatility - potential bounce"),o++):m.push("\u25D0 NEUTRAL: Price position and volatility not extreme"),{bullishSignals:o,bearishSignals:u,signals:m}}static calculateOverallSignal(t,e,n,s){let i=t-e,l=i>0?"BULLISH_BIAS":i<0?"BEARISH_BIAS":"NEUTRAL",r=h.calculateConfidence(n),c=h.calculateRiskLevel(s);return{bullishSignals:t,bearishSignals:e,signals:n,overallSignal:l,signalScore:i,confidence:r,riskLevel:c}}static calculateConfidence(t){return Math.min(t.length*10,100)}static calculateRiskLevel(t){return t<20?"LOW":t<40?"MEDIUM":"HIGH"}};function A(h,t=500){if(h.length<=t)return h;let e=[],n=h.length/t;e.push(h[0]);for(let s=1;s<t-1;s++){let i=Math.floor(s*n),l=Math.floor((s+1)*n),r=h.slice(i,l);if(r.length===0)continue;let c=Math.floor(r.length/2);e.push(r[c])}return e.push(h[h.length-1]),e}var C=class{static calculateZScore(t,e){return(t-e)/(e*.1)}static calculateOrnsteinUhlenbeck(t,e,n,s){let i=e,l=.1;if(s.length>1){let c=s.reduce((a,o)=>a+o*o,0)/s.length;l=Math.max(.01,Math.min(1,c*10))}let r=n*.01;return{mean:i,speed:l,volatility:r,currentValue:t}}static calculateKalmanFilter(t,e,n,s){let i=n*.001,l=n*1e-4,r=e,c=i;if(s.length>0){let a=r,o=c+l,u=o/(o+i);return r=a+u*(t-a),c=(1-u)*o,{state:r,covariance:c,gain:u}}return{state:t,covariance:c,gain:.5}}static calculateARIMA(t,e){if(e.length<3)return{forecast:[t*1.01,t*1.02],residuals:[0,0],aic:100};let n=e.length,s=0,i=0,l=0,r=0;for(let b=1;b<n;b++){let y=e[b],I=e[b-1];s+=y,i+=I,l+=y*I,r+=I*I}let c=(n*l-s*i)/(n*r-i*i),a=(s-c*i)/n,o=[];for(let b=1;b<n;b++){let y=a+c*e[b-1];o.push(e[b]-y)}let u=o.reduce((b,y)=>b+y*y,0),m=n*Math.log(u/n)+2*2,d=e[e.length-1],f=t+(a+c*d),g=f+(a+c*(a+c*d));return{forecast:[f,g],residuals:A(o),aic:m}}static calculateGARCH(t,e){if(e.length<5)return{volatility:t*.01,persistence:.9,meanReversion:.1};let n=e.map(c=>c*c),s=n.reduce((c,a)=>c+a,0)/n.length,i=.9;if(n.length>1){let c=n.reduce((a,o)=>a+o,0)/n.length;i=Math.min(.99,Math.max(.5,c/s))}let l=s*(1-i);return{volatility:Math.sqrt(s),persistence:i,meanReversion:l}}static calculateVAR(t,e,n=2){if(t.length<n+5||e.length<n+5)return{priceForecast:[t[t.length-1]*1.01],volumeForecast:[e[e.length-1]*1.01],coefficients:[[.5,.3],[.2,.6]],residuals:[[0],[0]]};let s=[],i=[];for(let b=1;b<t.length;b++)s.push((t[b]-t[b-1])/t[b-1]),i.push((e[b]-e[b-1])/e[b-1]);let l=[],r=[],c=[];for(let b=n;b<s.length;b++){let y=[1];for(let I=1;I<=n;I++)y.push(s[b-I]),y.push(i[b-I]);l.push(y),r.push(s[b]),c.push(i[b])}let a=[[.5,.3,.2,.1],[.2,.1,.6,.3]],o=[],u=[];for(let b=0;b<r.length;b++){let y=a[0].reduce((M,p,P)=>M+p*l[b][P],0),I=a[1].reduce((M,p,P)=>M+p*l[b][P],0);o.push(r[b]-y),u.push(c[b]-I)}let m=s[s.length-1],d=i[i.length-1],f=[t[t.length-1]*(1+m*.5)],g=[e[e.length-1]*(1+d*.5)];return{priceForecast:f,volumeForecast:g,coefficients:a,residuals:[A(o),A(u)]}}static calculateGaussianProcess(t,e=5){if(t.length<10)return{mean:[t[t.length-1]*1.01,t[t.length-1]*1.02],variance:[.01,.02],confidenceInterval:{lower:[t[t.length-1]*.99,t[t.length-1]*.98],upper:[t[t.length-1]*1.03,t[t.length-1]*1.04]}};let n=[],s=[],i=[],l=[],r=t[t.length-1],c=Math.sqrt(t.reduce((a,o)=>a+(o-r)**2,0)/t.length);for(let a=1;a<=e;a++){let o=(t[t.length-1]-t[t.length-10])/10,u=r+o*a;n.push(u);let m=c*(1+a*.1);s.push(m);let d=1.96*m;i.push(u-d),l.push(u+d)}return{mean:n,variance:s,confidenceInterval:{lower:i,upper:l}}}static calculatePairsTrading(t,e){if(t.length<20||e.length<20)return{spread:[0],zScore:[0],hedgeRatio:1,entrySignal:"NEUTRAL",exitSignal:"NEUTRAL",position:"FLAT"};let n=Math.min(t.length,e.length),s=0,i=0,l=0,r=0;for(let y=0;y<n;y++)s+=t[y],i+=e[y],l+=t[y]*e[y],r+=t[y]*t[y];let c=(n*l-s*i)/(n*r-s*s),a=[];for(let y=0;y<n;y++)a.push(e[y]-c*t[y]);let o=a.reduce((y,I)=>y+I,0)/a.length,u=Math.sqrt(a.reduce((y,I)=>y+(I-o)**2,0)/a.length),m=[];for(let y=0;y<a.length;y++)m.push((a[y]-o)/u);let d=m[m.length-1],f="NEUTRAL",g="NEUTRAL",b="FLAT";return d>2?(f="SHORT_SPREAD",b="SHORT"):d<-2?(f="LONG_SPREAD",b="LONG"):Math.abs(d)<.5&&(g="CLOSE_POSITION",b="FLAT"),{spread:A(a),zScore:A(m),hedgeRatio:c,entrySignal:f,exitSignal:g,position:b}}static calculateHilbertTransform(t,e){if(e.length<10)return{analytic:[t],phase:[0],amplitude:[t]};let n=[],s=[],i=[],l=[t-e[e.length-1],t];l.push(...e.map(r=>t+r));for(let r=0;r<l.length;r++){let c=l[r],a=r>0?(l[r]-l[r-1])*.5:0;n.push(c+a),s.push(Math.atan2(a,c)),i.push(Math.sqrt(c*c+a*a))}return{analytic:A(n),phase:A(s),amplitude:A(i)}}static calculateWaveletTransform(t,e){if(e.length<8)return{coefficients:[t],scales:[1]};let n=[t,...e.map(l=>t+l)],s=[],i=[];for(let l=1;l<=Math.min(4,Math.floor(Math.log2(n.length)));l++){let r=2**(l-1);i.push(l);for(let c=0;c<n.length-r;c+=r*2)if(c+r<n.length){let a=(n[c]-n[c+r])/2;s.push(a)}}return{coefficients:A(s),scales:A(i)}}static calculateFourierTransform(t){if(t.length<8)return{frequencies:[.1,.2],amplitudes:[t[t.length-1],t[t.length-1]*.5],phases:[0,Math.PI/4],dominantFrequencies:[.1]};let e=t.length,n=[],s=[],i=[];for(let a=0;a<e;a++){let o=a/e;n.push(o);let u=0,m=0;for(let g=0;g<e;g++){let b=-2*Math.PI*a*g/e;u+=t[g]*Math.cos(b),m+=t[g]*Math.sin(b)}let d=Math.sqrt(u*u+m*m)/e,f=Math.atan2(m,u);s.push(d),i.push(f)}let r=[...s].sort((a,o)=>o-a)[Math.floor(e*.1)],c=n.filter((a,o)=>s[o]>r);return{frequencies:A(n),amplitudes:A(s),phases:A(i),dominantFrequencies:A(c)}}static calculateEMD(t){if(t.length<10)return{imfs:[t],residual:[0],frequencies:[.1]};let e=[],n=[...t];for(let l=0;l<3&&n.length>5;l++){let r=[...n],c=0,a=10;for(;c<a;){let o=[];for(let m=1;m<r.length-1;m++)(r[m]>r[m-1]&&r[m]>r[m+1]||r[m]<r[m-1]&&r[m]<r[m+1])&&o.push(r[m]);if(o.length<3)break;let u=o.map((m,d)=>d===0?o[0]:d===o.length-1?o[o.length-1]:(o[d-1]+o[d+1])/2);for(let m=0;m<r.length;m++){let d=Math.floor(m*o.length/r.length);r[m]-=u[Math.min(d,u.length-1)]}c++}e.push(A([...r]));for(let o=0;o<n.length;o++)n[o]-=r[o]}let s=A(n),i=A(e.map((l,r)=>.1/(r+1)));return{imfs:e,residual:s,frequencies:i}}};var J=class h{static calculatePivotPoints(t,e,n){let s=[];for(let i=0;i<t.length;i++){let l=e[i]||t[i],r=n[i]||t[i],c=t[i],a=(l+r+c)/3,o=2*a-r,u=2*a-l,m=a+(l-r),d=a-(l-r),f=l+2*(a-r),g=r-2*(l-a);s.push({pp:a,r1:o,r2:m,r3:f,s1:u,s2:d,s3:g})}return s}static calculateFibonacciPivotPoints(t,e,n){let s=[];for(let i=0;i<t.length;i++){let l=e[i]||t[i],r=n[i]||t[i],c=t[i],a=(l+r+c)/3,o=l-r,u=a+.382*o,m=a+.618*o,d=a+1*o,f=a-.382*o,g=a-.618*o,b=a-1*o;s.push({pp:a,r1:u,r2:m,r3:d,s1:f,s2:g,s3:b})}return s}static calculateCamarillaPivotPoints(t,e,n){let s=[];for(let i=0;i<t.length;i++){let l=e[i]||t[i],r=n[i]||t[i],c=t[i],a=(l+r+c)/3,o=l-r,u=c+1.1/12*o,m=c+1.1/6*o,d=c+1.1/4*o,f=c-1.1/12*o,g=c-1.1/6*o,b=c-1.1/4*o;s.push({pp:a,r1:u,r2:m,r3:d,s1:f,s2:g,s3:b})}return s}static calculateFibonacciLevels(t){let e=[];for(let n=0;n<t.length;n++){let s=t[n];e.push({retracement:{level0:s,level236:s*.764,level382:s*.618,level500:s*.5,level618:s*.382,level786:s*.214,level100:s*0},extension:{level1272:s*1.272,level1618:s*1.618,level2618:s*2.618,level4236:s*4.236}})}return e}static calculateGannLevels(t){let e=[];if(t.length===0)return[];if(t.length<=500){for(let i=0;i<t.length;i++)e.push(t[i]*(1+i*.01));return e}let n=t.length/500;e.push(t[0]*1.01);for(let i=1;i<499;i++){let l=Math.floor(i*n),r=Math.floor((i+1)*n),c=t.slice(l,r);if(c.length===0)continue;let a=Math.floor(c.length/2),u=c[a]*(1+(l+a)*.01);e.push(u)}let s=t.length-1;return e.push(t[s]*(1+s*.01)),e}static calculateElliottWave(t){let e=[];if(t.length<10)return[];for(let n=0;n<t.length;n++){let s=[],i=1,l=.5;if(n>=4){let r=t.slice(n-4,n+1),c=h.detectPriceSwings(r);c.length>=3&&(s.push(...c.slice(0,3)),i=Math.min(c.length,5),l=h.calculateWavePosition(r))}e.push({waves:s.length>0?s:[t[n]],currentWave:i,wavePosition:l})}return e}static detectPriceSwings(t){let e=[];for(let n=1;n<t.length-1;n++){let s=t[n-1],i=t[n],l=t[n+1];(i>s&&i>l||i<s&&i<l)&&e.push(i)}return e}static calculateWavePosition(t){if(t.length<2)return .5;let e=t[t.length-1],n=Math.min(...t),s=Math.max(...t);return s!==n?(e-n)/(s-n):.5}static calculateHarmonicPatterns(t){let e=[];if(t.length<5)return[];let n=[];for(let i=4;i<t.length;i++){let l=t.slice(i-4,i+1),r=h.detectHarmonicPattern(l);n.push(r)}if(n.length<=500)return n;let s=n.length/500;e.push(n[0]);for(let i=1;i<499;i++){let l=Math.floor(i*s),r=Math.floor((i+1)*s),c=n.slice(l,r);if(c.length===0)continue;let a=c.reduce((o,u)=>u.completion>o.completion?u:o);e.push(a)}return e.push(n[n.length-1]),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=h.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 n=e.slice(-5);if(n.length<5)return{type:"Unknown",completion:0,target:t[t.length-1]*1.1,stopLoss:t[t.length-1]*.9};let[s,i,l,r,c]=n,a=Math.abs(l-i),o=Math.abs(r-l),u=Math.abs(c-r),m=Math.abs(i-s),d=a/m,f=o/a,g=u/o;return h.isInRange(d,.618,.05)&&h.isInRange(f,.382,.05)&&h.isInRange(g,.886,.05)?{type:"Gartley",completion:h.calculatePatternCompletion(t),target:c+(c-r)*.618,stopLoss:c*.99}:h.isInRange(d,.382,.05)&&h.isInRange(f,.382,.05)&&h.isInRange(g,.886,.05)?{type:"Bat",completion:h.calculatePatternCompletion(t),target:c+(c-r)*.382,stopLoss:c*.99}:h.isInRange(d,.786,.05)&&h.isInRange(f,.382,.05)&&h.isInRange(g,1.618,.05)?{type:"Butterfly",completion:h.calculatePatternCompletion(t),target:c+(c-r)*1.618,stopLoss:c*.99}:h.isInRange(d,.382,.05)&&h.isInRange(f,.886,.05)&&h.isInRange(g,3.618,.1)?{type:"Crab",completion:h.calculatePatternCompletion(t),target:c+(c-r)*1.618,stopLoss:c*.99}:h.isInRange(d,.382,.05)&&h.isInRange(f,.113,.05)&&h.isInRange(g,Math.SQRT2,.05)?{type:"Cypher",completion:h.calculatePatternCompletion(t),target:c+(c-r)*.786,stopLoss:c*.99}:h.isInRange(d,.886,.05)&&h.isInRange(f,.886,.05)&&h.isInRange(g,1.13,.05)?{type:"Shark",completion:h.calculatePatternCompletion(t),target:c+(c-r)*1.13,stopLoss:c*.99}:{type:"Unknown",completion:0,target:t[t.length-1]*1.1,stopLoss:t[t.length-1]*.9}}static isInRange(t,e,n){return Math.abs(t-e)<=n}static calculatePatternCompletion(t){if(t.length<2)return 0;let e=t[t.length-1],n=Math.max(...t),s=Math.min(...t);if(n===s)return 50;let i=n-s,l=(e-s)/i;return Math.min(100,Math.max(0,l*100))}};var z=class{static calculateMACD(t){let e=T.calculateEMA(t,12),n=T.calculateEMA(t,26),s=[],i=[];for(let r=0;r<Math.min(e.length,n.length);r++)i.push(e[r]-n[r]);let l=T.calculateEMA(i,9);for(let r=0;r<Math.min(i.length,l.length);r++)s.push({macd:i[r],signal:l[r],histogram:i[r]-l[r]});return s}static calculateADX(t,e,n){if(t.length<14)return[];let s=14,i=[],l=[],r=[],c=[];l.push(e[0]-n[0]),r.push(0),c.push(0);for(let M=1;M<t.length;M++){let p=e[M]||t[M],P=n[M]||t[M],v=e[M-1]||t[M-1],S=n[M-1]||t[M-1],x=t[M-1],F=p-P,L=Math.abs(p-x),D=Math.abs(P-x);l.push(Math.max(F,L,D));let N=p-v,O=S-P;N>O&&N>0?(r.push(N),c.push(0)):O>N&&O>0?(r.push(0),c.push(O)):(r.push(0),c.push(0))}let a=[],o=[],u=[],m=0,d=0,f=0;for(let M=0;M<s;M++)m+=l[M],d+=r[M],f+=c[M];a.push(m),o.push(d),u.push(f);for(let M=s;M<l.length;M++){let p=a[a.length-1]-a[a.length-1]/s+l[M],P=o[o.length-1]-o[o.length-1]/s+r[M],v=u[u.length-1]-u[u.length-1]/s+c[M];a.push(p),o.push(P),u.push(v)}let g=[],b=[];for(let M=0;M<a.length;M++)g.push(o[M]/a[M]*100),b.push(u[M]/a[M]*100);let y=[];for(let M=0;M<g.length;M++){let p=g[M]+b[M],P=Math.abs(g[M]-b[M]);y.push(p>0?P/p*100:0)}if(y.length<s)return[];let I=0;for(let M=0;M<s;M++)I+=y[M];i.push(I/s);for(let M=s;M<y.length;M++){let p=i[i.length-1]-i[i.length-1]/s+y[M];i.push(p)}return i}static calculateDMI(t,e,n){if(t.length<14)return[];let s=14,i=[],l=[],r=[],c=[];l.push(e[0]-n[0]),r.push(0),c.push(0);for(let p=1;p<t.length;p++){let P=e[p]||t[p],v=n[p]||t[p],S=e[p-1]||t[p-1],x=n[p-1]||t[p-1],F=t[p-1],L=P-v,D=Math.abs(P-F),N=Math.abs(v-F);l.push(Math.max(L,D,N));let O=P-S,$=x-v;O>$&&O>0?(r.push(O),c.push(0)):$>O&&$>0?(r.push(0),c.push($)):(r.push(0),c.push(0))}let a=[],o=[],u=[],m=0,d=0,f=0;for(let p=0;p<s;p++)m+=l[p],d+=r[p],f+=c[p];a.push(m),o.push(d),u.push(f);for(let p=s;p<l.length;p++){let P=a[a.length-1]-a[a.length-1]/s+l[p],v=o[o.length-1]-o[o.length-1]/s+r[p],S=u[u.length-1]-u[u.length-1]/s+c[p];a.push(P),o.push(v),u.push(S)}let g=[],b=[];for(let p=0;p<a.length;p++)g.push(o[p]/a[p]*100),b.push(u[p]/a[p]*100);let y=[];for(let p=0;p<g.length;p++){let P=g[p]+b[p],v=Math.abs(g[p]-b[p]);y.push(P>0?v/P*100:0)}if(y.length<s)return[];let I=[],M=0;for(let p=0;p<s;p++)M+=y[p];I.push(M/s);for(let p=s;p<y.length;p++){let P=I[I.length-1]-I[I.length-1]/s+y[p];I.push(P)}for(let p=0;p<I.length;p++)i.push({plusDI:g[p+s-1]||0,minusDI:b[p+s-1]||0,adx:I[p]});return i}static calculateIchimoku(t,e,n){if(t.length<52)return[];let s=[],i=[];for(let u=8;u<t.length;u++){let m=Math.max(...e.slice(u-8,u+1)),d=Math.min(...n.slice(u-8,u+1));i.push((m+d)/2)}let l=[];for(let u=25;u<t.length;u++){let m=Math.max(...e.slice(u-25,u+1)),d=Math.min(...n.slice(u-25,u+1));l.push((m+d)/2)}let r=[];for(let u=0;u<Math.min(i.length,l.length);u++)r.push((i[u]+l[u])/2);let c=[];for(let u=51;u<t.length;u++){let m=Math.max(...e.slice(u-51,u+1)),d=Math.min(...n.slice(u-51,u+1));c.push((m+d)/2)}let a=[];for(let u=26;u<t.length;u++)a.push(t[u-26]);let o=Math.min(i.length,l.length,r.length,c.length,a.length);for(let u=0;u<o;u++)s.push({tenkan:i[u],kijun:l[u],senkouA:r[u],senkouB:c[u],chikou:a[u]});return s}static calculateParabolicSAR(t,e,n){if(t.length<2)return[];let s=[],i=.02,l=.2,r=n[0],c=!0,a=i,o=e[0];s.push(r);for(let u=1;u<t.length;u++){let m=e[u]||t[u],d=n[u]||t[u];if(c){if(d<r)c=!1,r=o,o=d,a=i;else if(m>o&&(o=m,a=Math.min(a+i,l)),r=r+a*(o-r),u>0){let f=n[u-1]||t[u-1];r=Math.min(r,f)}}else if(m>r)c=!0,r=o,o=m,a=i;else if(d<o&&(o=d,a=Math.min(a+i,l)),r=r+a*(o-r),u>0){let f=e[u-1]||t[u-1];r=Math.max(r,f)}s.push(r)}return s}};var G=class h{static calculateBollingerBands(t,e=20,n=2){if(t.length<e)return[];let s=T.calculateSMA(t,e),i=[];for(let l=0;l<s.length;l++){let r=t.slice(l,l+e),c=s[l],a=r.reduce((d,f)=>d+(f-c)**2,0)/e,o=Math.sqrt(a),u=c+o*n,m=c-o*n;i.push({upper:u,middle:c,lower:m,bandwidth:(u-m)/c*100,percentB:(t[l]-m)/(u-m)*100})}return i}static calculateATR(t,e,n){if(t.length<2)return[];let s=[];for(let l=1;l<t.length;l++){let r=e[l]||t[l],c=n[l]||t[l],a=t[l-1],o=r-c,u=Math.abs(r-a),m=Math.abs(c-a);s.push(Math.max(o,u,m))}let i=[];if(s.length>=14){let l=s.slice(0,14).reduce((r,c)=>r+c,0);i.push(l/14);for(let r=14;r<s.length;r++)l=l-s[r-14]+s[r],i.push(l/14)}return i}static calculateKeltnerChannels(t,e,n){let s=[];if(t.length<20)return[];let r=T.calculateEMA(t,20),c=h.calculateATR(t,e,n);for(let a=0;a<Math.min(r.length,c.length);a++){let o=r[a],u=c[a];s.push({upper:o+2*u,middle:o,lower:o-2*u})}return s}static calculateDonchianChannels(t){let e=[];for(let n=20;n<t.length;n++){let s=t.slice(n-20,n);e.push({upper:Math.max(...s),middle:(Math.max(...s)+Math.min(...s))/2,lower:Math.min(...s)})}return e}static calculateChaikinVolatility(t,e,n){let s=[];if(t.length<10*2)return[];let l=[];for(let c=0;c<t.length;c++){let a=e[c]||t[c],o=n[c]||t[c];l.push(a-o)}let r=T.calculateEMA(l,10);for(let c=10;c<r.length;c++){let a=r[c],o=r[c-10],u=o!==0?(a-o)/o*100:0;s.push(u)}return s}};var W=class{static calculateOBV(t,e){let n=[e[0]];for(let s=1;s<t.length;s++)t[s]>t[s-1]?n.push(n[s-1]+e[s]):t[s]<t[s-1]?n.push(n[s-1]-e[s]):n.push(n[s-1]);return n}static calculateCMF(t,e,n,s){let i=[];if(t.length<20)return[];for(let r=19;r<t.length;r++){let c=0,a=0;for(let u=r-20+1;u<=r;u++){let m=e[u]||t[u],d=n[u]||t[u],f=t[u],g=s[u]||1,y=(f-d-(m-f))/(m-d)*g;c+=y,a+=g}let o=a!==0?c/a:0;i.push(o)}return i}static calculateADL(t,e,n,s){let i=[0];for(let l=1;l<t.length;l++){let r=e[l]||t[l],c=n[l]||t[l],a=t[l],o=s[l]||1,m=(a-c-(r-a))/(r-c)*o;i.push(i[l-1]+m)}return i}static calculateVolumeROC(t){let e=[];for(let n=10;n<t.length;n++)e.push((t[n]-t[n-10])/t[n-10]*100);return e}static calculateMFI(t,e,n,s){let i=[];if(t.length<15)return[];for(let r=14;r<t.length;r++){let c=0,a=0;for(let m=r-14+1;m<=r;m++){let d=e[m]||t[m],f=n[m]||t[m],g=t[m],b=s[m]||1,y=(d+f+g)/3,I=y*b;if(m>r-14+1){let M=e[m-1]||t[m-1],p=n[m-1]||t[m-1],P=t[m-1],v=(M+p+P)/3;y>v?c+=I:y<v&&(a+=I)}}let u=100-100/(1+(a!==0?c/a:0));i.push(u)}return i}static calculateVWAP(t,e){let n=[],s=0,i=0;for(let l=0;l<t.length;l++)s+=t[l]*(e[l]||1),i+=e[l]||1,n.push(s/i);return n}};function tt(h){return h.reduce((t,e)=>t+e,0)}var se=class{prices;volumes;highs;lows;constructor(t){this.prices=t.map(e=>e.trade>0?e.trade:e.midPrice),this.volumes=t.map(e=>e.volume),this.highs=t.map(e=>e.tradingSessionHighPrice>0?e.tradingSessionHighPrice:e.trade),this.lows=t.map(e=>e.tradingSessionLowPrice>0?e.tradingSessionLowPrice:e.trade)}calculatePriceChanges(){let t=[];for(let e=1;e<this.prices.length;e++)t.push((this.prices[e]-this.prices[e-1])/this.prices[e-1]);return t}analyze(){let t=this.prices[this.prices.length-1],e=this.prices[0],n=Math.max(...this.highs),s=Math.min(...this.lows),i=tt(this.volumes),l=i/this.volumes.length,r=this.calculatePriceChanges(),c=r.length>0?Math.sqrt(r.reduce((F,L)=>F+L**2,0)/r.length)*Math.sqrt(252)*100:0,a=(t-e)/e*100,o=(t-s)/(n-s)*100,u=this.prices.reduce((F,L,D)=>F+L*this.volumes[D],0)/i,m=this.prices.length>5?(t-this.prices[Math.max(0,this.prices.length-6)])/this.prices[Math.max(0,this.prices.length-6)]*100:0,d=this.prices.length>10?(t-this.prices[Math.max(0,this.prices.length-11)])/this.prices[Math.max(0,this.prices.length-11)]*100:0,f=U.calculateMaxDrawdown(this.prices),g=G.calculateATR(this.prices,this.highs,this.lows),b=g.length>0?g[g.length-1]:0,y=c,I=c,M=a/c,p=a/I,P=a/f,v=U.calculateMaxConsecutiveLosses(this.prices),S=U.calculateWinRate(this.prices),x=U.calculateProfitFactor(this.prices);return{currentPrice:t,startPrice:e,sessionHigh:n,sessionLow:s,totalVolume:i,avgVolume:l,volatility:c,sessionReturn:a,pricePosition:o,trueVWAP:u,momentum5:m,momentum10:d,maxDrawdown:f,atr:b,impliedVolatility:y,realizedVolatility:I,sharpeRatio:M,sortinoRatio:p,calmarRatio:P,maxConsecutiveLosses:v,winRate:S,profitFactor:x}}getTechnicalIndicators(){return{sma5:T.calculateSMA(this.prices,5),sma10:T.calculateSMA(this.prices,10),sma20:T.calculateSMA(this.prices,20),sma50:T.calculateSMA(this.prices,50),sma200:T.calculateSMA(this.prices,200),ema8:T.calculateEMA(this.prices,8),ema12:T.calculateEMA(this.prices,12),ema21:T.calculateEMA(this.prices,21),ema26:T.calculateEMA(this.prices,26),wma20:T.calculateWMA(this.prices,20),vwma20:T.calculateVWMA(this.prices,this.volumes,20),macd:z.calculateMACD(this.prices),adx:z.calculateADX(this.prices,this.highs,this.lows),dmi:z.calculateDMI(this.prices,this.highs,this.lows),ichimoku:z.calculateIchimoku(this.prices,this.highs,this.lows),parabolicSAR:z.calculateParabolicSAR(this.prices,this.highs,this.lows),rsi:X.calculateRSI(this.prices,14),stochastic:X.calculateStochastic(this.prices,this.highs,this.lows),cci:X.calculateCCI(this.prices,this.highs,this.lows),roc:X.calculateROC(this.prices),williamsR:X.calculateWilliamsR(this.prices),momentum:X.calculateMomentum(this.prices),bollinger:G.calculateBollingerBands(this.prices,20,2),atr:G.calculateATR(this.prices,this.highs,this.lows),keltner:G.calculateKeltnerChannels(this.prices,this.highs,this.lows),donchian:G.calculateDonchianChannels(this.prices),chaikinVolatility:G.calculateChaikinVolatility(this.prices,this.highs,this.lows),obv:W.calculateOBV(this.prices,this.volumes),cmf:W.calculateCMF(this.prices,this.highs,this.lows,this.volumes),adl:W.calculateADL(this.prices,this.highs,this.lows,this.volumes),volumeROC:W.calculateVolumeROC(this.volumes),mfi:W.calculateMFI(this.prices,this.highs,this.lows,this.volumes),vwap:W.calculateVWAP(this.prices,this.volumes),pivotPoints:J.calculatePivotPoints(this.prices,this.highs,this.lows),fibonacci:J.calculateFibonacciLevels(this.prices),gannLevels:J.calculateGannLevels(this.prices),elliottWave:J.calculateElliottWave(this.prices),harmonicPatterns:J.calculateHarmonicPatterns(this.prices)}}generateJSONAnalysis(t){let e=this.analyze(),n=this.getTechnicalIndicators(),s=this.calculatePriceChanges(),i=n.sma5.length>0?n.sma5[n.sma5.length-1]:null,l=n.sma10.length>0?n.sma10[n.sma10.length-1]:null,r=n.sma20.length>0?n.sma20[n.sma20.length-1]:null,c=n.sma50.length>0?n.sma50[n.sma50.length-1]:null,a=n.sma200.length>0?n.sma200[n.sma200.length-1]:null,o=n.ema8[n.ema8.length-1],u=n.ema12[n.ema12.length-1],m=n.ema21[n.ema21.length-1],d=n.ema26[n.ema26.length-1],f=n.wma20.length>0?n.wma20[n.wma20.length-1]:null,g=n.vwma20.length>0?n.vwma20[n.vwma20.length-1]:null,b=n.macd.length>0?n.macd[n.macd.length-1]:null,y=n.adx.length>0?n.adx[n.adx.length-1]:null,I=n.dmi.length>0?n.dmi[n.dmi.length-1]:null,M=n.ichimoku.length>0?n.ichimoku[n.ichimoku.length-1]:null,p=n.parabolicSAR.length>0?n.parabolicSAR[n.parabolicSAR.length-1]:null,P=n.rsi.length>0?n.rsi[n.rsi.length-1]:null,v=n.stochastic.length>0?n.stochastic[n.stochastic.length-1]:null,S=n.cci.length>0?n.cci[n.cci.length-1]:null,x=n.roc.length>0?n.roc[n.roc.length-1]:null,F=n.williamsR.length>0?n.williamsR[n.williamsR.length-1]:null,L=n.momentum.length>0?n.momentum[n.momentum.length-1]:null,D=n.bollinger.length>0?n.bollinger[n.bollinger.length-1]:null,N=n.atr.length>0?n.atr[n.atr.length-1]:null,O=n.keltner.length>0?n.keltner[n.keltner.length-1]:null,$=n.donchian.length>0?n.donchian[n.donchian.length-1]:null,Te=n.chaikinVolatility.length>0?n.chaikinVolatility[n.chaikinVolatility.length-1]:null,le=n.obv.length>0?n.obv[n.obv.length-1]:null,ce=n.cmf.length>0?n.cmf[n.cmf.length-1]:null,Fe=n.adl.length>0?n.adl[n.adl.length-1]:null,Ae=n.volumeROC.length>0?n.volumeROC[n.volumeROC.length-1]:null,ue=n.mfi.length>0?n.mfi[n.mfi.length-1]:null,De=n.vwap.length>0?n.vwap[n.vwap.length-1]:null,Ce=n.pivotPoints.length>0?n.pivotPoints[n.pivotPoints.length-1]:null,Oe=n.fibonacci.length>0?n.fibonacci[n.fibonacci.length-1]:null,ke=n.gannLevels.length>0?n.gannLevels:[],Ve=n.elliottWave.length>0?n.elliottWave[n.elliottWave.length-1]:null,Le=n.harmonicPatterns.length>0?n.harmonicPatterns:[],ne=this.volumes[this.volumes.length-1],Ee=ne/e.avgVolume,Be=(e.sessionHigh-e.currentPrice)/e.sessionHigh*100,He=(e.sessionHigh-e.sessionLow)/e.sessionLow*100,Ne=(e.currentPrice-e.trueVWAP)/e.trueVWAP*100,re=Y.generateSignals(e.currentPrice,e.trueVWAP,e.momentum5,e.momentum10,e.sessionReturn,ne,e.avgVolume,e.pricePosition,e.volatility),qe=Y.calculateOverallSignal(re.bullishSignals,re.bearishSignals,re.signals,e.volatility),oe=Math.max(e.sessionLow*1.005,e.trueVWAP*.998),_=e.sessionLow*.995,me=e.sessionHigh*.995,je=(me-e.currentPrice)/(e.currentPrice-_),he=U.calculatePositionSize(oe,_),Xe=he*(oe-_),Ge=C.calculateVAR(this.prices,this.volumes),We=C.calculateGaussianProcess(this.prices),$e=C.calculatePairsTrading(this.prices,this.prices.map(et=>et*1.01)),Ue=C.calculateFourierTransform(this.prices),Je=C.calculateEMD(this.prices),q=j.calculateBlackScholes(e.currentPrice,e.startPrice,e.avgVolume),ze=j.calculateBinomialTree(e.currentPrice,e.startPrice),Ke=j.calculateTrinomialTree(e.currentPrice,e.startPrice),Qe=j.calculateMonteCarlo(e.currentPrice,e.startPrice),Ye=j.calculateHestonModel(e.currentPrice,e.startPrice),Ze=j.calculateSABRModel(e.currentPrice,e.startPrice),_e=j.calculateVarianceGamma(e.currentPrice,e.startPrice);return{symbol:t,timestamp:new Date().toISOString(),marketStructure:{currentPrice:e.currentPrice,startPrice:e.startPrice,sessionHigh:e.sessionHigh,sessionLow:e.sessionLow,rangeWidth:He,totalVolume:e.totalVolume,sessionPerformance:e.sessionReturn,positionInRange:e.pricePosition},volatility:{impliedVolatility:e.impliedVolatility,realizedVolatility:e.realizedVolatility,atr:e.atr,maxDrawdown:e.maxDrawdown*100,currentDrawdown:Be},technicalIndicators:{sma5:i,sma10:l,sma20:r,sma50:c,sma200:a,ema8:o,ema12:u,ema21:m,ema26:d,wma20:f,vwma20:g,macd:b,adx:y,dmi:I,ichimoku:M,parabolicSAR:p,rsi:P,stochastic:v,cci:S,roc:x,williamsR:F,momentum:L,bollingerBands:D?{upper:D.upper,middle:D.middle,lower:D.lower,bandwidth:D.bandwidth,percentB:D.percentB}:null,atr:N,keltnerChannels:O?{upper:O.upper,middle:O.middle,lower:O.lower}:null,donchianChannels:$?{upper:$.upper,middle:$.middle,lower:$.lower}:null,chaikinVolatility:Te,obv:le,cmf:ce,adl:Fe,volumeROC:Ae,mfi:ue,vwap:De},volumeAnalysis:{currentVolume:ne,averageVolume:Math.round(e.avgVolume),volumeRatio:Ee,trueVWAP:e.trueVWAP,priceVsVWAP:Ne,obv:le,cmf:ce,mfi:ue},momentum:{momentum5:e.momentum5,momentum10:e.momentum10,sessionROC:e.sessionReturn,rsi:P,stochastic:v,cci:S},supportResistance:{pivotPoints:Ce,fibonacci:Oe,gannLevels:ke,elliottWave:Ve,harmonicPatterns:Le},tradingSignals:qe,statisticalModels:{zScore:C.calculateZScore(e.currentPrice,e.startPrice),ornsteinUhlenbeck:C.calculateOrnsteinUhlenbeck(e.currentPrice,e.startPrice,e.avgVolume,s),kalmanFilter:C.calculateKalmanFilter(e.currentPrice,e.startPrice,e.avgVolume,s),pairsTrading:$e,arima:C.calculateARIMA(e.currentPrice,s),garch:C.calculateGARCH(e.avgVolume,s),var:Ge,gaussianProcess:We,hilbertTransform:C.calculateHilbertTransform(e.currentPrice,s),waveletTransform:C.calculateWaveletTransform(e.currentPrice,s),fourierTransform:Ue,empiricalModeDecomposition:Je},optionsAnalysis:q?{blackScholes:q,binomialTree:ze,trinomialTree:Ke,monteCarlo:Qe,hestonModel:Ye,sabrModel:Ze,varianceGamma:_e,impliedVolatility:e.impliedVolatility,delta:q.delta,gamma:q.gamma,theta:q.theta,vega:q.vega,rho:q.rho,greeks:{delta:q.delta,gamma:q.gamma,theta:q.theta,vega:q.vega,rho:q.rho}}:null,riskManagement:{targetEntry:oe,stopLoss:_,profitTarget:me,riskRewardRatio:je,positionSize:he,maxRisk:Xe},performance:{sharpeRatio:e.sharpeRatio,sortinoRatio:e.sortinoRatio,calmarRatio:e.calmarRatio,maxDrawdown:e.maxDrawdown*100,winRate:e.winRate,profitFactor:e.profitFactor,totalReturn:e.sessionReturn,volatility:e.volatility}}}},pe=h=>async t=>{try{let e=t.symbol,n=h.get(e)||[];if(n.length===0)return{content:[{type:"text",text:`No price data available for ${e}. Please request market data first.`,uri:"technicalAnalysis"}]};if(!n.every(r=>typeof r.trade=="number"&&!Number.isNaN(r.trade)&&typeof r.midPrice=="number"&&!Number.isNaN(r.midPrice)))throw new Error("Invalid market data");let l=new se(n).generateJSONAnalysis(e);return{content:[{type:"text",text:`Technical Analysis for ${e}: ${JSON.stringify(l,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}}};import{Field as E,Fields as B,MDEntryType as w,Messages as nt}from"fixparser";import rt from"quickchart-js";var fe=(h,t)=>async e=>{try{h.logger.log({level:"info",message:`Sending market data request for symbols: ${e.symbols.join(", ")}`});let n=new Promise(c=>{t.set(e.mdReqID,c),h.logger.log({level:"info",message:`Registered callback for market data request ID: ${e.mdReqID}`})}),s=e.mdEntryTypes||[w.Bid,w.Offer,w.Trade,w.IndexValue,w.OpeningPrice,w.ClosingPrice,w.SettlementPrice,w.TradingSessionHighPrice,w.TradingSessionLowPrice,w.VWAP,w.Imbalance,w.TradeVolume,w.OpenInterest,w.CompositeUnderlyingPrice,w.SimulatedSellPrice,w.SimulatedBuyPrice,w.MarginRate,w.MidPrice,w.EmptyBook,w.SettleHighPrice,w.SettleLowPrice,w.PriorSettlePrice,w.SessionHighBid,w.SessionLowOffer,w.EarlyPrices,w.AuctionClearingPrice,w.SwapValueFactor,w.DailyValueAdjustmentForLongPositions,w.CumulativeValueAdjustmentForLongPositions,w.DailyValueAdjustmentForShortPositions,w.CumulativeValueAdjustmentForShortPositions,w.FixingPrice,w.CashRate,w.RecoveryRate,w.RecoveryRateForLong,w.RecoveryRateForShort,w.MarketBid,w.MarketOffer,w.ShortSaleMinPrice,w.PreviousClosingPrice,w.ThresholdLimitPriceBanding,w.DailyFinancingValue,w.AccruedFinancingValue,w.TWAP],i=[new E(B.MsgType,nt.MarketDataRequest),new E(B.SenderCompID,h.sender),new E(B.MsgSeqNum,h.getNextTargetMsgSeqNum()),new E(B.TargetCompID,h.target),new E(B.SendingTime,h.getTimestamp()),new E(B.MDReqID,e.mdReqID),new E(B.SubscriptionRequestType,e.subscriptionRequestType),new E(B.MarketDepth,0),new E(B.MDUpdateType,e.mdUpdateType)];i.push(new E(B.NoRelatedSym,e.symbols.length)),e.symbols.forEach(c=>{i.push(new E(B.Symbol,c))}),i.push(new E(B.NoMDEntryTypes,s.length)),s.forEach(c=>{i.push(new E(B.MDEntryType,c))});let l=h.createMessage(...i);if(!h.connected)return h.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};h.logger.log({level:"info",message:`Sending market data request message: ${JSON.stringify(l?.toFIXJSON())}`}),h.send(l);let r=await n;return h.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(r.toFIXJSON())}`,uri:"marketDataRequest"}]}}catch(n){return{content:[{type:"text",text:`Error: ${n instanceof Error?n.message:"Failed to request market data"}`,uri:"marketDataRequest"}],isError:!0}}},be=(h,t=240)=>{if(h.length<=t)return h;let e=[],n=h.length/t;e.push(h[0]);for(let s=1;s<t-1;s++){let i=Math.floor(s*n),l=Math.floor((s+1)*n),r=h.slice(i,l);if(r.length===0)continue;let c={timestamp:r[0].timestamp,bid:r.reduce((a,o)=>a+o.bid,0)/r.length,offer:r.reduce((a,o)=>a+o.offer,0)/r.length,spread:r.reduce((a,o)=>a+o.spread,0)/r.length,volume:r.reduce((a,o)=>a+o.volume,0)/r.length,trade:r.reduce((a,o)=>a+o.trade,0)/r.length,indexValue:r.reduce((a,o)=>a+o.indexValue,0)/r.length,openingPrice:r.reduce((a,o)=>a+o.openingPrice,0)/r.length,closingPrice:r.reduce((a,o)=>a+o.closingPrice,0)/r.length,settlementPrice:r.reduce((a,o)=>a+o.settlementPrice,0)/r.length,tradingSessionHighPrice:r.reduce((a,o)=>a+o.tradingSessionHighPrice,0)/r.length,tradingSessionLowPrice:r.reduce((a,o)=>a+o.tradingSessionLowPrice,0)/r.length,vwap:r.reduce((a,o)=>a+o.vwap,0)/r.length,imbalance:r.reduce((a,o)=>a+o.imbalance,0)/r.length,openInterest:r.reduce((a,o)=>a+o.openInterest,0)/r.length,compositeUnderlyingPrice:r.reduce((a,o)=>a+o.compositeUnderlyingPrice,0)/r.length,simulatedSellPrice:r.reduce((a,o)=>a+o.simulatedSellPrice,0)/r.length,simulatedBuyPrice:r.reduce((a,o)=>a+o.simulatedBuyPrice,0)/r.length,marginRate:r.reduce((a,o)=>a+o.marginRate,0)/r.length,midPrice:r.reduce((a,o)=>a+o.midPrice,0)/r.length,emptyBook:r.reduce((a,o)=>a+o.emptyBook,0)/r.length,settleHighPrice:r.reduce((a,o)=>a+o.settleHighPrice,0)/r.length,settleLowPrice:r.reduce((a,o)=>a+o.settleLowPrice,0)/r.length,priorSettlePrice:r.reduce((a,o)=>a+o.priorSettlePrice,0)/r.length,sessionHighBid:r.reduce((a,o)=>a+o.sessionHighBid,0)/r.length,sessionLowOffer:r.reduce((a,o)=>a+o.sessionLowOffer,0)/r.length,earlyPrices:r.reduce((a,o)=>a+o.earlyPrices,0)/r.length,auctionClearingPrice:r.reduce((a,o)=>a+o.auctionClearingPrice,0)/r.length,swapValueFactor:r.reduce((a,o)=>a+o.swapValueFactor,0)/r.length,dailyValueAdjustmentForLongPositions:r.reduce((a,o)=>a+o.dailyValueAdjustmentForLongPositions,0)/r.length,cumulativeValueAdjustmentForLongPositions:r.reduce((a,o)=>a+o.cumulativeValueAdjustmentForLongPositions,0)/r.length,dailyValueAdjustmentForShortPositions:r.reduce((a,o)=>a+o.dailyValueAdjustmentForShortPositions,0)/r.length,cumulativeValueAdjustmentForShortPositions:r.reduce((a,o)=>a+o.cumulativeValueAdjustmentForShortPositions,0)/r.length,fixingPrice:r.reduce((a,o)=>a+o.fixingPrice,0)/r.length,cashRate:r.reduce((a,o)=>a+o.cashRate,0)/r.length,recoveryRate:r.reduce((a,o)=>a+o.recoveryRate,0)/r.length,recoveryRateForLong:r.reduce((a,o)=>a+o.recoveryRateForLong,0)/r.length,recoveryRateForShort:r.reduce((a,o)=>a+o.recoveryRateForShort,0)/r.length,marketBid:r.reduce((a,o)=>a+o.marketBid,0)/r.length,marketOffer:r.reduce((a,o)=>a+o.marketOffer,0)/r.length,shortSaleMinPrice:r.reduce((a,o)=>a+o.shortSaleMinPrice,0)/r.length,previousClosingPrice:r.reduce((a,o)=>a+o.previousClosingPrice,0)/r.length,thresholdLimitPriceBanding:r.reduce((a,o)=>a+o.thresholdLimitPriceBanding,0)/r.length,dailyFinancingValue:r.reduce((a,o)=>a+o.dailyFinancingValue,0)/r.length,accruedFinancingValue:r.reduce((a,o)=>a+o.accruedFinancingValue,0)/r.length,twap:r.reduce((a,o)=>a+o.twap,0)/r.length};e.push(c)}return e.push(h[h.length-1]),e},ye=h=>async t=>{try{let e=t.symbol,n=h.get(e)||[];if(n.length===0)return{content:[{type:"text",text:`No price data available for ${e}`,uri:"getStockGraph"}]};let s=be(n,500),i=new rt;i.setWidth(1200),i.setHeight(600),i.setBackgroundColor("transparent");let l=s.map(p=>new Date(p.timestamp).toLocaleTimeString()),r=s.map(p=>p.bid),c=s.map(p=>p.offer),a=s.map(p=>p.spread),o=s.map(p=>p.volume),u=s.map(p=>p.trade),m=s.map(p=>p.vwap),d=s.map(p=>p.twap),f=Math.max(...o.filter(p=>p>0)),g=Math.max(...r,...c,...u,...m,...d),b=o.map(p=>p/f*g*.3),y={type:"line",data:{labels:l,datasets:[{label:"Bid",data:r,borderColor:"#28a745",backgroundColor:"rgba(40, 167, 69, 0.1)",fill:!1,tension:.4},{label:"Offer",data:c,borderColor:"#dc3545",backgroundColor:"rgba(220, 53, 69, 0.1)",fill:!1,tension:.4},{label:"Spread",data:a,borderColor:"#6c757d",backgroundColor:"rgba(108, 117, 125, 0.1)",fill:!1,tension:.4},{label:"Trade",data:u,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:d,borderColor:"#6610f2",backgroundColor:"rgba(102, 16, 242, 0.1)",fill:!1,tension:.4},{label:"Volume (Normalized)",data:b,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:{