# Pine Script Basics

> Learn Pine Script, TradingView's language for custom indicators, strategies and alerts. Covers series, plots, inputs, a crossover strategy and common pitfalls.

Source: https://learn.tradelabsai.com/programming/pine-script-basics/  
Track: Programming and Data · Level: Intermediate · Updated: 2026-10-03  
Publisher: TradeLabs AI (https://tradelabsai.com). Education, not financial advice.  
Cite as: TradeLabs Learn, "Pine Script Basics", https://learn.tradelabsai.com/programming/pine-script-basics/

Pine Script is the programming language built into TradingView. It lets traders write their own indicators, test simple strategies directly on charts and create alerts that fire when conditions are met. Pine is designed for one job, calculating values bar by bar on price data, so it is much simpler than a general language like Python. A useful indicator can be just a few lines. Its limits are just as clear: it runs only on TradingView, cannot place orders directly with most brokers and its built in backtester makes simplifying assumptions.

## How Pine Script thinks

Pine runs your script once for every bar on the chart, from the oldest to the newest. Variables like `close` are series: they hold a value for every bar, and `close[1]` refers to the previous bar's close. On the live bar, the script recalculates on each price update until the bar closes.

| Concept | Meaning |
|---|---|
| Series | A value per bar, such as close, high or an indicator |
| History operator `[n]` | The value n bars ago |
| `indicator()` | Declares an indicator script |
| `strategy()` | Declares a strategy script with simulated trades |
| `input.*()` | Settings the user can change |
| `plot()` | Draws a line or shape on the chart |

## A first indicator

```
//@version=6
indicator("Two moving averages", overlay=true)
fastLen = input.int(20, "Fast length")
slowLen = input.int(50, "Slow length")
fast = ta.sma(close, fastLen)
slow = ta.sma(close, slowLen)
plot(fast, "Fast", color=color.teal)
plot(slow, "Slow", color=color.orange)
```

The `ta` namespace holds built in technical analysis functions such as `ta.sma`, `ta.ema`, `ta.rsi` and `ta.atr`. See [Moving Averages Explained](https://learn.tradelabsai.com/indicators/moving-averages-explained/) and [RSI (Relative Strength Index)](https://learn.tradelabsai.com/indicators/rsi/).

## A simple strategy

```
//@version=6
strategy("SMA crossover", overlay=true, initial_capital=10000,
     commission_type=strategy.commission.percent, commission_value=0.05)
fast = ta.sma(close, 20)
slow = ta.sma(close, 50)
if ta.crossover(fast, slow)
    strategy.entry("Long", strategy.long)
if ta.crossunder(fast, slow)
    strategy.close("Long")
```

By default, strategy orders are evaluated at the bar close and filled at the next bar's open, which avoids the most obvious look ahead error. Set commissions and slippage in the declaration so results are not flattering. See [Costs and Slippage in Backtests](https://learn.tradelabsai.com/research/costs-and-slippage-in-backtests/).

## Adding alerts

```
alertcondition(ta.crossover(fast, slow), "Bullish cross", "Fast SMA crossed above slow SMA")
```

Alerts can notify you by app, email or webhook. Webhooks can forward signals to an execution service or your own server. See [Alerts and Webhooks](https://learn.tradelabsai.com/programming/alerts-and-webhooks/).

**Example: Repainting from higher timeframe data**
A trader builds a 5 minute strategy that filters trades using the daily close via `request.security`. The backtest looks excellent. The problem: on historical bars, the script saw each day's final close, but in real time the daily close is not known until the day ends. The fix is to request the previous completed daily value, for example by using `close[1]` inside the request with lookahead turned on, so historical and live behaviour match. Backtest results drop to a realistic level. See [Look-Ahead Bias](https://learn.tradelabsai.com/research/look-ahead-bias/).

## Repainting

A script repaints when its historical signals differ from what it would have shown in real time. Common causes:

- **Higher timeframe data** used without proper offsetting.
- **Signals on the unfinished live bar** that disappear before close.
- **Functions that look forward,** such as some pivot calculations that confirm only after later bars.

Repainting indicators make charts look far more accurate than they ever were live. Check by watching an indicator in real time or using bar replay. See [TradingView](https://learn.tradelabsai.com/industry/tradingview/).

## Limits of Pine Script

| Limit | Implication |
|---|---|
| Runs only on TradingView | Not portable to other platforms |
| Simplified fills | Intrabar paths are approximated |
| Limited data access | No arbitrary external data sources |
| Execution through alerts | Automating trades needs a webhook bridge or supported broker |

For research across many symbols or complex portfolios, Python is more flexible. See [Python for Trading](https://learn.tradelabsai.com/programming/python-for-trading/).

## Frequently asked questions

### What is Pine Script used for?

Writing custom indicators, testing simple strategies and creating alerts on TradingView charts.

### Is Pine Script hard to learn?

It is one of the easier trading languages, with simple syntax and built in indicator functions, though avoiding repainting takes care.

### Can Pine Script place real trades?

Not directly in most cases. Alerts can send webhooks to services or your own code that place orders, and some brokers integrate with TradingView for chart trading.

Next, put the pieces together in [Building Trading Bots](https://learn.tradelabsai.com/programming/building-trading-bots/).

## Continue learning

- Next lesson: [Building Trading Bots](https://learn.tradelabsai.com/programming/building-trading-bots/)
- Previous lesson: [Database Design for Market Data](https://learn.tradelabsai.com/programming/database-design-for-market-data/)
- Related: [Database Design for Market Data](https://learn.tradelabsai.com/programming/database-design-for-market-data/): How to design database tables for bars, ticks, symbols, orders and fills. Learn keys, indexes, partitioning, data types and how to avoid common design mistakes.
- Related: [TradingView](https://learn.tradelabsai.com/industry/tradingview/): TradingView is a browser based charting and social platform covering stocks, crypto, forex and futures. Learn its features, Pine Script, alerts, plans and limits.
- Related: [Alerts and Webhooks](https://learn.tradelabsai.com/programming/alerts-and-webhooks/): How price alerts and webhooks work, how to send TradingView alerts to your own server or a chat channel, and how to secure webhook endpoints against fake signals.
- Related: [Moving Averages Explained](https://learn.tradelabsai.com/indicators/moving-averages-explained/): Moving averages smooth price to show the trend. Learn SMA vs EMA, popular settings like the 20, 50 and 200 day, crossovers, dynamic support and common mistakes.
- Related: [Backtesting Methodology](https://learn.tradelabsai.com/research/backtesting-methodology/): A backtest simulates a strategy on historical data. Learn the steps, the key performance metrics, common biases and a checklist for backtests you can trust.
- Related: [Building Trading Bots](https://learn.tradelabsai.com/programming/building-trading-bots/): How to build a trading bot that is safe to run: the main components, an event loop, state and position tracking, risk checks, logging and a staged path to live.
