fixparser-plugin-mcp 9.2.3-ab08e099 → 9.2.3-d736ab12
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/RemoteServer.js +4 -4
- package/build/cjs/RemoteServer.js.map +3 -3
- package/build/cjs/StdioServer.js +1 -1
- package/build/cjs/StdioServer.js.map +2 -2
- package/build/esm/RemoteServer.mjs +4 -4
- package/build/esm/RemoteServer.mjs.map +3 -3
- package/build/esm/StdioServer.mjs +1 -1
- package/build/esm/StdioServer.mjs.map +2 -2
- package/package.json +1 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var tt=Object.create;var ie=Object.defineProperty;var nt=Object.getOwnPropertyDescriptor;var rt=Object.getOwnPropertyNames;var ot=Object.getPrototypeOf,st=Object.prototype.hasOwnProperty;var at=(m,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of rt(t))!st.call(m,o)&&o!==e&&ie(m,o,{get:()=>t[o],enumerable:!(n=nt(t,o))||n.enumerable});return m};var it=(m,t,e)=>(e=m!=null?tt(ot(m)):{},at(t||!m||!m.__esModule?ie(e,"default",{value:m,enumerable:!0}):e,m));var F=require("fixparser");var le=class{format;useStderr;constructor({format:m="json",useStderr:t=!1}){this.format=m,this.useStderr=t}configure(m){this.format=m.format||"json",m.useStderr!==void 0&&(this.useStderr=m.useStderr)}async send(m){let t=this.useStderr?console.error:console.log;if(this.format==="json")t(JSON.stringify(m));else if(this.format==="jsonrpc"){let{message:e,...n}=m,o={jsonrpc:"2.0",method:m.level,params:{message:e,...n}};t(JSON.stringify(o))}else{let{name:e,id:n,message:o,level:i,...l}=m,r=Object.entries(l).map(([a,s])=>`${a}: ${s}`),c="";e&&(c+=`${e} `),c+=`${n}: ${o}`,t(c,r.join(", "))}}async flush(){}async close(){}status(){return"connected"}};var ve=require("node:crypto"),Ie=require("node:http"),Re=require("@modelcontextprotocol/sdk/server/mcp.js"),we=require("@modelcontextprotocol/sdk/server/streamableHttp.js"),xe=require("@modelcontextprotocol/sdk/types.js"),L=require("zod");var Q=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 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"]}}};var q=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 o=n.map(a=>a>0?a:0),i=n.map(a=>a<0?Math.abs(a):0),l=o.slice(0,e).reduce((a,s)=>a+s,0)/e,r=i.slice(0,e).reduce((a,s)=>a+s,0)/e,c=[];for(let a=e;a<n.length;a++){let s=l/r;c.push(100-100/(1+s)),l=(l*(e-1)+o[a])/e,r=(r*(e-1)+i[a])/e}return c}static calculateStochastic(t,e,n){let o=[];if(t.length<14)return[];let c=[];for(let s=13;s<t.length;s++){let u=Math.max(...e.slice(s-14+1,s+1)),h=Math.min(...n.slice(s-14+1,s+1)),f=(t[s]-h)/(u-h)*100;c.push(f)}let a=[];for(let s=2;s<c.length;s++){let u=c.slice(s-3+1,s+1).reduce((h,d)=>h+d,0);a.push(u/3)}for(let s=2;s<a.length;s++){let h=a.slice(s-3+1,s+1).reduce((d,f)=>d+f,0)/3;o.push({k:a[s],d:h})}return o}static calculateCCI(t,e,n){let o=[];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,s=c.reduce((d,f)=>d+Math.abs(f-a),0)/20,u=(e[l]+n[l]+t[l])/3,h=s!==0?(u-a)/(.015*s):0;o.push(h)}return o}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 o=13;o<t.length;o++){let i=t.slice(o-14+1,o+1),l=Math.max(...i),r=Math.min(...i),c=t[o],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 A=class{static calculateSMA(t,e){let n=[];for(let o=e-1;o<t.length;o++){let i=t.slice(o-e+1,o+1).reduce((l,r)=>l+r,0);n.push(i/e)}return n}static calculateEMA(t,e){let n=2/(e+1),o=[t[0]];for(let i=1;i<t.length;i++)o.push(t[i]*n+o[i-1]*(1-n));return o}static calculateWMA(t,e){let n=[],o=Array.from({length:e},(l,r)=>r+1),i=o.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]*o[c];n.push(r/i)}return n}static calculateVWMA(t,e,n){let o=[];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}o.push(r/l)}return o}};var N=class m{static calculateBlackScholes(t,e,n){let o=t,i=e,l=1,r=.05,c=n*.01,a=(Math.log(o/i)+(r+c*c/2)*l)/(c*Math.sqrt(l)),s=a-c*Math.sqrt(l),u=o*m.normalCDF(a)-i*Math.exp(-r*l)*m.normalCDF(s),h=i*Math.exp(-r*l)*m.normalCDF(-s)-o*m.normalCDF(-a);return{callPrice:u,putPrice:h,delta:m.normalCDF(a),gamma:m.normalPDF(a)/(o*c*Math.sqrt(l)),theta:-o*m.normalPDF(a)*c/(2*Math.sqrt(l))-r*i*Math.exp(-r*l)*m.normalCDF(s),vega:o*Math.sqrt(l)*m.normalPDF(a),rho:i*l*Math.exp(-r*l)*m.normalCDF(s)}}static calculateBinomialTree(t,e,n=1,o=.05,i=.2,l=100){let r=n/l,c=Math.exp(i*Math.sqrt(r)),a=1/c,s=(Math.exp(o*r)-a)/(c-a),u=[];for(let M=0;M<=l;M++){u[M]=[];for(let R=0;R<=M;R++)u[M][R]=t*c**R*a**(M-R)}let h=[];h[l]=[];for(let M=0;M<=l;M++){let R=Math.max(0,u[l][M]-e);h[l][M]=R}let d=[];d[l]=[];for(let M=0;M<=l;M++){let R=Math.max(0,e-u[l][M]);d[l][M]=R}for(let M=l-1;M>=0;M--){h[M]=[];for(let R=0;R<=M;R++){let v=h[M+1][R+1],x=h[M+1][R],C=Math.exp(-o*r)*(s*v+(1-s)*x);h[M][R]=Math.max(C,u[M][R]-e)}}for(let M=l-1;M>=0;M--){d[M]=[];for(let R=0;R<=M;R++){let v=d[M+1][R+1],x=d[M+1][R],C=Math.exp(-o*r)*(s*v+(1-s)*x);d[M][R]=Math.max(C,e-u[M][R])}}let f=h[0][0],g=d[0][0],b=(h[1][1]-h[1][0])/(u[1][1]-u[1][0]),P=((h[1][1]-h[1][0])/(u[1][1]-u[1][0])-(h[1][0]-h[1][0])/(u[1][0]-u[1][0]))/(u[1][1]-u[1][0]),w=(h[1][0]-h[0][0])/r,S=(f-f*1.01)/(i*.01),p=(f-f*1.01)/(o*.01);return{callPrice:f,putPrice:g,delta:b,gamma:P,theta:w,vega:S,rho:p}}static calculateTrinomialTree(t,e,n=1,o=.05,i=.2,l=50){let r=n/l,c=i*Math.sqrt(3*r),a=Math.exp(c),s=.5*((o-.5*i*i)*r/c+i*i*r/(c*c)),u=.5*((o-.5*i*i)*r/c-i*i*r/(c*c)),h=1-s-u,d=[];for(let v=0;v<=l;v++){d[v]=[];for(let x=0;x<=2*v+1;x++){let C=x-v;d[v][x]=t*a**C}}let f=[];f[l]=[];for(let v=0;v<=2*l;v++){let x=Math.max(0,d[l][v]-e);f[l][v]=x}let g=[];g[l]=[];for(let v=0;v<=2*l;v++){let x=Math.max(0,e-d[l][v]);g[l][v]=x}for(let v=l-1;v>=0;v--){f[v]=[];for(let x=0;x<=2*v;x++){let C=f[v+1][x+2],E=f[v+1][x+1],O=f[v+1][x],B=Math.exp(-o*r)*(s*C+h*E+u*O);f[v][x]=Math.max(B,d[v][x]-e)}}for(let v=l-1;v>=0;v--){g[v]=[];for(let x=0;x<=2*v;x++){let C=g[v+1][x+2],E=g[v+1][x+1],O=g[v+1][x],B=Math.exp(-o*r)*(s*C+h*E+u*O);g[v][x]=Math.max(B,e-d[v][x])}}let b=f[0][0],P=g[0][0],w=(f[1][2]-f[1][0])/(d[1][2]-d[1][0]),S=((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,M=(b-b*1.01)/(i*.01),R=(b-b*1.01)/(o*.01);return{callPrice:b,putPrice:P,delta:w,gamma:S,theta:p,vega:M,rho:R}}static calculateMonteCarlo(t,e,n=1,o=.05,i=.2,l=1e4){let r=0,c=0,a=0,s=0;for(let M=0;M<l;M++){let R=m.boxMuller(),v=t*Math.exp((o-.5*i*i)*n+i*Math.sqrt(n)*R),x=Math.max(0,v-e),C=Math.max(0,e-v);r+=x,c+=C,v>e&&(a+=1,s+=0)}let u=Math.exp(-o*n),h=r/l*u,d=c/l*u,f=a/l*u,g=s/l*u,b=-(h*o),P=(h-h*1.01)/(i*.01),w=(h-h*1.01)/(o*.01),S=Math.sqrt(h*(1-h)/l),p={lower:h-1.96*S,upper:h+1.96*S};return{callPrice:h,putPrice:d,delta:f,gamma:g,theta:b,vega:P,rho:w,confidenceInterval:p}}static calculateHestonModel(t,e,n=1,o=.05,i=.2,l=.2,r=2,c=.3,a=-.5){let s=t*.6-e*Math.exp(-o*n)*.4,u=s-t+e*Math.exp(-o*n),h=Math.sqrt(2*Math.PI/n)*(s/t)*(1+.5*(s/t)),d=.6,f=.01/t,g=-(s*o),b=s*Math.sqrt(n),P=e*n*Math.exp(-o*n)*.4;return{callPrice:s,putPrice:u,impliedVolatility:h,delta:d,gamma:f,theta:g,vega:b,rho:P}}static calculateSABRModel(t,e,n=1,o=.05,i=.2,l=.5,r=-.5,c=.3){let a=t,s=e,u=n,h=c/i*Math.log(a/s),d=Math.log((Math.sqrt(1-2*r*h+h*h)+h-r)/(1-r)),f;Math.abs(a-s)<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*s)**((1-l)/2)*(1+((1-l)**2/24*i**2/(a*s)**(1-l)+r*l*i*c/(4*(a*s)**((1-l)/2))+(2-3*r**2)*c**2/24)*u)*h/d;let g=(Math.log(a/s)+(o+f*f/2)*u)/(f*Math.sqrt(u)),b=g-f*Math.sqrt(u),P=a*m.normalCDF(g)-s*Math.exp(-o*u)*m.normalCDF(b),w=s*Math.exp(-o*u)*m.normalCDF(-b)-a*m.normalCDF(-g),S=m.normalCDF(g),p=m.normalPDF(g)/(a*f*Math.sqrt(u)),M=-a*m.normalPDF(g)*f/(2*Math.sqrt(u))-o*s*Math.exp(-o*u)*m.normalCDF(b),R=a*Math.sqrt(u)*m.normalPDF(g),v=s*u*Math.exp(-o*u)*m.normalCDF(b);return{callPrice:P,putPrice:w,impliedVolatility:f,delta:S,gamma:p,theta:M,vega:R,rho:v}}static calculateVarianceGamma(t,e,n=1,o=.05,i=.2,l=-.1,r=.3){let c=t,a=e,s=n,u=o,h=c*.55-a*Math.exp(-u*s)*.45,d=h-c+a*Math.exp(-u*s),f=Math.sqrt(2*Math.PI/s)*(h/c)*(1+.5*(h/c)),g=.55,b=.01/c,P=-(h*u),w=h*Math.sqrt(s),S=a*s*Math.exp(-u*s)*.45;return{callPrice:h,putPrice:d,impliedVolatility:f,delta:g,gamma:b,theta:P,vega:w,rho:S}}static normalCDF(t){return .5*(1+m.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,o=1.421413741,i=-1.453152027,l=1.061405429,r=.3275911,c=t>=0?1:-1,a=Math.abs(t),s=1/(1+r*a),u=1-((((l*s+i)*s+o)*s+n)*s+e)*s*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 W=class{static calculateMaxDrawdown(t){let e=t[0],n=0;for(let o=1;o<t.length;o++){t[o]>e&&(e=t[o]);let i=(e-t[o])/e;i>n&&(n=i)}return n}static calculateMaxConsecutiveLosses(t){let e=0,n=0;for(let o=1;o<t.length;o++)t[o]<t[o-1]?(n++,e=Math.max(e,n)):n=0;return e}static calculateWinRate(t){let e=0,n=0;for(let o=1;o<t.length;o++)t[o]!==t[o-1]&&(n++,t[o]>t[o-1]&&e++);return n>0?e/n:0}static calculateProfitFactor(t){let e=0,n=0;for(let o=1;o<t.length;o++){let i=t[o]-t[o-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,o=n-e,i=t.reduce((r,c)=>r+(c-n)**2,0)/t.length,l=Math.sqrt(i);return l>0?o/l:0}static calculateSortinoRatio(t,e=.02){if(t.length===0)return 0;let n=t.reduce((c,a)=>c+a,0)/t.length,o=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?o/r:0}static calculateCalmarRatio(t,e){return e===0?0:t.reduce((o,i)=>o+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 J=class m{static generateSignals(t,e,n,o,i,l,r,c,a){let s=0,u=0,h=[];t>e?(h.push(`\u2713 BULLISH: Price above VWAP (+${((t-e)/e*100).toFixed(2)}%)`),s++):(h.push(`\u2717 BEARISH: Price below VWAP (${((t-e)/e*100).toFixed(2)}%)`),u++),n>0&&o>0?(h.push("\u2713 BULLISH: Positive momentum on both timeframes"),s++):n<0&&o<0?(h.push("\u2717 BEARISH: Negative momentum on both timeframes"),u++):h.push("\u25D0 MIXED: Conflicting momentum signals");let d=l/r;return d>1.2&&i>0?(h.push("\u2713 BULLISH: Above-average volume supporting upward move"),s++):d>1.2&&i<0?(h.push("\u2717 BEARISH: Above-average volume supporting downward move"),u++):h.push("\u25D0 NEUTRAL: Volume not providing clear direction"),c>65&&a>30?(h.push("\u2717 BEARISH: High in range with elevated volatility - reversal risk"),u++):c<35&&a>30?(h.push("\u2713 BULLISH: Low in range with volatility - potential bounce"),s++):h.push("\u25D0 NEUTRAL: Price position and volatility not extreme"),{bullishSignals:s,bearishSignals:u,signals:h}}static calculateOverallSignal(t,e,n,o){let i=t-e,l=i>0?"BULLISH_BIAS":i<0?"BEARISH_BIAS":"NEUTRAL",r=m.calculateConfidence(n),c=m.calculateRiskLevel(o);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 D(m,t=500){if(m.length<=t)return m;let e=[],n=m.length/t;e.push(m[0]);for(let o=1;o<t-1;o++){let i=Math.floor(o*n),l=Math.floor((o+1)*n),r=m.slice(i,l);if(r.length===0)continue;let c=Math.floor(r.length/2);e.push(r[c])}return e.push(m[m.length-1]),e}var k=class{static calculateZScore(t,e){return(t-e)/(e*.1)}static calculateOrnsteinUhlenbeck(t,e,n,o){let i=e,l=.1;if(o.length>1){let c=o.reduce((a,s)=>a+s*s,0)/o.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,o){let i=n*.001,l=n*1e-4,r=e,c=i;if(o.length>0){let a=r,s=c+l,u=s/(s+i);return r=a+u*(t-a),c=(1-u)*s,{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,o=0,i=0,l=0,r=0;for(let b=1;b<n;b++){let P=e[b],w=e[b-1];o+=P,i+=w,l+=P*w,r+=w*w}let c=(n*l-o*i)/(n*r-i*i),a=(o-c*i)/n,s=[];for(let b=1;b<n;b++){let P=a+c*e[b-1];s.push(e[b]-P)}let u=s.reduce((b,P)=>b+P*P,0),h=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:D(s),aic:h}}static calculateGARCH(t,e){if(e.length<5)return{volatility:t*.01,persistence:.9,meanReversion:.1};let n=e.map(c=>c*c),o=n.reduce((c,a)=>c+a,0)/n.length,i=.9;if(n.length>1){let c=n.reduce((a,s)=>a+s,0)/n.length;i=Math.min(.99,Math.max(.5,c/o))}let l=o*(1-i);return{volatility:Math.sqrt(o),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 o=[],i=[];for(let b=1;b<t.length;b++)o.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<o.length;b++){let P=[1];for(let w=1;w<=n;w++)P.push(o[b-w]),P.push(i[b-w]);l.push(P),r.push(o[b]),c.push(i[b])}let a=[[.5,.3,.2,.1],[.2,.1,.6,.3]],s=[],u=[];for(let b=0;b<r.length;b++){let P=a[0].reduce((S,p,M)=>S+p*l[b][M],0),w=a[1].reduce((S,p,M)=>S+p*l[b][M],0);s.push(r[b]-P),u.push(c[b]-w)}let h=o[o.length-1],d=i[i.length-1],f=[t[t.length-1]*(1+h*.5)],g=[e[e.length-1]*(1+d*.5)];return{priceForecast:f,volumeForecast:g,coefficients:a,residuals:[D(s),D(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=[],o=[],i=[],l=[],r=t[t.length-1],c=Math.sqrt(t.reduce((a,s)=>a+(s-r)**2,0)/t.length);for(let a=1;a<=e;a++){let s=(t[t.length-1]-t[t.length-10])/10,u=r+s*a;n.push(u);let h=c*(1+a*.1);o.push(h);let d=1.96*h;i.push(u-d),l.push(u+d)}return{mean:n,variance:o,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),o=0,i=0,l=0,r=0;for(let P=0;P<n;P++)o+=t[P],i+=e[P],l+=t[P]*e[P],r+=t[P]*t[P];let c=(n*l-o*i)/(n*r-o*o),a=[];for(let P=0;P<n;P++)a.push(e[P]-c*t[P]);let s=a.reduce((P,w)=>P+w,0)/a.length,u=Math.sqrt(a.reduce((P,w)=>P+(w-s)**2,0)/a.length),h=[];for(let P=0;P<a.length;P++)h.push((a[P]-s)/u);let d=h[h.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:D(a),zScore:D(h),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=[],o=[],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),o.push(Math.atan2(a,c)),i.push(Math.sqrt(c*c+a*a))}return{analytic:D(n),phase:D(o),amplitude:D(i)}}static calculateWaveletTransform(t,e){if(e.length<8)return{coefficients:[t],scales:[1]};let n=[t,...e.map(l=>t+l)],o=[],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;o.push(a)}}return{coefficients:D(o),scales:D(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=[],o=[],i=[];for(let a=0;a<e;a++){let s=a/e;n.push(s);let u=0,h=0;for(let g=0;g<e;g++){let b=-2*Math.PI*a*g/e;u+=t[g]*Math.cos(b),h+=t[g]*Math.sin(b)}let d=Math.sqrt(u*u+h*h)/e,f=Math.atan2(h,u);o.push(d),i.push(f)}let r=[...o].sort((a,s)=>s-a)[Math.floor(e*.1)],c=n.filter((a,s)=>o[s]>r);return{frequencies:D(n),amplitudes:D(o),phases:D(i),dominantFrequencies:D(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 s=[];for(let h=1;h<r.length-1;h++)(r[h]>r[h-1]&&r[h]>r[h+1]||r[h]<r[h-1]&&r[h]<r[h+1])&&s.push(r[h]);if(s.length<3)break;let u=s.map((h,d)=>d===0?s[0]:d===s.length-1?s[s.length-1]:(s[d-1]+s[d+1])/2);for(let h=0;h<r.length;h++){let d=Math.floor(h*s.length/r.length);r[h]-=u[Math.min(d,u.length-1)]}c++}e.push(D([...r]));for(let s=0;s<n.length;s++)n[s]-=r[s]}let o=D(n),i=D(e.map((l,r)=>.1/(r+1)));return{imfs:e,residual:o,frequencies:i}}};var $=class m{static calculatePivotPoints(t,e,n){let o=[];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,s=2*a-r,u=2*a-l,h=a+(l-r),d=a-(l-r),f=l+2*(a-r),g=r-2*(l-a);o.push({pp:a,r1:s,r2:h,r3:f,s1:u,s2:d,s3:g})}return o}static calculateFibonacciPivotPoints(t,e,n){let o=[];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,s=l-r,u=a+.382*s,h=a+.618*s,d=a+1*s,f=a-.382*s,g=a-.618*s,b=a-1*s;o.push({pp:a,r1:u,r2:h,r3:d,s1:f,s2:g,s3:b})}return o}static calculateCamarillaPivotPoints(t,e,n){let o=[];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,s=l-r,u=c+1.1/12*s,h=c+1.1/6*s,d=c+1.1/4*s,f=c-1.1/12*s,g=c-1.1/6*s,b=c-1.1/4*s;o.push({pp:a,r1:u,r2:h,r3:d,s1:f,s2:g,s3:b})}return o}static calculateFibonacciLevels(t){let e=[];for(let n=0;n<t.length;n++){let o=t[n];e.push({retracement:{level0:o,level236:o*.764,level382:o*.618,level500:o*.5,level618:o*.382,level786:o*.214,level100:o*0},extension:{level1272:o*1.272,level1618:o*1.618,level2618:o*2.618,level4236:o*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 o=t.length-1;return e.push(t[o]*(1+o*.01)),e}static calculateElliottWave(t){let e=[];if(t.length<10)return[];for(let n=0;n<t.length;n++){let o=[],i=1,l=.5;if(n>=4){let r=t.slice(n-4,n+1),c=m.detectPriceSwings(r);c.length>=3&&(o.push(...c.slice(0,3)),i=Math.min(c.length,5),l=m.calculateWavePosition(r))}e.push({waves:o.length>0?o:[t[n]],currentWave:i,wavePosition:l})}return e}static detectPriceSwings(t){let e=[];for(let n=1;n<t.length-1;n++){let o=t[n-1],i=t[n],l=t[n+1];(i>o&&i>l||i<o&&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),o=Math.max(...t);return o!==n?(e-n)/(o-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=m.detectHarmonicPattern(l);n.push(r)}if(n.length<=500)return n;let o=n.length/500;e.push(n[0]);for(let i=1;i<499;i++){let l=Math.floor(i*o),r=Math.floor((i+1)*o),c=n.slice(l,r);if(c.length===0)continue;let a=c.reduce((s,u)=>u.completion>s.completion?u:s);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=m.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[o,i,l,r,c]=n,a=Math.abs(l-i),s=Math.abs(r-l),u=Math.abs(c-r),h=Math.abs(i-o),d=a/h,f=s/a,g=u/s;return m.isInRange(d,.618,.05)&&m.isInRange(f,.382,.05)&&m.isInRange(g,.886,.05)?{type:"Gartley",completion:m.calculatePatternCompletion(t),target:c+(c-r)*.618,stopLoss:c*.99}:m.isInRange(d,.382,.05)&&m.isInRange(f,.382,.05)&&m.isInRange(g,.886,.05)?{type:"Bat",completion:m.calculatePatternCompletion(t),target:c+(c-r)*.382,stopLoss:c*.99}:m.isInRange(d,.786,.05)&&m.isInRange(f,.382,.05)&&m.isInRange(g,1.618,.05)?{type:"Butterfly",completion:m.calculatePatternCompletion(t),target:c+(c-r)*1.618,stopLoss:c*.99}:m.isInRange(d,.382,.05)&&m.isInRange(f,.886,.05)&&m.isInRange(g,3.618,.1)?{type:"Crab",completion:m.calculatePatternCompletion(t),target:c+(c-r)*1.618,stopLoss:c*.99}:m.isInRange(d,.382,.05)&&m.isInRange(f,.113,.05)&&m.isInRange(g,Math.SQRT2,.05)?{type:"Cypher",completion:m.calculatePatternCompletion(t),target:c+(c-r)*.786,stopLoss:c*.99}:m.isInRange(d,.886,.05)&&m.isInRange(f,.886,.05)&&m.isInRange(g,1.13,.05)?{type:"Shark",completion:m.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),o=Math.min(...t);if(n===o)return 50;let i=n-o,l=(e-o)/i;return Math.min(100,Math.max(0,l*100))}};var U=class{static calculateMACD(t){let e=A.calculateEMA(t,12),n=A.calculateEMA(t,26),o=[],i=[];for(let r=0;r<Math.min(e.length,n.length);r++)i.push(e[r]-n[r]);let l=A.calculateEMA(i,9);for(let r=0;r<Math.min(i.length,l.length);r++)o.push({macd:i[r],signal:l[r],histogram:i[r]-l[r]});return o}static calculateADX(t,e,n){if(t.length<14)return[];let o=14,i=[],l=[],r=[],c=[];l.push(e[0]-n[0]),r.push(0),c.push(0);for(let S=1;S<t.length;S++){let p=e[S]||t[S],M=n[S]||t[S],R=e[S-1]||t[S-1],v=n[S-1]||t[S-1],x=t[S-1],C=p-M,E=Math.abs(p-x),O=Math.abs(M-x);l.push(Math.max(C,E,O));let B=p-R,V=v-M;B>V&&B>0?(r.push(B),c.push(0)):V>B&&V>0?(r.push(0),c.push(V)):(r.push(0),c.push(0))}let a=[],s=[],u=[],h=0,d=0,f=0;for(let S=0;S<o;S++)h+=l[S],d+=r[S],f+=c[S];a.push(h),s.push(d),u.push(f);for(let S=o;S<l.length;S++){let p=a[a.length-1]-a[a.length-1]/o+l[S],M=s[s.length-1]-s[s.length-1]/o+r[S],R=u[u.length-1]-u[u.length-1]/o+c[S];a.push(p),s.push(M),u.push(R)}let g=[],b=[];for(let S=0;S<a.length;S++)g.push(s[S]/a[S]*100),b.push(u[S]/a[S]*100);let P=[];for(let S=0;S<g.length;S++){let p=g[S]+b[S],M=Math.abs(g[S]-b[S]);P.push(p>0?M/p*100:0)}if(P.length<o)return[];let w=0;for(let S=0;S<o;S++)w+=P[S];i.push(w/o);for(let S=o;S<P.length;S++){let p=i[i.length-1]-i[i.length-1]/o+P[S];i.push(p)}return i}static calculateDMI(t,e,n){if(t.length<14)return[];let o=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 M=e[p]||t[p],R=n[p]||t[p],v=e[p-1]||t[p-1],x=n[p-1]||t[p-1],C=t[p-1],E=M-R,O=Math.abs(M-C),B=Math.abs(R-C);l.push(Math.max(E,O,B));let V=M-v,G=x-R;V>G&&V>0?(r.push(V),c.push(0)):G>V&&G>0?(r.push(0),c.push(G)):(r.push(0),c.push(0))}let a=[],s=[],u=[],h=0,d=0,f=0;for(let p=0;p<o;p++)h+=l[p],d+=r[p],f+=c[p];a.push(h),s.push(d),u.push(f);for(let p=o;p<l.length;p++){let M=a[a.length-1]-a[a.length-1]/o+l[p],R=s[s.length-1]-s[s.length-1]/o+r[p],v=u[u.length-1]-u[u.length-1]/o+c[p];a.push(M),s.push(R),u.push(v)}let g=[],b=[];for(let p=0;p<a.length;p++)g.push(s[p]/a[p]*100),b.push(u[p]/a[p]*100);let P=[];for(let p=0;p<g.length;p++){let M=g[p]+b[p],R=Math.abs(g[p]-b[p]);P.push(M>0?R/M*100:0)}if(P.length<o)return[];let w=[],S=0;for(let p=0;p<o;p++)S+=P[p];w.push(S/o);for(let p=o;p<P.length;p++){let M=w[w.length-1]-w[w.length-1]/o+P[p];w.push(M)}for(let p=0;p<w.length;p++)i.push({plusDI:g[p+o-1]||0,minusDI:b[p+o-1]||0,adx:w[p]});return i}static calculateIchimoku(t,e,n){if(t.length<52)return[];let o=[],i=[];for(let u=8;u<t.length;u++){let h=Math.max(...e.slice(u-8,u+1)),d=Math.min(...n.slice(u-8,u+1));i.push((h+d)/2)}let l=[];for(let u=25;u<t.length;u++){let h=Math.max(...e.slice(u-25,u+1)),d=Math.min(...n.slice(u-25,u+1));l.push((h+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 h=Math.max(...e.slice(u-51,u+1)),d=Math.min(...n.slice(u-51,u+1));c.push((h+d)/2)}let a=[];for(let u=26;u<t.length;u++)a.push(t[u-26]);let s=Math.min(i.length,l.length,r.length,c.length,a.length);for(let u=0;u<s;u++)o.push({tenkan:i[u],kijun:l[u],senkouA:r[u],senkouB:c[u],chikou:a[u]});return o}static calculateParabolicSAR(t,e,n){if(t.length<2)return[];let o=[],i=.02,l=.2,r=n[0],c=!0,a=i,s=e[0];o.push(r);for(let u=1;u<t.length;u++){let h=e[u]||t[u],d=n[u]||t[u];if(c){if(d<r)c=!1,r=s,s=d,a=i;else if(h>s&&(s=h,a=Math.min(a+i,l)),r=r+a*(s-r),u>0){let f=n[u-1]||t[u-1];r=Math.min(r,f)}}else if(h>r)c=!0,r=s,s=h,a=i;else if(d<s&&(s=d,a=Math.min(a+i,l)),r=r+a*(s-r),u>0){let f=e[u-1]||t[u-1];r=Math.max(r,f)}o.push(r)}return o}};var X=class m{static calculateBollingerBands(t,e=20,n=2){if(t.length<e)return[];let o=A.calculateSMA(t,e),i=[];for(let l=0;l<o.length;l++){let r=t.slice(l,l+e),c=o[l],a=r.reduce((d,f)=>d+(f-c)**2,0)/e,s=Math.sqrt(a),u=c+s*n,h=c-s*n;i.push({upper:u,middle:c,lower:h,bandwidth:(u-h)/c*100,percentB:(t[l]-h)/(u-h)*100})}return i}static calculateATR(t,e,n){if(t.length<2)return[];let o=[];for(let l=1;l<t.length;l++){let r=e[l]||t[l],c=n[l]||t[l],a=t[l-1],s=r-c,u=Math.abs(r-a),h=Math.abs(c-a);o.push(Math.max(s,u,h))}let i=[];if(o.length>=14){let l=o.slice(0,14).reduce((r,c)=>r+c,0);i.push(l/14);for(let r=14;r<o.length;r++)l=l-o[r-14]+o[r],i.push(l/14)}return i}static calculateKeltnerChannels(t,e,n){let o=[];if(t.length<20)return[];let r=A.calculateEMA(t,20),c=m.calculateATR(t,e,n);for(let a=0;a<Math.min(r.length,c.length);a++){let s=r[a],u=c[a];o.push({upper:s+2*u,middle:s,lower:s-2*u})}return o}static calculateDonchianChannels(t){let e=[];for(let n=20;n<t.length;n++){let o=t.slice(n-20,n);e.push({upper:Math.max(...o),middle:(Math.max(...o)+Math.min(...o))/2,lower:Math.min(...o)})}return e}static calculateChaikinVolatility(t,e,n){let o=[];if(t.length<10*2)return[];let l=[];for(let c=0;c<t.length;c++){let a=e[c]||t[c],s=n[c]||t[c];l.push(a-s)}let r=A.calculateEMA(l,10);for(let c=10;c<r.length;c++){let a=r[c],s=r[c-10],u=s!==0?(a-s)/s*100:0;o.push(u)}return o}};var j=class{static calculateOBV(t,e){let n=[e[0]];for(let o=1;o<t.length;o++)t[o]>t[o-1]?n.push(n[o-1]+e[o]):t[o]<t[o-1]?n.push(n[o-1]-e[o]):n.push(n[o-1]);return n}static calculateCMF(t,e,n,o){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 h=e[u]||t[u],d=n[u]||t[u],f=t[u],g=o[u]||1,P=(f-d-(h-f))/(h-d)*g;c+=P,a+=g}let s=a!==0?c/a:0;i.push(s)}return i}static calculateADL(t,e,n,o){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],s=o[l]||1,h=(a-c-(r-a))/(r-c)*s;i.push(i[l-1]+h)}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,o){let i=[];if(t.length<15)return[];for(let r=14;r<t.length;r++){let c=0,a=0;for(let h=r-14+1;h<=r;h++){let d=e[h]||t[h],f=n[h]||t[h],g=t[h],b=o[h]||1,P=(d+f+g)/3,w=P*b;if(h>r-14+1){let S=e[h-1]||t[h-1],p=n[h-1]||t[h-1],M=t[h-1],R=(S+p+M)/3;P>R?c+=w:P<R&&(a+=w)}}let u=100-100/(1+(a!==0?c/a:0));i.push(u)}return i}static calculateVWAP(t,e){let n=[],o=0,i=0;for(let l=0;l<t.length;l++)o+=t[l]*(e[l]||1),i+=e[l]||1,n.push(o/i);return n}};function lt(m){return m.reduce((t,e)=>t+e,0)}var te=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),o=Math.min(...this.lows),i=lt(this.volumes),l=i/this.volumes.length,r=this.calculatePriceChanges(),c=r.length>0?Math.sqrt(r.reduce((C,E)=>C+E**2,0)/r.length)*Math.sqrt(252)*100:0,a=(t-e)/e*100,s=(t-o)/(n-o)*100,u=this.prices.reduce((C,E,O)=>C+E*this.volumes[O],0)/i,h=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=W.calculateMaxDrawdown(this.prices),g=X.calculateATR(this.prices,this.highs,this.lows),b=g.length>0?g[g.length-1]:0,P=c,w=c,S=a/c,p=a/w,M=a/f,R=W.calculateMaxConsecutiveLosses(this.prices),v=W.calculateWinRate(this.prices),x=W.calculateProfitFactor(this.prices);return{currentPrice:t,startPrice:e,sessionHigh:n,sessionLow:o,totalVolume:i,avgVolume:l,volatility:c,sessionReturn:a,pricePosition:s,trueVWAP:u,momentum5:h,momentum10:d,maxDrawdown:f,atr:b,impliedVolatility:P,realizedVolatility:w,sharpeRatio:S,sortinoRatio:p,calmarRatio:M,maxConsecutiveLosses:R,winRate:v,profitFactor:x}}getTechnicalIndicators(){return{sma5:A.calculateSMA(this.prices,5),sma10:A.calculateSMA(this.prices,10),sma20:A.calculateSMA(this.prices,20),sma50:A.calculateSMA(this.prices,50),sma200:A.calculateSMA(this.prices,200),ema8:A.calculateEMA(this.prices,8),ema12:A.calculateEMA(this.prices,12),ema21:A.calculateEMA(this.prices,21),ema26:A.calculateEMA(this.prices,26),wma20:A.calculateWMA(this.prices,20),vwma20:A.calculateVWMA(this.prices,this.volumes,20),macd:U.calculateMACD(this.prices),adx:U.calculateADX(this.prices,this.highs,this.lows),dmi:U.calculateDMI(this.prices,this.highs,this.lows),ichimoku:U.calculateIchimoku(this.prices,this.highs,this.lows),parabolicSAR:U.calculateParabolicSAR(this.prices,this.highs,this.lows),rsi:q.calculateRSI(this.prices,14),stochastic:q.calculateStochastic(this.prices,this.highs,this.lows),cci:q.calculateCCI(this.prices,this.highs,this.lows),roc:q.calculateROC(this.prices),williamsR:q.calculateWilliamsR(this.prices),momentum:q.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:j.calculateOBV(this.prices,this.volumes),cmf:j.calculateCMF(this.prices,this.highs,this.lows,this.volumes),adl:j.calculateADL(this.prices,this.highs,this.lows,this.volumes),volumeROC:j.calculateVolumeROC(this.volumes),mfi:j.calculateMFI(this.prices,this.highs,this.lows,this.volumes),vwap:j.calculateVWAP(this.prices,this.volumes),pivotPoints:$.calculatePivotPoints(this.prices,this.highs,this.lows),fibonacci:$.calculateFibonacciLevels(this.prices),gannLevels:$.calculateGannLevels(this.prices),elliottWave:$.calculateElliottWave(this.prices),harmonicPatterns:$.calculateHarmonicPatterns(this.prices)}}generateJSONAnalysis(t){let e=this.analyze(),n=this.getTechnicalIndicators(),o=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,s=n.ema8[n.ema8.length-1],u=n.ema12[n.ema12.length-1],h=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,P=n.adx.length>0?n.adx[n.adx.length-1]:null,w=n.dmi.length>0?n.dmi[n.dmi.length-1]:null,S=n.ichimoku.length>0?n.ichimoku[n.ichimoku.length-1]:null,p=n.parabolicSAR.length>0?n.parabolicSAR[n.parabolicSAR.length-1]:null,M=n.rsi.length>0?n.rsi[n.rsi.length-1]:null,R=n.stochastic.length>0?n.stochastic[n.stochastic.length-1]:null,v=n.cci.length>0?n.cci[n.cci.length-1]:null,x=n.roc.length>0?n.roc[n.roc.length-1]:null,C=n.williamsR.length>0?n.williamsR[n.williamsR.length-1]:null,E=n.momentum.length>0?n.momentum[n.momentum.length-1]:null,O=n.bollinger.length>0?n.bollinger[n.bollinger.length-1]:null,B=n.atr.length>0?n.atr[n.atr.length-1]:null,V=n.keltner.length>0?n.keltner[n.keltner.length-1]:null,G=n.donchian.length>0?n.donchian[n.donchian.length-1]:null,Te=n.chaikinVolatility.length>0?n.chaikinVolatility[n.chaikinVolatility.length-1]:null,ne=n.obv.length>0?n.obv[n.obv.length-1]:null,re=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,oe=n.mfi.length>0?n.mfi[n.mfi.length-1]:null,Ce=n.vwap.length>0?n.vwap[n.vwap.length-1]:null,De=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:[],Z=this.volumes[this.volumes.length-1],Ee=Z/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,_=J.generateSignals(e.currentPrice,e.trueVWAP,e.momentum5,e.momentum10,e.sessionReturn,Z,e.avgVolume,e.pricePosition,e.volatility),qe=J.calculateOverallSignal(_.bullishSignals,_.bearishSignals,_.signals,e.volatility),ee=Math.max(e.sessionLow*1.005,e.trueVWAP*.998),K=e.sessionLow*.995,se=e.sessionHigh*.995,Xe=(se-e.currentPrice)/(e.currentPrice-K),ae=W.calculatePositionSize(ee,K),je=ae*(ee-K),Ge=k.calculateVAR(this.prices,this.volumes),We=k.calculateGaussianProcess(this.prices),$e=k.calculatePairsTrading(this.prices,this.prices.map(et=>et*1.01)),Ue=k.calculateFourierTransform(this.prices),Je=k.calculateEMD(this.prices),H=N.calculateBlackScholes(e.currentPrice,e.startPrice,e.avgVolume),ze=N.calculateBinomialTree(e.currentPrice,e.startPrice),Ke=N.calculateTrinomialTree(e.currentPrice,e.startPrice),Qe=N.calculateMonteCarlo(e.currentPrice,e.startPrice),Ye=N.calculateHestonModel(e.currentPrice,e.startPrice),Ze=N.calculateSABRModel(e.currentPrice,e.startPrice),_e=N.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:s,ema12:u,ema21:h,ema26:d,wma20:f,vwma20:g,macd:b,adx:P,dmi:w,ichimoku:S,parabolicSAR:p,rsi:M,stochastic:R,cci:v,roc:x,williamsR:C,momentum:E,bollingerBands:O?{upper:O.upper,middle:O.middle,lower:O.lower,bandwidth:O.bandwidth,percentB:O.percentB}:null,atr:B,keltnerChannels:V?{upper:V.upper,middle:V.middle,lower:V.lower}:null,donchianChannels:G?{upper:G.upper,middle:G.middle,lower:G.lower}:null,chaikinVolatility:Te,obv:ne,cmf:re,adl:Fe,volumeROC:Ae,mfi:oe,vwap:Ce},volumeAnalysis:{currentVolume:Z,averageVolume:Math.round(e.avgVolume),volumeRatio:Ee,trueVWAP:e.trueVWAP,priceVsVWAP:Ne,obv:ne,cmf:re,mfi:oe},momentum:{momentum5:e.momentum5,momentum10:e.momentum10,sessionROC:e.sessionReturn,rsi:M,stochastic:R,cci:v},supportResistance:{pivotPoints:De,fibonacci:Oe,gannLevels:ke,elliottWave:Ve,harmonicPatterns:Le},tradingSignals:qe,statisticalModels:{zScore:k.calculateZScore(e.currentPrice,e.startPrice),ornsteinUhlenbeck:k.calculateOrnsteinUhlenbeck(e.currentPrice,e.startPrice,e.avgVolume,o),kalmanFilter:k.calculateKalmanFilter(e.currentPrice,e.startPrice,e.avgVolume,o),pairsTrading:$e,arima:k.calculateARIMA(e.currentPrice,o),garch:k.calculateGARCH(e.avgVolume,o),var:Ge,gaussianProcess:We,hilbertTransform:k.calculateHilbertTransform(e.currentPrice,o),waveletTransform:k.calculateWaveletTransform(e.currentPrice,o),fourierTransform:Ue,empiricalModeDecomposition:Je},optionsAnalysis:H?{blackScholes:H,binomialTree:ze,trinomialTree:Ke,monteCarlo:Qe,hestonModel:Ye,sabrModel:Ze,varianceGamma:_e,impliedVolatility:e.impliedVolatility,delta:H.delta,gamma:H.gamma,theta:H.theta,vega:H.vega,rho:H.rho,greeks:{delta:H.delta,gamma:H.gamma,theta:H.theta,vega:H.vega,rho:H.rho}}:null,riskManagement:{targetEntry:ee,stopLoss:K,profitTarget:se,riskRewardRatio:Xe,positionSize:ae,maxRisk:je},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}}}},ue=m=>async t=>{try{let e=t.symbol,n=m.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 te(n).generateJSONAnalysis(e);return{content:[{type:"text",text:`Technical Analysis for ${e}:
|
|
2
|
+
"use strict";var tt=Object.create;var ie=Object.defineProperty;var nt=Object.getOwnPropertyDescriptor;var rt=Object.getOwnPropertyNames;var ot=Object.getPrototypeOf,st=Object.prototype.hasOwnProperty;var at=(h,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of rt(t))!st.call(h,o)&&o!==e&&ie(h,o,{get:()=>t[o],enumerable:!(n=nt(t,o))||n.enumerable});return h};var it=(h,t,e)=>(e=h!=null?tt(ot(h)):{},at(t||!h||!h.__esModule?ie(e,"default",{value:h,enumerable:!0}):e,h));var F=require("fixparser");var le=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,o={jsonrpc:"2.0",method:h.level,params:{message:e,...n},id:h.id||Date.now()};t(JSON.stringify(o))}else{let{name:e,id:n,message:o,level:i,...l}=h,r=Object.entries(l).map(([a,s])=>`${a}: ${s}`),c="";e&&(c+=`${e} `),c+=`${n}: ${o}`,t(c,r.join(", "))}}async flush(){}async close(){}status(){return"connected"}};var ve=require("node:crypto"),Ie=require("node:http"),Re=require("@modelcontextprotocol/sdk/server/mcp.js"),we=require("@modelcontextprotocol/sdk/server/streamableHttp.js"),xe=require("@modelcontextprotocol/sdk/types.js"),L=require("zod");var Q=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 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"]}}};var q=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 o=n.map(a=>a>0?a:0),i=n.map(a=>a<0?Math.abs(a):0),l=o.slice(0,e).reduce((a,s)=>a+s,0)/e,r=i.slice(0,e).reduce((a,s)=>a+s,0)/e,c=[];for(let a=e;a<n.length;a++){let s=l/r;c.push(100-100/(1+s)),l=(l*(e-1)+o[a])/e,r=(r*(e-1)+i[a])/e}return c}static calculateStochastic(t,e,n){let o=[];if(t.length<14)return[];let c=[];for(let s=13;s<t.length;s++){let u=Math.max(...e.slice(s-14+1,s+1)),m=Math.min(...n.slice(s-14+1,s+1)),f=(t[s]-m)/(u-m)*100;c.push(f)}let a=[];for(let s=2;s<c.length;s++){let u=c.slice(s-3+1,s+1).reduce((m,d)=>m+d,0);a.push(u/3)}for(let s=2;s<a.length;s++){let m=a.slice(s-3+1,s+1).reduce((d,f)=>d+f,0)/3;o.push({k:a[s],d:m})}return o}static calculateCCI(t,e,n){let o=[];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,s=c.reduce((d,f)=>d+Math.abs(f-a),0)/20,u=(e[l]+n[l]+t[l])/3,m=s!==0?(u-a)/(.015*s):0;o.push(m)}return o}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 o=13;o<t.length;o++){let i=t.slice(o-14+1,o+1),l=Math.max(...i),r=Math.min(...i),c=t[o],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 A=class{static calculateSMA(t,e){let n=[];for(let o=e-1;o<t.length;o++){let i=t.slice(o-e+1,o+1).reduce((l,r)=>l+r,0);n.push(i/e)}return n}static calculateEMA(t,e){let n=2/(e+1),o=[t[0]];for(let i=1;i<t.length;i++)o.push(t[i]*n+o[i-1]*(1-n));return o}static calculateWMA(t,e){let n=[],o=Array.from({length:e},(l,r)=>r+1),i=o.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]*o[c];n.push(r/i)}return n}static calculateVWMA(t,e,n){let o=[];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}o.push(r/l)}return o}};var N=class h{static calculateBlackScholes(t,e,n){let o=t,i=e,l=1,r=.05,c=n*.01,a=(Math.log(o/i)+(r+c*c/2)*l)/(c*Math.sqrt(l)),s=a-c*Math.sqrt(l),u=o*h.normalCDF(a)-i*Math.exp(-r*l)*h.normalCDF(s),m=i*Math.exp(-r*l)*h.normalCDF(-s)-o*h.normalCDF(-a);return{callPrice:u,putPrice:m,delta:h.normalCDF(a),gamma:h.normalPDF(a)/(o*c*Math.sqrt(l)),theta:-o*h.normalPDF(a)*c/(2*Math.sqrt(l))-r*i*Math.exp(-r*l)*h.normalCDF(s),vega:o*Math.sqrt(l)*h.normalPDF(a),rho:i*l*Math.exp(-r*l)*h.normalCDF(s)}}static calculateBinomialTree(t,e,n=1,o=.05,i=.2,l=100){let r=n/l,c=Math.exp(i*Math.sqrt(r)),a=1/c,s=(Math.exp(o*r)-a)/(c-a),u=[];for(let M=0;M<=l;M++){u[M]=[];for(let R=0;R<=M;R++)u[M][R]=t*c**R*a**(M-R)}let m=[];m[l]=[];for(let M=0;M<=l;M++){let R=Math.max(0,u[l][M]-e);m[l][M]=R}let d=[];d[l]=[];for(let M=0;M<=l;M++){let R=Math.max(0,e-u[l][M]);d[l][M]=R}for(let M=l-1;M>=0;M--){m[M]=[];for(let R=0;R<=M;R++){let v=m[M+1][R+1],x=m[M+1][R],D=Math.exp(-o*r)*(s*v+(1-s)*x);m[M][R]=Math.max(D,u[M][R]-e)}}for(let M=l-1;M>=0;M--){d[M]=[];for(let R=0;R<=M;R++){let v=d[M+1][R+1],x=d[M+1][R],D=Math.exp(-o*r)*(s*v+(1-s)*x);d[M][R]=Math.max(D,e-u[M][R])}}let f=m[0][0],g=d[0][0],b=(m[1][1]-m[1][0])/(u[1][1]-u[1][0]),P=((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]),w=(m[1][0]-m[0][0])/r,S=(f-f*1.01)/(i*.01),p=(f-f*1.01)/(o*.01);return{callPrice:f,putPrice:g,delta:b,gamma:P,theta:w,vega:S,rho:p}}static calculateTrinomialTree(t,e,n=1,o=.05,i=.2,l=50){let r=n/l,c=i*Math.sqrt(3*r),a=Math.exp(c),s=.5*((o-.5*i*i)*r/c+i*i*r/(c*c)),u=.5*((o-.5*i*i)*r/c-i*i*r/(c*c)),m=1-s-u,d=[];for(let v=0;v<=l;v++){d[v]=[];for(let x=0;x<=2*v+1;x++){let D=x-v;d[v][x]=t*a**D}}let f=[];f[l]=[];for(let v=0;v<=2*l;v++){let x=Math.max(0,d[l][v]-e);f[l][v]=x}let g=[];g[l]=[];for(let v=0;v<=2*l;v++){let x=Math.max(0,e-d[l][v]);g[l][v]=x}for(let v=l-1;v>=0;v--){f[v]=[];for(let x=0;x<=2*v;x++){let D=f[v+1][x+2],E=f[v+1][x+1],O=f[v+1][x],B=Math.exp(-o*r)*(s*D+m*E+u*O);f[v][x]=Math.max(B,d[v][x]-e)}}for(let v=l-1;v>=0;v--){g[v]=[];for(let x=0;x<=2*v;x++){let D=g[v+1][x+2],E=g[v+1][x+1],O=g[v+1][x],B=Math.exp(-o*r)*(s*D+m*E+u*O);g[v][x]=Math.max(B,e-d[v][x])}}let b=f[0][0],P=g[0][0],w=(f[1][2]-f[1][0])/(d[1][2]-d[1][0]),S=((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,M=(b-b*1.01)/(i*.01),R=(b-b*1.01)/(o*.01);return{callPrice:b,putPrice:P,delta:w,gamma:S,theta:p,vega:M,rho:R}}static calculateMonteCarlo(t,e,n=1,o=.05,i=.2,l=1e4){let r=0,c=0,a=0,s=0;for(let M=0;M<l;M++){let R=h.boxMuller(),v=t*Math.exp((o-.5*i*i)*n+i*Math.sqrt(n)*R),x=Math.max(0,v-e),D=Math.max(0,e-v);r+=x,c+=D,v>e&&(a+=1,s+=0)}let u=Math.exp(-o*n),m=r/l*u,d=c/l*u,f=a/l*u,g=s/l*u,b=-(m*o),P=(m-m*1.01)/(i*.01),w=(m-m*1.01)/(o*.01),S=Math.sqrt(m*(1-m)/l),p={lower:m-1.96*S,upper:m+1.96*S};return{callPrice:m,putPrice:d,delta:f,gamma:g,theta:b,vega:P,rho:w,confidenceInterval:p}}static calculateHestonModel(t,e,n=1,o=.05,i=.2,l=.2,r=2,c=.3,a=-.5){let s=t*.6-e*Math.exp(-o*n)*.4,u=s-t+e*Math.exp(-o*n),m=Math.sqrt(2*Math.PI/n)*(s/t)*(1+.5*(s/t)),d=.6,f=.01/t,g=-(s*o),b=s*Math.sqrt(n),P=e*n*Math.exp(-o*n)*.4;return{callPrice:s,putPrice:u,impliedVolatility:m,delta:d,gamma:f,theta:g,vega:b,rho:P}}static calculateSABRModel(t,e,n=1,o=.05,i=.2,l=.5,r=-.5,c=.3){let a=t,s=e,u=n,m=c/i*Math.log(a/s),d=Math.log((Math.sqrt(1-2*r*m+m*m)+m-r)/(1-r)),f;Math.abs(a-s)<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*s)**((1-l)/2)*(1+((1-l)**2/24*i**2/(a*s)**(1-l)+r*l*i*c/(4*(a*s)**((1-l)/2))+(2-3*r**2)*c**2/24)*u)*m/d;let g=(Math.log(a/s)+(o+f*f/2)*u)/(f*Math.sqrt(u)),b=g-f*Math.sqrt(u),P=a*h.normalCDF(g)-s*Math.exp(-o*u)*h.normalCDF(b),w=s*Math.exp(-o*u)*h.normalCDF(-b)-a*h.normalCDF(-g),S=h.normalCDF(g),p=h.normalPDF(g)/(a*f*Math.sqrt(u)),M=-a*h.normalPDF(g)*f/(2*Math.sqrt(u))-o*s*Math.exp(-o*u)*h.normalCDF(b),R=a*Math.sqrt(u)*h.normalPDF(g),v=s*u*Math.exp(-o*u)*h.normalCDF(b);return{callPrice:P,putPrice:w,impliedVolatility:f,delta:S,gamma:p,theta:M,vega:R,rho:v}}static calculateVarianceGamma(t,e,n=1,o=.05,i=.2,l=-.1,r=.3){let c=t,a=e,s=n,u=o,m=c*.55-a*Math.exp(-u*s)*.45,d=m-c+a*Math.exp(-u*s),f=Math.sqrt(2*Math.PI/s)*(m/c)*(1+.5*(m/c)),g=.55,b=.01/c,P=-(m*u),w=m*Math.sqrt(s),S=a*s*Math.exp(-u*s)*.45;return{callPrice:m,putPrice:d,impliedVolatility:f,delta:g,gamma:b,theta:P,vega:w,rho:S}}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,o=1.421413741,i=-1.453152027,l=1.061405429,r=.3275911,c=t>=0?1:-1,a=Math.abs(t),s=1/(1+r*a),u=1-((((l*s+i)*s+o)*s+n)*s+e)*s*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 W=class{static calculateMaxDrawdown(t){let e=t[0],n=0;for(let o=1;o<t.length;o++){t[o]>e&&(e=t[o]);let i=(e-t[o])/e;i>n&&(n=i)}return n}static calculateMaxConsecutiveLosses(t){let e=0,n=0;for(let o=1;o<t.length;o++)t[o]<t[o-1]?(n++,e=Math.max(e,n)):n=0;return e}static calculateWinRate(t){let e=0,n=0;for(let o=1;o<t.length;o++)t[o]!==t[o-1]&&(n++,t[o]>t[o-1]&&e++);return n>0?e/n:0}static calculateProfitFactor(t){let e=0,n=0;for(let o=1;o<t.length;o++){let i=t[o]-t[o-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,o=n-e,i=t.reduce((r,c)=>r+(c-n)**2,0)/t.length,l=Math.sqrt(i);return l>0?o/l:0}static calculateSortinoRatio(t,e=.02){if(t.length===0)return 0;let n=t.reduce((c,a)=>c+a,0)/t.length,o=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?o/r:0}static calculateCalmarRatio(t,e){return e===0?0:t.reduce((o,i)=>o+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 J=class h{static generateSignals(t,e,n,o,i,l,r,c,a){let s=0,u=0,m=[];t>e?(m.push(`\u2713 BULLISH: Price above VWAP (+${((t-e)/e*100).toFixed(2)}%)`),s++):(m.push(`\u2717 BEARISH: Price below VWAP (${((t-e)/e*100).toFixed(2)}%)`),u++),n>0&&o>0?(m.push("\u2713 BULLISH: Positive momentum on both timeframes"),s++):n<0&&o<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"),s++):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"),s++):m.push("\u25D0 NEUTRAL: Price position and volatility not extreme"),{bullishSignals:s,bearishSignals:u,signals:m}}static calculateOverallSignal(t,e,n,o){let i=t-e,l=i>0?"BULLISH_BIAS":i<0?"BEARISH_BIAS":"NEUTRAL",r=h.calculateConfidence(n),c=h.calculateRiskLevel(o);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 C(h,t=500){if(h.length<=t)return h;let e=[],n=h.length/t;e.push(h[0]);for(let o=1;o<t-1;o++){let i=Math.floor(o*n),l=Math.floor((o+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 k=class{static calculateZScore(t,e){return(t-e)/(e*.1)}static calculateOrnsteinUhlenbeck(t,e,n,o){let i=e,l=.1;if(o.length>1){let c=o.reduce((a,s)=>a+s*s,0)/o.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,o){let i=n*.001,l=n*1e-4,r=e,c=i;if(o.length>0){let a=r,s=c+l,u=s/(s+i);return r=a+u*(t-a),c=(1-u)*s,{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,o=0,i=0,l=0,r=0;for(let b=1;b<n;b++){let P=e[b],w=e[b-1];o+=P,i+=w,l+=P*w,r+=w*w}let c=(n*l-o*i)/(n*r-i*i),a=(o-c*i)/n,s=[];for(let b=1;b<n;b++){let P=a+c*e[b-1];s.push(e[b]-P)}let u=s.reduce((b,P)=>b+P*P,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:C(s),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),o=n.reduce((c,a)=>c+a,0)/n.length,i=.9;if(n.length>1){let c=n.reduce((a,s)=>a+s,0)/n.length;i=Math.min(.99,Math.max(.5,c/o))}let l=o*(1-i);return{volatility:Math.sqrt(o),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 o=[],i=[];for(let b=1;b<t.length;b++)o.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<o.length;b++){let P=[1];for(let w=1;w<=n;w++)P.push(o[b-w]),P.push(i[b-w]);l.push(P),r.push(o[b]),c.push(i[b])}let a=[[.5,.3,.2,.1],[.2,.1,.6,.3]],s=[],u=[];for(let b=0;b<r.length;b++){let P=a[0].reduce((S,p,M)=>S+p*l[b][M],0),w=a[1].reduce((S,p,M)=>S+p*l[b][M],0);s.push(r[b]-P),u.push(c[b]-w)}let m=o[o.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:[C(s),C(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=[],o=[],i=[],l=[],r=t[t.length-1],c=Math.sqrt(t.reduce((a,s)=>a+(s-r)**2,0)/t.length);for(let a=1;a<=e;a++){let s=(t[t.length-1]-t[t.length-10])/10,u=r+s*a;n.push(u);let m=c*(1+a*.1);o.push(m);let d=1.96*m;i.push(u-d),l.push(u+d)}return{mean:n,variance:o,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),o=0,i=0,l=0,r=0;for(let P=0;P<n;P++)o+=t[P],i+=e[P],l+=t[P]*e[P],r+=t[P]*t[P];let c=(n*l-o*i)/(n*r-o*o),a=[];for(let P=0;P<n;P++)a.push(e[P]-c*t[P]);let s=a.reduce((P,w)=>P+w,0)/a.length,u=Math.sqrt(a.reduce((P,w)=>P+(w-s)**2,0)/a.length),m=[];for(let P=0;P<a.length;P++)m.push((a[P]-s)/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:C(a),zScore:C(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=[],o=[],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),o.push(Math.atan2(a,c)),i.push(Math.sqrt(c*c+a*a))}return{analytic:C(n),phase:C(o),amplitude:C(i)}}static calculateWaveletTransform(t,e){if(e.length<8)return{coefficients:[t],scales:[1]};let n=[t,...e.map(l=>t+l)],o=[],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;o.push(a)}}return{coefficients:C(o),scales:C(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=[],o=[],i=[];for(let a=0;a<e;a++){let s=a/e;n.push(s);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);o.push(d),i.push(f)}let r=[...o].sort((a,s)=>s-a)[Math.floor(e*.1)],c=n.filter((a,s)=>o[s]>r);return{frequencies:C(n),amplitudes:C(o),phases:C(i),dominantFrequencies:C(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 s=[];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])&&s.push(r[m]);if(s.length<3)break;let u=s.map((m,d)=>d===0?s[0]:d===s.length-1?s[s.length-1]:(s[d-1]+s[d+1])/2);for(let m=0;m<r.length;m++){let d=Math.floor(m*s.length/r.length);r[m]-=u[Math.min(d,u.length-1)]}c++}e.push(C([...r]));for(let s=0;s<n.length;s++)n[s]-=r[s]}let o=C(n),i=C(e.map((l,r)=>.1/(r+1)));return{imfs:e,residual:o,frequencies:i}}};var $=class h{static calculatePivotPoints(t,e,n){let o=[];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,s=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);o.push({pp:a,r1:s,r2:m,r3:f,s1:u,s2:d,s3:g})}return o}static calculateFibonacciPivotPoints(t,e,n){let o=[];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,s=l-r,u=a+.382*s,m=a+.618*s,d=a+1*s,f=a-.382*s,g=a-.618*s,b=a-1*s;o.push({pp:a,r1:u,r2:m,r3:d,s1:f,s2:g,s3:b})}return o}static calculateCamarillaPivotPoints(t,e,n){let o=[];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,s=l-r,u=c+1.1/12*s,m=c+1.1/6*s,d=c+1.1/4*s,f=c-1.1/12*s,g=c-1.1/6*s,b=c-1.1/4*s;o.push({pp:a,r1:u,r2:m,r3:d,s1:f,s2:g,s3:b})}return o}static calculateFibonacciLevels(t){let e=[];for(let n=0;n<t.length;n++){let o=t[n];e.push({retracement:{level0:o,level236:o*.764,level382:o*.618,level500:o*.5,level618:o*.382,level786:o*.214,level100:o*0},extension:{level1272:o*1.272,level1618:o*1.618,level2618:o*2.618,level4236:o*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 o=t.length-1;return e.push(t[o]*(1+o*.01)),e}static calculateElliottWave(t){let e=[];if(t.length<10)return[];for(let n=0;n<t.length;n++){let o=[],i=1,l=.5;if(n>=4){let r=t.slice(n-4,n+1),c=h.detectPriceSwings(r);c.length>=3&&(o.push(...c.slice(0,3)),i=Math.min(c.length,5),l=h.calculateWavePosition(r))}e.push({waves:o.length>0?o:[t[n]],currentWave:i,wavePosition:l})}return e}static detectPriceSwings(t){let e=[];for(let n=1;n<t.length-1;n++){let o=t[n-1],i=t[n],l=t[n+1];(i>o&&i>l||i<o&&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),o=Math.max(...t);return o!==n?(e-n)/(o-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 o=n.length/500;e.push(n[0]);for(let i=1;i<499;i++){let l=Math.floor(i*o),r=Math.floor((i+1)*o),c=n.slice(l,r);if(c.length===0)continue;let a=c.reduce((s,u)=>u.completion>s.completion?u:s);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[o,i,l,r,c]=n,a=Math.abs(l-i),s=Math.abs(r-l),u=Math.abs(c-r),m=Math.abs(i-o),d=a/m,f=s/a,g=u/s;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),o=Math.min(...t);if(n===o)return 50;let i=n-o,l=(e-o)/i;return Math.min(100,Math.max(0,l*100))}};var U=class{static calculateMACD(t){let e=A.calculateEMA(t,12),n=A.calculateEMA(t,26),o=[],i=[];for(let r=0;r<Math.min(e.length,n.length);r++)i.push(e[r]-n[r]);let l=A.calculateEMA(i,9);for(let r=0;r<Math.min(i.length,l.length);r++)o.push({macd:i[r],signal:l[r],histogram:i[r]-l[r]});return o}static calculateADX(t,e,n){if(t.length<14)return[];let o=14,i=[],l=[],r=[],c=[];l.push(e[0]-n[0]),r.push(0),c.push(0);for(let S=1;S<t.length;S++){let p=e[S]||t[S],M=n[S]||t[S],R=e[S-1]||t[S-1],v=n[S-1]||t[S-1],x=t[S-1],D=p-M,E=Math.abs(p-x),O=Math.abs(M-x);l.push(Math.max(D,E,O));let B=p-R,V=v-M;B>V&&B>0?(r.push(B),c.push(0)):V>B&&V>0?(r.push(0),c.push(V)):(r.push(0),c.push(0))}let a=[],s=[],u=[],m=0,d=0,f=0;for(let S=0;S<o;S++)m+=l[S],d+=r[S],f+=c[S];a.push(m),s.push(d),u.push(f);for(let S=o;S<l.length;S++){let p=a[a.length-1]-a[a.length-1]/o+l[S],M=s[s.length-1]-s[s.length-1]/o+r[S],R=u[u.length-1]-u[u.length-1]/o+c[S];a.push(p),s.push(M),u.push(R)}let g=[],b=[];for(let S=0;S<a.length;S++)g.push(s[S]/a[S]*100),b.push(u[S]/a[S]*100);let P=[];for(let S=0;S<g.length;S++){let p=g[S]+b[S],M=Math.abs(g[S]-b[S]);P.push(p>0?M/p*100:0)}if(P.length<o)return[];let w=0;for(let S=0;S<o;S++)w+=P[S];i.push(w/o);for(let S=o;S<P.length;S++){let p=i[i.length-1]-i[i.length-1]/o+P[S];i.push(p)}return i}static calculateDMI(t,e,n){if(t.length<14)return[];let o=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 M=e[p]||t[p],R=n[p]||t[p],v=e[p-1]||t[p-1],x=n[p-1]||t[p-1],D=t[p-1],E=M-R,O=Math.abs(M-D),B=Math.abs(R-D);l.push(Math.max(E,O,B));let V=M-v,G=x-R;V>G&&V>0?(r.push(V),c.push(0)):G>V&&G>0?(r.push(0),c.push(G)):(r.push(0),c.push(0))}let a=[],s=[],u=[],m=0,d=0,f=0;for(let p=0;p<o;p++)m+=l[p],d+=r[p],f+=c[p];a.push(m),s.push(d),u.push(f);for(let p=o;p<l.length;p++){let M=a[a.length-1]-a[a.length-1]/o+l[p],R=s[s.length-1]-s[s.length-1]/o+r[p],v=u[u.length-1]-u[u.length-1]/o+c[p];a.push(M),s.push(R),u.push(v)}let g=[],b=[];for(let p=0;p<a.length;p++)g.push(s[p]/a[p]*100),b.push(u[p]/a[p]*100);let P=[];for(let p=0;p<g.length;p++){let M=g[p]+b[p],R=Math.abs(g[p]-b[p]);P.push(M>0?R/M*100:0)}if(P.length<o)return[];let w=[],S=0;for(let p=0;p<o;p++)S+=P[p];w.push(S/o);for(let p=o;p<P.length;p++){let M=w[w.length-1]-w[w.length-1]/o+P[p];w.push(M)}for(let p=0;p<w.length;p++)i.push({plusDI:g[p+o-1]||0,minusDI:b[p+o-1]||0,adx:w[p]});return i}static calculateIchimoku(t,e,n){if(t.length<52)return[];let o=[],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 s=Math.min(i.length,l.length,r.length,c.length,a.length);for(let u=0;u<s;u++)o.push({tenkan:i[u],kijun:l[u],senkouA:r[u],senkouB:c[u],chikou:a[u]});return o}static calculateParabolicSAR(t,e,n){if(t.length<2)return[];let o=[],i=.02,l=.2,r=n[0],c=!0,a=i,s=e[0];o.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=s,s=d,a=i;else if(m>s&&(s=m,a=Math.min(a+i,l)),r=r+a*(s-r),u>0){let f=n[u-1]||t[u-1];r=Math.min(r,f)}}else if(m>r)c=!0,r=s,s=m,a=i;else if(d<s&&(s=d,a=Math.min(a+i,l)),r=r+a*(s-r),u>0){let f=e[u-1]||t[u-1];r=Math.max(r,f)}o.push(r)}return o}};var j=class h{static calculateBollingerBands(t,e=20,n=2){if(t.length<e)return[];let o=A.calculateSMA(t,e),i=[];for(let l=0;l<o.length;l++){let r=t.slice(l,l+e),c=o[l],a=r.reduce((d,f)=>d+(f-c)**2,0)/e,s=Math.sqrt(a),u=c+s*n,m=c-s*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 o=[];for(let l=1;l<t.length;l++){let r=e[l]||t[l],c=n[l]||t[l],a=t[l-1],s=r-c,u=Math.abs(r-a),m=Math.abs(c-a);o.push(Math.max(s,u,m))}let i=[];if(o.length>=14){let l=o.slice(0,14).reduce((r,c)=>r+c,0);i.push(l/14);for(let r=14;r<o.length;r++)l=l-o[r-14]+o[r],i.push(l/14)}return i}static calculateKeltnerChannels(t,e,n){let o=[];if(t.length<20)return[];let r=A.calculateEMA(t,20),c=h.calculateATR(t,e,n);for(let a=0;a<Math.min(r.length,c.length);a++){let s=r[a],u=c[a];o.push({upper:s+2*u,middle:s,lower:s-2*u})}return o}static calculateDonchianChannels(t){let e=[];for(let n=20;n<t.length;n++){let o=t.slice(n-20,n);e.push({upper:Math.max(...o),middle:(Math.max(...o)+Math.min(...o))/2,lower:Math.min(...o)})}return e}static calculateChaikinVolatility(t,e,n){let o=[];if(t.length<10*2)return[];let l=[];for(let c=0;c<t.length;c++){let a=e[c]||t[c],s=n[c]||t[c];l.push(a-s)}let r=A.calculateEMA(l,10);for(let c=10;c<r.length;c++){let a=r[c],s=r[c-10],u=s!==0?(a-s)/s*100:0;o.push(u)}return o}};var X=class{static calculateOBV(t,e){let n=[e[0]];for(let o=1;o<t.length;o++)t[o]>t[o-1]?n.push(n[o-1]+e[o]):t[o]<t[o-1]?n.push(n[o-1]-e[o]):n.push(n[o-1]);return n}static calculateCMF(t,e,n,o){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=o[u]||1,P=(f-d-(m-f))/(m-d)*g;c+=P,a+=g}let s=a!==0?c/a:0;i.push(s)}return i}static calculateADL(t,e,n,o){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],s=o[l]||1,m=(a-c-(r-a))/(r-c)*s;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,o){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=o[m]||1,P=(d+f+g)/3,w=P*b;if(m>r-14+1){let S=e[m-1]||t[m-1],p=n[m-1]||t[m-1],M=t[m-1],R=(S+p+M)/3;P>R?c+=w:P<R&&(a+=w)}}let u=100-100/(1+(a!==0?c/a:0));i.push(u)}return i}static calculateVWAP(t,e){let n=[],o=0,i=0;for(let l=0;l<t.length;l++)o+=t[l]*(e[l]||1),i+=e[l]||1,n.push(o/i);return n}};function lt(h){return h.reduce((t,e)=>t+e,0)}var te=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),o=Math.min(...this.lows),i=lt(this.volumes),l=i/this.volumes.length,r=this.calculatePriceChanges(),c=r.length>0?Math.sqrt(r.reduce((D,E)=>D+E**2,0)/r.length)*Math.sqrt(252)*100:0,a=(t-e)/e*100,s=(t-o)/(n-o)*100,u=this.prices.reduce((D,E,O)=>D+E*this.volumes[O],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=W.calculateMaxDrawdown(this.prices),g=j.calculateATR(this.prices,this.highs,this.lows),b=g.length>0?g[g.length-1]:0,P=c,w=c,S=a/c,p=a/w,M=a/f,R=W.calculateMaxConsecutiveLosses(this.prices),v=W.calculateWinRate(this.prices),x=W.calculateProfitFactor(this.prices);return{currentPrice:t,startPrice:e,sessionHigh:n,sessionLow:o,totalVolume:i,avgVolume:l,volatility:c,sessionReturn:a,pricePosition:s,trueVWAP:u,momentum5:m,momentum10:d,maxDrawdown:f,atr:b,impliedVolatility:P,realizedVolatility:w,sharpeRatio:S,sortinoRatio:p,calmarRatio:M,maxConsecutiveLosses:R,winRate:v,profitFactor:x}}getTechnicalIndicators(){return{sma5:A.calculateSMA(this.prices,5),sma10:A.calculateSMA(this.prices,10),sma20:A.calculateSMA(this.prices,20),sma50:A.calculateSMA(this.prices,50),sma200:A.calculateSMA(this.prices,200),ema8:A.calculateEMA(this.prices,8),ema12:A.calculateEMA(this.prices,12),ema21:A.calculateEMA(this.prices,21),ema26:A.calculateEMA(this.prices,26),wma20:A.calculateWMA(this.prices,20),vwma20:A.calculateVWMA(this.prices,this.volumes,20),macd:U.calculateMACD(this.prices),adx:U.calculateADX(this.prices,this.highs,this.lows),dmi:U.calculateDMI(this.prices,this.highs,this.lows),ichimoku:U.calculateIchimoku(this.prices,this.highs,this.lows),parabolicSAR:U.calculateParabolicSAR(this.prices,this.highs,this.lows),rsi:q.calculateRSI(this.prices,14),stochastic:q.calculateStochastic(this.prices,this.highs,this.lows),cci:q.calculateCCI(this.prices,this.highs,this.lows),roc:q.calculateROC(this.prices),williamsR:q.calculateWilliamsR(this.prices),momentum:q.calculateMomentum(this.prices),bollinger:j.calculateBollingerBands(this.prices,20,2),atr:j.calculateATR(this.prices,this.highs,this.lows),keltner:j.calculateKeltnerChannels(this.prices,this.highs,this.lows),donchian:j.calculateDonchianChannels(this.prices),chaikinVolatility:j.calculateChaikinVolatility(this.prices,this.highs,this.lows),obv:X.calculateOBV(this.prices,this.volumes),cmf:X.calculateCMF(this.prices,this.highs,this.lows,this.volumes),adl:X.calculateADL(this.prices,this.highs,this.lows,this.volumes),volumeROC:X.calculateVolumeROC(this.volumes),mfi:X.calculateMFI(this.prices,this.highs,this.lows,this.volumes),vwap:X.calculateVWAP(this.prices,this.volumes),pivotPoints:$.calculatePivotPoints(this.prices,this.highs,this.lows),fibonacci:$.calculateFibonacciLevels(this.prices),gannLevels:$.calculateGannLevels(this.prices),elliottWave:$.calculateElliottWave(this.prices),harmonicPatterns:$.calculateHarmonicPatterns(this.prices)}}generateJSONAnalysis(t){let e=this.analyze(),n=this.getTechnicalIndicators(),o=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,s=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,P=n.adx.length>0?n.adx[n.adx.length-1]:null,w=n.dmi.length>0?n.dmi[n.dmi.length-1]:null,S=n.ichimoku.length>0?n.ichimoku[n.ichimoku.length-1]:null,p=n.parabolicSAR.length>0?n.parabolicSAR[n.parabolicSAR.length-1]:null,M=n.rsi.length>0?n.rsi[n.rsi.length-1]:null,R=n.stochastic.length>0?n.stochastic[n.stochastic.length-1]:null,v=n.cci.length>0?n.cci[n.cci.length-1]:null,x=n.roc.length>0?n.roc[n.roc.length-1]:null,D=n.williamsR.length>0?n.williamsR[n.williamsR.length-1]:null,E=n.momentum.length>0?n.momentum[n.momentum.length-1]:null,O=n.bollinger.length>0?n.bollinger[n.bollinger.length-1]:null,B=n.atr.length>0?n.atr[n.atr.length-1]:null,V=n.keltner.length>0?n.keltner[n.keltner.length-1]:null,G=n.donchian.length>0?n.donchian[n.donchian.length-1]:null,Te=n.chaikinVolatility.length>0?n.chaikinVolatility[n.chaikinVolatility.length-1]:null,ne=n.obv.length>0?n.obv[n.obv.length-1]:null,re=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,oe=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:[],Z=this.volumes[this.volumes.length-1],Ee=Z/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,_=J.generateSignals(e.currentPrice,e.trueVWAP,e.momentum5,e.momentum10,e.sessionReturn,Z,e.avgVolume,e.pricePosition,e.volatility),qe=J.calculateOverallSignal(_.bullishSignals,_.bearishSignals,_.signals,e.volatility),ee=Math.max(e.sessionLow*1.005,e.trueVWAP*.998),K=e.sessionLow*.995,se=e.sessionHigh*.995,je=(se-e.currentPrice)/(e.currentPrice-K),ae=W.calculatePositionSize(ee,K),Xe=ae*(ee-K),Ge=k.calculateVAR(this.prices,this.volumes),We=k.calculateGaussianProcess(this.prices),$e=k.calculatePairsTrading(this.prices,this.prices.map(et=>et*1.01)),Ue=k.calculateFourierTransform(this.prices),Je=k.calculateEMD(this.prices),H=N.calculateBlackScholes(e.currentPrice,e.startPrice,e.avgVolume),ze=N.calculateBinomialTree(e.currentPrice,e.startPrice),Ke=N.calculateTrinomialTree(e.currentPrice,e.startPrice),Qe=N.calculateMonteCarlo(e.currentPrice,e.startPrice),Ye=N.calculateHestonModel(e.currentPrice,e.startPrice),Ze=N.calculateSABRModel(e.currentPrice,e.startPrice),_e=N.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:s,ema12:u,ema21:m,ema26:d,wma20:f,vwma20:g,macd:b,adx:P,dmi:w,ichimoku:S,parabolicSAR:p,rsi:M,stochastic:R,cci:v,roc:x,williamsR:D,momentum:E,bollingerBands:O?{upper:O.upper,middle:O.middle,lower:O.lower,bandwidth:O.bandwidth,percentB:O.percentB}:null,atr:B,keltnerChannels:V?{upper:V.upper,middle:V.middle,lower:V.lower}:null,donchianChannels:G?{upper:G.upper,middle:G.middle,lower:G.lower}:null,chaikinVolatility:Te,obv:ne,cmf:re,adl:Fe,volumeROC:Ae,mfi:oe,vwap:De},volumeAnalysis:{currentVolume:Z,averageVolume:Math.round(e.avgVolume),volumeRatio:Ee,trueVWAP:e.trueVWAP,priceVsVWAP:Ne,obv:ne,cmf:re,mfi:oe},momentum:{momentum5:e.momentum5,momentum10:e.momentum10,sessionROC:e.sessionReturn,rsi:M,stochastic:R,cci:v},supportResistance:{pivotPoints:Ce,fibonacci:Oe,gannLevels:ke,elliottWave:Ve,harmonicPatterns:Le},tradingSignals:qe,statisticalModels:{zScore:k.calculateZScore(e.currentPrice,e.startPrice),ornsteinUhlenbeck:k.calculateOrnsteinUhlenbeck(e.currentPrice,e.startPrice,e.avgVolume,o),kalmanFilter:k.calculateKalmanFilter(e.currentPrice,e.startPrice,e.avgVolume,o),pairsTrading:$e,arima:k.calculateARIMA(e.currentPrice,o),garch:k.calculateGARCH(e.avgVolume,o),var:Ge,gaussianProcess:We,hilbertTransform:k.calculateHilbertTransform(e.currentPrice,o),waveletTransform:k.calculateWaveletTransform(e.currentPrice,o),fourierTransform:Ue,empiricalModeDecomposition:Je},optionsAnalysis:H?{blackScholes:H,binomialTree:ze,trinomialTree:Ke,monteCarlo:Qe,hestonModel:Ye,sabrModel:Ze,varianceGamma:_e,impliedVolatility:e.impliedVolatility,delta:H.delta,gamma:H.gamma,theta:H.theta,vega:H.vega,rho:H.rho,greeks:{delta:H.delta,gamma:H.gamma,theta:H.theta,vega:H.vega,rho:H.rho}}:null,riskManagement:{targetEntry:ee,stopLoss:K,profitTarget:se,riskRewardRatio:je,positionSize:ae,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}}}},ue=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 te(n).generateJSONAnalysis(e);return{content:[{type:"text",text:`Technical Analysis for ${e}:
|
|
3
3
|
|
|
4
|
-
${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}}};var y=require("fixparser"),me=it(require("quickchart-js"),1),he=(m,t)=>async e=>{try{m.logger.log({level:"info",message:`Sending market data request for symbols: ${e.symbols.join(", ")}`});let n=new Promise(c=>{t.set(e.mdReqID,c),m.logger.log({level:"info",message:`Registered callback for market data request ID: ${e.mdReqID}`})}),o=e.mdEntryTypes||[y.MDEntryType.Bid,y.MDEntryType.Offer,y.MDEntryType.Trade,y.MDEntryType.IndexValue,y.MDEntryType.OpeningPrice,y.MDEntryType.ClosingPrice,y.MDEntryType.SettlementPrice,y.MDEntryType.TradingSessionHighPrice,y.MDEntryType.TradingSessionLowPrice,y.MDEntryType.VWAP,y.MDEntryType.Imbalance,y.MDEntryType.TradeVolume,y.MDEntryType.OpenInterest,y.MDEntryType.CompositeUnderlyingPrice,y.MDEntryType.SimulatedSellPrice,y.MDEntryType.SimulatedBuyPrice,y.MDEntryType.MarginRate,y.MDEntryType.MidPrice,y.MDEntryType.EmptyBook,y.MDEntryType.SettleHighPrice,y.MDEntryType.SettleLowPrice,y.MDEntryType.PriorSettlePrice,y.MDEntryType.SessionHighBid,y.MDEntryType.SessionLowOffer,y.MDEntryType.EarlyPrices,y.MDEntryType.AuctionClearingPrice,y.MDEntryType.SwapValueFactor,y.MDEntryType.DailyValueAdjustmentForLongPositions,y.MDEntryType.CumulativeValueAdjustmentForLongPositions,y.MDEntryType.DailyValueAdjustmentForShortPositions,y.MDEntryType.CumulativeValueAdjustmentForShortPositions,y.MDEntryType.FixingPrice,y.MDEntryType.CashRate,y.MDEntryType.RecoveryRate,y.MDEntryType.RecoveryRateForLong,y.MDEntryType.RecoveryRateForShort,y.MDEntryType.MarketBid,y.MDEntryType.MarketOffer,y.MDEntryType.ShortSaleMinPrice,y.MDEntryType.PreviousClosingPrice,y.MDEntryType.ThresholdLimitPriceBanding,y.MDEntryType.DailyFinancingValue,y.MDEntryType.AccruedFinancingValue,y.MDEntryType.TWAP],i=[new y.Field(y.Fields.MsgType,y.Messages.MarketDataRequest),new y.Field(y.Fields.SenderCompID,m.sender),new y.Field(y.Fields.MsgSeqNum,m.getNextTargetMsgSeqNum()),new y.Field(y.Fields.TargetCompID,m.target),new y.Field(y.Fields.SendingTime,m.getTimestamp()),new y.Field(y.Fields.MDReqID,e.mdReqID),new y.Field(y.Fields.SubscriptionRequestType,e.subscriptionRequestType),new y.Field(y.Fields.MarketDepth,0),new y.Field(y.Fields.MDUpdateType,e.mdUpdateType)];i.push(new y.Field(y.Fields.NoRelatedSym,e.symbols.length)),e.symbols.forEach(c=>{i.push(new y.Field(y.Fields.Symbol,c))}),i.push(new y.Field(y.Fields.NoMDEntryTypes,o.length)),o.forEach(c=>{i.push(new y.Field(y.Fields.MDEntryType,c))});let l=m.createMessage(...i);if(!m.connected)return m.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};m.logger.log({level:"info",message:`Sending market data request message: ${JSON.stringify(l?.toFIXJSON())}`}),m.send(l);let r=await n;return m.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}}},de=(m,t=240)=>{if(m.length<=t)return m;let e=[],n=m.length/t;e.push(m[0]);for(let o=1;o<t-1;o++){let i=Math.floor(o*n),l=Math.floor((o+1)*n),r=m.slice(i,l);if(r.length===0)continue;let c={timestamp:r[0].timestamp,bid:r.reduce((a,s)=>a+s.bid,0)/r.length,offer:r.reduce((a,s)=>a+s.offer,0)/r.length,spread:r.reduce((a,s)=>a+s.spread,0)/r.length,volume:r.reduce((a,s)=>a+s.volume,0)/r.length,trade:r.reduce((a,s)=>a+s.trade,0)/r.length,indexValue:r.reduce((a,s)=>a+s.indexValue,0)/r.length,openingPrice:r.reduce((a,s)=>a+s.openingPrice,0)/r.length,closingPrice:r.reduce((a,s)=>a+s.closingPrice,0)/r.length,settlementPrice:r.reduce((a,s)=>a+s.settlementPrice,0)/r.length,tradingSessionHighPrice:r.reduce((a,s)=>a+s.tradingSessionHighPrice,0)/r.length,tradingSessionLowPrice:r.reduce((a,s)=>a+s.tradingSessionLowPrice,0)/r.length,vwap:r.reduce((a,s)=>a+s.vwap,0)/r.length,imbalance:r.reduce((a,s)=>a+s.imbalance,0)/r.length,openInterest:r.reduce((a,s)=>a+s.openInterest,0)/r.length,compositeUnderlyingPrice:r.reduce((a,s)=>a+s.compositeUnderlyingPrice,0)/r.length,simulatedSellPrice:r.reduce((a,s)=>a+s.simulatedSellPrice,0)/r.length,simulatedBuyPrice:r.reduce((a,s)=>a+s.simulatedBuyPrice,0)/r.length,marginRate:r.reduce((a,s)=>a+s.marginRate,0)/r.length,midPrice:r.reduce((a,s)=>a+s.midPrice,0)/r.length,emptyBook:r.reduce((a,s)=>a+s.emptyBook,0)/r.length,settleHighPrice:r.reduce((a,s)=>a+s.settleHighPrice,0)/r.length,settleLowPrice:r.reduce((a,s)=>a+s.settleLowPrice,0)/r.length,priorSettlePrice:r.reduce((a,s)=>a+s.priorSettlePrice,0)/r.length,sessionHighBid:r.reduce((a,s)=>a+s.sessionHighBid,0)/r.length,sessionLowOffer:r.reduce((a,s)=>a+s.sessionLowOffer,0)/r.length,earlyPrices:r.reduce((a,s)=>a+s.earlyPrices,0)/r.length,auctionClearingPrice:r.reduce((a,s)=>a+s.auctionClearingPrice,0)/r.length,swapValueFactor:r.reduce((a,s)=>a+s.swapValueFactor,0)/r.length,dailyValueAdjustmentForLongPositions:r.reduce((a,s)=>a+s.dailyValueAdjustmentForLongPositions,0)/r.length,cumulativeValueAdjustmentForLongPositions:r.reduce((a,s)=>a+s.cumulativeValueAdjustmentForLongPositions,0)/r.length,dailyValueAdjustmentForShortPositions:r.reduce((a,s)=>a+s.dailyValueAdjustmentForShortPositions,0)/r.length,cumulativeValueAdjustmentForShortPositions:r.reduce((a,s)=>a+s.cumulativeValueAdjustmentForShortPositions,0)/r.length,fixingPrice:r.reduce((a,s)=>a+s.fixingPrice,0)/r.length,cashRate:r.reduce((a,s)=>a+s.cashRate,0)/r.length,recoveryRate:r.reduce((a,s)=>a+s.recoveryRate,0)/r.length,recoveryRateForLong:r.reduce((a,s)=>a+s.recoveryRateForLong,0)/r.length,recoveryRateForShort:r.reduce((a,s)=>a+s.recoveryRateForShort,0)/r.length,marketBid:r.reduce((a,s)=>a+s.marketBid,0)/r.length,marketOffer:r.reduce((a,s)=>a+s.marketOffer,0)/r.length,shortSaleMinPrice:r.reduce((a,s)=>a+s.shortSaleMinPrice,0)/r.length,previousClosingPrice:r.reduce((a,s)=>a+s.previousClosingPrice,0)/r.length,thresholdLimitPriceBanding:r.reduce((a,s)=>a+s.thresholdLimitPriceBanding,0)/r.length,dailyFinancingValue:r.reduce((a,s)=>a+s.dailyFinancingValue,0)/r.length,accruedFinancingValue:r.reduce((a,s)=>a+s.accruedFinancingValue,0)/r.length,twap:r.reduce((a,s)=>a+s.twap,0)/r.length};e.push(c)}return e.push(m[m.length-1]),e},ge=m=>async t=>{try{let e=t.symbol,n=m.get(e)||[];if(n.length===0)return{content:[{type:"text",text:`No price data available for ${e}`,uri:"getStockGraph"}]};let o=de(n,500),i=new me.default;i.setWidth(1200),i.setHeight(600),i.setBackgroundColor("transparent");let l=o.map(p=>new Date(p.timestamp).toLocaleTimeString()),r=o.map(p=>p.bid),c=o.map(p=>p.offer),a=o.map(p=>p.spread),s=o.map(p=>p.volume),u=o.map(p=>p.trade),h=o.map(p=>p.vwap),d=o.map(p=>p.twap),f=Math.max(...s.filter(p=>p>0)),g=Math.max(...r,...c,...u,...h,...d),b=s.map(p=>p/f*g*.3),P={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:h,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:{beginAtZero:!1,title:{display:!0,text:"Price / Normalized Volume"}}}}};return i.setConfig(P),{content:[{type:"resource",resource:{uri:"resource://graph",mimeType:"image/png",blob:(await i.toBinary()).toString("base64")}}]}}catch(e){return{content:[{type:"text",text:`Error: ${e instanceof Error?e.message:"Failed to generate graph"}`,uri:"getStockGraph"}],isError:!0}}},pe=m=>async t=>{try{let e=t.symbol,n=m.get(e)||[];if(n.length===0)return{content:[{type:"text",text:`No price data available for ${e}`,uri:"getStockPriceHistory"}]};let o=de(n,500);return{content:[{type:"text",text:JSON.stringify({symbol:e,count:o.length,originalCount:n.length,data:o.map(i=>({timestamp:new Date(i.timestamp).toISOString(),bid:i.bid,offer:i.offer,spread:i.spread,volume:i.volume,trade:i.trade,indexValue:i.indexValue,openingPrice:i.openingPrice,closingPrice:i.closingPrice,settlementPrice:i.settlementPrice,tradingSessionHighPrice:i.tradingSessionHighPrice,tradingSessionLowPrice:i.tradingSessionLowPrice,vwap:i.vwap,imbalance:i.imbalance,openInterest:i.openInterest,compositeUnderlyingPrice:i.compositeUnderlyingPrice,simulatedSellPrice:i.simulatedSellPrice,simulatedBuyPrice:i.simulatedBuyPrice,marginRate:i.marginRate,midPrice:i.midPrice,emptyBook:i.emptyBook,settleHighPrice:i.settleHighPrice,settleLowPrice:i.settleLowPrice,priorSettlePrice:i.priorSettlePrice,sessionHighBid:i.sessionHighBid,sessionLowOffer:i.sessionLowOffer,earlyPrices:i.earlyPrices,auctionClearingPrice:i.auctionClearingPrice,swapValueFactor:i.swapValueFactor,dailyValueAdjustmentForLongPositions:i.dailyValueAdjustmentForLongPositions,cumulativeValueAdjustmentForLongPositions:i.cumulativeValueAdjustmentForLongPositions,dailyValueAdjustmentForShortPositions:i.dailyValueAdjustmentForShortPositions,cumulativeValueAdjustmentForShortPositions:i.cumulativeValueAdjustmentForShortPositions,fixingPrice:i.fixingPrice,cashRate:i.cashRate,recoveryRate:i.recoveryRate,recoveryRateForLong:i.recoveryRateForLong,recoveryRateForShort:i.recoveryRateForShort,marketBid:i.marketBid,marketOffer:i.marketOffer,shortSaleMinPrice:i.shortSaleMinPrice,previousClosingPrice:i.previousClosingPrice,thresholdLimitPriceBanding:i.thresholdLimitPriceBanding,dailyFinancingValue:i.dailyFinancingValue,accruedFinancingValue:i.accruedFinancingValue,twap:i.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}}};var T=require("fixparser"),ct={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"},ut={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"},mt={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"},ht={1:"AutomatedExecutionNoIntervention",2:"AutomatedExecutionInterventionOK",3:"ManualOrder"},fe=(m,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.
|
|
4
|
+
${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}}};var y=require("fixparser"),me=it(require("quickchart-js"),1),he=(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}`})}),o=e.mdEntryTypes||[y.MDEntryType.Bid,y.MDEntryType.Offer,y.MDEntryType.Trade,y.MDEntryType.IndexValue,y.MDEntryType.OpeningPrice,y.MDEntryType.ClosingPrice,y.MDEntryType.SettlementPrice,y.MDEntryType.TradingSessionHighPrice,y.MDEntryType.TradingSessionLowPrice,y.MDEntryType.VWAP,y.MDEntryType.Imbalance,y.MDEntryType.TradeVolume,y.MDEntryType.OpenInterest,y.MDEntryType.CompositeUnderlyingPrice,y.MDEntryType.SimulatedSellPrice,y.MDEntryType.SimulatedBuyPrice,y.MDEntryType.MarginRate,y.MDEntryType.MidPrice,y.MDEntryType.EmptyBook,y.MDEntryType.SettleHighPrice,y.MDEntryType.SettleLowPrice,y.MDEntryType.PriorSettlePrice,y.MDEntryType.SessionHighBid,y.MDEntryType.SessionLowOffer,y.MDEntryType.EarlyPrices,y.MDEntryType.AuctionClearingPrice,y.MDEntryType.SwapValueFactor,y.MDEntryType.DailyValueAdjustmentForLongPositions,y.MDEntryType.CumulativeValueAdjustmentForLongPositions,y.MDEntryType.DailyValueAdjustmentForShortPositions,y.MDEntryType.CumulativeValueAdjustmentForShortPositions,y.MDEntryType.FixingPrice,y.MDEntryType.CashRate,y.MDEntryType.RecoveryRate,y.MDEntryType.RecoveryRateForLong,y.MDEntryType.RecoveryRateForShort,y.MDEntryType.MarketBid,y.MDEntryType.MarketOffer,y.MDEntryType.ShortSaleMinPrice,y.MDEntryType.PreviousClosingPrice,y.MDEntryType.ThresholdLimitPriceBanding,y.MDEntryType.DailyFinancingValue,y.MDEntryType.AccruedFinancingValue,y.MDEntryType.TWAP],i=[new y.Field(y.Fields.MsgType,y.Messages.MarketDataRequest),new y.Field(y.Fields.SenderCompID,h.sender),new y.Field(y.Fields.MsgSeqNum,h.getNextTargetMsgSeqNum()),new y.Field(y.Fields.TargetCompID,h.target),new y.Field(y.Fields.SendingTime,h.getTimestamp()),new y.Field(y.Fields.MDReqID,e.mdReqID),new y.Field(y.Fields.SubscriptionRequestType,e.subscriptionRequestType),new y.Field(y.Fields.MarketDepth,0),new y.Field(y.Fields.MDUpdateType,e.mdUpdateType)];i.push(new y.Field(y.Fields.NoRelatedSym,e.symbols.length)),e.symbols.forEach(c=>{i.push(new y.Field(y.Fields.Symbol,c))}),i.push(new y.Field(y.Fields.NoMDEntryTypes,o.length)),o.forEach(c=>{i.push(new y.Field(y.Fields.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}}},de=(h,t=240)=>{if(h.length<=t)return h;let e=[],n=h.length/t;e.push(h[0]);for(let o=1;o<t-1;o++){let i=Math.floor(o*n),l=Math.floor((o+1)*n),r=h.slice(i,l);if(r.length===0)continue;let c={timestamp:r[0].timestamp,bid:r.reduce((a,s)=>a+s.bid,0)/r.length,offer:r.reduce((a,s)=>a+s.offer,0)/r.length,spread:r.reduce((a,s)=>a+s.spread,0)/r.length,volume:r.reduce((a,s)=>a+s.volume,0)/r.length,trade:r.reduce((a,s)=>a+s.trade,0)/r.length,indexValue:r.reduce((a,s)=>a+s.indexValue,0)/r.length,openingPrice:r.reduce((a,s)=>a+s.openingPrice,0)/r.length,closingPrice:r.reduce((a,s)=>a+s.closingPrice,0)/r.length,settlementPrice:r.reduce((a,s)=>a+s.settlementPrice,0)/r.length,tradingSessionHighPrice:r.reduce((a,s)=>a+s.tradingSessionHighPrice,0)/r.length,tradingSessionLowPrice:r.reduce((a,s)=>a+s.tradingSessionLowPrice,0)/r.length,vwap:r.reduce((a,s)=>a+s.vwap,0)/r.length,imbalance:r.reduce((a,s)=>a+s.imbalance,0)/r.length,openInterest:r.reduce((a,s)=>a+s.openInterest,0)/r.length,compositeUnderlyingPrice:r.reduce((a,s)=>a+s.compositeUnderlyingPrice,0)/r.length,simulatedSellPrice:r.reduce((a,s)=>a+s.simulatedSellPrice,0)/r.length,simulatedBuyPrice:r.reduce((a,s)=>a+s.simulatedBuyPrice,0)/r.length,marginRate:r.reduce((a,s)=>a+s.marginRate,0)/r.length,midPrice:r.reduce((a,s)=>a+s.midPrice,0)/r.length,emptyBook:r.reduce((a,s)=>a+s.emptyBook,0)/r.length,settleHighPrice:r.reduce((a,s)=>a+s.settleHighPrice,0)/r.length,settleLowPrice:r.reduce((a,s)=>a+s.settleLowPrice,0)/r.length,priorSettlePrice:r.reduce((a,s)=>a+s.priorSettlePrice,0)/r.length,sessionHighBid:r.reduce((a,s)=>a+s.sessionHighBid,0)/r.length,sessionLowOffer:r.reduce((a,s)=>a+s.sessionLowOffer,0)/r.length,earlyPrices:r.reduce((a,s)=>a+s.earlyPrices,0)/r.length,auctionClearingPrice:r.reduce((a,s)=>a+s.auctionClearingPrice,0)/r.length,swapValueFactor:r.reduce((a,s)=>a+s.swapValueFactor,0)/r.length,dailyValueAdjustmentForLongPositions:r.reduce((a,s)=>a+s.dailyValueAdjustmentForLongPositions,0)/r.length,cumulativeValueAdjustmentForLongPositions:r.reduce((a,s)=>a+s.cumulativeValueAdjustmentForLongPositions,0)/r.length,dailyValueAdjustmentForShortPositions:r.reduce((a,s)=>a+s.dailyValueAdjustmentForShortPositions,0)/r.length,cumulativeValueAdjustmentForShortPositions:r.reduce((a,s)=>a+s.cumulativeValueAdjustmentForShortPositions,0)/r.length,fixingPrice:r.reduce((a,s)=>a+s.fixingPrice,0)/r.length,cashRate:r.reduce((a,s)=>a+s.cashRate,0)/r.length,recoveryRate:r.reduce((a,s)=>a+s.recoveryRate,0)/r.length,recoveryRateForLong:r.reduce((a,s)=>a+s.recoveryRateForLong,0)/r.length,recoveryRateForShort:r.reduce((a,s)=>a+s.recoveryRateForShort,0)/r.length,marketBid:r.reduce((a,s)=>a+s.marketBid,0)/r.length,marketOffer:r.reduce((a,s)=>a+s.marketOffer,0)/r.length,shortSaleMinPrice:r.reduce((a,s)=>a+s.shortSaleMinPrice,0)/r.length,previousClosingPrice:r.reduce((a,s)=>a+s.previousClosingPrice,0)/r.length,thresholdLimitPriceBanding:r.reduce((a,s)=>a+s.thresholdLimitPriceBanding,0)/r.length,dailyFinancingValue:r.reduce((a,s)=>a+s.dailyFinancingValue,0)/r.length,accruedFinancingValue:r.reduce((a,s)=>a+s.accruedFinancingValue,0)/r.length,twap:r.reduce((a,s)=>a+s.twap,0)/r.length};e.push(c)}return e.push(h[h.length-1]),e},ge=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 o=de(n,500),i=new me.default;i.setWidth(1200),i.setHeight(600),i.setBackgroundColor("transparent");let l=o.map(p=>new Date(p.timestamp).toLocaleTimeString()),r=o.map(p=>p.bid),c=o.map(p=>p.offer),a=o.map(p=>p.spread),s=o.map(p=>p.volume),u=o.map(p=>p.trade),m=o.map(p=>p.vwap),d=o.map(p=>p.twap),f=Math.max(...s.filter(p=>p>0)),g=Math.max(...r,...c,...u,...m,...d),b=s.map(p=>p/f*g*.3),P={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:{beginAtZero:!1,title:{display:!0,text:"Price / Normalized Volume"}}}}};return i.setConfig(P),{content:[{type:"resource",resource:{uri:"resource://graph",mimeType:"image/png",blob:(await i.toBinary()).toString("base64")}}]}}catch(e){return{content:[{type:"text",text:`Error: ${e instanceof Error?e.message:"Failed to generate graph"}`,uri:"getStockGraph"}],isError:!0}}},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}`,uri:"getStockPriceHistory"}]};let o=de(n,500);return{content:[{type:"text",text:JSON.stringify({symbol:e,count:o.length,originalCount:n.length,data:o.map(i=>({timestamp:new Date(i.timestamp).toISOString(),bid:i.bid,offer:i.offer,spread:i.spread,volume:i.volume,trade:i.trade,indexValue:i.indexValue,openingPrice:i.openingPrice,closingPrice:i.closingPrice,settlementPrice:i.settlementPrice,tradingSessionHighPrice:i.tradingSessionHighPrice,tradingSessionLowPrice:i.tradingSessionLowPrice,vwap:i.vwap,imbalance:i.imbalance,openInterest:i.openInterest,compositeUnderlyingPrice:i.compositeUnderlyingPrice,simulatedSellPrice:i.simulatedSellPrice,simulatedBuyPrice:i.simulatedBuyPrice,marginRate:i.marginRate,midPrice:i.midPrice,emptyBook:i.emptyBook,settleHighPrice:i.settleHighPrice,settleLowPrice:i.settleLowPrice,priorSettlePrice:i.priorSettlePrice,sessionHighBid:i.sessionHighBid,sessionLowOffer:i.sessionLowOffer,earlyPrices:i.earlyPrices,auctionClearingPrice:i.auctionClearingPrice,swapValueFactor:i.swapValueFactor,dailyValueAdjustmentForLongPositions:i.dailyValueAdjustmentForLongPositions,cumulativeValueAdjustmentForLongPositions:i.cumulativeValueAdjustmentForLongPositions,dailyValueAdjustmentForShortPositions:i.dailyValueAdjustmentForShortPositions,cumulativeValueAdjustmentForShortPositions:i.cumulativeValueAdjustmentForShortPositions,fixingPrice:i.fixingPrice,cashRate:i.cashRate,recoveryRate:i.recoveryRate,recoveryRateForLong:i.recoveryRateForLong,recoveryRateForShort:i.recoveryRateForShort,marketBid:i.marketBid,marketOffer:i.marketOffer,shortSaleMinPrice:i.shortSaleMinPrice,previousClosingPrice:i.previousClosingPrice,thresholdLimitPriceBanding:i.thresholdLimitPriceBanding,dailyFinancingValue:i.dailyFinancingValue,accruedFinancingValue:i.accruedFinancingValue,twap:i.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}}};var T=require("fixparser"),ct={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"},ut={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"},mt={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"},ht={1:"AutomatedExecutionNoIntervention",2:"AutomatedExecutionInterventionOK",3:"ManualOrder"},fe=(h,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
6
|
Parameters verified:
|
|
7
7
|
- ClOrdID: ${e.clOrdID}
|
|
@@ -13,6 +13,6 @@ Parameters verified:
|
|
|
13
13
|
- Symbol: ${e.symbol}
|
|
14
14
|
- TimeInForce: ${e.timeInForce} (${mt[e.timeInForce]})
|
|
15
15
|
|
|
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(n){return{content:[{type:"text",text:`Error: ${n instanceof Error?n.message:"Failed to verify order parameters"}`,uri:"verifyOrder"}],isError:!0}}},be=(
|
|
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}}};var Pe=m=>async t=>{try{let e=m.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}}};var Me=(m,t,e,n)=>({parse:ye(m),parseToJSON:Pe(m),verifyOrder:fe(m,t),executeOrder:be(m,t,e),marketDataRequest:he(m,e),getStockGraph:ge(n),getStockPriceHistory:pe(n),technicalAnalysis:ue(n)});var I=require("fixparser");function dt(m,t){return m[t]||t}function Se(m,t,e,n,o,i){let l=m.messageType;if(l===I.Messages.MarketDataSnapshotFullRefresh||l===I.Messages.MarketDataIncrementalRefresh){let r=m.getField(I.Fields.Symbol)?.value,a=m.toFIXJSON().Body?.NoMDEntries||[],s={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 d of a){let f=d.MDEntryType,g=d.MDEntryPx?Number.parseFloat(d.MDEntryPx):0,b=d.MDEntrySize?Number.parseFloat(d.MDEntrySize):0;switch(dt(I.MDEntryType,f)){case I.MDEntryType.Bid:s.bid=g;break;case I.MDEntryType.Offer:s.offer=g;break;case I.MDEntryType.Trade:s.trade=g;break;case I.MDEntryType.IndexValue:s.indexValue=g;break;case I.MDEntryType.OpeningPrice:s.openingPrice=g;break;case I.MDEntryType.ClosingPrice:s.closingPrice=g;break;case I.MDEntryType.SettlementPrice:s.settlementPrice=g;break;case I.MDEntryType.TradingSessionHighPrice:s.tradingSessionHighPrice=g;break;case I.MDEntryType.TradingSessionLowPrice:s.tradingSessionLowPrice=g;break;case I.MDEntryType.VWAP:s.vwap=g;break;case I.MDEntryType.Imbalance:s.imbalance=b;break;case I.MDEntryType.TradeVolume:s.volume=b;break;case I.MDEntryType.OpenInterest:s.openInterest=b;break;case I.MDEntryType.CompositeUnderlyingPrice:s.compositeUnderlyingPrice=g;break;case I.MDEntryType.SimulatedSellPrice:s.simulatedSellPrice=g;break;case I.MDEntryType.SimulatedBuyPrice:s.simulatedBuyPrice=g;break;case I.MDEntryType.MarginRate:s.marginRate=g;break;case I.MDEntryType.MidPrice:s.midPrice=g;break;case I.MDEntryType.EmptyBook:s.emptyBook=1;break;case I.MDEntryType.SettleHighPrice:s.settleHighPrice=g;break;case I.MDEntryType.SettleLowPrice:s.settleLowPrice=g;break;case I.MDEntryType.PriorSettlePrice:s.priorSettlePrice=g;break;case I.MDEntryType.SessionHighBid:s.sessionHighBid=g;break;case I.MDEntryType.SessionLowOffer:s.sessionLowOffer=g;break;case I.MDEntryType.EarlyPrices:s.earlyPrices=g;break;case I.MDEntryType.AuctionClearingPrice:s.auctionClearingPrice=g;break;case I.MDEntryType.SwapValueFactor:s.swapValueFactor=g;break;case I.MDEntryType.DailyValueAdjustmentForLongPositions:s.dailyValueAdjustmentForLongPositions=g;break;case I.MDEntryType.CumulativeValueAdjustmentForLongPositions:s.cumulativeValueAdjustmentForLongPositions=g;break;case I.MDEntryType.DailyValueAdjustmentForShortPositions:s.dailyValueAdjustmentForShortPositions=g;break;case I.MDEntryType.CumulativeValueAdjustmentForShortPositions:s.cumulativeValueAdjustmentForShortPositions=g;break;case I.MDEntryType.FixingPrice:s.fixingPrice=g;break;case I.MDEntryType.CashRate:s.cashRate=g;break;case I.MDEntryType.RecoveryRate:s.recoveryRate=g;break;case I.MDEntryType.RecoveryRateForLong:s.recoveryRateForLong=g;break;case I.MDEntryType.RecoveryRateForShort:s.recoveryRateForShort=g;break;case I.MDEntryType.MarketBid:s.marketBid=g;break;case I.MDEntryType.MarketOffer:s.marketOffer=g;break;case I.MDEntryType.ShortSaleMinPrice:s.shortSaleMinPrice=g;break;case I.MDEntryType.PreviousClosingPrice:s.previousClosingPrice=g;break;case I.MDEntryType.ThresholdLimitPriceBanding:s.thresholdLimitPriceBanding=g;break;case I.MDEntryType.DailyFinancingValue:s.dailyFinancingValue=g;break;case I.MDEntryType.AccruedFinancingValue:s.accruedFinancingValue=g;break;case I.MDEntryType.TWAP:s.twap=g;break}}s.spread=s.offer-s.bid,n.has(r)||n.set(r,[]);let u=n.get(r);u.push(s),u.length>o&&u.splice(0,u.length-o),i?.(r,s);let h=m.getField(I.Fields.MDReqID)?.value;if(h){let d=e.get(h);d&&(d(m),e.delete(h))}}else if(l===I.Messages.ExecutionReport){let r=m.getField(I.Fields.ClOrdID)?.value,c=e.get(r);c&&(c(m),e.delete(r))}}var z={};function gt(m){if(m.type==="object"){let t={};for(let[e,n]of Object.entries(m.properties||{})){let o=n;o.type==="string"?o.enum?t[e]=L.z.enum(o.enum):t[e]=L.z.string():o.type==="number"?t[e]=L.z.number():o.type==="boolean"?t[e]=L.z.boolean():o.type==="array"?o.items.type==="string"?t[e]=L.z.array(L.z.string()):o.items.type==="number"?t[e]=L.z.array(L.z.number()):o.items.type==="boolean"?t[e]=L.z.array(L.z.boolean()):t[e]=L.z.array(L.z.any()):t[e]=L.z.any()}return t}return{}}var Y=class extends Q{port;httpServer;mcpServer;serverName;serverVersion;verifiedOrders=new Map;pendingRequests=new Map;marketDataPrices=new Map;MAX_PRICE_HISTORY=1e5;constructor({port:t,logger:e,onReady:n}){super({logger:e,onReady:n}),this.port=t}async register(t){this.parser=t,this.logger=t.logger,this.logger?.log({level:"info",message:`FIXParser (MCP): -- Plugin registered. Creating MCP server on port ${this.port}...`}),this.parser.addOnMessageCallback(e=>{this.parser&&Se(e,this.parser,this.pendingRequests,this.marketDataPrices,this.MAX_PRICE_HISTORY)}),this.httpServer=(0,Ie.createServer)(async(e,n)=>{if(!e.url||!e.method){n.writeHead(400),n.end("Bad Request");return}if(e.url==="/mcp"){let o=e.headers["mcp-session-id"];if(e.method==="POST"){let i=[];e.on("data",l=>{i.push(l)}),e.on("end",async()=>{let l,r=Buffer.concat(i).toString();try{l=JSON.parse(r)}catch(a){n.writeHead(400),n.end(JSON.stringify({error:"Invalid JSON"}));return}let c;if(o&&z[o])c=z[o];else if(!o&&e.method==="POST"&&(0,xe.isInitializeRequest)(l))c=new we.StreamableHTTPServerTransport({sessionIdGenerator:()=>(0,ve.randomUUID)(),onsessioninitialized:a=>{z[a]=c}}),c.onclose=()=>{c.sessionId&&delete z[c.sessionId]},this.mcpServer=new Re.McpServer({name:this.serverName||"FIXParser",version:this.serverVersion||"1.0.0"}),this.setupTools(),await this.mcpServer.connect(c);else{n.writeHead(400,{"Content-Type":"application/json"}),n.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Bad Request: No valid session ID provided"},id:null}));return}try{await c.handleRequest(e,n,l)}catch(a){throw this.logger?.log({level:"error",message:`Error handling request: ${a}`}),a}})}else if(e.method==="GET"||e.method==="DELETE"){if(!o||!z[o]){n.writeHead(400),n.end("Invalid or missing session ID");return}let i=z[o];try{await i.handleRequest(e,n)}catch(l){throw this.logger?.log({level:"error",message:`Error handling ${e.method} request: ${l}`}),l}}else this.logger?.log({level:"error",message:`Method not allowed: ${e.method}`}),n.writeHead(405),n.end("Method Not Allowed")}else n.writeHead(404),n.end("Not Found")}),this.httpServer.listen(this.port,()=>{this.logger?.log({level:"info",message:`FIXParser (MCP): -- Server listening on http://localhost:${this.port}...`})}),this.onReady&&this.onReady()}setupTools(){if(!this.parser){this.logger?.log({level:"error",message:"FIXParser (MCP): -- FIXParser instance not initialized. Ignoring setup of tools..."});return}if(!this.mcpServer){this.logger?.log({level:"error",message:"FIXParser (MCP): -- MCP Server not initialized. Ignoring setup of tools..."});return}let t=Me(this.parser,this.verifiedOrders,this.pendingRequests,this.marketDataPrices);Object.entries(ce).forEach(([e,{description:n,schema:o}])=>{this.mcpServer?.registerTool(e,{description:n,inputSchema:gt(o)},async i=>{let l=t[e];if(!l)return{content:[{type:"text",text:`Tool not found: ${e}`}],isError:!0};let r=await l(i);return{content:r.content,isError:r.isError}})})}};var pt=async()=>{let m={FIXPARSER_LICENSE_KEY:process.env.FIXPARSER_LICENSE_KEY,FIXPARSER_HOST:process.env.FIXPARSER_HOST,FIXPARSER_PORT:process.env.FIXPARSER_PORT,FIXPARSER_SENDER:process.env.FIXPARSER_SENDER,FIXPARSER_TARGET:process.env.FIXPARSER_TARGET},t=Object.entries(m).filter(([r,c])=>!c).map(([r])=>r);if(t.length>0)throw new Error(`Missing required environment variables: ${t.join(", ")}`);await F.LicenseManager.setLicenseKey(m.FIXPARSER_LICENSE_KEY);let e=m.FIXPARSER_SENDER,n=m.FIXPARSER_TARGET,o=new F.FIXParser({logging:!0,logOptions:{name:e,level:"info",format:"jsonrpc",transport:new le({format:"jsonrpc",useStderr:!0})},plugins:[new Y({port:3099,onReady:()=>console.log("MCP Server started.")})]}),i=()=>{let r=o.createMessage(new F.Field(F.Fields.MsgType,F.Messages.Logon),new F.Field(F.Fields.MsgSeqNum,o.getNextTargetMsgSeqNum()),new F.Field(F.Fields.SenderCompID,e),new F.Field(F.Fields.SendingTime,o.getTimestamp()),new F.Field(F.Fields.TargetCompID,n),new F.Field(F.Fields.ResetSeqNumFlag,F.ResetSeqNumFlag.Yes),new F.Field(F.Fields.EncryptMethod,F.EncryptMethod.None),new F.Field(F.Fields.HeartBtInt,10)),c=o.parse(r.encode());console.log("sending message",c[0].description,c[0].messageString),o.send(r)},l={host:m.FIXPARSER_HOST,port:Number.parseInt(m.FIXPARSER_PORT,10),protocol:"tcp",sender:e,target:n,fixVersion:"FIX.4.4",onOpen:()=>{o.logger?.log({level:"info",message:"FIXParser (RemoteServer): -- Connection established"}),i()},onClose:()=>{o.logger?.log({level:"info",message:"FIXParser (RemoteServer): -- disconnected. Reconnecting in 1 second..."}),setTimeout(()=>{o.connect(l)},1e3)}};o.connect(l)};pt().catch(m=>console.error("Error initializing server:",m));
|
|
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(n){return{content:[{type:"text",text:`Error: ${n instanceof Error?n.message:"Failed to verify order parameters"}`,uri:"verifyOrder"}],isError:!0}}},be=(h,t,e)=>async n=>{try{let o=t.get(n.clOrdID);if(!o)return{content:[{type:"text",text:`Error: Order ${n.clOrdID} has not been verified. Please call verifyOrder first.`,uri:"executeOrder"}],isError:!0};if(o.handlInst!==n.handlInst||o.quantity!==Number.parseFloat(String(n.quantity))||o.price!==Number.parseFloat(String(n.price))||o.ordType!==n.ordType||o.side!==n.side||o.symbol!==n.symbol||o.timeInForce!==n.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 i=new Promise(c=>{e.set(n.clOrdID,c)}),l=h.createMessage(new T.Field(T.Fields.MsgType,T.Messages.NewOrderSingle),new T.Field(T.Fields.MsgSeqNum,h.getNextTargetMsgSeqNum()),new T.Field(T.Fields.SenderCompID,h.sender),new T.Field(T.Fields.TargetCompID,h.target),new T.Field(T.Fields.SendingTime,h.getTimestamp()),new T.Field(T.Fields.ClOrdID,n.clOrdID),new T.Field(T.Fields.Side,n.side),new T.Field(T.Fields.Symbol,n.symbol),new T.Field(T.Fields.OrderQty,Number.parseFloat(String(n.quantity))),new T.Field(T.Fields.Price,Number.parseFloat(String(n.price))),new T.Field(T.Fields.OrdType,n.ordType),new T.Field(T.Fields.HandlInst,n.handlInst),new T.Field(T.Fields.TimeInForce,n.timeInForce),new T.Field(T.Fields.TransactTime,h.getTimestamp()));if(!h.connected)return{content:[{type:"text",text:"Error: Not connected. Ignoring message.",uri:"executeOrder"}],isError:!0};h.send(l);let r=await i;return t.delete(n.clOrdID),{content:[{type:"text",text:r.messageType===T.Messages.Reject?`Reject message for order ${n.clOrdID}: ${JSON.stringify(r.toFIXJSON())}`:`Execution Report for order ${n.clOrdID}: ${JSON.stringify(r.toFIXJSON())}`,uri:"executeOrder"}]}}catch(o){return{content:[{type:"text",text:`Error: ${o instanceof Error?o.message:"Failed to execute order"}`,uri:"executeOrder"}],isError:!0}}};var ye=h=>async t=>{try{let e=h.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}}};var Pe=h=>async t=>{try{let e=h.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}}};var Me=(h,t,e,n)=>({parse:ye(h),parseToJSON:Pe(h),verifyOrder:fe(h,t),executeOrder:be(h,t,e),marketDataRequest:he(h,e),getStockGraph:ge(n),getStockPriceHistory:pe(n),technicalAnalysis:ue(n)});var I=require("fixparser");function dt(h,t){return h[t]||t}function Se(h,t,e,n,o,i){let l=h.messageType;if(l===I.Messages.MarketDataSnapshotFullRefresh||l===I.Messages.MarketDataIncrementalRefresh){let r=h.getField(I.Fields.Symbol)?.value,a=h.toFIXJSON().Body?.NoMDEntries||[],s={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 d of a){let f=d.MDEntryType,g=d.MDEntryPx?Number.parseFloat(d.MDEntryPx):0,b=d.MDEntrySize?Number.parseFloat(d.MDEntrySize):0;switch(dt(I.MDEntryType,f)){case I.MDEntryType.Bid:s.bid=g;break;case I.MDEntryType.Offer:s.offer=g;break;case I.MDEntryType.Trade:s.trade=g;break;case I.MDEntryType.IndexValue:s.indexValue=g;break;case I.MDEntryType.OpeningPrice:s.openingPrice=g;break;case I.MDEntryType.ClosingPrice:s.closingPrice=g;break;case I.MDEntryType.SettlementPrice:s.settlementPrice=g;break;case I.MDEntryType.TradingSessionHighPrice:s.tradingSessionHighPrice=g;break;case I.MDEntryType.TradingSessionLowPrice:s.tradingSessionLowPrice=g;break;case I.MDEntryType.VWAP:s.vwap=g;break;case I.MDEntryType.Imbalance:s.imbalance=b;break;case I.MDEntryType.TradeVolume:s.volume=b;break;case I.MDEntryType.OpenInterest:s.openInterest=b;break;case I.MDEntryType.CompositeUnderlyingPrice:s.compositeUnderlyingPrice=g;break;case I.MDEntryType.SimulatedSellPrice:s.simulatedSellPrice=g;break;case I.MDEntryType.SimulatedBuyPrice:s.simulatedBuyPrice=g;break;case I.MDEntryType.MarginRate:s.marginRate=g;break;case I.MDEntryType.MidPrice:s.midPrice=g;break;case I.MDEntryType.EmptyBook:s.emptyBook=1;break;case I.MDEntryType.SettleHighPrice:s.settleHighPrice=g;break;case I.MDEntryType.SettleLowPrice:s.settleLowPrice=g;break;case I.MDEntryType.PriorSettlePrice:s.priorSettlePrice=g;break;case I.MDEntryType.SessionHighBid:s.sessionHighBid=g;break;case I.MDEntryType.SessionLowOffer:s.sessionLowOffer=g;break;case I.MDEntryType.EarlyPrices:s.earlyPrices=g;break;case I.MDEntryType.AuctionClearingPrice:s.auctionClearingPrice=g;break;case I.MDEntryType.SwapValueFactor:s.swapValueFactor=g;break;case I.MDEntryType.DailyValueAdjustmentForLongPositions:s.dailyValueAdjustmentForLongPositions=g;break;case I.MDEntryType.CumulativeValueAdjustmentForLongPositions:s.cumulativeValueAdjustmentForLongPositions=g;break;case I.MDEntryType.DailyValueAdjustmentForShortPositions:s.dailyValueAdjustmentForShortPositions=g;break;case I.MDEntryType.CumulativeValueAdjustmentForShortPositions:s.cumulativeValueAdjustmentForShortPositions=g;break;case I.MDEntryType.FixingPrice:s.fixingPrice=g;break;case I.MDEntryType.CashRate:s.cashRate=g;break;case I.MDEntryType.RecoveryRate:s.recoveryRate=g;break;case I.MDEntryType.RecoveryRateForLong:s.recoveryRateForLong=g;break;case I.MDEntryType.RecoveryRateForShort:s.recoveryRateForShort=g;break;case I.MDEntryType.MarketBid:s.marketBid=g;break;case I.MDEntryType.MarketOffer:s.marketOffer=g;break;case I.MDEntryType.ShortSaleMinPrice:s.shortSaleMinPrice=g;break;case I.MDEntryType.PreviousClosingPrice:s.previousClosingPrice=g;break;case I.MDEntryType.ThresholdLimitPriceBanding:s.thresholdLimitPriceBanding=g;break;case I.MDEntryType.DailyFinancingValue:s.dailyFinancingValue=g;break;case I.MDEntryType.AccruedFinancingValue:s.accruedFinancingValue=g;break;case I.MDEntryType.TWAP:s.twap=g;break}}s.spread=s.offer-s.bid,n.has(r)||n.set(r,[]);let u=n.get(r);u.push(s),u.length>o&&u.splice(0,u.length-o),i?.(r,s);let m=h.getField(I.Fields.MDReqID)?.value;if(m){let d=e.get(m);d&&(d(h),e.delete(m))}}else if(l===I.Messages.ExecutionReport){let r=h.getField(I.Fields.ClOrdID)?.value,c=e.get(r);c&&(c(h),e.delete(r))}}var z={};function gt(h){if(h.type==="object"){let t={};for(let[e,n]of Object.entries(h.properties||{})){let o=n;o.type==="string"?o.enum?t[e]=L.z.enum(o.enum):t[e]=L.z.string():o.type==="number"?t[e]=L.z.number():o.type==="boolean"?t[e]=L.z.boolean():o.type==="array"?o.items.type==="string"?t[e]=L.z.array(L.z.string()):o.items.type==="number"?t[e]=L.z.array(L.z.number()):o.items.type==="boolean"?t[e]=L.z.array(L.z.boolean()):t[e]=L.z.array(L.z.any()):t[e]=L.z.any()}return t}return{}}var Y=class extends Q{port;httpServer;mcpServer;serverName;serverVersion;verifiedOrders=new Map;pendingRequests=new Map;marketDataPrices=new Map;MAX_PRICE_HISTORY=1e5;constructor({port:t,logger:e,onReady:n}){super({logger:e,onReady:n}),this.port=t}async register(t){this.parser=t,this.logger=t.logger,this.logger?.log({level:"info",message:`FIXParser (MCP): -- Plugin registered. Creating MCP server on port ${this.port}...`}),this.parser.addOnMessageCallback(e=>{this.parser&&Se(e,this.parser,this.pendingRequests,this.marketDataPrices,this.MAX_PRICE_HISTORY)}),this.httpServer=(0,Ie.createServer)(async(e,n)=>{if(!e.url||!e.method){n.writeHead(400),n.end("Bad Request");return}if(e.url==="/mcp"){let o=e.headers["mcp-session-id"];if(e.method==="POST"){let i=[];e.on("data",l=>{i.push(l)}),e.on("end",async()=>{let l,r=Buffer.concat(i).toString();try{l=JSON.parse(r)}catch(a){n.writeHead(400),n.end(JSON.stringify({error:"Invalid JSON"}));return}let c;if(o&&z[o])c=z[o];else if(!o&&e.method==="POST"&&(0,xe.isInitializeRequest)(l))c=new we.StreamableHTTPServerTransport({sessionIdGenerator:()=>(0,ve.randomUUID)(),onsessioninitialized:a=>{z[a]=c}}),c.onclose=()=>{c.sessionId&&delete z[c.sessionId]},this.mcpServer=new Re.McpServer({name:this.serverName||"FIXParser",version:this.serverVersion||"1.0.0"}),this.setupTools(),await this.mcpServer.connect(c);else{n.writeHead(400,{"Content-Type":"application/json"}),n.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Bad Request: No valid session ID provided"},id:null}));return}try{await c.handleRequest(e,n,l)}catch(a){throw this.logger?.log({level:"error",message:`Error handling request: ${a}`}),a}})}else if(e.method==="GET"||e.method==="DELETE"){if(!o||!z[o]){n.writeHead(400),n.end("Invalid or missing session ID");return}let i=z[o];try{await i.handleRequest(e,n)}catch(l){throw this.logger?.log({level:"error",message:`Error handling ${e.method} request: ${l}`}),l}}else this.logger?.log({level:"error",message:`Method not allowed: ${e.method}`}),n.writeHead(405),n.end("Method Not Allowed")}else n.writeHead(404),n.end("Not Found")}),this.httpServer.listen(this.port,()=>{this.logger?.log({level:"info",message:`FIXParser (MCP): -- Server listening on http://localhost:${this.port}...`})}),this.onReady&&this.onReady()}setupTools(){if(!this.parser){this.logger?.log({level:"error",message:"FIXParser (MCP): -- FIXParser instance not initialized. Ignoring setup of tools..."});return}if(!this.mcpServer){this.logger?.log({level:"error",message:"FIXParser (MCP): -- MCP Server not initialized. Ignoring setup of tools..."});return}let t=Me(this.parser,this.verifiedOrders,this.pendingRequests,this.marketDataPrices);Object.entries(ce).forEach(([e,{description:n,schema:o}])=>{this.mcpServer?.registerTool(e,{description:n,inputSchema:gt(o)},async i=>{let l=t[e];if(!l)return{content:[{type:"text",text:`Tool not found: ${e}`}],isError:!0};let r=await l(i);return{content:r.content,isError:r.isError}})})}};var pt=async()=>{await F.LicenseManager.setLicenseKey(process.env.FIXPARSER_LICENSE_KEY);let h=process.env.FIXPARSER_SENDER||"SENDER",t=process.env.FIXPARSER_TARGET||"TARGET",e=new F.FIXParser({plugins:[new Y({port:3099,onReady:()=>console.log("ready!")})]}),n=()=>{let i=e.createMessage(new F.Field(F.Fields.MsgType,F.Messages.Logon),new F.Field(F.Fields.MsgSeqNum,e.getNextTargetMsgSeqNum()),new F.Field(F.Fields.SenderCompID,h),new F.Field(F.Fields.SendingTime,e.getTimestamp()),new F.Field(F.Fields.TargetCompID,t),new F.Field(F.Fields.ResetSeqNumFlag,F.ResetSeqNumFlag.Yes),new F.Field(F.Fields.EncryptMethod,F.EncryptMethod.None),new F.Field(F.Fields.HeartBtInt,10)),l=e.parse(i.encode());console.log("sending message",l[0].description,l[0].messageString),e.send(i)},o={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:h,target:t,fixVersion:"FIX.4.4",logging:!0,logOptions:{name:h,level:"info",format:"json",transport:new le({format:"console"})},onOpen:()=>{console.log("Open"),n()},onClose:()=>{e.logger.log({level:"info",message:"FIXParser disconnected. Reconnecting in 1 second..."}),setTimeout(()=>{e.connect(o)},1e3)}};e.connect(o)};pt().catch(h=>console.error("Error initializing server:",h));
|
|
18
18
|
//# sourceMappingURL=RemoteServer.js.map
|