A self-hosted research-to-execution workspace for U.S. equities and spot crypto.
Screen markets, test ideas, review risk, build trade plans, and operate eligible Alpaca paper or live accounts from auditable workflows.
Capabilities · Workflow · Architecture · Quick start · Deployment · Security
AlphaLab v3.0.0 brings market research, strategy testing, portfolio-aware decision gates, and reviewed order execution into a single web application. The public site explains the product and methodology; the authenticated workspace contains the operational tools.
The platform is designed around visible evidence. Scanner inputs, validation results, blockers, order plans, and pipeline state remain inspectable instead of being hidden behind a single model score. AI providers can summarize evidence and challenge a decision, while deterministic code retains control of data-quality checks, portfolio admission, sizing, execution authorization, and hard risk stops.
The routed interface supports English and Simplified Chinese. New visitors start in English. An authenticated user's explicit language choice is saved with the workspace, restored across devices, and also controls supported Discord notification copy; local browser storage keeps switching usable while the backend is temporarily unavailable. Text returned by external providers may remain in its source language.
AlphaLab v3 public overview in the English interface. Figures shown in this product illustration are not live telemetry.
| Area | What is implemented |
|---|---|
| Market research | Market overview, Alpaca-backed U.S. equity scanning, configurable universes, symbol search, quotes, price history, news, technical context, and watchlists |
| Crypto research and automation | A 24/7 BTC/USD and ETH/USD spot workspace with completed-hour signals, long/flat sizing, Paper/Live separation, backtests after costs, published-research provenance, three-window Paper-only strategy learning, Settings-based AI review, emergency stop, and an auditable decision ledger |
| Symbol analysis | Multi-timeframe charts, SMA 20/50, RSI 14, observed support and resistance, company context, and direct handoff into backtesting |
| Research pipeline | A shared manual and scheduled seven-stage pipeline with stage progress, blockers, candidate evidence, run results, and stop controls |
| Validation and risk | Fine Scan evidence gates, cost- and risk-aware Deeper Validation, chronological walk-forward checks, portfolio admission, quote freshness, capacity, and duplicate-position/order checks |
| Strategy lab | Twelve backtest engines including a buy-and-hold benchmark, return/risk/trade metrics, equity and drawdown charts, trade records, exhaustive parameter-grid sweeps, comparison, and ranking |
| Trade planning | Trigger conditions, entry zones, sizing, stop and target geometry, order previews, and explicit paper/live authorization checks |
| Brokerage | Alpaca paper and live account views, positions, orders, assets, portfolio history, reviewed order entry, cancellation, and managed position protection |
| Portfolio evidence | Exposure, concentration, cash weight, drawdown, unrealized P/L, source freshness, holdings CSV export, and a versioned portfolio JSON report |
| Operations and safety | Activity log, runtime and configuration health, Safety Center controls, readiness checks, order and notification histories, scheduled-run state, pipeline diagnostics, and optional bilingual Discord notifications |
| Evidence and saved artifacts | Read-only candidate evidence drawers with sensitive-field redaction and JSON export, plus cross-device scanner settings, watchlists, and saved strategy blueprints |
| Configuration and identity | Per-user Alpaca, market-data, AI-provider, Finnhub, and Discord settings; persistent workspace mode and language; secure email password recovery; Supabase TOTP MFA enrollment and challenge flows |
Data freshness and availability depend on the connected vendor, account entitlements, market hours, and rate limits. AlphaLab reports missing or stale inputs where the integration exposes that state; it does not make every feed real-time.
Crypto release status: the current adaptive-trend strategy is not admitted for Live automation. The service defaults to Paper-only even when an Alpaca account is crypto-eligible. Live release requires a server-controlled research-admission gate in addition to account eligibility and the user's separate authorization. See docs/CRYPTO_STRATEGY.md for the current diagnostic evidence and acceptance standard.
Manual runs and scheduled headless runs use the same backend stage contract:
flowchart LR
A["1. Market Scanner"] --> B["2. Fine Scan"]
B --> C["3. Deeper Validation"]
C --> D["4. Portfolio Admission"]
D --> E["5. Entry Plan"]
E --> F["6. Execution"]
F --> G["7. Position & Exit"]
- Market Scanner ranks a configurable U.S. equity universe using market, liquidity, momentum, volatility, and data-quality evidence.
- Fine Scan evaluates setup fit, confirmation, liquidity, news, and risk. AI may challenge or downgrade a candidate, but it cannot promote a deterministic failure.
- Deeper Validation tests suitable strategies against costs, drawdown, benchmark performance, sample strength, parameter stability, and chronological walk-forward folds.
- Portfolio Admission checks current positions, open orders, capacity, drift, strategy consistency, and account-level conflicts before a candidate can advance.
- Entry Plan creates executable price geometry, sizing, triggers, invalidation, stops, targets, and an order preview from current evidence.
- Execution applies deterministic quote, market, account, order, and authorization checks. AI does not own order submission policy.
- Position & Exit reconciles managed plans, protective orders, hard stops, targets, and event/thesis review after entry.
| Mode | Behavior |
|---|---|
| Manual | Runs deterministic research and planning; no automatic order submission |
| Hybrid | Adds AI review and challenge; no automatic order submission |
| Full AI | May submit an eligible order only after deterministic gates and explicit execution authorization |
New accounts begin in paper mode. After a user explicitly chooses paper or live mode, that account-scoped preference is restored on later sign-ins and other devices instead of being reset by authentication changes. Live mode remains separate, requires valid live credentials, and unattended live execution additionally requires an explicit persisted opt-in.
flowchart TB
user["Browser"]
subgraph web["React 18 frontend"]
public["Public product and account pages"]
workspace["Authenticated research workspace"]
client["Typed REST client"]
end
subgraph core["Python 3.11 backend"]
api["Flask JSON REST API"]
pipeline["Seven-stage pipeline"]
scheduler["In-process market scheduler"]
guard["Position and exit guard"]
end
auth["Supabase Auth"]
db["Supabase Postgres<br>RLS configs, operations, artifacts, and run history"]
market["Market data and news<br>Alpaca · Finnhub"]
broker["Alpaca brokerage<br>paper · live"]
ai["Configurable AI providers<br>DeepSeek · OpenAI · Claude · Gemini · NVIDIA NIM"]
discord["Discord webhooks"]
user --> public
user --> workspace
public --> auth
workspace --> auth
workspace --> client
client -->|"Supabase bearer token"| api
api --> pipeline
scheduler --> pipeline
pipeline --> guard
api --> db
pipeline --> market
pipeline --> broker
pipeline --> ai
pipeline --> discord
The backend currently owns the REST API, scheduler, and managed-position guard. Keep exactly one Gunicorn worker in production; running multiple workers or replicas can create multiple schedulers because there is no distributed scheduler lock. Route-level React code splitting keeps public and authenticated pages out of the initial route bundle until they are needed. A bilingual top-level error boundary provides a recovery path for render failures, and optional privacy-minimized Web Vitals events can be enabled for a host application's telemetry collector.
| Layer | Technology |
|---|---|
| Frontend | React 18.2, TypeScript 4.9, Create React App 5, React Router 6, Ant Design 5, Redux Toolkit, Axios |
| Visualization | Recharts, Ant Design Plots, Lightweight Charts |
| Backend | Python 3.11, Flask, Flask-CORS, Gunicorn, Pandas, NumPy |
| Identity and storage | Supabase Auth and Postgres with row-level security |
| Integrations | Alpaca, Finnhub, configurable AI providers, Discord |
| Delivery | Cloudflare Pages + Render, or a single Docker image with Nginx |
| Tests | Pytest, Jest through React Scripts, and Playwright smoke tests |
| Workspace area | Routes | Purpose |
|---|---|---|
| Public | /, /platform, /workflow, /research, /examples, /data, /technology, /security, /about |
Product, methodology, examples, architecture, security, and project information |
| Account and legal | /signin, /signup, /forgot-password, /reset-password, /mfa, /terms, /privacy |
Supabase-backed account, TOTP MFA, and legal flows |
| Overview | /dashboard, /activity, /system-health |
Market overview, activity, configuration state, and runtime health |
| Markets | /market, /market/symbol/:symbol, /watchlist |
Scanner, symbol research, and saved market lists |
| Crypto | /crypto, /crypto/strategy, /crypto/automation, /crypto/ledger |
24/7 spot-crypto command desk, strategy evidence, automation controls, and user-scoped decisions |
| Research | /agent, /agent/candidates, /agent/review |
Pipeline control plus read-only candidate and review workspaces |
| Strategies | /backtest, /backtest/:id, /compare, /optimize, /ranking |
Backtests, details, parameter grids, comparison, and ranking |
| Trade | /trade, /portfolio |
Reviewed orders, account state, positions, and portfolio history |
| Settings and safety | /settings, /settings/configuration, /safety |
Preferences, MFA enrollment, external-service connections, readiness, entry pause/resume, order lifecycle, and delivery history |
| Prefix | Responsibility |
|---|---|
/api/health, /api/ready, /api/status |
Liveness, dependency/scheduler readiness, and platform status |
/api/config/, /api/settings/ |
Per-user provider and broker configuration |
/api/market/* |
Search, quotes, bars, news, user symbols, and scanning |
/api/crypto/* |
Crypto assets and bars, portfolio state, cost-aware backtests, Paper/Live cycles, automation controls, emergency stop, and audit ledger |
/api/backtest/* |
Backtests, history, and parameter-grid optimization |
/api/ai/, /api/ai-agent/ |
AI analysis, staged research, scheduler control, results, and history |
/api/entry-plan/, /api/trading/ |
Entry-plan checks, account data, reviewed orders, and cancellation |
/api/operations/* |
Durable Safety Center state, readiness, audit events, order lifecycle, notification delivery, and cross-device artifacts |
/api/notifications/* |
Discord configuration, testing, and event delivery |
The API is JSON/REST only. The repository does not currently include an OpenAPI specification or a WebSocket server. The first crypto release is intentionally limited to Alpaca-supported BTC/USD and ETH/USD spot trading; it does not short, use margin, or infer Live eligibility from saved credentials alone. See docs/CRYPTO_STRATEGY.md for the research and risk contract.
- Git
- Node.js 20 or newer and npm
- Python 3.11
- A Supabase project for authentication and persistent pipeline configuration
Alpaca, Finnhub, AI-provider, and Discord credentials are optional at boot. Add the integrations you need from Settings → Connections after signing in. Market research and brokerage features remain unavailable until their required providers are configured.
git clone https://github.com/Danielchen0101/Alpha_lab.git
cd Alpha_labCreate a Supabase project, enable the authentication providers you intend to use, then apply these SQL files in order in the Supabase SQL Editor:
backend/supabase_schema.sqlfor encrypted provider configuration, workspace preferences, pipeline schedules, and run history;backend/supabase_operations_store.sqlfor Safety Center state, readiness, append-only operational records, order and notification history, and cross-device artifacts;backend/supabase_security_hardening.sqlto make browser roles read-only and keep all validated mutations behind the backend;backend/migrations/20260726010000_worker_lease_runtime_hardening.sqlfor fenced, exact-owner worker leases used by unattended Kalshi and crypto order routing;backend/migrations/20260726060000_pipeline_config_atomic_merge.sqlfor atomic pipeline-config patches and the side-effect-free PostgREST readiness probe.
All five SQL files are required in production. Readiness fails closed when the atomic pipeline-config or fenced lease contract is missing. Real new-entry paths also fail closed when durable operations storage cannot be read, and the Safety Center and artifact APIs return an unavailable response instead of silently switching to process-local files. Local operations fallback is limited to development and test environments.
Collect:
- the project URL;
- the browser-safe anonymous key;
- the server-only service-role key.
cd backend
python3 -m venv .venv
source .venv/bin/activate
# Windows PowerShell: .\.venv\Scripts\Activate.ps1
python -m pip install -r requirements.txt
cp .env.example .envSet at least these values in backend/.env:
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_SERVICE_ROLE_KEY=your-server-only-service-role-key
FERNET_KEY=your-stable-fernet-key
FRONTEND_ORIGIN=http://localhost:3000
FLASK_ENV=developmentGenerate a Fernet key once and keep the same value across deployments:
python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"Start the development API:
python start_quant_backend.pyThe local backend listens on http://127.0.0.1:8889. Verify it from another terminal:
curl http://127.0.0.1:8889/api/health
# {"status":"ok"}
curl http://127.0.0.1:8889/api/ready
# {"status":"ready", ...}cd ../frontend
npm ci
cp .env.example .envSet these values in frontend/.env:
REACT_APP_API_BASE_URL=/api
REACT_APP_SUPABASE_URL=https://your-project.supabase.co
REACT_APP_SUPABASE_ANON_KEY=your-browser-safe-anon-key
REACT_APP_TURNSTILE_SITE_KEY=The local React proxy sends /api requests to port 8889. Turnstile can remain empty during development; production sign-in, sign-up, and account recovery require a valid site key.
npm startOpen http://localhost:3000, create or sign in to an account, and add provider credentials under Settings → Connections. Begin with an Alpaca paper account.
Every REACT_APP_* value is embedded into the browser build and must be treated as public. Never place a Supabase service-role key, Fernet key, broker secret, or AI secret in a frontend variable.
| Variable | Required | Purpose |
|---|---|---|
REACT_APP_ENV |
Production Docker | Set to production for Docker builds; Cloudflare Pages builds fail closed automatically when CF_PAGES=1 |
REACT_APP_API_BASE_URL |
Production | Use https://api.alphalabquant.com/api on Cloudflare Pages or /api for the same-origin Docker deployment |
REACT_APP_SITE_URL |
Production | Must be https://www.alphalabquant.com for authentication callbacks and the canonical public origin |
REACT_APP_SUPABASE_URL |
Yes | Must be https://nwpxjqgqegxttucsmvmp.supabase.co to match the deployed CSP |
REACT_APP_SUPABASE_ANON_KEY |
Yes | Browser-safe Supabase anonymous key |
REACT_APP_TURNSTILE_SITE_KEY |
Production auth | Public Cloudflare Turnstile site key |
REACT_APP_ENABLE_ANALYTICS |
No | Set to true to emit sanitized alphalab:web-vital browser events for a host telemetry collector |
| Variable | Required | Purpose |
|---|---|---|
SUPABASE_URL |
Yes | Supabase project used for token verification and durable state |
SUPABASE_SERVICE_ROLE_KEY |
Yes | Server-only database key; never expose it to React |
FERNET_KEY |
Yes in persistent environments | Encrypts saved Alpaca, AI, Finnhub, and Discord fields; it must remain stable |
APP_SECRET_KEY |
Production | Stable Flask session and application signing secret |
FRONTEND_ORIGIN |
One origin | Allowed browser origin |
CORS_ORIGINS |
Multiple origins | Comma-separated alternative to FRONTEND_ORIGIN |
FLASK_ENV |
Production | Set to production outside local development |
PORT |
Hosted Gunicorn | Port supplied by Render or another process manager; the local entry point remains on 8889 |
FLASK_DEBUG |
No | Enables Flask debug behavior for local development |
DEBUG_ENDPOINTS |
No | Enables diagnostic endpoints only when FLASK_ENV=development |
OPERATIONS_STORE_LOCAL_FALLBACK |
Development only | Allows the local JSON operations mirror outside tests; never enable it on a hosted production service |
CRYPTO_LIVE_RELEASE_ADMITTED |
No; defaults to false |
Server-only strategy release gate. Keep false until independent BTC/ETH release criteria pass; browser settings cannot override it |
CRYPTO_SCHEDULER_WORKERS |
No; defaults to 2 |
Bounded per-process Crypto scheduler concurrency; accepted range is 1–2 |
Authenticated broker and provider workflows use the per-user values saved from the Settings UI. They do not intentionally fall back to shared server-wide trading credentials.
AlphaLab supports a split web/API deployment and an all-in-one container.
| Service | Setting | Value |
|---|---|---|
| Cloudflare Pages | Root directory | frontend |
| Cloudflare Pages | Build command | npm ci && npm run build |
| Cloudflare Pages | Output directory | build |
| Render | Root directory | backend |
| Render | Build command | pip install -r requirements.txt |
| Render | Start command | MALLOC_ARENA_MAX=2 gunicorn start_quant_backend:app --bind 0.0.0.0:$PORT --workers 1 --threads 4 --timeout 900 |
Apply all five Supabase SQL files before deploying the application. Set the frontend build variables in Cloudflare Pages and the backend runtime variables in Render. Set REACT_APP_API_BASE_URL to https://api.alphalabquant.com/api, and set FRONTEND_ORIGIN to the exact deployed frontend origin.
Add the deployed frontend origin and its /auth/confirmed and /reset-password callbacks to the Supabase Auth URL configuration. Configure the same production host for Turnstile.
The equity scheduler, crypto scheduler, position guard, and order reconciliation run inside the backend process. Unattended operation therefore requires an always-on instance. A sleeping instance stops those tasks until the service wakes again. Pausing new entries in the Safety Center preserves broker-side protective sell, stop, and OCO orders; it does not make the in-process guard independent of backend availability.
The root Dockerfile builds the React frontend with Node 20, installs the Python 3.11 backend, runs one Gunicorn worker, and serves the application through Nginx on port 8080.
docker build \
--build-arg REACT_APP_API_BASE_URL=/api \
--build-arg REACT_APP_SITE_URL=https://www.alphalabquant.com \
--build-arg REACT_APP_SUPABASE_URL=https://nwpxjqgqegxttucsmvmp.supabase.co \
--build-arg REACT_APP_SUPABASE_ANON_KEY=your-browser-safe-anon-key \
--build-arg REACT_APP_TURNSTILE_SITE_KEY=your-public-site-key \
-t alphalab:v3.0.0 .
docker run --rm \
--env-file backend/.env \
-p 8080:8080 \
alphalab:v3.0.0Open http://localhost:8080 and check http://localhost:8080/api/health. Frontend build arguments are public; backend secrets belong only in the runtime environment.
The main-branch DockerHub workflow reads REACT_APP_SITE_URL and REACT_APP_SUPABASE_URL from GitHub Actions Variables, and reads REACT_APP_SUPABASE_ANON_KEY and REACT_APP_TURNSTILE_SITE_KEY from GitHub Actions Secrets. Missing or host-mismatched values stop the release before the image build.
See DEPLOYMENT.md for the hosting checklist. Deployment configuration is currently managed in provider dashboards rather than repository-owned Render or Cloudflare configuration files.
cd backend
python -m pytest -vThe backend test suite covers authentication behavior, scanner and validation gates, admission, entry execution, pipeline contracts and runtime state, position protection, and deployment invariants.
cd frontend
npm test -- --watchAll=false
npx eslint src/ --ext .js,.jsx,.ts,.tsx
npx tsc --noEmit
npm run buildPlaywright builds and serves the production frontend locally at http://127.0.0.1:4173 by default. Set PLAYWRIGHT_BASE_URL only when intentionally testing an external deployment:
npm run test:e2e
PLAYWRIGHT_BASE_URL=https://www.alphalabquant.com npm run test:e2eThe current validation baseline is 64 frontend Jest tests, 293 backend pytest tests, and 12 Chromium Playwright tests. CI also runs production builds, TypeScript and ESLint checks, high/critical npm dependency gating, Python dependency auditing, secret scanning, and Docker validation. Create React App remains a legacy toolchain, but the documentation does not pin audit or bundle-size counts that can become stale after each lockfile update.
These checks do not prove market-data quality, strategy validity, broker availability, deployment availability, or future trading performance. Verify every configured environment separately.
- Supabase sessions: the browser obtains a Supabase session and sends its bearer token with authenticated workspace requests.
- Owner-scoped storage: the supplied SQL enables row-level security for provider configuration, pipeline configuration, and run history. Backend service-role queries are scoped to the verified user.
- Durable operations state: the operations migration adds versioned Safety Center state, readiness, lifecycle and delivery records, and owner-scoped artifacts. Production real-entry checks fail closed if this store is unavailable.
- Server-side secrets:
SUPABASE_SERVICE_ROLE_KEYandFERNET_KEYstay on the backend. Browser builds receive only the Supabase anonymous key and other public build values. - Credential protection: provider fields are encrypted before storage and masked on reads when a stable Fernet key and the cryptography dependency are present. Missing or rotating the key can make stored values unreadable.
- Human verification: Turnstile protects production sign-in, registration, and password-recovery flows when configured.
- MFA: users can enroll a TOTP authenticator in Settings; enrolled accounts are routed through an AAL2 challenge when the Supabase session requires it.
- Account-scoped trading mode: new accounts start in paper mode, while an explicit paper/live choice is saved and restored across sessions and devices. Live and unattended execution still require separate authorization.
- Safety semantics: pausing new entries can optionally cancel pending managed buys while retaining protective exits; resuming uses optimistic version checks against durable state.
- Bounded AI authority: AI can summarize, challenge, or downgrade evidence; it cannot bypass deterministic data, capacity, duplicate-order, execution, or hard-stop controls. Crypto Live entries also fail closed when the reviewer is unavailable.
The Flask application retains legacy compatibility routes, and its built-in rate limiting is process-local rather than a distributed WAF. Review exposed routes, use HTTPS, restrict CORS to exact origins, place production deployments behind appropriate edge controls, and rotate any credential that may have been exposed.
To report a vulnerability, follow SECURITY.md. Avoid posting credentials, account data, or exploit details in a public issue; use GitHub private vulnerability reporting when it is available.
AlphaLab is research and execution software, not investment advice. Trading can result in partial or total loss.
- Start with paper trading and independently inspect every stage output before enabling live execution.
- Backtests and parameter sweeps are simplified research tools. Historical results, model scores, and walk-forward checks do not predict future performance.
- Quotes, bars, news, calendars, and broker state can be delayed, incomplete, stale, rate-limited, or unavailable.
- AI output can be incorrect or inconsistent. Deterministic gates reduce some failure modes but cannot eliminate market, model, software, or operational risk.
- The scheduler is process-local. A crash, deploy, network outage, or sleeping host stops scheduled work and position monitoring until the backend resumes.
- Use broker-side protective orders where appropriate, maintain independent account monitoring, set conservative permissions and limits, and keep a manual kill path.
You are responsible for provider agreements, market-data licensing, regulatory obligations, tax treatment, order review, and every trading decision made with the software.
Issues and pull requests are welcome.
- Read CONTRIBUTING.md and COMMIT_CONVENTION.md.
- Create a focused branch and keep unrelated generated, credential, runtime, and build files out of the change.
- Add or update tests for behavior changes.
- Run the relevant backend and frontend checks above.
- Open a pull request that explains the change, risk, validation, and any migration steps. Include screenshots for visible UI changes.
Please use Conventional Commit subjects such as feat(market): add a scanner filter or fix(pipeline): preserve a hard risk gate.
AlphaLab is available under the MIT License.

