Skip to content

sanmaxdev/twingrid-binance

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

13 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

⚑ TWIN GRID

Open-source, self-hosted grid trading bot for Binance USDT-M Futures

A full-stack FastAPI and Next.js platform that runs an adaptive grid strategy autonomously across multiple Binance Futures accounts, with a real-time dashboard, backtesting, multi-account workspaces, and enterprise-grade security.

🌐 Live Demo · Quickstart · Docs · Contributing · Report a Bug

CI CodeQL License: MIT PRs Welcome

Python FastAPI Next.js TypeScript PostgreSQL Docker


πŸ“‹ Table of Contents


πŸ”­ Overview

TWIN GRID is a self-hosted, multi-tenant platform that runs an adaptive grid trading strategy autonomously across multiple Binance USDT-M Futures accounts. It pairs a robust Python trading engine with a modern Next.js dashboard, giving you live equity tracking, workspace-based account organization, and enterprise security controls in one package.

If you find this project useful, please consider giving it a ⭐. It helps others discover it.


✨ Features

Feature Description
πŸ€– Autonomous Grid Bot Adaptive grid strategy with volatility-based spacing, ATR indicators, and auto-rebalancing
πŸ“Š Real-Time Dashboard Live wallet balance, PnL tracking, equity charts, and account sparklines
🏒 Multi-Tenant Workspaces Organize trading accounts into workspaces with instant context switching
πŸ” Enterprise Security AES-256 API key encryption, JWT auth, RBAC, rate limiting, and full audit logging
πŸ“ˆ Equity Analytics Time-series equity history with interactive charts and performance metrics
πŸ›‘οΈ Risk Management Per-account drawdown limits, position size caps, and automatic kill switches
πŸ”„ Trade Reconciliation Automatic order reconciliation between local state and Binance
πŸ§ͺ Backtesting Replay strategies against historical market data before going live
πŸ‘€ Onboarding Wizard Guided setup flow for first-time users
πŸ› οΈ Super Admin Panel Platform-wide user management, metrics, audit logs, and encryption controls

🧱 Tech Stack

Layer Technology
Backend Python 3.11, FastAPI, SQLAlchemy 2.0, Alembic
Frontend Next.js 14, TypeScript, Tailwind CSS, shadcn/ui, Recharts
Database PostgreSQL 15
Cache / Queue Redis 7, Celery
Deployment Docker Compose, Caddy (reverse proxy)
CI/CD GitHub Actions, CodeQL, Dependabot

πŸš€ Quickstart

Prerequisites

  • Docker and Docker Compose
  • A Binance account with USDT-M Futures API keys

1. Clone and configure

git clone https://github.com/sanmaxdev/twingrid-binance.git
cd twingrid-binance
cp .env.example .env

Edit .env with your configuration. The key values to set:

# Database
POSTGRES_PASSWORD=change_me_to_a_strong_random_password
DATABASE_URL=postgresql+asyncpg://app:change_me_to_a_strong_random_password@db:5432/twin_grid

# Cache / Queue
REDIS_URL=redis://redis:6379/0

# Security
JWT_SECRET=replace_with_a_64_byte_random_string
# Generate with: python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
MASTER_ENCRYPTION_KEY=

Binance API keys are added per-account through the dashboard and encrypted at rest. They are never stored in .env. See .env.example for the full list of variables.

2. Start the services

# Development
docker compose up -d

# Production (with the Caddy reverse proxy)
docker compose -f docker-compose.yml -f docker-compose.prod.yml up -d

3. Open the dashboard

Service URL
Frontend http://localhost:3000
Backend API http://localhost:8000
API Docs (Swagger) http://localhost:8000/docs

4. First-time setup

  1. Register a new account at /auth/register
  2. Complete the onboarding wizard
  3. Connect your Binance API credentials (start on Testnet)
  4. Configure your grid strategy parameters
  5. Start trading

πŸ— Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                     Caddy (HTTPS)                    β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚   Next.js 14       β”‚        FastAPI                  β”‚
β”‚   Dashboard UI     β”‚        REST API                 β”‚
β”‚   :3000            β”‚        :8000                    β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚                                                      β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚  β”‚ Celery  β”‚  β”‚  Redis   β”‚  β”‚    PostgreSQL 15     β”‚ β”‚
β”‚  β”‚ Workers │◄─│  Queue   β”‚  β”‚  (encrypted at rest) β”‚ β”‚
β”‚  β”‚ + Beat  β”‚  β”‚  + Cache β”‚  β”‚                      β”‚ β”‚
β”‚  β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚       β”‚                                              β”‚
β”‚       β–Ό                                              β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                             β”‚
β”‚  β”‚   Binance Futures   β”‚                             β”‚
β”‚  β”‚   WebSocket + REST  β”‚                             β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                             β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Core services

Service Responsibility
grid_bot.py Main trading loop that places and cancels grid orders
risk_manager.py Enforces drawdown limits and position size caps
reconciler.py Syncs local order state with the Binance exchange
audit_service.py Logs all sensitive actions for compliance
binance_client.py Encrypted API key management and Binance SDK wrapper
equity_task.py Periodic equity snapshots for historical charts

πŸ“ Project Structure

