Autonomous equity trading, in your terminal

Veloxformerly AlphaFlow

Six strategies, an 18-step signal pipeline, ML gating, VaR and a tiered circuit breaker, all behind one command. It trades US equities through Alpaca and runs in your terminal. No browser, no web server.

$ git clone https://github.com/lumenworksco/Velox.git && cd Velox
Python 3.12+MIT licenseAlpaca paper trading by default1,500+ tests
How it works

One trading day, start to finish

Velox is a single long-running process. It wakes up before the open, scans the universe each cycle, sends the survivors through a pipeline of checks, and manages every position until it exits. Times are US Eastern.

Prepare the universe

A dynamic universe picks ~127 symbols by volume, market cap and the current regime. Statistical mean reversion filters them with the Hurst exponent, an ADF stationarity test and the Ornstein-Uhlenbeck half-life. A pre-open gap analysis calibrates the mean-reversion and breakout strategies.

Scan, every ~2 minutes

All strategies scan for signals. The interval adapts to market activity (SCAN_INTERVAL_SEC defaults to 120). Each signal becomes a Signal object with an entry, stop-loss and take-profit.

Qualify, size, submit

Every signal runs the 18-step pipeline below: hard gates first, then a sizing stage where ML confidence, volatility targeting and sentiment adjust the position, then a bracket order with OMS tracking.

Manage exits

A single ExitOrchestrator decides every exit with a 10-level priority cascade. A WebSocket monitor watches prices so stops react between scans.

Housekeeping

A beta neutraliser hedges with SPY if portfolio beta passes ±0.3. Corporate actions and broker reconciliation run every 30 minutes. The correlation matrix refreshes intraday.

Close out

Day-hold positions are closed before the 16:00 bell and overnight holds are chosen. On Fridays a tax-loss harvesting scan runs, with wash-sale checks.

Summary

The day's P&L, per-strategy breakdown and consistency score are written to the SQLite database and shown in the dashboard. Weekly, KalmanPairs reselects its cointegrated pairs and a walk-forward check validates out-of-sample Sharpe.

A signal's journey

Eighteen steps between an idea and an order

Pick a step to see what it does. A gate can stop the signal. A sizing step can only make it smaller. Anything optional fails open, so a missing data source never freezes trading.

Strategies

Six strategies, five of them allocated

Capital is split across strategies that earn in different conditions. Allocations come from config/settings.py and always sum to 100% across the active ones.

StrategyAllocationTypeHoldIdea
StatMeanReversionSTAT_MR
28%
Mean reversionIntradayFits an Ornstein-Uhlenbeck process to 2-minute bars and enters on extreme z-scores, filtered by Hurst and ADF tests.
KalmanPairsTraderKALMAN_PAIRS
31%
Market-neutralMulti-dayA Kalman filter tracks a dynamic hedge ratio on cointegrated sector pairs and trades the spread.
PEADPEAD
20%
Event-drivenMulti-dayPost-earnings announcement drift, confirmed by FinBERT sentiment on the news.
VWAP v2 HybridVWAP
15%
Mean reversionIntradayVWAP deviation plus an OU z-score as dual confirmation, with a bid-ask spread filter.
IntradayMicroMomentumMICRO_MOM
6%
Event-driven~8 minSpots SPY volume spikes and scalps high-beta stocks in the direction of the move.
ORB v2ORB
0%
BreakoutDayOpening-range breakout with gap and range quality filters. Disabled since an alpha-decay alert on 2026-04-17; the code is kept.

Want to know whether a strategy earns its allocation? velox backtest runs four classic baselines (EMA crossover, RSI, momentum, Bollinger mean reversion) as yardsticks.

Risk and execution

Built to survive a bad day first

The defaults lean cautious: paper trading is on, short selling is off, and risk limits tighten automatically as losses build.

Tiered circuit breaker

Driven by the day's P&L, plus a trigger for sudden VIX spikes. Each tier is stricter than the last.

YELLOW−1%
New positions at half size
ORANGE−2%
No new entries
RED−3%
Close day trades, keep swings
BLACK−4%
Kill switch: close everything

Exit cascade

One orchestrator decides every exit. The first matching level wins, so a hard stop always beats a trailing stop.

  1. Hard stop loss
  2. Strategy-specific exits
  3. Adaptive VIX exit (mean reversion)
  4. Scaled take-profit and profit tiers
  5. ATR trailing stop
  6. RSI momentum exit
  7. Volatility-expansion exit
  8. Dead-signal detection
  9. Scale out of a loser
  10. Time stops

Order management

Every order is tracked through a state machine with idempotency keys, so a retry never double-submits. Five API failures in five minutes trip the kill switch.

PENDING→SUBMITTED→PARTIAL_FILL→FILLED
CANCELLEDREJECTEDEXPIREDFAILED

