Search code examples
pine-scripttradingview-apiloss

In the tradingview pine-script strategy, I set a takeprofit and stoploss but it doesn't work properly


I am not a programmer and recently I am learning pine script, so I hope some kindly help. In order to describe my questions clearly, let's discuss it in the example of a "double EMA strategy". The codes are as below:

//@version=5
strategy("strategy learning", overlay=true, initial_capital=10000000)

ema1 = ta.ema(close, 10)
ema2 = ta.ema(close, 90)
plot(ema1, color=color.yellow)
plot(ema2, color=color.blue)


longcondition = ta.crossover(ema1, ema2)
strategy.entry("buy", strategy.long, qty=1, when = longcondition)
strategy.exit("buy", limit=strategy.position_avg_price*1.02, stop=strategy.position_avg_price*0.98)

shortcondition = ta.crossunder(ema1, ema2)
strategy.entry("sell", strategy.short, qty=1, when = shortcondition)
strategy.exit("sell", limit=strategy.position_avg_price*0.98, stop=strategy.position_avg_price*1.02)

Above codes are working properly and no errors but a suggestion.

Question1: Since it suggests use "if" instead of "when", so I replace "when" with "if" as below:

longcondition = ta.crossover(ema1, ema2)
if (longcondition)
strategy.entry("buy", strategy.long, qty=1)
strategy.exit("buy", limit=strategy.position_avg_price*1.02, stop=strategy.position_avg_price*0.98)

But it has error saying "Mismatched input 'strategy.entry' expecting 'end of line without line continuation'". Why this error happen????(since I newly registered in tackoverflow so I can't upload images, sorry)

Question2: You see the codes and can see that I set "strategy.position_avg_price*0.02" as both the stoploss and takeprofit. I expect that all orders will be closed either losing 2% or earning 2%. But when I checked the orders list, many orders are closed not at ±2%. Why???? How should I revise the codes and set stoploss and takeprofit properly?


Solution

  • Answer 1 It's an indentation issue, a tabulation character is missing before the strategy.entry line

    Should be like this and the strategy.exit not in the if statement which is to capture the entry condition

    if (longcondition)
        strategy.entry("buy", strategy.long, qty=1)
    

    strategy.exit("buy", limit=strategy.position_avg_price1.02, stop=strategy.position_avg_price0.98)

    Answer 2

    Could be due to slippage