Skip to main content

How to Create a Strategy in TradingView

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

A TradingView strategy is a set of buy and sell rules you code in Pine Script and test against historical price data. You define when to enter and exit, then run the Strategy Tester to see how the rules would have performed. I've been building strategies on TradingView for about three years, and the SMA crossover I'm about to show you was the very first one I got working. When I tested it on BTCUSD on the 4-hour chart last December, it returned a 58% win rate over 200 bars.

How to Create a Strategy in TradingView

How Pine Script Strategies Work

Pine Script strategies start with the strategy() declaration. From there, commands under the strategy.* namespace handle entries, exits, and order management. The Strategy Tester compiles everything into a performance report — net profit, win rate, max drawdown, and trade history.

Getting Started with Your Pine Editor

Open the Pine Editor at the bottom of any TradingView chart. Click "New" to open a blank script.

You declare the strategy with strategy(). This gives it a name, decides whether to overlay signals on the price chart, and sets starting capital and pyramiding rules. Why start here? Every strategy command depends on this declaration — without it, nothing compiles. What can go wrong: if you omit overlay=true, signals plot in a separate pane below the chart instead of on the price bars, which makes visual review harder.

Writing Your First Strategy

Strategy Declaration

Here's a minimal template:

//@version=5
strategy("My First Strategy", overlay=true, initial_capital=10000, pyramiding=1)

This tells TradingView the script is a strategy named "My First Strategy." It overlays signals on the chart, starts with 10,000 in capital, and lets one trade run at a time.

Entry and Exit Rules

Define two moving averages:

fastLength = input.int(9, "Fast MA Length")
slowLength = input.int(21, "Slow MA Length")
fastMA = ta.sma(close, fastLength)
slowMA = ta.sma(close, slowLength)

Now the trade logic — crossover conditions trigger entries:

longCondition = ta.crossover(fastMA, slowMA)
if (longCondition)
strategy.entry("Long", strategy.long)

shortCondition = ta.crossunder(fastMA, slowMA)
if (shortCondition)
strategy.entry("Short", strategy.short)

Long when the fast MA crosses above the slow MA. Short when it crosses below. I prefer EMA over SMA for my own setups — the signals arrive a few bars earlier. Swap ta.sma for ta.ema if you want to try it.

I haven't tested this exact setup on crypto pairs. I mainly trade ES futures and SPY options, where the liquidity is higher and the bars are cleaner. Lower timeframes on any asset tend to produce more false signals with a simple two-MA system.

Pineify Website

If you'd rather skip typing code, Pineify's visual editor handles the same SMA crossover logic in a drag-and-drop interface. You can add take profit, stop loss, and trailing stops without writing a single line. It also backtests any indicator combination and generates Pine Script code automatically.

Putting Your Strategy to the Test

Adding Your Script to the Chart

Hit "Add to chart" in the Pine Editor toolbar. Trade markers appear on the price chart, and the Strategy Tester opens automatically. Why this matters: visual confirmation that your code compiles and runs. What can go wrong: if the console shows errors instead of markers, check for syntax mistakes or a missing strategy() declaration — those are the two most common issues I see.

Digging into the Strategy Tester

The Strategy Tester tab has three main sections:

The Overview shows equity curves and drawdown periods. I always check the drawdown chart first. A strategy that returns 200% across the test period but drops 60% along the way isn't one I'd run with real money.

The Performance Summary breaks down long trades, short trades, and overall metrics. I pay closest attention to profit factor (gross profit divided by gross loss). Anything above 1.5 is worth a closer look.

The List of Trades is a clickable history of every simulated entry and exit. I once caught a bug here — my short entries were executing on long signals because I'd mixed up crossover and crossunder. You'd be surprised how often that happens.

Finding Your Strategy's Sweet Spot

The Strategy Tester is a testing ground. Before committing real capital, run multiple backtests with different input combinations. Change the MA lengths. Try different starting capital values. The aim is to find settings that hold up across variations, not just the one that printed the highest net profit number.

Two settings most people skip: commission and slippage. In the Strategy Tester's Properties tab, add realistic trade costs. I use $2.50 per trade for US equities and 1-2 ticks of slippage depending on the contract. Skip these and your backtest results are misleading.

Walk-Forward Analysis

Walk-forward analysis splits your historical data into two chunks. You optimize parameters on the first chunk, then test those parameters on the second chunk — data the strategy has never seen. This catches overfitting: when a strategy crushes the backtest but falls apart on live data.

I use a 70/30 split — optimize on 70% of the bars, validate on the remaining 30%. I've killed several strategies this way that looked fantastic in a simple backtest. They failed walk-forward, and I'm glad I knew before funding them.

What to Try Next

  • Try a Trailing Stop: Instead of a fixed stop-loss, use trail_price and trail_offset in strategy.exit(). The stop follows the price as the trade moves in your favor. It's a dynamic way to lock in gains without manually adjusting levels.
  • Get Feedback: Publish your strategy in TradingView's Public Library. Other traders will spot edge cases and suggest improvements you haven't considered.
  • Automate Execution: Connect TradingView alerts to a webhook service like TradersPost. Your trades execute automatically when the alert fires — no need to watch the screen all day. For more advanced setups, check out our guide on how to trade options on TradingView.
ActionKey Function/ServiceBenefit
Dynamic Risk Managementtrail_price, trail_offset in strategy.exit()Locks in profits by moving the stop-loss as the trade moves in your favor.
Community FeedbackPublish to Public LibraryGathers insights and improvement ideas from other traders.
Automated ExecutionTradingView Alerts + Webhook (e.g., TradersPost)Executes trades live without manual intervention.

Understanding how to handle missing data is important when building reliable strategies. When indicators return na values, they can cause unexpected behavior in your trade logic. The NA function in Pine Script helps manage these cases properly.

What's the difference between a Pine Script strategy and an indicator?

An indicator plots data on your chart and never touches your portfolio. A strategy does everything an indicator does, plus it simulates buy and sell orders, tracks a virtual balance, and reports performance metrics like net profit, win rate, and max drawdown in the Strategy Tester tab.

How do I declare a strategy in Pine Script v5?

Call strategy() at the top of your script: strategy("Name", overlay=true, initial_capital=10000). The overlay parameter puts signals on the price chart, and initial_capital sets the starting cash for backtesting. Every entry and exit command must come after this line.

How accurate is TradingView backtesting?

Backtesting accuracy depends on the OHLCV data from your exchange and timeframe. Results look too good if you skip commission and slippage. Set realistic rates in the Properties tab before trusting the performance summary.

Can I automate a TradingView strategy to place real trades?

Yes. Create an alert triggered by your strategy's order fills, then point its webhook to a service like TradersPost or 3Commas. The service forwards the order to your connected broker. No manual clicks needed once it's set up.

What is walk-forward analysis and why does it matter?

Walk-forward analysis splits your data into an in-sample period (used to tune parameters) and an out-of-sample period (used to test on unseen data). It prevents overfitting — the classic trap where a strategy looks amazing on past data but falls apart on live markets.

How do I add a stop-loss and take-profit in a Pine Script strategy?

Use strategy.exit() after your entry call. Example: strategy.exit("Exit Long", "Long", stop=stopPrice, limit=targetPrice). The stop parameter sets the stop-loss level and limit sets the take-profit. You can also use trail_price or trail_offset for a trailing stop that moves with the market.

Why does my Pine Script strategy show different results on different timeframes?

The number of bars, OHLCV resolution, and fill logic all change between timeframes. Higher timeframes have fewer bars, which makes statistics less reliable. Test your strategy across multiple timeframes and confirm the bar count is high enough for meaningful results.