Crypto Bots

How to Create a TradingView Strategy and Alert to Auto-Trade

Use TradingView Pine Script to code your strategy, then send webhook alerts to a Python server that executes trades automatically on any exchange.

A
AI Agents Hubยท2026-02-02ยท4 min readยท717 words

Builder of AI agents, crypto trading bots, and open-source automation tools. Sharing practical guides on how to build, deploy, and profit from AI and DeFi technology.

TradingView has the best charting in crypto. Pine Script lets you code strategies visually. Webhooks let you auto-execute those signals. This guide connects all three into a complete trading system.

The Architecture

TradingView Alert โ†’ Webhook โ†’ Your Python Server โ†’ Exchange Order
  1. Pine Script detects your signal on TradingView
  2. TradingView fires a webhook to your server
  3. Your Python server receives the signal and places the order
  4. Exchange confirms the fill

Step 1: Write a Pine Script Strategy

//@version=5
strategy("EMA Crossover Bot", overlay=true, commission_value=0.1)

// Parameters
fast_len = input.int(9, "Fast EMA")
slow_len = input.int(21, "Slow EMA")

// Indicators  
fast_ema = ta.ema(close, fast_len)
slow_ema = ta.ema(close, slow_len)

// Plot
plot(fast_ema, color=color.blue, linewidth=2)
plot(slow_ema, color=color.orange, linewidth=2)

// Signals
long_condition = ta.crossover(fast_ema, slow_ema)
short_condition = ta.crossunder(fast_ema, slow_ema)

// Strategy entries
if long_condition
    strategy.entry("Long", strategy.long)
    
if short_condition
    strategy.close("Long")

// Visual alerts
plotshape(long_condition, style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small)
plotshape(short_condition, style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small)

Add this to TradingView: Open a chart โ†’ Click "Pine Editor" (bottom) โ†’ Paste โ†’ "Add to chart"

Step 2: Set Up the Webhook Alert

In TradingView:

  1. Click the clock icon (Alerts) โ†’ Create Alert
  2. Condition: "EMA Crossover Bot" โ†’ "Any alert() function call"
  3. Or use the crossover conditions from your strategy

Alert Message (JSON format your server will receive):

{
  "action": "{{strategy.order.action}}",
  "ticker": "{{ticker}}",
  "price": "{{close}}",
  "time": "{{time}}"
}
  1. Webhook URL: Enter your server URL (e.g., https://your-server.com/webhook)
  2. Set expiry (max 2 months free, unlimited with paid plan)

Step 3: Build the Python Webhook Server

from flask import Flask, request, jsonify
import ccxt
import os
import json
import hmac
import hashlib
from dotenv import load_dotenv

load_dotenv()
app = Flask(__name__)

exchange = ccxt.binance({
    'apiKey': os.getenv('BINANCE_API_KEY'),
    'secret': os.getenv('BINANCE_SECRET'),
    'enableRateLimit': True,
})

WEBHOOK_SECRET = os.getenv('WEBHOOK_SECRET', 'change-this-secret')
TRADE_SIZE_USDT = float(os.getenv('TRADE_SIZE_USDT', '100'))

@app.route('/webhook', methods=['POST'])
def webhook():
    # Verify it's from TradingView (optional but recommended)
    # TradingView doesn't send a signature, so add a secret param instead
    secret = request.args.get('secret', '')
    if secret != WEBHOOK_SECRET:
        return jsonify({'error': 'Unauthorized'}), 401
    
    data = request.json
    if not data:
        return jsonify({'error': 'No data'}), 400
    
    action = data.get('action', '').lower()
    ticker = data.get('ticker', 'BTCUSDT').replace('BINANCE:', '').replace('.P', '')
    price = float(data.get('price', 0))
    
    print(f"Signal received: {action} {ticker} @ ${price:,.2f}")
    
    try:
        if action == 'buy':
            result = execute_buy(ticker, TRADE_SIZE_USDT)
            return jsonify({'status': 'buy executed', 'order': result})
        
        elif action == 'sell':
            result = execute_sell(ticker)
            return jsonify({'status': 'sell executed', 'order': result})
        
        else:
            return jsonify({'status': 'no action', 'action': action})
    
    except Exception as e:
        print(f"Error executing trade: {e}")
        return jsonify({'error': str(e)}), 500

def execute_buy(symbol: str, usdt_amount: float):
    """Market buy."""
    symbol = symbol + '/USDT' if '/USDT' not in symbol else symbol
    balance = exchange.fetch_balance()['USDT']['free']
    size = min(usdt_amount, balance * 0.95)
    
    if size < 10:
        return {'status': 'skipped', 'reason': 'insufficient balance'}
    
    return exchange.create_market_buy_order(symbol, None, {'quoteOrderQty': size})

def execute_sell(symbol: str):
    """Market sell all holdings."""
    base = symbol.replace('USDT', '').replace('/USDT', '')
    balance = exchange.fetch_balance()
    amount = balance.get(base, {}).get('free', 0)
    
    if amount < 0.0001:
        return {'status': 'skipped', 'reason': 'no position'}
    
    symbol_pair = f"{base}/USDT"
    qty = exchange.amount_to_precision(symbol_pair, amount)
    return exchange.create_market_sell_order(symbol_pair, float(qty))

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080)

Step 4: Deploy the Server

Option 1: Free โ€” Railway.app

# Install Railway CLI
npm install -g @railway/cli

# Deploy
railway login
railway init
railway up

Option 2: Free โ€” Render.com

  1. Push code to GitHub
  2. Connect at render.com
  3. Create "Web Service" โ†’ your repo
  4. It runs 24/7 free

Option 3: $5/month VPS

# On Ubuntu 22.04
pip install flask ccxt python-dotenv gunicorn
gunicorn -w 1 -b 0.0.0.0:8080 webhook_server:app

Your Webhook URL

Once deployed, your webhook URL will be: https://your-app.railway.app/webhook?secret=your-secret

Enter this into TradingView's alert webhook field.

Testing

Test your server locally before deploying:

import requests

# Simulate a TradingView buy signal
test_signal = {
    "action": "buy",
    "ticker": "BTCUSDT",
    "price": "65000"
}

r = requests.post(
    "http://localhost:8080/webhook?secret=your-secret",
    json=test_signal
)
print(r.json())

Security Tips

  1. Always include a secret in the webhook URL
  2. Rate-limit your endpoint (maximum 1 trade per 60 seconds)
  3. Log every webhook request for debugging
  4. Add email/Telegram notifications for each trade execution
  5. Set a maximum daily loss threshold and stop trading if hit

This setup is powerful: you can run any Pine Script strategy โ€” even ones written by other TradingView community members โ€” and auto-execute them with real money.

Related Articles