Strategy · Pine Script v5 · On the chart

Backtester v5

by hasnocool

This strategy plots a 50-period and a 200-period simple moving average on the price chart and trades their crosses.

View on GitHub

GitHub stars106on the repository
Pine versionv5runs as is
Lines of code120
Settings14inputs
LicenceGPL-3.0
Last update2 years ago18 Sep 2024

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

120 lines of Pine Script v5 from Backtest Engine.pine, published under GPL-3.0. Keep the author's credit and licence lines when you reuse it.

Backtest Engine.pine
// Backtester v5 © gjfsdrtytru {
// On lines 31-37, use the variable longCondition to trigger your long entry, closeLong to trigger close long, etc.
// TP/SL are built into the script. There are also some inputs for bot commands in the settings UI if you want to set up a trading bot.
// No user input is required beyond line 49. Just define your strategy and let the engine do the rest!
// Thanks to Wunderbit Trading who helped in the making of this script with their open-source code and tutorials.
//@version=5
strategy(
  title                 = "Backtester v5", 
  shorttitle            = "Backtest",
  overlay               = true,
  calc_on_order_fills   = true,
  default_qty_type      = strategy.percent_of_equity,
  default_qty_value     = 100,
  initial_capital       = 10000) // }
// Start code here...
sma1 = ta.sma(close,50)
sma2 = ta.sma(close,200)
plot(sma1,"Fast MA",color.blue)
plot(sma2,"Slow MA",color.red)
// Define Entry/Close Conditions {
i_long  = input(true,"Long orders",group="Orders",tooltip="Toogle on/off long orders")
i_short = input(true,"Short orders",group="Orders",tooltip="Toogle on/off short orders")
longCondition   = false
closeLong       = false
shortCondition  = false
closeShort      = false
if i_long
    longCondition   := ta.crossover(sma1,sma2)      // Enter your conditions here
    closeLong       := ta.crossunder(sma1,sma2)     // Enter your conditions here
if i_short
    shortCondition  := ta.crossunder(sma1,sma2)     // Enter your conditions here
    closeShort      := ta.crossover(sma1,sma2)      // Enter your conditions here
// }
// Bot Web-link Alert - {{strategy.order.comment}} {
// LONG COMMENTS
botLong         = input("Long Entry",   title="Entry Long Command", group="Bot Commands",tooltip="Long entry bot command")
botLongClose    = input("Long Closed",  title="Exit Long Command",  group="Bot Commands",tooltip="Long close bot command")
// SHORT COMMENTS
botShort        = input("Short Entry",  title="Entry Short Command",group="Bot Commands",tooltip="Short entry bot command")
botShortClose   = input("Short Closed", title="Exit Short Command", group="Bot Commands",tooltip="Short close bot command")
// }
// BACKTEST ENGINE [NO USER INPUT REQUIRED] ////////////////// {
// Time period {
testStartYear   = input.int(2018,   title="Backtest Start Year",    minval=2010,maxval=2100,group="Backtest Period")
testStartMonth  = input.int(1,      title="Backtest Start Month",   minval=1,   maxval=12,  group="Backtest Period")
testStartDay    = input.int(1,      title="Backtest Start Day",     minval=1,   maxval=31,  group="Backtest Period")
testPeriodLen   = input.int(9999,   title="Backtest Period (days)", minval=1,               group="Backtest Period",tooltip="Days until strategy ends") * 86400000 // convert days into UNIX time
testPeriodStart = timestamp(testStartYear,testStartMonth,testStartDay,0,0)
testPeriodStop  = testPeriodStart + testPeriodLen
testPeriod() =>
    time >= testPeriodStart and time <= testPeriodStop ? true : false
