Reputation: 53
I am trying to set an entry order (long or short) when the price reaches a % above or below previous entry.
Right now I am setting an exit order to trigger the exit at that exact value, using limit
and stop
strategy.exit("Exit Buy", from_entry = "Buy", stop=level_dn, limit=level_up)
What I want to achieve is to enter a new order at the exact same price value.
I read that on historical bars is impossible to achieve that because we only execute on H,L,O,C even when using calc_on_order_fills
I am wondering if there is any way to achieve it on real time bars.
Upvotes: 1
Views: 848
Reputation: 333
You can save the previous entry price in a var variable. That type of variable keeps the value between bars.
var float last_order_price = an
Then you check if the price has gone up by 2% by dividing the last_order_price by the current price, and if that value is over 1.02 then you sell.
Here is some code that first buys when the two SMA lines cross. Then it sells when it has 2% profit. It is a bit funny that the Precent Profitable is 94% and the Profit Factor is 72. It is a very safe trading style.
Code:
// This source code is subject to the terms of the Mozilla Public License 2.0 at
https://mozilla.org/MPL/2.0/
// © CanYouCatchMe
//@version=4
strategy("My Strategy", overlay=true, margin_long=100, margin_short=100)
var float last_order_price = na
if (crossover(sma(close, 14), sma(close, 28)) and na(last_order_price)) //Need to check if "last_order_price" is "na", else it would change the "last_order_price" value
strategy.entry("Long", strategy.long)
last_order_price := open
if (open / last_order_price >= 1.02) //2% or more profit
strategy.close("Long")
last_order_price := na
plot(sma(close, 14))
plot(sma(close, 28))
Upvotes: 1