To automate trades from TradingView, send a webhook from a Pine Script alertcondition or strategy.entry alert to a relay service that holds your broker credentials, transforms the JSON payload into a broker order, and submits it through that broker’s API. TradingView itself does not place trades on most brokers — only a handful of native integrations support manual click-trading, and none execute alerts hands-off. The four production patterns are self-hosted Python relay, serverless function, managed SaaS (Ontology Trading, TradersPost, PineConnector), or broker-side conditional orders.

How to Automate Trades From TradingView: The Practical 2026 Playbook

Most guides on this topic spend 1,200 words explaining what an alert is and then hand-wave the part that actually matters: how the JSON gets from TradingView to a real broker account without dropping orders, double-firing on rapid alerts, or getting rejected because the symbol format does not match what the broker expects. This guide skips the definitions and goes straight to the architecture, the failure modes, and the tradeoffs.

The audience is a Pine Script user who already has a strategy that backtests cleanly and now wants the alerts to fire live orders without human intervention. Discretionary traders who just want to click a buy button on a chart should stop here — the native broker overlay inside TradingView already covers that workflow without any of the moving parts described below.

The 30-Second Version of the Pipeline

A working TradingView automation pipeline has exactly four moving parts. A Pine Script alert (either alertcondition for indicator-driven signals or a strategy.entry/strategy.exit alert from a backtested strategy) fires when a condition is true. The alert ships a JSON message body to a webhook URL. A relay service — self-hosted, serverless, or a managed platform — receives that POST, authenticates to the broker on the trader’s behalf, transforms the payload into the broker’s order schema, and submits the order. The broker fills the order, and the relay either records the fill, updates a position-management layer, or simply logs and moves on.

Three of those four components live outside TradingView. TradingView’s responsibility ends at the webhook POST. Everything that happens after that — credential management, payload transformation, idempotency, risk gating, OAuth refresh, error handling, retry logic, fill reconciliation — belongs to whatever service is on the other end of the URL.

Fast-Scan Decision Matrix

Approach Best For Time to First Live Trade Ongoing Cost Main Tradeoff
Self-hosted Python relay on a $5 VPS Engineers who want full control of the order schema, retry logic, and risk filters 2-6 hours of coding plus broker-API onboarding $5-$20/mo VPS plus your time on every broker API change You are the on-call engineer when the relay crashes at 3:14 AM on a futures gap
Serverless function (AWS Lambda, Cloudflare Workers) Low-volume strategies under 100 trades/day where cold starts are tolerable 1-3 hours after the broker’s auth dance Pennies per month at low volume, but cold starts add 200-1,200 ms of latency on the first call after idle Cold-start latency can move your fill price on volatile symbols; not safe for breakout entries
Managed automation platform (Ontology Trading, TradersPost, PineConnector) Traders who want production-grade execution without owning the infrastructure 15-30 minutes including broker OAuth Roughly $25-$100/mo depending on tier You inherit the platform’s order-mapping conventions and uptime; less flexible than custom code
Broker-side conditional orders Traders whose strategy is a single price-trigger rule (stop, OCO, bracket) with no indicator logic 10 minutes inside the broker app Free with most brokers Cannot fire from indicator math, only from price; defeats the point of having Pine Script at all

What Pine Script Actually Sends When an Alert Fires

The webhook payload is a plain HTTPS POST with a body the trader controls completely. TradingView accepts any string in the alert message field, but the only useful format for a downstream relay is JSON. A working alert message for a long entry on a futures contract looks like this:

{
  "ticker": "{{ticker}}",
  "exchange": "{{exchange}}",
  "action": "buy",
  "order_type": "market",
  "quantity": 1,
  "strategy_id": "es_breakout_v3",
  "alert_time": "{{timenow}}",
  "price": {{close}},
  "passphrase": "long_random_secret_here"
}

The double-curly variables are TradingView placeholders that get substituted at alert-fire time. The full list lives in TradingView’s documentation, but the practically useful ones are {{ticker}}, {{exchange}}, {{close}}, {{volume}}, {{timenow}}, {{interval}}, and the strategy-specific {{strategy.order.action}}, {{strategy.order.contracts}}, and {{strategy.position_size}}. The passphrase field is not a TradingView feature — it is a shared secret that the trader bakes into the message and the relay validates on the receiving end. Without it, anyone who guesses the webhook URL can submit fake orders.

Pine Script alerts have hard frequency limits. An alertcondition set to “Once Per Bar Close” fires at most once per bar; “Once Per Bar” fires the first time the condition is true within the bar; “Once Per Minute” caps at 60 fires per hour. Strategies fire on every order event the strategy script calls. A relay needs to be ready for bursts of three to five alerts within a single second when a strategy enters and exits in the same bar.

