Getting started with algorithmic trading doesn't have to be complicated. Pine Script, TradingView's native programming language, makes it surprisingly straightforward to develop and test your own trading strategies—even if you've never written code before.
In this guide, we'll walk through everything from basic concepts to building a complete trading strategy that you can actually backtest with real market data. No fluff, just practical steps to get you trading smarter.
Pine Script operates differently from traditional programming languages. Instead of running once, your code executes on every single candle in your chart—processing what's called "series data." Think of it like a film strip: each frame (candle) gets analyzed individually, building up the complete picture.
Here's what makes this unique: when you change your chart's timeframe, everything recalculates. A 30-minute moving average behaves completely differently from a 30-day one, and Pine Script handles this automatically based on your chart settings.
You'll work with two main script types. Indicators help you visualize market movements—drawing lines, patterns, and signals on your charts. Strategies go further by simulating actual trades, letting you backtest ideas before risking real money.
The free TradingView plan lets you run three indicators simultaneously. If you need more analytical firepower, paid plans bump this up—Pro allows five indicators, while Pro+ gives you ten along with advanced features like server-side alerts and multiple chart layouts.
When you're ready to level up your analysis and strategy development, 👉 explore TradingView's advanced charting features and premium tools that serious traders rely on daily.
Let's jump straight into code. Here's a simple moving average indicator that actually does something useful:
pinescript
//@version=5
indicator('First Pine Script', overlay=true)
fast = ta.sma(close, 24)
slow = ta.sma(close, 200)
plot(fast, color=color.new(color.blue, 0))
plot(slow, color=color.new(color.yellow, 0))
Breaking this down: the version declaration tells TradingView which Pine Script you're using. The indicator function names your script and sets overlay=true so lines appear directly on your price chart rather than in a separate panel.
We calculate two moving averages—a fast 24-period and slow 200-period—using the built-in sma() function. These look back at closing prices to compute averages. Finally, plot() draws blue and yellow lines on your chart.
Open the Pine Editor, paste this code, click "Add to Chart," and you'll see two lines tracking price movements. That's it—you've just created a functioning technical indicator.
Pine Script takes time series data, processes it through functions, and outputs strategies or indicators. Most functions you'll need are already built-in, saving you from reinventing the wheel.
Data sources include: open, high, low, close, volume, and time. Access previous values using bracket notation: close[1] gives you the prior candle's closing price.
Variables use familiar data types: int for whole numbers, float for decimals, bool for true/false, string for text, and color for visual styling (using hex codes like #FF003399).
Conditional logic uses indentation to define scope:
pinescript
if close >= open
doSomething()
You can chain conditions together for complex filtering:
pinescript
FilterOK = false
Filter1 = close > open
Filter2 = rising(volume, 1)
FilterOK := Filter1 and Filter2
For making your indicators user-friendly, input() functions let traders customize settings without touching code:
pinescript
myInput = input(title="Moving Average Length", type=input.int, defval=24)
Now for the interesting part—creating a strategy that actually enters and exits trades. We'll build a moving average crossover system that captures trending moves.
pinescript
//@version=5
strategy('Moving Average Strategy', overlay=true, initial_capital=1000, default_qty_value=100, default_qty_type=strategy.percent_of_equity)
fastEMA = ta.ema(close, 24)
slowEMA = ta.ema(close, 200)
goLongCondition1 = ta.crossover(fastEMA, slowEMA)
timePeriod = time >= timestamp(syminfo.timezone, 2020, 12, 15, 0, 0)
notInTrade = strategy.position_size <= 0
if goLongCondition1 and timePeriod and notInTrade
stopLoss = low * 0.97
takeProfit = high * 1.12
strategy.entry('long', strategy.long)
strategy.exit('exit', 'long', stop=stopLoss, limit=takeProfit)
plot(fastEMA, color=color.new(color.blue, 0))
plot(slowEMA, color=color.new(color.yellow, 0))
This strategy uses exponential moving averages (which react faster than simple ones) to spot trend changes. When the fast EMA crosses above the slow one, it signals potential upward momentum worth riding.
The timePeriod filter limits backtesting to recent bull market conditions—testing strategies across different market phases is crucial. We set a 3% stop-loss below the low and a 12% take-profit above the high to manage risk.
If you're developing more sophisticated strategies with multiple timeframes and indicators, 👉 TradingView's professional plan unlocks powerful backtesting capabilities that help refine your edge.
Copy the strategy into TradingView, select BTCUSD on a 1-hour timeframe, click "Add To Chart," then open the Strategy Tester tab. You'll see detailed performance metrics including net profit, Sharpe ratio, and maximum drawdown.
Our basic crossover strategy might show 35% returns—decent, but trailing a simple buy-and-hold approach. The chart reveals why: we're sitting out during strong uptrends, missing gains while getting whipsawed during choppy periods.
Here's how to improve it: Instead of waiting for specific crossovers, stay long whenever price trades above the 200-hour moving average. Add momentum filters by comparing exponential vs simple moving averages—the EMA weights recent data heavier, revealing current direction.
Replace fixed percentage stop-losses with Average True Range (ATR) for dynamic risk management that adapts to volatility. Here's the upgraded version:
pinescript
//@version=5
strategy('Enhanced MA Strategy', overlay=true, initial_capital=1000, default_qty_value=100, default_qty_type=strategy.percent_of_equity, commission_value=0.025)
fastEMA = ta.ema(close, 24)
fastSMA = ta.sma(close, 24)
slowEMA = ta.ema(close, 200)
atr = ta.atr(14)
goLongCondition1 = fastEMA > fastSMA
goLongCondition2 = fastEMA > slowEMA
exitCondition1 = fastEMA < fastSMA
exitCondition2 = close < slowEMA
notInTrade = strategy.position_size <= 0
timePeriod = time >= timestamp(syminfo.timezone, 2020, 12, 15, 0, 0)
if timePeriod and goLongCondition1 and goLongCondition2 and notInTrade
strategy.entry('long', strategy.long)
stopLoss = close - atr * 3
strategy.exit('exit', 'long', stop=stopLoss)
if exitCondition1 and exitCondition2
strategy.close(id='long')
plot(fastEMA, color=color.new(color.blue, 0))
plot(slowEMA, color=color.new(color.yellow, 0))
bgcolor(notInTrade ? color.red : color.green, transp=90)
This improved strategy returns 194%—capturing upside momentum while exiting before major crashes. The Sharpe ratio improves significantly because we're getting risk-adjusted returns by avoiding drawdowns. During sideways markets this gets chopped up, but in trending conditions it shines.
TradingView connects directly to brokers like Oanda, TradeStation, and Gemini for execution. But for serious algorithmic trading, you'll want more control than a browser-based platform provides.
The smart approach: migrate proven Pine Script strategies to Python or Node.js, then execute through official exchange APIs running on dedicated servers. This gives you redundancy, lower latency, and complete operational control.
For hedging long-term holdings, consider flipping the strategy to open short positions on perpetual futures when signals trigger. This lets you hedge spot holdings without moving all funds to exchanges—keeping most capital in cold storage while using leverage efficiently.
The key is treating Pine Script as your development environment where you test ideas rapidly, then productionizing winners with robust infrastructure behind them.
Pine Script removes the technical barriers to algorithmic trading. You don't need a computer science degree—just curiosity and willingness to test ideas systematically.
Start simple with basic indicators, understand how series data flows through your code, then gradually add complexity as strategies prove themselves in backtests. The TradingView community shares thousands of scripts worth studying—not to copy blindly, but to understand different approaches to common problems.
Remember: if someone's selling a "guaranteed profitable" strategy for $19/month, run away. Real edges are hard-won, carefully guarded, and constantly evolving. But Pine Script gives you the tools to discover your own.