NadirAliOfficial
tv-ibkr-v3
Python

Production-hardened TradingView to Interactive Brokers execution bridge with institutional-grade safety controls.

Last updated Jul 5, 2026
15
Stars
2
Forks
0
Issues
0
Stars/day
Attention Score
53
Language breakdown
Python 100.0%
โ–ธ Files click to expand
README

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 type

expected_positions

Position tracking from trade log, updated on each trade, used for reconciliation

reconciliation_log

Automated reconciliation results with mismatch detection and action taken

๐Ÿ”’ Security Best Practices

  • Change Default Secrets
- Generate strong random values for WEBHOOKSECRET and ADMINAPI_KEY - Never commit secrets to version control
  • Use HTTPS in Production
- Always use SSL/TLS for webhook endpoint - Consider Cloudflare for additional DDoS protection
  • Restrict API Access
- Use firewall rules to limit access - Consider IP whitelisting for admin endpoints
  • Monitor Audit Log
- Regularly review for suspicious activity - Set up alerts for unusual patterns
  • 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=true for 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

๐Ÿ”— More in this category

ยฉ 2026 GitRepoTrend ยท NadirAliOfficial/tv-ibkr-v3 ยท Updated daily from GitHub