//@version=4
strategy("YSPS Buy/Sell and Custom Incremental Partial Sell Strategy", overlay=true)
length = input(20, title="BB Length")
mult = input(2.0, title="BB MultFactor")
lengthKC = input(20, title="KC Length")
multKC = input(1.5, title="KC MultFactor")
useTrueRange = input(true, title="Use TrueRange (KC)")
thresholdType = input("Percentage", title="Sell Threshold Type", options=["Percentage", "Dollars", "Cents"])
sellThresholdValue = input(1.0, title="Sell Threshold Value")
incrementalSellPercent = input(1, title="Incremental Sell Percentage (%)")
// Calculate BB
source = close
basis = sma(source, length)
dev = mult * stdev(source, length)
upperBB = basis + dev
lowerBB = basis - dev
// Calculate KC
ma = sma(source, lengthKC)
range = useTrueRange ? tr : (high - low)
rangema = sma(range, lengthKC)
upperKC = ma + rangema * multKC
lowerKC = ma - rangema * multKC
// Buy and Sell conditions
val = linreg(source - avg(highest(high, lengthKC), lowest(low, lengthKC)), lengthKC, 0)
buySignal = crossover(val, 0)
sellSignal = crossunder(val, 0)
// Entry and exit strategy
strategy.entry("Buy", strategy.long, when = buySignal)
// Exit strategy, only if profitable
if (sellSignal and close > strategy.position_avg_price)
strategy.close("Buy", when = sellSignal)
// Incremental selling when profitable
var float sellThreshold = na
if (strategy.position_size > 0)
if (thresholdType == "Percentage")
sellThreshold := strategy.position_avg_price * (1 + sellThresholdValue / 100)
else if (thresholdType == "Dollars")
sellThreshold := strategy.position_avg_price + sellThresholdValue
else
sellThreshold := strategy.position_avg_price + sellThresholdValue / 100
incrementalSellCondition = strategy.position_size > 0 and close > sellThreshold
if (incrementalSellCondition)
strategy.close("Buy", qty_percent=incrementalSellPercent, when = incrementalSellCondition)
// Plot signals for manual alert setting
plotshape(series=buySignal, title="Buy Signal", location=location.belowbar, color=color.green, style=shape.labelup, text="Buy")
plotshape(series=sellSignal, title="Sell Signal", location=location.abovebar, color=color.red, style=shape.labeldown, text="Sell")
plotshape(series=incrementalSellCondition, title="Incremental Sell Signal", location=location.abovebar, color=color.purple, style=shape.labeldown, text="Incremental Sell")
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter