Bridge the gap between charting and automated execution. Master Pine Script v5 to create alert conditions and JSON webhooks for seamless TradingView trading.

Pine Script is TradingView's programming language that lets traders create custom indicators, strategies, and alerts for automated trading. For automation, you need to understand basic Pine Script syntax to write alert conditions that trigger webhook messages to your automation platform. While Pine Script requires some coding knowledge, the basics for automation focus on three core elements: defining entry/exit conditions, creating alert triggers, and formatting alert messages with proper variable syntax.
Pine Script is TradingView's proprietary programming language designed for creating technical indicators and trading strategies directly on their charting platform. For futures automation, Pine Script serves as the bridge between your trading logic and automated execution—it defines when alerts fire and what data gets sent to your automation platform.
Pine Script: A domain-specific programming language built for financial market analysis that uses simplified syntax compared to traditional programming languages. It's designed specifically for traders who need to code indicators and strategies without extensive programming experience.
Pine Script has evolved through five versions, with version 5 (released in 2021) adding features specifically for automation. The language uses indentation-based syntax similar to Python, making it more readable than bracket-heavy languages like JavaScript. For automation purposes, you're primarily working with three Pine Script capabilities: conditional logic to identify trading setups, the alert() function to trigger notifications, and variable placeholders that pass trade data to external platforms.
Most traders automating futures don't need advanced Pine Script knowledge. According to TradingView's documentation, approximately 70% of automated strategies use fewer than 100 lines of code, focusing on simple moving average crossovers, RSI thresholds, or breakout conditions. The automation component adds perhaps 5-10 lines to format the alert message properly.
Every Pine Script begins with a version declaration and indicator/strategy definition. These opening lines tell TradingView how to interpret your code and how to display results on your chart.
A minimal automation script structure looks like this: the version declaration (//@version=5), the indicator or strategy function that names your script and sets display properties, variable declarations for your indicators (like moving averages or RSI), conditional logic that defines your entry and exit rules, and finally the alert() function that formats the message sent to your webhook.
Strategy vs Indicator: In Pine Script, a "strategy" can generate hypothetical orders and appears in the Strategy Tester with performance metrics, while an "indicator" only displays visual elements on the chart. For automation testing, strategies provide better validation before going live.
The indicator() or strategy() function includes parameters like the script name, overlay setting (true to display on the price chart, false for a separate panel), and precision settings. For futures automation, you typically use strategy() during development to backtest logic, then may convert to indicator() for cleaner chart display once you've validated the approach.
Variable declarations calculate the technical indicators your strategy relies on. For example, a simple moving average crossover script would declare two SMA variables using ta.sma(). Pine Script includes built-in technical analysis functions under the "ta" namespace—ta.rsi() for RSI, ta.ema() for exponential moving averages, ta.atr() for Average True Range.
Alert conditions in Pine Script use boolean logic—statements that evaluate to either true or false. When a condition becomes true, the alert fires and sends your webhook message to the automation platform.
The basic structure uses comparison operators: greater than (>), less than (<), equal to (==), not equal to (!=), and logical operators like "and" and "or" to combine multiple conditions. For example, a long entry condition might check if a fast moving average crosses above a slow moving average AND the RSI is below 70 to avoid overbought entries.
Pine Script uses the crossover() and crossunder() functions to detect when one value crosses another, which is cleaner than manually tracking previous bar values. The ta.crossover(fastMA, slowMA) function returns true only on the specific bar where the fast MA crosses above the slow MA, not on every bar where it remains above.
Condition TypePine Script SyntaxWhen It TriggersCrossoverta.crossover(series1, series2)series1 crosses above series2Crossunderta.crossunder(series1, series2)series1 crosses below series2Greater thanrsi > 70Every bar where RSI exceeds 70Price breakoutclose > high[1]Close above previous bar's high
For automation, you typically want entry and exit conditions stored in separate boolean variables. This makes the code more readable and allows you to reference these conditions in both the strategy execution logic and the alert function. Name your conditions descriptively: longCondition, shortCondition, exitLong, exitShort.
The strategy.entry() and strategy.close() functions execute trades in the Strategy Tester when your conditions trigger. These functions also work with the alert system—when an entry executes in a strategy, TradingView can automatically generate an alert without additional coding if you configure "alert on order fills" when creating the alert.
The alert message is what gets sent to your automation platform's webhook URL when conditions trigger. This message must be formatted as JSON (JavaScript Object Notation) with specific fields your automation platform expects to parse correctly.
JSON Payload: A structured data format using key-value pairs that applications use to exchange information. Automation platforms parse JSON from TradingView alerts to extract trade parameters like symbol, action (buy/sell), and quantity.
A basic JSON alert message structure includes the ticker symbol, order action (buy or sell), and order type (market or limit). Advanced messages include position sizing based on account equity, stop loss and take profit levels calculated from ATR or fixed points, and order identifiers for tracking.
TradingView provides placeholder variables that auto-populate with real-time data when the alert fires. The most essential placeholders are: {{ticker}} for the symbol, {{close}} for the current closing price, {{time}} for the timestamp, and {{interval}} for the chart timeframe. For strategies, you get additional placeholders like {{strategy.order.action}} which automatically says "buy" or "sell" based on which order executed.
Here's a practical example for ES futures automation. The alert message might format as: {"ticker": "{{ticker}}", "action": "{{strategy.order.action}}", "quantity": 1, "order_type": "market"}. When the alert fires on an ES chart, {{ticker}} populates with "ES1!" (TradingView's continuous ES contract) and {{strategy.order.action}} becomes "buy" or "sell" depending on whether strategy.entry() triggered a long or short.
Platforms like ClearEdge Trading parse this JSON to execute the corresponding order with your connected futures broker. The webhook URL you get from your automation platform goes into the "Webhook URL" field when creating the alert in TradingView—this tells TradingView where to send the JSON message.
The Strategy Tester is Pine Script's built-in backtesting engine that shows how your automation logic would have performed historically. This testing phase is critical—it reveals whether your alert conditions trigger correctly and at reasonable frequencies before connecting to live broker execution.
When you add a strategy script to your chart, the Strategy Tester tab appears at the bottom of TradingView showing performance metrics: net profit, win rate, maximum drawdown, total trades, and profit factor. For automation validation, focus less on profitability metrics (backtesting has limitations) and more on whether the entry and exit logic behaves as expected.
Alert testing uses TradingView's alert creation interface. After adding your strategy to a chart, click the alarm clock icon and select your script from the "Condition" dropdown. The "Message" field should contain your JSON payload with placeholder variables. TradingView's alert log (bell icon in top-right) shows recently fired alerts, letting you verify the JSON populated correctly.
Before connecting alerts to live trading, use a webhook testing service like webhook.site to inspect the actual messages TradingView sends. Create an alert pointing to the webhook.site URL, let it trigger, then review the received payload to confirm formatting. This catches issues like missing commas in JSON or incorrect placeholder syntax that would cause broker API errors.
Paper trading is the final validation step. Most futures brokers offer simulated accounts that mirror live market conditions without real money. Connect your TradingView alerts to your automation platform using the sim account, run for several days or weeks, and verify executions match expectations. According to best practices from the TradingView automation guide, traders should paper trade any new strategy for at least 20-30 executions before live deployment.
No, but basic coding logic helps. Most automation strategies use simple if/then conditions and built-in indicator functions. TradingView's Pine Script documentation includes copy-paste templates for common setups like MA crossovers and RSI strategies that you can modify rather than writing from scratch.
Version 5 uses a clearer namespace system (ta.sma instead of sma, strategy.entry instead of just entry) and adds better alert customization options. All new scripts should use version 5, and TradingView provides a converter tool for upgrading v4 scripts.
Yes, if you use someone else's published strategy or indicator that already includes alert functionality. TradingView's community library has thousands of scripts, many with built-in alerts. You still need to understand how to configure the alert message properly for your automation platform.
Use TradingView's continuous contract symbols (ES1!, NQ1!, etc.) which automatically roll to the front month. Your automation platform should have settings to map the continuous symbol to the specific contract month you want to trade, or you can include contract month logic in your JSON message.
This usually happens when you use "alert.freq_all" in your alert function, which triggers on every bar where the condition remains true. For automation, use "alert.freq_once_per_bar_close" to trigger only when a bar closes with the condition met, preventing duplicate orders.
Pine Script for automation requires understanding three core components: conditional logic that defines your trading rules, the alert function that triggers when conditions are met, and JSON message formatting that communicates trade parameters to your broker. Most traders can learn these basics in a few days by modifying existing strategy templates rather than coding from scratch.
Start with TradingView's Strategy Tester to validate your logic on historical data, then paper trade with TradingView automation to confirm real-time execution works correctly. Only move to live trading after 20-30 successful paper trade executions demonstrate your Pine Script and alert setup function reliably.
Want to explore no-code automation options? ClearEdge Trading offers pre-built strategy templates that work with TradingView alerts without requiring custom Pine Script.
Disclaimer: This article is for educational and informational purposes only. It does not constitute trading advice, investment advice, or any recommendation to buy or sell futures contracts. ClearEdge Trading is a software platform that executes trades based on your predefined rules—it does not provide trading signals, strategies, or personalized recommendations.
Risk Warning: Futures trading involves substantial risk of loss and is not suitable for all investors. You could lose more than your initial investment. Past performance of any trading system, methodology, or strategy is not indicative of future results. Before trading futures, you should carefully consider your financial situation and risk tolerance. Only trade with capital you can afford to lose.
CFTC RULE 4.41: HYPOTHETICAL OR SIMULATED PERFORMANCE RESULTS HAVE CERTAIN LIMITATIONS. UNLIKE AN ACTUAL PERFORMANCE RECORD, SIMULATED RESULTS DO NOT REPRESENT ACTUAL TRADING. ALSO, SINCE THE TRADES HAVE NOT BEEN EXECUTED, THE RESULTS MAY HAVE UNDER-OR-OVER COMPENSATED FOR THE IMPACT, IF ANY, OF CERTAIN MARKET FACTORS, SUCH AS LACK OF LIQUIDITY.
By: ClearEdge Trading Team | About
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Block quote
Ordered list
Unordered list
Bold text
Emphasis
Superscript
Subscript
Every week, we break down real strategies from traders with 100+ years of combined experience, so you can skip the line and trade without emotion.
