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