Turning TradingView alerts into real trades on Interactive Brokers (IBKR) allows stocks and options traders to automate their execution workflows. This guide covers how to set up the connection using TWS/Gateway and configure robust risk management rules.
The Strategy-to-Execution Pipeline
To bridge TradingView and IBKR, the architecture requires three main modules:
1. **Signal Source**: A Pine Script indicator or strategy on TradingView triggering alert conditions.
2. **Relay Server**: A Python (e.g., using Flask and ib_insync) or Node.js application running on a VPS to receive HTTP POST signals.
3. **Execution Gateway**: Trader Workstation (TWS) or IB Gateway running alongside the relay server to authorize orders to IBKR servers.
Step-by-Step Implementation
1. Set Up the TWS/Gateway API
1. Launch Trader Workstation or IB Gateway.
2. Open **Configuration > API > Settings**.
3. Check **Enable ActiveX and Socket Clients**.
4. Note the port number (7497 for paper trading).
5. Add 127.0.0.1 to **Trusted IPs** if the relay server is running on the same machine.
2. Coding the Python Webhook Listener
Your Python script listens for TradingView webhooks, formats them, and submits them to IBKR:
from flask import Flask, request
from ib_insync import *
app = Flask(__name__)
ib = IB()
ib.connect('127.0.0.1', 7497, clientId=1)
@app.route('/webhook', methods=['POST'])
def webhook():
data = request.json
contract = Stock(data['symbol'], 'SMART', 'USD')
order = MarketOrder(data['action'].upper(), data['quantity'])
trade = ib.placeOrder(contract, order)
return {"status": "success", "orderId": trade.order.orderId}
if __name__ == '__main__':
app.run(port=5000)
3. Setting Up Alerts in TradingView
Set up an alert on your TradingView chart. Enter your webhook URL (e.g., http://your-server-ip:5000/webhook) and set the JSON message payload:
{
"action": "buy",
"symbol": "AAPL",
"quantity": 10
}
Advanced Options Automation
For options traders, the webhook relay can parse complex options contracts dynamically. By formatting the contract details in your JSON message (e.g., including option strike, expiry, and right), the bot can automatically route call or put orders for stocks like MSFT or SPY:
{
"action": "buy",
"symbol": "MSFT",
"secType": "OPT",
"expiry": "20260717",
"strike": 420,
"right": "C",
"quantity": 1
}
This lets you execute advanced strategies instantly when specific trend conditions are met on your charts.