Start investing in Bitcoin with Pix, in a few minutesSponsoredOpen free account
Price chart with simple and exponential moving average overlapping
Trading

Pine Script: Tutorial of Indicators and Strategies in TradingView

Pine Script Tutorial V6: How to open the Pine Editor, create an alert indicator and a crossover strategy with stop, costs and backtest.

Image: Alex Kofman, Public Domain, via Wikimedia Commons

By Boletim Bitcoin newsroom

. 6 min reading.

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=6 and a statement indicator() or strategy(). 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 account

How to open the Pine Editor and create the first script?

  1. Open a chartChoose an asset, for example BTCUSDT, and a chart time.
  2. Click on Pine EditorThe tab is at the bottom of the chart.
  3. Create a new scriptIn the menu to the left of the script name, choose Create a new indicator or strategy.
  4. Paste the code and saveThe script is saved in your account, visible only to you.
  5. 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:

StretchWhat are you doing
//@version=6Defines 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.

Price chart with MACD indicator 12, 26, 9 and its histogram on the bottom panel 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.1 charges 0.1% by order and slippage = 2 It 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.exit Creates 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?

ChangePractical impact
Parameter when removedConditions of order go within if
100% standard marginThe strategy does not open a position it cannot pay; There may be a sales margin call
bool do not accept naUndefined conditions turn false
Dynamic requests by defaultrequest.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 with lookahead activated;
  • Draw pivots and signs on the candle where they occurred before they were confirmed.
Tip: For signs that do not repaint, base the decision on closed candlesticks (for example, using 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:

  1. Brokers integrated with TradingView, manually operated by the trading panel.
  2. 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

  1. TradingView: Welcome to Pine Script v6
  2. TradingView: Pine Script docs, First indicator
  3. TradingView: Pine Script docs, Strategies
  4. TradingView: Migration to Pine Script V6
  5. TradingView: Pine Script v6 Reference Manual
  6. TradingView: Pine Script docs, Repainting
  7. TradingView: About webhooks
  • Pine Script
  • TradingView
  • Pine Script v6
  • indicator
  • strategy
  • backtest
  • alerts

This content is informative and is not an investment recommendation. found an error? Write to contato@boletimbitcoin.com.

Read also

Start in crypto today

Open your free account, deposit with PIX and access Spot, Futures, Copy Trading and Trading Robots in one app.

  • Easy deposits
  • Copy trading
  • Grid and DCA bots
  • All-in-one app
Advertising. Crypto involves risk, invest responsibly.
Create free account