In this guide, we’ll walk through creating a backtested Buy&Sell trading strategy using Pine Script, focusing on the 200-period Simple Moving Average (SMA) for BINANCE:BTCUSDT. This strategy is designed for educational purposes and illustrates key concepts in algorithmic trading.
Strategy Overview
Core Mechanics
- Asset: Bitcoin (BTC/USDT)
- Indicator: 200-period SMA.
- Entry Signal: Price crosses below the SMA.
- Exit Signal: Price crosses above the SMA.
- Position Sizing: 5% of equity per trade.
Key Features
- Single-trade execution (no overlapping positions).
- Backtested with realistic commissions (0.07%) and slippage (3 points).
Step-by-Step Implementation
1. Strategy Parameters
Define the foundational settings in Pine Script:
strategy(
"Buy&Sell Strategy Template [The Quant Science]",
overlay = true,
default_qty_type = strategy.percent_of_equity,
default_qty_value = 5,
initial_capital = 10000,
commission_value = 0.07,
slippage = 3,
process_orders_on_close = true
)overlay = true: Displays results on the price chart.process_orders_on_close: Ensures calculations use closed prices for accuracy.
2. Data Extrapolation
Calculate the 200-period SMA:
sma = ta.sma(close, 200)3. Trading Conditions
Set entry/exit rules:
entry_condition = ta.crossunder(close, sma) // Entry: Price < SMA
exit_condition = ta.crossover(close, sma) // Exit: Price > SMA 4. Trade Execution
Execute trades based on conditions:
if (entry_condition and strategy.opentrades == 0)
strategy.entry("Buy", strategy.long)
if (exit_condition)
strategy.exit("Sell", "Buy")5. Visualization
Plot the SMA for clarity:
plot(sma, title = "SMA", color = color.red)👉 Explore advanced trading strategies to enhance your algorithmic toolkit.
Complete Pine Script Code
//@version=6
strategy(
"Buy&Sell Strategy Template [The Quant Science]",
overlay = true,
default_qty_type = strategy.percent_of_equity,
default_qty_value = 5,
initial_capital = 10000,
commission_value = 0.07,
slippage = 3,
process_orders_on_close = true
)
sma = ta.sma(close, 200)
entry_condition = ta.crossunder(close, sma)
exit_condition = ta.crossover(close, sma)
if (entry_condition and strategy.opentrades == 0)
strategy.entry("Buy", strategy.long)
if (exit_condition)
strategy.exit("Sell", "Buy")
plot(sma, title = "SMA", color = color.red)FAQs
1. Can this strategy be used for live trading?
No. This is an educational example and lacks risk management features like stop-loss orders.
2. How do I adjust the SMA period?
Modify the 200 in ta.sma(close, 200) to test different timeframes (e.g., 50 or 100).
3. Why use 5% equity per trade?
Small position sizing reduces risk. Adjust via default_qty_value.
👉 Learn more about risk management in algorithmic trading.
Disclaimer
This strategy is for educational purposes only. TradingView and the author do not endorse using it for live trading. Always conduct independent research and backtesting before deploying capital.
For further reading, review TradingView’s Terms of Use.