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

Project: Pine Script Integration with Zerodha

Since a complete project involves multiple steps and technologies, I'll outline the entire project structure and provide you with a clear path for implementation.

Project: Pine Script Integration with Zerodha

Objective

To connect TradingView's Pine Script alerts with Zerodha's Kite API to automate trading actions based on signals.


1. Prerequisites

  1. Accounts and Tools:

    • A Zerodha account with Kite API subscription.
    • A TradingView Pro account (for webhook support).
    • A VPS or local machine with Python installed.
  2. Libraries: Install the following Python libraries:

    pip install flask kiteconnect requests
    

2. Pine Script Code

Write a simple strategy in TradingView. For this example, we'll generate Buy and Sell alerts using a moving average crossover.

Example Pine Script Code:

//@version=5
indicator("Zerodha Alert Integration", overlay=true)

// Define signals
fastMA = ta.sma(close, 10)
slowMA = ta.sma(close, 20)
buySignal = ta.crossover(fastMA, slowMA)
sellSignal = ta.crossunder(fastMA, slowMA)

// Plot signals on chart
plot(fastMA, color=color.green)
plot(slowMA, color=color.red)
plotshape(series=buySignal, title="Buy", location=location.belowbar, color=color.green, style=shape.labelup, text="BUY")
plotshape(series=sellSignal, title="Sell", location=location.abovebar, color=color.red, style=shape.labeldown, text="SELL")

// Alert conditions
if buySignal
 alert("BUY_SIGNAL")

if sellSignal
 alert("SELL_SIGNAL")

3. TradingView Alert Setup

  1. Go to the TradingView chart and set alerts:

    • Click the "Alerts" button.
    • In the Condition, select your Pine Script strategy.
    • In the Action, choose Webhook URL.
    • Add the webhook URL (this will be your Python Flask server, e.g.,
      http://yourserver.com/webhook
      ).
  2. Use JSON data for alerts: Example JSON for alerts:

    {
     "action": "{{strategy.order.action}}",
     "symbol": "{{ticker}}",
     "price": "{{close}}"
    }
    

4. Python Flask Webhook

Create a Flask server to receive alerts and connect to Zerodha's Kite API.

Flask Code:

from flask import Flask, request, jsonify
from kiteconnect import KiteConnect
import logging

# Initialize Flask app
app = Flask(__name__)

# Zerodha API credentials
api_key = "YOUR_API_KEY"
api_secret = "YOUR_API_SECRET"
access_token = "YOUR_ACCESS_TOKEN" # Update this daily

kite = KiteConnect(api_key=api_key)
kite.set_access_token(access_token)

# Webhook endpoint
@app.route('/webhook', methods=['POST'])
def webhook():
 data = request.json
 logging.info(f"Received alert: {data}")
 
 action = data.get("action").upper() # BUY or SELL
 symbol = data.get("symbol")
 price = float(data.get("price"))

 # Map TradingView symbols to Zerodha symbols (if needed)
 zerodha_symbol = map_tradingview_to_zerodha(symbol)

 # Place order
 try:
 if action == "BUY":
 order = kite.place_order(
 tradingsymbol=zerodha_symbol,
 exchange="NFO", # Change exchange based on your use case
 transaction_type="BUY",
 quantity=25, # Update lot size
 order_type="LIMIT",
 price=price,
 product="MIS" # Change to CNC for delivery
 )
 elif action == "SELL":
 order = kite.place_order(
 tradingsymbol=zerodha_symbol,
 exchange="NFO",
 transaction_type="SELL",
 quantity=25,
 order_type="LIMIT",
 price=price,
 product="MIS"
 )
 return jsonify({"success": True, "order_id": order})
 except Exception as e:
 logging.error(f"Order placement failed: {e}")
 return jsonify({"success": False, "error": str(e)})

def map_tradingview_to_zerodha(tv_symbol):
 # Add your symbol mapping logic if required
 return tv_symbol

if __name__ == "__main__":
 app.run(host="0.0.0.0", port=5000)

5. Deploy Flask Server

  1. Host the Flask app on a VPS (e.g., DigitalOcean, AWS) or use ngrok for local testing.

    • Install ngrok:
      ngrok http 5000
      
    • Copy the provided URL (e.g.,
      http://abcd1234.ngrok.io
      ) and use it in TradingView alerts.
  2. Ensure your server is secure:

    • Use HTTPS in production.
    • Authenticate requests from TradingView to avoid unauthorized access.

6. Authenticate Zerodha Daily

The Zerodha Kite API requires refreshing the access token daily. Automate this step using a cron job or manually login to generate the token.

Code to Fetch Access Token:

def generate_access_token(api_key, api_secret, request_token):
 kite = KiteConnect(api_key=api_key)
 data = kite.generate_session(request_token, api_secret)
 return data["access_token"]

# Use this function to update the access token daily

7. Test the System

  1. Trigger alerts from TradingView and check if the webhook receives them.
  2. Verify orders are placed in Zerodha.

8. Optional Enhancements

  • Database Logging: Save all alerts and orders in a database for reference.
  • Error Notifications: Set up email or Telegram alerts for errors.
  • Advanced Symbol Mapping: Handle complex symbol mappings (e.g., NSE, NFO, MCX).

 

caa January 01 2025 20 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 3
Members Online 1
Total Members: 12
Newest Member: karthik