🔥Black Friday Sale: Get 25% OFF Premium with code BLACKFRIDAY — Sale ends December 1st!🎉
Pine Script Tutorial for Beginners — Build Your First TradingView Strategy in 10 Minutes

Pine Script Tutorial for Beginners — Build Your First TradingView Strategy in 10 Minutes

By HorizonAI Team

Want to automate your trading ideas on TradingView but don't know where to start? This beginner-friendly tutorial will teach you Pine Script fundamentals by building a real, working trading strategy—no prior coding experience required.

By the end of this guide, you'll have a functional strategy running on your TradingView chart with entry signals, exits, and performance metrics.

What is Pine Script?

Pine Script is TradingView's programming language for creating:

  • Custom indicators (RSI, MACD, your own creations)
  • Trading strategies (automated backtesting with entry/exit signals)
  • Alerts (notifications when conditions are met)

Why Pine Script?

  • ✅ Easier than Python or JavaScript
  • ✅ Built into TradingView (no installation needed)
  • ✅ Instant visual feedback on charts
  • ✅ Huge community (10M+ TradingView users)

Prerequisites

  1. A TradingView account (free or paid)
  2. Basic understanding of trading concepts (moving averages, support/resistance)
  3. 10 minutes of focused time

That's it. Let's code.

Step 1: Open the Pine Editor

  1. Go to TradingView.com and open any chart
  2. At the bottom of the page, click "Pine Editor"
  3. You'll see a code editor panel with sample code

Delete everything in the editor. We're starting fresh.

Step 2: Your First Line of Code

Every Pine Script starts with a version declaration and script type. Type this:

//@version=5
strategy("My First Strategy", overlay=true)

What this means:

  • //@version=5 - Use Pine Script version 5 (still widely used; Pine Script v6 is also available)
  • strategy() - This is a strategy (not an indicator)
  • "My First Strategy" - The name that appears on your chart
  • overlay=true - Draw on the price chart (not in a separate pane)

Click "Add to Chart" (top right). You'll see your strategy name appear on the chart—nothing visual yet, but it's working!

Step 3: Calculate a Moving Average

Let's add a simple 50-period moving average:

//@version=5
strategy("My First Strategy", overlay=true)

// Calculate 50-period simple moving average
sma50 = ta.sma(close, 50)

// Draw it on the chart
plot(sma50, color=color.blue, linewidth=2, title="50 SMA")

What this does:

  • ta.sma(close, 50) - Calculates Simple Moving Average of closing prices over 50 bars
  • plot() - Draws a blue line on the chart

Click "Add to Chart" again. You'll see a blue line following the 50-period average price.

Congrats! You just wrote your first indicator.

Step 4: Add Entry Logic (Buy Signal)

Now let's make it actually trade. We'll buy when price crosses above the 50 SMA:

//@version=5
strategy("My First Strategy", overlay=true)

// Calculate 50-period moving average
sma50 = ta.sma(close, 50)
plot(sma50, color=color.blue, linewidth=2, title="50 SMA")

// Entry condition: price crosses above SMA
longCondition = ta.crossover(close, sma50)

// Execute trade when condition is true
if longCondition
    strategy.entry("Long", strategy.long)

What this does:

  • ta.crossover(close, sma50) - Returns true when close crosses above SMA
  • strategy.entry("Long", strategy.long) - Opens a long position

Click "Add to Chart". You'll see green arrows where the strategy would have bought!

Step 5: Add Exit Logic (Sell Signal)

Let's close positions when price crosses back below the SMA:

//@version=5
strategy("My First Strategy", overlay=true)

// Calculate moving average
sma50 = ta.sma(close, 50)
plot(sma50, color=color.blue, linewidth=2, title="50 SMA")

// Entry: price crosses above SMA
longCondition = ta.crossover(close, sma50)
if longCondition
    strategy.entry("Long", strategy.long)

// Exit: price crosses below SMA
exitCondition = ta.crossunder(close, sma50)
if exitCondition
    strategy.close("Long")

New function:

  • ta.crossunder(close, sma50) - Returns true when close crosses below SMA
  • strategy.close("Long") - Closes the open long position

Now you'll see red arrows where positions exit!

Step 6: Add Visual Signals (Optional but Cool)

Let's make entry/exit signals more obvious:

//@version=5
strategy("My First Strategy", overlay=true)

// Calculate moving average
sma50 = ta.sma(close, 50)
plot(sma50, color=color.blue, linewidth=2, title="50 SMA")

// Entry condition
longCondition = ta.crossover(close, sma50)
if longCondition
    strategy.entry("Long", strategy.long)

// Exit condition
exitCondition = ta.crossunder(close, sma50)
if exitCondition
    strategy.close("Long")

// Visual signals
plotshape(longCondition, style=shape.triangleup, location=location.belowbar, 
          color=color.green, size=size.small, title="Buy Signal")
plotshape(exitCondition, style=shape.triangledown, location=location.abovebar, 
          color=color.red, size=size.small, title="Sell Signal")

What plotshape() does:

  • Draws shapes (triangles) on the chart
  • location.belowbar - Draw below candles (for buy signals)
  • location.abovebar - Draw above candles (for sell signals)

Step 7: View Your Backtest Results

Click the "Strategy Tester" tab (next to Pine Editor). You'll see:

  • Net Profit - Total profit/loss
  • Total Trades - How many trades were executed
  • Win Rate - Percentage of winning trades
  • Profit Factor - Gross profit ÷ Gross loss
  • Max Drawdown - Largest peak-to-valley loss

Reality check: This simple strategy probably won't be profitable yet. That's okay—you're learning the process!

Making It Better: Add a Second Moving Average

Let's create a classic "Golden Cross" strategy (50 SMA crosses 200 SMA):

//@version=5
strategy("Golden Cross Strategy", overlay=true)

// Calculate two moving averages
sma50 = ta.sma(close, 50)
sma200 = ta.sma(close, 200)

// Plot them
plot(sma50, color=color.blue, linewidth=2, title="50 SMA")
plot(sma200, color=color.red, linewidth=2, title="200 SMA")

// Entry: 50 SMA crosses above 200 SMA (bullish)
longCondition = ta.crossover(sma50, sma200)
if longCondition
    strategy.entry("Long", strategy.long)

// Exit: 50 SMA crosses below 200 SMA (bearish)
exitCondition = ta.crossunder(sma50, sma200)
if exitCondition
    strategy.close("Long")

// Visual signals
plotshape(longCondition, style=shape.triangleup, location=location.belowbar, 
          color=color.green, size=size.normal)
plotshape(exitCondition, style=shape.triangledown, location=location.abovebar, 
          color=color.red, size=size.normal)

This strategy only trades when the fast SMA crosses the slow SMA—filtering out choppy markets.

Add Stop Loss and Take Profit

Real trading needs risk management. Let's add a 2% stop loss and 4% take profit:

//@version=5
strategy("Golden Cross with Risk Management", overlay=true)

// Inputs (adjustable in settings)
stopLossPercent = input.float(2.0, title="Stop Loss %", minval=0.1)
takeProfitPercent = input.float(4.0, title="Take Profit %", minval=0.1)

// Calculate moving averages
sma50 = ta.sma(close, 50)
sma200 = ta.sma(close, 200)

plot(sma50, color=color.blue, linewidth=2)
plot(sma200, color=color.red, linewidth=2)

// Entry condition
longCondition = ta.crossover(sma50, sma200)

if longCondition
    // Calculate stop loss and take profit levels
    stopLoss = close * (1 - stopLossPercent / 100)
    takeProfit = close * (1 + takeProfitPercent / 100)
    
    // Enter with stop loss and take profit
    strategy.entry("Long", strategy.long)
    strategy.exit("Exit", "Long", stop=stopLoss, limit=takeProfit)

// Exit on death cross
exitCondition = ta.crossunder(sma50, sma200)
if exitCondition
    strategy.close("Long")

plotshape(longCondition, style=shape.triangleup, location=location.belowbar, color=color.green)
plotshape(exitCondition, style=shape.triangledown, location=location.abovebar, color=color.red)

New concepts:

  • input.float() - Creates adjustable settings (you can change stop loss % without editing code)
  • strategy.exit() - Sets stop loss and take profit levels
  • stop= - Stop loss price
  • limit= - Take profit price

Now open Settings (gear icon on chart) → Inputs to adjust your stop loss and take profit percentages!

Common Pine Script Functions Reference

Here are the most useful functions you'll use constantly:

Price Data

  • close - Closing price of current bar
  • open - Opening price
  • high - Highest price
  • low - Lowest price
  • volume - Trading volume

Indicators

  • ta.sma(source, length) - Simple Moving Average
  • ta.ema(source, length) - Exponential Moving Average
  • ta.rsi(source, length) - Relative Strength Index
  • ta.macd(...) - MACD indicator
  • ta.atr(length) - Average True Range (volatility)

Conditions

  • ta.crossover(a, b) - True when a crosses above b
  • ta.crossunder(a, b) - True when a crosses below b
  • ta.highest(source, length) - Highest value in last N bars
  • ta.lowest(source, length) - Lowest value in last N bars

Strategy Orders

  • strategy.entry(id, direction) - Open position
  • strategy.close(id) - Close position
  • strategy.exit(id, from_entry, stop, limit) - Set stop/take profit

Next Steps: Practice Exercises

Try building these strategies on your own:

1. RSI Oversold/Overbought

  • Buy when RSI < 30
  • Sell when RSI > 70

2. Bollinger Band Bounce

  • Buy when price touches lower Bollinger Band
  • Sell when price touches upper band

3. Breakout Strategy

  • Buy when price breaks above 20-day high
  • Sell when price breaks below 20-day low

Hint: Use ta.rsi(), ta.bb(), ta.highest(), and ta.lowest()

Skip the Learning Curve: Use AI to Generate Pine Script

Learning to code is valuable, but if you want to test ideas fast, use HorizonAI to generate Pine Script from plain English.

Example prompts:

  • "Create a Pine Script strategy using 9/21 EMA crossover with ATR-based stop loss"
  • "Build a Bollinger Band mean reversion strategy with RSI confirmation"
  • "Convert this: buy when MACD crosses above signal line and volume is above average"

HorizonAI generates clean, validated Pine Script v6 code instantly—no syntax errors, no debugging.

Generate your first strategy free →

Common Beginner Mistakes to Avoid

❌ Don't: Use repainting indicators

// ❌ BAD - repaints (changes past signals)
if close &gt; high[1]

✅ Do: Wait for bar confirmation

// ✅ GOOD - only triggers on confirmed bars
if barstate.isconfirmed and close &gt; high[1]

❌ Don't: Ignore risk management

Never trade without stop losses. One bad trade can wipe out 10 good ones.

✅ Do: Always set stops

Use strategy.exit() with stop loss on every trade.

❌ Don't: Over-optimize

Testing 50 parameter combinations until one "works" = overfitting = will fail live.

✅ Do: Keep it simple

3-5 adjustable parameters max. Simple strategies are more robust.

Resources to Learn More

  • TradingView Pine Script Docs: tv/pine-script-docs
  • TradingView Public Library: Browse 100,000+ scripts to learn
  • Pine Script Discord: Community help and examples
  • HorizonAI Blog: More tutorials and strategy guides

Final Thoughts

You just wrote your first Pine Script trading strategy! Here's what you learned:

✅ Pine Script basics (syntax, structure, functions)
✅ Calculating indicators (moving averages)
✅ Creating entry/exit logic (crossovers)
✅ Adding risk management (stop loss, take profit)
✅ Visualizing signals (plotshape)
✅ Reading backtest results (Strategy Tester)

Next challenge: Take a strategy you trade manually and try coding it in Pine Script. Start simple, test on historical data, then paper trade before going live.

Have questions? Join our Discord community and share your first strategy!