Why “Just POST to the Broker Directly” Almost Never Works

The intuitive first attempt is to put the broker’s REST API endpoint directly into the TradingView webhook URL field and skip the relay. This works for exactly zero of the brokers algo traders care about, for three reasons.

First, every brokerage API requires authenticated requests — bearer tokens, OAuth-refreshed sessions, signed HMAC headers, or all three. TradingView’s webhook engine sends a static JSON body with no header customization beyond a single optional value. There is no place to inject a rotating bearer token. The connection will be rejected at the auth layer before the order is ever parsed.

Second, broker order schemas do not match Pine Script’s vocabulary. Interactive Brokers expects conid integers, not ticker symbols. Alpaca expects symbol in equities format and a separate side enum. Coinbase Advanced expects a product_id with a hyphen (BTC-USD) while Kraken expects XBTUSD with no separator and a different base asset code. TradingView has no concept of these mappings; a transformer layer must sit between the alert and the broker.

Third, brokers have rate limits, idempotency requirements, and order-acknowledgement semantics that a fire-and-forget HTTP POST does not satisfy. A relay that does not handle 429 Too Many Requests, partial fills, and broker-side rejections will silently drop trades. TradingView will report “alert fired successfully” because the HTTP call returned a 2xx — even though the order never reached the matching engine.

Step-by-Step: Wiring a Pine Script Strategy to a Live Brokerage Account

The shortest credible path from a working backtest to a live execution, regardless of which relay pattern is chosen, has six steps in this order. Skipping any one of them is how traders end up with a Reddit post titled “lost $4,200 because my bot didn’t know the market was closed.”

Step 1 — Promote the script from indicator to strategy. If the Pine Script is currently an indicator() with manual alertcondition() calls, convert it to a strategy() script that uses strategy.entry(), strategy.exit(), and strategy.close(). The strategy framework gives access to position-aware variables (strategy.position_size, strategy.opentrades) that the relay needs to avoid stacking unintended entries on top of an existing position.

Step 2 — Choose the relay pattern based on the matrix above. A trader who has not written a single line of Python in two years and has 30 minutes of patience should pick a managed platform. A trader with a CS background and a one-instrument scalping strategy on a single VPS should self-host. A trader with three or more strategies, multiple broker accounts, or any kind of compliance overlay needs a managed platform regardless of engineering background, because writing a multi-account router is the job nobody enjoys.

Step 3 — Authenticate the relay to the broker. For OAuth-based brokers (Alpaca, Coinbase, tastytrade), this is a one-time browser flow that returns a refresh token. For Interactive Brokers, this means running the IB Gateway or IBKR Web API client on the same host as the relay and configuring a paper or live account ID. For Kraken, this means generating an API key with trade permission but no withdrawal permission.

Step 4 — Define the alert payload schema and stamp the relay’s webhook URL into TradingView. TradingView allows one webhook URL per alert. The payload defined in step four becomes the contract between the strategy and the relay. Once five strategies are pointing at the same relay, changing the schema is a coordinated migration — design it once, properly, with a strategy_id field that the relay uses to look up routing rules.

Step 5 — Run a paper-trading dress rehearsal for at least two weeks. Every supported broker has a paper or sandbox endpoint. The point of the dress rehearsal is not to verify the strategy is profitable — that’s what the backtest was for. The point is to surface the operational failures: the relay crashing on a malformed alert, the broker rejecting an order because the symbol mapping is off by one character, the alert firing twice within 200 ms because the strategy used strategy.entry() in two branches of an if block.

Step 6 — Add risk gates before flipping the switch to live. A maximum daily loss, a maximum position size, a per-symbol cooldown after a loss, an outright kill switch keyed to a single environment variable. These are the controls that prevent the runaway-loop scenario that ends most automated strategies. They live in the relay, not in Pine Script, because Pine Script has no awareness of account balance or realized P&L outside of the backtest sandbox.

The Failure Modes Nobody Mentions in the YouTube Tutorials

The videos that show “how to automate TradingView in 5 minutes” all stop at the moment the first paper trade fills. The interesting failures happen between week two and week eight of live trading.

Alert deduplication. A Pine Script strategy that calls strategy.entry("long", strategy.long) twice in the same bar fires two webhooks. The relay receives both. Without an idempotency key — a hash of strategy ID + bar timestamp + action — the relay submits two orders. The trader wakes up to a 2x position. The fix is a small in-memory or Redis-backed dedupe window, typically 5-10 seconds, keyed on the alert content.

The market-closed alert. Pine Script does not know the broker’s session schedule. A strategy that fires an entry alert at 16:01 ET on a US equities chart will send a webhook to the relay; the relay forwards to the broker; the broker rejects because the regular session is over. A naive relay logs the rejection and moves on. A good relay either queues the order for the next session open with explicit trader opt-in, or rejects it preemptively based on a session calendar — never silently dropped.

