Oh no! Where's the JavaScript?
Your Web browser does not have JavaScript enabled or does not support JavaScript. Please enable JavaScript on your Web browser to properly view this Web site, or upgrade to a Web browser that does support JavaScript.
Articles

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

  1. TradingView Account: Create alerts for your trading strategy.
  2. Zerodha Account: Obtain API access via Zerodha Kite Connect.
  3. Server Setup: Use Python Flask to handle webhooks.
  4. Symbol Mapping File: Download the Zerodha instruments CSV from the Kite API dashboard.

Step 1: Set Up Zerodha Kite API

  1. Install KiteConnect SDK:

    pip install kiteconnect flask
    
  2. 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

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

  1. Download the file from the Kite Dashboard.
  2. Save it as
    instruments.csv
    in the project folder.

Step 4: Set Up TradingView Alerts

  1. On TradingView, create your desired alert condition.
  2. Use the following JSON payload in the alert message:
    {
     "symbol": "NSE:RELIANCE",
     "action": "BUY",
     "quantity": 1
    }
    
  3. Set the webhook URL to:
    http://yourserver.com/webhook
    .

Step 5: Deploy the Flask App

  1. Run the app locally:

    python app.py
    
  2. Use tools like ngrok to expose the server to the internet:

    ngrok http 5000
    
    • Use the provided public URL as the webhook in TradingView.
  3. For production deployment:

    • Host on a cloud platform like AWS, Heroku, or DigitalOcean.
    • Use
      gunicorn
      or
      uwsgi
      with Nginx for better performance.

Step 6: Test the Setup

  1. Trigger an alert on TradingView with the configured webhook.
  2. Monitor the server logs for incoming webhooks and order placement.

Folder Structure

tradingview-zerodha-integration/
├── app.py
├── instruments.csv
└── 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
    .

 

caa December 25 2024 9 reads 0 comments Print

0 comments

Leave a Comment

Please Login to Post a Comment.
  • No Comments have been Posted.

Sign In
Not a member yet? Click here to register.
Forgot Password?
Users Online Now
Guests Online 2
Members Online 0

Total Members: 11
Newest Member: Jhilam