I am studying pinescript for trading view to backtest my strategy and trying simple strategy (only for long) with slow stochastics as an example.
If %K crossover %D, then long entry should be done at the next bar. Otherwise(if %K crossnuder %D), the position shall be exited at the next bar.
For entry, it works but exit does not work.
I already checked the documentation about strategy.entry() and strategy.exit().
https://www.tradingcode.net/tradingview/strategy-exit-function/
https://www.tradingcode.net/tradingview/strategy-entry-function/
Here is my script.
//@version=5
strategy(title="Slow Stochastics Crossover", overlay=true,
pyramiding=0, initial_capital=100000,
commission_type=strategy.commission.cash_per_order,
commission_value=4, slippage=2)
smoothK = input.int(3, minval=1), smoothD = input.int(3, minval=1)
k = ta.sma(ta.stoch(close, high, low, 14), smoothK)
d = ta.sma(k, smoothD)
atrLen = input.int(14, title="ATR Length")
atrValue = ta.atr(atrLen)
stopOffset = input.float(2, title="Stop Offset Multiple", step=.25)
profitOffset = input.float(3, title="Stop Offset Multiple", step=.25)
enterLong = ta.crossover(k, d)
exitLong = ta.crossunder(k, d)
longProfit = close + (profitOffset * atrValue)
longStop = 0.0
longStop := enterLong ? close - (stopOffset * atrValue) :
longStop[1]
// Position sizing inputs
usePosSize = input.bool(true, title="Use Position Sizing?")
maxRisk = input.float(2, title="Max Position Risk %", step=.25)
maxExposure = input.float(10, title="Max Position Exposure %", step=1)
marginPerc = input.int(10, title="Margin %")
riskEquity = (maxRisk * 0.01) * strategy.equity
riskTrade = (atrValue * stopOffset) * syminfo.pointvalue
maxPos = ((maxExposure * 0.01) * strategy.equity) /
((marginPerc * 0.01) * (close * syminfo.pointvalue))
posSize = usePosSize ? math.min(math.floor(riskEquity / riskTrade), maxPos) : 1
plot(k, color=color.orange, title="Fast SMA")
plot(d, color=color.teal, linewidth=2, title="Slow SMA")
plot(strategy.position_size > 0 ? longStop : na, color=color.green,
linewidth=2, style=plot.style_circles)
if enterLong
strategy.entry("EL", strategy.long, qty=posSize, stop=longStop)
strategy.exit("XL", from_entry="EL", stop=longStop)
if exitLong
strategy.exit("XL", from_entry="EL", limit=longProfit)

Two things:
You shouldn't use multiple strategy.exit()s for TP ad SL. The last one will modify the first one. You can combine both of them in a single strategy.exit().
You want to close your position conditionally whenever that crossunder() event happens. In that case, you should use strategy.close() and not `strategy.exit().
Below change will do:
if enterLong
strategy.entry("EL", strategy.long, qty=posSize, stop=longStop)
strategy.exit("XL", from_entry="EL", stop=longStop, limit=longProfit)
if exitLong
strategy.close("EL")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With