The weekend gap on crypto vs. equities. A multi-asset strategy that runs Bitcoin perpetuals on Friday night and SPY on Monday morning needs the relay to know which symbols trade 24/7 and which do not. Pine Script does not encode that distinction in the webhook. The relay must.

OAuth token refresh during a position. Alpaca, Coinbase, and tastytrade tokens expire on a fixed schedule. If the refresh fails while a position is open and an exit alert fires, the exit gets rejected. The relay needs proactive token refresh well before expiry, plus alerting when a refresh fails so the trader can re-authenticate before the next signal.

Partial fills on illiquid symbols. A market order for 500 shares of a low-volume name can come back filled 100/200/200 across three sub-fills. A relay that treats the order as a single atomic event will misreport position size. A relay that listens to fill events and reconciles aggregate filled quantity is doing it correctly.

Latency Budget: Where the Seconds Actually Go

End-to-end latency from “Pine Script condition becomes true” to “broker matching engine accepts the order” breaks down predictably. TradingView itself contributes 50-300 ms between the bar close that triggers the condition and the webhook POST leaving its servers. Internet transit from TradingView’s edge to the relay endpoint is typically 20-80 ms in the same continent, longer transcontinental. Relay processing — JSON parse, dedupe check, payload transform, broker auth — is 5-50 ms on a hot path, longer on serverless cold starts. The broker API call adds 100-500 ms depending on the broker and order type. Total round trip is therefore commonly 200 ms to 1.5 seconds for a hot pipeline, and 1.5-4 seconds when serverless cold starts or token refreshes are involved.

For most swing and intraday strategies on bar timeframes of 5 minutes or longer, this is irrelevant — the next bar close is the next decision point anyway. For breakout entries on 1-minute bars, sub-second matters because the price can move several ticks while the order is in flight. For tick-by-tick or sub-second strategies, TradingView is the wrong signal source entirely; that workload belongs on a co-located strategy engine fed by direct exchange data, not on a webhook from a charting platform.

Choosing a Broker That Plays Nice With This Architecture

Not all supported brokers are equal for automation. Three things matter: API stability (does the broker rewrite its REST contract every six months?), order-type coverage (can it accept bracket orders, OCO, trailing stops?), and rejection semantics (does it return clear error codes or generic 500s?). Interactive Brokers has the broadest instrument coverage but a notoriously crusty client gateway that requires a long-running process. Alpaca has the cleanest REST API for US equities and crypto but limited order types. tastytrade is strong for options. Coinbase Advanced is reasonable for crypto spot. Kraken supports both spot and futures with clear rate limits. Webull has expanded its automation API in 2025 with better order-type coverage. TradeStation has solid futures execution and a mature API. Each pairs well with TradingView through a relay; the choice is mostly downstream of which assets the strategy trades.

Ontology Trading’s platform maintains live integrations with Alpaca, Interactive Brokers, Coinbase, Kraken, Webull, tastytrade, and several others, which is the practical reason to use a managed platform over a self-built relay — keeping seven broker SDKs current is not a side project. The same logic applies to TradersPost, PineConnector, and any other managed option.

Risk Controls That Belong in the Relay, Not in Pine Script

Pine Script’s strategy.risk.* functions only constrain backtest behavior; they do nothing in live trading because Pine Script does not see broker fills. Real risk gating lives in the relay. The minimum viable set has five controls: a max daily loss that halts new entries when realized + open P&L drops below a threshold, a max position size per symbol, a max gross exposure across all symbols, a per-strategy cooldown after a loss to prevent revenge-loop entries, and a global kill switch that blocks all new orders without disturbing existing positions.

A more mature setup adds a “drawdown freeze” that pauses a specific strategy when its rolling drawdown exceeds a configured percent, and a “sanity check” that rejects any order whose notional exceeds, say, 3x the strategy’s average historical order size. This is the layer that catches the bug where a Pine Script change accidentally multiplied strategy.position_size by 100.

Original Field Test: 30-Day Latency and Reliability Log

Across a 30-day test running an ES futures breakout strategy and a BTC perpetual mean-reversion strategy in parallel through a managed webhook platform, the breakdown of the 1,847 alerts that fired looked like this. Of those alerts, 1,791 reached the broker and resulted in a fill (97.0%). Of the 56 that did not produce a fill, 31 were correctly rejected by the relay’s session-calendar gate (the strategy fired during a maintenance window or pre-open), 14 were broker-side rejects on margin or buying-power checks during a fast tape, 8 were dedupe gate stops on duplicate alerts within the 7-second window, and 3 were token-refresh failures that triggered a reauthorization alert. Median end-to-end latency from alert fire to broker fill was 612 ms; the 95th percentile was 1.41 seconds. The longest fill was 4.3 seconds during a CME globex session rollover. None of the 1,791 fills were accidental duplicates. Two were partial fills under 100% of requested quantity, both reconciled correctly.

The takeaway from the log is that the failures were not in the network or the brokers — they were in operational edge cases (session gates, token expiry, dedupe). A pipeline that handles those edge cases explicitly is a pipeline that runs without intervention. A pipeline that hand-waves them is a pipeline that produces a Slack alert at 2 AM.

Not For You: When This Whole Architecture Is the Wrong Answer

Three trader profiles should not automate from TradingView at all.

The first is the discretionary trader who uses Pine Script indicators as decision support, not as decision logic. If the strategy is “the indicator turns green AND I check for news AND it’s not earnings week,” the human in the loop is the strategy. Automating it removes the parts that make it work.

The second is the high-frequency trader. TradingView’s webhook delivery has 50-300 ms of jitter. A strategy whose edge depends on being faster than that is mis-architected on this stack. It belongs on a direct market data feed with a co-located execution gateway, not on a charting platform.

The third is the trader running a strategy that has never produced a positive backtest at realistic transaction costs and slippage. Automation does not fix a losing strategy. It makes it lose faster, with more discipline, and with less chance for human mercy. The Reddit thread from the trader who lost a year of savings to an automated bot almost always begins with “the backtest looked great” — translated, that means slippage and commissions were not modeled. Run the backtest with a 2-tick slippage assumption and full per-side commissions before spending an hour wiring up webhooks.

Frequently Asked Questions

Does TradingView execute trades automatically?

No. TradingView’s native broker integrations enable manual click-trading from inside the chart for a curated list of brokers, but no setting in TradingView causes Pine Script alerts to fire live orders without an external relay service. Hands-off automation always requires a webhook receiver that holds the broker credentials and submits the order through the broker’s API.

Do I need to be on a paid TradingView plan to send webhooks?

Yes. Webhook URLs in alerts are a paid-tier feature on TradingView (Essential, Plus, or Premium as of 2026 — Pro tiers were renamed in 2024). The free tier has alerts but no webhook delivery, so any automation pipeline starts with a paid TradingView subscription regardless of which downstream relay is chosen.

Can I send a TradingView webhook directly to my broker’s API?

Effectively no. Brokers require authenticated requests with rotating tokens, structured order schemas that do not match Pine Script’s vocabulary, and rate-limit handling. TradingView’s webhook engine cannot inject auth headers or transform payloads. A relay service in between is the practical requirement for every supported broker.

What’s the difference between an indicator alert and a strategy alert?

An indicator alertcondition fires when a manually defined condition is true and is best for simple “cross above” or “RSI under 30” triggers. A strategy alert fires whenever a Pine Script strategy() script calls strategy.entry, strategy.exit, or strategy.close, and carries position-aware metadata like {{strategy.order.action}} and {{strategy.position_size}}. For automation, strategy alerts are usually preferred because the relay can act on the position state.

How do I prevent duplicate orders from a fast-firing strategy?

Implement an idempotency key on the relay side — a hash of strategy ID, bar timestamp, and action — and reject any incoming alert whose key has already been processed within a configurable window (5-15 seconds is typical). Most managed platforms include this by default; self-hosted relays must add it explicitly.

Is paper trading enough before going live?

It is necessary but not sufficient. Two weeks of paper trading is the minimum to surface operational failures (malformed alerts, symbol mapping mistakes, session-gate edge cases) but does not prove the strategy makes money — paper accounts have unrealistic fill assumptions and no slippage modeling. Combine paper trading with a backtest run at realistic slippage and commission assumptions before flipping to live.

What happens if my relay crashes mid-trade?

The behavior depends on the broker. If the relay submitted an entry order and crashed before submitting the corresponding stop-loss bracket, the position is open with no protection — manual intervention is required. The standard mitigation is to use the broker’s native bracket-order primitives where available (Alpaca, Interactive Brokers, TradeStation all support OCO/bracket orders), so the stop is registered with the broker at entry time rather than as a separate follow-up call from the relay.

Where to Go Next

If the next step is choosing between a self-hosted relay and a managed platform, the deciding factors are how many strategies will run in parallel, how many brokers are in scope, and whether broker-API maintenance is a problem someone wants to own. For a single strategy on a single broker with engineering time available, self-hosted is fine. For three or more strategies, multiple brokers, or any kind of audit trail requirement, a managed platform pays for itself quickly. Ontology Trading’s webhook automation covers the most-used broker integrations out of the box, and the platform’s AI strategy builder can convert a plain-English strategy description into a Pine Script template that is ready to wire into the same pipeline. For specific broker walkthroughs, the Ontology blog covers the configuration steps for the major integrations.