JayRogers

Strategy Code Example - Risk Management

42650 obejrzeń
2112
42650 52
*** 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!
Usuń z Ulubionych Skryptów Dodaj do Ulubionych Skryptów
//@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)
Hi, thank you very much for your work.
I'm interested for this kind of strategy for cryptos. As cryptos don't use Ticks, how can I adapte the ticks variables (trail_offset, trail_price, ...) ?
Thanks
Odpowiedź
THanks for this script.
So value of stoploss should be in minval = 2 for 2% stoploss and minval = 2 for 2% take profit ?
Odpowiedź
how will you create alerts on
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)


as those are functions of strategy.exit, right?
+5 Odpowiedź
Could someone help me out here? I cannot seem to get this to work using the OP's reference.

// the risk management inputs
inpTakeProfit = input(defval = 1000, title = "Take Profit", minval = 0)
inpStopLoss = input(defval = 5000, title = "Stop Loss", minval = 0)
inpTrailStop = input(defval = 5000, 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


//STRATEGY LOGIC
// === STRATEGY - LONG POSITION EXECUTION ===
enterLong() => crossover(wt1,wt2) // functions can be used to wrap up and work out complex conditions
exitLong() => not crossunder(wt1, wt2)
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() => crossunder(wt1, wt2)
exitShort() => not crossover(wt1, wt2)
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)
Odpowiedź
singhizhem singhizhem
@singhizhem, The problem i am having is that it closes out within seconds no matter how much i change the parameters for the risk management inputs. My guess is the "EnterLong()" "exitLong()" "entershort()" and "exitshort()" are not correct. If someone can help, it will be much appreciated.
Odpowiedź
aboveBelow = maFast >= maSlow ? true : false )))
Odpowiedź
Thank you for a useful example. I was trying to use this and I have a question.
Let us say we execute strategy.close first because neither does take profit condition not the stoploss was met. Then the exit order that first place because of strategy.exit would still be pending (as far as I understand). Should we not have an explicit statement which is cancelling the strategy.exit order when strategy.close order is executed?
Thank you for any inputs
Odpowiedź
is it possible to use sectional Tp example, %50 TP %30 TP etc.
+2 Odpowiedź
TY
Odpowiedź
Strona główna Skaner akcji Skaner Forex Skaner Krypto Kalendarz ekonomiczny Show Jak to działa Funkcje wykresów Cena Dobre Praktyki Moderatorzy Rozwiązania internetowe i brokerskie Widżety Wykresy Lekka Biblioteka Wykresów Centrum Pomocy Poleć przyjaciela Zgłoś dodatkową funkcjonalność Blog i wiadomości Twitter
Profil Ustawienia profilu Konto i płatności Poleć przyjaciela Wiadomości do działu obsługi Centrum Pomocy Opublikowane Pomysły Obserwujący Lista obserwowanych Wiadomość prywatna Czat Wyloguj