'Pine Script Strategy - Position Entry directly after Exit
i want to do a strategy that entries a position at the buy-level (blue Line) and sells after reaching the take-profit-Level (green line) or the stop-level (red line).
It works for the first step: The strategy buys in at the blue line, sells at the green line. But then after exiting the trade many entry/exits are done by the script (see picture).
After one trade is taken for the condition and i got take-profit or stopped-out, I don't want the strategy to dot another trade.
I'm sitting now for hours, maybe you can help me =)
//@version=5
strategy("Strategy", overlay=true)
BB = high>high[1] and low<low[1]
var float BB_high=0
var float BB_low=0
if (BB==true)
BB_high := high
BB_low := low
plotshape (BB, style=shape.triangleup, location=location.abovebar, color=color.green, size=size.small)
plotshape (BB, style=shape.triangledown, location=location.belowbar, color=color.red, size=size.small)
plot(BB_high)
plot(BB_low)
//Stoploss + Take profit
SL = input.float(0.5, step=0.1)
TP = input.float(2.5, step=0.1)
buyprice = BB_high
longstop = BB_high - (BB_high - BB_low)*SL
longprofit = BB_high + (BB_high - BB_low)/2 * TP
plot (longstop, color=color.red, linewidth=2)
plot (longprofit, color=color.green, linewidth=2)
//Position entry + exit (stoploss or takeprofit)
if strategy.position_size == 0
strategy.entry("Buy", strategy.long, stop=buyprice)
if strategy.position_size >0
strategy.exit (id="Exit Long", from_entry="Buy", stop=longstop, limit=longprofit)
Solution 1:[1]
As you see on your screenshot, you enter position with TP below entry, so it's instantly closed, same thing can happen on poorly designed exchange when you confuse TP with SL when setting. You don't have also any long condition, just long whenever it's flat. If you want to limit on blue line then use limit order:
if strategy.position_size == 0
strategy.entry("Buy", strategy.long, limit=buyprice)
Additionally plot limit order:
plot(strategy.position_size<= 0 ? buyprice : na, title="Limit order", color=color.blue, offset=1)
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 | Spy |