JayRogers

Strategy Code Example - Risk Management

*** THIS IS JUST AN EXAMPLE OF STRATEGY RISK MANAGEMENT CODE IMPLEMENTATION ***

For my own future reference, and for anyone else who needs it.

Pine script strategy code can be confusing and awkward, so I finally sat down and had a little think about it and put something together that actually works (i think...)

Code is commented where I felt might be necessary (pretty much everything..) and covers:
  • Take Profit
  • Stop Loss
  • Trailing Stop
  • Trailing Stop Offset
...and details how to handle the input values for these in a way that allows them to be disabled if set to 0, without breaking the strategy.exit functionality or requiring a silly amount of statement nesting.

Also shows how to use functions (or variables/series) to execute trade entries and exits.

Cheers!
Remove from Favorite Scripts Add to Favorite Scripts
//@version=2

strategy(title = "Strategy Code Example", shorttitle = "Strategy Code Example", overlay = true, pyramiding = 0, default_qty_type = strategy.percent_of_equity, default_qty_value = 10, currency = currency.GBP)

// Revision:        1
// Author:          @JayRogers
//
// *** THIS IS JUST AN EXAMPLE OF STRATEGY RISK MANAGEMENT CODE IMPLEMENTATION ***

// === GENERAL INPUTS ===
// short ma
maFastSource   = input(defval = open, title = "Fast MA Source")
maFastLength   = input(defval = 14, title = "Fast MA Period", minval = 1)
// long ma
maSlowSource   = input(defval = open, title = "Slow MA Source")
maSlowLength   = input(defval = 21, title = "Slow MA Period", minval = 1)

