Finbot is an AI-enabled trading research and execution platform that combines real-time APIs, ingestion pipelines, strategy engines, market data tooling, and observability into a single monorepo.
- Backend API: FastAPI server that exposes trading, market data, AI, and payments endpoints.
- Market data ingestion: Historical backfills, websocket streaming, adapters, and telemetry.
- Trading engine: Strategy management, backtesting, live execution, and risk controls.
- AI models: Pipelines, safety tooling, and assistant responses for finance questions.
- Data collector scripts: Standalone helpers for backfills, migrations, and mock ingestion.
- Observability + docs: Docker, compose profiles, Kubernetes helpers, and design docs.
- Analytics layer: Volatility regime detection powered by scikit-learn plus live order book imbalance analytics.
- Language: Python 3.11.9 (CI verified), Pydantic 2, FastAPI, SQLModel, SQLAlchemy
- Data & ML: pandas, numpy, scikit-learn, ta-lib, AlphalVantage, yfinance
- Infra: Docker, docker-compose, PostgreSQL, Redis, Prometheus, Sentry
- Dev tooling: pytest, black, ruff, mypy, isort, pre-commit
- Frontend: Vite/Tauri (React + Rust)
This guide provides instructions on how to set up and run the Finbot application, covering both the backend and frontend components.
Before you begin, ensure you have the following installed on your system:
- Python 3.11
- Node.js and npm: Required for running the frontend application.
- Docker and Docker Compose: Required if you choose to run the backend using Docker.
To bootstrap the entire stack (TimescaleDB + backend API + React dashboard + Grafana) run:
docker compose up --buildServices:
- Backend API:
http://localhost:8000 - React dashboard:
http://localhost:4173 - Grafana (pre-provisioned Postgres datasource + Finbot dashboard):
http://localhost:3000(admin/admin) - TimescaleDB:
localhost:5432(finbot/finbot)
The compose file automatically enables the Timescale extension and hypertables for candles, ticks, and order_book_snapshots.
You can run the backend using either Docker (recommended for a full setup) or locally with a simpler SQLite database.
This method uses Docker and Docker Compose to run the backend and a PostgreSQL database. It is the recommended setup for development and production.
Steps:
-
Clone the repository:
git clone <repo-url> cd blackboxai-finbot
-
Configure and Start Docker Services:
- From the repository root run:
docker compose up -d backend timescale
- This command builds the API image, starts TimescaleDB with the hypertable init script, and exposes the backend at
http://localhost:8000.
- From the repository root run:
-
Create a User:
- The application requires a user to be created in the database.
- Open a new terminal at the root of the project and run the
create_user.pyscript. This script connects to the database running inside the Docker container.
For PowerShell:
python create_user.py
For bash/zsh:
DATABASE_URL="$DATABASE_URL" python create_user.py -
Seed the Database (Optional):
- To populate the database with initial data, run the seeding script:
For PowerShell:
python seed.py
For bash/zsh:
DATABASE_URL="$DATABASE_URL" python seed.py
This method is simpler and does not require Docker. It uses a local Python environment and a SQLite database file.
Steps:
-
Clone the repository:
git clone <repo-url> cd blackboxai-finbot
-
Set Up a Virtual Environment:
- Create and activate a Python 3.11 virtual environment. This isolates the project dependencies.
# Create virtualenv python -m venv .venv # Activate on Windows .venv\Scripts\activate # Activate on macOS/Linux # source .venv/bin/activate
- Create and activate a Python 3.11 virtual environment. This isolates the project dependencies.
-
Install Dependencies:
- Install the required Python packages. Note that we are pinning
bcryptto a compatible version.pip install -r requirements.txt
- Install the required Python packages. Note that we are pinning
-
Run Database Migrations:
- Initialize and run database migrations using Alembic.
alembic upgrade head
- Initialize and run database migrations using Alembic.
-
Create a User and Database:
- Run the following script to create a
finbot.dbSQLite database file and add a new user to it.python create_user.py --email admin@finbot.com --password '@Dcmk2664'
- Run the following script to create a
-
Seed the Database (Optional):
- To populate the database with initial data, run the seeding script:
python seed.py
- To populate the database with initial data, run the seeding script:
-
Start the Backend API:
- Run the backend server using Uvicorn. The
--reloadflag enables hot-reloading.uvicorn backend.app.main:app --reload --host 0.0.0.0 --port 8000
- The backend API will be available at
http://localhost:8000.
- Run the backend server using Uvicorn. The
Follow these steps to run the frontend application.
-
Navigate to the Frontend Directory:
cd frontend -
Install npm Dependencies:
- Install the required Node.js packages.
npm install
- Install the required Node.js packages.
-
Run the Development Server:
- Start the Vite development server.
npm run dev
- The frontend application will be available at
http://localhost:5173(Vite's default port).
- Start the Vite development server.
The data_engine package provides reusable building blocks for ingesting ticks, persisting them, and producing OHLCV bars.
from datetime import datetime
from data_engine import CSVLogger, LiveDataEngine
logger = CSVLogger() # writes to data/raw/{symbol}_{date}.csv
engine = LiveDataEngine(timeframe_s=60, window_size=500, logger=logger)
tick_ts = datetime.utcnow()
current, completed = engine.on_tick("BTCUSD", tick_ts, price=42000.0, volume=0.5)
if completed:
print("Closed candle:", completed.to_dict())- CSV files are created under
data/raw/with the schematimestamp,symbol,price,volume. LiveDataEngine.on_tickcan be plugged intomarket_data.DataFeedwhich now accepts aLiveDataEngineinstance. Completed candles are pushed into rolling windows for indicator calculations.- Additional helpers (VWAP, ATR, rolling windows) live in
data_engine/, and tests are undertests/data_engine/.
Signals and strategies now live under the brain/ package. brain.signals.Signal standardizes outputs (action, price, order_type, meta) and brain.strategies.VWAPMicrotrendStrategy implements the “Brain” logic with VWAP/trend detection and market-session filters.
The backend exposes a hardened risk layer (risk/risk_manager.py) that halts trading when daily loss, position, price, margin, or session filters fail. Configure it through the .env file:
MAX_DAILY_LOSS_INR=1000
MAX_POSITION_DEFAULT=5
TRADE_CUTOFF_TIME=15:15
STRICT_CIRCUIT_CHECK=true # reject if circuit limits missingThe FastAPI route GET /risk/status surfaces the current kill-switch state (halted flag, margin, cutoff time) for dashboards. To run a manual check:
from datetime import datetime
from risk.risk_manager import OrderRequest, RiskContext, RiskEngine
risk_engine = RiskEngine(max_daily_loss=1000, max_pos_default=5)
ctx = RiskContext(
available_margin=150000.0,
day_pnl=-200.0,
positions={"INFY": 0.0},
last_price={"INFY": 1520.0},
circuit_limits={"INFY": (1400.0, 1600.0)},
max_daily_loss=1000.0,
)
decision = risk_engine.evaluate(
OrderRequest(ts=datetime.utcnow(), symbol="INFY", side="BUY", qty=1, price=1520.0),
ctx,
)
if not decision.approved:
raise RuntimeError(decision.message)When STRICT_CIRCUIT_CHECK is set to true (default), missing circuit bands automatically block new orders with MISSING_RISK_INPUT. Provide exchange circuit limits per symbol in portfolio_state["circuit_limits"] or disable the flag in development.
- Instantiate a strategy in a live loop:
from brain.strategies import VWAPMicrotrendConfig, VWAPMicrotrendStrategy config = VWAPMicrotrendConfig(symbol="INFY", timeframe_s=60) strategy = VWAPMicrotrendStrategy(data_feed=None, symbol="INFY", config=config) # for each completed candle produced by LiveDataEngine signals = strategy.on_candle(candle) for sig in signals: broker.submit(sig.to_dict())
- Run the lightweight backtester on CSV data (ticks logged under
data/raw/):A JSON report is saved underpython backtest/run_backtest.py \ --symbol INFY \ --csv data/raw/INFY_2024-01-10.csv \ --strategy vwap_microtrend \ --timeframe 60 \ --cash 200000
reports/. - Unit tests for the strategy framework, indicators, and data engine live under
tests/brain/andtests/data_engine/. Run them with:pytest tests/brain tests/data_engine
- Start at
docs/README.mdfor architecture, trading loop, AI pipeline, backtest pipeline, and module map. docs/README_FINBOT.md: High-level product overview and usage guidancedocs/README_MARKET_DATA.md: Ingestion deployment notes and operational checklistsdocs/trading_engine/: Strategy and backtesting walkthroughsdocs/architecture.md: Component interaction diagram- MVP run guide:
docs/mvp_guide.mdfor the paper-mode EMA crossover loop and dashboard.
GET /analytics/regime/{symbol}returns machine-learned volatility regimes (high/low), confidence, realized volatility, and ATR. The React dashboard visualizes the history and confidence bands.GET /analytics/order-book/{symbol}surfaces the latest top-of-book liquidity snapshot, computed imbalance, spread metrics, and depth levels built from the neworder_book_snapshotshypertable.- The new
order_book_imbalancestrategy consumes Level 2 data viadata_feed.get_latest_order_bookto produce microstructure-aware buy/sell/exit signals.