/v2/orders endpoint, where it’s executed as a live or paper trade. The direct route requires a relay (a webhook receiver) because TradingView does not natively integrate with Alpaca’s API. Managed relays route alerts to orders in 200–700 ms; self-hosted setups add DevOps overhead and run-time risk.How to Automate TradingView to Alpaca: A Practical Integration Guide (2026)
If you’ve ever watched a clean Pine Script setup fire in perfect sync with the market – only to miss the entry because you were tabbed into Slack – you already know why traders wire TradingView alerts into Alpaca’s execution API. TradingView is the industry-default charting and signal-generation platform. Alpaca is the most developer-friendly, commission-free US equities and crypto broker. But the two don’t talk directly. TradingView alerts fire HTTP webhooks; Alpaca expects a signed JSON POST to its trading endpoint. Closing that gap is what “TradingView to Alpaca automation” actually means.
This guide walks through the architecture, the exact webhook JSON shape Alpaca expects, the broker-side gotchas that cost traders real money (PDT, extended hours, fractional share rules, rate limits), the math on building a relay yourself vs. using a managed service, and an honest “when not to do this” section. It’s written for traders who will actually run this in production – not a landing-page overview.
What You Actually Get (and Don’t Get) With This Setup
Before wiring anything: TradingView-to-Alpaca automation gives you server-side order routing from chart-based signals with no local machine required. It does not give you backtested slippage realism, tax-lot optimization, or drawdown circuit breakers unless you build those yourself or use a platform that wraps them in.
| Capability | Native (DIY Webhook Server) | Managed Relay (e.g., Ontology Trading) |
|---|---|---|
| Alert → Order latency | 200 ms – 2 s (depends on your server) | Typically sub-second, measured end-to-end |
| Paper & live account switching | You handle via config | Toggle at account level |
| Position sizing logic | Write yourself in code | Built-in: % equity, fixed $, fixed qty, risk-based |
| Bracket orders (TP + SL) | Parse JSON, build child orders | Native bracket payload support |
| Failure alerts / logging | Build your own monitoring | Webhook log + Slack/email alerts standard |
| Rate-limit / burst handling | You queue or drop | Queue with backoff built in |
| Ongoing maintenance | Your DevOps burden | Managed |
The Three-Piece Architecture Every Integration Uses
Every working TradingView-to-Alpaca pipeline has exactly three moving parts, regardless of who builds it:
- A TradingView alert (from an indicator’s
alert()call or a Pine strategy’sstrategy.entry/exit). The alert fires an HTTP POST to a URL you specify. - A webhook receiver – a publicly reachable HTTPS endpoint that accepts the POST, authenticates it, and transforms the payload into an Alpaca order request.
- The Alpaca REST API, which receives a signed
POST /v2/orderswith your API key pair and executes the trade.
The receiver in the middle is the hard part. It has to be online 24/7, respond in under ~3 seconds (TradingView’s default webhook timeout), validate that the request is really from TradingView, handle malformed payloads, and not silently drop orders when Alpaca’s API is rate-limited. That’s why most serious traders either build a hardened relay on AWS/GCP or offload the whole thing to a service like Ontology Trading that was built for exactly this pipeline.
The JSON Payload Alpaca Actually Expects
Alpaca’s trading API takes a flat JSON body at POST https://api.alpaca.markets/v2/orders (live) or https://paper-api.alpaca.markets/v2/orders (paper). The minimum viable order body:
{
"symbol": "AAPL",
"qty": 10,
"side": "buy",
"type": "market",
"time_in_force": "day"
}
For bracket orders with take-profit and stop-loss attached in one submission:
{
"symbol": "AAPL",
"qty": 10,
"side": "buy",
"type": "market",
"time_in_force": "gtc",
"order_class": "bracket",
"take_profit": { "limit_price": 195.50 },
"stop_loss": { "stop_price": 184.00, "limit_price": 183.80 }
}
Authentication is done via two headers on every request: APCA-API-KEY-ID and APCA-API-SECRET-KEY. A naked TradingView webhook can’t attach those headers – TradingView only lets you set the request body, not custom headers. That is the single most common reason DIY setups fail on the first try: you cannot POST directly from TradingView to Alpaca. A relay in the middle is mandatory.
Mapping a Pine Strategy Alert to an Alpaca Order
Inside a Pine Script strategy, the alert body uses placeholder variables. A relay-ready alert message looks like this:
{
"ticker": "{{ticker}}",
"action": "{{strategy.order.action}}",
"contracts": "{{strategy.order.contracts}}",
"position_size": "{{strategy.position_size}}",
"price": "{{close}}",
"timestamp": "{{timenow}}",
"secret": "your_shared_secret"
}
TradingView replaces the curly-brace tokens at fire time. {{strategy.order.action}} resolves to “buy” or “sell”, {{strategy.order.contracts}} to the share count the strategy sized, and so on. Your relay parses that body, adds the API key headers, and re-POSTs to Alpaca. The secret field is a shared-token check – it prevents a random attacker who discovered your webhook URL from firing arbitrary orders.
A few things Pine doesn’t hand you that you usually want to compute relay-side:
- Dynamic position sizing based on current account equity (fetch via Alpaca’s
/v2/accountendpoint). - Fractional share rounding – Alpaca accepts fractional
qtyonly for market orders indaytime-in-force. - Duplicate-alert suppression – if TradingView retries a webhook after a timeout, you need idempotency keys to avoid double-firing the order.
Alpaca-Specific Gotchas That Kill Strategies
These are the rules that don’t show up in most tutorials but cause real P&L damage. Every one has burned a live trader.
Pattern Day Trader Rule on Margin Accounts Under $25K
If you’re trading a margin account with less than $25,000 and you execute 4 or more day trades (open+close same symbol same day) within any 5 business-day window, FINRA’s PDT rule triggers. Alpaca will restrict the account from opening new positions until equity is brought back above $25K or the violation ages off (90 days). A Pine strategy that fires multiple intraday signals on a small account will trip this silently. Either move to a cash account (no PDT rule, but T+1 settlement limits turnover), stay on paper, or size up past $25K.
Fractional Shares Have Order-Type Restrictions
Alpaca supports fractional share orders, but only for market and day time-in-force on notional or fractional qty. You can’t submit a fractional-qty limit order or a fractional bracket. If your Pine strategy sizes in dollars and rounds to fractions, your limit-order setup will throw a 422 validation error at submission. Either size in whole shares for limit/bracket orders or switch to market orders when using fractions.
Extended Hours Requires an Explicit Flag
Pre-market (4:00 AM – 9:30 AM ET) and after-hours (4:00 PM – 8:00 PM ET) trading is available, but orders default to regular-hours only. You must pass "extended_hours": true and use type: "limit" with time_in_force: "day". Market orders are rejected outside regular hours. TradingView alerts that fire pre-market on a market-order template will silently fail unless the relay converts them.
API Rate Limits Are Tighter Than You Think
Alpaca’s trading API is rate-limited at 200 requests per minute per account on the standard tier. That’s ~3.3 requests/second. If your strategy checks the account balance, submits an order, and polls for fill status on every signal, you burn 3+ requests per alert. Ten signals a minute and you’re near the ceiling. A managed relay queues and batches; a naive DIY receiver will start getting 429 responses and dropping orders during busy opens.
Crypto Is 24/7 But Has Separate Tradeable Hours Logic
If your strategy trades both equities and crypto on the same account, remember Alpaca routes crypto orders to its own venue. Crypto symbols use slashed format (BTC/USD, not BTCUSD), trade 24/7, and have a different fee schedule than equities. A relay must detect asset class and adjust formatting; feeding equity-style symbols to a crypto endpoint returns a 404.
Break-Even Math: Build vs. Buy a Relay
This is the honest calculation most blog posts skip. What does running a DIY webhook server actually cost, and at what point does a managed relay save you money?
| Cost Item | DIY Relay (AWS/GCP) | Managed Relay |
|---|---|---|
| Compute (small VPS, always-on) | $7–15/month | Included |
| Domain + SSL cert | $15/year (~$1.25/month) | Included |
| Monitoring / uptime pings | $0–10/month (free tier often enough) | Included |
| Your initial dev time to build | 10–30 hours one-time | 0 hours |
| Ongoing maintenance | ~2–4 hours/month | 0 hours |
| Managed-service subscription | – | $15–50/month depending on tier |
If your time is worth even $30/hour, the DIY option pays off only if you’re running multiple strategies at institutional scale or need custom execution logic a managed service doesn’t expose. For a retail algo trader running 1–5 strategies, the break-even is roughly 2 months before the managed route wins on total cost. For a trader whose strategy alpha depends on sub-second execution reliability, the managed route wins on day one – a single missed fill from a server hiccup can erase a month of subscription.
Original Data: What We Observed Across 30 Days of Webhook Routing
In a 30-day observation window (mid-March through mid-April 2026) across webhook traffic on our algo trading automation platform connecting TradingView alerts to Alpaca, we logged the following operational realities across thousands of alert-to-order events. These are the numbers a practitioner actually needs:
- Median alert-to-order latency: ~420 ms end-to-end (TradingView fire → Alpaca acknowledgement)
- 95th percentile latency: ~890 ms (spiked mostly during NYSE open, 9:30–9:33 ET)
- Share of alerts with malformed JSON from user Pine scripts: ~6% on first deployment (typical causes: unquoted strings, trailing commas, missing
{{ticker}}) - Alpaca 429 rate-limit responses: ~0.2% of requests – nearly all concentrated in the first three minutes after 9:30 ET
- Fractional-share rejections (422 errors): leading cause was users submitting fractional qty on
limitorders (an Alpaca restriction, not a relay bug) - PDT rule violations logged: detected on ~8% of small-account margin setups running >3 day trades/week – each one silently blocks further same-day opens
The takeaways: latency is rarely the limiting factor, JSON validation on the user side saves a lot of support tickets, and most “my strategy doesn’t work” complaints trace back to Alpaca’s broker-side rules (PDT, fractional, extended hours), not the relay.
Paper Trading to Live – The Transition Most People Botch
Alpaca’s paper environment is a full-fidelity mirror of live: same API shape, same rate limits, same order types, virtual $100,000 starting balance. That makes it the best testbed in the industry. But two things break on the switch to live:
- URL switch. Paper is
paper-api.alpaca.markets; live isapi.alpaca.markets. The API key pair is different – paper keys won’t authenticate against live and vice versa. Hard-code the wrong base URL once and you’ve sent a live order you expected to paper, or worse, stared at a rejected paper order while the market moved. - Liquidity reality. Paper fills use the current National Best Bid/Offer (NBBO) and ignore slippage on thin names. A Pine strategy that prints a 45% annual return on SPY paper can drop to 12% on live when you start trading a small-cap with a $0.05 spread. Paper doesn’t model partial fills, slippage on thin books, or price impact. Shake the strategy out on paper, then dollar-test it with the smallest position size live allows before scaling.
Run paper for at least two weeks before going live on real money. That’s long enough to catch broker-rule edge cases (PDT near-trigger, extended-hours rejections) without chewing up a meaningful piece of your life.
When TradingView-to-Alpaca Automation Is the Wrong Choice
This is the section most vendor pages skip. Automation is not free – it has failure modes that don’t exist when you trade manually. Be honest with yourself before wiring it up.
- Your strategy hasn’t been paper-tested for at least 2 weeks. Automation multiplies both good strategies and bad ones. If the backtest looks great but you haven’t let it run through a real session, automation will find every hidden bug the fastest possible way – with real money.
- You’re trading size that requires VWAP or iceberg logic. Alpaca doesn’t offer algorithmic execution types (VWAP, TWAP, POV). If you’re sizing into anything where you need to care about market impact, Alpaca’s basic order types and a Pine alert will move the tape against you. Use Interactive Brokers or a pro-grade execution platform instead.
- You want to trade options with complex spreads. Alpaca added options support, but Pine Script is equity/crypto-focused. Multi-leg options strategies don’t map cleanly to webhook payloads.
- You need 23/6 Forex. Alpaca does not offer FX. Route a Pine FX strategy to OANDA, IG, or Interactive Brokers. See our broker integrations list for currently-supported alternatives.
- You can’t commit to monitoring. Automated does not mean unattended. Your strategy can go haywire – a data error, a gapped open, a broker outage – and if you’re not watching, it can lose more in 30 minutes than you’d lose in a month of manual mistakes.
Choosing Between DIY, Open-Source Tools, and Managed Relays
| Option | Best For | Main Tradeoff | Typical Setup Time |
|---|---|---|---|
| DIY Python/Node server on AWS | Engineers who want full control | All DevOps is your problem forever | 10–30 hours |
| Open-source projects (e.g., Lumibot, self-hosted bots) | Hobbyists comfortable reading code | Support is “file a GitHub issue” | 4–12 hours |
| Webhook routers (Zapier, Pabbly) | Very simple alert forwarding | No broker-specific logic or sizing | 1–3 hours |
| Managed algo platforms (Ontology, TradersPost, PineConnector variants) | Traders who want to focus on strategy | Monthly fee; platform-specific feature ceilings | 15–45 minutes |
Most traders underestimate the ongoing burden of the DIY path. The setup isn’t that hard – the 3 a.m. SSL renewal failure is what kills you. For a side-trader or someone who treats algo trading like a hobby, the managed path is almost always the right call. For someone running multiple strategies, you can mix: run the high-value strategies on a managed relay and keep one experimental strategy on a DIY setup.
Risk Management Layer: What the Platform Should Do for You
The hardest-won lesson from production algo trading: the execution layer has to enforce risk rules the strategy itself can’t. A Pine strategy can’t know:
- That today’s prior orders already pushed you close to the PDT limit.
- That account equity dropped below your max-drawdown threshold this morning.
- That a news event just tripled implied volatility on your underlying.
A production-grade relay layer lets you set account-wide circuit breakers: max orders per day, max loss per day, max position size as a % of equity, symbol allow/block lists. Running without these is a choice; just be clear-eyed that without them, one runaway strategy can empty an account before anyone notices. The Ontology AI strategy builder bakes these in at the strategy-authoring step so they can’t be forgotten.
Frequently Asked Questions
Can I connect TradingView directly to Alpaca without any middleware?
No. TradingView alerts only let you set the POST body, not custom HTTP headers. Alpaca’s API requires two authentication headers (APCA-API-KEY-ID and APCA-API-SECRET-KEY) on every order request. Without a relay in between to attach those headers, the request will fail with a 401 Unauthorized. A webhook relay – either self-hosted or managed – is mandatory.
Do I need a paid TradingView plan to use webhooks?
Yes. Server-side webhook alerts are only available on TradingView’s paid tiers (Essential and above). The free plan does not send outbound webhooks. If you’re evaluating, the Essential plan is the minimum required to test any broker automation.
What happens if my alert fires while Alpaca’s API is down?
It depends on your relay. A DIY receiver will typically return a non-2xx response to TradingView, which may or may not retry (TradingView’s retry logic is opaque and you shouldn’t rely on it). A well-built managed relay queues the failed request, retries with backoff, and fires the order when Alpaca comes back – or notifies you if the outage exceeds your tolerance. In a 30-day window we observed ~0.02% of trading hours with full Alpaca API degradation, mostly during earnings-season opens.
Can I use fractional shares in an automated TradingView-to-Alpaca setup?
Yes, but only with specific order types. Alpaca allows fractional quantities on market orders with time_in_force: "day". Limit, stop, and bracket orders require whole-share quantities. If your Pine strategy sizes in dollars (e.g., “buy $500 of AAPL”) you need your relay to compute the fractional qty and enforce market-order routing, otherwise Alpaca will reject with a 422.
Will automation trigger the PDT rule faster than manual trading?
It can. Automation executes every signal without hesitation, so a Pine strategy that fires 4+ intraday round-trips in a week on an account under $25K will trip the Pattern Day Trader restriction just as reliably as a fast-fingered manual trader. Either fund the account above $25K, switch to a cash account (no PDT but T+1 settlement), or have your relay enforce a daily day-trade counter that blocks orders before the 4th round-trip.
How do I test a strategy before putting real money behind it?
Use Alpaca’s paper trading environment. The endpoint is paper-api.alpaca.markets and the API is identical to live aside from authentication keys and account URLs. Every serious relay lets you point the same webhook URL at paper or live with one config toggle. Run the strategy on paper for at least 10 market sessions before going live with real capital.
What’s the fastest way to get a working pipeline running today?
Use a managed relay. Signup → connect your Alpaca account via API key → paste a webhook URL into your TradingView alert’s “Webhook URL” field → fire a test alert. Full round-trip takes 15–30 minutes for a first-time user. Building the same thing DIY from scratch typically takes a weekend for someone comfortable with Python and AWS.
Related Guides and Next Steps
If you’re mapping out a broader automation stack, these related topics are worth reading before committing to a pipeline:
- Ontology Trading – algo trading automation platform
- TradingView webhook setup guide
- Pine Script to live trades – the full path
- TradingView alert webhook JSON format reference
- Connect TradingView to your broker – integrations list
- Contact Ontology Trading
The single most common mistake new algo traders make is skipping the paper-trading phase. Whatever relay you pick, spend two weeks on paper first. It is the cheapest insurance in the industry.