'Pine Script - Entry Based on Price reached Certain Level or %

I am developing a strategy which is based on two condition.

First it look candle crossover the 200 EMA and once the crossover/crossunder happened. it will take the entry after the price reached 0.7% Up / Down from the crossover/crossunder.

Please help me to figure out this condition.

Thanks

//@version=5
strategy("Candle EMA %", pyramiding=0, overlay=true, initial_capital=220, calc_on_every_tick=false, currency=currency.USD, 
  default_qty_type=strategy.percent_of_equity, default_qty_value=100)


//EMA'S
len3 = input.int(200, minval=1, title="EMA #3")
src3 = input(close, title="EMA Source #3")
out3 = ta.ema(src3, len3)
plot(out3, title="EMA #3", color=close >= out3 ? color.white : color.white, linewidth = 2)


targetlong = close * 0.07
targetshort = close * 0.07


longEntryPrice  = ta.crossover(close, out3) and targetlong
shortEntryPrice = ta.crossunder(close, out3) and targetshort



//Entry Orders

if longEntryPrice
    strategy.entry("Buy", strategy.long)

if shortEntryPrice
    strategy.entry("Sell", strategy.short)


Solution 1:[1]

There are multiple issues that need to be sorted out.

  • A variable that is not boolean but have a value is always TRUE. Your longEntryPrice is a Float, which will be always true. Thus it is useless to use this variable in an and condition
  • Multiplying the close with 0.07 almost nullifies it which was probably not your intention, you wanted to check for a price that is larger by 0.7% than close. That would be close * 1.007. First you have to use 1. in the multiplier to take into account close itself, second: 0.7% is 0.007 if expressed in Float (as 0.01 or one-hundredth is 1 percent)
  • You need to spend some time to understand how Pine works and runs your script on every bar, unfortunately it is not straighforward. Every variable's value is reset before each run so their value is lost. When your script runs on - say - bar #15, the value of your targetlong is calculated on that bar and at the next run of the script on bar #16, that calculated value becomes "previous" and is lost from targetlong. However on bar #16 the previous value will be available as targetlong[1]. (it is inferred that the current targetlong is the same as targetlong[0]

As you want to compare the current - modified - close to the previous close you need to use this formula:

targetlong = close[1] * 1.007 // this will calculate the expected price increase based on the previous Close
.
.
.
longEntryPrice  = ta.crossover(close, out3) and close > targetLong // we compare the current Close value to the previous, modified Close value.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 karatedog