twingrid-binance/
β”œβ”€β”€ backend/
β”‚   β”œβ”€β”€ app/
β”‚   β”‚   β”œβ”€β”€ api/v1/endpoints/    # REST API routes (auth, accounts, workspaces, history, admin)
β”‚   β”‚   β”œβ”€β”€ core/               # Config, security, database, rate limiting, Redis
β”‚   β”‚   β”œβ”€β”€ models/             # SQLAlchemy ORM models
β”‚   β”‚   β”œβ”€β”€ schemas/            # Pydantic request/response schemas
β”‚   β”‚   β”œβ”€β”€ services/           # Business logic (grid bot, risk manager, reconciler, audit)
β”‚   β”‚   β”œβ”€β”€ strategy/           # Trading strategy (grid, indicators, liquidation, state machine)
β”‚   β”‚   β”œβ”€β”€ tasks/              # Celery async tasks (equity snapshots, trading loops)
β”‚   β”‚   └── main.py             # FastAPI application entry point
β”‚   β”œβ”€β”€ alembic/                # Database migrations
β”‚   β”œβ”€β”€ tests/                  # Test suite
β”‚   └── Dockerfile
β”œβ”€β”€ frontend/
β”‚   β”œβ”€β”€ app/
β”‚   β”‚   β”œβ”€β”€ auth/               # Login and registration pages
β”‚   β”‚   β”œβ”€β”€ dashboard/          # Main dashboard, accounts, workspaces, profile, guide
β”‚   β”‚   β”œβ”€β”€ admin/              # Super admin panel (users, accounts, metrics, audit, events)
β”‚   β”‚   └── page.tsx            # Landing page
β”‚   β”œβ”€β”€ components/             # Reusable UI components (shadcn/ui)
β”‚   β”œβ”€β”€ lib/                    # API client, services, utilities
β”‚   └── Dockerfile
β”œβ”€β”€ docs/                       # Architecture, Security, Runbook, Changelog, Admin Handbook
β”œβ”€β”€ scripts/                    # Deployment and operations scripts
β”œβ”€β”€ docker-compose.yml          # Development environment
β”œβ”€β”€ docker-compose.prod.yml     # Production overrides
β”œβ”€β”€ Caddyfile                   # Reverse proxy configuration
└── .github/                    # CI/CD workflows, issue templates, security policy

πŸ” Security

  • API Key Encryption: AES-256 encryption at rest via the cryptography library
  • Authentication: JWT access and refresh tokens with secure httpOnly cookies
  • Authorization: Role-based access control (User, Admin, Super Admin)
  • Rate Limiting: Per-endpoint limits backed by a Redis sliding window
  • Audit Logging: Sensitive operations logged with user, IP, and timestamp
  • Tenant Isolation: Workspace-scoped queries prevent cross-tenant data access
  • Input Validation: Pydantic schema validation on every API endpoint
  • Automated Scanning: CodeQL, secret scanning, and dependency review run on every push and PR

See docs/SECURITY.md for the full security model, and .github/SECURITY.md to report a vulnerability privately.


πŸ”Œ API Overview

All endpoints are prefixed with /api/v1/.

Method Endpoint Description
POST /auth/register Register a new user
POST /auth/login Authenticate and receive tokens
GET /me Current user profile
GET /accounts/ List accounts in the active workspace
POST /accounts/ Connect a new Binance account
GET /accounts/{id}/dashboard Account metrics (balance, PnL)
POST /accounts/{id}/start Start the grid bot
POST /accounts/{id}/stop Stop the grid bot
GET /history/{id}/equity Equity time-series data
GET /workspaces/ List user workspaces
POST /workspaces/ Create a workspace

Full interactive docs are available at /docs (Swagger UI).


πŸ’» Development

Backend (without Docker)

cd backend
python -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate
pip install -e ".[dev]"
alembic upgrade head
uvicorn app.main:app --reload --port 8000

Lint and format the backend with ruff check app and ruff format app.

Frontend (without Docker)

cd frontend
npm install
npm run dev

Lint the frontend with npm run lint.

Running tests

cd backend
pytest -v

πŸ“š Documentation

Document Description
Architecture System design and component overview
Security Security model and threat mitigation
Runbook Operational procedures and troubleshooting
Admin Handbook Super admin guide
Changelog Version history

🀝 Contributing

Contributions are welcome and appreciated. Please read the Contributing Guide and our Code of Conduct before opening a pull request.

🌱 New here? Start with these

Run the backend tests (pytest -v) and the linters before submitting. Found a security issue? Please report it privately via our Security Policy.


⚠️ Disclaimer

This software is provided for educational and informational purposes only and is not financial advice. Trading cryptocurrency futures involves substantial risk of loss and is not suitable for every investor. Leverage can work against you as well as for you.

  • You are solely responsible for any trading activity conducted with this software.
  • Always test thoroughly on Binance Testnet before connecting live API keys.
  • Use API keys without withdrawal permissions.
  • The authors and contributors accept no liability for any financial losses, damages, or account actions resulting from the use of this software.

Use at your own risk.


πŸ“„ License

Distributed under the MIT License. See LICENSE for details.


Built with ⚑ by sanmaxdev
If this project helped you, consider leaving a ⭐

About

Open-source, self-hosted grid trading bot for Binance USDT-M Futures. Full-stack FastAPI and Next.js platform with automated grid strategy, real-time PnL dashboard, multi-account workspaces, backtesting, and enterprise security.

Topics

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors