name
stringlengths 1
64
| url
stringlengths 44
135
| author
stringlengths 3
30
| author_url
stringlengths 34
61
| likes_count
int64 0
33.2k
| kind
stringclasses 3
values | pine_version
int64 1
5
| license
stringclasses 3
values | source
stringlengths 177
279k
|
---|---|---|---|---|---|---|---|---|
MACD Strategy | https://www.tradingview.com/script/qxuLu0Lk/ | maxencetajet | https://www.tradingview.com/u/maxencetajet/ | 102 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © maxencetajet
//@version=5
strategy("MACD Strategy", overlay=true, initial_capital=1000)
tlpc = input.string(title="Alert", defval="PineConnector", options=["PineConnector", "Telegram"], tooltip="Go to alertatron to have alerts automatically sent to Telegram")
// Setting
ID = input("1234567890123", title="License ID (PineConnector)", group="Setting")
risk = input.float(2, title="Risk per Trade %", group="Setting", step=0.5)
typeSL = input.string(title="StopLoss", defval="Swing", options=["Swing", "ATR"], group="Setting")
typeTP = input.string(title="TakeProfit", defval="R:R", options=["R:R", "Multiple Target"], group="Setting")
_x = input.bool(false, title="do not take too small positions", group="Setting", tooltip="This parameter is used to avoid positions that have a stoploss too close to the entry point and that the broker's spreads take all the gains")
security = input.float(10, title="min of pips (00001.00)", group="Setting")
riskt = risk / 100 + 1
useDateFilter = input.bool(false, title="Filter Date Range of Backtest", group="Backtest Time Period")
backtestStartDate = input.time(timestamp("1 June 2022"), title="Start Date", group="Backtest Time Period", tooltip="This start date is in the time zone of the exchange " + "where the chart's instrument trades. It doesn't use the time " + "zone of the chart or of your computer.")
backtestEndDate = input.time(timestamp("1 July 2022"), title="End Date", group="Backtest Time Period", tooltip="This end date is in the time zone of the exchange " + "where the chart's instrument trades. It doesn't use the time " + "zone of the chart or of your computer.")
inTradeWindow = not useDateFilter or (time >= backtestStartDate and time < backtestEndDate)
//StopLoss
swingHighV = input.int(7, title="Swing High", group="Stop Loss", tooltip="Number of candles in which the parameter targets the highest")
swingLowV = input.int(7, title="Swing Low", group="Stop Loss", tooltip="Number of candles in which the parameter targets the lowest")
atr1 = input.int(14, title="ATR Period", group="Stop Loss")
atrMultiplierSL = input.int(2, title = "ATR Multiplier", group="Stop Loss")
atr = ta.atr(atr1)
swingHigh = ta.highest(high, swingHighV)
swingLow = ta.lowest(low, swingLowV)
atrSell = close + atr * atrMultiplierSL
atrBuy = close - atr * atrMultiplierSL
//TakeProfit
target_stop_ratio = input.float(title='Risk/Reward (R:R)', defval=3, minval=0.5, maxval=100, step=0.1, group="TakeProfit")
target1 = input.float(1, title='Target 1 R:R (Multiple Target)', group="TakeProfit", step=0.1, tooltip="SL moved to entry point if hit")
target2 = input.float(2, title='Target 2 R:R (Multiple Target)', group="TakeProfit", step=0.1)
//EMA
src1 = input(title="Source", defval=close, group="EMA")
emaV = input.int(200, title="Length", group="EMA")
ema = ta.ema(src1, emaV)
//Parabolic SAR
sarT = input.bool(true, title="Parabolic SAR Indicator", group="Parabolic SAR")
start = input(0.02, group="Parabolic SAR")
increment = input(0.02, group="Parabolic SAR")
maximum = input(0.2, "Max Value", group="Parabolic SAR")
SAR = ta.sar(start, increment, maximum)
myColor = SAR < low ? color.green : color.red
//MACD
src = input(title="Source", defval=close, group="MACD")
fast_length = input(title="Fast Length", defval=12, group="MACD")
slow_length = input(title="Slow Length", defval=26, group="MACD")
signal_length = input.int(title="Signal Smoothing", minval = 1, maxval = 50, defval = 9, group="MACD")
sma_source = input.string(title="Oscillator MA Type", defval="EMA", options=["SMA", "EMA"], group="MACD")
sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"], group="MACD")
fast_ma = sma_source == "SMA" ? ta.sma(src, fast_length) : ta.ema(src, fast_length)
slow_ma = sma_source == "SMA" ? ta.sma(src, slow_length) : ta.ema(src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)
hist = macd - signal
//Alert
getpips() =>
syminfo.mintick * (syminfo.type == "forex" ? 10 : 1)
mess_buyT = "📈 𝗔𝗖𝗛𝗔𝗧 🔵 " + str.tostring(syminfo.ticker) + "\n \n" + "Prix d'entrée " + str.tostring(close) + "\n" + "SL " + str.tostring(swingLow) + " ⛔️ \n" + "TP " + str.tostring(((close-swingLow)*target_stop_ratio)+close) + " 🎯 \n \n" + "⚠️ Avertissement : Respectez votre money management, risquez seulement " + str.tostring(risk) + "% de votre capital sur ce trade."
mess_sellT = "📉 𝗩𝗘𝗡𝗧𝗘 🔴 " + str.tostring(syminfo.ticker) + "\n \n" + "Prix d'entrée " + str.tostring(close) + "\n" + "SL " + str.tostring(swingHigh) + " ⛔️ \n" + "TP " + str.tostring(close-((swingHigh-close)*target_stop_ratio)) + " 🎯 \n \n" + "⚠️ Avertissement : Respectez votre money management, risquez seulement " + str.tostring(risk) + "% de votre capital sur ce trade."
mess_buyP = "" + str.tostring(ID) + ",buy," + str.tostring(syminfo.ticker) + ",sl=" + str.tostring(swingLow) + ",tp=" + str.tostring(((close-swingLow)*target_stop_ratio)+close) + ",risk=" + str.tostring(risk) + ""
mess_sellP = "" + str.tostring(ID) + ",sell," + str.tostring(syminfo.ticker) + ",sl=" + str.tostring(swingHigh) + ",tp=" + str.tostring(close-((swingHigh-close)*target_stop_ratio)) + ",risk=" + str.tostring(risk) + ""
mess_buyAT = "📈 𝗔𝗖𝗛𝗔𝗧 🔵 " + str.tostring(syminfo.ticker) + "\n \n" + "Prix d'entrée " + str.tostring(close) + "\n" + "SL " + str.tostring(atrBuy) + " ⛔️ \n" + "TP " + str.tostring(((close-atrBuy)*target_stop_ratio)+close) + " 🎯 \n \n" + "⚠️ Avertissement : Respectez votre money management, risquez seulement " + str.tostring(risk) + "% de votre capital sur ce trade."
mess_sellAT = "📉 𝗩𝗘𝗡𝗧𝗘 🔴 " + str.tostring(syminfo.ticker) + "\n \n" + "Prix d'entrée " + str.tostring(close) + "\n" + "SL " + str.tostring(atrSell) + " ⛔️ \n" + "TP " + str.tostring(close-((atrSell-close)*target_stop_ratio)) + " 🎯 \n \n" + "⚠️ Avertissement : Respectez votre money management, risquez seulement " + str.tostring(risk) + "% de votre capital sur ce trade."
mess_buyAP = "" + str.tostring(ID) + ",buy," + str.tostring(syminfo.ticker) + ",sl=" + str.tostring(atrBuy) + ",tp=" + str.tostring(((close-atrBuy)*target_stop_ratio)+close) + ",risk=" + str.tostring(risk) + ""
mess_sellAP = "" + str.tostring(ID) + ",sell," + str.tostring(syminfo.ticker) + ",sl=" + str.tostring(atrSell) + ",tp=" + str.tostring(close-((atrSell-close)*target_stop_ratio)) + ",risk=" + str.tostring(risk) + ""
mess_buyAMT = "📈 𝗔𝗖𝗛𝗔𝗧 🔵 " + str.tostring(syminfo.ticker) + "\n \n" + "Prix d'entrée " + str.tostring(close) + "\n" + "SL " + str.tostring(atrBuy) + " ⛔️ \n" + "TP1 " + str.tostring(((close-atrBuy)*target1)+close) + " 🎯 \n" + "TP2 " + str.tostring(((close-atrBuy)*target2)+close) + "🎯 \n \n" + "⚠️ Avertissement : Respectez votre money management, risquez seulement " + str.tostring(risk) + "% de votre capital sur ce trade. BE si TP1 touché"
mess_sellAMT = "📉 𝗩𝗘𝗡𝗧𝗘 🔴 " + str.tostring(syminfo.ticker) + "\n \n" + "Prix d'entrée " + str.tostring(close) + "\n" + "SL " + str.tostring(atrSell) + " ⛔️ \n" + "TP1 " + str.tostring(close-((atrSell-close)*target1)) + " 🎯 \n" + "TP2 " + str.tostring(close-((atrSell-close)*target2)) + "🎯 \n \n" + "⚠️ Avertissement : Respectez votre money management, risquez seulement " + str.tostring(risk) + "% de votre capital sur ce trade. BE si TP1 touché"
mess_buyAMP1 = "" + str.tostring(ID) + ",buy," + str.tostring(syminfo.ticker) + ",sl=" + str.tostring(atrBuy) + ",tp=" + str.tostring(((close-atrBuy)*target1)+close) + ",risk=" + str.tostring(risk/2) + ""
mess_buyAMP2 = "" + str.tostring(ID) + ",buy," + str.tostring(syminfo.ticker) + ",sl=" + str.tostring(atrBuy) + ",tp=" + str.tostring(((close-atrBuy)*target2)+close) + ",risk=" + str.tostring(risk/2) + ",betrigger=" + str.tostring(((((close-atrBuy)*target1)+close)-close)/getpips()) + ",beoffset=0"
mess_sellAMP1 = "" + str.tostring(ID) + ",sell," + str.tostring(syminfo.ticker) + ",sl=" + str.tostring(atrSell) + ",tp=" + str.tostring(close-((atrSell-close)*target1)) + ",risk=" + str.tostring(risk/2) + ""
mess_sellAMP2 = "" + str.tostring(ID) + ",sell," + str.tostring(syminfo.ticker) + ",sl=" + str.tostring(atrSell) + ",tp=" + str.tostring(close-((atrSell-close)*target2)) + ",risk=" + str.tostring(risk/2) + ",betrigger=" + str.tostring((close-(close-((atrSell-close)*target1)))/getpips()) + ",beoffset=0"
mess_buyMT = "📈 𝗔𝗖𝗛𝗔𝗧 🔵 " + str.tostring(syminfo.ticker) + "\n \n" + "Prix d'entrée " + str.tostring(close) + "\n" + "SL " + str.tostring(swingLow) + " ⛔️ \n" + "TP1 " + str.tostring(((close-swingLow)*target1)+close) + " 🎯 \n" + "TP2 " + str.tostring(((close-swingLow)*target2)+close) + "🎯 \n \n" + "⚠️ Avertissement : Respectez votre money management, risquez seulement " + str.tostring(risk) + "% de votre capital sur ce trade. BE si TP1 touché"
mess_sellMT = "📉 𝗩𝗘𝗡𝗧𝗘 🔴 " + str.tostring(syminfo.ticker) + "\n \n" + "Prix d'entrée " + str.tostring(close) + "\n" + "SL " + str.tostring(swingHigh) + " ⛔️ \n" + "TP1 " + str.tostring(close-((swingHigh-close)*target1)) + " 🎯 \n" + "TP2 " + str.tostring(close-((swingHigh-close)*target2)) + "🎯 \n \n" + "⚠️ Avertissement : Respectez votre money management, risquez seulement " + str.tostring(risk) + "% de votre capital sur ce trade. BE si TP1 touché"
mess_buyMP1 = "" + str.tostring(ID) + ",buy," + str.tostring(syminfo.ticker) + ",sl=" + str.tostring(swingLow) + ",tp=" + str.tostring(((close-swingLow)*target1)+close) + ",risk=" + str.tostring(risk/2) + ""
mess_buyMP2 = "" + str.tostring(ID) + ",buy," + str.tostring(syminfo.ticker) + ",sl=" + str.tostring(swingLow) + ",tp=" + str.tostring(((close-swingLow)*target2)+close) + ",risk=" + str.tostring(risk/2) + ",betrigger=" + str.tostring(((((close-swingLow)*target1)+close)-close)/getpips()) + ",beoffset=0"
mess_sellMP1 = "" + str.tostring(ID) + ",sell," + str.tostring(syminfo.ticker) + ",sl=" + str.tostring(swingHigh) + ",tp=" + str.tostring(close-((swingHigh-close)*target1)) + ",risk=" + str.tostring(risk/2) + ""
mess_sellMP2 = "" + str.tostring(ID) + ",sell," + str.tostring(syminfo.ticker) + ",sl=" + str.tostring(swingHigh) + ",tp=" + str.tostring(close-((swingHigh-close)*target2)) + ",risk=" + str.tostring(risk/2) + ",betrigger=" + str.tostring((close-(close-((swingHigh-close)*target1)))/getpips()) + ",beoffset=0"
// Strategy
float risk_long = na
float risk_short = na
float stopLoss = na
float takeProfit1 = na
float takeProfit2 = na
float entry_price = na
bool longcondition = na
bool shortcondition = na
if sarT
longcondition := close > ema and ta.crossover(macd, signal) and macd < 0 and high > SAR
shortcondition := close < ema and ta.crossunder(macd, signal) and macd > 0 and low < SAR
if not sarT
longcondition := close > ema and ta.crossover(macd, signal) and macd < 0
shortcondition := close < ema and ta.crossunder(macd, signal) and macd > 0
risk_long := risk_long[1]
risk_short := risk_short[1]
lotB = (strategy.equity*riskt-strategy.equity)/(close - swingLow)
lotS = (strategy.equity*riskt-strategy.equity)/(swingHigh - close)
lotB1 = (strategy.equity*riskt-strategy.equity)/(close - atrBuy)
lotS1 = (strategy.equity*riskt-strategy.equity)/(atrSell - close)
if typeSL == "ATR"
if typeTP == "Multiple Target"
if strategy.position_size == 0 and longcondition and inTradeWindow
risk_long := (close - atrBuy) / close
minp = close - atrBuy
if _x
if tlpc == "Telegram"
strategy.entry("long", strategy.long, qty=lotB1, comment="Buy " + str.tostring(close) + "", alert_message = mess_buyAMT, when = minp > security)
if tlpc == "PineConnector"
strategy.entry("long", strategy.long, qty=lotB1, comment="Buy " + str.tostring(close) + "", alert_message = mess_buyAMP1, when = minp > security)
alert(mess_sellAMP2, alert.freq_once_per_bar_close)
else
if tlpc == "Telegram"
strategy.entry("long", strategy.long, qty=lotB1, comment="Buy " + str.tostring(close) + "", alert_message = mess_buyAMT)
if tlpc == "PineConnector"
strategy.entry("long", strategy.long, qty=lotB1, comment="Buy " + str.tostring(close) + "", alert_message = mess_buyAMP1)
alert(mess_sellAMP2, alert.freq_once_per_bar_close)
if strategy.position_size == 0 and shortcondition and inTradeWindow
risk_short := (atrSell - close) / close
minp = atrSell - close
if _x
if tlpc == "Telegram"
strategy.entry("short", strategy.short, qty=lotS1, comment="Sell " + str.tostring(close) + "", alert_message = mess_sellAMT, when = minp > security)
if tlpc == "PineConnector"
strategy.entry("short", strategy.short, qty=lotS1, comment="Sell " + str.tostring(close) + "", alert_message = mess_sellAMP1, when = minp > security)
alert(mess_sellAMP2, alert.freq_once_per_bar_close)
else
if tlpc == "Telegram"
strategy.entry("short", strategy.short, qty=lotS1, comment="Sell " + str.tostring(close) + "", alert_message = mess_sellAMT)
if tlpc == "PineConnector"
strategy.entry("short", strategy.short, qty=lotS1, comment="Sell " + str.tostring(close) + "", alert_message = mess_sellAMP1)
alert(mess_sellAMP2, alert.freq_once_per_bar_close)
if typeTP == "R:R"
if strategy.position_size == 0 and longcondition and inTradeWindow
risk_long := (close - atrBuy) / close
minp = close - atrBuy
if _x
if tlpc == "Telegram"
strategy.entry("long", strategy.long, qty=lotB1, comment="Buy " + str.tostring(close) + "", alert_message = mess_buyAT, when = minp > security)
if tlpc == "PineConnector"
strategy.entry("long", strategy.long, qty=lotB1, comment="Buy " + str.tostring(close) + "", alert_message = mess_buyAP, when = minp > security)
else
if tlpc == "Telegram"
strategy.entry("long", strategy.long, qty=lotB1, comment="Buy " + str.tostring(close) + "", alert_message = mess_buyAT)
if tlpc == "PineConnector"
strategy.entry("long", strategy.long, qty=lotB1, comment="Buy " + str.tostring(close) + "", alert_message = mess_buyAP)
if strategy.position_size == 0 and shortcondition and inTradeWindow
risk_short := (atrSell - close) / close
minp = atrSell - close
if _x
if tlpc == "Telegram"
strategy.entry("short", strategy.short, qty=lotS1, comment="Sell " + str.tostring(close) + "", alert_message = mess_sellAT, when = minp > security)
if tlpc == "PineConnector"
strategy.entry("short", strategy.short, qty=lotS1, comment="Sell " + str.tostring(close) + "", alert_message = mess_sellAP, when = minp > security)
else
if tlpc == "Telegram"
strategy.entry("short", strategy.short, qty=lotS1, comment="Sell " + str.tostring(close) + "", alert_message = mess_sellAT)
if tlpc == "PineConnector"
strategy.entry("short", strategy.short, qty=lotS1, comment="Sell " + str.tostring(close) + "", alert_message = mess_sellAP)
if typeSL == "Swing"
if typeTP == "Multiple Target"
if strategy.position_size == 0 and longcondition and inTradeWindow
risk_long := (close - swingLow) / close
minp = close - swingLow
if _x
if tlpc == "Telegram"
strategy.entry("long", strategy.long, qty=lotB, comment="Buy " + str.tostring(close) + "", alert_message = mess_buyMT, when = minp > security)
if tlpc == "PineConnector"
strategy.entry("long", strategy.long, qty=lotB, comment="Buy " + str.tostring(close) + "", alert_message = mess_buyMP1, when = minp > security)
alert(mess_buyMP2, alert.freq_once_per_bar_close)
else
if tlpc == "Telegram"
strategy.entry("long", strategy.long, qty=lotB, comment="Buy " + str.tostring(close) + "", alert_message = mess_buyMT)
if tlpc == "PineConnector"
strategy.entry("long", strategy.long, qty=lotB, comment="Buy " + str.tostring(close) + "", alert_message = mess_buyMP1)
alert(mess_buyMP2, alert.freq_once_per_bar_close)
if strategy.position_size == 0 and shortcondition and inTradeWindow
risk_short := (swingHigh - close) / close
minp = swingHigh - close
if _x
if tlpc == "Telegram"
strategy.entry("short", strategy.short, qty=lotS, comment="Sell " + str.tostring(close) + "", alert_message = mess_sellMT, when = minp > security)
if tlpc == "PineConnector"
strategy.entry("short", strategy.short, qty=lotS, comment="Sell " + str.tostring(close) + "", alert_message = mess_sellMP1, when = minp > security)
alert(mess_sellMP2, alert.freq_once_per_bar_close)
else
if tlpc == "Telegram"
strategy.entry("short", strategy.short, qty=lotS, comment="Sell " + str.tostring(close) + "", alert_message = mess_sellMT)
if tlpc == "PineConnector"
strategy.entry("short", strategy.short, qty=lotS, comment="Sell " + str.tostring(close) + "", alert_message = mess_sellMP1)
alert(mess_sellMP2, alert.freq_once_per_bar_close)
if typeTP == "R:R"
if strategy.position_size == 0 and longcondition and inTradeWindow
risk_long := (close - swingLow) / close
minp = close - swingLow
if _x
if tlpc == "Telegram"
strategy.entry("long", strategy.long, qty=lotB, comment="Buy " + str.tostring(close) + "", alert_message = mess_buyT, when = minp > security)
if tlpc == "PineConnector"
strategy.entry("long", strategy.long, qty=lotB, comment="Buy " + str.tostring(close) + "", alert_message = mess_buyP, when = minp > security)
else
if tlpc == "Telegram"
strategy.entry("long", strategy.long, qty=lotB, comment="Buy " + str.tostring(close) + "", alert_message = mess_buyT)
if tlpc == "PineConnector"
strategy.entry("long", strategy.long, qty=lotB, comment="Buy " + str.tostring(close) + "", alert_message = mess_buyP)
if strategy.position_size == 0 and shortcondition and inTradeWindow
risk_short := (swingHigh - close) / close
minp = swingHigh - close
if _x
if tlpc == "Telegram"
strategy.entry("short", strategy.short, qty=lotS, comment="Sell " + str.tostring(close) + "", alert_message = mess_sellT, when = minp > security)
if tlpc == "PineConnector"
strategy.entry("short", strategy.short, qty=lotS, comment="Sell " + str.tostring(close) + "", alert_message = mess_sellP, when = minp > security)
else
if tlpc == "Telegram"
strategy.entry("short", strategy.short, qty=lotS, comment="Sell " + str.tostring(close) + "", alert_message = mess_sellT)
if tlpc == "PineConnector"
strategy.entry("short", strategy.short, qty=lotS, comment="Sell " + str.tostring(close) + "", alert_message = mess_sellP)
if typeTP == "Multiple Target"
if tlpc == "Telegram"
if strategy.position_size > 0
stopLoss := strategy.position_avg_price * (1 - risk_long)
takeProfit1 := strategy.position_avg_price * (1 + target1 * risk_long)
takeProfit2 := strategy.position_avg_price * (1 + target2 * risk_long)
entry_price := strategy.position_avg_price
mess_profit1 = "📈 𝗔𝗖𝗛𝗔𝗧 🔵 " + str.tostring(syminfo.ticker) + "\n" + "TP1 Touché ✅ +" + str.tostring(risk*target1) + "% "
strategy.exit("Exit 1", "long", limit = takeProfit1, qty_percent=50, comment_profit = "TP1 ✅", alert_profit = mess_profit1)
if ta.crossover(high, takeProfit1)
mess_profit2 = "📈 𝗔𝗖𝗛𝗔𝗧 🔵 " + str.tostring(syminfo.ticker) + "\n" + "TP2 Touché ✅ +" + str.tostring(risk*target2) + "% "
mess_be = "📈 𝗔𝗖𝗛𝗔𝗧 🔵 " + str.tostring(syminfo.ticker) + "\n" + "BE ❎"
strategy.exit("Exit 2", "long", stop = entry_price, limit = takeProfit2, qty_percent = 100, comment_profit = "TP2 ✅", comment_loss = "BE ❎", alert_profit = mess_profit2)
else
mess_loss = "📈 𝗔𝗖𝗛𝗔𝗧 🔵 " + str.tostring(syminfo.ticker) + "\n" + "SL Touché ❌ -" + str.tostring(risk) + "% "
strategy.exit("Exit 1", "long", stop = stopLoss, qty_percent = 100, comment_loss = "SL ❌", alert_loss = mess_loss)
if strategy.position_size < 0
stopLoss := strategy.position_avg_price * (1 + risk_short)
takeProfit1 := strategy.position_avg_price * (1 - target1 * risk_short)
takeProfit2 := strategy.position_avg_price * (1 - target2 * risk_short)
entry_price := strategy.position_avg_price
mess_profit1 = "📉 𝗩𝗘𝗡𝗧𝗘 🔴 " + str.tostring(syminfo.ticker) + "\n" + "TP1 Touché ✅ +" + str.tostring(risk*target1) + "% "
strategy.exit("Exit 1", "short", limit = takeProfit1, qty_percent = 50, comment_profit = "TP1 ✅", alert_profit = mess_profit1)
if ta.crossunder(low, takeProfit1)
mess_profit2 = "📉 𝗩𝗘𝗡𝗧𝗘 🔴 " + str.tostring(syminfo.ticker) + "\n" + "TP2 Touché ✅ +" + str.tostring(risk*target2) + "% "
mess_be = "📉 𝗩𝗘𝗡𝗧𝗘 🔴 " + str.tostring(syminfo.ticker) + "\n" + "BE ❎"
strategy.exit("Exit 2", "short", stop = entry_price, limit = takeProfit2, qty_percent = 100, comment_profit = "TP2 ✅", comment_loss = "BE ❎", alert_profit = mess_profit2)
else
mess_loss = "📉 𝗩𝗘𝗡𝗧𝗘 🔴 " + str.tostring(syminfo.ticker) + "\n" + "SL Touché ❌ -" + str.tostring(risk) + "% "
strategy.exit("Exit 1", "short", stop = stopLoss, qty_percent = 100, comment_loss = "SL ❌", alert_loss = mess_loss)
if tlpc == "PineConnector"
if strategy.position_size > 0
stopLoss := strategy.position_avg_price * (1 - risk_long)
takeProfit1 := strategy.position_avg_price * (1 + target1 * risk_long)
takeProfit2 := strategy.position_avg_price * (1 + target2 * risk_long)
entry_price := strategy.position_avg_price
strategy.exit("Exit 1", "long", limit = takeProfit1, qty_percent=50, comment_profit = "TP1 ✅")
if ta.crossover(high, takeProfit1)
strategy.exit("Exit 2", "long", stop = entry_price, limit = takeProfit2, qty_percent = 100, comment_profit = "TP2 ✅", comment_loss = "BE ❎")
else
strategy.exit("Exit 1", "long", stop = stopLoss, qty_percent = 100, comment_loss = "SL ❌")
if strategy.position_size < 0
stopLoss := strategy.position_avg_price * (1 + risk_short)
takeProfit1 := strategy.position_avg_price * (1 - target1 * risk_short)
takeProfit2 := strategy.position_avg_price * (1 - target2 * risk_short)
entry_price := strategy.position_avg_price
strategy.exit("Exit 1", "short", limit = takeProfit1, qty_percent = 50, comment_profit = "TP1 ✅")
if ta.crossunder(low, takeProfit1)
strategy.exit("Exit 2", "short", stop = entry_price, limit = takeProfit2, qty_percent = 100, comment_profit = "TP2 ✅", comment_loss = "BE ❎")
else
strategy.exit("Exit 1", "short", stop = stopLoss, qty_percent = 100, comment_loss = "SL ❌")
if typeTP == "R:R"
if strategy.position_size > 0
stopLoss := strategy.position_avg_price * (1 - risk_long)
takeProfit1 := strategy.position_avg_price * (1 + target_stop_ratio * risk_long)
entry_price := strategy.position_avg_price
if tlpc == "Telegram"
mess_profit = "📈 𝗔𝗖𝗛𝗔𝗧 🔵 " + str.tostring(syminfo.ticker) + "\n" + "TP Touché ✅ +" + str.tostring(risk*target_stop_ratio) + "% "
mess_loss = "📈 𝗔𝗖𝗛𝗔𝗧 🔵 " + str.tostring(syminfo.ticker) + "\n" + "SL Touché ❌ -" + str.tostring(risk) + "% "
strategy.exit("Exit long", "long", stop = stopLoss, limit = takeProfit1, comment_profit="TP ✅", comment_loss="SL ❌", alert_profit = mess_profit, alert_loss = mess_loss)
if tlpc == "PineConnector"
strategy.exit("Exit long", "long", stop = stopLoss, limit = takeProfit1, comment_profit="TP ✅", comment_loss="SL ❌")
if strategy.position_size < 0
stopLoss := strategy.position_avg_price * (1 + risk_short)
takeProfit1 := strategy.position_avg_price * (1 - target_stop_ratio * risk_short)
entry_price := strategy.position_avg_price
if tlpc == "Telegram"
mess_profit = "📉 𝗩𝗘𝗡𝗧𝗘 🔴 " + str.tostring(syminfo.ticker) + "\n" + "TP Touché ✅ +" + str.tostring(risk*target_stop_ratio) + "% "
mess_loss = "📉 𝗩𝗘𝗡𝗧𝗘 🔴 " + str.tostring(syminfo.ticker) + "\n" + "SL Touché ❌ -" + str.tostring(risk) + "% "
strategy.exit("Exit short", "short", stop = stopLoss, limit = takeProfit1, comment_profit="TP ✅" , comment_loss="SL ❌", alert_profit = mess_profit, alert_loss = mess_loss)
if tlpc == "PineConnector"
strategy.exit("Exit short", "short", stop = stopLoss, limit = takeProfit1, comment_profit="TP ✅" , comment_loss="SL ❌")
//Plot
exsar = sarT ? SAR : na
plot(exsar, "ParabolicSAR", style=plot.style_circles, color=myColor, linewidth=1)
plot(ema, color=color.white, linewidth=2, title="EMA")
exswingH = typeSL == "Swing" ? swingHigh : na
exswingL = typeSL == "Swing" ? swingLow : na
plot(exswingH, color=color.new(color.white, 60), style=plot.style_cross, title='Swing High')
plot(exswingL, color=color.new(color.white, 60), style=plot.style_cross, title='Swing Low')
exatrS = typeSL == "ATR" ? atrSell : na
exatrB = typeSL == "ATR" ? atrBuy : na
plot(exatrS, color=color.new(color.white, 60), title='ATR')
plot(exatrB, color=color.new(color.white, 60), title='ATR')
p_ep = plot(entry_price, color=color.new(color.white, 0), linewidth=2, style=plot.style_linebr, title='entry price')
p_sl = plot(stopLoss, color=color.new(color.red, 0), linewidth=2, style=plot.style_linebr, title='stopLoss')
p_tp2 = plot(takeProfit2, color=color.new(color.green, 0), linewidth=2, style=plot.style_linebr, title='takeProfit1')
p_tp1 = plot(takeProfit1, color=color.new(#52F071, 0), linewidth=1, style=plot.style_linebr, title='takeProfit2')
fill(p_sl, p_ep, color.new(color.red, transp=85))
fill(p_tp2, p_ep, color.new(color.green, transp=85))
fill(p_tp1, p_ep, color.new(#52F071, transp=85))
colorresult = strategy.netprofit > 0 ? color.green : color.red
profitprc = strategy.netprofit / strategy.initial_capital * 100
periodzone = (backtestEndDate - backtestStartDate) / 3600 / 24 / 1000
var tbl = table.new(position.top_right, 4, 2, border_width=3)
table.cell(tbl, 0, 0, "Symbole", bgcolor = #9B9B9B, width = 6, height = 6)
table.cell(tbl, 1, 0, "Net Profit", bgcolor = #9B9B9B, width = 6, height = 6)
table.cell(tbl, 2, 0, "Trades", bgcolor = #9B9B9B, width = 6, height = 6)
table.cell(tbl, 3, 0, "Period", bgcolor = #9B9B9B, width = 6, height = 6)
table.cell(tbl, 0, 1, str.tostring(syminfo.ticker), bgcolor = #E8E8E8, width = 6, height = 6)
table.cell(tbl, 1, 1, str.tostring(profitprc, format.mintick) + " %", bgcolor = colorresult, width = 6, height = 6)
table.cell(tbl, 2, 1, str.tostring(strategy.closedtrades), bgcolor = colorresult, width = 6, height = 6)
table.cell(tbl, 3, 1, str.tostring(periodzone) + " day", bgcolor = colorresult, width = 6, height = 6) |
Gotobi Teriyaki | https://www.tradingview.com/script/MlWTOkt4/ | hosono_p | https://www.tradingview.com/u/hosono_p/ | 41 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © hosono_p
//@version=5
strategy("Gotobi Teriyaki", overlay=true)
current_day= dayofmonth(time("1"), "Asia/Tokyo")
saturday = dayofmonth(time("1")+ 1000*60*60*24 , "Asia/Tokyo")
sunday = dayofmonth(time("1")+ 1000*60*60*48, "Asia/Tokyo")
is_5day_10day= current_day % 5==0
flyday = dayofweek(time("1"), "Asia/Tokyo") == 6
flyday_5day_10day = (flyday and saturday % 5==0) or (flyday and sunday % 5==0)
buy_time = time("1", "0200-0955:23456","Asia/Tokyo") and is_5day_10day or time("1", "0200-0955:23456","Asia/Tokyo") and flyday_5day_10day
bgcolor(buy_time ? color.new(color.green, 90) : na)
sell_time = time("1", "0955-1500:23456","Asia/Tokyo") and is_5day_10day or time("1", "0955-1500:23456","Asia/Tokyo") and flyday_5day_10day
bgcolor(sell_time ? color.new(color.red, 90) : na)
if strategy.position_size > 0
if not buy_time
strategy.close_all()
if strategy.position_size < 0
if not sell_time
strategy.close_all()
if strategy.position_size == 0
if buy_time
strategy.entry("buy",strategy.long)
if sell_time
strategy.entry("sell",strategy.short) |
J2S Backtest: 123-Stormer Strategy | https://www.tradingview.com/script/r7dHB8Ir-J2S-Backtest-123-Stormer-Strategy/ | julianossilva | https://www.tradingview.com/u/julianossilva/ | 114 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © julianossilva
//@version=5
strategy(title="J2S Backtest: 123-Stormer Strategy", shorttitle="J2S Backtest: 123-Stormer Strategy", overlay=true, initial_capital=1000, default_qty_value=10, default_qty_type=strategy.percent_of_equity, pyramiding=0)
// Initial Backtest Date Range
useStartDate = timestamp("01 Jan 2020 21:00:00")
useEndDate = timestamp("01 Jan 2023 21:00:00")
// User Inputs
SIGNAL_CONFIG = "BACKTEST: STORMER STRATEGY (123)"
longEntryInput = input.bool(defval=true, group=SIGNAL_CONFIG, title="Long entry")
shortEntryInput = input.bool(defval=true, group=SIGNAL_CONFIG, title="Short entry")
METHOD_CONFIG = "BACKTEST: METHOD"
barLimitForEntryInput = input.int(defval=3, group=METHOD_CONFIG, title="Bar limit for trading entry", tooltip="Given a signal, entry must be reached within how many bars?", minval=1)
barLimitForCloseInput = input.int(defval=8, group=METHOD_CONFIG, title="Bar limit for trading close", tooltip="Once a position is opened, close when it reaches the number of bars in trading.", minval=1)
profitOverRiskInput = input.float(defval=1, group=METHOD_CONFIG, title="Profit over risk", tooltip="Multiplication factor based on the risk assumed in trading. The value range from stop-loss to trade entry is used to determine the profit target. This value range is multiplied by the value entered in 'profit over risk' parameter.", minval=1, step=0.5)
insideBarStrategyInput = input.bool(defval=true, group=METHOD_CONFIG, title="Only third candle inside bar is valid", tooltip="According to Stomer, it would be the best signal for the strategy")
EMA_CONFIG = "BACKTEST: EXPONENTIAL MOVING AVERAGES"
emaTimeframeInput = input.timeframe("1W", group=EMA_CONFIG, title="Timeframe")
sourceInput = input.source(defval=close, group=EMA_CONFIG, title="Source")
fastEMALengthInput = input.int(defval=8, group=EMA_CONFIG, inline="03", title="Fast EMA length ")
useFastEMAInput = input.bool(defval=true, group=EMA_CONFIG, inline="03", title="Use")
slowEMALengthInput = input.int(defval=80, group=EMA_CONFIG, inline="04", title="Slow EMA length ")
useSlowEMAInput = input.bool(defval=true, group=EMA_CONFIG, inline="04", title="Use")
emaOffsetInput = input.int(defval=9, group=EMA_CONFIG, title="Offset")
PERIOD_CONFIG = "BACKTEST: TIME PERIOD"
useDateFilterInput = input.bool(defval=true, group=PERIOD_CONFIG, title="Filter date range of backtest")
backtestStartDateInput = input.time(defval=useStartDate, group=PERIOD_CONFIG, title="Start date")
backtestEndDateInput = input.time(defval=useEndDate, group=PERIOD_CONFIG, title="End date")
// Colors
candleColorDown = color.rgb(239, 83, 80, 80)
candleColorUp = color.rgb(38, 166, 154, 70)
insideBarColorDown = color.rgb(239, 83, 80, 40)
insideBarColorUp = color.rgb(38, 166, 154, 20)
downTrendColor = color.rgb(239, 83, 80, 80)
sidewaysTrendColor = color.rgb(252, 232, 131, 80)
upTrendColor = color.rgb(38, 166, 154, 80)
buySignalColor = color.lime
sellSignalColor = color.orange
// Candles
isCandleUp() => close > open
isCandleDown() => close <= open
barcolor(isCandleUp() ? candleColorUp : isCandleDown() ? candleColorDown : na)
// Exponential Moving Averages
fastEMA = request.security(syminfo.tickerid, emaTimeframeInput, ta.ema(sourceInput, fastEMALengthInput), barmerge.gaps_on, barmerge.lookahead_on)
currentFastEMA = request.security(syminfo.tickerid, emaTimeframeInput, ta.ema(sourceInput, fastEMALengthInput), barmerge.gaps_off, barmerge.lookahead_on)
previousFastEMA = request.security(syminfo.tickerid, emaTimeframeInput, ta.ema(sourceInput[1], fastEMALengthInput), barmerge.gaps_off, barmerge.lookahead_on)
slowEMA = request.security(syminfo.tickerid, emaTimeframeInput, ta.ema(sourceInput, slowEMALengthInput), barmerge.gaps_on, barmerge.lookahead_on)
currentSlowEMA = request.security(syminfo.tickerid, emaTimeframeInput, ta.ema(sourceInput, slowEMALengthInput), barmerge.gaps_off, barmerge.lookahead_on)
previousSlowEMA = request.security(syminfo.tickerid, emaTimeframeInput, ta.ema(sourceInput[1], slowEMALengthInput), barmerge.gaps_off, barmerge.lookahead_on)
// Trend Rules for Exponential Moving Averages
isSlowEMAUp() => currentSlowEMA > previousSlowEMA
isSlowEMADown() => currentSlowEMA < previousSlowEMA
isFastEMAUp() =>
if useFastEMAInput and useSlowEMAInput
currentFastEMA > previousFastEMA and isSlowEMAUp()
else if useFastEMAInput
currentFastEMA > previousFastEMA
else
false
isFastEMADown() =>
if useFastEMAInput and useSlowEMAInput
currentFastEMA < previousFastEMA and isSlowEMADown()
else if useFastEMAInput
currentFastEMA < previousFastEMA
else
false
// Exponential Moving Average Colors
fastEMAColor = isFastEMAUp() ? upTrendColor : isFastEMADown() ? downTrendColor : sidewaysTrendColor
slowEMAColor = isSlowEMAUp() ? upTrendColor : isSlowEMADown() ? downTrendColor : sidewaysTrendColor
// Display Exponential Moving Averages
plot(useFastEMAInput ? fastEMA : na, offset=emaOffsetInput, color=fastEMAColor, title="Fast EMA", style=plot.style_line, linewidth=4)
plot(useSlowEMAInput ? slowEMA : na, offset=emaOffsetInput, color=slowEMAColor, title="Slow EMA", style=plot.style_line, linewidth=7)
// Price Trend
pricesAboveFastEMA() => low[2] > currentFastEMA and low[1] > currentFastEMA and low > currentFastEMA
pricesAboveSlowEMA() => low[2] > currentSlowEMA and low[1] > currentSlowEMA and low > currentSlowEMA
pricesBelowFastEMA() => high[2] < currentFastEMA and high[1] < currentFastEMA and high < currentFastEMA
pricesBelowSlowEMA() => high[2] < currentSlowEMA and high[1] < currentSlowEMA and high < currentSlowEMA
// Market in Bullish Trend
isBullishTrend() =>
if useFastEMAInput and useSlowEMAInput
pricesAboveFastEMA() and pricesAboveSlowEMA()
else if useFastEMAInput
pricesAboveFastEMA()
else if useSlowEMAInput
pricesAboveSlowEMA()
else
na
// Market in Bearish Trend
isBearishTrend() =>
if useFastEMAInput and useSlowEMAInput
pricesBelowFastEMA() and pricesBelowSlowEMA()
else if useFastEMAInput
pricesBelowFastEMA()
else if useSlowEMAInput
pricesBelowSlowEMA()
else
na
// Stormer Strategy (123)
isFirstCandleUp() => high[2] > high[1] and low[2] > low[1]
isFirstCandleDown() => high[2] < high[1] and low[2] < low[1]
isThirdCandleUp() => low > low[1]
isThirdCandleDown() => high < high[1]
isThirdCandleInsideBar() => high < high[1] and low > low[1]
// Buy Signal
isStormer123Buy() =>
if insideBarStrategyInput
longEntryInput and isFirstCandleUp() and isThirdCandleInsideBar() and isBullishTrend()
else
longEntryInput and isFirstCandleUp() and isThirdCandleUp() and isBullishTrend()
// Sell Signal
isStormer123Sell() =>
if insideBarStrategyInput
shortEntryInput and isFirstCandleDown() and isThirdCandleInsideBar() and isBearishTrend()
else
shortEntryInput and isFirstCandleDown() and isThirdCandleDown() and isBearishTrend()
// Backtest Time Period
inTradeWindow = not useDateFilterInput or (time >= backtestStartDateInput and time < backtestEndDateInput)
isInTradeWindow() => inTradeWindow
isBacktestDateRangeOver() => not inTradeWindow and inTradeWindow[1]
// Backtest Price Parameters
highestPrice = ta.highest(high, 3)
lowestPrice = ta.lowest(low,3)
priceRange = highestPrice - lowestPrice
// Stormer Strategy (123): LONG
var myLongOrders = array.new_int(0)
longtEntryID = "Long Entry:\n" + str.tostring(bar_index)
longExitID = "Long Exit:\n" + str.tostring(bar_index)
stopLossInLong = lowestPrice + 1 * syminfo.mintick
takeProfitInLong = high + priceRange * profitOverRiskInput
longEntryHasBeenMet = isInTradeWindow() and isBullishTrend() and isStormer123Buy()
// Scheduling LONG entry
if longEntryHasBeenMet
array.push(myLongOrders, bar_index)
strategy.order(longtEntryID, strategy.long, stop=high)
strategy.exit(longExitID, longtEntryID, stop=stopLossInLong, limit=takeProfitInLong)
// In pine script, any order scheduled but not yet filled can be canceled.
// Once a order is filled, the trade is only finished with use of close or exit functions.
// As scheduled orders are not stored in the strategy.opentrades array, manual control is required.
int myLongOrderIndex = 0
while myLongOrderIndex < array.size(myLongOrders) and array.size(myLongOrders) > 0
myLongOrder = array.get(myLongOrders, myLongOrderIndex)
if bar_index - myLongOrder == barLimitForEntryInput
longEntryID = "Long Entry:\n" + str.tostring(myLongOrder)
strategy.cancel(longEntryID)
array.remove(myLongOrders, myLongOrderIndex)
continue
myLongOrderIndex += 1
// Stormer Strategy (123): SHORT
var myShortOrders = array.new_int(0)
shortEntryID = "Short Entry:\n" + str.tostring(bar_index)
shortExitID = "Short Exit:\n" + str.tostring(bar_index)
stopLossInShort = highestPrice + 1 * syminfo.mintick
takeProfitInShort = low - priceRange * profitOverRiskInput
shortEntryHasBeenMet = isInTradeWindow() and isBearishTrend() and isStormer123Sell()
// Scheduling SHORT entry
if shortEntryHasBeenMet
array.push(myShortOrders, bar_index)
strategy.order(shortEntryID, strategy.short, stop=low)
strategy.exit(shortExitID, shortEntryID, stop=stopLossInShort, limit=takeProfitInShort)
// In pine script, any order scheduled but not yet filled can be canceled.
// Once a order is filled, the trade is only finished with use of close or exit functions.
// As scheduled orders are not stored in the strategy.opentrades array, manual control is required.
int myShortOrderIndex = 0
while myShortOrderIndex < array.size(myShortOrders) and array.size(myShortOrders) > 0
myShortOrder = array.get(myShortOrders, myShortOrderIndex)
if bar_index - myShortOrder == barLimitForEntryInput
shortEntryID := "Short Entry:\n" + str.tostring(myShortOrder)
strategy.cancel(shortEntryID)
array.remove(myShortOrders, myShortOrderIndex)
continue
myShortOrderIndex += 1
// Trading must be stopped when candlestick limit reached in a trading
for tradeNumber = 0 to strategy.opentrades - 1
tradeEntryID = strategy.opentrades.entry_id(tradeNumber)
splitPosition = str.pos(tradeEntryID, ":")
entryBar = str.tonumber(str.substring(tradeEntryID, splitPosition + 1))
if bar_index - entryBar == barLimitForCloseInput
closeID = "Close Position:\n" + str.tostring(entryBar)
strategy.close(id=tradeEntryID, comment=closeID, immediately=true)
// Close all positions at the end of the backtest period
if isBacktestDateRangeOver()
strategy.cancel_all()
strategy.close_all(comment="Date Range Exit")
// Display Signals
plotshape(series=longEntryHasBeenMet, title="123 Buy", style=shape.triangleup, location=location.abovebar, color=buySignalColor, text="Buy", textcolor=buySignalColor)
plotshape(series=shortEntryHasBeenMet, title="123 Sell", style=shape.triangledown, location=location.belowbar, color=sellSignalColor, text="Sell", textcolor=sellSignalColor) |
R19 STRATEGY | https://www.tradingview.com/script/2LOPRpQH-R19-STRATEGY/ | SenatorVonShaft | https://www.tradingview.com/u/SenatorVonShaft/ | 155 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © onurenginogutcu
//@version=4
strategy("R19 STRATEGY", overlay=true, calc_on_every_tick=true , margin_long=100, margin_short=100 , process_orders_on_close=true )
sym = input(title="Symbol", type=input.symbol, defval="BINANCE:BTCUSDT" , group = "SYMBOL")
timeFrame = input(title="Strategy Decision Time Frame", type = input.resolution , defval="60")
adxlen = input(14, title="ADX Smoothing" , group = "ADX")
dilen = input(14, title="ADX DI Length", group = "ADX")
adxemalenght = input(30, title="ADX EMA", group = "ADX")
adxconstant = input(19, title="ADX CONSTANT", group = "ADX")
fibvar = input (title = "Fibo Look Back Canles" , defval = 50 , minval = 0 , group = "FIBO MACD SMA")
smaLookback = input (title = "SMA Look Back Candles" , defval = 30 , minval = 0 , group = "FIBO MACD SMA")
MACDFast = input (title = "MACD Fast Lenght" , defval = 15 , minval = 0 , group = "FIBO MACD SMA")
MACDSlow = input (title = "MACD Slow Lenght" , defval = 30 , minval = 0 , group = "FIBO MACD SMA")
MACDSmooth = input (title = "MACD Signal Smoothing" , defval = 9 , minval = 0 , group = "FIBO MACD SMA")
MACDLookback = input (title = "MACD Look Back Candles" , defval = 100 , minval = 0 , group = "FIBO MACD SMA")
trailingStopLong = input (title = "Trailing Long Stop %" , defval = 2.0 , step = 0.1, group = "TP & SL") * 0.01
trailingStopShort = input (title = "Trailing Short Stop %" , defval = 2.0 , step = 0.1 , group = "TP & SL") * 0.01
LongTrailingProfitStart = input (title = "Long Profit Start %" , defval = 2.0 , step = 0.1 , group = "TP & SL") * 0.01
ShortTrailingProfitStart = input (title = "Short Profit Start %" , defval = 2.0 , step = 0.1, group = "TP & SL") * 0.01
lsl = input(title="Max Long Stop Loss (%)",
minval=0.0, step=0.1, defval=3.0, group = "TP & SL") * 0.01
ssl = input(title="Max Short Stop Loss (%)",
minval=0.0, step=0.1, defval=2.5, group = "TP & SL") * 0.01
longtp = input(title="Long Take Profit (%)",
minval=0.0, step=0.1, defval=100, group = "TP & SL") * 0.01
shorttp = input(title="Short Take Profit (%)",
minval=0.0, step=0.1, defval=100, group = "TP & SL") * 0.01
capperc = input(title="Capital Percentage to Invest (%)",
minval=0.0, maxval=100, step=0.1, defval=95, group = "CAPITAL TO INVEST") * 0.01
symClose = security(sym, timeFrame, close)
symHigh = security(sym, timeFrame, high)
symLow = security(sym, timeFrame, low)
atr = atr (14)
/////////adx code
dirmov(len) =>
up = change(symHigh)
down = -change(symLow)
plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
truerange = rma(tr, len)
plus = fixnan(100 * rma(plusDM, len) / truerange)
minus = fixnan(100 * rma(minusDM, len) / truerange)
[plus, minus]
adx(dilen, adxlen) =>
[plus, minus] = dirmov(dilen)
sum = plus + minus
adx = 100 * rma(abs(plus - minus) / (sum == 0 ? 1 : sum), adxlen)
sig = adx(dilen, adxlen)
emasig = ema (sig , adxemalenght )
////////adx code over
i = ema (symClose , MACDFast) - ema (symClose , MACDSlow)
r = ema (i , MACDSmooth)
sapust = highest (i , MACDLookback) * 0.729
sapalt = lowest (i , MACDLookback) * 0.729
simRSI = rsi (symClose , 50 )
fibtop = lowest (symLow , fibvar) + ((highest (symHigh , fibvar) - lowest (symLow , fibvar)) * 0.50)
fibbottom = lowest (symLow , fibvar) + ((highest (symHigh , fibvar) - lowest (symLow , fibvar)) * 0.50)
cond1 = 0
cond2 = 0
cond3 = 0
cond4 = 0
longCondition = crossover(i, r) and i < sapalt and sig > adxconstant and symClose < sma (symClose , smaLookback) and simRSI < sma (simRSI , 50) and symClose < fibbottom
shortCondition = crossunder(i, r) and i > sapust and sig > adxconstant and symClose > sma (symClose , smaLookback) and simRSI > sma (simRSI , 50) and symClose > fibtop
//////////////////////probability long/short
if (crossover(i, r) and i < sapalt)
cond1 := 35
else if (crossunder(i, r) and i > sapust)
cond1 := -35
else
cond1 := 0
if (symClose < sma (symClose , smaLookback))
cond2 := 30
else if (symClose > sma (symClose , smaLookback))
cond2 := -30
else
cond2 := 0
if (simRSI < sma (simRSI , 50))
cond3 := 25
else if (simRSI > sma (simRSI , 50))
cond3 := -25
else
cond3 := 0
if (symClose < fibbottom)
cond4 := 10
else if (symClose > fibbottom)
cond4 := -10
else
cond4 := 0
probab = cond1 + cond2 + cond3 + cond4
////////////////////////////////////////////////////////////////
///////////////////////////////////////////STRATEGY ENTRIES AND STOP LOSSES /////
var startTrail = 0
var trailingLongPrice = 0.0
var trailingShortPrice = 0.0
if (longCondition and strategy.position_size == 0)
strategy.entry("Long", strategy.long , qty = capperc * strategy.equity / close )
if (shortCondition and strategy.position_size == 0)
strategy.entry("Short" , strategy.short , qty = capperc * strategy.equity / close )
if (strategy.position_size == 0)
trailingShortPrice := 0.0
trailingLongPrice := 0.0
startTrail := 0
/////////////////////////////////strategy exit
if (strategy.position_size > 0 and close >= strategy.position_avg_price * (1 + LongTrailingProfitStart))
startTrail := 1
if (strategy.position_size < 0 and close <= strategy.position_avg_price * (1 - ShortTrailingProfitStart))
startTrail := -1
trailingLongPrice := if strategy.position_size > 0 and startTrail == 1
stopMeasure = close * (1 - trailingStopLong)
max (stopMeasure , trailingLongPrice [1])
else if strategy.position_size > 0 and startTrail == 0
strategy.position_avg_price * (1 - lsl)
trailingShortPrice := if strategy.position_size < 0 and startTrail == -1
stopMeasure = close * (1 + trailingStopShort)
min (stopMeasure , trailingShortPrice [1])
else if strategy.position_size < 0 and startTrail == 0
strategy.position_avg_price * (1 + ssl)
if (strategy.position_size > 0)
strategy.exit("Exit Long", "Long", stop = trailingLongPrice , limit=strategy.position_avg_price*(1 + longtp))
if (strategy.position_size < 0)
strategy.exit("Exit Short", "Short", stop = trailingShortPrice , limit=strategy.position_avg_price*(1 - shorttp))
////////////////////////vertical colouring signals
bgcolor(color=longCondition ? color.new (color.green , 70) : na)
bgcolor(color=shortCondition ? color.new (color.red , 70) : na)
plot (trailingLongPrice , color = color.green) ///long price trailing stop
plot (trailingShortPrice , color = color.red) /// short price trailing stop
plot (startTrail , color = color.yellow)
plot (probab , color = color.white) ////probability
|
RSI Mean Reversion Strategy | https://www.tradingview.com/script/RAIkCOKJ-RSI-Mean-Reversion-Strategy/ | Sarahann999 | https://www.tradingview.com/u/Sarahann999/ | 152 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Sarahann999
//@version=5
strategy("RSI Strategy", shorttitle="RSI", overlay= false)
//Inputs
long_entry = input(true, title='Long Entry')
short_entry = input(true, title='Short Entry')
emaSettings = input(100, 'EMA Length')
ema = ta.ema(close,emaSettings)
rsi = ta.rsi(close,14)
rsios = input(40, title= 'RSI Oversold Settings')
rsiob = input(60, title= 'RSI Overbought Settings')
//Conditions
uptrend = close > ema
downtrend = close < ema
OB = rsi > rsiob
OS = rsi < rsios
buySignal = uptrend and OS and strategy.position_size == 0
sellSignal = downtrend and OB and strategy.position_size == 0
//Calculate Take Profit Percentage
longProfitPerc = input.float(title="Long Take Profit", group='Take Profit Percentage',
minval=0.0, step=0.1, defval=1) / 100
shortProfitPerc = input.float(title="Short Take Profit",
minval=0.0, step=0.1, defval=1) / 100
// Figure out take profit price 1
longExitPrice = strategy.position_avg_price * (1 + longProfitPerc)
shortExitPrice = strategy.position_avg_price * (1 - shortProfitPerc)
// Make inputs that set the stop % 1
longStopPerc = input.float(title="Long Stop Loss", group='Stop Percentage',
minval=0.0, step=0.1, defval=1.5) / 100
shortStopPerc = input.float(title="Short Stop Loss",
minval=0.0, step=0.1, defval=1.5) / 100
// Figure Out Stop Price
longStopPrice = strategy.position_avg_price * (1 - longStopPerc)
shortStopPrice = strategy.position_avg_price * (1 + shortStopPerc)
// Submit entry orders
if buySignal and long_entry
strategy.entry(id="Long", direction=strategy.long, alert_message="Enter Long")
if sellSignal and short_entry
strategy.entry(id="Short", direction=strategy.short, alert_message="Enter Short")
//Submit exit orders based on take profit price
if (strategy.position_size > 0)
strategy.exit(id="Long TP/SL", limit=longExitPrice, stop=longStopPrice, alert_message="Long Exit 1 at {{close}}")
if (strategy.position_size < 0)
strategy.exit(id="Short TP/SL", limit=shortExitPrice, stop=shortStopPrice, alert_message="Short Exit 1 at {{close}}")
//note: for custom alert messages to read, "{{strategy.order.alert_message}}" must be placed into the alert dialogue box when the alert is set.
plot(rsi, color= color.gray)
hline(40, "RSI Lower Band")
hline(60, "RSI Upper Band") |
RSI with Slow and Fast MA Crossing Strategy (by Coinrule) | https://www.tradingview.com/script/nFVRA9sy-RSI-with-Slow-and-Fast-MA-Crossing-Strategy-by-Coinrule/ | Coinrule | https://www.tradingview.com/u/Coinrule/ | 144 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Coinrule
//@version=5
strategy("RSI with Slow and Fast MA Crossing Strategy (by Coinrule)",
overlay=true,
initial_capital=10000,
process_orders_on_close=true,
default_qty_type=strategy.percent_of_equity,
default_qty_value=30,
commission_type=strategy.commission.percent,
commission_value=0.1)
showDate = input(defval=true, title='Show Date Range')
timePeriod = time >= timestamp(syminfo.timezone, 2020, 1, 1, 0, 0)
notInTrade = strategy.position_size <= 0
// RSI
length = input(14)
vrsi = ta.rsi(close, length)
// Moving Averages for Buy Condition
buyFastEMA = ta.ema(close, 9)
buySlowEMA = ta.ema(close, 50)
buyCondition1 = ta.crossover(buyFastEMA, buySlowEMA)
increase = 5
if ((vrsi > vrsi[1]+increase) and buyCondition1 and vrsi < 70 and timePeriod)
strategy.entry("Long", strategy.long)
// Moving Averages for Sell Condition
sellFastEMA = ta.ema(close, 9)
sellSlowEMA = ta.ema(close, 50)
plot(request.security(syminfo.tickerid, "60", sellFastEMA), color = color.blue)
plot(request.security(syminfo.tickerid, "60", sellSlowEMA), color = color.green)
condition = ta.crossover(sellSlowEMA, sellFastEMA)
//sellCondition1 = request.security(syminfo.tickerid, "60", condition)
strategy.close('Long', when = condition and timePeriod)
|
Strategy Myth-Busting #2 - Braid Filter+ADX+EMA-Trend - [MYN] | https://www.tradingview.com/script/ZmsAUj1J-Strategy-Myth-Busting-2-Braid-Filter-ADX-EMA-Trend-MYN/ | myncrypto | https://www.tradingview.com/u/myncrypto/ | 968 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © myn
//@version=5
strategy('Strategy Myth-Busting #2 - Braid Filter+ADX+EMA-Trend - [MYN]', max_bars_back=5000, overlay=true, pyramiding=0, initial_capital=20000, currency='USD', default_qty_type=strategy.percent_of_equity, default_qty_value=100.0, commission_value=0.075, use_bar_magnifier = true)
// Trading Rules
// 15 min / BTCUSD
// 1) Buy Price action above moving average. (bars are green)
// 2) Braid filter must issue a new green bar
// 3) ADX must be above the 20 level and be pointed up, If flat or downwards, don't enter trade
// 4) Stop loss at the moving average or recent swing low.
// Target 1.5x the risk
// Indicator changes per strategy recommendation
// Keep Braid Filter default
// CMA EMA TrendBars Change Uptrend to 100
// ADX and DI for V4 (uncheck DI+ and DI- in style) and make ADX line thicker
/////////////////////////////////////
//* Put your strategy logic below *//
/////////////////////////////////////
// 3a1mQJ26TOE
// Braid Filter by Robert Hill
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Copyright © Robert Hill, 2006
//@version=5
//indicator('Braid Filter')
//-- Inputs
maType = input.string('EMA', 'MA Type', options=['EMA', 'DEMA', 'TEMA', 'WMA', 'VWMA', 'SMA', 'SMMA', 'HMA', 'LSMA', 'Kijun', 'McGinley', 'RMA'], group="Braid Filter")
Period1 = input(3, 'Period 1')
Period2 = input(7, 'Period 2')
Period3 = input(14, 'Period 3')
PipsMinSepPercent = input(40)
//-- Moving Average
ma(type, src, len) =>
float result = 0
if type == 'SMA' // Simple
result := ta.sma(src, len)
result
if type == 'EMA' // Exponential
result := ta.ema(src, len)
result
if type == 'DEMA' // Double Exponential
e = ta.ema(src, len)
result := 2 * e - ta.ema(e, len)
result
if type == 'TEMA' // Triple Exponential
e = ta.ema(src, len)
result := 3 * (e - ta.ema(e, len)) + ta.ema(ta.ema(e, len), len)
result
if type == 'WMA' // Weighted
result := ta.wma(src, len)
result
if type == 'VWMA' // Volume Weighted
result := ta.vwma(src, len)
result
if type == 'SMMA' // Smoothed
w = ta.wma(src, len)
result := na(w[1]) ? ta.sma(src, len) : (w[1] * (len - 1) + src) / len
result
if type == 'RMA'
result := ta.rma(src, len)
result
if type == 'HMA' // Hull
result := ta.wma(2 * ta.wma(src, len / 2) - ta.wma(src, len), math.round(math.sqrt(len)))
result
if type == 'LSMA' // Least Squares
result := ta.linreg(src, len, 0)
result
if type == 'Kijun' //Kijun-sen
kijun = math.avg(ta.lowest(len), ta.highest(len))
result := kijun
result
if type == 'McGinley'
mg = 0.0
mg := na(mg[1]) ? ta.ema(src, len) : mg[1] + (src - mg[1]) / (len * math.pow(src / mg[1], 4))
result := mg
result
result
//-- Braid Filter
ma01 = ma(maType, close, Period1)
ma02 = ma(maType, open, Period2)
ma03 = ma(maType, close, Period3)
max = math.max(math.max(ma01, ma02), ma03)
min = math.min(math.min(ma01, ma02), ma03)
dif = max - min
filter = ta.atr(14) * PipsMinSepPercent / 100
//-- Plots
BraidColor = ma01 > ma02 and dif > filter ? color.green : ma02 > ma01 and dif > filter ? color.red : color.gray
//plot(dif, 'Braid', BraidColor, 5, plot.style_columns)
//plot(filter, 'Filter', color.new(color.blue, 0), 2, plot.style_line)
//bgcolor(BraidColor, transp=90)
//2) Braid filter must issue a new green/red bar
entryBbraidFilterGreenBar = BraidColor == color.green
entryBraidFilterRedBar = BraidColor == color.red
// CM_EMA Trend Bars by Chris Moody
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
//@version=5
//Created by ChrisMoody on 11/1/2014
//Bar Color Based on Above/Below EMA...
// indicator(title='CM_EMA Trend Bars', shorttitle='CM_EMA TrendBars', overlay=true)
ema1 = input.int(100, minval=1, maxval=300, title='EMA UpTrend', group="EMA Trend Bars")
shema = input(true, title='Show EMA Trend is Based On?')
usedEma = ta.ema(close, ema1)
emaUpColor() =>
hlc3 >= usedEma
emaDownColor() =>
hlc3 < usedEma
col = hlc3 >= usedEma ? color.lime : hlc3 < usedEma ? color.red : color.white
emaDownColor_1 = emaDownColor()
barcolor(emaUpColor() ? color.lime : emaDownColor_1 ? color.red : na)
plot(shema and usedEma ? usedEma : na, title='EMA', style=plot.style_line, linewidth=3, color=col)
// 1) Buy Price action above moving average. (bars are green)
entryPriceActionAboveEMATrend = emaUpColor()
entryPriceActionBelowEMATrend = emaDownColor()
// ADX and DI for V4 by Trend Bars by BeikabuOyaji
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © BeikabuOyaji
//@version=5
//indicator('ADX and DI for v4')
len = input(14)
th = input(20)
TrueRange = math.max(math.max(high - low, math.abs(high - nz(close[1]))), math.abs(low - nz(close[1])))
DirectionalMovementPlus = high - nz(high[1]) > nz(low[1]) - low ? math.max(high - nz(high[1]), 0) : 0
DirectionalMovementMinus = nz(low[1]) - low > high - nz(high[1]) ? math.max(nz(low[1]) - low, 0) : 0
SmoothedTrueRange = 0.0
SmoothedTrueRange := nz(SmoothedTrueRange[1]) - nz(SmoothedTrueRange[1]) / len + TrueRange
SmoothedDirectionalMovementPlus = 0.0
SmoothedDirectionalMovementPlus := nz(SmoothedDirectionalMovementPlus[1]) - nz(SmoothedDirectionalMovementPlus[1]) / len + DirectionalMovementPlus
SmoothedDirectionalMovementMinus = 0.0
SmoothedDirectionalMovementMinus := nz(SmoothedDirectionalMovementMinus[1]) - nz(SmoothedDirectionalMovementMinus[1]) / len + DirectionalMovementMinus
DIPlus = SmoothedDirectionalMovementPlus / SmoothedTrueRange * 100
DIMinus = SmoothedDirectionalMovementMinus / SmoothedTrueRange * 100
DX = math.abs(DIPlus - DIMinus) / (DIPlus + DIMinus) * 100
ADX = ta.sma(DX, len)
//plot(DIPlus, color=color.new(color.green, 0), title='DI+')
//plot(DIMinus, color=color.new(color.red, 0), title='DI-')
//plot(ADX, color=color.new(color.navy, 0), title='ADX')
//hline(th, color=color.black)
// 3) ADX must be above the 20 level and be pointed up. If flat or downwards, don't enter trade
iADXSlope = input.float(3.5, minval=0, maxval=300, title='ADX Slope', step=.5, group="ADX and DI")
entryADXAboveThreshold = ADX > th and (ADX[2] + iADXSlope < ADX[1]) and (ADX[1] + iADXSlope < ADX)
//entryADXAboveThreshold = ADX > th and (ADX[2] < ADX[1]) and (ADX[1] < ADX)
//////////////////////////////////////
//* Put your strategy rules below *//
/////////////////////////////////////
longCondition = entryPriceActionAboveEMATrend and entryBbraidFilterGreenBar and entryADXAboveThreshold
shortCondition = entryPriceActionBelowEMATrend and entryBraidFilterRedBar and entryADXAboveThreshold
//define as 0 if do not want to use
closeLongCondition = 0
closeShortCondition = 0
//Backtesting Time Period (Input.time not working as expected as of 03/30/2021. Giving odd start/end dates
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
useStartPeriodTime = input.bool(true, 'Start', group='Date Range', inline='Start Period')
startPeriodTime = input.time(timestamp('1 Jan 2019'), '', group='Date Range', inline='Start Period')
useEndPeriodTime = input.bool(true, 'End', group='Date Range', inline='End Period')
endPeriodTime = input.time(timestamp('31 Dec 2030'), '', group='Date Range', inline='End Period')
start = useStartPeriodTime ? startPeriodTime >= time : false
end = useEndPeriodTime ? endPeriodTime <= time : false
calcPeriod = not start and not end
// Trade Direction
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tradeDirection = input.string('Long and Short', title='Trade Direction', options=['Long and Short', 'Long Only', 'Short Only'], group='Trade Direction')
// Percent as Points
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
per(pcnt) =>
strategy.position_size != 0 ? math.round(pcnt / 100 * strategy.position_avg_price / syminfo.mintick) : float(na)
// Take profit 1
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tp1 = input.float(title='Take Profit 1 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 1')
q1 = input.int(title='% Of Position', defval=3, minval=0, group='Take Profit', inline='Take Profit 1')
// Take profit 2
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tp2 = input.float(title='Take Profit 2 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 2')
q2 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 2')
// Take profit 3
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tp3 = input.float(title='Take Profit 3 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 3')
q3 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 3')
// Take profit 4
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tp4 = input.float(title='Take Profit 4 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit')
/// Stop Loss
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
stoplossPercent = input.float(title='Stop Loss (%)', defval=12, minval=0.01, group='Stop Loss') * 0.01
slLongClose = close < strategy.position_avg_price * (1 - stoplossPercent)
slShortClose = close > strategy.position_avg_price * (1 + stoplossPercent)
/// Leverage
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
leverage = input.float(1, 'Leverage', step=.5, group='Leverage')
contracts = math.min(math.max(.000001, strategy.equity / close * leverage), 1000000000)
/// Trade State Management
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
isInLongPosition = strategy.position_size > 0
isInShortPosition = strategy.position_size < 0
/// ProfitView Alert Syntax String Generation
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
alertSyntaxPrefix = input.string(defval='CRYPTANEX_99FTX_Strategy-Name-Here', title='Alert Syntax Prefix', group='ProfitView Alert Syntax')
alertSyntaxBase = alertSyntaxPrefix + '\n#' + str.tostring(open) + ',' + str.tostring(high) + ',' + str.tostring(low) + ',' + str.tostring(close) + ',' + str.tostring(volume) + ','
/// Trade Execution
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
if calcPeriod
if longCondition and tradeDirection != 'Short Only' and isInLongPosition == false
strategy.entry('Long', strategy.long, qty=contracts)
alert(message=alertSyntaxBase + 'side:long', freq=alert.freq_once_per_bar_close)
if shortCondition and tradeDirection != 'Long Only' and isInShortPosition == false
strategy.entry('Short', strategy.short, qty=contracts)
alert(message=alertSyntaxBase + 'side:short', freq=alert.freq_once_per_bar_close)
//Inspired from Multiple %% profit exits example by adolgo https://www.tradingview.com/script/kHhCik9f-Multiple-profit-exits-example/
strategy.exit('TP1', qty_percent=q1, profit=per(tp1))
strategy.exit('TP2', qty_percent=q2, profit=per(tp2))
strategy.exit('TP3', qty_percent=q3, profit=per(tp3))
strategy.exit('TP4', profit=per(tp4))
strategy.close('Long', qty_percent=100, comment='SL Long', when=slLongClose)
strategy.close('Short', qty_percent=100, comment='SL Short', when=slShortClose)
strategy.close_all(when=closeLongCondition or closeShortCondition, comment='Close Postion')
/// Dashboard
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Inspired by https://www.tradingview.com/script/uWqKX6A2/ - Thanks VertMT
showDashboard = input.bool(group="Dashboard", title="Show Dashboard", defval=true)
f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) =>
_cellText = _title + "\n" + _value
table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor, text_size=size.auto)
// Draw dashboard table
if showDashboard
var bgcolor = color.new(color.black,0)
// Keep track of Wins/Losses streaks
newWin = (strategy.wintrades > strategy.wintrades[1]) and (strategy.losstrades == strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1])
newLoss = (strategy.wintrades == strategy.wintrades[1]) and (strategy.losstrades > strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1])
varip int winRow = 0
varip int lossRow = 0
varip int maxWinRow = 0
varip int maxLossRow = 0
if newWin
lossRow := 0
winRow := winRow + 1
if winRow > maxWinRow
maxWinRow := winRow
if newLoss
winRow := 0
lossRow := lossRow + 1
if lossRow > maxLossRow
maxLossRow := lossRow
// Prepare stats table
var table dashTable = table.new(position.bottom_right, 1, 15, border_width=1)
if barstate.islastconfirmedhistory
// Update table
dollarReturn = strategy.netprofit
f_fillCell(dashTable, 0, 0, "Start:", str.format("{0,date,long}", strategy.closedtrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.closedtrades.entry_time(0))
f_fillCell(dashTable, 0, 1, "End:", str.format("{0,date,long}", strategy.opentrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.opentrades.entry_time(0))
_profit = (strategy.netprofit / strategy.initial_capital) * 100
f_fillCell(dashTable, 0, 2, "Net Profit:", str.tostring(_profit, '##.##') + "%", _profit > 0 ? color.green : color.red, color.white)
_numOfDaysInStrategy = (strategy.opentrades.entry_time(0) - strategy.closedtrades.entry_time(0)) / (1000 * 3600 * 24)
f_fillCell(dashTable, 0, 3, "Percent Per Day", str.tostring(_profit / _numOfDaysInStrategy, '#########################.#####')+"%", _profit > 0 ? color.green : color.red, color.white)
_winRate = ( strategy.wintrades / strategy.closedtrades ) * 100
f_fillCell(dashTable, 0, 4, "Percent Profitable:", str.tostring(_winRate, '##.##') + "%", _winRate < 50 ? color.red : _winRate < 75 ? #999900 : color.green, color.white)
f_fillCell(dashTable, 0, 5, "Profit Factor:", str.tostring(strategy.grossprofit / strategy.grossloss, '##.###'), strategy.grossprofit > strategy.grossloss ? color.green : color.red, color.white)
f_fillCell(dashTable, 0, 6, "Total Trades:", str.tostring(strategy.closedtrades), bgcolor, color.white)
f_fillCell(dashTable, 0, 8, "Max Wins In A Row:", str.tostring(maxWinRow, '######') , bgcolor, color.white)
f_fillCell(dashTable, 0, 9, "Max Losses In A Row:", str.tostring(maxLossRow, '######') , bgcolor, color.white) |
VIDYA Trend Strategy | https://www.tradingview.com/script/mfOrooGt-VIDYA-Trend-Strategy/ | TradeAutomation | https://www.tradingview.com/u/TradeAutomation/ | 218 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// @version=5
// Author = TradeAutomation
strategy(title="VIDYA Trend Strategy", shorttitle="VIDYA Trend Strategy", process_orders_on_close=true, overlay=true, pyramiding=25, commission_type=strategy.commission.percent, commission_value=.075, slippage = 1, initial_capital = 1000000, default_qty_type=strategy.percent_of_equity, default_qty_value=4)
// Backtest Date Range Inputs //
StartTime = input.time(defval=timestamp('01 Jan 2000 08:00'), group="Date Range", title='Start Time')
EndTime = input.time(defval=timestamp('01 Jan 2099 00:00'), group="Date Range", title='End Time')
InDateRange = time>=StartTime and time<=EndTime
// Strategy Inputs //
len = input.int(title="VIDYA Length", defval=50, step=5,group="Trend Settings")
src = input.source(title="VIDYA Price Source",defval=ohlc4, group="Trend Settings")
// VIDYA Calculations //
valpha=2/(len+1)
vud1=src>src[1] ? src-src[1] : 0
vdd1=src<src[1] ? src[1]-src : 0
vUD=math.sum(vud1,9)
vDD=math.sum(vdd1,9)
vCMO=nz((vUD-vDD)/(vUD+vDD))
var VIDYA = 0.0
VIDYA := na(VIDYA[1]) ? ta.sma(src, len) : nz(valpha*math.abs(vCMO)*src)+(1-valpha*math.abs(vCMO))*nz(VIDYA[1])
plot(VIDYA, title="VIDYA",color=(VIDYA > VIDYA[1]) ? color.green : (VIDYA<VIDYA[1]) ? color.red : (VIDYA==VIDYA[1]) ? color.gray : color.black, linewidth=2)
// Entry & Exit Signals //
if (InDateRange)
strategy.entry("Long", strategy.long, when = VIDYA>VIDYA[1])
strategy.close("Long", when = VIDYA<VIDYA[1])
if (not InDateRange)
strategy.close_all()
|
RSI SMA Crossover Strategy | https://www.tradingview.com/script/ZINSYeR8-RSI-SMA-Crossover-Strategy/ | reees | https://www.tradingview.com/u/reees/ | 520 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © reees
//
//@version=5
//
strategy('RSI Crossover Strategy', shorttitle='RSI Cross', default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=1000, calc_on_every_tick=true)
// inputs
rsiLength = input(title='RSI Length', defval=50)
smaLength = input(title='SMA Length', defval=25)
// data/series
rsi = ta.rsi(close, rsiLength)
sma = ta.sma(rsi, smaLength)
// plot
plotColor = rsi > sma ? color.green : color.red
rsiPlot = plot(rsi, color=color.new(plotColor, 0), title='RSI')
smaPlot = plot(sma, color=color.new(color.black, 0), title='SMA')
fillColor = rsi > sma ? color.lime : color.red
fill(rsiPlot, smaPlot, color=color.new(fillColor, 75))
oversoldLine = hline(30, title='Oversold level')
overboughtLine = hline(70, title='Overbought level')
// strategy
buy = ta.crossover(rsi, sma)
sell = ta.crossunder(rsi, sma)
if buy == true
strategy.entry('Long', strategy.long, comment='Buy')
if sell == true
strategy.close('Long', comment='Sell') |
DCA After Downtrend (by BHD_Trade_Bot) | https://www.tradingview.com/script/L4ffblzk-DCA-After-Downtrend-by-BHD-Trade-Bot/ | BHD_Trade_Bot | https://www.tradingview.com/u/BHD_Trade_Bot/ | 73 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © BHD_Trade_Bot
// @version=5
strategy(
shorttitle = 'DCA After Downtrend',
title = 'DCA After Downtrend (by BHD_Trade_Bot)',
overlay = true,
calc_on_every_tick = true,
calc_on_order_fills = true,
use_bar_magnifier = true,
pyramiding = 100,
initial_capital = 0,
default_qty_type = strategy.cash,
default_qty_value = 1000,
commission_type = strategy.commission.percent,
commission_value = 0.1)
// Backtest Time Period
start_year = input(title='Start year' ,defval=2017)
start_month = input(title='Start month' ,defval=1)
start_day = input(title='Start day' ,defval=1)
start_time = timestamp(start_year, start_month, start_day, 00, 00)
end_year = input(title='end year' ,defval=2050)
end_month = input(title='end month' ,defval=1)
end_day = input(title='end day' ,defval=1)
end_time = timestamp(end_year, end_month, end_day, 23, 59)
window() => time >= start_time and time <= end_time ? true : false
// EMA
ema50 = ta.ema(close, 50)
ema200 = ta.ema(close, 200)
// EMA_CD
emacd = ema50 - ema200
emacd_signal = ta.ema(emacd, 20)
hist = emacd - emacd_signal
// Count n candles after x long entries
var int nPastCandles = 0
var int entryNumber = 0
nPastCandles := nPastCandles + 1
// ENTRY CONDITIONS
// 8 hours per day => 240 hours per month
entry_condition1 = nPastCandles > entryNumber * 240
// End of downtrend
entry_condition2 = ta.crossover(emacd, emacd_signal)
ENTRY_CONDITIONS = entry_condition1 and entry_condition2
if ENTRY_CONDITIONS and window()
entryNumber := entryNumber + 1
entryId = 'Long ' + str.tostring(entryNumber)
strategy.entry(entryId, strategy.long)
// CLOSE CONDITIONS
// Last bar
CLOSE_CONDITIONS = barstate.islast
if CLOSE_CONDITIONS
strategy.close_all()
// Draw
plot(ema50, color=color.orange, linewidth=3)
plot(ema200, color=entry_condition1 ? color.green : color.red, linewidth=3)
|
Astor SMA20/60 TW | https://www.tradingview.com/script/TiGkIrSj/ | Astorhsu | https://www.tradingview.com/u/Astorhsu/ | 21 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Astorhsu
//@version=5
strategy("Astor SMA20/60 TW", overlay=true, margin_long=100, margin_short=100)
backtest_year = input(2018, title='backtest_year') //回測開始年分
backtest_month = input.int(01, title='backtest_month', minval=1, maxval=12) //回測開始月份
backtest_day = input.int(01, title='backtest_day', minval=1, maxval=31) //回測開始日期
start_time = timestamp(backtest_year, backtest_month, backtest_day, 00, 00) //回測開始的時間函數
//Indicators
sma20 = ta.sma(close,20)
sma60 = ta.sma(close,60)
plot(sma20, color=color.green, title="sma(20)")
plot(sma60, color=color.red, title="sma(60)")
//進場條件
longCondition = ta.crossover(close, ta.sma(close, 20))
if (longCondition) and time >= start_time
strategy.entry("open long20", strategy.long, qty=1, comment="站上m20做多")
shortCondition = ta.crossunder(close, ta.sma(close, 20))
if (shortCondition) and time >= start_time
strategy.close("open long20",comment="跌破m20平倉", qty=1)
longCondition1 = ta.crossover(close, ta.sma(close, 60))
if (longCondition1) and time >= start_time
strategy.entry("open long60", strategy.long, qty=1, comment="站上m60做多")
shortCondition1 = ta.crossunder(close, ta.sma(close, 60))
if (shortCondition1) and time >= start_time
strategy.close("open long60",comment="跌破m60平倉", qty=1) |
EMA and MACD with Trailing Stop Loss (by Coinrule) | https://www.tradingview.com/script/UjQ8LuV2-EMA-and-MACD-with-Trailing-Stop-Loss-by-Coinrule/ | Coinrule | https://www.tradingview.com/u/Coinrule/ | 157 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Coinrule
//@version=5
strategy('EMA and MACD with Trailing Stop Loss',
overlay=true,
initial_capital=1000,
process_orders_on_close=true,
default_qty_type=strategy.percent_of_equity,
default_qty_value=30,
commission_type=strategy.commission.percent,
commission_value=0.1)
showDate = input(defval=true, title='Show Date Range')
timePeriod = time >= timestamp(syminfo.timezone, 2022, 1, 1, 0, 0)
notInTrade = strategy.position_size <= 0
// EMAs
fastEMA = ta.ema(close, 7)
slowEMA = ta.ema(close, 14)
plot(fastEMA, color = color.blue)
plot(slowEMA, color = color.green)
//buyCondition1 = ta.crossover(fastEMA, slowEMA)
buyCondition1 = fastEMA > slowEMA
// DMI and MACD inputs and calculations
[macd, macd_signal, macd_histogram] = ta.macd(close, 12, 26, 9)
buyCondition2 = ta.crossover(macd_signal, macd)
// Configure trail stop level with input options
longTrailPerc = input.float(title='Trail Long Loss (%)', minval=0.0, step=0.1, defval=3) * 0.01
shortTrailPerc = input.float(title='Trail Short Loss (%)', minval=0.0, step=0.1, defval=1) * 0.01
// Determine trail stop loss prices
longStopPrice = 0.0
shortStopPrice = 0.0
longStopPrice := if strategy.position_size > 0
stopValue = close * (1 - longTrailPerc)
math.max(stopValue, longStopPrice[1])
else
0
shortStopPrice := if strategy.position_size < 0
stopValue = close * (1 + shortTrailPerc)
math.min(stopValue, shortStopPrice[1])
else
999999
if (buyCondition1 and buyCondition2 and notInTrade and timePeriod)
strategy.entry(id="Long", direction = strategy.long)
strategy.exit(id="Exit", stop = longStopPrice, limit = shortStopPrice)
//if (sellCondition1 and sellCondition2 and notInTrade and timePeriod)
//strategy.close(id="Close", when = sellCondition1 or sellCondition2)
|
Astor SMA20/60 | https://www.tradingview.com/script/ZWt0Eu3t/ | Astorhsu | https://www.tradingview.com/u/Astorhsu/ | 15 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Astorhsu
//@version=5
strategy("Astor SMA20/60", overlay=true, margin_long=100, margin_short=100)
backtest_year = input(2018, title='backtest_year') //回測開始年分
backtest_month = input.int(01, title='backtest_month', minval=1, maxval=12) //回測開始月份
backtest_day = input.int(01, title='backtest_day', minval=1, maxval=31) //回測開始日期
start_time = timestamp(backtest_year, backtest_month, backtest_day, 00, 00) //回測開始的時間函數
//Indicators
sma10 = ta.sma(close,10)
sma20 = ta.sma(close,20)
sma60 = ta.sma(close,60)
plot(sma20, color=color.green, title="sma(20)")
plot(sma60, color=color.red, title="sma(60)")
//進場條件
// trend1 = sma60 > sma20 //假設目前趨勢為60>20
longCondition = ta.crossover(close, ta.sma(close, 20))
if (longCondition) and time >=start_time
strategy.entry("open long20", strategy.long, qty=0.1, comment="站上m20做多")
shortCondition = ta.crossunder(close, ta.sma(close, 20))
if (shortCondition) and time >=start_time
strategy.close("open long20",comment="跌破m20平倉", qty=0.1)
longCondition1 = ta.crossover(close, ta.sma(close, 60))
if (longCondition1) and time >=start_time
strategy.entry("open long60", strategy.long, qty=0.1, comment="站上m60做多")
shortCondition1 = ta.crossunder(close, ta.sma(close, 60))
if (shortCondition1) and time >=start_time
strategy.close("open long60",comment="跌破m60平倉", qty=0.1)
// longCondition2 = ta.crossover(close, ta.sma(close, 10))
// if (longCondition2)
// strategy.entry("open long10", strategy.long, qty=0.1, comment="站上m10做多")
// shortCondition2 = ta.crossunder(close, ta.sma(close, 10))
// if (shortCondition2)
// strategy.close("open long10",comment="跌破m10平倉", qty=0.1)
|
Strategy Myth-Busting #8 - TrendSurfers+TrendOsc - [MYN] | https://www.tradingview.com/script/gH3jt4wN-Strategy-Myth-Busting-8-TrendSurfers-TrendOsc-MYN/ | myncrypto | https://www.tradingview.com/u/myncrypto/ | 108 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © myn
//@version=5
strategy('Strategy Myth-Busting #8 - TrendSurfers+TrendOsc - [MYN]', max_bars_back=5000, overlay=true, pyramiding=0, initial_capital=20000, currency='USD', default_qty_type=strategy.percent_of_equity, default_qty_value=100.0, commission_value=0.075, use_bar_magnifier = false)
/////////////////////////////////////
//* Put your strategy logic below *//
/////////////////////////////////////
//cAe9It4ynO4
// Strategies
// Trend Surfers - Premium Indicator
// Mawreez' Trend Oscillator Indicator
// Trading Setup / Rules
// Long Condition
// Trend Surfers Trailing stop line goes below (Crosses) lowest low
// Bullish Candle (red)
// Mawreeze Trend Oscilator Indicator is green
// Short Condition
// Trend Surfers Trailing stop line goes above (Crosses) highest high
// Bearish Candle (red)
// Mawreeze Trend Oscilator Indicator is red
// Stop loss middle between high and low Risk 1:2
//@version=5
//strategy(shorttitle='Trend Surfers - Breakout', title='Trend Surfers - Premium Breakout', overlay=true, calc_on_every_tick=false, initial_capital=100000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type='percent', commission_value=0.04)
// Risk for position and pyramid
maxriskval = input.float(2, 'Max % risk', tooltip='Risk % over total equity / Position', group='Risk Management')
pairnumber = input.int(title='How many pairs', defval=1, tooltip='How many pairs are you trading with the strategy?', group='Risk Management')
// Emtry Exit
highPeriod = input.int(title='Highest High Period', defval=168, tooltip='Highest High of X bars - This will trigger a Long Entry when close is above. (Thin Green Line)', group='Entry Condition')
lowPeriod = input.int(title='Lowest Low Period', defval=168, tooltip='Lowest low of X bars - This will trigger a Short Entry when close is under. (Thin Red Line)', group='Entry Condition')
// Stoploss
trailingAtrPeriod = input.int(title='Trailing ATR Pediod', defval=10, tooltip='Average True Range for the Trailing Stop. (Thick Green Line) ', group='Exit Condition')
trailingAtrMultiplier = input.float(title='Trailing ATR Multiplier', defval=8, group='Exit Condition')
fixAtrPeriod = input.int(title='Fix ATR Pediod', defval=10, tooltip='Average True Range for the Fix Stoloss. (Thick Yellow Line)', group='Exit Condition')
fixAtrMultiplier = input.float(title='Fix ATR Multiplier', defval=2, group='Exit Condition')
// Pair info
pair = syminfo.basecurrency + syminfo.currency
// High Low Variable
highestHigh = ta.highest(high, highPeriod)[1]
lowestLow = ta.lowest(low, lowPeriod)[1]
trailingAtr = ta.atr(trailingAtrPeriod) * trailingAtrMultiplier
// Trade Condition
longConditionTrendSurfers = ta.crossover(close, highestHigh)
shortConditionTrendSurfers = ta.crossunder(close, lowestLow)
// Risk Variable
fixAtr = ta.atr(fixAtrPeriod) * fixAtrMultiplier
stopvaluelong = close[1] - fixAtr[1]
stopvalueshort = close[1] + fixAtr[1]
// Position size Long
maxpossize = strategy.equity / close
positionsizelong = maxriskval / 100 * strategy.equity / (close - stopvaluelong)
stopperclong = (close - stopvaluelong) / close * 100
leveragelong = math.max(1, math.ceil(positionsizelong / maxpossize)) * 2
posperclong = positionsizelong * close / strategy.equity * 100 / leveragelong / pairnumber
realposlong = posperclong / 100 * strategy.equity * leveragelong / close
// Position size Short
positionsizeshort = maxriskval / 100 * strategy.equity / (stopvalueshort - close)
stoppercshort = (close - stopvalueshort) / close * 100
leverageshort = math.max(1, math.ceil(positionsizeshort / maxpossize)) * 2
pospercshort = positionsizeshort * close / strategy.equity * 100 / leverageshort / pairnumber
realposshort = pospercshort / 100 * strategy.equity * leverageshort / close
// Alert Message
entry_long_message = '\nGo Long for ' + pair + 'NOW!' + '\nPosition Size % =' + str.tostring(posperclong) + '\nLeverage' + str.tostring(leveragelong) + '\nStoploss Price =' + str.tostring(stopvaluelong) + '\nClose any Short position that are open for ' + pair + '!' + '\n\nVisit TrendSurfersSignals.com' + '\nFor automated premium signals (FREE)'
entry_short_message = '\nGo Short for ' + pair + 'NOW!' + '\nPosition Size % =' + str.tostring(pospercshort) + '\nLeverage' + str.tostring(leverageshort) + '\nStoploss Price =' + str.tostring(stopvalueshort) + '\nClose any Long position that are open for ' + pair + '!' + '\n\nVisit TrendSurfersSignals.com' + '\nFor automated premium signals (FREE)'
exit_short_message = '\nExit Short for ' + pair + 'NOW!' + '\n\nVisit TrendSurfersSignals.com' + '\nFor automated premium signals (FREE)'
exit_long_message = '\nExit Long for ' + pair + 'NOW!' + '\n\nVisit TrendSurfersSignals.com' + '\nFor automated premium signals (FREE)'
// Order
// if longCondition
// strategy.entry('Long', strategy.long, stop=highestHigh, comment='Long', qty=realposlong, alert_message=entry_long_message)
// if shortCondition
// strategy.entry('Short', strategy.short, stop=lowestLow, comment='Short', qty=realposshort, alert_message=entry_short_message)
// Stoploss Trailing
longTrailing = close - trailingAtr
shortTrailing = close + trailingAtr
var longTrailingStop = 0.0
var shortTrailingStop = 999999.9
trailingStopLine = 0.0
trailingStopLine := na
fixedStopLine = 0.0
fixedStopLine := na
var inTrade = 0
if longConditionTrendSurfers or shortConditionTrendSurfers
if 0 == inTrade
if longConditionTrendSurfers
inTrade := 1
inTrade
else
inTrade := -1
inTrade
if 1 == inTrade and (shortConditionTrendSurfers or low <= math.max(fixedStopLine[1], longTrailingStop))
inTrade := 0
inTrade
if -1 == inTrade and (longConditionTrendSurfers or high >= math.min(fixedStopLine[1], shortTrailingStop))
inTrade := 0
inTrade
longTrailingStop := if 1 == inTrade
stopValue = longTrailing
math.max(stopValue, longTrailingStop[1])
else
0
shortTrailingStop := if -1 == inTrade
stopValue = shortTrailing
math.min(stopValue, shortTrailingStop[1])
else
999999
// Fix Stoploss
firstPrice = 0.0
firstFixAtr = 0.0
firstPrice := na
firstFixAtr := na
if 0 != inTrade
firstPrice := ta.valuewhen(inTrade != inTrade[1] and 0 != inTrade, close, 0)
firstFixAtr := ta.valuewhen(inTrade != inTrade[1] and 0 != inTrade, fixAtr, 0)
if 1 == inTrade
fixedStopLine := firstPrice - firstFixAtr
trailingStopLine := longTrailingStop
trailingStopLine
else
fixedStopLine := firstPrice + firstFixAtr
trailingStopLine := shortTrailingStop
trailingStopLine
// if strategy.position_size > 0
// strategy.exit(id='L Stop', stop=math.max(fixedStopLine, longTrailingStop), alert_message=exit_long_message)
// if strategy.position_size < 0
// strategy.exit(id='S Stop', stop=math.min(fixedStopLine, shortTrailingStop), alert_message=exit_short_message)
// Plot
plot(highestHigh, color=color.new(color.green, 0), linewidth=1, title='Highest High')
plot(lowestLow, color=color.new(color.red, 0), linewidth=1, title='Lowest Low')
plot(trailingStopLine, color=color.new(color.lime, 0), linewidth=2, offset=1, title='Trailing Stop')
plot(fixedStopLine, color=color.new(color.orange, 0), linewidth=2, offset=1, title='Fixed Stop')
// Trend Surfers Trailing stop line goes above (Crossesover) highest high
// Bearish Candle (red)
// Mawreeze Trend Oscilator Indicator is red
trendSurfersShortEntry = trailingStopLine > highestHigh and close < close[1]
trendSurfersLongEntry = trailingStopLine < lowestLow and close > close[1]
//@version=5
// Taken from the TradingView house rules regarding scripts:
// "All open source scripts that do not mention a specific open source license
// in their comments are licensed under the Mozilla Public License 2.0.
// Following the Mozilla License, any script reusing open source code originally
// published by someone else must also be open source, unless specific
// permission is granted by the original author."
//indicator('Mawreez\' Trend Oscillator', precision=3)
len = input.int(title='DI Length', minval=1, defval=14)
sens = input.float(title='Sensitivity', defval=25)
// Lag-free smoothing of a given series
smooth(series, len) =>
f28 = ta.ema(series, len)
f30 = ta.ema(f28, len)
vC = f28 * 1.5 - f30 * 0.5
f38 = ta.ema(vC, len)
f40 = ta.ema(f38, len)
v10 = f38 * 1.5 - f40 * 0.5
f48 = ta.ema(v10, len)
f50 = ta.ema(f48, len)
f48 * 1.5 - f50 * 0.5
// Constructing the +DI and -DI
up = ta.change(high)
down = -ta.change(low)
plus_dm = up > 0 and up > down ? up : 0
minus_dm = down > 0 and down > up ? down : 0
range_1 = ta.rma(ta.tr, len)
plus_di = smooth(ta.rma(plus_dm, len) / range_1, 3)
minus_di = smooth(ta.rma(minus_dm, len) / range_1, 3)
// Constructing and plotting the modified ADX
adj_adx = 100 * math.abs(plus_di - minus_di) / (plus_di + minus_di) - sens
adj_adx := (minus_di > plus_di ? -1 : 1) * (adj_adx < 0 ? 0 : adj_adx)
//plot(smooth(adj_adx, 3), color=plus_di > minus_di ? color.green : color.red, style=plot.style_columns)
trendOscShortEntry = plus_di < minus_di
trendOscLongEntry = plus_di > minus_di
//////////////////////////////////////
//* Put your strategy rules below *//
/////////////////////////////////////
longCondition = trendSurfersLongEntry and trendOscLongEntry
shortCondition = trendSurfersShortEntry and trendOscShortEntry
//define as 0 if do not want to use
closeLongCondition = 0
closeShortCondition = 0
// ADX
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
adxEnabled = input.bool(defval = false , title = "Average Directional Index (ADX)", tooltip = "", group ="ADX" )
adxlen = input(14, title="ADX Smoothing", group="ADX")
adxdilen = input(14, title="DI Length", group="ADX")
adxabove = input(25, title="ADX Threshold", group="ADX")
adxdirmov(len) =>
adxup = ta.change(high)
adxdown = -ta.change(low)
adxplusDM = na(adxup) ? na : (adxup > adxdown and adxup > 0 ? adxup : 0)
adxminusDM = na(adxdown) ? na : (adxdown > adxup and adxdown > 0 ? adxdown : 0)
adxtruerange = ta.rma(ta.tr, len)
adxplus = fixnan(100 * ta.rma(adxplusDM, len) / adxtruerange)
adxminus = fixnan(100 * ta.rma(adxminusDM, len) / adxtruerange)
[adxplus, adxminus]
adx(adxdilen, adxlen) =>
[adxplus, adxminus] = adxdirmov(adxdilen)
adxsum = adxplus + adxminus
adx = 100 * ta.rma(math.abs(adxplus - adxminus) / (adxsum == 0 ? 1 : adxsum), adxlen)
adxsig = adxEnabled ? adx(adxdilen, adxlen) : na
isADXEnabledAndAboveThreshold = adxEnabled ? (adxsig > adxabove) : true
//Backtesting Time Period (Input.time not working as expected as of 03/30/2021. Giving odd start/end dates
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
useStartPeriodTime = input.bool(true, 'Start', group='Date Range', inline='Start Period')
startPeriodTime = input.time(timestamp('1 Jan 2019'), '', group='Date Range', inline='Start Period')
useEndPeriodTime = input.bool(true, 'End', group='Date Range', inline='End Period')
endPeriodTime = input.time(timestamp('31 Dec 2030'), '', group='Date Range', inline='End Period')
start = useStartPeriodTime ? startPeriodTime >= time : false
end = useEndPeriodTime ? endPeriodTime <= time : false
calcPeriod = not start and not end
// Trade Direction
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tradeDirection = input.string('Long and Short', title='Trade Direction', options=['Long and Short', 'Long Only', 'Short Only'], group='Trade Direction')
// Percent as Points
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
per(pcnt) =>
strategy.position_size != 0 ? math.round(pcnt / 100 * strategy.position_avg_price / syminfo.mintick) : float(na)
// Take profit 1
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tp1 = input.float(title='Take Profit 1 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 1')
q1 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 1')
// Take profit 2
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tp2 = input.float(title='Take Profit 2 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 2')
q2 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 2')
// Take profit 3
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tp3 = input.float(title='Take Profit 3 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 3')
q3 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 3')
// Take profit 4
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
tp4 = input.float(title='Take Profit 4 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit')
/// Stop Loss
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
stoplossPercent = input.float(title='Stop Loss (%)', defval=999, minval=0.01, group='Stop Loss') * 0.01
slLongClose = close < strategy.position_avg_price * (1 - stoplossPercent)
slShortClose = close > strategy.position_avg_price * (1 + stoplossPercent)
/// Leverage
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
leverage = input.float(1, 'Leverage', step=.5, group='Leverage')
contracts = math.min(math.max(.000001, strategy.equity / close * leverage), 1000000000)
/// Trade State Management
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
isInLongPosition = strategy.position_size > 0
isInShortPosition = strategy.position_size < 0
/// ProfitView Alert Syntax String Generation
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
alertSyntaxPrefix = input.string(defval='CRYPTANEX_99FTX_Strategy-Name-Here', title='Alert Syntax Prefix', group='ProfitView Alert Syntax')
alertSyntaxBase = alertSyntaxPrefix + '\n#' + str.tostring(open) + ',' + str.tostring(high) + ',' + str.tostring(low) + ',' + str.tostring(close) + ',' + str.tostring(volume) + ','
/// Trade Execution
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
longConditionCalc = (longCondition and isADXEnabledAndAboveThreshold)
shortConditionCalc = (shortCondition and isADXEnabledAndAboveThreshold)
if calcPeriod
if longConditionCalc and tradeDirection != 'Short Only' and isInLongPosition == false
strategy.entry('Long', strategy.long, qty=contracts)
alert(message=alertSyntaxBase + 'side:long', freq=alert.freq_once_per_bar_close)
if shortConditionCalc and tradeDirection != 'Long Only' and isInShortPosition == false
strategy.entry('Short', strategy.short, qty=contracts)
alert(message=alertSyntaxBase + 'side:short', freq=alert.freq_once_per_bar_close)
//Inspired from Multiple %% profit exits example by adolgo https://www.tradingview.com/script/kHhCik9f-Multiple-profit-exits-example/
strategy.exit('TP1', qty_percent=q1, profit=per(tp1))
strategy.exit('TP2', qty_percent=q2, profit=per(tp2))
strategy.exit('TP3', qty_percent=q3, profit=per(tp3))
strategy.exit('TP4', profit=per(tp4))
strategy.close('Long', qty_percent=100, comment='SL Long', when=slLongClose)
strategy.close('Short', qty_percent=100, comment='SL Short', when=slShortClose)
strategy.close_all(when=closeLongCondition or closeShortCondition, comment='Close Postion')
/// Dashboard
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Inspired by https://www.tradingview.com/script/uWqKX6A2/ - Thanks VertMT
showDashboard = input.bool(group="Dashboard", title="Show Dashboard", defval=true)
f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) =>
_cellText = _title + "\n" + _value
table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor, text_size=size.auto)
// Draw dashboard table
if showDashboard
var bgcolor = color.new(color.black,0)
// Keep track of Wins/Losses streaks
newWin = (strategy.wintrades > strategy.wintrades[1]) and (strategy.losstrades == strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1])
newLoss = (strategy.wintrades == strategy.wintrades[1]) and (strategy.losstrades > strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1])
varip int winRow = 0
varip int lossRow = 0
varip int maxWinRow = 0
varip int maxLossRow = 0
if newWin
lossRow := 0
winRow := winRow + 1
if winRow > maxWinRow
maxWinRow := winRow
if newLoss
winRow := 0
lossRow := lossRow + 1
if lossRow > maxLossRow
maxLossRow := lossRow
// Prepare stats table
var table dashTable = table.new(position.bottom_right, 1, 15, border_width=1)
if barstate.islastconfirmedhistory
// Update table
dollarReturn = strategy.netprofit
f_fillCell(dashTable, 0, 0, "Start:", str.format("{0,date,long}", strategy.closedtrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.closedtrades.entry_time(0))
f_fillCell(dashTable, 0, 1, "End:", str.format("{0,date,long}", strategy.opentrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.opentrades.entry_time(0))
_profit = (strategy.netprofit / strategy.initial_capital) * 100
f_fillCell(dashTable, 0, 2, "Net Profit:", str.tostring(_profit, '##.##') + "%", _profit > 0 ? color.green : color.red, color.white)
_numOfDaysInStrategy = (strategy.opentrades.entry_time(0) - strategy.closedtrades.entry_time(0)) / (1000 * 3600 * 24)
f_fillCell(dashTable, 0, 3, "Percent Per Day", str.tostring(_profit / _numOfDaysInStrategy, '#########################.#####')+"%", _profit > 0 ? color.green : color.red, color.white)
_winRate = ( strategy.wintrades / strategy.closedtrades ) * 100
f_fillCell(dashTable, 0, 4, "Percent Profitable:", str.tostring(_winRate, '##.##') + "%", _winRate < 50 ? color.red : _winRate < 75 ? #999900 : color.green, color.white)
f_fillCell(dashTable, 0, 5, "Profit Factor:", str.tostring(strategy.grossprofit / strategy.grossloss, '##.###'), strategy.grossprofit > strategy.grossloss ? color.green : color.red, color.white)
f_fillCell(dashTable, 0, 6, "Total Trades:", str.tostring(strategy.closedtrades), bgcolor, color.white)
f_fillCell(dashTable, 0, 8, "Max Wins In A Row:", str.tostring(maxWinRow, '######') , bgcolor, color.white)
f_fillCell(dashTable, 0, 9, "Max Losses In A Row:", str.tostring(maxLossRow, '######') , bgcolor, color.white) |
Heiken Ashi & Super Trend | https://www.tradingview.com/script/KkA3sgXM/ | RingsCherrY | https://www.tradingview.com/u/RingsCherrY/ | 187 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RingsCherrY
//@version=5
strategy("Heiken Ashi & Super Trend", overlay=true, pyramiding=1,initial_capital = 10000, default_qty_type= strategy.percent_of_equity, default_qty_value = 100, calc_on_order_fills=false, slippage=0,commission_type=strategy.commission.percent,commission_value=0.02)
///////////////////////////////////////////////////
////////////////////Function///////////////////////
///////////////////////////////////////////////////
heikinashi_open = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
heikinashi_high = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
heikinashi_low = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
heikinashi_close= request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
heikinashi_color = heikinashi_open < heikinashi_close ? #53b987 : #eb4d5c
// plotbar(heikinashi_open, heikinashi_high, heikinashi_low, heikinashi_close, color=heikinashi_color)
x_sma(x, y) =>
sumx = 0.0
for i = 0 to y - 1
sumx := sumx + x[i] / y
sumx
x_rma(src, length) =>
alpha = 1/length
sum = 0.0
sum := na(sum[1]) ? x_sma(src, length) : alpha * src + (1 - alpha) * nz(sum[1])
x_atr(length) =>
trueRange = na(heikinashi_high[1])? heikinashi_high-heikinashi_low : math.max(math.max(heikinashi_high - heikinashi_low, math.abs(heikinashi_high - heikinashi_close[1])), math.abs(heikinashi_low - heikinashi_close[1]))
//true range can be also calculated with ta.tr(true)
x_rma(trueRange, length)
x_supertrend(factor, atrPeriod) =>
src = (heikinashi_high+heikinashi_low)/2
atr = x_atr(atrPeriod)
upperBand = src + factor * atr
lowerBand = src - factor * atr
prevLowerBand = nz(lowerBand[1])
prevUpperBand = nz(upperBand[1])
lowerBand := lowerBand > prevLowerBand or heikinashi_close[1] < prevLowerBand ? lowerBand : prevLowerBand
upperBand := upperBand < prevUpperBand or heikinashi_close[1] > prevUpperBand ? upperBand : prevUpperBand
int direction = na
float superTrend = na
prevSuperTrend = superTrend[1]
if na(atr[1])
direction := 1
else if prevSuperTrend == prevUpperBand
direction := heikinashi_close > upperBand ? -1 : 1
else
direction := heikinashi_close < lowerBand ? 1 : -1
superTrend := direction == -1 ? lowerBand : upperBand
[superTrend, direction]
///////////////////////////////////////////////////
////////////////////Indicators/////////////////////
///////////////////////////////////////////////////
atrPeriod = input(10, "ATR Length")
factor = input.float(3.0, "Factor", step = 0.01)
[supertrend, direction] = x_supertrend(factor, atrPeriod)
bodyMiddle = plot((heikinashi_open + heikinashi_close) / 2, display=display.none)
upTrend = plot(direction < 0 ? supertrend : na, "Up Trend", color = color.green, style=plot.style_linebr)
downTrend = plot(direction < 0? na : supertrend, "Down Trend", color = color.red, style=plot.style_linebr)
fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps=false)
fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps=false)
///////////////////////////////////////////////////
////////////////////Strategy///////////////////////
///////////////////////////////////////////////////
var bool longCond = na, var bool shortCond = na, longCond := nz(longCond[1]), shortCond := nz(shortCond[1])
var int CondIni_long = 0, var int CondIni_short = 0, CondIni_long := nz(CondIni_long[1]), CondIni_short := nz(CondIni_short[1])
var float open_longCondition = na, var float open_shortCondition = na
long = ta.change(direction) < 0
short = ta.change(direction) > 0
longCond := long
shortCond := short
CondIni_long := longCond[1] ? 1 : shortCond[1] ? -1 : nz(CondIni_long[1])
CondIni_short := longCond[1] ? 1 : shortCond[1] ? -1 : nz(CondIni_short[1])
longCondition = (longCond[1] and nz(CondIni_long[1]) == -1)
shortCondition = (shortCond[1] and nz(CondIni_short[1]) == 1)
open_longCondition := long ? close[1] : nz(open_longCondition[1])
open_shortCondition := short ? close[1] : nz(open_shortCondition[1])
//TP
tp = input.float(1.1 , "TP [%]", step = 0.1)
//BACKTESTING inputs --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
testStartYear = input.int(2000, title="start year", minval = 1997, maxval = 3000, group= "BACKTEST")
testStartMonth = input.int(01, title="start month", minval = 1, maxval = 12, group= "BACKTEST")
testStartDay = input.int(01, title="start day", minval = 1, maxval = 31, group= "BACKTEST")
testPeriodStart = timestamp(testStartYear,testStartMonth,testStartDay,0,0)
testStopYear = input.int(3333, title="stop year", minval=1980, maxval = 3333, group= "BACKTEST")
testStopMonth = input.int(12, title="stop month", minval=1, maxval=12, group= "BACKTEST")
testStopDay = input.int(31, title="stop day", minval=1, maxval=31, group= "BACKTEST")
testPeriodStop = timestamp(testStopYear, testStopMonth, testStopDay, 0, 0)
testPeriod = time >= testPeriodStart and time <= testPeriodStop ? true : false
// Backtest ==================================================================================================================================================================================================================================================================================================================================
if longCond
strategy.entry("L", strategy.long, when=testPeriod)
if shortCond
strategy.entry("S", strategy.short, when=testPeriod)
strategy.exit("TP_L", "L", profit =((open_longCondition * (1+(tp/100))) - open_longCondition)/syminfo.mintick)
strategy.exit("TP_S", "S", profit =((open_shortCondition * (1+(tp/100))) - open_shortCondition)/syminfo.mintick)
|
[Sniper] SSL Hybrid + QQE MOD + Waddah Attar Strategy | https://www.tradingview.com/script/FxJdGwmG/ | DuDu95 | https://www.tradingview.com/u/DuDu95/ | 360 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © fpemehd
// Thanks to myncrypto, jason5480, kevinmck100
// @version=5
strategy(title = '[D] SSL Hybrid + QQE MOD + Waddah Attar Strategy',
shorttitle = '[D] SQW Strategy',
overlay = true,
pyramiding = 0,
currency = currency.USD,
default_qty_type = strategy.percent_of_equity,
default_qty_value = 100,
commission_value = 0.1,
initial_capital = 100000,
max_bars_back = 500,
max_lines_count = 150,
max_labels_count = 300)
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Time, Direction, Etc - Basic Settings Inputs
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// 1. Time: Based on UTC +09:00
i_start = input.time (defval = timestamp("20 Jan 1990 00:00 +0900"), title = "Start Date", tooltip = "Choose Backtest Start Date", inline = "Start Date", group = "Time" )
i_end = input.time (defval = timestamp("20 Dec 2030 00:00 +0900"), title = "End Date", tooltip = "Choose Backtest End Date", inline = "End Date", group = "Time" )
inTime = time >= i_start and time <= i_end
// 2. Inputs for direction: Long? Short? Both?
i_longEnabled = input.bool (defval = true , title = "Long?", tooltip = "Enable Long Position Trade?", inline = "Long / Short", group = "Long / Short" )
i_shortEnabled = input.bool (defval = true , title = "Short?", tooltip = "Enable Short Position Trade?", inline = "Long / Short", group = "Long / Short" )
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Filter - Inputs, Indicaotrs
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// 3. Use Filters? What Filters?
//// 3-1. ATR Filter
i_ATRFilterOn = input.bool (defval = false , title = "ATR Filter On?", tooltip = "ATR Filter On? Order will not be made unless filter condition is fulfilled", inline = "1", group = "Filters")
i_ATRFilterLen = input.int (defval = 14, title = "Length for ATR Filter", minval = 1 , maxval = 100 , step = 1 , tooltip = "", inline = "2", group = "Filters")
i_ATRSMALen = input.int (defval = 40, title = "SMA Length for ATR SMA", minval = 1 , maxval = 100000 , step = 1 , tooltip = "ATR should be bigger than this", inline = "2", group = "Filters")
bool ATRFilter = ta.atr(i_ATRFilterLen) >= ta.sma(ta.atr(length = i_ATRFilterLen), i_ATRSMALen) ? true : false
//// 3-2. EMA Filter
i_EMAFilterOn = input.bool (defval = false , title = "EMA Filter On?", tooltip = "EMA Filter On? Order will not be made unless filter condition is fulfilled", inline = "3", group = "Filters")
i_EMALen = input.int (defval = 200, title = "EMA Length", minval = 1 , maxval = 100000 , step = 1 , tooltip = "EMA Length", inline = "4", group = "Filters")
bool longEMAFilter = close >= ta.ema(source = close, length = i_EMALen) ? true : false
bool shortEMAFilter = close <= ta.ema(source = close, length = i_EMALen) ? true : false
plot(i_EMAFilterOn ? ta.ema(source = close, length = i_EMALen) : na, title = "EMA Filter", color = color.new(color = color.orange , transp = 0), linewidth = 1)
//// 3-3. ADX Filter
//// 3-4. DMI Filter (Uses same ADX Length)
i_ADXFilterOn = input.bool (defval = false , title = "ADX Filter On?", tooltip = "ADX Filter On? Order will not be made unless filter condition is fulfilled", inline = "5", group = "Filters")
i_DMIFilterOn = input.bool (defval = false , title = "DMI Filter On?", tooltip = "DMI (Directional Moving Index) Filter On? Order will not be made unless filter condition is fulfilled", inline = "6", group = "Filters")
i_ADXLength = input.int (defval = 20, title = "ADX Length", minval = 1 , maxval = 100000 , step = 1 , tooltip = "ADX Length", inline = "7", group = "Filters")
i_ADXThreshold = input.int (defval = 25, title = "ADX Threshold", minval = 1 , maxval = 100000 , step = 1 , tooltip = "ADX should be bigger than threshold", inline = "8", group = "Filters")
//// 3-5. SuperTrend Filter
i_superTrendFilterOn = input.bool (defval = false , title = "Super Trend Filter On?", tooltip = "Super Trend Filter On? Order will not be made unless filter condition is fulfilled", inline = "9", group = "Filters")
i_superTrendATRLen = input.int (defval = 10, title = "ATR Length", minval = 1 , maxval = 100000 , step = 1 , tooltip = "Super Trend ATR Length", inline = "10", group = "Filters")
i_superTrendATRFactor = input.float (defval = 3, title = "Factor", minval = 1 , maxval = 100000 , step = 0.1 , tooltip = "Super Trend ATR Factor", inline = "11", group = "Filters")
// ADX and DI Thanks to @BeikabuOyaji
int len = i_ADXLength
float th = i_ADXThreshold
TR = math.max(math.max(high - low, math.abs(high - nz(close[1]))), math.abs(low - nz(close[1])))
DMPlus = high - nz(high[1]) > nz(low[1]) - low ? math.max(high - nz(high[1]), 0) : 0
DMMinus = nz(low[1]) - low > high - nz(high[1]) ? math.max(nz(low[1]) - low, 0) : 0
SmoothedTR = 0.0
SmoothedTR := nz(SmoothedTR[1]) - nz(SmoothedTR[1]) / len + TR
SmoothedDMPlus = 0.0
SmoothedDMPlus := nz(SmoothedDMPlus[1]) - nz(SmoothedDMPlus[1]) / len + DMPlus
SmoothedDMMinus = 0.0
SmoothedDMMinus := nz(SmoothedDMMinus[1]) - nz(SmoothedDMMinus[1]) / len + DMMinus
DIPlus = SmoothedDMPlus / SmoothedTR * 100
DIMinus = SmoothedDMMinus / SmoothedTR * 100
DX = math.abs(DIPlus - DIMinus) / (DIPlus + DIMinus) * 100
ADX = ta.sma(source = DX, length = len)
// plot(DIPlus, color=color.new(color.green, 0), title='DI+')
// plot(DIMinus, color=color.new(color.red, 0), title='DI-')
// plot(ADX, color=color.new(color.navy, 0), title='ADX')
// hline(th, color=color.white)
bool ADXFilter = ADX > th ? true : false
bool longDMIFilter = DIPlus >= DIMinus ? true : false
bool shortDMIFilter = DIPlus <= DIMinus ? true : false
// Calculate Super Trend for Filter
[supertrend, direction] = ta.supertrend(factor = i_superTrendATRFactor, atrPeriod = i_superTrendATRLen)
bodyMiddle = plot((open + close) / 2, display=display.none)
upTrend = plot(i_superTrendFilterOn ? direction < 0 ? supertrend : na : na, "Up Trend", color = color.green, style=plot.style_linebr)
downTrend = plot(i_superTrendFilterOn ? direction < 0 ? na : supertrend : na, "Down Trend", color = color.red, style=plot.style_linebr)
fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps=false)
fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps=false)
bool longSTFilter = direction <= 0
bool shortSTFilter = direction >= 0
// Filter
bool longFilterFilled = (not i_ATRFilterOn or ATRFilter) and (not i_EMAFilterOn or longEMAFilter) and (not i_ADXFilterOn or ADXFilter) and (not i_DMIFilterOn or longDMIFilter) and (not i_superTrendFilterOn or longSTFilter)
bool shortFilterFilled = (not i_ATRFilterOn or ATRFilter) and (not i_EMAFilterOn or shortEMAFilter) and (not i_ADXFilterOn or ADXFilter) and (not i_DMIFilterOn or shortDMIFilter) and (not i_superTrendFilterOn or shortSTFilter)
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Strategy Logic (Entry & Exit Condition) - Inputs, Indicators for Strategy
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
//// Indicators
// Inputs for Strategy Indicators
//// 1. SSL Hybrid Baseline
i_useTrueRange = input.bool (defval = true, title = "use true range for Keltner Channel?", tooltip = "", inline = "1", group = "1: SSL Hybrid")
i_maType = input.string (defval ='EMA', title='Baseline Type', options=['SMA', 'EMA', 'DEMA', 'TEMA', 'LSMA', 'WMA', 'VAMA', 'TMA', 'HMA', 'McGinley'], inline="2", group = "1: SSL Hybrid")
i_len = input.int (defval =30, title='Baseline Length', inline="2", group = "1: SSL Hybrid")
i_multy = input.float (defval = 0.2, title='Base Channel Multiplier', minval = 0, maxval = 100, step=0.05, inline="3", group = "1: SSL Hybrid")
i_volatility_lookback = input.int (defval =10, title='Volatility lookback length(for VAMA)', inline='4',group="1: SSL Hybrid")
tema(src, len) =>
ema1 = ta.ema(src, len)
ema2 = ta.ema(ema1, len)
ema3 = ta.ema(ema2, len)
3 * ema1 - 3 * ema2 + ema3
f_ma(type, src, len) =>
float result = 0
if type == 'TMA'
result := ta.sma(ta.sma(src, math.ceil(len / 2)), math.floor(len / 2) + 1)
result
if type == 'LSMA'
result := ta.linreg(src, len, 0)
result
if type == 'SMA' // Simple
result := ta.sma(src, len)
result
if type == 'EMA' // Exponential
result := ta.ema(src, len)
result
if type == 'DEMA' // Double Exponential
e = ta.ema(src, len)
result := 2 * e - ta.ema(e, len)
result
if type == 'TEMA' // Triple Exponential
e = ta.ema(src, len)
result := 3 * (e - ta.ema(e, len)) + ta.ema(ta.ema(e, len), len)
result
if type == 'WMA' // Weighted
result := ta.wma(src, len)
result
if type == 'VAMA' // Volatility Adjusted
/// Copyright © 2019 to present, Joris Duyck (JD)
mid = ta.ema(src, len)
dev = src - mid
vol_up = ta.highest(dev, i_volatility_lookback)
vol_down = ta.lowest(dev, i_volatility_lookback)
result := mid + math.avg(vol_up, vol_down)
result
if type == 'HMA' // Hull
result := ta.wma(2 * ta.wma(src, len / 2) - ta.wma(src, len), math.round(math.sqrt(len)))
result
if type == 'McGinley'
mg = 0.0
mg := na(mg[1]) ? ta.ema(src, len) : mg[1] + (src - mg[1]) / (len * math.pow(src / mg[1], 4))
result := mg
result
result
//// 1-1. SSL Hybrid Keltner Baseline Channel
BBMC = f_ma (i_maType, close, i_len) // BaseLone
Keltma = f_ma (i_maType, close, i_len)
range_1 = i_useTrueRange ? ta.tr : high - low
rangema = ta.ema(range_1, i_len)
upperk = Keltma + rangema * i_multy
lowerk = Keltma - rangema * i_multy
//// 2. QQE MOD, thanks to Mihkel100
RSI_Period = input.int (defval = 6, title = 'RSI Length', inline = "1", group = "2: QQE MOD")
SF = input.int (defval = 5, title = 'RSI Smoothing', inline = "2", group = "2: QQE MOD")
QQE = input.float (defval = 3, title = 'Fast QQE Factor', inline = "3", group = "2: QQE MOD")
ThreshHold = input.int (defval = 3, title = 'Thresh-hold', inline = "4", group = "2: QQE MOD")
src = input (defval = close, title='RSI Source')
Wilders_Period = RSI_Period * 2 - 1
Rsi = ta.rsi(src, RSI_Period)
RsiMa = ta.ema(Rsi, SF)
AtrRsi = math.abs(RsiMa[1] - RsiMa)
MaAtrRsi = ta.ema(AtrRsi, Wilders_Period)
dar = ta.ema(MaAtrRsi, Wilders_Period) * QQE
longband = 0.0
shortband = 0.0
trend = 0
DeltaFastAtrRsi = dar
RSIndex = RsiMa
newshortband = RSIndex + DeltaFastAtrRsi
newlongband = RSIndex - DeltaFastAtrRsi
longband := RSIndex[1] > longband[1] and RSIndex > longband[1] ? math.max(longband[1], newlongband) : newlongband
shortband := RSIndex[1] < shortband[1] and RSIndex < shortband[1] ? math.min(shortband[1], newshortband) : newshortband
cross_1 = ta.cross(longband[1], RSIndex)
trend := ta.cross(RSIndex, shortband[1]) ? 1 : cross_1 ? -1 : nz(trend[1], 1)
FastAtrRsiTL = trend == 1 ? longband : shortband
////////////////////
length = input.int (defval = 50, minval = 1, title = 'Bollinger Length', group = "2: QQE MOD")
mult = input.float (defval = 0.35, minval = 0.01, maxval = 5, step = 0.1, title = 'BB Multiplier', group = "2: QQE MOD")
basis = ta.sma(FastAtrRsiTL - 50, length)
dev = mult * ta.stdev(FastAtrRsiTL - 50, length)
upper = basis + dev
lower = basis - dev
color_bar = RsiMa - 50 > upper ? #00c3ff : RsiMa - 50 < lower ? #ff0062 : color.gray
//
// Zero cross
QQEzlong = 0
QQEzlong := nz(QQEzlong[1])
QQEzshort = 0
QQEzshort := nz(QQEzshort[1])
QQEzlong := RSIndex >= 50 ? QQEzlong + 1 : 0
QQEzshort := RSIndex < 50 ? QQEzshort + 1 : 0
//
// Zero = hline(0, color=color.white, linestyle=hline.style_dotted, linewidth=1)
////////////////////////////////////////////////////////////////
RSI_Period2 = input.int (defval = 6, title = 'RSI 2 Length', group = "2: QQE MOD")
SF2 = input.int (defval = 5, title = 'RSI Smoothing', group = "2: QQE MOD")
QQE2 = input.float (defval = 1.61, title = 'Fast QQE2 Factor', group = "2: QQE MOD")
ThreshHold2 = input.int (defval = 3, title = 'Thresh-hold', group = "2: QQE MOD")
src2 = input (defval = close, title = 'RSI Source', group = "2: QQE MOD")
//
//
Wilders_Period2 = RSI_Period2 * 2 - 1
Rsi2 = ta.rsi(src2, RSI_Period2)
RsiMa2 = ta.ema(Rsi2, SF2)
AtrRsi2 = math.abs(RsiMa2[1] - RsiMa2)
MaAtrRsi2 = ta.ema(AtrRsi2, Wilders_Period2)
dar2 = ta.ema(MaAtrRsi2, Wilders_Period2) * QQE2
longband2 = 0.0
shortband2 = 0.0
trend2 = 0
DeltaFastAtrRsi2 = dar2
RSIndex2 = RsiMa2
newshortband2 = RSIndex2 + DeltaFastAtrRsi2
newlongband2 = RSIndex2 - DeltaFastAtrRsi2
longband2 := RSIndex2[1] > longband2[1] and RSIndex2 > longband2[1] ? math.max(longband2[1], newlongband2) : newlongband2
shortband2 := RSIndex2[1] < shortband2[1] and RSIndex2 < shortband2[1] ? math.min(shortband2[1], newshortband2) : newshortband2
cross_2 = ta.cross(longband2[1], RSIndex2)
trend2 := ta.cross(RSIndex2, shortband2[1]) ? 1 : cross_2 ? -1 : nz(trend2[1], 1)
FastAtrRsi2TL = trend2 == 1 ? longband2 : shortband2
//
// Zero cross
QQE2zlong = 0
QQE2zlong := nz(QQE2zlong[1])
QQE2zshort = 0
QQE2zshort := nz(QQE2zshort[1])
QQE2zlong := RSIndex2 >= 50 ? QQE2zlong + 1 : 0
QQE2zshort := RSIndex2 < 50 ? QQE2zshort + 1 : 0
//
hcolor2 = RsiMa2 - 50 > ThreshHold2 ? color.silver : RsiMa2 - 50 < 0 - ThreshHold2 ? color.silver : na
Greenbar1 = RsiMa2 - 50 > ThreshHold2
Greenbar2 = RsiMa - 50 > upper
Redbar1 = RsiMa2 - 50 < 0 - ThreshHold2
Redbar2 = RsiMa - 50 < lower
//// 3. Waddah Attar Explosion V2 shayankm
sensitivity = input.float (defval = 150, title='Sensitivity', inline = "1", group = "3: Waddah Attar Explosion")
fastLength = input.int (defval = 20, title='FastEMA Length', inline = "2", group = "3: Waddah Attar Explosion")
slowLength = input.int (defval = 40, title='SlowEMA Length', inline = "2", group = "3: Waddah Attar Explosion")
channelLength = input.int (defval = 20, title='BB Channel Length', inline = "3", group = "3: Waddah Attar Explosion")
w_mult = input.float (defval = 2.0, title='BB Stdev Multiplier', inline = "4", group = "3: Waddah Attar Explosion")
// DEAD_ZONE = nz(ta.rma(ta.tr(true), 100)) * 3.7
calc_macd(source, fastLength, slowLength) =>
fastMA = ta.ema(source, fastLength)
slowMA = ta.ema(source, slowLength)
fastMA - slowMA
calc_BBUpper(source, length, mult) =>
basis = ta.sma(source, length)
dev = mult * ta.stdev(source, length)
basis + dev
calc_BBLower(source, length, mult) =>
basis = ta.sma(source, length)
dev = mult * ta.stdev(source, length)
basis - dev
t1 = (calc_macd(close, fastLength, slowLength) - calc_macd(close[1], fastLength, slowLength)) * sensitivity
e1 = calc_BBUpper(close, channelLength, w_mult) - calc_BBLower(close, channelLength, w_mult)
trendUp = t1 >= 0 ? t1 : 0
trendDown = t1 < 0 ? -1 * t1 : 0
// Plot: Indicators
//// 1. SSL Hybrid
var bullSSLColor = #00c3ff
var bearSSLColor = #ff0062
// color_bar = color.new(color = close > upperk ? bullSSLColor : close < lowerk ? bearSSLColor : color.gray, transp = 0)
// i_show_color_bar = input.bool(defval = true , title = "Color Bars")
// barcolor(i_show_color_bar ? color_bar : na)
plot(series = BBMC, title = 'MA Baseline', color = color_bar, linewidth = 1, style = plot.style_line)
up_channel = plot(upperk, color=color_bar, title='Baseline Upper Channel')
low_channel = plot(lowerk, color=color_bar, title='Basiline Lower Channel')
fill(up_channel, low_channel, color.new(color=color_bar, transp=90))
//// 2. QQE MOD: No Plotting because of overlay option
// plot(FastAtrRsi2TL - 50, title='QQE Line', color=color.new(color.white, 0), linewidth=2)
// plot(RsiMa2 - 50, color=hcolor2, title='Histo2', style=plot.style_columns, transp=50)
// plot(Greenbar1 and Greenbar2 == 1 ? RsiMa2 - 50 : na, title='QQE Up', style=plot.style_columns, color=color.new(#00c3ff, 0))
// plot(Redbar1 and Redbar2 == 1 ? RsiMa2 - 50 : na, title='QQE Down', style=plot.style_columns, color=color.new(#ff0062, 0))
//// 3. Waddah Attar Explosion V2 shayankm
// plot(trendUp, style=plot.style_columns, linewidth=1, color=trendUp < trendUp[1] ? color.lime : color.green, title='UpTrend', transp=45)
// plot(trendDown, style=plot.style_columns, linewidth=1, color=trendDown < trendDown[1] ? color.orange : color.red, title='DownTrend', transp=45)
// plot(e1, style=plot.style_line, linewidth=2, color=color.new(color.white, 0), title='ExplosionLine')
// plot(DEAD_ZONE, color=color.new(color.blue, 0), linewidth=1, style=plot.style_cross, title='DeadZoneLine')
////// Entry, Exit
// Long, Short Logic with Indicator
bool longSSLCond = close > BBMC
bool shortSSLCond = close < BBMC
bool longQQECond = (Greenbar1[1] == false or Greenbar2[1] == false) and (Greenbar1 and Greenbar2) == 1
bool shortQQECond = (Redbar1[1] == false or Redbar2[1] == false) and (Redbar1 and Redbar2) == 1
bool longWAECond = trendUp > 0 and trendDown == 0
bool shortWAECond = trendDown > 0 and trendUp == 0
// Basic Cond + Long, Short Entry Condition
bool longCond = (i_longEnabled and inTime) and (longSSLCond and longQQECond and longWAECond)
bool shortCond = (i_shortEnabled and inTime) and (shortSSLCond and shortQQECond and shortWAECond)
// Basic Cond + Long, Short Exit Condition
bool closeLong = (i_longEnabled) and ((Redbar1[1] == false or Redbar2[1] == false) and (Redbar1 and Redbar2) == 1)
bool closeShort = (i_shortEnabled) and ((Greenbar1[1] == false or Greenbar2[1] == false) and (Greenbar1 and Greenbar2) == 1)
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Position Control
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Long, Short Entry Condition + Not entered Position Yet
bool openLong = longCond and not (strategy.opentrades.size(strategy.opentrades - 1) > 0) and longFilterFilled
bool openShort = shortCond and not (strategy.opentrades.size(strategy.opentrades - 1) < 0) and shortFilterFilled
bool enteringTrade = openLong or openShort
float entryBarIndex = bar_index
// Long, Short Entry Fulfilled or Already Entered
bool inLong = openLong or strategy.opentrades.size(strategy.opentrades - 1) > 0 and not closeLong
bool inShort = openShort or strategy.opentrades.size(strategy.opentrades - 1) < 0 and not closeShort
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Stop Loss - Inputs, Indicaotrs
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
//// Use SL? TSL?
i_useSLTP = input.bool (defval = true, title = "Enable SL & TP?", tooltip = "", inline = "1", group = "Stop Loss")
i_tslEnabled = input.bool (defval = false , title = "Enable Trailing SL?", tooltip = "Enable Stop Loss & Take Profit? \n\Enable Trailing SL?", inline = "1", group = "Stop Loss")
// i_breakEvenAfterTP = input.bool (defval = false, title = 'Enable Break Even After TP?', tooltip = 'When Take Profit price target is hit, move the Stop Loss to the entry price (or to a more strict price defined by the Stop Loss %/ATR Multiplier).', inline = '2', group = 'Stop Loss / Take Profit')
//// Sl Options
i_slType = input.string (defval = "ATR", title = "Stop Loss Type", options = ["Percent", "ATR", "Previous LL / HH"], tooltip = "Stop Loss based on %? ATR?", inline = "3", group = "Stop Loss")
i_slATRLen = input.int (defval = 14, title = "ATR Length", minval = 1 , maxval = 200 , step = 1, inline = "4", group = "Stop Loss")
i_slATRMult = input.float (defval = 3, title = "ATR Multiplier", minval = 1 , maxval = 200 , step = 0.1, tooltip = "", inline = "4", group = "Stop Loss")
i_slPercent = input.float (defval = 3, title = "Percent", tooltip = "", inline = "5", group = "Stop Loss")
i_slLookBack = input.int (defval = 30, title = "Lowest Price Before Entry", group = "Stop Loss", inline = "6", minval = 1, step = 1, tooltip = "Lookback to find the Lowest Price. \nStopLoss is determined by the Lowest price of the look back period. Take Profit is derived from this also by multiplying the StopLoss value by the Risk:Reward multiplier.")
// Functions for Stop Loss
float openAtr = ta.valuewhen(condition = enteringTrade, source = ta.atr(i_slATRLen), occurrence = 0)
float openLowest = ta.valuewhen(condition = openLong, source = ta.lowest(low, i_slLookBack), occurrence = 0)
float openHighest = ta.valuewhen(condition = openShort, source = ta.highest(high, i_slLookBack), occurrence = 0)
f_getLongSLPrice(source) =>
switch i_slType
"Percent" => source * (1 - (i_slPercent/100))
"ATR" => source - (i_slATRMult * openAtr)
"Previous LL / HH" => openLowest
=> na
f_getShortSLPrice(source) =>
switch i_slType
"Percent" => source * (1 + (i_slPercent/100))
"ATR" => source + (i_slATRMult * openAtr)
"Previous LL / HH" => openHighest
=> na
// Calculate Stop Loss
var float longSLPrice = na
var float shortSLPrice = na
bool longTPExecuted = false
bool shortTPExecuted = false
longSLPrice := if (inLong and i_useSLTP)
if (openLong)
f_getLongSLPrice (close)
else
// 1. Trailing Stop Loss
if i_tslEnabled
stopLossPrice = f_getLongSLPrice (high)
math.max(stopLossPrice, nz(longSLPrice[1]))
// 2. Normal StopLoss
else
nz(source = longSLPrice[1], replacement = 0)
else
na
shortSLPrice := if (inShort and i_useSLTP)
if (openShort)
f_getShortSLPrice (close)
else
// 1. Trailing Stop Loss
if i_tslEnabled
stopLossPrice = f_getShortSLPrice (low)
math.min(stopLossPrice, nz(shortSLPrice[1]))
// 2. Normal StopLoss
else
nz(source = shortSLPrice[1], replacement = 999999.9)
else
na
// Plot: Stop Loss of Long, Short Entry
var longSLPriceColor = color.new(color.maroon, 0)
plot(series = longSLPrice, title = 'Long Stop Loss', color = longSLPriceColor, linewidth = 1, style = plot.style_linebr, offset = 1)
var shortSLPriceColor = color.new(color.maroon, 0)
plot(series = shortSLPrice, title = 'Short Stop Loss', color = shortSLPriceColor, linewidth = 1, style = plot.style_linebr, offset = 1)
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Take Profit - Inputs, Indicaotrs
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
i_useTPExit = input.bool (defval = true, title = "Use Take Profit?", tooltip = "", inline = "1", group = "Take Profit")
i_RRratio = input.float (defval = 1.5, title = "R:R Ratio", minval = 0.1 , maxval = 200 , step = 0.1, tooltip = "R:R Ratio > Risk Reward Ratio? It will automatically set Take Profit % based on Stop Loss", inline = "2", group = "Take Profit")
i_tpQuantityPerc = input.float (defval = 50, title = 'Take Profit Quantity %', minval = 0.0, maxval = 100, step = 1.0, tooltip = '% of position closed when tp target is met.', inline="34", group = 'Take Profit')
var float longTPPrice = na
var float shortTPPrice = na
f_getLongTPPrice() =>
close + i_RRratio * math.abs (close - f_getLongSLPrice (close))
f_getShortTPPrice() =>
close - i_RRratio * math.abs(close - f_getShortSLPrice (close))
longTPPrice := if (inLong and i_useSLTP)
if (openLong)
f_getLongTPPrice ()
else
nz(source = longTPPrice[1], replacement = f_getLongTPPrice ())
else
na
shortTPPrice := if (inShort and i_useSLTP)
if (openShort)
f_getShortTPPrice ()
else
nz(source = shortTPPrice[1], replacement = f_getShortTPPrice ())
else
na
// Plot: Take Profit of Long, Short Entry
var longTPPriceColor = color.new(color.teal, 0)
plot(series = longTPPrice, title = 'Long Take Profit', color = longTPPriceColor, linewidth = 1, style = plot.style_linebr, offset = 1)
var shortTPPriceColor = color.new(color.teal, 0)
plot(series = shortTPPrice, title = 'Short Take Profit', color = shortTPPriceColor, linewidth = 1, style = plot.style_linebr, offset = 1)
// Plot: Entry Price
var posColor = color.new(color.white, 0)
plot(series = strategy.opentrades.entry_price(strategy.opentrades - 1), title = 'Position Entry Price', color = posColor, linewidth = 1, style = plot.style_linebr)
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Quantity - Inputs
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
i_useRiskManangement = input.bool (defval = true, title = "Use Risk Manangement?", tooltip = "", inline = "1", group = "Quantity")
i_riskPerTrade = input.float (defval = 3, title = "Risk Per Trade (%)", minval = 0, maxval = 100, step = 0.1, tooltip = "Use Risk Manangement by Quantity Control?", inline = "2", group = "Quantity")
// i_leverage = input.float (defval = 2, title = "Leverage", minval = 0, maxval = 100, step = 0.1, tooltip = "Leverage", inline = "3", group = "Quantity")
float qtyPercent = na
float entryQuantity = na
f_calQtyPerc() =>
if (i_useRiskManangement)
riskPerTrade = (i_riskPerTrade) / 100 // 1번 거래시 3% 손실
stopLossPrice = openLong ? f_getLongSLPrice (close) : openShort ? f_getShortSLPrice (close) : na
riskExpected = math.abs((close-stopLossPrice)/close) // 손절가랑 6% 차이
riskPerTrade / riskExpected // 0 ~ 1
else
1
f_calQty(qtyPerc) =>
math.min (math.max (0.000001, strategy.equity / close * qtyPerc), 1000000000)
// TP Execution
longTPExecuted := strategy.opentrades.size(strategy.opentrades - 1) > 0 and (longTPExecuted[1] or strategy.opentrades.size(strategy.opentrades - 1) < strategy.opentrades.size(strategy.opentrades - 1)[1] or strategy.opentrades.size(strategy.opentrades - 1)[1] == 0 and high >= longTPPrice)
shortTPExecuted := strategy.opentrades.size(strategy.opentrades - 1) < 0 and (shortTPExecuted[1] or strategy.opentrades.size(strategy.opentrades - 1) > strategy.opentrades.size(strategy.opentrades - 1)[1] or strategy.opentrades.size(strategy.opentrades - 1)[1] == 0 and low <= shortTPPrice)
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Plot Label, Boxes, Results, Etc
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
i_showSimpleLabel = input.bool(false, "Show Simple Label for Entry?", group = "Strategy: Drawings", inline = "1", tooltip ="")
i_showLabels = input.bool(true, "Show Trade Exit Labels", group = "Strategy: Drawings", inline = "1", tooltip = "Useful labels to identify Profit/Loss and cumulative portfolio capital after each trade closes.\n\nAlso note that TradingView limits the max number of 'boxes' that can be displayed on a chart (max 500). This means when you lookback far enough on the chart you will not see the TP/SL boxes. However you can check this option to identify where trades exited.")
i_showDashboard = input.bool(true, "Show Dashboard", group = "Strategy: Drawings", inline = "2", tooltip = "Show Backtest Results. Backtest Dates, Win/Lose Rates, Etc.")
// Plot: Label for Long, Short Entry
var openLongColor = color.new(#2962FF, 0)
var openShortColor = color.new(#FF1744, 0)
var entryTextColor = color.new(color.white, 0)
if (openLong and i_showSimpleLabel)
label.new (x = bar_index, y = na, text = 'Open', yloc = yloc.belowbar, color = openLongColor, style = label.style_label_up, textcolor = entryTextColor)
entryBarIndex := bar_index
if (openShort and i_showSimpleLabel)
label.new (x = bar_index, y = na, text = 'Close', yloc = yloc.abovebar, color = openShortColor, style = label.style_label_down, textcolor = entryTextColor)
entryBarIndex := bar_index
float prevEntryPrice = strategy.closedtrades.entry_price (strategy.closedtrades - 1)
float pnl = strategy.closedtrades.profit (strategy.closedtrades - 1)
float prevExitPrice = strategy.closedtrades.exit_price (strategy.closedtrades - 1)
f_enteringTradeLabel(x, y, qty, entryPrice, slPrice, tpPrice, rrRatio, direction) =>
if i_showLabels
labelStr = ("Trade Start"
+ "\nDirection: " + direction
+ "\nRisk Per Trade: " + str.tostring (i_useRiskManangement ? i_riskPerTrade : 100, "#.##") + "%"
+ "\nExpected Risk: " + str.tostring (math.abs((close-slPrice)/close) * 100, "#.##") + "%"
+ "\nEntry Position Qty: " + str.tostring(math.abs(qty * 100), "#.##") + "%"
+ "\nEntry Price: " + str.tostring(entryPrice, "#.##"))
+ "\nStop Loss Price: " + str.tostring(slPrice, "#.##")
+ "\nTake Profit Price: " + str.tostring(tpPrice, "#.##")
+ "\nRisk - Reward Ratio: " + str.tostring(rrRatio, "#.##")
label.new(x = x, y = y, text = labelStr, color = color.new(color.blue, 60) , textcolor = color.white, style = label.style_label_up)
f_exitingTradeLabel(x, y, entryPrice, exitPrice, direction) =>
if i_showLabels
labelStr = ("Trade Result"
+ "\nDirection: " + direction
+ "\nEntry Price: " + str.tostring(entryPrice, "#.##")
+ "\nExit Price: " + str.tostring(exitPrice,"#.##")
+ "\nGain %: " + str.tostring(direction == 'Long' ? -(entryPrice-exitPrice) / entryPrice * 100 : (entryPrice-exitPrice) / entryPrice * 100 ,"#.##") + "%")
label.new(x = x, y = y, text = labelStr, color = pnl > 0 ? color.new(color.green, 60) : color.new(color.red, 60), textcolor = color.white, style = label.style_label_down)
f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) =>
_cellText = _title + " " + _value
table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor, text_size=size.auto)
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Orders
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
if (inTime)
if (openLong)
qtyPercent := f_calQtyPerc() > 1 ? 1 : f_calQtyPerc()
entryQuantity := f_calQty(qtyPercent)
strategy.entry(id = "Long", direction = strategy.long, qty = entryQuantity, comment = 'Long(' + syminfo.ticker + '): Started', alert_message = 'Long(' + syminfo.ticker + '): Started')
f_enteringTradeLabel(x = bar_index + 1, y = close-3*ta.tr, entryPrice = close, qty = qtyPercent, slPrice = longSLPrice, tpPrice = longTPPrice, rrRatio = i_RRratio, direction = "Long")
if (openShort)
qtyPercent := f_calQtyPerc() > 1 ? 1 : f_calQtyPerc()
entryQuantity := f_calQty(qtyPercent)
strategy.entry(id = "Short", direction = strategy.short, qty = entryQuantity, comment = 'Short(' + syminfo.ticker + '): Started', alert_message = 'Short(' + syminfo.ticker + '): Started')
f_enteringTradeLabel(x = bar_index + 1, y = close-3*ta.tr, entryPrice = close, qty = qtyPercent, slPrice = shortSLPrice, tpPrice = shortTPPrice, rrRatio = i_RRratio, direction = "Short")
if (closeLong)
strategy.close(id = 'Long', comment = 'Close Long', alert_message = 'Long: Closed at market price')
strategy.position_size > 0 ? f_exitingTradeLabel(x = bar_index, y = close+3*ta.tr, entryPrice = prevEntryPrice, exitPrice = prevExitPrice, direction = 'Long') : na
if (closeShort)
strategy.close(id = 'Short', comment = 'Close Short', alert_message = 'Short: Closed at market price')
strategy.position_size < 0 ? f_exitingTradeLabel(x = bar_index, y = close+3*ta.tr, entryPrice = prevEntryPrice, exitPrice = prevExitPrice, direction = 'Short') : na
if (inLong)
strategy.exit(id = 'Long TP / SL', from_entry = 'Long', qty_percent = i_tpQuantityPerc, limit = longTPPrice, stop = longSLPrice, alert_message = 'Long(' + syminfo.ticker + '): Take Profit or Stop Loss executed')
strategy.exit(id = 'Long SL', from_entry = 'Long', stop = longSLPrice, alert_message = 'Long(' + syminfo.ticker + '): Stop Loss executed')
if (inShort)
strategy.exit(id = 'Short TP / SL', from_entry = 'Short', qty_percent = i_tpQuantityPerc, limit = shortTPPrice, stop = shortSLPrice, alert_message = 'Short(' + syminfo.ticker + '): Take Profit or Stop Loss executed')
strategy.exit(id = 'Short SL', from_entry = 'Short', stop = shortSLPrice, alert_message = 'Short(' + syminfo.ticker + '): Stop Loss executed')
if strategy.position_size[1] > 0 and strategy.position_size == 0
f_exitingTradeLabel(x = bar_index, y = close+3*ta.tr, entryPrice = prevEntryPrice, exitPrice = prevExitPrice, direction = 'Long')
if strategy.position_size[1] < 0 and strategy.position_size == 0
f_exitingTradeLabel(x = bar_index, y = close+3*ta.tr, entryPrice = prevEntryPrice, exitPrice = prevExitPrice, direction = 'Short')
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Backtest Result Dashboard
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
if i_showDashboard
var bgcolor = color.new(color = color.black, transp = 100)
var greenColor = color.new(color = #02732A, transp = 0)
var redColor = color.new(color = #D92332, transp = 0)
var yellowColor = color.new(color = #F2E313, transp = 0)
// Keep track of Wins/Losses streaks
newWin = (strategy.wintrades > strategy.wintrades[1]) and (strategy.losstrades == strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1])
newLoss = (strategy.wintrades == strategy.wintrades[1]) and (strategy.losstrades > strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1])
varip int winRow = 0
varip int lossRow = 0
varip int maxWinRow = 0
varip int maxLossRow = 0
if newWin
lossRow := 0
winRow := winRow + 1
if winRow > maxWinRow
maxWinRow := winRow
if newLoss
winRow := 0
lossRow := lossRow + 1
if lossRow > maxLossRow
maxLossRow := lossRow
// Prepare stats table
var table dashTable = table.new(position.top_right, 1, 15, border_width=1)
if barstate.islastconfirmedhistory
dollarReturn = strategy.netprofit
f_fillCell(dashTable, 0, 0, "Start:", str.format("{0,date,long}", strategy.closedtrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.closedtrades.entry_time(0))
f_fillCell(dashTable, 0, 1, "End:", str.format("{0,date,long}", strategy.opentrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.opentrades.entry_time(0))
_profit = (strategy.netprofit / strategy.initial_capital) * 100
f_fillCell(dashTable, 0, 2, "Net Profit:", str.tostring(_profit, '##.##') + "%", _profit > 0 ? greenColor : redColor, color.white)
_numOfDaysInStrategy = (strategy.opentrades.entry_time(0) - strategy.closedtrades.entry_time(0)) / (1000 * 3600 * 24)
_winRate = ( strategy.wintrades / strategy.closedtrades ) * 100
f_fillCell(dashTable, 0, 4, "Percent Profitable:", str.tostring(_winRate, '##.##') + "%", _winRate < 50 ? redColor : _winRate < 75 ? greenColor : yellowColor, color.white)
f_fillCell(dashTable, 0, 5, "Profit Factor:", str.tostring(strategy.grossprofit / strategy.grossloss, '##.###'), strategy.grossprofit > strategy.grossloss ? greenColor : redColor, color.white)
f_fillCell(dashTable, 0, 6, "Total Trades:", str.tostring(strategy.closedtrades), bgcolor, color.white)
f_fillCell(dashTable, 0, 8, "Max Wins In A Row:", str.tostring(maxWinRow, '######') , bgcolor, color.white)
f_fillCell(dashTable, 0, 9, "Max Losses In A Row:", str.tostring(maxLossRow, '######') , bgcolor, color.white)
|
Ichimoku Cloud and ADX with Trailing Stop Loss (by Coinrule) | https://www.tradingview.com/script/dB4mrF4Y-Ichimoku-Cloud-and-ADX-with-Trailing-Stop-Loss-by-Coinrule/ | Coinrule | https://www.tradingview.com/u/Coinrule/ | 105 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Coinrule
//@version=5
strategy('Ichimoku Cloud with ADX with Trailing Stop Loss',
overlay=true,
initial_capital=1000,
process_orders_on_close=true,
default_qty_type=strategy.percent_of_equity,
default_qty_value=30,
commission_type=strategy.commission.percent,
commission_value=0.1)
showDate = input(defval=true, title='Show Date Range')
timePeriod = time >= timestamp(syminfo.timezone, 2018, 1, 1, 0, 0)
// Inputs
ts_bars = input.int(9, minval=1, title='Tenkan-Sen Bars')
ks_bars = input.int(26, minval=1, title='Kijun-Sen Bars')
ssb_bars = input.int(52, minval=1, title='Senkou-Span B Bars')
cs_offset = input.int(26, minval=1, title='Chikou-Span Offset')
ss_offset = input.int(26, minval=1, title='Senkou-Span Offset')
long_entry = input(true, title='Long Entry')
short_entry = input(true, title='Short Entry')
middle(len) => math.avg(ta.lowest(len), ta.highest(len))
// Ichimoku Components
tenkan = middle(ts_bars)
kijun = middle(ks_bars)
senkouA = math.avg(tenkan, kijun)
senkouB = middle(ssb_bars)
// Plot Ichimoku Kinko Hyo
plot(tenkan, color=color.new(#0496ff, 0), title='Tenkan-Sen')
plot(kijun, color=color.new(#991515, 0), title='Kijun-Sen')
plot(close, offset=-cs_offset + 1, color=color.new(#459915, 0), title='Chikou-Span')
sa = plot(senkouA, offset=ss_offset - 1, color=color.new(color.green, 0), title='Senkou-Span A')
sb = plot(senkouB, offset=ss_offset - 1, color=color.new(color.red, 0), title='Senkou-Span B')
fill(sa, sb, color=senkouA > senkouB ? color.green : color.red, title='Cloud color', transp=90)
ss_high = math.max(senkouA[ss_offset - 1], senkouB[ss_offset - 1])
ss_low = math.min(senkouA[ss_offset - 1], senkouB[ss_offset - 1])
// ADX
[pos_dm, neg_dm, avg_dm] = ta.dmi(14, 14)
// Entry/Exit Signals
tk_cross_bull = tenkan > kijun
tk_cross_bear = tenkan < kijun
cs_cross_bull = ta.mom(close, cs_offset - 1) > 0
cs_cross_bear = ta.mom(close, cs_offset - 1) < 0
price_above_kumo = close > ss_high
price_below_kumo = close < ss_low
bullish = tk_cross_bull and cs_cross_bull and price_above_kumo and avg_dm < 45 and pos_dm > neg_dm
bearish = tk_cross_bear and cs_cross_bear and price_below_kumo and avg_dm > 45 and pos_dm < neg_dm
// Configure trail stop level with input options
longTrailPerc = input.float(title='Trail Long Loss (%)', minval=0.0, step=0.1, defval=3) * 0.01
shortTrailPerc = input.float(title='Trail Short Loss (%)', minval=0.0, step=0.1, defval=3) * 0.01
// Determine trail stop loss prices
longStopPrice = 0.0
shortStopPrice = 0.0
longStopPrice := if strategy.position_size > 0
stopValue = close * (1 - longTrailPerc)
math.max(stopValue, longStopPrice[1])
else
0
shortStopPrice := if strategy.position_size < 0
stopValue = close * (1 + shortTrailPerc)
math.min(stopValue, shortStopPrice[1])
else
999999
strategy.entry('Long', strategy.long, when=bullish and long_entry and timePeriod)
strategy.exit('Long', stop = longStopPrice, limit = shortStopPrice)
//strategy.entry('Short', strategy.short, when=bearish and short_entry and timePeriod)
//strategy.exit('Short', stop = longStopPrice, limit = shortStopPrice)
|
Power Zonessssss | https://www.tradingview.com/script/SCAYsFn7-Power-Zonessssss/ | liuen | https://www.tradingview.com/u/liuen/ | 17 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © liuen
//@version=5
strategy("Power", overlay=false)
a=ta.vwap(close)
b=ta.ema(close,9)
c= close
d= ta.rsi(close, 14)
plot(a, title="VVWAP", color=color.blue)
plot(b, title="EMA", color=color.green)
plot(c, title="Close", color=color.black)
longCondition = ta.crossover(c, a) and d<50 and c>b
if (longCondition)
strategy.entry("BUY", strategy.long)
shortCondition = ta.crossunder(c, a) and d>50 and c<b
if (shortCondition)
strategy.entry("SELL", strategy.short)
|
Supertrend - Long & Short -Sachin Ughade | https://www.tradingview.com/script/zs0zv2Eh-Supertrend-Long-Short-Sachin-Ughade/ | hello_sachin | https://www.tradingview.com/u/hello_sachin/ | 270 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © MarketShree
//@version=4
strategy("Supertrend Strategy", overlay=true, default_qty_value=15)
closs_all=input(title="Close_all_Position", type=input.bool, defval=false)
cancel=input(title="Check To Cancel", type=input.bool, defval=false)
atrPeriod1 = input(7, "ATR Length-1")
factor1 = input(1.5,"Factor-1",type=input.float)
atrPeriod2 = input(10, "ATR Length-2")
factor2 = input(2, "Factor-2")
atrPeriod3 = input(20, "ATR Length-3")
factor3 = input(3, "Factor-3")
[superTrend1, direction1] = supertrend(factor1, atrPeriod1)
[superTrend2, direction2] = supertrend(factor2, atrPeriod2)
[superTrend3, direction3] = supertrend(factor3, atrPeriod3)
if change(direction1) < 0
strategy.entry("LONG", strategy.long)
if change(direction1) > 0
strategy.entry("SHORT", strategy.short)
strategy.close_all(when=closs_all,comment ="All postion are closed")
strategy.cancel_all(when=cancel)
if change(direction2) < 0
strategy.entry("LONG", strategy.long)
if change(direction2) > 0
strategy.entry("SHORT", strategy.short)
strategy.close_all(when=closs_all,comment ="All postion are closed")
strategy.cancel_all(when=cancel)
if change(direction3) < 0
strategy.entry("LONG", strategy.long)
if change(direction3) > 0
strategy.entry("SHORT", strategy.short)
strategy.close_all(when=closs_all,comment ="All postion are closed")
strategy.cancel_all(when=cancel)
colResistance = direction1 == 1 and direction1 == direction1[1] ? color.new(color.red, 0) : color.new(color.red, 100)
colSupport = direction1 == -1 and direction1 == direction1[1] ? color.new(color.green, 0) : color.new(color.green, 100)
plot(superTrend1, color = colResistance, linewidth=2)
plot(superTrend1, color = colSupport, linewidth=2)
colResistance1 = direction2 == 1 and direction2 == direction2[1] ? color.new(color.red, 0) : color.new(color.red, 100)
colSupport1 = direction2 == -1 and direction2 == direction2[1] ? color.new(color.green, 0) : color.new(color.green, 100)
plot(superTrend2, color = colResistance, linewidth=2)
plot(superTrend2, color = colSupport, linewidth=2)
colResistance2 = direction3 == 1 and direction3 == direction3[1] ? color.new(color.red, 0) : color.new(color.red, 100)
colSupport2 = direction3 == -1 and direction3 == direction3[1] ? color.new(color.green, 0) : color.new(color.green, 100)
plot(superTrend3, color = colResistance1, linewidth=2)
plot(superTrend3, color = colSupport1, linewidth=2)
|
How to use Leverage in PineScript | https://www.tradingview.com/script/QDOmrHmK/ | RingsCherrY | https://www.tradingview.com/u/RingsCherrY/ | 68 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RingsCherrY
//@version=5
leverage = input.int(2,title='Leverage',minval = 1, maxval = 100 ,step = 1)
// As the margin here must be a constant, can not be a variable
// so in adjusting the leverage at the same time you need to adjust the margin in the settings or source code at the same time
// initially set to 80% margin rate that burst
// 1./2*80 2 == leverage, 80 == margin rate that burst
strategy("How to use Leverage in PineScript", overlay=true, pyramiding=1, initial_capital=1000000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, calc_on_order_fills=false, slippage=0, commission_type=strategy.commission.percent, commission_value=0.04,margin_long = 1./2*80,margin_short = 1./2*80)
//////////////////////////////////////////
////////////////Indicators////////////////
//////////////////////////////////////////
length = input( 14 )
overSold = input( 30 )
overBought = input( 70 )
price = close
vrsi = ta.rsi(price, length)
co = ta.crossover(vrsi, overSold)
cu = ta.crossunder(vrsi, overBought)
//////////////////////////////////////////
/////////////////Leverage/////////////////
//////////////////////////////////////////
//The number of decimal places for each position opening, i.e., the accuracy
precision = input.int(1,title='Precision')
//Leverage, the default is 1, here is not recommended to open a high leverage
//Calculate the number of open contracts, here using equity for calculation, considering that everyone compound interest is used for trading equity
Lev = math.max(math.round(strategy.equity * leverage / close , precision), 0)
if (not na(vrsi))
if (co)
strategy.entry("RsiLE", strategy.long,qty = Lev, comment="RsiLE")
if (cu)
strategy.entry("RsiSE", strategy.short,qty = Lev, comment="RsiSE")
//plot(strategy.equity, title="equity", color=color.red, linewidth=2, style=plot.style_areabr) |
volume rsi strategy by pro trader123 | https://www.tradingview.com/script/3R28vGl5-volume-rsi-strategy-by-pro-trader123/ | VSlip | https://www.tradingview.com/u/VSlip/ | 49 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © VSlip
//@version=5
strategy("My script",overlay=true)
highestvol= ta.highest(volume,10)
highestvol5= ta.highest(volume,5)
rsiSourceInput = input.source(close)
up = ta.rma(math.max(ta.change(rsiSourceInput), 0), 14)
down = ta.rma(-math.min(ta.change(rsiSourceInput), 0), 14)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
rsiema= ta.sma(rsi,14)
takeprofit = (rsiema>rsi and rsi>50) or (rsiema>rsi and rsiema>50)
takeprofitshort= (rsiema<rsi and rsi<50) or (rsiema<rsi and rsiema<50)
notintrade=strategy.position_size<=0
a = 0
if(rsi<30)
a := 1
if(a[1]==1 and 30<rsi)
a:= 2
e=0
if(a==2 and rsiema>rsi)
e:=1
if(a==2 and rsiema<rsi)
e:=2
if(e[1]==1 and rsiema>rsi)
e:=1
if(e[1]==1 and rsiema<rsi)
e:=2
if(e[1]==2 and rsiema<rsi)
e:=2
if(e[1]==2 and rsiema>rsi)
e:=3
f=0
if(a==2 and rsiema<rsi)
f:=1
if(a==2 and rsiema>rsi)
f:=2
if(f[1]==1 and rsiema<rsi)
f:=1
if(f[1]==1 and rsiema>rsi)
f:=2
if(f[1]==2 and rsiema>rsi)
f:=2
if(f[1]==2 and rsiema<rsi)
f:=3
b = 0
if(rsi>70)
b := 1
if(b[1]==1 and rsi<70)
b:= 2
c=0
if(highestvol5==highestvol and rsi<30)
c:=1
if(c[1]==1 and rsi[1]<30)
c:=1
d=0
if(highestvol5==highestvol and rsi>70)
d:=1
if(d[1]==1 and rsi[1]>70)
d:=1
if(a==2 and c==1)
strategy.entry("long",strategy.long)
strategy.exit("long",loss = 30)
if(e==3)
strategy.close("long",when = e==3)
if(b==2 and d==1)
strategy.entry("short",strategy.short)
strategy.exit("short", loss = 30)
if(f==3)
strategy.close("short",when = f==3)
plot(e) |
[2022] MACD Cross Strategy (version 1) | https://www.tradingview.com/script/IkcC7lDu-2022-MACD-Cross-Strategy-version-1/ | spuckles12 | https://www.tradingview.com/u/spuckles12/ | 30 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//
// System Rules:
// Indicators: MACD indicator (default values), ATR (14), EMA (200)
// 1. Price must be trading above/below the 200 EMA
// 2. Only 1 bar can close above/below the 200 EMA over the past 5 bars
// 3. We take the FIRST MACD cross and ignore subsequent signals until TP/SL is hit
// 4. Stop Loss = 0.5 ATR above/below the recent swing high/low (7 bars lookback)
// 5. First take profit = 1:1 (25%)
// 6. Second take profit = 2:1 (100%)
// 7. Move stop loss to break-even after 1st target is hit
//
// @version=5
strategy("[2022] MACD Cross Strategy", overlay=true,
currency="USD",
calc_on_order_fills=true,
use_bar_magnifier=false,
initial_capital=10000,
default_qty_type=strategy.percent_of_equity,
default_qty_value=100, // 100% of balance invested on each trade
commission_type=strategy.commission.cash_per_contract)
//commission_value=0.005) // Interactive Brokers rate
// Import ZenLibrary
import ZenAndTheArtOfTrading/ZenLibrary/5 as zen
// Get user input
var g_system = "System Entry Settings"
i_ema_filter = input.int(title="EMA Filter Length", defval=200, group=g_system)
i_ema_filter2 = input.int(title="EMA Max Bars Above/Below", defval=1, group=g_system)
i_stop_multi = input.float(title="Stop Loss Multiplier", defval=0.5, step=0.5, group=g_system)
i_stop_lookback = input.int(title="Stop Loss Lookback", defval=7, group=g_system)
var g_risk = "System Risk Settings"
i_rr1 = input.float(title="Risk:Reward Target 1", defval=1.0, group=g_risk)
i_rr2 = input.float(title="Risk:Reward Target 2", defval=2.0, group=g_risk)
i_target1 = input.float(title="Profit % Target 1", defval=25, group=g_risk)
i_riskPerTrade = input.float(title="Forex Risk Per Trade %", defval=1.0)
var g_macd = "MACD Settings"
i_price_src = input.source(title="Price Source", defval=close, group=g_macd)
i_fast_length = input.int(title="Fast Length", defval=12, group=g_macd)
i_slow_length = input.int(title="Slow Length", defval=26, group=g_macd)
i_signal_length = input.int(title="Signal Smoothing", minval=1, maxval=50, defval=9, group=g_macd)
i_sma_source = input.string(title="Oscillator MA Type", defval="EMA", options=["SMA", "EMA"], group=g_macd)
i_sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"], group=g_macd)
//------------- DETERMINE CURRENCY CONVERSION RATE -------------//
// Check if our account currency is the same as the base or quote currency or neither (for risk $ conversion purposes)
accountSameAsCounterCurrency = strategy.account_currency == syminfo.currency
accountSameAsBaseCurrency = strategy.account_currency == syminfo.basecurrency
accountNeitherCurrency = not accountSameAsCounterCurrency and not accountSameAsBaseCurrency
// Get currency conversion rates if applicable
conversionCurrencyPair = accountSameAsCounterCurrency ? syminfo.tickerid : strategy.account_currency + syminfo.currency
conversionCurrencyRate = accountSameAsBaseCurrency or accountNeitherCurrency ? request.security(conversionCurrencyPair, "D", close, ignore_invalid_symbol=true) : 1.0
// Display the current conversion currency ticker (for debug purposes)
if barstate.islastconfirmedhistory
table t = table.new(position.top_right, 1, 2, color.black)
table.cell(t, 0, 0, "Conversion: " + conversionCurrencyPair + " (" + str.tostring(conversionCurrencyRate) + ")", text_color=color.white, text_size=size.small)
table.cell(t, 0, 1, "Account: $" + str.tostring(zen.truncate(strategy.equity)), text_color=color.white, text_size=size.small)
//------------- END CURRENCY CONVERSION RATE CODE -------------//
// Calculate MACD
[macdLine, signalLine, histLine] = ta.macd(i_price_src, i_fast_length, i_slow_length, i_signal_length)
// Get indicator values
ema = ta.ema(close, i_ema_filter)
atr = ta.atr(14)
// Check for zero-point crosses
crossUp = ta.crossover(signalLine, macdLine)
crossDown = ta.crossunder(signalLine, macdLine)
// Check general system filters
tradeFilters = not na(ema) and not na(atr)
// Check trend conditions
upTrend = close > ema
downTrend = close < ema
// Check trade conditions
longConditions = tradeFilters and macdLine[1] < 0 and signalLine[1] < 0
shortConditions = tradeFilters and macdLine[1] > 0 and signalLine[1] > 0
// Confirm long & short setups
longSignal = longConditions and upTrend and crossDown
shortSignal = shortConditions and downTrend and crossUp
// Calculate stop loss
longStop = ta.lowest(low, i_stop_lookback) - (atr * i_stop_multi)
shortStop = ta.highest(high, i_stop_lookback) + (atr * i_stop_multi)
// Save stops & targets
var float tradeStop = na
var float tradeTarget1 = na
var float tradeTarget2 = na
var float tradeSize = na
// Count bars above/below MA
int barsAboveMA = 0
int barsBelowMA = 0
for i = 1 to 5
if close[i] < ema[i]
barsBelowMA += 1
if close[i] > ema[i]
barsAboveMA += 1
// Combine signal filters
longTrade = longSignal and barsBelowMA <= i_ema_filter2 and strategy.position_size == 0
shortTrade = shortSignal and barsAboveMA <= i_ema_filter2 and strategy.position_size == 0
// Handle long trade entry (enter position, reset stops & targets)
if longTrade
if syminfo.type == "forex"
tradeStop := longStop
stopDistance = close - tradeStop
tradeTarget1 := close + (stopDistance * i_rr1)
tradeTarget2 := close + (stopDistance * i_rr2)
tradeSize := na
positionSize = zen.av_getPositionSize(strategy.equity, i_riskPerTrade, zen.toWhole(stopDistance) * 10, conversionCurrencyRate)
strategy.entry(id="Long", direction=strategy.long, qty=positionSize)
else
strategy.entry(id="Long", direction=strategy.long)
tradeStop := na
tradeTarget1 := na
tradeTarget2 := na
// Handle short trade entry (enter position, reset stops & targets)
if shortTrade
if syminfo.type == "forex"
tradeStop := shortStop
stopDistance = tradeStop - close
tradeTarget1 := close - (stopDistance * i_rr1)
tradeTarget2 := close - (stopDistance * i_rr2)
tradeSize := na
positionSize = zen.av_getPositionSize(strategy.equity, i_riskPerTrade, zen.toWhole(shortStop - close) * 10, conversionCurrencyRate)
strategy.entry(id="Short", direction=strategy.short, qty=positionSize)
else
strategy.entry(id="Short", direction=strategy.short)
tradeStop := na
tradeTarget1 := na
tradeTarget2 := na
// Handle forex trade size tracking variable
if syminfo.type == "forex" and strategy.position_size != 0 and na(tradeSize)
tradeSize := strategy.position_size
// Handle long stops & target calculation
if strategy.position_size > 0 and na(tradeStop) and syminfo.type != "forex"
tradeStop := longStop
stopDistance = strategy.position_avg_price - tradeStop
tradeTarget1 := strategy.position_avg_price + (stopDistance * i_rr1)
tradeTarget2 := strategy.position_avg_price + (stopDistance * i_rr2)
tradeSize := strategy.position_size
// Handle short stops & target calculation
if strategy.position_size < 0 and na(tradeStop) and syminfo.type != "forex"
tradeStop := shortStop
stopDistance = tradeStop - strategy.position_avg_price
tradeTarget1 := strategy.position_avg_price - (stopDistance * i_rr1)
tradeTarget2 := strategy.position_avg_price - (stopDistance * i_rr2)
tradeSize := strategy.position_size
// Handle trade exits
strategy.exit(id="Long Exit #1", from_entry="Long", limit=tradeTarget1, stop=tradeStop, qty_percent=i_target1)
strategy.exit(id="Long Exit #2", from_entry="Long", limit=tradeTarget2, stop=tradeStop, qty_percent=100)
strategy.exit(id="Short Exit #1", from_entry="Short", limit=tradeTarget1, stop=tradeStop, qty_percent=i_target1)
strategy.exit(id="Short Exit #2", from_entry="Short", limit=tradeTarget2, stop=tradeStop, qty_percent=100)
// Handle both long & short trade break-even stops (do this AFTER first position has exited above ^)
if strategy.position_size != tradeSize
tradeStop := strategy.position_avg_price
tradeTarget1 := na
// Draw conditional data
plot(ema, color=close > ema ? color.green : color.red, linewidth=2, title="EMA")
plotshape(longTrade, style=shape.triangleup, color=color.green, location=location.belowbar, title="Long Setup")
plotshape(shortTrade, style=shape.triangledown, color=color.red, location=location.abovebar, title="Short Setup")
// Draw stops & targets
plot(strategy.position_size != 0 ? tradeStop : na, color=color.red, style=plot.style_linebr, title="Stop Loss")
plot(strategy.position_size != 0 ? tradeTarget1 : na, color=color.green, style=plot.style_linebr, title="Profit Target 1")
plot(strategy.position_size != 0 ? tradeTarget2 : na, color=color.green, style=plot.style_linebr, title="Profit Target 2") |
X48 - Strategy | MA Type Cross + TPSL | Future&Spot | V.2 | https://www.tradingview.com/script/DAD06s8m-X48-Strategy-MA-Type-Cross-TPSL-Future-Spot-V-2/ | X4815162342 | https://www.tradingview.com/u/X4815162342/ | 523 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © X4815162342
// Thank You For Open Source Code, This Strategy Ref. By 1.Simple Strategy Like MA Crossover For Long/Short or Spot Trade, 2. CDC Action Zone V.2 for BarPaint
// This Strategy Mixing With MA Crossover Strategy and BarPaint By CDC Action Zone and TP/SL by Varbara
// and Thanks For Original Source Swing H/L by @millerrh
// How To Use Strategy : Setting EMA/SMA Crossover EMA/SMA, Any Value If You Want
// For Long Position : Cross Up
// For Short Position : Cross Down
// Can Use With Spot Trade : Cross Up = Buy, Cross Down = Sell
// In Setting
// Intitial Capital = Ex. 200
// Order Size = Should Be Money Management Not Use 100% of Capital Ex. 10% of Capital (200$) = Order Size 20$
// StopLoss and Take Profit = If You Run Trend TF 4H+ or 1D+ You Can Change TP% = 1,000% for nonlimit and Stop Loss 5 - 20% from your order size
// Ex. Stoploss 15% = OrderSize / 100 x %SL = 20$/100 x 15% = 3$ Loss from order size 20$ (if you not set stop loss.)
// Base Currency = (Your Currency) # Ex. USD
// Commission = (Your Trading Fee) # Ex. Future Fee Can Check At Binance Fee Rate > https://www.binance.com/en/fee/schedule > Choose Your Fee Type, Ex. USD M Future (Regular User) = 0.02 (Maker), 0.04 (Taker)
// Commission Symbol Type = % # (Ref. By Binance Fee Rate)
// Default Setting It's Realistic From Normal Life Ex. Capital 200$ / Ordersize 20$ (10%)/ Commission 0.1% (Buy+Sell) / Slippage = 2 / TP = 1000% (nonlimit) / SL = 15%/OrderSize
// Low Risk But High Return, Good Luck
// if you wanna try my bot auto trade X48-3in1-bot : Contact My Line ID : x4815x
//@version=5
strategy('X48 - Strategy | MA Multi Type Cross + TPSL + Swing + Surfing&Diving| Future&Spot | V.3.6', overlay=true, default_qty_type=strategy.cash, default_qty_value=20, initial_capital=200, currency=currency.USD, commission_value=0.1, slippage = 0)
// 📌📌 Spot Mode 📌📌
SMODE = input.bool(title="SPOT MODE", defval=false, group = '= SPOT SETTING =', tooltip = 'SPOT = Disable Short Position')
/////////// Normal Setting ////////////////
srcstrategy = input(close, title='Source Multi MA', group = '= Multi MA SETTING =', tooltip = 'Normal Line = Close \nSmooth Line = ohlc4')
///////////// EMA/SMA SETTING /////////////
pricestrategy = request.security(syminfo.tickerid, timeframe.period, srcstrategy)
fastSW = input.bool(title='Show Fast MA Line', defval=true, group = '= Multi MA SETTING =')
slowSW = input.bool(title='Show Slow MA Line', defval=true, group = '= Multi MA SETTING =')
ma1strategy = input(18, title='Fast MA Length', group = '= Multi MA SETTING =')
type1strategy = input.string('EMA', 'Fast MA Type', options=['SMA', 'EMA', 'WMA', 'HMA', 'RMA', 'VWMA'], group = '= Multi MA SETTING =', tooltip = 'SMA / EMA / WMA / HMA / RMA / VWMA')
MA2_MODE = input.bool(title="MA MIDDLE MODE", defval=false, group = '= MIDDLE 3MA SETTING =', tooltip = 'Strategy Is\nMA Fast > MA Slow = Long\nEMA Fast < MA Mid = Short')
ma2strategy = input(24, title='Middle MA Length', group = '= MIDDLE 3MA SETTING =')
type2strategy = input.string('EMA', 'Middle MA Type', options=['SMA', 'EMA', 'WMA', 'HMA', 'RMA', 'VWMA'], group = '= MIDDLE 3MA SETTING =', tooltip = 'SMA / EMA / WMA / HMA / RMA / VWMA')
ma3strategy = input(34, title='Slow MA Length', group = '= Multi MA SETTING =')
type3strategy = input.string('EMA', 'Slow MA Type', options=['SMA', 'EMA', 'WMA', 'HMA', 'RMA', 'VWMA'], group = '= Multi MA SETTING =', tooltip = 'SMA / EMA / WMA / HMA / RMA / VWMA')
price1strategy = switch type1strategy
"EMA" => ta.ema(pricestrategy, ma1strategy)
"SMA" => ta.sma(pricestrategy, ma1strategy)
"WMA" => ta.wma(pricestrategy, ma1strategy)
"HMA" => ta.hma(pricestrategy, ma1strategy)
"RMA" => ta.rma(pricestrategy, ma1strategy)
"VWMA" => ta.vwma(pricestrategy, ma1strategy)
price2strategy = switch type2strategy
"EMA" => ta.ema(pricestrategy, ma2strategy)
"SMA" => ta.sma(pricestrategy, ma2strategy)
"WMA" => ta.wma(pricestrategy, ma2strategy)
"HMA" => ta.hma(pricestrategy, ma2strategy)
"RMA" => ta.rma(pricestrategy, ma2strategy)
"VWMA" => ta.vwma(pricestrategy, ma2strategy)
price3strategy = switch type3strategy
"EMA" => ta.ema(pricestrategy, ma3strategy)
"SMA" => ta.sma(pricestrategy, ma3strategy)
"WMA" => ta.wma(pricestrategy, ma3strategy)
"HMA" => ta.hma(pricestrategy, ma3strategy)
"RMA" => ta.rma(pricestrategy, ma3strategy)
"VWMA" => ta.vwma(pricestrategy, ma3strategy)
/////////////////////////////////////////////////////////////////////////////////////////////////////
Text_Alert_Future = '{{strategy.order.alert_message}}'
copy_Fu = input( defval= Text_Alert_Future , title="Alert Message for BOT", inline = '00' ,group = '═ Bot Setting ═ \n >> If You Dont Use Bot Just Pass It' ,tooltip = 'Alert For X48-BOT > Copy and Paste To Alert Function')
passphrase = input.string(defval='1234', title ='Bot Pass',group='═ Bot Setting ═ \n >> If You Dont Use Bot Just Pass It', tooltip = 'Passphrase Must Be Same as X48-BOT')
leveragex = input.int(125,title='leverage',group='═ Bot Setting ═ \n >> If You Dont Use Bot Just Pass It',tooltip='"NOTHING" to do with Position size For Command To X48-BOT Only',minval=1)
longcommand = input.string(defval='AutoLong', title = 'Bot Long Command',group='═ Bot Setting ═ \n >> If You Dont Use Bot Just Pass It', tooltip = '1.OpenLong\n2.AutoLong\n***If AutoLong = Close(100%) First > Open Long Position Auto')
shortcommand = input.string(defval='AutoShort', title = 'Bot Short Command',group='═ Bot Setting ═ \n >> If You Dont Use Bot Just Pass It', tooltip = '1.OpenShort\n2.AutoShort\n***If AutoShort = Close(100%) First > Open Short Position Auto')
markettype = input.string(defval='bnfuture', title = 'Future/Spot Command',group='═ Bot Setting ═ \n >> If You Dont Use Bot Just Pass It', tooltip = '1. bnfuture = FUTURE MODE\n2. bnspot = SPOT MODE\n 3.bncombo = EZ 2in1 Order')
//////////////// Strategy Alert For X4815162342 BOT //////////////////////
//////// For Use Bot Can Change This Command By Your Self /////////////////////
string Alert_OpenLong = '{"ex":"'+markettype+'","side": "'+longcommand+'", "amount": "@{{strategy.order.contracts}}", "symbol": "{{ticker}}", "passphrase": "'+passphrase+'","leverage":"'+str.tostring(leveragex)+'"}'
string Alert_OpenShort = '{"ex":"'+markettype+'","side": "'+shortcommand+'", "amount": "@{{strategy.order.contracts}}", "symbol": "{{ticker}}", "passphrase": "'+passphrase+'","leverage":"'+str.tostring(leveragex)+'"}'
//string Alert_LongTP = '{"ex":"bnfuture","side": "CloseLong", "amount": "@{{strategy.order.contracts}}", "symbol": "{{ticker}}", "passphrase": "'+passphrase+'","leverage":"'+str.tostring(leveragex)+'"}'
//string Alert_ShortTP = '{"ex":"bnfuture","side": "CloseShort", "amount": "@{{strategy.order.contracts}}", "symbol": "{{ticker}}", "passphrase": "'+passphrase+'","leverage":"'+str.tostring(leveragex)+'"}'
//var message_closelong = '{"ex":"bnfuture","side": "CloseLong", "amount": "%100", "symbol": "{{ticker}}", "passphrase": "'+passphrase+'","leverage":"'+str.tostring(leveragex)+'"}'
//var message_closeshort = '{"ex":"bnfuture","side": "CloseShort", "amount": "%100", "symbol": "{{ticker}}", "passphrase": "'+passphrase+'","leverage":"'+str.tostring(leveragex)+'"}'
string Alert_StopLosslong = '{"ex":"'+markettype+'","side": "CloseLong", "amount": "%100", "symbol": "{{ticker}}", "passphrase": "'+passphrase+'","leverage":"'+str.tostring(leveragex)+'"}'
string Alert_StopLossshort = '{"ex":"'+markettype+'","side": "CloseShort", "amount": "%100", "symbol": "{{ticker}}", "passphrase": "'+passphrase+'","leverage":"'+str.tostring(leveragex)+'"}'
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
RSI_MODE = input.bool(title="RSI MODE", defval=false, group = '= RSI SETTING >> COMFIRM RSI BEFORE OPEN POSITION =', tooltip = 'If Mode On = Use RSI Strategy With Long and Short\n >> RSI Confirm Before Open Position')
//if RSI_MODE == true
RSILength = input(14, title='RSI Length', group = '= RSI SETTING >> PLOT RSI SIGNAL OB OS =')
OverBought = input(70, title='RSI OB', group = '= RSI SETTING >> PLOT RSI SIGNAL OB OS =', tooltip = 'Lil Cross Symbol')
OverSold = input(30, title='RSI OS', group = '= RSI SETTING >> PLOT RSI SIGNAL OB OS =', tooltip = 'Lil Diamond Symbol')
vrsi = ta.rsi(srcstrategy, RSILength)
RSIUP = ta.crossover(vrsi, OverBought)
RSIDOWN = ta.crossunder(vrsi, OverSold)
plotshape(RSI_MODE ? RSIUP : na, title='RSIUP', text = '⏰', color=color.new(color.yellow, 100), style=shape.circle, location=location.belowbar, size=size.tiny) //plot for buy icon
plotshape(RSI_MODE ? RSIDOWN : na, title='RSIDOWN', text = '☀️', color=color.new(color.red, 100), style=shape.circle, location=location.abovebar, size=size.tiny) //plot for buy icon
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
MACD_MODE_SIG= input.bool(title="MACD MODE = MACD Cross Signal", defval=false, group = '= MACD SETTING =', tooltip = 'If Mode On = Use MACD Strategy for Signal When Cross Up and Cross Down')
//if MACD_MODE_SIG == true
MACDfastLength = input(12, title='MACD Fast', group = '= MACD SETTING =')
MACDslowlength = input(26, title='MACD Slow', group = '= MACD SETTING =')
MACDLength = input(18, title='MACD Length', group = '= MACD SETTING =')
MACD = ta.ema(close, MACDfastLength) - ta.ema(close, MACDslowlength)
aMACD = ta.ema(MACD, MACDLength)
delta = MACD - aMACD
macdTPl = (ta.crossover(delta, 0))
macdTPs = (ta.crossunder(delta, 0))
plotshape(MACD_MODE_SIG ? macdTPl : na, title='macdTPl', text = '💎', color=color.new(color.yellow, 100), style=shape.circle, location=location.belowbar, size=size.tiny) //plot for buy icon
plotshape(MACD_MODE_SIG ? macdTPs : na, title='macdTPs', text = '💎', color=color.new(color.red, 100), style=shape.circle, location=location.abovebar, size=size.tiny) //plot for buy icon
////////////////////////////////////////////////////////////////////////////////////////////////
///////// Surfing and Diving /////////////
SURF_DIVE_MODE = input.bool(title="SURFING&DIVING MODE", defval=false, group = '= SURF&DIVING SETTING =', tooltip = 'How To Use\n3 Dot Waves CrossUp Purple Line = Bullish Trend\n3 Dot Waves CrossDown Purple Line = Bearish Trend\n\nBig Blue Dot is Surfing Zone\nCandle Price Close > Surfing Zone = Lil Bullish\nCandle Price Clsoe < Surfing Zone = Lil Bearish')
surfing_21 = ta.ema(close,21)
diving_144 = ta.ema(close,144)
diving_233 = ta.ema(close,233)
surfing_h = ta.sma(high,34)
surfing_c = ta.sma(close,34)
surfing_l = ta.sma(low,34)
surfingup = ta.crossover(close,surfing_21)
surfingdown = ta.crossunder(close,surfing_21)
showSurf = input(false, title='Show Surfing & Diving Signal', group = '= SURF&DIVING SETTING =', tooltip = 'Plot Symbol of Lil Trend By Surfing Man')
plotshowSurf = SURF_DIVE_MODE == true ? showSurf : na
plotshape(showSurf ? surfingup : na,'SurfingUp',location = location.belowbar,text = '🏄♂️')
plotshape(showSurf ? surfingdown : na,'SurfingDown',location = location.abovebar,text = '🏄')
plot(SURF_DIVE_MODE ? surfing_21 : na, 'surfing_21', color=color.new(#6EB0FF,20), linewidth = 1, style=plot.style_stepline_diamond)
plot(SURF_DIVE_MODE ? surfing_h : na, 'surfing_h', color=color.aqua, linewidth = 1, style=plot.style_circles)
plot(SURF_DIVE_MODE ? surfing_c : na, 'surfing_c', color=color.silver, linewidth = 1, style=plot.style_circles)
plot(SURF_DIVE_MODE ? surfing_l : na, 'surfing_l', color=color.blue, linewidth = 1, style=plot.style_circles)
plot(SURF_DIVE_MODE ? diving_144 : na, 'diving_144', color=color.purple, linewidth = 2, style=plot.style_line)
plot(SURF_DIVE_MODE ? diving_233 : na, 'diving_233', color=#FF00FF, linewidth = 2, style=plot.style_line)
///////////// Take Profit and Stop Loss Setting ////////////////////
tpsl(percent) =>
strategy.position_avg_price * percent / 100 / syminfo.mintick
mode = input.bool(title="Mode AUTO TP/SL", defval=true, group="= AUTO TP/SL =", tooltip = 'If Mode On = Use TP/SL\nIf Mode Off = Turn Off TP/SL Effect\nTP = 1000%+ for nonlimit TP Length \nSL = 1-100% if 100% Its Mean Liq. Position')
tp_l = tpsl(input.float(0, title='TP [LONG] %', group="= AUTO TP/SL =", tooltip = 'Disable = 0 (non limit profit)'))
tp_s = tpsl(input.float(0, title='TP [SHORT] %', group="= AUTO TP/SL =", tooltip = 'Disable = 0 (non limit profit)'))
sl = tpsl(input.float(0, title='Auto Stop Loss %', group="= AUTO TP/SL =", tooltip = 'Disable = 0 (non limit Stop Loss)'))
BOTrail_MODE = input.bool(defval = false, title = "🅾️ CALLBACK Trailing Stop Mode", group = "= AUTO TP/SL =", tooltip = "BreakOut Length For Who's Want Fast Trailing But This Low Profit But More Time For TP\nIt's Can Combo With Breakout and 15m")
lengthBO = input.int(title="1️⃣ Length CallBack", minval=1, maxval=1000, defval=5, group = "= AUTO TP/SL =")
triling_BO = input.float(title = "🅾️ BreakOut Trailing CALLBACK [%]", defval = 25, minval = 0.01, maxval = 999.99, group = "= AUTO TP/SL =", tooltip = "Binance Callback = 5%, Now You Can Customize Your Callback ><")
upBound = ta.highest(high, lengthBO)
downBound = ta.lowest(low, lengthBO)
SL_LongBO = (close < (upBound-((upBound*triling_BO)/100)))
SL_ShortBO = (close > (downBound+((downBound*triling_BO)/100)))
calcStopLossPrice(OffsetPts) =>
if strategy.position_size > 0
strategy.position_avg_price - OffsetPts * syminfo.mintick
else if strategy.position_size < 0
strategy.position_avg_price + OffsetPts * syminfo.mintick
else
na
calcStopLossL_AlertPrice(OffsetPts) =>
strategy.position_avg_price - OffsetPts * syminfo.mintick
calcStopLossS_AlertPrice(OffsetPts) =>
strategy.position_avg_price + OffsetPts * syminfo.mintick
calcTakeProfitPrice(OffsetPts) =>
if strategy.position_size > 0
strategy.position_avg_price + OffsetPts * syminfo.mintick
else if strategy.position_size < 0
strategy.position_avg_price - OffsetPts * syminfo.mintick
else
na
calcTakeProfitL_AlertPrice(OffsetPts) =>
strategy.position_avg_price + OffsetPts * syminfo.mintick
calcTakeProfitS_AlertPrice(OffsetPts) =>
strategy.position_avg_price - OffsetPts * syminfo.mintick
var stoploss = 0.
var stoploss_l = 0.
var stoploss_s = 0.
var takeprofit = 0.
var takeprofit_l = 0.
var takeprofit_s = 0.
var takeprofit_ll = 0.
var takeprofit_ss = 0.
if mode == true
if (strategy.position_size > 0)
if sl > 0
stoploss := calcStopLossPrice(sl)
stoploss_l := stoploss
else if sl <= 0
stoploss := na
if tp_l > 0
takeprofit := tp_l
takeprofit_ll := close + ((close/100)*tp_l)
//takeprofit_s := na
else if tp_l <= 0
takeprofit := na
if (strategy.position_size < 0)
if sl > 0
stoploss := calcStopLossPrice(sl)
stoploss_s := stoploss
else if sl <= 0
stoploss := na
if tp_s > 0
takeprofit := tp_s
takeprofit_ss := close - ((close/100)*tp_s)
//takeprofit_l := na
else if tp_s <= 0
takeprofit := na
else if strategy.position_size == 0
stoploss := na
takeprofit := na
//takeprofit_l := calcTakeProfitL_AlertPrice(tp_l)
//takeprofit_s := calcTakeProfitS_AlertPrice(tp_s)
//stoploss_l := calcStopLossL_AlertPrice(sl)
//stoploss_s := calcStopLossS_AlertPrice(sl)
//////////// INPUT BACKTEST RANGE ////////////////////////////////////////////////////
var string BTR1 = '════════ INPUT BACKTEST TIME RANGE ════════'
i_startTime = input.time(defval = timestamp("01 Jan 1945 00:00 +0000"), title = "Start", inline="timestart", group=BTR1, tooltip = 'Start Backtest YYYY/MM/DD')
i_endTime = input.time(defval = timestamp("01 Jan 2074 23:59 +0000"), title = "End", inline="timeend", group=BTR1, tooltip = 'End Backtest YYYY/MM/DD')
if time >= i_startTime and time <= i_endTime
if MA2_MODE == false
longCondition = ta.crossover(price1strategy, price3strategy)
if longCondition
strategy.entry('Long', strategy.long, alert_message = Alert_OpenLong, comment = "🌙")
shortCondition = ta.crossunder(price1strategy, price3strategy)
if shortCondition and SMODE == true
strategy.close('Long', qty_percent = 100, comment = '🎃')
if shortCondition and SMODE == false
strategy.entry('Short', strategy.short, alert_message = Alert_OpenShort, comment = "👻")
if MA2_MODE == true
longCondition = ta.crossover(price1strategy, price3strategy)
if longCondition
strategy.entry('Long', strategy.long, alert_message = Alert_OpenLong, comment = "🌙")
shortCondition = ta.crossunder(price1strategy, price3strategy)
StopshortCondition = ta.crossunder(price1strategy, price2strategy)
if StopshortCondition and SMODE == true
strategy.close('Long', qty_percent = 100, comment = '🎃')
if StopshortCondition and SMODE == false
strategy.close('Long', qty_percent = 100, comment = '🎃')
if shortCondition and SMODE == false
strategy.entry('Short', strategy.short, alert_message = Alert_OpenShort, comment = "👻")
////////////////// Strategy Take Profit and Stop Loss Label Here ///////////////////
//if mode == true
// if (strategy.position_size > 0)
// stoploss := calcStopLossPrice(sl)
// takeprofit := tp_l
// if (strategy.position_size < 0)
// stoploss := calcStopLossPrice(sl)
// takeprofit := tp_s
// else if strategy.position_size == 0
// stoploss := na
// takeprofit := na
if mode == true
if SMODE == false
if strategy.position_size > 0
strategy.exit("Exit",'Long', qty_percent = 100 , profit = takeprofit, stop = stoploss, comment_profit = "TP💚L", comment_loss = "SL💚L", alert_message = Alert_StopLosslong)
if strategy.position_size < 0
strategy.exit("Exit",'Short', qty_percent = 100, profit = takeprofit, stop = stoploss, comment_profit = "TP❤️️S", comment_loss = "SL❤️️S", alert_message = Alert_StopLossshort)
else if SMODE == true
if strategy.position_size > 0
strategy.exit("Exit",'Long', qty_percent = 100 , profit = takeprofit, stop = stoploss, comment_profit = "TP💚L", comment_loss = "SL💚L", alert_message = Alert_StopLosslong)
if BOTrail_MODE == true
if SMODE == false
if SL_LongBO and strategy.position_size > 0
strategy.close("Long", qty_percent = 100, comment = "❇️CALLBACK❇️", alert_message = Alert_StopLosslong)
if SL_ShortBO and strategy.position_size < 0
strategy.close("Short", qty_percent = 100, comment = "❇️CALLBACK❇️", alert_message = Alert_StopLossshort)
else if SMODE == true
if SL_LongBO and strategy.position_size > 0
strategy.close("Long", qty_percent = 100, comment = "❇️CALLBACK❇️", alert_message = Alert_StopLosslong)
//if strategy.position_size > 0
// strategy.exit("Exit",'Long', profit = takeprofit, when = stoploss, alert_message = Alert_StopLosslong)
// strategy.exit("Exit",'Long', profit = takeprofit, stop = stoploss, alert_message = Alert_StopLosslong)
//if strategy.position_size < 0
// strategy.exit("Exit",'Short', profit = takeprofit, stop = stoploss, alert_message = Alert_StopLossshort)
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
srccdc = input(title='Data Array', defval=ohlc4, group="Bar Paint Color Red/Blue/Yellow/Green", tooltip = 'Just Bar Paint Only\nNo Effect For EMA/SMA Line')
APcdc = ta.ema(srccdc, 2)
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ************** BarPaint ***********
Bullish = price1strategy > price3strategy
Bearish = price1strategy < price3strategy
Green = Bullish and APcdc > price1strategy
Red = Bearish and APcdc < price1strategy
Yellow = Bullish and APcdc < price1strategy
Blue = Bearish and APcdc > price1strategy
Buycdc = Bullish and Bearish[1]
Sellcdc = Bearish and Bullish[1]
//Plot
bcolor = Green ? color.lime : Red ? color.red : Yellow ? color.yellow : Blue ? color.blue : color.white
barcolor(color=bcolor)
//plot(series=price1strategy, style=plot.style_line, title='1st MA', color=color.new(color.yellow, 0), linewidth=2)
//plot(series=price2strategy, style=plot.style_line, title='2nd MA', color=color.new(color.blue, 0), linewidth=1)
//plot(series=price3strategy, style=plot.style_line, title='3rd MA', color=color.new(color.red, 0), linewidth=2)
FastL = plot(fastSW ? price1strategy : na, 'Fast MA', color=color.new(color.red, 0), style = plot.style_line, linewidth=2)
MidL = plot(MA2_MODE ? price2strategy : na, 'Middle MA', color=color.new(color.blue, 0), style = plot.style_line, linewidth=2)
SlowL = plot(slowSW ? price3strategy : na, 'Slow MA', color=color.new(color.yellow, 0), style = plot.style_line, linewidth=2)
fillcolor = Bullish ? color.new(color.green,90) : Bearish ? color.new(color.red,90) : color.new(color.black,90) // fillcolor = Bullish ? color.green : Bearish ? color.red : color.black
//fill(FastL, MidL, SlowL, fillcolor) // fill(price1strategy, price2strategy, price3strategy, fillcolor, transp=90)
//longCondition2 = ta.crossover(price1strategy, price3strategy)
//shortCondition2 = ta.crossunder(price1strategy, price2strategy)
//plotshape(longCondition, title='buytag', text='🌙', color=color.new(color.green, 0), style=shape.labelup, location=location.belowbar, size=size.large, textcolor=color.new(color.white, 0)) //plot for buy icon
//plotshape(shortCondition, title='selltag', text='👻', color=color.new(color.red, 0), style=shape.labeldown, location=location.abovebar, size=size.large, textcolor=color.new(color.white, 0)) //plot for sell icon
// Swing Plot
Swing_MODE = input.bool(title="SWING MODE", defval=true, group = '= SWING SETTING =', tooltip = 'If Mode On = Plot Swing High and Swing Low')
pvtLenL = input.int(6, minval=1, title='Pivot Length Left Hand Side', group = '= SWING SETTING =')
pvtLenR = input.int(6, minval=1, title='Pivot Length Right Hand Side', group = '= SWING SETTING =')
showStop = input(true, title='Show Recent Low Stop?', group = '= SWING SETTING =')
// Get High and Low Pivot Points
pvthi_ = ta.pivothigh(high, pvtLenL, pvtLenR)
pvtlo_ = ta.pivotlow(low, pvtLenL, pvtLenR)
// Force Pivot completion before plotting.
Shunt = 1 //Wait for close before printing pivot? 1 for true 0 for flase
maxLvlLen = 0 //Maximum Extension Length
pvthi = pvthi_[Shunt]
pvtlo = pvtlo_[Shunt]
// Count How many candles for current Pivot Level, If new reset.
counthi = ta.barssince(not na(pvthi))
countlo = ta.barssince(not na(pvtlo))
pvthis = fixnan(pvthi)
pvtlos = fixnan(pvtlo)
hipc = ta.change(pvthis) != 0 ? na : color.maroon
lopc = ta.change(pvtlos) != 0 ? na : color.green
// Display Pivot lines
plot(Swing_MODE ? maxLvlLen == 0 or counthi < maxLvlLen ? pvthis : na : na, color=hipc, linewidth=1, offset=-pvtLenR - Shunt, title='Top Levels')
plot(Swing_MODE ? maxLvlLen == 0 or countlo < maxLvlLen ? pvtlos : na : na, color=lopc, linewidth=1, offset=-pvtLenR - Shunt, title='Bottom Levels')
plot(Swing_MODE ? maxLvlLen == 0 or counthi < maxLvlLen ? pvthis : na : na, color=hipc, linewidth=1, offset=0, title='Top Levels 2')
plot(Swing_MODE ? maxLvlLen == 0 or countlo < maxLvlLen ? pvtlos : na : na, color=lopc, linewidth=1, offset=0, title='Bottom Levels 2')
// Stop Levels
stopLevel = ta.valuewhen(pvtlo_, low[pvtLenR], 0)
plotStopLevel = showStop == true ? stopLevel : na
plot(Swing_MODE ? plotStopLevel : na, style=plot.style_linebr, color=color.new(color.orange, 50), show_last=1, linewidth=2, trackprice=true)
//******************************************
TRAILING_MODE = input.bool(title="TRAILING MODE", defval=false, group = '= TRAILING TP/SL SETTING =', tooltip = 'When Candle Price Close > or < Trailing Line\nShould TP or SL by Your Position')
c480=request.security(syminfo.tickerid, "M", close, barmerge.gaps_off, barmerge.lookahead_on)
c4801=request.security(syminfo.tickerid, "M", close[1], barmerge.gaps_off, barmerge.lookahead_on)
c4802=request.security(syminfo.tickerid, "M", close[2], barmerge.gaps_off, barmerge.lookahead_on)
c4803=request.security(syminfo.tickerid, "M", close[3], barmerge.gaps_off, barmerge.lookahead_on)
c4804=request.security(syminfo.tickerid, "M", close[4], barmerge.gaps_off, barmerge.lookahead_on)
c4805=request.security(syminfo.tickerid, "M", close[5], barmerge.gaps_off, barmerge.lookahead_on)
h480=request.security(syminfo.tickerid, "480", high, barmerge.gaps_off, barmerge.lookahead_on)
mc=(c480+c4801+c4802+c4803+c4804)/5
plot(TRAILING_MODE ? mc : na, 'TrailingTP/SL', color=color.new(color.lime,0), style=plot.style_stepline, linewidth=2)
//********* Background Paint ***********************
BG_MODE = input.bool(title="BACKGROUND PAINT MODE", defval=true, group = '= BACKGROUND PAINT SETTING =', tooltip = 'Just Fill Background Color and Paint Line Between Space')
prefillFast = plot(BG_MODE ? price1strategy : na, 'Fast MA', color=color.new(color.red, 100), style = plot.style_line, linewidth=2)
prefillMid = plot(MA2_MODE ? BG_MODE ? price2strategy : na : na, 'Middle MA', color=color.new(color.blue, 100), style = plot.style_line, linewidth=2)
prefillSlow = plot(BG_MODE ? price3strategy : na, 'Fast MA', color=color.new(color.yellow, 100), style = plot.style_line, linewidth=2)
fcolor = price1strategy > price3strategy ? color.new(color.lime,70) : color.new(color.blue,70)
fcolor2 = price1strategy > price2strategy ? color.new(color.lime,70) : color.new(color.red,70)
fill(prefillFast,prefillSlow, color=fcolor, title='BACKGROUND PAINT')
fill(prefillFast,prefillMid, color=fcolor2, title='BACKGROUND PAINT')
// **********************************************
//เรียกใช้ library
import X4815162342/X48_LibaryStrategyStatus/2 as fuLi
//แสดงผล Backtest
show_Net = input.bool(true,'Monitor Profit&Loss', inline = 'Lnet', group = '= PNL MONITOR SETTING =')
position_ = input.string('bottom_center','Position', options = ['top_right','middle_right','bottom_right','top_center','middle_center','bottom_center','middle_left','bottom_left'] , inline = 'Lnet')
size_i = input.string('auto','size', options = ['auto','tiny','small','normal'] , inline = 'Lnet')
color_Net = input.color(color.blue,"" , inline = 'Lnet')
fuLi.NetProfit_Show(show_Net , position_ , size_i, color_Net ) |
HAERI 𝐍𝐄𝐓𝐖𝐎𝐑𝐊 | https://www.tradingview.com/script/qVSTEZum-HAERI-%F0%9D%90%8D%F0%9D%90%84%F0%9D%90%93%F0%9D%90%96%F0%9D%90%8E%F0%9D%90%91%F0%9D%90%8A/ | ahhanegin | https://www.tradingview.com/u/ahhanegin/ | 56 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ahhanegin
//@version=4
//study("Haeri")
strategy("HAERI 𝐍𝐄𝐓𝐖𝐎𝐑𝐊", overlay=true, initial_capital=1000, default_qty_type=strategy.percent_of_equity, default_qty_value=15)
price = plot(close, title="Close Line", color=color.blue, display=display.none)
////////////////////////////////////////////////////////////////////////////////
//TREND INDICATORS▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼
//Trend EMA
tttradetrend = "Only place BUY or SELL orders with the direction of the Trend EMA."
tradetrendoption = input(false, title="Only Tade with Trend", tooltip=tttradetrend)
len111 = input(defval=200, minval=0, maxval=2000, title="Trend EMA Length")
src111 = close
out111 = ema(src111, len111)
ma111 = plot(out111, title="EMA 200", linewidth=2, color=color.blue, offset=0)
mabuy = out111 > out111[1]
masell = out111 < out111[1]
//5 EMAs////////////////////////////////////////////////////////////////////////
len1 = 9
src1 = close
out1 = ema(src1, len1)
ema1color = (out1 > out1[1] ? #00bcd4 : #e91e63)
ema1 = plot(out1, title="EMA 9", linewidth=3, color=color.new(ema1color, 50), offset=0, display=display.none)
fill(price, ema1, title="EMA 9 Fill", color=color.new(ema1color, 90), editable=true)
len2 = 21
src2 = close
out2 = ema(src2, len2)
ema2color = (out2 > out2[1] ? #00bcd4 : #e91e63)
ema2 = plot(out2, title="EMA 21", linewidth=3, color=color.new(ema2color, 50), offset=0, display=display.none)
fill(price, ema2, title="EMA 21 Fill", color=color.new(ema2color, 90), editable=true)
len3 = 55
src3 = close
out3 = ema(src3, len3)
ema3color = (out3 > out3[1] ? #00bcd4 : #e91e63)
ema3 = plot(out3, title="EMA 55", linewidth=3, color=color.new(ema3color, 50), offset=0, display=display.none)
fill(price, ema3, title="EMA 55 Fill", color=color.new(ema3color, 90), editable=true)
len4 = 100
src4 = close
out4 = ema(src4, len4)
ema4color = (out4 > out4[1] ? #00bcd4 : #e91e63)
ema4 = plot(out4, title="EMA 100", linewidth=3, color=color.new(ema4color, 50), offset=0, display=display.none)
fill(price, ema4, title="EMA 100 Fill", color=color.new(ema4color, 90), editable=true)
len5 = 200
src5 = close
out5 = ema(src5, len5)
ema5color = (out5 > out5[1] ? #00bcd4 : #e91e63)
ema5 = plot(out5, title="EMA 200", linewidth=3, color=color.new(ema5color, 50), offset=0, display=display.none)
fill(price, ema5, title="EMA 200 Fill", color=color.new(ema5color, 90), editable=true)
//Supertrend////////////////////////////////////////////////////////////////////
atrPeriod = 10
factor = 3
[supertrend, direction] = supertrend(factor, atrPeriod)
bodyMiddle = plot((open + close) / 2, display=display.none, title="Body Middle Line")
uptrend = direction < 0 and direction[1] > 0[1] ? supertrend : na
downtrend = direction > 0 and direction[1] < 0[1] ? supertrend : na
//fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps=false)
//fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps=false)
//bullishsupertrend = supertrend < close and supertrend[1] > close
//plotshape(uptrend, style=shape.labelup, color=color.green, location=location.belowbar, size=size.large)
//HMA///////////////////////////////////////////////////////////////////////////
len6 = 100
src6 = close
hma = wma(2*wma(src6, len6/2)-wma(src6, len6), floor(sqrt(len6)))
hmacolor = close > hma ? #00bcd4 : #e91e63
plot(hma, title="HMA Line", color=color.new(hmacolor, 25), linewidth=5)
//Parabolic SAR/////////////////////////////////////////////////////////////////
start = 0.02
increment = 0.01
maximum = 0.2
psar = sar(start, increment, maximum)
//plot(psar, "ParabolicSAR", style=plot.style_circles, color=#ffffff)
//END▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
////////////////////////////////////////////////////////////////////////////////
//MOMENTUM INCIDATORS▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼
//RSI Divergence////////////////////////////////////////////////////////////////
len11 = 14
src11 = close
lbR11 = 2
lbL11 = 6
rangeUpper11 = 60
rangeLower11 = 5
plotBull11 = true
plotHiddenBull11 = false
plotBear11 = true
plotHiddenBear11 = false
bearColor11 = color.red
bullColor11 = color.green
hiddenBullColor11 = color.new(color.green, 80)
hiddenBearColor11 = color.new(color.red, 80)
textColor11 = color.white
noneColor11 = color.new(color.white, 100)
osc11 = rsi(src11, len11)
//plot(osc11, title="RSI", linewidth=2, color=#2962FF)
//hline(50, title="Middle Line", color=#787B86, linestyle=hline.style_dotted)
//obLevel11 = hline(70, title="Overbought", color=#787B86, linestyle=hline.style_dotted)
//osLevel11 = hline(30, title="Oversold", color=#787B86, linestyle=hline.style_dotted)
//fill(obLevel11, osLevel11, title="Background", color=color.rgb(33, 150, 243, 90))
plFound11 = na(pivotlow(osc11, lbL11, lbR11)) ? false : true
phFound11 = na(pivothigh(osc11, lbL11, lbR11)) ? false : true
_inRange11(cond) =>
bars11 = barssince(cond == true)
rangeLower11 <= bars11 and bars11 <= rangeUpper11
//Regular Bullish Divergence
//Osc: Higher Low
oscHL11 = osc11[lbR11] > valuewhen(plFound11, osc11[lbR11], 1) and _inRange11(plFound11[1])
//Price: Lower Low
priceLL11 = low[lbR11] < valuewhen(plFound11, low[lbR11], 1)
bullCond11 = plotBull11 and priceLL11 and oscHL11 and plFound11
//plot(plFound11 ? osc11[lbR11] : na, offset=-lbR11, title="Regular Bullish", linewidth=2, color=(bullCond11 ? bullColor11 : noneColor11))
//plotshape(bullCond11 ? osc11[lbR11] : na, offset=-lbR11, title="Regular Bullish Label", text=" Bull ", style=shape.labelup, location=location.absolute, color=bullColor11, textcolor=textColor11)
//Hidden Bullish Divergence
//Osc: Lower Low
oscLL11 = osc11[lbR11] < valuewhen(plFound11, osc11[lbR11], 1) and _inRange11(plFound11[1])
//Price: Higher Low
priceHL11 = low[lbR11] > valuewhen(plFound11, low[lbR11], 1)
hiddenBullCond11 = plotHiddenBull11 and priceHL11 and oscLL11 and plFound11
//plot(plFound11 ? osc11[lbR11] : na, offset=-lbR11, title="Hidden Bullish", linewidth=2, color=(hiddenBullCond11 ? hiddenBullColor11 : noneColor11))
//plotshape(hiddenBullCond11 ? osc11[lbR11] : na, offset=-lbR11, title="Hidden Bullish Label", text=" H Bull ", style=shape.labelup, location=location.absolute, color=bullColor11, textcolor=textColor11)
//Regular Bearish Divergence
//Osc: Lower High
oscLH11 = osc11[lbR11] < valuewhen(phFound11, osc11[lbR11], 1) and _inRange11(phFound11[1])
//Price: Higher High
priceHH11 = high[lbR11] > valuewhen(phFound11, high[lbR11], 1)
bearCond11 = plotBear11 and priceHH11 and oscLH11 and phFound11
//plot(phFound11 ? osc11[lbR11] : na, offset=-lbR11, title="Regular Bearish", linewidth=2, color=(bearCond11 ? bearColor11 : noneColor11))
//plotshape(bearCond11 ? osc11[lbR11] : na, offset=-lbR11, title="Regular Bearish Label", text=" Bear ", style=shape.labeldown, location=location.absolute, color=bearColor11, textcolor=textColor11)
//Hidden Bearish Divergence
//Osc: Higher High
oscHH11 = osc11[lbR11] > valuewhen(phFound11, osc11[lbR11], 1) and _inRange11(phFound11[1])
// Price: Lower High
priceLH11 = high[lbR11] < valuewhen(phFound11, high[lbR11], 1)
hiddenBearCond11 = plotHiddenBear11 and priceLH11 and oscHH11 and phFound11
//plot(phFound11 ? osc11[lbR11] : na, offset=-lbR11, title="Hidden Bearish", linewidth=2, color=(hiddenBearCond11 ? hiddenBearColor11 : noneColor11))
//plotshape(hiddenBearCond11 ? osc11[lbR11] : na, offset=-lbR11, title="Hidden Bearish Label", text=" H Bear ", style=shape.labeldown, location=location.absolute, color=bearColor11, textcolor=textColor11)
//MACD Divergence///////////////////////////////////////////////////////////////
fast_length12 = 12
slow_length12 = 26
src12 = close
signal_length12 = 9
sma_source12 = "EMA"
sma_signal12 = "EMA"
//Plot colors
col_macd12 = #2962FF
col_signal12 = #FF6D00
col_grow_above12 = #26A69A
col_fall_above12 = #B2DFDB
col_grow_below12 = #FFCDD2
col_fall_below12 = #FF5252
//Calculating
fast_ma12 = sma_source12 == "SMA" ? sma(src12, fast_length12) : ema(src12, fast_length12)
slow_ma12 = sma_source12 == "SMA" ? sma(src12, slow_length12) : ema(src12, slow_length12)
macd = fast_ma12 - slow_ma12
signal = sma_signal12 == "SMA" ? sma(macd, signal_length12) : ema(macd, signal_length12)
hist = macd - signal
//plot(hist, title="Histogram", style=plot.style_columns, color=(hist>=0 ? (hist[1] < hist ? col_grow_above12 : col_fall_above12) : (hist[1] < hist ? col_grow_below12 : col_fall_below12)))
//plot(macd, title="MACD", color=col_macd12)
//plot(signal, title="Signal", color=col_signal12)
donttouchzero12 = true
lbR12 = 2
lbL12 = 6
rangeUpper12 = 60
rangeLower12 = 5
plotBull12 = true
plotHiddenBull12 = false
plotBear12 = true
plotHiddenBear12 = false
bearColor12 = color.red
bullColor12 = color.green
hiddenBullColor12 = color.new(color.green, 80)
hiddenBearColor12 = color.new(color.red, 80)
textColor12 = color.white
noneColor12 = color.new(color.white, 100)
osc12 = macd
plFound12 = na(pivotlow(osc12, lbL12, lbR12)) ? false : true
phFound12 = na(pivothigh(osc12, lbL12, lbR12)) ? false : true
_inRange12(cond) =>
bars12 = barssince(cond == true)
rangeLower12 <= bars12 and bars12 <= rangeUpper12
//Regular Bullish Divergence
//Osc: Higher Low
oscHL12 = osc12[lbR12] > valuewhen(plFound12, osc12[lbR12], 1) and _inRange12(plFound12[1]) and osc12[lbR12] < 0
// Price: Lower Low
priceLL12 = low[lbR12] < valuewhen(plFound12, low[lbR12], 1)
priceHHZero12 = highest(osc12, lbL12+lbR12+5)
//plot(priceHHZero,title="priceHHZero",color=color.green)
blowzero12 = donttouchzero12 ? priceHHZero12 < 0 : true
bullCond12 = plotBull12 and priceLL12 and oscHL12 and plFound12 and blowzero12
//plot(plFound12 ? osc12[lbR12] : na, offset=-lbR12, title="Regular Bullish", linewidth=2, color=(bullCond12 ? bullColor12 : noneColor12))
//plotshape(bullCond12 ? osc12[lbR12] : na, offset=-lbR12, title="Regular Bullish Label", text=" Bull ", style=shape.labelup, location=location.absolute, color=bullColor12, textcolor=textColor12)
//Hidden Bullish Divergence
//Osc: Lower Low
oscLL12 = osc12[lbR12] < valuewhen(plFound12, osc12[lbR12], 1) and _inRange12(plFound12[1])
//Price: Higher Low
priceHL12 = low[lbR12] > valuewhen(plFound12, low[lbR12], 1)
hiddenBullCond12 = plotHiddenBull12 and priceHL12 and oscLL12 and plFound12
//plot(plFound12 ? osc12[lbR12] : na, offset=-lbR12, title="Hidden Bullish", linewidth=2, color=(hiddenBullCond12 ? hiddenBullColor12 : noneColor12))
//plotshape(hiddenBullCond12 ? osc12[lbR12] : na, offset=-lbR12, title="Hidden Bullish Label", text=" H Bull ", style=shape.labelup, location=location.absolute, color=bullColor12, textcolor=textColor12)
//Regular Bearish Divergence
//Osc: Lower High
oscLH12 = osc12[lbR12] < valuewhen(phFound12, osc12[lbR12], 1) and _inRange12(phFound12[1]) and osc12[lbR12] > 0
priceLLZero12 = lowest(osc12, lbL12+lbR12+5)
//plot(priceLLZero,title="priceLLZero", color=color.red)
bearzero12 = donttouchzero12 ? priceLLZero12 > 0 : true
//Price: Higher High
priceHH12 = high[lbR12] > valuewhen(phFound12, high[lbR12], 1)
bearCond12 = plotBear12 and priceHH12 and oscLH12 and phFound12 and bearzero12
//plot(phFound12 ? osc12[lbR12] : na, offset=-lbR12, title="Regular Bearish", linewidth=2, color=(bearCond12 ? bearColor12 : noneColor12))
//plotshape(bearCond12 ? osc12[lbR12] : na, offset=-lbR12, title="Regular Bearish Label", text=" Bear ", style=shape.labeldown, location=location.absolute, color=bearColor12, textcolor=textColor12)
//Hidden Bearish Divergence
//Osc: Higher High
oscHH12 = osc12[lbR12] > valuewhen(phFound12, osc12[lbR12], 1) and _inRange12(phFound12[1])
//Price: Lower High
priceLH12 = high[lbR12] < valuewhen(phFound12, high[lbR12], 1)
hiddenBearCond12 = plotHiddenBear12 and priceLH12 and oscHH12 and phFound12
//plot(phFound12 ? osc12[lbR12] : na, offset=-lbR12, title="Hidden Bearish", linewidth=2, color=(hiddenBearCond12 ? hiddenBearColor12 : noneColor12))
//plotshape(hiddenBearCond12 ? osc12[lbR12] : na, offset=-lbR12, title="Hidden Bearish Label", text=" H Bear ", style=shape.labeldown, location=location.absolute, color=bearColor12, textcolor=textColor12)
//Wave Trend Divergence/////////////////////////////////////////////////////////
n1 = 9
n2 = 12
ap = hlc3
esa = ema(ap, n1)
d1 = ema(abs(ap - esa), n1)
ci = (ap - esa) / (0.015 * d1)
tci = ema(ci, n2)
hline = 0
wt1 = tci
wt2 = sma(wt1, 4)
//plot(hline, color=color.gray)
//plot(wt1, color=color.white)
//plot(wt2, color=color.blue)
//Divergence
lbR13 = 2
lbL13 = 6
rangeUpper13 = 60
rangeLower13 = 5
plotBull13 = true
plotHiddenBull13 = false
plotBear13 = true
plotHiddenBear13 = false
bearColor13 = color.red
bullColor13 = color.green
hiddenBullColor13 = color.green
hiddenBearColor13 = color.red
textColor13 = color.white
noneColor13 = color.new(color.white, 100)
k13 = wt1
d13 = wt2
osc13 = k13
plFound13 = na(pivotlow(osc13, lbL13, lbR13)) ? false : true
phFound13 = na(pivothigh(osc13, lbL13, lbR13)) ? false : true
_inRange13(cond) =>
bars13 = barssince(cond == true)
rangeLower13 <= bars13 and bars13 <= rangeUpper13
//Regular Bullish
//Osc: Higher Low
oscHL13 = osc13[lbR13] > valuewhen(plFound13, osc13[lbR13], 1) and _inRange13(plFound13[1])
//Price: Lower Low
priceLL13 = low[lbR13] < valuewhen(plFound13, low[lbR13], 1)
bullCond13 = plotBull13 and priceLL13 and oscHL13 and plFound13
//plot(plFound13 ? osc13[lbR13] : na, offset=-lbR13, title="Regular Bullish", linewidth=2, color=(bullCond13 ? bullColor13 : noneColor13))
//plotshape(bullCond13 ? osc13[lbR13] : na, offset=-lbR13, title="Regular Bullish Label", text=" Bull ", style=shape.labelup, location=location.absolute, color=bullColor13, textcolor=textColor13)
//Hidden Bullish
//Osc: Lower Low
oscLL13 = osc13[lbR13] < valuewhen(plFound13, osc13[lbR13], 1) and _inRange13(plFound13[1])
//Price: Higher Low
priceHL13 = low[lbR13] > valuewhen(plFound13, low[lbR13], 1)
hiddenBullCond13 = plotHiddenBull13 and priceHL13 and oscLL13 and plFound13
//plot(plFound13 ? osc13[lbR13] : na, offset=-lbR13, title="Hidden Bullish", linewidth=2, color=(hiddenBullCond13 ? hiddenBullColor13 : noneColor13))
//plotshape(hiddenBullCond13 ? osc13[lbR13] : na, offset=-lbR13, title="Hidden Bullish Label", text=" H Bull ", style=shape.labelup, location=location.absolute, color=bullColor13, textcolor=textColor13)
//Regular Bearish
//Osc: Lower High
oscLH13 = osc13[lbR13] < valuewhen(phFound13, osc13[lbR13], 1) and _inRange13(phFound13[1])
//Price: Higher High
priceHH13 = high[lbR13] > valuewhen(phFound13, high[lbR13], 1)
bearCond13 = plotBear13 and priceHH13 and oscLH13 and phFound13
//plot(phFound13 ? osc13[lbR13] : na, offset=-lbR13, title="Regular Bearish", linewidth=2, color=(bearCond13 ? bearColor13 : noneColor13))
//plotshape(bearCond13 ? osc13[lbR13] : na, offset=-lbR13, title="Regular Bearish Label", text=" Bear ", style=shape.labeldown, location=location.absolute, color=bearColor13, textcolor=textColor13)
//Hidden Bearish
//Osc: Higher High
oscHH13 = osc13[lbR13] > valuewhen(phFound13, osc13[lbR13], 1) and _inRange13(phFound13[1])
//Price: Lower High
priceLH13 = high[lbR13] < valuewhen(phFound13, high[lbR13], 1)
hiddenBearCond13 = plotHiddenBear13 and priceLH13 and oscHH13 and phFound13
//plot(phFound13 ? osc13[lbR13] : na, offset=-lbR13, title="Hidden Bearish", linewidth=2, color=(hiddenBearCond13 ? hiddenBearColor13 : noneColor13))
//plotshape(hiddenBearCond13 ? osc13[lbR13] : na, offset=-lbR13, title="Hidden Bearish Label", text=" H Bear ", style=shape.labeldown, location=location.absolute, color=bearColor13, textcolor=textColor13)
//Stochastic Divergence/////////////////////////////////////////////////////////
periodK14 = 14
smoothK14 = 3
periodD14 = 3
k14 = sma(stoch(close, high, low, periodK14), smoothK14)
d14 = sma(k14, periodD14)
//plot(k14, title="%K", color=#2962FF)
//plot(d14, title="%D", color=#FF6D00)
//h0 = hline(80, "Upper Band", color=#787B86)
//h1 = hline(20, "Lower Band", color=#787B86)
//fill(h0, h1, color=color.rgb(33, 150, 243, 90), title="Background")
//Divergence
lbR14 = 2
lbL14 = 6
rangeUpper14 = 60
rangeLower14 = 5
plotBull14 = true
plotHiddenBull14 = false
plotBear14 = true
plotHiddenBear14 = false
bearColor14 = color.red
bullColor14 = color.green
hiddenBullColor14 = color.green
hiddenBearColor14 = color.red
textColor14 = color.white
noneColor14 = color.new(color.white, 100)
osc14 = k14
plFound14 = na(pivotlow(osc14, lbL14, lbR14)) ? false : true
phFound14 = na(pivothigh(osc14, lbL14, lbR14)) ? false : true
_inRange14(cond) =>
bars14 = barssince(cond == true)
rangeLower14 <= bars14 and bars14 <= rangeUpper14
//Regular Bullish
//Osc: Higher Low
oscHL14 = osc14[lbR14] > valuewhen(plFound14, osc14[lbR14], 1) and _inRange14(plFound14[1])
//Price: Lower Low
priceLL14 = low[lbR14] < valuewhen(plFound14, low[lbR14], 1)
bullCond14 = plotBull14 and priceLL14 and oscHL14 and plFound14
//plot(plFound14 ? osc14[lbR14] : na, offset=-lbR14, title="Regular Bullish", linewidth=2, color=(bullCond14 ? bullColor14 : noneColor14))
//plotshape(bullCond14 ? osc14[lbR14] : na, offset=-lbR14, title="Regular Bullish Label", text=" Bull ", style=shape.labelup, location=location.absolute, color=bullColor14, textcolor=textColor14)
//Hidden Bullish
//Osc: Lower Low
oscLL14 = osc14[lbR14] < valuewhen(plFound14, osc14[lbR14], 1) and _inRange14(plFound14[1])
//Price: Higher Low
priceHL14 = low[lbR14] > valuewhen(plFound14, low[lbR14], 1)
hiddenBullCond14 = plotHiddenBull14 and priceHL14 and oscLL14 and plFound14
//plot(plFound14 ? osc14[lbR14] : na, offset=-lbR14, title="Hidden Bullish", linewidth=2, color=(hiddenBullCond14 ? hiddenBullColor14 : noneColor14))
//plotshape(hiddenBullCond14 ? osc14[lbR14] : na, offset=-lbR14, title="Hidden Bullish Label", text=" H Bull ", style=shape.labelup, location=location.absolute, color=bullColor14, textcolor=textColor14)
//Regular Bearish
//Osc: Lower High
oscLH14 = osc14[lbR14] < valuewhen(phFound14, osc14[lbR14], 1) and _inRange14(phFound14[1])
//Price: Higher High
priceHH14 = high[lbR14] > valuewhen(phFound14, high[lbR14], 1)
bearCond14 = plotBear14 and priceHH14 and oscLH14 and phFound14
//plot(phFound14 ? osc14[lbR14] : na, offset=-lbR14, title="Regular Bearish", linewidth=2, color=(bearCond14 ? bearColor14 : noneColor14))
//plotshape(bearCond14 ? osc14[lbR14] : na, offset=-lbR14, title="Regular Bearish Label", text=" Bear ", style=shape.labeldown, location=location.absolute, color=bearColor14, textcolor=textColor14)
//Hidden Bearish
//Osc: Higher High
oscHH14 = osc14[lbR14] > valuewhen(phFound14, osc14[lbR14], 1) and _inRange14(phFound14[1])
//Price: Lower High
priceLH14 = high[lbR14] < valuewhen(phFound14, high[lbR14], 1)
hiddenBearCond14 = plotHiddenBear14 and priceLH14 and oscHH14 and phFound14
//plot(phFound14 ? osc14[lbR14] : na, offset=-lbR14, title="Hidden Bearish", linewidth=2, color=(hiddenBearCond14 ? hiddenBearColor14 : noneColor14))
//plotshape(hiddenBearCond14 ? osc14[lbR14] : na, offset=-lbR14, title="Hidden Bearish Label", text=" H Bear ", style=shape.labeldown, location=location.absolute, color=bearColor14, textcolor=textColor14)
//END▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
////////////////////////////////////////////////////////////////////////////////
//VOLATILITY INDICATORS▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼
//Bollinger Bands///////////////////////////////////////////////////////////////
length1 = 20
src7 = close
mult1 = 2.0
basis = sma(src7, length1)
dev = mult1 * stdev(src7, length1)
upper = basis + dev
lower = basis - dev
offset = 0
//plot(basis, "Basis", color=#FF6D00, offset = offset)
//p1 = plot(upper, "Upper", color=#2962FF, offset = 0)
//p2 = plot(lower, "Lower", color=#2962FF, offset = 0)
//fill(p1, p2, title = "Background", color=color.rgb(33, 150, 243, 95))
//Average True Range /////////////////////////////////////////////////
length2 = 1
mult2 = 1.85
showLabels = true
useClose = false
highlightState = false
atr = mult2 * atr(length2)
longStop = (useClose ? highest(close, length2) : highest(length2)) - atr
longStopPrev = nz(longStop[1], longStop)
longStop := close[1] > longStopPrev ? max(longStop, longStopPrev) : longStop
shortStop = (useClose ? lowest(close, length2) : lowest(length2)) + atr
shortStopPrev = nz(shortStop[1], shortStop)
shortStop := close[1] < shortStopPrev ? min(shortStop, shortStopPrev) : shortStop
var int dir = 1
dir := close > shortStopPrev ? 1 : close < longStopPrev ? -1 : dir
var color longColor = color.green
var color shortColor = color.red
buySignal = dir == 1 and dir[1] == -1
//plotshape(buySignal and showLabels ? longStop : na, title="Gold Buy", text="Buy", location=location.belowbar, style=shape.labelup, size=size.tiny, color=longColor, textcolor=color.new(color.white, 0))
sellSignal = dir == -1 and dir[1] == 1
//plotshape(sellSignal and showLabels ? shortStop : na, title="Gold Sell", text="Sell", location=location.abovebar, style=shape.labeldown, size=size.tiny, color=shortColor, textcolor=color.new(color.white, 0))
//Relative Volatility Index Divergence//////////////////////////////////////////
length15 = 12
src15 = close
len15 = 14
stddev15 = stdev(src15, length15)
upper15 = ema(change(src15) <= 0 ? 0 : stddev15, len15)
lower15 = ema(change(src15) > 0 ? 0 : stddev15, len15)
rvi = upper15 / (upper15 + lower15) * 100
//h0 = hline(80, "Upper Band", color=#787B86)
//h1 = hline(20, "Lower Band", color=#787B86)
//fill(h0, h1, color=color.rgb(126, 87, 194, 90), title="Background")
//plot(rvi15, title="RVI", color=#7E57C2, offset = offset)
//Divergence
lbR15 = 2
lbL15 = 6
rangeUpper15 = 60
rangeLower15 = 5
plotBull15 = true
plotHiddenBull15 = false
plotBear15 = true
plotHiddenBear15 = false
bearColor15 = color.red
bullColor15 = color.green
hiddenBullColor15 = color.green
hiddenBearColor15 = color.red
textColor15 = color.white
noneColor15 = color.new(color.white, 100)
d15 = rvi
osc15 = d15
plFound15 = na(pivotlow(osc15, lbL15, lbR15)) ? false : true
phFound15 = na(pivothigh(osc15, lbL15, lbR15)) ? false : true
_inRange15(cond) =>
bars15 = barssince(cond == true)
rangeLower15 <= bars15 and bars15 <= rangeUpper15
//Regular Bullish
//Osc: Higher Low
oscHL15 = osc15[lbR15] > valuewhen(plFound15, osc15[lbR15], 1) and _inRange15(plFound15[1])
//Price: Lower Low
priceLL15 = low[lbR15] < valuewhen(plFound15, low[lbR15], 1)
bullCond15 = plotBull15 and priceLL15 and oscHL15 and plFound15
//plot(plFound15 ? osc15[lbR15] : na, offset=-lbR15, title="Regular Bullish", linewidth=2, color=(bullCond15 ? bullColor15 : noneColor15))
//plotshape(bullCond15 ? osc15[lbR15] : na, offset=-lbR15, title="Regular Bullish Label", text=" Bull ", style=shape.labelup, location=location.absolute, color=bullColor15, textcolor=textColor15)
//Hidden Bullish
//Osc: Lower Low
oscLL15 = osc15[lbR15] < valuewhen(plFound15, osc15[lbR15], 1) and _inRange15(plFound15[1])
//Price: Higher Low
priceHL15 = low[lbR15] > valuewhen(plFound15, low[lbR15], 1)
hiddenBullCond15 = plotHiddenBull15 and priceHL15 and oscLL15 and plFound15
//plot(plFound15 ? osc15[lbR15] : na, offset=-lbR15, title="Hidden Bullish", linewidth=2, color=(hiddenBullCond15 ? hiddenBullColor15 : noneColor15))
//plotshape(hiddenBullCond15 ? osc15[lbR15] : na, offset=-lbR15, title="Hidden Bullish Label", text=" H Bull ", style=shape.labelup, location=location.absolute, color=bullColor15, textcolor=textColor15)
//Regular Bearish
//Osc: Lower High
oscLH15 = osc15[lbR15] < valuewhen(phFound15, osc15[lbR15], 1) and _inRange15(phFound15[1])
//Price: Higher High
priceHH15 = high[lbR15] > valuewhen(phFound15, high[lbR15], 1)
bearCond15 = plotBear15 and priceHH15 and oscLH15 and phFound15
//plot(phFound15 ? osc15[lbR15] : na, offset=-lbR15, title="Regular Bearish", linewidth=2, color=(bearCond15 ? bearColor15 : noneColor15))
//plotshape(bearCond15 ? osc15[lbR15] : na, offset=-lbR15, title="Regular Bearish Label", text=" Bear ", style=shape.labeldown, location=location.absolute, color=bearColor15, textcolor=textColor15)
//Hidden Bearish
//Osc: Higher High
oscHH15 = osc15[lbR15] > valuewhen(phFound15, osc15[lbR15], 1) and _inRange15(phFound15[1])
//Price: Lower High
priceLH15 = high[lbR15] < valuewhen(phFound15, high[lbR15], 1)
hiddenBearCond15 = plotHiddenBear15 and priceLH15 and oscHH15 and phFound15
//plot(phFound15 ? osc15[lbR15] : na, offset=-lbR15, title="Hidden Bearish", linewidth=2, color=(hiddenBearCond15 ? hiddenBearColor15 : noneColor15))
//plotshape(hiddenBearCond15 ? osc15[lbR15] : na, offset=-lbR15, title="Hidden Bearish Label", text=" H Bear ", style=shape.labeldown, location=location.absolute, color=bearColor15, textcolor=textColor15)
//Support and Resistance////////////////////////////////////////////////////////
left16 = 200
right16 = 20
quick_right16 = 5
src16 = "Close"
pivot_high16 = iff(src16=="Close",pivothigh(close,left16,right16),pivothigh(high,left16,right16))
pivot_lows16 = iff(src16=="Close",pivotlow(close, left16,right16),pivotlow(low,left16,right16))
quick_pivot_high16 = iff(src16=="Close",pivothigh(close,left16,quick_right16),pivothigh(high,left16,quick_right16))
quick_pivot_lows16 = iff(src16=="Close",pivotlow(close, left16,quick_right16),pivotlow(low, left16,quick_right16))
level1 = iff(src16=="Close",valuewhen(quick_pivot_high16, close[quick_right16], 0),valuewhen(quick_pivot_high16, high[quick_right16], 0))
level2 = iff(src16=="Close",valuewhen(quick_pivot_lows16, close[quick_right16], 0),valuewhen(quick_pivot_lows16, low[quick_right16], 0))
level3 = iff(src16=="Close",valuewhen(pivot_high16, close[right16], 0),valuewhen(pivot_high16, high[right16], 0))
level4 = iff(src16=="Close",valuewhen(pivot_lows16, close[right16], 0),valuewhen(pivot_lows16, low[right16], 0))
level5 = iff(src16=="Close",valuewhen(pivot_high16, close[right16], 1),valuewhen(pivot_high16, high[right16], 1))
level6 = iff(src16=="Close",valuewhen(pivot_lows16, close[right16], 1),valuewhen(pivot_lows16, low[right16], 1))
level7 = iff(src16=="Close",valuewhen(pivot_high16, close[right16], 2),valuewhen(pivot_high16, high[right16], 2))
level8 = iff(src16=="Close",valuewhen(pivot_lows16, close[right16], 2),valuewhen(pivot_lows16, low[right16], 2))
level1_col = close >= level1 ? color.green : color.red
level2_col = close >= level2 ? color.green : color.red
level3_col = close >= level3 ? color.green : color.red
level4_col = close >= level4 ? color.green : color.red
level5_col = close >= level5 ? color.green : color.red
level6_col = close >= level6 ? color.green : color.red
level7_col = close >= level7 ? color.green : color.red
level8_col = close >= level8 ? color.green : color.red
length17 = 9
src17 = close
hma17 = wma(2*wma(src17, length17/2)-wma(src17, length17), floor(sqrt(length17)))
buy1 = hma17 > level1 and hma17[1] < level1[1] and close > close[2]
buy2 = hma17 > level2 and hma17[1] < level2[1] and close > close[2]
buy3 = hma17 > level3 and hma17[1] < level3[1] and close > close[2]
buy4 = hma17 > level4 and hma17[1] < level4[1] and close > close[2]
buy5 = hma17 > level5 and hma17[1] < level5[1] and close > close[2]
buy6 = hma17 > level6 and hma17[1] < level6[1] and close > close[2]
buy7 = hma17 > level7 and hma17[1] < level7[1] and close > close[2]
buy8 = hma17 > level8 and hma17[1] < level8[1] and close > close[2]
sell1 = hma17 < level1 and hma17[1] > level1[1] and close < close[2]
sell2 = hma17 < level2 and hma17[1] > level2[1] and close < close[2]
sell3 = hma17 < level3 and hma17[1] > level3[1] and close < close[2]
sell4 = hma17 < level4 and hma17[1] > level4[1] and close < close[2]
sell5 = hma17 < level5 and hma17[1] > level5[1] and close < close[2]
sell6 = hma17 < level6 and hma17[1] > level6[1] and close < close[2]
sell7 = hma17 < level7 and hma17[1] > level7[1] and close < close[2]
sell8 = hma17 < level8 and hma17[1] > level8[1] and close < close[2]
//END▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
////////////////////////////////////////////////////////////////////////////////
//VOLUME INDICATORS▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼
//OBV Divergence////////////////////////////////////////////////////////////////
len18 = 20
src18 = close
lbR18 = 2
lbL18 = 6
rangeUpper18 = 60
rangeLower18 = 5
plotBull18 = true
plotHiddenBull18 = false
plotBear18 = true
plotHiddenBear18 = false
bearColor18 = color.red
bullColor18 = color.green
hiddenBullColor18 = color.green
hiddenBearColor18 = color.new(color.red, 80)
textColor18 = color.white
noneColor18 = color.new(color.white, 100)
csrc = change(src18)
obv1(src18) => cum(change(src18) > 0 ? volume : csrc < 0 ? -volume : 0*volume)
os = obv1(src18)
obv_osc = (os - ema(os,len18))
obc_color=obv_osc > 0 ? color.green : color.red
//plot(obv_osc, color=obc_color, style=plot.style_line,title="OBV-Points", linewidth=2)
//plot(obv_osc, color=color.silver, transp=70, title="OBV", style=plot.style_area)
//hline(0)
plFound18 = na(pivotlow(obv_osc, lbL18, lbR18)) ? false : true
phFound18 = na(pivothigh(obv_osc, lbL18, lbR18)) ? false : true
_inRange(cond) =>
bars = barssince(cond == true)
rangeLower18 <= bars and bars <= rangeUpper18
// Regular Bullish
// Osc: Higher Low
oscHL18 = obv_osc[lbR18] > valuewhen(plFound18, obv_osc[lbR18], 1) and _inRange(plFound18[1])
// Price: Lower Low
priceLL18 = low[lbR18] < valuewhen(plFound18, low[lbR18], 1)
bullCond18 = plotBull18 and priceLL18 and oscHL18 and plFound18
//plot(plFound18 ? obv_osc[lbR18] : na,offset=-lbR18,title="Regular Bullish",linewidth=2,color=(bullCond18 ? bullColor18 : noneColor18))
//plotshape(bullCond18 ? obv_osc[lbR18] : na,offset=-lbR18,title="Regular Bullish Label",text=" Bull ",style=shape.labelup,location=location.absolute,color=bullColor18,textcolor=textColor18)
// Hidden Bullish
// Osc: Lower Low
oscLL18 = obv_osc[lbR18] < valuewhen(plFound18, obv_osc[lbR18], 1) and _inRange(plFound18[1])
// Price: Higher Low
priceHL18 = low[lbR18] > valuewhen(plFound18, low[lbR18], 1)
hiddenBullCond18 = plotHiddenBull18 and priceHL18 and oscLL18 and plFound18
//plot(plFound18 ? obv_osc[lbR18] : na,offset=-lbR18,title="Hidden Bullish",linewidth=2,color=(hiddenBullCond18 ? hiddenBullColor18 : noneColor18))
//plotshape(hiddenBullCond18 ? obv_osc[lbR18] : na,offset=-lbR18,title="Hidden Bullish Label",text=" H Bull ",style=shape.labelup,location=location.absolute,color=bullColor18,textcolor=textColor18)
// Regular Bearish
// Osc: Lower High
oscLH18 = obv_osc[lbR18] < valuewhen(phFound18, obv_osc[lbR18], 1) and _inRange(phFound18[1])
// Price: Higher High
priceHH18 = high[lbR18] > valuewhen(phFound18, high[lbR18], 1)
bearCond18 = plotBear18 and priceHH18 and oscLH18 and phFound18
//plot(phFound18 ? obv_osc[lbR18] : na,offset=-lbR18,title="Regular Bearish",linewidth=2,color=(bearCond18 ? bearColor18 : noneColor18))
//plotshape(bearCond18 ? obv_osc[lbR18] : na,offset=-lbR18,title="Regular Bearish Label",text=" Bear ",style=shape.labeldown,location=location.absolute,color=bearColor18,textcolor=textColor18)
// Hidden Bearish
// Osc: Higher High
oscHH18 = obv_osc[lbR18] > valuewhen(phFound18, obv_osc[lbR18], 1) and _inRange(phFound18[1])
// Price: Lower High
priceLH18 = high[lbR18] < valuewhen(phFound18, high[lbR18], 1)
hiddenBearCond18 = plotHiddenBear18 and priceLH18 and oscHH18 and phFound18
//plot(phFound18 ? obv_osc[lbR18] : na,offset=-lbR18,title="Hidden Bearish",linewidth=2,color=(hiddenBearCond18 ? hiddenBearColor18 : noneColor18))
//plotshape(hiddenBearCond18 ? obv_osc[lbR18] : na,offset=-lbR18,title="Hidden Bearish Label",text=" H Bear ",style=shape.labeldown,location=location.absolute,color=bearColor18,textcolor=textColor18)
//Chaikin Money Flow////////////////////////////////////////////////////////////
length19 = 50
ad19 = close==high and close==low or high==low ? 0 : ((2*close-low-high)/(high-low))*volume
cmf = sum(ad19, length19) / sum(volume, length19)
//plot(cmf, color=#43A047, title="MF")
//hline(0, color=#787B86, title="Zero", linestyle=hline.style_dashed)
//VWAP//////////////////////////////////////////////////////////////////////////
computeVWAP(src20, isNewPeriod, stDevMultiplier) =>
var float sumSrcVol = na
var float sumVol = na
var float sumSrcSrcVol = na
sumSrcVol := isNewPeriod ? src20 * volume : src20 * volume + sumSrcVol[1]
sumVol := isNewPeriod ? volume : volume + sumVol[1]
// sumSrcSrcVol calculates the dividend of the equation that is later used to calculate the standard deviation
sumSrcSrcVol := isNewPeriod ? volume * pow(src20, 2) : volume * pow(src20, 2) + sumSrcSrcVol[1]
_vwap = sumSrcVol / sumVol
variance = sumSrcSrcVol / sumVol - pow(_vwap, 2)
variance := variance < 0 ? 0 : variance
stDev = sqrt(variance)
lowerBand20 = _vwap - stDev * stDevMultiplier
upperBand20 = _vwap + stDev * stDevMultiplier
[_vwap, lowerBand20, upperBand20]
hideonDWM = false
var anchor = "Session"
src20 = hlc3
offset20 = 0
showBands = true
stdevMult = 1.0
timeChange(period) =>
change(time(period))
new_earnings = earnings(syminfo.tickerid, earnings.actual, barmerge.gaps_on, barmerge.lookahead_on)
new_dividends = dividends(syminfo.tickerid, dividends.gross, barmerge.gaps_on, barmerge.lookahead_on)
new_split = splits(syminfo.tickerid, splits.denominator, barmerge.gaps_on, barmerge.lookahead_on)
tcD = timeChange("D")
tcW = timeChange("W")
tcM = timeChange("M")
tc3M = timeChange("3M")
tc12M = timeChange("12M")
isNewPeriod = anchor == "Earnings" ? new_earnings :
anchor == "Dividends" ? new_dividends :
anchor == "Splits" ? new_split :
na(src20[1]) ? true :
anchor == "Session" ? tcD :
anchor == "Week" ? tcW :
anchor == "Month" ? tcM :
anchor == "Quarter" ? tc3M :
anchor == "Year" ? tc12M :
anchor == "Decade" ? tc12M and year % 10 == 0 :
anchor == "Century" ? tc12M and year % 100 == 0 :
false
float vwapValue = na
float std = na
float upperBandValue = na
float lowerBandValue = na
if not (hideonDWM and timeframe.isdwm)
[_vwap, bottom, top] = computeVWAP(src20, isNewPeriod, stdevMult)
vwapValue := _vwap
upperBandValue := showBands ? top : na
lowerBandValue := showBands ? bottom : na
//plot(vwapValue, title="VWAP", color=#2962FF, offset=offset)
//upperBand20 = plot(upperBandValue, title="Upper Band", color=color.green, offset=offset)
//lowerBand20 = plot(lowerBandValue, title="Lower Band", color=color.green, offset=offset)
//fill(upperBand20, lowerBand20, title="Bands Fill", color= showBands ? color.new(color.green, 95) : na)
//Candle Patterns///////////////////////////////////////////////////////////////
//Bullish Engulfing
C_DownTrend = true
C_UpTrend = true
var trendRule1 = "SMA50"
var trendRule2 = "SMA50, SMA200"
var trendRule = trendRule1
if trendRule == trendRule1
priceAvg = sma(close, 50)
C_DownTrend := close < priceAvg
C_UpTrend := close > priceAvg
if trendRule == trendRule2
sma200 = sma(close, 200)
sma50 = sma(close, 50)
C_DownTrend := close < sma50 and sma50 < sma200
C_UpTrend := close > sma50 and sma50 > sma200
C_Len = 14 // ema depth for bodyAvg
C_ShadowPercent = 5.0 // size of shadows
C_ShadowEqualsPercent = 100.0
C_DojiBodyPercent = 5.0
C_Factor = 2.0 // shows the number of times the shadow dominates the candlestick body
C_BodyHi = max(close, open)
C_BodyLo = min(close, open)
C_Body = C_BodyHi - C_BodyLo
C_BodyAvg = ema(C_Body, C_Len)
C_SmallBody = C_Body < C_BodyAvg
C_LongBody = C_Body > C_BodyAvg
C_UpShadow = high - C_BodyHi
C_DnShadow = C_BodyLo - low
C_HasUpShadow = C_UpShadow > C_ShadowPercent / 100 * C_Body
C_HasDnShadow = C_DnShadow > C_ShadowPercent / 100 * C_Body
C_WhiteBody = open < close
C_BlackBody = open > close
C_Range = high-low
C_IsInsideBar = C_BodyHi[1] > C_BodyHi and C_BodyLo[1] < C_BodyLo
C_BodyMiddle = C_Body / 2 + C_BodyLo
C_ShadowEquals = C_UpShadow == C_DnShadow or (abs(C_UpShadow - C_DnShadow) / C_DnShadow * 100) < C_ShadowEqualsPercent and (abs(C_DnShadow - C_UpShadow) / C_UpShadow * 100) < C_ShadowEqualsPercent
C_IsDojiBody = C_Range > 0 and C_Body <= C_Range * C_DojiBodyPercent / 100
C_Doji = C_IsDojiBody and C_ShadowEquals
patternLabelPosLow = low - (atr(30) * 0.6)
patternLabelPosHigh = high + (atr(30) * 0.6)
label_color_bullish = color.blue
C_EngulfingBullishNumberOfCandles = 2
C_EngulfingBullish = C_DownTrend and C_WhiteBody and C_LongBody and C_BlackBody[1] and C_SmallBody[1] and close >= open[1] and open <= close[1] and ( close > open[1] or open < close[1] )
if C_EngulfingBullish
var ttBullishEngulfing = "Engulfing\nAt the end of a given downward trend, there will most likely be a reversal pattern. To distinguish the first day, this candlestick pattern uses a small body, followed by a day where the candle body fully overtakes the body from the day before, and closes in the trend’s opposite direction. Although similar to the outside reversal chart pattern, it is not essential for this pattern to completely overtake the range (high to low), rather only the open and the close."
//label.new(bar_index, patternLabelPosLow, text="BE", style=label.style_label_up, color = label_color_bullish, textcolor=color.white, tooltip = ttBullishEngulfing)
//bgcolor(highest(C_EngulfingBullish?1:0, C_EngulfingBullishNumberOfCandles)!=0 ? color.blue : na, offset=-(C_EngulfingBullishNumberOfCandles-1))
//Bearish Engulfing
label_color_bearish = color.red
C_EngulfingBearishNumberOfCandles = 2
C_EngulfingBearish = C_UpTrend and C_BlackBody and C_LongBody and C_WhiteBody[1] and C_SmallBody[1] and close <= open[1] and open >= close[1] and ( close < open[1] or open > close[1] )
if C_EngulfingBearish
var ttBearishEngulfing = "Engulfing\nAt the end of a given uptrend, a reversal pattern will most likely appear. During the first day, this candlestick pattern uses a small body. It is then followed by a day where the candle body fully overtakes the body from the day before it and closes in the trend’s opposite direction. Although similar to the outside reversal chart pattern, it is not essential for this pattern to fully overtake the range (high to low), rather only the open and the close."
//label.new(bar_index, patternLabelPosHigh, text="BE", style=label.style_label_down, color = label_color_bearish, textcolor=color.white, tooltip = ttBearishEngulfing)
//bgcolor(highest(C_EngulfingBearish?1:0, C_EngulfingBearishNumberOfCandles)!=0 ? color.red : na, offset=-(C_EngulfingBearishNumberOfCandles-1))
//END▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
////////////////////////////////////////////////////////////////////////////////
//SIGNAL SCORES▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼
//Alternate Signals Option
alternatesignals = input(title="Alternate Signals", defval=true)
//Position Options
longpositions = input(title="Long Positions", defval=true)
shortpositions = input(title="Short Positions", defval=true)
//Stop Loss Warning Option
stoplosspercent = input(title="Stop Loss Warning (%)", type=input.float, defval=-2.5, minval=-50, maxval=0, step=.1) / 100
//Score Requirements
stronglongscore = input(defval=6, minval=0, maxval=1000, title="Required Strong LONG Score")
strongshortscore = input(defval=6, minval=0, maxval=1000, title="Required Strong SHORT Score")
weaklongscore = input(defval=6, minval=0, maxval=1000, title="Required Weak LONG Score")
weakshortscore = input(defval=6, minval=0, maxval=1000, title="Required Weak SHORT Score")
//Trend Indicator Signals///////////////////////////////////////////////////////
//EMA Signals
emadirectionimportance = input(defval=2, minval=0, maxval=100, title="EMA Trend Direction Importance")
emadirectionup = out5 < close ? emadirectionimportance : 0
emadirectionupstatus = emadirectionup ? "EMA Trend Direction Up" : na
emadirectiondown = out5 > close ? emadirectionimportance : 0
emadirectiondownstatus = emadirectiondown ? "EMA Trend Direction Down" : na
emapushpullimportance = input(defval=2, minval=0, maxval=100, title="EMA Pressure Importance")
emapushup = out2 > out2[1] and out3 < out3[1] ? emapushpullimportance : 0
emapushupstatus = emapushup ? "EMA Pushing Up" : na
emapulldown = out2 < out2[1] and out3 > out3[1] ? emapushpullimportance : 0
emapulldownstatus = emapulldown ? "EMA Pulling Down" : na
//Super Trend Signals
supertrenddirimportance = input(defval=0, minval=0, maxval=100, title="SuperTrend Direction Importance")
supertrendup = direction < 0 ? supertrenddirimportance : 0
supertrendupstatus = supertrendup ? "SuperTrend Direction Up" : na
supertrenddown = direction > 0 ? supertrenddirimportance : 0
supertrenddownstatus = supertrenddown ? "SuperTrend Direction Down" : na
supertrendrevimportance = input(defval=4, minval=0, maxval=100, title="SuperTrend Reversal Importance")
supertrendrevup = direction < 0 and direction[1] > 0[1] ? supertrendrevimportance : 0
supertrendrevupstatus = supertrendrevup ? "SuperTrend Reversed Up" : na
supertrendrevdown = direction > 0 and direction[1] < 0[1] ? supertrendrevimportance : 0
supertrendrevdownstatus = supertrendrevdown ? "SuperTrend Reversed Down" : na
//Parabolic SAR Signals
psardirimportance = input(defval=0, minval=0, maxval=100, title="Parabolic SAR Direction Importance")
psardirup = psar < close ? psardirimportance : 0
psardirupstatus = psardirup ? "PSAR Direction Up" : na
psardirdown = psar > close ? psardirimportance : 0
psardirdownstatus = psardirdown ? "PSAR Direction Down" : na
psarrevimportance = input(defval=3, minval=0, maxval=100, title="Parabolic SAR Reversal Importance")
psarrevup = psar < close and psar[1] > close[1] ? psarrevimportance : 0
psarrevupstatus = psarrevup ? "PSAR Reversed Up" : na
psarrevdown = psar > close and psar[1] < close ? psarrevimportance : 0
psarrevdownstatus = psarrevdown ? "PSAR Reversed Down" : na
//HMA Signals
hmacloseposimportance = input(defval=1, minval=0, maxval=100, title="HMA Trend Direction Importance")
hmacloseposup = hma < close and hma[1] ? hmacloseposimportance : 0
hmacloseposupstatus = hmacloseposup ? "Price Crossed Over HMA" : na
hmacloseposdown = hma > close ? hmacloseposimportance : 0
hmacloseposdownstatus = hmacloseposdown ? "Price Crossed Under HMA" : na
hmapivotimportance = input(defval=3, minval=0, maxval=100, title="HMA Pivot Importance")
hmapivotup = hma > hma[1] and hma[1] < hma[2] ? hmapivotimportance : 0
hmapivotupstatus = hmapivotup ? "HMA Pivot Up" : na
hmapivotdown = hma < hma[1] and hma[1] > hma[2] ? hmapivotimportance : 0
hmapivotdownstatus = hmapivotdown ? "HMA Pivot Down" : na
//Momentum Indicator Signals////////////////////////////////////////////////////
//RSI Signals
rsidivimportance = input(defval=4, minval=0, maxval=100, title="RSI Divergence Importance")
rsidivup = bullCond11 or bullCond11[1] or bullCond11[2] ? rsidivimportance : 0
rsidivupstatus = rsidivup ? "Bullish RSI Divergence" : na
rsidivdown = bearCond11 or bearCond11[1] or bearCond11[2] ? rsidivimportance : 0
rsidivdownstatus = rsidivdown ? "Bearish RSI Divergence" : na
rsilevelimportance = input(defval=0, minval=0, maxval=100, title="RSI Level Importance")
rsioversold = osc11 < 30 ? rsilevelimportance : 0
rsioversoldstatus = rsioversold ? "RSI Oversold" : na
rsioverbought = osc11 > 70 ? rsilevelimportance : 0
rsioverboughtstatus = rsioverbought ? "RSI Overbought" : na
rsidirectionimportance = input(defval=1, minval=0, maxval=100, title="RSI Cross 50-Line Importance")
rsicrossup = (osc11 > 50 and osc11[1] < 50) or (osc11 > 50 and osc11[2] < 50) ? rsidirectionimportance : 0
rsicrossupstatus = rsicrossup ? "RSI Crossed 50-Line Up" : na
rsicrossdown = (osc11 < 50 and osc11[1] > 50) or (osc11 < 50 and osc11[2] > 50) ? rsidirectionimportance : 0
rsicrossdownstatus = rsicrossdown ? "RSI Crossed 50-Line Down" : na
//MACD Signals
macddivimportance = input(defval=0, minval=0, maxval=100, title="MACD Divergence Importance")
macddivup = bullCond12 or bullCond12[1] or bullCond12[2] ? macddivimportance : 0
macddivupstatus = macddivup ? "Bullish MACD Divergence" : na
macddivdown = bearCond12 or bearCond12[1] or bearCond12[2] ? macddivimportance : 0
macddivdownstatus = macddivdown ? "Bearish MACD Divergence" : na
histpivotimportance = input(defval=1, minval=0, maxval=100, title="MACD Histogram Pivot Importance")
histpivotup = hist > hist[1] and hist[1] < hist[2] and hist < 0 ? histpivotimportance : 0
histpivotupstatus = histpivotup ? "MACD Histogram Pivot Up" : na
histpivotdown = hist < hist[1] and hist[1] > hist[2] and hist > 0 ? histpivotimportance : 0
histpivotdownstatus = histpivotdown ? "MACD Histogram Pivot Down" : na
macdcrosssignalimportance = input(defval=1, minval=0, maxval=100, title="MACD Cross Signal Importance")
macdcrosssignalup = macd > signal and macd[1] < signal[1] and signal < 0 ? macdcrosssignalimportance : 0
macdcrosssignalupstatus = macdcrosssignalup ? "MACD Crossed Signal Up" : na
macdcrosssignaldown = macd < signal and macd[1] > signal[1] and signal > 0 ? macdcrosssignalimportance : 0
macdcrosssignaldownstatus = macdcrosssignaldown ? "MACD Crossed Signal Down" : na
//WaveTrend Signals
wtdivimportance = input(defval=0, minval=0, maxval=100, title="WaveTrend Divergence Importance")
wtdivup = bullCond13 or bullCond13[1] or bullCond13[2] ? wtdivimportance : 0
wtdivupstatus = wtdivup ? "Bullish WaveTrend Divergence" : na
wtdivdown = bearCond13 or bearCond13[1] or bearCond13[2] ? wtdivimportance : 0
wtdivdownstatus = wtdivdown ? "Bearish WaveTrend Divergence" : na
wtcrosssignalimportance = input(defval=4, minval=0, maxval=100, title="WaveTrend Cross Signal Importance")
wtcrosssignalup = wt1 > wt2 and wt1[1] < wt2[1] and wt2 < -10 ? wtcrosssignalimportance : 0
wtcrosssignalupstatus = wtcrosssignalup ? "WaveTrend Crossed Signal Up" : na
wtcrosssignaldown = wt1 < wt2 and wt1[1] > wt2[1] and wt2 > 10 ? wtcrosssignalimportance : 0
wtcrosssignaldownstatus = wtcrosssignaldown ? "WaveTrend Crossed Signal Down" : na
//Stochastic Signals
sdivimportance = input(defval=1, minval=0, maxval=100, title="Stochastic Divergence Importance")
sdivup = bullCond14 or bullCond14[1] or bullCond14[2] ? sdivimportance : 0
sdivupstatus = sdivup ? "Bullish Stoch Divergence" : na
sdivdown = bearCond14 or bearCond14[1] or bearCond14[2] ? sdivimportance : 0
sdivdownstatus = sdivdown ? "Bearish Stoch Divergence" : na
scrosssignalimportance = input(defval=1, minval=0, maxval=100, title="Stoch Cross Signal Importance")
scrosssignalup = k14 > d14 and k14[1] < d14[1] ? scrosssignalimportance : 0
scrosssignalupstatus = scrosssignalup ? "Stoch Crossed Signal Up" : na
scrosssignaldown = k14 < d14 and k14[1] > d14[1] ? scrosssignalimportance : 0
scrosssignaldownstatus = scrosssignaldown ? "Stoch Crossed Signal Down" : na
//Volatility Indicators/////////////////////////////////////////////////////////
//Bollinger Bands Signals
bbcontimportance = input(defval=0, minval=0, maxval=100, title="BollingerBands Contact Importance")
bbcontup = close < lower ? bbcontimportance : 0
bbcontupstatus = bbcontup ? "Price Contacted Lower BB" : na
bbcontdown = open > upper ? bbcontimportance : 0
bbcontdownstatus = bbcontdown ? "Price Contacted Upper BB" : na
//Average True Range Signals
atrrevimportance = input(defval=1, minval=0, maxval=100, title="ATR Reversal Importance")
atrrevup = buySignal ? atrrevimportance : 0
atrrevupstatus = atrrevup ? "ATR Reversed Up" : na
atrrevdown = sellSignal ? atrrevimportance : 0
atrrevdownstatus = atrrevdown ? "ATR Reversed Down" : na
//Relative Volatility Index Signals
rviposimportance = input(defval=3, minval=0, maxval=100, title="RVI Position Importance")
rviposup = rvi > 25 and rvi[1] < 40 ? rviposimportance : 0
rviposupstatus = rviposup ? "RVI Volatility Increasing" : na
rviposdown = rvi < 75 and rvi[1] > 60 ? rviposimportance : 0
rviposdownstatus = rviposdown ? "RVI Volatility Decreasing" : na
rvidivimportance = input(defval=4, minval=0, maxval=100, title="RVI Divergence Importance")
rvidivup = bullCond15 or bullCond15[1] or bullCond15[2] ? rvidivimportance : 0
rvidivupstatus = rvidivup ? "Bullish RVI Divergence" : na
rvidivdown = bearCond15 or bearCond15[1] or bearCond15[2] ? rvidivimportance : 0
rvidivdownstatus = rvidivdown ? "Bearish RVI Divergence" : na
//Support and Resistance Signals
srcrossimportance = input(defval=4, minval=0, maxval=100, title="Support/Resistance Cross Importance")
srcrossup = buy1 or buy2 or buy3 or buy4 or buy5 or buy6 or buy7 or buy8 ? srcrossimportance : 0
srcrossupstatus = srcrossup ? "Crossed Key Level Up" : na
srcrossdown = sell1 or sell2 or sell3 or sell4 or sell5 or sell6 or sell7 or sell8 ? srcrossimportance : 0
srcrossdownstatus = srcrossdown ? "Crossed Key Level Down" : na
//Volume Indicator Signals//////////////////////////////////////////////////////
//On Balance Volume Divergence Signals
obvdivimportance = input(defval=0, minval=0, maxval=100, title="OBV Divergence Importance")
obvdivup = bullCond18 or bullCond18[1] or bullCond18[2] ? obvdivimportance : 0
obvdivupstatus = obvdivup ? "Bullish OBV Divergence" : na
obvdivdown = bearCond18 or bearCond18[1] or bearCond18[2] ? obvdivimportance : 0
obvdivdownstatus = obvdivdown ? "Bearish OBV Divergence" : na
//Chaikin Money Flow Signals
cmfcrossimportance = input(defval=0, minval=0, maxval=100, title="CMF Cross 50-Line Importance")
cmfcrossup = cmf > 0 and cmf[1] < 0 ? cmfcrossimportance : 0
cmfcrossupstatus = cmfcrossup ? "CMF Crossed 50-Line Up" : na
cmfcrossdown = cmf < 0 and cmf[1] > 0 ? cmfcrossimportance : 0
cmfcrossdownstatus = cmfcrossdown ? "CMF Crossed 50-Line Down" : na
cmflevimportance = input(defval=0, minval=0, maxval=100, title="CMF Level Importance")
cmflevup = cmf > 0 ? cmflevimportance : 0
cmflevupstatus = cmflevup ? "CMF Level Up" : na
cmflevdown = cmf < 0 ? cmflevimportance : 0
cmflevdownstatus = cmflevdown ? "CMF Level Down" : na
//VWAP Signals
vwapcrossimportance = input(defval=0, minval=0, maxval=100, title="VWAP Cross HMA Importance")
vwapcrossup = hma < vwapValue and hma[1] > vwapValue[1] ? vwapcrossimportance : 0
vwapcrossupstatus = vwapcrossup ? "VWAP Crossed Above HMA" : na
vwapcrossdown = hma > vwapValue and hma[1] < vwapValue[1] ? vwapcrossimportance : 0
vwapcrossdownstatus = vwapcrossdown ? "VWAP Crossed Below HMA" : na
vwaptrendimportance = input(defval=0, minval=0, maxval=100, title="VWAP Trend Importance")
vwaptrendup = out2 > vwapValue ? vwaptrendimportance : 0
vwaptrendupstatus = vwaptrendup ? "VWAP Up Trend" : na
vwaptrenddown = out2 < vwapValue ? vwaptrendimportance : 0
vwaptrenddownstatus = vwaptrenddown ? "VWAP Down Trend" : na
//Candle Patterns Signals
engulfingcandleimportance = input(defval=0, minval=0, maxval=100, title="Engulfing Candle Importance")
bulleng = C_EngulfingBullish ? engulfingcandleimportance : 0
bullengstatus = bulleng ? "Bullish Engulfing Candle" : na
beareng = C_EngulfingBearish ? engulfingcandleimportance : 0
bearengstatus = beareng ? "Bearish Engulfing Candle" : na
//END▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
////////////////////////////////////////////////////////////////////////////////
//COLLECT SIGNALS▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼
//Classify Entries
stronglongentrysignal = emadirectionup + emapushup + supertrendup + supertrendrevup + psardirup + psarrevup + hmacloseposup + hmapivotup + rsidivup + rsioversold + rsicrossup + macddivup + histpivotup + macdcrosssignalup + wtdivup + wtcrosssignalup + sdivup + scrosssignalup + bbcontup + atrrevup + rviposup + rvidivup + srcrossup + obvdivup + cmfcrossup + cmflevup + vwapcrossup + vwaptrendup + bulleng >= stronglongscore
strongshortentrysignal = emadirectiondown + emapulldown + supertrenddown + supertrendrevdown + psardirdown + psarrevdown + hmacloseposdown + hmapivotdown + rsidivdown + rsioverbought + rsicrossdown + macddivdown + histpivotdown + macdcrosssignaldown + wtdivdown + wtcrosssignaldown + sdivdown + scrosssignaldown + bbcontdown + atrrevdown + rviposdown + rvidivdown + srcrossdown + obvdivdown + cmfcrossdown + cmflevdown + vwapcrossdown + vwaptrenddown + beareng >= strongshortscore
weaklongentrysignal = emadirectionup + emapushup + supertrendup + supertrendrevup + psardirup + psarrevup + hmacloseposup + hmapivotup + rsidivup + rsioversold + rsicrossup + macddivup + histpivotup + macdcrosssignalup + wtdivup + wtcrosssignalup + sdivup + scrosssignalup + bbcontup + atrrevup + rviposup + rvidivup + srcrossup + obvdivup + cmfcrossup + cmflevup + vwapcrossup + vwaptrendup + bulleng >= weaklongscore
weakshortentrysignal = emadirectiondown + emapulldown + supertrenddown + supertrendrevdown + psardirdown + psarrevdown + hmacloseposdown + hmapivotdown + rsidivdown + rsioverbought + rsicrossdown + macddivdown + histpivotdown + macdcrosssignaldown + wtdivdown + wtcrosssignaldown + sdivdown + scrosssignaldown + bbcontdown + atrrevdown + rviposdown + rvidivdown + srcrossdown + obvdivdown + cmfcrossdown + cmflevdown + vwapcrossdown + vwaptrenddown + beareng >= weakshortscore
//Alternate Entry Signals
var pos = 0
if stronglongentrysignal and pos <= 0
pos := 1
if strongshortentrysignal and pos >= 0
pos := -1
longentry = pos == 1 and (pos != 1)[1]
shortentry = pos == -1 and (pos != -1)[1]
alternatelong = alternatesignals ? longentry : stronglongentrysignal
alternateshort = alternatesignals ? shortentry : strongshortentrysignal
//END▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
////////////////////////////////////////////////////////////////////////////////
//PLOT SIGNALS▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼
plotshape(tradetrendoption ? alternatelong and mabuy : alternatelong, title="Strong Long Label", style=shape.labelup, location=location.belowbar, color=#00bcd4, text="𝐋𝐎𝐍𝐆", textcolor=color.white, size=size.small)
plotshape(tradetrendoption ? alternateshort and masell : alternateshort, title="Strong Short Label", style=shape.labeldown, location=location.abovebar, color=#e91e63, text="𝐒𝐇𝐎𝐑𝐓", textcolor=color.white, size=size.small)
plotshape(weaklongentrysignal, title="Weak Long Triangle", style=shape.triangleup, location=location.belowbar, color=color.new(#00bcd4, 50), size=size.tiny)
plotshape(weakshortentrysignal, title="Weak Short Triangle", style=shape.triangledown, location=location.abovebar, color=color.new(#e91e63, 50), size=size.tiny)
//END▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
////////////////////////////////////////////////////////////////////////////////
//PLOT STATUS▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼
var table statuswindow = table.new(position.top_right, 100, 100, border_width=2)
//Trend Status//////////////////////////////////////////////////////////////////
txt1 = "🡇 TREND 🡇"
table.cell(statuswindow, 3, 0, text=txt1, bgcolor=color.new(#000000, 50), text_color=color.white, text_size=size.small)
//EMA Status
if emadirectionup
table.cell(statuswindow, 3, 1, text=tostring(emadirectionupstatus), bgcolor=color.new(#00bcd4, 50), text_color=color.white, text_size=size.small)
if emadirectiondown
table.cell(statuswindow, 3, 1, text=tostring(emadirectiondownstatus), bgcolor=color.new(#e91e63, 50), text_color=color.white, text_size=size.small)
if emapushup ? 1 : na
table.cell(statuswindow, 3, 2, text=tostring(emapushupstatus), bgcolor=color.new(#00bcd4, 50), text_color=color.white, text_size=size.small)
if emapushup ? na : 1
table.clear(statuswindow, 3, 2)
if emapulldown ? 1 : na
table.cell(statuswindow, 3, 3, text=tostring(emapulldownstatus), bgcolor=color.new(#e91e63, 50), text_color=color.white, text_size=size.small)
if emapulldown ? na : 1
table.clear(statuswindow, 3, 3)
//SuperTrend Status
if supertrendup
table.cell(statuswindow, 3, 4, text=tostring(supertrendupstatus), bgcolor=color.new(#00bcd4, 50), text_color=color.white, text_size=size.small)
if supertrenddown
table.cell(statuswindow, 3, 4, text=tostring(supertrenddownstatus), bgcolor=color.new(#e91e63, 50), text_color=color.white, text_size=size.small)
if supertrendrevup ? 1 : na
table.cell(statuswindow, 3, 5, text=tostring(supertrendrevupstatus), bgcolor=color.new(#00bcd4, 50), text_color=color.white, text_size=size.small)
if supertrendrevup ? na : 1
table.clear(statuswindow, 3, 5)
if supertrendrevdown ? 1 : na
table.cell(statuswindow, 3, 6, text=tostring(supertrendrevdownstatus), bgcolor=color.new(#e91e63, 50), text_color=color.white, text_size=size.small)
if supertrendrevdown ? na : 1
table.clear(statuswindow, 3, 6)
//Parabolic SAR Status
if psardirup
table.cell(statuswindow, 3, 7, text=tostring(psardirupstatus), bgcolor=color.new(#00bcd4, 50), text_color=color.white, text_size=size.small)
if psardirdown
table.cell(statuswindow, 3, 7, text=tostring(psardirdownstatus), bgcolor=color.new(#e91e63, 50), text_color=color.white, text_size=size.small)
if psarrevup ? 1 : na
table.cell(statuswindow, 3, 8, text=tostring(psarrevupstatus), bgcolor=color.new(#00bcd4, 50), text_color=color.white, text_size=size.small)
if psarrevup ? na : 1
table.clear(statuswindow, 3, 8)
if psarrevdown ? 1 : na
table.cell(statuswindow, 3, 9, text=tostring(psarrevdownstatus), bgcolor=color.new(#e91e63, 50), text_color=color.white, text_size=size.small)
if psarrevdown ? na : 1
table.clear(statuswindow, 3, 9)
//HMA Status
if hmacloseposup
table.cell(statuswindow, 3, 10, text=tostring(hmacloseposupstatus), bgcolor=color.new(#00bcd4, 50), text_color=color.white, text_size=size.small)
if hmacloseposdown
table.cell(statuswindow, 3, 10, text=tostring(hmacloseposdownstatus), bgcolor=color.new(#e91e63, 50), text_color=color.white, text_size=size.small)
if hmapivotup ? 1 : na
table.cell(statuswindow, 3, 11, text=tostring(hmapivotupstatus), bgcolor=color.new(#00bcd4, 50), text_color=color.white, text_size=size.small)
if hmapivotup ? na : 1
table.clear(statuswindow, 3, 11)
if hmapivotdown ? 1 : na
table.cell(statuswindow, 3, 12, text=tostring(hmapivotdownstatus), bgcolor=color.new(#e91e63, 50), text_color=color.white, text_size=size.small)
if hmapivotdown ? na : 1
table.clear(statuswindow, 3, 12)
//Momentum Status///////////////////////////////////////////////////////////////
txt2 = "🡇 MOMENTUM 🡇"
table.cell(statuswindow, 2, 0, text=txt2, bgcolor=color.new(#000000, 50), text_color=color.white, text_size=size.small)
//RSI Status
if rsidivup ? 1 : na
table.cell(statuswindow, 2, 1, text=tostring(rsidivupstatus), bgcolor=color.new(#00bcd4, 50), text_color=color.white, text_size=size.small)
if rsidivup ? na : 1
table.clear(statuswindow, 2, 1)
if rsidivdown ? 1 : na
table.cell(statuswindow, 2, 2, text=tostring(rsidivdownstatus), bgcolor=color.new(#e91e63, 50), text_color=color.white, text_size=size.small)
if rsidivdown ? na : 1
table.clear(statuswindow, 2, 2)
if rsioversold ? 1 : na
table.cell(statuswindow, 2, 3, text=tostring(rsioversoldstatus), bgcolor=color.new(#00bcd4, 50), text_color=color.white, text_size=size.small)
if rsioversold ? na : 1
table.clear(statuswindow, 2, 3)
if rsioverbought ? 1 : na
table.cell(statuswindow, 2, 4, text=tostring(rsioverboughtstatus), bgcolor=color.new(#e91e63, 50), text_color=color.white, text_size=size.small)
if rsioverbought ? na : 1
table.clear(statuswindow, 2, 4)
if rsicrossup ? 1 : na
table.cell(statuswindow, 2, 5, text=tostring(rsicrossupstatus), bgcolor=color.new(#00bcd4, 50), text_color=color.white, text_size=size.small)
if rsicrossup ? na : 1
table.clear(statuswindow, 2, 5)
if rsicrossdown ? 1 : na
table.cell(statuswindow, 2, 6, text=tostring(rsicrossdownstatus), bgcolor=color.new(#e91e63, 50), text_color=color.white, text_size=size.small)
if rsicrossdown ? na : 1
table.clear(statuswindow, 2, 6)
//MACD Status
if macddivup ? 1 : na
table.cell(statuswindow, 2, 7, text=tostring(macddivupstatus), bgcolor=color.new(#00bcd4, 50), text_color=color.white, text_size=size.small)
if macddivup ? na : 1
table.clear(statuswindow, 2, 7)
if macddivdown ? 1 : na
table.cell(statuswindow, 2, 8, text=tostring(macddivdownstatus), bgcolor=color.new(#e91e63, 50), text_color=color.white, text_size=size.small)
if macddivdown ? na : 1
table.clear(statuswindow, 2, 8)
if histpivotup ? 1 : na
table.cell(statuswindow, 2, 9, text=tostring(histpivotupstatus), bgcolor=color.new(#00bcd4, 50), text_color=color.white, text_size=size.small)
if histpivotup ? na : 1
table.clear(statuswindow, 2, 9)
if histpivotdown ? 1 : na
table.cell(statuswindow, 2, 10, text=tostring(histpivotdownstatus), bgcolor=color.new(#e91e63, 50), text_color=color.white, text_size=size.small)
if histpivotdown ? na : 1
table.clear(statuswindow, 2, 10)
if macdcrosssignalup ? 1 : na
table.cell(statuswindow, 2, 11, text=tostring(macdcrosssignalupstatus), bgcolor=color.new(#00bcd4, 50), text_color=color.white, text_size=size.small)
if macdcrosssignalup ? na : 1
table.clear(statuswindow, 2, 11)
if macdcrosssignaldown ? 1 : na
table.cell(statuswindow, 2, 12, text=tostring(macdcrosssignaldownstatus), bgcolor=color.new(#e91e63, 50), text_color=color.white, text_size=size.small)
if macdcrosssignaldown ? na : 1
table.clear(statuswindow, 2, 12)
//Wave Trend Status
if wtdivup ? 1 : na
table.cell(statuswindow, 2, 13, text=tostring(wtdivupstatus), bgcolor=color.new(#00bcd4, 50), text_color=color.white, text_size=size.small)
if wtdivup ? na : 1
table.clear(statuswindow, 2, 13)
if wtdivdown ? 1 : na
table.cell(statuswindow, 2, 14, text=tostring(wtdivdownstatus), bgcolor=color.new(#e91e63, 50), text_color=color.white, text_size=size.small)
if wtdivdown ? na : 1
table.clear(statuswindow, 2, 14)
if wtcrosssignalup ? 1 : na
table.cell(statuswindow, 2, 15, text=tostring(wtcrosssignalupstatus), bgcolor=color.new(#00bcd4, 50), text_color=color.white, text_size=size.small)
if wtcrosssignalup ? na : 1
table.clear(statuswindow, 2, 15)
if wtcrosssignaldown ? 1 : na
table.cell(statuswindow, 2, 16, text=tostring(wtcrosssignaldownstatus), bgcolor=color.new(#e91e63, 50), text_color=color.white, text_size=size.small)
if wtcrosssignaldown ? na : 1
table.clear(statuswindow, 2, 16)
//Stochastic Status
if sdivup ? 1 : na
table.cell(statuswindow, 2, 17, text=tostring(sdivupstatus), bgcolor=color.new(#00bcd4, 50), text_color=color.white, text_size=size.small)
if sdivup ? na : 1
table.clear(statuswindow, 2, 17)
if sdivdown ? 1 : na
table.cell(statuswindow, 2, 18, text=tostring(sdivdownstatus), bgcolor=color.new(#e91e63, 50), text_color=color.white, text_size=size.small)
if sdivdown ? na : 1
table.clear(statuswindow, 2, 18)
if scrosssignalup ? 1 : na
table.cell(statuswindow, 2, 19, text=tostring(scrosssignalupstatus), bgcolor=color.new(#00bcd4, 50), text_color=color.white, text_size=size.small)
if scrosssignalup ? na : 1
table.clear(statuswindow, 2, 19)
if scrosssignaldown ? 1 : na
table.cell(statuswindow, 2, 20, text=tostring(scrosssignaldownstatus), bgcolor=color.new(#e91e63, 50), text_color=color.white, text_size=size.small)
if scrosssignaldown ? na : 1
table.clear(statuswindow, 2, 20)
//Volatility Status/////////////////////////////////////////////////////////////////
txt3 = "🡇 VOLATILITY 🡇"
table.cell(statuswindow, 1, 0, text=txt3, bgcolor=color.new(#000000, 50), text_color=color.white, text_size=size.small)
//Bollinger Bands Status
if bbcontup ? 1 : na
table.cell(statuswindow, 1, 1, text=tostring(bbcontupstatus), bgcolor=color.new(#00bcd4, 50), text_color=color.white, text_size=size.small)
if bbcontup ? na : 1
table.clear(statuswindow, 1, 1)
if bbcontup ? 1 : na
table.cell(statuswindow, 1, 2, text=tostring(bbcontdownstatus), bgcolor=color.new(#e91e63, 50), text_color=color.white, text_size=size.small)
if bbcontdown ? na : 1
table.clear(statuswindow, 1, 2)
//ATR Status
if atrrevup ? 1 : na
table.cell(statuswindow, 1, 3, text=tostring(atrrevupstatus), bgcolor=color.new(#00bcd4, 50), text_color=color.white, text_size=size.small)
if atrrevup ? na : 1
table.clear(statuswindow, 1, 3)
if atrrevdown ? 1 : na
table.cell(statuswindow, 1, 4, text=tostring(atrrevdownstatus), bgcolor=color.new(#e91e63, 50), text_color=color.white, text_size=size.small)
if atrrevdown ? na : 1
table.clear(statuswindow, 1, 4)
//RVI Status
if rviposup ? 1 : na
table.cell(statuswindow, 1, 5, text=tostring(rviposupstatus), bgcolor=color.new(#00bcd4, 50), text_color=color.white, text_size=size.small)
if rviposup ? na : 1
table.clear(statuswindow, 1, 5)
if rviposdown ? 1 : na
table.cell(statuswindow, 1, 6, text=tostring(rviposdownstatus), bgcolor=color.new(#e91e63, 50), text_color=color.white, text_size=size.small)
if rviposdown ? na : 1
table.clear(statuswindow, 1, 6)
if rvidivup ? 1 : na
table.cell(statuswindow, 1, 7, text=tostring(rvidivupstatus), bgcolor=color.new(#00bcd4, 50), text_color=color.white, text_size=size.small)
if rvidivup ? na : 1
table.clear(statuswindow, 1, 7)
if rvidivdown ? 1 : na
table.cell(statuswindow, 1, 8, text=tostring(rvidivdownstatus), bgcolor=color.new(#e91e63, 50), text_color=color.white, text_size=size.small)
if rvidivdown ? na : 1
table.clear(statuswindow, 1, 8)
//Support and Resistance Status
if srcrossup ? 1 : na
table.cell(statuswindow, 1, 9, text=tostring(srcrossupstatus), bgcolor=color.new(#00bcd4, 50), text_color=color.white, text_size=size.small)
if srcrossup ? na : 1
table.clear(statuswindow, 1, 9)
if srcrossdown ? 1 : na
table.cell(statuswindow, 1, 10, text=tostring(srcrossdownstatus), bgcolor=color.new(#e91e63, 50), text_color=color.white, text_size=size.small)
if srcrossdown ? na : 1
table.clear(statuswindow, 1, 10)
//Volume Status/////////////////////////////////////////////////////////////////
txt4 = "🡇 VOLUME 🡇"
table.cell(statuswindow, 0, 0, text=txt4, bgcolor=color.new(#000000, 50), text_color=color.white, text_size=size.small)
//On Balance Volume Status
if obvdivup ? 1 : na
table.cell(statuswindow, 0, 1, text=tostring(obvdivupstatus), bgcolor=color.new(#00bcd4, 50), text_color=color.white, text_size=size.small)
if obvdivup ? na : 1
table.clear(statuswindow, 0, 1)
if obvdivdown ? 1 : na
table.cell(statuswindow, 0, 2, text=tostring(obvdivdownstatus), bgcolor=color.new(#e91e63, 50), text_color=color.white, text_size=size.small)
if obvdivdown ? na : 1
table.clear(statuswindow, 0, 2)
//Chaikin Money Flow Status
if cmfcrossup ? 1 : na
table.cell(statuswindow, 0, 3, text=tostring(cmfcrossupstatus), bgcolor=color.new(#00bcd4, 50), text_color=color.white, text_size=size.small)
if cmfcrossup ? na : 1
table.clear(statuswindow, 0, 3)
if cmfcrossdown ? 1 : na
table.cell(statuswindow, 0, 4, text=tostring(cmfcrossdownstatus), bgcolor=color.new(#e91e63, 50), text_color=color.white, text_size=size.small)
if cmfcrossdown ? na : 1
table.clear(statuswindow, 0, 4)
if cmflevup ? 1 : na
table.cell(statuswindow, 0,5, text=tostring(cmflevupstatus), bgcolor=color.new(#00bcd4, 50), text_color=color.white, text_size=size.small)
if cmflevdown ? 1 : na
table.cell(statuswindow, 0, 5, text=tostring(cmflevdownstatus), bgcolor=color.new(#e91e63, 50), text_color=color.white, text_size=size.small)
//VWAP Status
if vwapcrossup ? 1 : na
table.cell(statuswindow, 0, 6, text=tostring(vwapcrossupstatus), bgcolor=color.new(#00bcd4, 50), text_color=color.white, text_size=size.small)
if vwapcrossup ? na : 1
table.clear(statuswindow, 0, 6)
if vwapcrossdown ? 1 : na
table.cell(statuswindow, 0, 7, text=tostring(vwapcrossdownstatus), bgcolor=color.new(#e91e63, 50), text_color=color.white, text_size=size.small)
if vwapcrossdown ? na : 1
table.clear(statuswindow, 0, 7)
if vwaptrendup ? 1 : na
table.cell(statuswindow, 0,8, text=tostring(vwaptrendupstatus), bgcolor=color.new(#00bcd4, 50), text_color=color.white, text_size=size.small)
if vwaptrenddown ? 1 : na
table.cell(statuswindow, 0, 8, text=tostring(vwaptrenddownstatus), bgcolor=color.new(#e91e63, 50), text_color=color.white, text_size=size.small)
//Candle Pattern Status
if bulleng ? 1 : na
table.cell(statuswindow, 0, 9, text=tostring(bullengstatus), bgcolor=color.new(#00bcd4, 50), text_color=color.white, text_size=size.small)
if bulleng ? na : 1
table.clear(statuswindow, 0, 9)
if beareng ? 1 : na
table.cell(statuswindow, 0, 10, text=tostring(bearengstatus), bgcolor=color.new(#e91e63, 50), text_color=color.white, text_size=size.small)
if beareng ? na : 1
table.clear(statuswindow, 0, 10)
//END▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
////////////////////////////////////////////////////////////////////////////////
//STOP LOSS WARNINGS▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼
//Stop Loss Criteria
longstoploss = strategy.position_avg_price * (1 + stoplosspercent)
shortstoploss = strategy.position_avg_price * (1 - stoplosspercent)
printstoplong = longstoploss > close and longstoploss[1] < close[1] and strategy.position_size > 0
printstopshort = shortstoploss < close and shortstoploss[1] > close[1] and strategy.position_size < 0
//Stop Loss Lines
plot(strategy.position_size > 0 ? longstoploss : na, style=plot.style_line, color=color.new(color.yellow, 50), linewidth=1, title="Stop Long Line", display=display.none)
plot(strategy.position_size < 0 ? shortstoploss : na, style=plot.style_line, color=color.new(color.yellow, 50), linewidth=1, title="Stop Short Line", display=display.none)
//Stop Loss Labels
plotshape(printstoplong, title="Stop Long Label", style=shape.labelup, location=location.belowbar, color=color.yellow, text="𝐒𝐓𝐎𝐏", textcolor=color.black, size=size.tiny)
plotshape(printstopshort, title="Stop Short Label", style=shape.labeldown, location=location.abovebar, color=color.yellow, text="𝐒𝐓𝐎𝐏", textcolor=color.black, size=size.tiny)
//Alerts
ttbuystring = "Input your custom alert message here. In the Alert settings, choose \"Neural Network\" and \"Alert() functionc calls only\"\nIf you're using a 3Commas Bot, make sure to format your message correctly with forward slashes in front of each quotation, you can find videos about how to do this on YouTube. Or ask 3Commas support about how to format the message for PineScript."
ttsellstring = "Input your custom alert message here. In the Alert settings, choose \"Neural Network\" and \"Alert() functionc calls only\"\nIf you're using a 3Commas Bot, make sure to format your message correctly with forward slashes in front of each quotation, you can find videos about how to do this on YouTube. Or ask 3Commas support about how to format the message for PineScript."
ttstopstring = "Input your custom alert message here. In the Alert settings, choose \"Neural Network\" and \"Alert() functionc calls only\"\nIf you're using a 3Commas Bot, make sure to format your message correctly with forward slashes in front of each quotation, you can find videos about how to do this on YouTube. Or ask 3Commas support about how to format the message for PineScript."
usebuyalert = input(defval=true, title="Use BUY Alert", group="Alert Messages")
//buystring = input(title="Buy Alert Message", defval="ENTER-LONG_OKEX-FUTURES_LINK-USDT-220805_my-trading-view_10M_80eba43b2348716e", type=input.string, confirm=false, group="Alert Messages", tooltip=ttbuystring)
buystring = "ENTER-LONG_BYBIT_LINKUSDT_mybybite-bot_10M_403d210eb46a9bd3"
usesellalert = input(defval=true, title="Use SELL Alert", group="Alert Messages")
//sellstring = input(title="Sell Alert Message", defval="ENTER-SHORT_OKEX-FUTURES_LINK-USDT-220805_my-trading-view_10M_80eba43b2348716e", type=input.string, confirm=false, group="Alert Messages", tooltip=ttsellstring)
sellstring = "ENTER-SHORT_BYBIT_LINKUSDT_mybybite-bot_10M_403d210eb46a9bd3"
usestopalert = input(defval=true, title="Use STOP Alert", group="Alert Messages")
stopstring = input(title="Stop Alert Message", defval="CLOSE", type=input.string, confirm=false, group="Alert Messages", tooltip=ttstopstring)
//buystring = "ENTER-LONG_BYBIT_LINKUSDT_mybybite-bot_10M_403d210eb46a9bd3"
//sellstring = "ENTER-SHORT_BYBIT_LINKUSDT_mybybite-bot_10M_403d210eb46a9bd3"
var LongPos = true
var ShortPos= true
//*********************************************************************************************************
// shooroe cod haye indicatore cci_s.....
source = input(close)
cci_period = input(20, "CCI Period")
stoch_period = input(20, "Stoch Period")
stoch_smooth_k = input(7, "Stoch Smooth K")
stoch_smooth_d = input(3, "Stoch Smooth D")
d_or_k = input(defval="D", options=["D", "K"])
OB = input(80, "Overbought", type=input.integer)
OS = input(20, "Oversold", type=input.integer)
midline= input(50, "Mid line", type=input.integer)
showArrows = input(true, "Show Arrows")
showArrowsEnter = input(true, "Show Arrows on Enter zone")
showArrowsCenter = input(false, "Show Arrows on Center zone")
showArrowsExit = input(true, "Show Arrows on Exit zone")
cci = cci(source, cci_period)
stoch_cci_k = sma(stoch(cci, cci, cci, stoch_period), stoch_smooth_k)
stoch_cci_d = sma(stoch_cci_k, stoch_smooth_d)
ma = (d_or_k == "D") ? stoch_cci_d : stoch_cci_k
trend_enter = if showArrowsEnter
if crossunder(ma, OS)
1
else
if crossover(ma, OB)
-1
//plot(trend_enter, title="trend_enter", transp=100)
trend_exit = if showArrowsExit
if crossunder(ma, OB)
-1
else
if crossover(ma, OS)
1
trend_center = if showArrowsCenter
if crossunder(ma, 50)
-1
else
if crossover(ma, 50)
1
// plot the OB and OS level
overbought = hline(OB, title="Upper Line", linestyle=hline.style_solid, linewidth=1, color=color.red)
oversold = hline(OS, title="Lower Line", linestyle=hline.style_solid, linewidth=1, color=color.lime)
band2 = hline(50, title="Mid Line", linestyle=hline.style_solid, linewidth=1, color=color.gray)
// Plot the moving average
//ma_color = ma > OB ? color.red : ma < OS ? color.green : color.gray
//plot(ma, "Moving Average", linewidth=3, color=ma_color, transp=0)
maxLevelPlot = hline(100, title="Max Level", linestyle=hline.style_dotted, color=color.new(color.white, 100))
minLevelPlot = hline(0, title="Min Level", linestyle=hline.style_dotted, color=color.new(color.white, 100))
//overbought = hline(OB, title="Hline Overbought", linestyle=hline.style_solid, color=color.new(color.white, 100))
//oversold = hline(OS, title="Hline Oversold", linestyle=hline.style_solid, color=color.new(color.white, 100))
color_fill_os = ma > OB ? color.new(color.red,80) : color.new(color.white, 100) // Short
ShortFlage = ma > OB ? 1 : 0 // Short
color_fill_ob = ma < OS ? color.new(color.green,80) : color.new(color.white, 100) // Long
LongFlage= ma < OS ? 1 : 0 // Long
fill(maxLevelPlot, overbought, color=color_fill_os) // Short
fill(minLevelPlot, oversold, color=color_fill_ob) // Long
//table.cell(LongPos, 1, 0, text=" LONG ", bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(LongPos, 2, 0, text=" SHORT", bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(LongPos, 1, 1, text=tostring(barssince(LongFlage==1)), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(LongPos, 2, 1, text=tostring(barssince(ShortFlage==1)), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
if open[1]-close[1]> 0 and open[1]-close[1]> 0.15
LongFlage=0
if open[1]-close[1]> 0 and open[1]-close[1]> 0.15
ShortFlage=0
if close[1]-open[1]> 0 and close[1]-open[1]> 0.15
LongFlage=0
if close[1]-open[1]> 0 and close[1]-open[1]> 0.15
ShortFlage=0
//close_Long_pos= color_fill_ob == "white" ? 1 : 0
//close_Short_pos= color_fill_os == "white" ? 1 : 0
//if close_Long_pos
// alert("exitLONGstring", alert.freq_once_per_bar)
//if close_Short_pos
// alert(exitSHORTstring, alert.freq_once_per_bar)
// Show the arrows
// Trend Enter
//plotshape((showArrows and showArrowsEnter and trend_enter == 1) ? 0 : na, color=color.green, transp=20, style=shape.arrowup, size=size.normal, location=location.absolute, title="Trend Enter Buy")
//plotshape((showArrows and showArrowsEnter and trend_enter == -1) ? 100 : na, color=color.red, transp=20, style=shape.arrowdown, size=size.normal, location=location.absolute, title="Trend Enter Sell")
// Trend Center
//plotshape((showArrows and showArrowsCenter and trend_center == 1) ? 35 : na, color=color.aqua, transp=20, style=shape.arrowup, size=size.normal, location=location.absolute, title="Trend Center Buy")
//plotshape((showArrows and showArrowsCenter and trend_center == -1) ? 65 : na, color=color.fuchsia, transp=20, style=shape.arrowdown, size=size.normal, location=location.absolute, title="Trend Center Sell")
// Trend Exit
//plotshape((showArrows and showArrowsExit and trend_exit == 1) ? 0 : na, color=color.orange, transp=20, style=shape.arrowup, size=size.normal, location=location.absolute, title="Trend Exit Buy")
//plotshape((showArrows and showArrowsExit and trend_exit == -1) ? 100 : na, color=color.maroon, transp=20, style=shape.arrowdown, size=size.normal, location=location.absolute, title="Trend Exit Sell")
//***************************************** RSI,16 EMA,50 LongFlage & ShortFlage #2 is set here ****************************************************************
LongFL2() =>
//src = close
//len21 = input(16, minval=1, title="RSI Length")
//len22 = input(50, minval=1, title="EMA of RSI Length")
up11 = rma(max(change(close), 0), 20)
down11 = rma(-min(change(close), 0), 20)
rsi11 = down11 == 0 ? 100 : up11 == 0 ? 0 : 100 - (100 / (1 + up11 / down11))
emaRSI11 = ema(rsi11,40)
rsi55 = rsi(close, 14)
k55 = sma(stoch(rsi55, rsi55, rsi55, 14), 3)
d55 = sma(k55, 3)
rsi11+1.8 > emaRSI11 ? 1 : 0
ShortFL2() =>
//src = close
//len21 = input(16, minval=1, title="RSI Length")
//len22 = input(50, minval=1, title="EMA of RSI Length")
up11 = rma(max(change(close), 0), 20)
down11 = rma(-min(change(close), 0), 20)
rsi11 = down11 == 0 ? 100 : up11 == 0 ? 0 : 100 - (100 / (1 + up11 / down11))
emaRSI11 = ema(rsi11,40)
rsi55 = rsi(close, 14)
k55 = sma(stoch(rsi55, rsi55, rsi55, 14), 3)
d55 = sma(k55, 3)
rsi11-1.8 < emaRSI11 ? 1 : 0
//LongFlage2= barssince(crossover(rsi11,emaRSI11)) < barssince(crossunder(rsi11,emaRSI11)) and rsi11-emaRSI11>1.5 and k55>d55 ? 1 : 0 // LongFlage #2
//ShortFlage2= barssince(crossunder(rsi11,emaRSI11)) < barssince(crossover(rsi11,emaRSI11)) and emaRSI11-rsi11>1.5 and d55>k55? 1 : 0 // ShortFlage #2
//LongFlage2= rsi11+1.8 > emaRSI11 ? 1 : 0 // LongFlage #2
//ShortFlage2= rsi11-1.8 < emaRSI11 ? 1 : 0 // ShortFlage #2
//*********************************************************************** END *****************************************************************************
//***************************************** Crossing of RSI,12 EMA,12 PLUSE Crossing fo Stoch-Rsi 14,3,3) ---> LongFlage & ShortFlage #3 is set here ****************************************************************
LongFL3() =>
//len21 = input(16, minval=1, title="RSI Length")
//len22 = input(50, minval=1, title="EMA of RSI Length")
up22 = rma(max(change(close), 0), 12)
down22 = rma(-min(change(close), 0), 12)
rsi22 = down22 == 0 ? 100 : up22 == 0 ? 0 : 100 - (100 / (1 + up22 / down22))
emaRSI22 = ema(rsi22,12)
rsi33 = rsi(close, 14)
k33 = sma(stoch(rsi33, rsi33, rsi33, 14), 3)
d33 = sma(k33, 3)
StochRsiUP = k33>d33 ? 1 : 0
StochRsiDOWN = k33<d33 ? 1 : 0
StochRsiUpSignal = StochRsiUP and barssince(crossover(k33,d33)) < barssince(crossunder(k33,d33)) and barssince(crossover(k33,d33)) <3 and k33-d33>0.7 ? 1 : 0//and d33<40 ? 1 : 0
StochRsiDownSignal = StochRsiDOWN and barssince(crossunder(k33,d33)) < barssince(crossover(k33,d33)) and barssince(crossunder(k33,d33)) <3 and d33-k33>0.7 ? 1 : 0//and k33 > 60 ? 1 : 0
RsiMa1212UP= rsi22>emaRSI22 ? 1:0
RsiMa1212DOWN= rsi22<emaRSI22 ? 1:0
RsiMa1212UpSignal = RsiMa1212UP and barssince(crossover(rsi22,emaRSI22)) < barssince(crossunder(rsi22,emaRSI22)) and barssince(crossover(rsi22,emaRSI22)) <3 and rsi22-emaRSI22>0.7 ? 1 : 0//and d33<40 ? 1 : 0
RsiMa1212DownSignal = RsiMa1212DOWN and barssince(crossunder(rsi22,emaRSI22)) < barssince(crossover(rsi22,emaRSI22)) and barssince(crossunder(rsi22,emaRSI22)) <3 and emaRSI22-rsi22>0.7 ? 1 : 0//and k33 > 60 ? 1 : 0
StochRsiUpSignal and RsiMa1212UpSignal ? 1 : 0 // LongFlage #3
ShortFL3() =>
//len21 = input(16, minval=1, title="RSI Length")
//len22 = input(50, minval=1, title="EMA of RSI Length")
up22 = rma(max(change(close), 0), 12)
down22 = rma(-min(change(close), 0), 12)
rsi22 = down22 == 0 ? 100 : up22 == 0 ? 0 : 100 - (100 / (1 + up22 / down22))
emaRSI22 = ema(rsi22,12)
rsi33 = rsi(close, 14)
k33 = sma(stoch(rsi33, rsi33, rsi33, 14), 3)
d33 = sma(k33, 3)
StochRsiUP = k33>d33 ? 1 : 0
StochRsiDOWN = k33<d33 ? 1 : 0
StochRsiUpSignal = StochRsiUP and barssince(crossover(k33,d33)) < barssince(crossunder(k33,d33)) and barssince(crossover(k33,d33)) <3 and k33-d33>0.7 ? 1 : 0//and d33<40 ? 1 : 0
StochRsiDownSignal = StochRsiDOWN and barssince(crossunder(k33,d33)) < barssince(crossover(k33,d33)) and barssince(crossunder(k33,d33)) <3 and d33-k33>0.7 ? 1 : 0//and k33 > 60 ? 1 : 0
RsiMa1212UP= rsi22>emaRSI22 ? 1:0
RsiMa1212DOWN= rsi22<emaRSI22 ? 1:0
RsiMa1212UpSignal = RsiMa1212UP and barssince(crossover(rsi22,emaRSI22)) < barssince(crossunder(rsi22,emaRSI22)) and barssince(crossover(rsi22,emaRSI22)) <3 and rsi22-emaRSI22>0.7 ? 1 : 0//and d33<40 ? 1 : 0
RsiMa1212DownSignal = RsiMa1212DOWN and barssince(crossunder(rsi22,emaRSI22)) < barssince(crossover(rsi22,emaRSI22)) and barssince(crossunder(rsi22,emaRSI22)) <3 and emaRSI22-rsi22>0.7 ? 1 : 0//and k33 > 60 ? 1 : 0
StochRsiDownSignal and RsiMa1212DownSignal ? 1 : 0 // ShortFlage #3
//LongFlage3= barssince(crossover(rsi22,emaRSI22)) < barssince(crossunder(rsi22,emaRSI22)) and barssince(crossover(rsi22,emaRSI22))<3 and StochRsiUP ? 1 : 0 // LongFlage #3
//ShortFlage3= barssince(crossunder(rsi22,emaRSI22)) < barssince(crossover(rsi22,emaRSI22)) and barssince(crossunder(rsi22,emaRSI22))<3 and StochRsiDOWN ? 1 : 0 // ShortFlage #3
//LongFlage3= rsi22 > emaRSI22 ?1 : 0 // LongFlage #3
//ShortFlage3= rsi22 < emaRSI22 ? 1 : 0 // ShortFlage #3
//table.cell(LongPos, 1, 3, text=tostring(LongFlage3), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(LongPos, 2, 3, text=tostring(ShortFlage3), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//*********************************************************************** END *****************************************************************************
//***************************************** Crossing of CCI 10 with, EMA 5 of CCI 20 ---> LongFlage & ShortFlage #4 is set here ****************************************************************
LongFL4() =>
cci4410= cci(close,10)
cci4420= cci(close,20)
emacci4420= ema(cci4420,5)
//Cci4410EmaCci4420Up = emacci4420>cci4410 and barssince(crossover(emacci4420,cci4410)<3 ?1 :0
cci4410>emacci4420 and barssince(crossover(cci4410,emacci4420))<barssince(crossunder(cci4410,emacci4420)) and barssince(crossover(cci4410,emacci4420))<3 ?1 :0
ShortFL4() =>
cci4410= cci(close,10)
cci4420= cci(close,20)
emacci4420= ema(cci4420,5)
//Cci4410EmaCci4420Up = emacci4420>cci4410 and barssince(crossover(emacci4420,cci4410)<3 ?1 :0
emacci4420>cci4410 and barssince(crossunder(cci4410,emacci4420))<barssince(crossover(cci4410,emacci4420)) and barssince(crossunder(cci4410,emacci4420))<3 ?1 :0
//*********************************************************************** END *****************************************************************************
//***************************************** HALFTREND & RSI 83,17 LongFlage & ShortFlage #5 is set here ****************************************************************
amplitude22 =1// input(title="Amplitude", defval=2)
channelDeviation22 =2 //input(title="Channel Deviation", defval=2)
//showArrows22 = input(title="Show Arrows", defval=true)
//showChannels22 = input(title="Show Channels", defval=true)
var int trend = 0
var int nextTrend = 0
var float maxLowPrice = nz(low[1], low)
var float minHighPrice = nz(high[1], high)
var float up = 0.0
var float down = 0.0
float atrHigh = 0.0
float atrLow = 0.0
float arrowUp = na
float arrowDown = na
atr2 = atr(100) / 2
dev22 = channelDeviation22 * atr2
highPrice = high[abs(highestbars(amplitude22))]
lowPrice = low[abs(lowestbars(amplitude22))]
highma = sma(high, amplitude22)
lowma = sma(low, amplitude22)
if nextTrend == 1
maxLowPrice := max(lowPrice, maxLowPrice)
if highma < maxLowPrice and close < nz(low[1], low)
trend := 1
nextTrend := 0
minHighPrice := highPrice
else
minHighPrice := min(highPrice, minHighPrice)
if lowma > minHighPrice and close > nz(high[1], high)
trend := 0
nextTrend := 1
maxLowPrice := lowPrice
if trend == 0
if not na(trend[1]) and trend[1] != 0
up := na(down[1]) ? down : down[1]
arrowUp := up - atr2
else
up := na(up[1]) ? maxLowPrice : max(maxLowPrice, up[1])
atrHigh := up + dev22
atrLow := up - dev22
else
if not na(trend[1]) and trend[1] != 1
down := na(up[1]) ? up : up[1]
arrowDown := down + atr2
else
down := na(down[1]) ? minHighPrice : min(minHighPrice, down[1])
atrHigh := down + dev22
atrLow := down - dev22
ht = trend == 0 ? up : down
var color buyColor = color.blue
var color sellColor = color.red
htColor = trend == 0 ? buyColor : sellColor
//htPlot = plot(ht, title="HalfTrend", linewidth=2, color=htColor)
buySignal55 = not na(arrowUp) and (trend == 0 and trend[1] == 1)
sellSignal55 = not na(arrowDown) and (trend == 1 and trend[1] == 0)
halfTrend= barssince(buySignal55)>=0 and barssince(buySignal55) < barssince(sellSignal55) ? "Blue" : "Red" /// 1= Long , 0= Short
//LongFlage5= crossunder(rsi66,30) and barssince(buySignal55)>0 and barssince(buySignal55) < barssince(sellSignal55) ? 1 :0
//ShortFlage5= crossover(rsi66,70) and barssince(sellSignal55)>0 and barssince(sellSignal55) < barssince(buySignal55) ? 1 :0
//LongFlage5= (rsi66<30 and barssince(buySignal55)>0 and barssince(buySignal55) < barssince(sellSignal55)) ? 1 :0 // khate Abi
//ShortFlage5= (rsi66>70 and barssince(sellSignal55)>0 and barssince(sellSignal55) < barssince(buySignal55)) ? 1 :0 //khate Ghermez
//LongFlage5= (shekasteRSItop and shekastCCItop and barssince(buySignal55)>0 and barssince(buySignal55) < barssince(sellSignal55)) ? 1 :0 // khate Abi
//ShortFlage5= (shekasteRSIkaf and shekastCCIkaf and barssince(sellSignal55)>0 and barssince(sellSignal55) < barssince(buySignal55)) ? 1 :0 //khate Ghermez
SHcciTop() =>
rsi66 = rsi(close,2)
rsi661 = rsi(close[1],2)
cci66= cci(close,2) // 5 bod
cci77 = open[0] > close[0] ? open[0]-close[0]>0.2 ? cci66+25 : 0 : close[0]-open[0]>0.2 ? cci66-25 : 0 // cci taghir yafteh bedelile candle bozorge
// tashkise shekaste CCI 5 dar zire -155 va balaye 155
finalCCi= cci77==0 ? cci66 : cci77
cci07=cci(close[0],2)
cci17=cci(close[1],2)
cci27=cci(close[2],2)
maCCI=ema(cci07,2)
crossunder(cci07,maCCI) and cci17>55 and finalCCi==cci66 ? 1 : 0
SHcciKaf() =>
rsi66 = rsi(close,2)
rsi661 = rsi(close[1],2)
cci66= cci(close,2) // 5 bod
cci77 = open[0] > close[0] ? open[0]-close[0]>0.2 ? cci66+25 : 0 : close[0]-open[0]>0.2 ? cci66-25 : 0 // cci taghir yafteh bedelile candle bozorge
// tashkise shekaste CCI 5 dar zire -155 va balaye 155
finalCCi= cci77==0 ? cci66 : cci77
cci07=cci(close[0],2)
cci17=cci(close[1],2)
cci27=cci(close[2],2)
maCCI=ema(cci07,2)
crossover(cci07,maCCI) and cci17<-55 and finalCCi==cci66 ? 1:0
SHrsiTop() =>
rsi07=cci(close[0],2)
rsi17=cci(close[1],2)
rsi27=cci(close[2],2)
maRSI=ema(rsi07,2)
crossunder(rsi07,maRSI) and rsi17>65 ? 1 : 0
SHrsiKaf() =>
rsi07=cci(close[0],2)
rsi17=cci(close[1],2)
rsi27=cci(close[2],2)
maRSI=ema(rsi07,2)
crossover(rsi07,maRSI) and rsi17<35 ? 1 : 0
LongFL5() =>
SHrsiKaf() and SHcciKaf() and barssince(buySignal55)>0 and barssince(buySignal55) < barssince(sellSignal55) ?1 : 0 // khate Abi
ShortFL5() =>
SHrsiTop() and SHcciTop() and barssince(sellSignal55)>0 and barssince(sellSignal55) < barssince(buySignal55) ? 1 :0 //khate Ghermez
//LongFlage5= (shekasteRSIkaf and shekastCCIkaf and barssince(buySignal55)>0 and barssince(buySignal55) < barssince(sellSignal55)) ? 1 :0 // khate Abi
//ShortFlage5= (shekasteRSItop and shekastCCItop and barssince(sellSignal55)>0 and barssince(sellSignal55) < barssince(buySignal55)) ? 1 :0 //khate Ghermez
LongFL6() =>
rsi661 = rsi(close[1],2)
rsi661<33 and SHcciKaf() ?1 :0
ShortFL6() =>
rsi661 = rsi(close[1],2)
rsi661>67 and SHcciTop()
//LongFlage6= rsi661<33 and shekastCCIkaf ? 1 :0
//ShortFlage6= rsi661>67 and shekastCCItop ? 1 :0
///
//Long5() =>
//*********************************************************************** END *****************************************************************************
//if rsi(close,14) < wma(rsi(14),14)
// LongFlage=0
// if open[1]<close[1] and close[1]-open[1]>0.08
// alert("OK", )
//buystring = "wrong buy"
longentry0=longentry and longpositions and usebuyalert ? 1 :0
shortentry0=shortentry and shortpositions and usesellalert ?1 :0
FinalLongSignal() =>
//FinalLongSignal1 = (longentry0 and LongFlage2 and LongFlage3 ) ? 1:0 // 54% sod ba dowm 42%
//FinalLongSignal2 = longentry0 and LongFlage3 and not ShortFlage5 ? 1 : 0
//FinalLongSignal3 = (weaklongentrysignal and LongFlage and LongFlage2 and LongFlage3) and not ShortFlage5 ? 1: 0
//FinalLongSignal4 = (weaklongentrysignal and LongFlage3) and not ShortFlage5 ? 1: 0
//FinalLongSignal5 = (longentry0 and LongFlage4 and LongFlage3) and not ShortFlage5 ? 1:0
//FinalLongSignal6 = (weaklongentrysignal and LongFlage4 and LongFlage3) and not ShortFlage5 ? 1: 0
(LongFL5() or LongFL2()) or LongFL6()//((LongFlage5 and LongFlage2) or LongFlage6) and not weakshortentrysignal ? 1: 0
//FinalLongSignal7 = LongFlage5 ? 1: 0
//FinalLongSignal8 = ((longentry0 or weaklongentrysignal) and LongFlage4 and LongFlage2 and LongFlage3) ?1:0 //and not ShortFlage5 ? 1:0
//FinalLongSignal= (FinalLongSignal1 or FinalLongSignal2 or FinalLongSignal3 or FinalLongSignal4 or FinalLongSignal5 or FinalLongSignal6
// or FinalLongSignal7 or FinalLongSignal8) //and rsi66<70 //? 1 : 0
//FinalLongSignal= FinalLongSignal7
//FinalLongSignal= FinalLongSignal8//FinalLongSignal5 or FinalLongSignal6 and rsi66<70 //? 1 : 0
FinalShortSignal() =>
//FinalShortSignal1 = (shortentry0 and ShortFlage2 and ShortFlage3) ? 1 : 0
//FinalShortSignal2 = (shortentry0 and ShortFlage3) and not LongFlage5 ? 1 : 0
//FinalShortSignal3 = (weakshortentrysignal and ShortFlage and ShortFlage2 and ShortFlage3) and not LongFlage5 ? 1 : 0
//FinalShortSignal4 = (weakshortentrysignal and ShortFlage3) and not LongFlage5 ? 1 : 0
//FinalShortSignal5 = (shortentry0 and ShortFlage4 and ShortFlage3) and not LongFlage5 ? 1 : 0
//FinalShortSignal6 = (weakshortentrysignal and ShortFlage4 and ShortFlage3) and not LongFlage5 ? 1 : 0
(ShortFL5() and ShortFL2()) or ShortFL6()//((ShortFlage5 and ShortFlage2 ) or ShortFlage6) and not weaklongentrysignal ? 1 : 0
//FinalShortSignal7 = ShortFlage5 ? 1 : 0
//FinalShortSignal8 = ((shortentry0 or weakshortentrysignal)and ShortFlage4 and ShortFlage2 and ShortFlage3) ?1:0//and not LongFlage5 ? 1 : 0
//FinalShortSignal = (FinalShortSignal1 or FinalShortSignal2 or FinalShortSignal3 or FinalShortSignal4 or FinalShortSignal5 or FinalShortSignal6
// or FinalShortSignal7 or FinalShortSignal8)// and rsi66>30 //? 1 :0
//FinalShortSignal = FinalShortSignal7
//FinalShortSignal = FinalShortSignal5 or FinalShortSignal6 and rsi66>30//? 1 :0
//FinalShortSignal = FinalShortSignal8
//********************************************************* EXIT ************************************************************
ExitLong() =>
rsi44 = rsi(close, 21)
k44 = ema(stoch(rsi44, rsi44, rsi44, 21), 3)
d44 = ema(k44, 3)
//ExitLong=crossover(ma,70) ? 1:0 //midline=57
weakshortentrysignal and k44<d44 ? 1 : 0 //and FinalLongSignal!=1 ? 1:0 //midline=57
//ExitLong = weakshortentrysignal and crossunder(k44,d44) and d44>60 ?1:0 //k44<d44 ? 1:0 //midline=57
//if open[0] > close[0]
ExitShort() =>
rsi44 = rsi(close, 21)
k44 = ema(stoch(rsi44, rsi44, rsi44, 21), 3)
d44 = ema(k44, 3)
//ExitShort= crossunder(ma,30) ? 1:0 //midline=43
weaklongentrysignal and k44>d44 ? 1: 0 //and FinalShortSignal!=1 ? 1:0 //midline=43
//ExitShort = weaklongentrysignal and crossover(k44,d44) and d44<40 ?1:0 //k44>d44 ? 1:0 //midline=43
//ExitShort = (rsi661<8 and shekastCCIkaf) or buySignal55//and finalCCi<-150 ? 1:0 //midline=43 // for halfTrend exit
EnterLong() =>
alert("EXIT-SHORT_BYBIT_LINKUSDT_mybybite-bot_10M_403d210eb46a9bd3", alert.freq_once_per_bar)
alert(buystring, alert.freq_once_per_bar)
LongPos = true
ShortPos= false
strategy.entry("LONG",1)
EnterShort() =>
alert("EXIT-LONG_BYBIT_LINKUSDT_mybybite-bot_10M_403d210eb46a9bd3", alert.freq_once_per_bar)
alert(sellstring, alert.freq_once_per_bar)
ShortPos= true
LongPos = false
strategy.entry("SHORT",0)
ExitPos() =>
if ExitLong() and not FinalLongSignal() //and LongPos
alert("EXIT-LONG_BYBIT_LINKUSDT_mybybite-bot_10M_403d210eb46a9bd3", alert.freq_once_per_bar)
LongPos = false
strategy.close("LONG",1)
//if ExitLong and not //and LongPos
// strategy.close("LONG",1)
if ExitShort() and not FinalShortSignal() //and ShortPos
alert("EXIT-SHORT_BYBIT_LINKUSDT_mybybite-bot_10M_403d210eb46a9bd3", alert.freq_once_per_bar)
ShortPos = false
strategy.close("SHORT",1)
//if ExitShort //and ShortPos
// strategy.close("SHORT",1)
//if rsi66>92
// alert("EXIT-LONG_BYBIT_LINKUSDT_mybybite-bot_10M_403d210eb46a9bd3", alert.freq_once_per_bar)
//********************************************************************************************************************************
//if FinalLongSignal==FinalShortSignal
// FinalLongSignal=0
// FinalShortSignal=0
//if ExitLong==ExitShort
// ExitLong=0
// ExitShort=0
//ExitPos()
if FinalLongSignal() and not ExitLong() //and not FinalShortSignal() // FinalLongSignal1 or FinalLongSignal2 or FinalLongSignal3 or FinalLongSignal4
EnterLong()
//strategy.entry("LONG",1,1,2,strategy.position_avg_price-0.50)
//if FinalLongSignal and not FinalShortSignal
// strategy.entry("LONG",1)
// LongPos = true
if FinalShortSignal() and not ExitShort() //and not FinalLongSignal()//FinalShortSignal1 or FinalShortSignal2 or FinalShortSignal3 or FinalShortSignal4
EnterShort()
ExitPos()
// strategy.entry("SHORT",0,1,2,strategy.position_avg_price+0.50)
//if FinalShortSignal and not FinalLongSignal
// strategy.entry("SHORT",0)
//if (longentry and longpositions and usebuyalert and LongFlage and LongFlage2) or (longentry and longpositions and usebuyalert and LongFlage3) or (weaklongentrysignal and LongFlage and LongFlage2 )
// alert(buystring, alert.freq_once_per_bar)
//if (shortentry and shortpositions and usesellalert and ShortFlage and ShortFlage2 ) or (shortentry and shortpositions and usesellalert and ShortFlage3 ) or (weakshortentrysignal and ShortFlage and ShortFlage2 )
// alert(sellstring, alert.freq_once_per_bar)
//if printstoplong or printstopshort and usestopalert
// alert(stopstring, alert.freq_once_per_bar)
//*********************************************************************** جدول وضعیت *****************************************************************************
var table LongPoss = table.new(position.bottom_center, 100, 100, border_width=2)
//table.cell(LongPoss, 0, 0, text=" ", bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(LongPoss, 0, 1, text="STOCH-RSI", bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(LongPoss, 0, 2, text="RSI-MA 12,12", bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(LongPoss, 0, 3, text="Long Flage #5", bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(LongPoss, 0, 4, text="Short Flage #5", bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(LongPoss, 0, 5, text="Final Long Entery", bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(LongPoss, 0, 6, text="Final Short Entery", bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(LongPoss, 1, 0, text="UP", bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(LongPoss, 2, 0, text="DOWN", bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(LongPoss, 3, 0, text="UP Signal", bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(LongPoss, 4, 0, text="DOWN Signal", bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(LongPoss, 5, 0, text="Bars Since Crossed UP", bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(LongPoss, 6, 0, text="Bars Since Crossed DOWN", bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(LongPoss, 1, 1, text=tostring(StochRsiUP), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(LongPoss, 1, 2, text=tostring(RsiMa1212UP), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(LongPoss, 2, 1, text=tostring(StochRsiDOWN), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(LongPoss, 2, 2, text=tostring(RsiMa1212DOWN), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(LongPoss, 3, 1, text=tostring(StochRsiUpSignal), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(LongPoss, 3, 2, text=tostring(RsiMa1212UpSignal), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(LongPoss, 4, 1, text=tostring(StochRsiDownSignal), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(LongPoss, 4, 2, text=tostring(RsiMa1212DownSignal), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(LongPoss, 5, 1, text=tostring(barssince(crossover(k33,d33))), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(LongPoss, 5, 2, text=tostring(barssince(crossover(rsi22,emaRSI22))), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(LongPoss, 6, 1, text=tostring(barssince(crossunder(k33,d33))), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(LongPoss, 6, 2, text=tostring(barssince(crossunder(rsi22,emaRSI22))), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(LongPoss, 3, 3, text=tostring(LongFlage5), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(LongPoss, 4, 4, text=tostring(ShortFlage5), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(LongPoss, 3, 5, text=tostring(FinalLongSignal), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(LongPoss, 4, 6, text=tostring(FinalShortSignal), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//************************************************************************************************************************************************************************
var table Pos = table.new(position.top_right, 100, 100, border_width=2)
table.cell(Pos, 0, 0, text="RSI 66 ", bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(Pos, 0, 1, text="Final Long Signal # 1", bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(Pos, 0, 2, text="Final Long Signal # 2", bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(Pos, 0, 3, text="Final Long Signal # 3", bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(Pos, 0, 4, text="Final Long Signal # 4", bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(Pos, 0, 5, text="Final Long Signal # 5", bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(Pos, 0, 6, text="Final Long Signal # 6", bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
table.cell(Pos, 0, 7, text="Final Long Signal ", bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(Pos, 0, 6, text="Final Short Signal # 1", bgcolor=color.new(color.red, 50), text_color=color.white, text_size=size.small)
//table.cell(Pos, 0, 7, text="Final Short Signal # 2", bgcolor=color.new(color.red, 50), text_color=color.white, text_size=size.small)
//table.cell(Pos, 0, 8, text="Final Short Signal # 3", bgcolor=color.new(color.red, 50), text_color=color.white, text_size=size.small)
//table.cell(Pos, 0, 9, text="Final Short Signal # 4", bgcolor=color.new(color.red, 50), text_color=color.white, text_size=size.small)
//table.cell(Pos, 0, 10, text="Final Short Signal # 5", bgcolor=color.new(color.red, 50), text_color=color.white, text_size=size.small)
//table.cell(Pos, 0, 11, text="Final Short Signal # 6", bgcolor=color.new(color.red, 50), text_color=color.white, text_size=size.small)
table.cell(Pos, 0, 12, text="Final Short Signal ", bgcolor=color.new(color.red, 50), text_color=color.white, text_size=size.small)
table.cell(Pos, 0, 13, text="Half Trend", bgcolor=color.new(color.red, 50), text_color=color.white, text_size=size.small)
table.cell(Pos, 0, 14, text="Exit Long", bgcolor=color.new(color.red, 50), text_color=color.white, text_size=size.small)
table.cell(Pos, 0, 15, text="Exit Short", bgcolor=color.new(color.red, 50), text_color=color.white, text_size=size.small)
table.cell(Pos, 0, 16, text="Shek CCI TOP", bgcolor=color.new(color.red, 50), text_color=color.white, text_size=size.small)
table.cell(Pos, 0, 17, text="Shek CCI Kaf", bgcolor=color.new(color.red, 50), text_color=color.white, text_size=size.small)
table.cell(Pos, 0, 18, text="In Long POS", bgcolor=color.new(color.red, 50), text_color=color.white, text_size=size.small)
table.cell(Pos, 0, 19, text="In Short POS", bgcolor=color.new(color.red, 50), text_color=color.white, text_size=size.small)
//table.cell(Pos, 1, 0, text=tostring(rsi66), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(Pos, 1, 1, text=tostring(FinalLongSignal1), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(Pos, 1, 2, text=tostring(FinalLongSignal2), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(Pos, 1, 3, text=tostring(FinalLongSignal3), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(Pos, 1, 4, text=tostring(FinalLongSignal4), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(Pos, 1, 5, text=tostring(FinalLongSignal5), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(Pos, 1, 6, text=tostring(FinalLongSignal6), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(Pos, 1, 7, text=tostring(FinalLongSignal), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(Pos, 1, 6, text=tostring(FinalShortSignal1), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(Pos, 1, 7, text=tostring(FinalShortSignal2), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(Pos, 1, 8, text=tostring(FinalShortSignal3), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(Pos, 1, 9, text=tostring(FinalShortSignal4), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(Pos, 1, 10, text=tostring(FinalShortSignal5), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(Pos, 1, 11, text=tostring(FinalShortSignal6), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(Pos, 1, 12, text=tostring(FinalShortSignal), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
a28=-129
b28=19
//table.cell(Pos, 1, 13, text=halfTrend, bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(Pos, 1, 14, text=tostring(ExitLong), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(Pos, 1, 15, text=tostring(ExitShort), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(Pos, 1, 16, text=tostring(shekastCCItop), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(Pos, 1, 17, text=tostring(shekastCCIkaf), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(Pos, 1, 18, text=tostring(LongPos), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//table.cell(Pos, 1, 19, text=tostring(ShortPos), bgcolor=color.new(color.green, 50), text_color=color.red, text_size=size.small)
//END▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
////////////////////////////////////////////////////////////////////////////////
|
[fpemehd] Strategy Template | https://www.tradingview.com/script/hzvQpMZa/ | DuDu95 | https://www.tradingview.com/u/DuDu95/ | 137 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © fpemehd
// Thanks to myncrypto, jason5480, kevinmck100
// @version=5
strategy(title = '[fpemehd] Strategy Template',
shorttitle = '[f] Template',
overlay = true,
pyramiding = 0,
currency = currency.USD,
default_qty_type = strategy.percent_of_equity,
default_qty_value = 100,
commission_value = 0.1,
initial_capital = 100000,
max_bars_back = 500,
max_lines_count = 150,
max_labels_count = 300)
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Time, Direction, Etc - Basic Settings Inputs
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// 1. Time: Based on UTC +09:00
i_start = input.time (defval = timestamp("20 Jan 1990 00:00 +0900"), title = "Start Date", tooltip = "Choose Backtest Start Date", inline = "Start Date", group = "Time" )
i_end = input.time (defval = timestamp("20 Dec 2030 00:00 +0900"), title = "End Date", tooltip = "Choose Backtest End Date", inline = "End Date", group = "Time" )
inTime = time >= i_start and time <= i_end
// 2. Inputs for direction: Long? Short? Both?
i_longEnabled = input.bool (defval = true , title = "Long?", tooltip = "Enable Long Position Trade?", inline = "Long / Short", group = "Long / Short" )
i_shortEnabled = input.bool (defval = true , title = "Short?", tooltip = "Enable Short Position Trade?", inline = "Long / Short", group = "Long / Short" )
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Filter - Inputs, Indicaotrs
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// 3. Use Filters? What Filters?
i_ATRFilterOn = input.bool (defval = false , title = "ATR Filter On?", tooltip = "ATR Filter On? Order will not be made unless filter condition is fulfilled", inline = "1", group = "Filters")
i_ATRFilterLen = input.int (defval = 14 , title = "Length for ATR Filter", minval = 1 , maxval = 100 , step = 1 , tooltip = "", inline = "2", group = "Filters")
i_ATRSMALen = input.int (defval = 40 , title = "SMA Length for ATR SMA", minval = 1 , maxval = 100000 , step = 1 , tooltip = "ATR should be bigger than this", inline = "2", group = "Filters")
bool i_ATRFilter = ta.atr(i_ATRFilterLen) >= ta.sma(ta.atr(length = i_ATRFilterLen), i_ATRSMALen) ? true : false
bool filterFulfilled = not i_ATRFilterOn or i_ATRFilter
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Strategy Logic (Entry & Exit Condition) - Inputs, Indicators for Strategy
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
//// Indicators
// Inputs for Strategy Indicators
i_fastMALen = input.int (defval = 21, title = 'Fast SMA Length', minval = 1, inline = 'MA Length', group = 'Strategy')
i_slowMALen = input.int (defval = 49, title = 'Slow SMA Length', minval = 1, tooltip = 'How many candles back to calculte the fast/slow SMA.', inline = 'MA Length', group = 'Strategy')
// Calculate Indicators
float indicator1 = ta.sma(source = close, length = i_fastMALen)
float indicator2 = ta.sma(source = close, length = i_slowMALen)
// Plot: Indicators
var indicator1Color = color.new(color = color.yellow, transp = 0)
plot(series = indicator1, title = 'indicator1', color = indicator1Color, linewidth = 1, style = plot.style_line)
var indicator2Color = color.new(color = color.orange, transp = 0)
plot(series = indicator2, title = 'indicator2', color = indicator2Color, linewidth = 1, style = plot.style_line)
////// Entry, Exit
// Long, Short Logic with Indicator
bool crossover = ta.crossover (indicator1, indicator2)
bool crossunder = ta.crossunder (indicator1, indicator2)
// Basic Cond + Long, Short Entry Condition
bool longCond = (i_longEnabled and inTime) and (crossover)
bool shortCond = (i_shortEnabled and inTime) and (crossunder)
// Basic Cond + Long, Short Exit Condition
bool closeLong = (i_longEnabled) and (crossunder)
bool closeShort = (i_shortEnabled) and (crossover)
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Position Control
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Long, Short Entry Condition + Not entered Position Yet
bool openLong = longCond and not (strategy.opentrades.size(strategy.opentrades - 1) > 0) and filterFulfilled
bool openShort = shortCond and not (strategy.opentrades.size(strategy.opentrades - 1) < 0) and filterFulfilled
bool enteringTrade = openLong or openShort
float entryBarIndex = bar_index
// Long, Short Entry Fulfilled or Already Entered
bool inLong = openLong or strategy.opentrades.size(strategy.opentrades - 1) > 0 and not closeLong
bool inShort = openShort or strategy.opentrades.size(strategy.opentrades - 1) < 0 and not closeShort
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Stop Loss - Inputs, Indicaotrs
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
//// Use SL? TSL?
i_useSLTP = input.bool (defval = true, title = "Enable SL & TP?", tooltip = "", inline = "1", group = "Stop Loss")
i_tslEnabled = input.bool (defval = false , title = "Enable Trailing SL?", tooltip = "Enable Stop Loss & Take Profit? \n\Enable Trailing SL?", inline = "1", group = "Stop Loss")
// i_breakEvenAfterTP = input.bool (defval = false, title = 'Enable Break Even After TP?', tooltip = 'When Take Profit price target is hit, move the Stop Loss to the entry price (or to a more strict price defined by the Stop Loss %/ATR Multiplier).', inline = '2', group = 'Stop Loss / Take Profit')
//// Sl Options
i_slType = input.string (defval = "ATR", title = "Stop Loss Type", options = ["Percent", "ATR", "Previous LL / HH"], tooltip = "Stop Loss based on %? ATR?", inline = "3", group = "Stop Loss")
i_slATRLen = input.int (defval = 14, title = "ATR Length", minval = 1 , maxval = 200 , step = 1, inline = "4", group = "Stop Loss")
i_slATRMult = input.float (defval = 3, title = "ATR Multiplier", minval = 1 , maxval = 200 , step = 0.1, tooltip = "", inline = "4", group = "Stop Loss")
i_slPercent = input.float (defval = 3, title = "Percent", tooltip = "", inline = "5", group = "Stop Loss")
i_slLookBack = input.int (defval = 30, title = "Lowest Price Before Entry", group = "Stop Loss", inline = "6", minval = 30, step = 1, tooltip = "Lookback to find the Lowest Price. \nStopLoss is determined by the Lowest price of the look back period. Take Profit is derived from this also by multiplying the StopLoss value by the Risk:Reward multiplier.")
// Functions for Stop Loss
float openAtr = ta.valuewhen(condition = enteringTrade, source = ta.atr(i_slATRLen), occurrence = 0)
float openLowest = ta.valuewhen(condition = openLong, source = ta.lowest(low, i_slLookBack), occurrence = 0)
float openHighest = ta.valuewhen(condition = openShort, source = ta.highest(high, i_slLookBack), occurrence = 0)
f_getLongSLPrice(source) =>
switch i_slType
"Percent" => source * (1 - (i_slPercent/100))
"ATR" => source - (i_slATRMult * openAtr)
"Previous LL / HH" => openLowest
=> na
f_getShortSLPrice(source) =>
switch i_slType
"Percent" => source * (1 + (i_slPercent/100))
"ATR" => source + (i_slATRMult * openAtr)
"Previous LL / HH" => openHighest
=> na
// Calculate Stop Loss
var float longSLPrice = na
var float shortSLPrice = na
bool longTPExecuted = false
bool shortTPExecuted = false
longSLPrice := if (inLong and i_useSLTP)
if (openLong)
f_getLongSLPrice (close)
else
// 1. Trailing Stop Loss
if i_tslEnabled
stopLossPrice = f_getLongSLPrice (high)
math.max(stopLossPrice, nz(longSLPrice[1]))
// 2. Normal StopLoss
else
nz(source = longSLPrice[1], replacement = 0)
else
na
shortSLPrice := if (inShort and i_useSLTP)
if (openShort)
f_getShortSLPrice (close)
else
// 1. Trailing Stop Loss
if i_tslEnabled
stopLossPrice = f_getShortSLPrice (low)
math.min(stopLossPrice, nz(shortSLPrice[1]))
// 2. Normal StopLoss
else
nz(source = shortSLPrice[1], replacement = 999999.9)
else
na
// Plot: Stop Loss of Long, Short Entry
var longSLPriceColor = color.new(color.maroon, 0)
plot(series = longSLPrice, title = 'Long Stop Loss', color = longSLPriceColor, linewidth = 1, style = plot.style_linebr, offset = 1)
var shortSLPriceColor = color.new(color.maroon, 0)
plot(series = shortSLPrice, title = 'Short Stop Loss', color = shortSLPriceColor, linewidth = 1, style = plot.style_linebr, offset = 1)
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Take Profit - Inputs, Indicaotrs
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
i_useTPExit = input.bool (defval = true, title = "Use Take Profit?", tooltip = "", inline = "1", group = "Take Profit")
i_RRratio = input.float (defval = 1.8, title = "R:R Ratio", minval = 0.1 , maxval = 200 , step = 0.1, tooltip = "R:R Ratio > Risk Reward Ratio? It will automatically set Take Profit % based on Stop Loss", inline = "2", group = "Take Profit")
i_tpQuantityPerc = input.float (defval = 50, title = 'Take Profit Quantity %', minval = 0.0, maxval = 100, step = 1.0, tooltip = '% of position closed when tp target is met.', inline="34", group = 'Take Profit')
var float longTPPrice = na
var float shortTPPrice = na
f_getLongTPPrice() =>
close + i_RRratio * math.abs (close - f_getLongSLPrice (close))
f_getShortTPPrice() =>
close - i_RRratio * math.abs(close - f_getShortSLPrice (close))
longTPPrice := if (inLong and i_useSLTP)
if (openLong)
f_getLongTPPrice ()
else
nz(source = longTPPrice[1], replacement = f_getLongTPPrice ())
else
na
shortTPPrice := if (inShort and i_useSLTP)
if (openShort)
f_getShortTPPrice ()
else
nz(source = shortTPPrice[1], replacement = f_getShortTPPrice ())
else
na
// Plot: Take Profit of Long, Short Entry
var longTPPriceColor = color.new(color.teal, 0)
plot(series = longTPPrice, title = 'Long Take Profit', color = longTPPriceColor, linewidth = 1, style = plot.style_linebr, offset = 1)
var shortTPPriceColor = color.new(color.teal, 0)
plot(series = shortTPPrice, title = 'Short Take Profit', color = shortTPPriceColor, linewidth = 1, style = plot.style_linebr, offset = 1)
// Plot: Entry Price
var posColor = color.new(color.white, 0)
plot(series = strategy.opentrades.entry_price(strategy.opentrades - 1), title = 'Position Entry Price', color = posColor, linewidth = 1, style = plot.style_linebr)
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Quantity - Inputs
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
i_useRiskManangement = input.bool (defval = true, title = "Use Risk Manangement?", tooltip = "", inline = "1", group = "Quantity")
i_riskPerTrade = input.float (defval = 3, title = "Risk Per Trade (%)", minval = 0, maxval = 100, step = 0.1, tooltip = "Use Risk Manangement by Quantity Control?", inline = "2", group = "Quantity")
// i_leverage = input.float (defval = 2, title = "Leverage", minval = 0, maxval = 100, step = 0.1, tooltip = "Leverage", inline = "3", group = "Quantity")
float qtyPercent = na
float entryQuantity = na
f_calQtyPerc() =>
if (i_useRiskManangement)
riskPerTrade = (i_riskPerTrade) / 100 // 1번 거래시 3% 손실
stopLossPrice = openLong ? f_getLongSLPrice (close) : openShort ? f_getShortSLPrice (close) : na
riskExpected = math.abs((close-stopLossPrice)/close) // 손절가랑 6% 차이
riskPerTrade / riskExpected // 0 ~ 1
else
1
f_calQty(qtyPerc) =>
math.min (math.max (0.000001, strategy.equity / close * qtyPerc), 1000000000)
// TP Execution
longTPExecuted := strategy.opentrades.size(strategy.opentrades - 1) > 0 and (longTPExecuted[1] or strategy.opentrades.size(strategy.opentrades - 1) < strategy.opentrades.size(strategy.opentrades - 1)[1] or strategy.opentrades.size(strategy.opentrades - 1)[1] == 0 and high >= longTPPrice)
shortTPExecuted := strategy.opentrades.size(strategy.opentrades - 1) < 0 and (shortTPExecuted[1] or strategy.opentrades.size(strategy.opentrades - 1) > strategy.opentrades.size(strategy.opentrades - 1)[1] or strategy.opentrades.size(strategy.opentrades - 1)[1] == 0 and low <= shortTPPrice)
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Plot Label, Boxes, Results, Etc
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
i_showSimpleLabel = input.bool(false, "Show Simple Label for Entry?", group = "Strategy: Drawings", inline = "1", tooltip ="")
i_showLabels = input.bool(true, "Show Trade Exit Labels", group = "Strategy: Drawings", inline = "1", tooltip = "Useful labels to identify Profit/Loss and cumulative portfolio capital after each trade closes.\n\nAlso note that TradingView limits the max number of 'boxes' that can be displayed on a chart (max 500). This means when you lookback far enough on the chart you will not see the TP/SL boxes. However you can check this option to identify where trades exited.")
i_showDashboard = input.bool(true, "Show Dashboard", group = "Strategy: Drawings", inline = "2", tooltip = "Show Backtest Results. Backtest Dates, Win/Lose Rates, Etc.")
// Plot: Label for Long, Short Entry
var openLongColor = color.new(#2962FF, 0)
var openShortColor = color.new(#FF1744, 0)
var entryTextColor = color.new(color.white, 0)
if (openLong and i_showSimpleLabel)
label.new (x = bar_index, y = na, text = 'Open', yloc = yloc.belowbar, color = openLongColor, style = label.style_label_up, textcolor = entryTextColor)
entryBarIndex := bar_index
if (openShort and i_showSimpleLabel)
label.new (x = bar_index, y = na, text = 'Close', yloc = yloc.abovebar, color = openShortColor, style = label.style_label_down, textcolor = entryTextColor)
entryBarIndex := bar_index
float prevEntryPrice = strategy.closedtrades.entry_price (strategy.closedtrades - 1)
float pnl = strategy.closedtrades.profit (strategy.closedtrades - 1)
float prevExitPrice = strategy.closedtrades.exit_price (strategy.closedtrades - 1)
f_enteringTradeLabel(x, y, qty, entryPrice, slPrice, tpPrice, rrRatio, direction) =>
if i_showLabels
labelStr = ("Trade Start"
+ "\nDirection: " + direction
+ "\nRisk Per Trade: " + str.tostring (i_useRiskManangement ? i_riskPerTrade : 100, "#.##") + "%"
+ "\nExpected Risk: " + str.tostring (math.abs((close-slPrice)/close) * 100, "#.##") + "%"
+ "\nEntry Position Qty: " + str.tostring(math.abs(qty * 100), "#.##") + "%"
+ "\nEntry Price: " + str.tostring(entryPrice, "#.##"))
+ "\nStop Loss Price: " + str.tostring(slPrice, "#.##")
+ "\nTake Profit Price: " + str.tostring(tpPrice, "#.##")
+ "\nRisk - Reward Ratio: " + str.tostring(rrRatio, "#.##")
label.new(x = x, y = y, text = labelStr, color = color.new(color.blue, 60) , textcolor = color.white, style = label.style_label_up)
f_exitingTradeLabel(x, y, entryPrice, exitPrice, direction) =>
if i_showLabels
labelStr = ("Trade Result"
+ "\nDirection: " + direction
+ "\nEntry Price: " + str.tostring(entryPrice, "#.##")
+ "\nExit Price: " + str.tostring(exitPrice,"#.##")
+ "\nGain %: " + str.tostring(direction == 'Long' ? -(entryPrice-exitPrice) / entryPrice * 100 : (entryPrice-exitPrice) / entryPrice * 100 ,"#.##") + "%")
label.new(x = x, y = y, text = labelStr, color = pnl > 0 ? color.new(color.green, 60) : color.new(color.red, 60), textcolor = color.white, style = label.style_label_down)
f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) =>
_cellText = _title + " " + _value
table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor, text_size=size.auto)
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Orders
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
if (inTime)
if (openLong)
qtyPercent := f_calQtyPerc()
entryQuantity := f_calQty(qtyPercent)
strategy.entry(id = "Long", direction = strategy.long, qty = entryQuantity, comment = 'Long(' + syminfo.ticker + '): Started', alert_message = 'Long(' + syminfo.ticker + '): Started')
f_enteringTradeLabel(x = bar_index + 1, y = close-3*ta.tr, entryPrice = close, qty = qtyPercent, slPrice = longSLPrice, tpPrice = longTPPrice, rrRatio = i_RRratio, direction = "Long")
if (openShort)
qtyPercent := f_calQtyPerc()
entryQuantity := f_calQty(qtyPercent)
strategy.entry(id = "Short", direction = strategy.short, qty = entryQuantity, comment = 'Short(' + syminfo.ticker + '): Started', alert_message = 'Short(' + syminfo.ticker + '): Started')
f_enteringTradeLabel(x = bar_index + 1, y = close-3*ta.tr, entryPrice = close, qty = qtyPercent, slPrice = shortSLPrice, tpPrice = shortTPPrice, rrRatio = i_RRratio, direction = "Short")
if (closeLong)
strategy.close(id = 'Long', comment = 'Close Long', alert_message = 'Long: Closed at market price')
strategy.position_size > 0 ? f_exitingTradeLabel(x = bar_index, y = close+3*ta.tr, entryPrice = prevEntryPrice, exitPrice = prevExitPrice, direction = 'Long') : na
if (closeShort)
strategy.close(id = 'Short', comment = 'Close Short', alert_message = 'Short: Closed at market price')
strategy.position_size < 0 ? f_exitingTradeLabel(x = bar_index, y = close+3*ta.tr, entryPrice = prevEntryPrice, exitPrice = prevExitPrice, direction = 'Short') : na
if (inLong)
strategy.exit(id = 'Long TP / SL', from_entry = 'Long', qty_percent = i_tpQuantityPerc, limit = longTPPrice, stop = longSLPrice, alert_message = 'Long(' + syminfo.ticker + '): Take Profit or Stop Loss executed')
strategy.exit(id = 'Long SL', from_entry = 'Long', stop = longSLPrice, alert_message = 'Long(' + syminfo.ticker + '): Stop Loss executed')
if (inShort)
strategy.exit(id = 'Short TP / SL', from_entry = 'Short', qty_percent = i_tpQuantityPerc, limit = shortTPPrice, stop = shortSLPrice, alert_message = 'Short(' + syminfo.ticker + '): Take Profit or Stop Loss executed')
strategy.exit(id = 'Short SL', from_entry = 'Short', stop = shortSLPrice, alert_message = 'Short(' + syminfo.ticker + '): Stop Loss executed')
if strategy.position_size[1] > 0 and strategy.position_size == 0
f_exitingTradeLabel(x = bar_index, y = close+3*ta.tr, entryPrice = prevEntryPrice, exitPrice = prevExitPrice, direction = 'Long')
if strategy.position_size[1] < 0 and strategy.position_size == 0
f_exitingTradeLabel(x = bar_index, y = close+3*ta.tr, entryPrice = prevEntryPrice, exitPrice = prevExitPrice, direction = 'Short')
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// Backtest Result Dashboard
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
if i_showDashboard
var bgcolor = color.new(color = color.black, transp = 100)
var greenColor = color.new(color = #02732A, transp = 0)
var redColor = color.new(color = #D92332, transp = 0)
var yellowColor = color.new(color = #F2E313, transp = 0)
// Keep track of Wins/Losses streaks
newWin = (strategy.wintrades > strategy.wintrades[1]) and (strategy.losstrades == strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1])
newLoss = (strategy.wintrades == strategy.wintrades[1]) and (strategy.losstrades > strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1])
varip int winRow = 0
varip int lossRow = 0
varip int maxWinRow = 0
varip int maxLossRow = 0
if newWin
lossRow := 0
winRow := winRow + 1
if winRow > maxWinRow
maxWinRow := winRow
if newLoss
winRow := 0
lossRow := lossRow + 1
if lossRow > maxLossRow
maxLossRow := lossRow
// Prepare stats table
var table dashTable = table.new(position.top_right, 1, 15, border_width=1)
if barstate.islastconfirmedhistory
dollarReturn = strategy.netprofit
f_fillCell(dashTable, 0, 0, "Start:", str.format("{0,date,long}", strategy.closedtrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.closedtrades.entry_time(0))
f_fillCell(dashTable, 0, 1, "End:", str.format("{0,date,long}", strategy.opentrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.opentrades.entry_time(0))
_profit = (strategy.netprofit / strategy.initial_capital) * 100
f_fillCell(dashTable, 0, 2, "Net Profit:", str.tostring(_profit, '##.##') + "%", _profit > 0 ? greenColor : redColor, color.white)
_numOfDaysInStrategy = (strategy.opentrades.entry_time(0) - strategy.closedtrades.entry_time(0)) / (1000 * 3600 * 24)
f_fillCell(dashTable, 0, 3, "Percent Per Day", str.tostring(_profit / _numOfDaysInStrategy, '#########################.#####')+"%", _profit > 0 ? greenColor : redColor, color.white)
_winRate = ( strategy.wintrades / strategy.closedtrades ) * 100
f_fillCell(dashTable, 0, 4, "Percent Profitable:", str.tostring(_winRate, '##.##') + "%", _winRate < 50 ? redColor : _winRate < 75 ? greenColor : yellowColor, color.white)
f_fillCell(dashTable, 0, 5, "Profit Factor:", str.tostring(strategy.grossprofit / strategy.grossloss, '##.###'), strategy.grossprofit > strategy.grossloss ? greenColor : redColor, color.white)
f_fillCell(dashTable, 0, 6, "Total Trades:", str.tostring(strategy.closedtrades), bgcolor, color.white)
f_fillCell(dashTable, 0, 8, "Max Wins In A Row:", str.tostring(maxWinRow, '######') , bgcolor, color.white)
f_fillCell(dashTable, 0, 9, "Max Losses In A Row:", str.tostring(maxLossRow, '######') , bgcolor, color.white) |
EMA12/26 with date backtest range (BTCpair) | https://www.tradingview.com/script/Sxxicud8-EMA12-26-with-date-backtest-range-BTCpair/ | HomoDeus666 | https://www.tradingview.com/u/HomoDeus666/ | 25 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HomoDeus666
//@version=5
strategy("CDC actionzone with date backtest range (BTCpair)", overlay=true,initial_capital = 1,commission_type = strategy.commission.percent,default_qty_value = 0.02,currency = currency.BTC,default_qty_type = strategy.cash)
//input date and time
useDateFilter = input.bool(false, title="Filter Date Range of Backtest",
group="Backtest Time Period")
backtestStartDate = input.time(timestamp("1 Jan 2021"),
title="Start Date", group="Backtest Time Period",
tooltip="This start date is in the time zone of the exchange " +
"where the chart's instrument trades. It doesn't use the time " +
"zone of the chart or of your computer.")
backtestEndDate = input.time(timestamp("1 Jan 2022"),
title="End Date", group="Backtest Time Period",
tooltip="This end date is in the time zone of the exchange " +
"where the chart's instrument trades. It doesn't use the time " +
"zone of the chart or of your computer.")
//check date and time option
inTradeWindow = not useDateFilter or (time >= backtestStartDate and
time < backtestEndDate)
/// plot and indicator
fastEMA = ta.ema(close,12), slowEMA=ta.ema(close,26)
plot(fastEMA,color=color.green,linewidth = 2)
plot(slowEMA,color=color.red,linewidth=2)
//entry when condition
longCondition = ta.crossover(fastEMA,slowEMA)
if (longCondition) and inTradeWindow
strategy.entry("buy", strategy.long)
if ta.crossunder(ta.ema(close, 12), ta.ema(close, 26)) and inTradeWindow
strategy.close("buy")
// trades and cancel all unfilled pending orders
if not inTradeWindow and inTradeWindow[1]
strategy.cancel_all()
strategy.close_all(comment="Date Range Exit") |
SuperTrend Multi Time Frame Long and Short Trading Strategy | https://www.tradingview.com/script/nXIb4hOt-SuperTrend-Multi-Time-Frame-Long-and-Short-Trading-Strategy/ | ranga_technologies | https://www.tradingview.com/u/ranga_technologies/ | 442 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ranga_trading
//@version=5
strategy(title='SuperTrend Multi Time Frame Long and Short Trading Strategy with Take Profit, Stop Loss and in build alerts V01', shorttitle='SuperTrend Multi Time Frame Long and Short Trading Strategy with Take Profit, Stop Loss and in build alerts V01 ', overlay=true, default_qty_value=60, initial_capital=2000, default_qty_type=strategy.percent_of_equity, pyramiding=0, process_orders_on_close=true)
tf1 = input.timeframe('D', title='Timeframe 1')
tf2 = input.timeframe('W', title='Timeframe 2')
length = input(title='ATR Period', defval=22)
mult = input.float(title='ATR Multiplier', step=0.1, defval=3.0)
showLabels = input(title='Show Buy/Sell Labels ?', defval=true)
useClose = input(title='Use Close Price for Extremums ?', defval=true)
highlightState = input(title='Highlight State ?', defval=true)
atr = mult * ta.atr(length)
longStop = (useClose ? ta.highest(close, length) : ta.highest(length)) - atr
longStopPrev = nz(longStop[1], longStop)
longStop := close[1] > longStopPrev ? math.max(longStop, longStopPrev) : longStop
shortStop = (useClose ? ta.lowest(close, length) : ta.lowest(length)) + atr
shortStopPrev = nz(shortStop[1], shortStop)
shortStop := close[1] < shortStopPrev ? math.min(shortStop, shortStopPrev) : shortStop
var int dir = 1
dir := close > shortStopPrev ? 1 : close < longStopPrev ? -1 : dir
var color longColor = color.green
var color shortColor = color.red
longStopPlot = plot(dir == 1 ? longStop : na, title='Long Stop', style=plot.style_linebr, linewidth=2, color=color.new(longColor, 0))
buySignal = dir == 1 and dir[1] == -1
plotshape(buySignal ? longStop : na, title='Long Stop Start', location=location.absolute, style=shape.circle, size=size.tiny, color=color.new(longColor, 0))
shortStopPlot = plot(dir == 1 ? na : shortStop, title='Short Stop', style=plot.style_linebr, linewidth=2, color=color.new(shortColor, 0))
sellSignal = dir == -1 and dir[1] == 1
plotshape(sellSignal ? shortStop : na, title='Short Stop Start', location=location.absolute, style=shape.circle, size=size.tiny, color=color.new(shortColor, 0))
midPricePlot = plot(ohlc4, title='', style=plot.style_circles, linewidth=0, display=display.none, editable=false)
longFillColor = highlightState ? dir == 1 ? longColor : na : na
shortFillColor = highlightState ? dir == -1 ? shortColor : na : na
fill(midPricePlot, longStopPlot, title='Long State Filling', color=longFillColor, transp=90)
fill(midPricePlot, shortStopPlot, title='Short State Filling', color=shortFillColor, transp=90)
// CE Function
ce() =>
atr2 = mult * ta.atr(length)
longStop2 = (useClose ? ta.highest(close, length) : ta.highest(length)) - atr2
longStop2Prev = nz(longStop2[1], longStop2)
longStop2 := close[1] > longStop2Prev ? math.max(longStop2, longStop2Prev) : longStop2
shortStop2 = (useClose ? ta.lowest(close, length) : ta.lowest(length)) + atr2
shortStop2Prev = nz(shortStop2[1], shortStop2)
shortStop2 := close[1] < shortStop2Prev ? math.min(shortStop2, shortStop2Prev) : shortStop2
var int dir2 = 1
dir2 := close > shortStop2Prev ? 1 : close < longStop2Prev ? -1 : dir2
ce = dir2 == 1 ? longStop2 : shortStop2
[dir2, ce]
[side, ce_plot] = ce()
ce1_plot = request.security(syminfo.tickerid, tf1, ce_plot[1], barmerge.gaps_off, barmerge.lookahead_on)
ce2_plot = request.security(syminfo.tickerid, tf2, ce_plot[1], barmerge.gaps_off, barmerge.lookahead_on)
ce1 = request.security(syminfo.tickerid, tf1, side[1], barmerge.gaps_off, barmerge.lookahead_on)
ce2 = request.security(syminfo.tickerid, tf2, side[1], barmerge.gaps_off, barmerge.lookahead_on)
long = buySignal and ce1 > 0 and ce2 > 0
short = sellSignal and ce1 < 0 and ce2 < 0
tradeType = input.string('BOTH', title='What trades should be taken : ', options=['LONG', 'SHORT', 'BOTH'])
// Position Management Tools
pos = 0.0
if tradeType == 'BOTH'
pos := long ? 1 : short ? -1 : pos[1]
pos
if tradeType == 'LONG'
pos := long ? 1 : pos[1]
pos
if tradeType == 'SHORT'
pos := short ? -1 : pos[1]
pos
longCond = long and (pos[1] != 1 or na(pos[1]))
shortCond = short and (pos[1] != -1 or na(pos[1]))
plot(ce1_plot, title='Timeframe 1 CE', color=ce1 > 0 ? #008000 : #800000, linewidth=2)
plot(ce2_plot, title='Timeframe 2 CE', color=ce2 > 0 ? color.green : color.red, linewidth=2)
// EXIT FUNCTIONS //
i_sl = input.float(5.0, title='Stop Loss %', minval=0, group='Trades')
sl = i_sl > 0 ? i_sl / 100 : 99999
long_entry = ta.valuewhen(longCond, close, 0)
short_entry = ta.valuewhen(shortCond, close, 0)
// Simple Stop Loss + 2 Take Profits
sl_long = strategy.position_avg_price * (1 - sl)
sl_short = strategy.position_avg_price * (1 + sl)
// Position Adjustment
long_sl = low < sl_long and pos[1] == 1
short_sl = high > sl_short and pos[1] == -1
if long_sl or short_sl
pos := 0
pos
long_exit = sellSignal and pos[1] == 1
short_exit = buySignal and pos[1] == -1
if long_exit or short_exit
pos := 0
pos
tp1percent = input.int(5, title='TP1 %', group='Trades') / 100.0
tp2percent = input.int(10, title='TP2 %', group='Trades') / 100.0
tp3percent = input.int(15, title='TP3 %', group='Trades') / 100.0
tp1amt = input.int(10, title='TP1 Amount %', group='Trades')
tp2amt = input.int(15, title='TP2 Amount %', group='Trades')
tp3amt = input.int(20, title='TP3 Amount %', group='Trades')
// Strategy Backtest Limiting Algorithm
i_startTime = input.time(defval=timestamp('01 Jun 2021 13:30 +0000'), title='Backtesting Start Time')
i_endTime = input.time(defval=timestamp('30 Sep 2099 19:30 +0000'), title='Backtesting End Time')
timeCond = time > i_startTime and time < i_endTime
KeepLastPosition = input(false)
// Make sure we are within the bar range, Set up entries and exit conditions
strategy.entry('long', strategy.long, when=longCond == true and tradeType != 'SHORT' and timeCond)
strategy.entry('short', strategy.short, when=shortCond == true and tradeType != 'LONG' and timeCond)
var float Qty1 = na
var float Qty2 = na
var float Qty3 = na
var float Qty4 = na
if strategy.position_size == 0
equity_q = (strategy.initial_capital + strategy.netprofit) / close
Qty1 := equity_q * tp1amt / 100.0
Qty2 := equity_q * tp2amt / 100.0
Qty3 := equity_q * tp3amt / 100.0
Qty4 := equity_q - Qty1 - Qty2 - Qty3
Qty4
strategy.exit('Exit1', qty=Qty1, stop=sl_long, limit=strategy.position_avg_price * (1 + tp1percent), when=strategy.position_size > 0)
strategy.exit('Exit2', qty=Qty2, stop=sl_long, limit=strategy.position_avg_price * (1 + tp2percent), when=strategy.position_size > 0)
strategy.exit('Exit3', qty=Qty3, stop=sl_long, limit=strategy.position_avg_price * (1 + tp3percent), when=strategy.position_size > 0)
strategy.exit('Exit4', qty=Qty4, stop=sl_long, when=strategy.position_size > 0 and KeepLastPosition == false)
strategy.close('long', when=long_exit, comment='CE Exit')
strategy.exit('Exit1', qty=Qty1, stop=sl_short, limit=strategy.position_avg_price * (1 - tp1percent), when=strategy.position_size < 0)
strategy.exit('Exit2', qty=Qty2, stop=sl_short, limit=strategy.position_avg_price * (1 - tp2percent), when=strategy.position_size < 0)
strategy.exit('Exit3', qty=Qty3, stop=sl_short, limit=strategy.position_avg_price * (1 - tp3percent), when=strategy.position_size < 0)
strategy.exit('Exit4', qty=Qty4, stop=sl_short, when=strategy.position_size < 0 and KeepLastPosition == false)
strategy.close('short', when=short_exit, comment='CE Exit')
plot(strategy.position_size > 0 ? strategy.position_avg_price * (1 + tp1percent) : na, color=color.new(color.green, 0), style=plot.style_linebr)
plot(strategy.position_size > 0 ? strategy.position_avg_price * (1 + tp2percent) : na, color=color.new(color.green, 0), style=plot.style_linebr)
plot(strategy.position_size > 0 ? strategy.position_avg_price * (1 + tp3percent) : na, color=color.new(color.green, 0), style=plot.style_linebr)
plot(strategy.position_size > 0 ? sl_long : na, color=color.new(color.red, 0), style=plot.style_linebr)
plot(strategy.position_size > 0 ? strategy.position_avg_price : na, color=color.new(color.gray, 0), style=plot.style_linebr)
plot(strategy.position_size < 0 ? strategy.position_avg_price * (1 - tp1percent) : na, color=color.new(color.green, 0), style=plot.style_linebr)
plot(strategy.position_size < 0 ? strategy.position_avg_price * (1 - tp2percent) : na, color=color.new(color.green, 0), style=plot.style_linebr)
plot(strategy.position_size < 0 ? strategy.position_avg_price * (1 - tp3percent) : na, color=color.new(color.green, 0), style=plot.style_linebr)
plot(strategy.position_size < 0 ? sl_short : na, color=color.new(color.red, 0), style=plot.style_linebr)
plot(strategy.position_size < 0 ? strategy.position_avg_price : na, color=color.new(color.gray, 0), style=plot.style_linebr)
|
Misery index strategy | https://www.tradingview.com/script/oIBrxndl-Misery-index-strategy/ | DynamicSignalLab | https://www.tradingview.com/u/DynamicSignalLab/ | 42 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © DynamicSignalLab
//@version=5
strategy("Misery index", overlay=false)
unemployment = request.security("FRED:UNRATE","M",close)
inflation = request.security("ECONOMICS:USIRYY","M",close)
misery = unemployment+inflation
plot(misery)
longCondition = misery<misery[1]
if (longCondition)
strategy.entry("My Long Entry Id", strategy.long)
shortCondition = misery>misery[1]
if (shortCondition)
strategy.entry("My Short Entry Id", strategy.short)
|
Trading range display with Box | https://www.tradingview.com/script/9EZsXM9F-Trading-range-display-with-Box/ | potatoshop | https://www.tradingview.com/u/potatoshop/ | 88 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © potatoshop
//@version=5
strategy("Trading range display with Box","Box", overlay = true,process_orders_on_close=true,calc_on_every_tick=true, max_boxes_count=500, initial_capital=1000, default_qty_type=strategy.percent_of_equity,
commission_type=strategy.commission.percent,default_qty_value=10,commission_value=0.04,slippage=2)
// Just simple strategy for test. Put your strategy here.
a= ta.sma(close, 14)
b= ta.sma(close, 20)
plot(a,color=color.white)
plot(b,color=color.blue)
longCondition = ta.crossover(a,b)
if (longCondition)
strategy.entry("L", strategy.long)
closeCondition = ta.crossunder(a,b)
if (closeCondition)
strategy.close("L",comment = "CL")
// From here on, just Copy and Paste
// 1.Making the trading signal to get the (left,right) for Box. left, right 를 구하기 위한 시그널 만들기.
is_trading = strategy.position_size != 0 // 거래 포지션이 0이 아니면 거래중으로 판단하며, true를 리턴.
is_trading_L = strategy.position_size > 0
is_trading_S = strategy.position_size < 0
tradingstart = (is_trading == true and is_trading[1] == false)
tradingstart_L = (is_trading_L == true and is_trading_L[1] == false)
tradingstart_S = (is_trading_S == true and is_trading_S[1] == false)
tradingend = (is_trading == false and is_trading[1] == true)
tradingend_L = (is_trading_L == false and is_trading_L[1] == true)
tradingend_S = (is_trading_S == false and is_trading_S[1] == true)
// plotchar(tradingstart,text="start",textcolor = color.white) // check the signal 시그널 확인용.
// plotshape(tradingend,text="End",textcolor = color.white)
// 2.Get the left, right. left, right 에 좌표 기준 만들어 주기.
var left_L = bar_index , var left_S = bar_index
var right_L = bar_index , var right_S = bar_index
if tradingstart_L
left_L := bar_index -1 // 거래 시작이 확정된 봉이 진짜 시점보다 1봉 이후에 나오므로 일부러 -1을 했다.
if tradingend_L or (barstate.islast and is_trading_L) // 과거데이타를 처리할때는 거래 종료 시점만 필요하지만, 현재 거래중일때는 지금의 정보를 계속 업데이트 시켜준다.
right_L := bar_index -1
if tradingstart_S
left_S := bar_index -1
if tradingend_S or (barstate.islast and is_trading_S)
right_S := bar_index -1
//3.We need two box to make body and wick. body 와 wick 느낌으로 만들기 위해서 top, bottom을 각각 나누어 만들었다.
entry = barstate.islast and is_trading? strategy.opentrades.entry_price(strategy.opentrades-1) : strategy.closedtrades.entry_price(strategy.closedtrades-1) // 진입한 가격을 두 상황에 나누어 정의해 준다.
exit = barstate.islast ? close : strategy.closedtrades.exit_price(strategy.closedtrades-1) // 현재 거래중일때는 현재종가가 기준이다.
// body
top_body = math.max(entry,exit)
bottom_body = math.min(entry,exit)
// wick
len_L = right_L and left_L ? right_L - left_L +1 : 1
high_session_L = ta.highest(high,len_L)
low_session_L = ta.lowest(low,len_L)
len_S = right_S and left_S ? right_S - left_S +1 : 1
high_session_S = ta.highest(high,len_S)
low_session_S = ta.lowest(low,len_S)
// Box color part.
DEFAULT_COLOR_GROWTH = color.rgb(0, 150, 136, 50)
DEFAULT_COLOR_FALL = color.rgb(244, 67, 54, 50)
color_growth = input.color(DEFAULT_COLOR_GROWTH, title='', inline='Body')
color_fall = input.color(DEFAULT_COLOR_FALL, title='Body', inline='Body')
color_border_growth = color.rgb(color.r(color_growth), color.g(color_growth), color.b(color_growth), 50)
color_border_fall = color.rgb(color.r(color_fall), color.g(color_fall), color.b(color_fall), 50)
past_profit = strategy.closedtrades.profit(strategy.closedtrades-1)
now_profit = strategy.opentrades.profit(strategy.opentrades-1)
colorBD = barstate.islast and is_trading? (now_profit > 0 ? color_growth : color_fall) : (past_profit > 0 ? color_growth : color_fall) // Body color
colorBL = barstate.islast and is_trading? (now_profit > 0 ? color_border_growth : color_border_fall) : (past_profit > 0 ? color_border_growth : color_border_fall)// : (exit - entry > 0 ? color_border_fall : color_border_growth) // wick color
// 4. Box part
var box last_box1_L = na
var box last_box2_L = na
// Long Position Box
if tradingend_L and not barstate.isrealtime // 1. 과거 데이타로 확인된 봉에서만 실행.
box.delete(last_box1_L) , box.delete(last_box2_L)
box.new(left_L,high_session_L,right_L,low_session_L, border_color = colorBL, bgcolor = colorBL)
box.new(left_L,top_body,right_L,bottom_body, border_color = colorBD, bgcolor = colorBD)
left_L := na
right_L := na
if barstate.islast // 2. 현재봉에서 거래중인지 확인후 실행.
if tradingend_L
last_box1_L := na
last_box2_L := na
else if is_trading_L
right_L := bar_index -1
box.delete(last_box1_L) , box.delete(last_box2_L)
last_box1_L := box.new(left_L,high_session_L,right_L,low_session_L, border_color = colorBL, bgcolor = colorBL)
last_box2_L := box.new(left_L,top_body,right_L,bottom_body, border_color = colorBD, bgcolor = colorBD)
// Short Position Box
var box last_box1_S = na
var box last_box2_S = na
if tradingend_S and not barstate.isrealtime
box.delete(last_box1_S) , box.delete(last_box2_S)
box.new(left_S,high_session_S,right_S,low_session_S, border_color = colorBL, bgcolor = colorBL)
box.new(left_S,top_body,right_S,bottom_body, border_color = colorBD, bgcolor = colorBD)
left_S := na
right_S := na
if barstate.islast
if tradingend
last_box1_S := na
last_box2_S := na
else if is_trading_S
right_S := bar_index -1
box.delete(last_box1_S) , box.delete(last_box2_S)
last_box1_S := box.new(left_S,high_session_S,right_S,low_session_S, border_color = colorBL, bgcolor = colorBL)
last_box2_S := box.new(left_S,top_body,right_S,bottom_body, border_color = colorBD, bgcolor = colorBD)
|
Band-Zigzag - TrendFollower Strategy [Trendoscope] | https://www.tradingview.com/script/9FsHYtrq-Band-Zigzag-TrendFollower-Strategy-Trendoscope/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 1,575 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © HeWhoMustNotBeNamed
// ░▒
// ▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒
// ▒▒▒▒▒▒▒░ ▒ ▒▒
// ▒▒▒▒▒▒ ▒ ▒▒
// ▓▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// ▒ ▒ ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░▒▒▒▒▒▒▒▒
// ▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒ ▒▒▒▒▒
// ░▒▒▒▒ ▒▒▒▒▓ ████████╗██████╗ ███████╗███╗ ██╗██████╗ ██████╗ ███████╗ ██████╗ ██████╗ ██████╗ ███████╗
// ▓▒▒▒▒ ▒▒▒▒ ╚══██╔══╝██╔══██╗██╔════╝████╗ ██║██╔══██╗██╔═══██╗██╔════╝██╔════╝██╔═══██╗██╔══██╗██╔════╝
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ██║ ██████╔╝█████╗ ██╔██╗ ██║██║ ██║██║ ██║███████╗██║ ██║ ██║██████╔╝█████╗
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██╔══██╗██╔══╝ ██║╚██╗██║██║ ██║██║ ██║╚════██║██║ ██║ ██║██╔═══╝ ██╔══╝
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██║ ██║███████╗██║ ╚████║██████╔╝╚██████╔╝███████║╚██████╗╚██████╔╝██║ ███████╗
// ▒▒ ▒
//@version=5
strategy("Band-Zigzag - TrendFollower Strategy [Trendoscope]", "BZSTF[Trendoscope]", overlay=true, initial_capital=1000,
default_qty_type=strategy.percent_of_equity, default_qty_value=10, commission_type=strategy.commission.percent,
pyramiding=1, commission_value=0.05, close_entries_rule="ANY", margin_long=100, margin_short=100,
max_lines_count=500, max_labels_count=500, max_boxes_count=500, use_bar_magnifier=false)
tradeDirection = input.string(strategy.direction.all, "Trade Direction", options=[strategy.direction.long, strategy.direction.short, strategy.direction.all],
group="Trade Settings", tooltip='Use this to filter only long or short trades')
tradeSettingsTooltip = 'Pullback - On first pullback after trend confirmation\nBreakout - On first breakout of trend\Pullback-Breakout - On first pullback and breakout of trend\nAny - As soon as trend change'
tradeType = input.string('Any', 'Trade Type', options=['Pullback', 'Breakout', 'Pullback-Breakout', 'Any'], group='Trade Settings', tooltip=tradeSettingsTooltip)
tradeOnBreakout = tradeType == 'Breakout'
tradeOnPullback = tradeType == 'Pullback'
tradeOnRetest = tradeType == 'Pullback-Breakout'
tradeOnAny = tradeType == 'Any'
useStopLoss = input.bool(false, 'Use Stop Loss', group='Trade Settings', tooltip = 'If set, initial stoploss is used for every trade. Otherwise, trade can only be closed by change of trend. Not required if using Recent Pivot Override')
strategy.risk.allow_entry_in(tradeDirection)
import HeWhoMustNotBeNamed/ta/1 as eta
import HeWhoMustNotBeNamed/arrays/1 as pa
import HeWhoMustNotBeNamed/eHarmonicpatternsExtended/6 as hp
bandType = input.string('Bollinger Bands', '', ['Bollinger Bands', 'Keltner Channel', 'Donchian Channel'], group='Bands', inline='b1')
maType = input.string('sma', '', options=['sma', 'ema', 'hma', 'rma', 'wma', 'vwma', 'highlow', 'linreg', 'median'], inline = 'b1', group='Bands')
maLength = input.int(20, '', minval = 5, step=5, inline = 'b1', group='Bands')
multiplier = input.float(2.0, '', step=0.5, minval=0.5, group='Bands', inline='b1', tooltip = 'Band parameters let you select type of band/channel, moving average base, length and multiplier')
useTrueRange = input.bool(true, 'Use True Range (For KC only)', group='Bands', tooltip = 'Used only for keltener channel calculation')
sticky = input.bool(true, 'Sticky', group='Bands', tooltip = 'Sticky bands avoids changing the band unless there is breach. Meaning, band positions only change when price is outside the band.')
useAdaptive = input.bool(true, 'Adaptive', group='Bands', tooltip = 'When selected, lower band will not decrease when pivot high is in motion and upper band will not increase when pivot low in motion')
showBands = input.bool(true, 'Display Bands', group='Bands', tooltip = 'If selected, displays bands on chart')
useLatestPivot = input.bool(true, 'Use Recent Pivot Override', group='Trend', inline='t')
currentTrendInvalidationMultiplier = input.float(1.618, '', 0, 100, 1, group='Trend', inline='t',
tooltip = 'Trend calculation is done on last confirmed pivot. This option provides opportunity to also consider current unconfirmed pivot for defining trend on extreme moves. This will help in avoiding steep drawbacks')
float upper = 0.0
float lower = 0.0
float middle = 0.0
type Pivot
float price
int bar
int bartime
int direction
float percentB
float ratio = 0
type Drawing
line zigzagLine
label zigzagLabel
unshift(array<Pivot> zigzag, Pivot p)=>
if(array.size(zigzag) > 1)
lastPivot = array.get(zigzag, 0)
llastPivot = array.get(zigzag, 1)
p.direction := p.price*p.direction > llastPivot.price*p.direction ? p.direction*2 : p.direction
p.ratio := math.abs(p.price - lastPivot.price)/math.abs(llastPivot.price - lastPivot.price)
array.unshift(zigzag, p)
if(array.size(zigzag)>15)
array.pop(zigzag)
shift(array<Drawing> drawings)=>
del = array.shift(drawings)
line.delete(del.zigzagLine)
label.delete(del.zigzagLabel)
unshift(array<Drawing> drawings, Drawing drawing, int maxItems)=>
array.unshift(drawings, drawing)
if(array.size(drawings) > maxItems)
del = array.pop(drawings)
line.delete(del.zigzagLine)
label.delete(del.zigzagLabel)
if(bandType == 'Bollinger Bands')
[bmiddle, bupper, blower] = eta.bb(close, maType, maLength, multiplier, sticky)
upper := bupper
lower := blower
middle := bmiddle
if(bandType == 'Keltner Channel')
[kmiddle, kupper, klower] = eta.kc(close, maType, maLength, multiplier, useTrueRange, sticky)
upper := kupper
lower := klower
middle := kmiddle
if(bandType == 'Donchian Channel')
[dmiddle, dupper, dlower] = eta.dc(maLength, false, close, sticky)
upper := dupper
lower := dlower
middle := dmiddle
var zigzag = array.new<Pivot>()
var trend = 0
var currentTrend = 0
var currentDir = 0
var currentTrendForce = 0
var currentTrendExtreme = 0
if(array.size(zigzag) > 1)
recentPivot = array.get(zigzag, 0)
lastPivot = array.get(zigzag, 1)
currentDir := recentPivot.direction
currentTrend := recentPivot.ratio > recentPivot.percentB? int(math.sign(recentPivot.direction)) : -int(math.sign(recentPivot.direction))
trend := lastPivot.ratio > lastPivot.percentB? int(math.sign(lastPivot.direction)) : -int(math.sign(lastPivot.direction))
currentTrendForce := recentPivot.ratio > recentPivot.percentB and recentPivot.ratio> currentTrendInvalidationMultiplier? int(math.sign(recentPivot.direction)) : -int(math.sign(recentPivot.direction))
var uupper = nz(upper)
var llower = nz(lower)
uupper := currentDir >= 0 or not useAdaptive? upper : math.min(upper, uupper)
llower := currentDir <= 0 or not useAdaptive? lower : math.max(lower, llower)
percentBHigh = (high - llower)/(uupper - llower)
percentBLow = (uupper - low)/(uupper - llower)
addPivot(zigzag, direction)=>
lastRemoved = false
price = direction > 0? high : low
percentB = direction > 0? percentBHigh : percentBLow
Pivot p = Pivot.new(price, bar_index, time, int(direction), percentB)
if(array.size(zigzag) == 0)
unshift(zigzag, p)
else
lastPivot = array.get(zigzag, 0)
lastPivotDirection = math.sign(lastPivot.direction)
if (lastPivotDirection != p.direction)
unshift(zigzag, p)
if(lastPivotDirection == p.direction and lastPivot.price*direction < p.price*direction)
array.remove(zigzag, 0)
unshift(zigzag, p)
lastRemoved := true
lastRemoved
add_pivots(zigzag, pHigh, pLow)=>
count = 0
removeLast = false
if(array.size(zigzag) == 0)
if(pHigh)
addPivot(zigzag, 1)
count+=1
if(pLow)
addPivot(zigzag, -1)
count+=1
else
lastPivot = array.get(zigzag, 0)
lastDir = math.sign(lastPivot.direction)
if(pHigh and lastDir == 1) or (pLow and lastDir == -1)
removeLast := addPivot(zigzag, lastDir)
count := removeLast ? count+1 : count
if(pHigh and (lastDir == -1)) or (pLow and (lastDir == 1))
addPivot(zigzag, -lastDir)
count+=1
[count, removeLast]
draw_zigzag(zigzag, count, removeLast)=>
var zigzagDrawings = array.new<Drawing>()
if(removeLast and array.size(zigzagDrawings) > 0)
shift(zigzagDrawings)
if(array.size(zigzag) > count and count >= 1)
for i=count to 1
startPivot = array.get(zigzag, count)
endPivot = array.get(zigzag, count-1)
startDirection = startPivot.direction
endDirection = endPivot.direction
lineColor = endDirection == 2? color.green : endDirection == -2? color.red : color.silver
txt = str.tostring(endPivot.ratio*100, format.percent) + "/" + str.tostring(endPivot.percentB*100, format.percent)
ln = line.new(startPivot.bartime, startPivot.price, endPivot.bartime, endPivot.price, xloc.bar_time, color=lineColor, width = 2)
lbl = label.new(endPivot.bartime, endPivot.price, txt, xloc.bar_time, yloc.price, lineColor, endPivot.direction > 0? label.style_label_down : label.style_label_up, textcolor = color.black)
Drawing dr = Drawing.new(ln, lbl)
unshift(zigzagDrawings, dr, 500)
zigzagDrawings
pHigh = high >= uupper
pLow = low <= llower
[count, removeLast] = add_pivots(zigzag, pHigh, pLow)
draw_zigzag(zigzag, count, removeLast)
plot(showBands? uupper:na, 'Upper', color.green, 0, plot.style_linebr)
plot(showBands? llower:na, 'Lower', color.red, 0, plot.style_linebr)
var combinedTrend = 0
combinedTrend := trend > 0 or (useLatestPivot and (currentTrendForce > 0))? 1 :
trend < 0 or (useLatestPivot and (currentTrendForce < 0))? -1 : combinedTrend
candleColor = combinedTrend > 0? color.green : combinedTrend < 0 ? color.red : color.silver
plot(trend, 'Last Pivot Trend', trend >0? color.green : trend < 0? color.red : color.silver, display=display.data_window)
plot(currentTrend, 'Current Pivot Trend', currentTrend > 0? color.green : currentTrend < 0? color.red : color.silver, display=display.data_window)
plot(currentTrendForce, 'Force Trend', currentTrendForce >0? color.green : currentTrendForce < 0? color.red : color.silver, display=display.data_window)
plot(combinedTrend, "Combined Trend", candleColor, display = display.data_window)
plot(currentDir, "Current Direction", color=currentDir>0?color.green:currentDir<0?color.red:color.silver, display = display.data_window)
var allowEntry = false
allowEntry := ta.crossover(combinedTrend, 0) or ta.crossunder(combinedTrend, 0)? true : allowEntry
if(combinedTrend > 0)
strategy.close("Short")
if((tradeOnBreakout and currentDir > 0) or (tradeOnPullback and currentDir < 0) or tradeOnAny or (currentTrend >0 and trend >0 and currentDir > 0 and tradeOnRetest)) and allowEntry
allowEntry := false
strategy.entry("Long", strategy.long)
if useStopLoss
strategy.exit("ExitLong", "Long", stop=low - (uupper-llower))
if(combinedTrend < 0)
strategy.close("Long")
if((tradeOnBreakout and currentDir < 0) or (tradeOnPullback and currentDir > 0) or tradeOnAny or (currentTrend < 0 and trend < 0 and currentDir < 0 and tradeOnRetest)) and allowEntry
allowEntry := false
strategy.entry("Short", strategy.short)
if useStopLoss
strategy.exit("ExitShort", "Short", stop=high + (uupper-llower))
if(combinedTrend == 0)
strategy.close_all()
plot(allowEntry?1:0, 'Allow Entry', display = display.data_window) |
JS-TechTrading: Supertrend-Strategy_Basic version | https://www.tradingview.com/script/kRMAa3JF-JS-TechTrading-Supertrend-Strategy-Basic-version/ | JS_TechTrading | https://www.tradingview.com/u/JS_TechTrading/ | 439 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © JS_TechTrading
//@version=5
strategy("Supertrend", overlay=true,default_qty_type =strategy.percent_of_equity,default_qty_value = 1,process_orders_on_close = false)
// group string////
var string group_text000="Choose Strategy"
var string group_text0="Supertrend Settings"
var string group_text0000="Ema Settings"
var string group_text00="Rsi Settings"
var string group_text1="Backtest Period"
var string group_text2="Trade Direction"
// var string group_text3="Quantity Settings"
var string group_text4="Sl/Tp Settings"
////////////////////
option_ch=input.string('Pullback',title = "Type Of Strategy",options =['Pullback','Simple'])
//atr period input supertrend
atrPeriod = input(10, "ATR Length",group = group_text0)
factor = input.float(3.0, "Factor", step = 0.01,group=group_text0)
[supertrend, direction] = ta.supertrend(factor, atrPeriod)
bodyMiddle = plot((open + close) / 2, display=display.none)
upTrend = plot(direction < 0 ? supertrend : na, "Up Trend", color = color.green, style=plot.style_linebr)
downTrend = plot(direction < 0? na : supertrend, "Down Trend", color = color.red, style=plot.style_linebr)
fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps=false)
fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps=false)
long=direction < 0 ? supertrend : na
short=direction < 0? na : supertrend
longpos=false
shortpos=false
longpos :=long?true :short?false:longpos[1]
shortpos:=short?true:long?false:shortpos[1]
fin_pullbuy= (ta.crossunder(low[1],long) and long and high>high[1])
fin_pullsell=(ta.crossover(high[1],short) and short and low<low[1])
//Ema 1
on_ma=input.bool(true,"Ema Condition On/Off",group=group_text0000)
ma_len= input.int(200, minval=1, title="Ema Length",group = group_text0000)
ma_src = input.source(close, title="Ema Source",group = group_text0000)
ma_out = ta.ema(ma_src, ma_len)
ma_buy=on_ma?close>ma_out?true:false:true
ma_sell=on_ma?close<ma_out?true:false:true
// rsi indicator and condition
// Get user input
en_rsi = input.bool(true,"Rsi Condition On/Off",group = group_text00)
rsiSource = input(title='RSI Source', defval=close,group = group_text00)
rsiLength = input(title='RSI Length', defval=14,group = group_text00)
rsiOverbought = input(title='RSI BUY Level', defval=50,group = group_text00)
rsiOversold = input(title='RSI SELL Level', defval=50,group = group_text00)
// Get RSI value
rsiValue = ta.rsi(rsiSource, rsiLength)
rsi_buy=en_rsi?rsiValue>=rsiOverbought ?true:false:true
rsi_sell=en_rsi?rsiValue<=rsiOversold?true:false:true
// final condition
buy_cond=option_ch=='Simple'?long and not(longpos[1]) and rsi_buy and ma_buy:option_ch=='Pullback'?fin_pullbuy and rsi_buy and ma_buy:na
sell_cond=option_ch=='Simple'?short and not(shortpos[1]) and rsi_sell and ma_sell:option_ch=='Pullback'?fin_pullsell and rsi_sell and ma_sell:na
//backtest engine
start = input.time(timestamp('2005-01-01'), title='Start calculations from',group=group_text1)
end=input.time(timestamp('2045-03-01'), title='End calculations',group=group_text1)
time_cond = time >= start and time<=end
// Make input option to configure trade direction
tradeDirection = input.string(title='Trade Direction', options=['Long', 'Short', 'Both'], defval='Both',group = group_text2)
// Translate input into trading conditions
longOK = (tradeDirection == "Long") or (tradeDirection == "Both")
shortOK = (tradeDirection == "Short") or (tradeDirection == "Both")
// strategy start
if buy_cond and longOK and time_cond and strategy.position_size==0
strategy.entry('long',direction = strategy.long)
if sell_cond and shortOK and time_cond and strategy.position_size==0
strategy.entry('short',direction =strategy.short)
// fixed percentage based stop loss and take profit
// User Options to Change Inputs (%)
stopPer = input.float(1.0,step=0.10, title='Stop Loss %',group =group_text4) / 100
takePer = input.float(1.0,step =0.10, title='Take Profit %',group =group_text4) / 100
// Determine where you've entered and in what direction
longStop = strategy.position_avg_price * (1 - stopPer)
shortStop = strategy.position_avg_price * (1 + stopPer)
shortTake = strategy.position_avg_price * (1 - takePer)
longTake = strategy.position_avg_price * (1 + takePer)
if strategy.position_size > 0
strategy.exit(id='Close Long',stop=longStop, limit=longTake)
if strategy.position_size < 0
strategy.exit(id='Close Short',stop=shortStop, limit=shortTake)
//PLOT FIXED SLTP LINE
plot(strategy.position_size > 0 ? longStop : na, style=plot.style_linebr, color=color.new(color.red, 0), linewidth=1, title='Long Fixed SL')
plot(strategy.position_size < 0 ? shortStop :na, style=plot.style_linebr, color=color.new(color.red, 0), linewidth=1, title='Short Fixed SL')
plot(strategy.position_size > 0 ? longTake : na, style=plot.style_linebr, color=color.new(color.green, 0), linewidth=1, title='Long Take Profit')
plot(strategy.position_size < 0 ? shortTake : na, style=plot.style_linebr, color=color.new(color.green, 0), linewidth=1, title='Short Take Profit')
// |
FFT Strategy Bi-Directional Stop/Profit/Trailing + VMA + Aroon | https://www.tradingview.com/script/vjTJMDno-FFT-Strategy-Bi-Directional-Stop-Profit-Trailing-VMA-Aroon/ | Gentleman-Goat | https://www.tradingview.com/u/Gentleman-Goat/ | 345 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Gentleman-Goat
// credit to tbiktag for FFT
// credit to lazybear for VMA
// House Rules: This code borrows from the user tbiktag's source code (many thanks for making it open source!) and what I did was modify it slightly and turned it into a strategy. His notes regarding it are below. I also borrowed and revised lazybears variable moving average (thank you as well!)
// tbiktag --notes below regarding usage
// This tool computes the one-dimensional N-point discrete Fourier Transform
// (DFT) with the efficient Fast Fourier Transform (FFT) algorithm.
//
// The tool uses FFT to decompose the input time series into its
// periodic constituents and seasonalities, in other words, its frequency
// components.
//
// Subsequently it allows reconstructing the time-domain data while using
// only the frequency components within a user-defined range (band-pass filtering).
// Thereby, this tool can reveal the cyclical characteristics of the studied market,
// and also remove high-frequency noise from the time series.
// -- end tbiktag notes
//@version=5
strategy(title="FFT Strategy",shorttitle = "FFT Strat", overlay=false,max_lines_count=500,max_labels_count = 500,max_bars_back=5000,initial_capital = 1000,default_qty_type = strategy.percent_of_equity,default_qty_value = 100,calc_on_every_tick = false,process_orders_on_close=true)
import tbiktag/FFTLibrary/1 as fft
//-- FFT --
src = input.source(title='Source', defval=ohlc4, group='Fourier Input', inline='linei1')
N = input.int(title='Length', defval=128, options=[8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096], group='Fourier Input', tooltip='Source and number of elements in the input dataset', inline='linei1')
ispp = input.bool(title='Standardize Input Dataset', defval=true, group='Fourier Input', tooltip='Subtracts the mean of the data set from each element and normalizes the result ' + 'by the standard deviation')
freqdomain = input.bool(title='Show Frequency-Domain Power Spectrum', defval=false, group='Fourier Output', tooltip='Plots the frequency spectrum of the squared magnitudes ' + 'of the Fourier coefficients (which are a measure of spectral power). ' + 'Zero frequency is omitted.')
istable = input.bool(title='Dominant Cycles, Rows:', defval=false, group='Fourier Output', inline='lineo1')
ntabfreqs = input.int(title='', defval=5, minval=1, group='Fourier Output', inline='lineo1', tooltip='Shows the table with the info about N most significant freqeuncy components. \n' + '-1st column: component number (N) \n' + '-2nd column: period of the component (in the units of input data resolution) \n' + '-3d column: relative power (normalized to the maximum power)')
//timedomain = input.bool(title='Show Inverse Fourier Transform (Filtered)', defval=false, group='Fourier Output', tooltip='Reconstructs and plots the dataset in the time domain, blocking ' + 'frequency components outside of the cutoff frequencies defined below.')
ismoving = input.bool(title='Apply FFT Filter in a Moving Window', defval=true, group='Fourier Output', tooltip='Applies the filter for each bar within ' + 'the time range defined below.')
islowthrs = input.bool(title='', defval=true, group='Filtered Fourier Components', inline='linef1')
N_first = input.int(title='Lowest Allowed N', defval=1, minval=0, group='Filtered Fourier Components', tooltip='The number of the lowest frequency component allowed to pass. ' + 'Frequency components above it will be blocked.', inline='linef1')
ishghthrs = input.bool(title='', defval=true, group='Filtered Fourier Components', inline='linef2')
N_last = input.int(title='Highest Allowed N ', defval=12, minval=0, group='Filtered Fourier Components', tooltip='The number of the highest frequency component allowed to pass. ' + 'Frequency components above it will be blocked.', inline='linef2')
fixedstart = input.bool(title='', group='Fourier Filtering Time Range', inline='linebac1', defval=false)
filter_start = input.time(title='', inline='linebac1', group='Fourier Filtering Time Range', defval=timestamp('01 Jan 2020 13:30 +0000'), tooltip='If deactivated, filtering stars from the first available bar.')
fixedend = input.bool(title='', group='Fourier Filtering Time Range', inline='linebac2', defval=false)
filter_end = input.time(title='', inline='linebac2', group='Fourier Filtering Time Range', defval=timestamp('30 Dec 2080 23:30 +0000'), tooltip='If deactivated, filtering ends at the last available bar.')
//-- VMA Filter --
use_vma_filter = input.bool(defval=true,title="Use VMA Filter",group="VMA Filter")
vma_src = input.source(defval=close,title="VMA Src",group="VMA Filter")
vma_length = input.int(defval=65,title="VMA Length",group="VMA Filter")
vma_timeframe = input.timeframe(defval="240",title="VMA Time Frame",group="VMA Filter")
allow_vma_filter_long = input.string(defval="Green or Blue",options=["Green","Blue","Red","Green or Blue","Blue or Red","Red or Green"],title="Allow Long When",group="VMA Filter")
allow_vma_filter_short = input.string(defval="Blue",options=["Green","Blue","Red","Green or Blue","Blue or Red","Red or Green"],title="Allow Short When",group="VMA Filter")
use_vma_filter_stop_loss = input.bool(defval=false,title="Use VMA Filter Stop Loss",group="VMA Filter Stop Loss")
cancel_long_when_vma_filter = input.string(defval="Red",options=["Green","Blue","Red","Green or Blue","Blue or Red","Red or Green"],title="Cancel Long When",group="VMA Filter Stop Loss")
cancel_short_when_vma_filter = input.string(defval="Green",options=["Green","Blue","Red","Green or Blue","Blue or Red","Red or Green"],title="Cancel Short When",group="VMA Filter Stop Loss")
//-- Aroon Filter --
use_aroon_filter_long = input.bool(defval=true,title="Use Aroon Filter Long",group="Aroon Filter")
use_aroon_filter_short = input.bool(defval=true,title="Use Aroon Filter Short",group="Aroon Filter")
aroon_length_long = input.int(defval=13,title="Length Long", minval=1,group="Aroon Filter")
aroon_length_short = input.int(defval=13,title="Length Short", minval=1,group="Aroon Filter")
aroon_upper_long_req = input.float(defval=1,title="Green (Upper) Line Below % (Long)", minval=0,maxval=100,group="Aroon Filter",inline='aroon_l1')
aroon_lower_long_req = input.float(defval=99,title="Red (Lower) Line Above % (Long)", minval=0,maxval=100,group="Aroon Filter",inline='aroon_l1')
aroon_upper_short_req = input.float(defval=99,title="Green (Upper) Line Above % (Short)", minval=0,maxval=100,group="Aroon Filter",inline='aroon_l2')
aroon_lower_short_req = input.float(defval=1,title="Red (Lower) Line Below % (Short)", minval=0,maxval=100,group="Aroon Filter",inline='aroon_l2')
aroon_upper_long = 100 * (ta.highestbars(high, aroon_length_long+1) + aroon_length_long)/aroon_length_long
aroon_lower_long = 100 * (ta.lowestbars(low, aroon_length_long+1) + aroon_length_long)/aroon_length_long
aroon_upper_short = 100 * (ta.highestbars(high, aroon_length_short+1) + aroon_length_short)/aroon_length_short
aroon_lower_short = 100 * (ta.lowestbars(low, aroon_length_short+1) + aroon_length_short)/aroon_length_short
aroonLongCross = false
if(aroon_upper_long < aroon_upper_long_req and aroon_lower_long > aroon_lower_long_req and strategy.position_size>0)
aroonLongCross := true
aroonShortCross = false
if(aroon_upper_short > aroon_upper_short_req and aroon_lower_short < aroon_lower_short_req and strategy.position_size<0)
aroonShortCross := true
plot(aroon_upper_long*0.05 - 2.5, "Aroon Up Long", color=color.rgb(0,255,0,70), linewidth = 1,display=(use_aroon_filter_long ? display.all : display.none))
plot(aroon_lower_long*0.05 - 2.5, "Aroon Down Long", color=color.rgb(255,0,0,70), linewidth = 1,display=(use_aroon_filter_long ? display.all : display.none))
plot(aroon_upper_long*0.05 - 2.5, "Aroon Up Short", color=color.rgb(0,255,0,70), linewidth = 1,display=(use_aroon_filter_short ? display.all : display.none))
plot(aroon_lower_long*0.05 - 2.5, "Aroon Down Short", color=color.rgb(255,0,0,70), linewidth = 1,display=(use_aroon_filter_short ? display.all : display.none))
//Arroon Points
//long
aroon_high_boundary_long = 5 * (0+aroon_upper_long_req*0.01) - 2.5
aroon_low_boundary_long = 5 * (0+aroon_lower_long_req*0.01) - 2.5
h1_arroon_long_upper = hline(aroon_high_boundary_long,color=color.green,display=(use_aroon_filter_long ? display.all : display.none))
h2_arroon_long_lower = hline(aroon_low_boundary_long,color=color.red,display=(use_aroon_filter_long ? display.all : display.none))
//short
aroon_high_boundary_short = 5 * (0+aroon_upper_short_req*0.01) - 2.5
aroon_low_boundary_short = 5 * (0+aroon_lower_short_req*0.01) - 2.5
h1_arroon_short_upper = hline(aroon_high_boundary_short,color=color.green,display=(use_aroon_filter_short ? display.all : display.none))
h2_arroon_short_lower = hline(aroon_low_boundary_short,color=color.red,display=(use_aroon_filter_short ? display.all : display.none))
// -- Strategy Specific --
allow_long = input.bool(defval=true,title="Long",group="Allow Entry")
allow_short = input.bool(defval=true,title="Short",group="Allow Entry")
use_stop_loss_long = input.bool(defval=true,title="Use Long",group="Stop Loss")
stop_loss_long_percentage = input.float(defval=7.5,title="Long %",group="Stop Loss") * .01
use_stop_loss_short = input.bool(defval=true,title="Use Short",group="Stop Loss")
stop_loss_short_percentage = input.float(defval=8.0,title="Short %",group="Stop Loss") * .01
use_trailing_stop_loss_long = input.bool(defval=false,title="Use Long",group="Trailing Stop Loss")
trailing_stop_loss_long_percentage = input.float(defval=2.0,title="Long %",group="Trailing Stop Loss") * .01
use_trailing_stop_loss_short = input.bool(defval=false,title="Use Short",group="Trailing Stop Loss")
trailing_stop_loss_short_percentage = input.float(defval=2.0,title="Short %",group="Trailing Stop Loss") * .01
use_take_profit_long = input.bool(defval=true,title="Use Long",group="Take Profit")
take_profit_long_percentage = input.float(defval=105,title="Long %",group="Take Profit") * .01
use_take_profit_short = input.bool(defval=true,title="Use Short",group="Take Profit")
take_profit_short_percentage = input.float(defval=50,title="Short %",group="Take Profit") * .01
use_trailing_take_profit_long = input.bool(defval=false,title="Use Long",group="Trailing Take Profit")
trailing_take_profit_long_min_profit_percentage = input.float(defval=10,title="Activation Minimum Profit Long %",group="Trailing Take Profit") * .01
trailing_take_profit_long_percentage = input.float(defval=2.0,title="Trailing Stop Long %",group="Trailing Take Profit") * .01
use_trailing_take_profit_short = input.bool(defval=false,title="Use Short",group="Trailing Take Profit")
trailing_take_profit_short_min_profit_percentage = input.float(defval=10,title="Activation Minimum Profit Short %",group="Trailing Take Profit") * .01
trailing_take_profit_short_percentage = input.float(defval=2.0,title="Trailing Stop Short %",group="Trailing Take Profit") * .01
//
//
// --- Initialiation ---
bool isinrange = (fixedstart ? time >= filter_start : true) and (fixedend ? time <= filter_end : true)
var line[] tLines = array.new_line(N-1)
var line[] fLines = array.new_line(N/2-2)
//
// Look back and see how many datapoints are available
int m = int(math.log(N)/math.log(2)) // approximate log2
int newM = 0
for j = 1 to m
if na(src[math.pow(2, j)])
break
newM := j
// Use fewer datapoints, if there is not enough
m := newM
N := int(math.pow(2, newM))
//
//
// -- Collect the data and apply FFT---
float[] dat_re = array.new_float(na)
float[] dat_im = array.new_float(na)
if N > 1 and (isinrange and ismoving or barstate.islast)
for i = 0 to N - 1
array.push(dat_re, src[i])
array.push(dat_im, 0.0)
if ispp
dat_re := array.standardize(dat_re)
dat_re
// forward FFT
fft.fft(dat_re, dat_im, "Forward")
//
//
// Collect Fourier amplitudes squared (powers)
float[] power = array.new_float(na)
if barstate.islast and N > 1
for i = 0 to N-1
array.push(power,math.pow(array.get(dat_re,i),2) + math.pow(array.get(dat_im,i),2))
array.set(power,0,0.0) // make sure that the 0th component doesn't affect the power spectrum
//
//
// -- Apply inverse FFT using selected frequency components --
float[] dat_re_filt = array.new_float(N)
float[] dat_im_filt = array.new_float(N)
N_first := islowthrs ? math.min(math.min(N_first, N_last), N / 2) : 0
N_last := ishghthrs ? math.min(N_last, N / 2) : N / 2
// Apply the bandpass filter
if N > 1 and (isinrange and ismoving or barstate.islast)
array.fill(dat_re_filt, 0.0)
array.fill(dat_im_filt, 0.0)
for i = N_first to N_last by 1
array.set(dat_re_filt, i, array.get(dat_re, i))
array.set(dat_im_filt, i, array.get(dat_im, i))
if i != 0
array.set(dat_re_filt, N - i, array.get(dat_re, N - i))
array.set(dat_im_filt, N - i, array.get(dat_im, N - i))
//inverse FFT
fft.fft(dat_re_filt, dat_im_filt, "Inverse")
//
// Apply the filter to real-time data
float src_filtered = ismoving and isinrange ? array.get(dat_re_filt, 0) : na
//
//
// --- Plotting ---
// Time-domain subplot
// if (barstate.islast) and timedomain and N > 1
// for i = 1 to N - 1
// float y_plt1 = array.get(dat_re_filt, i)
// float y_plt2 = array.get(dat_re_filt, i - 1)
// array.push(tLines, line.new(bar_index[i], y_plt1, bar_index[i - 1], y_plt2, width=2, color=#DE3163))
// line.delete(array.shift(tLines))
//
// Frequency-domain subplot
if (barstate.islast) and freqdomain and N > 1
float y_zero = array.max(dat_re_filt)
float y_scale = (array.max(dat_re_filt) - array.min(dat_re_filt)) / array.max(power)
line yax = line.new(bar_index, y_zero, bar_index[int(N / 2) + 5], y_zero, style=line.style_arrow_right, color=color.silver)
label ylb = label.new(bar_index[int(N / 2) + 6], y_zero, text='f', style=label.style_none, textcolor=color.silver)
line.delete( yax[1])
label.delete(ylb[1])
for i = 0 to int(N / 2)-2
isinwindow = i >= N_first and i <= N_last
float y_plt = array.get(power, i)
array.push(fLines, line.new(bar_index[i], y_zero, bar_index[i], y_plt * y_scale + y_zero, width=3, color=isinwindow ? #DE3163 : #AED6F1) )
line.delete(array.shift(fLines))
//
//
// --- Table ---
var table panel = table.new(position.top_right, 3, ntabfreqs + 1)
if (barstate.islast) and istable and N > 1
ntabfreqs := math.min(ntabfreqs, N / 2)
// Table header
table.cell(panel, 0, 0, 'N', bgcolor=#AED6F1, text_size=size.small)
table.cell(panel, 1, 0, 'Cycle Period', bgcolor=#AED6F1, text_size=size.small)
table.cell(panel, 2, 0, 'Rel. Power', bgcolor=#AED6F1, text_size=size.small)
// drop zero frequency from power array and sort it
power_sorted = array.copy(power)
array.remove(power_sorted, 0)
array.sort(power_sorted, order.descending)
//
for i = 0 to ntabfreqs - 1 by 1
// Period in left column
id = array.indexof(power, array.get(power_sorted, 2 * i))
table.cell(panel, 0, i + 1, str.format("{0,number,#}",id), bgcolor=#DFEEF7, text_size=size.small)
table.cell(panel, 1, i + 1, str.format("{0,number,#.#}",float(N) / float(id)), text_color=color.black, bgcolor=#DFEEF7, text_size=size.small)
table.cell(panel, 2, i + 1, str.format("{0,number,#.####}", array.get(power_sorted, 2 * i) / array.get(power_sorted, 0)), text_color=color.black, bgcolor=#DFEEF7, text_size=size.small)
//
//VMA (credit to LazyBear) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
makevma(src,l) =>
k = 1.0/l
pdm = math.max((src - src[1]), 0)
mdm = math.max((src[1] - src), 0)
pdmS = 0.0
pdmS := ((1 - k)*nz(pdmS[1]) + k*pdm)
mdmS = 0.0
mdmS := ((1 - k)*nz(mdmS[1]) + k*mdm)
s = pdmS + mdmS
pdi = pdmS/s
mdi = mdmS/s
pdiS = 0.0
pdiS := ((1 - k)*nz(pdiS[1]) + k*pdi)
mdiS = 0.0
mdiS := ((1 - k)*nz(mdiS[1]) + k*mdi)
d = math.abs(pdiS - mdiS)
s1 = pdiS + mdiS
iS = 0.0
iS := ((1 - k)*nz(iS[1]) + k*d/s1)
hhv = ta.highest(iS, l)
llv = ta.lowest(iS, l)
d1 = hhv - llv
vI = (iS - llv)/d1
vma = 0.0
vma := (1 - k*vI)*nz(vma[1]) + k*vI*src
vmaC=(vma > vma[1]) ? color.green : (vma<vma[1]) ? color.red : (vma==vma[1]) ? color.blue : color.black
[vma,vmaC]
[vma,vmaC] = makevma(vma_src,vma_length)
vma_val = request.security(syminfo.tickerid, vma_timeframe=="Same as chart" ? timeframe.period : vma_timeframe,vma[1], barmerge.gaps_off, barmerge.lookahead_on)
vmaC_val = request.security(syminfo.tickerid, vma_timeframe=="Same as chart" ? timeframe.period : vma_timeframe,vmaC[1], barmerge.gaps_off, barmerge.lookahead_on)
met_vma_filter_rules(direction,vma_color) =>
met_filter_rules = false
//["Green","Blue","Red","Green or Blue","Blue or Red","Red or Green"]
if(direction=="long")
if(allow_vma_filter_long=="Green" and vma_color==color.green)
met_filter_rules := true
if(allow_vma_filter_long=="Red" and vma_color==color.red)
met_filter_rules := true
if(allow_vma_filter_long=="Blue" and vma_color==color.blue)
met_filter_rules := true
if(allow_vma_filter_long=="Green or Blue" and (vma_color==color.green or vma_color==color.blue))
met_filter_rules := true
if(allow_vma_filter_long=="Blue or Red" and (vma_color==color.blue or vma_color==color.red))
met_filter_rules := true
if(allow_vma_filter_long=="Red or Green" and (vma_color==color.red or vma_color==color.green))
met_filter_rules := true
if(direction=="short")
if(allow_vma_filter_short=="Green" and vma_color==color.green)
met_filter_rules := true
if(allow_vma_filter_short=="Red" and vma_color==color.red)
met_filter_rules := true
if(allow_vma_filter_short=="Blue" and vma_color==color.blue)
met_filter_rules := true
if(allow_vma_filter_short=="Green or Blue" and (vma_color==color.green or vma_color==color.blue))
met_filter_rules := true
if(allow_vma_filter_short=="Blue or Red" and (vma_color==color.blue or vma_color==color.red))
met_filter_rules := true
if(allow_vma_filter_short=="Red or Green" and (vma_color==color.red or vma_color==color.green))
met_filter_rules := true
met_filter_rules
met_vma_cancel_rules(direction,vma_color) =>
met_cancel_rules = false
//["Green","Blue","Red","Green or Blue","Blue or Red","Red or Green"]
if(direction=="long")
if(cancel_long_when_vma_filter=="Green" and vma_color==color.green)
met_cancel_rules := true
if(cancel_long_when_vma_filter=="Red" and vma_color==color.red)
met_cancel_rules := true
if(cancel_long_when_vma_filter=="Blue" and vma_color==color.blue)
met_cancel_rules := true
if(cancel_long_when_vma_filter=="Green or Blue" and (vma_color==color.green or vma_color==color.blue))
met_cancel_rules := true
if(cancel_long_when_vma_filter=="Blue or Red" and (vma_color==color.blue or vma_color==color.red))
met_cancel_rules := true
if(cancel_long_when_vma_filter=="Red or Green" and (vma_color==color.red or vma_color==color.green))
met_cancel_rules := true
if(direction=="short")
if(cancel_short_when_vma_filter=="Green" and vma_color==color.green)
met_cancel_rules := true
if(cancel_short_when_vma_filter=="Red" and vma_color==color.red)
met_cancel_rules := true
if(cancel_short_when_vma_filter=="Blue" and vma_color==color.blue)
met_cancel_rules := true
if(cancel_short_when_vma_filter=="Green or Blue" and (vma_color==color.green or vma_color==color.blue))
met_cancel_rules := true
if(cancel_short_when_vma_filter=="Blue or Red" and (vma_color==color.blue or vma_color==color.red))
met_cancel_rules := true
if(cancel_short_when_vma_filter=="Red or Green" and (vma_color==color.red or vma_color==color.green))
met_cancel_rules := true
met_cancel_rules
//Plots & Boundaries
plot(src_filtered, color=(use_vma_filter ? vmaC_val : color.orange), title='filtered', linewidth=3)
plot(aroonLongCross ? src_filtered : na,color=color.green,style=plot.style_cross,linewidth=4,display=(use_aroon_filter_long ? display.all : display.none))
plot(aroonShortCross ? src_filtered : na,color=color.red,style=plot.style_cross,linewidth=4,display=(use_aroon_filter_short ? display.all : display.none))
hline(0)
//Actual Strategy Entries
if(src_filtered>0 and src_filtered[1]<=0)
//If any the filter fails for any reason then no entry is allowed
passed_vma_filter = true
if(use_vma_filter)
passed_vma_filter := met_vma_filter_rules("long",vmaC_val)
if(passed_vma_filter) //If it's disabled it assumes it passed by defaulting to true
if(allow_long==true)
strategy.entry("long",strategy.long)
else
strategy.close("short")
if(src_filtered<0 and src_filtered[1]>=0)
//If any the filter fails for any reason then no entry is allowed
passed_vma_filter = true
if(use_vma_filter)
passed_vma_filter := met_vma_filter_rules("short",vmaC_val)
if(passed_vma_filter)
if(allow_short==true)
strategy.entry("short",strategy.short)
else
strategy.close("long")
//VMA Stop Loss
passed_vma_cancel_long = false
passed_vma_cancel_short = false
if(use_vma_filter_stop_loss)
if(allow_long==true and strategy.position_size>0)
passed_vma_cancel_long := met_vma_cancel_rules("long",vmaC_val)
if(passed_vma_cancel_long==true)
strategy.close("long",comment="vma cancel")
if(allow_short==true and strategy.position_size<0)
passed_vma_cancel_short := met_vma_cancel_rules("short",vmaC_val)
if(passed_vma_cancel_short==true)
strategy.close("short",comment="vma cancel")
//Aroon Stop Loss
if(allow_long==true and strategy.position_size>0 and aroonLongCross and use_aroon_filter_long)
strategy.close("long",comment="aroon long stop loss")
if(allow_short==true and strategy.position_size<0 and aroonShortCross and use_aroon_filter_short)
strategy.close("short",comment="aroon short stop loss")
//Stop Loss, Take Profit, Trailing Stop Loss & Trailing Take Profit
stop_loss_value_long = strategy.position_avg_price*(1 - stop_loss_long_percentage)
take_profit_value_long = strategy.position_avg_price*(1 + take_profit_long_percentage)
stop_loss_value_short = strategy.position_avg_price*(1 + stop_loss_short_percentage)
take_profit_value_short = strategy.position_avg_price*(1 - take_profit_short_percentage)
// Determine trail stop loss prices
longStopPrice = 0.0
longStopPrice := if (strategy.position_size > 0)
stopValue = close * (1 - trailing_stop_loss_long_percentage)
math.max(stopValue, longStopPrice[1])
else
0
// Determine trailing short price
shortStopPrice = 0.0
shortStopPrice := if (strategy.position_size < 0)
stopValue = close * (1 + trailing_stop_loss_short_percentage)
math.min(stopValue, shortStopPrice[1])
else
999999
// Determine trailing take profit long price
longTPStopPrice = 0.0
var longTPActive = false //To keep track of once the stop loss becomes active
if(close>(strategy.opentrades.entry_price(0) * (1+trailing_take_profit_long_min_profit_percentage)))
longTPActive := true
longTPStopPrice := if (strategy.position_size >0)
stopValue = close * (1 - trailing_take_profit_long_percentage)
math.max(stopValue, longTPStopPrice[1])
else
0
// Determine trailing take profit short price
shortTPStopPrice = 0.0
var shortTPActive = false //To keep track of once the stop loss becomes active
if(close<(strategy.opentrades.entry_price(0) * (1-trailing_take_profit_short_min_profit_percentage)))
shortTPActive := true
shortTPStopPrice := if (strategy.position_size < 0)
stopValue = close * (1 + trailing_take_profit_short_percentage)
math.min(stopValue, shortTPStopPrice[1])
else
999999
//plot(longStopPrice,color=color.orange)
//plot(shortStopPrice,color=color.teal)
if(use_trailing_stop_loss_long and close<=longStopPrice and close>strategy.opentrades.entry_price(0))
strategy.close("long",comment="Trailing Stop Loss Long")
if(use_trailing_stop_loss_short and close>=shortStopPrice and close<strategy.opentrades.entry_price(0))
strategy.close("short",comment="Trailing Stop Loss Short")
// Only when the trailing take profit becomes activated at its profit target will the trailing stop losses be allowed to trigger and therefore close below
if(use_trailing_take_profit_long and close<=longTPStopPrice and longTPActive==true)
strategy.close("long",comment="Trailing Take Profit Stop Loss Long")
if(use_trailing_take_profit_short and close>=shortTPStopPrice and shortTPActive==true)
strategy.close("short",comment="Trailing Take Profit Stop Loss Short")
//Stop Loss, Take Profit & Trailing Stop Loss
if(strategy.position_size>0) //Creates exit condition once long order is detected
strategy.exit(id="TP/SL Long",from_entry="long", limit=use_take_profit_long ? take_profit_value_long : na, stop=use_stop_loss_long ? stop_loss_value_long : na,comment_loss = "Stop Loss Long",comment_profit = "Take Profit Long",comment_trailing = "Trailing Stop Loss Long")
if(strategy.position_size<0) //Creates exit condition once short order is detected
strategy.exit(id="TP/SL Short",from_entry="short", limit=use_take_profit_short ? take_profit_value_short : na, stop=use_stop_loss_short ? stop_loss_value_short : na,comment_loss = "Stop Loss Short",comment_profit = "Take Profit Short",comment_trailing = "Trailing Stop Loss Short")
//Reset variables when any order is closed, exited or flipped direction
if(strategy.opentrades == 0 or (strategy.position_size != strategy.position_size[1]))
longTPActive := false
shortTPActive := false |
TradePro's 2 EMA + Stoch RSI + ATR Strategy | https://www.tradingview.com/script/BUsgoYjm-TradePro-s-2-EMA-Stoch-RSI-ATR-Strategy/ | PtGambler | https://www.tradingview.com/u/PtGambler/ | 516 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © PtGambler
//@version=5
strategy("2 EMA + Stoch RSI + ATR [Pt]", shorttitle = "2EMA+Stoch+ATR", overlay=true, initial_capital = 10000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, calc_on_order_fills = false, max_bars_back = 500)
// ********************************** Trade Period / Strategy Setting **************************************
startY = input(title='Start Year', defval=2011, group = "Backtesting window")
startM = input.int(title='Start Month', defval=1, minval=1, maxval=12, group = "Backtesting window")
startD = input.int(title='Start Day', defval=1, minval=1, maxval=31, group = "Backtesting window")
finishY = input(title='Finish Year', defval=2050, group = "Backtesting window")
finishM = input.int(title='Finish Month', defval=12, minval=1, maxval=12, group = "Backtesting window")
finishD = input.int(title='Finish Day', defval=31, minval=1, maxval=31, group = "Backtesting window")
timestart = timestamp(startY, startM, startD, 00, 00)
timefinish = timestamp(finishY, finishM, finishD, 23, 59)
// ******************************************************************************************
group_ema = "EMA"
group_stoch = "Stochastic RSI"
group_atr = "ATR Stoploss Finder"
// ----------------------------------------- 2 EMA -------------------------------------
ema1_len = input.int(50, "EMA Length 1", group = group_ema)
ema2_len = input.int(200, "EMA Length 2", group = group_ema)
ema1 = ta.ema(close, ema1_len)
ema2 = ta.ema(close, ema2_len)
plot(ema1, "ema1", color.white, linewidth = 2)
plot(ema2, "ema2", color.orange, linewidth = 2)
ema_bull = ema1 > ema2
ema_bear = ema1 < ema2
// -------------------------------------- Stochastic RSI -----------------------------
smoothK = input.int(3, "K", minval=1, group = group_stoch)
smoothD = input.int(3, "D", minval=1, group = group_stoch)
lengthRSI = input.int(14, "RSI Length", minval=1, group = group_stoch)
lengthStoch = input.int(14, "Stochastic Length", minval=1, group = group_stoch)
src = close
rsi1 = ta.rsi(src, lengthRSI)
k = ta.sma(ta.stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)
d = ta.sma(k, smoothD)
var trigger_stoch_OB = k > 80
var trigger_stoch_OS = k < 20
stoch_crossdown = ta.crossunder(k, d)
stoch_crossup = ta.crossover(k, d)
P_hi = ta.pivothigh(k,1,1)
P_lo = ta.pivotlow(k,1,1)
previous_high = ta.valuewhen(P_hi, k, 1)
previous_low = ta.valuewhen(P_lo, k, 1)
recent_high = ta.valuewhen(P_hi, k, 0)
recent_low = ta.valuewhen(P_lo, k, 0)
// --------------------------------------- ATR stop loss finder ------------------------
length = input.int(title='Length', defval=14, minval=1, group = group_atr)
smoothing = input.string(title='Smoothing', defval='EMA', options=['RMA', 'SMA', 'EMA', 'WMA'], group = group_atr)
m = input.float(0.7, 'Multiplier', step = 0.1, group = group_atr)
src1 = input(high, "Source for upper band", group = group_atr)
src2 = input(low, "Source for lower band", group = group_atr)
showatr = input.bool(true, 'Show ATR Bands', group = group_atr)
collong = input.color(color.purple, 'Long ATR SL', inline='1', group = group_atr)
colshort = input.color(color.purple, 'Short ATR SL', inline='2', group = group_atr)
ma_function(source, length) =>
if smoothing == 'RMA'
ta.rma(source, length)
else
if smoothing == 'SMA'
ta.sma(source, length)
else
if smoothing == 'EMA'
ta.ema(source, length)
else
ta.wma(source, length)
a = ma_function(ta.tr(true), length) * m
up = ma_function(ta.tr(true), length) * m + src1
down = src2 - ma_function(ta.tr(true), length) * m
p1 = plot(showatr ? up : na, title='ATR Short Stop Loss', color=colshort)
p2 = plot(showatr ? down : na, title='ATR Long Stop Loss', color=collong)
// ******************************* Profit Target / Stop Loss *********************************************
RR = input.float(2.0, "Reward to Risk ratio (X times SL)", step = 0.1, group = "Profit Target")
breakeven = input.bool(true, "Move SL to breakeven when RR hit", group = "Profit Target", inline = 'breakenven')
be_RR = input.float(1.0, "", inline = 'breakeven', group = "Profit Target")
var L_PT = 0.0
var S_PT = 0.0
var L_SL = 0.0
var S_SL = 0.0
var L_be_PT = 0.0
var S_be_PT = 0.0
BSLE = ta.barssince(strategy.opentrades.entry_bar_index(0) == bar_index)
entry_price = strategy.position_size != 0 ? strategy.opentrades.entry_price(0) : na
if strategy.position_size > 0 //and BSLE == 1
L_PT := L_PT[1]
L_SL := (breakeven and high >= L_be_PT) ? entry_price : L_SL[1]
S_PT := close - (up - close)*RR
S_SL := up
L_be_PT := L_be_PT[1]
S_be_PT := close - (up - close)*be_RR
else if strategy.position_size < 0 //and BSLE == 1
S_PT := S_PT[1]
S_SL := (breakeven and low <= S_be_PT) ? entry_price : S_SL[1]
L_PT := close + (close-down)*RR
L_SL := down
S_be_PT := S_be_PT[1]
L_be_PT := close + (close-down)*be_RR
else if strategy.position_size != 0
L_PT := L_PT[1]
S_PT := S_PT[1]
else
L_PT := close + (close-down)*RR
L_SL := down
S_PT := close - (up - close)*RR
S_SL := up
L_be_PT := close + (close-down)*be_RR
S_be_PT := close - (up - close)*be_RR
entry_line = plot(entry_price, "Entry Price", color.white, linewidth = 1, style = plot.style_linebr)
L_PT_line = plot(strategy.position_size > 0 and BSLE > 0 ? L_PT : na, "L PT", color.green, linewidth = 2, style = plot.style_linebr)
S_PT_line = plot(strategy.position_size < 0 and BSLE > 0 ? S_PT : na, "S PT", color.green, linewidth = 2, style = plot.style_linebr)
L_SL_line = plot(strategy.position_size > 0 and BSLE > 0 ? L_SL : na, "L SL", color.red, linewidth = 2, style = plot.style_linebr)
S_SL_line = plot(strategy.position_size < 0 and BSLE > 0 ? S_SL : na, "S SL", color.red, linewidth = 2, style = plot.style_linebr)
L_be_PT_line = plot(strategy.position_size > 0 and BSLE > 0 ? L_be_PT : na, "L BE PT", color.blue, linewidth = 2, style = plot.style_linebr)
S_be_PT_line = plot(strategy.position_size < 0 and BSLE > 0 ? S_be_PT : na, "S BE PT", color.blue, linewidth = 2, style = plot.style_linebr)
fill(L_PT_line, entry_line, color = color.new(color.green,90))
fill(S_PT_line, entry_line, color = color.new(color.green,90))
fill(L_SL_line, entry_line, color = color.new(color.red,90))
fill(S_SL_line, entry_line, color = color.new(color.red,90))
// ---------------------------------- strategy setup ------------------------------------------------------
var L_entry_trigger1 = false
var S_entry_trigger1 = false
L_entry_trigger1 := ema_bull and close < ema1 and k < 20 and strategy.position_size == 0
S_entry_trigger1 := ema_bear and close > ema1 and k > 80 and strategy.position_size == 0
L_entry1 = L_entry_trigger1[1] and stoch_crossup and recent_low > previous_low
S_entry1 = S_entry_trigger1[1] and stoch_crossdown and recent_high < previous_high
//debugging
plot(L_entry_trigger1[1]?1:0, "L Entry Trigger")
plot(stoch_crossup?1:0, "Stoch Cross Up")
plot(recent_low > previous_low?1:0, "Higher low")
plot(S_entry_trigger1[1]?1:0, "S Entry Trigger")
plot(stoch_crossdown?1:0, "Stoch Cross down")
plot(recent_high < previous_high?1:0, "Lower high")
if L_entry1
strategy.entry("Long", strategy.long)
if S_entry1
strategy.entry("Short", strategy.short)
strategy.exit("Exit Long", "Long", limit = L_PT, stop = L_SL, comment_profit = "Exit Long, PT hit", comment_loss = "Exit Long, SL hit")
strategy.exit("Exit Short", "Short", limit = S_PT, stop = S_SL, comment_profit = "Exit Short, PT hit", comment_loss = "Exit Short, SL hit")
//resetting triggers
L_entry_trigger1 := L_entry_trigger1[1] ? L_entry1 or ema_bear or S_entry1 ? false : true : L_entry_trigger1
S_entry_trigger1 := S_entry_trigger1[1] ? S_entry1 or ema_bull or L_entry1 ? false : true : S_entry_trigger1
//Trigger zones
bgcolor(L_entry_trigger1 ? color.new(color.green ,90) : na)
bgcolor(S_entry_trigger1 ? color.new(color.red,90) : na) |
Quarterly Returns in Strategies vs Buy & Hold | https://www.tradingview.com/script/jmn6Bw7n-Quarterly-Returns-in-Strategies-vs-Buy-Hold/ | Dannnnnnny | https://www.tradingview.com/u/Dannnnnnny/ | 24 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Dannnnnnny
//@version=4
strategy(title="Quarterly Returns in Strategies vs Buy & Hold", initial_capital= 1000, overlay=true,default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, commission_value = 0.1)
maLength= input(400)
wma= vwma(hl2,maLength)
uptrend= rising(wma, 5)
downtrend= falling(wma,5)
plot(wma)
if uptrend
strategy.entry("Buy", strategy.long)
else
strategy.close("Buy")//
///////////////////
// QUARTERLY TABLE //
enableQuarterlyTable = input(title="Enable Quarterly Return table", type=input.bool, defval=false)
enableCompareWithMarket = input(title="Compare with Market Benchmark", type=input.bool, defval=false)
table_position = input(title="Table Position", type=input.string, defval='bottom_right', options=['bottom_right','bottom_left','top_right', 'top_left'])
precision = 2
new_quarter = ceil(month(time)/3) != ceil(month(time[1])/3)
new_year = year(time) != year(time[1])
eq = strategy.equity
bar_pnl = eq / eq[1] - 1
bar_bh = (close-close[1])/close[1]
cur_quarter_pnl = 0.0
cur_year_pnl = 0.0
cur_quarter_bh = 0.0
cur_year_bh = 0.0
// Current Quarterly P&L
cur_quarter_pnl := new_quarter ? 0.0 :
(1 + cur_quarter_pnl[1]) * (1 + bar_pnl) - 1
cur_quarter_bh := new_quarter ? 0.0 :
(1 + cur_quarter_bh[1]) * (1 + bar_bh) - 1
// Current Yearly P&L
cur_year_pnl := new_year ? 0.0 :
(1 + cur_year_pnl[1]) * (1 + bar_pnl) - 1
cur_year_bh := new_year ? 0.0 :
(1 + cur_year_bh[1]) * (1 + bar_bh) - 1
// Arrays to store Yearly and Quarterly P&Ls
var quarter_pnl = array.new_float(0)
var quarter_time = array.new_int(0)
var quarter_bh = array.new_float(0)
var year_pnl = array.new_float(0)
var year_time = array.new_int(0)
var year_bh = array.new_float(0)
end_time = false
end_time:= time_close + (time_close - time_close[1]) > timenow or barstate.islastconfirmedhistory
if (not na(cur_quarter_pnl[1]) and (new_quarter or end_time))
if (end_time[1])
array.pop(quarter_pnl)
array.pop(quarter_time)
array.push(quarter_pnl , cur_quarter_pnl[1])
array.push(quarter_time, time[1])
array.push(quarter_bh , cur_quarter_bh[1])
if (not na(cur_year_pnl[1]) and (new_year or end_time))
if (end_time[1])
array.pop(year_pnl)
array.pop(year_time)
array.push(year_pnl , cur_year_pnl[1])
array.push(year_time, time[1])
array.push(year_bh , cur_year_bh[1])
// Quarterly P&L Table
var quarterly_table = table(na)
getCellColor(pnl, bh) =>
if pnl > 0
if bh < 0 or pnl > 2 * bh
color.new(color.green, transp = 20)
else if pnl > bh
color.new(color.green, transp = 50)
else
color.new(color.green, transp = 80)
else
if bh > 0 or pnl < 2 * bh
color.new(color.red, transp = 20)
else if pnl < bh
color.new(color.red, transp = 50)
else
color.new(color.red, transp = 80)
if (end_time and enableQuarterlyTable)
quarterly_table := table.new(table_position, columns = 14, rows = array.size(year_pnl) + 1, border_width = 1)
table.cell(quarterly_table, 0, 0, "", bgcolor = #cccccc)
table.cell(quarterly_table, 1, 0, "Q1", bgcolor = #cccccc)
table.cell(quarterly_table, 2, 0, "Q2", bgcolor = #cccccc)
table.cell(quarterly_table, 3, 0, "Q3", bgcolor = #cccccc)
table.cell(quarterly_table, 4, 0, "Q4", bgcolor = #cccccc)
table.cell(quarterly_table, 5, 0, "Year", bgcolor = #999999)
for yi = 0 to array.size(year_pnl) - 1
table.cell(quarterly_table, 0, yi + 1, tostring(year(array.get(year_time, yi))), bgcolor = #cccccc)
y_color = getCellColor(array.get(year_pnl, yi), array.get(year_bh, yi))
table.cell(quarterly_table, 5, yi + 1, enableCompareWithMarket ? tostring(round(array.get(year_pnl, yi) * 100, precision)) + " (" + tostring(round(array.get(year_bh, yi) * 100, precision)) + ")" : tostring(round(array.get(year_pnl, yi) * 100, precision)), bgcolor = y_color, text_color=#bfbfbf)
for mi = 0 to array.size(quarter_time) - 1
m_row = year(array.get(quarter_time, mi)) - year(array.get(year_time, 0)) + 1
m_col = ceil(month(array.get(quarter_time, mi)) / 3)
m_color = getCellColor(array.get(quarter_pnl, mi), array.get(quarter_bh, mi))
table.cell(quarterly_table, m_col, m_row, enableCompareWithMarket ? tostring(round(array.get(quarter_pnl, mi) * 100, precision)) + " (" + tostring(round(array.get(quarter_bh, mi) * 100,precision)) +")" : tostring(round(array.get(quarter_pnl, mi) * 100, precision)), bgcolor = m_color, text_color=#bfbfbf) |
Liquidity Breakout - Strategy [presentTrading] | https://www.tradingview.com/script/UUHabgvo-Liquidity-Breakout-Strategy-presentTrading/ | PresentTrading | https://www.tradingview.com/u/PresentTrading/ | 186 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © PresentTrading
//@version=5
strategy('Liquidity Breakout - Strategy [presentTrading]' , overlay=true, precision=3, default_qty_type=strategy.cash,
commission_value= 0.1, commission_type=strategy.commission.percent, slippage= 1,
currency=currency.USD, default_qty_type = strategy.percent_of_equity, default_qty_value = 10, initial_capital= 10000)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
// Define trading direction options
tradeDirection = input.string(title="Trade Direction", defval="Both", options=["Long", "Short", "Both"])
length = input.int(12, 'Contraction Detection Lookback', minval = 1)
liqLength = input.int(20, 'Liquidity Levels', minval = 1)
// Define stop loss options
stopLossType = input.string(title="Stop Loss Type", defval="SuperTrend", options=["SuperTrend", "Fixed Percentage", "None"])
fixedPercentage = input.float(0.1, title="Fixed Percentage", step=0.01)
// Define Supertrend parameters
supertrendPeriod = input(10, "Supertrend Length")
supertrendMult = input.float(3.0, "Supertrend Mult", step = 0.1)
// Calculate Supertrend
[supertrend, direction] = ta.supertrend(supertrendMult, supertrendPeriod)
showMajor = input(true, 'Show Major Pattern')
showMinor = input(true, 'Show Minor Pattern')
//Style
bullCss = input.color(color.teal, 'Bullish Pattern', inline = 'bull', group = 'Pattern Style')
showBullBox = input(true, 'Area', inline = 'bull', group = 'Pattern Style')
showBullLvl = input(true, 'Line', inline = 'bull', group = 'Pattern Style')
bearCss = input.color(color.red, 'Bearish Pattern', inline = 'bear', group = 'Pattern Style')
showBearBox = input(true, 'Area', inline = 'bear', group = 'Pattern Style')
showBearLvl = input(true, 'Line', inline = 'bear', group = 'Pattern Style')
//Liquidity Style
showLiq = input(true, 'Show Liquidity Levels', group = 'Liquidity')
bullLiqCss = input.color(color.teal, 'Upper Liquidity', group = 'Liquidity')
bearLiqCss = input.color(color.red, 'Lower Liquidity', group = 'Liquidity')
//-----------------------------------------------------------------------------}
//UDT
//-----------------------------------------------------------------------------{
type mp
box area
line avg
bool breakup
bool breakdn
//-----------------------------------------------------------------------------}
//Detect contraction
//-----------------------------------------------------------------------------{
var phy = 0., var phx = 0, var pht = 0.
var ply = 0., var plx = 0, var plt = 0.
var float top = na
var float btm = na
n = bar_index
ph = ta.pivothigh(length, length)
pl = ta.pivotlow(length, length)
if ph
pht := math.sign(ph - phy)
phy := ph
if pht == -1 and plt == 1
top := ph
btm := ply
phx := n-length
if pl
plt := math.sign(pl - ply)
ply := pl
if pht == -1 and plt == 1
top := phy
btm := pl
plx := n-length
//-----------------------------------------------------------------------------}
//Set pattern
//-----------------------------------------------------------------------------{
var mp master = mp.new()
//Detect master pattern
isbull = high[length] > top and top > btm
isbear = low[length] < btm and top > btm
if isbull or isbear
css = isbull ? bullCss : bearCss
master.avg.set_x2(n-length)
val = math.avg(top, btm)
//Create new master pattern object
master := mp.new(
(isbull and showBullBox) or (isbear and showBearBox) ? box.new(math.max(phx, plx), top, n-length, btm, na, bgcolor = showMinor ? color.new(css, 50) : na) : na
, (isbull and showBullLvl) or (isbear and showBearLvl) ? line.new(n-length, val, n, val, color = showMinor ? css : na) : na
, isbull
, isbear)
top := na
btm := na
//Determine if pattern switch to major
if master.breakup
if low < master.area.get_bottom()
if not showMajor
master.area.delete()
master.avg.delete()
else
master.area.set_border_color(bullCss)
if not showMinor
master.area.set_bgcolor(color.new(bullCss, 50))
master.avg.set_color(bullCss)
else if master.breakdn
if high > master.area.get_top()
if not showMajor
master.area.delete()
master.avg.delete()
else
master.area.set_border_color(bearCss)
if not showMinor
master.area.set_bgcolor(color.new(bearCss, 50))
master.avg.set_color(bearCss)
//Set friction level x2 coordinate to current bar
if not na(master.avg)
master.avg.set_x2(n)
//-----------------------------------------------------------------------------}
//Liquidity levels
//-----------------------------------------------------------------------------{
var line liqup = na, var liqup_reach = false
var line liqdn = na, var liqdn_reach = false
liqph = ta.pivothigh(liqLength, liqLength)
liqpl = ta.pivotlow(liqLength, liqLength)
//Set upper liquidity
if liqph and showLiq
if not liqup_reach
liqup.set_x2(n-liqLength)
liqup := line.new(n-liqLength, liqph, n, liqph, color = bullLiqCss, style = line.style_dotted)
liqup_reach := false
else if not liqup_reach and showLiq
liqup.set_x2(n)
if high > liqup.get_y1()
liqup_reach := true
//Set lower liquidity
if liqpl and showLiq
if not liqdn_reach
liqdn.set_x2(n-liqLength)
liqdn := line.new(n-liqLength, liqpl, n, liqpl, color = bearLiqCss, style = line.style_dotted)
liqdn_reach := false
else if not liqdn_reach and showLiq
liqdn.set_x2(n)
if low < liqdn.get_y1()
liqdn_reach := true
//-----------------------------------------------------------------------------}
// Define entry conditions
bullishEntry = isbull //and direction < 0
bearishEntry = isbear //and direction > 0
// Execute trades
if (bullishEntry and (tradeDirection == "Long" or tradeDirection == "Both"))
strategy.entry("Buy", strategy.long)
if (stopLossType == "SuperTrend")
strategy.exit("Sell", "Buy", stop=supertrend)
else if (stopLossType == "Fixed Percentage")
strategy.exit("Sell", "Buy", stop=close * (1 - fixedPercentage))
if (bearishEntry and (tradeDirection == "Short" or tradeDirection == "Both"))
strategy.entry("Sell", strategy.short)
if (stopLossType == "SuperTrend")
strategy.exit("Buy", "Sell", stop=supertrend)
else if (stopLossType == "Fixed Percentage")
strategy.exit("Buy", "Sell", stop=close * (1 + fixedPercentage))
// Exit conditions
if (strategy.position_size > 0 and bearishEntry) // If in a long position and bearish entry condition is met
strategy.close("Buy")
if (strategy.position_size < 0 and bullishEntry) // If in a short position and bullish entry condition is met
strategy.close("Sell") |
*Backtesting System | https://www.tradingview.com/script/GRTkk75x-Backtesting-System/ | HALDRO | https://www.tradingview.com/u/HALDRO/ | 860 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// @HALDRO Project
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— \\
//@version=5
strategy('*Backtesting System',
overlay = true,
initial_capital = 10000,
commission_value = 0.04,
default_qty_value = 10,
slippage = 1,
pyramiding = 0,
max_lines_count = 500,
max_labels_count = 500,
currency = currency.USD,
default_qty_type = strategy.percent_of_equity)
MA(string _maType, float _maSource, simple int _maLength) =>
float ma = switch _maType
'ALMA' => ta.alma (_maSource, _maLength, 0.85, 6)
'EMA' => ta.ema (_maSource, _maLength)
'HMA' => ta.hma (_maSource, _maLength)
'RMA' => ta.rma (_maSource, _maLength)
'SMA' => ta.sma (_maSource, _maLength)
'VWMA' => ta.vwma (_maSource, _maLength)
'WMA' => ta.wma (_maSource, _maLength)
ma
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— \\
// —————— ToolTips
TText_source_ = '𝐄𝐱𝐭𝐞𝐫𝐧𝐚𝐥 𝐒𝐨𝐮𝐫𝐜𝐞 ➖ Here you must select your Indicator, having previously connected the "Connector" to it.\nIf the "Close" option is selected then you can test the backtest on regular MA crosses EMA 200 and EMA 50.'
TTreversesignal = '𝐖𝐚𝐢𝐭 𝐄𝐧𝐝 𝐃𝐞𝐚𝐥 ➖ Enable/Disable waiting for a trade to close at Stop Loss/Take Profit. Until the trade closes on the Stop Loss or Take Profit, no new trade will open. \n'
+ '𝐑𝐞𝐯𝐞𝐫𝐬𝐞 𝐃𝐞𝐚𝐥𝐬 ➖ If true strategy will go in the opposite direction from the signal.'
TTreOpenDeal = '𝐑𝐞𝐄𝐧𝐭𝐫𝐲 𝐃𝐞𝐚𝐥 ➖ If true trade was long and SL/TP was reached then go long again and vice versa. \n'
+ '𝐑𝐞𝐎𝐩𝐞𝐧 𝐃𝐞𝐚𝐥 ➖ If true and Wait End Deal is false then in case you are in a Long position and a new signal to Long, you will reEnter a new Long position and vice versa for Shorts.'
TTslType = '𝐅𝐈𝐗𝐄𝐃 % ➖ Fixed SL/TP in percent. \n'
+ '𝐅𝐈𝐗𝐄𝐃 $ ➖ Fixed SL/TP in cash. \n'
+ '𝐓𝐑𝐀𝐈𝐋𝐈𝐍𝐆 ➖ Trailing stop in % like on exchanges. Regulated by the "𝗧𝗿𝗮𝗶𝗹𝗶𝗻𝗴 %" parameter. \n'
+ '𝐅𝐀𝐒𝐓 𝐓𝐑𝐀𝐈𝐋 ➖ If in a long, it immediately follows the price when it rises otherwise it stands still. Vice versa for shorts. Regulated by the "𝗧𝗿𝗮𝗶𝗹𝗶𝗻𝗴 %" parameter. \n'
+ '𝐀𝐓𝐑 ➖ Fixed TP/SL depending on the current ATR. It is regulated by the "𝗔𝗧𝗥 𝗣𝗲𝗿𝗶𝗼𝗱" | "𝗠𝘂𝗹𝘁𝗶𝗽𝗹𝗶𝗲𝗿" parameters. \n'
+ '𝗔𝗧𝗥 𝐓𝐑𝐀𝐈𝐋 ➖ Trailing Stop calculated on the basis of the ATR. It is regulated by the "𝗔𝗧𝗥 𝗣𝗲𝗿𝗶𝗼𝗱" | "𝗠𝘂𝗹𝘁𝗶𝗽𝗹𝗶𝗲𝗿" parameters. \n'
+ '𝗥:𝗥 ➖ Risk Reward sets the TP depending on the size of the SL. For example, if SL is $100, and R:R = 2, then the TP is $200. \n'
+ '𝐇𝐇 / 𝐋𝐋 ➖ Searches for the last Extremum (High/Low) for the specified number of bars and sets a fixed Take. \n'
+ '𝐋𝐎 / 𝐇𝐈 ➖ Sets the SL for High/Low candles. "𝗟𝗢/𝗛𝗜" = 1 Sets the SL for the last High/Low. \n'
+ '𝐌𝐀 ➖ Movieng Average SL. A very diverse type of SL.'
// —————— Main Inputs
groupset = '➤ MAIN SETTINGS'
ext_source_ = input.source (close, ' 𝐄𝐱𝐭𝐞𝐫𝐧𝐚𝐥 𝐒𝐨𝐮𝐫𝐜𝐞 ', group=groupset, inline='esrc', tooltip=TText_source_)
bullDeal = input.bool (true, ' Long Deals ', group=groupset, inline='deal')
bearDeal = input.bool (true, ' Short Deals', group=groupset, inline='deal')
waitEndDeal = input.bool (true, ' Wait End Deal ', group=groupset, inline='ord1')
reversesignal = input.bool (false, ' Reverse Deals', group=groupset, inline='ord1', tooltip=TTreversesignal)
reEntryDeal = input.bool (false, ' ReEntry Deal ', group=groupset, inline='ord2')
reOpenDeal = input.bool (false, ' ReOpen Deal', group=groupset, inline='ord2', tooltip=TTreOpenDeal)
tpType = input.string ('R:R', ' 𝐓𝐚𝐤𝐞 𝐏𝐫𝐨𝐟𝐢𝐭', group=groupset, inline='type', options=['None', 'FIXED %', 'FIXED $', 'ATR', 'R:R', 'HH / LL'])
slType = input.string ('ATR', ' 𝐒𝐭𝐨𝐩 𝐋𝐨𝐬𝐬 ', group=groupset, inline='type', options=['None', 'FIXED %', 'FIXED $', 'TRAILING', 'FAST TRAIL', 'ATR', 'ATR TRAIL', 'LO / HI', 'MA'], tooltip=TTslType)
grouptakes = ' ➤ Take Profit Levels'
ontake1 = input.bool (false, '🇹🇵¹', group=grouptakes, inline='take')
qtake1 = input.int (20, '', group=grouptakes, inline='take', minval=1, step=5, maxval=100)
ontake2 = input.bool (false, '🇹🇵²', group=grouptakes, inline='take')
qtake2 = input.int (20, '', group=grouptakes, inline='take', minval=1, step=5, maxval=100)
ontake3 = input.bool (false, '🇹🇵³', group=grouptakes, inline='take')
qtake3 = input.int (50, '', group=grouptakes, inline='take', minval=1, step=5, maxval=100)
ontake4 = input.bool (false, '🇹🇵⁴', group=grouptakes, inline='take')
qtake4 = input.int (25, '', group=grouptakes, inline='take', minval=1, step=5, maxval=100)
ontake5 = input.bool (false, '🇹🇵⁵ ', group=grouptakes, inline='take')
qtake5 = input.int (25, '', group=grouptakes, inline='take', minval=1, step=5, maxval=100)
onstop0 = input.bool (false, '🇸🇱⁰ ', group=grouptakes, inline='take')
qstop0 = input.int (30, '', group=grouptakes, inline='take', minval=1, step=5, maxval=100)
// Example Connector
//Signal = buy ? +1 : sell ? -1 : 0
//plot(Signal, "🔌Connector🔌", display = display.none)
// —————— Variables Initialisation
ext_source = nz(ext_source_)
bull = ext_source == +1 // +1 is bull signal
bear = ext_source == -1 // -1 is bear signal
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— \\
// ————————————————————————————————————————————————— DATE RANGE ——————————————————————————————————————————————————————————— \\ // Credit @jason5480
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— \\
grouptime = '➤ TIME FILTERS'
src_timezone = input.string ('Exchange', 'Timezones Src->Dst', group=grouptime, inline='Timezone', options=['Exchange', 'UTC', 'America/Los_Angeles', 'America/Phoenix', 'America/Vancouver', 'America/El_Salvador', 'America/Bogota', 'America/Chicago', 'America/New_York', 'America/Toronto', 'America/Argentina/Buenos_Aires', 'America/Sao_Paulo', 'Etc/UTC', 'Europe/London', 'Europe/Berlin', 'Europe/Madrid', 'Europe/Paris', 'Europe/Warsaw', 'Europe/Athens', 'Europe/Moscow', 'Asia/Tehran', 'Asia/Dubai', 'Asia/Ashkhabad', 'Asia/Kolkata', 'Asia/Almaty', 'Asia/Bangkok', 'Asia/Hong_Kong', 'Asia/Shanghai', 'Asia/Singapore', 'Asia/Taipei', 'Asia/Seoul', 'Asia/Tokyo', 'Australia/ACT', 'Australia/Adelaide', 'Australia/Brisbane', 'Australia/Sydney', 'Pacific/Auckland', 'Pacific/Fakaofo', 'Pacific/Chatham', 'Pacific/Honolulu'])
dst_timezone = input.string ('Exchange', '->', group=grouptime, inline='Timezone', options=['Exchange', 'UTC', 'America/Los_Angeles', 'America/Phoenix', 'America/Vancouver', 'America/El_Salvador', 'America/Bogota', 'America/Chicago', 'America/New_York', 'America/Toronto', 'America/Argentina/Buenos_Aires', 'America/Sao_Paulo', 'Etc/UTC', 'Europe/London', 'Europe/Berlin', 'Europe/Madrid', 'Europe/Paris', 'Europe/Warsaw', 'Europe/Athens', 'Europe/Moscow', 'Asia/Tehran', 'Asia/Dubai', 'Asia/Ashkhabad', 'Asia/Kolkata', 'Asia/Almaty', 'Asia/Bangkok', 'Asia/Hong_Kong', 'Asia/Shanghai', 'Asia/Singapore', 'Asia/Taipei', 'Asia/Seoul', 'Asia/Tokyo', 'Australia/ACT', 'Australia/Adelaide', 'Australia/Brisbane', 'Australia/Sydney', 'Pacific/Auckland', 'Pacific/Fakaofo', 'Pacific/Chatham', 'Pacific/Honolulu'], tooltip='The Src is the timezone to be used as a reference for the time settings. The Dst is the timezone to convert into (e.g. the charslPrice\' timezone)')
usefromDate = input.bool (true, 'Srart From ', group=grouptime, inline='From Date')
fromDate = input.time (timestamp('01 Jan 2020 00:00'), '', group=grouptime, inline='From Date')
usetoDate = input.bool (false, 'End To ', group=grouptime, inline='To Date')
toDate = input.time (timestamp('01 Jul 2025 00:00'), '', group=grouptime, inline='To Date')
useSessionDay = input.bool (false, 'Session Days', group=grouptime, inline='Session Days')
mon = input.bool (true, 'Mon', group=grouptime, inline='Session Days')
tue = input.bool (true, 'Tue', group=grouptime, inline='Session Days')
wed = input.bool (true, 'Wed', group=grouptime, inline='Session Days')
thu = input.bool (true, 'Thu', group=grouptime, inline='Session Days')
fri = input.bool (true, 'Fri', group=grouptime, inline='Session Days')
sat = input.bool (false, 'Sat', group=grouptime, inline='Session Days')
sun = input.bool (false, 'Sun', group=grouptime, inline='Session Days')
useSessionStart = input.bool (false, 'Session Start', group=grouptime, inline='Session Start')
sessionStartHour = input.int (12, '', group=grouptime, inline='Session Start', minval=0, maxval=23, step=1)
sessionStartMinute = input.int (00, ':', group=grouptime, inline='Session Start', minval=0, maxval=59, step=1, tooltip='Start time of the session.')
useSessionEnd = input.bool (false, 'Session End ', group=grouptime, inline='Session End')
sessionEndHour = input.int (20, '', group=grouptime, inline='Session End', minval=0, maxval=23, step=1)
sessionEndMinute = input.int (00, ':', group=grouptime, inline='Session End', minval=0, maxval=59, step=1, tooltip='End time of the session.')
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— \\
ex_timezone(simple string tz) =>
switch tz
'Exchange' => syminfo.timezone
=> tz
if_in_date_range(simple bool usefromDate, simple int fromDate, simple bool usetoDate, simple int toDate, simple string src_timezone = 'Exchange', simple string dst_timezone = 'Exchange', int t = time_close) =>
var src_tz = ex_timezone(src_timezone)
var dst_tz = ex_timezone(dst_timezone)
var fromDateTz = timestamp(src_tz, year(fromDate, dst_tz), month(fromDate, dst_tz), dayofmonth(fromDate, dst_tz), hour(fromDate, dst_tz), minute(fromDate, dst_tz), second(fromDate, dst_tz))
var toDateTz = timestamp(src_tz, year(toDate, dst_tz), month(toDate, dst_tz), dayofmonth(toDate, dst_tz), hour(toDate, dst_tz), minute(toDate, dst_tz), second(toDate, dst_tz))
(usefromDate ? t >= fromDateTz : true) and (usetoDate ? t < toDateTz : true)
if_in_session(simple bool useSessionStart, simple int sessionStartHour, simple int sessionStartMinute, simple bool useSessionEnd, simple int sessionEndHour, simple int sessionEndMinute, simple bool useSessionDay = false, simple bool mon = true, simple bool tue = true, simple bool wed = true, simple bool thu = true, simple bool fri = true, simple bool sat = false, simple bool sun = false, simple string src_timezone = 'Exchange', simple string dst_timezone = 'Exchange', int t = time_close) =>
var one_day = 86400000
var utc_tz = 'UTC'
var src_tz = ex_timezone(src_timezone)
var dst_tz = ex_timezone(dst_timezone)
start_hr = sessionStartHour + (hour(t, dst_tz) - hour(t, src_tz))
start_min = sessionStartMinute + (minute(t, dst_tz) - minute(t, src_tz))
end_hr = sessionEndHour + (hour(t, dst_tz) - hour(t, src_tz))
end_min = sessionEndMinute + (minute(t, dst_tz) - minute(t, src_tz))
time_start_session = timestamp(dst_tz, year(t, src_tz), month(t, src_tz), dayofmonth(t, src_tz), start_hr, start_min, second(t, src_tz))
time_end_session = timestamp(dst_tz, year(t, src_tz), month(t, src_tz), dayofmonth(t, src_tz), end_hr, end_min, second(t, src_tz))
var bool isOvernight = time_start_session >= time_end_session
// in overnight sessions increase end time by one day
if (useSessionStart and useSessionEnd and isOvernight)
time_end_session := time_end_session + one_day
isSessionDay = switch dayofweek(t, src_tz)
dayofweek.monday => mon
dayofweek.tuesday => tue
dayofweek.wednesday => wed
dayofweek.thursday => thu
dayofweek.friday => fri
dayofweek.saturday => sat
dayofweek.sunday => sun
=> false
(useSessionDay ? isSessionDay : true) and (useSessionStart ? t >= time_start_session : true) and (useSessionEnd ? t < time_end_session : true)
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— \\
bool dateFilterApproval = if_in_date_range(usefromDate, fromDate, usetoDate, toDate, src_timezone, dst_timezone)
bool sessionFilterApproval = if_in_session(useSessionStart, sessionStartHour, sessionStartMinute, useSessionEnd, sessionEndHour, sessionEndMinute, useSessionDay, mon, tue, wed, thu, fri, sat, sun, src_timezone, dst_timezone)
bool timeFilterApproval = dateFilterApproval and sessionFilterApproval
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— \\
// ————————————————————————————————————————————— Signal Filters ——————————————————————————————————————————————————————————— \\ // Credit @pAulseperformance
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— \\
groupsignal = '➤ SIGNAL FILTERS'
FilterType1 = input.bool (false, '1. ADX', group=groupsignal, inline='FT1')
FilterType1Len = input.int (17, '', group=groupsignal, inline='FT1', minval=1 )
FilterType1Smt = input.int (14, '', group=groupsignal, inline='FT1', minval=1, maxval=50)
FilterType1Tresh = input.int (20, '', group=groupsignal, inline='FT1', minval=1, maxval=50, tooltip='ADX Lenght, Smooth, Level. \nTrade If ADX < Level')
FilterType2 = input.bool (false, '2. MACD', group=groupsignal, inline='FT2')
FilterType2Len1 = input.int (12, '', group=groupsignal, inline='FT2')
FilterType2Len2 = input.int (26, '', group=groupsignal, inline='FT2')
FilterType2Len3 = input.int (9, '', group=groupsignal, inline='FT2', tooltip='Fast Len, Slow Len, Smooth. \nLong Filter: MACD > 0\nShort Filter: MACD < 0')
FilterType3 = input.bool (false, '3. Bar direction=Trade direction', group=groupsignal, tooltip='Long filter: close>open\nShort Filter: close<open')
FilterType4 = input.bool (false, '4. Rising Volume', group=groupsignal, tooltip='Long Filter: Volume Increasing\nShort Filter: Volume Decreasing')
FilterType5 = input.bool (false, '5. Rising/Falling MA', group=groupsignal, inline='FT5', tooltip='Long Filter: SMA is Rising\nShort Filter: SMA Falling \nRising/Falling - For N Bars')
FilterType5Len = input.int (50, 'Length', group=groupsignal, inline='FT5', minval=2)
FilterType5Bars = input.int (1, 'Bars', group=groupsignal, inline='FT5', minval=1)
FilterType6 = input.bool (false, '6. High/Low Filter', group=groupsignal, inline='FT6')
FilterType6Bars = input.int (10, 'Lookback', group=groupsignal, inline='FT6', tooltip='If true then the signal bar must be the highest/lovest bar over X bars')
FilterType7 = input.bool (false, '7. Maximum close change (%) allowed on entry', group=groupsignal, inline='FT7')
FilterType7IncPct = input.float (10.0, '', group=groupsignal, inline='FT7', minval=0.0, step=0.5)
FilterType8 = input.bool (false, '8. Minimum close change (%) allowed on entry', group=groupsignal, inline='FT8')
FilterType8IncPct = input.float (1.0, '', group=groupsignal, inline='FT8', minval=0.0, step=0.5)
FilterType9 = input.bool (false, '9. RSI OS/OB', group=groupsignal, inline='FT9')
FilterType9Len = input.int (20, '', group=groupsignal, inline='FT9', minval=2)
FilterType9OS = input.int (25, '', group=groupsignal, inline='FT9', minval=0, maxval=100)
FilterType9OB = input.int (75, '', group=groupsignal, inline='FT9', minval=0, maxval=100, tooltip='RSI Length, OS Level, OB Level \nLong = RSI < OB\nShort = RSI > OS')
FilterType10 = input.bool (false, '10. MA', group=groupsignal, inline='FT10')
FilterType10MAType = input.string ('SMA', '', group=groupsignal, inline='FT10', options=['ALMA', 'EMA', 'HMA', 'RMA', 'SMA', 'VWMA', 'WMA'])
FilterType10Len = input.int (200, '', group=groupsignal, inline='FT10', minval=1, tooltip='MA Type, MA Source, MA Length\nLong = close > MA\nShort = close < MA')
// —————— Filter 1: ADX
[dip, dim, adx] = ta.dmi(FilterType1Len, FilterType1Smt)
Filter1Long = FilterType1 ? adx < FilterType1Tresh : true
Filter1Short = Filter1Long
// —————— Filter 2: MACD Hist
_macdLine = FilterType2 ? nz(MA('EMA', close, FilterType2Len1) - MA('EMA', close, FilterType2Len2)) : 0.
_macdSignal = FilterType2 ? nz(MA('EMA', _macdLine, FilterType2Len3)) : 0.
_macdHist = FilterType2 ? _macdLine - _macdSignal : 0.
Filter2Long = FilterType2 ? _macdHist > 0 : true
Filter2Short = FilterType2 ? _macdHist < 0 : true
// —————— Filter 3: Bar direction
Filter3Long = FilterType3 ? close > open : true
Filter3Short = FilterType3 ? close < open : true
// —————— Filter 4: Rising volume
Filter4Long = FilterType4 ? ta.rising(volume, 1) : true
Filter4Short = Filter4Long
// —————— Filter 5: Rising/Falling MA
Filter5Ma = FilterType5 ? nz(MA('SMA', close, FilterType5Len)) : 0
Filter5Long = FilterType5 ? ta.rising(Filter5Ma, FilterType5Bars) : true
Filter5Short = FilterType5 ? ta.falling(Filter5Ma, FilterType5Bars) : true
// —————— Filter 6: Check high & close filter
Filter6Long = FilterType6 ? high >= ta.highest(high, FilterType6Bars) : true
Filter6Short = FilterType6 ? low <= ta.lowest(low, FilterType6Bars) : true
// —————— Filter 7: Maximum delta with previous close allowed at entry
Filter7Long = FilterType7 ? close < close[1] * (1 + FilterType7IncPct / 100) : true
Filter7Short = FilterType7 ? close > close[1] * (1 - FilterType7IncPct / 100) : true
// —————— Filter 8: Minimum delta with previous close allowed at entry
Filter8Long = FilterType8 ? close > close[1] * (1 + FilterType8IncPct / 100) : true
Filter8Short = FilterType8 ? close < close[1] * (1 - FilterType8IncPct / 100) : true
// —————— Filter 9: RSI OS/OB
Rsi = FilterType9 ? ta.rsi(close, FilterType9Len) : 0
RsiOB = Rsi > FilterType9OB
RsiOS = Rsi < FilterType9OS
Filter9Long = FilterType9 ? not RsiOB : true
Filter9Short = FilterType9 ? not RsiOS : true
// —————— Filter 10: Moving Average
Filter10Ma = FilterType10 ? MA(FilterType10MAType, close, FilterType10Len) : 0.
Filter10Long = FilterType10 ? close > Filter10Ma : true
Filter10Short = FilterType10 ? close < Filter10Ma : true
// —————— Assemble Filters
FilterLongOK = Filter1Long and Filter2Long and Filter3Long and Filter4Long and Filter5Long
and Filter6Long and Filter7Long and Filter8Long and Filter9Long and Filter10Long
FilterShortOK = Filter1Short and Filter2Short and Filter3Short and Filter4Short and Filter5Short
and Filter6Short and Filter7Short and Filter8Short and Filter9Short and Filter10Short
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— \\
// ————————————————————————————————————————————————— Risk Managment ——————————————————————————————————————————————————————— \\ // Credit @Daveatt
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— \\
grouprisk = '➤ RISK MANAGEMENT'
setmaxLosingStreak = input.bool (false, '', group=grouprisk, inline='1')
maxLosingStreak = input.int (15, 'Loss Streak ', group=grouprisk, inline='1', minval=1)
setmaxWinStreak = input.bool (false, '', group=grouprisk, inline='1')
maxWinStreak = input.int (15, 'Win Streak ', group=grouprisk, inline='1', minval=1, tooltip='𝐋𝐨𝐬𝐬 𝐒𝐭𝐫𝐞𝐚𝐤 ➖ Set Max number of consecutive loss trades. \n𝐖𝐢𝐧 𝐒𝐭𝐫𝐞𝐚𝐤 ➖ Max Winning Streak Length.')
setmaxLosingDaysStreak = input.bool (false, '', group=grouprisk, inline='2')
maxLosingDaysStreak = input.int (3, 'Row Loss InDay', group=grouprisk, inline='2', minval=1)
setMaxDrawdown = input.bool (false, '', group=grouprisk, inline='2')
maxPercDd = input.int (10, 'DrawDown %', group=grouprisk, inline='2', minval=1, maxval=100, tooltip='𝐑𝐨𝐰 𝐋𝐨𝐬𝐬 𝐈𝐧𝐃𝐚𝐲 ➖ Max of consecutive days with a loss in a row. \n𝐃𝐫𝐚𝐰𝐃𝐨𝐰𝐧% ➖ Max DrawDown (in % of strategy equity).')
setMaxIntradayLoss = input.bool (false, '', group=grouprisk, inline='3')
maxIntradayLoss = input.int (3, 'InDay Loss % ', group=grouprisk, inline='3', minval=1, maxval=100)
setNumberDailyTrades = input.bool (false, '', group=grouprisk, inline='3')
maxDailyTrades = input.int (10, 'Daily Trades ', group=grouprisk, inline='3', minval=1, maxval=100, tooltip='𝐈𝐧𝐃𝐚𝐲 𝐋𝐨𝐬𝐬 % ➖ Set Max Intraday Loss. \n𝐃𝐚𝐢𝐥𝐲 𝐓𝐫𝐚𝐝𝐞𝐬 ➖ Limit the number of MAX trades per day.')
setNumberWeeklyTrades = input.bool (false, '', group=grouprisk, inline='4')
maxWeeklyTrades = input.int (50, 'Weekly Trades', group=grouprisk, inline='4', minval=1, maxval=100, tooltip='𝐖𝐞𝐞𝐤𝐥𝐲 𝐓𝐫𝐚𝐝𝐞𝐬 ➖ Limit the number of MAX trades per week.')
QTYMethod = input.string ('EQUITY', ' Order Size', group=grouprisk, inline=' ', options=['NONE', 'EQUITY', 'SIZE', 'CONTRACTS'])
useNetProfit = input.bool (true, 'Use Net Profit', group=grouprisk, inline=' ', tooltip='𝐔𝐬𝐞 𝐍𝐞𝐭 𝐏𝐫𝐨𝐟𝐢𝐭 ➖ On/Off the use of profit in the following trades. *Only works if the type is EQUITY')
riskPerc = input.int (10, '🇪🇶🇺🇮🇹🇾', group=grouprisk, inline='.', minval=1, maxval=100)
riskSize = input.int (1000, '🇸🇮🇿🇪', group=grouprisk, inline='.', minval=1)
riskCntr = input.int (1, '🇨🇴🇳🇹🇷🇦🇨🇹🇸', group=grouprisk, inline='.', minval=1, tooltip='𝐎𝐫𝐝𝐞𝐫 𝐒𝐢𝐳𝐞: \n𝐍𝐎𝐍𝐄 ➖ Use the default position size settings in Tab "Properties". \n𝐄𝐐𝐔𝐈𝐓𝐘 ➖ % per trade from the initial capital. \n𝐒𝐈𝐙𝐄 ➖ Fixed size amount of trade. \n𝐂𝐎𝐍𝐓𝐑𝐀𝐂𝐓𝐒 ➖ The fixed amount of the deal in contracts. \n')
// —————— Order Size
eqty = switch QTYMethod
'NONE' => na
'EQUITY' => riskPerc / close
'SIZE' => riskSize / close
'CONTRACTS' => riskCntr
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— \\
// —————— Intraday Loss %
condintradayloss = setMaxIntradayLoss ? maxIntradayLoss : 100
strategy.risk.max_intraday_loss(value=condintradayloss, type=strategy.percent_of_equity)
// —————— Max Drawdown %
condmaxdrawdown = setMaxDrawdown ? maxPercDd : 100
strategy.risk.max_drawdown(value=condmaxdrawdown, type=strategy.percent_of_equity)
// —————— Daily trades calculation
tradesIntradayCount = setNumberDailyTrades ? maxDailyTrades : 1000
strategy.risk.max_intraday_filled_orders(count=tradesIntradayCount)
// —————— Weekly trades calculation
tradesLastWeek = 0
tradesLastWeek := dayofweek == dayofweek.monday and dayofweek != dayofweek[1] ? strategy.closedtrades[1] + strategy.opentrades[1] : tradesLastWeek[1]
// —————— Calculate number of trades this week
weeklyTrades = strategy.closedtrades + strategy.opentrades - tradesLastWeek
okToTradeWeekly = setNumberWeeklyTrades ? weeklyTrades < maxWeeklyTrades : true
// —————— Consecutive loss days in a row
countConsLossDays = setmaxLosingDaysStreak ? maxLosingDaysStreak : 1000
strategy.risk.max_cons_loss_days(countConsLossDays)
// —————— Calculate the total losing streaks
newLoss = strategy.losstrades > strategy.losstrades[1] and strategy.wintrades == strategy.wintrades[1] and strategy.eventrades == strategy.eventrades[1]
// —————— Determine current losing streak length
streakLossLen = 0
streakLossLen := newLoss ? nz(streakLossLen[1]) + 1 : strategy.wintrades > strategy.wintrades[1] or strategy.eventrades > strategy.eventrades[1] ? 0 : nz(streakLossLen[1])
// —————— Check if losing streak is under max allowed
okToTradeLossStreak = setmaxLosingStreak ? streakLossLen < maxLosingStreak : true
// —————— Calculate the total winning streaks
newWin = strategy.wintrades > strategy.wintrades[1] and strategy.losstrades == strategy.losstrades[1] and strategy.eventrades == strategy.eventrades[1]
// —————— Figure out current winning streak length
streakWinLen = 0
streakWinLen := newWin ? nz(streakWinLen[1]) + 1 : strategy.losstrades > strategy.losstrades[1] or strategy.eventrades > strategy.eventrades[1] ? 0 : nz(streakWinLen[1])
// —————— Check if winning streak is under max allowed
okToTradeWinStreak = setmaxWinStreak ? streakWinLen < maxWinStreak : true
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— \\
// ————————————————————————————————————————————————— STRATEGY ————————————————————————————————————————————————————————————— \\
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— \\
percentTP = input.float (4.5, ' Profit % ', group=groupset, inline='fix', minval=0.1, step=0.1)
percentSL = input.float (1.5, ' Stop % ', group=groupset, inline='fix', minval=0.1, step=0.1)
moneyTP = input.float (333, ' Profit $ ', group=groupset, inline='mon', minval=1, step=5)
moneySL = input.float (100, ' Stop $ ', group=groupset, inline='mon', minval=1, step=5)
ATRLen = input.int (40, ' ATR Period ', group=groupset, inline='atr', minval=1, step=1)
ATRMult = input.float (4, ' Multiplier', group=groupset, inline='atr', minval=0.1, step=0.1)
trailPerc = input.float (3, ' Trailing % ', group=groupset, inline='trl', minval=0.1, step=0.1)
riskReward = input.float (2, ' R:R 1:', group=groupset, inline='trl', minval=0.5, step=0.1)
fixedRR = input.bool (true, ' Fixed RR', group=groupset, inline='trl', tooltip='𝐅𝐢𝐱𝐞𝐝 𝗥:𝗥 ➖ If the stop loss is Dynamic (Trailing or MA) then R:R can also be made Dynamic')
HHLL = input.int (200, ' HH / LL ', group=groupset, inline='hls', minval=1, step=5)
LoHi = input.int (5, ' LO / HI ', group=groupset, inline='hls', minval=1, step=1)
addPerc = input.bool (false, ' Add %', group=groupset, inline='hls', tooltip='𝐀𝐝𝐝 % ➖ If true, then with the "𝗦𝘁𝗼𝗽 %" parameter you can add percentages to any of the current SL. \nCan be especially useful when using Stop - 𝗔𝗧𝗥 or 𝗠𝗔 or 𝗟𝗢/𝗛𝗜. \nFor example with 𝗟𝗢/𝗛𝗜 to put a stop for the last High/Low and add 0.5% additional Stoploss')
maStopType = input.string ('SMA', ' MA Stop', group=groupset, inline='mas', options=['ALMA', 'EMA', 'HMA', 'RMA', 'SMA', 'VWMA', 'WMA'])
maStopLen = input.int (15, ' Len', group=groupset, inline='mas', minval=1, step=2)
maPerc = input.float (1.5, ' Step', group=groupset, inline='mas', minval=0, step=0.1, tooltip='𝐌𝐀 𝐒𝐭𝐨𝐩 ➖ allows to choose which MA to use. \n𝐋𝐞𝐧 ➖ Length of chosen MA. \n𝐒𝐭𝐞𝐩 ➖% step of change MA. Step = 0 will use the selected MA without changes. \nWARNING: When 𝐀𝐝𝐝 % is on, the MA calculation changes..')
bullcolor = input.color (#00bbd49a, 'Colors: FG', group=grouptakes, inline='col')
bearcolor = input.color (#c2185c9a, '', group=grouptakes, inline='col')
bullcolorb = input.color (#00bbd426, 'BG', group=grouptakes, inline='col')
bearcolorb = input.color (#c2185c27, '', group=grouptakes, inline='col')
TipLvl = input.string ('——⤴—⤴—⤴', '𝐓𝐈𝐏 𝐅𝐨𝐫 𝐓𝐏', group=grouptakes, inline='col', tooltip='Here you can set up intermediate Takes Profit.\nIn each line next to the TP/SL activation, you specify what % of the current position you want to close. \nFor example, if there is a checkmark next to TP 3 and its value = 50, then at this level 50% of the size of the current position will be closed.')
slNumber = input.int (3, ' SL 0 Position', group=grouptakes, inline='pos', minval=1, maxval=5)
ontpBE = input.bool (false, '', group=grouptakes, inline='pos')
tpBEnumber = input.int (3, 'Breakeven on TP', group=grouptakes, inline='pos', minval=1, maxval=5, tooltip='𝐒𝐋 𝟎 𝐏𝐨𝐬𝐢𝐭𝐢𝐨𝐧 ➖ Changes the position of the intermediate Stop Loss.\nThe value = 3 - the middle. \n𝐁𝐫𝐞𝐚𝐤𝐞𝐯𝐞𝐧 𝐨𝐧 𝐓𝐏 ➖ If true Set StopLoss to Breakeven after the specified TakeProfit is reached.')
barCoolDwn = input.int (0, ' CoolDown # Bars', group=grouptakes, inline=' ', minval=0, tooltip='Do Not open a new position until # bars have passed since the last trade.\nValue=0 - disables the function.')
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— \\
// —————— Trade variables
entry = strategy.position_avg_price
sizePos = strategy.position_size
inLong = sizePos > 0
inShort = sizePos < 0
inTrade = inLong or inShort
inPos = (inLong and not inShort[1]) or (inShort and not inLong[1])
var ID = 'TradeID'
var tpPrice = float(na)
var slPrice = float(na)
// —————— Signal
bull := ext_source_ == close ? ta.crossover (ta.ema(close, 50), ta.ema(close, 200)) : bull
bear := ext_source_ == close ? ta.crossunder(ta.ema(close, 50), ta.ema(close, 200)) : bear
bull := reversesignal ? bear : bull
bear := reversesignal ? bull : bear
// —————— Entry solutions
direction = 0
directionL = bull and (nz(direction[1]) == 0 or nz(direction[1]) == -1)
directionS = bear and (nz(direction[1]) == 0 or nz(direction[1]) == +1)
direction := directionL ? +1 : directionS ? -1 : (reEntryDeal ? direction[1] : direction[0])
checkCoolDwn = barCoolDwn >0 ? not inTrade[barCoolDwn] : true
OkToTrade = timeFilterApproval and okToTradeLossStreak and okToTradeWinStreak and checkCoolDwn
goLong = ( waitEndDeal ? not inTrade and direction==+1 : direction==+1 ) and bullDeal and OkToTrade and FilterLongOK
goShort = ( waitEndDeal ? not inTrade and direction==-1 : direction==-1 ) and bearDeal and OkToTrade and FilterShortOK
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— \\
DynamicStops = (slType == 'TRAILING' or slType == 'FAST TRAIL' or slType == 'ATR TRAIL' or slType == 'MA')
// —————— Fixed SL/TP
if tpType == 'FIXED %'
tpPrice := inLong and not inTrade[1] ? entry * (1 + percentTP/100) : inShort and not inTrade[1] ? entry * (1 - percentTP/100) : tpPrice
if slType == 'FIXED %'
slPrice := inLong and not inTrade[1] ? entry * (1 - percentSL/100) : inShort and not inTrade[1] ? entry * (1 + percentSL/100) : slPrice
// —————— Money SL/TP
if tpType == 'FIXED $'
tpPrice := inLong and not inTrade[1] ? entry + (moneyTP / math.abs(sizePos)) : inShort and not inTrade[1] ? entry - (moneyTP / math.abs(sizePos)) : tpPrice
if slType == 'FIXED $'
slPrice := inLong and not inTrade[1] ? entry - (moneySL / math.abs(sizePos)) : inShort and not inTrade[1] ? entry + (moneySL / math.abs(sizePos)) : slPrice
// —————— Trailing Stop
if slType == 'TRAILING'
StopL = 0., StopS = 0.
StopL := inLong ? math.max(close * (1 - trailPerc/100), StopL[1]) : 0
StopS := inShort ? math.min(close * (1 + trailPerc/100), StopS[1]) : 999999
slPrice := inLong ? StopL : inShort ? StopS : slPrice
// —————— Fast Trailing Stop
if slType == 'FAST TRAIL'
var stop = float(na)
stop := inLong and not inTrade[1] ? entry * (1 - trailPerc/100) : inShort and not inTrade[1] ? entry * (1 + trailPerc/100) : stop
stop := inLong and close > close[1] ? stop + (close - close[1]) : inShort and close < close[1] ? stop + (close - close[1]) : stop
slPrice := stop
// —————— ATR Fixed
StopATR = ta.atr(ATRLen) * ATRMult
if tpType == 'ATR'
tpPrice := inLong and not inTrade[1] ? entry + StopATR : inShort and not inTrade[1] ? entry - StopATR : tpPrice
if slType == 'ATR'
slPrice := inLong and not inTrade[1] ? entry - StopATR : inShort and not inTrade[1] ? entry + StopATR : slPrice
// —————— ATR Trail Stop
if slType == 'ATR TRAIL'
StopL = 0., StopS = 0.
StopL := inLong ? math.max(close - StopATR, StopL[1]) : 0
StopS := inShort ? math.min(close + StopATR, StopS[1]) : 999999
slPrice := inLong ? StopL : inShort ? StopS : slPrice
// —————— LO / HI Stop
if slType == 'LO / HI'
HiStop = ta.highest(high, LoHi)
LoStop = ta.lowest (low, LoHi)
slPrice := inLong and not inTrade[1] ? LoStop : inShort and not inTrade[1] ? HiStop : slPrice
// —————— HH / LL Take
if tpType == 'HH / LL'
HiStop = ta.highest(high, HHLL)
LoStop = ta.lowest (low, HHLL)
tpPrice := inLong and not inTrade[1] ? HiStop : inShort and not inTrade[1] ? LoStop : tpPrice
// —————— MA's Stops
if slType == 'MA'
maSType = MA(maStopType, close, maStopLen)
Stop = maSType * (maPerc / 100)
slPrice := inLong ? math.max(nz(slPrice[1], 0), maSType - Stop) : inShort ? math.min(nz(slPrice[1], 999999), maSType + Stop) : na
// —————— Risk Reward Take
if tpType == 'R:R'
check = fixedRR ? not inTrade[1] : true
tpPrice := inLong and check ? entry + (entry - slPrice) * riskReward : inShort and check ? entry - (slPrice - entry) * riskReward : tpPrice
// —————— Add Percents to SL
if addPerc
check = DynamicStops ? true : not inTrade[1]
slPrice := inLong and check ? slPrice * (1 - percentSL/100) : inShort and check ? slPrice * (1 + percentSL/100) : slPrice
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— \\
// —————— TPSL's
TypeStop = tpType != 'None' or slType == 'FIXED %' or slType == 'FIXED $' or slType == 'ATR' or slType == 'LO / HI'
BuildLeveles(take, nTake) => // Creating Intermediate Levels of the SL/TP - by shifting the current TP/SL to the entry level
nTakes = 6
var offset = float(na)
offset := not inPos[1] ? (entry - take) : offset
xentry = take + offset
levels = array.new_float()
for i = 1 to nTakes - 1
array.push(levels, xentry + (take - xentry) * i / (nTakes))
result = nTake >= 0 and nTake <= nTakes ? array.get(levels, nTake) : na
CheckLevels(lvl, isTake) => // Check if the SL/TP is reached
var float level = na
if isTake and ((inLong and high >= lvl) or (inShort and low <= lvl))
level := entry
if not isTake and ((inLong and low <= lvl) or (inShort and high >= lvl))
level := entry
if not inTrade
level := na
level
// —————— Get and Check Levels
stop0 = tpType != 'None' ? BuildLeveles(slPrice, slNumber-1) : slPrice , checkStop0 = TypeStop ? CheckLevels(stop0, false) : CheckLevels(stop0, true )
take1 = BuildLeveles(TypeStop ? tpPrice : slPrice, 0) , checkTake1 = TypeStop ? CheckLevels(take1, true ) : CheckLevels(take1, false)
take2 = BuildLeveles(TypeStop ? tpPrice : slPrice, 1) , checkTake2 = TypeStop ? CheckLevels(take2, true ) : CheckLevels(take2, false)
take3 = BuildLeveles(TypeStop ? tpPrice : slPrice, 2) , checkTake3 = TypeStop ? CheckLevels(take3, true ) : CheckLevels(take3, false)
take4 = BuildLeveles(TypeStop ? tpPrice : slPrice, 3) , checkTake4 = TypeStop ? CheckLevels(take4, true ) : CheckLevels(take4, false)
take5 = BuildLeveles(TypeStop ? tpPrice : slPrice, 4) , checkTake5 = TypeStop ? CheckLevels(take5, true ) : CheckLevels(take5, false)
// —————— Move Stop to Breakeven
slbecheck = (tpBEnumber==1 and ontake1) or (tpBEnumber==2 and ontake2) or (tpBEnumber==3 and ontake3) or (tpBEnumber==4 and ontake4) or (tpBEnumber==5 and ontake5)
if ontpBE and slbecheck and not DynamicStops
slbe = TypeStop ? CheckLevels(BuildLeveles(tpPrice, tpBEnumber-1), true) : CheckLevels(BuildLeveles(slPrice, tpBEnumber-1), false)
slPrice := slbe > 0 ? slbe : slPrice
stop0 := slPrice == entry ? slPrice : stop0
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— \\
// —————— Entry's
eqty(qty) => QTYMethod=='EQUITY' ? qty / 100 * (strategy.initial_capital + (useNetProfit ? strategy.netprofit : 0)) : QTYMethod=='SIZE' ? qty / syminfo.pointvalue : qty
if goLong
ID := 'Long'
if reOpenDeal and inLong and goLong
strategy.close(ID, comment='reOpen')
strategy.entry(ID, strategy.long, qty=eqty(eqty), comment=ID, alert_message=ID + 'Entry')
if goShort
ID := 'Short'
if reOpenDeal and inShort and goShort
strategy.close(ID, comment='reOpen')
strategy.entry(ID, strategy.short, qty=eqty(eqty), comment=ID, alert_message=ID + 'Entry')
// —————— Exit's
qty(perc) => math.abs(sizePos*perc/100)
if inTrade
strategy.exit('End_0', onstop0 ? ID : 'na', qty=qty(qstop0), limit=tpPrice, stop=stop0, comment_profit='TP 0', comment_loss='SL 0', alert_message=ID + 'SL/TP 0 Trigger')
strategy.exit('End_1', ontake1 ? ID : 'na', qty=qty(qtake1), limit=TypeStop ? take1 : tpPrice, stop=TypeStop ? slPrice : take1, comment_profit='TP 1', comment_loss='SL 1', alert_message=ID + 'SL/TP 1 Trigger')
strategy.exit('End_2', ontake2 ? ID : 'na', qty=qty(qtake2), limit=TypeStop ? take2 : tpPrice, stop=TypeStop ? slPrice : take2, comment_profit='TP 2', comment_loss='SL 2', alert_message=ID + 'SL/TP 2 Trigger')
strategy.exit('End_3', ontake3 ? ID : 'na', qty=qty(qtake3), limit=TypeStop ? take3 : tpPrice, stop=TypeStop ? slPrice : take3, comment_profit='TP 3', comment_loss='SL 3', alert_message=ID + 'SL/TP 3 Trigger')
strategy.exit('End_4', ontake4 ? ID : 'na', qty=qty(qtake4), limit=TypeStop ? take4 : tpPrice, stop=TypeStop ? slPrice : take4, comment_profit='TP 4', comment_loss='SL 4', alert_message=ID + 'SL/TP 4 Trigger')
strategy.exit('End_5', ontake5 ? ID : 'na', qty=qty(qtake5), limit=TypeStop ? take5 : tpPrice, stop=TypeStop ? slPrice : take5, comment_profit='TP 5', comment_loss='SL 5', alert_message=ID + 'SL/TP 5 Trigger')
strategy.exit('End_6', ID, limit=tpPrice, stop=slPrice, comment_profit='TP X', comment_loss='SL X', alert_message=ID + 'SL/TP X Trigger')
// ========================================================================================================================
// Plotting and Debugging
// ========================================================================================================================
plotColx = inLong ? bullcolor : inShort ? bearcolor : na
plotColy = inLong ? bullcolorb : inShort ? bearcolorb : na
tpcolor = tpType != 'None' ? bullcolor : plotColx
tp = plot(inPos ? tpPrice : na, 'Take', color=tpType != 'None' ? bullcolor : plotColx, style=plot.style_linebr, editable=false)
sl = plot(inPos ? slPrice : na, 'Stop', color=tpType != 'None' ? bearcolor : plotColx, style=plot.style_linebr, editable=false)
en = plot(TypeStop ? (inLong and slPrice > entry or inShort and slPrice < entry ? slPrice : entry) : inPos ? close : na, 'Price', color=TypeStop ? #787b86 : na, style=plot.style_linebr)
fill(tp, en, color=TypeStop ? bullcolorb : plotColy, editable=false)
fill(sl, en, color=TypeStop ? bearcolorb : plotColy, editable=false)
plotchar(inPos and not inPos[1]? tpPrice : na, 'Take Start', color=tpType != 'None' ? bullcolor : plotColx, char='➤', location=location.absolute, size=size.tiny)
plotchar(inPos and not inPos[1]? slPrice : na, 'Stop Start', color=tpType != 'None' ? bearcolor : plotColx, char='◉', location=location.absolute, size=size.tiny)
plot(inPos and ontake1 and not checkTake1[1] ? take1 : na, 'TP 1', color=tpcolor, style=plot.style_linebr, editable=false)
plot(inPos and ontake2 and not checkTake2[1] ? take2 : na, 'TP 2', color=tpcolor, style=plot.style_linebr, editable=false)
plot(inPos and ontake3 and not checkTake3[1] ? take3 : na, 'TP 3', color=tpcolor, style=plot.style_linebr, editable=false)
plot(inPos and ontake4 and not checkTake4[1] ? take4 : na, 'TP 4', color=tpcolor, style=plot.style_linebr, editable=false)
plot(inPos and ontake5 and not checkTake5[1] ? take5 : na, 'TP 5', color=tpcolor, style=plot.style_linebr, editable=false)
plot(inPos and onstop0 and not checkStop0[1] ? stop0 : na, 'SL 0', color=bearcolor, style=plot.style_linebr, editable=false)
plot(ext_source_ == close ? ta.ema(close, 50) : na, 'MA 1', color=#ffeb3b93, editable=false)
plot(ext_source_ == close ? ta.ema(close, 200) : na, 'MA 2', color=#ffeb3b93, editable=false)
//plotchar(goLong and not inPos, 'goLong' , char='✟', size=size.tiny, location=location.belowbar, color=#4caf4f )
//plotchar(goShort and not inPos, 'goShort', char='✟', size=size.tiny, location=location.abovebar, color=#ff5252 )
// Panel
//var table panel = table.new(position = position.bottom_right, columns = 2, rows = 1, bgcolor = #363A45, border_width = 1)
//table.cell(panel, 1, 0, text=str.tostring(0), text_color = #ffa726, bgcolor = #363A45)
// ———————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— \\ |
Backtests Are Broken | https://www.tradingview.com/script/fOKpEymF-Backtests-Are-Broken/ | and_then_it_CRASHED | https://www.tradingview.com/u/and_then_it_CRASHED/ | 77 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Copyright ©2022 and_then_it_CRASHED
//@version=5
strategy("Backtest Broken", overlay=true, margin_long=1, margin_short=1)
if strategy.position_size == 0 and math.random(0,100) < 5
strategy.entry('Long', strategy.long)
strategy.exit('Close Long', 'Long', trail_price = close+syminfo.mintick, trail_offset = 0)
|
Volatility Range Breakout Strategy [wbburgin] | https://www.tradingview.com/script/2cnPhDGs-Volatility-Range-Breakout-Strategy-wbburgin/ | wbburgin | https://www.tradingview.com/u/wbburgin/ | 333 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © wbburgin
//@version=5
strategy("Volatility Range Breakout Strategy [wbburgin]", shorttitle = "VRB Strategy [wbburgin]", overlay=true,
pyramiding=20,max_bars_back=2000,initial_capital=10000)
wma(float priceType,int length,float weight) =>
norm = 0.0
sum = 0.0
for i = 0 to length - 1
norm := norm + weight
sum := sum + priceType[i] * weight
sum / norm
// This definition of volatility uses the high-low range divided by the average of that range.
volatility(source,length) =>
h = ta.highest(source,length)
l = ta.lowest(source,length)
vx = 2 * (h - l) / (h + l)
vx
vm1 = input.int(100,"Average Length")
volLen = input.int(100,"Volatility Length")
vsrc = input.source(close,"Volatility Source")
cross_type = input.source(close,"Exit Source")
exit_type = input.string("Volatility MA",options=["Volatility MA","Range Crossover"],title="Exit Type")
volatility = volatility(vsrc,volLen)
highband1 = close + (close * volatility)
lowband1 = close - (close * volatility)
hb1 = wma(highband1,vm1,volatility)
lb1 = wma(lowband1,vm1,volatility)
hlavg = math.avg(hb1,lb1)
upcross = ta.crossover(high,hb1) //Crossing over the high band of historical volatility signifies a bullish breakout
dncross = ta.crossunder(low,lb1) //Crossing under the low band of historical volatility signifies a bearish breakout
vlong = upcross
vshort = dncross
vlong_exit = switch
exit_type == "Volatility MA" => ta.crossunder(cross_type,hlavg)
exit_type == "Range Crossover" => ta.crossunder(cross_type,hb1)
vshort_exit = switch
exit_type == "Volatility MA" => ta.crossover(cross_type,hlavg)
exit_type == "Range Crossover" => ta.crossover(cross_type,lb1)
if vlong
strategy.entry("Long",strategy.long)
if vlong_exit
strategy.close("Long")
if vshort
strategy.entry("Short",strategy.short)
if vshort_exit
strategy.close("Short")
plot(hlavg,color=color.white,title="Weighted Volatility Moving Average")
t = plot(hb1,color=color.new(color.red,50),title="Volatility Reversal Band - Top")
b = plot(lb1,color=color.new(color.green,50),title="Volatility Reversal Band - Bottom")
alertcondition(vlong,"Volatility Long Entry Signal")
alertcondition(vlong_exit,"Volatility Long Exit Signal")
alertcondition(vshort,"Volatility Short Entry Signal")
alertcondition(vshort_exit,"Volatility Short Exit Signal")
fill(t,b,color=color.new(color.aqua,90)) |
Grid Spot Trading Algorithm V2 - The Quant Science | https://www.tradingview.com/script/ZJseWDie-Grid-Spot-Trading-Algorithm-V2-The-Quant-Science/ | thequantscience | https://www.tradingview.com/u/thequantscience/ | 370 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © thequantscience
// ██████╗ ██████╗ ██╗██████╗ ███████╗██████╗ ██████╗ ████████╗ █████╗ ██╗ ██████╗ ██████╗ ██████╗ ██╗████████╗██╗ ██╗███╗ ███╗ ██╗ ██╗██████╗
// ██╔════╝ ██╔══██╗██║██╔══██╗ ██╔════╝██╔══██╗██╔═══██╗╚══██╔══╝ ██╔══██╗██║ ██╔════╝ ██╔═══██╗██╔══██╗██║╚══██╔══╝██║ ██║████╗ ████║ ██║ ██║╚════██╗
// ██║ ███╗██████╔╝██║██║ ██║ ███████╗██████╔╝██║ ██║ ██║ ███████║██║ ██║ ███╗██║ ██║██████╔╝██║ ██║ ███████║██╔████╔██║ ██║ ██║ █████╔╝
// ██║ ██║██╔══██╗██║██║ ██║ ╚════██║██╔═══╝ ██║ ██║ ██║ ██╔══██║██║ ██║ ██║██║ ██║██╔══██╗██║ ██║ ██╔══██║██║╚██╔╝██║ ╚██╗ ██╔╝██╔═══╝
// ╚██████╔╝██║ ██║██║██████╔╝ ███████║██║ ╚██████╔╝ ██║ ██║ ██║███████╗╚██████╔╝╚██████╔╝██║ ██║██║ ██║ ██║ ██║██║ ╚═╝ ██║ ╚████╔╝ ███████╗
// ╚═════╝ ╚═╝ ╚═╝╚═╝╚═════╝ ╚══════╝╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═══╝ ╚══════╝
//@version=5
strategy(
title = 'Grid Spot Trading Algorithm V2 - The Quant Science™',
overlay = true,
calc_on_every_tick = true,
initial_capital = 10000,
commission_type = strategy.commission.percent,
commission_value = 0.10,
pyramiding = 5,
default_qty_type = strategy.percent_of_equity,
close_entries_rule = 'ANY'
)
/////////////////////////////// Coded by The Quant Science™ ////////////////////////////////////
// Upgrade 2.00 (2022.30.07)
// Upgrade 3.00 (2022.11.11)
// Upgrade 4.00 (2022.20.01)
// New release version 2.0 (2023.10.05)
////////////////////////////////////////////////////////////////////////////////////////////////////
high_price = input.price(defval = 0.00, title = 'High price: ', group = "TOP PRICE GRID", confirm = true, tooltip = "Top grid price.")
close_price = input.price(defval = 0.00, title = 'Low price: ', group = "BOTTOM PRICE GRID", confirm = true, tooltip = "Bottom grid price.")
grid_destroyer = input.bool(defval = false,title = 'Active grid destroyer:',group = "STOP LOSS CONFIGURATION", inline = "SL", tooltip = "Destroy the grid when price crossunder the stop loss level.", confirm = false)
stop_level = input.price(defval = 0.00, title = '',group = "STOP LOSS CONFIGURATION", inline = "SL", confirm = false, tooltip = "Stop loss price level. Set price level to destroy the grid and close all the positions.")
grid_range = high_price - close_price
var float grid_1 = 0
var float grid_2 = 0
var float grid_3 = 0
var float grid_4 = 0
var float grid_5 = 0
var float grid_6 = 0
var float grid_7 = 0
var float grid_8 = 0
var float grid_9 = 0
var float grid_10 = 0
var float grid_factor = 0
if (high_price > 0 or close_price > 0)
grid_factor := grid_range / 9
grid_1 := (high_price)
grid_2 := (high_price - (grid_factor * 1))
grid_3 := (high_price - (grid_factor * 2))
grid_4 := (high_price - (grid_factor * 3))
grid_5 := (high_price - (grid_factor * 4))
grid_6 := (high_price - (grid_factor * 5))
grid_7 := (high_price - (grid_factor * 6))
grid_8 := (high_price - (grid_factor * 7))
grid_9 := (high_price - (grid_factor * 8))
grid_10 := (close_price)
var float lots = 0
var float account_balance = 0
long = (ta.crossunder(close, grid_5) or ta.crossover(close, grid_5))
if (high_price > 0 or close_price > 0)
if strategy.opentrades==0
account_balance := strategy.equity
lots := (account_balance / close)/5
if long
strategy.order(id = "O #1", direction = strategy.long, qty = lots, limit = grid_6)
strategy.order(id = "O #2", direction = strategy.long, qty = lots, limit = grid_7)
strategy.order(id = "O #3", direction = strategy.long, qty = lots, limit = grid_8)
strategy.order(id = "O #4", direction = strategy.long, qty = lots, limit = grid_9)
strategy.order(id = "O #5", direction = strategy.long, qty = lots, limit = grid_10)
Exit(type) =>
switch type
"Grid level 5" => grid_1
"Grid level 4" => grid_2
"Grid level 3" => grid_3
"Grid level 2" => grid_4
"Grid level 1" => grid_5
exit_input = input.string("Grid level 1", title = "Select exit", options = ["Grid level 1", "Grid level 2", "Grid level 3", "Grid level 4", "Grid level 5"], tooltip = "Starting from the middle to the top.", group = "Exit Configuration")
exit_price = Exit(exit_input)
if ta.crossover(close, exit_price) and (high_price > 0 or close_price > 0)
strategy.close_all("Close-Position")
strategy.cancel("O #1")
strategy.cancel("O #2")
strategy.cancel("O #3")
strategy.cancel("O #4")
strategy.cancel("O #5")
if (close < grid_10 or ta.crossover(close, grid_10))
strategy.cancel_all()
if (high_price > 0 or close_price > 0) and grid_destroyer==true
if ta.crossunder(close, stop_level)
strategy.close_all("Grid Destroyed !!!")
var float new_ten_grid_1 = 0
var float new_ten_grid_2 = 0
var float new_ten_grid_3 = 0
var float new_ten_grid_4 = 0
var float new_ten_grid_5 = 0
var float new_ten_grid_6 = 0
var float new_ten_grid_7 = 0
var float new_ten_grid_8 = 0
var float new_ten_grid_9 = 0
var float new_ten_grid_10 = 0
var float grid_destroyed_ten = 0
if (high_price > 0 or close_price > 0)
new_ten_grid_1 := grid_1
new_ten_grid_2 := grid_2
new_ten_grid_3 := grid_3
new_ten_grid_4 := grid_4
new_ten_grid_5 := grid_5
new_ten_grid_6 := grid_6
new_ten_grid_7 := grid_7
new_ten_grid_8 := grid_8
new_ten_grid_9 := grid_9
new_ten_grid_10 := grid_10
if grid_destroyer == true
grid_destroyed_ten := stop_level
else
new_ten_grid_1 := na
new_ten_grid_2 := na
new_ten_grid_3 := na
new_ten_grid_4 := na
new_ten_grid_5 := na
new_ten_grid_6 := na
new_ten_grid_7 := na
new_ten_grid_8 := na
new_ten_grid_9 := na
new_ten_grid_10 := na
if grid_destroyer == false
grid_destroyed_ten := na
fill(plot(new_ten_grid_1, color = color.new(#35f83b, 90)),
plot(new_ten_grid_2, color = color.new(#36fa3d, 90)),
color = color.new(#37ff3e, 90))
fill(plot(new_ten_grid_2, color = color.new(#35f53c, 85)),
plot(new_ten_grid_3, color = color.new(#36f53c, 85)),
color = color.new(#34fc3b, 85))
fill(plot(new_ten_grid_3, color = color.new(#35fa3c, 80)),
plot(new_ten_grid_4, color = color.new(#33f83a, 80)),
color = color.new(#32ff39, 80))
fill(plot(new_ten_grid_4, color = color.new(#35fc3c, 70)),
plot(new_ten_grid_5, color = color.new(#35f83c, 70)),
color = color.new(#34ff3b, 70))
fill(plot(new_ten_grid_5, color = color.new(#35f13b, 60)),
plot(new_ten_grid_6, color = color.new(#34fc3b, 60)),
color = color.new(#37ff3d, 60))
fill(plot(new_ten_grid_6, color = color.new(#f83333, 60)),
plot(new_ten_grid_7, color = color.new(#fd3838, 60)),
color = color.new(#ff3434, 60))
fill(plot(new_ten_grid_7, color = color.new(#fa3636, 70)),
plot(new_ten_grid_8, color = color.new(#fa3737, 70)),
color = color.new(#ff3636, 70))
fill(plot(new_ten_grid_8, color = color.new(#f83535, 80)),
plot(new_ten_grid_9, color = color.new(#fa3636, 80)),
color = color.new(#fd3434, 80))
fill(plot(new_ten_grid_9, color = color.new(#fc3434, 85)),
plot(new_ten_grid_10, color = color.new(#fc3737, 85)),
color = color.new(#ff3636, 85))
plot(grid_destroyed_ten, color = color.new(#fc3636, 80), linewidth = 10)
|
Master Supertrend Strategy [Trendoscope] | https://www.tradingview.com/script/YexkkFy8-Master-Supertrend-Strategy-Trendoscope/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 683 | strategy | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © Trendoscope Pty Ltd
// ░▒
// ▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒
// ▒▒▒▒▒▒▒░ ▒ ▒▒
// ▒▒▒▒▒▒ ▒ ▒▒
// ▓▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// ▒ ▒ ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░▒▒▒▒▒▒▒▒
// ▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒ ▒▒▒▒▒
// ░▒▒▒▒ ▒▒▒▒▓ ████████╗██████╗ ███████╗███╗ ██╗██████╗ ██████╗ ███████╗ ██████╗ ██████╗ ██████╗ ███████╗
// ▓▒▒▒▒ ▒▒▒▒ ╚══██╔══╝██╔══██╗██╔════╝████╗ ██║██╔══██╗██╔═══██╗██╔════╝██╔════╝██╔═══██╗██╔══██╗██╔════╝
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ██║ ██████╔╝█████╗ ██╔██╗ ██║██║ ██║██║ ██║███████╗██║ ██║ ██║██████╔╝█████╗
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██╔══██╗██╔══╝ ██║╚██╗██║██║ ██║██║ ██║╚════██║██║ ██║ ██║██╔═══╝ ██╔══╝
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██║ ██║███████╗██║ ╚████║██████╔╝╚██████╔╝███████║╚██████╗╚██████╔╝██║ ███████╗
// ▒▒ ▒
//
//@version=5
// indicator("Master Supertrend [Trendoscope]", "MST [Trendoscope]", overlay = true)
strategy("Master Supertrend Strategy [Trendoscope]", "MSTS [Trendoscope]", overlay=true, initial_capital=1000,
default_qty_type=strategy.percent_of_equity, default_qty_value=10, commission_type=strategy.commission.percent,
pyramiding=1, commission_value=0.05, close_entries_rule="ANY", margin_long=100, margin_short=100,
max_lines_count=500, max_labels_count=500, max_boxes_count=500, use_bar_magnifier=false)
import HeWhoMustNotBeNamed/ta/1 as eta
import HeWhoMustNotBeNamed/arrayutils/22 as pa
supertrendType = input.string('Plus/Minus Range', 'Range Type', ['Plus/Minus Range', 'Ladder TR', 'True Range', 'Standard Deviation'], 'Type of range used for supertrend calculation')
rangeType = input.string('high', 'Applied Calculation', ['sma', 'ema', 'hma', 'rma', 'wma', 'high', 'median'], 'Applied calculation method on the range before using them for calculation of supertrend stops')
length = input.int(60, 'Length', 10, 1000, 10, tooltip = 'Supertrend range calculation length')
multiplier = input.int(2, 'Multiplier', 2, 100, 1, tooltip='Supertrend range multiplier')
useClosePrices = input.bool(true, 'Use Close Price', tooltip = 'Use close price as reference instad of high/low for calculation of stop')
waitForClose = input.bool(true, 'Wait for Close', tooltip = 'Wait for close before changing the direction and change direction only if close price has breached the stop line')
useDiminishingRange = input.bool(true, 'Diminishing Stop Distance', tooltip = 'When selected stop distance from reference price can only decrease and not increase')
float ladderPositiveAtr = na
float ladderNegativeAtr = na
if(supertrendType == 'Ladder TR')
var plusLadderAtr = array.new<float>()
var minusLadderAtr = array.new<float>()
if(open < close)
pa.push(plusLadderAtr, ta.tr, length)
else
pa.push(minusLadderAtr, ta.tr, length)
ladderPositiveAtr := pa.ma(plusLadderAtr, rangeType, length)
ladderNegativeAtr := pa.ma(minusLadderAtr, rangeType, length)
plusRange = supertrendType == 'Plus/Minus Range' ? math.max(high-open, high-close[1]) : supertrendType == 'Ladder TR'? ladderPositiveAtr : supertrendType == 'True Range' ? ta.tr : ta.stdev(close, length, true)
minusRange = supertrendType == 'Plus/Minus Range' ? math.max(open-low, close[1]-low) : supertrendType == 'Ladder TR'? ladderNegativeAtr : supertrendType == 'True Range' ? ta.tr : ta.stdev(close, length, true)
appliedPlusRange = supertrendType == 'Ladder TR'? plusRange : eta.ma(plusRange, rangeType, length)
appliedMinusRange = supertrendType == 'Ladder TR'? minusRange: eta.ma(minusRange, rangeType, length)
var direction = 1
var derivedPlusRange = appliedPlusRange*multiplier
var derivedMinusRange = appliedMinusRange*multiplier
currentDerivedPlusRange = appliedPlusRange*multiplier
derivedPlusRange := direction < 0 and useDiminishingRange? math.min(nz(derivedPlusRange,currentDerivedPlusRange), currentDerivedPlusRange) : currentDerivedPlusRange
currentDerivedMinusRange = appliedMinusRange*multiplier
derivedMinusRange := direction > 0 and useDiminishingRange? math.min(nz(derivedMinusRange,currentDerivedMinusRange), currentDerivedMinusRange) : currentDerivedMinusRange
buyStopCurrent = (useClosePrices? close : low) - derivedMinusRange
var buyStop = buyStopCurrent
sellStopCurrent = (useClosePrices? close : high) + derivedPlusRange
var sellStop = sellStopCurrent
buyStop:= direction > 0? math.max(nz(buyStop, buyStopCurrent), buyStopCurrent) : buyStopCurrent
sellStop:=direction < 0? math.min(nz(sellStop, sellStopCurrent), sellStopCurrent) : sellStopCurrent
direction := direction > 0 and (waitForClose?close:low) < buyStop? -1 :
direction < 0 and (waitForClose?close:high) > sellStop? 1 : direction
supertrend = direction[1] > 0? buyStop : sellStop
plot(supertrend, 'Supertrend', direction[1]>0? color.red:color.green)
plot(direction, "direction", display = display.data_window)
plot(strategy.equity, "Equity", display = display.data_window)
plot(strategy.openprofit, "Open Profit", display = display.data_window)
plot(strategy.opentrades, "Open Trades", display = display.data_window)
if(direction > 0)
strategy.entry("Long", strategy.long)
if(direction < 0)
strategy.entry("Short", strategy.short) |
BB and KC Strategy | https://www.tradingview.com/script/hUK5mTUI-BB-and-KC-Strategy/ | jensenvilhelm | https://www.tradingview.com/u/jensenvilhelm/ | 52 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jensenvilhelm
//@version=5
strategy("BB and KC Strategy", overlay=true, default_qty_type=strategy.cash, default_qty_value=1000)
// Define the input parameters for the strategy, these can be changed by the user to adjust the strategy
kcLength = input.int(20, "KC Length", minval=1) // Length for Keltner Channel calculation
kcStdDev = input.float(2.2, "KC StdDev") // Standard Deviation for Keltner Channel calculation
bbLength = input.int(20, "BB Length", minval=1) // Length for Bollinger Bands calculation
bbStdDev = input.float(2, "BB StdDev") // Standard Deviation for Bollinger Bands calculation
volumeLength = input.int(10, "Volume MA Length", minval=1) // Length for moving average of volume calculation
stopLossPercent = input.float(1.5, "Stop Loss (%)") // Percent of price for Stop loss
trailStopPercent = input.float(2, "Trail Stop (%)") // Percent of price for Trailing Stop
barsInTrade = input.int(20, "Bars in trade before exit", minval = 1) // Minimum number of bars in trade before considering exit
// Calculate Bollinger Bands and Keltner Channel
[bb_middle, bb_upper, bb_lower] = ta.bb(close, bbLength, bbStdDev) // Bollinger Bands calculation
[kc_middle, kc_upper, kc_lower] = ta.kc(close, kcLength, kcStdDev) // Keltner Channel calculation
// Calculate moving average of volume
vol_ma = ta.sma(volume, volumeLength) // Moving average of volume calculation
// Plotting Bollinger Bands and Keltner Channels on the chart
plot(bb_upper, color=color.red) // Bollinger Bands upper line
plot(bb_middle, color=color.blue) // Bollinger Bands middle line
plot(bb_lower, color=color.red) // Bollinger Bands lower line
plot(kc_upper, color=color.rgb(105, 255, 82)) // Keltner Channel upper line
plot(kc_middle, color=color.blue) // Keltner Channel middle line
plot(kc_lower, color=color.rgb(105, 255, 82)) // Keltner Channel lower line
// Define entry conditions: long position if upper KC line crosses above upper BB line and volume is above MA of volume
// and short position if lower KC line crosses below lower BB line and volume is above MA of volume
longCond = ta.crossover(kc_upper, bb_upper) and volume > vol_ma // Entry condition for long position
shortCond = ta.crossunder(kc_lower, bb_lower) and volume > vol_ma // Entry condition for short position
// Define variables to store entry price and bar counter at entry point
var float entry_price = na // variable to store entry price
var int bar_counter = na // variable to store bar counter at entry point
// Check entry conditions and if met, open long or short position
if (longCond)
strategy.entry("Buy", strategy.long) // Open long position
entry_price := close // Store entry price
bar_counter := 1 // Start bar counter
if (shortCond)
strategy.entry("Sell", strategy.short) // Open short position
entry_price := close // Store entry price
bar_counter := 1 // Start bar counter
// If in a position and bar counter is not na, increment bar counter
if (strategy.position_size != 0 and na(bar_counter) == false)
bar_counter := bar_counter + 1 // Increment bar counter
// Define exit conditions: close position if been in trade for more than specified bars
// or if price drops by more than specified percent for long or rises by more than specified percent for short
if (bar_counter > barsInTrade) // Only consider exit after minimum bars in trade
if (bar_counter >= barsInTrade)
strategy.close_all() // Close all positions
// Stop loss and trailing stop
if (strategy.position_size > 0)
strategy.exit("Sell", "Buy", stop=entry_price * (1 - stopLossPercent/100), trail_points=entry_price * trailStopPercent/100) // Set stop loss and trailing stop for long position
else if (strategy.position_size < 0)
strategy.exit("Buy", "Sell", stop=entry_price * (1 + stopLossPercent/100), trail_points=entry_price * trailStopPercent/100) // Set stop loss and trailing stop for short position
|
Strategy Template | https://www.tradingview.com/script/ZeaaEnKo-Strategy-Template/ | BigJasTrades | https://www.tradingview.com/u/BigJasTrades/ | 28 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © BigJasTrades https://linktr.ee/bigjastrades
// READ THIS BEFORE USE:
// This code is provided as an example strategy for educational purposes only. It comes with NO warranty or claims of performance.
// It should be used as a basis for your own learning and development and to create your own strategies.
// It is NOT provided to enable you to profitably trade.
// If you use this code or any part of it you agree that you have thoroughly tested it and determined that it is suitable for your own purposes prior to use.
// If you use this code or any part of it you agree that you accept all risk and you are responsibile for the results.
//@version=5
strategy(title = "Strategy Template", shorttitle = "ST v1.0", overlay = true, pyramiding = 1, initial_capital = 1000, commission_type = strategy.commission.percent, commission_value = 0.1, max_labels_count = 500)
//INPUTS
//indicator values
shortSMAlength = input.int(defval = 14, title = "Short SMA Length", tooltip = "Set the length of the short simple moving average here.", minval = 1, step = 1, group = "Indicator Settings")
longSMAlength = input.int(defval = 28, title = "Long SMA Length", tooltip = "Set the length of the long simple moving average here.", minval = 1, step = 1, group = "Indicator Settings")
//compounding
compoundingSelected = input.bool(defval = true, title = "Compounding", tooltip = "Select this option if you want to compound your net profits.", group = "Compounding")
//take profit and stop loss
takeProfitSelected = input.bool(defval = true, title = "Use Take Profit", tooltip = "Select this to enable take profits.", group = "Take Profit and Stop Loss")
takeProfitPercent = input.float(defval = 1.0, title = "Take Profit %", tooltip = "Set the value of take profits here.", minval = 0.1, step = 0.1, group = "Take Profit and Stop Loss")
stopLossSelected = input.bool(defval = true, title = "Use Stop Loss", tooltip = "Select this to enable stop losses.", group = "Take Profit and Stop Loss")
stopLossPercent = input.float(defval = 1.0, title = "Stop Loss %", tooltip = "Set the value of stop losses here.", minval = 0.1, step = 0.1, group = "Take Profit and Stop Loss")
//trading window
startDate = input.time(defval = timestamp("1 Jan 2023 00:00:00"), title = "Start Date", tooltip = "Use this to set the date and time when the strategy will start placing trades. Set this to a time just after the last candle when activating auto trading.", group = "TRADING WINDOW")
endDate = input.time(defval = timestamp("1 Jan 2030 00:00:00"), title = "End Date", tooltip = "Use this to set the date and time when the strategy will stop placing trades.", group = "TRADING WINDOW")
//VARIABLES
var float tradingCapital = na //trading capital is used to calculate position size based on the intitial capital and, if compounding is selected, also the net profit
var float positionSize = na //position size is used to set the quantity of the asset you want to buy. It is based on the initial capital and the net profit if compounding is selected.
var float takeProfitPrice = na //this is used for take profit targets if selected
var float stopLossPrice = na //this is used for stop loss if selected
inTradeWindow = (time >= startDate) and (time < endDate) //calculate the trading/backtesting window
//COMPOUNDING
if compoundingSelected // set the tradingCapital available to the strategy based on wither Compounding has been selected or not. This will be used to determine the position size.
tradingCapital := strategy.initial_capital + strategy.netprofit
else
tradingCapital := strategy.initial_capital
//ENTRY CONDITIONS
//replace these with your own conditions
longCondition = ta.crossover(source1 = ta.sma(source = close, length = shortSMAlength), source2 = ta.sma(source = close, length =longSMAlength))
shortCondition = ta.crossunder(source1 = ta.sma(source = close, length = shortSMAlength), source2 = ta.sma(source = close, length = longSMAlength))
//EXIT CONDITIONS
//Exit conditions are based on stop loss, take profit and the opposite entry condition being present. Stop Loss and Take Profit are contained in the strategy.exit code below and are based on the value assigned in the Inputs.
//ENTRY ORDERS
//Enter Long
if longCondition and inTradeWindow
//close any prior short positions
if strategy.position_size < 0 //if in a short position
strategy.close_all(comment = "Buy to Close")
//set position size
positionSize := tradingCapital / close
//enter long position
strategy.entry(id = "Buy to Open", direction = strategy.long, qty = positionSize)
//Enter Short
if shortCondition and inTradeWindow
//close any prior long positions
if strategy.position_size > 0 //if in a long position
strategy.close_all(comment = "Sell to Close")
//set position size
positionSize := tradingCapital / close
//enter short position
strategy.entry(id = "Sell to Open", direction = strategy.short, qty = positionSize)
//IN-ORDER MANAGEMENT
//placeholder - none used in this template
//EXIT ORDERS
//Stop Loss and Take Profit for Long Positions
if strategy.opentrades > 0 and strategy.position_size > 0 and (takeProfitSelected or stopLossSelected) //if there is an open position and it is a long position and either a take profit or sto ploss is selected.
if takeProfitSelected
takeProfitPrice := strategy.position_avg_price * (1 + (takeProfitPercent / 100))
else
takeProfitPrice := na
if stopLossSelected
stopLossPrice := strategy.position_avg_price * (1 - (stopLossPercent / 100))
else
stopLossPrice := na
strategy.exit(id = "Exit", from_entry = "Buy to Open", qty_percent = 100, limit = takeProfitPrice, stop = stopLossPrice, comment_profit = "Long Take Profit", comment_loss = "Long Stop Loss")
//Stop Loss and Take Profit for Short Positions
if strategy.opentrades > 0 and strategy.position_size < 0 and (takeProfitSelected or stopLossSelected) //if there is an open position and it is a short position and either a take profit or sto ploss is selected.
if takeProfitSelected
takeProfitPrice := strategy.position_avg_price * (1 - (takeProfitPercent / 100))
else
takeProfitPrice := na
if stopLossSelected
stopLossPrice := strategy.position_avg_price * (1 + (stopLossPercent / 100))
else
stopLossPrice := na
strategy.exit(id = "Exit", from_entry = "Sell to Open", qty_percent = 100, limit = takeProfitPrice, stop = stopLossPrice, comment_profit = "Short Take Profit", comment_loss = "Short Stop Loss")
//DEBUGGING LABELS
//un-comment these lables to use for your debugging. Replace the text inside the str.tostring() function to display different values on the chart.
//label.new(x=bar_index, y=high, text=str.tostring(takeProfitPrice), yloc=yloc.abovebar, color=color.new(color.red,100), style=label.style_label_down, textcolor=color.white)
//label.new(x=bar_index, y=high, text=str.tostring(stopLossPrice), yloc=yloc.belowbar, color=color.new(color.red,100), style=label.style_label_down, textcolor=color.white)
//VISUALISATIONS
plot(series = ta.sma(source = close, length = shortSMAlength), title = "Short SMA", color = color.new(color = color.red, transp = 50), linewidth = 2)
plot(series = ta.sma(source = close, length = longSMAlength), title = "Long SMA", color = color.new(color = color.blue, transp = 50), linewidth = 2)
bgcolor(color = longCondition ? color.new(color = color.green, transp = 95) : na, title = "Long")
bgcolor(color = shortCondition ? color.new(color = color.red, transp = 95) : na, title = "Short") |
Heikin Ashi ROC Percentile Strategy | https://www.tradingview.com/script/h1pOrB3i-Heikin-Ashi-ROC-Percentile-Strategy/ | jensenvilhelm | https://www.tradingview.com/u/jensenvilhelm/ | 72 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jensenvilhelm
//@version=5
strategy("Heikin Ashi ROC Percentile Strategy", shorttitle="ROC ON" , overlay=false)
// User Inputs
zerohLine = input(0, title="Midline") // Zero line, baseline for ROC (customer can modify this to adjust midline)
rocLength = input(100, title="roc Length") // Lookback period for SMA and ROC (customer can modify this to adjust lookback period)
stopLossLevel = input(2, title="Stop Loss (%)") // Level at which the strategy stops the loss (customer can modify this to adjust stop loss level)
startDate = timestamp("2015 03 03") // Start date for the strategy (customer can modify this to adjust start date)
// Heikin Ashi values
var float haClose = na // Define Heikin Ashi close price
var float haOpen = na // Define Heikin Ashi open price
haClose := ohlc4 // Calculate Heikin Ashi close price as average of OHLC4 (no customer modification needed here)
haOpen := na(haOpen[1]) ? (open + close) / 2 : (haOpen[1] + haClose[1]) / 2 // Calculate Heikin Ashi open price (no customer modification needed here)
// ROC Calculation
roc = ta.roc(ta.sma(haClose, rocLength), rocLength) // Calculate Rate of Change (ROC) (customer can modify rocLength in the inputs)
rocHigh = ta.highest(roc, 50) // Get the highest ROC of the last 50 periods (customer can modify this to adjust lookback period)
rocLow = ta.lowest(roc, 50) // Get the lowest ROC of the last 50 periods (customer can modify this to adjust lookback period)
upperKillLine = ta.percentile_linear_interpolation(rocHigh, 10, 75) // Calculate upper kill line (customer can modify parameters to adjust this line)
lowerKillLine = ta.percentile_linear_interpolation(rocLow, 10, 25) // Calculate lower kill line (customer can modify parameters to adjust this line)
// Trade conditions
enterLong = ta.crossover(roc, lowerKillLine) // Define when to enter long positions (customer can modify conditions to adjust entry points)
exitLong = ta.crossunder(roc, upperKillLine) // Define when to exit long positions (customer can modify conditions to adjust exit points)
enterShort = ta.crossunder(roc, upperKillLine) // Define when to enter short positions (customer can modify conditions to adjust entry points)
exitShort = ta.crossover(roc, lowerKillLine ) // Define when to exit short positions (customer can modify conditions to adjust exit points)
// Strategy execution
if(time >= startDate) // Start strategy from specified start date
if (enterLong)
strategy.entry("Long", strategy.long) // Execute long trades
if (exitLong)
strategy.close("Long") // Close long trades
if (enterShort)
strategy.entry("Short", strategy.short) // Execute short trades
if (exitShort)
strategy.close("Short") // Close short trades
// Plotting
plot(zerohLine,title="Zeroline") // Plot zero line
plot(roc, "RSI", color=color.rgb(248, 248, 248)) // Plot ROC
plot(rocHigh, "Roc High", color = color.rgb(175, 78, 76)) // Plot highest ROC
plot(rocLow, "Roc Low", color = color.rgb(175, 78, 76)) // Plot lowest ROC
plot(upperKillLine, "Upper Kill Line", color = color.aqua) // Plot upper kill line
plot(lowerKillLine, "Lower Kill Line", color = color.aqua) // Plot lower kill line
|
Powertrend - Volume Range Filter Strategy [wbburgin] | https://www.tradingview.com/script/45FlB2qH-Powertrend-Volume-Range-Filter-Strategy-wbburgin/ | wbburgin | https://www.tradingview.com/u/wbburgin/ | 1,408 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © wbburgin
//@version=5
strategy("Powertrend - Volume Range Filter [wbburgin]",overlay=true,initial_capital = 1000, default_qty_type = strategy.percent_of_equity,
default_qty_value=10, commission_value=0.00, slippage = 0, shorttitle="Powertrend [wbburgin]")
import wbburgin/wbburgin_utils/2 as utils
rngfilt_volumeadj(float source1, float tethersource, float smoothrng)=>
rngfilt = source1
if tethersource > nz(tethersource[1])
rngfilt := (source1 - smoothrng) < nz(rngfilt[1]) ? nz(rngfilt[1]) : (source1 - smoothrng)
else
rngfilt := (source1 + smoothrng) > nz(rngfilt[1]) ? nz(rngfilt[1]) : (source1 + smoothrng)
rngfilt
l = input.int(200,"Length",group="General")
useadx = input.bool(false,"ADX Filter",group="Filters",inline="ADX")
lengthadx = input.int(14,title="",group="Filters",inline="ADX")
usehl = input.bool(false,"Range Supertrend",group="Filters",inline="HL")
lengthhl = input.int(14,title="",group="Filters",inline="HL")
showhl = input.bool(false,"Plot",group="Filters",inline="HL")
usevwma = input.bool(false,"VWMA Filter",group="Filters",inline="VWMA")
lengthvwma = input.int(200,title="",group="Filters",inline="VWMA")
showvwma = input.bool(false,"Plot",group="Filters",inline="VWMA")
highlighting = input.bool(true,"Highlighting",group="Display")
barcolors = input.bool(true,"Bar Colors",group="Display")
buyselllabels = input.bool(true,"Entry-Exit Labels",group="Display")
volrng = rngfilt_volumeadj(close,volume,utils.smoothrng(close,l,3))
smoothrng = utils.smoothrng(close,l,3)
basetype = volrng
hband = basetype + smoothrng
lowband = basetype - smoothrng
// Filters
// -- Built-in
uprng = utils.trendUp(basetype)
// -- ADX
[x,y,adx] = ta.dmi(lengthadx,lengthadx)
adx_vwma = ta.vwma(adx,lengthadx)
adx_filter = not useadx ? true : adx > adx_vwma ? true : false
// -- High/Low
lowband_trendfollow = ta.lowest(lowband,lengthhl)
highband_trendfollow = ta.highest(hband,lengthhl)
in_general_uptrend = ta.barssince(ta.crossover(close,highband_trendfollow[1])) < ta.barssince(ta.crossunder(close,lowband_trendfollow[1]))
igu_filter_positive = not usehl ? true : in_general_uptrend ? true : false
igu_filter_negative = not usehl ? true : not in_general_uptrend ? true : false
// -- VWMA
vwma = ta.vwma(volrng,lengthvwma)
vwma_filter_positive = not usevwma ? true : volrng > vwma ? true : false
//No negative needed
b = uprng and ta.crossover(close,hband) and igu_filter_positive and adx_filter and vwma_filter_positive
s = not uprng and ta.crossunder(close,lowband) and igu_filter_negative and adx_filter
in_b = ta.barssince(b)[1] < ta.barssince(s)[1]
in_s = ta.barssince(s)[1] < ta.barssince(b)[1]
if b
strategy.entry("Long",strategy.long)
alert("Powertrend Entry",freq=alert.freq_once_per_bar)
if s
strategy.close("Long")
alert("Powertrend Exit",freq=alert.freq_once_per_bar)
mp=plot(basetype,color=color.white,title="Volume Range")
hp=plot(hband,color=na,title="High Range")
lp=plot(lowband,color=na, title="Low Range")
bb=plot(not showhl ? na : in_general_uptrend ? lowband_trendfollow : na, color=color.lime, title="Bullish Trend Follow",style=plot.style_linebr)
uu=plot(not showhl ? na : not in_general_uptrend ? highband_trendfollow : na,color=color.yellow,title="Bearish Trend Follow",style=plot.style_linebr)
plot(not showvwma ? na : vwma, color = color.orange,title="VWMA")
fill(hp,mp,color=not highlighting ? na : color.new(color.lime,88))
fill(mp,lp,color=not highlighting ? na : color.new(color.yellow,88))
fill(uu,hp,color=not highlighting ? na : in_general_uptrend ? na : color.new(color.red,88))
fill(bb,lp,color=not highlighting ? na : not in_general_uptrend ? na : color.new(color.blue,88))
plotshape(b and not in_b and buyselllabels ? lowband : na,"Buy Label",style=shape.labelup,location=location.absolute,
color=color.green,textcolor=color.white,text = "Buy", size=size.tiny)
plotshape(s and not in_s and buyselllabels ? hband : na,"Sell Label",style=shape.labeldown,location=location.absolute,
color=color.red,textcolor=color.white,text = "Sell", size=size.tiny)
barcolor(barcolors ? uprng ? color.lime : color.yellow : na)
//alertcondition(b,"PT Buy")
//alertcondition(s,"PT Sell") |
Ta Strategy | https://www.tradingview.com/script/m5HpphJk-Ta-Strategy/ | AHMEDABDELAZIZZIZO | https://www.tradingview.com/u/AHMEDABDELAZIZZIZO/ | 116 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © AHMEDABDELAZIZZIZO
//@version=5
strategy("Ta Strategy", overlay=true,initial_capital = 1000 ,default_qty_type = strategy.percent_of_equity ,default_qty_value = 5 , commission_type = strategy.commission.percent , commission_value = 0.1 )
// inputs
inversestrategy = input.bool(false, title = "Inverse Strategy",tooltip = "This option makes you reverse the strategy so that long signals become where to short ")
direction = input.string(defval = "Both" , options = ["Both" , "Short" , "Long"] )
leftbars= input(6,title = " Left Bars" , group = "Support and resistance")
rightbars = input(6, title = " Right Bars", group = "Support and resistance")
macdfast = input(12, title = "MACD Fast", group = "MACD")
macdslow = input(26, title = "MACD Slow",group = "MACD")
macdsignal = input(7, "MACD Signal",group = "MACD")
sellqty = input(50, title = "QTY to sell at TP 1")
len = input(14, title="ADX Length" , group = "ADX")
// sup and res
res = fixnan(ta.pivothigh(high,leftbars,rightbars))
sup = fixnan(ta.pivotlow(low , leftbars,rightbars))
// macd
macd =ta.ema(close,macdfast) - ta.ema(close,macdslow)
signal=ta.ema(macd,macdsignal)
//adx
up = ta.change(high)
down = -ta.change(low)
plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
truerange = ta.rma(ta.tr,len)
plusDI = 100 * ta.rma(plusDM, len) / truerange
minusDI = 100 * ta.rma(minusDM, len) / truerange
dx = 100 * ta.rma(math.abs(plusDI - minusDI) / (plusDI + minusDI), len)
adx = ta.sma(dx, len)
// start deal condition
longcondition = ta.crossover(macd,signal) and close > res and ta.rsi(close,14) > 50 and plusDI > minusDI and adx > 20
shortcondition = ta.crossunder(macd,signal) and close < sup and ta.rsi(close,14) < 50 and plusDI < minusDI and adx > 20
//tp
longtp1 = input.float(6, "Long TP 1", minval = 0.0, step = 0.25, group = "Exit LONG Orders") /100
longtp2 = input.float(12, "Long TP 2", minval = 0.0, step = 0.25, group = "Exit LONG Orders") /100
longsl1 = input.float(3.0, "Long SL", minval = 0.0, step = 0.25, group = "Exit LONG Orders") /100
longtakeprofit1 = (strategy.position_avg_price * (1 + longtp1))
longstoploss1 = (strategy.position_avg_price * (1 - longsl1))
longtakeprofit2 = (strategy.position_avg_price * (1 + longtp2))
//sl
shorttp1 = input.float(6.0, "Short TP 1 ", minval = 0.0, step = 0.25, group = "Exit SHORT Orders")/100
shorttp2 = input.float(12.0, "Short TP 2", minval = 0.0, step = 0.25, group = "Exit SHORT Orders")/100
shortsl1 = input.float(3.0, "Short SL", minval = 0.0, step = 0.25, group = "Exit SHORT Orders")/100
shorttakeprofit1 = (strategy.position_avg_price * (1- shorttp1))
shortstoploss1 = (strategy.position_avg_price * (1 + shortsl1))
shorttakeprofit2 = (strategy.position_avg_price * (1- shorttp2))
//placeorders
if inversestrategy == false
if direction == "Both"
if longcondition and strategy.opentrades == 0
strategy.entry("long" , strategy.long )
strategy.exit("exit long 1","long",qty_percent = sellqty ,limit = longtakeprofit1,stop = longstoploss1)
strategy.exit("exit long 2","long",qty_percent = 100 ,limit = longtakeprofit2,stop = longstoploss1)
if high >= longtakeprofit1
strategy.cancel("exit long 2")
strategy.exit("exit long 3","long",qty_percent = 100 ,limit = longtakeprofit2,stop = strategy.position_avg_price)
if shortcondition and strategy.opentrades == 0
strategy.entry("short",strategy.short)
strategy.exit("exit short 1","short",qty_percent = sellqty ,limit = shorttakeprofit1,stop = shortstoploss1)
strategy.exit("exit short 2","short",qty_percent = 100 ,limit = shorttakeprofit2,stop = shortstoploss1)
if low <= shorttakeprofit1
strategy.cancel("exit short 2")
strategy.exit("exit short 3","short",qty_percent = 100 ,limit = shorttakeprofit2,stop = strategy.position_avg_price)
else if direction == "Long"
if longcondition and strategy.opentrades == 0
strategy.entry("long" , strategy.long )
strategy.exit("exit long 1","long",qty_percent = sellqty ,limit = longtakeprofit1,stop = longstoploss1)
strategy.exit("exit long 2","long",qty_percent = 100 ,limit = longtakeprofit2,stop = longstoploss1)
if high >= longtakeprofit1
strategy.cancel("exit long 2")
strategy.exit("exit long 3","long",qty_percent = 100 ,limit = longtakeprofit2,stop = strategy.position_avg_price)
else if direction == "Short"
if shortcondition and strategy.opentrades == 0
strategy.entry("short",strategy.short)
strategy.exit("exit short 1","short",qty_percent = sellqty ,limit = shorttakeprofit1,stop = shortstoploss1)
strategy.exit("exit short 2","short",qty_percent = 100 ,limit = shorttakeprofit2,stop = shortstoploss1)
if low <= shorttakeprofit1
strategy.cancel("exit short 2")
strategy.exit("exit short 3","short",qty_percent = 100 ,limit = shorttakeprofit2,stop = strategy.position_avg_price)
else
if direction == "Both"
if shortcondition and strategy.opentrades == 0
strategy.entry("long" , strategy.long )
strategy.exit("exit long 1","long",qty_percent = sellqty ,limit = longtakeprofit1,stop = longstoploss1)
strategy.exit("exit long 2","long",qty_percent = 100 ,limit = longtakeprofit2,stop = longstoploss1)
if high >= longtakeprofit1
strategy.cancel("exit long 2")
strategy.exit("exit long 3","long",qty_percent = 100 ,limit = longtakeprofit2,stop = strategy.position_avg_price)
if longcondition and strategy.opentrades == 0
strategy.entry("short",strategy.short)
strategy.exit("exit short 1","short",qty_percent = sellqty ,limit = shorttakeprofit1,stop = shortstoploss1)
strategy.exit("exit short 2","short",qty_percent = 100 ,limit = shorttakeprofit2,stop = shortstoploss1)
if low <= shorttakeprofit1
strategy.cancel("exit short 2")
strategy.exit("exit short 3","short",qty_percent = 100 ,limit = shorttakeprofit2,stop = strategy.position_avg_price)
else if direction == "Long"
if shortcondition and strategy.opentrades == 0
strategy.entry("long" , strategy.long )
strategy.exit("exit long 1","long",qty_percent = sellqty ,limit = longtakeprofit1,stop = longstoploss1)
strategy.exit("exit long 2","long",qty_percent = 100 ,limit = longtakeprofit2,stop = longstoploss1)
if high >= longtakeprofit1
strategy.cancel("exit long 2")
strategy.exit("exit long 3","long",qty_percent = 100 ,limit = longtakeprofit2,stop = strategy.position_avg_price)
else if direction == "Short"
if longcondition and strategy.opentrades == 0
strategy.entry("short",strategy.short)
strategy.exit("exit short 1","short",qty_percent = sellqty ,limit = shorttakeprofit1,stop = shortstoploss1)
strategy.exit("exit short 2","short",qty_percent = 100 ,limit = shorttakeprofit2,stop = shortstoploss1)
if low <= shorttakeprofit1
strategy.cancel("exit short 2")
strategy.exit("exit short 3","short",qty_percent = 100 ,limit = shorttakeprofit2,stop = strategy.position_avg_price)
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
lsl1 = plot(strategy.position_size <= 0 ? na : longstoploss1, color=color.rgb(124, 11, 11), style=plot.style_linebr, linewidth=1)
ltp1 = plot(strategy.position_size <= 0 ? na : longtakeprofit1, color=color.rgb(15, 116, 18), style=plot.style_linebr, linewidth=1)
ltp2 = plot(strategy.position_size <= 0 ? na : longtakeprofit2, color=color.rgb(15, 116, 18), style=plot.style_linebr, linewidth=1)
avg = plot(strategy.position_avg_price, color=color.rgb(255, 153, 0, 47), style=plot.style_linebr, linewidth=1)
fill(ltp1,avg , color =strategy.position_size <= 0 ? na : color.rgb(82, 255, 97, 90))
fill(ltp2,ltp1 , color =strategy.position_size <= 0 ? na : color.rgb(82, 255, 97, 90))
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
ssl1 = plot(strategy.position_size >= 0 ? na : shortstoploss1, color=color.red, style=plot.style_linebr, linewidth=1)
stp1 = plot(strategy.position_size >= 0 ? na : shorttakeprofit2, color=color.green, style=plot.style_linebr, linewidth=1)
stp2 = plot(strategy.position_size >= 0 ? na : shorttakeprofit1, color=color.green, style=plot.style_linebr, linewidth=1)
fill(stp1,avg , color =strategy.position_size >= 0 ? na : color.rgb(30, 92, 35, 90))
fill(stp2,stp1 , color =strategy.position_size >= 0 ? na : color.rgb(30, 92, 35, 90))
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
resplot = plot(res, color=ta.change(res) ? na : #bf141446, linewidth=3, offset=-(rightbars+1), title="res")
supplot = plot(sup, color=ta.change(sup) ? na : #118f113a, linewidth=3, offset=-(rightbars+1), title="sup") |
Yesterday's High v.17.07 | https://www.tradingview.com/script/ZSaEDKYt/ | tumiza999 | https://www.tradingview.com/u/tumiza999/ | 161 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Author: © tumiza 999
// © TheSocialCryptoClub
//@version=5
strategy("Yesterday's High v.17.07", overlay=true, pyramiding = 1,
initial_capital=10000,
default_qty_type=strategy.percent_of_equity, default_qty_value=10,
slippage=1, backtest_fill_limits_assumption=1, use_bar_magnifier=true,
commission_type=strategy.commission.percent, commission_value=0.075
)
// -----------------------------------------------------------------------------
// ROC Filter
// -----------------------------------------------------------------------------
// f_security function by LucF for PineCoders available here: https://www.tradingview.com/script/cyPWY96u-How-to-avoid-repainting-when-using-security-PineCoders-FAQ/
f_security(_sym, _res, _src, _rep) => request.security(_sym, _res, _src[not _rep and barstate.isrealtime ? 1 : 0])[_rep or barstate.isrealtime ? 0 : 1]
high_daily = f_security(syminfo.tickerid, "D", high, false)
roc_enable = input.bool(false, "", group="ROC Filter from CloseD", inline="roc")
roc_threshold = input.float(1, "Treshold", step=0.5, group="ROC Filter from CloseD", inline="roc")
closed = f_security(syminfo.tickerid,"1D",close, false)
roc_filter= roc_enable ? (close-closed)/closed*100 > roc_threshold : true
// -----------------------------------------------------------------------------
// Trigger Point
// -----------------------------------------------------------------------------
open_session = ta.change(time('D'))
price_session = ta.valuewhen(open_session, open, 0)
tf_session = timeframe.multiplier <= 60
bgcolor(open_session and tf_session ?color.new(color.blue,80):na, title = "Session")
first_bar = 0
if open_session
first_bar := bar_index
var max_today = 0.0
var min_today = 0.0
var high_daily1 = 0.0
var low_daily1 = 0.0
var today_open = 0.0
if first_bar
high_daily1 := max_today
low_daily1 := min_today
today_open := open
max_today := high
min_today := low
if high >= max_today
max_today := high
if low < min_today
min_today := low
same_day = today_open == today_open[1]
plot( timeframe.multiplier <= 240 and same_day ? high_daily1 : na, color= color.yellow , style=plot.style_linebr, linewidth=1, title='High line')
plot( timeframe.multiplier <= 240 and same_day ? low_daily1 : na, color= #E8000D , style=plot.style_linebr, linewidth=1, title='Low line')
// -----------------------------------------------------------------------------
// Strategy settings
// -----------------------------------------------------------------------------
Gap = input.float(1,"Gap%", step=0.5, tooltip="Gap di entrata su entry_price -n anticipa entrata, con +n posticipa entrata", group = "Entry")
Gap2 = (high_daily1 * Gap)/100
sl = input.float(3, "Stop-loss", step= 0.5, group = "Entry")
tp = input.float(9, "Take-profit", step= 0.5, group = "Entry")
stop_loss_price = strategy.position_avg_price * (1-sl/100)
take_price = strategy.position_avg_price * (1+tp/100)
sl_trl = input.float(2, "Trailing-stop", step = 0.5, tooltip = "Attiva trailing stop dopo che ha raggiunto...",group = "Trailing Stop Settings")//group = "Trailing Stop Settings")
Atrl= input.float(1, "Offset Trailing", step=0.5,tooltip = "Distanza dal prezzo", group = "Trailing Stop Settings")
stop_trl_price_cond = sl_trl * high/syminfo.mintick/100
stop_trl_price_offset_cond = Atrl * high/syminfo.mintick/100
stop_tick = sl * high/syminfo.mintick/100
profit_tick = tp * high/syminfo.mintick/100
mess_buy = "buy"
mess_sell = "sell"
// -----------------------------------------------------------------------------
// Entry - Exit - Close
// -----------------------------------------------------------------------------
if close < high_daily1 and roc_filter
strategy.entry("Entry", strategy.long, stop = high_daily1 + (Gap2), alert_message = mess_buy)
ts_n = input.bool(true, "Trailing-stop", tooltip = "Attiva o disattiva trailing-stop", group = "Trailing Stop Settings")
close_ema = input.bool(false, "Close EMA", tooltip = "Attiva o disattiva chiusura su EMA", group = "Trailing Stop Settings")
len1 = input.int(10, "EMA length", step=1, group = "Trailing Stop Settings")
ma1 = ta.ema(close, len1)
plot(ma1, title='EMA', color=color.new(color.yellow, 0))
if ts_n == true
strategy.exit("Trailing-Stop","Entry",loss= stop_tick, stop= stop_loss_price, limit= take_price, trail_points = stop_trl_price_cond, trail_offset = stop_trl_price_offset_cond, comment_loss="Stop-Loss!!",comment_profit ="CASH!!", comment_trailing = "TRL-Stop!!", alert_message = mess_sell)
else
strategy.exit("TP-SL", "Entry",loss= stop_tick, stop=stop_loss_price, limit= take_price, comment_loss= "Stop-loss!!!", comment_profit = "CASH!!", alert_message = mess_sell)
if close_ema == true and ta.crossunder(close,ma1)
strategy.close("Entry",comment = "Close" , alert_message = mess_sell)
|
Buy&Sell Bullish Engulfing - The Quant Science | https://www.tradingview.com/script/0moOi6G5-Buy-Sell-Bullish-Engulfing-The-Quant-Science/ | thequantscience | https://www.tradingview.com/u/thequantscience/ | 448 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © thequantscience
// ██████╗ ██╗ ██╗██╗ ██╗ ██╗███████╗██╗ ██╗ ███████╗███╗ ██╗ ██████╗ ██╗ ██╗██╗ ███████╗██╗███╗ ██╗ ██████╗
// ██╔══██╗██║ ██║██║ ██║ ██║██╔════╝██║ ██║ ██╔════╝████╗ ██║██╔════╝ ██║ ██║██║ ██╔════╝██║████╗ ██║██╔════╝
// ██████╔╝██║ ██║██║ ██║ ██║███████╗███████║ █████╗ ██╔██╗ ██║██║ ███╗██║ ██║██║ █████╗ ██║██╔██╗ ██║██║ ███╗
// ██╔══██╗██║ ██║██║ ██║ ██║╚════██║██╔══██║ ██╔══╝ ██║╚██╗██║██║ ██║██║ ██║██║ ██╔══╝ ██║██║╚██╗██║██║ ██║
// ██████╔╝╚██████╔╝███████╗███████╗██║███████║██║ ██║ ███████╗██║ ╚████║╚██████╔╝╚██████╔╝███████╗██║ ██║██║ ╚████║╚██████╔╝
// ╚═════╝ ╚═════╝ ╚══════╝╚══════╝╚═╝╚══════╝╚═╝ ╚═╝ ╚══════╝╚═╝ ╚═══╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝
//@version=5
strategy(
"Buy&Sell Bullish Engulfing - The Quant Science",
overlay = true,
default_qty_type = strategy.percent_of_equity,
default_qty_value = 100,
pyramiding = 1,
currency = currency.EUR,
initial_capital = 10000,
commission_type = strategy.commission.percent,
commission_value = 0.07,
process_orders_on_close = true,
close_entries_rule = "ANY"
)
startDate = input.int(title="D: ", defval=1, minval=1, maxval=31, inline = 'Start', group = "START DATE BACKTESTING", tooltip = "D is Day, M is Month, Y is Year.")
startMonth = input.int(title="M: ", defval=1, minval=1, maxval=12, inline = 'Start', group = "START DATE BACKTESTING", tooltip = "D is Day, M is Month, Y is Year.")
startYear = input.int(title="Y: ", defval=2022, minval=1800, maxval=2100, inline = 'Start', group = "START DATE BACKTESTING", tooltip = "D is Day, M is Month, Y is Year.")
endDate = input.int(title="D: ", defval=31, minval=1, maxval=31, inline = 'End', group = "END DATE BACKTESTING", tooltip = "D is Day, M is Month, Y is Year.")
endMonth = input.int(title="M: ", defval=12, minval=1, maxval=12, inline = 'End', group = "END DATE BACKTESTING", tooltip = "D is Day, M is Month, Y is Year.")
endYear = input.int(title="Y: ", defval=2023, minval=1800, maxval=2100, inline = 'End', group = "END DATE BACKTESTING", tooltip = "D is Day, M is Month, Y is Year.")
inDateRange = (time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0)) and (time < timestamp(syminfo.timezone, endYear, endMonth, endDate, 0, 0))
PROFIT = input.float(defval = 1, minval = 0, title = "Target profit (%): ", step = 0.10, group = "TAKE PROFIT-STOP LOSS")
STOPLOSS = input.float(defval = 1, minval = 0, title = "Stop Loss (%): ", step = 0.10, group = "TAKE PROFIT-STOP LOSS")
var float equity_trades = 0
equity_trades := strategy.initial_capital
var float equity = 0
var float qty_order = 0
t_ordersize = "Percentage size of each new order. With 'Reinvestment Profit' activate, the size will be calculate on the equity, with 'Reinvestment Profit' deactivate the size will be calculate on the initial capital."
orders_size = input.float(defval = 2, title = "Orders size (%): ", minval = 0.10, step = 0.10, maxval = 100, group = "RISK MANAGEMENT", tooltip = t_ordersize)
qty_order := ((equity_trades * orders_size) / 100 ) / close
C_DownTrend = true
C_UpTrend = true
var trendRule1 = "SMA50"
var trendRule2 = "SMA50, SMA200"
var trendRule = input.string(trendRule1, "Detect Trend Based On", options=[trendRule1, trendRule2, "No detection"], group = "BULLISH ENGULFING")
if trendRule == trendRule1
priceAvg = ta.sma(close, 50)
C_DownTrend := close < priceAvg
C_UpTrend := close > priceAvg
if trendRule == trendRule2
sma200 = ta.sma(close, 200)
sma50 = ta.sma(close, 50)
C_DownTrend := close < sma50 and sma50 < sma200
C_UpTrend := close > sma50 and sma50 > sma200
C_Len = 14
C_ShadowPercent = 5.0
C_ShadowEqualsPercent = 100.0
C_DojiBodyPercent = 5.0
C_Factor = 2.0
C_BodyHi = math.max(close, open)
C_BodyLo = math.min(close, open)
C_Body = C_BodyHi - C_BodyLo
C_BodyAvg = ta.ema(C_Body, C_Len)
C_SmallBody = C_Body < C_BodyAvg
C_LongBody = C_Body > C_BodyAvg
C_UpShadow = high - C_BodyHi
C_DnShadow = C_BodyLo - low
C_HasUpShadow = C_UpShadow > C_ShadowPercent / 100 * C_Body
C_HasDnShadow = C_DnShadow > C_ShadowPercent / 100 * C_Body
C_WhiteBody = open < close
C_BlackBody = open > close
C_Range = high-low
C_IsInsideBar = C_BodyHi[1] > C_BodyHi and C_BodyLo[1] < C_BodyLo
C_BodyMiddle = C_Body / 2 + C_BodyLo
C_ShadowEquals = C_UpShadow == C_DnShadow or (math.abs(C_UpShadow - C_DnShadow) / C_DnShadow * 100) < C_ShadowEqualsPercent and (math.abs(C_DnShadow - C_UpShadow) / C_UpShadow * 100) < C_ShadowEqualsPercent
C_IsDojiBody = C_Range > 0 and C_Body <= C_Range * C_DojiBodyPercent / 100
C_Doji = C_IsDojiBody and C_ShadowEquals
patternLabelPosLow = low - (ta.atr(30) * 0.6)
patternLabelPosHigh = high + (ta.atr(30) * 0.6)
label_color_bullish = input.color(color.rgb(43, 255, 0), title = "Label Color Bullish", group = "BULLISH ENGULFING")
C_EngulfingBullishNumberOfCandles = 2
C_EngulfingBullish = C_DownTrend and C_WhiteBody and C_LongBody and C_BlackBody[1] and C_SmallBody[1] and close >= open[1] and open <= close[1] and ( close > open[1] or open < close[1] )
if C_EngulfingBullish
var ttBullishEngulfing = "Engulfing\nAt the end of a given downward trend, there will most likely be a reversal pattern. To distinguish the first day, this candlestick pattern uses a small body, followed by a day where the candle body fully overtakes the body from the day before, and closes in the trend’s opposite direction. Although similar to the outside reversal chart pattern, it is not essential for this pattern to completely overtake the range (high to low), rather only the open and the close."
label.new(bar_index, patternLabelPosLow, text="BE", style=label.style_label_up, color = label_color_bullish, textcolor=color.white, tooltip = ttBullishEngulfing)
bgcolor(ta.highest(C_EngulfingBullish?1:0, C_EngulfingBullishNumberOfCandles)!=0 ? color.new(#21f321, 90) : na, offset=-(C_EngulfingBullishNumberOfCandles-1))
var float c = 0
var float o = 0
var float c_exit = 0
var float c_stopl = 0
if C_EngulfingBullish and strategy.opentrades==0 and inDateRange
c := strategy.equity
o := close
c_exit := c + (c * PROFIT / 100)
c_stopl := c - (c * STOPLOSS / 100)
strategy.entry(id = "LONG", direction = strategy.long, qty = qty_order, limit = o)
if ta.crossover(strategy.equity, c_exit)
strategy.exit(id = "CLOSE-LONG", from_entry = "LONG", limit = close)
if ta.crossunder(strategy.equity, c_stopl)
strategy.exit(id = "CLOSE-LONG", from_entry = "LONG", limit = close)
|
[EKIN] ATR Exit Strategy | https://www.tradingview.com/script/gMVECpa5/ | ekinbasarkomur | https://www.tradingview.com/u/ekinbasarkomur/ | 46 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ekinbasarkomur
//@version=5
strategy("[EKIN] ATR Exit Strategy", overlay=true, initial_capital = 1000, default_qty_value = 100, default_qty_type = strategy.percent_of_equity, calc_on_every_tick = true)
// Simple EMA tracking
fastEMA = ta.ema(close, 5)
slowEMA = ta.ema (close, 20)
atr = ta.atr(14)
// We define entry price for future reference
var float entry_price = na
// We define stop and take profit for future calculations
var float stop_price = na
var float take_profit_price = na
// We define atr limtim its here
var float atr_down = na
var float atr_up = na
var float atr_current = na
var float atr_ref = na
avg = (low + high) / 2
// Conditions
enterCondition = ta.crossover(fastEMA, slowEMA)
var bool tookProfit = false
timePeriod = time >= timestamp(syminfo.timezone, 2021, 12, 15, 0, 0)
InTrade = strategy.position_size > 0
// Go long if conditions are met
if (enterCondition and timePeriod and not InTrade)
// Calculate and update variables
entry_price := avg
atr_ref := atr
atr_div = int((avg - entry_price) / atr_ref)
atr_down := entry_price + (atr_ref * (atr_div - 1.5))
atr_up := entry_price + (atr_ref * (atr_div + 1))
atr_current := entry_price + (atr_ref * atr_div)
stop_price := (entry_price - (atr_ref * 1.5))
take_profit_price := (entry_price + (atr_ref * 3))
strategy.order("buy", strategy.long, qty = 2)
// Enter here if in position
if InTrade or tookProfit
stopCondition = avg < stop_price
takeProfitCondition = avg > take_profit_price
if avg < atr_down
stopCondition := true
// Move stop price and exit price if price for each atr price increase
if avg > atr_up
if tookProfit
atr_ref := atr
atr_div = int((avg - entry_price) / atr_ref)
atr_down := entry_price + (atr_ref * (atr_div - 1))
atr_up := entry_price + (atr_ref * (atr_div + 1))
atr_current := entry_price + (atr_ref * atr_div)
// Take half of the investment if current price is 3 atr higher than entry price
if (takeProfitCondition and timePeriod and InTrade and not tookProfit)
strategy.order("take_half_profit", strategy.short, qty = 1)
tookProfit := true
// Exit position if conditions are met and reset the variables
if (stopCondition and timePeriod and InTrade)
if tookProfit
strategy.order("exit", strategy.short, qty = 1)
else
strategy.order("stop_loss", strategy.short, qty = 2)
tookProfit := false
// Plot EMA's
plot(fastEMA, color = color.blue)
plot(slowEMA, color = color.yellow)
// Plot ATR Limit/Stop positions
profit_plot = plot(series = InTrade?atr_up:na, title = "profit", color = color.green, style=plot.style_linebr)
close_plot = plot(series = InTrade?atr_current:na, title = "close", color = color.white, style=plot.style_linebr)
stop_plot = plot(series = InTrade?atr_down:na, title = "stop_loss", color = color.red, style=plot.style_linebr)
fill(profit_plot, close_plot, color = color.new(color.green, 80))
fill(close_plot, stop_plot, color =color.new(color.red,80)) |
Crunchster's Normalised Trend Strategy | https://www.tradingview.com/script/KwYFiCcZ-Crunchster-s-Normalised-Trend-Strategy/ | Crunchster1 | https://www.tradingview.com/u/Crunchster1/ | 35 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Crunchster1
//@version=5
strategy(title="Crunchster's Normalised Trend Strategy", shorttitle="Normalised Trend Strategy", overlay=false, slippage=10, pyramiding=1, precision = 4, calc_on_order_fills = false, calc_on_every_tick = false, default_qty_value = 0.1, initial_capital = 1000, commission_value = 0.06, process_orders_on_close = true)
// Inputs and Parameters
src = input(close, 'Source', group='Strategy Settings')
length = input.int(title="Lookback period for price normalisation filter", defval=14, minval=2, group='Strategy Settings', tooltip='This sets the lookback period for the volatility adjustment of returns, which is used to transform the price series into the "real price"')
hlength = input.int(title="Lookback period for Hull Moving Average", defval=100, minval=2, group='Strategy Settings')
offset = input.int(title="HMA Offset", defval=0, minval=0, group='Strategy Settings')
long = input(true, 'Long', inline='08', group='Strategy Settings')
short = input(true, 'Short', inline='08', group='Strategy Settings', tooltip='Toggle long/short strategy on/off')
stopMultiple = input.float(1, 'Stop multiple', step=0.25, group='Risk Management Settings', tooltip='Multiple for ATR, setting hard stop loss from entry price')
lev = input.float(1, 'Max Leverage', step=0.5, group='Risk Management Settings', tooltip='Max leverage sets maximum allowable leverage of total capital (initial capital + any net profit), capping maximum volatility adjusted position size')
riskT = input.float(10, maxval=75, title='Annualised Volatility Target %', group='Risk Management Settings', tooltip='Specify annual risk target, used to determine volatility adjusted position size. Annualised daily volatility is referenced to this value and position size adjusted accordingly')
comp = input(false, 'Compounding', inline='09', group='Risk Management Settings')
Comppct = input.float(50, '%', step=5, inline='09', group='Risk Management Settings', tooltip='Toggle compounding of profit, and set % of profit to compound')
// Backtesting period
FromDay = input.int(defval=1, title='From Day', minval=1, maxval=31, inline='04', group='Backtest range')
FromMonth = input.int(defval=1, title='From Mon', minval=1, maxval=12, inline='04', group='Backtest range')
FromYear = input.int(defval=2018, title='From Yr', minval=1900, inline='04', group='Backtest range', tooltip='Set start of backtesting period')
ToDay = input.int(defval=1, title='To Day', minval=1, maxval=31, inline='05', group='Backtest range')
ToMonth = input.int(defval=1, title='To Mon', minval=1, maxval=12, inline='05', group='Backtest range')
ToYear = input.int(defval=9999, title='To Yr', minval=1900, inline='05', group='Backtest range', tooltip='Set end of backtesting period')
start = timestamp(FromYear, FromMonth, FromDay, 00, 00)
finish = timestamp(ToYear, ToMonth, ToDay, 23, 59)
window = time >= start and time <= finish
// Normalised returns calculation
nRet = (src - src[1]) / ta.stdev((src - src[1]), length)
nPrice = ta.cum(nRet)
//Hull Moving Average - using normalised price series
fHMA = ta.wma(2 * ta.wma(nPrice[offset], hlength / 2) - ta.wma(nPrice[offset], hlength), math.round(math.sqrt(hlength)))
//Risk Management formulae
tr = math.max(high - low, math.abs(high - close), math.abs(low - close)) //True range
stopL = ta.sma(tr, 14) //Average true range
stdev = ta.stdev(close-close[1], 14) //volatility of recent returns
maxcapital = strategy.initial_capital+strategy.netprofit //Maximum capital available to invest - initial capital net of profit
annvol = 100*math.sqrt(365)*stdev/close //converts recent volatility of returns into annualised volatility of returns - assumes daily timeframe
risk = 1.1
if comp
risk := (strategy.initial_capital+(Comppct*strategy.netprofit/100))//adjust investment capital to include compounding
else
risk := strategy.initial_capital
shares = (risk * (riskT/annvol)) / close //calculates volatility adjusted position size, dependent on user specified annualised risk target
if ((shares*close) > lev*maxcapital) //ensures position size does not exceed available capital multiplied by user specified maximum leverage
shares := lev*maxcapital/close
//To set the price at the entry point of trade
Posopen() =>
math.abs(strategy.position_size[1]) <= 0 and math.abs(strategy.position_size) > 0
var float openN = na
if Posopen()
openN := stopL
// Strategy Rules
if long
longCondition = ta.crossover(nPrice, fHMA) and window
exitlong = ta.crossunder(nPrice, fHMA)
if (longCondition)
strategy.entry('Go Long!', strategy.long, qty=shares)
if strategy.position_size > 0
strategy.exit('Stop Long', from_entry = 'Go Long!', stop=(strategy.opentrades.entry_price(0) - (openN * stopMultiple)))
if (exitlong)
strategy.close('Go Long!', immediately = true)
if short
shortCondition = ta.crossunder(nPrice, fHMA) and window
exitshort = ta.crossover(nPrice, fHMA)
if (shortCondition)
strategy.entry('Go Short!', strategy.short, qty=shares)
if strategy.position_size < 0
strategy.exit('Stop Short', from_entry = 'Go Short!', stop=(strategy.opentrades.entry_price(0) + (openN * stopMultiple)))
if (exitshort)
strategy.close('Go Short!', immediately = true)
// Visuals of trend and direction
plot(nPrice, title='Real Price', color=color.black)
MAColor = fHMA > fHMA[3] ? #00ff00 : #ff0000
MA1 = plot(fHMA, title='Hull MA', color=MAColor)
MA2 = plot(fHMA[3], title='Hull MA Offset', color=MAColor)
fill(MA1, MA2, title='Band Filler', color=MAColor) |
BTFD strategy [3min] | https://www.tradingview.com/script/qRwx46ZQ-BTFD-strategy-3min/ | wielkieef | https://www.tradingview.com/u/wielkieef/ | 388 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © wielkieef
//@version=5
strategy(title='BTFD strategy [3min]', overlay=true, pyramiding=5, initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, calc_on_order_fills=false, slippage=0, commission_type=strategy.commission.percent, commission_value=0.03)
// Volume
vol_sma_length = input.int(70, title='Volume lenght ', minval=1)
Volume_condt = volume > ta.sma(volume, vol_sma_length) * 2.5
// Rsi
rsi_lenght = input.int(20, title='RSI lenght', minval=0)
rsi_up = ta.rma(math.max(ta.change(close), 0), rsi_lenght)
rsi_down = ta.rma(-math.min(ta.change(close), 0), rsi_lenght)
rsi_value = rsi_down == 0 ? 100 : rsi_up == 0 ? 0 : 100 - 100 / (1 + rsi_up / rsi_down)
rsi_overs = rsi_value <= 30
rsi_overb = rsi_value >= 70
// logic
tp_1 = input.float(0.4," TP 1", minval=0.1, step=0.1)
tp_2 = input.float(0.6," TP 2", minval=0.2, step=0.1)
tp_3 = input.float(0.8," TP 3", minval=0.3, step=0.1)
tp_4 = input.float(1.0," TP 4", minval=0.4, step=0.1)
tp_5 = input.float(1.2," TP 5", minval=0.5, step=0.1)
q_1 = input.int(title=' % TP 1 Q ', defval=20, minval=1, step=10)
q_2 = input.int(title=' % TP 2 Q ', defval=40, minval=1, step=10)
q_3 = input.int(title=' % TP 3 Q ', defval=60, minval=1, step=10)
q_4 = input.int(title=' % TP 4 Q ', defval=80, minval=1, step=10)
q_5 = input.int(title=' % TP 5 Q ', defval=100, minval=1, step=10)
sl = input.float(5.0, '% Stop Loss', step=0.1)
long_cond = Volume_condt and rsi_overs
// this code is from author RafaelZioni, modified by wielkieef
per(procent) =>
strategy.position_size != 0 ? math.round(procent / 100 * strategy.position_avg_price / syminfo.mintick) : float(na)
// --------------------------------------------------------------------------------------------------------------------
if long_cond
strategy.entry('BUY', strategy.long)
strategy.exit('TP 1', qty_percent=q_1, profit=per(tp_1), loss=per(sl) )
strategy.exit('TP 2', qty_percent=q_2, profit=per(tp_2), loss=per(sl) )
strategy.exit('TP 3', qty_percent=q_3, profit=per(tp_3), loss=per(sl) )
strategy.exit('TP 4', qty_percent=q_4, profit=per(tp_4), loss=per(sl) )
strategy.exit('TP 5', qty_percent=q_5, profit=per(tp_5), loss=per(sl) )
// by wielkieef
|
SuperTrend Enhanced Pivot Reversal - Strategy [PresentTrading] | https://www.tradingview.com/script/wcegMOXj-SuperTrend-Enhanced-Pivot-Reversal-Strategy-PresentTrading/ | PresentTrading | https://www.tradingview.com/u/PresentTrading/ | 363 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © PresentTrading
//@version=5
strategy("SuperTrend Enhanced Pivot Reversal - Strategy [PresentTrading]", overlay=true, precision=3, default_qty_type=strategy.cash,
commission_value= 0.1, commission_type=strategy.commission.percent, slippage= 1,
currency=currency.USD, default_qty_type = strategy.percent_of_equity, default_qty_value = 10, initial_capital= 10000)
// Pivot Reversal parameters
leftBars = input(6)
rightBars = input(3)
swh = ta.pivothigh(leftBars, rightBars)
swl = ta.pivotlow(leftBars, rightBars)
// SuperTrend parameters
atrPeriod = input(5, "ATR Length")
factor = input.float(2.618, "Factor", step = 0.01)
[superTrend, direction] = ta.supertrend(factor, atrPeriod)
// Plot the SuperTrend
plot(superTrend, title="SuperTrend", color=color.blue)
// Trade Direction parameter
tradeDirection = input.string(title="Trade Direction", defval="Both", options=["Long", "Short", "Both"])
// Stop Loss Level (in %)
stopLossLevel = input(20, title="Stop Loss Level (%)")
// Convert the stop loss level to a price difference
stopLossPrice = stopLossLevel / 100
// Long entry
swh_cond = not na(swh)
hprice = 0.0
hprice := swh_cond ? swh : hprice[1]
le = false
le := swh_cond ? true : (le[1] and high > hprice ? false : le[1])
if (le and direction < 0 and (tradeDirection == "Long" or tradeDirection == "Both"))
strategy.entry("PivRevLE", strategy.long, comment="PivRevLE", stop=hprice + syminfo.mintick)
strategy.exit("Exit Long", "PivRevLE", stop = hprice * (1 - stopLossPrice))
// Short entry
swl_cond = not na(swl)
lprice = 0.0
lprice := swl_cond ? swl : lprice[1]
se = false
se := swl_cond ? true : (se[1] and low < lprice ? false : se[1])
if (se and direction > 0 and (tradeDirection == "Short" or tradeDirection == "Both"))
strategy.entry("PivRevSE", strategy.short, comment="PivRevSE", stop=lprice - syminfo.mintick)
strategy.exit("Exit Short", "PivRevSE", stop = lprice * (1 + stopLossPrice))
// Closing positions when the tradeDirection is one-sided or when SuperTrend direction changes
if ((tradeDirection == "Long" and se and direction < 0) or (tradeDirection == "Long" and direction < 0))
strategy.close("PivRevLE")
if ((tradeDirection == "Short" and le and direction > 0) or (tradeDirection == "Short" and direction > 0))
strategy.close("PivRevSE")
// Plot pivot highs and lows
plotshape(swh_cond, title="Pivot Highs", location=location.belowbar, color=color.green, style=shape.triangleup)
plotshape(swl_cond, title="Pivot Lows", location=location.abovebar, color=color.red, style=shape.triangledown)
// Closing positions when the tradeDirection is one-sided
if (tradeDirection == "Long" and se and direction < 0)
strategy.close("PivRevLE")
if (tradeDirection == "Short" and le and direction > 0)
strategy.close("PivRevSE")
|
TRAX Detrended Price Strategy | https://www.tradingview.com/script/B74emdHa-TRAX-Detrended-Price-Strategy/ | DraftVenture | https://www.tradingview.com/u/DraftVenture/ | 38 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © DraftVenture
//@version=5
strategy("TRAX DPO", overlay=true)
// TRAX Calculation
traxlength = input.int(12, title = "TRAX Length", minval=1)
trax = 10000 * ta.change(ta.vwma(ta.vwma(ta.vwma(math.log(close), traxlength), traxlength), traxlength))
// DPO Calculation
period_ = input.int(19, title="DPO Length", minval=1)
barsback = period_/2 + 1
ma = ta.sma(close, period_)
dpo = close[barsback] - ma
// MA Confirmation Calculation
len = input.int(3, minval=1, title="SMA Confirmation Length")
src = input(close, title="SMA Source")
offset = input.int(title="Offset", defval=0, minval=-500, maxval=500)
out = ta.sma(src, len)
plot(out, color=color.white, title="MA", offset=offset)
// DPO-TRAX Oscillator
dpotrax = dpo - trax
plot(dpotrax, color=color.blue, title="DPO-TRAX Oscillator", offset=offset)
// Crossover Conditions
longCondition = ta.crossover(dpo, trax) and trax < 0 and close > out
shortCondition = ta.crossunder(dpo, trax) and trax > 0 and close < out
// Strategy Logic
if (longCondition)
strategy.entry("Long", strategy.long)
if (shortCondition)
strategy.entry("Short", strategy.short)
// Highlight periods of zero-line crossover
bgcolor(longCondition ? color.new(color.green, 80) : na)
bgcolor(shortCondition ? color.new(color.red, 80) : na)
// Strategy by KP |
Vortex Cross w/MA Confirmation | https://www.tradingview.com/script/V3cRaSNH-Vortex-Cross-w-MA-Confirmation/ | DraftVenture | https://www.tradingview.com/u/DraftVenture/ | 31 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © DraftVenture
//@version=5
strategy("Vortex + Moving Average Strategy", overlay=true)
//Vortex settings
period_ = input.int(14, title="Vortex Length", minval=2)
VMP = math.sum( math.abs( high - low[1]), period_ )
VMM = math.sum( math.abs( low - high[1]), period_ )
STR = math.sum( ta.atr(1), period_ )
VIP = VMP / STR
VIM = VMM / STR
plot(VIP, title="VI +", color=color.white)
plot(VIM, title="VI -", color=color.white)
len = input.int(9, minval=1, title="MA Length")
src = input(close, title="Source")
offset = input.int(title="Offset", defval=0, minval=-500, maxval=500)
out = ta.sma(src, len)
plot(out, color=color.blue, title="MA", offset=offset)
ma(source, length, type) =>
switch type
"SMA" => ta.sma(source, length)
"EMA" => ta.ema(source, length)
"SMMA (RMA)" => ta.rma(source, length)
"WMA" => ta.wma(source, length)
"VWMA" => ta.vwma(source, length)
typeMA = input.string(title = "Method", defval = "SMA", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="Smoothing")
smoothingLength = input.int(title = "Length", defval = 5, minval = 1, maxval = 100, group="Smoothing")
smoothingLine = ma(out, smoothingLength, typeMA)
plot(smoothingLine, title="Smoothing Line", color=#f37f20, offset=offset, display=display.none)
// Determine long and short conditions
longCondition = ta.crossover(VIP, VIM) and close > smoothingLine
shortCondition = ta.crossunder(VIP, VIM) and close < smoothingLine
crossCondition = ta.crossunder(VIP, VIM) or ta.crossunder(VIM, VIP)
// Strategy entry and exit logic
if longCondition
strategy.entry("Long", strategy.long)
if shortCondition
strategy.entry("Short", strategy.short)
bgcolor(crossCondition ? color.new(color.white, 80) : na)
// Strategy by KP |
TrendGuard Flag Finder - Strategy [presentTrading] | https://www.tradingview.com/script/qDPWh3KO-TrendGuard-Flag-Finder-Strategy-presentTrading/ | PresentTrading | https://www.tradingview.com/u/PresentTrading/ | 174 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Amphibiantrading
//@version=5
strategy("TrendGuard Flag Finder - Strategy [presentTrading]", overlay = true, precision=3, default_qty_type=strategy.cash,
commission_value= 0.1, commission_type=strategy.commission.percent, slippage= 1,
currency=currency.USD, default_qty_type = strategy.percent_of_equity, default_qty_value = 10, initial_capital= 10000)
//inputs
//user controlled settings for the indicator, separated into 4 different groups
// Add a button to choose the trading direction
tradingDirection = input.string("Both","Trading Direction", options=["Long", "Short", "Both"])
// Supertrend parameters
SupertrendPeriod = input(10, "Supertrend Length",group ='SuperTrend Criteria')
SupertrendFactor = input.float(4.0, "Supertrend Factor", step = 0.01,group ='SuperTrend Criteria')
// Flag parameters
var g1 = 'Bull Flag Criteria'
max_depth = input.float(5, 'Max Flag Depth', step = .25, minval = 2.0, group = g1, tooltip = 'Maximum pullback allowed from flag high to flag low')
max_flag = input.int(7, 'Max Flag Length', group = g1, tooltip = 'The maximum number of bars the flag can last')
min_flag = input.int(3, 'Min Flag Length', group = g1, tooltip = 'The minimum number of bars required for the flag')
poleMin = input.float(3.0, 'Prior Uptrend Minimum', group = g1, tooltip = 'The minimum percentage gain required before a flag forms')
poleMaxLen = input.int(13, 'Max Flag Pole Length', minval = 1, group = g1, tooltip = 'The maximum number of bars the flagpole can be')
poleMinLen = input.int(7, 'Min Flag Pole Length', minval = 1, group = g1, tooltip = 'The minimum number of bars required for the flag pole')
var g2 = 'Bear Flag Criteria'
max_rally = input.float(5, 'Max Flag Rally', step = .25, minval = 2.0, group = g2, tooltip = 'Maximum rally allowed from flag low to flag low')
max_flagBear = input.int(7, 'Max Flag Length', group = g2, tooltip = 'The maximum number of bars the flag can last')
min_flagBear = input.int(3, 'Min Flag Length', group = g2, tooltip = 'The minimum number of bars required for the flag')
poleMinBear = input.float(3.0, 'Prior Downtrend Minimum', group = g2, tooltip = 'The minimum percentage loss required before a flag forms')
poleMaxLenBear = input.int(13, 'Max Flag Pole Length', minval = 1, group = g2, tooltip = 'The maximum number of bars the flagpole can be')
poleMinLenBear = input.int(7, 'Min Flag Pole Length', minval = 1, group = g2, tooltip = 'The minimum number of bars required for the flag pole')
var g3 = 'Bull Flag Display Options'
showF = input.bool(true, 'Show Bull Flags', group = g3)
showBO = input.bool(true,'Show Bull Flag Breakouts', group = g3)
lineColor = input.color(color.green, 'Bull Line Color', group = g3)
lineWidth = input.int(2, 'Bull Line Width', minval = 1, maxval = 5, group = g3)
var g4 = 'Bear Flag Display Options'
showBF = input.bool(true, 'Show Bear Flags', group = g4)
showBD = input.bool(true,'Show Bear Flag Breakdowns', group = g4)
lineColorBear = input.color(color.red, 'Bear Flag Line Color', group = g4)
lineWidthBear = input.int(2, 'Bear Flag Line Width', minval = 1, maxval = 5, group = g4)
//variables
//declare starting variables used for identfying flags
var baseHigh = high, var startIndex = 0, var flagLength = 0, var baseLow = low
var lowIndex = 0, var flagBool = false, var poleLow = 0.0, var poleLowIndex = 0
var line flagHLine = na, var line flagLLine = na, var line flagPLine = na
// bear flag variables
var flagLowBear = high, var startIndexBear = 0, var flagLengthBear = 0, var flagHigh = low
var highIndex = 0, var flagBoolBear = false, var poleHigh = 0.0, var polehighIndex = 0
var line flagBearHLine = na, var line flagBearLLine = na, var line flagBearPLine = na
//find bull flag highs
// check to see if the current bars price is higher than the previous base high or na and then sets the variables needed for flag detection
if high > baseHigh or na(baseHigh)
baseHigh := high
startIndex := bar_index
flagLength := 0
baseLow := low
lowIndex := bar_index
// check to see if the low of the current bar is lower than the base low, if it is set the base low to the low
if high <= baseHigh and low < baseLow
baseLow := low
lowIndex := bar_index
// moves the base low from the base high bar_index to prevent the high and low being the same bar
if high <= baseHigh and lowIndex == startIndex
baseLow := low
lowIndex := bar_index
//find bear flag lows
// check to see if the current bars price is lower than the previous flag low or na and then sets the variables needed for flag detection
if low < flagLowBear or na(flagLowBear)
flagLowBear := low
startIndexBear := bar_index
flagLengthBear := 0
flagHigh := high
highIndex := bar_index
// check to see if the high of the current bar is higher than the flag high, if it is set the flag high to the high
if low >= flagLowBear and high > flagHigh
flagHigh := high
highIndex := bar_index
// moves the flag high from the flag low bar_index to prevent the high and low being the same bar
if low >= flagLowBear and highIndex == startIndexBear
flagHigh := high
highIndex := bar_index
//calulations bullish
findDepth = math.abs(((baseLow / baseHigh) - 1) * 100) //calculate the depth of the flag
poleDepth = ((baseHigh / poleLow)- 1) * 100 // calculate the low of the flag pole to the base high
lower_close = close < close[1] // defines a lower close
//calculations bearish
findRally = math.abs(((flagHigh / flagLowBear) - 1) * 100) //calculate the rally of the flag
poleDepthBear = ((flagLowBear / poleHigh)- 1) * 100 // calculate the high of the flag pole to the low high
higher_close = close > close[1] // defines a higher close
//start the counters
// begins starting bars once a high is less than the flag high
if high < baseHigh and findDepth <= max_depth or (high == baseHigh and lower_close)
flagLength += 1
else
flagLength := 0
// begins starting bars once a low is higher than the flag low
if low > flagLowBear and findRally <= max_rally or (low == flagLowBear and higher_close)
flagLengthBear += 1
else
flagLengthBear := 0
// check for prior uptrend / downtrend to meet requirements
// loops through all the bars from the minimum pole length to the maximum pole length to check if the prior uptrend requirements are met and sets the variables to their new values
if high == baseHigh
for i = poleMinLen to poleMaxLen
if ((high / low[i]) - 1) * 100 >= poleMin
flagBool := true
poleLow := low[i]
poleLowIndex := bar_index[i]
break
// loops through all the bars from the minimum pole length to the maximum pole length to check if the prior downtrend requirements are met and sets the variables to their new values
if low == flagLowBear
for i = poleMinLenBear to poleMaxLenBear
if math.abs(((low / high[i]) - 1) * 100) >= poleMinBear
flagBoolBear := true
poleHigh := high[i]
polehighIndex := bar_index[i]
break
// reset variables if criteria for a flag is broken
// if the depth of the bull flag is greater than the maximum depth limit or the flag lasts longer than the maximum length everything is reset to beging looking for a new flag
if findDepth >= max_depth or flagLength > max_flag
flagBool := false
flagLength := 0
baseHigh := na
startIndex := na
lowIndex := na
baseLow := na
// if the rally of the bear flag is greater than the maximum rally limit or the flag lasts longer than the maximum length everything is reset to beging looking for a new flag
if findRally >= max_rally or flagLengthBear > max_flagBear
flagBoolBear := false
flagLengthBear := 0
flagLowBear := na
startIndexBear := na
highIndex := na
flagHigh := na
// reset the variables and begin looking for a new bull flag if price continues higher before the minimum flag length requirement is met
if high > baseHigh[1] and flagLength < min_flag
baseHigh := high
flagLength := 0
startIndex := bar_index
lowIndex := bar_index
baseLow := low
// reset the variables and begin looking for a new bear flag if price continues lower before the minimum bear flag length requirement is met
if low < flagLowBear[1] and flagLengthBear < min_flagBear
flagLowBear := low
flagLengthBear := 0
startIndexBear := bar_index
highIndex := bar_index
flagHigh := high
//define the flags
// if all requirements are met a bull flag is true, flagBool is true, flag length is less than maximum set length and more than miminum required. The prior run up also meets the requirements for length and price
flag = flagBool == true and flagLength < max_flag and findDepth < max_depth and flagLength >= min_flag and startIndex - poleLowIndex <= poleMaxLen
// if all requirements are met a bear flag is true, flagBoolBear is true, flag length is less than maximum set length and more than miminum required. The prior downtrend also meets the requirements for length and price
bearFlag = flagBoolBear == true and flagLengthBear < max_flagBear and findRally < max_rally and flagLengthBear >= min_flagBear and startIndexBear - polehighIndex <= poleMaxLen
//define flags, breakouts, breadowns
// a breakout is defined as the high going above the flag high and the length of the flag is greater than the minimum requirement. The flag boolean must also be true
breakout = high > baseHigh[1] and flagLength >= min_flag and flagBool == true
//a breakdown is defined as the depth of the flag being larger than user set parameter or the length of the flag exceeded the maximum flag length
breakdown = findDepth >= max_depth or flagLength > max_flag
// a separate variable to have breakouts only plot once using a plotshape
plotBO = flag[1] and high > baseHigh[1] and flagLength[1] >= min_flag and flagBool == true
// a bear flag breakout is defined as the low going below the flag low and the length of the flag is greater than the minimum requirement. The flag boolean must also be true
breakoutBear = low < flagLowBear[1] and flagLengthBear >= min_flagBear and flagBoolBear == true
//a breakdown is defined as the rally of the flag being larger than user set parameter or the length of the flag exceeded the maximum flag length
breakdownBear = findRally >= max_rally or flagLengthBear > max_flagBear
// a separate variable to have breakouts only plot once using a plotshape
plotBD = bearFlag[1] and low < flagLowBear[1] and flagLengthBear[1] >= min_flagBear and flagBoolBear == true
// if a bul flag is detected and the user has bull flags selected from the settings menu draw it on the chart
if flag and showF
//if a flag was detected on the previous bar, delete those lines and allow for new lines to be drawn
if flag[1]
line.delete(flagHLine[1]), line.delete(flagLLine[1]), line.delete(flagPLine[1])
//draw new lines
flagHLine := line.new(startIndex, baseHigh, bar_index, baseHigh, color=lineColor, width = lineWidth)
flagLLine := line.new(startIndex, baseLow, bar_index, baseLow, color=lineColor, width = lineWidth)
flagPLine := line.new(poleLowIndex +1, poleLow, startIndex , baseLow, color=lineColor, width = lineWidth)
// if a bear flag is detected and the user has bear flags selected from the settings menu draw it on the chart
if bearFlag and showBF
//if a bear flag was detected on the previous bar, delete those lines and allow for new lines to be drawn
if bearFlag[1]
line.delete(flagBearHLine[1]), line.delete(flagBearLLine[1]), line.delete(flagBearPLine[1])
//draw new lines
flagBearHLine := line.new(startIndexBear, flagHigh, bar_index, flagHigh, color=lineColorBear, width = lineWidthBear)
flagBearLLine := line.new(startIndexBear, flagLowBear, bar_index, flagLowBear, color=lineColorBear, width = lineWidthBear)
flagBearPLine := line.new(polehighIndex + 1, poleHigh, startIndexBear , flagHigh, color=lineColorBear, width = lineWidthBear)
//reset variables if a breakout occurs
if breakout // bull flag - high gets above flag high
flagLength := 0
baseHigh := high
startIndex := bar_index
lowIndex := bar_index
baseLow := low
if breakoutBear // bear flag - low gets below flag low
flagLengthBear := 0
flagLowBear := low
startIndexBear := bar_index
highIndex := bar_index
flagHigh := high
//reset the variables and highs from a failed bull flag. This allows stocks below previous highs to find new flags
highest = ta.highest(high, 10) // built in variable that finds the highest high lookingback the past 10 bars
if breakdown or flagLength == max_flag
flagBool := false
baseHigh := highest
startIndex := bar_index
lowIndex := bar_index
baseLow := low
//reset the variables and lows from a failed bear flag. This allows stocks above previous lows to find new flags
lowest = ta.lowest(low, 10) // built in variable that finds the lowest low lookingback the past 10 bars
if breakdownBear or flagLengthBear == max_flagBear
flagBoolBear := false
flagLowBear := lowest
startIndexBear := bar_index
highIndex := bar_index
flagHigh := high
// if a flag breakdowns remove the lines from the chart
if (breakdown and flag[1])
line.delete(flagHLine)
line.delete(flagLLine)
line.delete(flagPLine)
if (breakdownBear and bearFlag[1])
line.delete(flagBearHLine)
line.delete(flagBearLLine)
line.delete(flagBearPLine)
//plot breakouts
// use a plotshape to check if there is a breakout and the show breakout option is selected. If both requirements are met plot a shape at the breakout bar
plotshape(plotBO and showBO and showF, 'Breakout', shape.triangleup, location.belowbar, color.green, display = display.pane)
// use a plotshape to check if there is a breakout and the show breakout option is selected. If both requirements are met plot a shape at the breakout bar
plotshape(plotBD and showBD and showBF, 'Breakout', shape.triangledown, location.abovebar, color.red, display = display.pane)
// Define entry and exit conditions based on the indicator
bullishEntryFlag = plotBO and showBO and showF
bearishEntryFlag = plotBD and showBD and showBF
// Calculate Supertrend
[supertrend, direction] = ta.supertrend(SupertrendFactor, SupertrendPeriod)
bodyMiddle = plot((open + close) / 2, display=display.none)
upTrend = plot(direction < 0 ? supertrend : na, "Up Trend", color = color.green, style=plot.style_linebr)
downTrend = plot(direction < 0? na : supertrend, "Down Trend", color = color.red, style=plot.style_linebr)
fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps=false)
fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps=false)
// Define entry and exit conditions based on the indicator
bullishEntryST = direction < 0
bearishEntryST = direction > 0
// Entry
bullishEntry = bullishEntryFlag and bullishEntryST
bearishEntry = bearishEntryFlag and bearishEntryST
// Modify entry and exit conditions based on the selected trading direction
if (bullishEntry and (tradingDirection == "Long" or tradingDirection == "Both"))
strategy.entry("Buy", strategy.long)
strategy.exit("Sell", "Buy", stop=supertrend)
if (bearishEntry and (tradingDirection == "Short" or tradingDirection == "Both"))
strategy.entry("Sell", strategy.short)
strategy.exit("Cover", "Sell", stop=supertrend)
// Exit conditions
if (strategy.position_size > 0 and bearishEntry and (tradingDirection == "Long" or tradingDirection == "Both")) // If in a long position and bearish entry condition is met
strategy.close("Buy")
if (strategy.position_size < 0 and bullishEntry and (tradingDirection == "Short" or tradingDirection == "Both")) // If in a short position and bullish entry condition is met
strategy.close("Sell") |
Long-Only Opening Range Breakout (ORB) with Pivot Points | https://www.tradingview.com/script/6kDE9bLA-Long-Only-Opening-Range-Breakout-ORB-with-Pivot-Points/ | duronic12 | https://www.tradingview.com/u/duronic12/ | 151 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © duronic12
//@version=5
strategy(title='Long-Only Opening Range Breakout (ORB) with Pivot Points', overlay=true, default_qty_value=100, initial_capital=10000, default_qty_type=strategy.percent_of_equity, pyramiding=0, process_orders_on_close=true)
// Time Sessions
sess = input.session('0930-0945', title='Opening Session') + ':1234567'
t = time(timeframe.period, sess)
time_cond = na(t) ? 0 : 1
h = 0.0
l = 0.0
h := time_cond and not time_cond[1] ? high : time_cond and high > h[1] ? high : h[1]
// Pivots
is_newbar(res) =>
t = time(res)
not na(t) and (na(t[1]) or t > t[1])
prevCloseHTF = request.security(syminfo.tickerid, 'D', close[1], lookahead=barmerge.lookahead_on)
prevOpenHTF = request.security(syminfo.tickerid, 'D', open[1], lookahead=barmerge.lookahead_on)
prevHighHTF = request.security(syminfo.tickerid, 'D', high[1], lookahead=barmerge.lookahead_on)
prevLowHTF = request.security(syminfo.tickerid, 'D', low[1], lookahead=barmerge.lookahead_on)
pivot = (prevHighHTF + prevLowHTF + prevCloseHTF) / 3
range_1 = prevHighHTF - prevLowHTF
// Pivot Points Calculations
r1 = pivot + pivot - prevLowHTF
r2 = pivot + 1 * range_1
r3 = pivot * 2 + prevHighHTF - 2 * prevLowHTF
r4 = pivot * 3 + prevHighHTF - 3 * prevLowHTF
r5 = pivot * 4 + prevHighHTF - 4 * prevLowHTF
r0_5 = h + math.abs(r1 - h) / 2
r1_5 = r1 + math.abs(r1 - r2) / 2
r2_5 = r2 + math.abs(r2 - r3) / 2
r3_5 = r3 + math.abs(r3 - r4) / 2
r4_5 = r4 + math.abs(r4 - r5) / 2
newday = is_newbar('D')
plot(newday ? na : r1, style=plot.style_linebr, title='R1')
plot(newday ? na : r2, style=plot.style_linebr, title='R2')
plot(newday ? na : r3, style=plot.style_linebr, title='R3')
plot(newday ? na : r4, style=plot.style_linebr, title='R4')
plot(newday ? na : r5, style=plot.style_linebr, title='R5')
plot(newday ? na : r0_5, style=plot.style_linebr, color=color.new(color.gray, 0), title='R0.5')
plot(newday ? na : r1_5, style=plot.style_linebr, color=color.new(color.gray, 0), title='R1.5')
plot(newday ? na : r2_5, style=plot.style_linebr, color=color.new(color.gray, 0), title='R2.5')
plot(newday ? na : r3_5, style=plot.style_linebr, color=color.new(color.gray, 0), title='R3.5')
plot(newday ? na : r4_5, style=plot.style_linebr, color=color.new(color.gray, 0), title='R4.5')
// Opening Range
plot(not time_cond ? h : na, style=plot.style_linebr, color=color.new(color.green, 0), linewidth=2)
// Entry Conditions
long = open < h and high > h and r1 > h
max_trades = input(1, title='Max Trades per Day')
trades_counter = 0
// Position Management Tools
pos = 0.0
pos := long and (pos[1] != 1 or na(pos[1])) and trades_counter[1] < max_trades ? 1 : pos[1]
longCond = long and (pos[1] != 1 or na(pos[1])) and trades_counter[1] < max_trades
trades_counter := time_cond ? 0 : longCond ? trades_counter[1] + 1 : trades_counter[1]
// Stop Loss
initial_sl_sw = input.string('Percentage', title='Initial SL Type:', options=['Percentage', 'Previous Low'])
i_sl = input.float(3.0, title='Stop Loss %', minval=0)
sl = i_sl > 0 ? i_sl / 100 : 99999
long_entry = ta.valuewhen(longCond, close, 0)
ll = ta.valuewhen(longCond, low[1], 0)
sl_long0 = initial_sl_sw == 'Percentage' ? long_entry * (1 - sl) : ll
trail_long = 0.0
trail_long := longCond ? 0 : high > r5 and r4 > trail_long[1] ? r4 : high > r4_5 and r3_5 > trail_long[1] ? r3_5 : high > r4 and r3 > trail_long[1] ? r3 : high > r3_5 and r2_5 > trail_long[1] ? r2_5 : high > r3 and r2 > trail_long[1] ? r2 : high > r2_5 and r1_5 > trail_long[1] ? r1_5 : high > r2 and r1 > trail_long[1] ? r1 : high > r1_5 and r0_5 > trail_long[1] ? r0_5 : high > r0_5 and h > trail_long[1] ? h : trail_long[1]
sl_long = pos == 0 ? 0 : math.max(sl_long0, trail_long)
plot(sl_long > 0 and pos == 1 and not newday ? sl_long : na, style=plot.style_linebr, color=color.new(#FF0000, 0))
// Position Adjustment
long_sl = low < sl_long[1] and pos[1] == 1
if long_sl or newday
pos := 0
pos
// Backtester
i_startTime = input.time(defval=timestamp('01 Sep 2000 13:30 +0000'), title='Backtesting Start Time')
i_endTime = input.time(defval=timestamp('30 Sep 2099 19:30 +0000'), title='Backtesting End Time')
timeCond = time > i_startTime and time < i_endTime
// Entries and Exits
strategy.entry('long', strategy.long, when=open < h and trades_counter[1] < max_trades and timeCond, alert_message='BUY ALERT', stop=h)
strategy.cancel('long', when=longCond[1])
strategy.exit('SL/TP', from_entry='long', stop=sl_long, alert_message='SELL ALERT')
strategy.close_all(when=newday, comment='DayEnd', alert_message='EndofDay SELL ALERT')
|
Risk Management and Positionsize - MACD example | https://www.tradingview.com/script/HAp1ed0F-Risk-Management-and-Positionsize-MACD-example/ | Harrocop | https://www.tradingview.com/u/Harrocop/ | 159 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Harrocop
////////////////////////////////////////////////////////////////////////////////////////
// This is a basis position sizing tool to play around with marginfactor or quantity Contracts.
// It gives traders the possibility to quickly adjust settings to test backtesting outcomes.
// The Strategy comes with the following.
// - MACD Signalline based on Higher Time Frame Settings.
// - Filter based on Moving Average Type on higher time frame settings.
// - Dynamic smoothing calculations makes a sleek line, taking the ratio of minutes of the higher time frame to the current time frame.
// - Exit strategy is simplified using MACD crossover / crossunder.
// - no fixed stoploss.
// - The below strategy is for educational purposes about how to use position sizing.
////////////////////////////////////////////////////////////////////////////////////////
//@version=5
strategy(title = "Risk Management and Positionsize - MACD example", shorttitle = "Risk Management", overlay=false,
pyramiding=0, initial_capital = 10000,
calc_on_order_fills=false,
slippage = 0,
commission_type=strategy.commission.percent, commission_value=0.03)
//////////////////////////////////////////////////////
////////// Risk Management ////////////
//////////////////////////////////////////////////////
RISKM = "Risk Management"
InitialBalance = input.float(defval = 10000, title = "Initial Balance", minval = 1, maxval = 1000000, step = 1000, tooltip = "starting capital", group = RISKM)
LeverageEquity = input.bool(defval = true, title = "qty based on equity %", tooltip = "true turns on MarginFactor based on equity, false gives fixed qty for positionsize", group = RISKM)
MarginFactor = input.float(-0.5, minval = - 0.9, maxval = 100, step = 0.1, tooltip = "Margin Factor, meaning that 0.5 will add 50% extra capital to determine ordersize quantity, 0.0 means 100% of equity is used to decide quantity of instrument", inline = "qty", group = RISKM)
QtyNr = input.float(defval = 3.5, title = "Quantity Contracts", minval = 0, maxval = 1000000, step = 0.01, tooltip = "Margin Factor, meaning that 0.5 will add 50% extra capital to determine ordersize quantity, 0.0 means 100% of equity is used to decide quantity of instrument", inline = "qty", group = RISKM)
EquityCurrent = InitialBalance + strategy.netprofit[1]
QtyEquity = EquityCurrent * (1 + MarginFactor) / close[1]
QtyTrade = LeverageEquity ? QtyEquity : QtyNr
//////////////////////////////////////////////////////
////////// Input MACD HTF ////////////
//////////////////////////////////////////////////////
MACD_settings = "Higher Time Frame MACD Settings"
MA_Type = input.string(defval="EMA" , options=["EMA","DEMA","TEMA","SMA","WMA", "HMA"], title="MA type", inline = "1", group = MACD_settings)
TimeFrame_MACD = input.timeframe(title='Higher Time Frame', defval='30', inline = "1", group = MACD_settings)
fastlength = input.int(11, title="Fast MA Length", minval=1, inline = "2", group = MACD_settings)
slowlength = input.int(26, title="Slow MA Length", minval=1, inline = "2", group = MACD_settings)
signallength = input.int(9, title="Length Signal MA", minval=1, inline = "3", group = MACD_settings)
Plot_Signal = input.bool(true, title = "Plot Signal?", inline = "3", group = MACD_settings)
ma(type, src, length) =>
float result = 0
if type == 'TMA' // Triangular Moving Average
result := ta.sma(ta.sma(src, math.ceil(length / 2)), math.floor(length / 2) + 1)
result
if type == 'LSMA' // Least Squares Moving Average
result := ta.linreg(src, length, 0)
result
if type == 'SMA' // Simple Moving Average
result := ta.sma(src, length)
result
if type == 'EMA' // Exponential Moving Average
result := ta.ema(src, length)
result
if type == 'DEMA' // Double Exponential Moving Average
e = ta.ema(src, length)
result := 2 * e - ta.ema(e, length)
result
if type == 'TEMA' // Triple Exponentiale
e = ta.ema(src, length)
result := 3 * (e - ta.ema(e, length)) + ta.ema(ta.ema(e, length), length)
result
if type == 'WMA' // Weighted Moving Average
result := ta.wma(src, length)
result
if type == 'HMA' // Hull Moving Average
result := ta.wma(2 * ta.wma(src, length / 2) - ta.wma(src, length), math.round(math.sqrt(length)))
result
result
// MACD function for calculation higher timeframe
macd_function() =>
fast_ma = ma(MA_Type, close, fastlength)
slow_ma = ma(MA_Type, close, slowlength)
macd = fast_ma - slow_ma
macd
signal_function() =>
fast_ma = ma(MA_Type, close, fastlength)
slow_ma = ma(MA_Type, close, slowlength)
macd = fast_ma - slow_ma
signal = ma(MA_Type, macd, signallength)
signal
hist_function() =>
fast_ma = ma(MA_Type, close, fastlength)
slow_ma = ma(MA_Type, close, slowlength)
macd = fast_ma - slow_ma
signal = ma(MA_Type, macd, signallength)
hist = macd - signal
hist
MACD_Value_HTF = request.security(syminfo.ticker, TimeFrame_MACD, macd_function())
SIGNAL_Value_HTF = request.security(syminfo.ticker, TimeFrame_MACD, signal_function())
HIST_Value_HTF = MACD_Value_HTF - SIGNAL_Value_HTF
// Get minutes for current and higher timeframes
// Function to convert a timeframe string to its equivalent in minutes
timeframeToMinutes(tf) =>
multiplier = 1
if (str.endswith(tf, "D"))
multiplier := 1440
else if (str.endswith(tf, "W"))
multiplier := 10080
else if (str.endswith(tf, "M"))
multiplier := 43200
else if (str.endswith(tf, "H"))
multiplier := int(str.tonumber(str.replace(tf, "H", "")))
else
multiplier := int(str.tonumber(str.replace(tf, "m", "")))
multiplier
// Get minutes for current and higher timeframes
currentTFMinutes = timeframeToMinutes(timeframe.period)
higherTFMinutes = timeframeToMinutes(TimeFrame_MACD)
// Calculate the smoothing factor
dynamicSmoothing = math.round(higherTFMinutes / currentTFMinutes)
MACD_Value_HTF_Smooth = ta.sma(MACD_Value_HTF, dynamicSmoothing)
SIGNAL_Value_HTF_Smooth = ta.sma(SIGNAL_Value_HTF, dynamicSmoothing)
HIST_Value_HTF_Smooth = ta.sma(HIST_Value_HTF, dynamicSmoothing)
// Determin Long and Short Conditions
LongCondition = ta.crossover(MACD_Value_HTF_Smooth, SIGNAL_Value_HTF_Smooth) and MACD_Value_HTF_Smooth < 0
ShortCondition = ta.crossunder(MACD_Value_HTF_Smooth, SIGNAL_Value_HTF_Smooth) and MACD_Value_HTF_Smooth > 0
//////////////////////////////////////////////////////
////////// Filter Trend ////////////
//////////////////////////////////////////////////////
TREND = "Higher Time Frame Trend"
TimeFrame_Trend = input.timeframe(title='Higher Time Frame', defval='1D', inline = "Trend1", group = TREND)
length = input.int(55, title="Length MA", minval=1, tooltip = "Number of bars used to measure trend on higher timeframe chart", inline = "Trend1", group = TREND)
MA_Type_trend = input.string(defval="EMA" , options=["EMA","DEMA","TEMA","SMA","WMA", "HMA", "McGinley"], title="MA type for HTF trend", inline = "Trend2", group = TREND)
ma_trend(type, src, length) =>
float result = 0
if type == 'TMA' // Triangular Moving Average
result := ta.sma(ta.sma(src, math.ceil(length / 2)), math.floor(length / 2) + 1)
result
if type == 'LSMA' // Least Squares Moving Average
result := ta.linreg(src, length, 0)
result
if type == 'SMA' // Simple Moving Average
result := ta.sma(src, length)
result
if type == 'EMA' // Exponential Moving Average
result := ta.ema(src, length)
result
if type == 'DEMA' // Double Exponential Moving Average
e = ta.ema(src, length)
result := 2 * e - ta.ema(e, length)
result
if type == 'TEMA' // Triple Exponentiale
e = ta.ema(src, length)
result := 3 * (e - ta.ema(e, length)) + ta.ema(ta.ema(e, length), length)
result
if type == 'WMA' // Weighted Moving Average
result := ta.wma(src, length)
result
if type == 'HMA' // Hull Moving Average
result := ta.wma(2 * ta.wma(src, length / 2) - ta.wma(src, length), math.round(math.sqrt(length)))
result
if type == 'McGinley' // McGinley Dynamic Moving Average
mg = 0.0
mg := na(mg[1]) ? ta.ema(src, length) : mg[1] + (src - mg[1]) / (length * math.pow(src / mg[1], 4))
result := mg
result
result
// Moving Average
MAtrend = ma_trend(MA_Type_trend, close, length)
MA_Value_HTF = request.security(syminfo.ticker, TimeFrame_Trend, MAtrend)
// Get minutes for current and higher timeframes
higherTFMinutes_trend = timeframeToMinutes(TimeFrame_Trend)
// Calculate the smoothing factor
dynamicSmoothing_trend = math.round(higherTFMinutes_trend / currentTFMinutes)
MA_Value_Smooth = ta.sma(MA_Value_HTF, dynamicSmoothing_trend)
// Trend HTF
UP = MA_Value_Smooth > MA_Value_Smooth[1] // Use "UP" Function to use as filter in combination with other indicators
DOWN = MA_Value_Smooth < MA_Value_Smooth[1] // Use "Down" Function to use as filter in combination with other indicators
/////////////////////////////////////////////////
/////////// Strategy ////////////////
/////////////////////////////////////////////////
if LongCondition and UP == true
strategy.entry("Long", strategy.long, qty = QtyTrade)
strategy.close_all(when = strategy.position_size > 0 and ta.crossunder(MACD_Value_HTF_Smooth, SIGNAL_Value_HTF_Smooth))
if ShortCondition and DOWN == true
strategy.entry("Short", strategy.short, qty = QtyTrade)
strategy.close_all(when = strategy.position_size < 0 and ta.crossover(MACD_Value_HTF_Smooth, SIGNAL_Value_HTF_Smooth))
/////////////////////////////////////////////////
/////////// Plots ////////////////
/////////////////////////////////////////////////
hline(0, "Zero Line", color=color.new(#787B86, 50))
plot(HIST_Value_HTF_Smooth, title="Histogram", style=plot.style_columns, color=(HIST_Value_HTF_Smooth>=0 ? (HIST_Value_HTF_Smooth[1] < HIST_Value_HTF_Smooth ? color.rgb(0, 255, 8) : color.rgb(0, 100, 5)) : (HIST_Value_HTF_Smooth[1] < HIST_Value_HTF_Smooth ? color.rgb(150, 35, 35) : color.rgb(255, 0, 0))))
plot(SIGNAL_Value_HTF_Smooth, title="Signal", color=color.orange)
plot(MACD_Value_HTF_Smooth, title="MACD", color=color.blue)
plot(Plot_Signal ? LongCondition ? MACD_Value_HTF_Smooth : na : na, "Long Condition", style = plot.style_circles, color = color.rgb(0, 255, 8), linewidth = 4)
plot(Plot_Signal ? ShortCondition ? MACD_Value_HTF_Smooth : na : na, "Short Condition", style = plot.style_circles, color = color.rgb(255, 0, 0), linewidth = 4)
plotshape(UP == true, "trend up", style = shape.square, location = location.bottom, color = color.green, size = size.tiny)
plotshape(DOWN == true, "trend down", style = shape.square, location = location.bottom, color = color.red, size = size.tiny)
|
Dual-Supertrend with MACD - Strategy [presentTrading] | https://www.tradingview.com/script/zFKRj4Gi-Dual-Supertrend-with-MACD-Strategy-presentTrading/ | PresentTrading | https://www.tradingview.com/u/PresentTrading/ | 255 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © PresentTrading
//@version=5
// Define the strategy settings
strategy("Dual-Supertrend with MACD - Strategy [presentTrading]", overlay=true, precision=3, default_qty_type=strategy.cash,
commission_value= 0.1, commission_type=strategy.commission.percent, slippage= 1,
currency=currency.USD, default_qty_type = strategy.percent_of_equity, default_qty_value = 10, initial_capital= 10000)
// Trading Direction Dropdown
tradeDirection = input.string("both", "Trading Direction", options=["long", "short", "both"])
// MACD Inputs
fast_length = input(12, "Fast Length")
slow_length = input(26, "Slow Length")
signal_length = input(9, "Signal Smoothing")
sma_source = input.string("EMA", "Oscillator MA Type", options=["SMA", "EMA"])
sma_signal = input.string("EMA", "Signal Line MA Type", options=["SMA", "EMA"])
// MACD Calculation
fast_ma = sma_source == "SMA" ? ta.sma(close, fast_length) : ta.ema(close, fast_length)
slow_ma = sma_source == "SMA" ? ta.sma(close, slow_length) : ta.ema(close, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)
hist = macd - signal
// Input Parameters for Supertrend 1
atrPeriod1 = input(10, "ATR Length for Supertrend 1")
factor1 = input.float(3.0, "Factor for Supertrend 1", step=0.01)
// Supertrend Calculation for 1
[supertrend1, direction1] = ta.supertrend(factor1, atrPeriod1)
// Input Parameters for Supertrend 2
atrPeriod2 = input(20, "ATR Length for Supertrend 2")
factor2 = input.float(5.0, "Factor for Supertrend 2", step=0.01)
// Supertrend Calculation for 2
[supertrend2, direction2] = ta.supertrend(factor2, atrPeriod2)
// Combined Conditions
isBullish = direction1 < 0 and direction2 < 0 and hist > 0
isBearish = direction1 > 0 and direction2 > 0 and hist < 0
exitLong = direction1 > 0 or direction2 > 0 or hist < 0
exitShort = direction1 < 0 or direction2 < 0 or hist > 0
// Strategy Entry and Exit based on Trading Direction
if (tradeDirection == "both" or tradeDirection == "long")
strategy.entry("Buy", strategy.long, when=isBullish)
strategy.close("Buy", when=exitLong)
if (tradeDirection == "both" or tradeDirection == "short")
strategy.entry("Sell", strategy.short, when=isBearish)
strategy.close("Sell", when=exitShort)
bodyMiddle1 = plot((open + close) / 2, display=display.none)
upTrend1 = plot(direction1 < 0 ? supertrend1 : na, "Up Trend", color = color.green, style=plot.style_linebr)
downTrend1 = plot(direction1 < 0? na : supertrend1, "Down Trend", color = color.red, style=plot.style_linebr)
fill(bodyMiddle1, upTrend1, color.new(color.green, 90), fillgaps=false)
fill(bodyMiddle1, downTrend1, color.new(color.red, 90), fillgaps=false)
bodyMiddle2 = plot((open + close) / 2, display=display.none)
upTrend2 = plot(direction2 < 0 ? supertrend2 : na, "Up Trend", color = color.green, style=plot.style_linebr)
downTrend2 = plot(direction2 < 0? na : supertrend2, "Down Trend", color = color.red, style=plot.style_linebr)
fill(bodyMiddle2, upTrend2, color.new(color.green, 90), fillgaps=false)
fill(bodyMiddle2, downTrend2, color.new(color.red, 90), fillgaps=false) |
Buying Selling Volume Strategy | https://www.tradingview.com/script/mA6NEHZE-Buying-Selling-Volume-Strategy/ | exlux99 | https://www.tradingview.com/u/exlux99/ | 85 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © original author ceyhun
//@ exlux99 update
//@version=5
strategy('Buying Selling Volume Strategy', format=format.volume, precision=0, overlay=false)
weekly_vwap = request.security(syminfo.tickerid, "W", ta.vwap(hlc3))
vi = false
customTimeframe = input.timeframe("60", group="Entry Settings")
allow_long = input.bool(true, group="Entry Settings")
allow_short = input.bool(false, group="Entry Settings")
xVolume = request.security(syminfo.tickerid, customTimeframe, volume)
xHigh = request.security(syminfo.tickerid, customTimeframe, high)
xLow = request.security(syminfo.tickerid, customTimeframe, low)
xClose = request.security(syminfo.tickerid, customTimeframe, close)
BV = xHigh == xLow ? 0 : xVolume * (xClose - xLow) / (xHigh - xLow)
SV = xHigh == xLow ? 0 : xVolume * (xHigh - xClose) / (xHigh - xLow)
vol = xVolume > 0 ? xVolume : 1
TP = BV + SV
BPV = BV / TP * vol
SPV = SV / TP * vol
TPV = BPV + SPV
tavol20 = request.security(syminfo.tickerid, customTimeframe, ta.ema(vol, 20))
tabv20= request.security(syminfo.tickerid, customTimeframe, ta.ema(BV, 20))
tasv20= request.security(syminfo.tickerid, customTimeframe, ta.ema(SV, 20))
VN = vol / tavol20
BPN = BV / tabv20 * VN * 100
SPN = SV / tasv20 * VN * 100
TPN = BPN + SPN
xbvp = request.security(syminfo.tickerid, customTimeframe,-math.abs(BPV))
xbpn = request.security(syminfo.tickerid, customTimeframe,-math.abs(BPN))
xspv = request.security(syminfo.tickerid, customTimeframe,-math.abs(SPV))
xspn = request.security(syminfo.tickerid, customTimeframe,-math.abs(SPN))
BPc1 = BPV > SPV ? BPV : xbvp
BPc2 = BPN > SPN ? BPN : xbpn
SPc1 = SPV > BPV ? SPV : xspv
SPc2 = SPN > BPN ? SPN : xspn
BPcon = vi ? BPc2 : BPc1
SPcon = vi ? SPc2 : SPc1
minus = BPcon + SPcon
plot(minus, color = BPcon > SPcon ? color.green : color.red , style=plot.style_columns)
length = input.int(20, minval=1, group="Volatility Settings")
src = minus//input(close, title="Source")
mult = input.float(2.0, minval=0.001, maxval=50, title="StdDev", group="Volatility Settings")
xtasma = request.security(syminfo.tickerid, customTimeframe, ta.sma(src, length))
xstdev = request.security(syminfo.tickerid, customTimeframe, ta.stdev(src, length))
basis = xtasma
dev = mult * xstdev
upper = basis + dev
lower = basis - dev
plot(basis, "Basis", color=#FF6D00, offset = 0)
p1 = plot(upper, "Upper", color=#2962FF, offset = 0)
p2 = plot(lower, "Lower", color=#2962FF, offset = 0)
fill(p1, p2, title = "Background", color=color.rgb(33, 150, 243, 95))
// Original a
longOriginal = minus > upper and BPcon > SPcon and close > weekly_vwap
shortOriginal = minus > upper and BPcon < SPcon and close< weekly_vwap
high_daily = request.security(syminfo.tickerid, "D", high)
low_daily = request.security(syminfo.tickerid, "D", low)
close_daily = request.security(syminfo.tickerid, "D", close)
true_range = math.max(high_daily - low_daily, math.abs(high_daily - close_daily[1]), math.abs(low_daily - close_daily[1]))
atr_range = ta.sma(true_range*100/request.security(syminfo.tickerid, "D", close), 14)
ProfitTarget_Percent_long = input.float(100.0, title='TP Multiplier for Long entries ', step=0.5, step=0.5, group='Dynamic Risk Management')
Profit_Ticks_long = close + (close * (atr_range * ProfitTarget_Percent_long))/100
LossTarget_Percent_long = input.float(1.0, title='SL Multiplier for Long entries', step=0.5, group='Dynamic Risk Management')
Loss_Ticks_long = close - (close * (atr_range * LossTarget_Percent_long ))/100
ProfitTarget_Percent_short = input.float(100.0, title='TP Multiplier for Short entries ', step=0.5, step=0.5, group='Dynamic Risk Management')
Profit_Ticks_short = close - (close * (atr_range*ProfitTarget_Percent_short))/100
LossTarget_Percent_short = input.float(5.0, title='SL Multiplier for Short entries', step=0.5, group='Dynamic Risk Management')
Loss_Ticks_short = close + (close * (atr_range*LossTarget_Percent_short))/100
var longOpened_original = false
var int timeOfBuyLong = na
var float tpLong_long_original = na
var float slLong_long_original = na
long_entryx = longOriginal
longEntry_original = long_entryx and not longOpened_original
if longEntry_original
longOpened_original := true
tpLong_long_original := Profit_Ticks_long
slLong_long_original := Loss_Ticks_long
timeOfBuyLong := time
//lowest_low_var_sl := lowest_low
tpLong_trigger = longOpened_original[1] and ((close > tpLong_long_original) or (high > tpLong_long_original)) //or high > lowest_low_var_tp
slLong_Trigger = longOpened_original[1] and ((close < slLong_long_original) or (low < slLong_long_original)) //or low < lowest_low_var_sl
longExitSignal_original = shortOriginal or tpLong_trigger or slLong_Trigger
if(longExitSignal_original)
longOpened_original := false
tpLong_long_original := na
slLong_long_original := na
if(allow_long)
strategy.entry("long", strategy.long, when=longOriginal)
strategy.close("long", when= longExitSignal_original) //or shortNew
if(allow_short)
strategy.entry("short", strategy.short, when=shortOriginal )
strategy.close("short", when= longOriginal) //or shortNew
|
TradersPost Example MOMO Strategy WallyWorld | https://www.tradingview.com/script/IwgJPn72-TradersPost-Example-MOMO-Strategy-WallyWorld/ | mamalonefv | https://www.tradingview.com/u/mamalonefv/ | 4 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TradersPostInc
//@version=5
strategy('TradersPost Example MOMO Strategy', overlay=true, default_qty_value=100, initial_capital=100000, default_qty_type=strategy.percent_of_equity, pyramiding=0)
startTime = input.time(defval = timestamp('01 Jan 2021 00:00 +0000'), title = 'Start Time', group = 'Date Range')
endTime = input.time(defval = timestamp('31 Dec 2023 23:59 +0000'), title = 'End Time', group = 'Date Range')
timeCondition = time >= startTime and time < endTime
timeConditionEnd = timeCondition[1] and not timeCondition
fastEmaLength = input.int(defval = 8, title = 'Fast EMA Length')
slowEmaLength = input.int(defval = 21, title = 'Slow EMA Length')
sides = input.string(defval = 'Both', title = 'Sides', options = ['Long', 'Short', 'Both', 'None'])
fastEma = ta.ema(close, fastEmaLength)
slowEma = ta.ema(close, slowEmaLength)
isUptrend = fastEma >= slowEma
isDowntrend = fastEma <= slowEma
trendChanging = ta.cross(fastEma, slowEma)
ema105 = request.security(syminfo.tickerid, '30', ta.ema(close, 105)[1], barmerge.gaps_off, barmerge.lookahead_on)
ema205 = request.security(syminfo.tickerid, '30', ta.ema(close, 20)[1], barmerge.gaps_off, barmerge.lookahead_on)
plot(ema105, linewidth=4, color=color.new(color.purple, 0), editable=true)
plot(ema205, linewidth=2, color=color.new(color.purple, 0), editable=true)
aa = plot(fastEma, linewidth=3, color=color.new(color.green, 0), editable=true)
bb = plot(slowEma, linewidth=3, color=color.new(color.red, 0), editable=true)
fill(aa, bb, color=isUptrend ? color.green : color.red, transp=90)
tradersPostBuy = trendChanging and isUptrend and timeCondition
tradersPostSell = trendChanging and isDowntrend and timeCondition
pips = syminfo.pointvalue / syminfo.mintick
percentOrPipsInput = input.string('Percent', title='Percent or Pips', options=['Percent', 'Pips'])
stopLossLongInput = input.float(defval=0, step=0.01, title='Stop Loss Long', minval=0)
stopLossShortInput = input.float(defval=0, step=0.01, title='Stop Loss Short', minval=0)
takeProfitLongInput = input.float(defval=0, step=0.01, title='Target Profit Long', minval=0)
takeProfitShortInput = input.float(defval=0, step=0.01, title='Target Profit Short', minval=0)
stopLossPriceLong = ta.valuewhen(tradersPostBuy, close, 0) * (stopLossLongInput / 100) * pips
stopLossPriceShort = ta.valuewhen(tradersPostSell, close, 0) * (stopLossShortInput / 100) * pips
takeProfitPriceLong = ta.valuewhen(tradersPostBuy, close, 0) * (takeProfitLongInput / 100) * pips
takeProfitPriceShort = ta.valuewhen(tradersPostSell, close, 0) * (takeProfitShortInput / 100) * pips
takeProfitALong = takeProfitLongInput > 0 ? takeProfitLongInput : na
takeProfitBLong = takeProfitPriceLong > 0 ? takeProfitPriceLong : na
takeProfitAShort = takeProfitShortInput > 0 ? takeProfitShortInput : na
takeProfitBShort = takeProfitPriceShort > 0 ? takeProfitPriceShort : na
stopLossALong = stopLossLongInput > 0 ? stopLossLongInput : na
stopLossBLong = stopLossPriceLong > 0 ? stopLossPriceLong : na
stopLossAShort = stopLossShortInput > 0 ? stopLossShortInput : na
stopLossBShort = stopLossPriceShort > 0 ? stopLossPriceShort : na
takeProfitLong = percentOrPipsInput == 'Pips' ? takeProfitALong : takeProfitBLong
stopLossLong = percentOrPipsInput == 'Pips' ? stopLossALong : stopLossBLong
takeProfitShort = percentOrPipsInput == 'Pips' ? takeProfitAShort : takeProfitBShort
stopLossShort = percentOrPipsInput == 'Pips' ? stopLossAShort : stopLossBShort
buyAlertMessage = '{"ticker": "' + syminfo.ticker + '", "action": "buy", "price": ' + str.tostring(close) + '}'
sellAlertMessage = '{"ticker": "' + syminfo.ticker + '", "action": "sell", "price": ' + str.tostring(close) + '}'
exitLongAlertMessage = '{"ticker": "' + syminfo.ticker + '", "action": "exit", "price": ' + str.tostring(close) + '}'
exitShortAlertMessage = '{"ticker": "' + syminfo.ticker + '", "action": "exit", "price": ' + str.tostring(close) + '}'
if (sides != "None")
if tradersPostBuy
strategy.entry('Long', strategy.long, when = sides != 'Short', alert_message = buyAlertMessage)
strategy.close('Short', when = sides == "Short" and timeCondition, alert_message = exitShortAlertMessage)
if tradersPostSell
strategy.entry('Short', strategy.short, when = sides != 'Long', alert_message = sellAlertMessage)
strategy.close('Long', when = sides == 'Long', alert_message = exitLongAlertMessage)
exitAlertMessage = '{"ticker": "' + syminfo.ticker + '", "action": "exit"}'
strategy.exit('Exit Long', from_entry = "Long", profit = takeProfitLong, loss = stopLossLong, alert_message = exitAlertMessage)
strategy.exit('Exit Short', from_entry = "Short", profit = takeProfitShort, loss = stopLossShort, alert_message = exitAlertMessage)
strategy.close_all(when = timeConditionEnd) |
F2.2 Martingale Magic Scalping | https://www.tradingview.com/script/0bJOdS0w-F2-2-Martingale-Magic-Scalping/ | cloudofw | https://www.tradingview.com/u/cloudofw/ | 128 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © cloudofw
//@version=5
strategy("F2.2 Martingale Scalping Strategy", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=1)
// Input parameters
rsiOverbought = input.int(70, "RSI Overbought Threshold")
rsiOversold = input.int(30, "RSI Oversold Threshold")
oscillatorPeriod = input.int(5, "Period for oscillator")
k1 = input.float(0.2, "K1 for oscillator's zone")
k2 = input.float(0.5, "K2 for oscillator's zone")
trendActivity = input.float(1.0, "Main Trend filter", minval=0.1)
decreasePerOrder = input.float(0.1, "Trend filter decrease per order", minval=0.01)
// Calculate custom oscillator and RSI
oscillator = ta.stoch(close, high, low, oscillatorPeriod)
rsiValue = ta.rsi(close, 14)
zoneHigh = 100 - k1 * 100
zoneLow = k2 * 100
// Entry conditions
longCondition = oscillator < zoneLow and trendActivity > 0 and rsiValue < rsiOversold
shortCondition = oscillator > zoneHigh and trendActivity > 0 and rsiValue > rsiOverbought
// Martingale logic
var lot_multiplier = 1.0
var last_lot_size = strategy.equity * 0.01
var trade_1_profit = 0.0
if (strategy.position_size != 0)
lot_multiplier := last_lot_size / strategy.position_size < 1.5 ? lot_multiplier * 1.5 : 1.0
trade_1_profit := strategy.grossprofit
else
lot_multiplier := 1.0
trade_1_profit := 0.0
lot_size = strategy.equity * 0.01 * lot_multiplier + trade_1_profit
last_lot_size := lot_size
// Trading logic
if longCondition and strategy.position_size == 0
strategy.entry("Long", strategy.long, qty=lot_size)
if shortCondition and strategy.position_size == 0
strategy.entry("Short", strategy.short, qty=lot_size)
// Exit conditions
if longCondition == false and strategy.position_size > 0
strategy.close("Long")
if shortCondition == false and strategy.position_size < 0
strategy.close("Short")
// Indicators on chart
plotshape(series=longCondition, title="Buy Entry", location=location.belowbar, color=color.green, style=shape.labelup, text="Buy")
plotshape(series=shortCondition, title="Sell Entry", location=location.abovebar, color=color.red, style=shape.labeldown, text="Sell")
plot(oscillator, color=color.blue, title="Oscillator")
hline(zoneHigh, "Upper Zone", color=color.red)
hline(zoneLow, "Lower Zone", color=color.green)
|
Heatmap MACD Strategy | https://www.tradingview.com/script/DIDy8Fkj-Heatmap-MACD-Strategy/ | Daveatt | https://www.tradingview.com/u/Daveatt/ | 98 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
//@strategy_alert_message {{strategy.order.alert_message}}
SCRIPT_NAME = "Heatmap MACD Strategy"
strategy(SCRIPT_NAME,
overlay= true,
process_orders_on_close = true,
calc_on_every_tick = true,
pyramiding = 1,
initial_capital = 100000000,
default_qty_type = strategy.fixed,
default_qty_value = 1,
commission_type = strategy.commission.percent,
commission_value = 0.075,
slippage = 1
)
long_alert_entry_msg = input.text_area("Long Entry", title = "Long Entry Alert Message", group = "Alerts")
short_alert_entry_msg = input.text_area("Short Entry", title = "Short Entry Alert Message", group = "Alerts")
long_alert_exit_msg = input.text_area("Long Exit", title = "Long Exit Alert Message", group = "Alerts")
short_alert_exit_msg = input.text_area("Short Exit", title = "Short Exit Alert Message", group = "Alerts")
res1 = input.timeframe('60', title='First Timeframe', group = "Timeframes")
res2 = input.timeframe('120', title='Second Timeframe', group = "Timeframes")
res3 = input.timeframe('240', title='Third Timeframe', group = "Timeframes")
res4 = input.timeframe('240', title='Fourth Timeframe', group = "Timeframes")
res5 = input.timeframe('480', title='Fifth Timeframe', group = "Timeframes")
macd_src = input.source(close, title="Source", group = "MACD")
fast_len = input.int(20, minval=1, title="Fast Length", group = "MACD")
slow_len = input.int(50, minval=1, title="Slow Length", group = "MACD")
sig_len = input.int(50, minval=1, title="Signal Length", group = "MACD")
// # ========================================================================= #
// # | Stop Loss |
// # ========================================================================= #
use_sl = input.bool(true, title = "Use Stop Loss?", group = "Stop Loss")
sl_mode = "pips"//input.string("%", title = "Mode", options = ["%", "pips"], group = "Stop Loss")
sl_value = input.float(40, step = 0.1, minval = 0, title = "Value", group = "Stop Loss", inline = "stoploss")// * 0.01
// # ========================================================================= #
// # | Trailing Stop Loss |
// # ========================================================================= #
use_tsl = input.bool(false, title = "Use Trailing Stop Loss?", group = "Trailing Stop Loss")
tsl_input_pips = input.float(10, minval = 0, title = "Trailing Stop Loss (pips)", group = "Trailing Stop Loss")
// # ========================================================================= #
// # | Take Profit |
// # ========================================================================= #
use_tp1 = input.bool(true, title = "Use Take Profit 1?", group = "Take Profit 1")
tp1_value = input.float(30, step = 0.1, minval = 0, title = "Value (pips)", group = "Take Profit 1")// * 0.01
tp1_qty = input.float(50, step = 0.1, minval = 0, title = "Quantity (%)", group = "Take Profit 1")// * 0.01
use_tp2 = input.bool(true, title = "Use Take Profit 2?", group = "Take Profit 2")
tp2_value = input.float(50, step = 0.1, minval = 0, title = "Value (pips)", group = "Take Profit 2")// * 0.01
// # ========================================================================= #
// # | Stop Loss to Breakeven |
// # ========================================================================= #
use_sl_be = input.bool(false, title = "Use Stop Loss to Breakeven Mode?", group = "Break Even")
sl_be_value = input.float(30, step = 0.1, minval = 0, title = "Value (pips)", group = "Break Even", inline = "breakeven")
sl_be_offset = input.int(1, step = 1, minval = 0, title = "Offset (pips)", group = "Break Even", tooltip = "Set the SL at BE price +/- offset value")
[_, _, MTF1_hist] = request.security(syminfo.tickerid, res1, ta.macd(macd_src, fast_len, slow_len, sig_len))
[_, _, MTF2_hist] = request.security(syminfo.tickerid, res2, ta.macd(macd_src, fast_len, slow_len, sig_len))
[_, _, MTF3_hist] = request.security(syminfo.tickerid, res3, ta.macd(macd_src, fast_len, slow_len, sig_len))
[_, _, MTF4_hist] = request.security(syminfo.tickerid, res4, ta.macd(macd_src, fast_len, slow_len, sig_len))
[_, _, MTF5_hist] = request.security(syminfo.tickerid, res5, ta.macd(macd_src, fast_len, slow_len, sig_len))
bull_hist1 = MTF1_hist > 0 and MTF1_hist[1] < 0
bull_hist2 = MTF2_hist > 0 and MTF2_hist[1] < 0
bull_hist3 = MTF3_hist > 0 and MTF3_hist[1] < 0
bull_hist4 = MTF4_hist > 0 and MTF4_hist[1] < 0
bull_hist5 = MTF5_hist > 0 and MTF5_hist[1] < 0
bear_hist1 = MTF1_hist < 0 and MTF1_hist[1] > 0
bear_hist2 = MTF2_hist < 0 and MTF2_hist[1] > 0
bear_hist3 = MTF3_hist < 0 and MTF3_hist[1] > 0
bear_hist4 = MTF4_hist < 0 and MTF4_hist[1] > 0
bear_hist5 = MTF5_hist < 0 and MTF5_hist[1] > 0
plotshape(bull_hist1, title = "Bullish MACD 1", location = location.bottom, style = shape.diamond, size = size.normal, color = #33e823)
plotshape(bull_hist2, title = "Bullish MACD 2", location = location.bottom, style = shape.diamond, size = size.normal, color = #1a7512)
plotshape(bull_hist3, title = "Bullish MACD 3", location = location.bottom, style = shape.diamond, size = size.normal, color = #479c40)
plotshape(bull_hist4, title = "Bullish MACD 4", location = location.bottom, style = shape.diamond, size = size.normal, color = #81cc7a)
plotshape(bull_hist5, title = "Bullish MACD 5", location = location.bottom, style = shape.diamond, size = size.normal, color = #76d66d)
plotshape(bear_hist1, title = "Bearish MACD 1", location = location.top, style = shape.diamond, size = size.normal, color = #d66d6d)
plotshape(bear_hist2, title = "Bearish MACD 2", location = location.top, style = shape.diamond, size = size.normal, color = #de4949)
plotshape(bear_hist3, title = "Bearish MACD 3", location = location.top, style = shape.diamond, size = size.normal, color = #cc2525)
plotshape(bear_hist4, title = "Bearish MACD 4", location = location.top, style = shape.diamond, size = size.normal, color = #a11d1d)
plotshape(bear_hist5, title = "Bearish MACD 5", location = location.top, style = shape.diamond, size = size.normal, color = #ed2424)
bull_count = (MTF1_hist > 0 ? 1 : 0) + (MTF2_hist > 0 ? 1 : 0) + (MTF3_hist > 0 ? 1 : 0) + (MTF4_hist > 0 ? 1 : 0) + (MTF5_hist > 0 ? 1 : 0)
bear_count = (MTF1_hist < 0 ? 1 : 0) + (MTF2_hist < 0 ? 1 : 0) + (MTF3_hist < 0 ? 1 : 0) + (MTF4_hist < 0 ? 1 : 0) + (MTF5_hist < 0 ? 1 : 0)
bull = bull_count == 5 and bull_count[1] < 5 and barstate.isconfirmed
bear = bear_count == 5 and bear_count[1] < 5 and barstate.isconfirmed
signal_candle = bull or bear
entryLongPrice = ta.valuewhen(bull and strategy.position_size[1] <= 0, close, 0)
entryShortPrice = ta.valuewhen(bear and strategy.position_size[1] >= 0, close, 0)
get_pip_size() =>
float _pipsize = 1.
if syminfo.type == "forex"
_pipsize := (syminfo.mintick * (str.contains(syminfo.ticker, "JPY") ? 100 : 10))
else if str.contains(syminfo.ticker, "XAU") or str.contains(syminfo.ticker, "XAG")
_pipsize := 0.1
_pipsize
//get_pip_size() =>
// syminfo.type == "forex" ? syminfo.pointvalue * 100 : 1
// # ========================================================================= #
// # | Stop Loss |
// # ========================================================================= #
var float final_SL_Long = 0.
var float final_SL_Short = 0.
if signal_candle and use_sl
final_SL_Long := entryLongPrice - (sl_value * get_pip_size())
final_SL_Short := entryShortPrice + (sl_value * get_pip_size())
// # ========================================================================= #
// # | Trailing Stop Loss |
// # ========================================================================= #
var MaxReached = 0.0
if signal_candle[1]
MaxReached := strategy.position_size > 0 ? high : low
MaxReached := strategy.position_size > 0
? math.max(nz(MaxReached, high), high)
: strategy.position_size < 0 ? math.min(nz(MaxReached, low), low) : na
if use_tsl and use_sl
if strategy.position_size > 0
stopValue = MaxReached - (tsl_input_pips * get_pip_size())
final_SL_Long := math.max(stopValue, final_SL_Long[1])
else if strategy.position_size < 0
stopValue = MaxReached + (tsl_input_pips * get_pip_size())
final_SL_Short := math.min(stopValue, final_SL_Short[1])
// # ========================================================================= #
// # | Take Profit 1 |
// # ========================================================================= #
var float final_TP1_Long = 0.
var float final_TP1_Short = 0.
final_TP1_Long := entryLongPrice + (tp1_value * get_pip_size())
final_TP1_Short := entryShortPrice - (tp1_value * get_pip_size())
plot(use_tp1 and strategy.position_size > 0 ? final_TP1_Long : na, title = "TP1 Long", color = color.aqua, linewidth=2, style=plot.style_linebr)
plot(use_tp1 and strategy.position_size < 0 ? final_TP1_Short : na, title = "TP1 Short", color = color.blue, linewidth=2, style=plot.style_linebr)
// # ========================================================================= #
// # | Take Profit 2 |
// # ========================================================================= #
var float final_TP2_Long = 0.
var float final_TP2_Short = 0.
final_TP2_Long := entryLongPrice + (tp2_value * get_pip_size())
final_TP2_Short := entryShortPrice - (tp2_value * get_pip_size())
plot(use_tp2 and strategy.position_size > 0 and tp1_qty != 100 ? final_TP2_Long : na, title = "TP2 Long", color = color.orange, linewidth=2, style=plot.style_linebr)
plot(use_tp2 and strategy.position_size < 0 and tp1_qty != 100 ? final_TP2_Short : na, title = "TP2 Short", color = color.white, linewidth=2, style=plot.style_linebr)
// # ========================================================================= #
// # | Stop Loss to Breakeven |
// # ========================================================================= #
var bool SL_BE_REACHED = false
// Calculate open profit or loss for the open positions.
tradeOpenPL() =>
sumProfit = 0.0
for tradeNo = 0 to strategy.opentrades - 1
sumProfit += strategy.opentrades.profit(tradeNo)
result = sumProfit
//get_pip_size() =>
// syminfo.type == "forex" ? syminfo.pointvalue * 100 : 1
current_profit = tradeOpenPL()// * get_pip_size()
current_long_profit = (close - entryLongPrice) / (syminfo.mintick * 10)
current_short_profit = (entryShortPrice - close) / (syminfo.mintick * 10)
plot(current_short_profit, title = "Current Short Profit", display = display.data_window)
plot(current_long_profit, title = "Current Long Profit", display = display.data_window)
if use_sl_be
if strategy.position_size[1] > 0
if not SL_BE_REACHED
if current_long_profit >= sl_be_value
final_SL_Long := entryLongPrice + (sl_be_offset * get_pip_size())
SL_BE_REACHED := true
else if strategy.position_size[1] < 0
if not SL_BE_REACHED
if current_short_profit >= sl_be_value
final_SL_Short := entryShortPrice - (sl_be_offset * get_pip_size())
SL_BE_REACHED := true
plot(use_sl and strategy.position_size > 0 ? final_SL_Long : na, title = "SL Long", color = color.fuchsia, linewidth=2, style=plot.style_linebr)
plot(use_sl and strategy.position_size < 0 ? final_SL_Short : na, title = "SL Short", color = color.fuchsia, linewidth=2, style=plot.style_linebr)
// # ========================================================================= #
// # | Strategy Calls |
// # ========================================================================= #
if bull
strategy.entry("Long", strategy.long, comment="Long", alert_message = long_alert_entry_msg)
else if bear
strategy.entry("Short", strategy.short, comment="Short", alert_message = short_alert_entry_msg)
if strategy.position_size[1] > 0
if low <= final_SL_Long and use_sl
strategy.close("Long", comment = "Close SL Long", alert_message = long_alert_exit_msg)
else
strategy.exit("Exit TP1 Long", "Long", limit = final_TP1_Long, comment_profit = "Exit TP1 Long", qty_percent = tp1_qty)
strategy.exit("Exit TP2 Long", "Long", limit = final_TP2_Long, comment_profit = "Exit TP2 Long", alert_message = long_alert_exit_msg)
if bull_count[1] == 5 and bull_count < 5
strategy.close("Long", comment = "1 or more MACD(s) became bearish", alert_message = long_alert_exit_msg)
else if strategy.position_size[1] < 0
if high >= final_SL_Short and use_sl
strategy.close("Short", comment = "Close SL Short", alert_message = short_alert_exit_msg)
else
strategy.exit("Exit TP1 Short", "Short", limit = final_TP1_Short, comment_profit = "Exit TP1 Short", qty_percent = tp1_qty)
strategy.exit("Exit TP2 Short", "Short", limit = final_TP2_Short, comment_profit = "Exit TP2 Short", alert_message = short_alert_exit_msg)
if bear_count[1] == 5 and bear_count < 5
strategy.close("Short", comment = "1 or more MACD(s) became bullish", alert_message = short_alert_entry_msg)
// # ========================================================================= #
// # | Reset Variables |
// # ========================================================================= #
if (strategy.position_size > 0 and strategy.position_size[1] <= 0)
or (strategy.position_size < 0 and strategy.position_size[1] >= 0)
SL_BE_REACHED := false |
simple pull back TJlv26 | https://www.tradingview.com/script/eS0yG7Nq/ | TJlv26 | https://www.tradingview.com/u/TJlv26/ | 12 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © tsujimoto0403
//@version=5
strategy("simple pull back", overlay=true,default_qty_type=strategy.percent_of_equity,
default_qty_value=100)
//input value
malongperiod=input.int(200,"長期移動平均BASE200/period of long term sma",group = "パラメータ")
mashortperiod=input.int(10,"長期移動平均BASE10/period of short term sma",group = "パラメータ")
stoprate=input.int(5,title = "損切の割合%/stoploss percentages",group = "パラメータ")
profit=input.int(20,title = "利食いの割合%/take profit percentages",group = "パラメータ")
startday=input.time(title="バックテストを始める日/start trade day", defval=timestamp("01 Jan 2000 13:30 +0000"), group="期間")
endday=input.time(title="バックテスを終わる日/finish date day", defval=timestamp("1 Jan 2099 19:30 +0000"), group="期間")
//polt indicators that we use
malong=ta.sma(close,malongperiod)
mashort=ta.sma(close,mashortperiod)
plot(malong,color=color.aqua,linewidth = 2)
plot(mashort,color=color.yellow,linewidth = 2)
//date range
datefilter = time >= startday and time <= endday
//open conditions
if close>malong and close<mashort and strategy.position_size == 0 and datefilter and ta.rsi(close,3)<30
strategy.entry(id="long", direction=strategy.long)
//sell conditions
strategy.exit(id="cut",from_entry="long",stop=(1-0.01*stoprate)*strategy.position_avg_price,limit=(1+0.01*profit)*strategy.position_avg_price)
if close>mashort and close<low[1] and strategy.position_size>0
strategy.close(id ="long")
|
Supertrend Advance Pullback Strategy | https://www.tradingview.com/script/IRCgOETG-Supertrend-Advance-Pullback-Strategy/ | JS_TechTrading | https://www.tradingview.com/u/JS_TechTrading/ | 31 | strategy | 5 | MPL-2.0 | // This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © JS_TechTrading
//@version=5
strategy("Supertrend advance", overlay=true,default_qty_type =strategy.percent_of_equity,default_qty_value = 1,process_orders_on_close = false)
// group string////
var string group_text000="Choose Strategy"
var string group_text0="Supertrend Settings"
var string group_text0000="Ema Settings"
var string group_text00="Rsi Settings"
var string group_text1="Backtest Period"
var string group_text2="Trade Direction"
var string group_text3="Quantity Settings"
var string group_text4="Sl/Tp Settings"
var string group_text5="Enable/Disable Condition Filter"
var string group_macd="Macd Set"
var group_cci="Cci Set"
var string group_text6="Choose Sl/Tp"
var string group_text7="Percentage Sl/Tp"
var string group_text9="Atr SL/Tp"
var string group_text8='Swing Hl & Supertrend Sl/Tp'
// filter enable and disbale
on_ma =input.bool(true,"Ema Condition On/Off",group=group_text5,inline = "CL")
en_rsi = input.bool(true,"Rsi Condition On/Off",group = group_text5,inline = "CL")
en_macd=input.bool(true,title ="Enable Macd Condition",group =group_text5,inline = "CS")
en_cci=input.bool(true,title ="Enable/Disable CCi Filter",group =group_text5,inline = "CS")
////////////////////
option_ch=input.string('Pullback',title = "Type Of Stratgey",options =['Pullback','Simple'],group = "Choose Strategy Type")
// option for stop loss and take profit
option_ts=input.string("Percentage","Chosse Type Of Sl/tp",["Percentage","Supertrend","Swinghl","Atr"],group=group_text6)
//atr period input supertrend
atrPeriod = input(10, "ATR Length",group = group_text0)
factor = input.float(3.0, "Factor", step = 0.01,group=group_text0)
[supertrend, direction] = ta.supertrend(factor, atrPeriod)
bodyMiddle = plot((open + close) / 2, display=display.none)
upTrend = plot(direction < 0 ? supertrend : na, "Up Trend", color = color.green, style=plot.style_linebr)
downTrend = plot(direction < 0? na : supertrend, "Down Trend", color = color.red, style=plot.style_linebr)
fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps=false)
fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps=false)
long=direction < 0 ? supertrend : na
short=direction < 0? na : supertrend
longpos=false
shortpos=false
longpos :=long?true :short?false:longpos[1]
shortpos:=short?true:long?false:shortpos[1]
fin_pullbuy= (ta.crossunder(low[1],long) and long and high>high[1])
fin_pullsell=(ta.crossover(high[1],short) and short and low<low[1])
//Ema 1
ma_len= input.int(200, minval=1, title="Ema Length",group = group_text0000)
ma_src = input.source(close, title="Ema Source",group = group_text0000)
ma_out = ta.ema(ma_src, ma_len)
ma_buy=on_ma?close>ma_out?true:false:true
ma_sell=on_ma?close<ma_out?true:false:true
// rsi indicator and condition
// Get user input
rsiSource = input(title='RSI Source', defval=close,group = group_text00)
rsiLength = input(title='RSI Length', defval=14,group = group_text00)
rsiOverbought = input(title='RSI BUY Level', defval=50,group = group_text00)
rsiOversold = input(title='RSI SELL Level', defval=50,group = group_text00)
// Get RSI value
rsiValue = ta.rsi(rsiSource, rsiLength)
rsi_buy=en_rsi?rsiValue>=rsiOverbought ?true:false:true
rsi_sell=en_rsi?rsiValue<=rsiOversold?true:false:true
// Getting inputs macd
fast_length = input(title="Fast Length", defval=12,group =group_macd)
slow_length = input(title="Slow Length", defval=26,group =group_macd)
macd_src = input(title="Source", defval=close,group =group_macd)
signal_length = input.int(title="Signal Smoothing", minval = 1, maxval = 50, defval = 9,group =group_macd)
[macdLine, signalLine, histLine] = ta.macd(macd_src, fast_length ,slow_length,signal_length)
buy_macd=en_macd?macdLine>0?true:false:true
sell_macd=en_macd?macdLine<0?true:false:true
// CCI indicator
length_cci = input.int(20, minval=1,group = group_cci)
src_cci = input(hlc3, title="Source",group = group_cci)
cci_gr=input.int(200,title = "CCi > Input",group = group_cci,tooltip ="CCi iS Greater thn 100 buy")
cci_ls=input.int(-200,title = "CCi < -Input",group = group_cci,tooltip ="CCi iS Less thn -100 Sell")
ma = ta.sma(src_cci, length_cci)
cci = (src_cci - ma) / (0.015 * ta.dev(src_cci, length_cci))
//cci buy and sell
buy_cci=en_cci?cci>cci_gr?true:false:true
sell_cci=en_cci?cci<cci_ls?true:false:true
// final condition
buy_cond=option_ch=='Simple'?long and not(longpos[1]) and rsi_buy and ma_buy and buy_macd and buy_cci:option_ch=='Pullback'?fin_pullbuy and rsi_buy and ma_buy and buy_macd and buy_cci:na
sell_cond=option_ch=='Simple'?short and not(shortpos[1]) and rsi_sell and ma_sell and sell_macd and sell_cci:option_ch=='Pullback'?fin_pullsell and rsi_sell and ma_sell and sell_macd and sell_cci:na
//backtest engine
start = input.time(timestamp('2005-01-01'), title='Start calculations from',group=group_text1)
end=input.time(timestamp('2045-03-01'), title='End calculations',group=group_text1)
time_cond = time >= start and time<=end
// Make input option to configure trade direction
tradeDirection = input.string(title='Trade Direction', options=['Long', 'Short', 'Both'], defval='Both',group = group_text2)
// Translate input into trading conditions
longOK = (tradeDirection == "Long") or (tradeDirection == "Both")
shortOK = (tradeDirection == "Short") or (tradeDirection == "Both")
// quantity
qty_new=input.float(1.0,step =0.10,title ="Quantity",group =group_text3)
// supertrend and swing high and low
tpnewf = input.float(title="take profit swinghl||supertrend ", step=0.1, defval=1.5, group=group_text8)
hiLen = input.int(title='Highest High Lookback', defval=6, minval=2, group=group_text8)
loLen = input.int(title='Lowest Low Lookback', defval=6, minval=2, group=group_text8)
globl = option_ts=="Swinghl"? nz(ta.lowest(low, loLen),low[1]):option_ts=="Supertrend"?nz(supertrend,low[1]):na
globl2=option_ts=="Swinghl"? nz(ta.highest(high, hiLen),high[1]) :option_ts=="Supertrend"?nz(supertrend,high[1]):na
var store = float(na)
var store2=float(na)
// strategy start
if buy_cond and longOK and time_cond and strategy.position_size==0
strategy.entry("enter long",direction = strategy.long,qty =qty_new)
store:=globl
if sell_cond and shortOK and time_cond and strategy.position_size==0
strategy.entry("enter short",direction =strategy.short,qty =qty_new)
store2:=globl2
//stop loss and take profit
enable_trail=input.bool(false,"Enable Trail",group =group_text7)
stopPer = input.float(1.0,step=0.10,title='Stop Loss %',group=group_text7)* 0.01
takePer = input.float(2.0,step=0.10, title='Take Profit %',group=group_text7)* 0.01
//TRAILING STOP CODE
trailStop = input.float(title='Trailing Stop (%)', minval=0.0, step=0.1, defval=1,group=group_text7) * 0.01
longStopPrice = 0.0
shortStopPrice = 0.0
longStopPrice := if strategy.position_size > 0
stopValue = close * (1 - trailStop)
math.max(stopValue, longStopPrice[1])
else
0
shortStopPrice := if strategy.position_size < 0
stopValue = close * (1 + trailStop)
math.min(stopValue, shortStopPrice[1])
else
999999
// Determine where you've entered and in what direction
longStop = 0.0
shortStop =0.0
shortTake =0.0
longTake = 0.0
if (option_ts=="Percentage" )
// Determine where you've entered and in what direction
longStop := strategy.position_avg_price * (1 - stopPer)
shortStop := strategy.position_avg_price * (1 + stopPer)
shortTake := strategy.position_avg_price * (1 - takePer)
longTake := strategy.position_avg_price * (1 + takePer)
if enable_trail and (option_ts=="Percentage" )
longStop := longStopPrice
shortStop := shortStopPrice
//single take profit exit position
if strategy.position_size > 0 and option_ts=="Percentage"
strategy.exit(id='Close Long',from_entry = "enter long", stop=longStop, limit=longTake)
if strategy.position_size < 0 and option_ts=="Percentage"
strategy.exit(id='Close Short',from_entry = "enter short", stop=shortStop, limit=shortTake)
//PLOT FIXED SLTP LINE
plot(strategy.position_size > 0 and option_ts=="Percentage" ? longStop : na, style=plot.style_linebr, color=enable_trail?na:color.new(#c0ff52, 0), linewidth=1, title='Long Fixed SL')
plot(strategy.position_size < 0 and option_ts=="Percentage"? shortStop : na, style=plot.style_linebr, color=enable_trail?na:color.new(#5269ff, 0), linewidth=1, title='Short Fixed SL')
plot(strategy.position_size > 0 and option_ts=="Percentage"? longTake : na, style=plot.style_linebr, color=color.new(#5e6192, 0), linewidth=1, title='Long Take Profit')
plot(strategy.position_size < 0 and option_ts=="Percentage"? shortTake : na, style=plot.style_linebr, color=color.new(#dcb53d, 0), linewidth=1, title='Short Take Profit')
//PLOT TSL LINES
plot(series=strategy.position_size > 0 and option_ts=="Percentage" and enable_trail ? longStopPrice : na, color=color.new(color.red, 0), style=plot.style_linebr, linewidth=1, title='Long Trail Stop', offset=1)
plot(series=strategy.position_size < 0 and option_ts=="Percentage" and enable_trail ? shortStopPrice : na, color=color.new(color.red, 0), style=plot.style_linebr, linewidth=1, title='Short Trail Stop', offset=1)
// swing high and low
//take profit
takeProfit_buy = strategy.position_avg_price - ((store - strategy.position_avg_price) * tpnewf)
takeProfit_sell = strategy.position_avg_price - ((store2 - strategy.position_avg_price) * tpnewf)
// Submit stops based on highest high and lowest low
if strategy.position_size >= 0 and (option_ts=="Swinghl" or option_ts=="Supertrend")
strategy.exit(id='XL HH',from_entry = "enter long", stop=store,limit=takeProfit_buy,comment ="Long Exit")
if strategy.position_size <= 0 and (option_ts=="Swinghl" or option_ts=="Supertrend")
strategy.exit(id='XS LL',from_entry = "enter short", stop=store2,limit=takeProfit_sell,comment = "Short Exit")
// plot take profit
plot(series=strategy.position_size < 0 and (option_ts=="Swinghl" or option_ts=="Supertrend")? takeProfit_sell : na, style=plot.style_circles, color=color.orange, linewidth=1, title="take profit sell")
plot(series=strategy.position_size > 0 and (option_ts=="Swinghl" or option_ts=="Supertrend")? takeProfit_buy: na, style=plot.style_circles, color=color.blue, linewidth=1, title="take profit buy")
// Plot stop Loss for visual confirmation
plot(series=strategy.position_size > 0 and (option_ts=="Swinghl" or option_ts=="Supertrend")? store : na, style=plot.style_circles, color=color.new(color.green, 0), linewidth=1, title='Lowest Low Stop')
plot(series=strategy.position_size < 0 and (option_ts=="Swinghl" or option_ts=="Supertrend")? store2 : na, style=plot.style_circles, color=color.new(color.red, 0), linewidth=1, title='Highest High Stop')
// atr
enable_atrtrail=input.bool(false,"Enable Atr Trail",group = group_text9)
atrLength = input(title='ATR Length', defval=14,group =group_text9)
slATRMult = input.float(title='Stop loss ATR multiplier',step=0.1, defval=2.0,group =group_text9)
tpATRMult = input.float(title='Take profit multiplier',step=0.1, defval=1.5,group =group_text9)
lookback = input.int(title='How Far To Look Back For High/Lows', defval=7, minval=1,group =group_text9)
atr = ta.atr(atrLength)
lowestLow = ta.lowest(low, lookback)
highestHigh = ta.highest(high, lookback)
longStopa = (enable_atrtrail ? lowestLow : close) - atr * slATRMult
shortStopa = (enable_atrtrail ? highestHigh : close) + atr * slATRMult
atr_l=0.0
atr_s=0.0
atr_l:=nz(strategy.position_avg_price-(atr[1] * slATRMult),strategy.position_avg_price-(1 * slATRMult))
atr_s:=nz(strategy.position_avg_price+ (atr[1] * slATRMult),strategy.position_avg_price-(1 * slATRMult))
stoploss_l = ta.valuewhen(strategy.position_size != 0 and strategy.position_size[1] == 0,atr_l, 0)
stoploss_s = ta.valuewhen(strategy.position_size != 0 and strategy.position_size[1] == 0,atr_s, 0)
takeprofit_l = strategy.position_avg_price - ((stoploss_l - strategy.position_avg_price) * tpATRMult)
takeprofit_s = strategy.position_avg_price - ((stoploss_s - strategy.position_avg_price) * tpATRMult)
// Submit stops based on highest high and lowest low
if strategy.position_size > 0 and (option_ts=="Atr")
strategy.exit(id='Xl', stop= enable_atrtrail?longStopa:stoploss_l,limit=takeprofit_l ,comment ="Long Exit")
if strategy.position_size < 0 and (option_ts=="Atr")
strategy.exit(id='XH', stop=enable_atrtrail?shortStopa:stoploss_s,limit=takeprofit_s,comment = "Short Exit")
// // plot take profit
plot(series=strategy.position_size > 0 and (option_ts=="Atr")? takeprofit_l : na, style=plot.style_circles, color=color.orange, linewidth=1, title="take profit sell")
plot(series=strategy.position_size < 0 and (option_ts=="Atr")? takeprofit_s: na, style=plot.style_circles, color=color.blue, linewidth=1, title="take profit buy")
// Plot stop Loss for visual confirmation
plot(series=strategy.position_size >0 and (option_ts=="Atr") and not enable_atrtrail? stoploss_l : na, style=plot.style_circles, color=color.new(color.green, 0), linewidth=1, title='Lowest Low Stop')
plot(series=strategy.position_size < 0 and (option_ts=="Atr") and not enable_atrtrail? stoploss_s : na, style=plot.style_circles, color=color.new(color.red, 0), linewidth=1, title='Highest High Stop')
//PLOT TSL LINES
plot(series=strategy.position_size >0 and option_ts=="Atr" and enable_atrtrail ? longStopa : na, color=color.new(color.green, 0), style=plot.style_linebr, linewidth=1, title='Long Trail Stop', offset=1)
plot(series=strategy.position_size < 0 and (option_ts=="Atr") and enable_atrtrail? shortStopa : na, style=plot.style_linebr, color=color.new(color.red, 0), linewidth=1, title='short Trail Stop', offset=1)
|
RSI & Backed-Weighted MA Strategy | https://www.tradingview.com/script/FOf28r5x/ | gsanson66 | https://www.tradingview.com/u/gsanson66/ | 34 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © gsanson66
//This code is based on RSI and a backed weighted MA
//@version=5
strategy("RSI + MA STRATEGY", overlay=true, initial_capital=1000, default_qty_type=strategy.fixed, commission_type=strategy.commission.percent, commission_value=0.18, slippage=3)
//------------------------TOOL TIPS---------------------------//
t1 = "Choice between a Standard MA (SMA) or a backed-weighted MA (RWMA) which permits to minimize the impact of short term reversal. Default is RWMA."
t2 = "Value of RSI to send a LONG or a SHORT signal. RSI above 60 is a LONG signal and RSI below 40 is a SHORT signal."
t3 = "Rate of Change Value of selected MA to send a LONG or a SHORT signal. By default : ROC MA below 0 is a LONG signal and ROC MA above 0 is a SHORT signal"
t4 = "Threshold value to trigger trailing Take Profit. This threshold is calculated as a multiple of the ATR (Average True Range)."
t5 = "Percentage value of trailing Take Profit. This Trailing TP follows the profit if it increases, remaining selected percentage below it, but stops if the profit decreases."
t6 = "The maximum percentage of the trade value we can lose. Default is 10%"
t7 = "Each gain or losse (relative to the previous reference) in an amount equal to this fixed ratio will change quantity of orders."
t8 = "The amount of money to be added to or subtracted from orders once the fixed ratio has been reached."
//------------------------FUNCTIONS---------------------------//
//@function which calculate a retro weighted moving average to minimize the impact of short term reversal
rwma(source, length) =>
sum = 0.0
denominator = 0.0
weight = 0.0
weight_x = 100/(4+(length-4)*1.30)
weight_y = 1.30*weight_x
for i=0 to length - 1
if i <= 3
weight := weight_x
else
weight := weight_y
sum := sum + source[i] * weight
denominator := denominator + weight
rwma = sum/denominator
//@function which permits the user to choose a moving average type
ma(source, length, type) =>
switch type
"SMA" => ta.sma(source, length)
"RWMA" => rwma(source, length)
//@function Displays text passed to `txt` when called.
debugLabel(txt, color) =>
label.new(bar_index, high, text = txt, color=color, style = label.style_label_lower_right, textcolor = color.black, size = size.small)
//@function which looks if the close date of the current bar falls inside the date range
inBacktestPeriod(start, end) => (time >= start) and (time <= end)
//--------------------------------USER INPUTS-------------------------------//
//Technical parameters
rsiLengthInput = input.int(20, minval=1, title="RSI Length", group="RSI Settings")
maTypeInput = input.string("RWMA", title="MA Type", options=["SMA", "RWMA"], group="MA Settings", inline="1", tooltip=t1)
maLenghtInput = input.int(19, minval=1, title="MA Length", group="MA Settings", inline="1")
rsiLongSignalValue = input.int(60, minval=1, maxval=99, title="RSI Long Signal", group="Strategy parameters", inline="3")
rsiShortSignalValue = input.int(40, minval=1, maxval=99, title="RSI Short Signal", group="Strategy parameters", inline="3", tooltip=t2)
rocMovAverLongSignalValue = input.float(0, maxval=0, title="ROC MA Long Signal", group="Strategy parameters", inline="4")
rocMovAverShortSignalValue = input.float(0, minval=0, title="ROC MA Short Signal", group="Strategy parameters", inline="4", tooltip=t3)
//TP Activation and Trailing TP
takeProfitActivationInput = input.float(5, minval=1.0, title="TP activation in multiple of ATR", group="Strategy parameters", tooltip=t4)
trailingStopInput = input.float(3, minval=0, title="Trailing TP in percentage", group="Strategy parameters", tooltip=t5)
maxSl = input.float(10, "Max loss per trade (in %)", minval=0, tooltip=t6)
//Money Management
fixedRatio = input.int(defval=400, minval=1, title="Fixed Ratio Value ($)", group="Money Management", tooltip=t7)
increasingOrderAmount = input.int(defval=200, minval=1, title="Increasing Order Amount ($)", group="Money Management", tooltip=t8)
//Backtesting period
startDate = input.time(title="Start Date", defval=timestamp("1 Jan 2017 00:00:00"), group="Backtesting Period")
endDate = input.time(title="End Date", defval=timestamp("1 July 2024 00:00:00"), group="Backtesting Period")
//------------------------------VARIABLES INITIALISATION-----------------------------//
float rsi = ta.rsi(close, rsiLengthInput)
float ma = ma(close, maLenghtInput, maTypeInput)
float roc_ma = ((ma/ma[maLenghtInput]) - 1)*100
float atr = ta.atr(20)
var float trailingStopOffset = na
var float trailingStopActivation = na
var float trailingStop = na
var float stopLoss = na
var bool long = na
var bool short = na
var bool bufferTrailingStopDrawing = na
float theoreticalStopPrice = na
bool inRange = na
equity = math.abs(strategy.equity - strategy.openprofit)
var float capital_ref = strategy.initial_capital
var float cashOrder = strategy.initial_capital * 0.95
//------------------------------CHECKING SOME CONDITIONS ON EACH SCRIPT EXECUTION-------------------------------//
//Checking if the date belong to the range
inRange := inBacktestPeriod(startDate, endDate)
//Checking performances of the strategy
if equity > capital_ref + fixedRatio
spread = (equity - capital_ref)/fixedRatio
nb_level = int(spread)
increasingOrder = nb_level * increasingOrderAmount
cashOrder := cashOrder + increasingOrder
capital_ref := capital_ref + nb_level*fixedRatio
if equity < capital_ref - fixedRatio
spread = (capital_ref - equity)/fixedRatio
nb_level = int(spread)
decreasingOrder = nb_level * increasingOrderAmount
cashOrder := cashOrder - decreasingOrder
capital_ref := capital_ref - nb_level*fixedRatio
//Checking if we close all trades in case where we exit the backtesting period
if strategy.position_size!=0 and not inRange
debugLabel("END OF BACKTESTING PERIOD : we close the trade", color=color.rgb(116, 116, 116))
strategy.close_all()
bufferTrailingStopDrawing := false
stopLoss := na
trailingStopActivation := na
trailingStop := na
short := false
long := false
//------------------------------STOP LOSS AND TRAILING STOP ACTIVATION----------------------------//
// We handle the stop loss and trailing stop activation
if (low <= stopLoss or high >= trailingStopActivation) and long
if high >= trailingStopActivation
bufferTrailingStopDrawing := true
else if low <= stopLoss
long := false
stopLoss := na
trailingStopActivation := na
if (low <= trailingStopActivation or high >= stopLoss) and short
if low <= trailingStopActivation
bufferTrailingStopDrawing := true
else if high >= stopLoss
short := false
stopLoss := na
trailingStopActivation := na
//-------------------------------------TRAILING STOP--------------------------------------//
// If the traling stop is activated, we manage its plotting with the bufferTrailingStopDrawing
if bufferTrailingStopDrawing and long
theoreticalStopPrice := high - trailingStopOffset * syminfo.mintick
if na(trailingStop)
trailingStop := theoreticalStopPrice
else if theoreticalStopPrice > trailingStop
trailingStop := theoreticalStopPrice
else if low <= trailingStop
trailingStop := na
bufferTrailingStopDrawing := false
long := false
if bufferTrailingStopDrawing and short
theoreticalStopPrice := low + trailingStopOffset * syminfo.mintick
if na(trailingStop)
trailingStop := theoreticalStopPrice
else if theoreticalStopPrice < trailingStop
trailingStop := theoreticalStopPrice
else if high >= trailingStop
trailingStop := na
bufferTrailingStopDrawing := false
short := false
//---------------------------------LONG CONDITION--------------------------//
if rsi >= 60 and roc_ma <= rocMovAverLongSignalValue and inRange and not long
if short
bufferTrailingStopDrawing := false
stopLoss := na
trailingStopActivation := na
trailingStop := na
short := false
trailingStopActivation := close + takeProfitActivationInput*atr
trailingStopOffset := (trailingStopActivation * trailingStopInput/100) / syminfo.mintick
stopLossAtr = close - 3*atr
if (stopLossAtr/close) - 1 < -maxSl/100
stopLoss := close*(1-maxSl/100)
else
stopLoss := stopLossAtr
long := true
qty = cashOrder/close
strategy.entry("Long", strategy.long, qty)
strategy.exit("Exit Long", "Long", stop = stopLoss, trail_price = trailingStopActivation,
trail_offset = trailingStopOffset)
//--------------------------------SHORT CONDITION-------------------------------//
if rsi <= 40 and roc_ma >= rocMovAverShortSignalValue and inRange and not short
if long
bufferTrailingStopDrawing := false
stopLoss := na
trailingStopActivation := na
trailingStop := na
long := false
trailingStopActivation := close - takeProfitActivationInput*atr
trailingStopOffset := (trailingStopActivation * trailingStopInput/100) / syminfo.mintick
stopLossAtr = close + 3*atr
if (stopLossAtr/close) - 1 > maxSl/100
stopLoss := close*(1+maxSl/100)
else
stopLoss := stopLossAtr
short := true
qty = cashOrder/close
strategy.entry("Short", strategy.short, qty)
strategy.exit("Exit Short", "Short", stop = stopLoss, trail_price = trailingStopActivation,
trail_offset = trailingStopOffset)
//--------------------------------PLOTTING ELEMENT---------------------------------//
// Plotting of element in the graph
plotchar(rsi, "RSI", "", location.top, color.rgb(0, 214, 243))
plot(ma, "MA", color.rgb(219, 219, 18))
plotchar(roc_ma, "ROC MA", "", location.top, color=color.orange)
// Visualizer trailing stop and stop loss movement
plot(stopLoss, "SL", color.red, 3, plot.style_linebr)
plot(trailingStopActivation, "Trigger Trail", color.green, 3, plot.style_linebr)
plot(trailingStop, "Trailing Stop", color.blue, 3, plot.style_linebr)
|
Rate of Change Strategy | https://www.tradingview.com/script/l2nAUB2f/ | gsanson66 | https://www.tradingview.com/u/gsanson66/ | 30 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © gsanson66
//This strategy use the Rate of Change (ROC) of the closing price to send enter signal.
//@version=5
strategy("RATE OF CHANGE STRATEGY", shorttitle="ROC STRATEGY", overlay=false, precision=3, initial_capital=1000, default_qty_type=strategy.cash, default_qty_value=950, commission_type=strategy.commission.percent, commission_value=0.18, slippage=3)
//--------------------------------TOOL TIPS-----------------------------------//
t1 = "Rate of Change length. We compare the current price with that of the selected length ago."
t2 = "The Rate of Change value which indicates that we are in a bubble. This value varies according to the financial products."
t3 = "Stop Loss value in percentage. This is the maximum loss a trade can incur."
t4 = "Each gain or losse (relative to the previous reference) in an amount equal to this fixed ratio will change quantity of orders."
t5 = "The amount of money to be added to or subtracted from orders once the fixed ratio has been reached."
//--------------------------------FUNCTIONS-----------------------------------//
//@function Displays text passed to `txt` when called.
debugLabel(txt, color, loc) =>
label.new(bar_index, loc, text = txt, color=color, style = label.style_label_lower_right, textcolor = color.black, size = size.small)
//@function which looks if the close date of the current bar falls inside the date range
inBacktestPeriod(start, end) => (time >= start) and (time <= end)
//----------------------------------USER INPUTS----------------------------------//
//Technical parameters
rocLength = input.int(defval=365, minval=0, title='ROC Length', group="Technical parameters", tooltip=t1)
bubbleValue = input.int(defval=180, minval=0, title="ROC Bubble signal", group="Technical parameters", tooltip=t2)
//Risk management
stopLossInput = input.float(defval=6, minval=0, title="Stop Loss (in %)", group="Risk Management", tooltip=t3)
//Money management
fixedRatio = input.int(defval=400, minval=1, title="Fixed Ratio Value ($)", group="Money Management", tooltip=t4)
increasingOrderAmount = input.int(defval=200, minval=1, title="Increasing Order Amount ($)", group="Money Management", tooltip=t5)
//Backtesting period
startDate = input.time(title="Start Date", defval=timestamp("1 Jan 2017 00:00:00"), group="Backtesting Period")
endDate = input.time(title="End Date", defval=timestamp("1 July 2024 00:00:00"), group="Backtesting Period")
//-------------------------------------VARIABLES INITIALISATION-----------------------------//
roc = (close/close[rocLength] - 1)*100
midlineConst = 0
var bool inBubble = na
bool shortBubbleCondition = na
equity = math.abs(strategy.equity - strategy.openprofit)
var float capital_ref = strategy.initial_capital
var float cashOrder = strategy.initial_capital * 0.95
bool inRange = na
//------------------------------CHECKING SOME CONDITIONS ON EACH SCRIPT EXECUTION-------------------------------//
//Checking if the date belong to the range
inRange := inBacktestPeriod(startDate, endDate)
//Checking if we are in a bubble
if roc > bubbleValue and not inBubble
inBubble := true
//Checking if the bubble is over
if roc < 0 and inBubble
inBubble := false
//Checking the condition to short the bubble : The ROC must be above the bubblevalue for at least 1 week
if roc[1]>bubbleValue and roc[2]>bubbleValue and roc[3]>bubbleValue and roc[4]>bubbleValue and roc[5]>bubbleValue and roc[6]>bubbleValue and roc[7]>bubbleValue
shortBubbleCondition := true
//Checking performances of the strategy
if equity > capital_ref + fixedRatio
spread = (equity - capital_ref)/fixedRatio
nb_level = int(spread)
increasingOrder = nb_level * increasingOrderAmount
cashOrder := cashOrder + increasingOrder
capital_ref := capital_ref + nb_level*fixedRatio
if equity < capital_ref - fixedRatio
spread = (capital_ref - equity)/fixedRatio
nb_level = int(spread)
decreasingOrder = nb_level * increasingOrderAmount
cashOrder := cashOrder - decreasingOrder
capital_ref := capital_ref - nb_level*fixedRatio
//Checking if we close all trades in case where we exit the backtesting period
if strategy.position_size!=0 and not inRange
debugLabel("END OF BACKTESTING PERIOD : we close the trade", color=color.rgb(116, 116, 116), loc=roc)
strategy.close_all()
//-------------------------------LONG/SHORT CONDITION-------------------------------//
//Long condition
//We reduce noise by taking signal only if the last roc value is in the same side as the current one
if (strategy.position_size<=0 and ta.crossover(roc, midlineConst)[1] and roc>0 and inRange)
//If we were in a short position, we pass to a long position
qty = cashOrder/close
strategy.entry("Long", strategy.long, qty)
stopLoss = close * (1-stopLossInput/100)
strategy.exit("Long Risk Managment", "Long", stop=stopLoss)
//Short condition
//We take a short position if we are in a bubble and roc is decreasing
if (strategy.position_size>=0 and ta.crossunder(roc, midlineConst)[1] and roc<0 and inRange) or
(strategy.position_size>=0 and inBubble and ta.crossunder(roc, bubbleValue) and shortBubbleCondition and inRange)
//If we were in a long position, we pass to a short position
qty = cashOrder/close
strategy.entry("Short", strategy.short, qty)
stopLoss = close * (1+stopLossInput/100)
strategy.exit("Short Risk Managment", "Short", stop=stopLoss)
//--------------------------------RISK MANAGEMENT--------------------------------------//
//We manage our risk and change the sense of position after SL is hitten
if strategy.position_size == 0 and inRange
//We find the direction of the last trade
id = strategy.closedtrades.entry_id(strategy.closedtrades-1)
if id == "Short"
qty = cashOrder/close
strategy.entry("Long", strategy.long, qty)
stopLoss = close * (1-stopLossInput/100)
strategy.exit("Long Risk Managment", "Long", stop=stopLoss)
else if id =="Long"
qty = cashOrder/close
strategy.entry("Short", strategy.short, qty)
stopLoss = close * (1+stopLossInput/100)
strategy.exit("Short Risk Managment", "Short", stop=stopLoss)
//---------------------------------PLOTTING ELEMENTS---------------------------------------//
//Plotting of ROC
rocPlot = plot(roc, "ROC", color=#7E57C2)
midline = hline(0, "ROC Middle Band", color=color.new(#787B86, 25))
midLinePlot = plot(0, color = na, editable = false, display = display.none)
fill(rocPlot, midLinePlot, 40, 0, top_color = strategy.position_size>0 ? color.new(color.green, 0) : strategy.position_size<0 ? color.new(color.red, 0) : na, bottom_color = strategy.position_size>0 ? color.new(color.green, 100) : strategy.position_size<0 ? color.new(color.red, 100) : na, title = "Positive area")
fill(rocPlot, midLinePlot, 0, -40, top_color = strategy.position_size<0 ? color.new(color.red, 100) : strategy.position_size>0 ? color.new(color.green, 100) : na, bottom_color = strategy.position_size<0 ? color.new(color.red, 0) : strategy.position_size>0 ? color.new(color.green, 0) : na, title = "Negative area")
|
2Mars strategy [OKX] | https://www.tradingview.com/script/nzilXPNB-2Mars-strategy-OKX/ | facejungle | https://www.tradingview.com/u/facejungle/ | 197 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@strategy_alert_message {{strategy.order.alert_message}}
//@version=5
// | ╔══╗╔╗──╔╗╔══╗╔═══╗╔══╗ ____/\_____________ |
// | ╚═╗║║║──║║║╔╗║║╔═╗║║╔═╝ Strategy /\ / \/\ /\ |
// | ╔═╝║║╚╗╔╝║║╚╝║║╚═╝║║╚═╗ /\ __/__\/______\/________ |
// | ║╔═╝║╔╗╔╗║║╔╗║║╔╗╔╝╚═╗║ / \ /\/ |
// | ║╚═╗║║╚╝║║║║║║║║║║─╔═╝║ / \/ |
// | ╚══╝╚╝──╚╝╚╝╚╝╚╝╚╝─╚══╝ / ©facejungle |
// |__________________________/_________________________________|
strategy('2Mars strategy [OKX]',
shorttitle = '2Mars [OKX]',
overlay = true,
initial_capital = 10000,
pyramiding = 3,
currency = currency.USD,
default_qty_type = strategy.percent_of_equity,
default_qty_value = 5,
commission_type = strategy.commission.percent,
commission_value = 0.1,
margin_long = 100.0,
margin_short = 100.0,
max_bars_back = 5000,
calc_on_order_fills = false,
calc_on_every_tick = false,
process_orders_on_close = true,
use_bar_magnifier = false
)
import facejungle/utils/17 as utils
float epsilon = syminfo.mintick
int character_count = int(math.log10(1/epsilon))
float priceMedianHighLow = (high + low) / 2
float priceMedianOpenClose = (open + close) / 2
string GENERAL_GRP = 'General'
float priceSource = input.source(close, 'Source', group=GENERAL_GRP, display = display.none)
int barsConfirm = input.int(2, 'Bars confirm', minval=1, step=1, display = display.none, group=GENERAL_GRP)
string entryTrigger = input.string('close', 'Entry trigger', ['close', 'high/low', 'high/low median', 'open/close median'], group=GENERAL_GRP, display = display.none)
string ST_GRP = "SuperTrend"
bool useSuperTrendSignal = input.bool(false, title='SuperTrend as entry signal', tooltip = 'Not a required! Uses for additional entry to position. For entry will required confirm MA trend', display = display.none, group=ST_GRP)
bool useSuperTrend = input.bool(true, title='SuperTrend confirm', tooltip = 'Not a required! Uses for - Confirm entry to position. Stop-loss confirm. Stop-loss price.', display = display.none, group=ST_GRP)
float superTrendFactor = input.float(4, title="Factor", step=0.1, display = display.none, group=ST_GRP)
int superTrendPeriod = input.int(20, title="Length", display = display.none, group=ST_GRP)
[supertrendOrig, supertrendDirection] = ta.supertrend(superTrendFactor, superTrendPeriod)
float supertrend = ta.rma(supertrendOrig, 4)
string MA_GRP = "Moving average"
bool useMaStrategy = input.bool(true, title='Use MA Cross strategy', tooltip = 'Not a required! Uses for - Entry signal to position when signal and basis line cross (MA Cross strategy). When price cross the MA (add. orders #3).', display = display.none, group=MA_GRP)
string maBasisType = input.string('sma', 'Basis MA type', ['alma', 'ema', 'dema', 'tema', 'sma', 'smma', 'ssma', 'hma', 'rma', 'swma', 'vwma', 'wma', 'linreg', 'median', 'mom', 'high', 'low', 'medianHigh', 'medianLow', 'percentrank'], group=MA_GRP, display = display.none)
string maSignalType = input.string('sma', 'Signal MA type', ['alma', 'ema', 'dema', 'tema', 'sma', 'smma', 'ssma', 'hma', 'rma', 'swma', 'vwma', 'wma', 'linreg', 'median', 'mom', 'high', 'low', 'medianHigh', 'medianLow', 'percentrank'], group=MA_GRP, display = display.none)
float maRatio = input.float(1.08, 'Ratio', minval=0.01, step=0.02, group=MA_GRP, display = display.none)
int maMultiplier = input.int(89, 'Multiplier', minval=1, step=1, group=MA_GRP, tooltip = 'Basis length = Ratio * Multiplier, Signal length = Multiplier', display = display.none)
int maBasisLengh = math.round(maRatio * maMultiplier)
float maBasis = utils.maCustomseries(priceSource, maBasisType, maBasisLengh)
float maSignal = utils.maCustomseries(priceSource, maSignalType, maMultiplier)
string BB_GRP = "Bollinger Bands"
string bbType = input.string('wma', 'Type', ['alma', 'ema', 'dema', 'tema', 'sma', 'smma', 'ssma', 'hma', 'rma', 'swma', 'vwma', 'wma', 'linreg', 'median', 'mom', 'high', 'low', 'medianHigh', 'medianLow', 'percentrank'], tooltip = 'Not a required! Uses for - Take profit. Additionals orders #1 and #2. If use ATR stop-loss, lower and upper line #3 used for stop-loss price update.', group=BB_GRP, display = display.none)
int bbLength = input.int(30, 'length', minval=1, step=1, group=BB_GRP, display = display.none)
float bbMultiplier = input.float(3, minval=1, maxval=50, step=0.1, title="StdDev", group=BB_GRP, display = display.none)
string useBBLong = input.string('lower3', '↗️ Long orders :', ['lower', 'lower2', 'lower3', 'upper', 'upper2', 'upper3', 'off'], inline='Short orders', display = display.none)
string useBBLong2 = input.string('lower2', ' + ', ['lower', 'lower2', 'lower3', 'upper', 'upper2', 'upper3', 'off'], inline='Short orders', display = display.none)
string useBBLong3 = input.string('off', ' + ', ['basis', 'signal', 'off'], inline='Short orders', display = display.none)
string useBBShort = input.string('upper3', '↘️ Short orders:', ['upper', 'upper2', 'upper3', 'lower', 'lower2', 'lower3', 'off'], inline='Long orders', display = display.none)
string useBBShort2 = input.string('upper2', ' + ', ['upper', 'upper2', 'upper3', 'lower', 'lower2', 'lower3', 'off'], inline='Long orders', display = display.none)
string useBBShort3 = input.string('off', ' + ', ['basis', 'signal', 'off'], inline='Long orders', display = display.none)
[bbMiddle, bbUpper, bbUpper2, bbUpper3, bbUpper4, bbLower, bbLower2, bbLower3, bbLower4] = utils.fj_stdev(priceSource, bbLength, bbMultiplier, bbType)
string TP_GRP = "Take-Profit"
string takeProfitTrigger = input.string('close', 'Take-profit trigger', ['close', 'high/low', 'high/low median', 'open/close median'], tooltip = 'Not a required! Take-profit when the Bollinger band 1, 2, 3 crosses', group=TP_GRP, display = display.none)
bool useTakeProfit = input.bool(false, title='Use TP orders', display = display.none, group=TP_GRP)
bool useTakeProfit2 = input.bool(true, title='Use TP orders 2', display = display.none, group=TP_GRP)
bool useTakeProfit3 = input.bool(true, title='Use TP orders 3', display = display.none, group=TP_GRP)
int takeProfitLongQty = input.int(5, '↗️ Long qty %', minval=0, maxval=100, step=2, inline='takeQty', display = display.none, group=TP_GRP)
int takeProfitShortQty = input.int(5, '↘️ Short qty %', minval=0, maxval=100, step=2, inline='takeQty', display = display.none, group=TP_GRP)
string LO_GRP = "Limit-Orders"
bool useLimitOrder = input.bool(false, title='Use limit orders', tooltip = 'Calculate for before each entry order. Long: low price - ATR * Multiplier, Short: high price + ATR * Multiplier', display = display.none, group=LO_GRP)
int limitOrderPeriod = input.int(12, 'Length', minval=1, step=1, tooltip = 'ATR', display = display.none, group=LO_GRP)
float limitOrderMultiplier = input.float(0.1, 'Multiplier', step=0.1, display = display.none, group=LO_GRP)
series float limitOrderAtr = ta.atr(limitOrderPeriod)
var series float limitOrderPrice = na
var array<float>limitBackups = array.new_float(0)
float lastLimitOrderPrice = array.size(limitBackups) > 0 ? array.last(limitBackups) : na
var string limitOrderDirection = 'flat'
float limitOrderPriceLong = useLimitOrder ? math.round(low - (limitOrderAtr * limitOrderMultiplier), character_count) : na
float limitOrderPriceShort = useLimitOrder ? math.round(high + (limitOrderAtr * limitOrderMultiplier), character_count) : na
string SL_GRP = "Stop-Loss"
string stopLossTrigger = input.string('open/close median', 'Stop-loss trigger', ['close', 'high/low', 'high/low median', 'open/close median'], group=SL_GRP, display = display.none)
string stopLossType = input.string('ATR', 'Stop-loss:', ['off', 'SuperTrend + ATR', 'ATR', 'StdDev'], tooltip = 'Update with each entry order and take profit #3. SuperTrend + ATR: update with each trend change not in our favor. If use "SuperTrend confirm", then the stop loss will require confirmation trend change.', group=SL_GRP, display = display.none)
int SLAtrPeriod = input.int(12, title="Length", tooltip = 'ATR and StdDev', display = display.none, group=SL_GRP)
float SLAtrMultiplierLong = input.float(6, title="Long mult.", step=0.1, tooltip = 'ATR: low - ATR * Long mult. / SuperTrend: SuperTrend - ATR * Long mult. / StdDev: low - StdDev - ATR * Long mult.', display = display.none, group=SL_GRP)
float SLAtrMultiplierShort = input.float(4.3, title="Short mult.", step=0.1, tooltip = 'ATR: high + ATR * Short mult. / SuperTrend: SuperTrend + ATR * Short mult. / StdDev: high + StdDev + ATR * Short mult.', display = display.none, group=SL_GRP)
series float stopLossAtr = ta.atr(SLAtrPeriod)
series float stopLossStdDev = ta.stdev(priceSource, SLAtrPeriod)
bool useFlexStopLoss = input.bool(false, title='Use flex stop-loss for ATR and StdDev', tooltip = 'If the SuperTrend or MA trend changes not in our favor, then adjusting the stop loss.', display = display.none, group=SL_GRP)
float SLFlexMult = input.float(0, step=0.1, title="Multiplier", tooltip = 'Long: stop-loss price + (ATR * Long mult.) * Multiplier. Short: stop-loss price - (ATR * Short mult.) * Multiplier.', display = display.none, group=SL_GRP)
var series float stopLossPriceLong = na
var series float stopLossPriceShort = na
float calcStopLossPriceLong =
stopLossType == 'SuperTrend + ATR' ? math.round(supertrend[1] - (stopLossAtr * SLAtrMultiplierLong), character_count) :
stopLossType == 'ATR' ? math.round(low - (stopLossAtr * SLAtrMultiplierLong), character_count):
stopLossType == 'StdDev' ? math.round(low - stopLossStdDev - (stopLossAtr * SLAtrMultiplierLong), character_count) :
na
float calcStopLossPriceShort =
stopLossType == 'SuperTrend + ATR' ? math.round(supertrend[1] + (stopLossAtr * SLAtrMultiplierShort), character_count) :
stopLossType == 'ATR' ? math.round(high + (stopLossAtr * SLAtrMultiplierShort), character_count) :
stopLossType == 'StdDev' ? math.round(high + stopLossStdDev + (stopLossAtr * SLAtrMultiplierShort), character_count) :
na
string ALERT_GRP = "OKX alerts"
string okx_signalToken = input("signal_token", "Signal Token _______________________________", group = ALERT_GRP, display = display.none)
string okx_entryInvestmentType = input.string("percentage_balance", "Investment Type", options = ["margin", "contract", "percentage_balance", "percentage_investment"], tooltip = 'margin - Invested margin in quote currency. contract - Fixed number of contracts. percentage_balance - Based on the % of Available Balance (i.e., the margin available for opening new orders). percentage_investment - Based on the % of Initial Invested Margin upon bot creation', display = display.none, group = ALERT_GRP)
float okx_amount = input.float(5, "Amount", minval = 0.01, display = display.none, group = ALERT_GRP)
string okx_entryType = useLimitOrder ? 'limit' : 'market'
string okx_entryPriceOffset = useLimitOrder ? lastLimitOrderPrice < close ? str.tostring(100 - (lastLimitOrderPrice / close) * 100) : str.tostring(100 - (close / lastLimitOrderPrice) * 100) : ''
string msgFreq = alert.freq_once_per_bar_close
string msgOpenLong = utils.okxAlertMsg(
action = 'ENTER_LONG',
signalToken = okx_signalToken,
orderType = okx_entryType,
orderPriceOffset = okx_entryPriceOffset,
investmentType = okx_entryInvestmentType,
amount = str.tostring(okx_amount)
)
string msgOpenShort = utils.okxAlertMsg(
action = 'ENTER_SHORT',
signalToken = okx_signalToken,
orderType = okx_entryType,
orderPriceOffset = okx_entryPriceOffset,
investmentType = okx_entryInvestmentType,
amount = str.tostring(okx_amount)
)
string msgTakeProfitLong = utils.okxAlertMsg(
action = 'EXIT_LONG',
signalToken = okx_signalToken,
orderType = "market",
orderPriceOffset = "",
investmentType = "percentage_position",
amount = str.tostring(takeProfitLongQty)
)
string msgTakeProfitShort = utils.okxAlertMsg(
action = 'EXIT_SHORT',
signalToken = okx_signalToken,
orderType = "market",
orderPriceOffset = "",
investmentType = "percentage_position",
amount = str.tostring(takeProfitShortQty)
)
string msgStopLossLong = utils.okxAlertMsg(
action = 'EXIT_LONG',
signalToken = okx_signalToken,
orderType = "market",
orderPriceOffset = "",
investmentType = "percentage_position",
amount = "100"
)
string msgStopLossShort = utils.okxAlertMsg(
action = 'EXIT_SHORT',
signalToken = okx_signalToken,
orderType = "market",
orderPriceOffset = "",
investmentType = "percentage_position",
amount = "100"
)
// _________________________________________________
// v v
// v COUNTERS v
// v_______________________________________________v
counterEvent(bool enent, bool enent2) =>
int scount = 0
scount := enent and enent2 ? nz(scount[1]) + 1 : 0
barCrossoverCounter(float signalPrice, float basePrice) =>
bool bcond = signalPrice > basePrice
int bcount = 0
bcount := bcond ? nz(bcount[1]) + 1 : 0
barCrossunderCounter(float signalPrice, float basePrice) =>
bool scond = signalPrice < basePrice
int scount = 0
scount := scond ? nz(scount[1]) + 1 : 0
// _________________________________________________
// v v
// v CONDITIONS BLOCK v
// v_______________________________________________v
float entryTriggerLong = entryTrigger == 'high/low' ? high : entryTrigger == 'high/low median' ? priceMedianHighLow : entryTrigger == 'open/close median' ? priceMedianOpenClose : close
bool condPositionLong = strategy.position_size > 0
bool condSuperTrendLong = supertrendDirection < 0
bool condSuperTrendLongSignal = barsConfirm == barCrossunderCounter(supertrendDirection, 0)
bool condMaLong = barsConfirm == barCrossoverCounter(maSignal, maBasis)
bool condBasisLong = barsConfirm == barCrossoverCounter(entryTriggerLong, maBasis)
bool condSignalLong = barsConfirm == barCrossoverCounter(entryTriggerLong, maSignal)
bool condBBLong1 = barsConfirm == barCrossoverCounter(entryTriggerLong, bbLower)
bool condBBLong2 = barsConfirm == barCrossoverCounter(entryTriggerLong, bbLower2)
bool condBBLong3 = barsConfirm == barCrossoverCounter(entryTriggerLong, bbLower3)
bool condBBLong4 = barsConfirm == barCrossoverCounter(entryTriggerLong, bbUpper)
bool condBBLong5 = barsConfirm == barCrossoverCounter(entryTriggerLong, bbUpper2)
bool condBBLong6 = barsConfirm == barCrossoverCounter(entryTriggerLong, bbUpper3)
float entryTriggerShort = entryTrigger == 'high/low' ? low : entryTrigger == 'high/low median' ? priceMedianHighLow : entryTrigger == 'open/close median' ? priceMedianOpenClose : close
bool condPositionShort = strategy.position_size < 0
bool condSuperTrendShort = supertrendDirection > 0
bool condSuperTrendShortSignal = barsConfirm == barCrossoverCounter(supertrendDirection, 0)
bool condMaShort = barsConfirm == barCrossunderCounter(maSignal, maBasis)
bool condBasisShort = barsConfirm == barCrossunderCounter(entryTriggerShort, maBasis)
bool condSignalShort = barsConfirm == barCrossunderCounter(entryTriggerShort, maSignal)
bool condBBShort1 = barsConfirm == barCrossunderCounter(entryTriggerShort, bbUpper)
bool condBBShort2 = barsConfirm == barCrossunderCounter(entryTriggerShort, bbUpper2)
bool condBBShort3 = barsConfirm == barCrossunderCounter(entryTriggerShort, bbUpper3)
bool condBBShort4 = barsConfirm == barCrossunderCounter(entryTriggerShort, bbLower)
bool condBBShort6 = barsConfirm == barCrossunderCounter(entryTriggerShort, bbLower3)
bool condBBShort5 = barsConfirm == barCrossunderCounter(entryTriggerShort, bbLower2)
// _________________________________________________
// v v
// v TRADING FUNCTIONS BLOCK v
// v_______________________________________________v
stopLossShort(string orderComment=na) =>
strategy.cancel('Short') // cancel short orders
strategy.close ('Short', qty_percent = 100, comment = na(orderComment) == false ? orderComment : na, alert_message = msgStopLossShort)
stopLossLong(string orderComment=na) =>
strategy.cancel('Long') // cancel long orders
strategy.close ('Long', qty_percent = 100, comment = na(orderComment) == false ? orderComment : na, alert_message = msgStopLossLong)
// >>>>>>>>>>>>>>>>>>>>>> Function for entry to long position
newEntryLong(string orderComment=na) =>
if condPositionShort
stopLossShort('Close short')
strategy.entry(
'Long',
strategy.long,
stop = stopLossType != 'off' ? stopLossPriceLong : na,
limit = useLimitOrder ? limitOrderPriceLong : na,
comment = na(orderComment) == false ? orderComment : na,
alert_message = msgOpenLong
)
// >>>>>>>>>>>>>>>>>>>>>> Function for entry to short position
newEntryShort(string orderComment=na) =>
if condPositionLong
stopLossLong('Close short')
strategy.entry(
'Short',
strategy.short,
stop = stopLossType != 'off' ? stopLossPriceShort : na,
limit = useLimitOrder ? limitOrderPriceShort : na,
comment = na(orderComment) == false ? orderComment : na,
alert_message = msgOpenShort
)
// >>>>>>>>>>>>>>>>>>>>>>
takeLong(string orderComment=na) =>
strategy.close('Long', qty_percent = takeProfitLongQty, comment = na(orderComment) == false ? orderComment : na, alert_message = msgTakeProfitLong)
// >>>>>>>>>>>>>>>>>>>>>>
takeShort(string orderComment=na) =>
strategy.close('Short', qty_percent = takeProfitShortQty, comment = na(orderComment) == false ? orderComment : na, alert_message = msgTakeProfitShort)
// _________________________________________________
// v v
// v POSITION ENTRIES BLOCK v
// v_______________________________________________v
if useSuperTrendSignal
if condSuperTrendLongSignal and maSignal > maBasis
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong(orderComment=utils.commentOrderCustomseries('enter_long', 'supertrend'))
if condSuperTrendShortSignal and maSignal < maBasis
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('enter_short', 'supertrend'))
if useSuperTrend
// >>>>>>>>>>>>>>>>>>>>>> LONG ORDERS WITH SuperTrend
//-> Additionals ordrders #1-2
if useBBLong == 'lower' or useBBLong2 == 'lower'
if condBBLong1 and condSuperTrendLong
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong(orderComment=utils.commentOrderCustomseries('enter_long', 'bbLower' ))
if useBBLong == 'lower2' or useBBLong2 == 'lower2'
if condBBLong2 and condSuperTrendLong
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong(orderComment=utils.commentOrderCustomseries('enter_long', 'bbLower2'))
if useBBLong == 'lower3' or useBBLong2 == 'lower3'
if condBBLong3 and condSuperTrendLong
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong(orderComment=utils.commentOrderCustomseries('enter_long', 'bbLower3'))
if useBBLong == 'upper' or useBBLong2 == 'upper'
if condBBLong4 and condSuperTrendLong
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong(orderComment=utils.commentOrderCustomseries('enter_long', 'bbUpper'))
if useBBLong == 'upper2' or useBBLong2 == 'upper2'
if condBBLong5 and condSuperTrendLong
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong( orderComment=utils.commentOrderCustomseries('enter_long', 'bbUpper2'))
if useBBLong == 'upper3' or useBBLong2 == 'upper3'
if condBBLong6 and condSuperTrendLong
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong(orderComment=utils.commentOrderCustomseries('enter_long', 'bbUpper3'))
//-> Additionals ordrders #3
if useBBLong3 == 'basis'
if condBasisLong and condSuperTrendLong
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong(orderComment=utils.commentOrderCustomseries('enter_long', 'maBasis'))
if useBBLong3 == 'signal'
if condSignalLong and condSuperTrendLong
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong(orderComment=utils.commentOrderCustomseries('enter_long', 'maSignal'))
//-> cross ma strategy
if useMaStrategy and condSuperTrendLong and condMaLong
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong(orderComment=utils.commentOrderCustomseries('enter_long', 'maCross'))
// >>>>>>>>>>>>>>>>>>>>>> SHORT ORDERS WITH SuperTrend
//-> Additionals ordrders #1-2
if useBBShort == 'upper' or useBBShort2 == 'upper'
if condBBShort1 and condSuperTrendShort
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('enter_short', 'bbUpper'))
if useBBShort == 'upper2' or useBBShort2 == 'upper2'
if condBBShort2 and condSuperTrendShort
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('enter_short', 'bbUpper2'))
if useBBShort == 'upper3' or useBBShort2 == 'upper3'
if condBBShort3 and condSuperTrendShort
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('enter_short', 'bbUpper3'))
if useBBShort == 'lower' or useBBShort2 == 'lower'
if condBBShort4 and condSuperTrendShort
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('enter_short', 'bbLower'))
if useBBShort == 'lower2' or useBBShort2 == 'lower2'
if condBBShort5 and condSuperTrendShort
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('enter_short', 'bbLower2'))
if useBBShort == 'lower3' or useBBShort2 == 'lower3'
if condBBShort6 and condSuperTrendShort
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('enter_short', 'bbLower3'))
//-> Additionals ordrders #3
if useBBShort3 == 'basis'
if condBasisShort and condSuperTrendShort
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('enter_short', 'maBasis'))
if useBBShort3 == 'signal'
if condSignalShort and condSuperTrendShort
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('enter_short', 'maSignal'))
//-> cross ma strategy
if useMaStrategy and condSuperTrendShort and condMaShort
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('enter_short', 'maCross'))
else
// >>>>>>>>>>>>>>>>>>>>>> LONG ORDERS
//vvvvvvvvv Additionals ordrders #1-2 vvvvvvvvv
if useBBLong == 'lower' or useBBLong2 == 'lower'
if condBBLong1
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong(orderComment=utils.commentOrderCustomseries('enter_long', 'bbLower'))
if useBBLong == 'lower2' or useBBLong2 == 'lower2'
if condBBLong2
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong(orderComment=utils.commentOrderCustomseries('enter_long', 'bbLower2'))
if useBBLong == 'lower3' or useBBLong2 == 'lower3'
if condBBLong3
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong(orderComment=utils.commentOrderCustomseries('enter_long', 'bbLower3'))
if useBBLong == 'upper' or useBBLong2 == 'upper'
if condBBLong4
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong(orderComment=utils.commentOrderCustomseries('enter_long', 'bbUpper'))
if useBBLong == 'upper2' or useBBLong2 == 'upper2'
if condBBLong5
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong(orderComment=utils.commentOrderCustomseries('enter_long', 'bbUpper2'))
if useBBLong == 'upper3' or useBBLong2 == 'upper3'
if condBBLong6
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong(orderComment=utils.commentOrderCustomseries('enter_long', 'bbUpper3'))
//vvvvvvvvv Additionals ordrders #3 vvvvvvvvv
if useBBLong3 == 'basis'
if condBasisLong
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong(orderComment=utils.commentOrderCustomseries('enter_long', 'maBasis'))
if useBBLong3 == 'signal'
if condSignalLong
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong(orderComment=utils.commentOrderCustomseries('enter_long', 'maSignal'))
//vvvvvvvvv cross ma strategy vvvvvvvvv
if useMaStrategy and condMaLong
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong(orderComment=utils.commentOrderCustomseries('enter_long', 'maCross'))
// >>>>>>>>>>>>>>>>>>>>>> SHORT ORDERS
//vvvvvvvvv Additionals ordrders #1-2 vvvvvvvvv
if useBBShort == 'upper' or useBBShort2 == 'upper'
if condBBShort1
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('Short', 'bbUpper'))
if useBBShort == 'upper2' or useBBShort2 == 'upper2'
if condBBShort2
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('Short', 'bbUpper2'))
if useBBShort == 'upper3' or useBBShort2 == 'upper3'
if condBBShort3
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('Short', 'bbUpper3'))
if useBBShort == 'lower' or useBBShort2 == 'lower'
if condBBShort4
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('Short', 'bbLower'))
if useBBShort == 'lower2' or useBBShort2 == 'lower2'
if condBBShort5
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('Short', 'bbLower2'))
if useBBShort == 'lower3' or useBBShort2 == 'lower3'
if condBBShort6
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('Short', 'bbLower3'))
//vvvvvvvvv Additionals ordrders #3 vvvvvvvvv
if useBBShort3 == 'basis'
if condBasisShort
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('Short', 'maBasis'))
if useBBShort3 == 'signal'
if condSignalShort
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('Short', 'maSignal'))
//vvvvvvvvv Cross MA strategy vvvvvvvvv
if useMaStrategy and condMaShort
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('Short', 'maCross'))
if na(limitOrderPrice) == false
array.push(limitBackups, limitOrderPrice)
// _________________________________________________
// v v
// v TAKE PROFIT BLOCK v
// v_______________________________________________v
// >>>>>>>>>>>>>>>>>>>>>> Conditions
float takeTriggerLong = takeProfitTrigger == 'high/low' ? high : takeProfitTrigger == 'high/low median' ? priceMedianHighLow : takeProfitTrigger == 'open/close median' ? priceMedianOpenClose : close
bool condTakePriceLong = strategy.position_avg_price < close
bool condTakeLong1 = ta.crossover(takeTriggerLong, bbUpper[1]) and condPositionLong
bool condTakeLong2 = ta.crossover(takeTriggerLong, bbUpper2[1]) and condPositionLong
bool condTakeLong3 = ta.crossover(takeTriggerLong, bbUpper3[1]) and condPositionLong
float takeTriggerhort = takeProfitTrigger == 'high/low' ? low : takeProfitTrigger == 'high/low median' ? priceMedianHighLow : takeProfitTrigger == 'open/close median' ? priceMedianOpenClose : close
bool condTakePriceShort = strategy.position_avg_price > close
bool condTakeShort1 = ta.crossunder(takeTriggerhort, bbLower[1]) and condPositionShort
bool condTakeShort2 = ta.crossunder(takeTriggerhort, bbLower2[1]) and condPositionShort
bool condTakeShort3 = ta.crossunder(takeTriggerhort, bbLower3[1]) and condPositionShort
// >>>>>>>>>>>>>>>>>>>>>> Use take profit
if useTakeProfit
if condTakeLong1 and condTakePriceLong
takeLong(utils.commentOrderCustomseries('take_long', 'bbUpper', qty = takeProfitLongQty))
if condTakeShort1 and condTakePriceShort
takeShort(utils.commentOrderCustomseries('take_short', 'bbLower', qty = takeProfitShortQty))
// >>>>>>>>>>>>>>>>>>>>>> Use take profit 2
if useTakeProfit2
if condTakeLong2 and condTakePriceLong
takeLong(utils.commentOrderCustomseries('take_long', 'bbUpper2', qty = takeProfitLongQty))
if condTakeShort2 and condTakePriceShort
takeShort(utils.commentOrderCustomseries('take_short', 'bbLower2', qty = takeProfitShortQty))
// >>>>>>>>>>>>>>>>>>>>>> Use take profit 3
if useTakeProfit3
if condTakeLong3 and condTakePriceLong
stopLossPriceLong := calcStopLossPriceLong
takeLong(utils.commentOrderCustomseries('take_long', 'bbUpper3', qty = takeProfitLongQty))
if condTakeShort3 and condTakePriceShort
stopLossPriceShort := calcStopLossPriceShort
takeShort(utils.commentOrderCustomseries('take_short', 'bbLower3', qty = takeProfitShortQty))
// _________________________________________________
// v v
// v STOP LOSS BLOCK v
// v_______________________________________________v
// >>>>>>>>>>>>>>>>>>>>>> Conditions
bool condStopSuperTrendLong = barCrossoverCounter(supertrendDirection, 0) == 1 and condPositionLong
bool condStopSuperTrendShort = barCrossunderCounter(supertrendDirection, 0) == 1 and condPositionShort
bool condStopFlexSuperTrendLong = counterEvent(condPositionLong, condSuperTrendShort) == 1
bool condStopFlexMaLong = counterEvent(condPositionLong, condMaShort) == 1
bool condStopFlexSuperTrendShort = counterEvent(condPositionShort, condSuperTrendLong) == 1
bool condStopFlexMaShort = counterEvent(condPositionShort, condMaLong) == 1
// >>>>>>>>>>>>>>>>>>>>>> Setting stop loss price for SuperTrend option
if stopLossType == 'SuperTrend + ATR'
if condStopSuperTrendLong
stopLossPriceLong := supertrend[1] - (stopLossAtr * SLAtrMultiplierLong)
if stopLossType == 'SuperTrend + ATR'
if condStopSuperTrendShort
stopLossPriceShort := supertrend[1] + (stopLossAtr * SLAtrMultiplierShort)
// >>>>>>>>>>>>>>>>>>>>>> Setting flex stop loss price for ATR and StdDev options
if useFlexStopLoss
if stopLossType == 'ATR' or stopLossType == 'StdDev'
if condStopFlexSuperTrendLong
stopLossPriceLong := stopLossPriceLong + (stopLossAtr * SLAtrMultiplierLong) * SLFlexMult
if condStopFlexMaLong
stopLossPriceLong := stopLossPriceLong + (stopLossAtr * SLAtrMultiplierLong) * SLFlexMult
if condStopFlexSuperTrendShort
stopLossPriceShort := stopLossPriceShort - (stopLossAtr * SLAtrMultiplierLong) * SLFlexMult
if condStopFlexMaShort
stopLossPriceShort := stopLossPriceShort - (stopLossAtr * SLAtrMultiplierLong) * SLFlexMult
// >>>>>>>>>>>>>>>>>>>>>> Trading logic
float stopTriggerLong = stopLossTrigger == 'high/low' ? low : stopLossTrigger == 'high/low median' ? priceMedianHighLow : stopLossTrigger == 'open/close median' ? priceMedianOpenClose : close
bool condStopLong = stopTriggerLong < stopLossPriceLong and condPositionLong
float stopTriggerShort = stopLossTrigger == 'high/low' ? high : stopLossTrigger == 'high/low median' ? priceMedianHighLow : stopLossTrigger == 'open/close median' ? priceMedianOpenClose : close
bool condStopShort = stopTriggerShort > stopLossPriceShort and condPositionShort
if stopLossType != 'off'
if useSuperTrend
if condStopLong and condSuperTrendShort
stopLossLong(utils.commentOrderCustomseries('stop_long', 'stop'))
if limitOrderDirection == 'Long'
limitOrderPrice := na
limitOrderDirection := 'flat'
if condStopShort and condSuperTrendLong
if limitOrderDirection == 'Short'
limitOrderPrice := na
limitOrderDirection := 'flat'
stopLossShort(utils.commentOrderCustomseries('stop_short', 'stop'))
else
if condStopLong
if limitOrderDirection == 'Long'
limitOrderPrice := na
limitOrderDirection := 'flat'
stopLossLong(utils.commentOrderCustomseries('stop_long', 'stop'))
if condStopShort
if limitOrderDirection == 'Short'
limitOrderPrice := na
limitOrderDirection := 'flat'
stopLossShort(utils.commentOrderCustomseries('stop_short', 'stop'))
// _________________________________________________
// v v
// v LIMIT ORDER BLOCK v
// v_______________________________________________v
// >>>>>>>>>>>>>>>>>>>>>> Conditions
bool condLimitPrirceExist = na(limitOrderPrice) == false
// >>>>>>>>>>>>>>>>>>>>>> limit orders triggered
if useLimitOrder and condLimitPrirceExist
for i = 1 to strategy.opentrades
if math.abs(limitOrderPrice - strategy.opentrades.entry_price(strategy.opentrades - i)) < epsilon
limitOrderPrice := na
limitOrderDirection := 'flat'
// _________________________________________________
// v v
// v PLOT BLOCK v
// v_______________________________________________v
colorGreen = #00ff08cc
colorGreen2 = #00ff0863
colorGreen3 = #089981
colorRed = #ff0000d4
colorRed2 = #ff000071
colorPurple = #8400ff23
colorPurple2 = #45008657
colorPurple3 = #8400ff09
colorOrange = #f57b00c7
colorBlack = color.rgb(70, 70, 70, 50)
// >>>>>>>>>>>>>>>>>>>>>> SuperTrend
pPriceMedian = plot(useSuperTrend ? priceMedianOpenClose : na, "[Price Median]", color=color.black, linewidth=1, style=plot.style_line, display=display.none)
pSuperTrend = plot(useSuperTrend ? supertrend : na, "[SuperTrend]", color=condSuperTrendLong ? colorGreen2 : colorRed2, linewidth=2, style=plot.style_line, display=useSuperTrend ? display.pane : display.none)
fill(pPriceMedian, pSuperTrend, title = "[SuperTrend] Background", color = condSuperTrendLong ? color.rgb(0, 255, 8, 90) : color.rgb(255, 0, 0, 90), display = display.all)
// >>>>>>>>>>>>>>>>>>>>>> Moving Averages
basis = plot(maBasis, "[MA] Basis", color = maSignal > maBasis ? colorGreen2 : colorRed2, linewidth=1, style=plot.style_line, display=display.pane)
signal = plot(maSignal, "[MA] Signal", color = maSignal > maBasis ? colorGreen2 : colorRed2, linewidth=1, style=plot.style_line, display=display.pane)
plot(ta.crossover(maSignal, maBasis) ? maBasis : na, "[MA] Long signal", color=colorGreen, style = plot.style_circles, linewidth = 4, display=display.pane)
plot(ta.crossunder(maSignal, maBasis) ? maBasis : na, "[MA] Short signal", color=colorRed, style = plot.style_circles, linewidth = 4, display=display.pane)
fill(basis, signal, title = "[MA] Background", color = maSignal > maBasis ? colorGreen2 : colorRed2, display = display.all)
// >>>>>>>>>>>>>>>>>>>>>> Stop loss
bool plotCondStopLossLong = useSuperTrend ? condPositionLong and condSuperTrendShort : condPositionLong
bool plotCondStopLossShort = useSuperTrend ? condPositionShort and condSuperTrendLong : condPositionShort
plot(condPositionLong? stopLossPriceLong : na, "Stop-loss price: Long", color=plotCondStopLossLong ? colorRed : colorOrange, style = plot.style_linebr, linewidth = 2, display=display.none)
plot(condPositionShort? stopLossPriceShort : na, "Stop-loss price: Short", color=plotCondStopLossShort ? colorRed : colorOrange, style = plot.style_linebr, linewidth = 2, display=display.none)
// >>>>>>>>>>>>>>>>>>>>>> Bollinger bands
u1 = plot(bbUpper, "[BB] Upper", color=colorPurple, display = display.pane)
l1 = plot(bbLower, "[BB] Lower", color=colorPurple, display = display.pane)
u2 = plot(bbUpper2, "[BB] Upper 2", color=colorPurple, display = display.pane)
l2 = plot(bbLower2, "[BB] Lower 2", color=colorPurple, display = display.pane)
u3 = plot(bbUpper3, "[BB] Upper 2", color=colorPurple, display = display.pane)
l3 = plot(bbLower3, "[BB] Lower 2", color=colorPurple, display = display.pane)
fill(u1, l1, title = "[BB] Background 1-1", color=colorPurple3, display = display.all)
fill(u2, l2, title = "[BB] Background 2-2", color=colorPurple3, display = display.all)
fill(u3, l3, title = "[BB] Background 3-3", color=colorPurple3, display = display.all)
// _________________________________________________
// v v
// v CURRENT POSITION BLOCK v
// v_______________________________________________v
var string currentPosition = 'flat'
currentPosition := strategy.position_size > 0 ? 'Long ↗' : 'Short ↘'
if strategy.position_size == 0
currentPosition := 'flat'
bool condPositionExist = currentPosition == 'Long ↗' or currentPosition == 'Short ↘'
float lastEntryPrice = strategy.opentrades.entry_price(strategy.opentrades - 1)
// >>>>>>>>>>>>>>>>>>>>>> Position table
var table positionTable = table.new(position = position.top_right, columns = 2, rows = 5)
table.cell(table_id = positionTable, column = 1, row = 0, text = "Position", bgcolor=colorBlack, text_color=color.white, text_halign = text.align_right, tooltip = strategy.opentrades == 1 ? strategy.opentrades.entry_comment(strategy.opentrades - 1) : na)
table.clear(positionTable, 0, 1, 1, 4)
table.cell(table_id = positionTable, column = 0, row = 1, text = "Direction:", bgcolor=colorBlack, text_color=color.white, text_halign = text.align_left)
table.cell(table_id = positionTable, column = 1, row = 1, text = currentPosition, bgcolor=strategy.opentrades == 0 ? colorBlack : condPositionShort ? colorRed2 : colorGreen3, text_color=color.rgb(255, 255, 255), text_halign = text.align_right)
if condPositionExist
table.cell(table_id = positionTable, column = 0, row = 2, text = "Amount:", bgcolor=colorBlack, text_color=color.white, text_halign = text.align_left)
table.cell(table_id = positionTable, column = 1, row = 2, text =str.tostring(strategy.position_size), bgcolor=colorBlack, text_color=color.white, text_halign = text.align_right)
if strategy.opentrades > 1
table.cell(table_id = positionTable, column = 0, row = 3, text = "Avg. price:", bgcolor=colorBlack, text_color=color.white, text_halign = text.align_left)
table.cell(table_id = positionTable, column = 1, row = 3, text =str.tostring(strategy.position_avg_price, '#.###'), bgcolor=colorBlack, text_color=color.white, text_halign = text.align_right)
if strategy.opentrades == 1
table.cell(table_id = positionTable, column = 0, row = 3, text = "Entry price:", bgcolor=colorBlack, text_color=color.white, text_halign = text.align_left, tooltip = strategy.opentrades == 1 ? strategy.opentrades.entry_comment(strategy.opentrades - 1) : na)
table.cell(table_id = positionTable, column = 1, row = 3, text =str.tostring(strategy.opentrades.entry_price(strategy.opentrades - 1), '#.###'), bgcolor=colorBlack, text_color=color.white, text_halign = text.align_right)
if stopLossType != 'off'
table.cell(table_id = positionTable, column = 0, row = 4, text = "Stop Loss:", bgcolor=colorBlack, text_color=color.white)
table.cell(table_id = positionTable, column = 1, row = 4, text =str.tostring(strategy.position_size > 0 ? stopLossPriceLong : stopLossPriceShort, '#.###'), bgcolor=colorBlack, text_color=color.white)
// >>>>>>>>>>>>>>>>>>>>>> Entries table
var table entriesTable = table.new(position = position.middle_right, columns = 2, rows = 6)
if strategy.opentrades > 1 and strategy.opentrades < 5
table.cell(table_id = entriesTable, column = 1, row = 0, text = "Entries", bgcolor=colorBlack, text_color=color.white, text_halign = text.align_right)
table.clear(entriesTable, 0, 1, 1, 5)
for i = 1 to strategy.opentrades by 1
table.cell(table_id = entriesTable, column = 0, row = 0 + i, text = '#' + str.tostring(i), bgcolor=colorBlack, text_color=color.white, text_halign = text.align_left)
table.cell(table_id = entriesTable, column = 1, row = 0 + i, text =str.tostring(strategy.opentrades.entry_price(strategy.opentrades - i)) + ' 💬', bgcolor=colorBlack, text_color=color.white, text_halign = text.align_right, tooltip = strategy.opentrades.entry_comment(strategy.opentrades - i))
else if strategy.opentrades <= 1
table.clear(entriesTable, 0, 0, 1, 5)
// >>>>>>>>>>>>>>>>>>>>>> Limit Order table
if useLimitOrder
var table limitOrderTable = table.new(position = position.bottom_right, columns = 2, rows = 3)
table.clear(limitOrderTable, 0, 0, 1, 2)
if na(limitOrderPrice) == false
table.cell(table_id = limitOrderTable, column = 1, row = 0, text = "Limit order", bgcolor=colorBlack, text_color=color.white, text_halign = text.align_right)
table.cell(table_id = limitOrderTable, column = 0, row = 1, text = "Direction:", bgcolor=colorBlack, text_color=color.white, text_halign = text.align_left)
table.cell(table_id = limitOrderTable, column = 1, row = 1, text =str.tostring(limitOrderDirection), bgcolor=limitOrderDirection == 'Short' ? colorRed2 : colorGreen3, text_color=color.white, text_halign = text.align_right)
table.cell(table_id = limitOrderTable, column = 0, row = 2, text = "Price:", bgcolor=colorBlack, text_color=color.white, text_halign = text.align_left)
table.cell(table_id = limitOrderTable, column = 1, row = 2, text =str.tostring(limitOrderPrice), bgcolor=colorBlack, text_color=color.white, text_halign = text.align_right) |
Machine Learning: SuperTrend Strategy TP/SL [YinYangAlgorithms] | https://www.tradingview.com/script/9Mm3qKME-Machine-Learning-SuperTrend-Strategy-TP-SL-YinYangAlgorithms/ | YinYangAlgorithms | https://www.tradingview.com/u/YinYangAlgorithms/ | 262 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ,@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ .@@@@@@@@@@@@@@@ @@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ *@@@@@@@@@@@@@@ @@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@. @@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@. @
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@, @
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @
// @@@@@@@@@@@@@@@@@@@@@@@@@@@ @
// @@@@@@@@@@@@@@@@@@@@@@@@@ @@
// @@@@@@@@@@@@@@@@@@@@@@@ @@
// @@@@@@@@@@@@@@@@@@@@@@ @@@
// @@@@@@@@@@@@@@@@@@@@@* @@@@@ @@@@
// @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@ @@@@@
// @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@
// @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@% @@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@ %@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// © YinYangAlgorithms
//@version=5
strategy("Machine Learning: SuperTrend Strategy - Trailing Take Profit and Stop Loss [YinYangAlgorithms]", overlay=true, initial_capital=1000000, default_qty_type=strategy.percent_of_equity, default_qty_value=100)
// ~~~~~~~~~~~~ INPUTS ~~~~~~~~~~~~ //
//Supertrend
atrPeriod = input.int(4, "ATR Length", minval = 1, group="Supertrend", tooltip="ATR Length used to create the Original Supertrend.")
factor = input.float(2.94, "Factor", minval = 0.01, step = 0.01, group="Supertrend", tooltip="Multiplier used to create the Original Supertrend.")
stoplossMult = input.float(0.0000025, "Stop Loss Multiplier", group="Supertrend", tooltip="0 = Don't use Stop Loss. Stop loss can be useful for helping to prevent false signals but also may result in more loss when hit and less profit when switching trends.")
takeprofitMult = input.float(0.022, "Take Profit Multiplier", group="Supertrend", tooltip="Take Profits can be useful within the Supertrend Strategy to stop the price reverting all the way to the Stop Loss once it's been profitable.")
//Machine Learning
onlyUseSameTrendDirections = input.bool(true, "Only Factor Same Trend Direction", group="Machine Learning", tooltip="Very useful for ensuring that data used in KNN is not manipulated by different SuperTrend Directional data. Please note, it doesn't effect KNN Exponential.")
useRationalQudratics = input.string("All", "Rationalized Source Type", options=["All", "Close", "HL2", "ATR", "None"], group="Machine Learning", tooltip="Should we Rationalize only a specific source, All or None?")
useMachineLearning = input.string("KNN Average", "Machine Learning Type", options=["KNN Average", "KNN Exponential Average", "Simple Average", "None"], group="Machine Learning", tooltip="Are we using a Simple ML Average, KNN Mean Average, KNN Exponential Average or None?")
distanceType = input.string("Both", "KNN Distance Type", options=["Both", "Max", "Min"], group="Machine Learning", tooltip="We need to check if distance is within the KNN Min/Max distance, which distance checks are we using.")
mlType = input.string("SMA", "Machine Learning Smoothing Type", options=["SMA", "EMA", "VWMA"], group="Machine Learning" ,tooltip="How should we smooth our Fast and Slow ML Datas to be used in our KNN Distance calculation? SMA, EMA or VWMA?")
mlLength = input.int(100, "Machine Learning Length", group="Machine Learning", tooltip="How far back is our Machine Learning going to keep data for.")
knnLength = input.int(2, "k-Nearest Neighbour (KNN) Length", group="Machine Learning", tooltip="How many k-Nearest Neighbours will we account for?")
fastLength = input.int(3, "Fast ML Data Length", group="Machine Learning", tooltip="What is our Fast ML Length?? This is used with our Slow Length to create our KNN Distance.")
slowLength = input.int(50, "Slow ML Data Length", group="Machine Learning", tooltip="What is our Slow ML Length?? This is used with our Fast Length to create our KNN Distance.")
// ~~~~~~~~~~~~ VARIABLES ~~~~~~~~~~~~ //
rationalizeHL2 = useRationalQudratics == "HL2" or useRationalQudratics == "All"
rationalizeClose = useRationalQudratics == "Close" or useRationalQudratics == "All"
rationalizeATR = useRationalQudratics == "ATR" or useRationalQudratics == "All"
distanceTypeMin = distanceType == "Min" or distanceType == "Both"
distanceTypeMax = distanceType == "Max" or distanceType == "Both"
// ~~~~~~~~~~~~ FUNCTIONS ~~~~~~~~~~~~ //
//@jdehorty Kernel Function
//used to turn a source into a rational quadratic which performs better in ML calculations
rationalQuadratic(_src, _lookback, _relativeWeight, startAtBar) =>
float _currentWeight = 0.
float _cumulativeWeight = 0.
_size = array.size(array.from(_src))
for i = 0 to _size + startAtBar
y = _src[i]
w = math.pow(1 + (math.pow(i, 2) / ((math.pow(_lookback, 2) * 2 * _relativeWeight))), -_relativeWeight)
_currentWeight += y*w
_cumulativeWeight += w
yhat = _currentWeight / _cumulativeWeight
yhat
//Calculate a traditional Supertrend but with the ability to replace its sources with Rationalized versions as well as with a Stop loss
getSupertrend(factor, atrPeriod) =>
src = rationalizeHL2 ? rationalQuadratic(hl2, 8, 8., 25) : hl2
atr = rationalizeATR ? rationalQuadratic(ta.atr(atrPeriod), 8, 8., 25) : ta.atr(atrPeriod)
upperBand = src + factor * atr
lowerBand = src - factor * atr
prevLowerBand = nz(lowerBand[1])
prevUpperBand = nz(upperBand[1])
closeSrc = rationalizeClose ? rationalQuadratic(close, 8, 8., 25) : close
lowerBand := lowerBand > prevLowerBand or closeSrc[1] < prevLowerBand ? lowerBand : prevLowerBand
upperBand := upperBand < prevUpperBand or closeSrc[1] > prevUpperBand ? upperBand : prevUpperBand
int direction = na
float superTrend = na
float stoploss = direction[1] == -1 ? lowerBand - (lowerBand * stoplossMult) : upperBand + (upperBand * stoplossMult)
prevSuperTrend = superTrend[1]
if na(atr[1])
direction := 1
else if prevSuperTrend == prevUpperBand
direction := closeSrc > stoploss ? -1 : 1
else
direction := closeSrc < stoploss ? 1 : -1
superTrend := direction == -1 ? lowerBand : upperBand
[superTrend, direction, stoploss]
//Get the exponential average of an array, where the exponential weight is focused on the first value of this array (current source)
getExponentialDataAverage(_data, _length) =>
avg = 0.
maxLen = math.min(_data.size(), _length)
if maxLen > 0
for i = 0 to maxLen - 1
curData = _data.get(i)
tempAvg = curData
if i > 0
for a = 0 to i
tempAvg += array.get(_data, a)
tempAvg := math.avg(_data.get(0), tempAvg / i)
avg += math.avg(_data.get(0), math.avg(curData, tempAvg))
avg / _length
else
avg
//Uses KNN to sort distances with our ML fast and slow data
//This is a modified version that sorts distances but rather than saving and outputting the distance average it outputs the mean of the valid distance and averages the total
knnAverage_fromDistance(_currentDirection, _dataFast, _dataSlow, _directions, _minDist, _maxDist) =>
//failsafe we need at least 1 distance
maxDist = not _minDist ? true : _maxDist
//Calculate the distance between slow and fast moving Datas
distances = array.new_float(0)
for i = 0 to _dataSlow.size() - 1
if not onlyUseSameTrendDirections or _currentDirection == _directions.get(i)
distance = _dataSlow.get(i) - _dataFast.get(i)
distances.push(distance)
//clone the array so it doesn't modify it
clonedDistances = distances.copy()
//slice the length from the array and calculate the max value from this slice
splicedDistances = clonedDistances.slice(0, math.min(knnLength, clonedDistances.size()))
maxDistanceAllowed = splicedDistances.max()
minDistanceAllowed = splicedDistances.min()
//scan all distances and add any that are less than max distance
validDistances = array.new_float(0)
for i = 0 to distances.size() - 1
if (not maxDist or distances.get(i) <= maxDistanceAllowed) and (not _minDist or distances.get(i) >= minDistanceAllowed)
and (not onlyUseSameTrendDirections or _currentDirection == _directions.get(i))
distAvg = (_dataSlow.get(i) + _dataFast.get(i)) / 2
validDistances.push(distAvg)
// Get exponential or regular average
if useMachineLearning == "KNN Exponential Average"
getExponentialDataAverage(validDistances, 1)
else
validDistances.avg()
// ~~~~~~~~~~~~ CALCULATIONS ~~~~~~~~~~~~ //
//Get our current supertrend
[supertrendOG, directionOG, stoplossOG] = getSupertrend(factor, atrPeriod)
//Create save variables based on our current Supertrend
float supertrend = supertrendOG
int direction = directionOG
float stoploss = stoplossOG
//Apply Machine Learning logic to our Supertrend if selected
if useMachineLearning != "None"
//Save our directions so we can filter data based on directions (removes inconsistencies)
directions = array.new_int(mlLength)
//populate our directions
for d = 0 to mlLength - 1
directions.set(d, direction[d])
if useMachineLearning == "Simple Average"
// -- A simple machine Learning Average
//essentially just a simple Average of supertrend data (potentially filtered to account for directions)
supertrendData = array.new_float(0)
for i = 0 to mlLength - 1
if not onlyUseSameTrendDirections or direction == directions.get(i)
supertrendData.push(supertrend[i])
supertrend := supertrendData.avg()
else
// -- A still simple but more complex approach to Machine Learning using KNN to sort validDistances
//Calculate our fast and slow MA's based on the current Supertrend
float supertrendFast = mlType == "SMA" ? ta.sma(supertrend, fastLength) : mlType == "EMA" ? ta.ema(supertrend, fastLength) : ta.vwma(supertrend, fastLength)
float supertrendSlow = mlType == "SMA" ? ta.sma(supertrend, slowLength) : mlType == "EMA" ? ta.ema(supertrend, slowLength) : ta.vwma(supertrend, slowLength)
//create storage data for ML lookbacks
supertrendFastData = array.new_float(mlLength)
supertrendSlowData = array.new_float(mlLength)
//populate our ML storage with lookbacks at our Fast and Slow Supertrend MAs
for i = 0 to mlLength - 1
supertrendFastData.set(i, supertrendFast[i])
supertrendSlowData.set(i, supertrendSlow[i])
//calculate our new Supertrend using KNN by using distances within KNN min/max and filtering by direction
supertrend := knnAverage_fromDistance(direction, supertrendFastData, supertrendSlowData, directions, distanceTypeMin, distanceTypeMax)
//Recalculate the Stop loss based on new supertrend (this is used in the direction recalculation below so needs to be done before)
stoploss := direction == -1 ? supertrend - (supertrend * stoplossMult) : supertrend + (supertrend * stoplossMult)
//Recalculate the direction based on the new supertrend
direction := close > stoploss ? -1 : 1
//Calculate the take profit location
takeprofit = direction == -1 ? supertrend + (supertrend * takeprofitMult) : supertrend - (supertrend * takeprofitMult)
// ~~~~~~~~~~~~ PLOTS ~~~~~~~~~~~~ //
//Plot all of our supertrend data
supertrend := barstate.isfirst ? na : supertrend
bodyMiddle = plot(barstate.isfirst ? na : (open + close) / 2, display = display.none)
upTrend = plot(direction < 0 ? supertrend : na, "Up Trend", color = color.green, style = plot.style_linebr)
downTrend = plot(direction < 0 ? na : supertrend, "Down Trend", color = color.red, style = plot.style_linebr)
upTrendStoploss = plot(stoplossMult != 0 ? direction < 0 ? stoploss : na : na, "Stop Loss", color =color.green, style = plot.style_linebr)
downTrendStoploss = plot(stoplossMult != 0 ? direction < 0 ? na : stoploss : na, "Stop Loss", color = color.red, style = plot.style_linebr)
upTrendTakeprofit = plot(takeprofitMult != 0 ? direction < 0 ? takeprofit : na : na, "Stop Loss", color =color.rgb(16, 105, 179), style = plot.style_linebr)
downTrendTakeprofit = plot(takeprofitMult != 0 ? direction < 0 ? na : takeprofit : na, "Stop Loss", color = color.rgb(206, 113, 1), style = plot.style_linebr)
//Fill all of our supertrend data
fill(bodyMiddle, upTrend, color.new(color.green, 90))
fill(bodyMiddle, downTrend, color.new(color.red, 90))
fill(upTrendStoploss, upTrend, color.new(color.green, 95))
fill(downTrendStoploss, downTrend, color.new(color.red, 95))
// ~~~~~~~~~~~~ STRATEGY ~~~~~~~~~~~~ //
//Trend Change (includes Stop Loss)
if direction != direction[1]
if direction == -1
strategy.entry("Buy", strategy.long)
else
strategy.entry("Sell", strategy.short)
//Take Profit
if takeprofitMult != 0
if direction == -1 and close > takeprofit
strategy.close("Buy")
else if direction == 1 and close < takeprofit
strategy.close("Sell")
// ~~~~~~~~~~~~ ALERTS ~~~~~~~~~~~~ //
if (direction != direction[1]) or (takeprofitMult != 0 and ((direction == -1 and close > takeprofit) or (direction == 1 and close < takeprofit)))
alert("{{strategy.order.action}} | {{ticker}} | {{close}}", alert.freq_once_per_bar)
// ~~~~~~~~~~~~ END ~~~~~~~~~~~~ // |
SessionVolumeProfile | https://www.tradingview.com/script/5ubxXb8z-SessionVolumeProfile/ | jmosullivan | https://www.tradingview.com/u/jmosullivan/ | 10 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jmosullivan
//@version=5
// @description Analyzes price & volume during regular trading hours to provide a session volume profile analysis.
// To learn more about this library and how you can use it, click on the website link in my profile where you will
// find a blog post with detailed information.
library("SessionVolumeProfile", overlay=true)
import jmosullivan/Table/1
import jmosullivan/Utils/3
export type Object
// Configuration Settings
int numberOfRows = 24
int valueAreaCoverage = 70
bool trackDevelopingVa = false
// Values we are searching for
float valueAreaHigh = na
float pointOfControl = na
float valueAreaLow = na
int startTime = na
int endTime = na
// Private properties for tracking things
float dayHigh = na
float dayLow = na
float step = na
int pointOfControlLevel = na
int valueAreaHighLevel = na
int valueAreaLowLevel = na
array<float> volumeRows = na
array<float> priceLevelRows = na
array<float> ltfSessionHighs = na
array<float> ltfSessionLows = na
array<float> ltfSessionVols = na
// @function Helper function to write some information about the supplied SVP object to the screen in a table.
// @param vp The SVP object to debug
// @param position The position.* to place the table. Defaults to position.bottom_center
export debug(Object vp, string position = position.bottom_center) =>
if not na(vp)
h = str.split('VAH,POC,VAL,Start,End,Now', ',')
r = array.from(str.tostring(vp.valueAreaHigh, format.mintick), str.tostring(vp.pointOfControl, format.mintick), str.tostring(vp.valueAreaLow, format.mintick), Utils.getDateTimeString(vp.startTime), Utils.getDateTimeString(vp.endTime), Utils.getDateTimeString(time))
m = matrix.new<string>()
matrix.add_row(m, 0, h)
matrix.add_row(m, 1, r)
Table.fromMatrix(m, position)
// @function Depending on the timeframe of the chart, determines a lower timeframe to grab volume data from for the analysis
// @returns The timeframe string to fetch volume for
export getLowerTimeframe() =>
timeframeInSeconds = timeframe.in_seconds()
oneMinuteInSeconds = timeframe.in_seconds("1")
fiveMinutesInSeconds = timeframe.in_seconds("5")
fifteenMinutesInSeconds = timeframe.in_seconds("15")
thirtyMinutesInSeconds = timeframe.in_seconds("30")
oneHourInSeconds = timeframe.in_seconds("60")
twoHoursInSeconds = timeframe.in_seconds("120")
fourHoursInSeconds = timeframe.in_seconds("240")
oneDayInSeconds = timeframe.in_seconds("1D")
switch
timeframeInSeconds >= oneMinuteInSeconds and timeframeInSeconds <= fifteenMinutesInSeconds => "1"
timeframeInSeconds > fifteenMinutesInSeconds and timeframeInSeconds <= thirtyMinutesInSeconds => "5"
timeframeInSeconds > thirtyMinutesInSeconds and timeframeInSeconds <= oneHourInSeconds => "10"
timeframeInSeconds > oneHourInSeconds and timeframeInSeconds <= twoHoursInSeconds => "15"
timeframeInSeconds > twoHoursInSeconds and timeframeInSeconds <= fourHoursInSeconds => "30"
timeframeInSeconds > fourHoursInSeconds and timeframeInSeconds <= oneDayInSeconds => "60"
timeframeInSeconds > oneDayInSeconds => "1D"
=> "10s"
// @function Private function used to calculate the volume used across candles.
getVolumeForRow(rowHigh, rowLow, candleHigh, candleLow, candleVolume) =>
rowRange = rowHigh - rowLow
candleRange = candleHigh - candleLow
pricePortion = 0.
if candleHigh > rowHigh and candleLow < rowLow
// The candle engulfed the row, so take the entire row range's portion of volume out of the candle
pricePortion := rowRange
else if candleHigh <= rowHigh and candleLow >= rowLow
// The top of the candle is in-or-equal the row, the bottom of the candle is also in-or-equal the row
pricePortion := candleRange
else if candleHigh > rowHigh and candleLow >= rowLow and candleLow
// The top of the candle is above the row, and the bottom is in-or-equal the row
pricePortion := rowHigh - candleLow
else if candleHigh <= rowHigh and candleLow < rowLow
// The top of the candle is in-or-equal the row, the bottom of the candle is below the row
pricePortion := candleHigh - rowLow
else
// The candle didn't intersect with the row at at all
pricePortion := 0
// return the portion of volume from the candle relative to the amount of price intersecting the row
(pricePortion * candleVolume) / candleRange
// @function Populated the provided SessionVolumeProfile object with vp data on the session.
// @param volumeProfile The SessionVolumeProfile object to populate
// @param lowerTimeframeHigh The lower timeframe high values
// @param lowerTimeframeLow The lower timeframe low values
// @param lowerTimeframeVolume The lower timeframe volume values
export get(Object volumeProfile, array<float> lowerTimeframeHigh, array<float> lowerTimeframeLow, array<float> lowerTimeframeVolume) =>
// Don't do SVP unless the chart is >= 1m and < 1d
timeframeInSeconds = timeframe.in_seconds()
if timeframeInSeconds >= timeframe.in_seconds("1") and timeframeInSeconds < timeframe.in_seconds("1D")
valueAreaCoveragePercent = volumeProfile.valueAreaCoverage / 100
// Make sure arrays are defined
if na(volumeProfile.ltfSessionHighs)
volumeProfile.ltfSessionHighs := array.new<float>()
if na(volumeProfile.ltfSessionLows)
volumeProfile.ltfSessionLows := array.new<float>()
if na(volumeProfile.ltfSessionVols)
volumeProfile.ltfSessionVols := array.new<float>()
// Collect all of the session values into the arrays
if session.ismarket and barstate.isconfirmed
volumeProfile.ltfSessionHighs := array.concat(volumeProfile.ltfSessionHighs, lowerTimeframeHigh)
volumeProfile.ltfSessionLows := array.concat(volumeProfile.ltfSessionLows, lowerTimeframeLow)
volumeProfile.ltfSessionVols := array.concat(volumeProfile.ltfSessionVols, lowerTimeframeVolume)
// If you don't need the developing VA, you can stop all that processing on every candle by setting it to false (default)
// and then only processing the value area on (a) the last bar of the day or (b) the last bar loaded on the chart during
// the regular session (aka session.ismarket)
onlyTrackOnLastBar = volumeProfile.trackDevelopingVa == true ? true : barstate.islast or session.islastbar_regular
if session.ismarket and onlyTrackOnLastBar
volumeProfile.endTime := time
// If we've collected data...
sessionCandleCount = array.size(volumeProfile.ltfSessionHighs)
if sessionCandleCount > 0
volumeProfile.dayHigh := array.max(volumeProfile.ltfSessionHighs)
volumeProfile.dayLow := array.min(volumeProfile.ltfSessionLows)
volumeProfile.step := (volumeProfile.dayHigh - volumeProfile.dayLow) / volumeProfile.numberOfRows
volumeRows = array.new<float>(volumeProfile.numberOfRows, 0.)
priceLevelRows = array.new<float>(volumeProfile.numberOfRows, 0.)
pocLevel = 0
vahLevel = 0
valLevel = 0
highestVol = 0.
// Loop through all of the collected session values placing them into their appropriate levels
level = 0
for priceLevel = volumeProfile.dayLow to volumeProfile.dayHigh by volumeProfile.step
if (level < volumeProfile.numberOfRows)
array.set(priceLevelRows, level, priceLevel) // + (step / 2))
levelVol = array.get(volumeRows, level)
for i = 0 to sessionCandleCount - 1
h = array.get(volumeProfile.ltfSessionHighs, i) // high
l = array.get(volumeProfile.ltfSessionLows, i) // low
r = h - l // range
v = nz(array.get(volumeProfile.ltfSessionVols, i)) // volume
if h >= priceLevel and l < (priceLevel + volumeProfile.step)
levelVol += getVolumeForRow(priceLevel + volumeProfile.step, priceLevel, h, l, v)
if levelVol > highestVol
highestVol := levelVol
pocLevel := level
array.set(volumeRows, level, levelVol)
level += 1
// Start building value from the POC upwards and downwards
valueAreaTracking = array.get(volumeRows, pocLevel)
totalVol = array.sum(volumeRows)
valueAreaVol = totalVol * valueAreaCoveragePercent
vahLevel := pocLevel
valLevel := pocLevel
volumeAbovePoc = 0.
volumeBelowPoc = 0.
loopCount = 0
while valueAreaTracking < valueAreaVol and loopCount <= volumeProfile.numberOfRows // Prevent infinite looping
loopCount += 1
// Break if we've gone below or above the numRows
if valLevel <= 0 and vahLevel >= volumeProfile.numberOfRows - 1
break
volumeAbovePoc := vahLevel >= volumeProfile.numberOfRows - 1 ? 0 : array.get(volumeRows, vahLevel + 1)
volumeBelowPoc := valLevel <= 0 ? 0 : array.get(volumeRows, valLevel - 1)
if volumeAbovePoc >= volumeBelowPoc
valueAreaTracking += volumeAbovePoc
vahLevel += 1
else
valueAreaTracking += volumeBelowPoc
valLevel -= 1
if valLevel < 0
valLevel := 0
if vahLevel >= volumeProfile.numberOfRows - 1
vahLevel := volumeProfile.numberOfRows - 1
// Define the key return values on the volume profile object so library users can do things with them...
volumeProfile.priceLevelRows := priceLevelRows
volumeProfile.volumeRows := volumeRows
volumeProfile.pointOfControlLevel := pocLevel
volumeProfile.valueAreaHighLevel := vahLevel
volumeProfile.valueAreaLowLevel := valLevel
volumeProfile.pointOfControl := array.get(priceLevelRows, pocLevel) + (volumeProfile.step / 2)
volumeProfile.valueAreaHigh := array.get(priceLevelRows, vahLevel) + volumeProfile.step
volumeProfile.valueAreaLow := array.get(priceLevelRows, valLevel)
// When we start a session ...
if session.isfirstbar_regular
// ... Reset things
array.clear(volumeProfile.ltfSessionHighs)
array.clear(volumeProfile.ltfSessionLows)
array.clear(volumeProfile.ltfSessionVols)
volumeProfile.startTime := time
// @function Given a SessionVolumeProfile Object, will render the historical value areas for that object.
// @param todaySessionVolumeProfile The SessionVolumeProfile Object to draw
// @param extendYesterdayOverToday Defaults to true
// @param showLabels Defaults to true
// @param labelSize Defaults to size.small
// @param pocColor Defaults to #e500a4
// @param pocStyle Defaults to line.style_solid
// @param pocWidth Defaults to 1
// @param vahlColor The color of the value area high/low lines. Defaults to #1592e6
// @param vahlStyle The style of the value area high/low lines. Defaults to line.style_solid
// @param vahlWidth The width of the value area high/low lines. Defaults to 1
// @param vaColor The color of the value area background. Defaults to #00bbf911)
export drawPriorValueAreas(Object todaySessionVolumeProfile, bool extendYesterdayOverToday = true, bool showLabels = true, string labelSize = size.small, color pocColor = #e500a4, string pocStyle = line.style_solid, int pocWidth=1, color vahlColor = #1592e6, string vahlStyle = line.style_solid, int vahlWidth = 1, color vaColor = #00bbf911) =>
var Object yesterdaySVP = na
// Yesterday drawings
var line yesterdayPocLine = line.new(time, 0, time, 0, color=pocColor, style=pocStyle, width=pocWidth, xloc=xloc.bar_time)
var line yesterdayVahLine = line.new(time, 0, time, 0, color=vahlColor, style=vahlStyle, width=vahlWidth, xloc=xloc.bar_time)
var line yesterdayValLine = line.new(time, 0, time, 0, color=vahlColor, style=vahlStyle, width=vahlWidth, xloc=xloc.bar_time)
var label yesterdayPocLabel = label.new(x=0, y=0, text="", xloc=xloc.bar_time, color=#00000000, style=label.style_label_left, textcolor=pocColor, size=labelSize, textalign=text.align_left)
var label yesterdayVahLabel = label.new(x=0, y=0, text="", xloc=xloc.bar_time, color=#00000000, style=label.style_label_left, textcolor=vahlColor, size=labelSize, textalign=text.align_left)
var label yesterdayValLabel = label.new(x=0, y=0, text="", xloc=xloc.bar_time, color=#00000000, style=label.style_label_left, textcolor=vahlColor, size=labelSize, textalign=text.align_left)
var box yesterdayVaBox = box.new(time, 0, time, 0, border_width=0, bgcolor=vaColor, xloc=xloc.bar_time)
labelTemplate = '{0} {1}'
labelPercentTemplate = '{0} {1} ({2,number,#.##}%)'
// SessionVolumeProfile.get() completes the configuration of a session on session.islastbar_regular, so
// (assuming it was configured before this was called), at this point you should have everything you
// need for the current day. So, any values already in yesterdaySVP now represent 2 days ago. So
// (a) drop drawings for that day out onto the chart in their "final" state, and (b) then copy the
// current SVP onto yesterdaySVP.
if session.islastbar_regular
if not na(yesterdaySVP)
// If we have yesterday's SVP, create drawings for that day
histVahLine = line.copy(yesterdayVahLine)
histValLine = line.copy(yesterdayValLine)
histPocLine = line.copy(yesterdayPocLine)
histVaBox = box.copy(yesterdayVaBox)
// Update where they end
line.set_x2(histVahLine, yesterdaySVP.endTime)
line.set_x2(histValLine, yesterdaySVP.endTime)
line.set_x2(histPocLine, yesterdaySVP.endTime)
box.set_right(histVaBox, yesterdaySVP.endTime)
// Do the same for labels if you are showing them
if showLabels
histVahLabel = label.copy(yesterdayVahLabel)
histValLabel = label.copy(yesterdayValLabel)
histPocLabel = label.copy(yesterdayPocLabel)
label.set_x(histVahLabel, yesterdaySVP.endTime)
label.set_x(histValLabel, yesterdaySVP.endTime)
label.set_x(histPocLabel, yesterdaySVP.endTime)
label.set_text(histVahLabel, str.format(labelTemplate, str.tostring(yesterdaySVP.valueAreaHigh, format.mintick), 'VAH'))
label.set_text(histValLabel, str.format(labelTemplate, str.tostring(yesterdaySVP.valueAreaLow, format.mintick), 'VAL'))
label.set_text(histPocLabel, str.format(labelTemplate, str.tostring(yesterdaySVP.pointOfControl, format.mintick), 'POC'))
// Copy today's volume profile over yesterday's
yesterdaySVP := todaySessionVolumeProfile.copy()
// Update the position of the drawings for yesterday...
// Lines
line.set_xy1(yesterdayVahLine, yesterdaySVP.startTime, yesterdaySVP.valueAreaHigh)
line.set_xy2(yesterdayVahLine, yesterdaySVP.endTime, yesterdaySVP.valueAreaHigh)
line.set_xy1(yesterdayValLine, yesterdaySVP.startTime, yesterdaySVP.valueAreaLow)
line.set_xy2(yesterdayValLine, yesterdaySVP.endTime, yesterdaySVP.valueAreaLow)
line.set_xy1(yesterdayPocLine, yesterdaySVP.startTime, yesterdaySVP.pointOfControl)
line.set_xy2(yesterdayPocLine, yesterdaySVP.endTime, yesterdaySVP.pointOfControl)
// Box
box.set_lefttop(yesterdayVaBox, yesterdaySVP.startTime, yesterdaySVP.valueAreaHigh)
box.set_rightbottom(yesterdayVaBox, yesterdaySVP.endTime, yesterdaySVP.valueAreaLow)
// Labels
if showLabels
label.set_text(yesterdayVahLabel, str.format(labelPercentTemplate, str.tostring(yesterdaySVP.valueAreaHigh, format.mintick), 'VAH', (yesterdaySVP.valueAreaHigh-close)/close*100))
label.set_text(yesterdayValLabel, str.format(labelPercentTemplate, str.tostring(yesterdaySVP.valueAreaLow, format.mintick), 'VAL', (yesterdaySVP.valueAreaLow-close)/close*100))
label.set_text(yesterdayPocLabel, str.format(labelPercentTemplate, str.tostring(yesterdaySVP.pointOfControl, format.mintick), 'POC', (yesterdaySVP.pointOfControl-close)/close*100))
label.set_xy(yesterdayVahLabel, yesterdaySVP.endTime, yesterdaySVP.valueAreaHigh)
label.set_xy(yesterdayValLabel, yesterdaySVP.endTime, yesterdaySVP.valueAreaLow)
label.set_xy(yesterdayPocLabel, yesterdaySVP.endTime, yesterdaySVP.pointOfControl)
// If in regular session...
if not na(yesterdaySVP)
// Update the label information (so % from price stays accurate)
if showLabels
label.set_text(yesterdayVahLabel, str.format(labelPercentTemplate, str.tostring(yesterdaySVP.valueAreaHigh, format.mintick), 'VAH', (yesterdaySVP.valueAreaHigh-close)/close*100))
label.set_text(yesterdayValLabel, str.format(labelPercentTemplate, str.tostring(yesterdaySVP.valueAreaLow, format.mintick), 'VAL', (yesterdaySVP.valueAreaLow-close)/close*100))
label.set_text(yesterdayPocLabel, str.format(labelPercentTemplate, str.tostring(yesterdaySVP.pointOfControl, format.mintick), 'POC', (yesterdaySVP.pointOfControl-close)/close*100))
// Update the end location of the lines & labels overtop of today's trading hours
if extendYesterdayOverToday
// Keep extending yesterday's value area over the current day as it develops
line.set_x2(yesterdayVahLine, time)
line.set_x2(yesterdayValLine, time)
line.set_x2(yesterdayPocLine, time)
box.set_right(yesterdayVaBox, time)
if showLabels
label.set_x(yesterdayVahLabel, time)
label.set_x(yesterdayValLabel, time)
label.set_x(yesterdayPocLabel, time)
// @function Given a SessionVolumeProfile object, will render the histogram for that object.
// @param volumeProfile The SessionVolumeProfile object to draw
// @param bgColor The baseline color to use for the histogram. Defaults to #00bbf9
// @param showVolumeOnHistogram Show the volume amount on the histogram bars. Defaults to false.
export drawHistogram(Object volumeProfile, color bgColor = #00bbf9, bool showVolumeOnHistogram = false) =>
if not na(volumeProfile.volumeRows) and session.islastbar_regular
histLevel = 0
histPrice = volumeProfile.dayLow
barRange = time - volumeProfile.startTime
stepSpacer = volumeProfile.step * 0.05
totalVol = array.sum(volumeProfile.volumeRows)
for vol in volumeProfile.volumeRows
clr = color.new(bgColor, histLevel < volumeProfile.valueAreaLowLevel or histLevel > volumeProfile.valueAreaHighLevel ? 70 : 40)
volWidthPercent = vol / totalVol
int histWidth = math.round(barRange * volWidthPercent * 2)
histRightTime = volumeProfile.startTime + histWidth
topLeft = chart.point.from_time(volumeProfile.startTime, histPrice + volumeProfile.step - stepSpacer)
bottomRight = chart.point.from_time(histRightTime, histPrice + stepSpacer)
histBarText = showVolumeOnHistogram ? str.format("{0}", vol) : ""
box.new(topLeft, bottomRight, border_color=#00000000, bgcolor=clr, text=histBarText, text_size=size.auto, text_halign=text.align_left, xloc=xloc.bar_time)
histLevel += 1
histPrice += volumeProfile.step
histBgColor = color.new(bgColor, 90)
box.new(chart.point.from_time(volumeProfile.startTime, volumeProfile.dayHigh), chart.point.from_time(time, volumeProfile.dayLow), histBgColor, bgcolor=histBgColor, xloc=xloc.bar_time)
// Logic
// Settings
grp1 = "General Settings"
numRows = input.int(group=grp1, defval=24, title="Row Size")
valueAreaCoverage = input.int(group=grp1, defval=70, title="Value Area Volume", minval=1, maxval=100, step=1)
grp2 = "Appearance"
extendYesterdayOverToday = input.bool(group=grp2, defval=true, title="Extend yesterday's volume profile over today")
showVa = input.bool(group=grp2, defval=true, title="Show Value Area", inline="vaBox")
vaColor = input.color(group=grp2, defval=#00bbf911, title="", inline="vaBox")
pocColor = input.color(group=grp2, defval=#e500a4, title="Point of Control ", inline="poc")
pocStyleEnglish = input.string(group=grp2, title="", defval="Solid", options=["Solid", "Dotted", "Dashed"], inline="poc")
pocStyle = Utils.getLineStyleFromString(pocStyleEnglish)
pocWidth = input.int(group=grp2, title="", defval=1, minval=1, maxval=6, step=1, inline="poc")
vahlColor = input.color(group=grp2, defval=#1592e6, title="Value Area High/Low", inline="vahl")
vahlStyleEnglish = input.string(group=grp2, title="", defval="Solid", options=["Solid", "Dotted", "Dashed"], inline="vahl")
vahlStyle = Utils.getLineStyleFromString(vahlStyleEnglish)
vahlWidth = input.int(group=grp2, title="", defval=1, minval=1, maxval=6, step=1, inline="vahl")
showLabels = input.bool(group=grp2, defval=true, title="Labels", inline="labels")
labelSize = input.string(group=grp2, defval=size.small, title="", options=[size.auto, size.tiny, size.small, size.normal, size.large, size.huge], inline="labels")
showHistogram = input.bool(group=grp2, defval=true, title="Show Histogram", inline="histogramBox")
histColor = input.color(group=grp2, defval=#00bbf9, title="", inline="histogramBox")
showVolumeOnHistogram = input.bool(group=grp2, defval=false, title="Show Volume on Histogram")
showDevelopingValueArea = input.bool(group=grp2, defval=false, title="Show Developing Value Area", inline="developing")
devColor = input.color(group=grp2, defval=color.fuchsia, title="", inline="developing")
// Request data from lower timeframe to calculate volume profile
[ltfHigh, ltfLow, ltfVolume] = request.security_lower_tf(syminfo.tickerid, getLowerTimeframe(), [high, low, volume])
// Create volume profile to contain developing values
var Object todaySVP = Object.new(numRows, valueAreaCoverage, showDevelopingValueArea)
// Populate the SVP object
get(todaySVP, ltfHigh, ltfLow, ltfVolume)
// Render the value area
if showVa
drawPriorValueAreas(todaySVP, extendYesterdayOverToday=extendYesterdayOverToday, showLabels=showLabels, labelSize=labelSize, pocColor=pocColor, pocStyle=pocStyle, pocWidth=pocWidth, vahlColor=vahlColor, vahlStyle=vahlStyle, vahlWidth=vahlWidth, vaColor=vaColor)
// Render a histogram
if showHistogram
drawHistogram(todaySVP, bgColor=histColor, showVolumeOnHistogram=showVolumeOnHistogram)
// Render the developing value area...
devVah = showDevelopingValueArea ? todaySVP.valueAreaHigh : na
devVal = showDevelopingValueArea ? todaySVP.valueAreaLow : na
devPoc = showDevelopingValueArea ? todaySVP.pointOfControl : na
plot(devVah, "Developing Value Area High", color.new(devColor, 60), 1)
plot(devPoc, "Developing Point of Control", devColor, 2)
plot(devVal, "Developing Value Area Low", color.new(devColor, 60), 1) |
Multi-TF AI SuperTrend with ADX - Strategy [PresentTrading] | https://www.tradingview.com/script/FeoUBe91-Multi-TF-AI-SuperTrend-with-ADX-Strategy-PresentTrading/ | PresentTrading | https://www.tradingview.com/u/PresentTrading/ | 139 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © PresentTrading
//@version=5
strategy("Multi-TF AI-Enhanced SuperTrend with ADX Filter - Strategy [PresentTrading]", overlay=true, precision=3, default_qty_type=strategy.cash,
commission_value= 0.1, commission_type=strategy.commission.percent, slippage= 1,
currency=currency.USD, default_qty_type = strategy.percent_of_equity, default_qty_value = 10, initial_capital= 10000)
// ~~ ToolTips {
t1="Number of nearest neighbors in KNN algorithm (k): Increase to consider more neighbors, providing a more balanced view but possibly smoothing out local patterns. Decrease for fewer neighbors to make the algorithm more responsive to recent changes. \n\nNumber of data points to consider (n): Increase for more historical data, providing a broader context but possibly diluting recent trends. Decrease for less historical data to focus more on recent behavior."
t2="Length of weighted moving average for price (KNN_PriceLen): Higher values create a smoother price line, influencing the KNN algorithm to be more stable but less sensitive to short-term price movements. Lower values enhance responsiveness in KNN predictions to recent price changes but may lead to more noise. \n\nLength of weighted moving average for SuperTrend (KNN_STLen): Higher values lead to a smoother SuperTrend line, affecting the KNN algorithm to emphasize long-term trends. Lower values make KNN predictions more sensitive to recent SuperTrend changes but may result in more volatility."
t3="Length of the SuperTrend (len): Increase for a smoother trend line, ideal for identifying long-term trends but possibly ignoring short-term fluctuations. Decrease for more responsiveness to recent changes but risk of more false signals. \n\nMultiplier for ATR in SuperTrend calculation (factor): Increase for wider bands, capturing larger price movements but possibly missing subtle changes. Decrease for narrower bands, more sensitive to small shifts but risk of more noise."
t4="Type of moving average for SuperTrend calculation (maSrc): Choose based on desired characteristics. SMA is simple and clear, EMA emphasizes recent prices, WMA gives more weight to recent data, RMA is less sensitive to recent changes, and VWMA considers volume."
t5="Color for bullish trend (upCol): Select to visually identify upward trends. \n\nColor for bearish trend (dnCol): Select to visually identify downward trends.\n\nColor for neutral trend (neCol): Select to visually identify neutral trends."
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// Add Button for Trading Direction
tradeDirection = input.string("Both", "Select Trading Direction", options=["Long", "Short", "Both"])
// ~~ Input settings for K and N values
k = input.int(3, title = "Neighbors", minval=1, maxval=100,inline="AI", group="AI Settings")
n_ = input.int(24, title ="Data", minval=1, maxval=100,inline="AI", group="AI Settings", tooltip=t1)
n = math.max(k,n_)
// Second KNN Parameters
k2 = input.int(3, title = "2nd Neighbors", minval=1, maxval=100,inline="AI2", group="AI2 Settings")
n2_ = input.int(24, title ="2nd Data", minval=1, maxval=100,inline="AI2", group="AI2 Settings")
n2 = math.max(k2, n2_)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Input settings for prediction values
KNN_PriceLen = input.int(10, title="Price Trend", minval=2, maxval=500, step=10,inline="AITrend", group="AI Trend")
KNN_STLen = input.int(80, title="Prediction Trend", minval=2, maxval=500, step=10, inline="AITrend", group="AI Trend", tooltip=t2)
KNN_PriceLen2 = input.int(10, title="2nd Price Trend", minval=2, maxval=500, step=10,inline="AI2Trend", group="AI Trend")
KNN_STLen2 = input.int(80, title="2nd Prediction Trend", minval=2, maxval=500, step=10, inline="AI2Trend", group="AI Trend")
aisignals = input.bool(true,title="AI Trend Signals",inline="signal", group="AI Trend")
Bullish_col = input.color(color.lime,"",inline="signal", group="AI Trend")
Bearish_col = input.color(color.red,"",inline="signal", group="AI Trend")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Define SuperTrend parameters
// Add Higher Timeframe Inputs
higherTf1 = input.timeframe(title='Higher Time Frame for 1st ST', defval='480',group="Super Trend Settings")
higherTf2 = input.timeframe(title='Higher Time Frame for 2nd ST', defval='D',group="Super Trend Settings")
maSrc = input.string("WMA","Moving Average Source",["SMA","EMA","WMA","RMA","VWMA"],inline="", group="Super Trend Settings", tooltip=t4)
len = input.int(10, "Length", minval=1,inline="SuperTrend", group="Super Trend Settings")
factor = input.float(3.0,step=.1,inline="SuperTrend", group="Super Trend Settings", tooltip=t3)
// Calculate the Second SuperTrend
len2 = input.int(5, "2nd Length", minval=1,inline="SuperTrend", group="Super Trend Settings")
factor2 = input.float(3.0,step=.1,inline="SuperTrend", group="Super Trend Settings")
upCol = input.color(color.lime,"Bullish Color",inline="col", group="Super Trend Coloring")
dnCol = input.color(color.red,"Bearish Color",inline="col", group="Super Trend Coloring")
neCol = input.color(color.blue,"Neutral Color",inline="col", group="Super Trend Coloring", tooltip=t5)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// Add an input to select the higher timeframe for the ADX and DMI filter:
adxLength = input.int(14, title="ADX Length", minval=1, group="ADX and DMI Settings")
adxTf = input.timeframe(title='Time Frame for ADX and DMI Filter 1', defval='D', group="ADX and DMI Settings")
useAdxFilter = input.bool(true, title="Use ADX and DMI Filter?", group="ADX and DMI Settings")
HTF_Close = request.security(syminfo.tickerid, adxTf, close)
HTF_High = request.security(syminfo.tickerid, adxTf, high)
HTF_Low = request.security(syminfo.tickerid, adxTf, low)
deltaHigh = HTF_High - HTF_High[1]
deltaLow = HTF_Low[1] - HTF_Low
plusDM = deltaHigh > deltaLow and deltaHigh > 0? deltaHigh: 0
minusDM = deltaLow > deltaHigh and deltaLow > 0? deltaLow: 0
ATR = ta.wma(math.abs(HTF_High - HTF_Low) + math.abs(HTF_High - HTF_Close[1]) + math.abs(HTF_Low - HTF_Close[1]), adxLength)
plusDI = 100 * ta.wma(plusDM, adxLength) / ATR
minusDI = 100 * ta.wma(minusDM, adxLength) / ATR
DX = 100 * math.abs(plusDI - minusDI) / (plusDI + minusDI)
ADX = ta.wma(DX, adxLength)
// ~~ Calculate the SuperTrend based on the user's choice
// ~~ First Supertrend
TfClose1 = request.security(syminfo.tickerid, higherTf1, close)
vwma1 = switch maSrc
"SMA" => ta.sma(TfClose1*volume, len) / ta.sma(volume, len)
"EMA" => ta.ema(TfClose1*volume, len) / ta.ema(volume, len)
"WMA" => ta.wma(TfClose1*volume, len) / ta.wma(volume, len)
"RMA" => ta.rma(TfClose1*volume, len) / ta.rma(volume, len)
"VWMA" => ta.vwma(TfClose1*volume, len) / ta.vwma(volume, len)
atr = request.security(syminfo.tickerid, higherTf1, ta.atr(len))
upperBand = vwma1 + factor * atr
lowerBand = vwma1 - factor * atr
prevLowerBand = nz(lowerBand[1])
prevUpperBand = nz(upperBand[1])
// ~~ Second Supertrend
TfClose2 = request.security(syminfo.tickerid, higherTf2, close)
vwma2 = switch maSrc
"SMA" => ta.sma(TfClose2*volume, len2) / ta.sma(volume, len2)
"EMA" => ta.ema(TfClose2*volume, len2) / ta.ema(volume, len2)
"WMA" => ta.wma(TfClose2*volume, len2) / ta.wma(volume, len2)
"RMA" => ta.rma(TfClose2*volume, len2) / ta.rma(volume, len2)
"VWMA" => ta.vwma(TfClose2*volume, len2) / ta.vwma(volume, len2)
atr2 = request.security(syminfo.tickerid, higherTf2, ta.atr(len2))
upperBand2 = vwma2 + factor2 * atr2
lowerBand2 = vwma2 - factor2 * atr2
prevLowerBand2 = nz(lowerBand2[1])
prevUpperBand2 = nz(upperBand2[1])
lowerBand := lowerBand > prevLowerBand or close[1] < prevLowerBand ? lowerBand : prevLowerBand
upperBand := upperBand < prevUpperBand or close[1] > prevUpperBand ? upperBand : prevUpperBand
int direction = na
float superTrend = na
lowerBand2 := lowerBand2 > prevLowerBand2 or close[1] < prevLowerBand2 ? lowerBand2 : prevLowerBand2
upperBand2 := upperBand2 < prevUpperBand2 or close[1] > prevUpperBand2 ? upperBand2 : prevUpperBand2
int direction2 = na
float superTrend2 = na
prevSuperTrend = superTrend[1]
if na(atr[1])
direction := 1
else if prevSuperTrend == prevUpperBand
direction := close > upperBand ? -1 : 1
else
direction := close < lowerBand ? 1 : -1
superTrend := direction == -1 ? lowerBand : upperBand
prevSuperTrend2 = superTrend2[1]
if na(atr2[1])
direction2 := 1
else if prevSuperTrend2 == prevUpperBand2
direction2 := close > upperBand2 ? -1 : 1
else
direction2 := close < lowerBand2 ? 1 : -1
superTrend2 := direction2 == -1 ? lowerBand2 : upperBand2
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Collect data points and their corresponding labels
price = ta.wma(close,KNN_PriceLen)
sT = ta.wma(superTrend,KNN_STLen)
data = array.new_float(n)
labels = array.new_int(n)
for i = 0 to n - 1
data.set(i, superTrend[i])
label_i = price[i] > sT[i] ? 1 : 0
labels.set(i, label_i)
// Collect data points for second SuperTrend and their corresponding labels
price2 = ta.wma(close,KNN_PriceLen2)
sT2 = ta.wma(superTrend2,KNN_STLen2)
data2 = array.new_float(n)
labels2 = array.new_int(n)
for i = 0 to n - 1
data2.set(i, superTrend2[i])
label_i2 = price2[i] > sT2[i] ? 1 : 0 // Assuming same price for second SuperTrend
labels2.set(i, label_i2)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Define a function to compute distance between two data points
distance(x1, x2) =>
math.abs(x1 - x2)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Define the weighted k-nearest neighbors (KNN) function
knn_weighted(data, labels, k, x) =>
n1 = data.size()
distances = array.new_float(n1)
indices = array.new_int(n1)
// Compute distances from the current point to all other points
for i = 0 to n1 - 1
x_i = data.get(i)
dist = distance(x, x_i)
distances.set(i, dist)
indices.set(i, i)
// Sort distances and corresponding indices in ascending order
// Bubble sort method
for i = 0 to n1 - 2
for j = 0 to n1 - i - 2
if distances.get(j) > distances.get(j + 1)
tempDist = distances.get(j)
distances.set(j, distances.get(j + 1))
distances.set(j + 1, tempDist)
tempIndex = indices.get(j)
indices.set(j, indices.get(j + 1))
indices.set(j + 1, tempIndex)
// Compute weighted sum of labels of the k nearest neighbors
weighted_sum = 0.
total_weight = 0.
for i = 0 to k - 1
index = indices.get(i)
label_i = labels.get(index)
weight_i = 1 / (distances.get(i) + 1e-6)
weighted_sum += weight_i * label_i
total_weight += weight_i
weighted_sum / total_weight
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Classify the current data point
current_superTrend = superTrend
label_ = knn_weighted(data, labels, k, current_superTrend)
label_upTrend = label_ == 1 ? 1:0
label_downTrend = label_ == 0 ? -1:0
// Classify the current data point for second SuperTrend
current_superTrend2 = superTrend2
label2_ = knn_weighted(data2, labels2, k, current_superTrend2)
label2_upTrend = label2_ == 1 ? 1:0
label2_downTrend = label2_ == 0 ? -1:0
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Plot
col = label_ == 1?upCol:label_ == 0?dnCol:neCol
plot(current_superTrend, color=col, title="Volume Super Trend AI")
upTrend = plot(superTrend==lowerBand?current_superTrend:na, title="Up Volume Super Trend AI", color=col, style=plot.style_linebr)
Middle = plot((open + close) / 2, display=display.none, editable=false)
downTrend = plot(superTrend==upperBand?current_superTrend:na, title="Down Volume Super Trend AI", color=col, style=plot.style_linebr)
fill_col = color.new(col,95)
fill(Middle, upTrend, fill_col, fillgaps=false,title="Up Volume Super Trend AI")
fill(Middle, downTrend, fill_col, fillgaps=false, title="Down Volume Super Trend AI")
// Plot Second SuperTrend
col2 = label2_ == 1 ? upCol : label2_ == 0 ? dnCol : neCol
plot(current_superTrend2, color=col2, title="Volume Super Trend AI 2")
upTrend2 = plot(superTrend2==lowerBand2 ? current_superTrend2 : na, title="Up Volume Super Trend AI 2", color=col2, style=plot.style_linebr)
downTrend2 = plot(superTrend2==upperBand2 ? current_superTrend2 : na, title="Down Volume Super Trend AI 2", color=col2, style=plot.style_linebr)
fill_col2 = color.new(col2, 95)
fill(Middle, upTrend2, fill_col2, fillgaps=false, title="Up Volume Super Trend AI 2")
fill(Middle, downTrend2, fill_col2, fillgaps=false, title="Down Volume Super Trend AI 2")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Ai Super Trend Signals
Start_TrendUp = col==upCol and (col[1]!=upCol or col[1]==neCol) and aisignals
Start_TrendDn = col==dnCol and (col[1]!=dnCol or col[1]==neCol) and aisignals
// Second AI Super Trend Signals
Start_TrendUp2 = col2==upCol and (col2[1]!=upCol or col2[1]==neCol) and aisignals
Start_TrendDn2 = col2==dnCol and (col2[1]!=dnCol or col2[1]==neCol) and aisignals
TrendUp = direction == -1 and direction[1] == 1 and label_ == 1 and aisignals
TrendDn = direction == 1 and direction[1] ==-1 and label_ == 0 and aisignals
TrendUp2 = direction2 == -1 and direction2[1] == 1 and label2_ == 1 and aisignals
TrendDn2 = direction2 == 1 and direction2[1] ==-1 and label2_ == 0 and aisignals
plotshape(Start_TrendUp?superTrend:na, location=location.absolute, style= shape.circle, size=size.tiny, color=Bullish_col, title="AI Bullish Trend Start")
plotshape(Start_TrendDn?superTrend:na, location=location.absolute, style= shape.circle,size=size.tiny, color=Bearish_col, title="AI Bearish Trend Start")
plotshape(TrendUp?superTrend:na, location=location.absolute, style= shape.triangleup, size=size.small, color=Bullish_col, title="AI Bullish Trend Signal")
plotshape(TrendDn?superTrend:na, location=location.absolute, style= shape.triangledown,size=size.small, color=Bearish_col, title="AI Bearish Trend Signal")
plotshape(Start_TrendUp2 ? superTrend2 : na, location=location.absolute, style= shape.circle, size=size.tiny, color=Bullish_col, title="AI Bullish Trend Start 2")
plotshape(Start_TrendDn2 ? superTrend2 : na, location=location.absolute, style= shape.circle, size=size.tiny, color=Bearish_col, title="AI Bearish Trend Start 2")
plotshape(TrendUp2?superTrend2:na, location=location.absolute, style= shape.triangleup, size=size.small, color=Bullish_col, title="AI Bullish Trend Signal")
plotshape(TrendDn2?superTrend2:na, location=location.absolute, style= shape.triangledown,size=size.small, color=Bearish_col, title="AI Bearish Trend Signal")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
//longCondition = (Start_TrendUp or Start_TrendUp2) or (TrendUp or TrendUp2)
//shortCondition = (Start_TrendDn or Start_TrendDn2) or (TrendDn or TrendDn2)
longAdxCondition = useAdxFilter ? (ADX > 20 and plusDI > minusDI) : true
shortAdxCondition = useAdxFilter ? (ADX > 20 and minusDI > plusDI) : true
longCondition = direction == -1 and label_ == 1 and direction2 == -1 and label2_ == 1 and longAdxCondition
shortCondition = direction == 1 and label_ == 0 and direction2 == 1 and label2_ == 0 and shortAdxCondition
// Double AI Trend Continuation Signals
longExitCondition1 = direction == -1 and label_ == 1
longExitCondition2 = direction2 == -1 and label2_ == 1
shortExitCondition1 = direction == 1 and label_ == 0
shortExitCondition2 = direction2 == 1 and label2_ == 0
longExitCondition = not (TrendUp or TrendUp2)
shortExitCondition = not (TrendDn or TrendDn2)
// Dynamic Trailing Stop Loss
longTrailingStop = superTrend - atr * factor
shortTrailingStop = superTrend + atr * factor
// Adjust Enter and Exit Conditions based on Trading Direction
if (tradeDirection == "Long" or tradeDirection == "Both")
strategy.entry("Long", strategy.long, when=longCondition)
strategy.exit("Exit Long", "Long", stop=longTrailingStop, when=longExitCondition)
if (tradeDirection == "Short" or tradeDirection == "Both")
strategy.entry("Short", strategy.short, when=shortCondition)
strategy.exit("Exit Short", "Short", stop=shortTrailingStop, when=shortExitCondition)
// Create Alert Conditions
alertcondition(longCondition, title="Long Entry Alert", message="Long Entry Signal Generated")
alertcondition(shortCondition, title="Short Entry Alert", message="Short Entry Signal Generated")
alertcondition(longExitCondition, title="Long Exit Alert", message="Long Exit Signal Generated")
alertcondition(shortExitCondition, title="Short Exit Alert", message="Short Exit Signal Generated") |
RMI Trend Sync - Strategy [presentTrading] | https://www.tradingview.com/script/mUUZpFlE-RMI-Trend-Sync-Strategy-presentTrading/ | PresentTrading | https://www.tradingview.com/u/PresentTrading/ | 28 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// @ presentTrading
//@version=5
strategy("RMI Trend Sync - Strategy [presentTrading]", shorttitle = "RMI Sync [presentTrading]", overlay=true, precision=3,
commission_value= 0.1, commission_type=strategy.commission.percent, slippage= 1,
currency=currency.USD, default_qty_type = strategy.percent_of_equity, default_qty_value = 10, initial_capital= 10000)
// ---> Inputs --------------
// Add Button for Trading Direction
tradeDirection = input.string("Both", "Select Trading Direction", options=["Long", "Short", "Both"])
// Relative Momentum Index (RMI) Settings
Length = input.int(21, "RMI Length", group = "RMI Settings")
pmom = input.int(70, "Positive Momentum Threshold", group = "RMI Settings")
nmom = input.int(30, "Negative Momentum Threshold", group = "RMI Settings")
bandLength = input.int(30, "Band Length", group = "Momentum Settings")
rwmaLength = input.int(20, "RWMA Length", group = "Momentum Settings")
// Super Trend Settings
len = input.int(10, "Super Trend Length", minval=1, group="Super Trend Settings")
higherTf1 = input.timeframe('480', "Higher Time Frame", group="Super Trend Settings")
factor = input.float(3.5, "Super Trend Factor", step=.1, group="Super Trend Settings")
maSrc = input.string("WMA", "MA Source", options=["SMA", "EMA", "WMA", "RMA", "VWMA"], group="Super Trend Settings")
atr = request.security(syminfo.tickerid, higherTf1, ta.atr(len))
TfClose1 = request.security(syminfo.tickerid, higherTf1, close)
// Visual Settings
filleshow = input.bool(true, "Display Range MA", group = "Visual Settings")
bull = input.color(#00bcd4, "Bullish Color", group = "Visual Settings")
bear = input.color(#ff5252, "Bearish Color", group = "Visual Settings")
// Calculation of Bar Range
barRange = high - low
// RMI and MFI Calculations
upChange = ta.rma(math.max(ta.change(close), 0), Length)
downChange = ta.rma(-math.min(ta.change(close), 0), Length)
rsi = downChange == 0 ? 100 : upChange == 0 ? 0 : 100 - (100 / (1 + upChange / downChange))
mf = ta.mfi(hlc3, Length)
rsiMfi = math.avg(rsi, mf)
// Momentum Conditions
positiveMomentum = rsiMfi[1] < pmom and rsiMfi > pmom and rsiMfi > nmom and ta.change(ta.ema(close,5)) > 0
negativeMomentum = rsiMfi < nmom and ta.change(ta.ema(close,5)) < 0
// Momentum Status
bool positive = positiveMomentum ? true : negativeMomentum ? false : na
bool negative = negativeMomentum ? true : positiveMomentum ? false : na
// Band Calculation
calculateBand(len) =>
math.min(ta.atr(len) * 0.3, close * (0.3/100)) * 4
band = calculateBand(bandLength)
// Range Weighted Moving Average (RWMA) Calculation
calculateRwma(range_, period) =>
weight = range_ / math.sum(range_, period)
sumWeightedClose = math.sum(close * weight, period)
totalWeight = math.sum(weight, period)
sumWeightedClose / totalWeight
rwma = calculateRwma(barRange, rwmaLength)
colour = positive ? bull : negative ? bear : na
rwmaAdjusted = positive ? rwma - band : negative ? rwma + band : na
max = rwma + band
min = rwma - band
longCondition = positive and not positive[1]
shortCondition = negative and not negative[1]
longExitCondition = shortCondition
shortExitCondition = longCondition
// Dynamic Trailing Stop Loss
vwma1 = switch maSrc
"SMA" => ta.sma(TfClose1*volume, len) / ta.sma(volume, len)
"EMA" => ta.ema(TfClose1*volume, len) / ta.ema(volume, len)
"WMA" => ta.wma(TfClose1*volume, len) / ta.wma(volume, len)
upperBand = vwma1 + factor * atr
lowerBand = vwma1 - factor * atr
prevLowerBand = nz(lowerBand[1])
prevUpperBand = nz(upperBand[1])
float superTrend = na
int direction = na
superTrend := direction == -1 ? lowerBand : upperBand
longTrailingStop = superTrend - atr * factor
shortTrailingStop = superTrend + atr * factor
// Strategy Order Execution
if (tradeDirection == "Long" or tradeDirection == "Both")
strategy.entry("Long", strategy.long, when = longCondition)
strategy.exit("Exit Long", "Long", when=longExitCondition, stop = longTrailingStop)
if (tradeDirection == "Short" or tradeDirection == "Both")
strategy.entry("Short", strategy.short, when =shortCondition)
strategy.exit("Exit Short", "Short", when=shortExitCondition, stop = shortTrailingStop) |
2Mars - MA / BB / SuperTrend | https://www.tradingview.com/script/Y68meyX1-2mars-ma-bb-supertrend/ | facejungle | https://www.tradingview.com/u/facejungle/ | 462 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
// | ╔══╗╔╗──╔╗╔══╗╔═══╗╔══╗ ____/\_____________ |
// | ╚═╗║║║──║║║╔╗║║╔═╗║║╔═╝ Strategy /\ / \/\ /\ |
// | ╔═╝║║╚╗╔╝║║╚╝║║╚═╝║║╚═╗ /\ __/__\/______\/________ |
// | ║╔═╝║╔╗╔╗║║╔╗║║╔╗╔╝╚═╗║ / \ /\/ |
// | ║╚═╗║║╚╝║║║║║║║║║║─╔═╝║ / \/ |
// | ╚══╝╚╝──╚╝╚╝╚╝╚╝╚╝─╚══╝ / ©facejungle |
// |__________________________/_________________________________|
strategy('2Mars - MA / BB / SuperTrend',
shorttitle = '2Mars',
overlay = true,
initial_capital = 10000,
pyramiding = 3,
currency = currency.USD,
default_qty_type = strategy.percent_of_equity,
default_qty_value = 5,
commission_type = strategy.commission.percent,
commission_value = 0.1,
margin_long = 100.0,
margin_short = 100.0,
max_bars_back = 5000,
calc_on_order_fills = false,
calc_on_every_tick = false,
process_orders_on_close = true,
use_bar_magnifier = false
)
import facejungle/utils/17 as utils
float epsilon = syminfo.mintick
int character_count = int(math.log10(1/epsilon))
float priceMedianHighLow = (high + low) / 2
float priceMedianOpenClose = (open + close) / 2
string GENERAL_GRP = 'General'
float priceSource = input.source(close, 'Source', group=GENERAL_GRP, display = display.none)
int barsConfirm = input.int(2, 'Bars confirm', minval=1, step=1, display = display.none, group=GENERAL_GRP)
string entryTrigger = input.string('close', 'Entry trigger', ['close', 'high/low', 'high/low median', 'open/close median'], group=GENERAL_GRP, display = display.none)
string ST_GRP = "SuperTrend"
bool useSuperTrendSignal = input.bool(false, title='SuperTrend as entry signal', tooltip = 'Not a required! Uses for additional entry to position. For entry will required confirm MA trend', display = display.none, group=ST_GRP)
bool useSuperTrend = input.bool(true, title='SuperTrend confirm', tooltip = 'Not a required! Uses for - Confirm entry to position. Stop-loss confirm. Stop-loss price.', display = display.none, group=ST_GRP)
float superTrendFactor = input.float(4, title="Factor", step=0.1, display = display.none, group=ST_GRP)
int superTrendPeriod = input.int(20, title="Length", display = display.none, group=ST_GRP)
[supertrendOrig, supertrendDirection] = ta.supertrend(superTrendFactor, superTrendPeriod)
float supertrend = ta.rma(supertrendOrig, 4)
string MA_GRP = "Moving average"
bool useMaStrategy = input.bool(true, title='Use MA Cross strategy', tooltip = 'Not a required! Uses for - Entry signal to position when signal and basis line cross (MA Cross strategy). When price cross the MA (add. orders #3).', display = display.none, group=MA_GRP)
string maBasisType = input.string('sma', 'Basis MA type', ['alma', 'ema', 'dema', 'tema', 'sma', 'smma', 'ssma', 'hma', 'rma', 'swma', 'vwma', 'wma', 'linreg', 'median', 'mom', 'high', 'low', 'medianHigh', 'medianLow', 'percentrank'], group=MA_GRP, display = display.none)
string maSignalType = input.string('sma', 'Signal MA type', ['alma', 'ema', 'dema', 'tema', 'sma', 'smma', 'ssma', 'hma', 'rma', 'swma', 'vwma', 'wma', 'linreg', 'median', 'mom', 'high', 'low', 'medianHigh', 'medianLow', 'percentrank'], group=MA_GRP, display = display.none)
float maRatio = input.float(1.08, 'Ratio', minval=0.01, step=0.02, group=MA_GRP, display = display.none)
int maMultiplier = input.int(89, 'Multiplier', minval=1, step=1, group=MA_GRP, tooltip = 'Basis length = Ratio * Multiplier, Signal length = Multiplier', display = display.none)
int maBasisLengh = math.round(maRatio * maMultiplier)
float maBasis = utils.maCustomseries(priceSource, maBasisType, maBasisLengh)
float maSignal = utils.maCustomseries(priceSource, maSignalType, maMultiplier)
string BB_GRP = "Bollinger Bands"
string bbType = input.string('wma', 'Type', ['alma', 'ema', 'dema', 'tema', 'sma', 'smma', 'ssma', 'hma', 'rma', 'swma', 'vwma', 'wma', 'linreg', 'median', 'mom', 'high', 'low', 'medianHigh', 'medianLow', 'percentrank'], tooltip = 'Not a required! Uses for - Take profit. Additionals orders #1 and #2. If use ATR stop-loss, lower and upper line #3 used for stop-loss price update.', group=BB_GRP, display = display.none)
int bbLength = input.int(30, 'length', minval=1, step=1, group=BB_GRP, display = display.none)
float bbMultiplier = input.float(3, minval=1, maxval=50, step=0.1, title="StdDev", group=BB_GRP, display = display.none)
string useBBLong = input.string('lower3', '↗️ Long orders :', ['lower', 'lower2', 'lower3', 'upper', 'upper2', 'upper3', 'off'], inline='Short orders', display = display.none)
string useBBLong2 = input.string('lower2', ' + ', ['lower', 'lower2', 'lower3', 'upper', 'upper2', 'upper3', 'off'], inline='Short orders', display = display.none)
string useBBLong3 = input.string('off', ' + ', ['basis', 'signal', 'off'], inline='Short orders', display = display.none)
string useBBShort = input.string('upper3', '↘️ Short orders:', ['upper', 'upper2', 'upper3', 'lower', 'lower2', 'lower3', 'off'], inline='Long orders', display = display.none)
string useBBShort2 = input.string('upper2', ' + ', ['upper', 'upper2', 'upper3', 'lower', 'lower2', 'lower3', 'off'], inline='Long orders', display = display.none)
string useBBShort3 = input.string('off', ' + ', ['basis', 'signal', 'off'], inline='Long orders', display = display.none)
[bbMiddle, bbUpper, bbUpper2, bbUpper3, bbUpper4, bbLower, bbLower2, bbLower3, bbLower4] = utils.fj_stdev(priceSource, bbLength, bbMultiplier, bbType)
string TP_GRP = "Take-Profit"
string takeProfitTrigger = input.string('close', 'Take-profit trigger', ['close', 'high/low', 'high/low median', 'open/close median'], tooltip = 'Not a required! Take-profit when the Bollinger band 1, 2, 3 crosses', group=TP_GRP, display = display.none)
bool useTakeProfit = input.bool(false, title='Use TP orders', display = display.none, group=TP_GRP)
bool useTakeProfit2 = input.bool(true, title='Use TP orders 2', display = display.none, group=TP_GRP)
bool useTakeProfit3 = input.bool(true, title='Use TP orders 3', display = display.none, group=TP_GRP)
int takeProfitLongQty = input.int(5, '↗️ Long qty %', minval=0, maxval=100, step=2, inline='takeQty', display = display.none, group=TP_GRP)
int takeProfitShortQty = input.int(5, '↘️ Short qty %', minval=0, maxval=100, step=2, inline='takeQty', display = display.none, group=TP_GRP)
string LO_GRP = "Limit-Orders"
bool useLimitOrder = input.bool(false, title='Use limit orders', tooltip = 'Calculate for before each entry order. Long: low price - ATR * Multiplier, Short: high price + ATR * Multiplier', display = display.none, group=LO_GRP)
int limitOrderPeriod = input.int(12, 'Length', minval=1, step=1, tooltip = 'ATR', display = display.none, group=LO_GRP)
float limitOrderMultiplier = input.float(0.1, 'Multiplier', step=0.1, display = display.none, group=LO_GRP)
series float limitOrderAtr = ta.atr(limitOrderPeriod)
var float limitOrderPrice = na
var string limitOrderDirection = 'flat'
float limitOrderPriceLong = useLimitOrder ? math.round(low - (limitOrderAtr * limitOrderMultiplier), character_count) : na
float limitOrderPriceShort = useLimitOrder ? math.round(high + (limitOrderAtr * limitOrderMultiplier), character_count) : na
string SL_GRP = "Stop-Loss"
string stopLossTrigger = input.string('open/close median', 'Stop-loss trigger', ['close', 'high/low', 'high/low median', 'open/close median'], group=SL_GRP, display = display.none)
string stopLossType = input.string('ATR', 'Stop-loss:', ['off', 'SuperTrend + ATR', 'ATR', 'StdDev'], tooltip = 'Update with each entry order and take profit #3. SuperTrend + ATR: update with each trend change not in our favor. If use "SuperTrend confirm", then the stop loss will require confirmation trend change.', group=SL_GRP, display = display.none)
int SLAtrPeriod = input.int(12, title="Length", tooltip = 'ATR and StdDev', display = display.none, group=SL_GRP)
float SLAtrMultiplierLong = input.float(6, title="Long mult.", step=0.1, tooltip = 'ATR: low - ATR * Long mult. / SuperTrend: SuperTrend - ATR * Long mult. / StdDev: low - StdDev - ATR * Long mult.', display = display.none, group=SL_GRP)
float SLAtrMultiplierShort = input.float(4.3, title="Short mult.", step=0.1, tooltip = 'ATR: high + ATR * Short mult. / SuperTrend: SuperTrend + ATR * Short mult. / StdDev: high + StdDev + ATR * Short mult.', display = display.none, group=SL_GRP)
series float stopLossAtr = ta.atr(SLAtrPeriod)
series float stopLossStdDev = ta.stdev(priceSource, SLAtrPeriod)
bool useFlexStopLoss = input.bool(false, title='Use flex stop-loss for ATR and StdDev', tooltip = 'If the SuperTrend or MA trend changes not in our favor, then adjusting the stop loss.', display = display.none, group=SL_GRP)
float SLFlexMult = input.float(0, step=0.1, title="Multiplier __________________________________", tooltip = 'Long: stop-loss price + (ATR * Long mult.) * Multiplier. Short: stop-loss price - (ATR * Short mult.) * Multiplier.', display = display.none, group=SL_GRP)
var series float stopLossPriceLong = na
var series float stopLossPriceShort = na
float calcStopLossPriceLong =
stopLossType == 'SuperTrend + ATR' ? math.round(supertrend[1] - (stopLossAtr * SLAtrMultiplierLong), character_count) :
stopLossType == 'ATR' ? math.round(low - (stopLossAtr * SLAtrMultiplierLong), character_count):
stopLossType == 'StdDev' ? math.round(low - stopLossStdDev - (stopLossAtr * SLAtrMultiplierLong), character_count) :
na
float calcStopLossPriceShort =
stopLossType == 'SuperTrend + ATR' ? math.round(supertrend[1] + (stopLossAtr * SLAtrMultiplierShort), character_count) :
stopLossType == 'ATR' ? math.round(high + (stopLossAtr * SLAtrMultiplierShort), character_count) :
stopLossType == 'StdDev' ? math.round(high + stopLossStdDev + (stopLossAtr * SLAtrMultiplierShort), character_count) :
na
// >>>>>>>>>>>>>>>>>>>>>> Counters
counterEvent(bool enent, bool enent2) =>
int scount = 0
scount := enent and enent2 ? nz(scount[1]) + 1 : 0
barCrossoverCounter(float signalPrice, float basePrice) =>
bool bcond = signalPrice > basePrice
int bcount = 0
bcount := bcond ? nz(bcount[1]) + 1 : 0
barCrossunderCounter(float signalPrice, float basePrice) =>
bool scond = signalPrice < basePrice
int scount = 0
scount := scond ? nz(scount[1]) + 1 : 0
// _________________________________________________
// v v
// v CONDITIONS BLOCK v
// v_______________________________________________v
float entryTriggerLong = entryTrigger == 'high/low' ? high : entryTrigger == 'high/low median' ? priceMedianHighLow : entryTrigger == 'open/close median' ? priceMedianOpenClose : close
bool condPositionLong = strategy.position_size > 0
bool condSuperTrendLong = supertrendDirection < 0
bool condSuperTrendLongSignal = barsConfirm == barCrossunderCounter(supertrendDirection, 0)
bool condMaLong = barsConfirm == barCrossoverCounter(maSignal, maBasis)
bool condBasisLong = barsConfirm == barCrossoverCounter(entryTriggerLong, maBasis)
bool condSignalLong = barsConfirm == barCrossoverCounter(entryTriggerLong, maSignal)
bool condBBLong1 = barsConfirm == barCrossoverCounter(entryTriggerLong, bbLower)
bool condBBLong2 = barsConfirm == barCrossoverCounter(entryTriggerLong, bbLower2)
bool condBBLong3 = barsConfirm == barCrossoverCounter(entryTriggerLong, bbLower3)
bool condBBLong4 = barsConfirm == barCrossoverCounter(entryTriggerLong, bbUpper)
bool condBBLong5 = barsConfirm == barCrossoverCounter(entryTriggerLong, bbUpper2)
bool condBBLong6 = barsConfirm == barCrossoverCounter(entryTriggerLong, bbUpper3)
float entryTriggerShort = entryTrigger == 'high/low' ? low : entryTrigger == 'high/low median' ? priceMedianHighLow : entryTrigger == 'open/close median' ? priceMedianOpenClose : close
bool condPositionShort = strategy.position_size < 0
bool condSuperTrendShort = supertrendDirection > 0
bool condSuperTrendShortSignal = barsConfirm == barCrossoverCounter(supertrendDirection, 0)
bool condMaShort = barsConfirm == barCrossunderCounter(maSignal, maBasis)
bool condBasisShort = barsConfirm == barCrossunderCounter(entryTriggerShort, maBasis)
bool condSignalShort = barsConfirm == barCrossunderCounter(entryTriggerShort, maSignal)
bool condBBShort1 = barsConfirm == barCrossunderCounter(entryTriggerShort, bbUpper)
bool condBBShort2 = barsConfirm == barCrossunderCounter(entryTriggerShort, bbUpper2)
bool condBBShort3 = barsConfirm == barCrossunderCounter(entryTriggerShort, bbUpper3)
bool condBBShort4 = barsConfirm == barCrossunderCounter(entryTriggerShort, bbLower)
bool condBBShort6 = barsConfirm == barCrossunderCounter(entryTriggerShort, bbLower3)
bool condBBShort5 = barsConfirm == barCrossunderCounter(entryTriggerShort, bbLower2)
// _________________________________________________
// v v
// v TRADING FUNCTIONS BLOCK v
// v_______________________________________________v
stopLossShort(string orderComment=na) =>
strategy.cancel('Short') // cancel short orders
strategy.close ('Short', qty_percent = 100, comment = na(orderComment) == false ? orderComment : na)
stopLossLong(string orderComment=na) =>
strategy.cancel('Long') // cancel long orders
strategy.close ('Long', qty_percent = 100, comment = na(orderComment) == false ? orderComment : na)
// >>>>>>>>>>>>>>>>>>>>>> Function for entry to long position
newEntryLong(string orderComment=na) =>
if condPositionShort
stopLossShort('Close short')
strategy.entry(
'Long',
strategy.long,
stop = stopLossType != 'off' ? stopLossPriceLong : na,
limit = useLimitOrder ? limitOrderPriceLong : na,
comment = na(orderComment) == false ? orderComment : na
)
// >>>>>>>>>>>>>>>>>>>>>> Function for entry to short position
newEntryShort(string orderComment=na) =>
if condPositionLong
stopLossLong('Close short')
strategy.entry(
'Short',
strategy.short,
stop = stopLossType != 'off' ? stopLossPriceShort : na,
limit = useLimitOrder ? limitOrderPriceShort : na,
comment = na(orderComment) == false ? orderComment : na
)
// >>>>>>>>>>>>>>>>>>>>>>
takeLong(string orderComment=na) =>
strategy.close('Long', qty_percent = takeProfitLongQty, comment = na(orderComment) == false ? orderComment : na)
// >>>>>>>>>>>>>>>>>>>>>>
takeShort(string orderComment=na) =>
strategy.close('Short', qty_percent = takeProfitShortQty, comment = na(orderComment) == false ? orderComment : na)
// _________________________________________________
// v v
// v POSITION ENTRIES BLOCK v
// v_______________________________________________v
if useSuperTrendSignal
if condSuperTrendLongSignal and maSignal > maBasis
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong(orderComment=utils.commentOrderCustomseries('enter_long', 'supertrend'))
if condSuperTrendShortSignal and maSignal < maBasis
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('enter_short', 'supertrend'))
if useSuperTrend
// >>>>>>>>>>>>>>>>>>>>>> LONG ORDERS WITH SuperTrend
//-> Additionals ordrders #1-2
if useBBLong == 'lower' or useBBLong2 == 'lower'
if condBBLong1 and condSuperTrendLong
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong(orderComment=utils.commentOrderCustomseries('enter_long', 'bbLower' ))
if useBBLong == 'lower2' or useBBLong2 == 'lower2'
if condBBLong2 and condSuperTrendLong
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong(orderComment=utils.commentOrderCustomseries('enter_long', 'bbLower2'))
if useBBLong == 'lower3' or useBBLong2 == 'lower3'
if condBBLong3 and condSuperTrendLong
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong(orderComment=utils.commentOrderCustomseries('enter_long', 'bbLower3'))
if useBBLong == 'upper' or useBBLong2 == 'upper'
if condBBLong4 and condSuperTrendLong
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong(orderComment=utils.commentOrderCustomseries('enter_long', 'bbUpper'))
if useBBLong == 'upper2' or useBBLong2 == 'upper2'
if condBBLong5 and condSuperTrendLong
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong( orderComment=utils.commentOrderCustomseries('enter_long', 'bbUpper2'))
if useBBLong == 'upper3' or useBBLong2 == 'upper3'
if condBBLong6 and condSuperTrendLong
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong(orderComment=utils.commentOrderCustomseries('enter_long', 'bbUpper3'))
//-> Additionals ordrders #3
if useBBLong3 == 'basis'
if condBasisLong and condSuperTrendLong
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong(orderComment=utils.commentOrderCustomseries('enter_long', 'maBasis'))
if useBBLong3 == 'signal'
if condSignalLong and condSuperTrendLong
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong(orderComment=utils.commentOrderCustomseries('enter_long', 'maSignal'))
//-> cross ma strategy
if useMaStrategy and condSuperTrendLong and condMaLong
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong(orderComment=utils.commentOrderCustomseries('enter_long', 'maCross'))
// >>>>>>>>>>>>>>>>>>>>>> SHORT ORDERS WITH SuperTrend
//-> Additionals ordrders #1-2
if useBBShort == 'upper' or useBBShort2 == 'upper'
if condBBShort1 and condSuperTrendShort
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('enter_short', 'bbUpper'))
if useBBShort == 'upper2' or useBBShort2 == 'upper2'
if condBBShort2 and condSuperTrendShort
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('enter_short', 'bbUpper2'))
if useBBShort == 'upper3' or useBBShort2 == 'upper3'
if condBBShort3 and condSuperTrendShort
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('enter_short', 'bbUpper3'))
if useBBShort == 'lower' or useBBShort2 == 'lower'
if condBBShort4 and condSuperTrendShort
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('enter_short', 'bbLower'))
if useBBShort == 'lower2' or useBBShort2 == 'lower2'
if condBBShort5 and condSuperTrendShort
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('enter_short', 'bbLower2'))
if useBBShort == 'lower3' or useBBShort2 == 'lower3'
if condBBShort6 and condSuperTrendShort
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('enter_short', 'bbLower3'))
//-> Additionals ordrders #3
if useBBShort3 == 'basis'
if condBasisShort and condSuperTrendShort
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('enter_short', 'maBasis'))
if useBBShort3 == 'signal'
if condSignalShort and condSuperTrendShort
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('enter_short', 'maSignal'))
//-> cross ma strategy
if useMaStrategy and condSuperTrendShort and condMaShort
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('enter_short', 'maCross'))
else
// >>>>>>>>>>>>>>>>>>>>>> LONG ORDERS
//vvvvvvvvv Additionals ordrders #1-2 vvvvvvvvv
if useBBLong == 'lower' or useBBLong2 == 'lower'
if condBBLong1
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong(orderComment=utils.commentOrderCustomseries('enter_long', 'bbLower'))
if useBBLong == 'lower2' or useBBLong2 == 'lower2'
if condBBLong2
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong(orderComment=utils.commentOrderCustomseries('enter_long', 'bbLower2'))
if useBBLong == 'lower3' or useBBLong2 == 'lower3'
if condBBLong3
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong(orderComment=utils.commentOrderCustomseries('enter_long', 'bbLower3'))
if useBBLong == 'upper' or useBBLong2 == 'upper'
if condBBLong4
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong(orderComment=utils.commentOrderCustomseries('enter_long', 'bbUpper'))
if useBBLong == 'upper2' or useBBLong2 == 'upper2'
if condBBLong5
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong(orderComment=utils.commentOrderCustomseries('enter_long', 'bbUpper2'))
if useBBLong == 'upper3' or useBBLong2 == 'upper3'
if condBBLong6
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong(orderComment=utils.commentOrderCustomseries('enter_long', 'bbUpper3'))
//vvvvvvvvv Additionals ordrders #3 vvvvvvvvv
if useBBLong3 == 'basis'
if condBasisLong
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong(orderComment=utils.commentOrderCustomseries('enter_long', 'maBasis'))
if useBBLong3 == 'signal'
if condSignalLong
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong(orderComment=utils.commentOrderCustomseries('enter_long', 'maSignal'))
//vvvvvvvvv cross ma strategy vvvvvvvvv
if useMaStrategy and condMaLong
limitOrderPrice := limitOrderPriceLong
limitOrderDirection := 'Long'
stopLossPriceLong := calcStopLossPriceLong
newEntryLong(orderComment=utils.commentOrderCustomseries('enter_long', 'maCross'))
// >>>>>>>>>>>>>>>>>>>>>> SHORT ORDERS
//vvvvvvvvv Additionals ordrders #1-2 vvvvvvvvv
if useBBShort == 'upper' or useBBShort2 == 'upper'
if condBBShort1
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('Short', 'bbUpper'))
if useBBShort == 'upper2' or useBBShort2 == 'upper2'
if condBBShort2
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('Short', 'bbUpper2'))
if useBBShort == 'upper3' or useBBShort2 == 'upper3'
if condBBShort3
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('Short', 'bbUpper3'))
if useBBShort == 'lower' or useBBShort2 == 'lower'
if condBBShort4
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('Short', 'bbLower'))
if useBBShort == 'lower2' or useBBShort2 == 'lower2'
if condBBShort5
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('Short', 'bbLower2'))
if useBBShort == 'lower3' or useBBShort2 == 'lower3'
if condBBShort6
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('Short', 'bbLower3'))
//vvvvvvvvv Additionals ordrders #3 vvvvvvvvv
if useBBShort3 == 'basis'
if condBasisShort
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('Short', 'maBasis'))
if useBBShort3 == 'signal'
if condSignalShort
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('Short', 'maSignal'))
//vvvvvvvvv Cross MA strategy vvvvvvvvv
if useMaStrategy and condMaShort
limitOrderPrice := limitOrderPriceShort
limitOrderDirection := 'Short'
stopLossPriceShort := calcStopLossPriceShort
newEntryShort(orderComment=utils.commentOrderCustomseries('Short', 'maCross'))
// _________________________________________________
// v v
// v TAKE PROFIT BLOCK v
// v_______________________________________________v
// >>>>>>>>>>>>>>>>>>>>>> Conditions
float takeTriggerLong = takeProfitTrigger == 'high/low' ? high : takeProfitTrigger == 'high/low median' ? priceMedianHighLow : takeProfitTrigger == 'open/close median' ? priceMedianOpenClose : close
bool condTakePriceLong = strategy.position_avg_price < close
bool condTakeLong1 = ta.crossover(takeTriggerLong, bbUpper[1]) and condPositionLong
bool condTakeLong2 = ta.crossover(takeTriggerLong, bbUpper2[1]) and condPositionLong
bool condTakeLong3 = ta.crossover(takeTriggerLong, bbUpper3[1]) and condPositionLong
float takeTriggerhort = takeProfitTrigger == 'high/low' ? low : takeProfitTrigger == 'high/low median' ? priceMedianHighLow : takeProfitTrigger == 'open/close median' ? priceMedianOpenClose : close
bool condTakePriceShort = strategy.position_avg_price > close
bool condTakeShort1 = ta.crossunder(takeTriggerhort, bbLower[1]) and condPositionShort
bool condTakeShort2 = ta.crossunder(takeTriggerhort, bbLower2[1]) and condPositionShort
bool condTakeShort3 = ta.crossunder(takeTriggerhort, bbLower3[1]) and condPositionShort
// >>>>>>>>>>>>>>>>>>>>>> Use take profit
if useTakeProfit
if condTakeLong1 and condTakePriceLong
takeLong(utils.commentOrderCustomseries('take_long', 'bbUpper', qty = takeProfitLongQty))
if condTakeShort1 and condTakePriceShort
takeShort(utils.commentOrderCustomseries('take_short', 'bbLower', qty = takeProfitShortQty))
// >>>>>>>>>>>>>>>>>>>>>> Use take profit 2
if useTakeProfit2
if condTakeLong2 and condTakePriceLong
takeLong(utils.commentOrderCustomseries('take_long', 'bbUpper2', qty = takeProfitLongQty))
if condTakeShort2 and condTakePriceShort
takeShort(utils.commentOrderCustomseries('take_short', 'bbLower2', qty = takeProfitShortQty))
// >>>>>>>>>>>>>>>>>>>>>> Use take profit 3
if useTakeProfit3
if condTakeLong3 and condTakePriceLong
stopLossPriceLong := calcStopLossPriceLong
takeLong(utils.commentOrderCustomseries('take_long', 'bbUpper3', qty = takeProfitLongQty))
if condTakeShort3 and condTakePriceShort
stopLossPriceShort := calcStopLossPriceShort
takeShort(utils.commentOrderCustomseries('take_short', 'bbLower3', qty = takeProfitShortQty))
// _________________________________________________
// v v
// v STOP LOSS BLOCK v
// v_______________________________________________v
// >>>>>>>>>>>>>>>>>>>>>> Conditions
bool condStopSuperTrendLong = barCrossoverCounter(supertrendDirection, 0) == 1 and condPositionLong
bool condStopSuperTrendShort = barCrossunderCounter(supertrendDirection, 0) == 1 and condPositionShort
bool condStopFlexSuperTrendLong = counterEvent(condPositionLong, condSuperTrendShort) == 1
bool condStopFlexMaLong = counterEvent(condPositionLong, condMaShort) == 1
bool condStopFlexSuperTrendShort = counterEvent(condPositionShort, condSuperTrendLong) == 1
bool condStopFlexMaShort = counterEvent(condPositionShort, condMaLong) == 1
// >>>>>>>>>>>>>>>>>>>>>> Setting stop loss price for SuperTrend option
if stopLossType == 'SuperTrend + ATR'
if condStopSuperTrendLong
stopLossPriceLong := supertrend[1] - (stopLossAtr * SLAtrMultiplierLong)
if stopLossType == 'SuperTrend + ATR'
if condStopSuperTrendShort
stopLossPriceShort := supertrend[1] + (stopLossAtr * SLAtrMultiplierShort)
// >>>>>>>>>>>>>>>>>>>>>> Setting flex stop loss price for ATR and StdDev options
if useFlexStopLoss
if stopLossType == 'ATR' or stopLossType == 'StdDev'
if condStopFlexSuperTrendLong
stopLossPriceLong := stopLossPriceLong + (stopLossAtr * SLAtrMultiplierLong) * SLFlexMult
if condStopFlexMaLong
stopLossPriceLong := stopLossPriceLong + (stopLossAtr * SLAtrMultiplierLong) * SLFlexMult
if condStopFlexSuperTrendShort
stopLossPriceShort := stopLossPriceShort - (stopLossAtr * SLAtrMultiplierLong) * SLFlexMult
if condStopFlexMaShort
stopLossPriceShort := stopLossPriceShort - (stopLossAtr * SLAtrMultiplierLong) * SLFlexMult
// >>>>>>>>>>>>>>>>>>>>>> Trading logic
float stopTriggerLong = stopLossTrigger == 'high/low' ? low : stopLossTrigger == 'high/low median' ? priceMedianHighLow : stopLossTrigger == 'open/close median' ? priceMedianOpenClose : close
bool condStopLong = stopTriggerLong < stopLossPriceLong and condPositionLong
float stopTriggerShort = stopLossTrigger == 'high/low' ? high : stopLossTrigger == 'high/low median' ? priceMedianHighLow : stopLossTrigger == 'open/close median' ? priceMedianOpenClose : close
bool condStopShort = stopTriggerShort > stopLossPriceShort and condPositionShort
if stopLossType != 'off'
if useSuperTrend
if condStopLong and condSuperTrendShort
stopLossLong(utils.commentOrderCustomseries('stop_long', 'stop'))
if limitOrderDirection == 'Long'
limitOrderPrice := na
limitOrderDirection := 'flat'
if condStopShort and condSuperTrendLong
if limitOrderDirection == 'Short'
limitOrderPrice := na
limitOrderDirection := 'flat'
stopLossShort(utils.commentOrderCustomseries('stop_short', 'stop'))
else
if condStopLong
if limitOrderDirection == 'Long'
limitOrderPrice := na
limitOrderDirection := 'flat'
stopLossLong(utils.commentOrderCustomseries('stop_long', 'stop'))
if condStopShort
if limitOrderDirection == 'Short'
limitOrderPrice := na
limitOrderDirection := 'flat'
stopLossShort(utils.commentOrderCustomseries('stop_short', 'stop'))
// _________________________________________________
// v v
// v LIMIT ORDER BLOCK v
// v_______________________________________________v
// >>>>>>>>>>>>>>>>>>>>>> Conditions
bool condLimitPrirceExist = na(limitOrderPrice) == false
// >>>>>>>>>>>>>>>>>>>>>> limit orders triggered
if useLimitOrder and condLimitPrirceExist
for i = 1 to strategy.opentrades
if math.abs(limitOrderPrice - strategy.opentrades.entry_price(strategy.opentrades - i)) < epsilon
limitOrderPrice := na
limitOrderDirection := 'flat'
// _________________________________________________
// v v
// v PLOT BLOCK v
// v_______________________________________________v
colorGreen = #00ff08cc
colorGreen2 = #00ff0863
colorGreen3 = #089981
colorRed = #ff0000d4
colorRed2 = #ff000071
colorPurple = #8400ff23
colorPurple2 = #45008657
colorPurple3 = #8400ff09
colorOrange = #f57b00c7
colorBlack = color.rgb(70, 70, 70, 50)
// >>>>>>>>>>>>>>>>>>>>>> SuperTrend
pPriceMedian = plot(useSuperTrend ? priceMedianOpenClose : na, "[Price Median]", color=color.black, linewidth=1, style=plot.style_line, display=display.none)
pSuperTrend = plot(useSuperTrend ? supertrend : na, "[SuperTrend]", color=condSuperTrendLong ? colorGreen2 : colorRed2, linewidth=2, style=plot.style_line, display=useSuperTrend ? display.pane : display.none)
fill(pPriceMedian, pSuperTrend, title = "[SuperTrend] Background", color = condSuperTrendLong ? color.rgb(0, 255, 8, 90) : color.rgb(255, 0, 0, 90), display = display.all)
// >>>>>>>>>>>>>>>>>>>>>> Moving Averages
basis = plot(maBasis, "[MA] Basis", color = maSignal > maBasis ? colorGreen2 : colorRed2, linewidth=1, style=plot.style_line, display=display.pane)
signal = plot(maSignal, "[MA] Signal", color = maSignal > maBasis ? colorGreen2 : colorRed2, linewidth=1, style=plot.style_line, display=display.pane)
plot(ta.crossover(maSignal, maBasis) ? maBasis : na, "[MA] Long signal", color=colorGreen, style = plot.style_circles, linewidth = 4, display=display.pane)
plot(ta.crossunder(maSignal, maBasis) ? maBasis : na, "[MA] Short signal", color=colorRed, style = plot.style_circles, linewidth = 4, display=display.pane)
fill(basis, signal, title = "[MA] Background", color = maSignal > maBasis ? colorGreen2 : colorRed2, display = display.all)
// >>>>>>>>>>>>>>>>>>>>>> Stop loss
bool plotCondStopLossLong = useSuperTrend ? condPositionLong and condSuperTrendShort : condPositionLong
bool plotCondStopLossShort = useSuperTrend ? condPositionShort and condSuperTrendLong : condPositionShort
plot(condPositionLong? stopLossPriceLong : na, "Stop-loss price: Long", color=plotCondStopLossLong ? colorRed : colorOrange, style = plot.style_linebr, linewidth = 2, display=display.none)
plot(condPositionShort? stopLossPriceShort : na, "Stop-loss price: Short", color=plotCondStopLossShort ? colorRed : colorOrange, style = plot.style_linebr, linewidth = 2, display=display.none)
// >>>>>>>>>>>>>>>>>>>>>> Bollinger bands
u1 = plot(bbUpper, "[BB] Upper", color=colorPurple, display = display.pane)
l1 = plot(bbLower, "[BB] Lower", color=colorPurple, display = display.pane)
u2 = plot(bbUpper2, "[BB] Upper 2", color=colorPurple, display = display.pane)
l2 = plot(bbLower2, "[BB] Lower 2", color=colorPurple, display = display.pane)
u3 = plot(bbUpper3, "[BB] Upper 2", color=colorPurple, display = display.pane)
l3 = plot(bbLower3, "[BB] Lower 2", color=colorPurple, display = display.pane)
fill(u1, l1, title = "[BB] Background 1-1", color=colorPurple3, display = display.all)
fill(u2, l2, title = "[BB] Background 2-2", color=colorPurple3, display = display.all)
fill(u3, l3, title = "[BB] Background 3-3", color=colorPurple3, display = display.all)
// _________________________________________________
// v v
// v CURRENT POSITION BLOCK v
// v_______________________________________________v
var string currentPosition = 'flat'
currentPosition := strategy.position_size > 0 ? 'Long ↗' : 'Short ↘'
if strategy.position_size == 0
currentPosition := 'flat'
bool condPositionExist = currentPosition == 'Long ↗' or currentPosition == 'Short ↘'
float lastEntryPrice = strategy.opentrades.entry_price(strategy.opentrades - 1)
// >>>>>>>>>>>>>>>>>>>>>> Position table
var table positionTable = table.new(position = position.top_right, columns = 2, rows = 5)
table.cell(table_id = positionTable, column = 1, row = 0, text = "Position", bgcolor=colorBlack, text_color=color.white, text_halign = text.align_right, tooltip = strategy.opentrades == 1 ? strategy.opentrades.entry_comment(strategy.opentrades - 1) : na)
table.clear(positionTable, 0, 1, 1, 4)
table.cell(table_id = positionTable, column = 0, row = 1, text = "Direction:", bgcolor=colorBlack, text_color=color.white, text_halign = text.align_left)
table.cell(table_id = positionTable, column = 1, row = 1, text = currentPosition, bgcolor=strategy.opentrades == 0 ? colorBlack : condPositionShort ? colorRed2 : colorGreen3, text_color=color.rgb(255, 255, 255), text_halign = text.align_right)
if condPositionExist
table.cell(table_id = positionTable, column = 0, row = 2, text = "Amount:", bgcolor=colorBlack, text_color=color.white, text_halign = text.align_left)
table.cell(table_id = positionTable, column = 1, row = 2, text =str.tostring(strategy.position_size), bgcolor=colorBlack, text_color=color.white, text_halign = text.align_right)
if strategy.opentrades > 1
table.cell(table_id = positionTable, column = 0, row = 3, text = "Avg. price:", bgcolor=colorBlack, text_color=color.white, text_halign = text.align_left)
table.cell(table_id = positionTable, column = 1, row = 3, text =str.tostring(strategy.position_avg_price, '#.###'), bgcolor=colorBlack, text_color=color.white, text_halign = text.align_right)
if strategy.opentrades == 1
table.cell(table_id = positionTable, column = 0, row = 3, text = "Entry price:", bgcolor=colorBlack, text_color=color.white, text_halign = text.align_left, tooltip = strategy.opentrades == 1 ? strategy.opentrades.entry_comment(strategy.opentrades - 1) : na)
table.cell(table_id = positionTable, column = 1, row = 3, text =str.tostring(strategy.opentrades.entry_price(strategy.opentrades - 1), '#.###'), bgcolor=colorBlack, text_color=color.white, text_halign = text.align_right)
if stopLossType != 'off'
table.cell(table_id = positionTable, column = 0, row = 4, text = "Stop Loss:", bgcolor=colorBlack, text_color=color.white)
table.cell(table_id = positionTable, column = 1, row = 4, text =str.tostring(strategy.position_size > 0 ? stopLossPriceLong : stopLossPriceShort, '#.###'), bgcolor=colorBlack, text_color=color.white)
// >>>>>>>>>>>>>>>>>>>>>> Entries table
var table entriesTable = table.new(position = position.middle_right, columns = 2, rows = 6)
if strategy.opentrades > 1 and strategy.opentrades < 5
table.cell(table_id = entriesTable, column = 1, row = 0, text = "Entries", bgcolor=colorBlack, text_color=color.white, text_halign = text.align_right)
table.clear(entriesTable, 0, 1, 1, 5)
for i = 1 to strategy.opentrades by 1
table.cell(table_id = entriesTable, column = 0, row = 0 + i, text = '#' + str.tostring(i), bgcolor=colorBlack, text_color=color.white, text_halign = text.align_left)
table.cell(table_id = entriesTable, column = 1, row = 0 + i, text =str.tostring(strategy.opentrades.entry_price(strategy.opentrades - i)) + ' 💬', bgcolor=colorBlack, text_color=color.white, text_halign = text.align_right, tooltip = strategy.opentrades.entry_comment(strategy.opentrades - i))
else if strategy.opentrades <= 1
table.clear(entriesTable, 0, 0, 1, 5)
// >>>>>>>>>>>>>>>>>>>>>> Limit Order table
if useLimitOrder
var table limitOrderTable = table.new(position = position.bottom_right, columns = 2, rows = 3)
table.clear(limitOrderTable, 0, 0, 1, 2)
if na(limitOrderPrice) == false
table.cell(table_id = limitOrderTable, column = 1, row = 0, text = "Limit order", bgcolor=colorBlack, text_color=color.white, text_halign = text.align_right)
table.cell(table_id = limitOrderTable, column = 0, row = 1, text = "Direction:", bgcolor=colorBlack, text_color=color.white, text_halign = text.align_left)
table.cell(table_id = limitOrderTable, column = 1, row = 1, text =str.tostring(limitOrderDirection), bgcolor=limitOrderDirection == 'Short' ? colorRed2 : colorGreen3, text_color=color.white, text_halign = text.align_right)
table.cell(table_id = limitOrderTable, column = 0, row = 2, text = "Price:", bgcolor=colorBlack, text_color=color.white, text_halign = text.align_left)
table.cell(table_id = limitOrderTable, column = 1, row = 2, text =str.tostring(limitOrderPrice), bgcolor=colorBlack, text_color=color.white, text_halign = text.align_right) |
Double AI Super Trend Trading - Strategy [PresentTrading] | https://www.tradingview.com/script/hLZPT7it-Double-AI-Super-Trend-Trading-Strategy-PresentTrading/ | PresentTrading | https://www.tradingview.com/u/PresentTrading/ | 588 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © PresentTrading
//@version=5
strategy("Double AI Super Trend Trading - Strategy [PresentTrading]", overlay=true, precision=3, default_qty_type=strategy.cash,
commission_value= 0.1, commission_type=strategy.commission.percent, slippage= 1,
currency=currency.USD, default_qty_type = strategy.percent_of_equity, default_qty_value = 10, initial_capital= 10000)
// ~~ ToolTips {
t1="Number of nearest neighbors in KNN algorithm (k): Increase to consider more neighbors, providing a more balanced view but possibly smoothing out local patterns. Decrease for fewer neighbors to make the algorithm more responsive to recent changes. \n\nNumber of data points to consider (n): Increase for more historical data, providing a broader context but possibly diluting recent trends. Decrease for less historical data to focus more on recent behavior."
t2="Length of weighted moving average for price (KNN_PriceLen): Higher values create a smoother price line, influencing the KNN algorithm to be more stable but less sensitive to short-term price movements. Lower values enhance responsiveness in KNN predictions to recent price changes but may lead to more noise. \n\nLength of weighted moving average for SuperTrend (KNN_STLen): Higher values lead to a smoother SuperTrend line, affecting the KNN algorithm to emphasize long-term trends. Lower values make KNN predictions more sensitive to recent SuperTrend changes but may result in more volatility."
t3="Length of the SuperTrend (len): Increase for a smoother trend line, ideal for identifying long-term trends but possibly ignoring short-term fluctuations. Decrease for more responsiveness to recent changes but risk of more false signals. \n\nMultiplier for ATR in SuperTrend calculation (factor): Increase for wider bands, capturing larger price movements but possibly missing subtle changes. Decrease for narrower bands, more sensitive to small shifts but risk of more noise."
t4="Type of moving average for SuperTrend calculation (maSrc): Choose based on desired characteristics. SMA is simple and clear, EMA emphasizes recent prices, WMA gives more weight to recent data, RMA is less sensitive to recent changes, and VWMA considers volume."
t5="Color for bullish trend (upCol): Select to visually identify upward trends. \n\nColor for bearish trend (dnCol): Select to visually identify downward trends.\n\nColor for neutral trend (neCol): Select to visually identify neutral trends."
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// Add Button for Trading Direction
tradeDirection = input.string("Both", "Select Trading Direction", options=["Long", "Short", "Both"])
// ~~ Input settings for K and N values
k = input.int(3, title = "Neighbors", minval=1, maxval=100,inline="AI", group="AI Settings")
n_ = input.int(12, title ="Data", minval=1, maxval=100,inline="AI", group="AI Settings", tooltip=t1)
n = math.max(k,n_)
// Second KNN Parameters
k2 = input.int(5, title = "2nd Neighbors", minval=1, maxval=100,inline="AI2", group="AI2 Settings")
n2_ = input.int(20, title ="2nd Data", minval=1, maxval=100,inline="AI2", group="AI2 Settings")
n2 = math.max(k2, n2_)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Input settings for prediction values
KNN_PriceLen = input.int(20, title="Price Trend", minval=2, maxval=500, step=10,inline="AITrend", group="AI Trend")
KNN_STLen = input.int(80, title="Prediction Trend", minval=2, maxval=500, step=10, inline="AITrend", group="AI Trend", tooltip=t2)
KNN_PriceLen2 = input.int(40, title="2nd Price Trend", minval=2, maxval=500, step=10,inline="AI2Trend", group="AI Trend")
KNN_STLen2 = input.int(80, title="2nd Prediction Trend", minval=2, maxval=500, step=10, inline="AI2Trend", group="AI Trend")
aisignals = input.bool(true,title="AI Trend Signals",inline="signal", group="AI Trend")
Bullish_col = input.color(color.lime,"",inline="signal", group="AI Trend")
Bearish_col = input.color(color.red,"",inline="signal", group="AI Trend")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Define SuperTrend parameters
maSrc = input.string("WMA","Moving Average Source",["SMA","EMA","WMA","RMA","VWMA"],inline="", group="Super Trend Settings", tooltip=t4)
len = input.int(10, "Length", minval=1,inline="SuperTrend", group="Super Trend Settings")
factor = input.float(4.0,step=.1,inline="SuperTrend", group="Super Trend Settings", tooltip=t3)
// Calculate the Second SuperTrend
len2 = input.int(5, "2nd Length", minval=1,inline="SuperTrend", group="Super Trend Settings")
factor2 = input.float(3.0,step=.1,inline="SuperTrend", group="Super Trend Settings")
upCol = input.color(color.lime,"Bullish Color",inline="col", group="Super Trend Coloring")
dnCol = input.color(color.red,"Bearish Color",inline="col", group="Super Trend Coloring")
neCol = input.color(color.blue,"Neutral Color",inline="col", group="Super Trend Coloring", tooltip=t5)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Calculate the SuperTrend based on the user's choice
vwma = switch maSrc
"SMA" => ta.sma(close*volume, len) / ta.sma(volume, len)
"EMA" => ta.ema(close*volume, len) / ta.ema(volume, len)
"WMA" => ta.wma(close*volume, len) / ta.wma(volume, len)
"RMA" => ta.rma(close*volume, len) / ta.rma(volume, len)
"VWMA" => ta.vwma(close*volume, len) / ta.vwma(volume, len)
atr = ta.atr(len)
upperBand = vwma + factor * atr
lowerBand = vwma - factor * atr
prevLowerBand = nz(lowerBand[1])
prevUpperBand = nz(upperBand[1])
atr2 = ta.atr(len2)
upperBand2 = vwma + factor2 * atr2
lowerBand2 = vwma - factor2 * atr2
prevLowerBand2 = nz(lowerBand2[1])
prevUpperBand2 = nz(upperBand2[1])
lowerBand := lowerBand > prevLowerBand or close[1] < prevLowerBand ? lowerBand : prevLowerBand
upperBand := upperBand < prevUpperBand or close[1] > prevUpperBand ? upperBand : prevUpperBand
int direction = na
float superTrend = na
lowerBand2 := lowerBand2 > prevLowerBand2 or close[1] < prevLowerBand2 ? lowerBand2 : prevLowerBand2
upperBand2 := upperBand2 < prevUpperBand2 or close[1] > prevUpperBand2 ? upperBand2 : prevUpperBand2
int direction2 = na
float superTrend2 = na
prevSuperTrend = superTrend[1]
if na(atr[1])
direction := 1
else if prevSuperTrend == prevUpperBand
direction := close > upperBand ? -1 : 1
else
direction := close < lowerBand ? 1 : -1
superTrend := direction == -1 ? lowerBand : upperBand
prevSuperTrend2 = superTrend2[1]
if na(atr2[1])
direction2 := 1
else if prevSuperTrend2 == prevUpperBand2
direction2 := close > upperBand2 ? -1 : 1
else
direction2 := close < lowerBand2 ? 1 : -1
superTrend2 := direction2 == -1 ? lowerBand2 : upperBand2
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Collect data points and their corresponding labels
price = ta.wma(close,KNN_PriceLen)
sT = ta.wma(superTrend,KNN_STLen)
data = array.new_float(n)
labels = array.new_int(n)
for i = 0 to n - 1
data.set(i, superTrend[i])
label_i = price[i] > sT[i] ? 1 : 0
labels.set(i, label_i)
// Collect data points for second SuperTrend and their corresponding labels
price2 = ta.wma(close,KNN_PriceLen2)
sT2 = ta.wma(superTrend2,KNN_STLen2)
data2 = array.new_float(n)
labels2 = array.new_int(n)
for i = 0 to n - 1
data2.set(i, superTrend2[i])
label_i2 = price2[i] > sT2[i] ? 1 : 0 // Assuming same price for second SuperTrend
labels2.set(i, label_i2)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Define a function to compute distance between two data points
distance(x1, x2) =>
math.abs(x1 - x2)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Define the weighted k-nearest neighbors (KNN) function
knn_weighted(data, labels, k, x) =>
n1 = data.size()
distances = array.new_float(n1)
indices = array.new_int(n1)
// Compute distances from the current point to all other points
for i = 0 to n1 - 1
x_i = data.get(i)
dist = distance(x, x_i)
distances.set(i, dist)
indices.set(i, i)
// Sort distances and corresponding indices in ascending order
// Bubble sort method
for i = 0 to n1 - 2
for j = 0 to n1 - i - 2
if distances.get(j) > distances.get(j + 1)
tempDist = distances.get(j)
distances.set(j, distances.get(j + 1))
distances.set(j + 1, tempDist)
tempIndex = indices.get(j)
indices.set(j, indices.get(j + 1))
indices.set(j + 1, tempIndex)
// Compute weighted sum of labels of the k nearest neighbors
weighted_sum = 0.
total_weight = 0.
for i = 0 to k - 1
index = indices.get(i)
label_i = labels.get(index)
weight_i = 1 / (distances.get(i) + 1e-6)
weighted_sum += weight_i * label_i
total_weight += weight_i
weighted_sum / total_weight
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Classify the current data point
current_superTrend = superTrend
label_ = knn_weighted(data, labels, k, current_superTrend)
label_upTrend = label_ == 1 ? 1:0
label_downTrend = label_ == 0 ? -1:0
// Classify the current data point for second SuperTrend
current_superTrend2 = superTrend2
label2_ = knn_weighted(data2, labels2, k, current_superTrend2)
label2_upTrend = label2_ == 1 ? 1:0
label2_downTrend = label2_ == 0 ? -1:0
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Plot
col = label_ == 1?upCol:label_ == 0?dnCol:neCol
plot(current_superTrend, color=col, title="Volume Super Trend AI")
upTrend = plot(superTrend==lowerBand?current_superTrend:na, title="Up Volume Super Trend AI", color=col, style=plot.style_linebr)
Middle = plot((open + close) / 2, display=display.none, editable=false)
downTrend = plot(superTrend==upperBand?current_superTrend:na, title="Down Volume Super Trend AI", color=col, style=plot.style_linebr)
fill_col = color.new(col,95)
fill(Middle, upTrend, fill_col, fillgaps=false,title="Up Volume Super Trend AI")
fill(Middle, downTrend, fill_col, fillgaps=false, title="Down Volume Super Trend AI")
// Plot Second SuperTrend
col2 = label2_ == 1 ? upCol : label2_ == 0 ? dnCol : neCol
plot(current_superTrend2, color=col2, title="Volume Super Trend AI 2")
upTrend2 = plot(superTrend2==lowerBand2 ? current_superTrend2 : na, title="Up Volume Super Trend AI 2", color=col2, style=plot.style_linebr)
downTrend2 = plot(superTrend2==upperBand2 ? current_superTrend2 : na, title="Down Volume Super Trend AI 2", color=col2, style=plot.style_linebr)
fill_col2 = color.new(col2, 95)
fill(Middle, upTrend2, fill_col2, fillgaps=false, title="Up Volume Super Trend AI 2")
fill(Middle, downTrend2, fill_col2, fillgaps=false, title="Down Volume Super Trend AI 2")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Ai Super Trend Signals
Start_TrendUp = col==upCol and (col[1]!=upCol or col[1]==neCol) and aisignals
Start_TrendDn = col==dnCol and (col[1]!=dnCol or col[1]==neCol) and aisignals
// Second AI Super Trend Signals
Start_TrendUp2 = col2==upCol and (col2[1]!=upCol or col2[1]==neCol) and aisignals
Start_TrendDn2 = col2==dnCol and (col2[1]!=dnCol or col2[1]==neCol) and aisignals
TrendUp = direction == -1 and direction[1] == 1 and label_ == 1 and aisignals
TrendDn = direction == 1 and direction[1] ==-1 and label_ == 0 and aisignals
TrendUp2 = direction2 == -1 and direction2[1] == 1 and label2_ == 1 and aisignals
TrendDn2 = direction2 == 1 and direction2[1] ==-1 and label2_ == 0 and aisignals
plotshape(Start_TrendUp?superTrend:na, location=location.absolute, style= shape.circle, size=size.tiny, color=Bullish_col, title="AI Bullish Trend Start")
plotshape(Start_TrendDn?superTrend:na, location=location.absolute, style= shape.circle,size=size.tiny, color=Bearish_col, title="AI Bearish Trend Start")
plotshape(TrendUp?superTrend:na, location=location.absolute, style= shape.triangleup, size=size.small, color=Bullish_col, title="AI Bullish Trend Signal")
plotshape(TrendDn?superTrend:na, location=location.absolute, style= shape.triangledown,size=size.small, color=Bearish_col, title="AI Bearish Trend Signal")
plotshape(Start_TrendUp2 ? superTrend2 : na, location=location.absolute, style= shape.circle, size=size.tiny, color=Bullish_col, title="AI Bullish Trend Start 2")
plotshape(Start_TrendDn2 ? superTrend2 : na, location=location.absolute, style= shape.circle, size=size.tiny, color=Bearish_col, title="AI Bearish Trend Start 2")
plotshape(TrendUp2?superTrend2:na, location=location.absolute, style= shape.triangleup, size=size.small, color=Bullish_col, title="AI Bullish Trend Signal")
plotshape(TrendDn2?superTrend2:na, location=location.absolute, style= shape.triangledown,size=size.small, color=Bearish_col, title="AI Bearish Trend Signal")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
//longCondition = (Start_TrendUp or Start_TrendUp2) or (TrendUp or TrendUp2)
//shortCondition = (Start_TrendDn or Start_TrendDn2) or (TrendDn or TrendDn2)
longCondition = direction == -1 and label_ == 1 and direction2 == -1 and label2_ == 1
shortCondition = direction == 1 and label_ == 0 and direction2 == 1 and label2_ == 0
// Double AI Trend Continuation Signals
longExitCondition1 = direction == -1 and label_ == 1
longExitCondition2 = direction2 == -1 and label2_ == 1
shortExitCondition1 = direction == 1 and label_ == 0
shortExitCondition2 = direction2 == 1 and label2_ == 0
longExitCondition = not (TrendUp or TrendUp2)
shortExitCondition = not (TrendDn or TrendDn2)
// Dynamic Trailing Stop Loss
longTrailingStop = superTrend - atr * factor
shortTrailingStop = superTrend + atr * factor
// Adjust Enter and Exit Conditions based on Trading Direction
if (tradeDirection == "Long" or tradeDirection == "Both")
strategy.entry("Long", strategy.long, when=longCondition)
strategy.exit("Exit Long", "Long", stop=longTrailingStop, when=longExitCondition)
if (tradeDirection == "Short" or tradeDirection == "Both")
strategy.entry("Short", strategy.short, when=shortCondition)
strategy.exit("Exit Short", "Short", stop=shortTrailingStop, when=shortExitCondition) |
Backtest Strategy Optimizer Adapter | https://www.tradingview.com/script/tsHCuCEi-Backtest-Strategy-Optimizer-Adapter/ | DinGrogu | https://www.tradingview.com/u/DinGrogu/ | 3 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © DinGrogu
//@version=5
library('backtest')
// ############################################################
// # FUNCTIONS
// ############################################################
f_backtest_table_margin(int margin) =>
margin_string = ''
for i = 1 to margin
margin_string := margin_string + ' '
margin_string
// @function - Get the take profit price (only used externally).
f_take_profit_price(_entry_price, _take_profit_percentage, _atr_length=14) =>
atr_enabled = _atr_length > 0
atr = atr_enabled ? ta.sma(ta.tr, _atr_length) : 0
_take_profit_percentage > 0 ? atr_enabled ? _entry_price + (atr * _take_profit_percentage) : _entry_price + (_entry_price * (_take_profit_percentage / 100)) : na
// @function - Get the stop loss price (only used externally).
f_stop_loss_price(_entry_price, _stop_loss_percentage, _atr_length=14) =>
atr_enabled = _atr_length > 0
atr = atr_enabled ? ta.sma(ta.tr, _atr_length) : 0
_stop_loss_percentage > 0 ? atr_enabled ? _entry_price - (atr * _stop_loss_percentage) : _entry_price - (_entry_price * (_stop_loss_percentage / 100)) : na
// @function - Backtesting statistics table
f_backtest_table(_initial_capital, _profit_and_loss, _open_balance, _winrate, _entries, _exits, _wins, _losses, _table_position='RIGHT', _table_margin=15, _table_transparency=20, _table_cell_color=color.purple, _table_title_cell_color=color.gray, _table_text_color=color.white) =>
var green = #26A69A
var red = #FF5252
var table_width = 0
var table_margin_right = _table_margin > 0 ? str.tostring(f_backtest_table_margin(_table_margin)) : ''
var table_position = _table_position == 'LEFT' ? position.bottom_left : position.bottom_right
var table_titles = _table_position == 'LEFT' ? 1 : 0
var table_values = _table_position == 'LEFT' ? 2 : 1
var table_offset = _table_position == 'LEFT' ? 0 : 2
backtesting_table = table.new(table_position, columns=3, rows=7, border_width=3)
profit_color = _open_balance > _initial_capital ? green : red
table.cell(backtesting_table, table_titles, 0, text=' Initial Balance ', bgcolor=_table_title_cell_color, text_color=_table_text_color, text_halign=text.align_left, text_size=size.small)
table.cell(backtesting_table, table_titles, 1, text=' Close Balance ', bgcolor=_table_title_cell_color, text_color=_table_text_color, text_halign=text.align_left, text_size=size.small)
table.cell(backtesting_table, table_titles, 2, text=' Profit / Loss ($) ', bgcolor=_table_title_cell_color, text_color=_table_text_color, text_halign=text.align_left, text_size=size.small)
table.cell(backtesting_table, table_titles, 3, text=' Profit / Loss (%) ', bgcolor=_table_title_cell_color, text_color=_table_text_color, text_halign=text.align_left, text_size=size.small)
table.cell(backtesting_table, table_titles, 4, text=' Entries / Exits ', bgcolor=_table_title_cell_color, text_color=_table_text_color, text_halign=text.align_left, text_size=size.small)
table.cell(backtesting_table, table_titles, 5, text=' Wins / Losses ', bgcolor=_table_title_cell_color, text_color=_table_text_color, text_halign=text.align_left, text_size=size.small)
table.cell(backtesting_table, table_titles, 6, text=' Winrate (%) ', bgcolor=_table_title_cell_color, text_color=_table_text_color, text_halign=text.align_left, text_size=size.small)
table.cell(backtesting_table, table_values, 0, text=' ' + str.tostring(_initial_capital, '###,###.##') + ' ', width=table_width, bgcolor=color.new(_table_cell_color, _table_transparency), text_color=color.new(color.white, 0), text_halign=text.align_right, text_size=size.small)
table.cell(backtesting_table, table_values, 1, text=' ' + str.tostring(_open_balance, '###,###.##') + ' ', width=table_width, bgcolor=color.new(profit_color, _table_transparency), text_color=color.new(color.white, 0), text_halign=text.align_right, text_size=size.small)
table.cell(backtesting_table, table_values, 2, text=' ' + str.tostring(_open_balance - _initial_capital, '###,###.##') + ' ', width=table_width, bgcolor=color.new(profit_color, _table_transparency), text_color=color.new(color.white, 0), text_halign=text.align_right, text_size=size.small)
table.cell(backtesting_table, table_values, 3, text=' ' + str.tostring(_profit_and_loss, format.percent) + ' ', width=table_width, bgcolor=color.new(_open_balance - _initial_capital >= 0 ? green : red, _table_transparency), text_color=color.new(color.white, 0), text_halign=text.align_right, text_size=size.small)
table.cell(backtesting_table, table_values, 4, text=' ' + str.tostring(_entries, '###,###.##') + ' / ' + str.tostring(_exits, '###,###.##') + ' ', width=table_width, bgcolor=color.new(_table_cell_color, _table_transparency), text_color=color.new(color.white, 0), text_halign=text.align_right, text_size=size.small)
table.cell(backtesting_table, table_values, 5, text=' ' + str.tostring(_wins, '###,###.##') + ' / ' + str.tostring(_losses, '###,###.##') + ' ', width=table_width, bgcolor=color.new(_table_cell_color, _table_transparency), text_color=color.new(color.white, 0), text_halign=text.align_right, text_size=size.small)
table.cell(backtesting_table, table_values, 6, text=' ' + str.tostring(_winrate, '#.##') + '%' + ' ', width=table_width, bgcolor=color.new(_table_cell_color, _table_transparency), text_color=color.new(color.white, 0), text_halign=text.align_right, text_size=size.small)
table.cell(backtesting_table, table_offset, 0, table_margin_right, bgcolor=color.new(color.white, 100), text_color=color.white, text_size=size.small)
// @function - Main backtesting function.
f_backtest_main(_date_start, _date_end, _entry_signal, _exit_signal, _take_profit_percentage=0.0, _stop_loss_percentage=0.0, _atr_length=0, _initial_capital=1000.00, _order_size=100, _commission=0.0, _on_bar_close=false, _high=high, _low=low, _src=close, _chart=false) =>
var open_balance = _initial_capital
var initial_capital = _initial_capital
var order_size = _order_size
var commission = _commission
var entries = 0
var exits = 0
var wins = 0
var losses = 0
var float cumulative_profit = 0.0
var float profit_factor = 0.0
var float total_purchased = 0.0
var float entry_commission = 0.0
var float exit_commission = 0.0
var float total_commission = 0.0
var float trade_profit = 0.0
var float gross = 0.0
var float net = 0.0
var float winrate = 0.0
var float closing_balance = 0.0
var float profit_and_loss = 0.0
var open_trade = false
// Here, we store the 'last_bar_index' value that is known from the beginning of the script's calculation.
// The 'last_bar_index' will change when new real-time bars appear, so we declare 'last_bar' with the 'var' keyword.
var last_bar = last_bar_index
// Check if the current bar_index is '_date_start' removed from the last bar on the chart, or the chart is traded in real-time.
// Or if the _date start is bigger than 476928000 it's probably a date and we use the date time.
date_in_range = _date_start < 476928000 ? (last_bar - bar_index <= _date_start) : (time >= _date_start and time < _date_end)
if (date_in_range)
var line_src = 0.0
var label_position = label.style_label_down
var last_entry_signal_bar_index = 0
var last_exit_signal_bar_index = 0
var entry_price = 0.0
var exit_price = 0.0
var exit_profit = 0.0
var exit_comment = ''
var take_profit_price = 0.0
var stop_loss_price = 0.0
var take_profit_enabled = false
var take_profit_condition = false
var take_profit_condition_cross = false
var take_profit_condition_close = false
var stop_loss_enabled = false
var stop_loss_condition = false
var stop_loss_condition_cross = false
var stop_loss_condition_close = false
take_profit_enabled := _take_profit_percentage > 0
take_profit_percentage = take_profit_enabled ? (_take_profit_percentage / 100) : 9999
stop_loss_enabled := _stop_loss_percentage > 0
stop_loss_percentage = stop_loss_enabled ? (_stop_loss_percentage / 100) : 9999
atr_enabled = _atr_length > 0
tr = math.max(_high - _low, math.abs(_high - _src[1]), math.abs(_low - _src[1]))
atr = atr_enabled ? ta.sma(tr, _atr_length) : 0
entry_signal = _entry_signal
entry_condition = not open_trade and entry_signal
entry_signal_value = ta.valuewhen(entry_condition, _src, 0)
if (entry_condition)
open_trade := true
entry_price := _src
// Only show labels on chart when using the full backtest function.
if (_chart)
last_entry_signal_bar_index := bar_index
entry_label_bar_index = _on_bar_close ? last_entry_signal_bar_index : last_entry_signal_bar_index + 1
entry_label_text = str.tostring(math.round_to_mintick(entry_price))
label.new(entry_label_bar_index, na, entry_label_text, color=color.green, textcolor=color.white, size=size.normal, style=label.style_label_up, yloc=yloc.belowbar)
cumulative_profit := open_balance * (order_size / 100)
entry_commission := (cumulative_profit / 100) * commission
profit_factor := cumulative_profit - entry_commission
total_purchased := profit_factor / entry_price
// Increase the entries count.
entries += 1
// Reset the exit price
exit_price := na
exit_signal = _exit_signal
// Take Profit Conditions
if (open_trade and take_profit_enabled)
take_profit_price := atr_enabled ? entry_price + (atr * (take_profit_percentage * 100)) : entry_price + (entry_price * take_profit_percentage)
take_profit_condition_cross := ta.crossover(_high, take_profit_price) or ta.crossunder(_high, take_profit_price) or ta.cross(_src, take_profit_price)
take_profit_condition_close := _src >= take_profit_price
take_profit_condition := ta.crossover(_high, take_profit_price) or take_profit_condition_close
exit_signal := exit_signal or take_profit_condition
// Stop Loss Conditions
if (open_trade and stop_loss_enabled)
stop_loss_price := atr_enabled ? entry_price - (atr * (stop_loss_percentage * 100)) : entry_price - (entry_price * stop_loss_percentage)
stop_loss_condition_cross := ta.crossunder(_low, stop_loss_price) or ta.crossunder(_low, stop_loss_price) or ta.cross(_src, stop_loss_price)
stop_loss_condition_close := _src <= stop_loss_price
stop_loss_condition := stop_loss_condition_cross or stop_loss_condition_close
exit_signal := exit_signal or stop_loss_condition
exit_condition = open_trade and exit_signal
exit_signal_value = ta.valuewhen(exit_condition, _src, 0)
if (exit_condition)
open_trade := false
exit_price := _src
// Only show labels on chart when using the full backtest function.
if (_chart)
if (stop_loss_enabled and stop_loss_condition)
exit_price := stop_loss_price
exit_comment := 'SL @ '
if (take_profit_enabled and take_profit_condition)
exit_price := take_profit_price
exit_comment := 'TP @ '
//if (last_entry_signal_bar_index != bar_index)
line_profit_color = entry_price < exit_price ? color.green : color.red
label_profit_color = entry_price < exit_price ? color.blue : color.red
// Draw a line between exit and entry.
line_bar_index = _on_bar_close ? last_entry_signal_bar_index : last_entry_signal_bar_index + 1
line.new(line_bar_index, exit_price, bar_index, exit_price, extend=extend.none, color=color.new(line_profit_color, 20))
//line_bar_price = line.get_x2(order_line)
exit_profit := (((exit_price - entry_price) / entry_price) * 100)
// The exit label.
bar_index_exit_label = _on_bar_close ? bar_index : bar_index + 1
label.new(bar_index_exit_label, na, exit_comment + str.tostring(math.round_to_mintick(exit_price)) + ' (' + str.tostring(exit_profit, '#.##') + '%)', color=label_profit_color, textcolor=color.white, size=size.normal, style=label.style_label_down, yloc=yloc.abovebar)
// Reset the bar_index of the entry_signal.
last_entry_signal_bar_index := 0
// Calculate the total Wins / Losses and Winrate (%)
if (exit_price > entry_price)
wins += 1
else
losses += 1
winrate := nz(math.round((wins / (wins + losses) * 100), 2))
// Reset the entry price.
entry_price := na
exit_profit := 0
// Reset the TP/SL conditions
take_profit_condition := false
take_profit_condition_cross := false
take_profit_condition_close := false
stop_loss_condition := false
stop_loss_condition_cross := false
stop_loss_condition_close := false
// Cum. Profit % = Profit / (Initial Capital + Cumulative Profit of the previous trade) * 100%
// Calculate the profit and loss.
gross := total_purchased * exit_signal_value
net := gross - profit_factor
exit_commission := (gross / 100) * commission
total_commission := (entry_commission + exit_commission)
trade_profit := net - total_commission
closing_balance := open_balance + trade_profit
open_balance := closing_balance
profit_and_loss := ((open_balance - initial_capital) / initial_capital) * 100
// Increase the exits count.
exits += 1
[profit_and_loss, open_balance, winrate, entries, exits, wins, losses]
// @function - Show full backtesting results.
f_backtest(_date_start, _date_end, _entry_signal, _exit_signal, _take_profit_percentage=0.0, _stop_loss_percentage=0.0, _atr_length=0, _initial_capital=1000.00, _order_size=100, _commission=0.0, _on_bar_close=true, _high=high, _low=low, _src=close, _chart=true) =>
[profit_and_loss, open_balance, winrate, entries, exits, wins, losses] = f_backtest_main(_date_start, _date_end, _entry_signal, _exit_signal, _take_profit_percentage, _stop_loss_percentage, _atr_length, _initial_capital, _order_size, _commission, _on_bar_close, _high, _low, _src, _chart)
// @function - Show backtesting profit.
f_backtest_profit(_date_start, _date_end, _entry_signal, _exit_signal, _take_profit_percentage=0.0, _stop_loss_percentage=0.0, _atr_length=0, _initial_capital=1000.00, _order_size=100, _commission=0.0, _on_bar_close=true, _high=high, _low=low, _src=close, _chart=false) =>
[profit_and_loss, _, _, _, _, _, _] = f_backtest_main(_date_start, _date_end, _entry_signal, _exit_signal, _take_profit_percentage, _stop_loss_percentage, _atr_length, _initial_capital, _order_size, _commission, _on_bar_close, _high, _low, _src, _chart)
response = profit_and_loss
// @function - Show backtesting winrate.
f_backtest_winrate(_date_start, _date_end, _entry_signal, _exit_signal, _take_profit_percentage=0.0, _stop_loss_percentage=0.0, _atr_length=0, _initial_capital=1000.00, _order_size=100, _commission=0.0, _on_bar_close=true, _high=high, _low=low, _src=close, _chart=false) =>
[_, _, winrate, _, _, _, _] = f_backtest_main(_date_start, _date_end, _entry_signal, _exit_signal, _take_profit_percentage, _stop_loss_percentage, _atr_length, _initial_capital, _order_size, _commission, _on_bar_close, _high, _low, _src, _chart)
response = winrate
// @function - Define random colors for plots.
// The most stupid function I've ever created. "ChatGPT".
f_color(_n) =>
color = _n == 1 or _n == 16 or _n == 32 or _n == 48 or _n == 64 or _n == 80 or _n == 96 or _n == 112 or _n == 128 or _n == 144 or _n == 160 or _n == 176 or _n == 192 or _n == 208 or _n == 224 or _n == 240 ? color.aqua : _n == 2 or _n == 18 or _n == 34 or _n == 50 or _n == 66 or _n == 82 or _n == 98 or _n == 114 or _n == 130 or _n == 146 or _n == 162 or _n == 178 or _n == 194 or _n == 210 or _n == 226 or _n == 242 ? color.yellow : _n == 3 or _n == 19 or _n == 35 or _n == 51 or _n == 67 or _n == 83 or _n == 99 or _n == 115 or _n == 131 or _n == 147 or _n == 163 or _n == 179 or _n == 195 or _n == 211 or _n == 227 or _n == 243 ? color.fuchsia : _n == 4 or _n == 20 or _n == 36 or _n == 52 or _n == 68 or _n == 84 or _n == 100 or _n == 116 or _n == 132 or _n == 148 or _n == 164 or _n == 180 or _n == 196 or _n == 212 or _n == 228 or _n == 244 ? color.gray : _n == 5 or _n == 21 or _n == 37 or _n == 53 or _n == 69 or _n == 85 or _n == 101 or _n == 117 or _n == 133 or _n == 149 or _n == 165 or _n == 181 or _n == 197 or _n == 213 or _n == 229 or _n == 245 ? color.green : _n == 6 or _n == 22 or _n == 38 or _n == 54 or _n == 70 or _n == 86 or _n == 102 or _n == 118 or _n == 134 or _n == 150 or _n == 166 or _n == 182 or _n == 198 or _n == 214 or _n == 230 or _n == 246 ? color.lime : _n == 7 or _n == 23 or _n == 39 or _n == 55 or _n == 71 or _n == 87 or _n == 103 or _n == 119 or _n == 135 or _n == 151 or _n == 167 or _n == 183 or _n == 199 or _n == 215 or _n == 231 or _n == 247 ? color.maroon : _n == 8 or _n == 24 or _n == 40 or _n == 56 or _n == 72 or _n == 88 or _n == 104 or _n == 120 or _n == 136 or _n == 152 or _n == 168 or _n == 184 or _n == 200 or _n == 216 or _n == 232 or _n == 248 ? color.navy : _n == 9 or _n == 25 or _n == 41 or _n == 57 or _n == 73 or _n == 89 or _n == 105 or _n == 121 or _n == 137 or _n == 153 or _n == 169 or _n == 185 or _n == 201 or _n == 217 or _n == 233 or _n == 249 ? color.olive : _n == 10 or _n == 26 or _n == 42 or _n == 58 or _n == 74 or _n == 90 or _n == 106 or _n == 122 or _n == 138 or _n == 154 or _n == 170 or _n == 186 or _n == 202 or _n == 218 or _n == 234 or _n == 250 ? color.orange : _n == 11 or _n == 27 or _n == 43 or _n == 59 or _n == 75 or _n == 91 or _n == 107 or _n == 123 or _n == 139 or _n == 155 or _n == 171 or _n == 187 or _n == 203 or _n == 219 or _n == 235 or _n == 251 ? color.purple : _n == 12 or _n == 28 or _n == 44 or _n == 60 or _n == 76 or _n == 92 or _n == 108 or _n == 124 or _n == 140 or _n == 156 or _n == 172 or _n == 188 or _n == 204 or _n == 220 or _n == 236 or _n == 252 ? color.red : _n == 13 or _n == 29 or _n == 45 or _n == 61 or _n == 77 or _n == 93 or _n == 109 or _n == 125 or _n == 141 or _n == 157 or _n == 173 or _n == 189 or _n == 205 or _n == 221 or _n == 237 or _n == 253 ? color.silver : _n == 14 or _n == 30 or _n == 46 or _n == 62 or _n == 78 or _n == 94 or _n == 110 or _n == 126 or _n == 142 or _n == 158 or _n == 174 or _n == 190 or _n == 206 or _n == 222 or _n == 238 or _n == 254 ? color.teal : _n == 15 or _n == 31 or _n == 47 or _n == 63 or _n == 79 or _n == 95 or _n == 111 or _n == 127 or _n == 143 or _n == 159 or _n == 175 or _n == 191 or _n == 207 or _n == 223 or _n == 239 or _n == 255 ? color.blue : color.blue
color_transparency = _n < 15 ? 0 : _n > 15 and _n < 30 ? 5 : _n > 30 and _n < 45 ? 8 : _n > 45 and _n < 60 ? 11 : _n > 60 and _n < 75 ? 14 : _n > 75 and _n < 90 ? 17 : _n > 90 and _n < 105 ? 20 : _n > 105 and _n < 120 ? 23 : _n > 120 and _n < 135 ? 26 : _n > 135 and _n < 150 ? 29 : _n > 150 and _n < 165 ? 32 : _n > 165 and _n < 180 ? 35 : _n > 180 and _n < 195 ? 38 : _n > 195 and _n < 210 ? 41 : _n > 210 and _n < 225 ? 44 : _n > 225 and _n < 240 ? 47 : _n > 240 and _n < 255 ? 50 : _n > 255 and _n < 270 ? 53 : _n > 270 and _n < 285 ? 56 : _n > 285 and _n < 300 ? 59 : _n > 300 and _n < 315 ? 62 : _n > 315 and _n < 330 ? 65 : _n > 330 and _n < 345 ? 68 : _n > 345 and _n < 360 ? 71 : _n > 360 and _n < 375 ? 74 : _n > 375 and _n < 390 ? 77 : _n > 390 and _n < 405 ? 80 : _n > 405 and _n < 420 ? 83 : _n > 420 and _n < 435 ? 86 : _n > 435 and _n < 450 ? 89 : _n > 450 and _n < 465 ? 92 : _n > 465 and _n < 480 ? 95 : _n > 480 and _n < 495 ? 98 : _n > 495 and _n < 510 ? 101 : 0
color.new(color, color_transparency)
// ############################################################
// # EXPORT FUNCTIONS
// ############################################################
// @function - Get a random color, great for using many plots.
// @param _n <int> A random number.
export color(int _n=1) =>
f_color(_n)
// @function - Shortcut to get the take profit price.
// @param _entry_price <series float> The entry price.
// @param _take_profit_percentage <float> The take profit percentage / atr multiplier.
// @param _atr_length <int> The ATR Length.
export take_profit_price(series float _entry_price=close, float _take_profit_percentage=0.0, int _atr_length=14) =>
f_take_profit_price(_entry_price, _take_profit_percentage, _atr_length)
// @function - Shortcut to get the take profit price.
// @param _entry_price <series float> The entry price.
// @param _stop_loss_percentage <float> The stop loss percentage / atr multiplier.
// @param _atr_length <int> The ATR Length.
export stop_loss_price(series float _entry_price=close, float _stop_loss_percentage=0.0, int _atr_length=14) =>
f_stop_loss_price(_entry_price, _stop_loss_percentage, _atr_length)
// @function - Show a table of the backtest results.
// @param _initial_capital <simple float> Initial Capital.
// @param _profit_and_loss <simple float> Profit and Loss.
// @param _open_balance <simple float> Open Balance.
// @param _winrate <float> Winrate.
// @param _entries <int> Number of entries.
// @param _wins <int> Number of wins.
// @param _losses <int> Number of losses.
// @param _table_position <string> The position of the table.
// @param _table_margin <string> The margin of the table.
// @param _table_transparency <string> The transparency of the table.
// @param _table_cell_color <string> The cell color of the table.
// @param _table_title_cell_color <string> The title cell color of the table.
// @param _table_text_color <string> The text color.
export table(float _initial_capital, float _profit_and_loss, float _open_balance, float _winrate, int _entries, int _exits, int _wins, int _losses, string _table_position='RIGHT', int _table_margin=15, int _table_transparency=20, color _table_cell_color=color.purple, color _table_title_cell_color=color.gray, color _table_text_color=color.white) =>
f_backtest_table(_initial_capital, _profit_and_loss, _open_balance, _winrate, _entries, _exits, _wins, _losses, _table_position, _table_margin, _table_transparency, _table_cell_color, _table_title_cell_color, _table_text_color)
// @function - Show a table of the backtest results.
// @param _date_start <int> Start Date (When using a value below 5000 instead of date it will use bars back as starting point).
// @param _date_end <int> End Date.
// @param _entry_signal <bool> The Entry Signal.
// @param _exit_signal <int> The Exit Signal.
// @param _take_profit_percentage <simple float> The take profit percentage / atr multiplier.
// @param _stop_loss_percentage <simple float> The stop loss percentage / atr multiplier.
// @param _atr_length <simple int> The ATR length for TP/SL.
// @param _initial_capital <float> Initial Capital.
// @param _order_size <float> The order size.
// @param _commission <float> The commission.
// @param _on_bar_close <string> On Bar Close toggle (It's recommended to not change this value).
// @param _high <series float> High source.
// @param _low <series float> Low source.
// @param _src <series float> Calculation source.
// @param _chart <bool> Enable / Disable visuals, labels of the backtesting results.
export run(int _date_start, int _date_end, bool _entry_signal, bool _exit_signal, simple float _take_profit_percentage=0.0, simple float _stop_loss_percentage=0.0, simple int _atr_length=0, float _initial_capital=1000.00, float _order_size=100, float _commission=0.0, bool _on_bar_close=true, series float _high=high, series float _low=low, series float _src=close, simple bool _chart=true) =>
[profit_and_loss, open_balance, winrate, entries, exits, wins, losses] = f_backtest_main(_date_start, _date_end, _entry_signal, _exit_signal, _take_profit_percentage, _stop_loss_percentage, _atr_length, _initial_capital, _order_size, _commission, _on_bar_close, _high, _low, _src, _chart)
export results(int _date_start, int _date_end, bool _entry_signal, bool _exit_signal, simple float _take_profit_percentage=0.0, simple float _stop_loss_percentage=0.0, simple int _atr_length=0, float _initial_capital=1000.00, float _order_size=100, float _commission=0.0, bool _on_bar_close=true, series float _high=high, series float _low=low, series float _src=close, simple bool _chart=true) =>
[profit_and_loss, open_balance, winrate, entries, exits, wins, losses] = f_backtest_main(_date_start, _date_end, _entry_signal, _exit_signal, _take_profit_percentage, _stop_loss_percentage, _atr_length, _initial_capital, _order_size, _commission, _on_bar_close, _high, _low, _src, _chart)
// @function - Only show the profit.
export profit(int _date_start, int _date_end, bool _entry_signal, bool _exit_signal, simple float _take_profit_percentage=0.0, simple float _stop_loss_percentage=0.0, simple int _atr_length=0, float _initial_capital=1000.00, float _order_size=100, float _commission=0.0, bool _on_bar_close=true, series float _high=high, series float _low=low, series float _src=close, simple bool _chart=false) =>
[profit_and_loss, _, _, _, _, _, _] = f_backtest_main(_date_start, _date_end, _entry_signal, _exit_signal, _take_profit_percentage, _stop_loss_percentage, _atr_length, _initial_capital, _order_size, _commission, _on_bar_close, _high, _low, _src, _chart)
response = profit_and_loss
// @function - Only show the winrate.
export winrate(int _date_start, int _date_end, bool _entry_signal, bool _exit_signal, simple float _take_profit_percentage=0.0, simple float _stop_loss_percentage=0.0, simple int _atr_length=0, float _initial_capital=1000.00, float _order_size=100, float _commission=0.0, bool _on_bar_close=true, series float _high=high, series float _low=low, series float _src=close, simple bool _chart=false) =>
[_, _, winrate, _, _, _, _] = f_backtest_main(_date_start, _date_end, _entry_signal, _exit_signal, _take_profit_percentage, _stop_loss_percentage, _atr_length, _initial_capital, _order_size, _commission, _on_bar_close, _high, _low, _src, _chart)
response = winrate
|
Statistics Table | https://www.tradingview.com/script/8mFshMiO-Statistics-Table/ | DinGrogu | https://www.tradingview.com/u/DinGrogu/ | 8 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © DinGrogu
//@version=5
library('statistics')
// ############################################################
// # INTERNAL FUNCTIONS
// ############################################################
table_margin(int margin) =>
margin_string = ''
for i = 1 to margin
margin_string := margin_string + ' '
margin_string
statistics_average_bars_per_trade() =>
sum_bars_per_trade = 0
for trade_number = 0 to strategy.closedtrades - 1
sum_bars_per_trade += strategy.closedtrades.exit_bar_index(trade_number) - strategy.closedtrades.entry_bar_index(trade_number) + 1
response = math.round(nz(sum_bars_per_trade / strategy.closedtrades))
statistics_maximum_trade_drawdown() =>
highest_drawdown = 0.0
for trade_number = 0 to strategy.closedtrades - 1
trade_price = strategy.closedtrades.entry_price(trade_number) * math.abs(strategy.closedtrades.size(trade_number))
trade_drawdown = strategy.closedtrades.max_drawdown(trade_number)
drawdown = trade_drawdown / trade_price * 100
if (drawdown > highest_drawdown)
highest_drawdown := drawdown
response = math.round(highest_drawdown, 2)
statistics_maximum_trade_runup() =>
highest_runup = 0.0
for trade_number = 0 to strategy.closedtrades - 1
trade_price = strategy.closedtrades.entry_price(trade_number) * math.abs(strategy.closedtrades.size(trade_number))
trade_drawdown = strategy.closedtrades.max_runup(trade_number)
runup = trade_drawdown / trade_price * 100
if (runup > highest_runup)
highest_runup := runup
response = math.round(highest_runup, 2)
statistics_avg_trade_profit_percent(int _maximum_trades=5000) =>
profits_list = array.new_float(0)
for trade_number = 0 to strategy.closedtrades - 1
if (array.size(profits_list) > _maximum_trades)
array.remove(profits_list, 0)
commision = math.abs(strategy.closedtrades.commission(trade_number) / (strategy.netprofit + strategy.closedtrades.commission(trade_number))) * 100
profit = ((strategy.closedtrades.exit_price(trade_number) - strategy.closedtrades.entry_price(trade_number)) / strategy.closedtrades.entry_price(trade_number)) * 100
profit := profit - (commision * 2)
if (profit > 0)
array.push(profits_list, profit)
response = array.size(profits_list) > 1 ? math.round(array.avg(profits_list), 2) : 0
// ############################################################
// # EXPORT FUNCTIONS
// ############################################################
// @function - A function to show a table with statistics on strategies.
// @param _initial_capital <float> The initial capital used for trading (usually the value from properties tab).
// @param _src <series float> The source for all calculations (usually close)
// @param _statistics_table_enabled <string> Input value if the table is enabled.
// @param _statistics_table_position <string> Input value for the table position.
// @param _statistics_table_margin <string> Input value for the table margin.
// @param _statistics_table_transparency <string> Input value for the table transparency.
// @param _statistics_table_text_color <series color> Input value for the table cell text color.
// @param _statistics_table_title_cell_color <series color> Input value for the table title cell text color.
// @param _statistics_table_text_color <series color> Input value for the table cell text color.
// @param _statistics_table_cell_color <series color> Input value for the table cell background color.
export table(float _initial_capital, series float _src, string _statistics_table_enabled, string _statistics_table_position, int _statistics_table_margin, int _statistics_table_transparency, series color _statistics_table_text_color, series color _statistics_table_title_cell_color, series color _statistics_table_cell_color) =>
var green_increase = #26A69A
var red_increase = #FF5252
var table_price = 0.0
table_price := na(table_price[1]) ? na : table_price[1]
var table_percentage_prefix = ''
var table_percentage = 0.0
table_percentage := na(table_percentage[1]) ? na : table_percentage[1]
var table_bars = '0'
table_bars := na(table_bars[1]) ? na : table_bars[1]
if (_statistics_table_enabled == 'YES')
has_trades = strategy.closedtrades > 0
open_trade = strategy.position_size != 0
first_order = strategy.closedtrades.entry_price(0)
bars_since_closed = has_trades ? bar_index - strategy.closedtrades.exit_bar_index(strategy.closedtrades - 1) + 1 : 0
bars_since_opened = has_trades ? bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades - 1) + 1 : 0
order_entry_price = has_trades ? strategy.opentrades.entry_price(strategy.opentrades - 1) : _src
last_order_exit_price = has_trades ? strategy.closedtrades.exit_price(strategy.closedtrades - 1) : _src
last_order_price = open_trade ? _src : last_order_exit_price
//initial_capital = strategy.initial_capital
final_balance = _initial_capital + strategy.netprofit
net_profit_percentage = (final_balance - _initial_capital) / _initial_capital * 100
average_trade_profit_percentage = has_trades ? statistics_avg_trade_profit_percent(100) : 0
buy_and_hold_percentage = has_trades ? math.round(((last_order_price - first_order) / first_order) * 100, 2) : 0
profit_factor = has_trades ? math.round(net_profit_percentage / buy_and_hold_percentage, 2) : 0
win_trades = strategy.wintrades
loss_trades = strategy.losstrades
winrate = nz(math.round((win_trades / (win_trades + loss_trades) * 100), 2))
table_color = color.blue
if (open_trade)
table_price := order_entry_price
table_percentage := math.abs((order_entry_price - _src) / _src * 100)
table_bars := str.tostring(nz(bars_since_opened))
table_color := _src > order_entry_price ? green_increase : red_increase
table_percentage_prefix := close > order_entry_price ? '' : '-'
else
table_price := last_order_exit_price
table_percentage := math.abs((last_order_exit_price - _src) / _src * 100)
table_bars := str.tostring(nz(bars_since_closed))
table_color := _src < last_order_exit_price ? green_increase : red_increase
table_percentage_prefix := close > last_order_exit_price ? '-' : ''
var table_width = 0
var table_margin_right = _statistics_table_margin > 0 ? str.tostring(table_margin(_statistics_table_margin)) : ''
var table_position = _statistics_table_position == 'LEFT' ? position.bottom_left : position.bottom_right
var statistics_table_titles = _statistics_table_position == 'LEFT' ? 1 : 0
var statistics_table_values = _statistics_table_position == 'LEFT' ? 2 : 1
var statistics_table_offset = _statistics_table_position == 'LEFT' ? 0 : 2
profit_color = open_trade ? close > order_entry_price ? green_increase : red_increase : _statistics_table_cell_color
var statistics_table = table.new(table_position, 3, 13, border_width=3)
table.cell(statistics_table, statistics_table_titles, 0, ' (%) EXIT PRICE ', width=table_width, bgcolor=color.new(color.white, 100), text_color=color.new(color.white, 100), text_size=size.small, text_halign=text.align_left)
table.cell(statistics_table, statistics_table_titles, 1, ' ($) TRADE PRICE ', width=table_width, bgcolor=_statistics_table_title_cell_color, text_color=_statistics_table_text_color, text_size=size.small, text_halign=text.align_left)
table.cell(statistics_table, statistics_table_titles, 2, ' (%) SINCE TRADE ', width=table_width, bgcolor=_statistics_table_title_cell_color, text_color=_statistics_table_text_color, text_size=size.small, text_halign=text.align_left)
table.cell(statistics_table, statistics_table_titles, 3, ' (B) SINCE TRADE ', width=table_width, bgcolor=_statistics_table_title_cell_color, text_color=_statistics_table_text_color, text_size=size.small, text_halign=text.align_left)
table.cell(statistics_table, statistics_table_titles, 4, ' (%) NET PROFIT ', width=table_width, bgcolor=_statistics_table_title_cell_color, text_color=_statistics_table_text_color, text_size=size.small, text_halign=text.align_left)
table.cell(statistics_table, statistics_table_titles, 5, ' (%) BUY & HOLD ', width=table_width, bgcolor=_statistics_table_title_cell_color, text_color=_statistics_table_text_color, text_size=size.small, text_halign=text.align_left)
table.cell(statistics_table, statistics_table_titles, 6, ' (X) PROFIT FACTOR ', width=table_width, bgcolor=_statistics_table_title_cell_color, text_color=_statistics_table_text_color, text_size=size.small, text_halign=text.align_left)
table.cell(statistics_table, statistics_table_titles, 7, ' (%) WINRATE ', width=table_width, bgcolor=_statistics_table_title_cell_color, text_color=_statistics_table_text_color, text_size=size.small, text_halign=text.align_left)
table.cell(statistics_table, statistics_table_titles, 8, ' (N) WIN / LOSS ', width=table_width, bgcolor=_statistics_table_title_cell_color, text_color=_statistics_table_text_color, text_size=size.small, text_halign=text.align_left)
table.cell(statistics_table, statistics_table_titles, 9, ' (B) AVG BARS ', width=table_width, bgcolor=_statistics_table_title_cell_color, text_color=_statistics_table_text_color, text_size=size.small, text_halign=text.align_left)
table.cell(statistics_table, statistics_table_titles, 10, ' (%) AVG PROFIT ', width=table_width, bgcolor=_statistics_table_title_cell_color, text_color=_statistics_table_text_color, text_size=size.small, text_halign=text.align_left)
table.cell(statistics_table, statistics_table_titles, 11, ' (%) MAX DRAWDOWN ', width=table_width, bgcolor=_statistics_table_title_cell_color, text_color=_statistics_table_text_color, text_size=size.small, text_halign=text.align_left)
table.cell(statistics_table, statistics_table_titles, 12, ' (%) MAX RUNUP ', width=table_width, bgcolor=_statistics_table_title_cell_color, text_color=_statistics_table_text_color, text_size=size.small, text_halign=text.align_left)
table.cell(statistics_table, statistics_table_values, 0, ' ' + str.tostring(math.round_to_mintick(table_price)) + '% ', width=table_width, bgcolor=color.new(_statistics_table_cell_color, 100), text_color=color.new(color.white, 100), text_size=size.small)
table.cell(statistics_table, statistics_table_values, 1, ' ' + str.tostring(math.round_to_mintick(table_price)) + ' ', width=table_width, bgcolor=color.new(open_trade ? profit_color : _statistics_table_cell_color, _statistics_table_transparency), text_color=_statistics_table_text_color, text_size=size.small)
table.cell(statistics_table, statistics_table_values, 2, ' ' + table_percentage_prefix + str.tostring(table_percentage, '#.##') + '% ', width=table_width, bgcolor=color.new(open_trade ? profit_color : _statistics_table_cell_color, _statistics_table_transparency), text_color=_statistics_table_text_color, text_size=size.small)
table.cell(statistics_table, statistics_table_values, 3, ' ' + table_bars + ' ', width=table_width, bgcolor=open_trade ? color.new(color.orange, _statistics_table_transparency) : color.new(_statistics_table_cell_color, _statistics_table_transparency), text_color=_statistics_table_text_color, text_size=size.small)
table.cell(statistics_table, statistics_table_values, 4, ' ' + str.tostring(math.round(net_profit_percentage, 2)) + '% ', width=table_width, bgcolor=net_profit_percentage < 0 ? color.new(red_increase, _statistics_table_transparency) : color.new(green_increase, _statistics_table_transparency), text_color=_statistics_table_text_color, text_size=size.small)
table.cell(statistics_table, statistics_table_values, 5, ' ' + str.tostring(buy_and_hold_percentage) + '% ', width=table_width, bgcolor=color.new(_statistics_table_cell_color, _statistics_table_transparency), text_color=_statistics_table_text_color, text_size=size.small)
table.cell(statistics_table, statistics_table_values, 6, ' ' + str.tostring(profit_factor) + 'x ', width=table_width, bgcolor=color.new(_statistics_table_cell_color, _statistics_table_transparency), text_color=_statistics_table_text_color, text_size=size.small)
table.cell(statistics_table, statistics_table_values, 7, ' ' + str.tostring(winrate, '#.##') + '% ', width=table_width, bgcolor=color.new(_statistics_table_cell_color, _statistics_table_transparency), text_color=_statistics_table_text_color, text_size=size.small)
table.cell(statistics_table, statistics_table_values, 8, ' ' + str.tostring(win_trades) + ' / ' + str.tostring(loss_trades) + ' ', width=table_width, bgcolor=color.new(_statistics_table_cell_color, _statistics_table_transparency), text_color=_statistics_table_text_color, text_size=size.small)
table.cell(statistics_table, statistics_table_values, 9, ' ' + str.tostring(statistics_average_bars_per_trade()) + ' ', width=table_width, bgcolor=color.new(_statistics_table_cell_color, _statistics_table_transparency), text_color=_statistics_table_text_color, text_size=size.small)
table.cell(statistics_table, statistics_table_values, 10, ' ' + str.tostring(statistics_avg_trade_profit_percent()) + '% ', width=table_width, bgcolor=color.new(_statistics_table_cell_color, _statistics_table_transparency), text_color=_statistics_table_text_color, text_size=size.small)
table.cell(statistics_table, statistics_table_values, 11, ' ' + str.tostring(statistics_maximum_trade_drawdown()) + '% ', width=table_width, bgcolor=color.new(_statistics_table_cell_color, _statistics_table_transparency), text_color=_statistics_table_text_color, text_size=size.small)
table.cell(statistics_table, statistics_table_values, 12, ' ' + str.tostring(statistics_maximum_trade_runup()) + '% ', width=table_width, bgcolor=color.new(_statistics_table_cell_color, _statistics_table_transparency), text_color=_statistics_table_text_color, text_size=size.small)
table.cell(statistics_table, statistics_table_offset, 0, table_margin_right, bgcolor=color.new(color.white, 100), text_color=color.white, text_size=size.small)
|
Captain Backtest Model [TFO] | https://www.tradingview.com/script/tOQ8gnxj-Captain-Backtest-Model-TFO/ | tradeforopp | https://www.tradingview.com/u/tradeforopp/ | 1,583 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © tradeforopp
//@version=5
strategy("Captain Backtest Model [TFO]", "Captain Backtest Model [TFO]", true, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500)
var g_SET = "Time"
prev_range = input.session("0600-1000", "Price Range", tooltip = "The range from which the high and low will be tracked for bias", group = g_SET)
take_by = input.session("1000-1115", "Window to Determine Bias", tooltip = "Price must take the high or low of the price range within this time window. Otherwise, will not determine a bias and will not trade for that session", group = g_SET)
trade_window = input.session("1000-1600", "Trade Window", tooltip = "Time window to take trades", group = g_SET)
var g_STRAT = "Strategy"
retrace_1 = input.bool(true, "Wait for Retracement - Opposite Close Candles", tooltip = "Wait for down close candles after long bias has been determined, or up close candles after short bias has been determined", group = g_STRAT)
retrace_2 = input.bool(true, "Wait for Retracement - Took Previous High/Low", tooltip = "Wait for price to take a previous candle low after long bias has been determined, or for price to take a previous candle high after short bias has been determined", group = g_STRAT)
stop_orders = input.bool(false, "Use Stop Orders", tooltip = "When enabled, will only enter long setups once price has taken the previous candle's high (and vice versa), as opposed to entering immediately once all criteria are met", group = g_STRAT)
fixed_rr = input.bool(true, "Use Fixed R:R", tooltip = "When enabled, will use the risk and reward inputs as stop loss and take profit orders. Otherwise, will hold until the trade window closes (EOD)", group = g_STRAT)
risk = input.float(25, "Risk (Points)", tooltip = "Stop loss, specified in points", group = g_STRAT)
reward = input.float(75, "Reward (Points)", tooltip = "Profit target, specified in points", group = g_STRAT)
var g_VIS = "Visuals"
range_color = input.color(color.new(color.blue, 70), "Price Range Color", group = g_VIS)
show_bias = input.bool(true, "Show Bias", inline = "BIAS", tooltip = "Display bias for the day", group = g_VIS)
long_color = input.color(color.teal, "", inline = "BIAS", group = g_VIS)
short_color = input.color(color.red, "", inline = "BIAS", group = g_VIS)
draw_rr = input.bool(true, "Draw Fixed R:R", tooltip = "Draw risk to reward boxes relative to entry", group = g_VIS)
draw_cutoff = input.bool(true, "Draw Time Cutoff", tooltip = "Draw the cutoff time for when price needs to take the range high or low", group = g_VIS)
t_pre = not na(time("", prev_range, "America/New_York"))
t_take = not na(time("", take_by, "America/New_York"))
t_trade = not na(time("", trade_window, "America/New_York"))
var float pre_h = na
var float pre_l = na
var box pre_box = na
var line pre_h_line = na
var line pre_l_line = na
var bool bias = na
var bool long = false
var bool short = false
var bool opp_close = false
var bool took_hl = false
var float buy_stop = na
var float sell_stop = na
var float entry = na
var line entry_line = na
var box[] risk_box = array.new_box()
var box[] reward_box = array.new_box()
var float[] risk_price = array.new_float()
var float[] reward_price = array.new_float()
rr_boxes(entry, long) =>
if long
reward_box.unshift(box.new(time[1], entry + reward, time, entry, xloc = xloc.bar_time, bgcolor = color.new(long_color, 50), border_color = color.new(long_color, 50)))
risk_box.unshift(box.new(time[1], entry, time, entry - risk, xloc = xloc.bar_time, bgcolor = color.new(short_color, 50), border_color = color.new(short_color, 50)))
else
reward_box.unshift(box.new(time[1], entry, time, entry - reward, xloc = xloc.bar_time, bgcolor = color.new(long_color, 50), border_color = color.new(long_color, 50)))
risk_box.unshift(box.new(time[1], entry + risk, time, entry, xloc = xloc.bar_time, bgcolor = color.new(short_color, 50), border_color = color.new(short_color, 50)))
if t_pre
pre_h := na(pre_h) ? high : math.max(pre_h, high)
pre_l := na(pre_l) ? low : math.min(pre_l, low)
if not t_pre[1]
pre_box := box.new(time, high, time, low, xloc = xloc.bar_time, bgcolor = range_color, border_color = na, text = str.tostring(prev_range), text_color = range_color)
pre_h_line := line.new(time, high, time, high, xloc = xloc.bar_time, color = color.new(range_color, 0))
pre_l_line := line.new(time, low, time, low, xloc = xloc.bar_time, color = color.new(range_color, 0))
else
pre_box.set_top(pre_h)
pre_box.set_rightbottom(time, pre_l)
pre_h_line.set_y1(pre_h)
pre_h_line.set_xy2(time, pre_h)
pre_l_line.set_y1(pre_l)
pre_l_line.set_xy2(time, pre_l)
if not t_trade and t_trade[1]
pre_h := na
pre_l := na
bias := na
entry := na
buy_stop := na
sell_stop := na
entry_line := na
long := false
short := false
opp_close := false
took_hl := false
reward_box.clear()
risk_box.clear()
if t_take
if high > pre_h and na(bias)
bias := true
pre_h_line.set_x2(time)
if show_bias
label.new(bar_index, high, "Bias Long", textcolor = color.white, color = long_color)
else if low < pre_l and na(bias)
bias := false
pre_l_line.set_x2(time)
if show_bias
label.new(bar_index, low, "Bias Short", textcolor = color.white, color = short_color, style = label.style_label_up)
if not t_take and t_take[1]
if draw_cutoff
line.new(bar_index, high, bar_index, low, extend = extend.both, color = chart.fg_color, style = line.style_dotted)
if na(bias)
label.new(bar_index, high, "Range Not Breached\nby 11:15", textcolor = chart.bg_color, color = chart.fg_color)
plotshape(show_bias, color = (bias == true) ? long_color : (bias == false) ? short_color : na, location = location.bottom, size = size.small, style = shape.square)
plotshape(long[1] and not long[2], color = long_color, location = location.belowbar, size = size.small, style = shape.triangleup)
plotshape(short[1] and not short[2], color = short_color, location = location.abovebar, size = size.small, style = shape.triangledown)
if t_trade
if not na(entry_line) and na(entry)
entry_line.set_x2(time)
if not retrace_1
opp_close := true
else
if bias == true and close < open
opp_close := true
if bias == false and close > open
opp_close := true
if not retrace_2
took_hl := true
else
if bias == true and low < low[1]
took_hl := true
if bias == false and high > high[1]
took_hl := true
if bias[1] == true and close > high[1] and opp_close and took_hl and not long
long := true
buy_stop := high
if stop_orders
entry_line := line.new(time, buy_stop, time + timeframe.in_seconds() * 1000, buy_stop, xloc = xloc.bar_time, color = long_color)
if bias[1] == false and close < low[1] and opp_close and took_hl and not short
short := true
sell_stop := low
if stop_orders
entry_line := line.new(time, sell_stop, time + timeframe.in_seconds() * 1000, sell_stop, xloc = xloc.bar_time, color = short_color)
if long == true and na(entry)
strategy.entry("Long", strategy.long, stop = stop_orders ? buy_stop : na)
else if short == true and na(entry)
strategy.entry("Short", strategy.short, stop = stop_orders ? sell_stop : na)
if fixed_rr
if strategy.position_size[1] == 0 and strategy.position_size != 0
if strategy.position_size > 0
entry := stop_orders ? buy_stop : open
risk_price.unshift(entry - risk)
reward_price.unshift(entry + reward)
if strategy.position_size < 0
entry := stop_orders ? sell_stop : open
risk_price.unshift(entry + risk)
reward_price.unshift(entry - reward)
if strategy.position_size > 0
strategy.exit("Long", comment = "Exit Long", limit = reward_price.get(0), stop = risk_price.get(0))
if draw_rr
if fixed_rr and na(entry[2]) and risk_box.size() == 0
rr_boxes(entry, true)
if risk_box.size() > 0
risk_box.get(0).set_right(time)
reward_box.get(0).set_right(time)
if strategy.position_size < 0
strategy.exit("Short", comment = "Exit Short", limit = reward_price.get(0), stop = risk_price.get(0))
if draw_rr
if fixed_rr and na(entry[2]) and risk_box.size() == 0
rr_boxes(entry, false)
if risk_box.size() > 0
risk_box.get(0).set_right(time)
reward_box.get(0).set_right(time)
if not t_trade and t_trade[1]
strategy.close_all("EOD") |