### Install and Run MCP Server (Bash) Source: https://github.com/ubongisrael/trading-intelligence-mcp/blob/master/README.md Commands to install dependencies, configure the environment, build, and run the MCP server in development or production mode. Requires Node.js and Redis. ```bash npm install cp .env.example .env nano .env npm run build npm run dev npm start ``` -------------------------------- ### Get Price Tool Example (JSON) Source: https://github.com/ubongisrael/trading-intelligence-mcp/blob/master/README.md An example JSON payload for the `get_price` MCP tool to retrieve real-time asset prices. Supports stocks, crypto, and forex. ```json { "symbol": "AAPL" } ``` -------------------------------- ### Start Trading Intelligence MCP Server Source: https://context7.com/ubongisrael/trading-intelligence-mcp/llms.txt Instructions on how to start the MCP server in different modes (stdio, HTTP, development, production). It uses Node.js and npm scripts for execution. ```typescript import { createServer } from './server.js'; async function main() { const server = createServer(); await server.start(); // Graceful shutdown process.on('SIGINT', async () => { await server.shutdown(); process.exit(0); }); } main(); ``` ```bash # Start in development mode with stdio transport npm run dev # Start HTTP server for Context Protocol npm run dev:http # Production mode npm start # stdio mode npm start:http # HTTP mode ``` -------------------------------- ### Environment Configuration (.env file) Source: https://context7.com/ubongisrael/trading-intelligence-mcp/llms.txt Provides an example of the `.env` file used for configuring the server. It lists essential variables for server settings, Redis connection, API keys, cache TTLs, and feature flags. ```bash # Server Configuration PORT=3000 NODE_ENV=development LOG_LEVEL=info # Redis (required for caching) REDIS_URL=redis://localhost:6379 REDIS_PASSWORD= REDIS_POOL_SIZE=10 # API Keys ALPHA_VANTAGE_API_KEY=your_key_here # Required for fundamentals COINGECKO_API_KEY=your_key_here # Optional, higher rate limits FINNHUB_API_KEY=your_key_here # Optional # Cache TTLs (seconds) CACHE_TTL_PRICES=300 # 5 minutes CACHE_TTL_LIQUIDITY=900 # 15 minutes CACHE_TTL_FUNDAMENTALS=3600 # 1 hour # Features ENABLE_CACHING=true ENABLE_HISTORICAL_DATA=true ``` -------------------------------- ### HTTP Server for Context Protocol (TypeScript) Source: https://context7.com/ubongisrael/trading-intelligence-mcp/llms.txt Sets up and starts an HTTP server for the Context Protocol, enabling StreamableHTTP transport for cloud deployments. It includes details on server start and available endpoints. ```typescript import { createHttpServer } from './http-server.js'; const server = createHttpServer(); await server.start(); // Server runs on PORT (default 3000) // Available endpoints: // GET / - Server info // GET /health - Health check (no auth) // POST /mcp - MCP requests (JWT authenticated) // GET /mcp - Long polling (JWT authenticated) ``` -------------------------------- ### Deploy MCP Server (Bash) Source: https://github.com/ubongisrael/trading-intelligence-mcp/blob/master/README.md Commands to build the project for production and start the production server. Suitable for deployment on platforms like Railway or Render. ```bash npm run build npm start ``` -------------------------------- ### GET /contextual_fundamentals Source: https://context7.com/ubongisrael/trading-intelligence-mcp/llms.txt Provides AI-powered fundamental analysis, including year-over-year changes, pattern detection, insider trading insights, and contextual information. ```APIDOC ## GET /contextual_fundamentals ### Description Retrieves AI-enhanced fundamental data for a stock. This endpoint offers insights into year-over-year metric changes, identifies financial patterns, analyzes insider trading activity, and provides contextual commentary. ### Method GET ### Endpoint /contextual_fundamentals ### Parameters #### Query Parameters - **symbol** (string) - Required - The stock ticker symbol (e.g., "NVDA"). - **includeInsider** (boolean) - Optional - Whether to include insider trading analysis. Defaults to `true`. - **includeEvents** (boolean) - Optional - Whether to include analysis of material events. Defaults to `true`. ### Request Example ```json { "symbol": "NVDA", "includeInsider": true, "includeEvents": true } ``` ### Response #### Success Response (200) - **symbol** (string) - The stock ticker symbol. - **headline** (string) - A concise summary or headline about the company's fundamentals. - **yoyChanges** (array) - An array detailing year-over-year changes in key metrics. - **metric** (string) - The financial metric that changed (e.g., "revenue", "grossMargin"). - **change** (number) - The absolute change in the metric. - **changePercent** (number) - The percentage change in the metric. - **direction** (string) - The direction of the change ("up" or "down"). - **patterns** (array) - Detected financial or operational patterns. - **type** (string) - The type of pattern identified (e.g., "revenue_acceleration"). - **severity** (string) - The significance of the pattern (e.g., "positive", "negative"). - **description** (string) - A description of the pattern. - **insiderActivity** (object) - Analysis of insider trading. - **netActivity** (string) - Net activity (e.g., "net_buying", "net_selling"). - **pattern** (string) - The pattern observed in insider trades (e.g., "clustered"). - **sentiment** (string) - The sentiment derived from insider activity (e.g., "bullish"). - **keyInsights** (array) - Bullet points highlighting significant findings. - **sentiment** (string) - Overall sentiment towards the stock based on the analysis (e.g., "bullish", "bearish", "neutral"). #### Response Example ```json { "symbol": "NVDA", "headline": "NVDA shows strong revenue growth with improving margins", "yoyChanges": [ { "metric": "revenue", "change": 15000000000, "changePercent": 122.5, "direction": "up" }, { "metric": "grossMargin", "change": 5.2, "changePercent": 8.3, "direction": "up" } ], "patterns": [ { "type": "revenue_acceleration", "severity": "positive", "description": "Revenue growth accelerating" } ], "insiderActivity": { "netActivity": "net_buying", "pattern": "clustered", "sentiment": "bullish" }, "keyInsights": [ "Revenue grew 122% YoY driven by AI chip demand", "Gross margin expansion indicates pricing power" ], "sentiment": "bullish" } ``` ``` -------------------------------- ### GET /full_fundamentals Source: https://context7.com/ubongisrael/trading-intelligence-mcp/llms.txt Retrieves comprehensive fundamental data for a stock, including company overview, earnings history, and calculated financial metrics. ```APIDOC ## GET /full_fundamentals ### Description Fetches a complete set of fundamental data for a given stock symbol. This includes company overview details, historical earnings, and various financial metrics. ### Method GET ### Endpoint /full_fundamentals ### Parameters #### Query Parameters - **symbol** (string) - Required - The stock ticker symbol (e.g., "GOOGL"). ### Request Example ```json { "symbol": "GOOGL" } ``` ### Response #### Success Response (200) - **symbol** (string) - The stock ticker symbol. - **overview** (object) - Contains general company information. - **symbol** (string) - Company ticker. - **name** (string) - Company name. - **marketCap** (number) - Market capitalization. - **peRatio** (number) - Price-to-earnings ratio. - ... (other overview fields) - **earnings** (object) - Contains earnings history data (structure similar to `/earnings` endpoint). - **summary** (string) - A textual summary of the company's financial status. - **source** (string) - The data source (e.g., "alpha_vantage"). #### Response Example ```json { "symbol": "GOOGL", "overview": { "symbol": "GOOGL", "name": "Alphabet Inc", "marketCap": 1750000000000, "peRatio": 24.5 }, "earnings": { "symbol": "GOOGL", "earnings": [] }, "summary": "Financial Summary for Alphabet Inc: Market Cap $1.75T...", "source": "alpha_vantage" } ``` ``` -------------------------------- ### Get Nearest Support and Resistance Levels (TypeScript) Source: https://context7.com/ubongisrael/trading-intelligence-mcp/llms.txt Retrieves the nearest support and resistance levels for quick trading decisions. It returns only the key levels closest to the current price. The input requires a trading symbol and optionally a timeframe. The response includes the current price, nearest support and resistance levels, and their respective strengths. ```typescript // MCP Tool Input { "symbol": "NVDA", "timeframe": "4h" // Optional } // Example Response { "symbol": "NVDA", "currentPrice": 495.22, "nearestSupport": 480.00, "nearestResistance": 510.00, "supportStrength": 0.9, "resistanceStrength": 0.6 } ``` -------------------------------- ### Get All Funding Rates for Market-Wide Analysis (TypeScript) Source: https://context7.com/ubongisrael/trading-intelligence-mcp/llms.txt Retrieves funding rates for all available perpetual futures on a specific exchange, typically Binance, for market-wide sentiment analysis. No input parameters are required. The response is an array of funding rate objects for multiple symbols, along with a timestamp. ```typescript import { fetchAllFundingRates } from './services/funding.js'; const allRates = await fetchAllFundingRates(); const avgRate = allRates.reduce((sum, r) => sum + r.rate, 0) / allRates.length; const bullish = allRates.filter(r => r.rate > 0).length; console.log(`Market avg funding: ${(avgRate * 100).toFixed(4)}%`); console.log(`Bullish symbols: ${bullish}/${allRates.length}`); ``` -------------------------------- ### Get Company Overview and Fundamental Data (TypeScript) Source: https://context7.com/ubongisrael/trading-intelligence-mcp/llms.txt Fetches fundamental company data, including profile information and key financial metrics like sector, market cap, P/E ratio, EPS, and 52-week range. The input requires a stock ticker symbol. The response provides a comprehensive overview of the company's financial standing. ```typescript import { fetchCompanyOverview } from './services/fundamentals-alphavantage.js'; const overview = await fetchCompanyOverview('MSFT'); console.log(`${overview.name} (${overview.sector})`); console.log(`Market Cap: $${(overview.marketCap / 1e9).toFixed(2)}B`); console.log(`P/E: ${overview.peRatio}, EPS: $${overview.eps}`); ``` -------------------------------- ### GET /earnings Source: https://context7.com/ubongisrael/trading-intelligence-mcp/llms.txt Retrieves the quarterly earnings history for a given stock symbol, including EPS estimates, actuals, and surprise percentages. ```APIDOC ## GET /earnings ### Description Fetches quarterly earnings data for a specified stock symbol. This includes reported Earnings Per Share (EPS), estimated EPS, and the surprise percentage. ### Method GET ### Endpoint /earnings ### Parameters #### Query Parameters - **symbol** (string) - Required - The stock ticker symbol (e.g., "AAPL"). - **limit** (integer) - Optional - The number of past quarters to retrieve. Defaults to 8. ### Request Example ```json { "symbol": "AAPL", "limit": 8 } ``` ### Response #### Success Response (200) - **symbol** (string) - The stock ticker symbol. - **earnings** (array) - An array of quarterly earnings objects. - **fiscalDateEnding** (string) - The fiscal date ending for the quarter (e.g., "2024-Q1"). - **reportedEPS** (number) - The actual reported Earnings Per Share. - **estimatedEPS** (number) - The estimated Earnings Per Share. - **surprise** (number) - The difference between reported and estimated EPS. - **surprisePercentage** (number) - The surprise amount as a percentage of the estimated EPS. - **source** (string) - The data source (e.g., "alpha_vantage"). - **cached** (boolean) - Indicates if the data was served from cache. #### Response Example ```json { "symbol": "AAPL", "earnings": [ { "fiscalDateEnding": "2024-Q1", "reportedEPS": 2.18, "estimatedEPS": 2.10, "surprise": 0.08, "surprisePercentage": 3.81 } ], "source": "alpha_vantage", "cached": false } ``` ``` -------------------------------- ### HTTP Server Health Check (Bash) Source: https://context7.com/ubongisrael/trading-intelligence-mcp/llms.txt Demonstrates how to perform a health check on the running HTTP server using curl. It shows the command to execute and an example of the expected JSON response. ```bash # Health check curl http://localhost:3000/health # Response { "status": "healthy", "version": "0.1.0", "name": "trading-intelligence", "uptime": 123.456, "transport": "StreamableHTTP", "securityEnabled": true } ``` -------------------------------- ### Cache Service API Source: https://context7.com/ubongisrael/trading-intelligence-mcp/llms.txt Provides domain-specific caching with a Redis backend using the cache-aside pattern. Supports caching for prices, liquidity/technical analysis, and fundamentals. Includes methods for getting, fetching, and invalidating cache entries, as well as a health check. ```APIDOC ## Cache Service API ### Description Provides domain-specific caching with a Redis backend and cache-aside pattern. ### Methods - `initializeRedis()`: Initializes the Redis connection. - `getCacheService()`: Gets the singleton cache service instance. - `prices.getOrFetch(symbol, fetchFunction)`: Gets or fetches stock prices. - `liquidity.getOrFetch(symbol, interval, fetchFunction)`: Gets or fetches liquidity/technical analysis data. - `fundamentals.getOrFetch(symbol, type, fetchFunction)`: Gets or fetches fundamental data. - `healthCheck()`: Checks the health of the cache service. - `prices.invalidate(symbol)`: Invalidates the cache for a specific stock price. - `prices.invalidateAll()`: Invalidates all cached stock prices. - `shutdownRedis()`: Gracefully shuts down the Redis connection. ### Request Example (Conceptual) ```typescript // Initialize Redis connection await initializeRedis(); // Get singleton cache service const cache = getCacheService(); // Price caching const priceResult = await cache.prices.getOrFetch('AAPL', async () => { return await fetchStockPrice('AAPL'); }); console.log(`Price: $${priceResult.data.price}, Cached: ${priceResult.cached}`); // Invalidate cache await cache.prices.invalidate('AAPL'); // Graceful shutdown await shutdownRedis(); ``` ### Response Example (Conceptual) ```json { "data": { "price": 170.50 }, "cached": true } ``` ### Error Handling - Errors during Redis operations will be thrown. - `fetchFunction` errors will be propagated. ``` -------------------------------- ### Get Liquidity Zones for Technical Analysis (TypeScript) Source: https://context7.com/ubongisrael/trading-intelligence-mcp/llms.txt Identifies key support and resistance levels (liquidity zones) based on historical pivot points. It returns the top 5 most significant price levels with strength ratings. Input requires a trading symbol and optionally a timeframe and lookback period. The response includes current price, identified zones, trend, and a recommendation. ```typescript import { calculateLiquidityZones } from './services/liquidity.js'; const analysis = await calculateLiquidityZones('TSLA', '1d', 90); console.log(`Current: $${analysis.currentPrice}, Trend: ${analysis.trend}`); analysis.liquidityZones.forEach(zone => { console.log(`${zone.type}: $${zone.price} (${zone.strength} strength, ${zone.touchCount} touches)`); }); ``` -------------------------------- ### Get Full Fundamentals Data (TypeScript) Source: https://context7.com/ubongisrael/trading-intelligence-mcp/llms.txt Fetches comprehensive fundamental data for a stock symbol, including company overview, earnings history, and calculated financial metrics. It requires a stock symbol as input and returns a detailed object containing various financial aspects. ```typescript // MCP Tool Input { "symbol": "GOOGL" } // Example Response { "symbol": "GOOGL", "overview": { "symbol": "GOOGL", "name": "Alphabet Inc", "marketCap": 1750000000000, "peRatio": 24.5, ... }, "earnings": { "symbol": "GOOGL", "earnings": [...], ... }, "summary": "Financial Summary for Alphabet Inc: Market Cap $1.75T...", "source": "alpha_vantage" } // Usage in code import { fetchFullFundamentals } from './services/fundamentals-alphavantage.js'; const data = await fetchFullFundamentals('GOOGL'); console.log(`${data.overview.name}`); console.log(`Gross Margin: ${data.metrics.profitability.grossMargin}%`); console.log(`ROE: ${data.metrics.profitability.roe}%`); ``` -------------------------------- ### Get Quarterly Earnings History (TypeScript) Source: https://context7.com/ubongisrael/trading-intelligence-mcp/llms.txt Retrieves historical quarterly earnings data for a given stock symbol, including reported and estimated EPS, and surprise percentages. It takes a symbol and an optional limit for the number of quarters. The output is a list of earnings reports. ```typescript // MCP Tool Input { "symbol": "AAPL", "limit": 8 // Optional: Number of quarters (default: 8) } // Example Response { "symbol": "AAPL", "earnings": [ { "fiscalDateEnding": "2024-Q1", "reportedEPS": 2.18, "estimatedEPS": 2.10, "surprise": 0.08, "surprisePercentage": 3.81 }, // ... more quarters ], "source": "alpha_vantage", "cached": false } // Usage in code import { fetchEarnings } from './services/fundamentals-alphavantage.js'; const earnings = await fetchEarnings('AAPL', 8); const beats = earnings.filter(e => (e.surprisePercent || 0) > 0).length; console.log(`AAPL beat estimates ${beats}/${earnings.length} quarters`); ``` -------------------------------- ### Get Contextual Fundamentals with AI Analysis (TypeScript) Source: https://context7.com/ubongisrael/trading-intelligence-mcp/llms.txt Retrieves AI-powered fundamental data, including year-over-year changes, pattern detection, insider trading analysis, and contextual insights for a given stock symbol. It accepts a symbol and optional flags for including insider and event data. ```typescript // MCP Tool Input { "symbol": "NVDA", "includeInsider": true, // Optional: Include insider trading (default: true) "includeEvents": true // Optional: Include material events (default: true) } // Example Response { "symbol": "NVDA", "headline": "NVDA shows strong revenue growth with improving margins", "yoyChanges": [ { "metric": "revenue", "change": 15000000000, "changePercent": 122.5, "direction": "up" }, { "metric": "grossMargin", "change": 5.2, "changePercent": 8.3, "direction": "up" } ], "patterns": [ { "type": "revenue_acceleration", "severity": "positive", "description": "Revenue growth accelerating" } ], "insiderActivity": { "netActivity": "net_buying", "pattern": "clustered", "sentiment": "bullish" }, "keyInsights": [ "Revenue grew 122% YoY driven by AI chip demand", "Gross margin expansion indicates pricing power" ], "sentiment": "bullish" } ``` -------------------------------- ### Get Funding Rate for Perpetual Futures (TypeScript) Source: https://context7.com/ubongisrael/trading-intelligence-mcp/llms.txt Fetches the current funding rate for a specified cryptocurrency perpetual future. Positive rates indicate bullish sentiment (longs pay shorts), while negative rates indicate bearish sentiment. The input requires a crypto symbol. The response includes the symbol, funding rate, next funding time, and sentiment interpretation. ```typescript import { fetchFundingRate } from './services/funding.js'; const rate = await fetchFundingRate('ETH'); console.log(`${rate.symbol} Funding: ${(rate.rate * 100).toFixed(4)}%`); console.log(`Next funding: ${rate.nextFundingTime}`); ``` -------------------------------- ### Running the Test Suite for Alpha Vantage Integration Source: https://github.com/ubongisrael/trading-intelligence-mcp/blob/master/TASK_MANIFEST.md Provides instructions on how to execute the test suite for the Alpha Vantage integration. This includes navigating to the project directory and running the test script using Node.js. ```bash cd "C:\Users\Jerry\Desktop\Sheikh\Unboundling Monopolies\trading-intelligence-mcp" node test-alphavantage.js ``` -------------------------------- ### Deployment Checklist for Production Readiness Source: https://github.com/ubongisrael/trading-intelligence-mcp/blob/master/TASK_MANIFEST.md Outlines the deployment checklist, indicating the status of various tasks required for production readiness. It includes checks for feature implementation, test status, error handling, caching, documentation, and build processes. ```text Deployment Checklist - [x] Build successful (`npm run build`) - [x] Tests passing (`node test-alphavantage.js`) - [x] Configuration template provided - [x] Documentation complete - [ ] User configuration updated (Sheikh's action) - [ ] Claude Desktop restarted (Sheikh's action) - [ ] Production verification (Sheikh's action) ``` -------------------------------- ### Run Development Commands (Bash) Source: https://github.com/ubongisrael/trading-intelligence-mcp/blob/master/README.md Common development commands for the project, including running tests, linting, and formatting code. Uses npm scripts. ```bash npm test npm run lint npm run format ``` -------------------------------- ### Environment Configuration Source: https://context7.com/ubongisrael/trading-intelligence-mcp/llms.txt Configures the server via environment variables, typically in a `.env` file. Covers server settings, Redis connection details, API keys for external services, and cache Time-To-Live (TTL) values. ```APIDOC ## Environment Configuration ### Description Configure the server via environment variables, typically in a `.env` file. ### Server Configuration - `PORT` (number): The port the server will listen on. Default: `3000`. - `NODE_ENV` (string): The Node.js environment (`development`, `production`, etc.). Default: `development`. - `LOG_LEVEL` (string): The logging verbosity level (e.g., `info`, `debug`, `error`). Default: `info`. ### Redis Configuration (Required for Caching) - `REDIS_URL` (string): The URL for the Redis instance (e.g., `redis://localhost:6379`). - `REDIS_PASSWORD` (string): The password for Redis authentication (if required). - `REDIS_POOL_SIZE` (number): The maximum number of connections in the Redis pool. Default: `10`. ### API Keys - `ALPHA_VANTAGE_API_KEY` (string): Required for fetching fundamental data from Alpha Vantage. - `COINGECKO_API_KEY` (string): Optional. Provides higher rate limits for Coingecko data. - `FINNHUB_API_KEY` (string): Optional. Used for fetching financial data from Finnhub. ### Cache TTLs (Time-To-Live in Seconds) - `CACHE_TTL_PRICES` (number): Duration in seconds for which price data is cached. Default: `300` (5 minutes). - `CACHE_TTL_LIQUIDITY` (number): Duration in seconds for which liquidity data is cached. Default: `900` (15 minutes). - `CACHE_TTL_FUNDAMENTALS` (number): Duration in seconds for which fundamental data is cached. Default: `3600` (1 hour). ### Features - `ENABLE_CACHING` (boolean): Enables or disables the caching layer. Default: `true`. - `ENABLE_HISTORICAL_DATA` (boolean): Enables or disables fetching historical data. Default: `true`. ### Example `.env` file ```bash PORT=3000 NODE_ENV=development LOG_LEVEL=info REDIS_URL=redis://localhost:6379 REDIS_PASSWORD= REDIS_POOL_SIZE=10 ALPHA_VANTAGE_API_KEY=your_key_here COINGECKO_API_KEY=your_key_here FINNHUB_API_KEY=your_key_here CACHE_TTL_PRICES=300 CACHE_TTL_LIQUIDITY=900 CACHE_TTL_FUNDAMENTALS=3600 ENABLE_CACHING=true ENABLE_HISTORICAL_DATA=true ``` ``` -------------------------------- ### v0.1.0 - Alpha Vantage Migration Summary Source: https://github.com/ubongisrael/trading-intelligence-mcp/blob/master/TASK_MANIFEST.md Details the changes introduced in version 0.1.0, which involved migrating from Finnhub to Alpha Vantage. This version includes the addition of Alpha Vantage fundamentals, a 7-day Redis cache, and new tools for company overview, earnings, and financial statements. ```text v0.1.0 - Alpha Vantage Migration (January 29, 2026) **Status**: CURRENT VERSION ✅ **Added**: - Alpha Vantage fundamentals service - 7-day Redis caching (Opus) - Sequential API calls (Opus) - Company overview tool - Earnings data tool - Financial statements tool - Full fundamentals tool - Integration test suite - Comprehensive documentation **Fixed**: - Finnhub.io blocking issue - Rate limit errors (sequential calls) - Redis lifecycle management - TypeScript type safety **Changed**: - Migrated from Finnhub to Alpha Vantage - Extended cache TTL from 1 hour to 7 days - Improved error messages - Enhanced usage statistics **Performance**: - System score: 8/10 → 9.5/10 - Functionality: 60% → 100% - Cache efficiency: 24x → 168x multiplier ``` -------------------------------- ### Environment Variables for Alpha Vantage Configuration Source: https://github.com/ubongisrael/trading-intelligence-mcp/blob/master/TASK_MANIFEST.md Specifies the required environment variables for configuring the Alpha Vantage integration, including the API key and Redis connection URL. Optional variables for upgrading the tier and customizing cache TTL are also listed. ```bash ALPHA_VANTAGE_API_KEY=your_key_here REDIS_URL=rediss://default:password@host:6379 # Optional Configuration ALPHA_VANTAGE_TIER=premium # If upgraded CACHE_TTL_FUNDAMENTALS=604800 # 7 days (default) ``` -------------------------------- ### API Consumption Statistics and Usage Pattern Source: https://github.com/ubongisrael/trading-intelligence-mcp/blob/master/TASK_MANIFEST.md Details the API consumption limits for the free tier of Alpha Vantage, including daily and minute limits, cache duration, and effective weekly capacity. It also outlines a typical weekly usage pattern demonstrating how the cache strategy keeps usage well within limits. ```text API Consumption (Free Tier) - Daily Limit: 25 requests - Minute Limit: 5 requests - Cache Duration: 7 days - Effective Capacity: 175+ queries/week Typical Weekly Usage Pattern ``` Monday: Build cache (20 stocks) → 20 API calls Tue-Sun: Query cached stocks → 0 API calls Next Monday: Refresh 10-15 expired → 15 API calls Average: ~20 calls/week (well within 175/week limit) ``` Cache Hit Rates (Expected) - Day 1: 0% (building cache) - Days 2-7: 90-95% (most queries cached) - Week 2+: 70-80% (some refreshes needed) ``` -------------------------------- ### Cache Service API (TypeScript) Source: https://context7.com/ubongisrael/trading-intelligence-mcp/llms.txt Demonstrates the usage of the cache service for fetching and caching financial data like stock prices, liquidity, and fundamentals. It includes initialization, retrieval, invalidation, and shutdown of the Redis connection. ```typescript import { getCacheService, initializeRedis, shutdownRedis } from './cache/index.js'; // Initialize Redis connection await initializeRedis(); // Get singleton cache service const cache = getCacheService(); // Price caching const priceResult = await cache.prices.getOrFetch('AAPL', async () => { return await fetchStockPrice('AAPL'); }); console.log(`Price: $${priceResult.data.price}, Cached: ${priceResult.cached}`); // Liquidity/Technical analysis caching const liquidityResult = await cache.liquidity.getOrFetch('TSLA', '1d', async () => { return await calculateLiquidityZones('TSLA', '1d'); }); // Fundamentals caching const fundamentalsResult = await cache.fundamentals.getOrFetch('MSFT', 'overview', async () => { return await fetchCompanyOverview('MSFT'); }); // Cache health check const health = await cache.healthCheck(); console.log(`Cache connected: ${health.connected}, Hit rate: ${health.stats.hitRate}%`); // Invalidate cache await cache.prices.invalidate('AAPL'); await cache.prices.invalidateAll(); // Graceful shutdown await shutdownRedis(); ``` -------------------------------- ### Performance Benchmarks for Alpha Vantage Operations Source: https://github.com/ubongisrael/trading-intelligence-mcp/blob/master/TASK_MANIFEST.md Presents performance benchmarks for various Alpha Vantage operations, comparing measured response times for first calls and cached responses against target times. It also details cache performance metrics like hit rates and response times for hits and misses. ```text Response Times (Measured) | Operation | First Call | Cached | Target | Status | |-----------|-----------|---------|---------|--------| | Company Overview | 2-3s | <100ms | <5s | ✅ Exceeded | | Earnings | 2-3s | <100ms | <5s | ✅ Exceeded | | Financial Statements | ~36s | <100ms | <60s | ✅ Met | | Full Fundamentals | ~15s | <100ms | <30s | ✅ Exceeded | Cache Performance - Hit Rate (Day 1): 0% - Hit Rate (Days 2-7): 90-95% - Average Hit Rate (Weekly): 70-80% - Response Time (Hit): <100ms - Response Time (Miss): 2-36s ``` -------------------------------- ### MCP Tools API Source: https://github.com/ubongisrael/trading-intelligence-mcp/blob/master/README.md This section details the available MCP tools for querying trading intelligence data, including prices, liquidity zones, and fundamental data. ```APIDOC ## MCP Tools API This section details the available MCP tools for querying trading intelligence data, including prices, liquidity zones, and fundamental data. ### `get_price` Retrieve real-time prices for any asset (stocks, crypto, forex). #### Method GET #### Endpoint /api/v1/price #### Query Parameters - **symbol** (string) - Required - Asset symbol (e.g., "AAPL", "BTC", "EUR/USD") - **assetType** (string) - Optional - Asset type filter (e.g., "stock", "crypto", "forex") #### Request Example ```json { "symbol": "AAPL" } ``` #### Success Response (200) - **price** (number) - The current price of the asset. - **symbol** (string) - The requested asset symbol. - **timestamp** (string) - The timestamp of the price data. #### Response Example ```json { "price": 175.50, "symbol": "AAPL", "timestamp": "2023-10-27T10:00:00Z" } ``` ### `get_liquidity_zones` Identify key liquidity zones and support/resistance levels. #### Method GET #### Endpoint /api/v1/liquidity #### Query Parameters - **symbol** (string) - Required - Asset symbol - **timeframe** (string) - Required - Chart timeframe (e.g., "1h", "4h", "1d") #### Request Example ```json { "symbol": "BTC/USD", "timeframe": "4h" } ``` #### Success Response (200) - **liquidityZones** (array) - An array of liquidity zone objects. - **level** (number) - The price level of the liquidity zone. - **type** (string) - The type of zone (e.g., "support", "resistance"). - **volume** (number) - The volume associated with the zone. #### Response Example ```json { "liquidityZones": [ { "level": 35000.00, "type": "support", "volume": 1200.50 }, { "level": 36500.00, "type": "resistance", "volume": 950.75 } ] } ``` ### `get_fundamentals` Retrieve fundamental data including financials, earnings, and SEC filings. #### Method GET #### Endpoint /api/v1/fundamentals #### Query Parameters - **symbol** (string) - Required - Stock symbol - **dataType** (string) - Required - Type of fundamental data (e.g., "earnings", "balance_sheet", "income_statement", "sec_filings") #### Request Example ```json { "symbol": "MSFT", "dataType": "earnings" } ``` #### Success Response (200) - **data** (object) - An object containing the requested fundamental data. #### Response Example ```json { "data": { "symbol": "MSFT", "period": "Q4 2023", "eps_actual": 2.92, "eps_estimate": 2.70, "revenue_actual": 56.19e9, "revenue_estimate": 54.20e9 } } ``` ``` -------------------------------- ### get_batch_prices - Batch Price Fetching Source: https://context7.com/ubongisrael/trading-intelligence-mcp/llms.txt Fetches prices for multiple assets in a single request, optimizing for efficiency. Supports up to 50 symbols per request. ```APIDOC ## POST /api/prices/batch ### Description Retrieves price data for multiple assets concurrently. This endpoint is optimized for batch processing and can handle up to 50 symbols in a single request. ### Method POST ### Endpoint /api/prices/batch ### Parameters #### Request Body - **symbols** (array of strings) - Required - A list of asset symbols for which to fetch prices (max 50). - **assetType** (string) - Optional - The type of asset, either 'stock' or 'crypto'. If provided, it applies to all symbols in the request. If omitted, the server will attempt to auto-detect for each symbol. ### Request Example ```json { "symbols": ["AAPL", "MSFT", "GOOGL", "BTC", "ETH"], "assetType": "stock" } ``` ### Response #### Success Response (200) - **prices** (array of objects) - A list of price data objects for each requested symbol. - Each object contains fields like 'symbol', 'price', 'changePercent', etc. - **timestamp** (string) - The ISO 8601 timestamp of the batch price data. #### Response Example ```json { "prices": [ { "symbol": "AAPL", "price": 178.72, "changePercent": 1.32, "timestamp": "2024-01-15T16:00:00.000Z", "source": "yahoo-finance", "cached": false }, { "symbol": "MSFT", "price": 402.56, "changePercent": 0.89, "timestamp": "2024-01-15T16:00:00.000Z", "source": "yahoo-finance", "cached": false }, { "symbol": "GOOGL", "price": 141.80, "changePercent": 1.05, "timestamp": "2024-01-15T16:00:00.000Z", "source": "yahoo-finance", "cached": false }, { "symbol": "BTC", "price": 42850.00, "changePercent": 2.15, "timestamp": "2024-01-15T16:00:00.000Z", "source": "coingecko", "cached": false }, { "symbol": "ETH", "price": 2520.00, "changePercent": 3.42, "timestamp": "2024-01-15T16:00:00.000Z", "source": "coingecko", "cached": false } ], "timestamp": "2024-01-15T16:00:00.000Z" } ``` ``` -------------------------------- ### HTTP Server for Context Protocol Source: https://context7.com/ubongisrael/trading-intelligence-mcp/llms.txt Provides a StreamableHTTP transport for Context Protocol cloud deployment with JWT authentication. Supports server info, health checks, and MCP requests/long polling. ```APIDOC ## HTTP Server for Context Protocol ### Description Provides StreamableHTTP transport for Context Protocol cloud deployment with JWT authentication. ### Method - `createHttpServer()`: Creates a new HTTP server instance. - `server.start()`: Starts the HTTP server. ### Endpoints - **GET /**: Server info. - **GET /health**: Health check (no authentication required). - **POST /mcp**: MCP requests (JWT authentication required). - **GET /mcp**: Long polling for MCP data (JWT authentication required). ### Parameters #### Query Parameters None for the main endpoints. #### Request Body - **POST /mcp**: Requires a valid JWT in the `Authorization` header. ### Request Example (Health Check) ```bash curl http://localhost:3000/health ``` ### Response #### Success Response (200) - **GET /**: Server information (e.g., version, name, transport). - **GET /health**: Health status object. - **POST /mcp**: Response to MCP request. - **GET /mcp**: Long-polling response. #### Response Example (Health Check) ```json { "status": "healthy", "version": "0.1.0", "name": "trading-intelligence", "uptime": 123.456, "transport": "StreamableHTTP", "securityEnabled": true } ``` ### Error Handling - Unauthorized access to protected endpoints (`/mcp`) will result in a 401 error. - Invalid requests may result in 400 or other appropriate HTTP error codes. ``` -------------------------------- ### POST /run_dcf_analysis Source: https://context7.com/ubongisrael/trading-intelligence-mcp/llms.txt Performs a Discounted Cash Flow (DCF) analysis for a stock, providing intrinsic value, WACC, projections, and a recommendation. ```APIDOC ## POST /run_dcf_analysis ### Description Executes a Discounted Cash Flow (DCF) valuation analysis for a given stock. The analysis includes intrinsic value calculation, Weighted Average Cost of Capital (WACC) breakdown, 10-year financial projections, and an investment recommendation. ### Method POST ### Endpoint /run_dcf_analysis ### Parameters #### Request Body - **symbol** (string) - Required - The US-listed stock ticker symbol (e.g., "AAPL"). ### Request Example ```json { "symbol": "AAPL" } ``` ### Response #### Success Response (200) - **metadata** (object) - Contains metadata about the analysis. - **companyName** (string) - The name of the company. - **ticker** (string) - The stock ticker symbol. - **dcfMethod** (string) - The method used for DCF calculation (e.g., "fcf_based"). - **currentMarketData** (object) - Current market information. - **currentPrice** (number) - The current stock price. - **marketCap** (number) - The company's market capitalization. - **growthAnalysis** (object) - Analysis of historical and projected growth rates. - **historicalGrowthRates** (object) - CAGR for revenue and free cash flow. - **compositeGrowth** (object) - A composite growth rate. - **waccCalculation** (object) - Details of the WACC calculation. - **wacc** (number) - The calculated WACC. - **waccFormatted** (string) - The WACC formatted as a percentage. - **valuationSummary** (object) - Summary of the valuation results. - **intrinsicValue** (number) - The calculated intrinsic value per share. - **currentPrice** (number) - The current market price. - **upsideDownsideFormatted** (string) - The potential upside or downside as a percentage. - **valuation** (string) - The valuation assessment (e.g., "UNDERVALUED", "OVERVALUED"). - **investmentRecommendation** (object) - The investment recommendation. - **recommendation** (string) - The recommendation (e.g., "BUY", "HOLD", "SELL"). - **confidence** (string) - The confidence level of the recommendation. - **targetPrice** (number) - The target price based on the analysis. - **expectedReturn** (number) - The expected rate of return. #### Response Example ```json { "metadata": { "companyName": "Apple Inc.", "ticker": "AAPL", "dcfMethod": "fcf_based" }, "currentMarketData": { "currentPrice": 178.72, "marketCap": 2780000000000 }, "growthAnalysis": { "historicalGrowthRates": { "revenueCagr3yr": 0.08, "normalizedFcfCagr3yr": 0.12 }, "compositeGrowth": { "rate": 0.10 } }, "waccCalculation": { "wacc": 0.0892, "waccFormatted": "8.92%" }, "valuationSummary": { "intrinsicValue": 195.50, "currentPrice": 178.72, "upsideDownsideFormatted": "+9.4%", "valuation": "UNDERVALUED" }, "investmentRecommendation": { "recommendation": "BUY", "confidence": "Medium", "targetPrice": 195.50, "expectedReturn": 0.094 } } ``` ``` -------------------------------- ### Batch Fetch Asset Prices (get_batch_prices) Source: https://context7.com/ubongisrael/trading-intelligence-mcp/llms.txt Retrieves prices for multiple assets in a single request, optimizing performance for bulk data retrieval. It accepts an array of symbols and an optional asset type applicable to all. The response includes an array of price data for each requested symbol. ```typescript // MCP Tool Input { "symbols": ["AAPL", "MSFT", "GOOGL", "BTC", "ETH"], "assetType": "stock" // Optional: applies to all symbols } // Example Response { "prices": [ { "symbol": "AAPL", "price": 178.72, "changePercent": 1.32, ... }, { "symbol": "MSFT", "price": 402.56, "changePercent": 0.89, ... }, { "symbol": "GOOGL", "price": 141.80, "changePercent": 1.05, ... }, { "symbol": "BTC", "price": 42850.00, "changePercent": 2.15, ... }, { "symbol": "ETH", "price": 2520.00, "changePercent": 3.42, ... } ], "timestamp": "2024-01-15T16:00:00.000Z" } // Usage in code import { getMultiplePrices } from './services/prices.js'; const queries = [ { symbol: 'AAPL', assetType: 'stock' }, { symbol: 'BTC', assetType: 'crypto' } ]; const results = await getMultiplePrices(queries); results.forEach((result, symbol) => { console.log(`${symbol}: $${result.data.price} (cached: ${result.cached})`); }); ``` -------------------------------- ### get_price - Fetch Real-Time Asset Prices Source: https://context7.com/ubongisrael/trading-intelligence-mcp/llms.txt Retrieves the current price data for a specified stock or cryptocurrency. The asset type is automatically detected if not provided. Data is cached for 5 minutes. ```APIDOC ## GET /api/price ### Description Fetches real-time price data for a given asset symbol. Supports automatic detection of asset type (stock or cryptocurrency). Data is cached for 5 minutes to ensure freshness and reduce API load. ### Method GET ### Endpoint /api/price ### Parameters #### Query Parameters - **symbol** (string) - Required - The ticker symbol of the asset (e.g., AAPL, BTC). - **assetType** (string) - Optional - The type of asset, either 'stock' or 'crypto'. If omitted, the server will attempt to auto-detect. ### Request Example (No request body for GET requests, parameters are typically sent as query parameters) ### Response #### Success Response (200) - **symbol** (string) - The asset symbol. - **price** (number) - The current price of the asset. - **change** (number) - The price change since the last market close. - **changePercent** (number) - The percentage change since the last market close. - **volume** (number) - The trading volume for the asset. - **marketCap** (number) - The market capitalization of the asset (for stocks). - **timestamp** (string) - The ISO 8601 timestamp of the price data. - **source** (string) - The data source (e.g., 'yahoo-finance', 'coingecko'). - **cached** (boolean) - Indicates if the data was served from cache. #### Response Example ```json { "symbol": "AAPL", "price": 178.72, "change": 2.34, "changePercent": 1.32, "volume": 52847293, "marketCap": 2780000000000, "timestamp": "2024-01-15T16:00:00.000Z", "source": "yahoo-finance", "cached": false } ``` ```