Skip to content

Instantly share code, notes, and snippets.

@princefr
Created June 24, 2020 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save princefr/f41c51a0507ad32b916f47e8bb251a69 to your computer and use it in GitHub Desktop.
Save princefr/f41c51a0507ad32b916f47e8bb251a69 to your computer and use it in GitHub Desktop.
backtest ma
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © prince_ond
//@version=4
strategy(title='[STRATEGY][UL]MA strategy', pyramiding=0, overlay=true, initial_capital=20000, calc_on_every_tick=false,
currency=currency.USD, default_qty_type=strategy.percent_of_equity, default_qty_value=100)
ma = ema(close, 50)
ma_color() => ma[5] > ma[2] ? color.red : color.green
ma__isdown() => ma[5] > ma[2]
ma_is_up() => ma[5] < ma[2]
plot(ma, color=ma_color())
// Strategy: (Thanks to JayRogers)
// === STRATEGY RELATED INPUTS ===
//tradeInvert = input(defval = false, title = "Invert Trade Direction?")
// the risk management inputs
inpTakeProfit = input(defval = 0, title = "Take Profit Points", minval = 0)
inpStopLoss = input(defval = 0, title = "Stop Loss Points", minval = 0)
inpTrailStop = input(defval = 0, title = "Trailing Stop Loss Points", minval = 0)
inpTrailOffset = input(defval = 0, title = "Trailing Stop Loss Offset Points", minval = 0)
// === RISK MANAGEMENT VALUE PREP ===
// if an input is less than 1, assuming not wanted so we assign 'na' value to disable it.
useTakeProfit = inpTakeProfit >= 1 ? inpTakeProfit : na
useStopLoss = inpStopLoss >= 1 ? inpStopLoss : na
useTrailStop = inpTrailStop >= 1 ? inpTrailStop : na
useTrailOffset = inpTrailOffset >= 1 ? inpTrailOffset : na
// === STRATEGY - LONG POSITION EXECUTION ===
strategy.entry(id = "Buy", long = true, when = ma_is_up() )// use function or simple condition to decide when to get in
strategy.close(id = "Buy", when = ma__isdown() )
// === STRATEGY - SHORT POSITION EXECUTION ===
strategy.entry(id = "Sell", long = false, when = ma__isdown())
strategy.close(id = "Sell", when = ma_is_up())
// === STRATEGY RISK MANAGEMENT EXECUTION ===
// finally, make use of all the earlier values we got prepped
strategy.exit("Exit Buy", from_entry = "Buy", profit = useTakeProfit, loss = useStopLoss, trail_points = useTrailStop, trail_offset = useTrailOffset)
strategy.exit("Exit Sell", from_entry = "Sell", profit = useTakeProfit, loss = useStopLoss, trail_points = useTrailStop, trail_offset = useTrailOffset)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment