[SOLVED] How Can I Set SL and TP?

Issue

This Content is from Stack Overflow. Question asked by Mohammad Hasanpoor

i have strategy for entry and my stop loss is low of before candle.
and my tp is R/R 3 that it set according to Stoploss.

i wrote code but it not work.

strategy.entry(“Long Position”,strategy.long,when = LongEntry)
strategy.exit(“Exit Long” , from_entry = “Long Position” , stop = low[1] , profit = 3*low[1] )

what is problem?



Solution

The problem is, you will be updating your stop loss and take profit prices on every bar as it is written in your example. Because, with every new bar, there will be a new low value. And with every new bar, your strategy.exit() function will be called.

What you can do is, store the low price at the time of the entry and use it in your strategy.exit() call.

var float low_at_entry = na

if (LongEntry)
    low_at_entry := low

strategy.entry("Long Position",strategy.long,when = LongEntry)

if (strategy.position_size > 0)
    strategy.exit("Exit Long" , from_entry = "Long Position" , stop = low_at_entry [1] , profit = 3*low_at_entry [1] )

Note: You need to make sure that your LongEntry is true only once during a trade. Otherwise low_at_entry will be updated after the entry again.


This Question was asked in StackOverflow by Mohammad Hasanpoor and Answered by vitruvius It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?