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/readyanswers 503 withdatabase=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.
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.
/portfolioshows 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 (fictitiousDEMO-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
Quotes are served from the in-process cache, not Redis. See docs/ARCHITECTURE.md for the request flows.
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 synchronousbacktestV2tRPC router and the queued backtest, sweep and walk-forward jobs inserver/workers/.
- Look-ahead: with the default
NEXT_BAR_OPENpolicy, rules are evaluated on bar i−1 and filled at bar i's open.server/domain/strategy/truncated-history.test.tschecks 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.tsrepeats that on seeded random paths and also replaces every bar after T with unrelated data.fill-bar-look-ahead.test.tschecks that changing the fill bar's high/low/close/volume does not change anything decided at its open. Indicators are trailing andnullduring warm-up. Corporate actions and point-in-time fundamentals are not applied (B, C), so results use the candles as stored.- Risk gates:
maximumDrawdownPercentflattens at the close and stops trading;maximumDailyLossPercentflattens 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.backtestV2presets use a flat 10 bps per leg (FIXED_BPS,feeBpsdefault 10; no fee when 0). Strategy Lab definitions can selectVOLUME_AWARE, the statutory Indian schedule inshared/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, andstrategyOptimisation.getSweepreturns 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 exampleserver/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). SetSTRATEGY_JOBS_IN_PROCESS=falseto run them in a separatebun run worker:strategy-jobsprocess 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, andLIQUIDITY_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.
-
Three Data Series: Generates
RAW,SPLIT_ADJUSTED, andTOTAL_RETURN_ADJUSTEDprice 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-v3accepts corporate actions, but no caller passes any and no corporate-action data is ingested, so production backtests use stored candles.server/data/sources/yahoo.tsstores Yahoo's quote OHLC arrays (notadjclose); 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 knownavailableFrom(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 populatesuniverse_membershipyet, 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_fromare always null), so point-in-time fundamentals cannot be backed by real availability dates until such a source is added. The/data-qualitypage 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) orSYMBOL_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.
rebalanceScheduleis accepted but not implemented.
-
Three-Phase Windowing: Each window is training (in sample) → validation (out-of-sample holdout) → test (out of sample), with exact calendar-day spans:
trainingWindowDays, thenvalidationWindowDaysfor 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;
assertNoDataLeakagethrows 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;
nullwith 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.getWalkForwardand 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.
- 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_SIZEandHIGH_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.getSweepreturns this analysis, includingselection.pboandselection.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, soHIGH_COST_DRAGcan fire.
- 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.tschecks them against the strategy engine's indicator cache. Bars inside an indicator's warm-up window havenullvalues, not0.
- 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".
- 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.
- Users place
MARKET,LIMITandSTOP_LOSS_LIMITorders.MARKETandLIMITentries can carry stop-loss and take-profit prices, which become a take-profitLIMITand aSTOP_LOSS_MARKETexit (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 unlessPAPER_EXECUTION_ALLOW_DELAYED=true). The starting balance isPAPER_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.tsclaims, 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 stayPENDING, 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.
- 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.
- 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.
- 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.tsuses Newton's method with a bracketed bisection fallback and returnsnullwhen 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.
- 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.
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
-
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_URLis required outside tests) - Optional: Google Cloud BigQuery service account
Clone the repository and install dependencies using Bun:
git clone https://github.com/tanmay-alpha/MAET.git
cd MAET
bun install --frozen-lockfileCopy .env.example to .env in the root directory and configure necessary credentials:
cp .env.example .envKey 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.
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 devThe root bun run dev only loads the standalone orchestrator module; it does not start the API or the website.
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-migrateTests never fall back to a default database either: with NODE_ENV=test the server's database client requires TEST_DATABASE_URL.
Run from a trusted machine, never from CI:
- Check connectivity with
bun run check:db(uses.env). After restoring the database, runbun 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 onpaper_*tables inside a read-only transaction that is always rolled back. It readsSUPABASE_DB_URL/DATABASE_URL(or--url-env=VAR), never.env; exit codes are 0 pass, 1 failure, 2 cannot connect, 3 usage error. - 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_dumpfirst 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.
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:demoIt 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.
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:allEnd-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.
# 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.
# Build frontend bundle
bun run build
# Build backend server bundle
bun run --cwd server buildCI 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.
-
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). -
Corporate Action Split Invariant (research): stock splits (e.g. 2:1) adjust historical series without creating artificial drawdown anomalies (
p2-research-invariants.test.ts). -
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). -
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). -
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). -
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). -
Robustness Overfit Detection: fragile parameter spikes (e.g. high Sharpe with zero neighbour support) are flagged with
OVERFIT_RISK(p2-research-invariants.test.ts). -
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). -
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). -
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 isNOT_FOUND(server/infra/auth/auth.test.ts,server/api/paper/auth-boundary.test.ts,workspace/tenant-isolationandtrade-theses/ownershipPostgres tests,0028/0029-upgrade.integration.test.ts,research-reportsandstrategy-replayPostgres tests). -
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-v2Postgres test,screenerrouter test,nse-company-mastertest). -
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). -
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). -
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.
- Frontend (Vercel): deploys
mainto production through the Git integration (TanStack Start, prebuilt Nitro output in.vercel/output). Every response carriesx-maet-build: <commit>.verify-vercel.ymlwaits untilhttps://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
mainusingrender.yaml. CI boots the built bundle on Node 22 (Bun runs the tests, Node runs production).deploy-render.ymlwaits until/api/readyanswers 200 for the pushed commit, then runsscripts/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/healthis liveness (Render'shealthCheckPath): it always answers HTTP 200, so Render does not restart an instance over an external outage.GET /api/readyreturns 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 reportsstatus: "ok"or"degraded",version(the deployed commit) and per-componentchecks:database(liveselect 1) andredis(livePING), each with a 2 s timeout and cached for 10 s, plusorchestratorandmarketDataas reported by those components. Database connectivity failures surface from tRPC asSERVICE_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 directdb.<ref>.supabase.cohost is unreachable from it.
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.