Engineering Handbook · v2026.07

AlphaSwarm

An AI quant team in a browser tab. Describe a strategy in plain English — the AI writes the code, backtests it against realistic market reality, and trades it through your own broker. We never touch your money. This is the document that explains how all of it actually works.

MVP live FastAPI · asyncpg Next.js 14 Celery · Redis PostgreSQL 16 Agent Framework · BYOK
01

The mental model

A user describes a trading strategy in plain English — “buy RELIANCE when RSI drops below 30” — and the AI writes validated Python for it, backtests that Python against realistic conditions, and, once the user connects their own brokerage, trades it on their behalf.

Around that core sit three products for three audiences: a wealth copilot for retail investors, a Bloomberg-style terminal for active traders, and a GitHub-style commons where quants fork, copy, and honestly-score each other's strategies.

Bloomberg Terminal meets GitHub — on your own broker and your own AI key.

The one non-negotiable rule underneath all of it: the platform is software that sends orders — not a broker, not a fund. That single fact is the trust model and the business model at once.

02

Why “no custody” is the entire strategy

Everyone assumes the hard part of a trading platform is the trading. It isn't — it's regulation. The moment you hold customer funds or pool money into a fund, you need money-transmitter and broker-dealer licenses, custody insurance, audits, and capital reserves. That's a multi-year, multi-million-dollar moat pointed at the founder. AlphaSwarm sidesteps all of it with two principles:

Bring Your Own Broker

BYOB

The user connects their existing regulated brokerage. Our servers send buy/sell instructions through the broker's API. Cash and securities never leave the user's account — so we're a software vendor, not a financial institution.

Bring Your Own Key

BYOK

The AI runs on the user's own free LLM key (Groq, Gemini, OpenRouter, local Ollama). No shipped paid key, no token billing — which kills the single largest variable cost of an AI product and lets the AI features be free forever.

How to teach it: the genius isn't the AI — it's the org chart. By refusing to hold the money and the AI key, AlphaSwarm hands the two most expensive, most regulated parts of a fintech back to the user and keeps only the part that's pure software.

TierWhat it unlocksPrice
Free / BYOKAI builder & advisor, paper trading, full backtester, terminal, goal wizard, the Swarm₹0
Quant TierLive agent deployment + live broker executionStripe · Razorpay
Swarm Tax1% / month on copied capital, split 50/50 platform ↔ creatorUsage
03

Architecture in four planes

Each plane has a single responsibility. The key decision: the API control plane is stateless and fast — it never runs a trading loop, so a slow strategy can't block a dashboard request. All long-running, risky work lives in isolated workers.

01 · Presentation — Next.js 14 / Vercel
Dashboard · Terminal · Strategies · Leaderboard · Advisor · Portfolio · Feed · Login
▼   REST + WebSocket · JWT Bearer   ▼
02 · Control Plane — FastAPI + asyncpg
The front desk: validates, authorizes, reads/writes Postgres, enqueues work. Holds no trading loop itself.
▼   Celery over Redis  ·  direct async calls   ▼
03a · Execution Plane
Celery workers. Strategy loop · the risk gate · order execution · SIP · Swarm Tax · out-of-sample recompute.
03b · Intelligence Services
market data · indicators · backtest · forecaster · strategy builder · AI advisor · OAuth.
04 · Data Plane
PostgreSQL 16 — the source of truth  ·  Redis 7 — Celery broker + pub/sub bus.
04

How it flows

Reading data-flow beats reading feature lists. Two flows define the product.

A · Plain English → a live strategy

User types a strategy in plain English; the frontend POSTs it with a JWT.

The control plane authenticates and calls the strategy builder — an Agent Framework ReAct agent.

The agent writes candidate Python, runs it in the sandbox, reads the real errors, and fixes itself in a loop until it's a valid strategy.

The user backtests it. The same risk gate that governs live trading runs on every simulated order.

Connect a broker, click Deploy (Quant Tier gate). A worker runs the loop: indicators → intent → risk gate → real broker call.

B · A creator's signal → 400 followers' brokers

A creator publishes a strategy — publishing pins an immutable version and requires ≥ 3 backtests first.

Followers subscribe, each allocating their own capital. No money moves to AlphaSwarm — the allocation is just a sizing number.

On a signal, the engine fans out: per-subscriber advisory lock → size to their capital → their risk gate → their broker.

400 followers = 400 independent orders in 400 independent accounts. Funds are never pooled.

It copies the decision, not the money — that's why it needs no fund license.
05

The subsystems

Six pieces do the heavy lifting. Each below: the problem, the mechanism, and the concept you'd teach from it.

The risk gate

domain/risk.py

A trading bug loses real money in milliseconds. There must be exactly one gate, with no second door.

verify_order_intent() is a pure function running 9 checks in sequence — market hours, symbol allow-list, order & position & daily notional caps, whole-share rules — and fails closed. A 3% gap-safety margin makes it reject on violent opens.

Concept to teach A single, un-bypassable choke point, proven by tests — safety comes from one enforced place, not scattered checks.

Concurrency lock

services/execution.py

Two signals for one account arrive at once. Read-decide-place is a classic race that can double-fill.

A PostgreSQL transactional advisory lock (pg_advisory_xact_lock) keyed to the account, with the position read done inside the same transaction. One signal waits for the other.

