TradingView Webhook to Zerodha Order Placement
Here's a complete project outline for integrating TradingView webhooks with Zerodha's Kite API to place trades.
Project: TradingView Webhook to Zerodha Order Placement
Prerequisites
- TradingView Account: Create alerts for your trading strategy.
- Zerodha Account: Obtain API access via Zerodha Kite Connect.
- Server Setup: Use Python Flask to handle webhooks.
- Symbol Mapping File: Download the Zerodha instruments CSV from the Kite API dashboard.
Step 1: Set Up Zerodha Kite API
-
Install KiteConnect SDK:
pip install kiteconnect flask
-
Generate API Key and Access Token:
- Sign up for Kite API.
- Get your API key and secret.
- Use the following script to generate an access token:
from kiteconnect import KiteConnect
kite = KiteConnect(api_key="your_api_key")
print(f"Login URL: {kite.login_url()}")
# After logging in and getting the request token
request_token = "your_request_token"
data = kite.generate_session(request_token, api_secret="your_api_secret")
print("Access Token:", data["access_token"])
Step 2: Create Flask App
File: app.py
app.py
from flask import Flask, request, jsonify
from kiteconnect import KiteConnect
import csv
app = Flask(__name__)
# Zerodha API setup
kite = KiteConnect(api_key="your_api_key")
kite.set_access_token("your_access_token")
# Load token mappings from Zerodha instruments CSV
def load_token_mapping(file_path):
mapping = {}
with open(file_path, "r") as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
mapping[f"{row['exchange']}:{row['tradingsymbol']}"] = row['instrument_token']
return mapping
token_map = load_token_mapping("instruments.csv")
@app.route('/webhook', methods=['POST'])
def webhook():
data = request.json
if not data:
return jsonify({"error": "Invalid payload"}), 400
# Extract data from webhook
symbol = data.get("symbol")
action = data.get("action").upper()
quantity = int(data.get("quantity", 1))
instrument_token = token_map.get(symbol)
if not instrument_token:
return jsonify({"error": "Symbol mapping not found"}), 400
# Place order via Kite API
try:
order = kite.place_order(
tradingsymbol=symbol.split(":")[1],
exchange="NSE",
transaction_type="BUY" if action == "BUY" else "SELL",
quantity=quantity,
order_type="MARKET",
product="MIS" # For intraday
)
return jsonify({"status": "success", "order_id": order})
except Exception as e:
return jsonify({"error": str(e)}), 500
if __name__ == '__main__':
app.run(port=5000)
Step 3: Download Zerodha Instruments CSV
- Download the file from the Kite Dashboard.
- Save it as
in the project folder.instruments.csv
Step 4: Set Up TradingView Alerts
- On TradingView, create your desired alert condition.
- Use the following JSON payload in the alert message:
{ "symbol": "NSE:RELIANCE", "action": "BUY", "quantity": 1 }
- Set the webhook URL to:
.http://yourserver.com/webhook
Step 5: Deploy the Flask App
-
Run the app locally:
python app.py
-
Use tools like ngrok to expose the server to the internet:
ngrok http 5000
- Use the provided public URL as the webhook in TradingView.
-
For production deployment:
- Host on a cloud platform like AWS, Heroku, or DigitalOcean.
- Use
orgunicorn
with Nginx for better performance.uwsgi
Step 6: Test the Setup
- Trigger an alert on TradingView with the configured webhook.
- Monitor the server logs for incoming webhooks and order placement.
Folder Structure
tradingview-zerodha-integration/ ├── app.py ├── instruments.csv └── requirements.txt
requirements.txt
:
requirements.txt
flask kiteconnect
Step 7: Enhancements
- Logging: Save webhook and order details to a file.
- Security: Validate webhook payloads to prevent unauthorized access.
- Error Handling: Add detailed error messages for failed API calls.
- Symbol Updates: Automate the download and processing of
.instruments.csv
No Comments have been Posted.