Production-hardened TradingView to Interactive Brokers execution bridge with institutional-grade safety controls.
TV-IBKR: Complete TradingView to Interactive Brokers Integration
Production-ready automated trading system connecting TradingView alerts to Interactive Brokers with enterprise-grade security, risk management, and monitoring.
๐ฏ Overview
This system provides a secure, reliable bridge between TradingView webhooks and Interactive Brokers for automated strategy execution. It includes comprehensive risk controls, position tracking, reconciliation, and audit logging.
๐ Quick Start
Prerequisites
- Python 3.9+
- Interactive Brokers TWS or IB Gateway (paper or live account)
- TradingView account with webhook support
Installation
# 1. Clone or download the project
cd tv-ibkr-system
2. Create virtual environment
python3 -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
3. Install dependencies
pip install -r requirements.txt
Configuration
# 1. Copy environment template
cp .env.template .env
2. Generate secrets
python3 -c "import secrets; print(secrets.token_hex(32))"
Copy output to WEBHOOK_SECRET in .env
python3 -c "import secrets; print(secrets.token_hex(32))"
Copy output to ADMINAPIKEY in .env
3. Edit .env file with your settings
nano .env # or use your favorite editor
Minimum Required Configuration:
# Security (REQUIRED - use generated secrets above) WEBHOOK_SECRET=your-generated-secret-here ADMINAPIKEY=your-generated-admin-key-here
IBKR Connection
IBKR_HOST=127.0.0.1
IBKR_PORT=7497 # 7497 for TWS paper, 7496 for TWS live
Start with dry run for testing
DRY_RUN=true
Start IBKR TWS
- Open Interactive Brokers TWS or IB Gateway
- Go to Configure โ Settings โ API โ Settings
- Enable "Enable ActiveX and Socket Clients"
- Verify "Socket port" is 7497 (paper) or 7496 (live)
- Uncheck "Read-Only API"
- Click OK
Run the Application
# Activate virtual environment
source venv/bin/activate
Run the application
uvicorn m4_final:app --host 0.0.0.0 --port 8000
You should see:
INFO: ๐ IBKR CONNECTED!
INFO: Application ready
Verify Setup
# Check health
curl http://localhost:8000/health
Check system status (replace YOURADMINKEY)
curl -H "X-API-Key: YOURADMINKEY" http://localhost:8000/admin/status
Run test suite
python test/m4finaltest.py
Expected: All 14 tests should pass โ
๐ Features
Security (Milestone 1)
- โ HMAC-SHA256 webhook authentication
- โ Timestamp validation with replay protection
- โ Idempotency key generation
- โ Pydantic schema validation
- โ Cloudflare-ready architecture
Risk Management (Milestone 2)
- โ Emergency kill switch
- โ Daily loss limits
- โ Position size limits
- โ Maximum trade count limits
- โ Circuit breaker for failures
- โ Telegram alerts (optional)
- โ Dry-run mode for testing
Persistence (Milestone 3)
- โ SQLite database with WAL mode
- โ Single-writer queue pattern
- โ Complete trade logging
- โ Expected position tracking
- โ Automated reconciliation (60s)
- โ Auto-halt on position mismatch
- โ Comprehensive audit trail
Administration (Milestone 4)
- โ Full REST API for management
- โ System status monitoring
- โ Trade history queries
- โ Reconciliation reports
- โ Kill switch controls
- โ Health/readiness endpoints
- โ Complete test suite
๐๏ธ Architecture
โโโโโโโโโโโโโโโโ
โ TradingView โ Alerts with HMAC signatures
โ Webhooks โ
โโโโโโโโฌโโโโโโโโ
โ HTTPS
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ FastAPI Application โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ โ
โ โ Security โ โ Risk Engine โ โ
โ โ โข HMAC โ โ โข Kill Switch โ โ
โ โ โข Replay โ โ โข Limits โ โ
โ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ โ
โ โ
โ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ โ
โ โ Persistence โ โ Reconciliation โ โ
โ โ โข SQLite โ โ โข Auto-check โ โ
โ โ โข Audit โ โ โข Auto-halt โ โ
โ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโ
โ โ
โผ โผ
โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ
โ SQLite โ โ IBKR โ
โ Database โ โ TWS/Gateway โ
โ (WAL mode) โ โ โ
โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ
๐ก API Endpoints
Public Endpoints
GET / # Service info
GET /health # Health check
GET /ready # Readiness check
POST /webhook # TradingView webhook (HMAC auth)
Admin Endpoints (requires X-API-Key header)
GET /admin/status # System status
POST /admin/kill # Activate kill switch
POST /admin/resume # Deactivate kill switch
POST /admin/reconcile # Force reconciliation
GET /admin/trades?limit=50 # Trade history
GET /admin/audit-log?limit=100 # Audit log
GET /admin/reconciliation-history # Reconciliation history
GET /admin/expected-positions # Expected positions
GET /admin/actual-positions # Actual IBKR positions
POST /admin/reset-limits # Reset daily counters
๐งช Testing
Run Complete Test Suite
# All tests (recommended)
python test/m4finaltest.py
Expected output:
โ
M1: Health Endpoint: PASSED
โ
M1: Valid Signature: PASSED
โ
M1: Invalid Signature Rejection: PASSED
โ
M1: Old Timestamp Rejection: PASSED
โ
M2: System Status: PASSED
โ
M2: Kill Switch: PASSED
โ
M2: Position Size Limit: PASSED
โ
M3: Trade Logging: PASSED
โ
M3: Expected Positions: PASSED
โ
M3: Manual Reconciliation: PASSED
โ
M3: Audit Log: PASSED
โ
M4: Admin Authentication: PASSED
โ
M4: Reconciliation History: PASSED
โ
M4: Reset Daily Limits: PASSED
#
Success Rate: 100.0%
Manual Testing
1. Check Health:
curl http://localhost:8000/health
2. Check System Status:
curl -H "X-API-Key: YOURADMINKEY" http://localhost:8000/admin/status
3. Send Test Webhook:
import hmac, hashlib, json, requests from datetime import datetime, timezone
payload = { "ticker": "AAPL", "action": "BUY", "quantity": 10, "order_type": "MARKET", "strategy": "test", "timestamp": datetime.now(timezone.utc).isoformat() }
secret = "YOURWEBHOOKSECRET" payload_json = json.dumps(payload, separators=(',', ':')) signature = hmac.new(secret.encode(), payload_json.encode(), hashlib.sha256).hexdigest() payload['signature'] = signature
response = requests.post('http://localhost:8000/webhook', json=payload) print(response.json())
๐ง Configuration
Essential Environment Variables
# Security (REQUIRED)
WEBHOOKSECRET=<strong-random-key> # Generate with secrets.tokenhex(32)
ADMINAPIKEY=<strong-random-key> # Generate with secrets.token_hex(32)
WEBHOOKTIMESTAMPTOLERANCE_SECONDS=30
IBKR Connection (REQUIRED)
IBKR_HOST=127.0.0.1
IBKR_PORT=7497 # 7497=paper, 7496=live
IBKRCLIENTID=1
Risk Limits (Adjust based on account size)
MAXPOSITIONSIZE=100
MAXDAILYLOSS=500.0
MAXPORTFOLIOEXPOSURE=0.25
MAXDAILYTRADES=50
Circuit Breaker
CIRCUITBREAKERTHRESHOLD=3
CIRCUITBREAKERTIMEOUT=60
Persistence
DATABASE_PATH=trading.db
RECONCILIATION_INTERVAL=60
RECONCILIATION_TOLERANCE=0
AUTOHALTON_MISMATCH=true
Features
TRADING_ENABLED=true
DRY_RUN=false # Set true for testing
ENABLERISKENGINE=true
ENABLEORDEREXECUTION=true
ENABLE_TELEGRAM=false # Optional
ENABLE_RECONCILIATION=true
Logging
LOG_LEVEL=INFO
See .env.template for all options with detailed comments.
๐จ Emergency Procedures
Activate Kill Switch
curl -X POST http://localhost:8000/admin/kill \
-H "X-API-Key: YOURADMINKEY" \
-H "Content-Type: application/json" \
-d '{
"reason": "Emergency halt - market volatility",
"actor": "TRADER"
}'
Resume Trading
curl -X POST http://localhost:8000/admin/resume \
-H "X-API-Key: YOURADMINKEY" \
-H "Content-Type: application/json" \
-d '{
"reason": "All clear",
"actor": "TRADER"
}'
Check System Status
curl -H "X-API-Key: YOURADMINKEY" http://localhost:8000/admin/status
Force Reconciliation
curl -X POST -H "X-API-Key: YOURADMINKEY" http://localhost:8000/admin/reconcile
๐ Database Schema
trades
Complete record of all trades with status tracking (PENDING โ FILLED/REJECTED/FAILED)audit_log
All system events with timestamps, searchable by event typeexpected_positions
Position tracking from trade log, updated on each trade, used for reconciliationreconciliation_log
Automated reconciliation results with mismatch detection and action taken๐ Security Best Practices
- Change Default Secrets
- Use HTTPS in Production
- Restrict API Access
- Monitor Audit Log
- Backup Database
sqlite3 trading.db ".backup tradingbackup$(date +%Y%m%d).db"
๐ Monitoring
Key Metrics to Track
- Daily trade count and P&L
- Position sizes and exposure
- Reconciliation status
- Circuit breaker state
- Database size and performance
Database Queries
-- Daily trade summary
SELECT
date(timestamp) as date,
COUNT(*) as trades,
SUM(CASE WHEN status='FILLED' THEN 1 ELSE 0 END) as filled,
SUM(CASE WHEN status='REJECTED' THEN 1 ELSE 0 END) as rejected
FROM trades
GROUP BY date(timestamp)
ORDER BY date DESC;
-- Current positions SELECT ticker, SUM(CASE WHEN action='BUY' THEN quantity ELSE -quantity END) as net_position FROM trades WHERE status='FILLED' GROUP BY ticker;
-- Recent reconciliation results SELECT * FROM reconciliation_log ORDER BY timestamp DESC LIMIT 10;
๐ Troubleshooting
IBKR Connection Failed
Symptoms:
{"level":"ERROR","msg":"IBKR connection failed error=Connection refused"}
Solutions:
- Verify TWS/Gateway is running
- Check API settings are enabled in TWS
- Verify port number (7497 for paper, 7496 for live)
- Check firewall settings
- Ensure client ID is not in use
Webhook Signature Invalid
Symptoms:
HTTP 401: Invalid signature
Solutions:
- Verify WEBHOOK_SECRET matches in both .env and signature calculation
- Check timestamp is current (within 30 seconds)
- Ensure JSON payload format is correct (no extra spaces)
Position Mismatch
Symptoms:
{"level":"WARNING","msg":"Position mismatch detected"} Kill switch activated
Solutions:
- Check audit log for unexpected fills
- Verify no manual trades were made in IBKR
- Review reconciliation history
- Manually adjust expected positions if needed:
sqlite3 trading.db "UPDATE expected_positions SET quantity=0 WHERE ticker='AAPL'"
Tests Timing Out
Symptoms:
โ M1: Valid Signature: FAILED - Read timed out
Solutions:
- Ensure IBKR is connected
- Set
DRY_RUN=truefor faster tests - Disable Telegram:
ENABLE_TELEGRAM=false - Check kill switch is not active
๐ Prerequisites
- Python 3.9 or higher
- Interactive Brokers account (paper or live)
- TWS or IB Gateway installed
- TradingView account with webhook support
- Basic command line knowledge
๐พ Dependencies
Install with: pip install -r requirements.txt
Main Dependencies:
- FastAPI + Uvicorn (web framework)
- IB-Insync (IBKR integration)
- aiosqlite (async database)
- pydantic (validation)
- python-telegram-bot (optional alerts)
๐ Project Structure
tv-ibkr-system/
โโโ m4_final.py # Main application
โโโ test/
โ โโโ m4finaltest.py # Test suite
โโโ .env # Configuration (create from template)
โโโ .env.template # Configuration template
โโโ requirements.txt # Python dependencies
โโโ README.md # This file
โโโ trading.db # SQLite database (auto-created)
โโโ trading.db-wal # Write-ahead log (auto-created)
โโโ trading.db-shm # Shared memory (auto-created)
๐ Deployment
Development
uvicorn m4_final:app --host 0.0.0.0 --port 8000 --reload
Production with systemd
Create /etc/systemd/system/tv-ibkr.service:
[Unit]
Description=TV-IBKR Trading System
After=network.target
[Service] Type=simple User=your-username WorkingDirectory=/path/to/tv-ibkr-system Envir ExecStart=/path/to/venv/bin/uvicorn m4_final:app --host 0.0.0.0 --port 8000 Restart=always RestartSec=10
[Install] WantedBy=multi-user.target
Enable and start:
sudo systemctl daemon-reload sudo systemctl enable tv-ibkr sudo systemctl start tv-ibkr sudo systemctl status tv-ibkr
Production with Docker
Create Dockerfile:
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "m4_final:app", "--host", "0.0.0.0", "--port", "8000"]
Build and run:
docker build -t tv-ibkr . docker run -d -p 8000:8000 --env-file .env tv-ibkr
๐ TradingView Webhook Setup
1. Create Alert in TradingView
- Open your strategy/indicator
- Click "Create Alert"
- Set condition
- Select "Webhook URL"
2. Webhook URL
https://your-domain.com/webhook
3. Message Format
{
"ticker": "{{ticker}}",
"action": "BUY",
"quantity": 10,
"order_type": "MARKET",
"strategy": "my_strategy",
"timestamp": "{{timenow}}",
"signature": "calculatedhmacsignature"
}
Note: You'll need to calculate the HMAC signature. See test file for example.
๐ Additional Documentation
- Quick Start Guide: See installation section above
- Configuration Reference: See
.env.template - API Reference: See API Endpoints section
- Troubleshooting: See Troubleshooting section
โ ๏ธ Disclaimer
This software is provided for educational and research purposes. Trading involves risk. Past performance does not guarantee future results. Always test thoroughly with paper trading before using real money. The authors assume no liability for trading losses.
๐ System Status
Status: โ Production Ready Version: 3.0.0 Milestones: 4/4 Complete Test Coverage: 14/14 Tests Passing (100%) Documentation: Complete
๐ฏ What's Included
- โ
Complete FastAPI application (
m4_final.py) - โ
Comprehensive test suite (
test/m4finaltest.py) - โ
All dependencies listed (
requirements.txt) - โ
Configuration template (
.env.template) - โ Professional documentation (this README)
- โ Production-ready with all 4 milestones complete
๐ค Support
For issues or questions:
- Check this documentation
- Review logs for errors
- Run test suite:
python test/m4finaltest.py - Verify configuration in
.env
๐ License
Team NAK - All Rights Reserved