fixparser-plugin-mcp 9.1.7-ff7241ee → 9.2.0
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 +18 -0
- package/build/cjs/RemoteServer.js.map +7 -0
- package/build/cjs/StdioServer.js +18 -0
- package/build/cjs/StdioServer.js.map +7 -0
- package/build/esm/RemoteServer.mjs +18 -0
- package/build/esm/RemoteServer.mjs.map +7 -0
- package/build/esm/StdioServer.mjs +18 -0
- package/build/esm/StdioServer.mjs.map +7 -0
- package/package.json +12 -14
- package/build/cjs/MCPLocal.js +0 -1456
- package/build/cjs/MCPLocal.js.map +0 -7
- package/build/cjs/MCPRemote.js +0 -608
- package/build/cjs/MCPRemote.js.map +0 -7
- package/build/esm/MCPLocal.mjs +0 -1431
- package/build/esm/MCPLocal.mjs.map +0 -7
- package/build/esm/MCPRemote.mjs +0 -592
- package/build/esm/MCPRemote.mjs.map +0 -7
- package/build-examples/cjs/example_mcp_local.js +0 -64
- package/build-examples/cjs/example_mcp_local.js.map +0 -7
- package/build-examples/esm/example_mcp_local.mjs +0 -64
- package/build-examples/esm/example_mcp_local.mjs.map +0 -7
- package/types/MCPLocal.d.ts +0 -16
- package/types/MCPRemote.d.ts +0 -60
- package/types/PluginOptions.d.ts +0 -6
- package/types/index.d.ts +0 -3
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";var Ye=Object.create;var ie=Object.defineProperty;var Ze=Object.getOwnPropertyDescriptor;var _e=Object.getOwnPropertyNames;var et=Object.getPrototypeOf,tt=Object.prototype.hasOwnProperty;var nt=(h,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of _e(t))!tt.call(h,s)&&s!==e&&ie(h,s,{get:()=>t[s],enumerable:!(n=Ze(t,s))||n.enumerable});return h};var rt=(h,t,e)=>(e=h!=null?Ye(et(h)):{},nt(t||!h||!h.__esModule?ie(e,"default",{value:h,enumerable:!0}):e,h));var A=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,s={jsonrpc:"2.0",method:h.level,params:{message:e,...n},id:h.id||Date.now()};t(JSON.stringify(s))}else{let{name:e,id:n,message:s,level:i,...l}=h,r=Object.entries(l).map(([a,o])=>`${a}: ${o}`),c="";e&&(c+=`${e} `),c+=`${n}: ${s}`,t(c,r.join(", "))}}async flush(){}async close(){}status(){return"connected"}};var Se=require("@modelcontextprotocol/sdk/server/index.js"),ve=require("@modelcontextprotocol/sdk/server/stdio.js"),X=require("zod");var z=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 ee={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 s=n.map(a=>a>0?a:0),i=n.map(a=>a<0?Math.abs(a):0),l=s.slice(0,e).reduce((a,o)=>a+o,0)/e,r=i.slice(0,e).reduce((a,o)=>a+o,0)/e,c=[];for(let a=e;a<n.length;a++){let o=l/r;c.push(100-100/(1+o)),l=(l*(e-1)+s[a])/e,r=(r*(e-1)+i[a])/e}return c}static calculateStochastic(t,e,n){let s=[];if(t.length<14)return[];let c=[];for(let o=13;o<t.length;o++){let u=Math.max(...e.slice(o-14+1,o+1)),m=Math.min(...n.slice(o-14+1,o+1)),f=(t[o]-m)/(u-m)*100;c.push(f)}let a=[];for(let o=2;o<c.length;o++){let u=c.slice(o-3+1,o+1).reduce((m,d)=>m+d,0);a.push(u/3)}for(let o=2;o<a.length;o++){let m=a.slice(o-3+1,o+1).reduce((d,f)=>d+f,0)/3;s.push({k:a[o],d:m})}return s}static calculateCCI(t,e,n){let s=[];if(t.length<20)return[];for(let l=19;l<t.length;l++){let c=t.slice(l-20+1,l+1).map((d,f)=>{let g=e[l-20+1+f]||d,b=n[l-20+1+f]||d;return(g+b+d)/3}),a=c.reduce((d,f)=>d+f,0)/20,o=c.reduce((d,f)=>d+Math.abs(f-a),0)/20,u=(e[l]+n[l]+t[l])/3,m=o!==0?(u-a)/(.015*o):0;s.push(m)}return s}static calculateROC(t){let e=[];for(let n=10;n<t.length;n++)e.push((t[n]-t[n-10])/t[n-10]*100);return e}static calculateWilliamsR(t){let e=[];if(t.length<14)return[];for(let s=13;s<t.length;s++){let i=t.slice(s-14+1,s+1),l=Math.max(...i),r=Math.min(...i),c=t[s],a=(l-c)/(l-r)*-100;e.push(a)}return e}static calculateMomentum(t){let e=[];for(let n=10;n<t.length;n++)e.push(t[n]-t[n-10]);return e}};var F=class{static calculateSMA(t,e){let n=[];for(let s=e-1;s<t.length;s++){let i=t.slice(s-e+1,s+1).reduce((l,r)=>l+r,0);n.push(i/e)}return n}static calculateEMA(t,e){let n=2/(e+1),s=[t[0]];for(let i=1;i<t.length;i++)s.push(t[i]*n+s[i-1]*(1-n));return s}static calculateWMA(t,e){let n=[],s=Array.from({length:e},(l,r)=>r+1),i=s.reduce((l,r)=>l+r,0);for(let l=e-1;l<t.length;l++){let r=0;for(let c=0;c<e;c++)r+=t[l-c]*s[c];n.push(r/i)}return n}static calculateVWMA(t,e,n){let s=[];for(let i=n-1;i<t.length;i++){let l=0,r=0;for(let c=0;c<n;c++){let a=e[i-c]||1;l+=a,r+=t[i-c]*a}s.push(r/l)}return s}};var H=class h{static calculateBlackScholes(t,e,n){let s=t,i=e,l=1,r=.05,c=n*.01,a=(Math.log(s/i)+(r+c*c/2)*l)/(c*Math.sqrt(l)),o=a-c*Math.sqrt(l),u=s*h.normalCDF(a)-i*Math.exp(-r*l)*h.normalCDF(o),m=i*Math.exp(-r*l)*h.normalCDF(-o)-s*h.normalCDF(-a);return{callPrice:u,putPrice:m,delta:h.normalCDF(a),gamma:h.normalPDF(a)/(s*c*Math.sqrt(l)),theta:-s*h.normalPDF(a)*c/(2*Math.sqrt(l))-r*i*Math.exp(-r*l)*h.normalCDF(o),vega:s*Math.sqrt(l)*h.normalPDF(a),rho:i*l*Math.exp(-r*l)*h.normalCDF(o)}}static calculateBinomialTree(t,e,n=1,s=.05,i=.2,l=100){let r=n/l,c=Math.exp(i*Math.sqrt(r)),a=1/c,o=(Math.exp(s*r)-a)/(c-a),u=[];for(let M=0;M<=l;M++){u[M]=[];for(let x=0;x<=M;x++)u[M][x]=t*c**x*a**(M-x)}let m=[];m[l]=[];for(let M=0;M<=l;M++){let x=Math.max(0,u[l][M]-e);m[l][M]=x}let d=[];d[l]=[];for(let M=0;M<=l;M++){let x=Math.max(0,e-u[l][M]);d[l][M]=x}for(let M=l-1;M>=0;M--){m[M]=[];for(let x=0;x<=M;x++){let v=m[M+1][x+1],w=m[M+1][x],D=Math.exp(-s*r)*(o*v+(1-o)*w);m[M][x]=Math.max(D,u[M][x]-e)}}for(let M=l-1;M>=0;M--){d[M]=[];for(let x=0;x<=M;x++){let v=d[M+1][x+1],w=d[M+1][x],D=Math.exp(-s*r)*(o*v+(1-o)*w);d[M][x]=Math.max(D,e-u[M][x])}}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]),R=(m[1][0]-m[0][0])/r,S=(f-f*1.01)/(i*.01),p=(f-f*1.01)/(s*.01);return{callPrice:f,putPrice:g,delta:b,gamma:P,theta:R,vega:S,rho:p}}static calculateTrinomialTree(t,e,n=1,s=.05,i=.2,l=50){let r=n/l,c=i*Math.sqrt(3*r),a=Math.exp(c),o=.5*((s-.5*i*i)*r/c+i*i*r/(c*c)),u=.5*((s-.5*i*i)*r/c-i*i*r/(c*c)),m=1-o-u,d=[];for(let v=0;v<=l;v++){d[v]=[];for(let w=0;w<=2*v+1;w++){let D=w-v;d[v][w]=t*a**D}}let f=[];f[l]=[];for(let v=0;v<=2*l;v++){let w=Math.max(0,d[l][v]-e);f[l][v]=w}let g=[];g[l]=[];for(let v=0;v<=2*l;v++){let w=Math.max(0,e-d[l][v]);g[l][v]=w}for(let v=l-1;v>=0;v--){f[v]=[];for(let w=0;w<=2*v;w++){let D=f[v+1][w+2],L=f[v+1][w+1],O=f[v+1][w],E=Math.exp(-s*r)*(o*D+m*L+u*O);f[v][w]=Math.max(E,d[v][w]-e)}}for(let v=l-1;v>=0;v--){g[v]=[];for(let w=0;w<=2*v;w++){let D=g[v+1][w+2],L=g[v+1][w+1],O=g[v+1][w],E=Math.exp(-s*r)*(o*D+m*L+u*O);g[v][w]=Math.max(E,e-d[v][w])}}let b=f[0][0],P=g[0][0],R=(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),x=(b-b*1.01)/(s*.01);return{callPrice:b,putPrice:P,delta:R,gamma:S,theta:p,vega:M,rho:x}}static calculateMonteCarlo(t,e,n=1,s=.05,i=.2,l=1e4){let r=0,c=0,a=0,o=0;for(let M=0;M<l;M++){let x=h.boxMuller(),v=t*Math.exp((s-.5*i*i)*n+i*Math.sqrt(n)*x),w=Math.max(0,v-e),D=Math.max(0,e-v);r+=w,c+=D,v>e&&(a+=1,o+=0)}let u=Math.exp(-s*n),m=r/l*u,d=c/l*u,f=a/l*u,g=o/l*u,b=-(m*s),P=(m-m*1.01)/(i*.01),R=(m-m*1.01)/(s*.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:R,confidenceInterval:p}}static calculateHestonModel(t,e,n=1,s=.05,i=.2,l=.2,r=2,c=.3,a=-.5){let o=t*.6-e*Math.exp(-s*n)*.4,u=o-t+e*Math.exp(-s*n),m=Math.sqrt(2*Math.PI/n)*(o/t)*(1+.5*(o/t)),d=.6,f=.01/t,g=-(o*s),b=o*Math.sqrt(n),P=e*n*Math.exp(-s*n)*.4;return{callPrice:o,putPrice:u,impliedVolatility:m,delta:d,gamma:f,theta:g,vega:b,rho:P}}static calculateSABRModel(t,e,n=1,s=.05,i=.2,l=.5,r=-.5,c=.3){let a=t,o=e,u=n,m=c/i*Math.log(a/o),d=Math.log((Math.sqrt(1-2*r*m+m*m)+m-r)/(1-r)),f;Math.abs(a-o)<1e-8?f=i/a**(1-l)*(1+((1-l)**2/24*i**2/a**(2-2*l)+r*l*i*c/(4*a**(1-l))+(2-3*r**2)*c**2/24)*u):f=i/(a*o)**((1-l)/2)*(1+((1-l)**2/24*i**2/(a*o)**(1-l)+r*l*i*c/(4*(a*o)**((1-l)/2))+(2-3*r**2)*c**2/24)*u)*m/d;let g=(Math.log(a/o)+(s+f*f/2)*u)/(f*Math.sqrt(u)),b=g-f*Math.sqrt(u),P=a*h.normalCDF(g)-o*Math.exp(-s*u)*h.normalCDF(b),R=o*Math.exp(-s*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))-s*o*Math.exp(-s*u)*h.normalCDF(b),x=a*Math.sqrt(u)*h.normalPDF(g),v=o*u*Math.exp(-s*u)*h.normalCDF(b);return{callPrice:P,putPrice:R,impliedVolatility:f,delta:S,gamma:p,theta:M,vega:x,rho:v}}static calculateVarianceGamma(t,e,n=1,s=.05,i=.2,l=-.1,r=.3){let c=t,a=e,o=n,u=s,m=c*.55-a*Math.exp(-u*o)*.45,d=m-c+a*Math.exp(-u*o),f=Math.sqrt(2*Math.PI/o)*(m/c)*(1+.5*(m/c)),g=.55,b=.01/c,P=-(m*u),R=m*Math.sqrt(o),S=a*o*Math.exp(-u*o)*.45;return{callPrice:m,putPrice:d,impliedVolatility:f,delta:g,gamma:b,theta:P,vega:R,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,s=1.421413741,i=-1.453152027,l=1.061405429,r=.3275911,c=t>=0?1:-1,a=Math.abs(t),o=1/(1+r*a),u=1-((((l*o+i)*o+s)*o+n)*o+e)*o*Math.exp(-a*a);return c*u}static boxMuller(){let t=Math.random(),e=Math.random();return Math.sqrt(-2*Math.log(t))*Math.cos(2*Math.PI*e)}};var W=class{static calculateMaxDrawdown(t){let e=t[0],n=0;for(let s=1;s<t.length;s++){t[s]>e&&(e=t[s]);let i=(e-t[s])/e;i>n&&(n=i)}return n}static calculateMaxConsecutiveLosses(t){let e=0,n=0;for(let s=1;s<t.length;s++)t[s]<t[s-1]?(n++,e=Math.max(e,n)):n=0;return e}static calculateWinRate(t){let e=0,n=0;for(let s=1;s<t.length;s++)t[s]!==t[s-1]&&(n++,t[s]>t[s-1]&&e++);return n>0?e/n:0}static calculateProfitFactor(t){let e=0,n=0;for(let s=1;s<t.length;s++){let i=t[s]-t[s-1];i>0?e+=i:n+=Math.abs(i)}return n>0?e/n:0}static calculateSharpeRatio(t,e=.02){if(t.length===0)return 0;let n=t.reduce((r,c)=>r+c,0)/t.length,s=n-e,i=t.reduce((r,c)=>r+(c-n)**2,0)/t.length,l=Math.sqrt(i);return l>0?s/l:0}static calculateSortinoRatio(t,e=.02){if(t.length===0)return 0;let n=t.reduce((c,a)=>c+a,0)/t.length,s=n-e,l=t.filter(c=>c<n).reduce((c,a)=>c+(a-n)**2,0)/t.length,r=Math.sqrt(l);return r>0?s/r:0}static calculateCalmarRatio(t,e){return e===0?0:t.reduce((s,i)=>s+i,0)/t.length/e}static calculatePositionSize(t,e){let n=Math.abs(t-e);return n>0?100/n:1}static calculateConfidence(t){return Math.min(t.length*10,100)}static calculateRiskLevel(t){return t<20?"LOW":t<40?"MEDIUM":"HIGH"}};var J=class h{static generateSignals(t,e,n,s,i,l,r,c,a){let o=0,u=0,m=[];t>e?(m.push(`\u2713 BULLISH: Price above VWAP (+${((t-e)/e*100).toFixed(2)}%)`),o++):(m.push(`\u2717 BEARISH: Price below VWAP (${((t-e)/e*100).toFixed(2)}%)`),u++),n>0&&s>0?(m.push("\u2713 BULLISH: Positive momentum on both timeframes"),o++):n<0&&s<0?(m.push("\u2717 BEARISH: Negative momentum on both timeframes"),u++):m.push("\u25D0 MIXED: Conflicting momentum signals");let d=l/r;return d>1.2&&i>0?(m.push("\u2713 BULLISH: Above-average volume supporting upward move"),o++):d>1.2&&i<0?(m.push("\u2717 BEARISH: Above-average volume supporting downward move"),u++):m.push("\u25D0 NEUTRAL: Volume not providing clear direction"),c>65&&a>30?(m.push("\u2717 BEARISH: High in range with elevated volatility - reversal risk"),u++):c<35&&a>30?(m.push("\u2713 BULLISH: Low in range with volatility - potential bounce"),o++):m.push("\u25D0 NEUTRAL: Price position and volatility not extreme"),{bullishSignals:o,bearishSignals:u,signals:m}}static calculateOverallSignal(t,e,n,s){let i=t-e,l=i>0?"BULLISH_BIAS":i<0?"BEARISH_BIAS":"NEUTRAL",r=h.calculateConfidence(n),c=h.calculateRiskLevel(s);return{bullishSignals:t,bearishSignals:e,signals:n,overallSignal:l,signalScore:i,confidence:r,riskLevel:c}}static calculateConfidence(t){return Math.min(t.length*10,100)}static calculateRiskLevel(t){return t<20?"LOW":t<40?"MEDIUM":"HIGH"}};function C(h,t=500){if(h.length<=t)return h;let e=[],n=h.length/t;e.push(h[0]);for(let s=1;s<t-1;s++){let i=Math.floor(s*n),l=Math.floor((s+1)*n),r=h.slice(i,l);if(r.length===0)continue;let c=Math.floor(r.length/2);e.push(r[c])}return e.push(h[h.length-1]),e}var k=class{static calculateZScore(t,e){return(t-e)/(e*.1)}static calculateOrnsteinUhlenbeck(t,e,n,s){let i=e,l=.1;if(s.length>1){let c=s.reduce((a,o)=>a+o*o,0)/s.length;l=Math.max(.01,Math.min(1,c*10))}let r=n*.01;return{mean:i,speed:l,volatility:r,currentValue:t}}static calculateKalmanFilter(t,e,n,s){let i=n*.001,l=n*1e-4,r=e,c=i;if(s.length>0){let a=r,o=c+l,u=o/(o+i);return r=a+u*(t-a),c=(1-u)*o,{state:r,covariance:c,gain:u}}return{state:t,covariance:c,gain:.5}}static calculateARIMA(t,e){if(e.length<3)return{forecast:[t*1.01,t*1.02],residuals:[0,0],aic:100};let n=e.length,s=0,i=0,l=0,r=0;for(let b=1;b<n;b++){let P=e[b],R=e[b-1];s+=P,i+=R,l+=P*R,r+=R*R}let c=(n*l-s*i)/(n*r-i*i),a=(s-c*i)/n,o=[];for(let b=1;b<n;b++){let P=a+c*e[b-1];o.push(e[b]-P)}let u=o.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(o),aic:m}}static calculateGARCH(t,e){if(e.length<5)return{volatility:t*.01,persistence:.9,meanReversion:.1};let n=e.map(c=>c*c),s=n.reduce((c,a)=>c+a,0)/n.length,i=.9;if(n.length>1){let c=n.reduce((a,o)=>a+o,0)/n.length;i=Math.min(.99,Math.max(.5,c/s))}let l=s*(1-i);return{volatility:Math.sqrt(s),persistence:i,meanReversion:l}}static calculateVAR(t,e,n=2){if(t.length<n+5||e.length<n+5)return{priceForecast:[t[t.length-1]*1.01],volumeForecast:[e[e.length-1]*1.01],coefficients:[[.5,.3],[.2,.6]],residuals:[[0],[0]]};let s=[],i=[];for(let b=1;b<t.length;b++)s.push((t[b]-t[b-1])/t[b-1]),i.push((e[b]-e[b-1])/e[b-1]);let l=[],r=[],c=[];for(let b=n;b<s.length;b++){let P=[1];for(let R=1;R<=n;R++)P.push(s[b-R]),P.push(i[b-R]);l.push(P),r.push(s[b]),c.push(i[b])}let a=[[.5,.3,.2,.1],[.2,.1,.6,.3]],o=[],u=[];for(let b=0;b<r.length;b++){let P=a[0].reduce((S,p,M)=>S+p*l[b][M],0),R=a[1].reduce((S,p,M)=>S+p*l[b][M],0);o.push(r[b]-P),u.push(c[b]-R)}let m=s[s.length-1],d=i[i.length-1],f=[t[t.length-1]*(1+m*.5)],g=[e[e.length-1]*(1+d*.5)];return{priceForecast:f,volumeForecast:g,coefficients:a,residuals:[C(o),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=[],s=[],i=[],l=[],r=t[t.length-1],c=Math.sqrt(t.reduce((a,o)=>a+(o-r)**2,0)/t.length);for(let a=1;a<=e;a++){let o=(t[t.length-1]-t[t.length-10])/10,u=r+o*a;n.push(u);let m=c*(1+a*.1);s.push(m);let d=1.96*m;i.push(u-d),l.push(u+d)}return{mean:n,variance:s,confidenceInterval:{lower:i,upper:l}}}static calculatePairsTrading(t,e){if(t.length<20||e.length<20)return{spread:[0],zScore:[0],hedgeRatio:1,entrySignal:"NEUTRAL",exitSignal:"NEUTRAL",position:"FLAT"};let n=Math.min(t.length,e.length),s=0,i=0,l=0,r=0;for(let P=0;P<n;P++)s+=t[P],i+=e[P],l+=t[P]*e[P],r+=t[P]*t[P];let c=(n*l-s*i)/(n*r-s*s),a=[];for(let P=0;P<n;P++)a.push(e[P]-c*t[P]);let o=a.reduce((P,R)=>P+R,0)/a.length,u=Math.sqrt(a.reduce((P,R)=>P+(R-o)**2,0)/a.length),m=[];for(let P=0;P<a.length;P++)m.push((a[P]-o)/u);let d=m[m.length-1],f="NEUTRAL",g="NEUTRAL",b="FLAT";return d>2?(f="SHORT_SPREAD",b="SHORT"):d<-2?(f="LONG_SPREAD",b="LONG"):Math.abs(d)<.5&&(g="CLOSE_POSITION",b="FLAT"),{spread: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=[],s=[],i=[],l=[t-e[e.length-1],t];l.push(...e.map(r=>t+r));for(let r=0;r<l.length;r++){let c=l[r],a=r>0?(l[r]-l[r-1])*.5:0;n.push(c+a),s.push(Math.atan2(a,c)),i.push(Math.sqrt(c*c+a*a))}return{analytic:C(n),phase:C(s),amplitude:C(i)}}static calculateWaveletTransform(t,e){if(e.length<8)return{coefficients:[t],scales:[1]};let n=[t,...e.map(l=>t+l)],s=[],i=[];for(let l=1;l<=Math.min(4,Math.floor(Math.log2(n.length)));l++){let r=2**(l-1);i.push(l);for(let c=0;c<n.length-r;c+=r*2)if(c+r<n.length){let a=(n[c]-n[c+r])/2;s.push(a)}}return{coefficients:C(s),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=[],s=[],i=[];for(let a=0;a<e;a++){let o=a/e;n.push(o);let u=0,m=0;for(let g=0;g<e;g++){let b=-2*Math.PI*a*g/e;u+=t[g]*Math.cos(b),m+=t[g]*Math.sin(b)}let d=Math.sqrt(u*u+m*m)/e,f=Math.atan2(m,u);s.push(d),i.push(f)}let r=[...s].sort((a,o)=>o-a)[Math.floor(e*.1)],c=n.filter((a,o)=>s[o]>r);return{frequencies:C(n),amplitudes:C(s),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 o=[];for(let m=1;m<r.length-1;m++)(r[m]>r[m-1]&&r[m]>r[m+1]||r[m]<r[m-1]&&r[m]<r[m+1])&&o.push(r[m]);if(o.length<3)break;let u=o.map((m,d)=>d===0?o[0]:d===o.length-1?o[o.length-1]:(o[d-1]+o[d+1])/2);for(let m=0;m<r.length;m++){let d=Math.floor(m*o.length/r.length);r[m]-=u[Math.min(d,u.length-1)]}c++}e.push(C([...r]));for(let o=0;o<n.length;o++)n[o]-=r[o]}let s=C(n),i=C(e.map((l,r)=>.1/(r+1)));return{imfs:e,residual:s,frequencies:i}}};var U=class h{static calculatePivotPoints(t,e,n){let s=[];for(let i=0;i<t.length;i++){let l=e[i]||t[i],r=n[i]||t[i],c=t[i],a=(l+r+c)/3,o=2*a-r,u=2*a-l,m=a+(l-r),d=a-(l-r),f=l+2*(a-r),g=r-2*(l-a);s.push({pp:a,r1:o,r2:m,r3:f,s1:u,s2:d,s3:g})}return s}static calculateFibonacciPivotPoints(t,e,n){let s=[];for(let i=0;i<t.length;i++){let l=e[i]||t[i],r=n[i]||t[i],c=t[i],a=(l+r+c)/3,o=l-r,u=a+.382*o,m=a+.618*o,d=a+1*o,f=a-.382*o,g=a-.618*o,b=a-1*o;s.push({pp:a,r1:u,r2:m,r3:d,s1:f,s2:g,s3:b})}return s}static calculateCamarillaPivotPoints(t,e,n){let s=[];for(let i=0;i<t.length;i++){let l=e[i]||t[i],r=n[i]||t[i],c=t[i],a=(l+r+c)/3,o=l-r,u=c+1.1/12*o,m=c+1.1/6*o,d=c+1.1/4*o,f=c-1.1/12*o,g=c-1.1/6*o,b=c-1.1/4*o;s.push({pp:a,r1:u,r2:m,r3:d,s1:f,s2:g,s3:b})}return s}static calculateFibonacciLevels(t){let e=[];for(let n=0;n<t.length;n++){let s=t[n];e.push({retracement:{level0:s,level236:s*.764,level382:s*.618,level500:s*.5,level618:s*.382,level786:s*.214,level100:s*0},extension:{level1272:s*1.272,level1618:s*1.618,level2618:s*2.618,level4236:s*4.236}})}return e}static calculateGannLevels(t){let e=[];if(t.length===0)return[];if(t.length<=500){for(let i=0;i<t.length;i++)e.push(t[i]*(1+i*.01));return e}let n=t.length/500;e.push(t[0]*1.01);for(let i=1;i<499;i++){let l=Math.floor(i*n),r=Math.floor((i+1)*n),c=t.slice(l,r);if(c.length===0)continue;let a=Math.floor(c.length/2),u=c[a]*(1+(l+a)*.01);e.push(u)}let s=t.length-1;return e.push(t[s]*(1+s*.01)),e}static calculateElliottWave(t){let e=[];if(t.length<10)return[];for(let n=0;n<t.length;n++){let s=[],i=1,l=.5;if(n>=4){let r=t.slice(n-4,n+1),c=h.detectPriceSwings(r);c.length>=3&&(s.push(...c.slice(0,3)),i=Math.min(c.length,5),l=h.calculateWavePosition(r))}e.push({waves:s.length>0?s:[t[n]],currentWave:i,wavePosition:l})}return e}static detectPriceSwings(t){let e=[];for(let n=1;n<t.length-1;n++){let s=t[n-1],i=t[n],l=t[n+1];(i>s&&i>l||i<s&&i<l)&&e.push(i)}return e}static calculateWavePosition(t){if(t.length<2)return .5;let e=t[t.length-1],n=Math.min(...t),s=Math.max(...t);return s!==n?(e-n)/(s-n):.5}static calculateHarmonicPatterns(t){let e=[];if(t.length<5)return[];let n=[];for(let i=4;i<t.length;i++){let l=t.slice(i-4,i+1),r=h.detectHarmonicPattern(l);n.push(r)}if(n.length<=500)return n;let s=n.length/500;e.push(n[0]);for(let i=1;i<499;i++){let l=Math.floor(i*s),r=Math.floor((i+1)*s),c=n.slice(l,r);if(c.length===0)continue;let a=c.reduce((o,u)=>u.completion>o.completion?u:o);e.push(a)}return e.push(n[n.length-1]),e}static detectHarmonicPattern(t){if(t.length<5)return{type:"Unknown",completion:0,target:t[t.length-1]*1.1,stopLoss:t[t.length-1]*.9};let e=h.detectPriceSwings(t);if(e.length<4)return{type:"Unknown",completion:0,target:t[t.length-1]*1.1,stopLoss:t[t.length-1]*.9};let n=e.slice(-5);if(n.length<5)return{type:"Unknown",completion:0,target:t[t.length-1]*1.1,stopLoss:t[t.length-1]*.9};let[s,i,l,r,c]=n,a=Math.abs(l-i),o=Math.abs(r-l),u=Math.abs(c-r),m=Math.abs(i-s),d=a/m,f=o/a,g=u/o;return h.isInRange(d,.618,.05)&&h.isInRange(f,.382,.05)&&h.isInRange(g,.886,.05)?{type:"Gartley",completion:h.calculatePatternCompletion(t),target:c+(c-r)*.618,stopLoss:c*.99}:h.isInRange(d,.382,.05)&&h.isInRange(f,.382,.05)&&h.isInRange(g,.886,.05)?{type:"Bat",completion:h.calculatePatternCompletion(t),target:c+(c-r)*.382,stopLoss:c*.99}:h.isInRange(d,.786,.05)&&h.isInRange(f,.382,.05)&&h.isInRange(g,1.618,.05)?{type:"Butterfly",completion:h.calculatePatternCompletion(t),target:c+(c-r)*1.618,stopLoss:c*.99}:h.isInRange(d,.382,.05)&&h.isInRange(f,.886,.05)&&h.isInRange(g,3.618,.1)?{type:"Crab",completion:h.calculatePatternCompletion(t),target:c+(c-r)*1.618,stopLoss:c*.99}:h.isInRange(d,.382,.05)&&h.isInRange(f,.113,.05)&&h.isInRange(g,Math.SQRT2,.05)?{type:"Cypher",completion:h.calculatePatternCompletion(t),target:c+(c-r)*.786,stopLoss:c*.99}:h.isInRange(d,.886,.05)&&h.isInRange(f,.886,.05)&&h.isInRange(g,1.13,.05)?{type:"Shark",completion:h.calculatePatternCompletion(t),target:c+(c-r)*1.13,stopLoss:c*.99}:{type:"Unknown",completion:0,target:t[t.length-1]*1.1,stopLoss:t[t.length-1]*.9}}static isInRange(t,e,n){return Math.abs(t-e)<=n}static calculatePatternCompletion(t){if(t.length<2)return 0;let e=t[t.length-1],n=Math.max(...t),s=Math.min(...t);if(n===s)return 50;let i=n-s,l=(e-s)/i;return Math.min(100,Math.max(0,l*100))}};var $=class{static calculateMACD(t){let e=F.calculateEMA(t,12),n=F.calculateEMA(t,26),s=[],i=[];for(let r=0;r<Math.min(e.length,n.length);r++)i.push(e[r]-n[r]);let l=F.calculateEMA(i,9);for(let r=0;r<Math.min(i.length,l.length);r++)s.push({macd:i[r],signal:l[r],histogram:i[r]-l[r]});return s}static calculateADX(t,e,n){if(t.length<14)return[];let s=14,i=[],l=[],r=[],c=[];l.push(e[0]-n[0]),r.push(0),c.push(0);for(let S=1;S<t.length;S++){let p=e[S]||t[S],M=n[S]||t[S],x=e[S-1]||t[S-1],v=n[S-1]||t[S-1],w=t[S-1],D=p-M,L=Math.abs(p-w),O=Math.abs(M-w);l.push(Math.max(D,L,O));let E=p-x,V=v-M;E>V&&E>0?(r.push(E),c.push(0)):V>E&&V>0?(r.push(0),c.push(V)):(r.push(0),c.push(0))}let a=[],o=[],u=[],m=0,d=0,f=0;for(let S=0;S<s;S++)m+=l[S],d+=r[S],f+=c[S];a.push(m),o.push(d),u.push(f);for(let S=s;S<l.length;S++){let p=a[a.length-1]-a[a.length-1]/s+l[S],M=o[o.length-1]-o[o.length-1]/s+r[S],x=u[u.length-1]-u[u.length-1]/s+c[S];a.push(p),o.push(M),u.push(x)}let g=[],b=[];for(let S=0;S<a.length;S++)g.push(o[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<s)return[];let R=0;for(let S=0;S<s;S++)R+=P[S];i.push(R/s);for(let S=s;S<P.length;S++){let p=i[i.length-1]-i[i.length-1]/s+P[S];i.push(p)}return i}static calculateDMI(t,e,n){if(t.length<14)return[];let s=14,i=[],l=[],r=[],c=[];l.push(e[0]-n[0]),r.push(0),c.push(0);for(let p=1;p<t.length;p++){let M=e[p]||t[p],x=n[p]||t[p],v=e[p-1]||t[p-1],w=n[p-1]||t[p-1],D=t[p-1],L=M-x,O=Math.abs(M-D),E=Math.abs(x-D);l.push(Math.max(L,O,E));let V=M-v,G=w-x;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=[],o=[],u=[],m=0,d=0,f=0;for(let p=0;p<s;p++)m+=l[p],d+=r[p],f+=c[p];a.push(m),o.push(d),u.push(f);for(let p=s;p<l.length;p++){let M=a[a.length-1]-a[a.length-1]/s+l[p],x=o[o.length-1]-o[o.length-1]/s+r[p],v=u[u.length-1]-u[u.length-1]/s+c[p];a.push(M),o.push(x),u.push(v)}let g=[],b=[];for(let p=0;p<a.length;p++)g.push(o[p]/a[p]*100),b.push(u[p]/a[p]*100);let P=[];for(let p=0;p<g.length;p++){let M=g[p]+b[p],x=Math.abs(g[p]-b[p]);P.push(M>0?x/M*100:0)}if(P.length<s)return[];let R=[],S=0;for(let p=0;p<s;p++)S+=P[p];R.push(S/s);for(let p=s;p<P.length;p++){let M=R[R.length-1]-R[R.length-1]/s+P[p];R.push(M)}for(let p=0;p<R.length;p++)i.push({plusDI:g[p+s-1]||0,minusDI:b[p+s-1]||0,adx:R[p]});return i}static calculateIchimoku(t,e,n){if(t.length<52)return[];let s=[],i=[];for(let u=8;u<t.length;u++){let m=Math.max(...e.slice(u-8,u+1)),d=Math.min(...n.slice(u-8,u+1));i.push((m+d)/2)}let l=[];for(let u=25;u<t.length;u++){let m=Math.max(...e.slice(u-25,u+1)),d=Math.min(...n.slice(u-25,u+1));l.push((m+d)/2)}let r=[];for(let u=0;u<Math.min(i.length,l.length);u++)r.push((i[u]+l[u])/2);let c=[];for(let u=51;u<t.length;u++){let m=Math.max(...e.slice(u-51,u+1)),d=Math.min(...n.slice(u-51,u+1));c.push((m+d)/2)}let a=[];for(let u=26;u<t.length;u++)a.push(t[u-26]);let o=Math.min(i.length,l.length,r.length,c.length,a.length);for(let u=0;u<o;u++)s.push({tenkan:i[u],kijun:l[u],senkouA:r[u],senkouB:c[u],chikou:a[u]});return s}static calculateParabolicSAR(t,e,n){if(t.length<2)return[];let s=[],i=.02,l=.2,r=n[0],c=!0,a=i,o=e[0];s.push(r);for(let u=1;u<t.length;u++){let m=e[u]||t[u],d=n[u]||t[u];if(c){if(d<r)c=!1,r=o,o=d,a=i;else if(m>o&&(o=m,a=Math.min(a+i,l)),r=r+a*(o-r),u>0){let f=n[u-1]||t[u-1];r=Math.min(r,f)}}else if(m>r)c=!0,r=o,o=m,a=i;else if(d<o&&(o=d,a=Math.min(a+i,l)),r=r+a*(o-r),u>0){let f=e[u-1]||t[u-1];r=Math.max(r,f)}s.push(r)}return s}};var N=class h{static calculateBollingerBands(t,e=20,n=2){if(t.length<e)return[];let s=F.calculateSMA(t,e),i=[];for(let l=0;l<s.length;l++){let r=t.slice(l,l+e),c=s[l],a=r.reduce((d,f)=>d+(f-c)**2,0)/e,o=Math.sqrt(a),u=c+o*n,m=c-o*n;i.push({upper:u,middle:c,lower:m,bandwidth:(u-m)/c*100,percentB:(t[l]-m)/(u-m)*100})}return i}static calculateATR(t,e,n){if(t.length<2)return[];let s=[];for(let l=1;l<t.length;l++){let r=e[l]||t[l],c=n[l]||t[l],a=t[l-1],o=r-c,u=Math.abs(r-a),m=Math.abs(c-a);s.push(Math.max(o,u,m))}let i=[];if(s.length>=14){let l=s.slice(0,14).reduce((r,c)=>r+c,0);i.push(l/14);for(let r=14;r<s.length;r++)l=l-s[r-14]+s[r],i.push(l/14)}return i}static calculateKeltnerChannels(t,e,n){let s=[];if(t.length<20)return[];let r=F.calculateEMA(t,20),c=h.calculateATR(t,e,n);for(let a=0;a<Math.min(r.length,c.length);a++){let o=r[a],u=c[a];s.push({upper:o+2*u,middle:o,lower:o-2*u})}return s}static calculateDonchianChannels(t){let e=[];for(let n=20;n<t.length;n++){let s=t.slice(n-20,n);e.push({upper:Math.max(...s),middle:(Math.max(...s)+Math.min(...s))/2,lower:Math.min(...s)})}return e}static calculateChaikinVolatility(t,e,n){let s=[];if(t.length<10*2)return[];let l=[];for(let c=0;c<t.length;c++){let a=e[c]||t[c],o=n[c]||t[c];l.push(a-o)}let r=F.calculateEMA(l,10);for(let c=10;c<r.length;c++){let a=r[c],o=r[c-10],u=o!==0?(a-o)/o*100:0;s.push(u)}return s}};var j=class{static calculateOBV(t,e){let n=[e[0]];for(let s=1;s<t.length;s++)t[s]>t[s-1]?n.push(n[s-1]+e[s]):t[s]<t[s-1]?n.push(n[s-1]-e[s]):n.push(n[s-1]);return n}static calculateCMF(t,e,n,s){let i=[];if(t.length<20)return[];for(let r=19;r<t.length;r++){let c=0,a=0;for(let u=r-20+1;u<=r;u++){let m=e[u]||t[u],d=n[u]||t[u],f=t[u],g=s[u]||1,P=(f-d-(m-f))/(m-d)*g;c+=P,a+=g}let o=a!==0?c/a:0;i.push(o)}return i}static calculateADL(t,e,n,s){let i=[0];for(let l=1;l<t.length;l++){let r=e[l]||t[l],c=n[l]||t[l],a=t[l],o=s[l]||1,m=(a-c-(r-a))/(r-c)*o;i.push(i[l-1]+m)}return i}static calculateVolumeROC(t){let e=[];for(let n=10;n<t.length;n++)e.push((t[n]-t[n-10])/t[n-10]*100);return e}static calculateMFI(t,e,n,s){let i=[];if(t.length<15)return[];for(let r=14;r<t.length;r++){let c=0,a=0;for(let m=r-14+1;m<=r;m++){let d=e[m]||t[m],f=n[m]||t[m],g=t[m],b=s[m]||1,P=(d+f+g)/3,R=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],x=(S+p+M)/3;P>x?c+=R:P<x&&(a+=R)}}let u=100-100/(1+(a!==0?c/a:0));i.push(u)}return i}static calculateVWAP(t,e){let n=[],s=0,i=0;for(let l=0;l<t.length;l++)s+=t[l]*(e[l]||1),i+=e[l]||1,n.push(s/i);return n}};function ot(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),s=Math.min(...this.lows),i=ot(this.volumes),l=i/this.volumes.length,r=this.calculatePriceChanges(),c=r.length>0?Math.sqrt(r.reduce((D,L)=>D+L**2,0)/r.length)*Math.sqrt(252)*100:0,a=(t-e)/e*100,o=(t-s)/(n-s)*100,u=this.prices.reduce((D,L,O)=>D+L*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=N.calculateATR(this.prices,this.highs,this.lows),b=g.length>0?g[g.length-1]:0,P=c,R=c,S=a/c,p=a/R,M=a/f,x=W.calculateMaxConsecutiveLosses(this.prices),v=W.calculateWinRate(this.prices),w=W.calculateProfitFactor(this.prices);return{currentPrice:t,startPrice:e,sessionHigh:n,sessionLow:s,totalVolume:i,avgVolume:l,volatility:c,sessionReturn:a,pricePosition:o,trueVWAP:u,momentum5:m,momentum10:d,maxDrawdown:f,atr:b,impliedVolatility:P,realizedVolatility:R,sharpeRatio:S,sortinoRatio:p,calmarRatio:M,maxConsecutiveLosses:x,winRate:v,profitFactor:w}}getTechnicalIndicators(){return{sma5:F.calculateSMA(this.prices,5),sma10:F.calculateSMA(this.prices,10),sma20:F.calculateSMA(this.prices,20),sma50:F.calculateSMA(this.prices,50),sma200:F.calculateSMA(this.prices,200),ema8:F.calculateEMA(this.prices,8),ema12:F.calculateEMA(this.prices,12),ema21:F.calculateEMA(this.prices,21),ema26:F.calculateEMA(this.prices,26),wma20:F.calculateWMA(this.prices,20),vwma20:F.calculateVWMA(this.prices,this.volumes,20),macd:$.calculateMACD(this.prices),adx:$.calculateADX(this.prices,this.highs,this.lows),dmi:$.calculateDMI(this.prices,this.highs,this.lows),ichimoku:$.calculateIchimoku(this.prices,this.highs,this.lows),parabolicSAR:$.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:N.calculateBollingerBands(this.prices,20,2),atr:N.calculateATR(this.prices,this.highs,this.lows),keltner:N.calculateKeltnerChannels(this.prices,this.highs,this.lows),donchian:N.calculateDonchianChannels(this.prices),chaikinVolatility:N.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:U.calculatePivotPoints(this.prices,this.highs,this.lows),fibonacci:U.calculateFibonacciLevels(this.prices),gannLevels:U.calculateGannLevels(this.prices),elliottWave:U.calculateElliottWave(this.prices),harmonicPatterns:U.calculateHarmonicPatterns(this.prices)}}generateJSONAnalysis(t){let e=this.analyze(),n=this.getTechnicalIndicators(),s=this.calculatePriceChanges(),i=n.sma5.length>0?n.sma5[n.sma5.length-1]:null,l=n.sma10.length>0?n.sma10[n.sma10.length-1]:null,r=n.sma20.length>0?n.sma20[n.sma20.length-1]:null,c=n.sma50.length>0?n.sma50[n.sma50.length-1]:null,a=n.sma200.length>0?n.sma200[n.sma200.length-1]:null,o=n.ema8[n.ema8.length-1],u=n.ema12[n.ema12.length-1],m=n.ema21[n.ema21.length-1],d=n.ema26[n.ema26.length-1],f=n.wma20.length>0?n.wma20[n.wma20.length-1]:null,g=n.vwma20.length>0?n.vwma20[n.vwma20.length-1]:null,b=n.macd.length>0?n.macd[n.macd.length-1]:null,P=n.adx.length>0?n.adx[n.adx.length-1]:null,R=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,x=n.stochastic.length>0?n.stochastic[n.stochastic.length-1]:null,v=n.cci.length>0?n.cci[n.cci.length-1]:null,w=n.roc.length>0?n.roc[n.roc.length-1]:null,D=n.williamsR.length>0?n.williamsR[n.williamsR.length-1]:null,L=n.momentum.length>0?n.momentum[n.momentum.length-1]:null,O=n.bollinger.length>0?n.bollinger[n.bollinger.length-1]:null,E=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,Ie=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,xe=n.adl.length>0?n.adl[n.adl.length-1]:null,Re=n.volumeROC.length>0?n.volumeROC[n.volumeROC.length-1]:null,oe=n.mfi.length>0?n.mfi[n.mfi.length-1]:null,we=n.vwap.length>0?n.vwap[n.vwap.length-1]:null,Te=n.pivotPoints.length>0?n.pivotPoints[n.pivotPoints.length-1]:null,Ae=n.fibonacci.length>0?n.fibonacci[n.fibonacci.length-1]:null,Fe=n.gannLevels.length>0?n.gannLevels:[],De=n.elliottWave.length>0?n.elliottWave[n.elliottWave.length-1]:null,Ce=n.harmonicPatterns.length>0?n.harmonicPatterns:[],Y=this.volumes[this.volumes.length-1],Oe=Y/e.avgVolume,ke=(e.sessionHigh-e.currentPrice)/e.sessionHigh*100,Ve=(e.sessionHigh-e.sessionLow)/e.sessionLow*100,Le=(e.currentPrice-e.trueVWAP)/e.trueVWAP*100,Z=J.generateSignals(e.currentPrice,e.trueVWAP,e.momentum5,e.momentum10,e.sessionReturn,Y,e.avgVolume,e.pricePosition,e.volatility),Ee=J.calculateOverallSignal(Z.bullishSignals,Z.bearishSignals,Z.signals,e.volatility),_=Math.max(e.sessionLow*1.005,e.trueVWAP*.998),K=e.sessionLow*.995,se=e.sessionHigh*.995,Be=(se-e.currentPrice)/(e.currentPrice-K),ae=W.calculatePositionSize(_,K),He=ae*(_-K),qe=k.calculateVAR(this.prices,this.volumes),Ne=k.calculateGaussianProcess(this.prices),je=k.calculatePairsTrading(this.prices,this.prices.map(Qe=>Qe*1.01)),Xe=k.calculateFourierTransform(this.prices),Ge=k.calculateEMD(this.prices),B=H.calculateBlackScholes(e.currentPrice,e.startPrice,e.avgVolume),We=H.calculateBinomialTree(e.currentPrice,e.startPrice),Ue=H.calculateTrinomialTree(e.currentPrice,e.startPrice),$e=H.calculateMonteCarlo(e.currentPrice,e.startPrice),Je=H.calculateHestonModel(e.currentPrice,e.startPrice),Ke=H.calculateSABRModel(e.currentPrice,e.startPrice),ze=H.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:Ve,totalVolume:e.totalVolume,sessionPerformance:e.sessionReturn,positionInRange:e.pricePosition},volatility:{impliedVolatility:e.impliedVolatility,realizedVolatility:e.realizedVolatility,atr:e.atr,maxDrawdown:e.maxDrawdown*100,currentDrawdown:ke},technicalIndicators:{sma5:i,sma10:l,sma20:r,sma50:c,sma200:a,ema8:o,ema12:u,ema21:m,ema26:d,wma20:f,vwma20:g,macd:b,adx:P,dmi:R,ichimoku:S,parabolicSAR:p,rsi:M,stochastic:x,cci:v,roc:w,williamsR:D,momentum:L,bollingerBands:O?{upper:O.upper,middle:O.middle,lower:O.lower,bandwidth:O.bandwidth,percentB:O.percentB}:null,atr:E,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:Ie,obv:ne,cmf:re,adl:xe,volumeROC:Re,mfi:oe,vwap:we},volumeAnalysis:{currentVolume:Y,averageVolume:Math.round(e.avgVolume),volumeRatio:Oe,trueVWAP:e.trueVWAP,priceVsVWAP:Le,obv:ne,cmf:re,mfi:oe},momentum:{momentum5:e.momentum5,momentum10:e.momentum10,sessionROC:e.sessionReturn,rsi:M,stochastic:x,cci:v},supportResistance:{pivotPoints:Te,fibonacci:Ae,gannLevels:Fe,elliottWave:De,harmonicPatterns:Ce},tradingSignals:Ee,statisticalModels:{zScore:k.calculateZScore(e.currentPrice,e.startPrice),ornsteinUhlenbeck:k.calculateOrnsteinUhlenbeck(e.currentPrice,e.startPrice,e.avgVolume,s),kalmanFilter:k.calculateKalmanFilter(e.currentPrice,e.startPrice,e.avgVolume,s),pairsTrading:je,arima:k.calculateARIMA(e.currentPrice,s),garch:k.calculateGARCH(e.avgVolume,s),var:qe,gaussianProcess:Ne,hilbertTransform:k.calculateHilbertTransform(e.currentPrice,s),waveletTransform:k.calculateWaveletTransform(e.currentPrice,s),fourierTransform:Xe,empiricalModeDecomposition:Ge},optionsAnalysis:B?{blackScholes:B,binomialTree:We,trinomialTree:Ue,monteCarlo:$e,hestonModel:Je,sabrModel:Ke,varianceGamma:ze,impliedVolatility:e.impliedVolatility,delta:B.delta,gamma:B.gamma,theta:B.theta,vega:B.vega,rho:B.rho,greeks:{delta:B.delta,gamma:B.gamma,theta:B.theta,vega:B.vega,rho:B.rho}}:null,riskManagement:{targetEntry:_,stopLoss:K,profitTarget:se,riskRewardRatio:Be,positionSize:ae,maxRisk:He},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}}}},ce=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
|
+
|
|
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"),ue=rt(require("quickchart-js"),1),me=(h,t)=>async e=>{try{h.logger.log({level:"info",message:`Sending market data request for symbols: ${e.symbols.join(", ")}`});let n=new Promise(c=>{t.set(e.mdReqID,c),h.logger.log({level:"info",message:`Registered callback for market data request ID: ${e.mdReqID}`})}),s=e.mdEntryTypes||[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,s.length)),s.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}}},he=(h,t=240)=>{if(h.length<=t)return h;let e=[],n=h.length/t;e.push(h[0]);for(let s=1;s<t-1;s++){let i=Math.floor(s*n),l=Math.floor((s+1)*n),r=h.slice(i,l);if(r.length===0)continue;let c={timestamp:r[0].timestamp,bid:r.reduce((a,o)=>a+o.bid,0)/r.length,offer:r.reduce((a,o)=>a+o.offer,0)/r.length,spread:r.reduce((a,o)=>a+o.spread,0)/r.length,volume:r.reduce((a,o)=>a+o.volume,0)/r.length,trade:r.reduce((a,o)=>a+o.trade,0)/r.length,indexValue:r.reduce((a,o)=>a+o.indexValue,0)/r.length,openingPrice:r.reduce((a,o)=>a+o.openingPrice,0)/r.length,closingPrice:r.reduce((a,o)=>a+o.closingPrice,0)/r.length,settlementPrice:r.reduce((a,o)=>a+o.settlementPrice,0)/r.length,tradingSessionHighPrice:r.reduce((a,o)=>a+o.tradingSessionHighPrice,0)/r.length,tradingSessionLowPrice:r.reduce((a,o)=>a+o.tradingSessionLowPrice,0)/r.length,vwap:r.reduce((a,o)=>a+o.vwap,0)/r.length,imbalance:r.reduce((a,o)=>a+o.imbalance,0)/r.length,openInterest:r.reduce((a,o)=>a+o.openInterest,0)/r.length,compositeUnderlyingPrice:r.reduce((a,o)=>a+o.compositeUnderlyingPrice,0)/r.length,simulatedSellPrice:r.reduce((a,o)=>a+o.simulatedSellPrice,0)/r.length,simulatedBuyPrice:r.reduce((a,o)=>a+o.simulatedBuyPrice,0)/r.length,marginRate:r.reduce((a,o)=>a+o.marginRate,0)/r.length,midPrice:r.reduce((a,o)=>a+o.midPrice,0)/r.length,emptyBook:r.reduce((a,o)=>a+o.emptyBook,0)/r.length,settleHighPrice:r.reduce((a,o)=>a+o.settleHighPrice,0)/r.length,settleLowPrice:r.reduce((a,o)=>a+o.settleLowPrice,0)/r.length,priorSettlePrice:r.reduce((a,o)=>a+o.priorSettlePrice,0)/r.length,sessionHighBid:r.reduce((a,o)=>a+o.sessionHighBid,0)/r.length,sessionLowOffer:r.reduce((a,o)=>a+o.sessionLowOffer,0)/r.length,earlyPrices:r.reduce((a,o)=>a+o.earlyPrices,0)/r.length,auctionClearingPrice:r.reduce((a,o)=>a+o.auctionClearingPrice,0)/r.length,swapValueFactor:r.reduce((a,o)=>a+o.swapValueFactor,0)/r.length,dailyValueAdjustmentForLongPositions:r.reduce((a,o)=>a+o.dailyValueAdjustmentForLongPositions,0)/r.length,cumulativeValueAdjustmentForLongPositions:r.reduce((a,o)=>a+o.cumulativeValueAdjustmentForLongPositions,0)/r.length,dailyValueAdjustmentForShortPositions:r.reduce((a,o)=>a+o.dailyValueAdjustmentForShortPositions,0)/r.length,cumulativeValueAdjustmentForShortPositions:r.reduce((a,o)=>a+o.cumulativeValueAdjustmentForShortPositions,0)/r.length,fixingPrice:r.reduce((a,o)=>a+o.fixingPrice,0)/r.length,cashRate:r.reduce((a,o)=>a+o.cashRate,0)/r.length,recoveryRate:r.reduce((a,o)=>a+o.recoveryRate,0)/r.length,recoveryRateForLong:r.reduce((a,o)=>a+o.recoveryRateForLong,0)/r.length,recoveryRateForShort:r.reduce((a,o)=>a+o.recoveryRateForShort,0)/r.length,marketBid:r.reduce((a,o)=>a+o.marketBid,0)/r.length,marketOffer:r.reduce((a,o)=>a+o.marketOffer,0)/r.length,shortSaleMinPrice:r.reduce((a,o)=>a+o.shortSaleMinPrice,0)/r.length,previousClosingPrice:r.reduce((a,o)=>a+o.previousClosingPrice,0)/r.length,thresholdLimitPriceBanding:r.reduce((a,o)=>a+o.thresholdLimitPriceBanding,0)/r.length,dailyFinancingValue:r.reduce((a,o)=>a+o.dailyFinancingValue,0)/r.length,accruedFinancingValue:r.reduce((a,o)=>a+o.accruedFinancingValue,0)/r.length,twap:r.reduce((a,o)=>a+o.twap,0)/r.length};e.push(c)}return e.push(h[h.length-1]),e},de=h=>async t=>{try{let e=t.symbol,n=h.get(e)||[];if(n.length===0)return{content:[{type:"text",text:`No price data available for ${e}`,uri:"getStockGraph"}]};let s=he(n,500),i=new ue.default;i.setWidth(1200),i.setHeight(600),i.setBackgroundColor("transparent");let l=s.map(p=>new Date(p.timestamp).toLocaleTimeString()),r=s.map(p=>p.bid),c=s.map(p=>p.offer),a=s.map(p=>p.spread),o=s.map(p=>p.volume),u=s.map(p=>p.trade),m=s.map(p=>p.vwap),d=s.map(p=>p.twap),f=Math.max(...o.filter(p=>p>0)),g=Math.max(...r,...c,...u,...m,...d),b=o.map(p=>p/f*g*.3),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}}},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:"getStockPriceHistory"}]};let s=he(n,500);return{content:[{type:"text",text:JSON.stringify({symbol:e,count:s.length,originalCount:n.length,data:s.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"),st={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"},at={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"},it={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"},lt={1:"AutomatedExecutionNoIntervention",2:"AutomatedExecutionInterventionOK",3:"ManualOrder"},pe=(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
|
+
|
|
6
|
+
Parameters verified:
|
|
7
|
+
- ClOrdID: ${e.clOrdID}
|
|
8
|
+
- HandlInst: ${e.handlInst} (${lt[e.handlInst]})
|
|
9
|
+
- Quantity: ${e.quantity}
|
|
10
|
+
- Price: ${e.price}
|
|
11
|
+
- OrdType: ${e.ordType} (${st[e.ordType]})
|
|
12
|
+
- Side: ${e.side} (${at[e.side]})
|
|
13
|
+
- Symbol: ${e.symbol}
|
|
14
|
+
- TimeInForce: ${e.timeInForce} (${it[e.timeInForce]})
|
|
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}}},fe=(h,t,e)=>async n=>{try{let s=t.get(n.clOrdID);if(!s)return{content:[{type:"text",text:`Error: Order ${n.clOrdID} has not been verified. Please call verifyOrder first.`,uri:"executeOrder"}],isError:!0};if(s.handlInst!==n.handlInst||s.quantity!==Number.parseFloat(String(n.quantity))||s.price!==Number.parseFloat(String(n.price))||s.ordType!==n.ordType||s.side!==n.side||s.symbol!==n.symbol||s.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(s){return{content:[{type:"text",text:`Error: ${s instanceof Error?s.message:"Failed to execute order"}`,uri:"executeOrder"}],isError:!0}}};var be=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 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:"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 Pe=(h,t,e,n)=>({parse:be(h),parseToJSON:ye(h),verifyOrder:pe(h,t),executeOrder:fe(h,t,e),marketDataRequest:me(h,e),getStockGraph:de(n),getStockPriceHistory:ge(n),technicalAnalysis:ce(n)});var I=require("fixparser");function ct(h,t){return h[t]||t}function Me(h,t,e,n,s,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||[],o={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(ct(I.MDEntryType,f)){case I.MDEntryType.Bid:o.bid=g;break;case I.MDEntryType.Offer:o.offer=g;break;case I.MDEntryType.Trade:o.trade=g;break;case I.MDEntryType.IndexValue:o.indexValue=g;break;case I.MDEntryType.OpeningPrice:o.openingPrice=g;break;case I.MDEntryType.ClosingPrice:o.closingPrice=g;break;case I.MDEntryType.SettlementPrice:o.settlementPrice=g;break;case I.MDEntryType.TradingSessionHighPrice:o.tradingSessionHighPrice=g;break;case I.MDEntryType.TradingSessionLowPrice:o.tradingSessionLowPrice=g;break;case I.MDEntryType.VWAP:o.vwap=g;break;case I.MDEntryType.Imbalance:o.imbalance=b;break;case I.MDEntryType.TradeVolume:o.volume=b;break;case I.MDEntryType.OpenInterest:o.openInterest=b;break;case I.MDEntryType.CompositeUnderlyingPrice:o.compositeUnderlyingPrice=g;break;case I.MDEntryType.SimulatedSellPrice:o.simulatedSellPrice=g;break;case I.MDEntryType.SimulatedBuyPrice:o.simulatedBuyPrice=g;break;case I.MDEntryType.MarginRate:o.marginRate=g;break;case I.MDEntryType.MidPrice:o.midPrice=g;break;case I.MDEntryType.EmptyBook:o.emptyBook=1;break;case I.MDEntryType.SettleHighPrice:o.settleHighPrice=g;break;case I.MDEntryType.SettleLowPrice:o.settleLowPrice=g;break;case I.MDEntryType.PriorSettlePrice:o.priorSettlePrice=g;break;case I.MDEntryType.SessionHighBid:o.sessionHighBid=g;break;case I.MDEntryType.SessionLowOffer:o.sessionLowOffer=g;break;case I.MDEntryType.EarlyPrices:o.earlyPrices=g;break;case I.MDEntryType.AuctionClearingPrice:o.auctionClearingPrice=g;break;case I.MDEntryType.SwapValueFactor:o.swapValueFactor=g;break;case I.MDEntryType.DailyValueAdjustmentForLongPositions:o.dailyValueAdjustmentForLongPositions=g;break;case I.MDEntryType.CumulativeValueAdjustmentForLongPositions:o.cumulativeValueAdjustmentForLongPositions=g;break;case I.MDEntryType.DailyValueAdjustmentForShortPositions:o.dailyValueAdjustmentForShortPositions=g;break;case I.MDEntryType.CumulativeValueAdjustmentForShortPositions:o.cumulativeValueAdjustmentForShortPositions=g;break;case I.MDEntryType.FixingPrice:o.fixingPrice=g;break;case I.MDEntryType.CashRate:o.cashRate=g;break;case I.MDEntryType.RecoveryRate:o.recoveryRate=g;break;case I.MDEntryType.RecoveryRateForLong:o.recoveryRateForLong=g;break;case I.MDEntryType.RecoveryRateForShort:o.recoveryRateForShort=g;break;case I.MDEntryType.MarketBid:o.marketBid=g;break;case I.MDEntryType.MarketOffer:o.marketOffer=g;break;case I.MDEntryType.ShortSaleMinPrice:o.shortSaleMinPrice=g;break;case I.MDEntryType.PreviousClosingPrice:o.previousClosingPrice=g;break;case I.MDEntryType.ThresholdLimitPriceBanding:o.thresholdLimitPriceBanding=g;break;case I.MDEntryType.DailyFinancingValue:o.dailyFinancingValue=g;break;case I.MDEntryType.AccruedFinancingValue:o.accruedFinancingValue=g;break;case I.MDEntryType.TWAP:o.twap=g;break}}o.spread=o.offer-o.bid,n.has(r)||n.set(r,[]);let u=n.get(r);u.push(o),u.length>s&&u.splice(0,u.length-s),i?.(r,o);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 Q=class extends z{verifiedOrders=new Map;pendingRequests=new Map;marketDataPrices=new Map;MAX_PRICE_HISTORY=1e5;server=new Se.Server({name:"fixparser",version:"1.0.0"},{capabilities:{tools:Object.entries(ee).reduce((t,[e,{description:n,schema:s}])=>(t[e]={description:n,parameters:s},t),{})}});transport=new ve.StdioServerTransport;constructor({logger:t,onReady:e}){super({logger:t,onReady:e})}async register(t){this.parser=t,this.parser.addOnMessageCallback(e=>{Me(e,this.parser,this.pendingRequests,this.marketDataPrices,this.MAX_PRICE_HISTORY)}),this.addWorkflows(),await this.server.connect(this.transport),this.onReady&&this.onReady()}addWorkflows(){this.parser&&this.server&&(this.server.setRequestHandler(X.z.object({method:X.z.literal("tools/list")}),async()=>({tools:Object.entries(ee).map(([t,{description:e,schema:n}])=>({name:t,description:e,inputSchema:n}))})),this.server.setRequestHandler(X.z.object({method:X.z.literal("tools/call"),params:X.z.object({name:X.z.string(),arguments:X.z.any(),_meta:X.z.object({progressToken:X.z.number()}).optional()})}),async t=>{let{name:e,arguments:n}=t.params,i=Pe(this.parser,this.verifiedOrders,this.pendingRequests,this.marketDataPrices)[e];if(!i)return{content:[{type:"text",text:`Tool not found: ${e}`,uri:e}],isError:!0};let l=await i(n);return{content:l.content,isError:l.isError}}),process.on("SIGINT",async()=>{await this.server.close(),process.exit(0)}))}};var ut=async()=>{await A.LicenseManager.setLicenseKey(process.env.FIXPARSER_LICENSE_KEY);let h=process.env.FIXPARSER_SENDER||"SENDER",t=process.env.FIXPARSER_TARGET||"TARGET",e=new A.FIXParser({logging:!0,logOptions:{level:"info",format:"jsonrpc",transport:new le({format:"jsonrpc"})},plugins:[new Q({port:3099,onReady:()=>{}})]}),n=()=>{let i=e.createMessage(new A.Field(A.Fields.MsgType,A.Messages.Logon),new A.Field(A.Fields.MsgSeqNum,e.getNextTargetMsgSeqNum()),new A.Field(A.Fields.SenderCompID,h),new A.Field(A.Fields.SendingTime,e.getTimestamp()),new A.Field(A.Fields.TargetCompID,t),new A.Field(A.Fields.ResetSeqNumFlag,A.ResetSeqNumFlag.Yes),new A.Field(A.Fields.EncryptMethod,A.EncryptMethod.None),new A.Field(A.Fields.HeartBtInt,10));e.send(i)},s={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",onOpen:()=>{e.logger.log({level:"info",message:"FIXParser logging in..."}),n()},onClose:()=>{e.logger.log({level:"info",message:"FIXParser disconnected. Reconnecting in 1 second..."}),setTimeout(()=>{e.connect(s)},1e3)}};e.connect(s)};ut().catch(h=>console.error("Error initializing server:",h));
|
|
18
|
+
//# sourceMappingURL=StdioServer.js.map
|