1
votes

I am having trouble with the following:

I enter a strategy which is closed after close < ema. For the sake of a better exit, I would like to close it when close > ema but the low (of any given bar after the entry) is lower than ema (low < ema).

I cannot figure out how to do the 'any given bar after the entry' moment. I guess the script should somehow store the value of the previous bar if true, but then comes the problem with scripting when the strategy has actually started. Any help would be appreciated!

PS. As you can see I am not a coder and this is probably hard to understand. I really apoligize for it and thank you for your time.

Mihail

I have tried with stating when the entry condition is on with strategy.position_avg_price > 0, adding to it the desired conditions:

    h = nz(strategy.position_avg_price) > 0 and not 
    crossunder(close,ema(close,length)) and                         
    crossunder(low,ema(close,length)) ? 1 : 0 
    rightborder = barstate.islast // treat the last bar (most recent bar) 
    as the right edge of the lookback window range
    // if examining the last bar (newest bar, rightborder is true)
    // set variable "val" to the previous value of series variable "h"
    // else set to na so nothing is plotted
    val = rightborder ? h[1] : na

But without success...

    scalp = b and c and d and e and f and g  ? 1 : 0 // scalp is main 
    variable, if 1 the strategy is entered//
    if (scalp)
    strategy.entry("Short", strategy.short, when = scalp) // entry of 
    strategy
    if (crossunder(close,ema(close,length))) // usual close of strategy
    strategy.close("Short")
    if (not crossunder(close,ema(close,length)) and 
    crossunder(low,ema(close,length))) // attempt for a better exit!
    strategy.close("Short")    

After working on Mickey's suggestion:

///Entry 
if entry_on == 0 and scalp
 strategy.entry("Short", strategy.short) 
 entry_on := 1

///Desired exit 
if entry_on == 1 and crossunder(close,ema(close,length)) 
 strategy.close("Short") 
 entry_on := 0

/// Risk mitigation - 1 - Additional risk mitigation (when close > ema but 
low < ema of any given candle after entry -> exit at breakeven) 

if entry_on == 1 and close > ema(close, length) and low < ema(close, length) 
 entry_on := 2 

if entry_on == 2 and crossover(close,strategy.position_avg_price) 
 strategy.close("Short") 
 entry_on := 0

/// Risk mitigation - 2 - exit 15 bars after entry if not desired exit or 
risk mitigation - 1 

if entry_on == 1 and scalp[15] 
 strategy.close("Short") 
 entry_on := 0
1

1 Answers

3
votes

Try something like this:

entry_on = 0.0
entry_on := entry_on[1] //this will carry entry_on result from last candle
if entry_on == 0 and close > ema(close, length)
    xx enter your open position code
    entry_on := 1

if entry_on == 1
    if close < ema(close, length) or low < ema(close, length)
    xx enter your close position code
    entry_on := 0