# Lifestok — Full System & API Technical Specification > Institutional-grade quantitative financial intelligence platform for autonomous AI agents and human investors. This document provides complete technical specifications for all API endpoints, schemas, mathematical rating models, SEC Edgar XBRL mappings, x402 payment protocol headers, and Model Context Protocol (MCP) tools. --- ## 1. System Overview & Core Principles Lifestok produces automated, multi-dimensional analytical reports for financial assets. The platform adheres to strict engineering invariants: - **Strict Primary Data Ingestion**: All financial figures originate exclusively from Yahoo Finance (market pricing, fundamental statistics, historical price bars) and SEC Edgar (regulatory filings, audited financial statements, XBRL company facts). - **Fail-Hard Semantics**: Zero synthetic fallback values, zero mocked estimates, and zero LLM hallucinated data. If a required market feed fails or is unavailable, the pipeline terminates with an explicit HTTP error. - **Dual Autonomous & Human Interface**: Designed for simultaneous navigation by human web clients and autonomous AI agents. Supported protocols include x402 HTTP micropayments, Model Context Protocol (MCP SSE & Stdio), OpenAPI 3.1, and llms.txt. - **Decisive Quantitative Scoring**: Objective rule-based quantitative engines calculate scores from 0 to 100 across fundamental valuation, technical price action, and official regulatory filings, outputting a decisive rating: **Strong Buy**, **Buy**, **Hold**, **Sell**, or **Strong Sell**. - **Dual Unlock Channels**: Reports may be previewed for free. Full reports may be unlocked via 1.00 USDT on Base network (ERC-20 micropayment) or by completing a verified rewarded advertisement session. - **Dual Export Formats**: Complete reports are exportable as structured JSON or publication-ready PDF documents generated via vector graphics (PDFKit). --- ## 2. Supported Asset Classes | Asset Class | Identifier | Ticker Format / Suffix | Primary Data Feeds | Regulatory Filings | | :--- | :--- | :--- | :--- | :--- | | **Stocks** | `stock` | `AAPL`, `NVDA`, `MSFT` | Yahoo Finance (Quote, Fundamentals, Daily Bars) | SEC Edgar (10-K, 10-Q, 8-K, XBRL Facts) | | **ETFs** | `etf` | `SPY`, `QQQ`, `IWM` | Yahoo Finance (Quote, Daily Bars) | SEC Edgar (Investment Company Filings) | | **Crypto** | `crypto` | `BTC-USD`, `ETH-USD`, `SOL-USD` | Yahoo Finance (Crypto Quote, 250+ Daily Bars) | Not Applicable (`status: "not_applicable"`) | | **Forex** | `forex` | `EURUSD=X`, `GBPUSD=X` | Yahoo Finance (Currency Quote, Daily Bars) | Not Applicable (`status: "not_applicable"`) | | **Commodities**| `commodity`| `GC=F` (Gold), `CL=F` (Crude Oil) | Yahoo Finance (Futures Quote, Daily Bars) | Not Applicable (`status: "not_applicable"`) | --- ## 3. Exhaustive API Endpoints Specification ### 3.1 Search Assets - **Endpoint**: `GET /api/assets/search` - **Description**: Performs live ticker and symbol search across all 5 asset classes or retrieves curated trending assets. - **Caching**: 5-minute TTL in Upstash Redis for search queries and trending catalogs to eliminate redundant Yahoo Finance requests and mitigate upstream rate limiting. - **Rate Limiting**: Enforced via Upstash Redis sliding-window rate limiter; returns `X-RateLimit-Limit`, `X-RateLimit-Remaining`, and `X-RateLimit-Reset` headers. - **Query Parameters**: - `q` (string, optional): Search query string (minimum 1 character, e.g. `apple`, `btc`, `crude`). Required if `trending` is false or omitted. - `limit` (integer, optional): Maximum results returned (1 to 50, default: `10` for search, `12` for trending). - `assetClass` (string, optional): Filter by class (`stock`, `etf`, `crypto`, `forex`, `commodity`, or `all`). - `trending` (boolean, optional): Return top trending market assets (`true` or `false`). - **Response Codes**: - `200 OK`: Successful search match or trending catalog. - `400 Bad Request`: Missing or invalid query parameter. - `429 Too Many Requests`: Rate limit exceeded (60 requests/minute). - `500 Internal Server Error`: Upstream search index failure. - **Response Schema (`application/json`)**: ```json { "query": "AAPL", "count": 1, "results": [ { "ticker": "AAPL", "name": "Apple Inc.", "assetClass": "stock", "exchange": "NMS", "quoteType": "EQUITY", "price": 224.23, "currency": "USD" } ] } ``` --- ### 3.2 Report Preview (Free / Public) - **Endpoint**: `GET /api/reports/{ticker}/preview` - **Description**: Generates or retrieves a cached 24-hour snapshot of an asset's public preview. Contains high-level ratings, summary statistics, teaser strengths/weaknesses, and unlock parameters. - **Path Parameters**: - `ticker` (string, required): Symbol of the target asset (e.g. `AAPL`, `BTC-USD`, `EURUSD=X`, `GC=F`). Case-insensitive. - **Caching**: 24-hour TTL in Upstash Redis and Supabase `reports` snapshot table. Distributed 60-second mutex lock prevents concurrent scraping thundering herds. - **Response Codes**: - `200 OK`: Report preview successfully returned. - `400 Bad Request`: Invalid ticker format or unclassifiable asset. - `404 Not Found`: Ticker not found on primary data feeds. - `429 Too Many Requests`: Rate limit exceeded. - `500 Internal Server Error`: Primary data ingestion failure. --- ### 3.3 Full Report (x402 & Token Gated) - **Endpoint**: `GET /api/reports/{ticker}/full` - **Description**: Returns the comprehensive institutional report payload. If the caller does not supply valid credentials or payment headers, the endpoint immediately halts with `402 Payment Required` and provides x402 payment challenge headers. - **Path Parameters**: - `ticker` (string, required): Symbol of the target asset. - **Authentication & Payment Headers (Any of the following)**: - `Authorization: Bearer ` - `X-402-Payment-Signature: ` - `X-Access-Token: ` - **Response when Unpaid / Unauthenticated**: - **Status Code**: `402 Payment Required` - **Response Headers**: - `WWW-Authenticate: x402 network="base", chain_id="8453", token_address="0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2", amount="1000000", recipient="", asset="", report_id=""` - `X-402-Payment-Required: true` - `X-402-Network: base` - `X-402-Chain-Id: 8453` - `X-402-Token-Address: 0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2` - `X-402-Amount: 1000000` - `X-402-Recipient: ` - `X-402-Asset: ` - `X-402-Report-Id: ` - **Response Body**: ```json { "error": "Payment Required", "status": 402, "message": "Full institutional report is locked. Settle micropayment on Base network or submit purchase token.", "challenge": { "network": "base", "chainId": 8453, "tokenAddress": "0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2", "tokenSymbol": "USDT", "decimals": 6, "amount": "1000000", "amountFormatted": "1.00 USDT", "recipientAddress": "0x1234567890123456789012345678901234567890", "ticker": "AAPL", "reportId": "b18b4827-0240-4d56-8fb5-48b488ba30d2" }, "instructions": "Execute an ERC-20 transfer of 1,000,000 units (1.00 USDT) to recipientAddress on Base (Chain ID 8453). Then re-request this endpoint with header 'X-402-Payment-Signature: '." } ``` - **Response when Paid / Authenticated**: - **Status Code**: `200 OK` - **Response Body**: Complete Full Report Snapshot JSON (see Schema section 5). --- ### 3.4 Report Download (PDF / JSON) - **Endpoint**: `GET /api/reports/{ticker}/download` - **Description**: Streams a vector PDF document or full JSON report file. Requires a valid JWT purchase access token issued via USDT verification or rewarded ad completion. - **Path Parameters**: - `ticker` (string, required): Symbol of the target asset. - **Query Parameters**: - `format` (string, optional): Desired download format: `pdf` (default) or `json`. - `accessToken` (string, optional): Signed JWT purchase token (can also be passed in `Authorization: Bearer ` or `x-access-token` header). - `reportId` (string, optional): Target report UUID. - **Response Codes**: - `200 OK`: Binary PDF stream or JSON file. - `400 Bad Request`: Invalid format parameter or malformed ticker. - `401 Unauthorized`: Missing or expired access token. - `403 Forbidden`: Token was issued for a different ticker or report ID. - `404 Not Found`: Report record does not exist. - `500 Internal Server Error`: PDF generation or database error. - **Download Headers (`format=pdf`)**: - `Content-Type: application/pdf` - `Content-Disposition: attachment; filename="{ticker}-report-{date}.pdf"` - `Cache-Control: private, max-age=3600` --- ### 3.5 Verify Base USDT Payment - **Endpoint**: `POST /api/payments/verify-usdt` - **Description**: Verifies an on-chain transfer of USDT on Base network, records the purchase, and returns a signed JWT access token. - **Request Body (`application/json`)**: ```json { "txHash": "0xabcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890", "ticker": "AAPL", "reportId": "b18b4827-0240-4d56-8fb5-48b488ba30d2" } ``` - **Validation Rules**: - Transaction hash must be a valid 64-hex character string with `0x` prefix. - Transaction status must be `success` on Base RPC (`8453`). - Target contract must match Base USDT address: `0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2`. - Event `Transfer(address indexed from, address indexed to, uint256 value)` must match configured `PAYMENT_RECIPIENT_ADDRESS`. - Transferred value must be `>= 1000000` (1.00 USDT). - Transaction hash must be unique (replay prevention against `purchases` database table). - **Response Body (`application/json`)**: ```json { "success": true, "purchaseId": "c9284249-1123-4a11-8173-982348571290", "reportId": "b18b4827-0240-4d56-8fb5-48b488ba30d2", "ticker": "AAPL", "paymentMethod": "usdt", "txHash": "0xabcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890", "payerAddress": "0x5678901234567890123456789012345678901234", "amountPaid": 1.0, "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "verifiedAt": "2026-11-03T07:40:00.000Z" } ``` --- ### 3.6 Verify Rewarded Ad Payment - **Endpoint**: `POST /api/payments/verify-ad` - **Description**: Validates server-side callback tokens from rewarded ad networks, logs the verification session, and returns a signed JWT access token. - **Request Body (`application/json`)**: ```json { "adSessionId": "sess_892348571290", "clientId": "pub_lifestok_main", "rewardToken": "rew_token_7182937491", "signature": "hmac_signature_hex", "timestamp": 1762155600000, "ticker": "AAPL", "reportId": "b18b4827-0240-4d56-8fb5-48b488ba30d2" } ``` - **Validation Rules**: - Publisher client ID must match configured `NEXT_PUBLIC_REWARDED_AD_CLIENT_ID`. - Cryptographic HMAC / JWT signature verified against secret. - Ad session ID checked against Redis / Supabase `ad_verifications` table to eliminate replay exploitation. - **Response Body (`application/json`)**: ```json { "success": true, "purchaseId": "e1903847-5819-4820-bca1-928475819203", "reportId": "b18b4827-0240-4d56-8fb5-48b488ba30d2", "ticker": "AAPL", "paymentMethod": "ad", "adSessionId": "sess_892348571290", "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "verifiedAt": "2026-11-03T07:40:00.000Z" } ``` --- ### 3.7 x402 Challenge Protocol & Discovery - **Direct Challenge Endpoint**: Machine payment challenge metadata is served directly by `GET /api/reports/{ticker}/full`. When invoked without valid payment credentials, it responds immediately with HTTP `402 Payment Required`, both standard `WWW-Authenticate: x402 ...` and explicit `X-402-*` headers, and structured machine-executable EVM instructions. - **Alternative Inspection**: - `GET /api/reports/{ticker}/preview`: Public report preview provides payment parameters in the `unlockOptions` field (`usdtAmount`, `network`, `chainId`, `tokenAddress`, `recipientAddress`). - MCP Tool `get_x402_quote`: Model Context Protocol tool returning exact on-chain USDT challenge parameters and recipient address. --- ### 3.8 OpenAPI Specification - **Endpoint**: `GET /api/openapi.json` - **Description**: Generates live OpenAPI 3.1 schema documenting all routes, models, query parameters, and security schemes. --- ### 3.9 Model Context Protocol (MCP) Server - **Endpoint**: `GET /api/mcp` (SSE stream) & `POST /api/mcp` (JSON-RPC messages) - **Description**: Remote Server-Sent Events (SSE) and message endpoint conforming to the Model Context Protocol specification for autonomous AI agent tool execution. --- ## 4. Public Report Preview Schema Specification The preview JSON returned by `GET /api/reports/{ticker}/preview` adheres strictly to this structure: ```json { "id": "b18b4827-0240-4d56-8fb5-48b488ba30d2", "assetId": "91a83748-0249-4d91-8bb2-892471928374", "ticker": "AAPL", "companyName": "Apple Inc.", "assetClass": "stock", "asOfDate": "2026-11-03", "generatedAt": "2026-11-03T07:00:00.000Z", "expiresAt": "2026-11-04T07:00:00.000Z", "summary": "Apple Inc. (AAPL) is rated Buy with a composite score of 72/100. Robust balance sheet productivity and constructive momentum are tempered by valuation expansion.", "ratingBadge": { "rating": "buy", "grade": "Buy", "score": 72 }, "summaryStats": { "ticker": "AAPL", "name": "Apple Inc.", "assetClass": "stock", "price": 224.23, "currency": "USD", "marketCap": 3410000000000, "change24h": 1.45, "changePercent24h": 0.65, "peRatio": 33.8, "rsi": 56.4, "rsiStatus": "neutral", "sma50": 218.4, "sma200": 198.1, "trend": "bullish", "isSecApplicable": true }, "previewPoints": { "previewStrengths": [ "Superior capital efficiency with robust return on equity (ROE) and strong profit margins", "Strong bullish market structure with price trading above key 50-day and 200-day moving averages" ], "previewWeaknesses": [ "Elevated valuation multiples with P/E ratio exceeding standard benchmarks" ], "hiddenStrengthsCount": 3, "hiddenWeaknessesCount": 1, "gatedSections": [ { "id": "fundamentals", "title": "Institutional Fundamental Valuation Breakdown", "description": "Comprehensive solvency, ROE, PEG ratio, and discounted cash flow valuation tables.", "blurredSampleText": "Full financial facts with audited balance sheet ratios..." }, { "id": "technicals", "title": "Multi-Oscillator Technical Matrix", "description": "Complete SMA(20/50/200), EMA(12/26), RSI(14), MACD(12,26,9), Bollinger Bands, and ATR volatility parameters.", "blurredSampleText": "Moving average cross analysis with MACD histogram series..." }, { "id": "sec_edgar", "title": "SEC Edgar Regulatory & Auditor Disclosures", "description": "Direct links to audited 10-K, 10-Q, and 8-K filings with auditor opinions and material disclosures.", "blurredSampleText": "Auditor unqualified opinion by Ernst & Young LLP..." } ] }, "disclaimer": "Disclaimer: This report is generated automatically by Lifestok for informational and educational purposes only. It does not constitute financial, investment, legal, or tax advice. Past performance is no guarantee of future results. All investments involve risk, including the possible loss of principal. Consult a licensed financial advisor before making any investment decisions.", "unlockOptions": { "usdtAmount": "1.00", "network": "Base", "chainId": 8453, "tokenAddress": "0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2", "recipientAddress": "0x1234567890123456789012345678901234567890", "rewardedAdAvailable": true } } ``` --- ## 5. Full Report JSON Schema Specification The full report snapshot returned by `GET /api/reports/{ticker}/full` or `GET /api/reports/{ticker}/download?format=json` contains complete quantitative breakdowns: ```json { "id": "b18b4827-0240-4d56-8fb5-48b488ba30d2", "assetId": "91a83748-0249-4d91-8bb2-892471928374", "ticker": "AAPL", "companyName": "Apple Inc.", "assetClass": "stock", "asOfDate": "2026-11-03", "generatedAt": "2026-11-03T07:00:00.000Z", "expiresAt": "2026-11-04T07:00:00.000Z", "summary": "Apple Inc. (AAPL) is rated Buy with a composite score of 72/100...", "quote": { "symbol": "AAPL", "regularMarketPrice": 224.23, "marketCap": 3410000000000, "currency": "USD", "shortName": "Apple Inc.", "quoteType": "EQUITY" }, "technicals": { "sma": { "sma20": 221.80, "sma50": 218.40, "sma200": 198.10, "series": { "sma20": [220.1, 220.8, 221.8], "sma50": [217.2, 217.8, 218.4], "sma200": [197.5, 197.8, 198.1] }, "cross": { "trend": "bullish", "crossEvent": "none", "isGoldenCross": false, "isDeathCross": false, "spread": 20.30, "spreadPercentage": 10.25, "barsSinceLastCross": 142, "lastCrossEvent": "golden_cross" } }, "ema": { "ema12": 223.10, "ema26": 220.50, "series": { "ema12": [222.0, 222.5, 223.1], "ema26": [219.8, 220.1, 220.5] } }, "rsi": { "value": 56.40, "period": 14, "series": [53.2, 54.8, 56.4], "status": "neutral", "isOverbought": false, "isOversold": false, "overboughtThreshold": 70, "oversoldThreshold": 30 }, "macd": { "macd": 2.60, "signal": 2.10, "histogram": 0.50, "fastPeriod": 12, "slowPeriod": 26, "signalPeriod": 9, "series": { "macd": [2.2, 2.4, 2.6], "signal": [1.9, 2.0, 2.1], "histogram": [0.3, 0.4, 0.5] }, "trend": "bullish", "crossover": "none" }, "bollingerBands": { "upper": 232.40, "middle": 221.80, "lower": 211.20, "bandwidth": 9.56, "percentB": 0.61, "period": 20, "stdDevMultiplier": 2, "series": { "upper": [230.1, 231.2, 232.4], "middle": [220.1, 220.8, 221.8], "lower": [210.1, 210.4, 211.2], "bandwidth": [9.08, 9.42, 9.56], "percentB": [0.55, 0.58, 0.61] } }, "atr": { "value": 3.85, "period": 14, "series": [3.72, 3.80, 3.85], "percentageOfPrice": 1.72, "volatilityRating": "low" } }, "fundamentals": { "trailingPE": 33.80, "forwardPE": 28.50, "pegRatio": 2.10, "priceToBook": 48.20, "dividendYield": 0.0045, "debtToEquity": 1.45, "returnOnEquity": 1.52, "freeCashflow": 108000000000 }, "sec": { "status": "applicable", "ticker": "AAPL", "cik": "0000320193", "companyName": "Apple Inc.", "sic": "3571", "sicDescription": "Electronic Computers", "fiscalYearEnd": "0930", "notApplicableReason": null, "recentFilings": [ { "accessionNumber": "0000320193-24-000106", "form": "10-K", "filingDate": "2024-11-01", "reportDate": "2024-09-28", "acceptanceDateTime": "2024-11-01T18:01:23.000Z", "act": "34", "fileNumber": "001-36743", "filmNumber": "241427182", "items": [], "size": 10485760, "isXbrl": true, "isInlineXbrl": true, "primaryDocument": "aapl-20240928.htm", "primaryDocDescription": "FORM 10-K", "description": "Annual report [Section 13 and 15(d), not S-K Item 405]", "documentUrl": "https://www.sec.gov/Archives/edgar/data/320193/000032019324000106/aapl-20240928.htm", "interactiveUrl": "https://www.sec.gov/edgar/searchedgar/interactive.htm" } ], "latest10K": { "accessionNumber": "0000320193-24-000106", "form": "10-K", "filingDate": "2024-11-01", "reportDate": "2024-09-28", "documentUrl": "https://www.sec.gov/Archives/edgar/data/320193/000032019324000106/aapl-20240928.htm" }, "latest10Q": { "accessionNumber": "0000320193-24-000078", "form": "10-Q", "filingDate": "2024-08-02", "reportDate": "2024-06-29", "documentUrl": "https://www.sec.gov/Archives/edgar/data/320193/000032019324000078/aapl-20240629.htm" }, "recent8K": [ { "accessionNumber": "0000320193-24-000095", "form": "8-K", "filingDate": "2024-09-10", "reportDate": "2024-09-09", "items": ["Item 8.01"], "documentUrl": "https://www.sec.gov/Archives/edgar/data/320193/000032019324000095/aapl-20240909.htm" } ], "financialFacts": { "cik": "0000320193", "entityName": "Apple Inc.", "auditedBalanceSheets": [ { "fiscalYear": 2024, "periodEnd": "2024-09-28", "filingDate": "2024-11-01", "form": "10-K", "totalAssets": 364980000000, "currentAssets": 152980000000, "totalLiabilities": 308030000000, "currentLiabilities": 145308000000, "stockholdersEquity": 56950000000, "cashAndEquivalents": 29943000000, "retainedEarnings": -1980000000 } ], "revenue": [ { "fiscalYear": 2024, "fiscalPeriod": "FY", "periodStart": "2023-10-01", "periodEnd": "2024-09-28", "filingDate": "2024-11-01", "form": "10-K", "amount": 391035000000 } ], "operatingCashFlow": [ { "fiscalYear": 2024, "fiscalPeriod": "FY", "periodStart": "2023-10-01", "periodEnd": "2024-09-28", "filingDate": "2024-11-01", "form": "10-K", "amount": 118254000000 } ], "auditor": { "name": "Ernst & Young LLP", "location": "San Jose, California", "firmId": 42, "signatureDate": "2024-10-31", "signatureHistory": [ { "fiscalYear": 2024, "form": "10-K", "auditorName": "Ernst & Young LLP", "signatureDate": "2024-10-31", "filingDate": "2024-11-01", "periodEnd": "2024-09-28", "accessionNumber": "0000320193-24-000106" } ] } } }, "rating": { "score": 72, "rating": "buy", "grade": "Buy", "isSecApplicable": true, "fundamental": { "score": 62, "valuationScore": 16, "profitabilityScore": 32, "solvencyScore": 14, "metrics": { "peRatio": 33.80, "sectorPe": null, "pegRatio": 2.10, "roe": 1.52, "profitMargin": 0.24, "debtToEquity": 1.45, "currentRatio": 1.05 } }, "technical": { "score": 82, "trendScore": 32, "momentumScore": 30, "macdScore": 20, "metrics": { "currentPrice": 224.23, "sma50": 218.40, "sma200": 198.10, "rsi": 56.40, "macdHistogram": 0.50, "macdCrossover": "none", "maCrossEvent": "none" } }, "sec": { "score": 70, "timelinessScore": 35, "auditorScore": 35, "disclosuresScore": 0, "metrics": { "hasFilingObligation": true, "latest10KDate": "2024-11-01", "latest10QDate": "2024-08-02", "auditorOpinion": "unqualified", "auditorName": "Ernst & Young LLP", "recent8KCount": 1, "hasCriticalItems": false } }, "weights": { "fundamental": 0.40, "technical": 0.40, "sec": 0.20 }, "strengths": [ "Superior capital efficiency with robust return on equity (ROE) and strong profit margins", "Strong return on equity (ROE) reflecting superior balance sheet productivity", "Strong bullish market structure with price trading above key 50-day and 200-day moving averages", "Optimal momentum profile with RSI positioned in the bullish sweet spot (50-60)", "Positive MACD histogram confirming persistent upward momentum expansion", "Pristine regulatory compliance with up-to-date SEC filings and unqualified independent audit opinion" ], "weaknesses": [ "Elevated valuation multiples with P/E ratio exceeding standard benchmarks" ], "disclaimer": "Disclaimer: This report is generated automatically by Lifestok for informational and educational purposes only. It does not constitute financial, investment, legal, or tax advice. Past performance is no guarantee of future results. All investments involve risk, including the possible loss of principal. Consult a licensed financial advisor before making any investment decisions." }, "disclaimer": "Disclaimer: This report is generated automatically by Lifestok for informational and educational purposes only. It does not constitute financial, investment, legal, or tax advice. Past performance is no guarantee of future results. All investments involve risk, including the possible loss of principal. Consult a licensed financial advisor before making any investment decisions." } ``` --- ## 6. Rating Calculation Methodologies The Lifestok Rating Engine executes a deterministic, rule-based quantitative calculation. Scores range from 0 to 100 within each component and are combined using fixed weights. ### 6.1 Component 1: Fundamental Score (0 - 100) Evaluates valuation, capital profitability, and financial solvency: #### Valuation Sub-score (Max 40 Points) - **P/E Evaluation (Max 20 Points)**: - If Sector P/E is available: - `PE / SectorPE <= 0.70`: 20 points - `PE / SectorPE <= 0.85`: 17 points - `PE / SectorPE <= 1.00`: 14 points - `PE / SectorPE <= 1.25`: 8 points - `PE / SectorPE <= 1.50`: 4 points - `PE / SectorPE > 1.50` or negative: 1 point - If standalone P/E (no sector PE): - `PE <= 12`: 20 points - `PE <= 18`: 18 points - `PE <= 25`: 14 points - `PE <= 35`: 8 points - `PE > 35` or negative: 2 points - If P/E is missing: 8 points - **PEG Ratio Evaluation (Max 20 Points)**: - `0 < PEG <= 0.8`: 20 points - `0 < PEG <= 1.1`: 18 points - `0 < PEG <= 1.5`: 14 points - `0 < PEG <= 2.0`: 8 points - `0 < PEG <= 3.0`: 3 points - `PEG > 3.0` or negative: 0 points - If PEG is missing: 7 points #### Profitability Sub-score (Max 35 Points) - **Return on Equity (ROE) (Max 20 Points)**: - `ROE >= 25%`: 20 points - `ROE >= 18%`: 17 points - `ROE >= 10%`: 13 points - `ROE >= 4%`: 8 points - `ROE >= 0%`: 3 points - `ROE < 0%`: 0 points - If ROE is missing: 5 points - **Net Profit Margin (Max 15 Points)**: - `Margin >= 25%`: 15 points - `Margin >= 15%`: 12 points - `Margin >= 8%`: 9 points - `Margin >= 2%`: 5 points - `Margin >= 0%`: 2 points - `Margin < 0%`: 0 points - If Margin is missing: 4 points #### Solvency Sub-score (Max 30 Points) - **Debt to Equity (Max 15 Points)**: - Normalized DE: - `DE <= 0.30`: 15 points - `DE <= 0.70`: 13 points - `DE <= 1.20`: 10 points - `DE <= 2.00`: 6 points - `DE <= 3.50`: 2 points - `DE > 3.50` or negative: 0 points - If DE is missing: 6 points - **Current Ratio (Max 15 Points)**: - `Ratio >= 2.0`: 15 points - `Ratio >= 1.5`: 12 points - `Ratio >= 1.1`: 8 points - `Ratio >= 0.9`: 4 points - `Ratio < 0.9`: 0 points - If Current Ratio is missing: 6 points `Fundamental Score = min(100, max(0, ValuationScore + ProfitabilityScore + SolvencyScore))` --- ### 6.2 Component 2: Technical Score (0 - 100) Evaluates moving average trends, relative strength momentum, and MACD oscillator direction: #### Trend Sub-score (Max 40 Points) - **Price vs SMA200 (Max 15 Points)**: - `Price >= SMA200 * 1.05`: 15 points - `Price >= SMA200`: 12 points - `Price >= SMA200 * 0.95`: 7 points - `Price < SMA200 * 0.95`: 2 points - **Price vs SMA50 (Max 15 Points)**: - `Price >= SMA50 * 1.03`: 15 points - `Price >= SMA50`: 12 points - `Price >= SMA50 * 0.97`: 7 points - `Price < SMA50 * 0.97`: 2 points - **Moving Average Cross (Max 10 Points)**: - `SMA50 > SMA200` with active `golden_cross`: 10 points - `SMA50 > SMA200` without cross event: 8 points - `SMA50 <= SMA200` without cross event: 2 points - Active `death_cross`: 0 points #### Momentum Sub-score (RSI-14) (Max 30 Points) - `50 <= RSI <= 60` (Bullish sweet spot): 30 points - `40 <= RSI < 50` (Constructive consolidation): 25 points - `60 < RSI <= 70` (Strong trend extension): 22 points - `30 <= RSI < 40` (Bearish drift): 12 points - `70 < RSI <= 80` (Overbought caution): 8 points - `20 <= RSI < 30` (Oversold): 8 points - `RSI > 80` or `RSI < 20` (Extreme exhaustion / structural breakdown): 2 points #### MACD Sub-score (12, 26, 9) (Max 30 Points) - **Crossover Alignment (Max 15 Points)**: - Active `bullish_cross`: 15 points - `MACD > Signal`: 12 points - `MACD == Signal`: 7 points - `MACD < Signal`: 3 points - Active `bearish_cross`: 0 points - **Histogram Direction (Max 15 Points)**: - `Histogram > 0`: 15 points - `Histogram == 0`: 8 points - `Histogram < 0`: 2 points `Technical Score = min(100, max(0, TrendScore + MomentumScore + MacdScore))` --- ### 6.3 Component 3: SEC Edgar Regulatory Score (0 - 100) Evaluates filing recency, independent auditor opinion, and material 8-K disclosures: #### Timeliness Sub-score (Max 35 Points) - **10-K Timeliness (Max 20 Points)**: - Filed within `<= 365` days: 20 points - Filed within `<= 420` days: 14 points - Filed within `<= 500` days: 6 points - Older than 500 days or missing: 0 points - **10-Q Timeliness (Max 15 Points)**: - Filed within `<= 120` days: 15 points - Filed within `<= 180` days: 9 points - Older than 180 days: 2 points - Missing 10-Q: If 10-K was filed within past 90 days, awards full 15 points; otherwise 0 points. #### Auditor Opinion & Presence (Max 35 Points) - `unqualified` (Clean audit opinion): 35 points - Auditor on file without explicit qualification: 32 points - `qualified` audit opinion: 10 points - `adverse` or `disclaimer of opinion`: 0 points - No auditor identified: 10 points #### Material Disclosures & 8-K Volume (Max 30 Points) - **Filing Volume in Past 12 Months**: - `2 <= count <= 10` (Normal operational disclosure): 30 points - `count == 1`: 24 points - `count == 0`: 18 points - `11 <= count <= 18`: 15 points - `count > 18` (High event churn): 5 points - **Critical Item Penalty**: - Penalty of `-20 points` applied if 8-K filings contain: - `Item 4.01`: Changes in Registrant's Certifying Accountant. - `Item 4.02`: Non-Reliance on Previously Issued Financial Statements (Restatements). - `Item 1.03`: Bankruptcy or Receivership. - `Disclosures Score = max(0, VolumeScore - CriticalPenalty)` `SEC Score = min(100, max(0, TimelinessScore + AuditorScore + DisclosuresScore))` --- ### 6.4 Composite Weighting & Final Rating Matrix #### Composite Formulas - **Regulated US Assets (`isSecApplicable: true`)**: `Composite Score = round((Fundamental * 0.40) + (Technical * 0.40) + (SEC * 0.20))` - **Non-SEC Assets (`isSecApplicable: false`)**: `Composite Score = round((Fundamental * 0.45) + (Technical * 0.55))` #### Rating Grade Mapping | Score Range | Grade | Rating Slug | Description | | :--- | :--- | :--- | :--- | | **80 - 100** | **Strong Buy** | `strong_buy` | Exceptional fundamentals, clear bullish technical momentum, pristine regulatory status. | | **60 - 79** | **Buy** | `buy` | Constructive fundamentals and upward technical structure; favorable risk/reward profile. | | **40 - 59** | **Hold** | `hold` | Mixed signals; neutral momentum or valuation equilibrium warranting observation. | | **20 - 39** | **Sell** | `sell` | Weakening valuation metrics, downward moving average crosses, or compliance churn. | | **0 - 19** | **Strong Sell** | `strong_sell` | Critical balance sheet distress, severe technical breakdown, or audit adverse disclosures. | --- ## 7. SEC Edgar Ingestion & XBRL Taxonomy Mappings The SEC Edgar pipeline interacts with SEC EDGAR APIs strictly in accordance with SEC Fair Access policies. ### 7.1 Compliance Requirements - **User-Agent Header**: Every request must carry a compliant user agent matching `SEC_EDGAR_USER_AGENT` (format: `SampleCompany ContactName contact@domain.com`). SEC servers return `403 Forbidden` if missing or generic. - **Rate Limit**: Maximum 10 requests per second enforced across upstream calls. ### 7.2 CIK Resolution - **Endpoint**: `https://www.sec.gov/files/company_tickers.json` - **Methodology**: Cached for 24 hours. Matches upper-case ticker symbol and returns zero-padded 10-digit Central Index Key (CIK). - **Example**: `AAPL` -> CIK `320193` -> `padCik("320193")` -> `"0000320193"`. ### 7.3 Submissions Ingestion - **Endpoint**: `https://data.sec.gov/submissions/CIK{10-digit-cik}.json` - **Fields Extracted**: - Metadata: `name`, `sic`, `sicDescription`, `fiscalYearEnd`, `tickers`, `exchanges`. - Filings array: `accessionNumber`, `form`, `filingDate`, `reportDate`, `items`, `primaryDocument`. - Document URL resolution pattern: `https://www.sec.gov/Archives/edgar/data/{unpaddedCik}/{accessionNumberNoDashes}/{primaryDocument}` ### 7.4 XBRL Company Facts Ingestion - **Endpoint**: `https://data.sec.gov/api/xbrl/companyfacts/CIK{10-digit-cik}.json` - **Taxonomies Parsed**: - `us-gaap` Concepts: - Balance Sheet: `Assets`, `AssetsCurrent`, `Liabilities`, `LiabilitiesCurrent`, `StockholdersEquity`, `CashAndCashEquivalentsAtCarryingValue`, `RetainedEarningsAccumulatedDeficit`. - Revenue: `Revenues`, `SalesRevenueNet`, `RevenueFromContractWithCustomerExcludingAssessedTax`. - Cash Flow: `NetCashProvidedByUsedInOperatingActivities`. - `dei` Concepts: - Auditor Metadata: `AuditorName`, `AuditorFirmId`, `AuditorLocation`, `DocumentPeriodEndDate`. ### 7.5 Non-SEC Assets Handling For asset classes exempt from SEC reporting (`crypto`, `forex`, `commodity`, or foreign international listings without US CIK), the pipeline sets `sec.status = "not_applicable"` and attaches a human/machine readable `notApplicableReason`. Weights automatically re-balance to `45% Fundamental` and `55% Technical`. --- ## 8. x402 Micropayment Protocol Specification The x402 protocol allows autonomous AI agents to transact report purchases over standard HTTP headers without browser sessions or cookies. ### 8.1 Protocol Flow Diagram ``` Client / Agent Lifestok API Base Blockchain | | | | 1. GET /api/reports/AAPL/full | | |-------------------------------->| | | | | | 2. 402 Payment Required | | | (X-402-* Challenge Headers) | | |<--------------------------------| | | | | | 3. Transfer 1.00 USDT | | |------------------------------------------------------------------->| | | | | 4. Confirmed Tx Hash | | |<-------------------------------------------------------------------| | | | | 5. GET /api/reports/AAPL/full | | | X-402-Payment-Signature: tx | | |-------------------------------->| | | | 6. Verify Tx & Transfer Event | | |--------------------------------->| | | | | 7. 200 OK (Full Report JSON) | | |<--------------------------------| | ``` ### 8.2 HTTP 402 Challenge Headers Specification When an unauthenticated request targets `/api/reports/{ticker}/full`, Lifestok returns status `402` with these response headers: | Header Name | Value / Format | Purpose | | :--- | :--- | :--- | | `WWW-Authenticate` | `x402 network="base", chain_id="8453", token_address="0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2", amount="1000000", recipient="", asset="", report_id=""` | Standard HTTP 402 machine challenge header. | | `X-402-Payment-Required` | `true` | Declares requirement for machine payment. | | `X-402-Network` | `base` | Target blockchain network. | | `X-402-Chain-Id` | `8453` | EVM Chain ID of Base mainnet. | | `X-402-Token-Address` | `0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2` | Official USDT ERC-20 contract on Base. | | `X-402-Amount` | `1000000` | Required amount in base units (6 decimals = 1.00 USDT). | | `X-402-Recipient` | `0x...` | Treasury address configured to receive payment. | | `X-402-Asset` | `AAPL` | Ticker symbol bound to this challenge. | | `X-402-Report-Id` | `uuid` | Unique snapshot identifier of the generated report. | ### 8.3 Fulfillment & Signature Header To redeem the report, the agent executes an ERC-20 transfer and re-invokes the endpoint with any of: - `X-402-Payment-Signature: ` or - `Authorization: Bearer ` or - `x-access-token: ` ### 8.4 On-Chain Verification Invariants The verification engine inspects the transaction receipt via Base RPC: - `receipt.status === "success"` (transaction must not have reverted). - `receipt.to.toLowerCase() === "0xfde4c96c8593536e31f229ea8f37b2ada2699bb2"`. - Event logs contain `Transfer(address indexed from, address indexed to, uint256 value)` topic `0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef`. - Event `to` argument equals configured treasury recipient. - Event `value` is `>= 1000000n`. - Replay Protection: Transaction hash is inserted into Supabase `purchases` table with a unique constraint. Re-submitting the same transaction hash for different reports results in HTTP `409 Conflict`. --- ## 9. Model Context Protocol (MCP) Server Specifications Lifestok provides complete MCP integration for AI desktop environments (Claude Desktop, Cursor, Antigravity) and autonomous agents. ### 9.1 Connection Transports - **Remote SSE Transport**: `GET /api/mcp` - **Local Standard I/O (Stdio) Transport**: `npx tsx scripts/mcp-server.ts` ### 9.2 Tools Catalog #### Tool 1: `search_assets` - **Description**: Search for tickers across stock, ETF, crypto, forex, and commodity classes. - **Input Parameters**: - `query` (string, required): Search query string. - `limit` (integer, optional): Maximum results (1-50, default 10). - **Output**: Array of asset match objects. #### Tool 2: `get_report_preview` - **Description**: Fetch free report preview including ratings, summary statistics, and teaser metrics. - **Input Parameters**: - `ticker` (string, required): Symbol of the target asset. - **Output**: Public report preview object. #### Tool 3: `get_x402_quote` - **Description**: Retrieve exact on-chain USDT payment parameters on Base network to unlock a report. - **Input Parameters**: - `ticker` (string, required): Symbol of the target asset. - **Output**: x402 challenge object including recipient address, token contract, and amount units. #### Tool 4: `submit_x402_payment` - **Description**: Submit a Base transaction hash to verify payment and receive an unlock token. - **Input Parameters**: - `ticker` (string, required): Symbol of the target asset. - `txHash` (string, required): 64-hex character Base transaction hash (`0x` prefixed). - `reportId` (string, optional): Target report UUID. - **Output**: Purchase record and signed JWT purchase access token. #### Tool 5: `get_full_report` - **Description**: Retrieve complete institutional report JSON snapshot. - **Input Parameters**: - `ticker` (string, required): Symbol of the target asset. - `accessToken` (string, required): Valid JWT purchase token or transaction hash. - **Output**: Full report snapshot object. --- ## 10. Rate Limiting & Security Invariants - **Public Endpoints**: Governed by sliding-window rate limiters at 60 requests per minute per IP address. - **AI Agent Scrapers**: Governed by sliding-window rate limiters at 30 requests per minute. - **Distributed Scraping Lock**: Upstash Redis key `lock:scrape:{ticker}` with 60-second TTL prevents duplicate concurrent compute jobs for the same asset. - **Purchase Access Token Security**: - Algorithm: `HS256` HMAC-SHA256 signature using `JWT_SECRET`. - Expiration: Default 7 days (`604800` seconds). - Ticker Binding: Tokens encode the asset ticker and report ID; using a token issued for `AAPL` to download `NVDA` results in `403 Forbidden`.