Strategy · Pine Script v4 · On the chart

Moving Averages Crossover Bot

by infinityhao

The Moving Averages Crossover Bot calculates two configurable moving averages directly on the price chart using selectable types such as SMA, EMA, WMA, RMA, HMA, DEMA, or TEMA.

View on GitHub

Repaints

GitHub stars3on the repository
Pine versionv4older, still runs
Lines of code93
Settings9inputs
LicenceNone statedfile: MPL-2.0
Last update5 years ago25 Mar 2021

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

93 lines of Pine Script v4 from MA Crossovers Bot.txt, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

MA Crossovers Bot.txt
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ©author infinityhao

//@version=4

strategy(shorttitle = "MA Crossover Bot", title = "Moving Averages Crossover Bot", overlay = true, calc_on_every_tick = true)  //calculation to occur on every real-time tick

// MAPeriod is a variable used to store the indicator lookback period.
// Input type - https://www.tradingview.com/pine-script-docs/en/v4/annotations/Script_inputs.html
MA1Period = input(50, title = "MA Period")
MA1Type = input(title = "MA1 Type", defval = "SMA", options = ["RMA", "SMA", "EMA", "WMA"])
MA1Source = input(title="MA1 Source", type = input.source, defval = close)
MA1Visible = input(title = "MA1 Visible", type = input.bool, defval = true) //default show crossover containing this MA
MA2Period = input(100, title = "MA2 Period")
MA2Type = input(title = "MA2 Type", defval = "SMA", options = ["RMA", "SMA", "EMA", "WMA"])
MA2Source = input(title="MA1 Source", type = input.source, defval = close)
MA2Visible = input(title = "MA2 Visible", type = input.bool, defval = true) //default show crossover containing this MA

ShowCrosses = input(title = "Show Crosses", type = input.bool, defval = true)

// MA is a variable used to store the moving average value.
// if statements - https://www.tradingview.com/pine-script-reference/#op_if
// MA functions - https://www.tradingview.com/pine-script-reference/ (must search for appropriate MA)
MA1 = if MA1Type == "SMA"
    sma(MA1Source, MA1Period)
else
    if MA1Type == "EMA"
        ema(MA1Source, MA1Period)
    else
        if MA1Type == "WMA"
            wma(MA1Source, MA1Period)
        else
            if MA1Type == "RMA"
                rma(MA1Source, MA1Period)
            else
                if MA1Type == "HMA"
                    wma(2 * wma(MA1Source, MA1Period/2) - wma(MA1Source, MA1Period), round(sqrt(MA1Period)))
                else
                    if MA1Type == "DEMA"
                        e = ema(MA1Source, MA1Period)
                        2 * e - ema(e, MA1Period)
                    else
                        if MA1Type == "TEMA"
                            e = ema(MA1Source, MA1Period)
                            3 * (e - ema(e, MA1Period)) + ema(ema(e, MA1Period), MA1Period)


MA2 = if MA2Type == "SMA"
    sma(MA2Source, MA2Period)
else
    if MA2Type == "EMA"
        ema(MA2Source, MA2Period)
    else
        if MA2Type == "WMA"
            wma(MA2Source, MA2Period)
        else
            if MA2Type == "RMA"
                rma(MA2Source, MA2Period)
            else
                if MA2Type == "HMA"
                    wma(2 * wma(MA2Source, MA2Period/2) - wma(MA2Source, MA2Period), round(sqrt(MA2Period)))
                else
                    if MA2Type == "DEMA"
                        e = ema(MA2Source, MA2Period)
                        2 * e - ema(e, MA2Period)
                    else
                        if MA2Type == "TEMA"
                            e = ema(MA2Source, MA2Period)
                            3 * (e - ema(e, MA2Period)) + ema(ema(e, MA2Period), MA2Period)

// AI section
// AI section - https://www.tradingview.com/pine-script-docs/en/v4/essential/Strategies.html
if ShowCrosses and MA1Visible and MA2Visible and crossunder(MA1, MA2)
    lun1 = label.new(bar_index, na, tostring(MA1Period)+' '+MA1Type+' crossed under '+tostring(MA2Period)+' '+MA2Type,
      color = color.red,
      textcolor = color.red,
      style = label.style_xcross, size = size.small)
    label.set_y(lun1, MA1)
    strategy.entry("sell", strategy.short, 100, when=strategy.position_size > 0)
if ShowCrosses and MA1Visible and MA2Visible and crossover(MA1, MA2)
    lup1 = label.new(bar_index, na, tostring(MA1Period)+' '+MA1Type+' crossed over '+tostring(MA2Period)+' '+MA2Type,
      color = color.green,
      textcolor = color.green,
      style = label.style_xcross, size = size.small)
    label.set_y(lup1, MA1)
    strategy.entry("buy", strategy.long, 100, when=strategy.position_size <= 0)


// Plot - This will plot the information on the chart
// Plot - https://www.tradingview.com/pine-script-docs/en/v4/annotations/plot_annotations.html
// if MAVisible is true, then plot the MA with label.
plot(MA1Visible ? MA1 : na, color = color.green, linewidth = 2)
plot(MA2Visible ? MA2 : na, color = color.yellow, linewidth = 3)

Overview

Moving Averages Crossover Bot identifies signals when the first moving average crosses above or below the second moving average. Users can customize lookback periods, calculation types, price sources, and toggle cross labels. Because calculation occurs on every real-time tick, intrabar signals can repaint prior to bar completion, and the strategy lacks defined stop loss rules.

Details

Published by

infinityhao on GitHub

Type

Strategy, Pine Script v4

Draws

On the price chart

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

  • Signals can change on the live bar or after it closes (repainting)
  • The strategy enters trades without a stop loss

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
MA Periodint50MA1Period
MA1 TypestringSMAMA1Type
MA1 SourcesourcecloseMA1Source
MA1 VisiblebooltrueMA1Visible
MA2 Periodint100MA2Period
MA2 TypestringSMAMA2Type
MA1 SourcesourcecloseMA2Source
MA2 VisiblebooltrueMA2Visible
Show CrossesbooltrueShowCrosses
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

Doge SMA

by hackingthemarkets
474 stars

Doge SMA is a long-only moving-average crossover strategy drawn on the price chart. It calculates a fast and a slow simple moving average of close and enters a long position when the fast average crosses above the slow average, but only inside a user-defined s

Strategy v4 TrendMoving averages
Updated 4 years ago · None stated GitHub repository of Doge SMA

This strategy calculates and plots a fast Exponential Moving Average (EMA) and a slow EMA directly on the main price chart. It enters long trades when the fast EMA crosses above the slow EMA and exits when the fast EMA crosses below the slow EMA. Inputs allow

Strategy v6 TrendMoving averages
Updated 2 days ago · AGPL-3.0 GitHub repository of Forven S01508 — Simple EMA20/50 Cross
330 stars

2 EMA/SMA + RSI Strategy [Alorse] combines three configurable moving averages with a short-period Relative Strength Index filter. It plots fast, slow, and trend moving averages on the price chart. Long entries trigger when the fast moving average is above the

Strategy v4 TrendOscillators & momentum
Updated 2 months ago · None stated GitHub repository of 2 EMA/SMA + RSI Strategy [Alorse]

Acrypto - Weighted Strategy

by AlbertoCuadra
318 stars

This strategy plots on the price chart and opens long or short positions when a weighted score from MACD, Stochastic RSI, RSI, Supertrend and a moving-average crossover exceeds a user-set trigger. Each component has its own weight and candle delay. Entries can

Strategy v5 TrendOscillators & momentum
Updated 3 years ago · Custom licence GitHub repository of Acrypto - Weighted Strategy
257 stars

This strategy calculates dynamic support and resistance levels using pivot highs and lows alongside a custom smoothed trend filter and a 3-period EMA. It identifies entry opportunities when price breaks out relative to the trend filter and short-term EMA cross

Strategy v5 TrendSupport & resistance Repaints
Updated 7 weeks ago · None stated GitHub repository of 30s - ES 1m Strategy Candle Bar

EMA Crossover Strategy

by TradersPost
228 stars

EMA Crossover Strategy plots a fast and a slow exponential moving average on the price chart. It treats a confirmed fast-over-slow cross as a long condition and a confirmed cross under as a short condition. Position size is a percentage of equity. Optional per

Strategy v6 TrendMoving averages
Updated 3 months ago · None stated GitHub repository of EMA Crossover Strategy

More Moving averages scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers