Pine Script is the TradingView language to create indicators, backtest strategies and custom alerts. You write the code in the Pine Editor, at the footer of the chart, click on “Add to Graph” and the script runs on the TradingView servers, without installing anything. In this tutorial you create an alert with an alert and a complete strategy in Pine Script V6, the current version.
In short: Every script starts with
//@version=6and a statementindicator()orstrategy(). The code runs once per candlestick, from the oldest to the most recent. Indicators draw and alert; Strategies simulate orders and generate backtest report. Set up commission and slippage in the strategy, or the result will be too optimistic.
What can you do with Pine Script?
- Own indicators: Mediums, oscillators, levels, information panels.
- Backtest strategies: Inputs, outputs, stop and simulated target in history.
- Alerts: Notices on mobile, email or webhook when a condition happens.
- Libraries: Reusable functions published for other scripts.
According to official documentation, the community has already published more than 150,000 scripts, about half with open source. Reading code from good public scripts is a great way to learn. If you are still getting to know the platform, start with TradingView Guide.
Everything in one appSpot, futures, copy trading and bots. Free sign-up in minutes.Create accountHow to open the Pine Editor and create the first script?
- Open a chartChoose an asset, for example BTCUSDT, and a chart time.
- Click on Pine EditorThe tab is at the bottom of the chart.
- Create a new scriptIn the menu to the left of the script name, choose Create a new indicator or strategy.
- Paste the code and saveThe script is saved in your account, visible only to you.
- Add to chartClick "Add to Graph" and adjust the entries in the gear.
The step by step follows the script of the first documentation indicator.
Example 1: Moving average indicator with alert
//@version=6
indicator("Média com alerta", overlay = true)
periodo = input.int(20, "Período", minval = 1)
media = ta.sma(close, periodo)
acima = close > media
plot(media, "SMA", color = acima ? color.green : color.red, linewidth = 2)
cruzouCima = ta.crossover(close, media)
alertcondition(cruzouCima, "Preço cruzou a média", "O preço cruzou acima da SMA")
Line by line:
| Stretch | What are you doing |
|---|---|
//@version=6 | Defines the version of the language (mandatory) |
indicator(..., overlay = true) | Declares a drawn indicator on the price |
input.int(20, ...) | Creates an editable field in the settings |
ta.sma(close, periodo) | Simple moving average locks |
plot(...) | Draw line, green above price and red below |
alertcondition(...) | Provides the condition in the alerts window |
Change ta.sma by ta.ema to use the exponential average. The difference between the two is in the moving averages. Other useful namespace functions ta: ta.rsi (IFR) ta.macd, ta.bb (Bollinger) and ta.atr.
Indicators such as MACD, which are on a panel below price, are created in PINE with Overlay = False and the TA.MACD function. Credit: Kevin Ryde, CC BY-SA 3.0 license, via Wikimedia Commons.
Example 2: Means crossing strategy with stop and target
//@version=6
strategy("Cruzamento de médias v6", overlay = true, initial_capital = 10000,
default_qty_type = strategy.percent_of_equity, default_qty_value = 10,
commission_type = strategy.commission.percent, commission_value = 0.1,
slippage = 2)
rapidaLen = input.int(9, "Média rápida", minval = 1)
lentaLen = input.int(21, "Média lenta", minval = 2)
stopPct = input.float(2.0, "Stop (%)", minval = 0.1) / 100
alvoPct = input.float(4.0, "Alvo (%)", minval = 0.1) / 100
rapida = ta.ema(close, rapidaLen)
lenta = ta.ema(close, lentaLen)
plot(rapida, "Rápida", color = color.teal)
plot(lenta, "Lenta", color = color.orange)
compra = ta.crossover(rapida, lenta)
saida = ta.crossunder(rapida, lenta)
if compra and strategy.position_size == 0
strategy.entry("Long", strategy.long)
if strategy.position_size > 0
preco = strategy.position_avg_price
strategy.exit("Stop/Alvo", "Long", stop = preco * (1 - stopPct), limit = preco * (1 + alvoPct))
if saida
strategy.close("Long", comment = "Cruzou para baixo")
plotshape(compra, title = "Compra", style = shape.triangleup, location = location.belowbar, color = color.green, size = size.small)
What to observe:
- Declaration costs:
commission_value = 0.1charges 0.1% by order andslippage = 2It worsens each run by 2 ticks. Without it, the backtesting mind. - Position size: 10% of the capital per down payment (
strategy.percent_of_equity). - STOP AND TARGET:
strategy.exitCreates exit orders from the average position price. - Realistic execution: By default, the market order is filled in the next available tick, usually the opening of the candlestick next to the signal, according to the Strategy Documentation.
When adding to the chart, open the Strategy Tester. The report brings performance metrics, drawdown and the list of operations, which can be exported. How to read these numbers is in backtest.
What has changed in Pine Script V6?
| Change | Practical impact |
|---|---|
Parameter when removed | Conditions of order go within if |
| 100% standard margin | The strategy does not open a position it cannot pay; There may be a sales margin call |
bool do not accept na | Undefined conditions turn false |
| Dynamic requests by default | request.security() Can run inside loops and conditionals |
Source: Migration Guide to V6. Old scripts can be converted by the editor himself, but review the result. The complete list of functions is in the V6 Reference Manual.
Repainting: The error that makes the backtest lie
Repainting happens when the script calculates one way in history and another in real time. common causes, according to the Repainting documentation:
- Use still open candlestick values, which change until closing;
- Search for larger chart time data with
request.security()without waiting for confirmation or withlookaheadactivated; - Draw pivots and signs on the candle where they occurred before they were confirmed.
close[1] or checking barstate.isconfirmed). The signal arrives a candlestick later, but it is the same in the historic and live.Repainting is a relative of the overfitting: Both create results that are not repeated in the real account.
From Pine Script to Actual Operation
A strategy in TradingView simulates orders. To actually run, there are two paths:
- Brokers integrated with TradingView, manually operated by the trading panel.
- Alerts with webhook: The alert sends a message to a server of yours, which forwards the order to the broker through the API. TradingView only accepts webhooks on ports 80 and 443, requires two-factor authentication, and cancels the request if the server does not respond within three seconds, as per the Webhooks support page.
The second path requires safe care of the keys, subject of the guide of Crypto brokerage API. For Forex and CFDs, many people rewrite the strategy in MQL5 And it runs on MetaTrader 5.
The official TradingView channel in Brazil has a series in Portuguese on the programming of indicators; The first episode is a good addition to this tutorial.
Next steps
- Modify Example 2 to use Stop by ATR instead of fixed percentage.
- Testing on BTC, ETH and a pair of Forex: A robust idea doesn't depend on a single asset.
- Separate a recent period to validate without optimizing.
- Define risk per operation based on stop; vide Risk Management in Trading.
For the complete script, from the idea to the robot connected, read How to create a trading robot from scratch.
Informational content, not investment advice.
Frequently asked questions
What is Pine Script?
It is the TradingView programming language to create indicators, backtest strategies and alerts. The scripts run on the TradingView servers, without installing anything.
Is Pine Script hard to learn?
It is one of the easiest languages for trading. A simple indicator fits into five lines. The biggest challenge is to understand how the script runs candlesticks and avoid repainting.
What is the difference between Indicator and Strategy in Pine Script?
A indicator only calculates and draws on the graph (and can generate alerts). A Strategy also simulates buy and sell orders and generates backtest report with profit, drawdown and operations list.
Pine Script executes orders on the brokerage?
Not directly like a MetaTrader robot. The strategy simulates orders; To actually operate, the integration of TradingView's own brokers or webhook alerts sent to an external system is used.
What is the current version of Pine Script?
Version 6. It removed the when parameter from the order functions, passed the standard margin of the strategies to 100% and eliminated the value in Boolean variables.
References
This content is informative and is not an investment recommendation. found an error? Write to contato@boletimbitcoin.com.