Webhook Auto-Trading#

TradingView’s alert system supports Webhooks: when a signal triggers, it automatically sends an HTTP POST request to a specified URL. Combined with an intermediary server, this enables fully automated order placement from Pine Script strategies.

Overall Architecture#

TradingView Chart
    ↓ Strategy signal triggers
Pine Script alert()
    ↓ HTTP POST + JSON
Intermediary Server (Webhook receiver)
    ↓ Parse message, call API
Broker Order API
    ↓
Actual Execution

TradingView does not connect directly to brokers — you need to self-host or use a third-party Webhook intermediary service to bridge the two.

Pine Script Side: Designing Webhook Messages#

Webhook messages are typically in JSON format, sent via alert() or the alert_message parameter of strategy.entry:

//@version=6
strategy("Webhook Auto-Trading Demo", overlay=true,
         default_qty_type=strategy.fixed,
         default_qty_value=1)

ma5  = ta.sma(close, 5)
ma20 = ta.sma(close, 20)

// Golden cross: go long
if ta.crossover(ma5, ma20)
    strategy.entry("Long", strategy.long,
        alert_message='{"action":"buy","symbol":"{{ticker}}","qty":1,"price":{{close}},"time":"{{timenow}}"}')

// Death cross: close position
if ta.crossunder(ma5, ma20)
    strategy.close("Long",
        alert_message='{"action":"sell","symbol":"{{ticker}}","qty":1,"price":{{close}},"time":"{{timenow}}"}')

TradingView automatically replaces placeholders like {{ticker}}, {{close}}, and {{timenow}} with real values before sending the POST request.

Setting Up a Webhook Alert#

  1. Apply the strategy script to the chart
  2. Click the alarm clock icon in the top-right corner → Create Alert
  3. Set the condition to “Any strategy() function call” for that strategy
  4. Trigger: Every time condition is met
  5. Notification: Check Webhook URL
  6. Enter your intermediary server URL (e.g. https://your-server.com/webhook)
  7. Click Save

Note: Webhook functionality requires a TradingView Essential plan or above (not available on the free plan).

Intermediary Server Example (Python)#

Here is a minimal example of a Webhook receiver using Python + Flask:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
from flask import Flask, request, jsonify
import json

app = Flask(__name__)

@app.route("/webhook", methods=["POST"])
def webhook():
    data = request.json
    print(f"Signal received: {data}")

    action = data.get("action")
    symbol = data.get("symbol")
    qty    = data.get("qty", 1)
    price  = data.get("price")

    if action == "buy":
        # Call broker API to place a buy order
        place_order(symbol, "buy", qty)
        print(f"Buy order placed: {symbol} x {qty} @ {price}")
    elif action == "sell":
        # Call broker API to place a sell order
        place_order(symbol, "sell", qty)
        print(f"Sell order placed: {symbol} x {qty} @ {price}")

    return jsonify({"status": "ok"})

def place_order(symbol, side, qty):
    # Implement the broker API call here
    pass

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

Security Considerations#

Automated trading systems directly involve real money. The following security measures are essential:

1. Verify the Source#

TradingView Webhooks do not include signature verification, so anyone can send requests to your server. It is recommended to include a secret token in the message:

// Add a secret token on the Pine Script side
alert_message='{"token":"YOUR_SECRET_TOKEN","action":"buy","symbol":"{{ticker}}"}'
1
2
3
4
5
6
7
8
9
# Verify the secret token on the server side
SECRET_TOKEN = "YOUR_SECRET_TOKEN"

@app.route("/webhook", methods=["POST"])
def webhook():
    data = request.json
    if data.get("token") != SECRET_TOKEN:
        return jsonify({"error": "unauthorized"}), 401
    # ...

2. Use HTTPS#

Your server must use HTTPS — TradingView does not accept HTTP Webhook URLs.

3. Set Order Size Limits#

Limit the maximum order size per request on the server side to prevent abnormal signals from placing large unintended orders.

4. Log All Signals#

Keep a complete log of all signals to make post-event investigation easier.

Frequently Asked Questions#

Q: Is Webhook reliable? Can signals be missed?

TradingView’s Webhook delivery is not 100% guaranteed — delays or losses can occur during network instability or server busy states. Recommendations:

  • Log the timestamp of every signal on the server and periodically reconcile with position state
  • Implement retry logic
  • Do not rely entirely on Webhooks for trading; maintain manual oversight

Q: Can I use Webhook on the free plan?

No. Webhook functionality requires the Essential or higher paid plan.

Q: Can both Pine Script strategies and indicators use Webhooks?

Yes. Strategies use the alert_message parameter; indicators use alertcondition() or alert(). When creating the alert, enter the Webhook URL in the notification settings.

Reference#