## ๐ Methods to Connect TradingView to Flattrade API
### **1. Using TradingView Alerts + Webhook โ Python โ Flattrade API**
* TradingView lets you set alerts on indicators, price, or strategies.
* In the alert box, you can choose **Webhook URL**.
* Set this webhook to a small Python/Flask server running on your system or cloud (like AWS, Heroku, Railway).
* That server receives the alert and then calls **Flattrade API** (place order, fetch data, etc.).
**Steps:**
1. Get Flattrade API credentials (API key, secret, and session token).
2. Create a Flask/FastAPI app that exposes an endpoint
/tv_alert
.
3. In TradingView, set webhook URL to
http://yourserver.com/tv_alert
.
4. Your Python code parses TradingViewโs JSON alert and places an order through Flattrade API.
---
### **2. Using Pine Script strategy + Webhook**
* Write a TradingView **strategy script** (Pine Script) that generates buy/sell alerts.
* In the
alert_message
, embed JSON like:
json
{
"symbol": "{{ticker}}",
"action": "BUY",
"price": "{{close}}"
}
* Your webhook listener (Python) takes this JSON and directly executes Flattrade API calls.
---
### **3. Using 3rd Party Middleware (like AlgoTest, Tradetron, or Python bridge)**
* Some platforms already connect TradingView alerts to Indian brokers (Flattrade included in some cases).
* But if you want **full control**, a custom Python bridge is better.
---
## ๐ง Example Python Snippet (Webhook Listener โ Flattrade Order)
python
from flask import Flask, request, jsonify
import requests
app = Flask(__name__)
# Flattrade API credentials
API_KEY = "your_api_key"
ACCESS_TOKEN = "your_session_token" # Generate daily via login API
BASE_URL = "https://piconnect.flattrade.in/PiConnectTP/"
def place_order(symbol, side, qty=1, price_type="MKT"):
url = BASE_URL + "placeorder"
data = {
"exchange": "NSE",
"tradingsymbol": symbol,
"transactiontype": side, # BUY or SELL
"ordertype": price_type,
"producttype": "INTRADAY",
"quantity": qty,
"price": 0,
"clientid": API_KEY,
"token": ACCESS_TOKEN
}
r = requests.post(url, json=data)
return r.json()
@app.route("/tv_alert", methods=["POST"])
def tv_alert():
alert = request.json
symbol = alert.get("symbol", "RELIANCE-EQ")
action = alert.get("action", "BUY")
qty = alert.get("qty", 1)
response = place_order(symbol, action, qty)
return jsonify(response)
if __name__ == "__main__":
app.run(port=5000, debug=True)
๐ Now, in TradingView:
* Set webhook to
http://yourserver:5000/tv_alert
* Add alert with message:
json
{"symbol": "RELIANCE-EQ", "action": "BUY", "qty": 10}
With this setup:
* TradingView โ generates signal
* Webhook โ Python server
* Python โ places order via Flattrade API