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