Portfolio guards

  • VaR monitor: parametric, historical and Monte Carlo (10,000 paths) at 95% and 99%.
  • Correlation limiter: eigenvalue-based effective bets plus a 30% sector cap.
  • Volatility targeting: sizes positions toward a 1% daily portfolio volatility.
  • Daily P&L lock: sizing drops to 30% after +1.5%, and new trades halt at −1.0%.
  • TWAP execution: orders over $2,000 are split into five slices.
  • Restart recovery: positions are reconciled with the broker on startup.
What it uses

A plain Python stack

One process, one SQLite file, no message broker and no web framework. Pinned versions live in requirements.txt.

Broker and data

alpaca-pyyfinancewebsockets

Orders, positions and market data from Alpaca, VIX and daily bars from Yahoo, live price updates over WebSocket.

Machine learning

XGBoostLightGBMCatBoostscikit-learnOptuna

A four-model averaging ensemble scores signals from 50 features. Optuna tunes hyperparameters.

Statistics

statsmodelsSciPyhmmlearnpykalmanpandas-ta

ADF and cointegration tests, HMM market regimes, Kalman-filter hedge ratios and technical indicators.

Language models

FinBERTClaude (optional)

FinBERT runs locally for news sentiment. A Claude model can optionally score signals.

Terminal interface

Richstructlog

Rich draws the live dashboard and the tables. Structured JSON logs are available for servers.

Storage and ops

SQLiteDockerpytestGitHub Actions

Trades, positions and snapshots live in bot.db. CI runs the suite on Python 3.12 and 3.13.

Use it yourself

From clone to running, in minutes

You need Python 3.12+ and, to trade, a free Alpaca paper-trading account. You can explore the dashboard and backtests without any account at all.

1

Install

Clone the repository and install the dependencies in a virtual environment.

$ python3 -m venv .venv && source .venv/bin/activate && pip install -r requirements.txt
2

Preview the dashboard

Renders the live terminal view with synthetic data, so you can see what the bot shows without a broker.

$ python velox.py demo
3

Backtest the baselines

Runs four classic strategies on bundled sample data, with each symbol's buy-and-hold return for comparison.

$ python velox.py backtest --symbols AAPL,SPY
Before you go live: run on paper for weeks, read config/settings.py end to end, and keep ALPACA_LIVE=false until you understand every limit. Velox is experimental software and carries real risk of loss.

Command reference

velox run [--live] [--diagnose]Run the bot here with the live dashboard.
velox start / stopRun in the background, or stop gracefully.
velox status [--watch]Heartbeat, open positions, recent trades.
velox killClose all positions and cancel all orders.
velox healthExit 0 if the heartbeat is fresh.
velox backtestBaselines on CSV or yfinance data, or --strategy velox.
velox tearsheet --days 90Performance report from the trade database.
velox demoThe dashboard with synthetic data.
velox strategiesStrategies, allocations and baselines.
Project map

Where things live

Roughly 51,000 lines of Python in a flat set of packages, with about 1,500 tests.

velox.py          # the CLI: run, status, kill, backtest, ...
main.py           # startup, position recovery, the main trading loop
dashboard.py      # Rich live terminal dashboard
config/            # every strategy and risk parameter (settings.py)
database.py        # SQLite: trades, positions, snapshots, signal log

engine/           # the trading engine
  scanner.py         # strategy scans, adaptive intervals
  signal_processor.py# the 18-step pipeline
  exit_orchestrator.py # 10-level exit cascade
  broker_sync.py     # reconciliation with the broker
  daily_tasks.py     # daily reset, weekly tasks, EOD close
strategies/       # StatMR, KalmanPairs, PEAD, VWAP, MicroMomentum, ORB
risk/             # circuit breaker, VaR, correlation, vol targeting, P&L lock
oms/              # order state machine, idempotency, kill switch
execution/         # bracket orders, TWAP, chase logic
ml/                # features, ensemble inference, training, FinBERT
analytics/         # metrics, OU fitting, Hurst, HMM regimes
backtesting/       # Monte Carlo, classic baselines
data/              # market data, feed monitor, sample CSVs
compliance/ ops/   # audit trail, PDT rule; disaster recovery, tax harvesting
tests/             # pytest suite
History

Where Velox came from

Velox grew over twelve major versions. In 2026 it absorbed two earlier projects and became terminal-only.

Predecessor

AlphaFlow

A Python and FastAPI trading platform for Alpaca with a strategy engine, backtester, risk manager and a React interface. Velox is its direct successor.

Merged in

Trading Algorithms

A Rust workspace with SIMD indicators and a backtester. Its MA-crossover, RSI, momentum and Bollinger strategies now live on as Velox's backtest baselines.

Today

Terminal only

The web dashboard, Prometheus and Grafana were removed. A velox command, a terminal kill switch and a heartbeat health check replaced them.

Risk warning. This is experimental software provided for education and research. Trading equities involves substantial risk of loss and past performance does not predict future results. You are responsible for any losses incurred.