Concept to teach TOCTOU races — check and act atomically, or the window between them will eventually hurt you.

Honest backtester

services/backtest.py

Most retail backtesters lie: they fill stops at the stop price and assume infinite liquidity. The pretty curve evaporates live.

Models adverse gap fills, a 10% volume-participation cap (Almgren–Chriss), bid/ask, commissions, and short-borrow. The risk gate runs on every simulated order.

Concept to teach Backtest realism — a backtest is only useful to the degree it refuses to let you cheat.

The Swarm commons

db/repositories/social.py

Public leaderboards rot into survivorship-bias theater — only winners shown, posts edited after the fact.

Immutable pinned versions + a fork graph + a daily job that backtests each listing on data that only exists after its publish date — a real out-of-sample scorecard.

Concept to teach Out-of-sample validation & provenance — the only performance test that counts is on data the strategy never saw.

Portfolio risk review

services/portfolio_risk.py

An investor doesn't want P&L — they want “what should I sell?” Being wrong there costs money.

A pure, LLM-free engine scores each holding Trim / Review / Hold from concentration (weight + HHI), drawdown, and broker mix. An optional BYOK AI layer only narrates it.

Concept to teach Deterministic core, AI as a layer — compute the consequential number defensibly; use the model to explain, never to decide.

Advisor RAG

services/ai_advisor.py

A generic LLM advisor gives generic advice, ungrounded in anything the platform actually knows.

When a user describes a thesis, the advisor retrieves the most relevant published commons strategies (tickers weighted 2×) and injects them as few-shot context.

Concept to teach Retrieval-augmented generation — every strategy published to the commons makes the advisor smarter. A compounding data moat.

06

Security architecture

A checklist you can defend line by line.

Access token
RS256 JWT · 15-min expiry · user_id + tenant_id + role (HS256 dev fallback)
Refresh token
32-byte random · SHA-256 hashed in DB · 30-day · rotated on use, reuse-detected
Action tokens
Stateless signed JWTs. The reset link embeds a hash of the current password, so it self-invalidates the instant the password changes
Login OTPs
Only sha256(code) stored · single-use · attempt-capped · resend-throttled
Multi-tenancy
Every query carries WHERE tenant_id = $N — enforced in BaseRepo, structurally impossible to skip
Broker keys
HKDF + Fernet envelope encryption at rest · decrypted in memory only
Code sandbox
RestrictedPython · str-subclass guard · format denylist · iter-DoS removed · exec timeout
LLM access
Strict BYOK · founder-only platform-key fallback gated by a timing-safe email compare
07

Quant glossary

Every finance term you'd need to teach the system — one sentence each.

Notional
The cash value of an order or position (qty × price); risk limits are expressed in it.
Slippage
The gap between the price you expected and the price you got — markets move between decision and fill.
Market impact
Your own order moves the price against you; a fill is capped at ~10% of a bar's volume (Almgren–Chriss).
Gap fill
When a market opens far from the prior close, a stop fills at the gapped open — not the price it “should” have.
Sharpe / Sortino
Return per unit of volatility. Sortino penalizes only downside volatility — upside swings aren't “risk.”
Max drawdown
The largest peak-to-trough drop in the equity curve — the worst pain an investor would have felt.
Calmar
CAGR ÷ max drawdown — return measured against worst-case pain.
Profit factor
Gross profit ÷ gross loss; above 1 means the wins outweigh the losses.
In- vs out-of-sample
Measured on data you fit to (easy to curve-fit, near worthless) vs. data the strategy never saw (the real test).
Survivorship bias
Judging from only the winners — which massively overstates expected performance.
XIRR
The money-weighted return across irregular cash flows (monthly SIPs at different prices), solved numerically.
HHI
Sum of squared weights — a concentration measure. One holding at 100% = 1.0 (dangerous); many equal = near 0.
SIP / SWP
Systematic Investment Plan (invest on a schedule) / Systematic Withdrawal Plan (the retirement reverse).
Monte Carlo / GBM
Thousands of simulated price paths give a distribution of outcomes (P10/P50/P90), not one false number.
08

How to explain it

Three ready-made scripts, for three rooms.

60 seconds · an investor at a party

“AlphaSwarm is an AI quant team in a browser tab. You describe a trading strategy in plain English, the AI writes and honestly backtests the code, and it trades it through your own brokerage — we never touch your money. Because we hold neither the money nor the AI key, the whole thing is fundable by one person and free at the base tier. We only charge to go live and take a small cut of copied capital.”

5 minutes · a technical hire

Walk the four planes: a stateless Next.js frontend, a fast FastAPI control plane that never runs a trading loop, isolated Celery workers that do, Postgres + Redis underneath. Then the two flows: NL → validated Python → honest backtest → gated live deployment; and a creator's signal fanning out to hundreds of independent broker accounts.

Land on the three pillars — the un-bypassable risk gate, the honest backtester, and the out-of-sample commons.

Whiteboard · a systems interview

Draw the four planes; stress the web-tier / worker-tier split and why — a slow strategy can't block a dashboard request. Then the order path: intent → verify_order_intent() (single choke point, fails closed) → advisory-locked execution → broker.

Explain the TOCTOU race and the pg_advisory_xact_lock fix. Finish on tenant isolation in BaseRepo and BYOB/BYOK as the regulatory + cost moat.