// }
// Calculate TP/SL {
// User inputs
i_longTP     = input.float(title="Long Take Profit (%)" ,minval=0.0, step=1, defval=0,group="Take Profit/Stop Loss") * 0.01
i_longSL     = input.float(title="Long Stop Loss (%)"   ,minval=0.0, step=1, defval=0,group="Take Profit/Stop Loss") * 0.01
i_shortTP    = input.float(title="Short Take Profit (%)",minval=0.0, step=1, defval=0,group="Take Profit/Stop Loss") * 0.01
i_shortSL    = input.float(title="Short Stop Loss (%)"  ,minval=0.0, step=1, defval=0,group="Take Profit/Stop Loss") * 0.01
// 0% TP/SL = OFF (a value of 0 turns off TP/SL feature)
longTP     = i_longTP  == 0 ? 1000 : i_longTP
longSL     = i_longSL  == 0 ? 1    : i_longSL
shortTP    = i_shortTP == 0 ? 1    : i_shortTP
shortSL    = i_shortSL == 0 ? 1000 : i_shortSL
// Determine TP/SL price based on percentage given
longTP      := strategy.position_avg_price * (1 + longTP)
longSL      := strategy.position_avg_price * (1 - longSL)
shortTP     := strategy.position_avg_price * (1 - shortTP)
shortSL     := strategy.position_avg_price * (1 + shortSL) 
// }
// Anti-overlap {
isEntry_Long    = false
isEntry_Long    := nz(isEntry_Long[1], false)
isExit_Long     = false
isExit_Long     := nz(isExit_Long[1], false)
isEntry_Short   = false
isEntry_Short   := nz(isEntry_Short[1], false)
isExit_Short    = false
isExit_Short    := nz(isExit_Short[1], false)
entryLong       = not isEntry_Long and longCondition
exitLong        = not isExit_Long and closeLong
entryShort      = not isEntry_Short and  shortCondition
exitShort       = not isExit_Short and closeShort
if (entryLong)
    isEntry_Long := true
    isExit_Long := false
if (exitLong)
    isEntry_Long := false
    isExit_Long := true
if (entryShort)
    isEntry_Short := true
    isExit_Short := false
if (exitShort)
    isEntry_Short := false
    isExit_Short := true
// }
// Order Execution {
// Entries
if testPeriod()
    strategy.entry("Long" ,strategy.long ,when=entryLong ,comment=botLong)
    strategy.entry("Short",strategy.short,when=entryShort,comment=botShort)
// TP/SL
if (strategy.position_size > 0) 
    strategy.exit(from_entry="Long", id="Long SL/TP",   qty_percent=100,limit=longTP, stop=longSL) 
    strategy.close(id       ="Long", when=exitLong,     qty_percent=100,comment=botLongClose)
if (strategy.position_size < 0)
    strategy.exit(from_entry="Short", id="Short TP/SL", qty_percent=100,limit=shortTP,stop=shortSL)
    strategy.close(id       ="Short", when=exitShort,   qty_percent=100,comment=botShortClose)
// }
// Draw Entry, TP and SL Levels {
// Long positions
plot(strategy.position_size > 0 ? strategy.position_avg_price   : na, style=plot.style_linebr, color=color.blue,    title="Long Entry")
plot(strategy.position_size > 0 ? i_longTP    == 0 ? na : longTP  : na, style=plot.style_linebr, color=color.green,   title="Long TP")
plot(strategy.position_size > 0 ? i_longSL    == 0 ? na : longSL  : na, style=plot.style_linebr, color=color.red,     title="Long SL")
// Short positions
plot(strategy.position_size < 0 ? strategy.position_avg_price   : na, style=plot.style_linebr, color=color.blue,    title="Short Entry")
plot(strategy.position_size < 0 ? i_shortTP   == 0 ? na : shortTP : na, style=plot.style_linebr, color=color.green,   title="Short TP")
plot(strategy.position_size < 0 ? i_shortSL   == 0 ? na : shortSL : na, style=plot.style_linebr, color=color.red,     title="Short SL")
// }
// }
Expand (130 lines)

Overview

Backtester v5 opens a long when the fast average crosses above the slow average and closes that long on the opposite cross; shorts use the reverse crosses. Separate toggles enable or disable long and short orders. Percentage take-profit and stop-loss inputs default to zero, so no protective exit is active until the user sets them. A start date and day count limit the test window, and comment strings can label bot alerts. Orders use the full account equity.

Details

Published by

hasnocool on GitHub

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Trend, Moving averages

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

  • The strategy enters trades without a stop loss

Topics

analysisbtcusdtcryptocurrencydatapandaspythonsimulationtradingtradingview

Settings

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

SettingTypeDefaultVariable
Long ordersbooltruei_long
Short ordersbooltruei_short
Entry Long CommandstringLong EntrybotLong
Exit Long CommandstringLong ClosedbotLongClose
Entry Short CommandstringShort EntrybotShort
Exit Short CommandstringShort ClosedbotShortClose
Backtest Start Yearint2018testStartYear
Backtest Start Monthint1testStartMonth
Backtest Start Dayint1testStartDay
Backtest Period (days)int9999testPeriodLen
Long Take Profit (%)float0i_longTP
Long Stop Loss (%)float0i_longSL
Show all 14 settings
SettingTypeDefaultVariable
Short Take Profit (%)float0i_shortTP
Short Stop Loss (%)float0i_shortSL
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 today · 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 6 weeks ago · None stated GitHub repository of 30s - ES 1m Strategy Candle Bar

More strategys

Trade Your Charts With a Regulated Broker

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

Compare brokers