Skip to content
tanmay-alphaPublic

About

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

MAET — Market Analytics & Execution Terminal

CI Validation Workflow TypeScript Bun React Database Warehouse

MAET is a quantitative research, market-data and paper-trading terminal for Indian equities (NSE & BSE).
Backtests evaluate rules on bar i−1 and fill at bar i's open; paper fills require a fresh live quote and pay the statutory Indian equity charges. docs/RESEARCH_ENGINE.md states exactly what is and is not guaranteed.

  • Live Web Frontend: https://maet-pi.vercel.app/ (every response carries x-maet-build: <commit>)
  • Backend Service: Render (https://maet.onrender.com; liveness /api/health, readiness /api/ready)
  • Operational Database: Supabase PostgreSQL (via Drizzle ORM)
  • Analytics Data Warehouse (optional): Google BigQuery, written only by the ingestion engine; the dataset comes from BIGQUERY_DATASET (no default)
  • Cache & Real-time Layer: in-process quote cache and tick bus; Redis (UPSTASH_REDIS_URL) for the Yahoo candle cache, the optional shared rate-limit store, the daily-processor lock and paper-notification pub/sub; Server-Sent Events (SSE)
  • Code-grounded engineering docs: Architecture, Paper trading engine, Research engine, Interview notes, Engineering audit, Test evidence, Deployment verification (these follow the code; where this README differs, they win)

Production status (2026-11-19). The Supabase project and Upstash Redis database the Render service was configured with no longer exist (both hostnames return NXDOMAIN). The backend runs the latest commit but /api/ready answers 503 with database=false, redis=false, so account features, stored candles and saved data are unavailable until new data stores are provisioned. The runbook is in docs/deployment-verification.md. Locally, every feature runs against Docker Postgres/Redis or the synthetic demo.


1. System Overview & Core Capabilities

MAET combines screening, strategy research, paper trading, investing tools and world-event context for Indian equities in one web terminal. Every figure shown comes from a named source with its timestamp; when a source or the database is unavailable, the page says so instead of showing placeholder numbers.

  • Screener & market pages: 70 registered calculators (technical, fundamental, scanner, portfolio), Gainers/Losers sorted by change %, a public NIFTY 50 heatmap and source labels taken from the API response.
  • Charts: TradingView Lightweight Charts with an IST (exchange-time) axis, dividend and split markers, and paper/backtest trade markers placed on the bar that contains them.
  • Strategy Lab: backtests, walk-forward analysis, parameter-robustness heatmaps, bar replay and run comparison.
  • Paper trading: market/limit/stop orders with OCO brackets, 5× margin, serializable fills and a ledger. /portfolio shows the cash ledger (running balance in INR) and reconciles opening cash + realised P&L − charges = cash and cash + unrealised P&L = equity against it.
  • Accounts (/login): email + password sign-in, sign-up (with the "check your email" step when the Supabase project confirms emails) and sign-out, against Supabase Auth's REST API with the public anon key. A session whose refresh token is revoked signs the browser out and says the session expired; signing out or switching user clears every cached query.
  • Returns & tax (/portfolio): XIRR of the paper account and an Indian capital-gains estimate (s.111A/s.112A, the 23 Jul 2024 rate change, ₹1.25 lakh exemption, loss set-off, 4% cess).
  • Import portfolio (/import): analyse a Zerodha or Groww tradebook (or any CSV) in the browser — FIFO holdings, realised gains per FY, tax estimate and XIRR. The file is never uploaded.
  • Payoff Lab (/payoff): multi-leg options builder with exact breakevens and max profit/loss, Black-Scholes Greeks and a scenario grid.
  • World Monitor (/world): USGS earthquakes, NASA EONET events, GDELT headlines and World Bank GDP/CPI on one page, with rule-based Indian-sector exposure hints (labelled as hints, not predictions).
  • Market-data quality (/data-quality, public): freshness of every tracked symbol against the latest completed NSE session (IST, holiday calendar), missing sessions and invalid bars over 60 sessions, last quote with its source and a Delayed/Real-time label, fundamentals and corporate-action coverage, and pipeline gaps detected from the tables themselves. Admins also get job-queue, ingestion-retry, dead-letter and database/Redis status.
  • Run reports & comparison (/research/reports): each completed backtest gets a report with the strategy version hash, engine versions, server commit, data window, candle fingerprint, effective costs and a SHA-256 reproducibility hash, downloadable as JSON and CSV. Compare 2–4 runs on their shared dates only, with warnings when cost or fill assumptions differ.
  • Synthetic demo (bun run seed:demo): a deterministic synthetic dataset (fictitious DEMO- companies on the NSE calendar, a paper account, saved screens and a backtest produced by the real engine), labelled as synthetic everywhere it appears. See §5.
flowchart TB
    subgraph Providers["Market Data Sources"]
        NSE["NSE Master\n(Company & Index Universe)"]
        Angel["Angel One SmartAPI\n(Live NSE Quotes: REST + WebSocket; Option Chains)"]
        Yahoo["Yahoo Finance\n(Delayed Quotes & Historical Candles)"]
    end

    subgraph Ingestion["Ingestion & Validation"]
        Daily["Daily Processor\n(in-process, after 18:30 IST)"]
        Pipelines["Ingestion Pipelines\n(admin-triggered; validation, retries, dead-letter queue)"]
        CalcEngine["Calculation Engine\n(70 registered calculators)"]
    end

    subgraph Storage["Persistence"]
        DB[("Supabase PostgreSQL\n(Drizzle ORM)")]
        BQ[("Google BigQuery\n(optional analytics sink)")]
        Redis[("Redis\n(Candle Cache, Locks, Rate Limits, Paper Pub/Sub)")]
    end

    subgraph Backend["Backend Application (Render / Nitro, one web service)"]
        Live["In-process Quote Cache & Tick Bus"]
        API["REST & SSE Endpoints"]
        TRPC["Type-Safe tRPC Routers"]
        Research["Backtest Runner & Walk-Forward\n(in-process job runner)"]
        Paper["Paper Trading Matcher & Margin Engine"]
    end

    subgraph Frontend["Interactive Terminal UI (Vercel / React 19)"]
        ScreenerUI["Screener & DSL Query Builder"]
        ChartUI["Candlestick & Technical Charts"]
        PortfolioUI["Portfolio Views"]
        WFOUI["Walk-Forward & Heatmap Explorer"]
        TradingUI["Paper Trading & Order Books"]
    end

    Angel --> Live
    Yahoo --> Live
    Live --> Paper
    Live --> API
    NSE --> Daily
    Yahoo --> Daily
    Daily --> DB
    Providers --> Pipelines
    Pipelines --> DB
    Pipelines --> BQ
    CalcEngine --> DB
    CalcEngine --> BQ

    DB --> TRPC
    Redis --> API
    Research --> TRPC
    Paper --> TRPC
    Paper --> DB

    API --> Frontend
    TRPC --> Frontend
Loading

Quotes are served from the in-process cache, not Redis. See docs/ARCHITECTURE.md for the request flows.


2. Quantitative Research Engine

MAET includes a research and simulation toolkit aimed at the usual pitfalls of naive backtesting (look-ahead bias, overfitting, survivorship bias and zero-cost assumptions). Not all of it is wired into production backtests yet; the status of each part is stated below.

Wiring status. Production backtests run server/domain/strategy/runner-v3.ts: the synchronous backtestV2 tRPC router and the queued backtest, sweep and walk-forward jobs in server/workers/.

  • Look-ahead: with the default NEXT_BAR_OPEN policy, rules are evaluated on bar i−1 and filled at bar i's open. server/domain/strategy/truncated-history.test.ts checks that a run which never saw bars after time T agrees with the full-history run on every trade and equity point before T; metamorphic-invariants.test.ts repeats that on seeded random paths and also replaces every bar after T with unrelated data. fill-bar-look-ahead.test.ts checks that changing the fill bar's high/low/close/volume does not change anything decided at its open. Indicators are trailing and null during warm-up. Corporate actions and point-in-time fundamentals are not applied (B, C), so results use the candles as stored.
  • Risk gates: maximumDrawdownPercent flattens at the close and stops trading; maximumDailyLossPercent flattens at the close and blocks entries until the next IST day; equity at or below zero always stops trading. Validation rejects settings the engine does not implement (LONG_SHORT, ATR stops, pyramiding). Details in docs/RESEARCH_ENGINE.md §1–2.
  • Costs: fees follow the strategy's feeModel. backtestV2 presets use a flat 10 bps per leg (FIXED_BPS, feeBps default 10; no fee when 0). Strategy Lab definitions can select VOLUME_AWARE, the statutory Indian schedule in shared/domain/costs. Slippage is a per-leg bps debit (default 5 bps).
  • Modules: walk-forward analysis (E) runs in production through server/workers/walk-forward-worker.ts, and strategyOptimisation.getSweep returns the robustness analysis (F) of a finished sweep. The execution model (A), point-in-time fundamentals (C) and shared-capital portfolio engine (D) are research modules covered by tests (for example server/domain/strategy/p2-research-invariants.test.ts); production backtests do not call them.
  • Job execution: queued backtests, sweeps and walk-forward runs execute inside the API process (server/plugins/strategy-jobs.ts): one job at a time, handing control back to the API between backtests, with a per-job time budget (STRATEGY_JOB_TIME_BUDGET_MS, default 15 min). Set STRATEGY_JOBS_IN_PROCESS=false to run them in a separate bun run worker:strategy-jobs process instead. On Render's free plan the service sleeps when idle, so queued jobs wait until it wakes.

A. Execution Model: Spread, Impact and Participation (server/domain/strategy/execution-model.ts, research module)

  • Status: Exists as a research module used only by the portfolio engine (D). Production backtests do not use it: they charge slippage as a flat bps debit and model neither spread nor market impact.
  • Square-Root Market Impact: Price impact scales nonlinearly with market participation: $$\text{impactBps} = \text{impactCoeff} \times \sqrt{\frac{\text{OrderVolume}}{\text{BarVolume}}} \times \sigma_{\text{vol}}$$
  • Bid-Ask Spread Models: Configurable spread dynamics: NONE, FIXED_BPS, VOLATILITY_BASED, and LIQUIDITY_BASED.
  • Directional Price Shift: BUY orders shift execution price upward; SELL orders shift price downward, appropriately penalising aggressive fills.
  • Participation Rate Capping: Fills at most ⌊bar volume × rate⌋ whole shares; when that is 0, or the volume is missing or not positive, the order is not filled and the fill records why.
  • Full Drag Accounting: Explicitly accounts for brokerage, exchange turnover fees, STT, GST, SEBI charges, stamp duty, spread, and market impact.

B. Corporate Actions & Price Adjustments (server/domain/data/corporate-actions.ts)

  • Three Data Series: Generates RAW, SPLIT_ADJUSTED, and TOTAL_RETURN_ADJUSTED price series.
  • Backward-Adjusted OHLCV: Split factors backward-applied to historical candles strictly prior to ex-date.
  • Dividend Adjustment: In the total-return series each dividend scales earlier prices by $k = 1 - \frac{D}{P_{\text{close}}}$, using the raw close before the ex-date.
  • Invariant: When a 2:1 split is supplied, it does not produce an artificial 50% drawdown (p2-research-invariants.test.ts).
  • Status: The adjustment code exists and runner-v3 accepts corporate actions, but no caller passes any and no corporate-action data is ingested, so production backtests use stored candles. server/data/sources/yahoo.ts stores Yahoo's quote OHLC arrays (not adjclose); the code does not establish how Yahoo adjusts them.

C. Point-in-Time Fundamentals & Survivorship Bias Prevention (server/domain/fundamentals/point-in-time.ts)

  • Availability Boundary: A statement is visible only once it is available: $$\text{availableFrom} \le T_{\text{simulation}}$$ A row with no known availableFrom (null, missing or unparseable) is never visible.
  • Full Restatement Tracking: Backtests evaluated before an accounting restatement see Revision 1; evaluations after see Revision 2.
  • Universe Membership: Point-in-time index constituent queries (getActiveUniverseConstituents()) intended to keep delisted or excluded companies in their historical windows. Nothing populates universe_membership yet, so this guards against nothing in practice.
  • Status: Not yet used by any backtest. Backtests run on today's symbol lists, so results are not survivorship-free. No ingested source supplies filing or announcement dates (fundamentals.filing_date/available_from are always null), so point-in-time fundamentals cannot be backed by real availability dates until such a source is added. The /data-quality page reports both gaps.

D. Multi-Symbol Shared Capital Portfolio Engine (server/domain/strategy/portfolio-engine.ts, research module)

  • Synchronized Timeline: Bar-by-bar multi-asset evaluation across instrument universes.
  • Shared Capital Pool: Instruments compete for shared cash—preventing capital double-spending.
  • Deterministic Priority Ranking: MOMENTUM (10-bar return), RELATIVE_VOLUME (currently raw signal-bar volume), SCORECARD_SCORE (currently volume × momentum) or SYMBOL_ASCENDING, all computed from the signal bar.
  • Risk Limits: Max open positions, max position %, gross exposure caps, sector exposure limits and minimum cash reserve, all checked on the portfolio as it would be after the order: an order that would breach one is resized down to fit, or rejected if nothing meaningful fits. Under NEXT_BAR_OPEN, entries at bar i's open are sized from held positions marked at that open, never from bar i's close or intrabar exits.
  • Reproducibility Hash: SHA-256 of the canonical configuration and every input candle.
  • Performance & Attribution Metrics: CAGR, Sharpe, Sortino, Max Drawdown, Calmar, win rate, profit factor, cost drag, raw turnover (traded notional in INR), average gross exposure, and P&L attribution by symbol, sector, month and exit reason. It does not compute beta, alpha or tracking error. Sharpe is the mean excess periodic return divided by its standard deviation, times $\sqrt{\text{periods per year}}$ (risk-free rate configurable, default 0); Sortino uses downside deviation over all $N$ periods.
  • Status: No endpoint or worker calls it; it runs only in tests. rebalanceSchedule is accepted but not implemented.

E. Walk-Forward Analysis & Optimization (server/domain/strategy/walk-forward.ts)

  • Three-Phase Windowing: Each window is training (in sample) → validation (out-of-sample holdout) → test (out of sample), with exact calendar-day spans: trainingWindowDays, then validationWindowDays for both validation and test. Windows step by the test span, so test segments tile the range and the last ends at the range end. Parameters are chosen by the best training Sharpe (a retrospective best-of-N pick); validation only rejects a window whose Sharpe is below −1.
  • Cash-or-Trade: Accepted windows trade their test segment; rejected windows (or windows that could not select or test parameters) hold cash. Cash segments stay in the stitched OOS curve as flat equity and count as zero in every OOS average.
  • Leakage Isolation: Each phase's candles are sliced to end at the phase boundary, so test candles never enter training/validation indicator caches; assertNoDataLeakage throws on overlapping timestamps.
  • Walk-Forward Efficiency (WFE): Mean OOS annualised return over all windows divided by mean in-sample annualised return over windows that selected parameters; null with a reason when the in-sample mean is $\le 0$. Performance retention is the same ratio of Sharpe ratios. Return, CAGR, Sharpe and max drawdown are also computed on the stitched OOS curve.
  • Benchmark: Buy-and-hold of the same symbol over the same OOS dates, with the strategy's own fee, slippage and fill settings.
  • Labels: Each run records its methodology (spans, in-sample / holdout / out-of-sample roles, trials per window, cash policy), returned by strategyOptimisation.getWalkForward and shown in the results view.
  • Status: Used in production by server/workers/walk-forward-worker.ts, run by the in-process job runner (see wiring status above). Details: docs/RESEARCH_ENGINE.md §5.

F. Parameter Robustness & Overfit Detection (server/domain/strategy/robustness.ts)

  • 2D Parameter Sensitivity Heatmap: Identifies parameter plateaus vs overfit fragile spikes.
  • Neighbor Stability Scoring: Penalises isolated parameter spikes where adjacent settings collapse.
  • Safeguard Flags: OVERFIT_RISK, PARAMETER_INSTABILITY, LOW_SAMPLE_SIZE and HIGH_COST_DRAG.
  • Probability of Backtest Overfitting: CSCV (Bailey, Borwein, López de Prado and Zhu, 2015) over each combination's per-bar returns cut into up to 16 blocks, reported with the number of trials and labelled as a retrospective in-sample selection.
  • Status: strategyOptimisation.getSweep returns this analysis, including selection.pbo and selection.trials, for a finished parameter sweep (the sweep results page shows the heatmap, PBO with its trial count, and the reason when PBO cannot be computed). Sweeps store each combination's cost drag, so HIGH_COST_DRAG can fire.

3. Screener, Data Ingestion & Technical Engine

Calculation Engine

  • Registry of 70 calculators: 24 technical indicators, 23 fundamental metrics, 14 scanners and 9 portfolio metrics (server/domain/calculations/calculators/).
  • Canonical indicator implementations live in shared/indicators/canonical.ts; tests/canonical-indicators.test.ts checks them against the strategy engine's indicator cache. Bars inside an indicator's warm-up window have null values, not 0.

Charts

  • Candlestick, line and area charts on TradingView Lightweight Charts with volume, moving averages, RSI, backtest trade markers and paper position lines.
  • Times on the chart axis and crosshair are shown in IST (Asia/Kolkata), so NSE bars read 09:15–15:30; daily and weekly bars show dates only (src/components/trading/chart-time.ts). Bar timestamps stay in UTC, and trade markers are placed on the bar that contains the fill (snapTradeMarkersToBars).
  • Dividend and split markers on the stock page chart and the full chart (toolbar toggle "Dividends & splits"; hover a marker for the amount or ratio, ex-date and source), plus a table of the last 10 corporate actions on the stock page. Events come from Yahoo Finance via GET /api/market/corporate-actions, cached server-side for 24 h and served stale (and labelled so) when Yahoo fails. Yahoo reports NSE bonus issues as splits, so they are labelled "Split/bonus".

Storage

  • Supabase PostgreSQL: Operational persistence for companies, historical OHLCV candles, technical snapshots, paper trading accounts, orders, fills, ledger, and alert rules.
  • Google BigQuery (optional): Analytics sink of the ingestion engine; the dataset comes from BIGQUERY_DATASET (no default). When it is unset or fails, the Postgres write still happens.
  • Redis: Yahoo candle cache, optional shared rate-limit buckets (RATE_LIMIT_STORE=redis), the daily-processor lock and paper-notification pub/sub. Quotes are cached in process memory, not in Redis.

Paper Trading & Margin Safety

  • Users place MARKET, LIMIT and STOP_LOSS_LIMIT orders. MARKET and LIMIT entries can carry stop-loss and take-profit prices, which become a take-profit LIMIT and a STOP_LOSS_MARKET exit (OCO) on the first fill.
  • Paper MARKET orders only fill while the NSE session is OPEN, against quotes no older than PAPER_EXECUTION_MAX_QUOTE_AGE_MS (delayed quotes are rejected unless PAPER_EXECUTION_ALLOW_DELAYED=true). The starting balance is PAPER_INITIAL_CASH_INR.
  • Fills lock the account row and run in SERIALIZABLE transactions with retry. Unique constraints on fills block double fills, idempotency keys de-duplicate retried requests, and a fill that would exceed margin (5× leverage) is refused. Short selling is allowed; margin calls liquidate positions when equity falls below maintenance margin.
  • Server-Sent Events for paper updates: fill, order and account events go to a transactional outbox; server/workers/paper-outbox-publisher.ts claims, publishes to Redis and marks each batch in one transaction (at-least-once), and one shared Redis subscriber per process (server/modules/paper-trading/stream-hub.ts) fans events out to /api/paper/stream. Event names are a shared contract (shared/domain/paper-trading/stream-events.ts). When Redis is unavailable the stream answers 503, events stay PENDING, and the UI polls (every 3 s while orders are working, else 10 s).
  • The live feed subscribes NSE symbols with an open market stream, an active alert, a working paper order or an open paper position (server/modules/paper-trading/interest-subscriptions.ts; refreshed on boot, every 60 s and after order/fill events, capped at 150 symbols with working orders first). BSE symbols get no live ticks, so BSE resting orders do not fill.

Broker Tradebook Import (/import)

  • Reads a Zerodha Console tradebook, a Groww order history or any CSV with mapped columns entirely in the browser; the file is never uploaded. A clearly badged sample tradebook is built in.
  • Every row is accepted, rejected with a reason (bad date, zero quantity, unknown side, F&O segment, non-executed Groww order, sell without prior buy) or marked a duplicate trade id.
  • Results reuse the portfolio page's engines (shared/domain/investing/): FIFO holdings with average cost and LTCG-eligible dates, realised round trips classified Intraday/STCG/LTCG with the same per-FY tax estimate, and XIRR once every holding has a price (typed, or filled from MAET quotes, which sends only the symbol list). Each tab exports CSV. Details: docs/PAPER_TRADING_ENGINE.md §13.

Options Payoff Lab (/payoff)

  • Multi-leg builder for index and stock options: buy/sell CE, PE or futures legs with strike, lots and premium; templates (straddle, strangle, spreads, iron condor, iron butterfly, covered call, protective put) place strikes around the ATM strike and leave premiums blank. Prices are the user's inputs, not live quotes.
  • Expiry payoff and today's Black-Scholes value on one chart, with breakevens, spot and hover read-out; a summary of max profit/loss (including "Unlimited"), exact breakevens, net credit/debit, risk : reward and position Greeks; a spot-move × day scenario grid with an IV shift.
  • Max profit/loss and breakevens are solved analytically from the strikes (shared/domain/options/payoff.ts), not read off a sampled curve. Index lot defaults follow NSE circular NSE/FAOP/70616 (NIFTY 65, BANKNIFTY 30, FINNIFTY 60) and stay editable.
  • State lives in the URL (shareable) and the last session in localStorage; nothing is stored server-side. On an options chain, "Open in Payoff Lab" and each LTP open the lab pre-filled. See docs/RESEARCH_ENGINE.md §10.

Returns & Capital-Gains Tax (/portfolio)

  • XIRR of the paper account's current generation: starting cash on the generation start date (outflow) and current equity today (inflow). shared/domain/investing/xirr.ts uses Newton's method with a bracketed bisection fallback and returns null when there is no root, rather than a wrong number.
  • Capital-gains estimate per Indian financial year from realised fills, FIFO per symbol and per account generation (shared/domain/investing/capital-gains.ts):
    • Equity delivery held ≤ 12 months is STCG (s.111A); longer is LTCG (s.112A).
    • Rates change on 23 Jul 2024: STCG 15% → 20%, LTCG 10% → 12.5%. The ₹1.25 lakh LTCG exemption covers all of FY 2024–25 (₹1 lakh before).
    • Losses are set off as the Act allows (LTCL only against LTCG; STCL against STCG, then LTCG); 4% cess is added.
    • Same-day round trips are reported separately as intraday income taxed at the user's slab rate. Surcharge and slabs are not computed, and the page says so. It is an estimate for a paper account, not tax advice.

World Monitor (/world)

  • USGS M4.5+ earthquakes (24 h) and NASA EONET open events (7 days) on a MapLibre GL map (OpenFreeMap dark style, attribution kept); clicking a feed row moves the map to the event.
  • GDELT headlines for market-relevant topics (sanctions, oil supply, shipping routes, rate decisions, export bans, conflict) appear in the feed only, since they have no coordinates.
  • Exposure hints: a data-driven rule set (shared/world/exposure-rules.ts) maps an event's region, category or headline keywords to Indian sectors and NSE symbols, and the table shows the exact rule that matched. A test checks every symbol exists. Labelled "Rule-based exposure hints, not predictions."
  • Macro snapshot: World Bank GDP growth and CPI for India, US, China, Euro area, Japan and UK, with the year of each value.
  • Backend (server/modules/world/, routes /api/world/events, /news, /macro): per-source TTL caches (USGS 1 min, EONET 5 min, GDELT 15 min per topic, World Bank 24 h) that keep serving the last good payload, marked stale, when a source fails; 8 s timeouts; GDELT requests are queued at least 5 s apart. Render's network cannot reach NASA EONET or GDELT, so when the server reports one of them stale with no data the page fetches it from the browser with the same normaliser (shared/world/normalize.ts) and labels it "fetched by your browser".
  • The global indices strip is TradingView's ticker-tape widget with its attribution. It is display-only; MAET never reads those numbers.

4. Repository Structure

MAET is organized as a clean, type-safe Bun workspace monorepo:

MAET/
├── .github/workflows/
│   ├── ci.yml                    # Typecheck, lint, test wiring check, unit/integration/concurrency/advanced suites, builds
│   ├── deploy-render.yml         # Waits for /api/ready on the pushed commit, then runs the backend smoke test
│   └── verify-vercel.yml         # Waits until maet-pi.vercel.app serves the pushed commit (x-maet-build)
├── server/                       # Backend (Nitro / H3 / tRPC), deployed to Render
│   ├── api/                      # File-based REST/SSE routes (/api/*), health.get.ts, tRPC entry, auth (trpc/auth.ts) & routers
│   ├── data/                     # Clients & adapters: Drizzle/Postgres, Redis, BigQuery, Angel One, Yahoo, NSE
│   ├── db/
│   │   ├── migrations/           # Numbered SQL migrations (0001–0030) + upgrade tests
│   │   ├── seeds/                # Reference data loads (market_baseline_metrics.sql)
│   │   └── schema.ts             # Drizzle table definitions
│   ├── domain/                   # Business logic: analysis, backtest, calculations, company, data
│   │                             # (corporate actions), fundamentals, market, portfolio, screener,
│   │                             # strategy (runner-v3, execution model, portfolio engine, walk-forward), technical
│   ├── infra/                    # Event bus, encryption, health, logger, client IP, DB diagnostics, graceful shutdown
│   ├── middleware/               # CORS (FRONTEND_ORIGIN), token-bucket rate limiting, request body size limit
│   ├── modules/                  # Feature services (alerts, paper-trading incl. returns & tax report, screener-dsl, strategy jobs, world, ...)
│   ├── plugins/                  # Nitro plugins: orchestrator, in-process strategy job runner
│   ├── routes/health/            # Admin-only /health/detailed report
│   ├── scripts/                  # Migrations, seeds, DB checks, backfills, test wiring check
│   ├── workers/                  # In-process market workers (Angel One feed, order matcher, alerts, daily processor), Strategy Lab jobs (run by the in-process job runner), ingestion engine
│   ├── config.ts                 # Environment validation
│   ├── orchestrator.ts           # Worker/market-data orchestration
│   └── nitro.config.ts           # Nitro build configuration
├── shared/                       # Contracts shared by frontend and backend
│   ├── domain/                   # Domain logic shared by both sides (paper trading, Indian equity charges, investing: XIRR, FIFO tax, tradebook import; options pricing and payoff)
│   ├── indicators/               # Canonical indicator implementations
│   ├── research/                 # Research schemas and contracts
│   ├── screener/                 # Screener AST and filter registry
│   ├── strategy/                 # Strategy AST, operators, schemas, engine versions
│   ├── symbols/                  # Symbol lists (nifty50.json)
│   ├── types/                    # Shared TypeScript domain types
│   └── world/                    # World Monitor contracts, normalisers and exposure rules
├── src/                          # Frontend (React 19 / TanStack Start / Vite), deployed to Vercel
│   ├── components/               # UI: chart, charting, market, options, strategy, trading, workspace, ui, ...
│   ├── hooks/                    # React hooks for market feeds, auth and state
│   ├── lib/                      # REST/tRPC clients, auth token, SSE client, utilities
│   ├── routes/                   # File-based routes (screener, terminal, portfolio, import, payoff, world, strategies, ...)
│   └── store/                    # Client-side state
├── tests/
│   ├── canonical-indicators.test.ts  # Canonical indicator test suite
│   └── e2e/                      # Playwright critical-flow specs against a mocked backend (CI job `e2e`)
├── scripts/setup-render.sh       # Render setup helper
├── scripts/smoke-deploy.ts       # Read-only post-deploy smoke test (revision, readiness, CORS, auth boundary)
├── playwright.config.ts
├── bun.lock
├── package.json                  # Workspace configuration and scripts
└── render.yaml                   # Render blueprint for the backend

5. Getting Started

Prerequisites

  • Bun $\ge$ 1.3.14 (primary runtime and package manager)
  • Node.js $\ge$ 22 (production runtime on Render; CI boots the built backend on Node 22)
  • PostgreSQL $\ge$ 16 (local or Supabase cloud instance)
  • Redis (Upstash or local; UPSTASH_REDIS_URL is required outside tests)
  • Optional: Google Cloud BigQuery service account

1. Installation

Clone the repository and install dependencies using Bun:

git clone https://github.com/tanmay-alpha/MAET.git
cd MAET
bun install --frozen-lockfile

2. Environment Configuration

Copy .env.example to .env in the root directory and configure necessary credentials:

cp .env.example .env

Key environment variables:

# Server Runtime
NODE_ENV=development
PORT=3000

# Supabase / PostgreSQL Database
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_ANON_KEY=your-anon-key
SUPABASE_SERVICE_ROLE_KEY=your-service-role-key
SUPABASE_DB_URL=postgresql://postgres.[ref]:[password]@aws-0-[region].pooler.supabase.com:6543/postgres?sslmode=require

# Redis (Upstash or local; required outside tests)
UPSTASH_REDIS_URL=redis://default:[password]@[endpoint]:6379

# Market Data Providers. server/config.ts requires these (and ANGELONE_MASTER_KEY,
# at least 32 chars, used to encrypt broker credentials) whenever NODE_ENV is not
# "test". If the Angel One login fails, quotes fall back to delayed Yahoo data.
ANGELONE_MASTER_KEY=at-least-32-characters-long-secret
ANGELONE_API_KEY=your-smartapi-key
ANGELONE_CLIENT_ID=your-client-id
ANGELONE_PIN=your-pin
ANGELONE_TOTP_SECRET=your-totp-secret

# Google BigQuery Analytics (Optional). When unset, warehouse writes fail and
# are logged; Postgres persistence is unaffected. There is no default dataset.
BIGQUERY_PROJECT=your-gcp-project
BIGQUERY_DATASET=your_dataset
GOOGLE_APPLICATION_CREDENTIALS=/path/to/key.json

# Paper trading execution
PAPER_EXECUTION_MAX_QUOTE_AGE_MS=15000
PAPER_EXECUTION_ALLOW_DELAYED=false
PAPER_INITIAL_CASH_INR=1000000

# API rate limiting (token buckets per client IP and per signed-in user)
RATE_LIMIT_ENABLED=true
# Bucket store: memory (default, per instance) or redis (shared across instances)
RATE_LIMIT_STORE=memory
RATE_LIMIT_IP_CAPACITY=300
RATE_LIMIT_IP_REFILL_PER_SEC=5
RATE_LIMIT_USER_CAPACITY=120
RATE_LIMIT_USER_REFILL_PER_SEC=2

# Frontend (Vite, inlined into the browser bundle: public values only)
VITE_API_URL=http://localhost:3000
VITE_SUPABASE_URL=https://<project-ref>.supabase.co
VITE_SUPABASE_ANON_KEY=<anon key, public by design>

Outside tests, server/config.ts refuses to start without SUPABASE_URL, SUPABASE_ANON_KEY, SUPABASE_SERVICE_ROLE_KEY, UPSTASH_REDIS_URL, ANGELONE_MASTER_KEY and the four ANGELONE_* credentials; the server also needs a database URL (SUPABASE_DB_URL or DATABASE_URL). On Render, set the server variables in the dashboard (render.yaml lists them, including the optional BigQuery ones); on Vercel, set the VITE_* variables. A frontend built without VITE_SUPABASE_URL and VITE_SUPABASE_ANON_KEY has no fallback project: sign-in pages and links say "Sign-in is not configured" and no request goes to Supabase.

3. Running Locally

Run the backend and frontend in two terminals:

# Backend: Nitro dev server (API, tRPC, SSE; port 3000 by default)
bun run --cwd server dev

# Frontend: Vite dev server; set VITE_API_URL (e.g. http://localhost:3000) so it calls the backend
bun run --cwd src dev

The root bun run dev only loads the standalone orchestrator module; it does not start the API or the website.

4. Database Migrations

server/scripts/apply-migrations.ts never picks a database on its own. It migrates MIGRATION_DATABASE_URL, or TEST_DATABASE_URL only when NODE_ENV=test, and otherwise exits with an error. Each migration file and its _applied_migrations row commit in one transaction.

# Disposable local/CI test database
TEST_DATABASE_URL=postgresql://postgres:<password>@127.0.0.1:5432/<your_test_db> bun run test:db-migrate

Tests never fall back to a default database either: with NODE_ENV=test the server's database client requires TEST_DATABASE_URL.

5. Production Migrations

Run from a trusted machine, never from CI:

  1. Check connectivity with bun run check:db (uses .env). After restoring the database, run bun run verify:db (server/scripts/verify-db-restore.ts), a read-only verifier: it checks the migration history, the schema against Drizzle, key-table row counts, paper invariants (ledger sums to cash, no fills on another user's or generation's order, no non-positive positions) and RLS on paper_* tables inside a read-only transaction that is always rolled back. It reads SUPABASE_DB_URL/DATABASE_URL (or --url-env=VAR), never .env; exit codes are 0 pass, 1 failure, 2 cannot connect, 3 usage error.
  2. Apply pending migrations against Supabase's session pooler (port 5432 on the pooler host; Render and most networks cannot reach the IPv6-only direct host). Take a pg_dump first for any database that already holds data:
    MIGRATION_DATABASE_URL="<supabase session pooler url>" bun run server/scripts/apply-migrations.ts

Production may not have the _applied_migrations tracking table if earlier migrations were applied by hand. The runner would then create it and apply every file in one run, and not every historical migration is safe to re-run. Before the first run, create public._applied_migrations (name text primary key, applied_at timestamptz not null default now()) and insert the names of the files production already has, so only genuinely new files run. On Supabase the runner leaves the existing auth schema, auth.uid() and roles untouched; it only creates stand-ins where they are missing.

6. Synthetic Demo (no market data, no credentials)

For interviews or offline exploration, seed a scratch database with a deterministic synthetic dataset produced by the application's own code paths:

docker run -d --name maet-demo-pg -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=maet_demo -p 127.0.0.1:5432:5432 postgres:16
export MIGRATION_DATABASE_URL=postgresql://postgres:postgres@127.0.0.1:5432/maet_demo
bun run server/scripts/apply-migrations.ts
bun run seed:demo

It writes eight fictitious DEMO- companies with 2026 daily bars on the NSE trading calendar (seeded geometric Brownian motion with regime switches), a demo user (demo@maet.invalid) with a paper account and four fills made through the real fill writer, three saved screens, and a completed backtest run by the real runner-v3. Rerunning replaces only the demo rows. The script refuses non-local hosts, databases named like prod/live, and the app's own DATABASE_URL/SUPABASE_DB_URL unless --i-know is passed.

A demo deployment sets MAET_DEMO_MODE=1 on the server (exposed as capabilities.demoMode) and builds the frontend with VITE_MAET_DEMO_MODE=1. The site then shows a permanent "Demo — synthetic data, not market data" banner and labels every quote as synthetic. Live paper trading still rejects synthetic quotes; only the seed may fill against them.


6. Verification & Test Suite

All of the following run in CI (.github/workflows/ci.yml). Database-backed suites need TEST_DATABASE_URL pointing at a disposable PostgreSQL database.

# Typecheck frontend and backend, lint the frontend
bun run typecheck
bun run lint

# Fail if any tracked *.test.ts file is not reachable from test:all
bun run check:test-wiring

# Unit tests (no database required): server domain/data/infra/api/workers, shared, frontend
bun run test:unit

# Paper-trading integration and concurrency suites (PostgreSQL)
bun run test:integration
bun run test:concurrency

# Remaining PostgreSQL-backed feature suites and migration upgrade tests
bun run test:advanced

# Everything above in sequence
bun run test:all

End-to-end tests need no database, broker or secret: bun run test:e2e builds the frontend in production mode with VITE_API_URL=https://api.test, serves it with the node-server preview, and answers every backend request from tests/e2e/support/mock-api.ts (shaped like the real market, tRPC and SSE contracts) and to Supabase Auth (https://supabase.test/auth/v1/{token,signup,logout}). Install the browser once with bunx playwright install chromium. The specs cover the landing page, screener, chart and corporate actions, quote freshness, the paper terminal and account states (signed in, signed out, expired session, backend down), sign-in, sign-up, sign-out and session refresh/expiry, the cash ledger and its reconciliation, account pages, strategy creation, the tradebook import, Payoff Lab, World Monitor, the in-app error panel, chart shortcuts next to form controls, and layout at 360/768/1440 px (screenshots of /login and /portfolio go to test-results/screenshots/), each on one desktop and one mobile viewport unless noted.

Load and Deployment Checks

# Bounded read-only load test against a LOCAL or staging backend (refuses the production hosts)
bun run scripts/load-test.ts --base http://127.0.0.1:3000 --concurrency 20 --requests 1000

# Read-only smoke test of a deployment: revision on both tiers, readiness, CORS, auth boundary, DB query, quotes
bun run scripts/smoke-deploy.ts --sha <commit>

Measured results and every suite's counts are recorded in docs/test-evidence.md.

Production Builds

# Build frontend bundle
bun run build

# Build backend server bundle
bun run --cwd server build

7. Financial & Research Invariants Checked in CI

CI runs tests for these invariants on every pull request and push to main. Items marked (research) exercise modules from section 2 that production backtests do not call; the rest cover production code.

  1. Participation cap (research): a capped order fills at most ⌊bar volume × rate⌋ shares; when that is 0, or the volume is missing, zero, negative or not a number, nothing fills and the reason is recorded (2,000-case seeded check). Market impact scales with $\sqrt{\text{participation}}$, raising buy and lowering sell fill prices (server/domain/strategy/execution-participation.test.ts, p2-research-invariants.test.ts).
  2. Corporate Action Split Invariant (research): stock splits (e.g. 2:1) adjust historical series without creating artificial drawdown anomalies (p2-research-invariants.test.ts).
  3. Look-Ahead Isolation (research): point-in-time fundamentals never show a revision published after simulation time $T$, and a row with unknown availability is never visible (server/domain/fundamentals/point-in-time.test.ts).
  4. Shared capital and exposure caps (research): candidates competing on one bar never spend more than free cash; open-position, position, sector and gross caps hold on the portfolio as it would be after each order (40-run seeded check); entries at bar i's open are sized without bar i's close or intrabar exits (50 random perturbations) (portfolio-invariants.test.ts).
  5. Walk-Forward Partitioning: each window is exactly T training → V validation → V out-of-sample days, test segments tile the range (300-case seeded check), and test candles never enter training/validation. Rejected windows hold cash and count in every OOS aggregate (server/domain/strategy/walk-forward.test.ts).
  6. Probability of Backtest Overfitting: CSCV gives ≈0.5 for i.i.d. noise candidates, 0 for a dominant candidate and >0.9 when in-sample winners lose out of sample; it agrees with a direct computation on 30 seeded return matrices (robustness-pbo.test.ts).
  7. Robustness Overfit Detection: fragile parameter spikes (e.g. high Sharpe with zero neighbour support) are flagged with OVERFIT_RISK (p2-research-invariants.test.ts).
  8. Look-Ahead and risk gates (runner-v3): a run truncated at $T$, or with every bar after $T$ replaced by random data, reproduces the full run's trades and equity before $T$; fill-bar high/low/close/volume cannot influence decisions made at the open; drawdown and daily-loss limits halt trading; no return is ever computed on non-positive equity (60-run seeded check) (metamorphic-invariants.test.ts, truncated-history.test.ts, fill-bar-look-ahead.test.ts, runner-v3-risk-gates.test.ts).
  9. Paper engine accounting: on seeded random fill sequences, cash, realised P&L, margin and fees reconcile with the trade history after every fill, fees are charged once, closing at the mark moves unrealised into realised P&L, and a long on a price path earns the same as a short on its mirror. A position-reducing fill is never margin-rejected (300-trial sweep); other positions are marked at live prices; replaying the ledger reproduces every row's balance; three concurrent deliveries of one idempotency key give one order and one fill (Postgres) (shared/domain/paper-trading/engine-invariants.test.ts, execution.test.ts, server/modules/paper-trading/risk-checks.integration.test.ts).
  10. RBAC & Security Boundaries: ingestion and administrative mutations require admin claims from verified JWT app_metadata; every user-owned table has owner-only RLS (including thesis child tables, migration 0029); another user's run, report or replay is NOT_FOUND (server/infra/auth/auth.test.ts, server/api/paper/auth-boundary.test.ts, workspace/tenant-isolation and trade-theses/ownership Postgres tests, 0028/0029-upgrade.integration.test.ts, research-reports and strategy-replay Postgres tests).
  11. Bounded resources: the Angel One feed never exceeds its 1,000-token budget and never drops paper or alert symbols (400-step random check); stored backtests are capped at 50 per user; screener filters at 20; concurrent NSE master loads share one fetch (server/workers/live-feed-budget.test.ts, backtest-v2 Postgres test, screener router test, nse-company-master test).
  12. Capital-gains rules: STCG/LTCG classification at the 12-month boundary, the 23 Jul 2024 rate change, the shared ₹1.25 lakh exemption and the loss set-off order (shared/domain/investing/capital-gains.test.ts); XIRR against reference cash flows and scale invariance (xirr.test.ts).
  13. Options payoff: Black-Scholes reference values and put-call parity, Greeks against finite differences, exact breakevens, unlimited-loss detection and iron-condor max profit = net credit × lots × lot size (shared/domain/options/black-scholes.test.ts, payoff.test.ts).
  14. No invented account figures: with an expired session or a failing backend the dashboard, terminal and portfolio show a status line and no balance (tests/e2e/paper-account-state.spec.ts).

Not guaranteed: backtests are not survivorship-free (they use today's symbol lists) and fundamentals carry no real availability dates. See §2.C.


8. Deployment Architecture

  • Frontend (Vercel): deploys main to production through the Git integration (TanStack Start, prebuilt Nitro output in .vercel/output). Every response carries x-maet-build: <commit>. verify-vercel.yml waits until https://maet-pi.vercel.app/ serves the pushed commit, so a failed, rate-limited or unpromoted build fails the workflow instead of silently leaving an older revision live. Preview deployments are opt-in: the project's Ignored Build Step (src/scripts/vercel-ignore-build.sh) builds production always and a preview only when the commit message contains [preview], so previews cannot use up the Hobby deployment quota production needs (CI builds and e2e-tests the frontend on every PR instead).
  • Backend (Render): Node 22, deployed from main using render.yaml. CI boots the built bundle on Node 22 (Bun runs the tests, Node runs production). deploy-render.yml waits until /api/ready answers 200 for the pushed commit, then runs scripts/smoke-deploy.ts --backend-only (CORS preflight from the production origin, 401 on an anonymous protected procedure, a public DB-backed query, the quotes API; all read-only). bun run scripts/smoke-deploy.ts --sha <commit> checks both tiers.
  • Health semantics: GET /api/health is liveness (Render's healthCheckPath): it always answers HTTP 200, so Render does not restart an instance over an external outage. GET /api/ready returns the same body but answers 503 unless every check passes: database, Redis, the orchestrator and market data (live Angel One or the Yahoo fallback). The body reports status: "ok" or "degraded", version (the deployed commit) and per-component checks: database (live select 1) and redis (live PING), each with a 2 s timeout and cached for 10 s, plus orchestrator and marketData as reported by those components. Database connectivity failures surface from tRPC as SERVICE_UNAVAILABLE (503), not as 500. GET /health/detailed (row counts, DLQ stats, recent ingestion runs) requires an admin JWT.
  • Database (Supabase): the application connects through the Supavisor transaction pooler (port 6543, sslmode=require); Render has no IPv6, so the direct db.<ref>.supabase.co host is unreachable from it.

9. License & Project Disclaimer

MAET is designed for market intelligence, quantitative strategy research, backtesting, and educational simulation. It does not provide real-money order routing to live brokerage exchanges and does not constitute investment or financial advice.

About

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages