Skip to main content

How to Build Your Own TradingView Strategy

· 10 min read
Pineify Team
Pine Script and AI trading workflow research team

A TradingView strategy is a set of automated rules written in Pine Script that simulates buying and selling on historical data. Instead of just drawing lines like an indicator, it places trades, moves stops, and reports performance in the Strategy Tester tab. I've used this approach to validate dozens of ideas without risking a dollar.

How to Make Your Own Strategy in TradingView

Before You Write Code: What to Decide First

Skipping this planning step is the #1 reason strategies fail. Take 10 minutes to get these four things straight.

What type of move are you trying to catch? Trend-following, mean reversion, or breakout? I mostly build trend-following systems for BTCUSD on the 4-hour chart. They're simpler to code and easier to validate.

What timeframe fits your schedule? If you can't stare at charts all day, don't pick a 5-minute timeframe. Start with daily or 4-hour. You'll get fewer signals but better quality.

Which signals will trigger your trades? Moving averages, RSI, MACD — pick 1 or 2. I've found that combining SMA crossover with an RSI filter (under 70 for longs, over 30 for shorts) catches most good entries without overloading the logic.

How will you protect your capital? This is non-negotiable. Decide position size, stop-loss %, and take-profit % before you write a single line. I haven't tested any strategy that survives without these three numbers defined upfront.

Setting Up Your Pine Script Environment

Open TradingView and find the "Pine Editor" tab at the bottom. That's your workspace. Replace the default code with this:

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

Two things happen here. The //@version=5 line tells TradingView you're using the latest Pine Script syntax. The strategy() line names your script and sets overlay=true, which plots signals directly on the price chart — way easier to debug than a separate pane.

Pineify Website

Writing the Strategy Code

1. Make Every Setting Adjustable

Hard-coding numbers is the fastest way to waste time. Use input() so you can tweak values from the Strategy Tester's settings panel:

fastLength = input.int(10, title="Fast SMA Length")
slowLength = input.int(30, title="Slow SMA Length")
stopLossPct = input.float(1.0, title="Stop Loss (%)")
takeProfitPct = input.float(2.0, title="Take Profit (%)")

Now you can test 5 different SMA lengths in 30 seconds instead of editing code each time.

2. Calculate Your Indicators

fastSMA = ta.sma(close, fastLength)
slowSMA = ta.sma(close, slowLength)
rsiValue = ta.rsi(close, 14)

These three lines define the raw material your entry logic will use. The SMA values smooth out price action; the RSI tells you if momentum supports the move.

3. Build Entry Rules With Why

longCondition  = ta.crossover(fastSMA, slowSMA) and rsiValue < 70
shortCondition = ta.crossunder(fastSMA, slowSMA) and rsiValue > 30

if (longCondition)
strategy.entry("Long", strategy.long)

if (shortCondition)
strategy.entry("Short", strategy.short)

Why this works: the SMA crossover catches trend direction, and the RSI filter keeps you from entering when the market is already stretched. The strategy.entry() function handles position management automatically — no need to manually close the opposite side.

4. Add Protective Exits

stopLevel  = strategy.position_avg_price * (1 - stopLossPct / 100)
profitLevel = strategy.position_avg_price * (1 + takeProfitPct / 100)

strategy.exit("Exit Long", from_entry="Long", stop=stopLevel, limit=profitLevel)
strategy.exit("Exit Short", from_entry="Short", stop=profitLevel, limit=stopLevel)

What can go wrong: if your stop is too tight (say 0.5%), normal market noise will hit it before your signal has time to play out. I use 1-2% depending on the asset's average true range. For more on visualizing exits, see our plotshape function reference.

5. Visualize Everything

plot(fastSMA, color=color.blue, title="Fast SMA")
plot(slowSMA, color=color.orange, title="Slow SMA")
plotshape(longCondition, title="Buy", style=shape.triangleup, location=location.belowbar, color=color.green)
plotshape(shortCondition, title="Sell", style=shape.triangledown, location=location.abovebar, color=color.red)

Seeing green and red triangles on your chart lets you catch logic bugs at a glance. If a buy signal fires when price is falling, you know something's wrong.

Backtesting: How Your Strategy Performs on Historical Data

Once your code is on the chart, open the "Strategy Tester" tab. It runs through every bar in your visible date range and builds a report.

The three numbers that matter most:

MetricWhat It Tells You
Net ProfitTotal gain or loss after all simulated trades.
Win RatePercentage of trades that were profitable. 40% is fine if winners are 2x the size of losers.
Maximum DrawdownBiggest peak-to-trough loss. Keep this under 20% if you want to sleep at night.

I've seen strategies with a 70% win rate blow up because the losing trades were massive. Don't fixate on win rate alone.

Fine-Tuning Without Over-Fitting

This is where most people go wrong. You want the strategy to look good, but optimizing too hard on past data guarantees failure on future data.

  1. Adjust one parameter at a time in the Inputs tab. Change the SMA length, run the backtest, note the result. Then change the next one. I keep a spreadsheet for this.
  2. Premium users can enable Bar Magnifier (use_bar_magnifier=true) for intra-bar fills. It helps, but it's not a magic fix. I haven't tested it enough to say it changes outcomes consistently.
  3. Check the List of Trades tab. Look for long losing streaks. If your strategy had a 12-trade losing streak in 2022, you need to know that before you go live.

Common Mistakes When Building TradingView Strategies

Over-fitting to past data. You're not building a perfect backtest — you're building a system that works on unseen data. Forward-test every strategy for at least 2 months before trusting it with real money. I learned this the hard way after a strategy that backtested at 300% returns lost 40% in its first month live.

Ignoring transaction costs. Set commission to 0.1% and slippage to 2 ticks in the Strategy Tester Properties. Your backtest numbers will drop, but they'll be honest. A strategy that only looks good without costs isn't worth running.

Too many indicators. Three indicators can give you 21 different crossover combinations. Stick to 1-2. In my experience, adding a third indicator never improved results — it just made debugging harder.

PitfallWhy It's a ProblemThe Fix
Over-fitting to past dataGreat backtest, terrible live results.Forward-test on unseen data for 2+ months.
Ignoring slippage & commissionUnrealistically high profit projections.Add 0.1% commission and 1-2 tick slippage.
Too many indicatorsConflicting signals, hard to debug.Use 1-2 indicators maximum.

Getting Started Next

Open the Pine Editor and write the starter code. Then swap in your own entry rules. Our Pineify backtest guide covers advanced scenarios like multi-timeframe confirmation and walk-forward testing. You can also check out the TradingView Pine Script strategy documentation for function references beyond what we covered here.

Pine Script Questions I Get Asked Most

What's the real difference between a TradingView strategy and an indicator?

An indicator only draws visual elements (lines, shapes) on a chart. A strategy uses the strategy() function and simulates real trades — entries, exits, stop-losses, and take-profits — then reports performance results in the Strategy Tester tab.

How do I add commission and slippage to my backtest in TradingView?

Open the Strategy Tester, click the gear icon (Properties), and fill in the Commission and Slippage fields. Setting realistic values (e.g., 0.1% commission and 1-2 tick slippage) gives you a far more accurate picture of live performance.

Can I use multiple timeframes in a single Pine Script strategy?

Yes. Use the request.security() function to fetch OHLCV data or indicator values from any symbol and timeframe. For example, you can run your strategy on a 1-hour chart while referencing the daily RSI for confirmation signals.

What does Maximum Drawdown actually tell me?

Maximum Drawdown shows the largest peak-to-trough decline in your simulated account equity. It represents the worst losing streak your strategy would have experienced. A lower drawdown generally means a less risky, more recoverable strategy.

How do I avoid over-fitting my strategy to past data?

Avoid tweaking parameters purely to maximize past performance. Instead, choose settings that make logical sense, keep the number of indicators small, and always forward-test your strategy on out-of-sample data or via paper trading before using real capital.

When should I use the Bar Magnifier feature?

Bar Magnifier (available on Premium plans) lets the Strategy Tester simulate intra-bar order fills using higher-resolution data. Enable it by adding use_bar_magnifier=true inside your strategy() call to get more accurate backtest results.