Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save khalidsalomao/2810182e9ec4f275b7c24939ddc72c6c to your computer and use it in GitHub Desktop.
Save khalidsalomao/2810182e9ec4f275b7c24939ddc72c6c to your computer and use it in GitHub Desktop.
A simple template for backtesting a trading view pine strategy
//@version=3
// TODO: update strategy name
strategy("{STRATEGY NAME}", overlay=true)
// === TA LOGIC ===
//
//
// TODO: PUT YOUR TA LOGIC HERE
LONG_SIGNAL_BOOLEAN = crossover(sma(close, 13), sma(close, 34))
SHORT_SIGNAL_BOOLEAN = crossunder(sma(close, 12), sma(close, 21))
// === INPUT BACKTEST DATE RANGE ===
strategyType = input(defval="Long Only", options=["Long & Short", "Long Only", "Short Only"])
enableShorts = input(false, title="Enable short entries?")
FromMonth = input(defval = 5, title = "From Month", minval = 1, maxval = 12)
FromDay = input(defval = 18, title = "From Day", minval = 1, maxval = 31)
FromYear = input(defval = 2018, title = "From Year", minval = 2017)
ToMonth = input(defval = 9, title = "To Month", minval = 1, maxval = 12)
ToDay = input(defval = 1, title = "To Day", minval = 1, maxval = 31)
ToYear = input(defval = 2018, title = "To Year", minval = 2017)
start = timestamp(FromYear, FromMonth, FromDay, 00, 00) // backtest start window
finish = timestamp(ToYear, ToMonth, ToDay, 23, 59) // backtest finish window
window() => time >= start and time <= finish ? true : false // create function "within window of time"
// === STRATEGY BUY / SELL ENTRIES ===
// TODO: update the placeholder LONG_SIGNAL_BOOLEAN and SHORT_SIGNAL_BOOLEAN to signal
// long and short entries
buy() => window() and LONG_SIGNAL_BOOLEAN
sell() => window() and SHORT_SIGNAL_BOOLEAN
if buy()
if (strategyType == "Short Only")
strategy.close("Short")
else
strategy.entry("Long", strategy.long, comment="Long")
if sell()
if (strategyType == "Long Only")
strategy.close("Long")
else
strategy.entry("Short", strategy.short, comment="Short")
// === BACKTESTING: EXIT strategy ===
sl_inp = input(10, title='Stop Loss %', type=float)/100
tp_inp = input(30, title='Take Profit %', type=float)/100
stop_level = strategy.position_avg_price * (1 - sl_inp)
take_level = strategy.position_avg_price * (1 + tp_inp)
strategy.exit("Stop Loss/Profit", "Long", stop=stop_level, limit=take_level)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment