Você desenhou uma strategy em Pine Script e quer que ela opere sozinha. Mas o TradingView não executa ordens na sua broker diretamente (salvo integrações nativas). A ponte é o webhook: o alerta dispara, manda uma mensagem for um servidor seu, e esse servidor executa a ordem via API da broker. Este guia monta esse pipeline inteiro — e é honesto about where ele can falhar.
01A arquitetura ponta a ponta
There are four links. Understanding the flow is essential before writing a single line:
Prerequisite: the webhook feature in alerts requires a paid TradingView plan. Free plans don't send webhooks. And you need a server with a public URL (a VPS, or services like Render/Railway) to receive the POST.
02Step 1: o alerta no TradingView
In your Pine Script, you use alert() with a JSON message (for the server to interpret). Then, when creating the alert in the interface, you paste your webhook URL in the "Webhook URL" field.
// no Pine Script — mensagem estruturada em JSON if ta.crossover(ma_rapida, ma_lenta) alert('{"segredo":"MEU_SEGREDO","acao":"COMPRA","ativo":"BTCUSDT","qtd":0.01}', alert.freq_once_per_bar_close)
The secret is vital — it's what prevents anyone who discovers your URL from firing fake orders. We'll see the validation on the server.
03Step 2: o servidor receptor
A simple Python server with FastAPI that receives the webhook, validates the secret and processes:
# servidor.py from fastapi import FastAPI, Request, HTTPException import os app = FastAPI() SEGREDO = os.getenv("WEBHOOK_SECRET") # never hardcode @app.post("/webhook") async def webhook(request: Request): dados = await request.json() # 1. valida o segredo — barra requisições falsas if dados.get("segredo") != SEGREDO: raise HTTPException(status_code=403, detail="Não autorizado") # 2. interpreta o sinal acao = dados.get("acao") ativo = dados.get("ativo") qtd = dados.get("qtd") # 3. executa na broker (função do seu módulo de execution) if acao == "COMPRA": executar_compra(ativo, qtd) elif acao == "VENDA": executar_venda(ativo, qtd) return {"status": "ok", "acao": acao}
A função executar_compra usa a API da broker — exatamente o código que mostramos no tutorial da Binance ou na API do MT5. The webhook only replaces the "deciding" part — now Pine Script decides.
Security is mandatory, not optional: your webhook URL is public. Without secret validation, anyone who discovers the URL can fire orders on your account. Always use: (1) a secret in the message, (2) HTTPS, (3) ideally also validate TradingView's origin IP. Treat this like you would treat your bank password.
04Step 3: where hospedar o servidor
The server needs a public URL and must always be running. Options:
- VPS (a mesma do bot) — controle total, IP fixo for você poder filtrar. Veja nosso guia de VPS.
- Platforms de deploy (Render, Railway, Fly.io) — sobem o servidor rápido, têm plano gratuito limitado. Bom for testar.
- Túnel local (ngrok) — só for testes, expõe seu PC local temporariamente. Never for produção.
Precisa de uma VPS for hospedar?
See how to choose and configure the VPS that will run your webhook server 24/7.
05Webhook vs. integração nativa
Antes de montar todo esse pipeline, considere a alternativa: algumas brokers têm integração nativa com o TradingView — você manda ordem direto do chart, without servidor intermediário. A Pepperstone is an example. Compare:
- Webhook + servidor: flexível (funciona com any broker que tenha API), but adiciona pontos de falha (servidor, latency, segurança) e exige manutenção.
- Integração nativa: mais simples e confiável (sem servidor seu no meio), but limitada às brokers que oferecem e ao que a integração permite.
Recomendação: se sua broker tem integração nativa e ela atende sua strategy, prefira-a — menos coisa for quebrar. O webhook brilha when você precisa de lógica customizada no meio (ex: risk management própria, múltiplas brokers) ou when a broker só oferece API, não integração TradingView.
06Os riscos honestos da automação por webhook
O que can dar errado (e vai, uma hora): o servidor can cair e você perde o sinal. A requisição can se perder na rede. Há latency between o alerta e a execution (segundos can importar). Um alerta can disparar duas vezes (ordem duplicada). Você precisa de logs, idempotência (não executar a mesma ordem duas vezes) e monitoramento. Automation por webhook é poderosa, but isn't "configure e esqueça".
Práticas que reduzem o risco: logar toda requisição recebida e toda ordem enviada; implementar idempotência (cada alerta tem um ID, ignore repetidos); ter um "kill switch" (forma de desligar tudo rápido); e — always — testar o pipeline inteiro em demo account por semanas before de any real.
07अक्सर पूछे जाने वाले सवाल
What is um webhook do TradingView?
É uma requisição HTTP que o TradingView envia automaticamente for uma URL sua when um alerta dispara. Essa requisição can acionar um servidor que executa ordens na broker, automatizando strategys feitas em Pine Script.
Do I need a paid TradingView plan?
Yes. The webhook feature in alerts requires a paid plan. Free plans don't allow sending webhooks. Additionally, you need a server with a public URL to receive them.
Is it safe to automate via webhook?
Tem riscos: a URL é pública (precisa de validação por segredo), o servidor can cair, há latency, e alertas can duplicar. Pra strategys sensíveis a tempo, integração nativa é mais confiável. Always test on demo e use logs, idempotência e kill switch.
What's the difference from native integration?
Integração nativa (ex: Pepperstone) executa direto do chart, without servidor seu — mais simples e confiável. Webhook é mais flexível (any broker com API, lógica customizada no meio) but adiciona pontos de falha. Prefira nativa when ela atender.
Can I use webhooks for B3?
Sim, since que sua broker tenha API acessível. O servidor receptor chamaria a API da broker (ou a ponte MT5-Python) for executar na B3. O fluxo é o mesmo; muda só a função de execution no final.