USER
convert to a strategy
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © scottclayton22
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © BackQuant
import TradingView/ta/7 as ta
//@version=5
indicator(
title="DEMA Adaptive DMI [BackQuant]",
shorttitle = "DEMA DMI [BackQuant]",
overlay=false,
timeframe="",
timeframe_gaps=true
)
// Define User Inputs
const string group1 = "Calculation"
const string group2 = "UI Settings"
simple int len_dema = input.int(15, minval=1, title = "DEMA Calculation Period", tooltip = "The DEMA is being used as the source for the DMI Calculation", group = group1 )
simple int di_len = input.int(18, minval=1, title = "DI Length", group = group1 )
simple int adx_smoothing_len = input.int(18, minval=1, title = "ADX Smoothing Period", group = group1 )
simple bool showdivergences = input.bool(false, "Show Detected Divergences?", group = 'DIVERGENCES')
simple int lbR = input.int(title="Pivot Lookback Right", defval=10,group = 'DIVERGENCES', inline = "div")
simple int lbL = input.int(title="Pivot Lookback Left", defval=10,group = 'DIVERGENCES', inline = "div")
simple int signalLen = 7
simple bool showoboslvls = input.bool(true, "Show Static High and Low Levels (Extreme DMI Thresholds)", group =group2)
simple bool paintCandles = input.bool(false, "Color Bars According to Trend?", tooltip = "If DMI > 0 bar will be green and turn to red when it is below 0", group =group2)
simple bool show_big_ob_os = input.bool(true, "Show Extreme Value Background Hues?", group =group2)
simple int ob_trigger = input.int(30, "Extreme OB (Upper) Thresholds", group = group2)
simple int os_trigger = input.int(-30, "Extreme OS (Lower) Thresholds", group = group2)
// DEMA DMI Function
dema_dmi(len_dema, di_len, adx_smoothing_len)=>
demah = ta.dema(high, len_dema)
demal = ta.dema(low, len_dema)
u = ta.change(demah)
d = -ta.change(demal)
p = na(u) ? na : (u > d and u > 0 ? u : 0)
m = na(d) ? na : (d > u and d > 0 ? d : 0)
t = ta.rma(ta.tr, di_len)
plus = fixnan(100 * ta.rma(p, di_len) / t)
minus = fixnan(100 * ta.rma(m, di_len) / t)
sum = plus + minus
adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), adx_smoothing_len)
[adx,plus,minus]
[adx, plus, minus]=dema_dmi(len_dema, di_len, adx_smoothing_len)
// Long and Short Conditions
x = adx > adx[1]
dmil = plus > minus
dmis = minus > plus
L = dmil
S = dmis
var score = 0
if L and not S
score := 1
if S
score := -1
hist_color = score == 1 ? #33ff00fc : score == -1 ? #ff0000 : color.gray
plotosc = plus - minus
// Plotting
var plotcol = #1dcaff4d
if plotosc > 0 and plotosc < 5
plotcol := #1dcaff4d
if plotosc > 0 and plotosc > 5
plotcol := #1e9b254d
if plotosc > 0 and plotosc > 10
plotcol := #00ff003d
if plotosc > 0 and plotosc > 20
plotcol := #00ff0080
if plotosc > 0 and plotosc > 25
plotcol := #33ff00fc
if plotosc < 0 and plotosc > -5
plotcol := #e651004d
if plotosc < 0 and plotosc < -5
plotcol := #7715154d
if plotosc < 0 and plotosc < -10
plotcol := #ff00004d
if plotosc < 0 and plotosc < -20
plotcol := #ff000080
if plotosc < 0 and plotosc < -25
plotcol := #ff0000
plot((plus - minus), title="DMI Histogram", color=plotcol, style=plot.style_columns, linewidth=2)
// Other UI Features
osbgcol = #00e6764d
obbgcol = #ff52524d
obcol = #ff0000fc
oscol = #00ff00fc
midcol = #ffffff4d
barcolor = #00000000
obupper = plot(showoboslvls ? 30 : na , "+", obcol, editable = false)
osupper = plot(showoboslvls ? -20 : na , "-", oscol, editable = false)
oblower = plot(showoboslvls ? 20 : na , "+", obcol, editable = false)
oslower = plot(showoboslvls ? -30 : na , "-", oscol, editable = false)
fill(obupper, oblower, #7715154d, 'OB Fill')
fill(osupper, oslower, #1e9b254d, 'OS Fill')
midline = hline(0, "0 Line", midcol, hline.style_solid)
barcolor(paintCandles ? ((plus - minus) > 0 ? #00ff00fc : #ff0000fc) : na)
bgcolor(show_big_ob_os?(plus-minus>ob_trigger?obbgcol:na):na)
bgcolor(show_big_ob_os?(plus-minus<os_trigger?osbgcol:na):na)
// Divergences
bearColor = obcol
bullColor = oscol
hiddenBullColor = color.new(oscol, 50)
hiddenBearColor = color.new(obcol, 50)
textColor = color.white
noneColor = color.new(color.white, 100)
plFound = na(ta.pivotlow(plotosc, lbL, lbR)) ? false : true
phFound = na(ta.pivothigh(plotosc, lbL, lbR)) ? false : true
_inRange(cond) =>
bars = ta.barssince(cond == true)
-80 <= bars and bars <= 80
//------------------------------------------------------------------------------
// Regular Bullish
// MOM: Higher Low
oscHL = plotosc[lbR] > ta.valuewhen(plFound, plotosc[lbR], 1) and _inRange(plFound[1])
// Price: Lower Low
priceLL = low[lbR] < ta.valuewhen(plFound, low[lbR], 1)
bullCond = showdivergences and priceLL and oscHL and plFound
plot(
plFound ? plotosc[lbR] : na,
offset=-lbR,
title="Regular Bullish",
linewidth=2,
color=(bullCond ? bullColor : noneColor)
)
plotshape(
bullCond ? plotosc[lbR] : na,
offset=-lbR,
title="Regular Bullish Label",
text="ℝ",
style=shape.labelup,
location=location.absolute,
color=bullColor,
textcolor=textColor
)
//------------------------------------------------------------------------------
// Hidden Bullish
// MOM: Lower Low
oscLL = plotosc[lbR] < ta.valuewhen(plFound, plotosc[lbR], 1) and _inRange(plFound[1])
// Price: Higher Low
priceHL = low[lbR] > ta.valuewhen(plFound, low[lbR], 1)
hiddenBullCond = showdivergences and priceHL and oscLL and plFound
plot(
plFound ? plotosc[lbR] : na,
offset=-lbR,
title="Hidden Bullish",
linewidth=2,
color=(hiddenBullCond ? hiddenBullColor : noneColor)
)
plotshape(
hiddenBullCond ? plotosc[lbR] : na,
offset=-lbR,
title="Hidden Bullish Label",
text="ℍ",
style=shape.labelup,
location=location.absolute,
color=bullColor,
textcolor=textColor
)
//------------------------------------------------------------------------------
// Regular Bearish
// MOM: Lower High
oscLH = plotosc[lbR] < ta.valuewhen(phFound, plotosc[lbR], 1) and _inRange(phFound[1])
// Price: Higher High
priceHH = high[lbR] > ta.valuewhen(phFound, high[lbR], 1)
bearCond = showdivergences and priceHH and oscLH and phFound
plot(
phFound ? plotosc[lbR] : na,
offset=-lbR,
title="Regular Bearish",
linewidth=2,
color=(bearCond ? bearColor : noneColor)
)
plotshape(
bearCond ? plotosc[lbR] : na,
offset=-lbR,
title="Regular Bearish Label",
text="ℝ",
style=shape.labeldown,
location=location.absolute,
color=bearColor,
textcolor=textColor
)
//------------------------------------------------------------------------------
// Hidden Bearish
// MOM: Higher High
oscHH = plotosc[lbR] > ta.valuewhen(phFound, plotosc[lbR], 1) and _inRange(phFound[1])
// Price: Lower High
priceLH = high[lbR] < ta.valuewhen(phFound, high[lbR], 1)
hiddenBearCond = showdivergences and priceLH and oscHH and phFound
plot(
phFound ? plotosc[lbR] : na,
offset=-lbR,
title="Hidden Bearish",
linewidth=2,
color=(hiddenBearCond ? hiddenBearColor : noneColor)
)
plotshape(
hiddenBearCond ? plotosc[lbR] : na,
offset=-lbR,
title="Hidden Bearish Label",
text="ℍ",
style=shape.labeldown,
location=location.absolute,
color=bearColor,
textcolor=textColor
)
// Alert Conditions
alertcondition(ta.crossover(plus - minus, 0), title="DEMA DMI Long", message="DEMA DMI Long {{exchange}}:{{ticker}}")
alertcondition(ta.crossunder(plus - minus, 0), title="DEMA DMI Short", message="DEMA DMI Short {{exchange}}:{{ticker}}")
alertcondition(plus-minus>30, title="DEMA DMI OB", message="DEMA DMI OB {{exchange}}:{{ticker}}")
alertcondition(plus-minus<-30, title="DEMA DMI OS", message="DEMA DMI OS {{exchange}}:{{ticker}}")
ASSISTANT
To convert your indicator into a strategy, you'll need to change the script type from `indicator` to `strategy` and implement entry and exit conditions using `strategy.entry` and `strategy.exit` functions. Below is the converted strategy code based on your original script:
```pine
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © scottclayton22
//@version=5
strategy(
title="DEMA Adaptive DMI Strategy",
shorttitle = "DEMA DMI Strategy",
overlay=false,
default_qty_type=strategy.percent_of_equity,
default_qty_value=10, // Adjust the position size as desired
initial_capital=10000,
currency=currency.USD,
commission_type=strategy.commission.percent,
commission_value=0.0
)
// Define User Inputs
const string group1 = "Calculation"
const string group2 = "UI Settings"
const string group3 = "Divergences"
len_dema = input.int(15, minval=1, title = "DEMA Calculation Period", tooltip = "The DEMA is being used as the source for the DMI Calculation", group = group1 )
di_len = input.int(18, minval=1, title = "DI Length", group = group1 )
adx_smoothing_len = input.int(18, minval=1, title = "ADX Smoothing Period", group = group1 )
showdivergences = input.bool(false, "Show Detected Divergences?", group = group3)
lbR = input.int(10, minval=1, title="Pivot Lookback Right", group = group3)
lbL = input.int(10, minval=1, title="Pivot Lookback Left", group = group3)
showoboslvls = input.bool(true, "Show Static High and Low Levels (Extreme DMI Thresholds)", group =group2)
paintCandles = input.bool(false, "Color Bars According to Trend?", tooltip = "If DMI > 0 bar will be green and turn to red when it is below 0", group =group2)
show_big_ob_os = input.bool(true, "Show Extreme Value Background Hues?", group =group2)
ob_trigger = input.int(30, "Extreme OB (Upper) Thresholds", group = group2)
os_trigger = input.int(-30, "Extreme OS (Lower) Thresholds", group = group2)
// DEMA DMI Function
dema_dmi(len_dema, di_len, adx_smoothing_len)=>
demah = ta.dema(high, len_dema)
demal = ta.dema(low, len_dema)
u = ta.change(demah)
d = -ta.change(demal)
p = na(u) ? na : (u > d and u > 0 ? u : 0)
m = na(d) ? na : (d > u and d > 0 ? d : 0)
t = ta.rma(ta.tr, di_len)
plus = fixnan(100 * ta.rma(p, di_len) / t)
minus = fixnan(100 * ta.rma(m, di_len) / t)
sum = plus + minus
adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), adx_smoothing_len)
[adx,plus,minus]
[adx, plus, minus] = dema_dmi(len_dema, di_len, adx_smoothing_len)
// Calculate Histogram Value
plotosc = plus - minus
// Entry conditions
longCondition = ta.crossover(plotosc, 0)
shortCondition = ta.crossunder(plotosc, 0)
// Strategy Entry Orders
if (longCondition)
strategy.entry("Trade", strategy.long)
if (shortCondition)
strategy.entry("Trade", strategy.short)
// Plotting Histogram
var plotcol = #1dcaff4d
if plotosc > 0 and plotosc < 5
plotcol := #1dcaff4d
if plotosc > 5 and plotosc <= 10
plotcol := #1e9b254d
if plotosc > 10 and plotosc <= 20
plotcol := #00ff003d
if plotosc > 20 and plotosc <= 25
plotcol := #00ff0080
if plotosc > 25
plotcol := #33ff00fc
if plotosc < 0 and plotosc > -5
plotcol := #e651004d
if plotosc <= -5 and plotosc > -10
plotcol := #7715154d
if plotosc <= -10 and plotosc > -20
plotcol := #ff00004d
if plotosc <= -20 and plotosc > -25
plotcol := #ff000080
if plotosc <= -25
plotcol := #ff0000
plot(plotosc, title="DMI Histogram", color=plotcol, style=plot.style_columns, linewidth=2)
// Other UI Features
osbgcol = #00e6764d
obbgcol = #ff52524d
obcol = #ff0000fc
oscol = #00ff00fc
midcol = #ffffff4d
barcolor = #00000000
obupper = plot(showoboslvls ? 30 : na , "+", obcol, editable = false)
osupper = plot(showoboslvls ? -20 : na , "-", oscol, editable = false)
oblower = plot(showoboslvls ? 20 : na , "+", obcol, editable = false)
oslower = plot(showoboslvls ? -30 : na , "-", oscol, editable = false)
fill(obupper, oblower, #7715154d, 'OB Fill')
fill(osupper, oslower, #1e9b254d, 'OS Fill')
midline = hline(0, "0 Line", midcol, hline.style_solid)
barcolor(paintCandles ? (plotosc > 0 ? #00ff00fc : #ff0000fc) : na)
bgcolor(show_big_ob_os ? (plotosc > ob_trigger ? obbgcol : na) : na)
bgcolor(show_big_ob_os ? (plotosc < os_trigger ? osbgcol : na) : na)
// Divergences
bearColor = obcol
bullColor = oscol
hiddenBullColor = color.new(oscol, 50)
hiddenBearColor = color.new(obcol, 50)
textColor = color.white
noneColor = color.new(color.white, 100)
plFound = na(ta.pivotlow(plotosc, lbL, lbR)) ? false : true
phFound = na(ta.pivothigh(plotosc, lbL, lbR)) ? false : true
_inRange(cond) =>
bars = ta.barssince(cond == true)
-80 <= bars and bars <= 80
// Regular Bullish Divergence
oscHL = plotosc[lbR] > ta.valuewhen(plFound, plotosc[lbR], 1) and _inRange(plFound[1])
priceLL = low[lbR] < ta.valuewhen(plFound, low[lbR], 1)
bullCond = showdivergences and priceLL and oscHL and plFound
plot(
plFound ? plotosc[lbR] : na,
offset=-lbR,
title="Regular Bullish",
linewidth=2,
color=(bullCond ? bullColor : noneColor)
)
plotshape(
bullCond ? plotosc[lbR] : na,
offset=-lbR,
title="Regular Bullish Label",
text="ℝ",
style=shape.labelup,
location=location.absolute,
color=bullColor,
textcolor=textColor
)
// Hidden Bullish Divergence
oscLL = plotosc[lbR] < ta.valuewhen(plFound, plotosc[lbR], 1) and _inRange(plFound[1])
priceHL = low[lbR] > ta.valuewhen(plFound, low[lbR], 1)
hiddenBullCond = showdivergences and priceHL and oscLL and plFound
plot(
plFound ? plotosc[lbR] : na,
offset=-lbR,
title="Hidden Bullish",
linewidth=2,
color=(hiddenBullCond ? hiddenBullColor : noneColor)
)
plotshape(
hiddenBullCond ? plotosc[lbR] : na,
offset=-lbR,
title="Hidden Bullish Label",
text="ℍ",
style=shape.labelup,
location=location.absolute,
color=bullColor,
textcolor=textColor
)
// Regular Bearish Divergence
oscLH = plotosc[lbR] < ta.valuewhen(phFound, plotosc[lbR], 1) and _inRange(phFound[1])
priceHH = high[lbR] > ta.valuewhen(phFound, high[lbR], 1)
bearCond = showdivergences and priceHH and oscLH and phFound
plot(
phFound ? plotosc[lbR] : na,
offset=-lbR,
title="Regular Bearish",
linewidth=2,
color=(bearCond ? bearColor : noneColor)
)
plotshape(
bearCond ? plotosc[lbR] : na,
offset=-lbR,
title="Regular Bearish Label",
text="ℝ",
style=shape.labeldown,
location=location.absolute,
color=bearColor,
textcolor=textColor
)
// Hidden Bearish Divergence
oscHH = plotosc[lbR] > ta.valuewhen(phFound, plotosc[lbR], 1) and _inRange(phFound[1])
priceLH = high[lbR] < ta.valuewhen(phFound, high[lbR], 1)
hiddenBearCond = showdivergences and priceLH and oscHH and phFound
plot(
phFound ? plotosc[lbR] : na,
offset=-lbR,
title="Hidden Bearish",
linewidth=2,
color=(hiddenBearCond ? hiddenBearColor : noneColor)
)
plotshape(
hiddenBearCond ? plotosc[lbR] : na,
offset=-lbR,
title="Hidden Bearish Label",
text="ℍ",
style=shape.labeldown,
location=location.absolute,
color=bearColor,
textcolor=textColor
)
// Alert Conditions
alertcondition(longCondition, title="DEMA DMI Long", message="DEMA DMI Long on {{ticker}}")
alertcondition(shortCondition, title="DEMA DMI Short", message="DEMA DMI Short on {{ticker}}")
alertcondition(plotosc > 30, title="DEMA DMI Overbought", message="DEMA DMI Overbought on {{ticker}}")
alertcondition(plotosc < -30, title="DEMA DMI Oversold", message="DEMA DMI Oversold on {{ticker}}")
```
**Explanation of Changes:**
- **Script Type Change:** Changed from `indicator` to `strategy` to enable backtesting and trading functionalities.
- **Entry Conditions:** Implemented `strategy.entry` to open positions when the `plotosc` crosses over zero for longs and crosses under zero for shorts.
- **Position Management:** By using the same order ID `"Trade"` in `strategy.entry`, the strategy automatically handles position reversal when a new signal is generated.
- **Removed Unnecessary Variables:** Omitted variables and conditions related to plotting that are not essential for the strategy execution.
- **Alerts Update:** Modified alert conditions to correspond with the new strategy logic.
**How It Works:**
- **Long Entry:** When the `plotosc` histogram crosses above zero, the strategy enters a long position.
- **Short Entry:** When the `plotosc` histogram crosses below zero, the strategy enters a short position.
- **Position Reversal:** Using the same order ID allows the strategy to reverse positions automatically without the need for explicit exit commands.
- **Plotting and Visuals:** The plotting code is retained for visualization purposes, so you can see the DMI histogram and divergence signals on the chart.
**Note:**
- **Position Sizing:** Adjust the `default_qty_value` to control the percentage of equity used per trade.
- **Testing Period:** Use the strategy tester to evaluate performance over different timeframes and market conditions.
- **Risk Management:** Consider implementing stop-loss and take-profit levels for better risk management.
Feel free to adjust the parameters and conditions to better suit your trading style and to optimize the strategy's performance.