Prerequisites
Before starting, you need:
- A TradingView account (free tier works for development)
- Basic programming knowledge (variables, if/else, loops)
- An understanding of candlestick charts and basic indicators (SMA, RSI)
If you have never written code before, this tutorial will be challenging but doable. PineScript is one of the most beginner-friendly trading languages.
Step 1: Understanding the PineScript Environment
Open TradingView, navigate to any chart, and click "Pine Editor" at the bottom. This is where you write and test strategies.
Every PineScript strategy starts with a declaration:
//@version=5
strategy("My First Strategy", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100)Key parameters:
- overlay=true means the strategy plots on the price chart (not a separate panel)
- default_qty_type controls position sizing (percent of equity is safest for beginners)
- default_qty_value=100 means use 100% of available equity per trade
Step 2: Define Your Indicators
We will build a simple dual moving average crossover strategy. Not because it is the most profitable — but because it teaches the core concepts clearly.
// Moving averages
fastMA = ta.sma(close, 10)
slowMA = ta.sma(close, 30)
// Plot them on the chart
plot(fastMA, "Fast MA", color=color.blue, linewidth=1)
plot(slowMA, "Slow MA", color=color.red, linewidth=1)ta.sma(close, 10) calculates the 10-period Simple Moving Average of closing prices. When the fast MA crosses above the slow MA, we buy. When it crosses below, we sell.
Step 3: Entry and Exit Logic
// Crossover detection
longCondition = ta.crossover(fastMA, slowMA)
shortCondition = ta.crossunder(fastMA, slowMA)
// Execute trades
if (longCondition)
strategy.entry("Long", strategy.long)
if (shortCondition)
strategy.close("Long")This is the most basic version. It will trade. It will probably not be profitable yet. That is normal.
Step 4: Add Filters
Raw crossover signals generate too many false entries in choppy markets. Add filters:
// Trend filter: only trade when price is above 200 SMA
trendFilter = close > ta.sma(close, 200)
// Volatility filter: only trade when ATR is above its average
atr = ta.atr(14)
atrFilter = atr > ta.sma(atr, 50)
// Combined entry
if (longCondition and trendFilter and atrFilter)
strategy.entry("Long", strategy.long)The trend filter keeps you on the right side of the major trend. The volatility filter avoids low-volatility chop where moving average crossovers generate noise.
Step 5: Risk Management
This is where most tutorials stop and most strategies fail. Add stop losses and take profits:
// Risk parameters
stopLossPercent = input.float(2.0, "Stop Loss %", step=0.5)
takeProfitPercent = input.float(4.0, "Take Profit %", step=0.5)
if (longCondition and trendFilter and atrFilter)
stopPrice = close * (1 - stopLossPercent / 100)
tpPrice = close * (1 + takeProfitPercent / 100)
strategy.entry("Long", strategy.long)
strategy.exit("Exit", "Long", stop=stopPrice, limit=tpPrice)A 2:1 reward-to-risk ratio (4% take profit vs 2% stop loss) means you only need to win 34% of trades to break even. That is a realistic target.
Step 6: Backtesting and Evaluation
Click "Add to Chart" to run the backtest. Look at the Strategy Tester tab for results.
Key metrics to evaluate:
- Net Profit: Total P&L after commissions
- Max Drawdown: The worst peak-to-trough decline. If this exceeds 20%, your strategy is too risky for most traders.
- Profit Factor: Gross profits / gross losses. Above 1.5 is good. Above 2.0 is excellent.
- Number of Trades: Below 30 trades means insufficient sample size. Do not trust the results.
- Win Rate: Above 40% with a positive expectancy is fine. Do not chase high win rates — they often come at the cost of risk/reward.
Step 7: Walk-Forward Testing
Do not skip this step. It is the difference between a strategy that works in backtesting and one that works in live trading.
- Optimize your strategy on data from 2020-2023
- Test the optimized parameters on 2024 data (out-of-sample)
- If the out-of-sample results are within 70% of the in-sample results, your strategy is likely robust
- If out-of-sample results are dramatically worse, you have overfit
Next Steps
This tutorial covers the foundation. From here, you can:
- Add more sophisticated entry signals (RSI divergence, volume confirmation)
- Implement portfolio-level risk management
- Set up TradingView alerts for live signal generation
- Connect to NinjaTrader via NinjaSync for automated execution
The full PineScript documentation is available on TradingView's website. The GFREQ Discord community also has a dedicated PineScript channel where members share strategies and get feedback.
Trading involves risk. Past performance does not guarantee future results. Only trade with capital you can afford to lose.