// === STRATEGY RELATED INPUTS ===
tradeInvert     = input(defval = false, title = "Invert Trade Direction?")
// the risk management inputs
inpTakeProfit   = input(defval = 1000, title = "Take Profit", minval = 0)
inpStopLoss     = input(defval = 200, title = "Stop Loss", minval = 0)
inpTrailStop    = input(defval = 200, title = "Trailing Stop Loss", minval = 0)
inpTrailOffset  = input(defval = 0, title = "Trailing Stop Loss Offset", 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

// === SERIES SETUP ===
/// a couple of ma's..
maFast = ema(maFastSource, maFastLength)
maSlow = ema(maSlowSource, maSlowLength)

// === PLOTTING ===
fast = plot(maFast, title = "Fast MA", color = green, linewidth = 2, style = line, transp = 50)
slow = plot(maSlow, title = "Slow MA", color = red, linewidth = 2, style = line, transp = 50)

// === LOGIC ===
// is fast ma above slow ma?
aboveBelow = maFast >= maSlow ? true : false
// are we inverting our trade direction?
tradeDirection = tradeInvert ? aboveBelow ? false : true : aboveBelow ? true : false

// === STRATEGY - LONG POSITION EXECUTION ===
enterLong() => not tradeDirection[1] and tradeDirection // functions can be used to wrap up and work out complex conditions
exitLong() => tradeDirection[1] and not tradeDirection
strategy.entry(id = "Long", long = true, when = enterLong()) // use function or simple condition to decide when to get in
strategy.close(id = "Long", when = exitLong()) // ...and when to get out
// === STRATEGY - SHORT POSITION EXECUTION ===
enterShort() => tradeDirection[1] and not tradeDirection
exitShort() => not tradeDirection[1] and tradeDirection
strategy.entry(id = "Short", long = false, when = enterShort())
strategy.close(id = "Short", when = exitShort())

// === STRATEGY RISK MANAGEMENT EXECUTION ===
// finally, make use of all the earlier values we got prepped
strategy.exit("Exit Long", from_entry = "Long", profit = useTakeProfit, loss = useStopLoss, trail_points = useTrailStop, trail_offset = useTrailOffset)
strategy.exit("Exit Short", from_entry = "Short", profit = useTakeProfit, loss = useStopLoss, trail_points = useTrailStop, trail_offset = useTrailOffset)
Such an awesome post, thank you Jay!
+2 Reply
JayRogers pbergden
I'm glad people are finding it useful, thanks for the feedback :)
Reply
you are teaching heart of this game, thank you very much again.
+1 Reply
JayRogers jackvmk
Very welcome.
Reply
Extended this example with basic time limiting functionality here:
Strategy Code Example  2 - Time Limiting
Reply
how to download this EA? Thanks
Reply
So by having
+1 Reply
kakola kakola
So by having
strategy.entry(when = enterLong())
strategy.close(when = exitLong())
strategy.exit(profit = useTakeProfit, loss = useStopLoss, trail_points = useTrailStop, trail_offset = useTrailOffset)

the close AND the exit parameter, you're telling it to exit either when the exitLong condition OR the stoploss is hit?
Reply
That is correct for this example.
Reply
These units are all in pips? Are they converted to pennies if you're on a stock chart?

inpTakeProfit = input(defval = 1000, title = "Take Profit", minval = 0)
inpStopLoss = input(defval = 200, title = "Stop Loss", minval = 0)
inpTrailStop = input(defval = 200, title = "Trailing Stop Loss", minval = 0)
inpTrailOffset = input(defval = 0, title = "Trailing Stop Loss Offset", minval = 0)
Reply
To keep it simple based on my understanding, I have only used values that are specified in 'ticks'. As such, a value of 200 should be 200 times the minimum tick value of a chart. So for example on EURUSD, 200 would in fact be 20 pips.
+1 Reply
Hello Jay Rogers;
How would you go about finding a Dynamic Solution to place a 20 PIP Stop for both USDJPY (3 Decimals) and EURUSD(5 Decimals) and MSFT(2 Decimals) without referencing the TickerID name. To allow it to adapt to most securities on trading view ?

Started Googling for the Math Doctor !!
Reply
JayRogers AlAlawiAlawi
I haven't had much time to think about coding recently, but I don't recall seeing any method of ascertaining the number of decimal places on a chart.. So other than hard coding values for each item and conditionally checking the current chart symbol against the list, I don't know at this point I'm afraid.
Reply
Absolutely mind testing, I stumbled to a much dynamically friendly Stop using the ATR. My stop is the ATR. It shows fantastic results while back testing using any stock commodity or forex. Which makes me wonder only!
Reply
AlAlawiAlawi PRO AlAlawiAlawi
snapshot


A picture worth a thousand words
Reply
I am getting an error while compiling this code on Mt4

On Line 3: 'strategy' - declaration without type

Can anyone help plz?
Reply
JayRogers ArupNag
Scripts written for tradingview are in PineScript which is wildly different to mt4's MQL4 language, and thus incompatible. You need an understanding of both languages in order to be able to properly port over a concept from one platform to the other.
Reply
Thanks man. This helped me out a great deal
Reply
Thank you very much for posting this. It's been my best Christmas present!
Reply
Excellent stuff. I was looking for strategizing certain ideas that require trailing stop loss. Did'nt understand how to do it, till I bumped into your super post. Many thanks.
Reply
Hello, how can it possible that the long trades on 20.05, 26.05 were closed exactly on the high of the bar?
18.05, 23.05, 24.05, 27.05 short trades closed exactly on the low of the bar.

just some trades as example. Is it possible with trailing stop loss?
What is different between trailing stop and trailing stop offset?

Thx
Reply
@robot2006, i would like to know as well
Reply
Hey do you find issues with the trailing stop in backtesting?

I find it gives a false value for the exit. If the trailing stop is triggered, it reports the trade close as either high or low of the bar, seemingly depending if you are long or short - giving wildly succesful backtest results , but false ones.

Anyone else get this?
Reply
Ideas Scripts Chart
United States
United Kingdom
India
España
France
Italia
Polska
Brasil
Россия
Türkiye
日本
한국
Home Stock Screener Forex Signal Finder Economic Calendar How It Works Chart Features House Rules Moderators For the WEB Widgets Stock Charting Library Priority Support Feature Request Blog & News FAQ Help & Wiki Twitter
Private Messages Chat Ideas Published Followers Following Priority Support Public Profile Profile Settings Account and Billing Sign Out