How to Create a Strategy in TradingView Pine Script: SMA Crossover Strategy

Automated trading strategies help traders remove emotional decision-making by following predefined technical rules. In this article, we will explore how to build a Simple Moving Average (SMA) crossover strategy using TradingView Pine Script v6. We will cover what an automated technical trading strategy is, the basics of the SMA indicator, the concept behind SMA crossovers, and finally, provide a fully configurable Pine Script code example.

What Is an Automated Technical Trading Strategy?

An automated technical trading strategy is a set of rules programmed into software to execute trades based on technical indicators and market data.

Here are some benefits of using such strategies:

  • Emotion-Free Trading: Removes human bias and emotion from trading decisions.
  • Consistency: Trades are executed according to predefined criteria, ensuring a consistent approach.
  • Speed: Automation allows for quick order execution which is especially important in fast-moving markets.
  • Backtesting: Strategies can be tested on historical data to evaluate their potential performance before risking actual capital.

Overview of the SMA Technical Indicator

The Simple Moving Average (SMA) is one of the most commonly used technical indicators. It calculates the average price of an asset over a specific period, smoothing out price fluctuations and highlighting underlying trends. For example, a 50-period SMA averages the closing prices of the last 50 bars, while a 200-period SMA does the same for 200 bars. These averages can help traders identify support and resistance levels or confirm trends.

The SMA Crossover Trading Strategy

The SMA crossover strategy is based on the idea of using two different SMAs – one fast and one slow. The typical rules for this strategy are:


  • Buy Signal: When the fast SMA (e.g., 50-period) crosses above the slow SMA (e.g., 200-period), it indicates that the recent price momentum is increasing relative to the longer-term trend.


  • Sell (or Short) Signal: When the fast SMA crosses below the slow SMA, it suggests a potential downturn.


This simple yet effective strategy is widely used to capture trend reversals and confirm momentum changes in the market.

Implementing the Strategy in Pine Script v6

TradingView’s Supercharts

Figure 1. SMA Crossover Trading Strategy in Pine Script v.6

Below is the complete Pine Script v6 code for a configurable SMA crossover strategy. In this script, you can adjust the periods for both SMAs, and each moving average is plotted in a different color for clear visualization.


//@version=6

strategy("SMA Crossover Strategy", overlay=true, initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=10)


// Configurable Parameters

fastLength = input.int(50, title="Fast SMA Length", minval=1)

slowLength = input.int(200, title="Slow SMA Length", minval=1)

fastColor = input.color(color.blue, title="Fast SMA Color")

slowColor = input.color(color.red, title="Slow SMA Color")


// Calculating the Simple Moving Averages

fastSMA = ta.sma(close, fastLength)

slowSMA = ta.sma(close, slowLength)


// Plotting the SMAs on the chart

plot(fastSMA, title="Fast SMA", color=fastColor, linewidth=2)

plot(slowSMA, title="Slow SMA", color=slowColor, linewidth=2)


// Generating Buy and Sell Signals Based on Crossover

longCondition = ta.crossover(fastSMA, slowSMA)

shortCondition = ta.crossunder(fastSMA, slowSMA)


// Enter a long position when fast SMA crosses above slow SMA

if (longCondition)

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


// Enter a short position when fast SMA crosses below slow SMA

if (shortCondition)

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


Code Explanation

  • Strategy Declaration:
    The strategy() function sets up the strategy's title, display settings (like overlay=true), initial capital, and default trade size.
  • Input Parameters:
    The script defines inputs for the lengths of the fast and slow SMAs and their colors. This allows traders to easily adjust the settings from the strategy’s settings panel.
  • SMA Calculation:
    The built-in function ta.sma() calculates the simple moving averages based on the closing price and the specified lengths.
  • Plotting the Averages:
    The plot() function draws both SMAs on the chart using the chosen colors and line widths for clarity.
  • Trading Signals:
    The ta.crossover() and ta.crossunder() functions detect when the fast SMA crosses the slow SMA from below or above, respectively. When these conditions are met, the strategy executes a long or short entry accordingly.

Conclusion

Writing trading strategies in Pine Script empowers traders to automate their trading systems, making them consistent and emotion-free. In this article, we built a basic SMA crossover strategy that buys when the fast SMA crosses above the slow SMA and sells (or shorts) when the opposite occurs. With configurable parameters and clear plotting, this strategy serves as an excellent starting point for further experimentation and refinement.

Sergey Buzz