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
|
---|---|---|---|---|---|---|---|---|
DRSI DMA Scalping Strategy No Repaint | https://www.tradingview.com/script/RAfAWxLC-DRSI-DMA-Scalping-Strategy-No-Repaint/ | allenlk | https://www.tradingview.com/u/allenlk/ | 502 | 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/
// © Allenlk
//@version=4
strategy("DRSI DMA Scalping Strategy", shorttitle="DRSIDMA", overlay=false, initial_capital=1000, pyramiding=2, default_qty_type=strategy.percent_of_equity, default_qty_value=100)
//Inputs
matype = input(7, minval=1, maxval=8, title="1=SMA, 2=EMA, 3=WMA, 4=HullMA, 5=VWMA, 6=RMA, 7=TEMA, 8=Tilson T3", group="Moving Average")
masrc = input(close, title="MA Source", group="Moving Average")
malen = input(5, title="Moving Average Length - LookBack Period", group="Moving Average")
factorT3 = input(defval=7, title="Tilson T3 Factor - *.10 - so 7 = .7 etc.", minval=0, group="Moving Average")
maderiv = input(3, title="MA Slope Lookback", minval=1, group="Moving Average")
masmooth = input(5, title="MA Slope Smoothing", minval=1, group="Moving Average")
momtype = input(3, minval=1, maxval=3, title="1=RSI, 2=CCI, 3=RSI/ROC", group="Momentum Moving Average")
momsrc = input(close, title="Momentum Source", group="Momentum Moving Average")
momlen = input(3, title="Momentum Length", minval=1, group="Momentum Moving Average")
momderiv = input(8, title="Momentum Slope Lookback", minval=1, group="Momentum Moving Average")
momsmooth = input(7, title="Momentum Slope Smoothing", minval=1, group="Momentum Moving Average")
higherTf = input("1", title="Higher timeframe?", type = input.resolution, group="Time Resolution")
higherTfmult = input(130, title="MA Slope multiplier for Alternate Resolutions (Make the waves of the blue line similar size as the orange line)", group="Time Resolution")
buffup = input(0.02, title="Buy when both slopes cross this line", step=0.01, group="Buy and Sell Threshold")
bufflow = input(-0.03, title="Sell when both slopes cross this line", step=0.01, group="Buy and Sell Threshold")
lowVolMALength = input(28, title="Big MA Length", minval=1, group="Low Volatility Function")
MAlength = input(10, title="Low Volatility Moving Average Length", minval=1, group="Low Volatility Function")
MAThresh = input(0.05, title="Low Volatility Buy and Sell Threshold", step=0.01, group="Low Volatility Function")
Volminimum = input(2.5, title="Minimum volatility to trade", minval=0, step=0.01, group="Low Volatility Function")
//Low Volatility Function
//When Volatility is low refer to the slope of a long moving average
low_vol_MA = sma(close, lowVolMALength)
low_vol_down = (low_vol_MA[3] - low_vol_MA[1]) > MAThresh
low_vol_up = (low_vol_MA[3] - low_vol_MA[1]) < MAThresh * -1
percent_volatility = (1 - (low / high)) * 100
chng_MA = sma(percent_volatility, MAlength)
bad_vol = chng_MA < Volminimum
//No repaint function
nrp_funct(_symbol, _res, _src) => security(_symbol, _res, _src[barstate.isrealtime ? 1 : 0])
//hull ma definition
hullma = wma(2*wma(masrc, malen/2)-wma(masrc, malen), round(sqrt(malen)))
//TEMA definition
ema1 = ema(masrc, malen)
ema2 = ema(ema1, malen)
ema3 = ema(ema2, malen)
tema = 3 * (ema1 - ema2) + ema3
//Tilson T3
factor = factorT3 *.10
gd(masrc, malen, factor) => ema(masrc, malen) * (1 + factor) - ema(ema(masrc, malen), malen) * factor
t3(masrc, malen, factor) => gd(gd(gd(masrc, malen, factor), malen, factor), malen, factor)
tilT3 = t3(masrc, malen, factor)
//MA Type
avg = matype == 1 ? sma(masrc,malen) : matype == 2 ? ema(masrc,malen) : matype == 3 ? wma(masrc,malen) : matype == 4 ? hullma : matype == 5 ? vwma(masrc, malen) : matype == 6 ? rma(masrc,malen) : matype == 7 ? 3 * (ema1 - ema2) + ema3 : tilT3
//MA Slope Percentage
DeltaAvg = (avg / avg[maderiv]) - 1
SmoothedAvg = sma(DeltaAvg, masmooth)
MAout = nrp_funct(syminfo.tickerid, higherTf, SmoothedAvg) * higherTfmult
//Momentum indicators
Momentum = momtype == 1 ? rsi(momsrc, momlen) : momtype == 2 ? cci(momsrc, momlen) : momtype == 3 ? rsi(roc(momsrc,momlen),momlen) : na
//Momentum Slope Percentage
Deltamom = (Momentum / Momentum[momderiv]) - 1
SmoothedMom = sma(Deltamom, momsmooth)
Momout = nrp_funct(syminfo.tickerid, higherTf, SmoothedMom)
//Plottings
plot(buffup, color=color.green, title="Buy line")
plot(bufflow, color=color.red, title="Sell line")
plot(MAout, color=color.blue, linewidth=2, title="MA Slope")
plot(Momout, color=color.orange, linewidth=2, title="Momentum Slope")
longCondition = bad_vol ? low_vol_up : MAout > buffup and Momout > buffup
if (longCondition)
strategy.entry("Buy", strategy.long)
shortCondition = bad_vol ? low_vol_down : MAout < bufflow and Momout < bufflow
if (shortCondition)
strategy.entry("Sell", strategy.short) |
[KL] Bollinger bands + RSI Strategy | https://www.tradingview.com/script/GgCbRaj6-KL-Bollinger-bands-RSI-Strategy/ | DojiEmoji | https://www.tradingview.com/u/DojiEmoji/ | 308 | 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/
// © DojiEmoji
//
//@version=4
strategy("[KL] BOLL + RSI Strategy",overlay=true,pyramiding=1)
// Timeframe {
backtest_timeframe_start = input(defval = timestamp("01 Apr 2016 13:30 +0000"), title = "Backtest Start Time", type = input.time)
USE_ENDTIME = input(false,title="Define backtest end-time (If false, will test up to most recent candle)")
backtest_timeframe_end = input(defval = timestamp("01 May 2021 19:30 +0000"), title = "Backtest End Time (if checked above)", type = input.time)
within_timeframe = time >= backtest_timeframe_start and (time <= backtest_timeframe_end or not USE_ENDTIME)
// }
// Bollinger bands (sdv=2, len=20) {
BOLL_length = 20, BOLL_src = close, SMA20 = sma(BOLL_src, BOLL_length), BOLL_sDEV_x2 = 2 * stdev(BOLL_src, BOLL_length)
BOLL_upper = SMA20 + BOLL_sDEV_x2, BOLL_lower = SMA20 - BOLL_sDEV_x2
plot(SMA20, "Basis", color=#872323, offset = 0)
BOLL_p1 = plot(BOLL_upper, "BOLL Upper", color=color.navy, offset = 0, transp=50)
BOLL_p2 = plot(BOLL_lower, "BOLL Lower", color=color.navy, offset = 0, transp=50)
fill(BOLL_p1, BOLL_p2, title = "Background", color=#198787, transp=85)
// }
// Volatility Indicators {
ATR_x2 = atr(BOLL_length) * 2 // multiplier aligns with BOLL
avg_atr = sma(ATR_x2, input(1,title="No. of candles to lookback when determining ATR is decreasing"))
plot(SMA20+ATR_x2, "SMA20 + ATR_x2", color=color.gray, offset = 0, transp=50)
plot(SMA20-ATR_x2, "SMA20 - ATR_x2", color=color.gray, offset = 0, transp=50)
plotchar(ATR_x2, "ATR_x2", "", location = location.bottom)
//}
// Trailing stop loss {
TSL_source = low
var entry_price = float(0), var stop_loss_price = float(0)
trail_profit_line_color = color.green
if strategy.position_size == 0 or not within_timeframe
trail_profit_line_color := color.black
stop_loss_price := TSL_source - ATR_x2
else if strategy.position_size > 0
stop_loss_price := max(stop_loss_price, TSL_source - ATR_x2)
plot(stop_loss_price, color=trail_profit_line_color)
if strategy.position_size > 0 and stop_loss_price > stop_loss_price[1]
alert("Stop loss limit raised", alert.freq_once_per_bar)
// } end of Trailing stop loss
//Buy setup - Long positions {
is_squeezing = ATR_x2 > BOLL_sDEV_x2
if is_squeezing and within_timeframe and not is_squeezing[1]
alert("BOLL bands are squeezing", alert.freq_once_per_bar)
else if not is_squeezing and within_timeframe and is_squeezing[1]
alert("BOLL bands stopped squeezing", alert.freq_once_per_bar)
ema_trend = ema(close, 20)
concat(a, b) =>
concat = a
if a != ""
concat := concat + ", "
concat := concat + b
concat
// }
// Sell setup - Long position {
rsi_10 = rsi(close, 10), rsi_14 = rsi(close, 14)
overbought = rsi_14 > input(70,title="[Exit] RSI(14) value considered as overbought") and rsi_10 > rsi_14
// } end of Sell setup - Long position
// MAIN: {
if within_timeframe
entry_msg = ""
exit_msg = ""
// ENTRY {
conf_count = 0
volat_decr = avg_atr <= avg_atr[1]
rsi_upslope = rsi_10 > rsi_10[1] and rsi_14 > rsi_14[1]
if volat_decr and rsi_upslope and is_squeezing and strategy.position_size == 0
strategy.entry("Long",strategy.long, comment=entry_msg)
entry_price := close
stop_loss_price := TSL_source - ATR_x2
// }
// EXIT {
if strategy.position_size > 0
bExit = false
if close <= entry_price and TSL_source <= stop_loss_price
exit_msg := concat(exit_msg, "stop loss [TSL]")
bExit := true
else if close > entry_price and TSL_source <= stop_loss_price
exit_msg := concat(exit_msg, "take profit [TSL]")
bExit := true
else if overbought
exit_msg := concat(exit_msg, "overbought")
bExit := true
strategy.close("Long", when=bExit, comment=exit_msg)
// }
// }
// CLEAN UP:
if strategy.position_size == 0 and not is_squeezing
entry_price := 0
stop_loss_price := float(0)
|
Does your trading pass the seasonality test? | https://www.tradingview.com/script/jWAYPx4v-Does-your-trading-pass-the-seasonality-test/ | DasanC | https://www.tradingview.com/u/DasanC/ | 163 | 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/
// © EmpiricalFX
//@version=4
strategy("Seasonality Benchmark ","Season",overlay=false,default_qty_type=strategy.percent_of_equity,
default_qty_value=25,initial_capital=100000,currency="USD",
commission_type=strategy.commission.percent,commission_value=0.5)
input_entry_direction = input("Long","Position Type",options=["Long","Short"])
input_entry_month = input("Oct","Entry Month",options=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"])
input_exit_month = input("Jan","Entry Month",options=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"])
//Convert three character month string to integer
month_str_to_int(m)=>
ret = m == "Jan" ? 1 :
m == "Feb" ? 2 :
m == "Mar" ? 3 :
m == "Apr" ? 4 :
m == "May" ? 5 :
m == "Jun" ? 6 :
m == "Jul" ? 7 :
m == "Aug" ? 8 :
m == "Sep" ? 9 :
m == "Oct" ? 10 :
m == "Nov" ? 11 :
m == "Dec" ? 12 : -1
is_long = input_entry_direction == "Long" ? true : false
entry = month_str_to_int(input_entry_month)
exit = month_str_to_int(input_exit_month)
var balance = strategy.equity
//Entering a position is conditional on:
//1. No currently active trades
//2. Input entry month matches current month
if(strategy.opentrades == 0 and entry == month)
strategy.entry("Swing",is_long)
//Exiting a position is conditional on:
//1. Must have open trade
//2. Input exit month matches current month
if(strategy.opentrades > 0 and exit == month)
strategy.close("Swing")
//Update the balance every time a trade is exited
if(change(strategy.closedtrades)>0)
balance := strategy.equity
plot(strategy.equity,"Equity",color.orange)
plot(balance,"Balance",color.red)
|
Multi Supertrend with no-repaint HTF option strategy | https://www.tradingview.com/script/DrNY2LOA-Multi-Supertrend-with-no-repaint-HTF-option-strategy/ | ramki_simple | https://www.tradingview.com/u/ramki_simple/ | 610 | 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/
// © ramki_simple
// Thanks to LonesomeTheBlue for the original code
//@version=4
strategy("Multi Supertrend with no-repaint HTF option strategy", overlay = true, shorttitle='Multi Supertrend')
//auto higher time frame
HTFAuto = timeframe.period == '1' ? '5' :
timeframe.period == '3' ? '15' :
timeframe.period == '5' ? '15' :
timeframe.period == '15' ? '60' :
timeframe.period == '30' ? '60' :
timeframe.period == '45' ? '60' :
timeframe.period == '60' ? '240' :
timeframe.period == '120' ? '240' :
timeframe.period == '180' ? '240' :
timeframe.period == '240' ? 'D' :
timeframe.period == 'D' ? 'W' :
'5W'
HTFSelection = input(title='Select HTF Automatically for Additional Supertrend', type=input.bool, defval=false)
HTFUserSel = input(title='Select Higher Timeframe for Additional Supertrend',type=input.resolution, defval ='')
HTF = HTFSelection ? HTFAuto : HTFUserSel
Mult1 = input(title='Multiplier for Default Supertrend', defval=3.0, minval = 0, maxval = 10)
Period1 = input(title='Period for Default Supertrend', defval=10, minval = 1, maxval = 100)
Mult2 = input(title='Multiplier for Additional Supertrend', defval=2.0, minval = 0, maxval = 10)
Period2 = input(title='Period for Additional Supertrend', defval=14, minval = 1, maxval = 100)
chbarcol = input(true, title = "Change Bar Color")
[Trailings, Trend] = supertrend(Mult1, Period1)
linecolor = Trend == -1 and Trend[1] == -1 ? color.teal :
Trend == 1 and Trend[1] == 1 ? color.red :
color.new(color.white, 100)
plot(Trailings, color = linecolor, linewidth = 2,title = "SuperTrend")
f_Security(_symbol, _res, _src) => security(_symbol, _res, _src[1], lookahead = barmerge.lookahead_on)
nonVectorSupertrend(Mult, Period) =>
[Trail_, Trend_] = supertrend(Mult, Period)
Trail_*Trend_
[TrailingslHtf, TrendHtf] = supertrend(Mult2, Period2)
if HTF != timeframe.period and HTF != ''
CompositeTrailHtf = f_Security(syminfo.tickerid, HTF,nonVectorSupertrend(Mult2, Period2) )
TrailingslHtf := abs(CompositeTrailHtf)
TrendHtf := CompositeTrailHtf > 0 ? 1 : -1
linecolorHtf = TrendHtf == -1 and TrendHtf[1] == -1 ? color.blue :
TrendHtf == 1 and TrendHtf[1] == 1 ? color.maroon :
color.new(color.white, 100)
plot(TrailingslHtf, color = linecolorHtf, linewidth = 3, title = "Supertrend Higher Time Frame")
barcolor_ = Trend == -1 and TrendHtf == -1 ? color.lime :
Trend == 1 and TrendHtf == 1 ? color.red :
color.white
barcolor(color = chbarcol ? barcolor_ : na)
vwapfilter = input(false)
Long = Trend == -1 and TrendHtf == -1
Short = Trend == 1 and TrendHtf == 1
strategy.entry("enter long", true, 1, when = Long and not Long[1] and (vwapfilter and close > vwap or not vwapfilter))
strategy.entry("enter short", false, 1, when = Short and not Short[1] and (vwapfilter and close < vwap or not vwapfilter))
strategy.close("enter long", when = Long[1] and not Long)
strategy.close("enter short", when = Short[1] and not Short) |
BB+RSI+OBV | https://www.tradingview.com/script/zqWwm7TT-BB-RSI-OBV/ | atakhadivi | https://www.tradingview.com/u/atakhadivi/ | 47 | 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/
// © atakhadivi
//@version=4
strategy("BB+RSI+OBV", overlay=true)
src = close
obv = cum(sign(change(src)) * volume)
// plot(obv, color=#3A6CA8, title="OnBalanceVolume")
source = close
length = input(20, minval=1)
mult = input(2.0, minval=0.001, maxval=50)
basis = sma(source, length)
dev = mult * stdev(source, length)
upper = basis + dev
lower = basis - dev
buyEntry = source > basis and rsi(close, 14) > 50 and obv[1] < obv
buyExit = source < lower
sellEntry = source < basis and rsi(close, 14) < 50 and obv[1] > obv
sellExit = source > upper
strategy.entry("BBandLE", strategy.long, stop=lower, oca_name="BollingerBands", oca_type=strategy.oca.cancel, comment="BBandLE", when=buyEntry)
strategy.exit(id='BBandLE', when=buyExit)
strategy.entry("BBandSE", strategy.short, stop=upper, oca_name="BollingerBands", oca_type=strategy.oca.cancel, comment="BBandSE", when=sellEntry)
strategy.exit(id='BBandSE', when=sellExit) |
A Strategy for Leledec | https://www.tradingview.com/script/yxDDArYq-A-Strategy-for-Leledec/ | Joy_Bangla | https://www.tradingview.com/u/Joy_Bangla/ | 99 | 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/
// © Joy_Bangla
//@version=4
strategy("A Strategy for Leledec", shorttitle ="Leledec Strategy", overlay=true, commission_value=0.075, initial_capital=10000, default_qty_type = strategy.percent_of_equity, default_qty_value = 10)
maj = input(true, "Major Leledec Exhausion Bar :: Show")
min=input(false, "Minor Leledec Exhausion Bar :: Show")
leledcSrc = input(close, "Major Leledec Exhausion Bar :: Source")
maj_qual = input(6, "Major Leledec Exhausion Bar :: Bar count no")
maj_len = input(30, "Major Leledec Exhausion Bar :: Highest / Lowest")
min_qual=input(5, "Minor Leledec Exhausion Bar :: Bar count no")
min_len=input(5, "Minor Leledec Exhausion Bar :: Bar count no")
bindexSindex = input(1, "bindexSindex")
closeVal = input(4, "Close")
lele(qual, len) =>
bindex = 0
sindex = 0
bindex := nz(bindex[bindexSindex], 0)
sindex := nz(sindex[bindexSindex], 0)
ret = 0
if close > close[closeVal]
bindex := bindex + 1
bindex
if close < close[closeVal]
sindex := sindex + 1
sindex
if bindex > qual and close < open and high >= highest(high, len)
bindex := 0
ret := -1
ret
if sindex > qual and close > open and low <= lowest(low, len)
sindex := 0
ret := 1
ret
return = ret
return
major = lele(maj_qual, maj_len)
minor=lele(min_qual,min_len)
plotchar(maj ? major == -1 ? high : na : na, char='•', location=location.absolute, color=color.red, transp=0, size=size.large)
plotchar(maj ? major == 1 ? low : na : na, char='•', location=location.absolute, color=color.lime, transp=0, size=size.large)
plotchar(min ? (minor==1?high:na) : na, char='x', location=location.absolute, color=color.red, transp=0, size=size.small)
plotchar(min ? (minor==-1?low:na) : na, char='x', location=location.absolute, color=color.lime, transp=0, size=size.small)
leledecMajorBullish = major==1?low:na
leledecMajorBearish = major==-1?high:na
leledecMinorBullish = minor==1?low:na
leledecMinorBearish = minor==-1?high:na
buySignalBasedOnMajorLeledecOnly = major==1?low:na
sellSignalBasedOnMajorLeldecOnly = minor==-1?high:na
// === INPUT BACKTEST RANGE ===
fromMonth = input(defval = 1, title = "From Month", type = input.integer, minval = 1, maxval = 12)
fromDay = input(defval = 1, title = "From Day", type = input.integer, minval = 1, maxval = 31)
fromYear = input(defval = 2018, title = "From Year", type = input.integer, minval = 2017, maxval = 2030)
thruMonth = input(defval = 12, title = "Thru Month", type = input.integer, minval = 1, maxval = 11)
thruDay = input(defval = 1, title = "Thru Day", type = input.integer, minval = 1, maxval = 30)
thruYear = input(defval = 2030, title = "Thru Year", type = input.integer, minval = 2017, maxval = 2030)
// === INPUT SHOW PLOT ===
showDate = input(defval = true, title = "Show Date Range", type = input.bool)
// === FUNCTION EXAMPLE ===
start = timestamp(fromYear, fromMonth, fromDay, 00, 00) // backtest start window
finish = timestamp(thruYear, thruMonth, thruDay, 23, 59) // backtest finish window
window() => time >= start and time <= finish ? true : false // create function "within window of time"
if (window())
strategy.entry("buy", strategy.long, when=buySignalBasedOnMajorLeledecOnly)
strategy.entry("sell", strategy.short, when=sellSignalBasedOnMajorLeldecOnly)
|
GANN_EMA_VWAP_BY_THEHOUSEOFTRADERS | https://www.tradingview.com/script/3MQProH9-GANN-EMA-VWAP-BY-THEHOUSEOFTRADERS/ | TheHouseOfTraders | https://www.tradingview.com/u/TheHouseOfTraders/ | 53 | 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/
// © THEHOUSEOFTRADERS
//@version=4
strategy("GANN_EMA_VWAP_BY_THEHOUSEOFTRADERS", overlay=true)
// VWAP BY SPA
price = input(type=input.source, defval=hlc3, title="VWAP Source")
enable_vwap = input(true, title="Enable VWAP")
vwapResolution = input(title = "VWAP Resolution", defval = "", type=input.resolution)
vwapFunction = vwap(price)
vwapSecurity = security(syminfo.tickerid, vwapResolution, vwapFunction)
plot(enable_vwap ? vwapSecurity : na, title="VWAP", linewidth=2, color=color.rgb(255,0,127), editable=true) // All TimeFrames
// EMA BY SPA
s50ema = ema(close, 50)
s100ema = ema(close, 100)
s200ema = ema(close, 200)
plot(s50ema, title="Ema 50", color = color.green, linewidth = 3 )
plot(s100ema, title="Ema 100", color = color.rgb(153,51,255), linewidth = 3)
plot(s200ema, title="Ema 200", color = color.black, linewidth = 3)
// GANN By SPA
hline(1,title="1",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1.5625,title="1.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2.25,title="1.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(3.0625,title="1.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(4,title="2",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(5.0625,title="2.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(6.25,title="2.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(7.5625,title="2.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(9,title="3",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(10.5625,title="3.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(12.25,title="3.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(14.0625,title="3.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(16,title="4",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(18.0625,title="4.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(20.25,title="4.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(22.5625,title="4.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(25,title="5",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(27.5625,title="5.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(30.25,title="5.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(33.0625,title="5.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(36,title="6",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(39.0625,title="6.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(42.25,title="6.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(45.5625,title="6.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(49,title="7",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(52.5625,title="7.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(56.25,title="7.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(60.0625,title="7.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(64,title="8",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(68.0625,title="8.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(72.25,title="8.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(76.5625,title="8.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(81,title="9",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(85.5625,title="9.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(90.25,title="9.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(95.0625,title="9.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(100,title="10",color=color.red, linestyle=hline.style_solid, linewidth=3, editable=false)
hline(105.0625,title="10.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(110.25,title="10.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(115.5625,title="10.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(121,title="11",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(126.5625,title="11.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(132.25,title="11.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(138.0625,title="11.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(144,title="12",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(150.0625,title="12.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(156.25,title="12.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(162.5625,title="12.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(169,title="13",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(175.5625,title="13.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(182.25,title="13.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(189.0625,title="13.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(196,title="14",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(203.0625,title="14.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(210.25,title="14.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(217.5625,title="14.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(225,title="15",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(232.5625,title="15.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(240.25,title="15.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(248.0625,title="15.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(256,title="16",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(264.0625,title="16.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(272.25,title="16.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(280.5625,title="16.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(289,title="17",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(297.5625,title="17.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(306.25,title="17.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(315.0625,title="17.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(324,title="18",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(333.0625,title="18.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(342.25,title="18.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(351.5625,title="18.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(361,title="19",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(370.5625,title="19.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(380.25,title="19.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(390.0625,title="19.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(400,title="20",color=color.red, linestyle=hline.style_solid, linewidth=3, editable=false)
hline(410.0625,title="20.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(420.25,title="20.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(430.5625,title="20.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(441,title="21",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(451.5625,title="21.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(462.25,title="21.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(473.0625,title="21.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(484,title="22",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(495.0625,title="22.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(506.25,title="22.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(517.5625,title="22.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(529,title="23",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(540.5625,title="23.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(552.25,title="23.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(564.0625,title="23.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(576,title="24",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(588.0625,title="24.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(600.25,title="24.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(612.5625,title="24.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(625,title="25",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(637.5625,title="25.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(650.25,title="25.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(663.0625,title="25.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(676,title="26",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(689.0625,title="26.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(702.25,title="26.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(715.5625,title="26.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(729,title="27",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(742.5625,title="27.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(756.25,title="27.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(770.0625,title="27.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(784,title="28",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(798.0625,title="28.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(812.25,title="28.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(826.5625,title="28.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(841,title="29",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(855.5625,title="29.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(870.25,title="29.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(885.0625,title="29.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(900,title="30",color=color.red, linestyle=hline.style_solid, linewidth=3, editable=false)
hline(915.0625,title="30.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(930.25,title="30.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(945.5625,title="30.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(961,title="31",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(976.5625,title="31.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(992.25,title="31.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1008.0625,title="31.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1024,title="32",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1040.0625,title="32.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1056.25,title="32.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1072.5625,title="32.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1089,title="33",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1105.5625,title="33.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1122.25,title="33.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1139.0625,title="33.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1156,title="34",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1173.0625,title="34.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1190.25,title="34.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1207.5625,title="34.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1225,title="35",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1242.5625,title="35.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1260.25,title="35.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1278.0625,title="35.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1296,title="36",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1314.0625,title="36.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1332.25,title="36.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1350.5625,title="36.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1369,title="37",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1387.5625,title="37.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1406.25,title="37.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1425.0625,title="37.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1444,title="38",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1463.0625,title="38.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1482.25,title="38.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1501.5625,title="38.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1521,title="39",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1540.5625,title="39.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1560.25,title="39.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1580.0625,title="39.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1600,title="40",color=color.red, linestyle=hline.style_solid, linewidth=3, editable=false)
hline(1620.0625,title="40.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1640.25,title="40.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1660.5625,title="40.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1681,title="41",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1701.5625,title="41.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1722.25,title="41.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1743.0625,title="41.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1764,title="42",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1785.0625,title="42.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1806.25,title="42.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1827.5625,title="42.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1849,title="43",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1870.5625,title="43.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1892.25,title="43.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1914.0625,title="43.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1936,title="44",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1958.0625,title="44.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(1980.25,title="44.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2002.5625,title="44.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2025,title="45",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2047.5625,title="45.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2070.25,title="45.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2093.0625,title="45.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2116,title="46",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2139.0625,title="46.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2162.25,title="46.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2185.5625,title="46.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2209,title="47",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2232.5625,title="47.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2256.25,title="47.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2280.0625,title="47.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2304,title="48",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2328.0625,title="48.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2352.25,title="48.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2376.5625,title="48.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2401,title="49",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2425.5625,title="49.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2450.25,title="49.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2475.0625,title="49.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2500,title="50",color=color.red, linestyle=hline.style_solid, linewidth=3, editable=false)
hline(2525.0625,title="50.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2550.25,title="50.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2575.5625,title="50.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2601,title="51",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2626.5625,title="51.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2652.25,title="51.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2678.0625,title="51.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2704,title="52",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2730.0625,title="52.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2756.25,title="52.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2782.5625,title="52.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2809,title="53",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2835.5625,title="53.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2862.25,title="53.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2889.0625,title="53.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2916,title="54",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2943.0625,title="54.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2970.25,title="54.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(2997.5625,title="54.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(3025,title="55",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(3052.5625,title="55.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(3080.25,title="55.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(3108.0625,title="55.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(3136,title="56",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(3164.0625,title="56.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(3192.25,title="56.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(3220.5625,title="56.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(3249,title="57",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(3277.5625,title="57.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(3306.25,title="57.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(3335.0625,title="57.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(3364,title="58",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(3393.0625,title="58.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(3422.25,title="58.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(3451.5625,title="58.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(3481,title="59",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(3510.5625,title="59.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(3540.25,title="59.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(3570.0625,title="59.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(3600,title="60",color=color.red, linestyle=hline.style_solid, linewidth=3, editable=false)
hline(3630.0625,title="60.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(3660.25,title="60.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(3690.5625,title="60.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(3721,title="61",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(3751.5625,title="61.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(3782.25,title="61.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(3813.0625,title="61.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(3844,title="62",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(3875.0625,title="62.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(3906.25,title="62.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(3937.5625,title="62.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(3969,title="63",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(4000.5625,title="63.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(4032.25,title="63.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(4064.0625,title="63.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(4096,title="64",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(4128.0625,title="64.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(4160.25,title="64.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(4192.5625,title="64.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(4225,title="65",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(4257.5625,title="65.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(4290.25,title="65.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(4323.0625,title="65.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(4356,title="66",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(4389.0625,title="66.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(4422.25,title="66.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(4455.5625,title="66.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(4489,title="67",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(4522.5625,title="67.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(4556.25,title="67.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(4590.0625,title="67.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(4624,title="68",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(4658.0625,title="68.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(4692.25,title="68.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(4726.5625,title="68.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(4761,title="69",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(4795.5625,title="69.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(4830.25,title="69.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(4865.0625,title="69.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(4900,title="70",color=color.red, linestyle=hline.style_solid, linewidth=3, editable=false)
hline(4935.0625,title="70.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(4970.25,title="70.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(5005.5625,title="70.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(5041,title="71",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(5076.5625,title="71.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(5112.25,title="71.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(5148.0625,title="71.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(5184,title="72",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(5220.0625,title="72.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(5256.25,title="72.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(5292.5625,title="72.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(5329,title="73",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(5365.5625,title="73.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(5402.25,title="73.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(5439.0625,title="73.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(5476,title="74",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(5513.0625,title="74.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(5550.25,title="74.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(5587.5625,title="74.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(5625,title="75",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(5662.5625,title="75.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(5700.25,title="75.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(5738.0625,title="75.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(5776,title="76",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(5814.0625,title="76.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(5852.25,title="76.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(5890.5625,title="76.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(5929,title="77",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(5967.5625,title="77.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(6006.25,title="77.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(6045.0625,title="77.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(6084,title="78",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(6123.0625,title="78.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(6162.25,title="78.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(6201.5625,title="78.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(6241,title="79",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(6280.5625,title="79.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(6320.25,title="79.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(6360.0625,title="79.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(6400,title="80",color=color.red, linestyle=hline.style_solid, linewidth=3, editable=false)
hline(6440.0625,title="80.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(6480.25,title="80.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(6520.5625,title="80.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(6561,title="81",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(6601.5625,title="81.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(6642.25,title="81.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(6683.0625,title="81.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(6724,title="82",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(6765.0625,title="82.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(6806.25,title="82.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(6847.5625,title="82.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(6889,title="83",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(6930.5625,title="83.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(6972.25,title="83.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(7014.0625,title="83.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(7056,title="84",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(7098.0625,title="84.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(7140.25,title="84.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(7182.5625,title="84.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(7225,title="85",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(7267.5625,title="85.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(7310.25,title="85.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(7353.0625,title="85.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(7396,title="86",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(7439.0625,title="86.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(7482.25,title="86.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(7525.5625,title="86.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(7569,title="87",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(7612.5625,title="87.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(7656.25,title="87.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(7700.0625,title="87.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(7744,title="88",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(7788.0625,title="88.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(7832.25,title="88.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(7876.5625,title="88.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(7921,title="89",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(7965.5625,title="89.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(8010.25,title="89.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(8055.0625,title="89.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(8100,title="90",color=color.red, linestyle=hline.style_solid, linewidth=3, editable=false)
hline(8145.0625,title="90.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(8190.25,title="90.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(8235.5625,title="90.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(8281,title="91",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(8326.5625,title="91.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(8372.25,title="91.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(8418.0625,title="91.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(8464,title="92",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(8510.0625,title="92.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(8556.25,title="92.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(8602.5625,title="92.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(8649,title="93",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(8695.5625,title="93.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(8742.25,title="93.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(8789.0625,title="93.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(8836,title="94",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(8883.0625,title="94.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(8930.25,title="94.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(8977.5625,title="94.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(9025,title="95",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(9072.5625,title="95.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(9120.25,title="95.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(9168.0625,title="95.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(9216,title="96",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(9264.0625,title="96.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(9312.25,title="96.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(9360.5625,title="96.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(9409,title="97",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(9457.5625,title="97.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(9506.25,title="97.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(9555.0625,title="97.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(9604,title="98",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(9653.0625,title="98.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(9702.25,title="98.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(9751.5625,title="98.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(9801,title="99",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(9850.5625,title="99.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(9900.25,title="99.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(9950.0625,title="99.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(10000,title="100",color=color.red, linestyle=hline.style_solid, linewidth=3, editable=false)
hline(10050.0625,title="100.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(10100.25,title="100.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(10150.5625,title="100.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(10201,title="101",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(10251.5625,title="101.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(10302.25,title="101.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(10353.0625,title="101.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(10404,title="102",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(10455.0625,title="102.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(10506.25,title="102.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(10557.5625,title="102.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(10609,title="103",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(10660.5625,title="103.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(10712.25,title="103.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(10764.0625,title="103.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(10816,title="104",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(10868.0625,title="104.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(10920.25,title="104.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(10972.5625,title="104.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(11025,title="105",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(11077.5625,title="105.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(11130.25,title="105.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(11183.0625,title="105.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(11236,title="106",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(11289.0625,title="106.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(11342.25,title="106.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(11395.5625,title="106.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(11449,title="107",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(11502.5625,title="107.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(11556.25,title="107.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(11610.0625,title="107.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(11664,title="108",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(11718.0625,title="108.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(11772.25,title="108.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(11826.5625,title="108.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(11881,title="109",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(11935.5625,title="109.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(11990.25,title="109.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(12045.0625,title="109.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(12100,title="110",color=color.red, linestyle=hline.style_solid, linewidth=3, editable=false)
hline(12155.0625,title="110.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(12210.25,title="110.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(12265.5625,title="110.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(12321,title="111",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(12376.5625,title="111.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(12432.25,title="111.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(12488.0625,title="111.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(12544,title="112",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(12600.0625,title="112.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(12656.25,title="112.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(12712.5625,title="112.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(12769,title="113",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(12825.5625,title="113.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(12882.25,title="113.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(12939.0625,title="113.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(12996,title="114",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(13053.0625,title="114.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(13110.25,title="114.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(13167.5625,title="114.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(13225,title="115",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(13282.5625,title="115.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(13340.25,title="115.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(13398.0625,title="115.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(13456,title="116",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(13514.0625,title="116.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(13572.25,title="116.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(13630.5625,title="116.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(13689,title="117",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(13747.5625,title="117.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(13806.25,title="117.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(13865.0625,title="117.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(13924,title="118",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(13983.0625,title="118.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(14042.25,title="118.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(14101.5625,title="118.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(14161,title="119",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(14220.5625,title="119.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(14280.25,title="119.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(14340.0625,title="119.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(14400,title="120",color=color.red, linestyle=hline.style_solid, linewidth=3, editable=false)
hline(14460.0625,title="120.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(14520.25,title="120.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(14580.5625,title="120.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(14641,title="121",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(14701.5625,title="121.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(14762.25,title="121.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(14823.0625,title="121.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(14884,title="122",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(14945.0625,title="122.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(15006.25,title="122.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(15067.5625,title="122.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(15129,title="123",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(15190.5625,title="123.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(15252.25,title="123.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(15314.0625,title="123.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(15376,title="124",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(15438.0625,title="124.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(15500.25,title="124.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(15562.5625,title="124.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(15625,title="125",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(15687.5625,title="125.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(15750.25,title="125.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(15813.0625,title="125.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(15876,title="126",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(15939.0625,title="126.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(16002.25,title="126.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(16065.5625,title="126.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(16129,title="127",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(16192.5625,title="127.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(16256.25,title="127.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(16320.0625,title="127.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(16384,title="128",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(16448.0625,title="128.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(16512.25,title="128.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(16576.5625,title="128.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(16641,title="129",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(16705.5625,title="129.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(16770.25,title="129.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(16835.0625,title="129.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(16900,title="130",color=color.red, linestyle=hline.style_solid, linewidth=3, editable=false)
hline(16965.0625,title="130.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(17030.25,title="130.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(17095.5625,title="130.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(17161,title="131",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(17226.5625,title="131.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(17292.25,title="131.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(17358.0625,title="131.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(17424,title="132",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(17490.0625,title="132.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(17556.25,title="132.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(17622.5625,title="132.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(17689,title="133",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(17755.5625,title="133.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(17822.25,title="133.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(17889.0625,title="133.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(17956,title="134",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(18023.0625,title="134.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(18090.25,title="134.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(18157.5625,title="134.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(18225,title="135",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(18292.5625,title="135.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(18360.25,title="135.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(18428.0625,title="135.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(18496,title="136",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(18564.0625,title="136.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(18632.25,title="136.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(18700.5625,title="136.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(18769,title="137",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(18837.5625,title="137.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(18906.25,title="137.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(18975.0625,title="137.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(19044,title="138",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(19113.0625,title="138.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(19182.25,title="138.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(19251.5625,title="138.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(19321,title="139",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(19390.5625,title="139.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(19460.25,title="139.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(19530.0625,title="139.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(19600,title="140",color=color.red, linestyle=hline.style_solid, linewidth=3, editable=false)
hline(19670.0625,title="140.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(19740.25,title="140.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(19810.5625,title="140.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(19881,title="141",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(19951.5625,title="141.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(20022.25,title="141.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(20093.0625,title="141.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(20164,title="142",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(20235.0625,title="142.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(20306.25,title="142.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(20377.5625,title="142.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(20449,title="143",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(20520.5625,title="143.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(20592.25,title="143.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(20664.0625,title="143.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(20736,title="144",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(20808.0625,title="144.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(20880.25,title="144.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(20952.5625,title="144.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(21025,title="145",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(21097.5625,title="145.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(21170.25,title="145.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(21243.0625,title="145.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(21316,title="146",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(21389.0625,title="146.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(21462.25,title="146.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(21535.5625,title="146.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(21609,title="147",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(21682.5625,title="147.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(21756.25,title="147.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(21830.0625,title="147.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(21904,title="148",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(21978.0625,title="148.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(22052.25,title="148.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(22126.5625,title="148.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(22201,title="149",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(22275.5625,title="149.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(22350.25,title="149.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(22425.0625,title="149.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(22500,title="150",color=color.red, linestyle=hline.style_solid, linewidth=3, editable=false)
hline(22575.0625,title="150.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(22650.25,title="150.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(22725.5625,title="150.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(22801,title="151",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(22876.5625,title="151.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(22952.25,title="151.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(23028.0625,title="151.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(23104,title="152",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(23180.0625,title="152.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(23256.25,title="152.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(23332.5625,title="152.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(23409,title="153",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(23485.5625,title="153.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(23562.25,title="153.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(23639.0625,title="153.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(23716,title="154",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(23793.0625,title="154.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(23870.25,title="154.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(23947.5625,title="154.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(24025,title="155",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(24102.5625,title="155.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(24180.25,title="155.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(24258.0625,title="155.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(24336,title="156",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(24414.0625,title="156.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(24492.25,title="156.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(24570.5625,title="156.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(24649,title="157",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(24727.5625,title="157.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(24806.25,title="157.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(24885.0625,title="157.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(24964,title="158",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(25043.0625,title="158.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(25122.25,title="158.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(25201.5625,title="158.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(25281,title="159",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(25360.5625,title="159.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(25440.25,title="159.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(25520.0625,title="159.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(25600,title="160",color=color.red, linestyle=hline.style_solid, linewidth=3, editable=false)
hline(25680.0625,title="160.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(25760.25,title="160.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(25840.5625,title="160.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(25921,title="161",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(26001.5625,title="161.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(26082.25,title="161.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(26163.0625,title="161.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(26244,title="162",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(26325.0625,title="162.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(26406.25,title="162.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(26487.5625,title="162.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(26569,title="163",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(26650.5625,title="163.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(26732.25,title="163.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(26814.0625,title="163.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(26896,title="164",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(26978.0625,title="164.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(27060.25,title="164.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(27142.5625,title="164.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(27225,title="165",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(27307.5625,title="165.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(27390.25,title="165.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(27473.0625,title="165.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(27556,title="166",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(27639.0625,title="166.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(27722.25,title="166.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(27805.5625,title="166.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(27889,title="167",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(27972.5625,title="167.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(28056.25,title="167.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(28140.0625,title="167.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(28224,title="168",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(28308.0625,title="168.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(28392.25,title="168.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(28476.5625,title="168.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(28561,title="169",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(28645.5625,title="169.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(28730.25,title="169.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(28815.0625,title="169.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(28900,title="170",color=color.red, linestyle=hline.style_solid, linewidth=3, editable=false)
hline(28985.0625,title="170.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(29070.25,title="170.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(29155.5625,title="170.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(29241,title="171",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(29326.5625,title="171.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(29412.25,title="171.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(29498.0625,title="171.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(29584,title="172",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(29670.0625,title="172.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(29756.25,title="172.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(29842.5625,title="172.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(29929,title="173",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(30015.5625,title="173.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(30102.25,title="173.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(30189.0625,title="173.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(30276,title="174",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(30363.0625,title="174.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(30450.25,title="174.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(30537.5625,title="174.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(30625,title="175",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(30712.5625,title="175.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(30800.25,title="175.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(30888.0625,title="175.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(30976,title="176",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(31064.0625,title="176.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(31152.25,title="176.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(31240.5625,title="176.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(31329,title="177",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(31417.5625,title="177.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(31506.25,title="177.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(31595.0625,title="177.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(31684,title="178",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(31773.0625,title="178.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(31862.25,title="178.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(31951.5625,title="178.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(32041,title="179",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(32130.5625,title="179.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(32220.25,title="179.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(32310.0625,title="179.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(32400,title="180",color=color.red, linestyle=hline.style_solid, linewidth=3, editable=false)
hline(32490.0625,title="180.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(32580.25,title="180.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(32670.5625,title="180.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(32761,title="181",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(32851.5625,title="181.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(32942.25,title="181.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(33033.0625,title="181.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(33124,title="182",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(33215.0625,title="182.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(33306.25,title="182.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(33397.5625,title="182.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(33489,title="183",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(33580.5625,title="183.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(33672.25,title="183.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(33764.0625,title="183.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(33856,title="184",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(33948.0625,title="184.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(34040.25,title="184.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(34132.5625,title="184.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(34225,title="185",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(34317.5625,title="185.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(34410.25,title="185.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(34503.0625,title="185.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(34596,title="186",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(34689.0625,title="186.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(34782.25,title="186.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(34875.5625,title="186.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(34969,title="187",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(35062.5625,title="187.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(35156.25,title="187.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(35250.0625,title="187.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(35344,title="188",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(35438.0625,title="188.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(35532.25,title="188.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(35626.5625,title="188.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(35721,title="189",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(35815.5625,title="189.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(35910.25,title="189.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(36005.0625,title="189.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(36100,title="190",color=color.red, linestyle=hline.style_solid, linewidth=3, editable=false)
hline(36195.0625,title="190.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(36290.25,title="190.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(36385.5625,title="190.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(36481,title="191",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(36576.5625,title="191.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(36672.25,title="191.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(36768.0625,title="191.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(36864,title="192",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(36960.0625,title="192.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(37056.25,title="192.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(37152.5625,title="192.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(37249,title="193",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(37345.5625,title="193.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(37442.25,title="193.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(37539.0625,title="193.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(37636,title="194",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(37733.0625,title="194.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(37830.25,title="194.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(37927.5625,title="194.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(38025,title="195",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(38122.5625,title="195.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(38220.25,title="195.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(38318.0625,title="195.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(38416,title="196",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(38514.0625,title="196.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(38612.25,title="196.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(38710.5625,title="196.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(38809,title="197",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(38907.5625,title="197.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(39006.25,title="197.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(39105.0625,title="197.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(39204,title="198",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(39303.0625,title="198.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(39402.25,title="198.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(39501.5625,title="198.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(39601,title="199",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(39700.5625,title="199.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(39800.25,title="199.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(39900.0625,title="199.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(40000,title="200",color=color.red, linestyle=hline.style_solid, linewidth=3, editable=false)
hline(40100.0625,title="200.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(40200.25,title="200.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(40300.5625,title="200.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(40401,title="201",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(40501.5625,title="201.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(40602.25,title="201.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(40703.0625,title="201.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(40804,title="202",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(40905.0625,title="202.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(41006.25,title="202.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(41107.5625,title="202.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(41209,title="203",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(41310.5625,title="203.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(41412.25,title="203.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(41514.0625,title="203.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(41616,title="204",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(41718.0625,title="204.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(41820.25,title="204.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(41922.5625,title="204.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(42025,title="205",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(42127.5625,title="205.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(42230.25,title="205.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(42333.0625,title="205.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(42436,title="206",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(42539.0625,title="206.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(42642.25,title="206.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(42745.5625,title="206.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(42849,title="207",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(42952.5625,title="207.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(43056.25,title="207.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(43160.0625,title="207.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(43264,title="208",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(43368.0625,title="208.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(43472.25,title="208.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(43576.5625,title="208.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(43681,title="209",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(43785.5625,title="209.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(43890.25,title="209.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(43995.0625,title="209.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(44100,title="210",color=color.red, linestyle=hline.style_solid, linewidth=3, editable=false)
hline(44205.0625,title="210.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(44310.25,title="210.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(44415.5625,title="210.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(44521,title="211",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(44626.5625,title="211.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(44732.25,title="211.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(44838.0625,title="211.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(44944,title="212",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(45050.0625,title="212.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(45156.25,title="212.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(45262.5625,title="212.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(45369,title="213",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(45475.5625,title="213.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(45582.25,title="213.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(45689.0625,title="213.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(45796,title="214",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(45903.0625,title="214.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(46010.25,title="214.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(46117.5625,title="214.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(46225,title="215",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(46332.5625,title="215.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(46440.25,title="215.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(46548.0625,title="215.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(46656,title="216",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(46764.0625,title="216.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(46872.25,title="216.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(46980.5625,title="216.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(47089,title="217",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(47197.5625,title="217.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(47306.25,title="217.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(47415.0625,title="217.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(47524,title="218",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(47633.0625,title="218.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(47742.25,title="218.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(47851.5625,title="218.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(47961,title="219",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(48070.5625,title="219.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(48180.25,title="219.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(48290.0625,title="219.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(48400,title="220",color=color.red, linestyle=hline.style_solid, linewidth=3, editable=false)
hline(48510.0625,title="220.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(48620.25,title="220.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(48730.5625,title="220.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(48841,title="221",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(48951.5625,title="221.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(49062.25,title="221.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(49173.0625,title="221.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(49284,title="222",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(49395.0625,title="222.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(49506.25,title="222.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(49617.5625,title="222.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(49729,title="223",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(49840.5625,title="223.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(49952.25,title="223.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(50064.0625,title="223.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(50176,title="224",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(50288.0625,title="224.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(50400.25,title="224.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(50512.5625,title="224.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(50625,title="225",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(50737.5625,title="225.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(50850.25,title="225.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(50963.0625,title="225.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(51076,title="226",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(51189.0625,title="226.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(51302.25,title="226.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(51415.5625,title="226.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(51529,title="227",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(51642.5625,title="227.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(51756.25,title="227.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(51870.0625,title="227.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(51984,title="228",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(52098.0625,title="228.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(52212.25,title="228.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(52326.5625,title="228.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(52441,title="229",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(52555.5625,title="229.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(52670.25,title="229.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(52785.0625,title="229.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(52900,title="230",color=color.red, linestyle=hline.style_solid, linewidth=3, editable=false)
hline(53015.0625,title="230.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(53130.25,title="230.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(53245.5625,title="230.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(53361,title="231",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(53476.5625,title="231.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(53592.25,title="231.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(53708.0625,title="231.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(53824,title="232",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(53940.0625,title="232.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(54056.25,title="232.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(54172.5625,title="232.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(54289,title="233",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(54405.5625,title="233.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(54522.25,title="233.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(54639.0625,title="233.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(54756,title="234",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(54873.0625,title="234.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(54990.25,title="234.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(55107.5625,title="234.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(55225,title="235",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(55342.5625,title="235.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(55460.25,title="235.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(55578.0625,title="235.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(55696,title="236",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(55814.0625,title="236.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(55932.25,title="236.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(56050.5625,title="236.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(56169,title="237",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(56287.5625,title="237.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(56406.25,title="237.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(56525.0625,title="237.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(56644,title="238",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(56763.0625,title="238.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(56882.25,title="238.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(57001.5625,title="238.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(57121,title="239",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(57240.5625,title="239.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(57360.25,title="239.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(57480.0625,title="239.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(57600,title="240",color=color.red, linestyle=hline.style_solid, linewidth=3, editable=false)
hline(57720.0625,title="240.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(57840.25,title="240.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(57960.5625,title="240.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(58081,title="241",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(58201.5625,title="241.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(58322.25,title="241.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(58443.0625,title="241.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(58564,title="242",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(58685.0625,title="242.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(58806.25,title="242.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(58927.5625,title="242.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(59049,title="243",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(59170.5625,title="243.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(59292.25,title="243.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(59414.0625,title="243.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(59536,title="244",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(59658.0625,title="244.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(59780.25,title="244.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(59902.5625,title="244.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(60025,title="245",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(60147.5625,title="245.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(60270.25,title="245.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(60393.0625,title="245.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(60516,title="246",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(60639.0625,title="246.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(60762.25,title="246.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(60885.5625,title="246.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(61009,title="247",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(61132.5625,title="247.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(61256.25,title="247.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(61380.0625,title="247.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(61504,title="248",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(61628.0625,title="248.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(61752.25,title="248.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(61876.5625,title="248.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(62001,title="249",color=color.red, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(62125.5625,title="249.25",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(62250.25,title="249.5",color=color.fuchsia, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(62375.0625,title="249.75",color=color.blue, linestyle=hline.style_solid, linewidth=2, editable=false)
hline(62500,title="250",color=color.red, linestyle=hline.style_solid, linewidth=3, editable=false)
|
Bollinger Band + RSI + ADX + MACD + Heikinashi | https://www.tradingview.com/script/ezkXKevK-Bollinger-Band-RSI-ADX-MACD-Heikinashi/ | TradeUsingPivots | https://www.tradingview.com/u/TradeUsingPivots/ | 285 | 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/
// © abilash.s.90
dIMinusCalc(adxLen) =>
smoothedTrueRange = 0.0
smoothedDirectionalMovementMinus = 0.0
dIMinus = 0.0
trueRange = 0.0
directionalMovementMinus = 0.0
trueRange := max(max(high-low, abs(high-nz(close[1]))), abs(low-nz(close[1])))
directionalMovementMinus := nz(low[1])-low > high-nz(high[1]) ? max(nz(low[1])-low, 0): 0
smoothedTrueRange := nz(smoothedTrueRange[1]) - (nz(smoothedTrueRange[1])/adxLen) + trueRange
smoothedDirectionalMovementMinus := nz(smoothedDirectionalMovementMinus[1]) - (nz(smoothedDirectionalMovementMinus[1])/adxLen) + directionalMovementMinus
dIMinus := smoothedDirectionalMovementMinus / smoothedTrueRange * 100
dIMinus
dIPlusCalc(adxLen) =>
smoothedTrueRange = 0.0
smoothedDirectionalMovementPlus = 0.0
dIPlus = 0.0
trueRange = 0.0
directionalMovementPlus = 0.0
trueRange := max(max(high-low, abs(high-nz(close[1]))), abs(low-nz(close[1])))
directionalMovementPlus := high-nz(high[1]) > nz(low[1])-low ? max(high-nz(high[1]), 0): 0
smoothedTrueRange := nz(smoothedTrueRange[1]) - (nz(smoothedTrueRange[1])/adxLen) + trueRange
smoothedDirectionalMovementPlus := nz(smoothedDirectionalMovementPlus[1]) - (nz(smoothedDirectionalMovementPlus[1])/adxLen) + directionalMovementPlus
dIPlus := smoothedDirectionalMovementPlus / smoothedTrueRange * 100
dIPlus
Adx(adxLen) =>
dIPlus = 0.0
dIMinus = 0.0
dX = 0.0
aDX = 0.0
dIPlus := dIPlusCalc(adxLen)
dIMinus := dIMinusCalc(adxLen)
dX := abs(dIPlus-dIMinus) / (dIPlus+dIMinus)*100
aDX := sma(dX, adxLen)
aDX
BarInSession(sess) => time(timeframe.period, sess) != 0
//@version=4
strategy("Bollinger Band + RSI + ADX + MACD", overlay=true)
//Session
session = input(title="Trading Session", type=input.session, defval="0930-1500")
sessionColor = BarInSession(session) ? color.green : na
bgcolor(color=sessionColor, transp=95)
// Bollinger Bands
src = input(high, title="Bollinger Band Source", type=input.source)
length = input(3, minval=1, type=input.integer, title="Bollinger Band Length")
mult = input(4.989, minval=0.001, maxval=50, step=0.001, type=input.float, title="Bollinger Band Std Dev")
basis = sma(src, length)
dev = mult * stdev(src, length)
upper = basis + dev
lower = basis - dev
plot(upper, title="Bollinger Band Upper", color=color.red)
plot(lower, title="Bollinger Band Lower", color=color.green)
// RSI
rsiSrc = input(close, title="RSI Source", type=input.source)
rsiLength = input(16, minval=1, type=input.integer, title="RSI Length")
rsiComparator = input(39.2, title="RSI Comparator", type=input.float, step=0.1)
rsi = rsi(rsiSrc, rsiLength)
// ADX
adxLength = input(14, minval=1, type=input.integer, title="ADX Length")
adxComparator = input(14, minval=1, type=input.integer, title="ADX Comparator")
adx = Adx(adxLength)
// Heikinashi
haClose = security(heikinashi(syminfo.ticker), timeframe.period, close)
haOpen = security(heikinashi(syminfo.ticker), timeframe.period, open)
nextHaOpen = (haOpen + haClose) / 2
//MACD
macdCalcTypeProcessed = input(title="MACD Source", type=input.source, defval=high)
fast = input(12, title="MACD Fast")
slow = input(20, title="MACD Slow")
signalLen = input(15, title="MACD Signal")
fastMA = ema(macdCalcTypeProcessed, fast)
slowMA = ema(macdCalcTypeProcessed, slow)
macd = fastMA - slowMA
signal = sma(macd, signalLen)
longCondition() =>
(low < lower) and (rsi[0] > rsiComparator) and (adx > adxComparator) and (close > nextHaOpen) and BarInSession(session) and macd > signal
stop = (close - max((low - (low * 0.0022)), (close - (close * 0.0032)))) / syminfo.mintick
target = (max(upper, (close + (close * 0.0075))) - close) / syminfo.mintick
strategy.entry("SX,LE", strategy.long, when=longCondition(), comment="SX,LE")
strategy.close_all(when=(not BarInSession(session)))
strategy.exit("LX", from_entry="SX,LE", profit=target, loss=stop)
|
Simple MACD strategy | https://www.tradingview.com/script/yF94AKKh-Simple-MACD-strategy/ | Hurmun | https://www.tradingview.com/u/Hurmun/ | 96 | 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/
// © Hurmun
//@version=4
strategy("Simple MACD strategy ", overlay=true, margin_long=100, margin_short=100)
fast_length = input(title="Fast Length", type=input.integer, defval=12)
slow_length = input(title="Slow Length", type=input.integer, defval=26)
src = input(title="Source", type=input.source, defval=close)
signal_length = input(title="Signal Smoothing", type=input.integer, minval = 1, maxval = 50, defval = 9)
sma_source = input(title="Simple MA (Oscillator)", type=input.bool, defval=false)
sma_signal = input(title="Simple MA (Signal Line)", type=input.bool, defval=false)
// Plot colors
col_grow_above = #26A69A
col_grow_below = #FFCDD2
col_fall_above = #B2DFDB
col_fall_below = #EF5350
col_macd = #0094ff
col_signal = #ff6a00
// Calculating
fast_ma = sma_source ? sma(src, fast_length) : ema(src, fast_length)
slow_ma = sma_source ? sma(src, slow_length) : ema(src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal ? sma(macd, signal_length) : ema(macd, signal_length)
hist = macd - signal
movinga2 = input(title="movinga 2", type=input.integer, defval=200)
movinga200 = sma(close, movinga2)
plot(movinga200, "MA", color.orange)
longCondition = crossover(macd, signal) and macd < 0 and signal < 0 and close > movinga200
if (longCondition)
strategy.entry("My Long Entry Id", strategy.long)
shortCondition = crossunder(macd, signal) and macd > 0 and signal > 0 and close < movinga200
if (shortCondition)
strategy.entry("My Short Entry Id", strategy.short)
shortProfitPerc = input(title="Short Take Profit (%)", minval=0.0, step=0.1, defval=2) / 100
longProfitPerc = input(title="Long Take Profit (%)", minval=0.0, step=0.1, defval=2) / 100
stoploss = input(title="stoploss in %", minval = 0.0, step=1, defval=2) /100
longStoploss = strategy.position_avg_price * (1 - stoploss)
longExitPrice = strategy.position_avg_price * (1 + longProfitPerc)
shortExitPrice = strategy.position_avg_price * (1 - shortProfitPerc)
shortStoploss = strategy.position_avg_price * (1 + stoploss)
if (strategy.position_size > 0 )
strategy.exit(id="XL TP", limit=longExitPrice, stop=longStoploss)
if (strategy.position_size < 0 )
strategy.exit(id="XS TP", limit=shortExitPrice, stop=shortStoploss) |
Moving Average - Intraday | https://www.tradingview.com/script/VHagIA63-Moving-Average-Intraday/ | Pritesh-StocksDeveloper | https://www.tradingview.com/u/Pritesh-StocksDeveloper/ | 120 | 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/
// © Pritesh-StocksDeveloper
//@version=5
strategy("Moving Average - Intraday", shorttitle = "MA - Intraday",
overlay=true, calc_on_every_tick = true)
// Used for intraday handling
// Session value should be from market start to the time you want to square-off
// your intraday strategy
var i_marketSession = input.session(title="Market session",
defval="0915-1455", confirm=true)
// Short & Long moving avg. period
var int i_shortPeriod = input.int(title = "Short MA Period",
defval = 10, minval = 2, maxval = 20, confirm=true)
var int i_longPeriod = input.int(title = "Long MA Period",
defval = 40, minval = 3, maxval = 120, confirm=true)
// A function to check whether the bar is in intraday session
barInSession(sess) => time(timeframe.period, sess) != 0
// Calculate moving averages
shortAvg = ta.sma(close, i_shortPeriod)
longAvg = ta.sma(close, i_longPeriod)
// Plot moving averages
plot(series = shortAvg, color = color.red, title = "Short MA",
linewidth = 2)
plot(series = longAvg, color = color.blue, title = "Long MA",
linewidth = 2)
// Long/short condition
longCondition = ta.crossover(shortAvg, longAvg)
shortCondition = ta.crossunder(shortAvg, longAvg)
// See if intraday session is active
bool intradaySession = barInSession(i_marketSession)
// Trade only if intraday session is active
// Long position
strategy.entry(id = "Long", direction = strategy.long,
when = longCondition and intradaySession)
// Short position
strategy.entry(id = "Short", direction = strategy.short,
when = shortCondition and intradaySession)
// Square-off position (when session is over and position is open)
squareOff = (not intradaySession) and (strategy.position_size != 0)
strategy.close_all(when = squareOff, comment = "Square-off") |
Ichimoku Cloud Strategy Long Only [Bitduke] | https://www.tradingview.com/script/xJZp0Pm1-Ichimoku-Cloud-Strategy-Long-Only-Bitduke/ | Bitduke | https://www.tradingview.com/u/Bitduke/ | 290 | 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/
// Simple long-only Ichimoku Cloud Strategy
// Enter position when conversion line crosses base line up, and close it when the opposite happens.
// Additional condition for open / close the trade is lagging span, it should be higher than cloud to open position and below - to close it.
//@version=4
strategy("Ichimoku Cloud Strategy Long Only", shorttitle="Ichimoku Cloud Strategy (long only)", overlay=true, calc_on_every_tick=true,pyramiding=0, default_qty_type=strategy.cash,default_qty_value=1000, currency=currency.USD, initial_capital=1000,commission_type=strategy.commission.percent, commission_value=0.075)
conversion_length = input(9, minval=1, title="Conversion Line Periods"),
base_length = input(26, minval=1, title="Base Line Periods")
lagging_length = input(52, minval=1, title="Lagging Span 2 Periods"),
delta = input(26, minval=1, title="Delta")
average(len) => avg(lowest(len), highest(len))
conversion_line = average(conversion_length) // tenkan sen - trend
base_line = average(base_length) // kijun sen - movement
lead_line_a = avg(conversion_line, base_line) // senkou span A
lead_line_b = average(lagging_length) // senkou span B
lagging_span = close // chikou span - trend / move power
plot(conversion_line, color=color.blue, linewidth=2, title="Conversion Line")
plot(base_line, color=color.white, linewidth=2, title="Base Line")
plot(lagging_span, offset = -delta, color=color.purple, linewidth=2, title="Lagging Span")
lead_line_a_plot = plot(lead_line_a, offset = delta, color=color.green, title="Lead 1")
lead_line_b_plot = plot(lead_line_b, offset = delta, color=color.red, title="Lead 2")
fill(lead_line_a_plot, lead_line_b_plot, color = lead_line_a > lead_line_b ? color.green : color.red)
// Strategy logic
long_signal = crossover(conversion_line,base_line) and ((lagging_span) > (lead_line_a)) and ((lagging_span) > (lead_line_b))
short_signal = crossover(base_line, conversion_line) and ((lagging_span) < (lead_line_a)) and ((lagging_span) < (lead_line_b))
strategy.entry("LONG", strategy.long, when=strategy.opentrades == 0 and long_signal, alert_message='BUY')
strategy.close("LONG", when=strategy.opentrades > 0 and short_signal, alert_message='SELL')
// === Backtesting Dates === thanks to Trost
testPeriodSwitch = input(true, "Custom Backtesting Dates")
testStartYear = input(2021, "Backtest Start Year")
testStartMonth = input(1, "Backtest Start Month")
testStartDay = input(1, "Backtest Start Day")
testStartHour = input(0, "Backtest Start Hour")
testPeriodStart = timestamp(testStartYear, testStartMonth, testStartDay, testStartHour, 0)
testStopYear = input(2021, "Backtest Stop Year")
testStopMonth = input(12, "Backtest Stop Month")
testStopDay = input(1, "Backtest Stop Day")
testStopHour = input(0, "Backtest Stop Hour")
testPeriodStop = timestamp(testStopYear, testStopMonth, testStopDay, testStopHour, 0)
testPeriod() =>
time >= testPeriodStart and time <= testPeriodStop ? true : false
testPeriod_1 = testPeriod()
isPeriod = testPeriodSwitch == true ? testPeriod_1 : true
// === /END
if not isPeriod
strategy.cancel_all()
strategy.close_all() |
Atrend by OTS | https://www.tradingview.com/script/JA5PdXjR-Atrend-by-OTS/ | prim722 | https://www.tradingview.com/u/prim722/ | 42 | 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/
// © prim722
// © OTS Music
//@version=4
strategy("Atrend by OTS", overlay=true)
fastLength = input(12)
slowlength = input(26)
MACDLength = input(9)
MACD = ema(close, fastLength) - ema(close, slowlength)
aMACD = ema(MACD, MACDLength)
delta = MACD - aMACD
if (crossover(delta, 0))
strategy.entry("MACD buy", strategy.long, comment="MACD buy")
if (crossunder(delta, 0))
strategy.entry("MACD sell", strategy.short, comment="MACD sell")
//plot(strategy.equity, title="equity", color=color.red, linewidth=2, style=plot.style_areabr)
length = input( 18 )
overSold = input( 30 )
overBought = input( 70 )
price = close
vrsi = rsi(price, length)
co = crossover(vrsi, overSold)
cu = crossunder(vrsi, overBought)
if (not na(vrsi))
if (co)
strategy.entry("RSI buy", strategy.long, comment="RSI buy")
if (cu)
strategy.entry("RSI sell", strategy.short, comment="RSI sell")
//plot(strategy.equity, title="equity", color=color.red, linewidth=2, style=plot.style_areabr)
Periods = input(title="ATR Period", type=input.integer, defval=10)
src = input(hl2, title="Source")
Multiplier = input(title="ATR Multiplier", type=input.float, step=0.1, defval=3.0)
changeATR= input(title="Change ATR Calculation Method ?", type=input.bool, defval=true)
showsignals = input(title="Show Buy/Sell Signals ?", type=input.bool, defval=false)
highlighting = input(title="Highlighter On/Off ?", type=input.bool, defval=false)
atr2 = sma(tr, Periods)
atr= changeATR ? atr(Periods) : atr2
up=src-(Multiplier*atr)
up1 = nz(up[1],up)
up := close[1] > up1 ? max(up,up1) : up
dn=src+(Multiplier*atr)
dn1 = nz(dn[1], dn)
dn := close[1] < dn1 ? min(dn, dn1) : dn
trend = 1
trend := nz(trend[1], trend)
trend := trend == -1 and close > dn1 ? 1 : trend == 1 and close < up1 ? -1 : trend
upPlot = plot(trend == 1 ? up : na, title="Up Trend", style=plot.style_line, linewidth=2, color=color.white)
buySignal = trend == 1 and trend[1] == -1
plotshape(buySignal ? up : na, title="UpTrend Begins", location=location.absolute, style=shape.circle, size=size.tiny, color=color.green, transp=0)
plotshape(buySignal and showsignals ? up : na, title="", text="", location=location.absolute, style=shape.labelup, size=size.tiny, color=color.white, textcolor=color.white, transp=0)
dnPlot = plot(trend == 1 ? na : dn, title="Down Trend", style=plot.style_line, linewidth=2, color=color.gray)
sellSignal = trend == -1 and trend[1] == 1
plotshape(sellSignal ? dn : na, title="DownTrend Begins", location=location.absolute, style=shape.circle, size=size.tiny, color=color.red, transp=0)
plotshape(sellSignal and showsignals ? dn : na, title="", text="", location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.red, textcolor=color.white, transp=0)
mPlot = plot(ohlc4, title="", style=plot.style_circles, linewidth=0)
longFillColor = highlighting ? (trend == 1 ? color.white : color.white) : color.white
shortFillColor = highlighting ? (trend == -1 ? color.gray : color.white) : color.white
fill(mPlot, upPlot, title="UpTrend Highligter", color=longFillColor)
fill(mPlot, dnPlot, title="DownTrend Highligter", color=shortFillColor)
alertcondition(buySignal, title="ATrend Buy", message="ATrend Buy!")
alertcondition(sellSignal, title="ATrend Sell", message="ATrend Sell!")
changeCond = trend != trend[1]
alertcondition(changeCond, title="ATrend Direction Change", message="ATrend has changed direction!")
length1 = input(25, minval=1)
srcb = input(close, title="Source")
e1 = ema(srcb, length1)
e2 = ema(e1, length)
dema = 2 * e1 - e2
plot(dema, "DEMA", color.red) |
EMA_cumulativeVolume_crossover[Strategy V2] | https://www.tradingview.com/script/mUKDFKzn-EMA-cumulativeVolume-crossover-Strategy-V2/ | mohanee | https://www.tradingview.com/u/mohanee/ | 591 | 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/
// © mohanee
//@version=4
strategy("EMA_cumulativeVolume_crossover[Strategy]", overlay=true, pyramiding=5, default_qty_type=strategy.percent_of_equity, default_qty_value=20, initial_capital=10000)
emaLength= input(25, title="EMA Length", minval=1, maxval=200)
cumulativePeriod = input(100, title="cumulative volume Period", minval=1, maxval=200)
riskCapital = input(title="Risk % of capital", defval=10, minval=1)
stopLoss=input(8,title="Stop Loss",minval=1)
takePartialProfits=input(true, title="take partial profits (percentage same as stop loss)")
tradeDirection=input(title="Trade Direction", defval="LONG", options=["LONG", "SHORT"])
avgPrice = (high + low + close) / 3
avgPriceVolume = avgPrice * volume
cumulPriceVolume = sum(avgPriceVolume, cumulativePeriod)
cumulVolume = sum(volume, cumulativePeriod)
cumValue = cumulPriceVolume / cumulVolume
emaVal=ema(close, emaLength)
emaCumValue1=ema(cumValue, emaLength)
emaCumValue2=ema(cumValue, emaLength*2)
emaCumValueHistory=ema(cumValue[emaLength], emaLength)
//vwapVal1=vwap(hlc3)
rsiVal=rsi(close,5)
plotEma=plot(emaVal, title="EMA", color=color.green, transp=25)
//plot(vwapValue, title="Cumulate Volumne", color=color.orange, linewidth=2, transp=25)
//plot(vwapVal1, title="vwapVal1", color=color.purple, linewidth=1, transp=25)
plotCum=plot(emaCumValue1, title="emaVwapValue", color=color.purple, linewidth=2, transp=35)
plot(emaCumValue2, title="emaVwapValue", color=color.yellow, linewidth=3, transp=25)
fill(plotEma,plotCum, color=emaVal>emaCumValue1 ? color.lime : color.red, transp=35, title="ema and cum area")
plot(emaCumValueHistory, title="emaCumValueHistory", color=color.black, linewidth=2, transp=25)
//bgcolor(emaVal>vwapValue?color.blue:color.purple)
//Entry--
//Echeck how many units can be purchased based on risk manage ment and stop loss
qty1 = (strategy.equity * riskCapital / 100 ) / (close*stopLoss/100)
//check if cash is sufficient to buy qty1 , if capital not available use the available capital only
qty1:= (qty1 * close >= strategy.equity ) ? (strategy.equity / close) : qty1
//strategy.entry(id="LE",comment="LE", long=true, qty=qty1, when=crossover(emaVal, vwapValue) and (tradeDirection=="LONG") ) //emaVal>vwapValue and crossover(close , emaVal)
strategy.entry(id="LE",comment="LE", long=true, qty=qty1, when=strategy.position_size==0 and crossover(emaVal, emaCumValue1) and (tradeDirection=="LONG") ) //emaVal>vwapValue and crossover(close , emaVal)
//re-entry
rentryCondition1=strategy.position_size>1 and emaVal > emaCumValue1 and emaCumValue1>emaCumValue2 and crossover(close, emaCumValue2) and close>open and (tradeDirection=="LONG")
strategy.entry(id="LE",comment="LE RE", long=true, qty=qty1, when=rentryCondition1 )
rentryCondition2=strategy.position_size>1 and emaVal > emaCumValue1 and emaCumValue1>emaCumValueHistory and crossover(close, emaCumValueHistory) and close>open and (tradeDirection=="LONG")
//strategy.entry(id="LE",comment="LE RE", long=true, qty=qty1, when=rentryCondition2 )
//stoploss
stopLossVal= strategy.position_size>=1 ? (strategy.position_avg_price * (1-(stopLoss*0.01) )) : 0.00
//draw initil stop loss
//plot(strategy.position_size>=1 ? stopLossVal : na, color = color.purple , style=plot.style_linebr, linewidth = 2, title = "stop loss")
//partial exits
takeProfit= strategy.position_size>=1 ? (strategy.position_avg_price * (1+(1*0.01) )) : ( close[1] * 2 )
//if(takePartialProfits==true)
//strategy.close(id="LE", comment="Partial"+tostring(close-strategy.position_avg_price, "###.##") , qty=strategy.position_size/3 , when = (tradeDirection=="LONG" ) and close>takeProfit and crossunder(close, emaVal) ) //close<close[1] and close[1]<close[2] and close[2]<close[3])
strategy.close(id="LE", comment="PExit Points=>"+tostring(close-strategy.position_avg_price, "###.##") , qty=strategy.position_size/3 , when = (tradeDirection=="LONG" ) and takePartialProfits == true and close>=takeProfit and crossunder(rsiVal,90) )
profitVal= strategy.position_size>=1 ? (strategy.position_avg_price * (1+(1*0.01) )) : ( close[1] * 2 )
//strategy.close(id="LE" , comment="LE Exit Points="+tostring(close-strategy.position_avg_price, "###.##"), when=crossunder(emaVal, vwapValue) and (tradeDirection=="LONG") )
strategy.close(id="LE" , comment="Exit Points=>"+tostring(close-strategy.position_avg_price, "###.##"), when= crossunder(emaVal, emaCumValue1) and (tradeDirection=="LONG") )
strategy.close(id="LE" , comment="SL Exit Loss="+tostring(close-strategy.position_avg_price, "###.##"), when= close < stopLossVal and (tradeDirection=="LONG") )
//for short you dont have to wait crossodown of ema, falling is speed , so just check if close crossing down vwapVal
strategy.entry(id="SE",comment="SE", long=false, qty=qty1, when=crossunder(emaVal, emaCumValue1) and (tradeDirection=="SHORT") ) //emaVal>vwapValue and crossover(close , emaVal)
//stoploss
stopLossValUpside= abs(strategy.position_size)>=1 and tradeDirection=="SHORT" ? (strategy.position_avg_price * (1+(stopLoss*0.01) )) : 0.00
//draw initil stop loss
//plot(abs(strategy.position_size)>=1 and tradeDirection=="SHORT" ? stopLossValUpside : na, color = color.purple , style=plot.style_linebr, linewidth = 2, title = "stop loss")
//partial exits
shortTakeProfit= abs(strategy.position_size)>=1 and tradeDirection=="SHORT" ? (strategy.position_avg_price * (1-(stopLoss*0.01) )) : 0.00
if(takePartialProfits==true)
strategy.close(id="SE", comment="Partial" , qty=strategy.position_size/3 , when = (tradeDirection=="SHORT" ) and crossover(rsiVal,15) ) //close<takeProfit and (emaVal - close)>8 )
//strategy.close(id="SE" , comment="SE Exit Points="+tostring(close-strategy.position_avg_price, "###.##"), when=crossover(emaVal, vwapValue) and (tradeDirection=="SHORT") )
//strategy.close(id="SE" , comment="SE Exit Points="+tostring(close-strategy.position_avg_price, "###.##"), when= abs(strategy.position_size)>=1 and ( (emaVal<emaCumValue1 and close>emaCumValue1 and open>emaCumValue1 and close>open ) or (crossover(emaVal,emaCumValue1)) ) and (tradeDirection=="SHORT") )
//strategy.close(id="SE" , comment="SL Exit Loss="+tostring(close-strategy.position_avg_price, "###.##"), when= abs(strategy.position_size)>=1 and close > stopLossValUpside and (tradeDirection=="SHORT" ) )
strategy.close(id="SE" , comment="SL Exit Loss="+tostring(close-strategy.position_avg_price, "###.##"), when= abs(strategy.position_size)>=1 and crossover(emaVal, emaCumValue1) and (tradeDirection=="SHORT" ) )
|
Binomial Strategy | https://www.tradingview.com/script/xYEdNZmP-Binomial-Strategy/ | pieroliviermarquis | https://www.tradingview.com/u/pieroliviermarquis/ | 72 | 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/
// © pieroliviermarquis
//@version=4
strategy("Binomial Strategy", overlay=false, default_qty_type= strategy.percent_of_equity, default_qty_value= 100, slippage=1, initial_capital= 10000, calc_on_every_tick=true)
factorial(length) =>
n = 1
if length != 0
for i = 1 to length
n := n * i
n
binomial_pdf(success, trials, p) =>
q = 1-p
coef = factorial(trials) / (factorial(trials-success) * factorial(success))
pdf = coef * pow(p, success) * pow(q, trials-success)
binomial_cdf(success, trials, p) =>
q = 1-p
cdf = 0.0
for i = 0 to success
cdf := cdf + binomial_pdf(i, trials, p)
up = close[0] > close[1] ? 1 : 0
//long-term probabilities
lt_lookback = 100
lt_up_bars = sum(up, lt_lookback)
prob = lt_up_bars/lt_lookback
//lookback for cdf
lookback = 20
up_bars = sum(up, lookback)
cdf = binomial_cdf(up_bars, lookback, prob)
//ema on cdf
ema1 = ema(cdf, 10)
ema2 = ema(cdf, 20)
plot(cdf*100)
plot(ema1*100, color=color.red)
plot(ema2*100, color=color.orange)
buy = ema1 > ema2
sell = ema1 < ema2
//////////////////////Bar Colors//////////////////
var color buy_or_sell = na
if buy == true
buy_or_sell := #3BB3E4
else if sell == true
buy_or_sell := #FF006E
barcolor(buy_or_sell)
///////////////////////////Orders////////////////
if buy
strategy.entry("Long", strategy.long, comment="")
if sell
strategy.close("Long", comment="Sell")
|
Custom Date Buy/Sell Strategy | https://www.tradingview.com/script/7Ki6pZc8-Custom-Date-Buy-Sell-Strategy/ | tormunddookie | https://www.tradingview.com/u/tormunddookie/ | 75 | 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/
//@version=4
strategy("Custom Date Buy/Sell", overlay=true, currency=currency.USD, default_qty_value=1.0,initial_capital=30000.00,default_qty_type=strategy.percent_of_equity)
direction = input(defval='Long', options=['Long','Short'], title='Direction')
frommonth = input(defval = 6, minval = 01, maxval = 12, title = "From Month")
fromday = input(defval = 14, minval = 01, maxval = 31, title = "From day")
fromyear = input(defval = 2019, minval = 1900, maxval = 2100, title = "From Year")
tomonth = input(defval = 7, minval = 01, maxval = 12, title = "To Month")
today = input(defval = 15, minval = 01, maxval = 31, title = "To day")
toyear = input(defval = 2021, minval = 1900, maxval = 2100, title = "To Year")
if time == timestamp(fromyear, frommonth, fromday, 00, 00)
if direction == 'Long'
strategy.entry("Long", strategy.long)
else if direction == 'Short'
strategy.entry("Short", strategy.short)
if time == timestamp(toyear, tomonth, today, 00, 00)
strategy.close_all()
|
FXFUNDINGMATE TREND INDICATOR | https://www.tradingview.com/script/k0LMZo1H-FXFUNDINGMATE-TREND-INDICATOR/ | FXFUNDINGMATE | https://www.tradingview.com/u/FXFUNDINGMATE/ | 628 | 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/
// © FXFUNDINGMATE
//@version=4
strategy(title="FXFUNDINGMATE TREND INDICATOR", overlay=true)
//Ichimoku Cloud
conversionPeriods = input(9, minval=1, title="Conversion Line Length")
basePeriods = input(26, minval=1, title="Base Line Length")
laggingSpan2Periods = input(52, minval=1, title="Lagging Span 2 Length")
displacement = input(26, minval=1, title="Displacement")
donchian(len) => avg(lowest(len), highest(len))
conversionLine = donchian(conversionPeriods)
baseLine = donchian(basePeriods)
leadLine1 = avg(conversionLine, baseLine)[displacement - 1]
leadLine2 = donchian(laggingSpan2Periods)[displacement - 1]
//macd
fast_length = input(title="Fast Length", type=input.integer, defval=12)
slow_length = input(title="Slow Length", type=input.integer, defval=26)
src = input(title="Source", type=input.source, defval=close)
signal_length = input(title="Signal Smoothing", type=input.integer, minval = 1, maxval = 50, defval = 9)
sma_source = input(title="Simple MA (Oscillator)", type=input.bool, defval=false)
sma_signal = input(title="Simple MA (Signal Line)", type=input.bool, defval=false)
fast_ma = sma_source ? sma(src, fast_length) : ema(src, fast_length)
slow_ma = sma_source ? sma(src, slow_length) : ema(src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal ? sma(macd, signal_length) : ema(macd, signal_length)
hist = macd - signal
//kd
periodK = input(5, title="%K Length", minval=1)
smoothK = input(3, title="%K Smoothing", minval=1)
periodD = input(3, title="%D Smoothing", minval=1)
k = sma(stoch(close, high, low, periodK), smoothK)
d = sma(k, periodD)
//atr
atrlength = input(title="Atr Length", defval=8, minval=1)
SMulti = input(title="Stop loss multi Atr", defval=1.0)
TMulti = input(title="Take profit multi Atr", defval=1.0)
smoothing = input(title="Smoothing", defval="RMA", options=["RMA", "SMA", "EMA", "WMA"])
ma_function(source, length) =>
if smoothing == "RMA"
rma(source, length)
else
if smoothing == "SMA"
sma(source, length)
else
if smoothing == "EMA"
ema(source, length)
else
wma(source, length)
atr = ma_function(tr(true), atrlength)
operation_type = input(defval = "Both", title = "Position side", options = ["Long", "Short", "Both"])
operation = operation_type == "Long" ? 1 : operation_type == "Short" ? 2 : 3
showlines = input(true, title="Show sl&tp lines")
// MA
sma_len = input(100, title="MA Length", type=input.integer)
sma = sma(close, sma_len)
longCond = crossover(k, 20) and macd > 0 and close > sma and close > leadLine1 and close > leadLine2
shortCond = crossunder(k, 80) and macd < 0 and close < sma and close < leadLine1 and close < leadLine2
entry_price = float(0.0) //set float
entry_price := strategy.position_size != 0 or longCond or shortCond ? strategy.position_avg_price : entry_price[1]
entry_atr = valuewhen(longCond or shortCond, atr,0)
short_stop_level = float(0.0) //set float
short_profit_level = float(0.0) //set float
long_stop_level = float(0.0) //set float
long_profit_level = float(0.0) //set float
short_stop_level := entry_price + SMulti * entry_atr
short_profit_level := entry_price - TMulti * entry_atr
long_stop_level := entry_price - SMulti * entry_atr
long_profit_level := entry_price + TMulti * entry_atr
// Strategy Backtest Limiting Algorithm
i_startTime = input(defval = timestamp("1 Jan 2020 00:00 +0000"), title = "Backtesting Start Time", type = input.time)
i_endTime = input(defval = timestamp("31 Dec 2025 23:59 +0000"), title = "Backtesting End Time", type = input.time)
timeCond = (time > i_startTime) and (time < i_endTime)
if (operation == 1 or operation == 3)
strategy.entry("long" , strategy.long , when=longCond and timeCond, alert_message = "Long")
strategy.exit("SL/TP", from_entry = "long" , limit = long_profit_level , stop = long_stop_level , alert_message = "Long exit")
if (operation == 2 or operation == 3)
strategy.entry("short", strategy.short, when=shortCond and timeCond, alert_message="Short")
strategy.exit("SL/TP", from_entry = "short", limit = short_profit_level , stop = short_stop_level , alert_message = "Short exit")
if time > i_endTime
strategy.close_all(comment = "close all", alert_message = "close all")
plot(showlines and strategy.position_size <= 0 ? na : long_stop_level, color=color.red, style=plot.style_linebr, linewidth = 2)
plot(showlines and strategy.position_size <= 0 ? na : long_profit_level, color=color.lime, style=plot.style_linebr, linewidth = 2)
plot(showlines and strategy.position_size >= 0 ? na : short_stop_level, color=color.red, style=plot.style_linebr, linewidth = 2)
plot(showlines and strategy.position_size >= 0 ? na : short_profit_level, color=color.lime, style=plot.style_linebr, linewidth = 2)
//}
|
7-RSI strategy | https://www.tradingview.com/script/UVsO8cbm-7-rsi-strategy/ | rrolik66 | https://www.tradingview.com/u/rrolik66/ | 285 | 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/
// © rrolik66
//@version=4
strategy(title="7-RSI strategy", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=5, currency=currency.USD)
// inputs
src = input(close, "Source RSI", type = input.source)
bot_res = input(title="Bot period", type=input.resolution, defval="1")
srcin_bot = input(ohlc4, "Source Bot", type = input.source)
src_bot = security(syminfo.tickerid, bot_res, srcin_bot)
tradeDirection = input(title="Trade Direction", type=input.string,
options=["Long Bot", "Short Bot"], defval="Long Bot")
rsi1_res = input(title="RSI-1 period", type=input.resolution, defval="1", group="indicators")
rsi1_Len = input(14, minval=1, title="RSI-1 Length", group="indicators")
rsi2_res = input(title="RSI-2 period", type=input.resolution, defval="5", group="indicators")
rsi2_Len = input(14, minval=1, title="RSI-2 Length", group="indicators")
rsi3_res = input(title="RSI-3 period", type=input.resolution, defval="15", group="indicators")
rsi3_Len = input(14, minval=1, title="RSI-3 Length", group="indicators")
rsi4_res = input(title="RSI-4 period", type=input.resolution, defval="30", group="indicators")
rsi4_Len = input(14, minval=1, title="RSI-4 Length", group="indicators")
rsi5_res = input(title="RSI-5 period", type=input.resolution, defval="60", group="indicators")
rsi5_Len = input(14, minval=1, title="RSI-5 Length", group="indicators")
rsi6_res = input(title="RSI-6 period", type=input.resolution, defval="120", group="indicators")
rsi6_Len = input(14, minval=1, title="RSI-6 Length", group="indicators")
rsi7_res = input(title="RSI-7 period", type=input.resolution, defval="1D", group="indicators")
rsi7_Len = input(14, minval=1, title="RSI-7 Length", group="indicators")
longProfitPerc = input(title="Long Bot Take Profit (%)",
type=input.float, minval=0.0, step=0.05, defval=0.5, group="Long Bot") * 0.01
st_long_orders = input(title="Long Bot Step orders (%)",
type=input.float, minval=0.0, step=0.1, defval=2.0, group="Long Bot") * 0.01
rsi1_low = input(100, title="RSI-1 <", group="Long Bot")
rsi2_low = input(100, title="RSI-2 <", group="Long Bot")
rsi3_low = input(100, title="RSI-3 <", group="Long Bot")
rsi4_low = input(100, title="RSI-4 <", group="Long Bot")
rsi5_low = input(100, title="RSI-5 <", group="Long Bot")
rsi6_low = input(100, title="RSI-6 <", group="Long Bot")
rsi7_low = input(100, title="RSI-7 <", group="Long Bot")
shortProfitPerc = input(title="Short Bot Take Profit (%)",
type=input.float, minval=0.0, step=0.05, defval=0.5, group="Short Bot") * 0.01
st_short_orders = input(title="Short Bot Step orders (%)",
type=input.float, minval=0.0, step=0.1, defval=2.0, group="Short Bot") * 0.01
rsi1_up = input(0, title="RSI-1 >", group="Short Bot")
rsi2_up = input(0, title="RSI-2 >", group="Short Bot")
rsi3_up = input(0, title="RSI-3 >", group="Short Bot")
rsi4_up = input(0, title="RSI-4 >", group="Short Bot")
rsi5_up = input(0, title="RSI-5 >", group="Short Bot")
rsi6_up = input(0, title="RSI-6 >", group="Short Bot")
rsi7_up = input(0, title="RSI-7 >", group="Short Bot")
//indicators
rsi1 = rsi(src, rsi1_Len)
rsi1_sec = security(syminfo.tickerid, rsi1_res, rsi1)
rsi2 = rsi(src, rsi2_Len)
rsi2_sec = security(syminfo.tickerid, rsi2_res, rsi2)
rsi3 = rsi(src, rsi3_Len)
rsi3_sec = security(syminfo.tickerid, rsi3_res, rsi3)
rsi4 = rsi(src, rsi4_Len)
rsi4_sec = security(syminfo.tickerid, rsi4_res, rsi4)
rsi5 = rsi(src, rsi5_Len)
rsi5_sec = security(syminfo.tickerid, rsi5_res, rsi5)
rsi6 = rsi(src, rsi6_Len)
rsi6_sec = security(syminfo.tickerid, rsi6_res, rsi6)
rsi7 = rsi(src, rsi7_Len)
rsi7_sec = security(syminfo.tickerid, rsi7_res, rsi7)
//RSI
rsi1_up_signal = rsi1_sec > rsi1_up
rsi1_low_signal = rsi1_sec < rsi1_low
rsi2_up_signal = rsi2_sec > rsi2_up
rsi2_low_signal = rsi2_sec < rsi2_low
rsi3_up_signal = rsi3_sec > rsi3_up
rsi3_low_signal = rsi3_sec < rsi3_low
rsi4_up_signal = rsi4_sec > rsi4_up
rsi4_low_signal = rsi4_sec < rsi4_low
rsi5_up_signal = rsi5_sec > rsi5_up
rsi5_low_signal = rsi5_sec < rsi5_low
rsi6_up_signal = rsi6_sec > rsi6_up
rsi6_low_signal = rsi6_sec < rsi6_low
rsi7_up_signal = rsi7_sec > rsi7_up
rsi7_low_signal = rsi7_sec < rsi7_low
//Buy & Sell
Buy = rsi1_low_signal and rsi2_low_signal and rsi3_low_signal and rsi4_low_signal and rsi5_low_signal and rsi6_low_signal and rsi7_low_signal
Sell = rsi1_up_signal and rsi2_up_signal and rsi3_up_signal and rsi4_up_signal and rsi5_up_signal and rsi6_up_signal and rsi7_up_signal
// input into trading conditions
longOK = (tradeDirection == "Long Bot")
shortOK = (tradeDirection == "Short Bot")
// in entry orders price
longEntryPrice1 = src_bot * (1 - (st_long_orders))
longEntryPrice2 = src_bot * (1 - (st_long_orders*2))
longEntryPrice3 = src_bot * (1 - (st_long_orders*3))
longEntryPrice4 = src_bot * (1 - (st_long_orders*4))
longEntryPrice5 = src_bot * (1 - (st_long_orders*5))
longEntryPrice6 = src_bot * (1 - (st_long_orders*6))
longEntryPrice7 = src_bot * (1 - (st_long_orders*7))
longEntryPrice8 = src_bot * (1 - (st_long_orders*8))
longEntryPrice9 = src_bot * (1 - (st_long_orders*9))
longEntryPrice10 = src_bot * (1 - (st_long_orders*10))
longEntryPrice11 = src_bot * (1 - (st_long_orders*11))
longEntryPrice12 = src_bot * (1 - (st_long_orders*12))
longEntryPrice13 = src_bot * (1 - (st_long_orders*13))
longEntryPrice14 = src_bot * (1 - (st_long_orders*14))
longEntryPrice15 = src_bot * (1 - (st_long_orders*15))
longEntryPrice16 = src_bot * (1 - (st_long_orders*16))
longEntryPrice17 = src_bot * (1 - (st_long_orders*17))
longEntryPrice18 = src_bot * (1 - (st_long_orders*18))
longEntryPrice19 = src_bot * (1 - (st_long_orders*19))
shortEntryPrice1 = src_bot * (1 + st_short_orders)
shortEntryPrice2 = src_bot * (1 + (st_short_orders*2))
shortEntryPrice3 = src_bot * (1 + (st_short_orders*3))
shortEntryPrice4 = src_bot * (1 + (st_short_orders*4))
shortEntryPrice5 = src_bot * (1 + (st_short_orders*5))
shortEntryPrice6 = src_bot * (1 + (st_short_orders*6))
shortEntryPrice7 = src_bot * (1 + (st_short_orders*7))
shortEntryPrice8 = src_bot * (1 + (st_short_orders*8))
shortEntryPrice9 = src_bot * (1 + (st_short_orders*9))
shortEntryPrice10 = src_bot * (1 + (st_short_orders*10))
shortEntryPrice11 = src_bot * (1 + (st_short_orders*11))
shortEntryPrice12 = src_bot * (1 + (st_short_orders*12))
shortEntryPrice13 = src_bot * (1 + (st_short_orders*13))
shortEntryPrice14 = src_bot * (1 + (st_short_orders*14))
shortEntryPrice15 = src_bot * (1 + (st_short_orders*15))
shortEntryPrice16 = src_bot * (1 + (st_short_orders*16))
shortEntryPrice17 = src_bot * (1 + (st_short_orders*17))
shortEntryPrice18 = src_bot * (1 + (st_short_orders*18))
shortEntryPrice19 = src_bot * (1 + (st_short_orders*19))
// take profit price
longExitPrice = strategy.position_avg_price * (1 + longProfitPerc)
shortExitPrice = strategy.position_avg_price * (1 - shortProfitPerc)
// take profit values for confirmation
plot(series=(strategy.position_size > 0) ? longExitPrice : na,
color=color.green, style=plot.style_circles,
linewidth=3, title="Long Take Profit")
plot(series=(strategy.position_size < 0) ? shortExitPrice : na,
color=color.red, style=plot.style_circles,
linewidth=3, title="Short Take Profit")
// entry orders
if (strategy.position_size == 0)
strategy.order(id="Long0", long=true, limit=src_bot, when=longOK and Buy)
strategy.order(id="Long1", long=true, limit=longEntryPrice1, when=longOK and Buy)
strategy.order(id="Long2", long=true, limit=longEntryPrice2, when=longOK and Buy)
strategy.order(id="Long3", long=true, limit=longEntryPrice3, when=longOK and Buy)
strategy.order(id="Long4", long=true, limit=longEntryPrice4, when=longOK and Buy)
strategy.order(id="Long5", long=true, limit=longEntryPrice5, when=longOK and Buy)
strategy.order(id="Long6", long=true, limit=longEntryPrice6, when=longOK and Buy)
strategy.order(id="Long7", long=true, limit=longEntryPrice7, when=longOK and Buy)
strategy.order(id="Long8", long=true, limit=longEntryPrice8, when=longOK and Buy)
strategy.order(id="Long9", long=true, limit=longEntryPrice9, when=longOK and Buy)
strategy.order(id="Long10", long=true, limit=longEntryPrice10, when=longOK and Buy)
strategy.order(id="Long11", long=true, limit=longEntryPrice11, when=longOK and Buy)
strategy.order(id="Long12", long=true, limit=longEntryPrice12, when=longOK and Buy)
strategy.order(id="Long13", long=true, limit=longEntryPrice13, when=longOK and Buy)
strategy.order(id="Long14", long=true, limit=longEntryPrice14, when=longOK and Buy)
strategy.order(id="Long15", long=true, limit=longEntryPrice15, when=longOK and Buy)
strategy.order(id="Long16", long=true, limit=longEntryPrice16, when=longOK and Buy)
strategy.order(id="Long17", long=true, limit=longEntryPrice17, when=longOK and Buy)
strategy.order(id="Long18", long=true, limit=longEntryPrice18, when=longOK and Buy)
strategy.order(id="Long19", long=true, limit=longEntryPrice19, when=longOK and Buy)
if (strategy.position_size == 0)
strategy.order(id="Short0", long=false, limit=src_bot, when=shortOK and Sell)
strategy.order(id="Short1", long=false, limit=shortEntryPrice1, when=shortOK and Sell)
strategy.order(id="Short2", long=false, limit=shortEntryPrice2, when=shortOK and Sell)
strategy.order(id="Short3", long=false, limit=shortEntryPrice3, when=shortOK and Sell)
strategy.order(id="Short4", long=false, limit=shortEntryPrice4, when=shortOK and Sell)
strategy.order(id="Short5", long=false, limit=shortEntryPrice5, when=shortOK and Sell)
strategy.order(id="Short6", long=false, limit=shortEntryPrice6, when=shortOK and Sell)
strategy.order(id="Short7", long=false, limit=shortEntryPrice7, when=shortOK and Sell)
strategy.order(id="Short8", long=false, limit=shortEntryPrice8, when=shortOK and Sell)
strategy.order(id="Short9", long=false, limit=shortEntryPrice9, when=shortOK and Sell)
strategy.order(id="Short10", long=false, limit=shortEntryPrice10, when=shortOK and Sell)
strategy.order(id="Short11", long=false, limit=shortEntryPrice11, when=shortOK and Sell)
strategy.order(id="Short12", long=false, limit=shortEntryPrice12, when=shortOK and Sell)
strategy.order(id="Short13", long=false, limit=shortEntryPrice13, when=shortOK and Sell)
strategy.order(id="Short14", long=false, limit=shortEntryPrice14, when=shortOK and Sell)
strategy.order(id="Short15", long=false, limit=shortEntryPrice15, when=shortOK and Sell)
strategy.order(id="Short16", long=false, limit=shortEntryPrice16, when=shortOK and Sell)
strategy.order(id="Short17", long=false, limit=shortEntryPrice17, when=shortOK and Sell)
strategy.order(id="Short18", long=false, limit=shortEntryPrice18, when=shortOK and Sell)
strategy.order(id="Short19", long=false, limit=shortEntryPrice19, when=shortOK and Sell)
// exit position based on take profit price
if (strategy.position_size > 0)
strategy.order(id="exit_Long", long=false, limit=longExitPrice, qty=strategy.position_size)
if (strategy.position_size < 0)
strategy.order(id="exit_Short", long=true, limit=shortExitPrice, qty=abs(strategy.position_size))
|
Three (3)-Bar and Four (4)-Bar Plays Strategy | https://www.tradingview.com/script/xO3hDxjU-Three-3-Bar-and-Four-4-Bar-Plays-Strategy/ | tormunddookie | https://www.tradingview.com/u/tormunddookie/ | 67 | 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/
//Adopted from JRL_6 -- https://www.tradingview.com/script/2IhYFRpf-3-Bar-and-4-Bar-Plays/
//@version=4
strategy(title="Three (3)-Bar and Four (4)-Bar Plays Strategy", shorttitle="Three (3)-Bar and Four (4)-Bar Plays Strategy", overlay=true, calc_on_every_tick=true, currency=currency.USD, default_qty_value=1.0,initial_capital=30000.00,default_qty_type=strategy.percent_of_equity)
frommonth = input(defval = 1, minval = 01, maxval = 12, title = "From Month")
fromday = input(defval = 1, minval = 01, maxval = 31, title = "From day")
fromyear = input(defval = 2021, minval = 1900, maxval = 2100, title = "From Year")
tomonth = input(defval = 12, minval = 01, maxval = 12, title = "To Month")
today = input(defval = 31, minval = 01, maxval = 31, title = "To day")
toyear = input(defval = 2100, minval = 1900, maxval = 2100, title = "To Year")
garBarSetting1 = input(defval = 1.5, minval = 0.0, maxval = 100.0, title = "Gap Bar Size", type = input.float)
garBarSetting2 = input(defval = 0.70, minval = 0.0, maxval = 100.0, title = "Gap Bar Body Size", type = input.float)
TopSetting = input(defval = 0.10, minval = 0.0, maxval = 100.0, title = "Bull Top Bar Size", type = input.float)
profitMultiplier = input(defval = 2.0, minval = 1.0, maxval = 100.0, title = "Profit Multiplier", type = input.float)
// Plot Donchian Channel
showDonchian = input(title="Show Donchian Channel?", type=input.bool, defval=true)
lookbackLen = input(30, minval=1, title="No. of Bars to look back for breakout")
donchianOffset = input(1, minval=1, title="Offset of Donchian Channel") // offsetting by at least 1 bar allows the price to break the channel
highestHighs = highest(high, lookbackLen)[donchianOffset]
lowestLows = lowest(low, lookbackLen)[donchianOffset]
plotHigh = if showDonchian
highestHighs
else
na
plotLow = if showDonchian
lowestLows
else
na
plot(plotHigh, title="Resistance", color=color.yellow, linewidth=1, transp=0)
plot(plotLow, title="Support", color=color.orange, linewidth=1, transp=0)
// ========== 3-Bar and 4-Bar Play Setup ==========
barSize = abs(high - low)
bodySize = abs(open - close)
gapBar = (barSize > (atr(1000) * garBarSetting1)) and (bodySize >= (barSize * garBarSetting2)) // find a wide ranging bar that is more than 2.5x the size of the average bar size and body is at least 65% of bar size
breakoutAbove = close > highestHighs // look for breakout above Resistance
breakoutBelow = close < lowestLows // look for breakout below Support
bullTop = close > close[1] + barSize[1] * TopSetting ? false : true // check if top of bar is relatively equal to top of the gap bar (first collecting bull bar)
bullTop2 = close > close[2] + barSize[2] * TopSetting ? false : true // check if top of bar is relatively equal to top of the gap bar (second collecting bull bar)
bearTop = close < close[1] - barSize[1] * TopSetting ? false : true // check if top of bar is relatively equal to top of the gap bar (second collecting bear bar)
bearTop2 = close < close[2] - barSize[2] * TopSetting ? false : true // check if top of bar is relatively equal to top of the gap bar (second collecting bear bar)
collectingBarBull = barSize < barSize[1] / 2 and low > close[1] - barSize[1] / 2 and bullTop // find a collecting bull bar
collectingBarBear = barSize < barSize[1] / 2 and high < close[1] + barSize[1] / 2 and bearTop // find a collecting bear bar
collectingBarBull2 = barSize < barSize[2] / 2 and low > close[2] - barSize[2] / 2 and bullTop2 // find a second collecting bull bar
collectingBarBear2 = barSize < barSize[2] / 2 and high < close[2] + barSize[2] / 2 and bearTop2 // find a second collecting bear bar
triggerThreeBarBull = close > close[1] and close > close[2] and high > high[1] and high > high[2] // find a bull trigger bar in a 3 bar play
triggerThreeBarBear = close < close[1] and close < close[2] and high < high[1] and high < high[2] // find a bear trigger bar in a 3 bar play
triggerFourBarBull = close > close[1] and close > close[2] and close > close[3] and high > high[1] and high > high[2] and high > high[3] // find a bull trigger bar in a 4 bar play
triggerFourBarBear = close < close[1] and close < close[2] and close < close[3] and high < high[1] and high < high[2] and high < high[3] // find a bear trigger bar in a 4 bar play
threeBarSetupBull = gapBar[2] and breakoutAbove[2] and collectingBarBull[1] and triggerThreeBarBull // find 3-bar Bull Setup
threeBarSetupBear = gapBar[2] and breakoutBelow[2] and collectingBarBear[1] and triggerThreeBarBear // find 3-bar Bear Setup
fourBarSetupBull = gapBar[3] and breakoutAbove[3] and collectingBarBull[2] and collectingBarBull2[1] and triggerFourBarBull // find 4-bar Bull Setup
fourBarSetupBear = gapBar[3] and breakoutBelow[3] and collectingBarBear[2] and collectingBarBear2[1] and triggerFourBarBear // find 4-bar Bear Setup
labels = input(title="Show Buy/Sell Labels?", type=input.bool, defval=true)
plotshape(threeBarSetupBull and labels, title="3-Bar Bull", text="3-Bar Play", location=location.abovebar, style=shape.labeldown, size=size.tiny, color=color.green, textcolor=color.white, transp=0)
plotshape(threeBarSetupBear and labels, text="3-Bar Bear", title="3-Bar Play", location=location.belowbar, style=shape.labelup, size=size.tiny, color=color.red, textcolor=color.white, transp=0)
plotshape(fourBarSetupBull and labels, title="4-Bar Bull", text="4-Bar Play", location=location.abovebar, style=shape.labeldown, size=size.tiny, color=color.green, textcolor=color.white, transp=0)
plotshape(fourBarSetupBear and labels, text="4-Bar Bear", title="4-Bar Play", location=location.belowbar, style=shape.labelup, size=size.tiny, color=color.red, textcolor=color.white, transp=0)
alertcondition(threeBarSetupBull or threeBarSetupBear or fourBarSetupBull or fourBarSetupBear, title="Potential 3-bar or 4-bar Play", message="Potential 3-bar or 4-bar Play")
float sl = na
float tp = na
sl := nz(sl[1], 0.0)
tp := nz(tp[1], 0.0)
plot(sl==0.0?na:sl,title='SL', color = color.red)
plot(tp==0.0?na:tp,title='TP', color = color.green)
if (time > timestamp(fromyear, frommonth, fromday, 00, 00) and time < timestamp(toyear, tomonth, today, 00, 00))
if threeBarSetupBull and strategy.position_size <=0
strategy.entry("3 Bar Long", strategy.long, when=threeBarSetupBull)
sl :=low[1]
if threeBarSetupBear and strategy.position_size >=0
strategy.entry("3 Bar Short", strategy.short, when=threeBarSetupBull)
sl :=high[1]
if fourBarSetupBull and strategy.position_size <=0
strategy.entry("4 Bar Long", strategy.long, when=fourBarSetupBull)
sl :=min(low[1], low[2])
if fourBarSetupBear and strategy.position_size >=0
strategy.entry("4 Bar Short", strategy.short, when=fourBarSetupBear)
sl :=max(high[1], high[2])
if sl !=0.0
if strategy.position_size > 0
tp := strategy.position_avg_price + ((strategy.position_avg_price - sl) * profitMultiplier)
strategy.exit(id="Exit", limit=tp, stop=sl)
if strategy.position_size < 0
tp := strategy.position_avg_price - ((sl - strategy.position_avg_price) * profitMultiplier)
strategy.exit(id="Exit", limit=tp, stop=sl) |
Forex bot full strategy with risk management | https://www.tradingview.com/script/U0AU6PJx-Forex-bot-full-strategy-with-risk-management/ | exlux99 | https://www.tradingview.com/u/exlux99/ | 301 | 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/
// © exlux99
//@version=4
strategy("Scalping FOrex full strategy with risk management",overlay=true,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.cash_per_contract ,commission_value=0.00005)
//VOLUME o
shortlen = input(1, minval=1, title = "Short Length OBV")
longlen = input(8, minval=1, title = "Long Length OBV")
upColor = #2196F3//input(#2196F3, "Color Up")
dnColor = #6B1599//input(#6B1599, "Color Down")
f_normGradientColor(_series, _crossesZero, _colorNormLen, _dnColor, _upColor) =>
_dnValue = _crossesZero?-100:0
_mult = 0.0
_lowest = lowest(_colorNormLen)
_highest = highest(_colorNormLen)
_diff1 = close - _lowest
_diff2 = _highest - _lowest
if _diff2 > 0
_mult := _diff1 / _diff2 * 100
color.from_gradient(sign(_series) * _mult, _dnValue, 100, _dnColor, _upColor)
shorta = ema(volume, shortlen)
longa = ema(volume, longlen)
osc = 100 * (shorta - longa) / longa
start = input(0.1, title="PSAR START")
increment = input(0.05,title="PSAR INC")
maximum = input(0.3, title="PSAR MAX")
// multitp=input(1)
// multisl=input(1)
var bool uptrend = na
var float EP = na
var float SAR = na
var float AF = start
var float nextBarSAR = na
if bar_index > 0
firstTrendBar = false
SAR := nextBarSAR
if bar_index == 1
float prevSAR = na
float prevEP = na
lowPrev = low[1]
highPrev = high[1]
closeCur = close
closePrev = close[1]
if closeCur > closePrev
uptrend := true
EP := high
prevSAR := lowPrev
prevEP := high
else
uptrend := false
EP := low
prevSAR := highPrev
prevEP := low
firstTrendBar := true
SAR := prevSAR + start * (prevEP - prevSAR)
if uptrend
if SAR > low
firstTrendBar := true
uptrend := false
SAR := max(EP, high)
EP := low
AF := start
else
if SAR < high
firstTrendBar := true
uptrend := true
SAR := min(EP, low)
EP := high
AF := start
if not firstTrendBar
if uptrend
if high > EP
EP := high
AF := min(AF + increment, maximum)
else
if low < EP
EP := low
AF := min(AF + increment, maximum)
if uptrend
SAR := min(SAR, low[1])
if bar_index > 1
SAR := min(SAR, low[2])
else
SAR := max(SAR, high[1])
if bar_index > 1
SAR := max(SAR, high[2])
nextBarSAR := SAR + AF * (EP - SAR)
// if barstate.isconfirmed
// if uptrend
// strategy.entry("ParSE", strategy.short, stop=nextBarSAR, comment="ParSE")
// strategy.cancel("ParLE")
// else
// strategy.entry("ParLE", strategy.long, stop=nextBarSAR, comment="ParLE")
// strategy.cancel("ParSE")
//plot(SAR, style=plot.style_cross, linewidth=3, color=color.orange)
psarshort = close- SAR
psarlong= SAR-close
lena = input(200, minval=1, title="Length EMA")
srca = input(close, title="Source")
out = ema(srca, lena)
fast_length = input(title="Fast Length MACD", type=input.integer, defval=12)
slow_length = input(title="Slow Length MACD", type=input.integer, defval=25)
src = input(title="Source", type=input.source, defval=close)
signal_length = input(title="Signal Smoothing MACD", type=input.integer, minval = 1, maxval = 50, defval = 9)
sma_source = input(title="Simple MA (Oscillator)", type=input.bool, defval=true)
sma_signal = input(title="Simple MA (Signal Line)", type=input.bool, defval=true)
// Calculating
fast_ma = sma_source ? sma(src, fast_length) : ema(src, fast_length)
slow_ma = sma_source ? sma(src, slow_length) : ema(src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal ? sma(macd, signal_length) : ema(macd, signal_length)
hist = macd - signal
long = hist[1]<0 and hist > 0 and close > out and uptrend and osc < 0
short = hist[1]>0 and hist< 0 and close < out and not uptrend and osc >0
// ------------------------- Strategy Logic --------------------------------- //
var longOpeneds = false
var shortOpeneds = false
var int timeOfBuys = na
var float tpLong = na
var float slLong = na
var int entrys = na
longConditions = long and not longOpeneds and entrys<100
if longConditions
longOpeneds := true
timeOfBuys := time
tpLong := close+ (psarshort) //* multitp)
slLong := close- (psarshort)//*multisl)
entrys:=entrys+1
tpLongTrigger = (longOpeneds[1] and (crossover(close, tpLong) or crossover( high,tpLong)))
slLongTrigger = (longOpeneds[1] and (crossunder(close, slLong) or crossunder( low,slLong)))
longExitSignals = slLongTrigger or tpLongTrigger or short
exitLongConditions = longOpeneds[1] and longExitSignals
if exitLongConditions
longOpeneds := false
timeOfBuys := na
tpLong := na
slLong := na
if(short)
entrys:=0
//short
// ------------------------- Strategy Logic --------------------------------- //
var longOpenedss = false
// var shortOpeneds = false
var int timeOfBuyss = na
var float tpLongs = na
var float slLongs = na
var int entry = na
longConditionss = short and not longOpenedss and entry<100
if longConditionss
longOpenedss := true
timeOfBuyss := time
tpLongs := close- (psarlong)//*multitp )
slLongs := close+ (psarlong)//*multisl)
entry:=1
tpLongTriggers = (longOpenedss[1] and ( crossunder(close, tpLongs) or crossunder( low,tpLongs)))
slLongTriggers = (longOpenedss[1] and (crossover(close, slLongs) or crossover( high,slLongs)))
longExitSignalss = slLongTriggers or tpLongTriggers or long
exitLongConditionss = longOpenedss[1] and longExitSignalss
if exitLongConditionss
longOpenedss := false
timeOfBuyss := na
tpLongs := na
slLongs := na
if(long)
entry:=0
longEntry=input(true)
shortEntry=input(true)
if(longEntry)
strategy.entry("long",1,when=longConditions)
strategy.close('long',when=exitLongConditions)
if(shortEntry)
strategy.entry("short",0,when=longConditionss)
strategy.close("short",when=exitLongConditionss)
|
VWMA with kNN Machine Learning: MFI/ADX | https://www.tradingview.com/script/73oLZ8IM-VWMA-with-kNN-Machine-Learning-MFI-ADX/ | lastguru | https://www.tradingview.com/u/lastguru/ | 638 | 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/
// © lastguru
//@version=4
strategy(title="VWMA with kNN Machine Learning: MFI/ADX by lastguru", shorttitle="VWMA + kNN: MFI/ADX", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100)
/////////
// kNN //
/////////
// Define storage arrays for: parameter 1, parameter 2, price, result (up = 1; down = -1)
var knn1 = array.new_float(1, 0)
var knn2 = array.new_float(1, 0)
var knnp = array.new_float(1, 0)
var knnr = array.new_float(1, 0)
// Store the previous trade; buffer the current one until results are in
_knnStore (p1, p2, src) =>
var prevp1 = 0.0
var prevp2 = 0.0
var prevsrc = 0.0
array.push(knn1, prevp1)
array.push(knn2, prevp2)
array.push(knnp, prevsrc)
array.push(knnr, src >= prevsrc ? 1 : -1)
prevp1 := p1
prevp2 := p2
prevsrc := src
// Get neighbours by getting k smallest distances from the distance array, and then getting all results with these distances
_knnGet(arr1, arr2, k) =>
sarr = array.copy(arr1)
array.sort(sarr)
ss = array.slice(sarr, 0, min(k, array.size(sarr)))
m = array.max(ss)
out = array.new_float(0)
for i = 0 to array.size(arr1) - 1
if (array.get(arr1, i) <= m)
array.push(out, array.get(arr2, i))
out
// Create a distance array from the two given parameters
_knnDistance(p1, p2) =>
dist = array.new_float(0)
n = array.size(knn1) - 1
for i = 0 to n
d = sqrt( pow(p1 - array.get(knn1, i), 2) + pow(p2 - array.get(knn2, i), 2) )
array.push(dist, d)
dist
// Make a prediction, finding k nearest neighbours
_knn(p1, p2, k) =>
slice = _knnGet(_knnDistance(p1, p2), array.copy(knnr), k)
knn = array.sum(slice)
////////////
// Inputs //
////////////
SRC = input(title="Source", type=input.source, defval=open)
FAST = input(title="Fast Length", type=input.integer, defval=13)
SLOW = input(title="Slow Length", type=input.integer, defval=19)
APPLY = input(title = "Apply kNN filter", defval=true)
FILTER = input(title="Filter Length", type=input.integer, defval=13)
SMOOTH = input(title="Filter Smoothing", type=input.integer, defval=6)
// When DIST is 0, KNN default was 23
KNN = input(title="kNN nearest neighbors (k)", type=input.integer, defval=45)
DIST = input(title="kNN minimum difference", type=input.integer, defval=2)
BACKGROUND = input(title = "Draw background", defval=false)
////////
// MA //
////////
fastMA = vwma(SRC, FAST)
slowMA = vwma(SRC, SLOW)
/////////
// DMI //
/////////
// Wilder's Smoothing (Running Moving Average)
_rma(src, length) =>
out = 0.0
out := ((length - 1) * nz(out[1]) + src) / length
// DMI (Directional Movement Index)
_dmi (len, smooth) =>
up = change(high)
down = -change(low)
plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
trur = _rma(tr, len)
plus = fixnan(100 * _rma(plusDM, len) / trur)
minus = fixnan(100 * _rma(minusDM, len) / trur)
sum = plus + minus
adx = 100 * _rma(abs(plus - minus) / (sum == 0 ? 1 : sum), smooth)
[plus, minus, adx]
[diplus, diminus, adx] = _dmi(FILTER, SMOOTH)
/////////
// MFI //
/////////
// common RSI function
_rsi(upper, lower) =>
if lower == 0
100
if upper == 0
0
100.0 - (100.0 / (1.0 + upper / lower))
mfiUp = sum(volume * (change(ohlc4) <= 0 ? 0 : ohlc4), FILTER)
mfiDown = sum(volume * (change(ohlc4) >= 0 ? 0 : ohlc4), FILTER)
mfi = _rsi(mfiUp, mfiDown)
////////////
// Filter //
////////////
longCondition = crossover(fastMA, slowMA)
shortCondition = crossunder(fastMA, slowMA)
if (longCondition or shortCondition)
_knnStore(adx, mfi, SRC)
filter = _knn(adx, mfi, KNN)
/////////////
// Actions //
/////////////
bgcolor(BACKGROUND ? filter >= 0 ? color.green : color.red : na)
plot(fastMA, color=color.red)
plot(slowMA, color=color.green)
if (longCondition and (not APPLY or filter >= DIST))
strategy.entry("Long", strategy.long)
if (shortCondition and (not APPLY or filter <= -DIST))
strategy.entry("Short", strategy.short) |
Ichimoku Cloud Strategy Idea | https://www.tradingview.com/script/VRDSoZdu-Ichimoku-Cloud-Strategy-Idea/ | QuantCT | https://www.tradingview.com/u/QuantCT/ | 194 | 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/
// © QuantCT
//@version=4
strategy("Ichimoku Cloud Strategy Idea",
shorttitle="Ichimoku",
overlay=true,
pyramiding=0,
default_qty_type=strategy.percent_of_equity,
default_qty_value=99,
initial_capital=1000,
commission_type=strategy.commission.percent,
commission_value=0.1)
// ____ Inputs
conversion_period = input(9, minval=1, title="Conversion Line Period")
base_period = input(26, minval=1, title="Base Line Period")
lagging_span2_period = input(52, minval=1, title="Lagging Span 2 Period")
displacement = input(26, minval=1, title="Displacement")
long_only = input(title="Long Only", defval=false)
slp = input(title="Stop-loss (%)", minval=1.0, maxval=25.0, defval=5.0)
use_sl = input(title="Use Stop-Loss", defval=false)
// ____ Logic
donchian(len) => avg(lowest(len), highest(len))
conversion_line = donchian(conversion_period)
base_line = donchian(base_period)
lead_line1 = avg(conversion_line, base_line)
lead_line2 = donchian(lagging_span2_period)
chikou = close
chikou_free_long = close > high[displacement] and close > max(lead_line1[2 * displacement], lead_line2[2 * displacement])
enter_long = chikou_free_long and close > max(lead_line1[displacement], lead_line2[displacement])
exit_long = close < lead_line1[displacement] or close < lead_line2[displacement]
chikou_free_short = close < low[displacement] and close < min(lead_line1[2 * displacement], lead_line2[2 * displacement])
enter_short = chikou_free_short and close < min(lead_line1[displacement], lead_line2[displacement])
exit_short = close > lead_line1[displacement] or close > lead_line2[displacement]
strategy.entry("Long", strategy.long, when=enter_long)
strategy.close("Long", when=exit_long)
if (not long_only)
strategy.entry("Short", strategy.short, when=enter_short)
strategy.close("Short", when=exit_short)
// ____ SL
sl_long = strategy.position_avg_price * (1- (slp/100))
sl_short = strategy.position_avg_price * (1 + (slp/100))
if (use_sl)
strategy.exit(id="SL", from_entry="Long", stop=sl_long)
strategy.exit(id="SL", from_entry="Short", stop=sl_short)
// ____ Plots
colors =
enter_long ? #27D600 :
enter_short ? #E30202 :
color.orange
p1 = plot(lead_line1, offset = displacement, color=colors,
title="Lead 1")
p2 = plot(lead_line2, offset = displacement, color=colors,
title="Lead 2")
fill(p1, p2, color = colors)
plot(chikou, offset = -displacement, color=color.blue)
|
Hull Crossover Strategy no TP or SL | https://www.tradingview.com/script/5BJ5tnca-Hull-Crossover-Strategy-no-TP-or-SL/ | Tuned_Official | https://www.tradingview.com/u/Tuned_Official/ | 222 | 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/
// © Tuned_Official
//@version=4
strategy(title="Hull Crossover Strategy no TP or SL", overlay = true, pyramiding=1, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=0.04)
//Inputs
hullLen1 = input(title="Hull fast length", defval=56)
hullLen2 = input(title="Hull slow length", defval=76)
//Indicators
fasthull = hma(close, hullLen1)
slowhull = hma(close, hullLen2)
//conditions
go_long = crossover(fasthull, slowhull)
go_short = crossunder(fasthull, slowhull)
//Entry
strategy.order("long", strategy.long, when=go_long)
strategy.order("Short", strategy.short, when=go_short) |
Ichimoku + RSI Crypto trending strategy | https://www.tradingview.com/script/UorXzio2-Ichimoku-RSI-Crypto-trending-strategy/ | exlux99 | https://www.tradingview.com/u/exlux99/ | 198 | 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/
// © exlux99
//@version=4
strategy(title="Ichimoku + RSI Crypto trending strategy", overlay=true, initial_capital = 1000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=0.1, pyramiding=1 )
UseHAcandles = input(true, title="Use Heikin Ashi Candles in Algo Calculations")
//
// === /INPUTS ===
// === BASE FUNCTIONS ===
haClose = UseHAcandles ? security(heikinashi(syminfo.tickerid), timeframe.period, close) : close
haOpen = UseHAcandles ? security(heikinashi(syminfo.tickerid), timeframe.period, open) : open
haHigh = UseHAcandles ? security(heikinashi(syminfo.tickerid), timeframe.period, high) : high
haLow = UseHAcandles ? security(heikinashi(syminfo.tickerid), timeframe.period, low) : low
//Inputs
ts_bars = input(20, minval=1, title="Tenkan-Sen Bars")
ks_bars = input(50, minval=1, title="Kijun-Sen Bars")
ssb_bars = input(120, minval=1, title="Senkou-Span B Bars")
cs_offset = input(30, minval=1, title="Chikou-Span Offset")
ss_offset = input(30, minval=1, title="Senkou-Span Offset")
long_entry = input(true, title="Long Entry")
short_entry = input(true, title="Short Entry")
//Volatility
//vollength = input(defval=1, title="VolLength")
//voltarget = input(defval=0., type=input.float, step=0.1, title="Volatility Target")
//Difference = abs((haClose - haOpen)/((haClose + haOpen)/2) * 100)
//MovingAverage = sma(Difference, vollength)
//highvolatility = MovingAverage > voltarget
////////////////////////////////////////////////////////////////////////////////
// BACKTESTING RANGE
// From Date Inputs
fromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31)
fromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12)
fromYear = input(defval = 2019, title = "From Year", minval = 1970)
// To Date Inputs
toDay = input(defval = 31, title = "To Day", minval = 1, maxval = 31)
toMonth = input(defval = 12, title = "To Month", minval = 1, maxval = 12)
toYear = input(defval = 2021, title = "To Year", minval = 1970)
// Calculate start/end date and time condition
startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00)
finishDate = timestamp(toYear, toMonth, toDay, 00, 00)
time_cond = time >= startDate and time <= finishDate
////////////////////////////////////////////////////////////////////////////////
middle(len) => avg(lowest(len), highest(len))
// Ichimoku Components
tenkan = middle(ts_bars)
kijun = middle(ks_bars)
senkouA = avg(tenkan, kijun)
senkouB = middle(ssb_bars)
//RSI
change = change(haClose)
gain = change >= 0 ? change : 0.0
loss = change < 0 ? (-1) * change : 0.0
avgGain = rma(gain, 14)
avgLoss = rma(loss, 14)
rs = avgGain / avgLoss
rsi = 100 - (100 / (1 + rs))
ss_high = max(senkouA[ss_offset-1], senkouB[ss_offset-1])
ss_low = min(senkouA[ss_offset-1], senkouB[ss_offset-1])
// Entry/Exit Signals
tk_cross_bull = tenkan > kijun
tk_cross_bear = tenkan < kijun
cs_cross_bull = mom(haClose, cs_offset-1) > 0
cs_cross_bear = mom(haClose, cs_offset-1) < 0
price_above_kumo = haClose > ss_high
price_below_kumo = haClose < ss_low
rsi_bullish = rsi > 50
rsi_bearish = rs < 50
bullish = tk_cross_bull and cs_cross_bull and price_above_kumo and rsi_bullish //and highvolatility
bearish = tk_cross_bear and cs_cross_bear and price_below_kumo and rsi_bearish //and highvolatility
strategy.entry("Long", strategy.long, when=bullish and long_entry and time_cond)
strategy.entry("Short", strategy.short, when=bearish and short_entry and time_cond)
strategy.close("Long", when=bearish and not short_entry and time_cond)
strategy.close("Short", when=bullish and not long_entry and time_cond)
|
BTC Sentiment analysis RSI 2xEMA | https://www.tradingview.com/script/kGVzpniP-BTC-Sentiment-analysis-RSI-2xEMA/ | exlux99 | https://www.tradingview.com/u/exlux99/ | 114 | 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/
// © exlux99
//@version=4
strategy("BTC Sentiment analysis RSI",initial_capital = 1000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=0.03, pyramiding=1 )
longs = change(security("BITFINEX:BTCUSDLONGS", timeframe.period, close))
shorts = change(security("BITFINEX:BTCUSDSHORTS", timeframe.period, close))
l = input(48, title="RSI length")
rsilong = rsi(security("BITFINEX:BTCUSDLONGS", timeframe.period, close), l)
rsishort = rsi(security("BITFINEX:BTCUSDSHORTS", timeframe.period, close), l)
plot(rsilong, color=color.green, style=plot.style_line)
plot(rsishort, color=color.red, style=plot.style_line)
ema_input=input(10)
ema_1 = ema(longs, ema_input)
ema_2 = ema(shorts, ema_input)
ema_3 = ema(longs, ema_input)
ema_4 = ema(shorts, ema_input)
bcolor = longs > ema(longs, ema_input) and shorts > ema(shorts, ema_input) ? color.yellow :
longs > ema_1 and shorts < ema_2 ? color.lime :
longs < ema_3 and shorts > ema_4 ? color.red : color.gray
plot(0, color=bcolor, style=plot.style_cross, linewidth=3)
hline(0)
fromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31)
fromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12)
fromYear = input(defval = 2000, title = "From Year", minval = 1970)
//monday and session
// To Date Inputs
toDay = input(defval = 31, title = "To Day", minval = 1, maxval = 31)
toMonth = input(defval = 12, title = "To Month", minval = 1, maxval = 12)
toYear = input(defval = 2021, title = "To Year", minval = 1970)
startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00)
finishDate = timestamp(toYear, toMonth, toDay, 00, 00)
time_cond = time >= startDate and time <= finishDate
if(time_cond)
strategy.entry("long",1,when=crossover(rsilong,rsishort) and (longs > ema_1 and shorts < ema_2))
strategy.close('long',when=crossunder(rsilong,rsishort) and (longs < ema_3 and shorts > ema_4))
//strategy.entry('short',0,when=crossunder(rsilong,rsishort) and longs < ema_3 and shorts > ema_4)
|
Alert(), alertcondition() or strategy alerts? | https://www.tradingview.com/script/WHOZ6UPz-Alert-alertcondition-or-strategy-alerts/ | Peter_O | https://www.tradingview.com/u/Peter_O/ | 494 | 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/
// © Peter_O
//@version=4
strategy(title="TradingView Alerts to MT4 MT5 example with cancelling pending orders", commission_type=strategy.commission.cash_per_order, commission_value=0.00003, overlay=true, default_qty_value=100000, initial_capital=1000)
// This script was created for educational purposes only.
// It is showing how to create pending orders and cancel them
// Together with syntax to send these events through TradingView alerts system
// All the way to brokers for execution
TakeProfitLevel=input(400)
// **** Entries logic **** {
periodK = 13 //input(13, title="K", minval=1)
periodD = 3 //input(3, title="D", minval=1)
smoothK = 4 //input(4, title="Smooth", minval=1)
k = sma(stoch(close, high, low, periodK), smoothK)
d = sma(k, periodD)
// plot(k, title="%K", color=color.blue)
// plot(d, title="%D", color=color.orange)
// h0 = hline(80)
// h1 = hline(20)
// fill(h0, h1, color=color.purple, transp=75)
GoLong=crossover(k,d) and k<80
GoShort=crossunder(k,d) and k>20
// } End of entries logic
// **** Pivot-points and stop-loss logic **** {
piv_high = pivothigh(high,1,1)
piv_low = pivotlow(low,1,1)
var float stoploss_long=low
var float stoploss_short=high
pl=valuewhen(piv_low,piv_low,0)
ph=valuewhen(piv_high,piv_high,0)
if GoLong
stoploss_long := low<pl ? low : pl
if GoShort
stoploss_short := high>ph ? high : ph
plot(stoploss_long, color=color.lime, title="stoploss_long")
plot(stoploss_short, color=color.red, title="stoploss_short")
// } End of Pivot-points and stop-loss logic
CancelLong=crossunder(low,stoploss_long) and strategy.position_size[1]<=0 and strategy.position_size<=0
CancelShort=crossover(high,stoploss_short) and strategy.position_size[1]>=0 and strategy.position_size>=0
entry_distance=input(10, title="Entry distance for stop orders")
plotshape(CancelLong ? stoploss_long[1]-10*syminfo.mintick : na, location=location.absolute, style=shape.labelup, color=color.gray, textcolor=color.white, text="cancel\nlong", size=size.tiny)
plotshape(CancelShort ? stoploss_short[1]+10*syminfo.mintick : na, location=location.absolute, style=shape.labeldown, color=color.gray, textcolor=color.white, text="cancel\nshort", size=size.tiny)
strategy.entry("Long", strategy.long, when=GoLong, stop=close+entry_distance*syminfo.mintick)
strategy.exit("XLong", from_entry="Long", stop=stoploss_long, profit=TakeProfitLevel)
strategy.cancel("Long", when = CancelLong)
strategy.entry("Short", strategy.short, when=GoShort, stop=close-entry_distance*syminfo.mintick)
strategy.exit("XShort", from_entry="Short", stop=stoploss_short, profit=TakeProfitLevel)
strategy.cancel("Short", when = CancelShort)
if GoLong
alertsyntax_golong='long offset=' + tostring(entry_distance) + ' slprice=' + tostring(stoploss_long) + ' tp=' + tostring(TakeProfitLevel)
alert(message=alertsyntax_golong, freq=alert.freq_once_per_bar_close)
if GoShort
alertsyntax_goshort='short offset=' + tostring(-entry_distance) + ' slprice=' + tostring(stoploss_short) + ' tp=' + tostring(TakeProfitLevel)
alert(message=alertsyntax_goshort, freq=alert.freq_once_per_bar_close)
if CancelLong
alertsyntax_cancellong='cancel long'
alert(message=alertsyntax_cancellong, freq=alert.freq_once_per_bar_close)
if CancelShort
alertsyntax_cancelshort='cancel short'
alert(message=alertsyntax_cancelshort, freq=alert.freq_once_per_bar_close)
|
CoinruleCombinedCryptoStrat | https://www.tradingview.com/script/ftmVDSyS-CoinruleCombinedCryptoStrat/ | SnoDragon | https://www.tradingview.com/u/SnoDragon/ | 40 | 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/
// © syfuslokust
//@version=4
strategy(shorttitle='CoinruleCombinedCryptoStrat',title='CoinruleCombinedCryptoStrat', overlay=true, initial_capital = 10000, pyramiding = 1000, process_orders_on_close=true, default_qty_type = strategy.percent_of_equity, default_qty_value = 2, commission_type=strategy.commission.percent, commission_value=0.35)
// RSI inputs and calculations
lengthRSI = 14
RSI = rsi(close, lengthRSI)
//Normal
oversold = input(35)
overbought = input(70)
res = input(title="Additional Timescale", defval="60", options=["5", "15", "60", "360", "1D"])
//ALGO
//oversold= input(26)
//overbought= input(80)
//sell pct
SellPct = input(15)
ExitPct = input(50)
//MA inputs and calculations
movingaverage_signal = sma(close, input(9))
movingaverage_fast = sma(close, input(50))
movingaverage_slow = sma(close, input(200))
movingaverage_mid= sma(close, input(100))
long_ma_signal = security(syminfo.tickerid, res, sma(close, input(9)), lookahead=barmerge.lookahead_on)
long_ma_fast = security(syminfo.tickerid, res, sma(close, input(50)), lookahead=barmerge.lookahead_on)
long_ma_slow = security(syminfo.tickerid, res, sma(close, input(200)), lookahead=barmerge.lookahead_on)
long_ma_mid= security(syminfo.tickerid, res, sma(close, input(100)), lookahead=barmerge.lookahead_on)
//Look Back
inp_lkb = input(12, title='Lookback Long Period')
inp_lkb_2 = input(2, title='Lookback Short Period')
perc_change(lkb) =>
overall_change = ((close[0] - close[lkb]) / close[lkb]) * 100
//Entry
//MA
bullish = crossover(movingaverage_signal, movingaverage_fast)
//Execute buy
strategy.entry(id="long", long = true, when = (RSI < oversold) and movingaverage_signal < movingaverage_mid, comment="BuyIn")
//when = crossover(close, movingaverage_signal) and movingaverage_signal < movingaverage_slow and RSI < oversold)
//Exit
//RSI
Stop_loss= ((input (4))/100)
longStopPrice = strategy.position_avg_price * (1 - Stop_loss)
//MA
bearish = crossunder(close, long_ma_mid)
//Execute sell
strategy.close("long", qty_percent = SellPct, when = RSI > overbought and movingaverage_fast > movingaverage_mid, comment="SmallSell")
strategy.close("long", qty_percent = ExitPct, when = bearish, comment="StopLoss")
//strategy.close("long", qty_percent = ExitPct, when = bearish )
//when = (crossunder(low, movingaverage_signal) and movingaverage_fast > movingaverage_slow and RSI > overbought) or (movingaverage_signal < movingaverage_fast and crossunder(low, movingaverage_fast)) or (low < longStopPrice))
//PLOT
plot(movingaverage_signal, color=color.white, linewidth=2, title="signal")
plot(movingaverage_fast, color=color.orange, linewidth=2, title="fast")
plot(movingaverage_slow, color=color.purple, linewidth=2, title="slow")
plot(movingaverage_mid, color=color.blue, linewidth=2, title="mid")
plot(long_ma_signal, color=color.yellow, linewidth=1, title="long signal")
plot(long_ma_mid, color=color.red, linewidth=1, title="long slow") |
3 RSI 6sma/ema ribbon crypto strategy | https://www.tradingview.com/script/9ZTsvMk5-3-RSI-6sma-ema-ribbon-crypto-strategy/ | exlux99 | https://www.tradingview.com/u/exlux99/ | 210 | 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/
// © exlux99
//@version=4
strategy(title="3 RSI MA movement crypto strategy", overlay=true, initial_capital = 100, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=0.03, pyramiding=1 )
///////////////
fromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31)
fromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12)
fromYear = input(defval = 2019, title = "From Year", minval = 1970)
//monday and session
// To Date Inputs
toDay = input(defval = 31, title = "To Day", minval = 1, maxval = 31)
toMonth = input(defval = 12, title = "To Month", minval = 1, maxval = 12)
toYear = input(defval = 2021, title = "To Year", minval = 1970)
startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00)
finishDate = timestamp(toYear, toMonth, toDay, 00, 00)
time_cond = time >= startDate and time <= finishDate
source = input(ohlc4)
RSIFast = rsi(source, 50)
RSINorm = rsi(source, 75)
RSISlow = rsi(source, 100)
// plot(RSIFast, color=color.silver, style=plot.style_area, histbase=50)
// plot(RSINorm, color=#98b8be, style=plot.style_area, histbase=50)
// plot(RSISlow, color=#be9e98, style=plot.style_area, histbase=50)
// plot(RSIFast, color=color.gray, style=plot.style_line, linewidth=1)
// plot(RSINorm, color=color.purple, style=plot.style_line, linewidth=2)
// plot(RSISlow, color=color.black, style=plot.style_line, linewidth=3)
exponential = false//input(false, title="Exponential MA")
src = (RSIFast)
ma05 = exponential ? ema(src, 05) : sma(src, 05)
ma30 = exponential ? ema(src, 30) : sma(src, 30)
ma50 = exponential ? ema(src, 50) : sma(src, 50)
ma70 = exponential ? ema(src, 70) : sma(src, 70)
ma90 = exponential ? ema(src, 90) : sma(src, 90)
ma100 = exponential ? ema(src, 100) : sma(src, 100)
leadMAColor = change(ma30)>=0 and ma30>ma100 ? color.lime : change(ma30)<0 and ma30>ma100 ? color.red : change(ma30)<=0 and ma30<ma100 ? color.maroon : change(ma30)>=0 and ma30<ma100 ? color.green : color.gray
maColor(ma, maRef) =>
change(ma)>=0 and ma30>maRef ? color.lime : change(ma)<0 and ma30>maRef ? color.red : change(ma)<=0 and ma30<maRef ? color.maroon : change(ma)>=0 and ma30<maRef ? color.green : color.gray
// plot( ma30, color=maColor(ma30,ma100), style=plot.style_line, title="MMA30", linewidth=2)
// plot( ma50, color=maColor(ma50,ma100), style=plot.style_line, title="MMA50", linewidth=2)
// plot( ma70, color=maColor(ma70,ma100), style=plot.style_line, title="MMA70", linewidth=2)
// plot( ma90, color=maColor(ma90,ma100), style=plot.style_line, title="MMA90", linewidth=2)
long0=(leadMAColor==color.lime and maColor(ma30,ma100)==color.lime and maColor(ma50,ma100)==color.lime and maColor(ma70,ma100)==color.lime and maColor(ma90,ma100)==color.lime ) or (leadMAColor==color.green and maColor(ma30,ma100)==color.green and maColor(ma50,ma100)==color.green and maColor(ma70,ma100)==color.green and maColor(ma90,ma100)==color.green )
exit0=leadMAColor==color.maroon and maColor(ma30,ma100)==color.maroon and maColor(ma50,ma100)==color.maroon and maColor(ma70,ma100)==color.maroon and maColor(ma90,ma100)==color.maroon
exponential1 = false//input(false, title="Exponential MA")
src1 = (RSINorm)
ma051 = exponential1 ? ema(src1, 05) : sma(src1, 05)
ma301 = exponential1 ? ema(src1, 30) : sma(src1, 30)
ma501 = exponential1 ? ema(src1, 50) : sma(src1, 50)
ma701 = exponential1 ? ema(src1, 70) : sma(src1, 70)
ma901 = exponential1 ? ema(src1, 90) : sma(src1, 90)
ma1001 = exponential1 ? ema(src1, 100) : sma(src1, 100)
leadMAColor1 = change(ma051)>=0 and ma051>ma1001 ? color.lime : change(ma051)<0 and ma051>ma1001 ? color.red : change(ma051)<=0 and ma051<ma1001 ? color.maroon : change(ma051)>=0 and ma051<ma1001 ? color.green : color.gray
maColor1(ma, maRef) =>
change(ma)>=0 and ma05>maRef ? color.lime : change(ma)<0 and ma05>maRef ? color.red : change(ma)<=0 and ma05<maRef ? color.maroon : change(ma)>=0 and ma05<maRef ? color.green : color.gray
// plot( ma051, color=leadMAColor1, style=plot.style_line, title="MMA05", linewidth=1)
// plot( ma301, color=maColor1(ma301,ma1001), style=plot.style_line, title="MMA30", linewidth=3)
// plot( ma501, color=maColor1(ma501,ma1001), style=plot.style_line, title="MMA50", linewidth=3)
// plot( ma701, color=maColor1(ma701,ma1001), style=plot.style_line, title="MMA70", linewidth=3)
// plot( ma901, color=maColor1(ma901,ma1001), style=plot.style_line, title="MMA90", linewidth=3)
long1=(leadMAColor1==color.lime and maColor1(ma301,ma1001)==color.lime and maColor1(ma501,ma1001)==color.lime and maColor1(ma701,ma1001)==color.lime and maColor1(ma901,ma1001)==color.lime ) or (leadMAColor1==color.green and maColor1(ma301,ma1001)==color.green and maColor1(ma501,ma1001)==color.green and maColor1(ma701,ma1001)==color.green and maColor1(ma901,ma100)==color.green )
exit1=leadMAColor1==color.maroon and maColor1(ma301,ma1001)==color.maroon and maColor1(ma501,ma1001)==color.maroon and maColor1(ma701,ma1001)==color.maroon and maColor1(ma901,ma1001)==color.maroon
exponential2 = false//input(false, title="Exponential MA")
src2 = (RSISlow)
ma052 = exponential2 ? ema(src2, 05) : sma(src2, 05)
ma302 = exponential2 ? ema(src2, 30) : sma(src2, 30)
ma502 = exponential2 ? ema(src2, 50) : sma(src2, 50)
ma702 = exponential2 ? ema(src2, 70) : sma(src2, 70)
ma902 = exponential2 ? ema(src2, 90) : sma(src2, 90)
ma1002 = exponential2 ? ema(src2, 100) : sma(src2, 100)
leadMAColor2 = change(ma052)>=0 and ma052>ma1002 ? color.lime : change(ma052)<0 and ma052>ma1002 ? color.red : change(ma052)<=0 and ma052<ma1002 ? color.maroon : change(ma052)>=0 and ma052<ma1002 ? color.green : color.gray
maColor2(ma, maRef) =>
change(ma)>=0 and ma05>maRef ? color.lime : change(ma)<0 and ma05>maRef ? color.red : change(ma)<=0 and ma05<maRef ? color.maroon : change(ma)>=0 and ma05<maRef ? color.green : color.gray
// plot( ma052, color=leadMAColor2, style=plot.style_line, title="MMA05", linewidth=1)
// plot( ma302, color=maColor2(ma302,ma1001), style=plot.style_line, title="MMA30", linewidth=4)
// plot( ma502, color=maColor2(ma502,ma1001), style=plot.style_line, title="MMA50", linewidth=4)
// plot( ma702, color=maColor2(ma701,ma1001), style=plot.style_line, title="MMA70", linewidth=4)
// plot( ma902, color=maColor2(ma901,ma1001), style=plot.style_line, title="MMA90", linewidth=4)
long2=(leadMAColor2==color.lime and maColor2(ma302,ma1002)==color.lime and maColor2(ma502,ma1002)==color.lime and maColor2(ma702,ma1002)==color.lime and maColor2(ma902,ma1002)==color.lime ) or (leadMAColor2==color.green and maColor2(ma302,ma1002)==color.green and maColor2(ma502,ma1002)==color.green and maColor2(ma701,ma1002)==color.green and maColor2(ma901,ma1002)==color.green )
exit2=leadMAColor2==color.maroon and maColor2(ma302,ma1002)==color.maroon and maColor2(ma502,ma1002)==color.maroon and maColor2(ma702,ma1002)==color.maroon and maColor2(ma902,ma1002)==color.maroon
long= long1 or long2
exit= exit1 or exit2
// ------------------------- Strategy Logic --------------------------------- //
var longOpened = false
var shortOpened = false
var int timeOfBuy = na
longConditionLongOnly= long and not longOpened
if longConditionLongOnly
longOpened := true
timeOfBuy := time
longExitSignal = exit
exitLongConditionLongOnly = longOpened[1] and longExitSignal
if exitLongConditionLongOnly
longOpened := false
timeOfBuy := na
//plotshape(longConditionLongOnly, color=color.green, text= "Buy", location= location.belowbar,style= shape.labelup, textcolor=color.white, size = size.tiny, title="Buy Alert",editable=false, transp=60)
//plotshape(exitLongConditionLongOnly, color=color.red, text= "exit", location= location.abovebar,style= shape.labeldown, textcolor=color.white, size = size.tiny, title="Sell Alert", editable=false, transp=60)
//alertcondition(longConditionLongOnly ,title='Buy Alert', message='Buy Alert')
//alertcondition(exitLongConditionLongOnly , title='exit Alert', message='exit Alert')
if(time_cond)
strategy.entry("long",1,when=longConditionLongOnly)
strategy.entry("short",0,when=exitLongConditionLongOnly) |
Average Highest High and Lowest Low Swinger Strategy | https://www.tradingview.com/script/jZyFMNoL-Average-Highest-High-and-Lowest-Low-Swinger-Strategy/ | exlux99 | https://www.tradingview.com/u/exlux99/ | 215 | 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/
// © exlux99
//@version=4
strategy(title = "Avg HH/LL Crypto Swinger", overlay = true, initial_capital = 100, default_qty_type= strategy.percent_of_equity, default_qty_value = 100, commission_type=strategy.commission.percent,commission_value=0.1)
varLo = input(title="Fast Line", type=input.integer, defval=9, minval=1)
varHi = input(title="Slow Line", type=input.integer, defval=26, minval=1)
a = lowest(varLo)
b = highest(varLo)
c = (a + b ) / 2
d = lowest(varHi)
e = highest(varHi)
f = (d + e) / 2
g = ((c + f) / 2)[varHi]
h = ((highest(varHi * 2) + lowest(varHi * 2)) / 2)[varHi]
long=close > c and close > f and close >g and close > h
short=close < c and close < f and close<g and close < h
strategy.entry("long",1,when=long)
strategy.entry('short',0,when=short) |
Date Range Demonstration | https://www.tradingview.com/script/TzCa3XcU-Date-Range-Demonstration/ | UnknownUnicorn19826629 | https://www.tradingview.com/u/UnknownUnicorn19826629/ | 14 | 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/
// © LasciviousMonk
//@version=4
//
// This is a simple strategy to demonstrate a quick and easy way to impose a date range on a strategy for
// for backtesting purposes.
// To use:
// 1. Copy the code between the '////' lines into your strategy
// 2. Add the variable 'inDateRange' to your entry conditions.
//
strategy("Date Range Demonstration", overlay=true)
//////////////////////////////
// Limit backtesting dates //
//////////////////////////////
useDateRange = input(defval=true, title="Limit backtesting by date", type=input.bool, group="Limit by date")
rangeType = input(defval="Custom", title="Date range:", options=["Custom", "30 Days", "90 Days", "180 Days", "Year to Date"], group="Limit by date", tooltip="If set to other than custom, this overrides any set dates.")
startDate = input(title="Start Date (YYYY/DD/MM)", type=input.time,
defval=timestamp("1 Jan 2021 1:01 -0400"), group="Limit by date")
endDate = input(title="End Date (YYYY/DD/MM) ", type=input.time,
defval=timestamp("31 Dec 2100 19:59 -0400"), group="Limit by date", tooltip="You likely want to leave this far in the future.")
// subtract number of days (in milliseconds) from current time
startDate := rangeType == "Custom" ? startDate :
rangeType == "30 Days" ? timenow - 2592000000 :
rangeType == "90 Days" ? timenow - 7776000000 :
rangeType == "180 Days" ? timenow - 15552000000 :
rangeType == "Year to Date" ? timestamp(syminfo.timezone, year(timenow), 01, 01, 00, 01) : na
inDateRange = (time >= startDate) and (time < endDate)
inDateRange := useDateRange ? inDateRange : 1
//////////////////////////////
longCondition = crossover(sma(close, 14), sma(close, 28))
if inDateRange and longCondition
strategy.entry("My Long Entry Id", strategy.long) |
[VJ]Phoenix Force of PSAR +MACD +RSI | https://www.tradingview.com/script/f66PxwyP-VJ-Phoenix-Force-of-PSAR-MACD-RSI/ | vikris | https://www.tradingview.com/u/vikris/ | 98 | 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/
// © vikris
//@version=4
strategy("[VJ]Phoenix Force of PSAR +MACD +RSI", overlay=true, calc_on_every_tick = false,pyramiding=0)
// ********** Strategy inputs - Start **********
// Used for intraday handling
// Session value should be from market start to the time you want to square-off
// your intraday strategy
// Important: The end time should be at least 2 minutes before the intraday
// square-off time set by your broker
var i_marketSession = input(title="Market session", type=input.session,
defval="0915-1455", confirm=true)
// Make inputs that set the take profit % (optional)
longProfitPerc = input(title="Long Take Profit (%)",
type=input.float, minval=0.0, step=0.1, defval=3) * 0.01
shortProfitPerc = input(title="Short Take Profit (%)",
type=input.float, minval=0.0, step=0.1, defval=3) * 0.01
// Set stop loss level with input options (optional)
longLossPerc = input(title="Long Stop Loss (%)",
type=input.float, minval=0.0, step=0.1, defval=3) * 0.01
shortLossPerc = input(title="Short Stop Loss (%)",
type=input.float, minval=0.0, step=0.1, defval=3) * 0.01
// ********** Strategy inputs - End **********
// ********** Supporting functions - Start **********
// A function to check whether the bar or period is in intraday session
barInSession(sess) => time(timeframe.period, sess) != 0
// Figure out take profit price
longExitPrice = strategy.position_avg_price * (1 + longProfitPerc)
shortExitPrice = strategy.position_avg_price * (1 - shortProfitPerc)
// Determine stop loss price
longStopPrice = strategy.position_avg_price * (1 - longLossPerc)
shortStopPrice = strategy.position_avg_price * (1 + shortLossPerc)
// ********** Supporting functions - End **********
// ********** Strategy - Start **********
// See if intraday session is active
bool intradaySession = barInSession(i_marketSession)
// Trade only if intraday session is active
//=================Strategy logic goes in here===========================
psar = sar(0.02,0.02,0.2)
c1a = close > psar
c1v = close < psar
malen = input(50, title="MA Length")
mm200 = sma(close, malen)
c2a = close > mm200
c2v = close < mm200
fast = input(12, title="MACD Fast EMA Length")
slow = input(26, title="MACD Slow EMA Length")
[macd,signal,hist] = macd(close, fast,slow, 9)
c3a = macd >= 0
c3v = macd <= 0
rsilen = input(7, title="RSI Length")
th = input(50, title="RSI Threshold")
rsi14 = rsi(close, rsilen)
c4a = rsi14 >= th
c4v = rsi14 <= th
chopi = input(7, title="Chop Index lenght")
ci = 100 * log10(sum(atr(1), chopi) / (highest(chopi) - lowest(chopi))) / log10(chopi)
buy = c1a and c2a and c3a and c4a ? 1 : 0
sell = c1v and c2v and c3v and c4v ? -1 : 0
//Final Long/Short Condition
longCondition = buy==1 and ci <50
shortCondition = sell==-1 and ci <50
//Long Strategy - buy condition and exits with Take profit and SL
if (longCondition and intradaySession)
stop_level = longStopPrice
profit_level = longExitPrice
strategy.entry("My Long Entry Id", strategy.long)
strategy.exit("TP/SL", "My Long Entry Id", stop=stop_level, limit=profit_level)
//Short Strategy - sell condition and exits with Take profit and SL
if (shortCondition and intradaySession)
stop_level = shortStopPrice
profit_level = shortExitPrice
strategy.entry("My Short Entry Id", strategy.short)
strategy.exit("TP/SL", "My Short Entry Id", stop=stop_level, limit=profit_level)
// Square-off position (when session is over and position is open)
squareOff = (not intradaySession) and (strategy.position_size != 0)
strategy.close_all(when = squareOff, comment = "Square-off")
// ********** Strategy - End ********** |
Optimized Keltner Channels SL/TP Strategy for BTC | https://www.tradingview.com/script/eH0FxdMp/ | chanu_lev10k | https://www.tradingview.com/u/chanu_lev10k/ | 342 | 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/
// © chanu_lev10k
//@version=4
strategy(title="Optimized Keltner Channels SL/TP Strategy for BTC", overlay=true)
length = input(9, minval=1)
mult = input(1.0, "Multiplier")
src = input(close, title="Source")
exp = input(true, "Use Exponential MA")
BandsStyle = input("Average True Range", options = ["Average True Range", "True Range", "Range"], title="Bands Style")
atrlength = input(19, "ATR Length")
sl = input(defval=20, minval=0, type=input.float, step=0.1, title="Stop Loss (%)")
tp = input(defval=20.3, minval=0, type=input.float, step=0.1, title="Take Profit (%)")
esma(source, length)=>
s = sma(source, length)
e = ema(source, length)
exp ? e : s
ma = esma(src, length)
rangema = BandsStyle == "True Range" ? rma(tr(true), length) : BandsStyle == "Average True Range" ? atr(atrlength) : rma(high - low, length)
upper = ma + rangema * mult
lower = ma - rangema * mult
c = color.blue
u = plot(upper, color=color.green, title="Upper")
plot(ma, color=#0094FF, title="Basis")
l = plot(lower, color=color.red, title="Lower")
fill(u, l, color.new(color=#0094FF, transp=95), title="Background")
crossUpper = crossover(src, upper)
crossLower = crossunder(src, lower)
bprice = 0.0
bprice := crossUpper ? close+syminfo.mintick : nz(bprice[1])
sprice = 0.0
sprice := crossLower ? close-syminfo.mintick : nz(sprice[1])
crossBcond = false
crossBcond := crossUpper ? true
: na(crossBcond[1]) ? false : crossBcond[1]
crossScond = false
crossScond := crossLower ? true
: na(crossScond[1]) ? false : crossScond[1]
cancelBcond = crossBcond and (src < ma or high >= bprice )
cancelScond = crossScond and (src > ma or low <= sprice )
if (cancelBcond)
strategy.cancel("KltChLE")
if (crossUpper)
strategy.entry("KltChLE", strategy.long, stop=bprice, comment="Long")
if (cancelScond)
strategy.cancel("KltChSE")
if (crossLower)
strategy.entry("KltChSE", strategy.short, stop=sprice, comment="Short")
strategy.exit("Long exit", "KltChLE", profit = close * tp * 0.01 / syminfo.mintick, loss = close * sl * 0.01 / syminfo.mintick)
strategy.exit("Short exit", "KltChSE", profit = close * tp * 0.01 / syminfo.mintick, loss = close * sl * 0.01 / syminfo.mintick)
plot(bprice, color=color.green)
plot(sprice, color=color.red) |
[VJ] Viper VWAP Intraday | https://www.tradingview.com/script/EH1LM5Kx-VJ-Viper-VWAP-Intraday/ | vikris | https://www.tradingview.com/u/vikris/ | 178 | 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/
// © vikris
//@version=4
strategy("[VJ] Viper VWAP Intraday", overlay=true, calc_on_every_tick = false)
// ********** Strategy inputs - Start **********
// Used for intraday handling
// Session value should be from market start to the time you want to square-off
// your intraday strategy
// Important: The end time should be at least 2 minutes before the intraday
// square-off time set by your broker
var i_marketSession = input(title="Market session", type=input.session,
defval="0915-1455", confirm=true)
// Make inputs that set the take profit % (optional)
longProfitPerc = input(title="Long Take Profit (%)",
type=input.float, minval=0.0, step=0.1, defval=1) * 0.01
shortProfitPerc = input(title="Short Take Profit (%)",
type=input.float, minval=0.0, step=0.1, defval=1) * 0.01
// Set stop loss level with input options (optional)
longLossPerc = input(title="Long Stop Loss (%)",
type=input.float, minval=0.0, step=0.1, defval=0.5) * 0.01
shortLossPerc = input(title="Short Stop Loss (%)",
type=input.float, minval=0.0, step=0.1, defval=0.5) * 0.01
// ********** Strategy inputs - End **********
// ********** Supporting functions - Start **********
// A function to check whether the bar or period is in intraday session
barInSession(sess) => time(timeframe.period, sess) != 0
// Figure out take profit price
longExitPrice = strategy.position_avg_price * (1 + longProfitPerc)
shortExitPrice = strategy.position_avg_price * (1 - shortProfitPerc)
// Determine stop loss price
longStopPrice = strategy.position_avg_price * (1 - longLossPerc)
shortStopPrice = strategy.position_avg_price * (1 + shortLossPerc)
// ********** Supporting functions - End **********
// ********** Strategy - Start **********
cilength = input(title="Length", type=input.integer, defval=14, minval=1, maxval=2000)
src = hlc3
upper = sum(volume * (change(src) <= 0 ? 0 : src), cilength)
lower = sum(volume * (change(src) >= 0 ? 0 : src), cilength)
_rsi(upper, lower) =>
100.0 - (100.0 / (1.0 + upper / lower))
mf = _rsi(upper, lower)
ci = 100 * log10(sum(atr(1), cilength) / (highest(cilength) - lowest(cilength))) / log10(cilength)
// bcod = mf < 25 and ci <50
// scod = mf >75 and ci <50
citrendfactor = input(title="Trend Factor", type=input.float, defval=38.2, minval=1.0, maxval=100.0)
bcod = mf < 25
scod = mf >75
//Vol Confirmation
vol = volume > volume[1]
//Engulfing candle confirm
// bullishEC = close > open[1] and close[1] < open[1]
// bearishEC = close < open[1] and close[1] > open[1]
//Candles colors
greenCandle = (close > open)
redCandle = (close < open)
// See if intraday session is active
bool intradaySession = barInSession(i_marketSession)
// Trade only if intraday session is active
//Final Long/Short Condition
longCondition = redCandle and vol and vwap > vwap[1] and ci <citrendfactor
shortCondition =greenCandle and vol and vwap < vwap[1] and ci <citrendfactor
// Long position
// When longCondition and intradaySession both are true
strategy.entry(id = "Long", long = strategy.long,
when = longCondition and intradaySession)
// Short position
// When shortCondition and intradaySession both are true
strategy.entry(id = "Short", long = strategy.short,
when = shortCondition and intradaySession)
// Square-off position (when session is over and position is open)
squareOff = (not intradaySession) and (strategy.position_size != 0)
strategy.close_all(when = squareOff, comment = "Square-off")
// ********** Strategy - End ********** |
Qullamaggie Breakout V2 | https://www.tradingview.com/script/5bTajWQM-Qullamaggie-Breakout-V2/ | millerrh | https://www.tradingview.com/u/millerrh/ | 821 | 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/
// © millerrh
// The intent of this strategy is to buy breakouts with a tight stop on smaller timeframes in the direction of the longer term trend.
// Then use a trailing stop of a close below either the 10 MA or 20 MA (user choice) on that larger timeframe as the position
// moves in your favor (i.e. whenever position price rises above the MA).
// Option of using daily ADR as a measure of finding contracting ranges and ensuring a decent risk/reward.
// (If the difference between the breakout point and your stop level is below a certain % of ATR, it could possibly find those consolidating periods.)
// V2 - updates code of original Qullamaggie Breakout to optimize and debug it a bit - the goal is to remove some of the whipsaw and poor win rate of the
// original by incorporating some of what I learned in the Breakout Trend Follower script.
//@version=5
strategy("Qullamaggie Breakout V2", overlay=true, initial_capital=100000, currency='USD', calc_on_every_tick = true,
default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=0.1)
// === BACKTEST RANGE ===
Start = input.time(defval = timestamp("01 Jan 2019 06:00 +0000"), title = "Backtest Start Date", group = "backtest window and pivot history")
Finish = input.time(defval = timestamp("01 Jan 2100 00:00 +0000"), title = "Backtest End Date", group = "backtest window and pivot history")
// Inputs
showPivotPoints = input.bool(title = "Show Historical Pivot Points?", defval = false, group = "backtest window and pivot history",
tooltip = "Toggle this on to see the historical pivot points that were used. Change the Lookback Periods to adjust the frequency of these points.")
htf = input.timeframe(defval="D", title="Timeframe of Moving Averages", group = "moving averages",
tooltip = "Allows you to set a different time frame for the moving averages and your trailing stop.
The default behavior is to identify good tightening setups on a larger timeframe
(like daily) and enter the trade on a breakout occuring on a smaller timeframe, using the moving averages of the larger timeframe to trail your stop.")
maType = input.string(defval="SMA", options=["EMA", "SMA"], title = "Moving Average Type", group = "moving averages")
ma1Length = input.int(defval = 10, title = "1st Moving Average: Length", minval = 1, group = "moving averages", inline = "1ma")
ma1Color = input.color(color.new(color.purple, 60), title = " Color", group = "moving averages", inline = "1ma")
ma2Length = input.int(defval = 20, title = "2nd Moving Average: Length", minval = 1, group = "moving averages", inline = "2ma")
ma2Color = input.color(color.new(color.yellow, 60), title = " Color", group = "moving averages", inline = "2ma")
ma3Length = input.int(defval = 50, title = "3rd Moving Average: Length", minval = 1, group = "moving averages", inline = "3ma")
ma3Color = input.color(color.new(color.white, 60), title = " Color", group = "moving averages", inline = "3ma")
useMaFilter = input.bool(title = "Use 3rd Moving Average for Filtering?", defval = true, group = "moving averages",
tooltip = "Signals will be ignored when price is under this slowest moving average. The intent is to keep you out of bear periods and only
buying when price is showing strength or trading with the longer term trend.")
trailMaInput = input.string(defval="1st Moving Average", options=["1st Moving Average", "2nd Moving Average"], title = "Trailing Stop", group = "stops",
tooltip = "Initial stops after entry follow the range lows. Once in profit, the trade gets more wiggle room and
stops will be trailed when price breaches this moving average.")
trailMaTF = input.string(defval="Same as Moving Averages", options=["Same as Moving Averages", "Same as Chart"], title = "Trailing Stop Timeframe", group = "stops",
tooltip = "Once price breaches the trail stop moving average, the stop will be raised to the low of that candle that breached. You can choose to use the
chart timeframe's candles breaching or use the same timeframe the moving averages use. (i.e. if daily, you wait for the daily bar to close before setting
your new stop level.)")
currentColorS = input.color(color.new(color.orange,50), title = "Current Range S/R Colors: Support", group = "stops", inline = "lineColor")
currentColorR = input.color(color.new(color.blue,50), title = " Resistance", group = "stops", inline = "lineColor")
colorStop = input.color(color.new(color.orange,50), title = "Stop Colors: Initial", group = "stops", inline = "stopColor")
colorTrail = input.color(color.new(color.blue,50), title = " Moving Average Trailing", group = "stops", inline = "stopColor")
// Pivot lookback
lbHigh = 3
lbLow = 3
// MA Calculations (can likely move this to a tuple for a single security call!!)
ma(maType, src, length) =>
maType == "EMA" ? ta.ema(src, length) : ta.sma(src, length) //Ternary Operator (if maType equals EMA, then do ema calc, else do sma calc)
ma1 = request.security(syminfo.tickerid, htf, ma(maType, close, ma1Length), barmerge.gaps_off, barmerge.lookahead_on)
ma2 = request.security(syminfo.tickerid, htf, ma(maType, close, ma2Length), barmerge.gaps_off, barmerge.lookahead_on)
ma3 = request.security(syminfo.tickerid, htf, ma(maType, close, ma3Length), barmerge.gaps_off, barmerge.lookahead_on)
plot(ma1, color=ma1Color, style=plot.style_line, title="MA1", linewidth=2)
plot(ma2, color=ma2Color, style=plot.style_line, title="MA2", linewidth=2)
plot(ma3, color=ma3Color, style=plot.style_line, title="MA3", linewidth=2)
// === USE ADR FOR FILTERING ===
// The idea here is that you want to buy in a consolodating range for best risk/reward. So here you can compare the current distance between
// support/resistance vs. the ADR and make sure you aren't buying at a point that is too extended.
useAdrFilter = input.bool(title = "Use ADR for Filtering?", defval = false, group = "adr filtering",
tooltip = "Signals will be ignored if the distance between support and resistance is larger than a user-defined percentage of ADR (or monthly volatility
in the stock screener). This allows the user to ensure they are not buying something that is too extended and instead focus on names that are consolidating more.")
adrPerc = input.int(defval = 120, title = "% of ADR Value", minval = 1, group = "adr filtering")
tableLocation = input.string(defval="Bottom", options=["Top", "Bottom"], title = "ADR Table Visibility", group = "adr filtering",
tooltip = "Place ADR table on the top of the pane, the bottom of the pane, or off.")
adrValue = request.security(syminfo.tickerid, "D", ta.sma((high-low)/math.abs(low) * 100, 21), barmerge.gaps_off, barmerge.lookahead_on) // Monthly Volatility in Stock Screener (also ADR)
adrCompare = (adrPerc * adrValue) / 100
// === PLOT SWING HIGH/LOW AND MOST RECENT LOW TO USE AS STOP LOSS EXIT POINT ===
ph = ta.pivothigh(high, lbHigh, lbHigh)
pl = ta.pivotlow(low, lbLow, lbLow)
highLevel = ta.valuewhen(ph, high[lbHigh], 0)
lowLevel = ta.valuewhen(pl, low[lbLow], 0)
barsSinceHigh = ta.barssince(ph) + lbHigh
barsSinceLow = ta.barssince(pl) + lbLow
timeSinceHigh = time[barsSinceHigh]
timeSinceLow = time[barsSinceLow]
//Removes color when there is a change to ensure only the levels are shown (i.e. no diagonal lines connecting the levels)
pvthis = fixnan(ph)
pvtlos = fixnan(pl)
hipc = ta.change(pvthis) != 0 ? na : color.new(color.maroon, 0)
lopc = ta.change(pvtlos) != 0 ? na : color.new(color.green, 0)
// Display Pivot lines
plot(showPivotPoints ? pvthis : na, color=hipc, linewidth=1, offset=-lbHigh, title="Top Levels")
plot(showPivotPoints ? pvthis : na, color=hipc, linewidth=1, offset=0, title="Top Levels 2")
plot(showPivotPoints ? pvtlos : na, color=lopc, linewidth=1, offset=-lbLow, title="Bottom Levels")
plot(showPivotPoints ? pvtlos : na, color=lopc, linewidth=1, offset=0, title="Bottom Levels 2")
// BUY AND SELL CONDITIONS
buyLevel = ta.valuewhen(ph, high[lbHigh], 0) //Buy level at Swing High
// Conditions for entry
stopLevel = float(na) // Define stop level here as "na" so that I can reference it in the ADR calculation before the stopLevel is actually defined.
buyConditions = (useMaFilter ? buyLevel > ma3 : true) and
(useAdrFilter ? (buyLevel - stopLevel[1]) < adrCompare : true) and
time > Start and time < Finish
buySignal = ta.crossover(high, buyLevel) and buyConditions
// Trailing stop points - when price punctures the moving average, move stop to the low of that candle - Define as function/tuple to only use one security call
trailMa = trailMaInput == "1st Moving Average" ? ma1 : ma2
f_getCross() =>
maCrossEvent = ta.crossunder(low, trailMa)
maCross = ta.valuewhen(maCrossEvent, low, 0)
maCrossLevel = fixnan(maCross)
maCrossPc = ta.change(maCrossLevel) != 0 ? na : color.new(color.blue, 0) //Removes color when there is a change to ensure only the levels are shown (i.e. no diagonal lines connecting the levels)
[maCrossEvent, maCross, maCrossLevel, maCrossPc]
crossTF = trailMaTF == "Same as Moving Averages" ? htf : ""
[maCrossEvent, maCross, maCrossLevel, maCrossPc] = request.security(syminfo.tickerid, crossTF, f_getCross(), barmerge.gaps_off, barmerge.lookahead_on)
plot(showPivotPoints ? maCrossLevel : na, color = maCrossPc, linewidth=1, offset=0, title="Ma Stop Levels")
// == STOP AND PRICE LEVELS ==
inPosition = strategy.position_size > 0
buyLevel := inPosition ? buyLevel[1] : buyLevel
stopDefine = ta.valuewhen(pl, low[lbLow], 0) //Stop Level at Swing Low
inProfit = strategy.position_avg_price <= stopDefine[1]
// stopLevel := inPosition ? stopLevel[1] : stopDefine // Set stop loss based on swing low and leave it there
stopLevel := inPosition and not inProfit ? stopDefine : inPosition and inProfit ? stopLevel[1] : stopDefine // Trail stop loss until in profit
trailStopLevel = float(na)
// trying to figure out a better way for waiting on the trail stop - it can trigger if above the stopLevel even if the MA hadn't been breached since opening the trade
notInPosition = strategy.position_size == 0
inPositionBars = ta.barssince(notInPosition)
maCrossBars = ta.barssince(maCrossEvent)
trailCross = inPositionBars > maCrossBars
// trailCross = trailMa > stopLevel
trailStopLevel := inPosition and trailCross ? maCrossLevel : na
plot(inPosition ? stopLevel : na, style=plot.style_linebr, color=colorStop, linewidth = 2, title = "Historical Stop Levels", trackprice=false)
plot(inPosition ? trailStopLevel : na, style=plot.style_linebr, color=colorTrail, linewidth = 2, title = "Historical Trail Stop Levels", trackprice=false)
// == PLOT SUPPORT/RESISTANCE LINES FOR CURRENT CHART TIMEFRAME ==
// Use a function to define the lines
f_line(x1, y1, y2, _color) =>
var line id = na
line.delete(id)
id := line.new(x1, y1, time, y2, xloc.bar_time, extend.right, _color)
highLine = f_line(timeSinceHigh, highLevel, highLevel, currentColorR)
lowLine = f_line(timeSinceLow, lowLevel, lowLevel, currentColorS)
// == ADR TABLE ==
tablePos = tableLocation == "Top" ? position.top_right : position.bottom_right
var table adrTable = table.new(tablePos, 2, 1, border_width = 3)
lightTransp = 90
avgTransp = 80
heavyTransp = 70
posColor = color.rgb(38, 166, 154)
negColor = color.rgb(240, 83, 80)
volColor = color.new(#999999, 0)
f_fillCellVol(_table, _column, _row, _value) =>
_transp = math.abs(_value) > 7 ? heavyTransp : math.abs(_value) > 4 ? avgTransp : lightTransp
_cellText = str.tostring(_value, "0.00") + "%\n" + "ADR"
table.cell(_table, _column, _row, _cellText, bgcolor = color.new(volColor, _transp), text_color = volColor, width = 6)
srDistance = (highLevel - lowLevel)/highLevel * 100
f_fillCellCalc(_table, _column, _row, _value) =>
_c_color = _value >= adrCompare ? negColor : posColor
_transp = _value >= adrCompare*0.8 and _value <= adrCompare*1.2 ? lightTransp :
_value >= adrCompare*0.5 and _value < adrCompare*0.8 ? avgTransp :
_value < adrCompare*0.5 ? heavyTransp :
_value > adrCompare*1.2 and _value <= adrCompare*1.5 ? avgTransp :
_value > adrCompare*1.5 ? heavyTransp : na
_cellText = str.tostring(_value, "0.00") + "%\n" + "Range"
table.cell(_table, _column, _row, _cellText, bgcolor = color.new(_c_color, _transp), text_color = _c_color, width = 6)
if barstate.islast
f_fillCellVol(adrTable, 0, 0, adrValue)
f_fillCellCalc(adrTable, 1, 0, srDistance)
// f_fillCellVol(adrTable, 0, 0, inPositionBars)
// f_fillCellCalc(adrTable, 1, 0, maCrossBars)
// == STRATEGY ENTRY AND EXIT ==
strategy.entry("Buy", strategy.long, stop = buyLevel, when = buyConditions)
stop = stopLevel > trailStopLevel ? stopLevel : close[1] > trailStopLevel and close[1] > trailMa ? trailStopLevel : stopLevel
strategy.exit("Sell", from_entry = "Buy", stop=stop)
|
EMA pullback strategy | https://www.tradingview.com/script/nCJPecMy-EMA-pullback-strategy/ | Space_Jellyfish | https://www.tradingview.com/u/Space_Jellyfish/ | 110 | 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/
// created by Space Jellyfish
//@version=4
strategy("EMA pullback strategy", overlay = true, initial_capital=10000, commission_value = 0.075)
target_stop_ratio = input(title="Take Profit Stop Loss ratio", type=input.float, defval=2.06, minval=0.5, maxval=100)
riskLimit_low = input(title="lowest risk per trade", type=input.float, defval=0.008, minval=0, maxval=100)
riskLimit_high = input(title="highest risk per trade", type=input.float, defval=0.025, minval=0, maxval=100)
//give up the trade, if the risk is smaller than limit, adjust position size if risk is bigger than limit
ema_pullbackLevel_period = input(title="EMA1 for pullback level Period", type=input.integer, defval=33, minval=1, maxval=10000)
ema_pullbackLimiit_period = input(title="EMA2 for pullback limit Period", type=input.integer, defval=165, minval=1, maxval=10000)
ema_trend_period = input(title="EMA3 for trend Period", type=input.integer, defval=365, minval=1, maxval=10000)
startDate = input(title="Start Date", type=input.integer, defval=1, minval=1, maxval=31)
startMonth = input(title="Start Month", type=input.integer, defval=1, minval=1, maxval=12)
startYear = input(title="Start Year", type=input.integer, defval=2018, minval=2008, maxval=2200)
label_forward_offset = input(25, title = "offset label")
inDateRange = (time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0))
ema_pullbackLevel = ema(close, ema_pullbackLevel_period)
ema_pullbackLimit = ema(close, ema_pullbackLimiit_period)
ema_trendDirection = ema(close, ema_trend_period)
//ema pullback
float pricePullAboveEMA_maxClose = na
float pricePullAboveEMA_maxHigh = na
float pricePullBelowEMA_minClose = na
float pricePullBelowMA_minLow = na
if(crossover(close, ema_pullbackLevel))
pricePullAboveEMA_maxClose := close
pricePullAboveEMA_maxHigh := high
else
pricePullAboveEMA_maxClose := pricePullAboveEMA_maxClose[1]
pricePullAboveEMA_maxHigh := pricePullAboveEMA_maxHigh[1]
if(close > pricePullAboveEMA_maxClose)
pricePullAboveEMA_maxClose := close
if(high > pricePullAboveEMA_maxHigh)
pricePullAboveEMA_maxHigh := high
if(crossunder(close, ema_pullbackLevel))
pricePullBelowEMA_minClose := close
pricePullBelowMA_minLow := low
else
pricePullBelowEMA_minClose :=pricePullBelowEMA_minClose[1]
pricePullBelowMA_minLow:=pricePullBelowMA_minLow[1]
if(close < pricePullBelowEMA_minClose)
pricePullBelowEMA_minClose := close
if(low < pricePullBelowMA_minLow)
pricePullBelowMA_minLow := low
long_strategy = crossover(close, ema_pullbackLevel) and pricePullBelowEMA_minClose < ema_pullbackLimit and ema_pullbackLevel>ema_trendDirection
short_strategy = crossunder(close, ema_pullbackLevel) and pricePullAboveEMA_maxClose > ema_pullbackLimit and ema_pullbackLevel<ema_trendDirection
float risk_long = na
float risk_short = na
float stopLoss = na
float takeProfit = na
float entry_price = na
float entryContracts = 0
risk_long := risk_long[1]
risk_short := risk_short[1]
//open a position determine the position size
if (strategy.position_size == 0 and long_strategy and inDateRange)
risk_long := (close - pricePullBelowMA_minLow) / close
if(risk_long < riskLimit_high)
entryContracts := strategy.equity / close
else
entryContracts := (strategy.equity * riskLimit_high / risk_long)/close
if(risk_long > riskLimit_low)
strategy.entry("long", strategy.long, qty = entryContracts, when = long_strategy)
if (strategy.position_size == 0 and short_strategy and inDateRange)
risk_short := (pricePullAboveEMA_maxHigh - close) / close
if(risk_short < riskLimit_high)
entryContracts := strategy.equity / close
else
entryContracts := (strategy.equity * riskLimit_high / risk_short)/close
if(risk_short > riskLimit_low)
strategy.entry("short", strategy.short, qty = entryContracts, when = short_strategy)
//take profit / stop loss
if(strategy.position_size > 0)
stopLoss := strategy.position_avg_price*(1 - risk_long)
takeProfit := strategy.position_avg_price*(1 + target_stop_ratio * risk_long)
entry_price := strategy.position_avg_price
strategy.exit("Long exit","long", limit = takeProfit , stop = stopLoss)
if(strategy.position_size < 0)
stopLoss := strategy.position_avg_price*(1 + risk_short)
takeProfit := strategy.position_avg_price*(1 - target_stop_ratio * risk_short)
entry_price := strategy.position_avg_price
strategy.exit("Short exit","short", limit = takeProfit, stop = stopLoss)
plot(ema_pullbackLevel, color=color.aqua, title="ema pullback level")
plot(ema_pullbackLimit, color=color.purple, title="ema pullback limit")
plot(ema_trendDirection, color=color.white, title="ema trend")
p_ep = plot(entry_price, color = color.yellow, linewidth = 1, style = plot.style_linebr, title="entry_price")
p_sl = plot(stopLoss, color = color.red, linewidth = 1, style = plot.style_linebr, title="stopLoss")
p_tp = plot(takeProfit, color = color.green, linewidth = 1, style = plot.style_linebr, title="takeProfit")
fill(p_tp, p_ep, color.new(color.green, transp = 90))
fill(p_sl, p_ep, color.new(color.red, transp = 90))
label_text = ""
if(strategy.position_size == 0)
label_text := "No Open Position"
else
label_text := "Open: " + strategy.position_entry_name + " " + tostring(strategy.position_size)
label_text := label_text + "\n\nNet Profit: " + tostring(strategy.netprofit/strategy.initial_capital * 100, '#.##') + "%"
label_text := label_text + "\nWin Rate: "+ tostring(strategy.wintrades/(strategy.wintrades+strategy.losstrades) * 100, '#.##') + "%" + "\n wins: " + tostring(strategy.wintrades) + "\n loses: " + tostring(strategy.losstrades)
label_text := label_text + "\nMax Draw Down: " + tostring(strategy.max_drawdown/strategy.initial_capital * 100, '#.##') + "%"
lbl = label.new(
x = time + label_forward_offset *(time - time[1]),
y = close, text = label_text,
xloc = xloc.bar_time,
yloc = yloc.price,
color = color.new(color.silver, transp = 90),
textcolor = color.new(color.white, transp = 0),
size = size.normal,
textalign = text.align_left
)
label.delete(lbl[1])
// |
Initial template | https://www.tradingview.com/script/VwrYqoUp-Initial-template/ | trading_mentalist | https://www.tradingview.com/u/trading_mentalist/ | 34 | 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/
// © TradingMentalist
//@version=4
strategy("Initial template",initial_capital=1000, overlay=true, pyramiding=0, commission_type=strategy.commission.percent, commission_value=0.04, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, currency = currency.USD)
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////ordercomments
enterlongcomment = "ENTERLONGCOMMENT"
entershortcomment = "ENTERSHORTCOMMENT"
exitlongcomment = "EXITLONGCOMMENT"
exitshortcomment = "EXITSHORTCOMMENT"
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////inputs
sidein2 = input(200, step=10, title='lookback for average range (bars)')
sidein = input(1, title='filter trades if range is less than (%)')/100
equityIn = input(42, title='filter trades if equity is below ema()')
sidewayssw = input(false, title='sideways filter?')
equitysw = input(false, title='equity filter?')
bestpricein = input(0.003,step=0.001, title='best price +/-?')/100
//longtpin = input(1,step=0.1, title='long TP %')/100
//longslin = input(0.4,step=0.1, title='long SL %')/100
//shorttpin = input(1,step=0.1, title='short TP %')/100
//shortslin = input(0.4,step=0.1, title='short SL %')/100
longinc=input(true, title="include longs?")
lConSw2=input(true, title="condition two?")
lConSw3=input(true, title="condition three?")
shotinc=input(true, title="include shorts?")
sConSw2=input(true, title="condition two?")
sConSw3=input(true, title="condition three?")
percent2points(percent) =>
strategy.position_avg_price * percent / 100 / syminfo.mintick
sl = percent2points(input(2, title = "stop loss %%"))
tp1 = percent2points(input(3, title = "take profit 1 %%"))
tp2 = percent2points(input(7, title = "take profit 2 %%"))
tp3 = percent2points(input(22, title = "take profit 3 %%"))
activateTrailingOnThirdStep = input(true, title = "trail on stage 3? tp3=amount tp2=offset")
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////filters
side1 = (close[1] + close[sidein2]) / 2
side2 = close[1] - close[sidein2]
side3 = side2 / side1
notsideways = side3 > sidein
equityMa = equitysw ? ema(strategy.equity, equityIn) : 0
equityCon = strategy.equity >= equityMa
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////functions
longatm = strategy.position_size[0] > 0
shortatm = strategy.position_size[0] < 0
bought = strategy.opentrades[0] == 1 and strategy.position_size[0] > strategy.position_size[1]
sold = strategy.opentrades[0] == 1 and strategy.position_size[0] < strategy.position_size[1]
var longconmet = false
var shortconmet = false
if strategy.position_size[1] > 0 and strategy.position_size[0] == 0
longconmet:=false
if strategy.position_size[1] < 0 and strategy.position_size[0] == 0
shortconmet:=false
exitcomment = longatm ? exitlongcomment : shortatm ? exitshortcomment : ""
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////indicators
ma1 = ema(close, 9)
ma2 = ema(close, 21)
ma3 = ema(close, 50)
plot(ma1, color=color.new(#E8B6B0,50))
plot(ma2, color=color.new(#B0E8BE,50))
plot(ma3, color=color.new(#00EEFF,50))
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////conditions
longConditionTrigger = crossover(ma2,ma3)
shortConditionTrigger = crossover(ma3,ma2)
if longConditionTrigger
longconmet:=true
if shortConditionTrigger
shortconmet:=true
bestpricel = valuewhen(longconmet,open,0) * (1-bestpricein)
bestprices = valuewhen(shortconmet,open,0) * (1+bestpricein)
longCondition1 = longconmet == true
longCondition2 = close[1] <= bestpricel
longCondition3 = true
shortCondition1 = shortconmet == true
shortCondition2 = close[1] >= bestprices
shortCondition3 = true
closelong = shortCondition1
closeshort = longCondition1
longCondition1in = longCondition1
longCondition2in = lConSw2 ? longCondition2 : true
longCondition3in = lConSw3 ? longCondition3 : true
shortCondition1in = shortCondition1
shortCondition2in = sConSw2 ? shortCondition2: true
shortCondition3in = sConSw3 ? shortCondition3: true
longConditions = longCondition1in and longCondition2in and longCondition3in
shortConditions = shortCondition1in and shortCondition2in and shortCondition3in
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////execution
long = sidewayssw ? notsideways and equityCon and longConditions : equityCon and longConditions
short = sidewayssw ? notsideways and equityCon and shortConditions : equityCon and shortConditions
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////risk
//longtplevel = strategy.position_avg_price * (1 + longtpin)
//longsllevel = strategy.position_avg_price * (1 - longslin)
//shorttplevel = strategy.position_avg_price * (1 - shorttpin)
//shortsllevel = strategy.position_avg_price * (1 + shortslin)
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////timeframe
startyear = 2000
startmonth = 1
startday = 1
stopyear = 9999
stopmonth = 12
stopday = 31
//(leave as is)
startperiod = timestamp(startyear,startmonth,startday,0,0)
periodstop = timestamp(stopyear,stopmonth,stopday,0,0)
timeframe() =>
time >= startperiod and time <= periodstop ? true : false
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////exiting::::::::::credit to creator::::::::::adolgov::::::::::https://www.tradingview.com/script/jjhUHcje-Stepped-trailing-strategy-example::::::::::
curProfitInPts() =>
if strategy.position_size > 0
(high - strategy.position_avg_price) / syminfo.mintick
else if strategy.position_size < 0
(strategy.position_avg_price - low) / syminfo.mintick
else
0
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
calcProfitTrgtPrice(OffsetPts) =>
calcStopLossPrice(-OffsetPts)
getCurrentStage() =>
var stage = 0
if strategy.position_size == 0
stage := 0
if stage == 0 and strategy.position_size != 0
stage := 1
else if stage == 1 and curProfitInPts() >= tp1
stage := 2
else if stage == 2 and curProfitInPts() >= tp2
stage := 3
stage
calcTrailingAmountLevel(points) =>
var float level = na
level := calcProfitTrgtPrice(points)
if not na(level)
if strategy.position_size > 0
if not na(level[1])
level := max(level[1], level)
if not na(level)
level := max(high, level)
else if strategy.position_size < 0
if not na(level[1])
level := min(level[1], level)
if not na(level)
level := min(low, level)
calcTrailingOffsetLevel(points, offset) =>
float result = na
amountLevel = calcTrailingAmountLevel(points)
if strategy.position_size > 0
trailActiveDiff = amountLevel - calcProfitTrgtPrice(points)
if trailActiveDiff > 0
result := trailActiveDiff + calcProfitTrgtPrice(offset)
else if strategy.position_size < 0
trailActiveDiff = calcProfitTrgtPrice(points) - amountLevel
if trailActiveDiff > 0
result := calcProfitTrgtPrice(offset) - trailActiveDiff
result
float stopLevel = na
float trailOffsetLevel = na
float profitLevel = activateTrailingOnThirdStep ? calcTrailingAmountLevel(tp3) : calcProfitTrgtPrice(tp3)
trailOffsetLevelTmp = calcTrailingOffsetLevel(tp3, tp2)
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////orders
if timeframe()
if longinc
if strategy.position_size == 0 or strategy.position_size > 0
strategy.entry(id="long", long=true, when=long, comment=enterlongcomment)
if shotinc
if strategy.position_size == 0 or strategy.position_size < 0
strategy.entry(id="short", long=false, when=short, comment = entershortcomment)
curStage = getCurrentStage()
if curStage == 1
stopLevel := calcStopLossPrice(sl)
strategy.exit("x", loss = sl, profit = tp3, comment = exitcomment)
else if curStage == 2
stopLevel := calcStopLossPrice(0)
strategy.exit("x", stop = stopLevel, profit = tp3, comment = exitcomment)
else if curStage == 3
stopLevel := calcStopLossPrice(-tp1)
if activateTrailingOnThirdStep
trailOffsetLevel := trailOffsetLevelTmp
strategy.exit("x", stop = stopLevel, trail_points = tp3, trail_offset = tp3-tp2, comment = exitcomment)
else
strategy.exit("x", stop = stopLevel, profit = tp3, comment = exitcomment)
else
strategy.cancel("x")
plot(stopLevel, style = plot.style_linebr, color = color.red)
plot(profitLevel, style = plot.style_linebr, color = color.blue)
plot(trailOffsetLevel, style = plot.style_linebr, color = color.green)
//strategy.exit("stop","long", limit=longtplevel, stop=longsllevel,comment=" ")
//strategy.close(id="long", when=closelong, comment = " ")
//strategy.exit("stop","short", limit=shorttplevel, stop=shortsllevel,comment = " ")
//strategy.close(id="short", when=closeshort, comment = " ") |
WEEKLY BTC TRADING SCRYPT | https://www.tradingview.com/script/DSB0583M-WEEKLY-BTC-TRADING-SCRYPT/ | taberandwords | https://www.tradingview.com/u/taberandwords/ | 84 | 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/
// © taberandwords
//developer: taberandwords
//author: taberandwords
//@version=4
strategy("WEEKLY BTC TRADING SCRYPT","WBTS",overlay=false,default_qty_type=strategy.fixed)
source=input(defval=close,title="source",group="STRATEGY")
btc=security('BTCUSDT','1W', source)
ma=sma(btc,8)
buy_condition= crossover(btc,ma)
sell_condition= crossunder(btc,ma)
ma_color=input(defval=#FF3232,title="COLOR",group="MA")
ma_linewidth=input(defval=2,title="LINE WIDTH",group="MA")
graphic_color=input(defval=#6666FF,title="COLOR",group="GRAPHIC")
graphic_linewidth=input(defval=2,title="LINE WIDTH",group="GRAPHIC")
start_date=input(defval=2020,title="YEAR",group="STRATEGY EXECUTION YEAR")
loss_ratio=input(defval=1,title="LOSS RATIO", group="STRATEGY")
reward_ratio=input(defval=3,title="REWARD RATIO", group="STRATEGY")
if(year>=start_date)
strategy.entry('BUY',long=true,when=buy_condition,alert_message='Price came to buying value!')
if(strategy.long)
alert('BTC buy order trigerred!',alert.freq_once_per_bar)
strategy.exit(id="SELL",loss=loss_ratio,profit=reward_ratio,when=sell_condition,alert_message='Price came to position closing value!')
if(sell_condition)
alert('BTC sell order trigerred!',alert.freq_once_per_bar)
plot(series=source,title="WEEKLY CLOSE",color=graphic_color,linewidth=graphic_linewidth)
plot(ma,title="SMA8 WEEKLY",color=ma_color,linewidth=ma_linewidth)
plot(strategy.equity,display=0)
|
Supertrend + RSI Strategy [Alose] | https://www.tradingview.com/script/zLLibnMR-Supertrend-RSI-Strategy-Alose/ | alorse | https://www.tradingview.com/u/alorse/ | 440 | 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/
// © alorse
//@version=5
strategy("Supertrend + RSI Strategy [Alose]", overlay=true, pyramiding=0, currency=currency.USD, default_qty_type=strategy.percent_of_equity, initial_capital=1000, default_qty_value=20, commission_type=strategy.commission.percent, commission_value=0.01)
stGroup = 'Supertrend'
atrPeriod = input(10, "ATR Length", group=stGroup)
factor = input.float(3.0, "Factor", step = 0.01, group=stGroup)
[_, direction] = ta.supertrend(factor, atrPeriod)
// RSI
rsiGroup = 'RSI'
src = input(title='Source', defval=close, group=rsiGroup)
lenRSI = input.int(14, title='Length', minval=1, group=rsiGroup)
RSI = ta.rsi(src, lenRSI)
// Strategy Conditions
stratGroup = 'Strategy'
showLong = input.bool(true, title='Long entries', group=stratGroup)
showShort = input.bool(false, title='Short entries', group=stratGroup)
RSIoverbought = input.int(72, title='Exit Long', minval=1, group=stratGroup, tooltip='The trade will close when the RSI crosses up this point.')
RSIoversold = input.int(28, title='Exit Short', minval=1, group=stratGroup, tooltip='The trade will close when the RSI crosses below this point.')
entryLong = ta.change(direction) < 0
exitLong = RSI > RSIoverbought or ta.change(direction) > 0
entryShort = ta.change(direction) > 0
exitShort = RSI < RSIoversold or ta.change(direction) < 0
if showLong
strategy.entry("Long", strategy.long, when=entryLong)
strategy.close("Long", when=exitLong)
if showShort
strategy.entry("Short", strategy.short, when=entryShort)
strategy.close("Short", when=exitShort)
|
VCP pivot buy | https://www.tradingview.com/script/ZjWK7n8O-VCP-pivot-buy/ | perrycc007 | https://www.tradingview.com/u/perrycc007/ | 332 | 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/
// © stockone1231
//@version=4
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © perrycc007
//@version=4
strategy("My Strategy", overlay=true)
len50 = input(50, minval=1, title="Length")
src = input(close, title="Source")
offset = input(title="Offset", type=input.integer, defval=0, minval=-500, maxval=500)
out50 = sma(src, len50)
plot(out50, color=color.blue, title="MA", offset=offset)
len200 = input(200, minval=1, title="Length")
out200 = sma(src, len200)
plot(out200, color=color.red, title="MA", offset=offset)
len150 = input(150, minval=1, title="Length")
out150 = sma(src, len150)
plot(out150, color=color.green, title="MA", offset=offset)
slow = input(50, minval=1, title="TREND") // 10 days a
signal_length = input(title="Signal Smoothing", type=input.integer, minval = 1, maxval = 500, defval = 10)
// Calculations
slowline = sma(volume, slow)
trend = sma(slowline, signal_length)
tema(s, p) =>
3 * ema(s, p) - 3 * ema(ema(s, p), p) + ema(ema(ema(s, p), p), p)
ma(t, s, p) =>
ema_1 = ema(s, p)
rma_1 = rma(s, p)
vwma_1 = vwma(s, p)
wma_1 = wma(s, p)
tema_1 = tema(s, p)
sma_1 = sma(s, p)
t == "ema" ? ema_1 : t == "rma" ? rma_1 :
t == "vwma" ? vwma_1 : t == "wma" ? wma_1 : t == "tema" ? tema_1 : sma_1
off(s, o) =>
offset_1 = offset(s, o == 0 ? 1 : o)
o > 0 ? offset_1 : s
mat11 = input(defval="ema", options=["ema", "sma", "rma", "vwma", "wma", "tema"], title="Moving Average 1 Type")
len11 = input(10, minval=1, title="Moving Average 1 Length")
src11 = input(close, title="Moving Average 1 Source")
off11 = input(0, minval=0, title="Moving Average 1 Offset")
mat22 = input(defval="ema", options=["ema", "sma", "rma", "vwma", "wma", "tema"], title="Moving Average 2 Type")
len22 = input(20, minval=1, title="Moving Average 2 Length")
src22 = input(close, title="Moving Average 2 Source")
off22 = input(0, minval=0, title="Moving Average 2 Offset")
out11 = ma(mat11, off(src11, off11), len11)
out22 = ma(mat22, off(src22, off22), len22)
plot(out11, color=#1155CC, transp=0, title="MA 1")
plot(out22, color=#FF0000, transp=50, linewidth=2, title="MA 2")
//trade to hold trend indicator//
bullishtrenddef = (close>out50) and (out50>out150) and (out150>out200) and (out200>out200[1]) and (out200>out200[20]) and (out50>=out50[1])
//pivot
atr_length = input(defval=3, title="ATR Length", type=input.integer)
lookback = input(defval=150, title="Look Back Period", type=input.integer)
closerange = input(defval=4, title="Close range", type=input.integer)
percentile1 = input(defval=30, title="Smaller Percentile", type=input.integer)
percentile2 = input(defval=40, title="Largerer Percentile", type=input.integer)
//range2
atr_value1 = 0.0
stan1 = 0.0
range1 = 0.0
l1=0.0
h1=0.0
for i = 1 to atr_length
h1:=highest(high,atr_length)
l1:=lowest(low,atr_length)
range1 := h1-l1
atrp1 = (range1 / h1) * 100
//range2
atr_value2 = 0.0
stan2 = 0.0
range2 = 0.0
l2=0.0
h2=0.0
for i = 1 to atr_length
h2:=highest(close,atr_length)
l2:=lowest(close,atr_length)
range2 := h2-l2
atrp2 = (range2 / h2) * 100
per1 = percentrank( atrp1, lookback)
per2 = percentrank( atrp2, lookback)
setting1 = (per1 <= percentile2) and (per1 > percentile1)
rangepivot = (per1 <= percentile1) and (atrp1<=10)
closepivot = (atrp2<=closerange)
pivot = rangepivot or closepivot
sessioncolor2 = setting1 and bullishtrenddef? color.yellow :na
sessioncolor3 = rangepivot and bullishtrenddef? color.blue :na
sessioncolor4 = closepivot and bullishtrenddef? color.red :na
bgcolor(sessioncolor2 , transp=70)
bgcolor(sessioncolor3 , transp=70)
bgcolor(sessioncolor4 , transp=70)
high_loopback = input(3, "High Lookback Length")
h3 = float (highest(high, high_loopback))
takePer = input(10.0, title='Take Profit %', type=input.float) / 100
shortPer = input(10.0, title='Stoploss %', type=input.float) / 100
stoploss = strategy.position_avg_price * (1 - shortPer)
longTake1 = strategy.position_avg_price * (1 + takePer)
longTake2 = strategy.position_avg_price * (1 + takePer*2)
longTake3 = strategy.position_avg_price * (1 + takePer*3)
long1 = bullishtrenddef and pivot
if (long1)
strategy.entry("Long", strategy.long, stop = h3[1] )
if strategy.position_size > 0
strategy.exit(id="Close Long1", qty_percent = 25, stop=stoploss, limit=longTake1)
if strategy.position_size > 0
strategy.exit(id="Close Long2", qty_percent = 50, stop=stoploss, limit=longTake2)
if strategy.position_size > 0
strategy.exit(id="Close Long3", qty_percent = 100, stop=stoploss, limit=longTake3)
|
Rising ADX strategy | https://www.tradingview.com/script/z2yjKdbe-Rising-ADX-strategy/ | dhilipthegreat | https://www.tradingview.com/u/dhilipthegreat/ | 172 | 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/
// © dhilipthegreat
//@version=4
//Rising ADX strategy
strategy(title="Rising ADX strategy", overlay=false,pyramiding=25, default_qty_type=strategy.fixed, default_qty_value=25, initial_capital=100000, currency=currency.USD)
adxlen = input(14, title="ADX Length", minval=1)
threshold = input(10, title="threshold", minval=5)
hline(threshold, color=color.black, linestyle=hline.style_dashed)
atype = input(2,minval=1,maxval=7,title="1=SMA, 2=EMA, 3=WMA, 4=HullMA")
malen=input(20, title="Moving average 1 ",minval=1, maxval=50)
avg = atype == 1 ? sma(close,malen) : atype == 2 ? ema(close,malen) : atype == 3 ? wma(close,malen) : atype == 4 ? hma(close,malen) : na
atype2 = input(2,minval=1,maxval=7,title="1=SMA, 2=EMA, 3=WMA, 4=HullMA")
malen2=input(20, title="Moving average 2",minval=1, maxval=200)
avg2 = atype2 == 1 ? sma(close,malen2) : atype2 == 2 ? ema(close,malen2) : atype2 == 3 ? wma(close,malen2) : atype2 == 4 ? hma(close,malen2) : na
//ADX&DI
dilen = 14
dirmov(len,_high,_low,_tr) =>
up = change(_high)
down = -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 = rma(_tr, len)
plus = fixnan(100 * rma(plusDM, len) / truerange)
minus = fixnan(100 * rma(minusDM, len) / truerange)
[plus, minus]
adx(dilen, adxlen,_high,_low,_tr) =>
[plus, minus] = dirmov(dilen,_high,_low,_tr)
sum = plus + minus
adx = 100 * rma(abs(plus - minus) / (sum == 0 ? 1 : sum), adxlen)
[plus, minus] = dirmov(dilen,high,low,tr)
sig = adx(dilen, adxlen,high,low,tr)
prev_sig = adx(dilen, adxlen,high[1],low[1],tr)
plot(sig ? sig : na, color = rising(sig, 1) ? color.lime : falling(sig, 1) ? color.orange : color.purple, title="ADX",linewidth=2)
//////
longCondition= sig > threshold and rising(sig, 1) and falling(prev_sig, 1) and close > avg and close > avg2
barcolor(longCondition ? color.yellow: na)
Long_side = input(false, "Long side")
if Long_side
strategy.entry(id="Long", long=true, when= longCondition and strategy.position_size<1)
exitCondition= (rising(prev_sig, 1) and falling(sig, 1)) or close < avg and close < avg2
strategy.close(id="Long",comment="L exit", qty=strategy.position_size , when= exitCondition) //close all
shortCondition= sig > threshold and rising(sig, 1) and falling(prev_sig, 1) and close < avg and close < avg2
barcolor(shortCondition ? color.gray: na)
Short_side = input(false, "Short side")
if Short_side
strategy.entry(id="Short", long=false, when= shortCondition and strategy.position_size<1)
sell_exitCondition= (rising(prev_sig, 1) and falling(sig, 1)) or close > avg and close > avg2
strategy.close(id="Short",comment="S exit", qty=strategy.position_size , when= sell_exitCondition) //close all
barcolor(strategy.position_size>1 ? color.lime: na)
bgcolor(strategy.position_size>1 ? color.lime: na)
barcolor(strategy.position_size<0 ? color.orange: na)
bgcolor(strategy.position_size<0 ? color.orange: na) |
Williams Fractals Strategy | https://www.tradingview.com/script/WVajplfL-Williams-Fractals-Strategy/ | B_L_A_C_K_S_C_O_R_P_I_O_N | https://www.tradingview.com/u/B_L_A_C_K_S_C_O_R_P_I_O_N/ | 453 | 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/
// © B_L_A_C_K_S_C_O_R_P_I_O_N
// v 1.1
//@version=4
strategy("Williams Fractals Strategy by ȼhąţhµяąɲǥą", overlay=true, default_qty_type=strategy.cash, default_qty_value=1000, currency='USD')
// *************Appearance*************
theme = input(type=input.string, defval="dark", options=["light","dark"], group="Appearance")
show_fractals = input(false, "Show Fractals", group="Appearance")
show_ema = input(false, "Show EMAs", group="Appearance")
// *************colors*************
color_green = color.green
color_red = color.red
color_yellow = color.yellow
color_orange = color.orange
color_blue = color.blue
color_white = color.white
// *************WF*************
// Define "n" as the number of periods and keep a minimum value of 2 for error handling.
n = input(title="Fractal Periods", defval=2, minval=2, type=input.integer, group="Williams Fractals")
// UpFractal
bool upflagDownFrontier = true
bool upflagUpFrontier0 = true
bool upflagUpFrontier1 = true
bool upflagUpFrontier2 = true
bool upflagUpFrontier3 = true
bool upflagUpFrontier4 = true
for i = 1 to n
upflagDownFrontier := upflagDownFrontier and (high[n-i] < high[n])
upflagUpFrontier0 := upflagUpFrontier0 and (high[n+i] < high[n])
upflagUpFrontier1 := upflagUpFrontier1 and (high[n+1] <= high[n] and high[n+i + 1] < high[n])
upflagUpFrontier2 := upflagUpFrontier2 and (high[n+1] <= high[n] and high[n+2] <= high[n] and high[n+i + 2] < high[n])
upflagUpFrontier3 := upflagUpFrontier3 and (high[n+1] <= high[n] and high[n+2] <= high[n] and high[n+3] <= high[n] and high[n+i + 3] < high[n])
upflagUpFrontier4 := upflagUpFrontier4 and (high[n+1] <= high[n] and high[n+2] <= high[n] and high[n+3] <= high[n] and high[n+4] <= high[n] and high[n+i + 4] < high[n])
flagUpFrontier = upflagUpFrontier0 or upflagUpFrontier1 or upflagUpFrontier2 or upflagUpFrontier3 or upflagUpFrontier4
upFractal = (upflagDownFrontier and flagUpFrontier)
// downFractal
bool downflagDownFrontier = true
bool downflagUpFrontier0 = true
bool downflagUpFrontier1 = true
bool downflagUpFrontier2 = true
bool downflagUpFrontier3 = true
bool downflagUpFrontier4 = true
for i = 1 to n
downflagDownFrontier := downflagDownFrontier and (low[n-i] > low[n])
downflagUpFrontier0 := downflagUpFrontier0 and (low[n+i] > low[n])
downflagUpFrontier1 := downflagUpFrontier1 and (low[n+1] >= low[n] and low[n+i + 1] > low[n])
downflagUpFrontier2 := downflagUpFrontier2 and (low[n+1] >= low[n] and low[n+2] >= low[n] and low[n+i + 2] > low[n])
downflagUpFrontier3 := downflagUpFrontier3 and (low[n+1] >= low[n] and low[n+2] >= low[n] and low[n+3] >= low[n] and low[n+i + 3] > low[n])
downflagUpFrontier4 := downflagUpFrontier4 and (low[n+1] >= low[n] and low[n+2] >= low[n] and low[n+3] >= low[n] and low[n+4] >= low[n] and low[n+i + 4] > low[n])
flagDownFrontier = downflagUpFrontier0 or downflagUpFrontier1 or downflagUpFrontier2 or downflagUpFrontier3 or downflagUpFrontier4
downFractal = (downflagDownFrontier and flagDownFrontier)
plotshape(downFractal and show_fractals, style=shape.triangleup, location=location.belowbar, offset=-n, color=color_green)
plotshape(upFractal and show_fractals, style=shape.triangledown, location=location.abovebar, offset=-n, color=color_red)
// *************EMA*************
len_a = input(20, minval=1, title="EMA Length A", group="EMA")
src_a = input(close, title="EMA Source A", group="EMA")
offset_a = input(title="EMA Offset A", type=input.integer, defval=0, minval=-500, maxval=500, group="EMA")
out_a = ema(src_a, len_a)
plot(show_ema ? out_a : na, title="EMA A", color=color_green, offset=offset_a)
len_b = input(50, minval=1, title="EMA Length B", group="EMA")
src_b = input(close, title="EMA Source B", group="EMA")
offset_b = input(title="EMA Offset B", type=input.integer, defval=0, minval=-500, maxval=500, group="EMA")
out_b = ema(src_b, len_b)
ema_b_color = (theme == "dark") ? color_yellow : color_orange
plot(show_ema ? out_b : na, title="EMA B", color=ema_b_color, offset=offset_b)
len_c = input(100, minval=1, title="EMA Length C", group="EMA")
src_c = input(close, title="EMA Source C", group="EMA")
offset_c = input(title="EMA Offset C", type=input.integer, defval=0, minval=-500, maxval=500, group="EMA")
out_c = ema(src_c, len_c)
ema_c_color = (theme == "dark") ? color_white : color_blue
plot(show_ema ? out_c : na, title="EMA C", color=ema_c_color, offset=offset_c)
// *************RSI*************
rsi_len = input(14, minval=1, title="RSI Length", group="RSI")
rsi_src = input(close, "RSI Source", type = input.source, group="RSI")
up = rma(max(change(rsi_src), 0), rsi_len)
down = rma(-min(change(rsi_src), 0), rsi_len)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
// *************Calculation*************
long = (out_a > out_b) and (out_a > out_c) and downFractal and low[2] > out_c and rsi[2] < rsi
short = (out_a < out_b) and (out_a < out_c) and upFractal and high[2] < out_c and rsi[2] > rsi
plotshape(long, style=shape.labelup, color=color_green, location=location.belowbar, title="long label", text= "L", textcolor=color_white)
plotshape(short, style=shape.labeldown, color=color_red, location=location.abovebar, title="short label", text= "S", textcolor=color_white)
// *************End of Signals calculation*************
// Make input options that configure backtest date range
startDate = input(title="Start Date", type=input.integer,
defval=1, minval=1, maxval=31, group="Orders")
startMonth = input(title="Start Month", type=input.integer,
defval=1, minval=1, maxval=12, group="Orders")
startYear = input(title="Start Year", type=input.integer,
defval=2018, minval=1800, maxval=2100, group="Orders")
endDate = input(title="End Date", type=input.integer,
defval=1, minval=1, maxval=31, group="Orders")
endMonth = input(title="End Month", type=input.integer,
defval=12, minval=1, maxval=12, group="Orders")
endYear = input(title="End Year", type=input.integer,
defval=2022, minval=1800, maxval=2100, group="Orders")
// Look if the close time of the current bar
// falls inside the date range
inDateRange = (time >= timestamp(syminfo.timezone, startYear,
startMonth, startDate, 0, 0)) and
(time < timestamp(syminfo.timezone, endYear, endMonth, endDate, 0, 0))
// Make inputs that set the take profit % (optional)
longProfitPerc = input(title="Long Take Profit (%)",
type=input.float, minval=0.0, step=0.1, defval=0.5, group="Orders") * 0.01
shortProfitPerc = input(title="Short Take Profit (%)",
type=input.float, minval=0.0, step=0.1, defval=0.5, group="Orders") * 0.01
// Figure out take profit price
longExitPrice = strategy.position_avg_price * (1 + longProfitPerc)
shortExitPrice = strategy.position_avg_price * (1 - shortProfitPerc)
// Plot take profit values for confirmation
plot(series=(strategy.position_size > 0) ? longExitPrice : na,
color=color_green, style=plot.style_circles,
linewidth=1, title="Long Take Profit")
plot(series=(strategy.position_size < 0) ? shortExitPrice : na,
color=color_green, style=plot.style_circles,
linewidth=1, title="Short Take Profit")
// Submit entry orders
if (inDateRange and long and strategy.opentrades == 0)
strategy.entry(id="Long", long=true)
if (inDateRange and short and strategy.opentrades == 0)
strategy.entry(id="Short", long=false)
// Set stop loss level with input options (optional)
longLossPerc = input(title="Long Stop Loss (%)",
type=input.float, minval=0.0, step=0.1, defval=3.1, group="Orders") * 0.01
shortLossPerc = input(title="Short Stop Loss (%)",
type=input.float, minval=0.0, step=0.1, defval=3.1, group="Orders") * 0.01
// Determine stop loss price
longStopPrice = strategy.position_avg_price * (1 - longLossPerc)
shortStopPrice = strategy.position_avg_price * (1 + shortLossPerc)
// Plot stop loss values for confirmation
plot(series=(strategy.position_size > 0) ? longStopPrice : na,
color=color_red, style=plot.style_cross,
linewidth=1, title="Long Stop Loss")
plot(series=(strategy.position_size < 0) ? shortStopPrice : na,
color=color_red, style=plot.style_cross,
linewidth=1, title="Short Stop Loss")
// Submit exit orders based on calculated stop loss price
if (strategy.position_size > 0)
strategy.exit(id="ExL",limit=longExitPrice, stop=longStopPrice)
if (strategy.position_size < 0)
strategy.exit(id="ExS", limit=shortExitPrice, stop=shortStopPrice)
// Exit open market position when date range ends
if (not inDateRange)
strategy.close_all() |
MFI Simple Strategy | https://www.tradingview.com/script/AKXK9Jub-MFI-Simple-Strategy/ | OztheWoz | https://www.tradingview.com/u/OztheWoz/ | 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/
// © OztheWoz
//@version=5
strategy("MFI Simple Strategy", overlay=false)
len = input(18, "Length")
mfi = ta.sma(ta.mfi(close, len), len)
mfiup = (mfi[1] < mfi) and (mfi[2] < mfi[1])
mfidn = (mfi[1] > mfi) and (mfi[2] < mfi[1])
goldsma = ta.sma(close, 200)
if goldsma < close
strategy.entry("Long", strategy.long, when=mfiup)
strategy.exit("Long", stop=goldsma)
strategy.close("Long", when=mfidn)
a = plot(mfi)
b = plot(80, color=color.gray)
c = plot(20, color=color.gray)
fillclr = color.new(color.blue, 70)
fill(a, b, color=(mfi > 80) ? fillclr : na)
// fill(a, c)
|
RSI Centered Pivots | https://www.tradingview.com/script/vbn4jPnf-RSI-Centered-Pivots/ | OztheWoz | https://www.tradingview.com/u/OztheWoz/ | 192 | 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/
// © OztheWoz
//@version=4
strategy("RSI Fractals", initial_capital=10000, commission_type=strategy.commission.percent, commission_value=0.1, slippage=3)
// study("RSI Fractals")
len = input(19, "Length")
rsi = rsi(close, len)
fractup = pivotlow(rsi, 2, 2)
fractdn = pivothigh(rsi, 2, 2)
plot(rsi)
hline(80, color=color.gray)
hline(20, color=color.gray)
plotshape(fractup, style=shape.triangleup, location=location.bottom, color=color.green, offset=-2)
strategy.entry("Long", true, 1, when=fractup)
strategy.close("Long", when=(rsi >= 80))
stoploss = close[1] - (close[1] * 0.5/100)
strategy.exit("Long", "Exit Long", stop=stoploss)
// alertcondition(fractup, "RSI Fractal Up", "RSI Fractal V \nExpect Reversal Bearish")
// alertcondition(fractdn, "RSI Fractal Down", "RSI Fractal ^ \nExpect Reversal Bullish")
// alertcondition((rsi >= 80), "RSI Overbought", "RSI Overbought \nSell Before Bearish Reversal")
// alertcondition((rsi <= 20), "RSI Underbought", "RSI Underbought \nSell Before Bullish Reversal") |
ST_greed_spot_example | https://www.tradingview.com/script/i0HNfq2Z-st-greed-spot-example/ | IntelTrading | https://www.tradingview.com/u/IntelTrading/ | 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/
// © Alferow
//@version=5
strategy("ST_gree_spot_example", overlay=true, initial_capital = 1000, pyramiding = 20, commission_value = 0.06, default_qty_type = strategy.percent_of_equity, default_qty_value = 100)
start = input.time(timestamp("01 Jan 2001 00:00"), title = 'Start date')
finish = input.time(timestamp("01 Jan 2101 00:00"), title = 'Finish date')
trig = time > start and time < finish ? true : false
l = ta.lowest(low, input(50, title = 'Period for low'))
hl = l[6]
// plot(hl, color = color.red)
n = input(10, title = 'Depth grid')
var money = 0.0
var price1 = 0.0
cond = low < hl and close > hl
if strategy.position_size == 0 and cond and strategy.equity > 0
price1 := close[1]
money := strategy.equity/n
vol1 = money/price1
var i = 0
if strategy.position_size > strategy.position_size[1]
i := i + 1
if strategy.position_size == 0
i := 0
k = input(3.0, title = 'Drawdown %')
pricen = strategy.position_avg_price * (1 - (k/100))
voln = money/pricen
t = input(3.0, title = 'Take %')
tp = strategy.position_avg_price * (1 + (t/100))
plot(strategy.position_avg_price, color = color.white)
plot(tp, color = color.green)
plot(pricen, color = color.red, offset = 3)
if cond and strategy.position_size == 0 and strategy.equity > 0 and trig
strategy.entry('buy', strategy.long, qty = vol1, limit = price1)
if strategy.position_size != 0 and strategy.equity > 0 and trig and i <= n - 1
strategy.order('buy', strategy.long, qty = voln, limit = pricen)
if trig
strategy.exit('buy', limit = tp)
|
RSI Rising Crypto Trending Strategy | https://www.tradingview.com/script/1bUkkXFG-RSI-Rising-Crypto-Trending-Strategy/ | exlux99 | https://www.tradingview.com/u/exlux99/ | 289 | 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/
// © exlux99
//@version=4
strategy(title = "RSI Rising", overlay = true, initial_capital = 100, default_qty_type= strategy.percent_of_equity, default_qty_value = 100, slippage=0,commission_type=strategy.commission.percent,commission_value=0.03)
/////////////////////
source = close
bb_length = 20
bb_mult = 1.0
basis = sma(source, bb_length)
dev = bb_mult * stdev(source, bb_length)
upperx = basis + dev
lowerx = basis - dev
bbr = (source - lowerx)/(upperx - lowerx)
bbr_len = 21
bbr_std = stdev(bbr, bbr_len)
bbr_std_thresh = 0.1
is_sideways = (bbr > 0.0 and bbr < 1.0) and bbr_std <= bbr_std_thresh
////////////////
fromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31)
fromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12)
fromYear = input(defval = 2010, title = "From Year", minval = 1970)
//monday and session
// To Date Inputs
toDay = input(defval = 31, title = "To Day", minval = 1, maxval = 31)
toMonth = input(defval = 12, title = "To Month", minval = 1, maxval = 12)
toYear = input(defval = 2021, title = "To Year", minval = 1970)
startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00)
finishDate = timestamp(toYear, toMonth, toDay, 00, 00)
time_cond = time >= startDate and time <= finishDate
sourcex = close
length = 2
pcntChange = 1
roc = 100 * (sourcex - sourcex[length])/sourcex[length]
emaroc = ema(roc, length/2)
isMoving() => emaroc > (pcntChange / 2) or emaroc < (0 - (pcntChange / 2))
periods = input(19)
smooth = input(14, title="RSI Length" )
src = input(low, title="Source" )
rsiClose = rsi(ema(src, periods), smooth)
long=rising(rsiClose,2) and not is_sideways and isMoving()
short=not rising(rsiClose,2) and not is_sideways and isMoving()
if(time_cond)
strategy.entry('long',1,when=long)
strategy.entry('short',0,when=short)
|
Mean Reversion Strategy v2 [KL] | https://www.tradingview.com/script/EDkimR4l-Mean-Reversion-Strategy-v2-KL/ | DojiEmoji | https://www.tradingview.com/u/DojiEmoji/ | 292 | 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/
// © DojiEmoji
//@version=5
strategy("Mean Reversion (ATR) Strategy v2 [KL] ", overlay=true, pyramiding=1, initial_capital=1000000000)
var string ENUM_LONG = "Long"
var string GROUP_TEST = "Hypothesis testing"
var string GROUP_TSL = "Stop loss"
var string GROUP_TREND = "Trend prediction"
var string GROUP_ORDER = "Order size and Profit taking"
backtest_timeframe_start = input.time(defval=timestamp("01 Apr 2000 13:30 +0000"), title="Backtest Start Time")
within_timeframe = time >= backtest_timeframe_start
// TSL: calculate the stop loss price. {
_multiple = input(2.0, title="ATR Multiplier for trailing stop loss", group=GROUP_TSL)
ATR_TSL = ta.atr(input(14, title="Length of ATR for trailing stop loss", group=GROUP_TSL, tooltip="Initial risk amount = atr(this length) x multiplier")) * _multiple
TSL_source = low
TSL_line_color = color.green
TSL_transp = 100
var stop_loss_price = float(0)
var float initial_entry_p = float(0)
var float risk_amt = float(0)
var float initial_order_size = float(0)
if strategy.position_size == 0 or not within_timeframe
TSL_line_color := color.black
stop_loss_price := TSL_source - ATR_TSL
else if strategy.position_size > 0
stop_loss_price := math.max(stop_loss_price, TSL_source - ATR_TSL)
TSL_transp := 0
plot(stop_loss_price, color=color.new(TSL_line_color, TSL_transp))
// } end of "TSL" block
// Order size and profit taking {
pcnt_alloc = input.int(5, title="Allocation (%) of portfolio into this security", tooltip="Size of positions is based on this % of undrawn capital. This is fixed throughout the backtest period.", minval=0, maxval=100, group=GROUP_ORDER) / 100
// Taking profits at user defined target levels relative to risked amount (i.e 1R, 2R, 3R)
var bool tp_mode = input(true, title="Take profit and different levels", group=GROUP_ORDER)
var float FIRST_LVL_PROFIT = input.float(1, title="First level profit", tooltip="Relative to risk. Example: entry at $10 and inital stop loss at $9. Taking first level profit at 1R means taking profits at $11", group=GROUP_ORDER)
var float SECOND_LVL_PROFIT = input.float(2, title="Second level profit", tooltip="Relative to risk. Example: entry at $10 and inital stop loss at $9. Taking second level profit at 2R means taking profits at $12", group=GROUP_ORDER)
var float THIRD_LVL_PROFIT = input.float(3, title="Third level profit", tooltip="Relative to risk. Example: entry at $10 and inital stop loss at $9. Taking third level profit at 3R means taking profits at $13", group=GROUP_ORDER)
// }
// ATR diversion test {
// Hypothesis testing (2-tailed):
//
// Null hypothesis (H0) and Alternative hypothesis (Ha):
// H0 : atr_fast equals atr_slow
// Ha : atr_fast not equals to atr_slow; implies atr_fast is either too low or too high
len_fast = input(5,title="Length of ATR (fast) for diversion test", group=GROUP_TEST)
atr_fast = ta.atr(len_fast)
atr_slow = ta.atr(input(50,title="Length of ATR (slow) for diversion test", group=GROUP_TEST, tooltip="This needs to be larger than Fast"))
// Calculate test statistic (test_stat)
std_error = ta.stdev(ta.tr, len_fast) / math.pow(len_fast, 0.5)
test_stat = (atr_fast - atr_slow) / std_error
// Compare test_stat against critical value defined by user in settings
//critical_value = input.float(1.645,title="Critical value", tooltip="Strategy uses 2-tailed test to compare atr_fast vs atr_slow. Null hypothesis (H0) is that both should equal. Based on the computed test statistic value, if absolute value of it is +/- this critical value, then H0 will be rejected.", group=GROUP_TEST)
conf_interval = input.string(title="Confidence Interval", defval="95%", options=["90%","95%","99%"], tooltip="Critical values of 1.645, 1.96, 2.58, for CI=90%/95%/99%, respectively; Under 2-tailed test to compare atr_fast vs atr_slow. Null hypothesis (H0) is that both should equal. Based on the computed test statistic value, if absolute value of it is +/- critical value, then H0 will be rejected.")
critical_value = conf_interval == "90%" ? 1.645 : conf_interval == "95%" ? 1.96 : 2.58
reject_H0 = math.abs(test_stat) > critical_value
// } end of "ATR diversion test" block
// Entry signals {
// main entry signal (if reject_H0 == true); gets passed onto the next bar because strategy needs to check for confirmation
var _entry_signal_triggered = false
if not _entry_signal_triggered
_entry_signal_triggered := reject_H0
// Confirmation signal: Trend prediction based on expected log returns
_prcntge_chng = math.log(close / close[1])
len_drift = input(14, title="Length of drift", group=GROUP_TREND, tooltip="For calculation of Drift, where Drift = moving average of Log(close/prev_close) + 0.5 * its variance; If this curve is upward sloping, strategy predicts price to trend upward")
_drift = ta.sma(_prcntge_chng, len_drift) - math.pow(ta.stdev(_prcntge_chng, len_drift), 2) * 0.5 // Expected return (drift) = average percentage change + half variance over the lookback period
_confirmation = _drift > _drift[1]
entry_signal_all = _entry_signal_triggered and _confirmation // Putting it together, Entry signal = main signal + confirmation signal
if entry_signal_all
_entry_signal_triggered := false //reset
// } end of "Entry signals" block
// MAIN {
// Update the stop limit if strategy holds a position.
if strategy.position_size > 0
strategy.exit(ENUM_LONG, comment="SL", stop=stop_loss_price)
// Entry
if within_timeframe and entry_signal_all and strategy.position_size == 0
initial_entry_p := close
risk_amt := ATR_TSL
initial_order_size := math.floor(pcnt_alloc * strategy.equity / close)
strategy.entry(ENUM_LONG, strategy.long, qty=initial_order_size)
var int TP_taken_count = 0
if tp_mode and close > strategy.position_avg_price
if close >= initial_entry_p + THIRD_LVL_PROFIT * risk_amt and TP_taken_count == 2
strategy.close(ENUM_LONG, comment="TP Lvl3", qty=math.floor(initial_order_size / 3))
TP_taken_count := TP_taken_count + 1
else if close >= initial_entry_p + SECOND_LVL_PROFIT * risk_amt and TP_taken_count == 1
strategy.close(ENUM_LONG, comment="TP Lvl2", qty=math.floor(initial_order_size / 3))
TP_taken_count := TP_taken_count + 1
else if close >= initial_entry_p + FIRST_LVL_PROFIT * risk_amt and TP_taken_count == 0
strategy.close(ENUM_LONG, comment="TP Lvl1", qty=math.floor(initial_order_size / 3))
TP_taken_count := TP_taken_count + 1
// Alerts
_atr = ta.atr(14)
alert_helper(msg) =>
prefix = "[" + syminfo.root + "] "
suffix = "(P=" + str.tostring(close, "#.##") + "; atr=" + str.tostring(_atr, "#.##") + ")"
alert(str.tostring(prefix) + str.tostring(msg) + str.tostring(suffix), alert.freq_once_per_bar)
if strategy.position_size > 0 and ta.change(strategy.position_size)
if strategy.position_size > strategy.position_size[1]
alert_helper("BUY")
else if strategy.position_size < strategy.position_size[1]
alert_helper("SELL")
// Clean up - set the variables back to default values once no longer in use
if ta.change(strategy.position_size) and strategy.position_size == 0
TP_taken_count := 0
initial_entry_p := float(0)
risk_amt := float(0)
initial_order_size := float(0)
stop_loss_price := float(0)
// } end of MAIN block
|
RS9.1 | https://www.tradingview.com/script/WGoItzRB/ | Ricardo_Silva | https://www.tradingview.com/u/Ricardo_Silva/ | 24 | 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/
// © Ricardo_Silva
//@version=5
strategy("RS9.1", overlay=true, margin_long=100, margin_short=100)
ema9 = ta.ema(close,9)
//ema21 = ta.ema(close,21)
//ema50 = ta.ema(close,50)
//ema100 = ta.ema(close,100)
//ema200 = ta.ema(close,200)
ema9up= ema9>ema9[1]
colorup=(ema9up ? color.green:na)
ema9down=ema9<ema9[1]
colordown = (ema9down ? color.red:na)
ema9n=not ema9up and not ema9down
colorn=(ema9n ? color.yellow:na)
plot(ema9, title="EMA 9 UP",linewidth=2,color=colorup)
plot(ema9, title="EMA 9 DOWN",linewidth=2,color=colordown)
plot(ema9, title="EMA 9 N",linewidth=2,color=colorn)
//plot(ema21, title="EMA 26 N",linewidth=2,color=color.orange)
//plot(ema50, title="EMA 50 N",linewidth=2,color=color.gray)
//plot(ema100, title="EMA 100", linewidth=2, color=color.blue)
//plot(ema200, title="EMA 200", linewidth=3, color=color.black)
// text signal
textbuy= high>high[1] and close>ema9 and close[1]<ema9[1]
textsell= low<low[1] and close<ema9 and close[1]>ema9[1]
long = close > ema9
short = close < ema9
//barcolor signal
buybarsignal= close>close[1] and textbuy
sellbarsignal = close<close[1] and textsell
barcolor(buybarsignal? #0e0ffb:na,title="BuyBar")
barcolor(sellbarsignal? color.purple:na,title="SellBar")
bgcolor(color=long ? color.new(color.green,80) : color.new(color.red,80))
|
ETF 3-Day Reversion Strategy | https://www.tradingview.com/script/Cvi9Zf0q-ETF-3-Day-Reversion-Strategy/ | TradeAutomation | https://www.tradingview.com/u/TradeAutomation/ | 259 | 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="ETF 3-Day Reversion Strategy", shorttitle="ETF 3-Day Reversion Strategy", process_orders_on_close=true, overlay=true, commission_type=strategy.commission.cash_per_order, commission_value=1, initial_capital = 10000000, default_qty_type=strategy.percent_of_equity, default_qty_value=100)
// Backtest Date Range Inputs //
StartTime = input.time(defval=timestamp('01 Jan 2012 05:00 +0000'), title='Start Time')
EndTime = input.time(defval=timestamp('01 Jan 2099 00:00 +0000'), title='End Time')
InDateRange = time>=StartTime and time<=EndTime
// Strategy Rules //
DayEMA5 = ta.ema(close, 5)
EMAQualInput = input.bool(false, "Only enter trades when above qualifier EMA?", tooltip="When this is selected, a trade will only be entered when the price is above the EMA qualifier line.")
QEMA = ta.ema(close, input.int(200, "EMA Trade Qualifier Length"))
EMAQualifier = close>QEMA
Rule1 = EMAQualInput==true ? EMAQualifier : close>0
Rule2 = close<DayEMA5
Rule3 = high<high[1] and low<low[1] and high[1]<high[2] and low[1]<low[2] and high[2]<high[3] and low[2]<low[3]
ExitEMA = ta.ema(close, input.int(5, "EMA Length For Exit Strategy", tooltip = "The strategy will sell when the price crosses over this EMA"))
plot(DayEMA5, "Five Period EMA")
plot(QEMA, "Qualifier EMA")
plot(ExitEMA, "Exit EMA", color=color.green)
// Entry & Exit Functions //
if (InDateRange)
strategy.entry("Long", strategy.long, when = Rule1 and Rule2 and Rule3)
strategy.close("Long", when = ta.crossover(close, ExitEMA))
if (not InDateRange)
strategy.close_all() |
5min MACD scalp by Joel | https://www.tradingview.com/script/qN11DuKy-5min-MACD-scalp-by-Joel/ | Zippy111 | https://www.tradingview.com/u/Zippy111/ | 1,479 | 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/
// © Zippy111 and inspired by the youtuber Joel on Crypto
//@version=5
strategy("5min MACD scalp by Joel (3commas)", shorttitle = "5m MACD scalp", overlay=true, margin_long=100, margin_short=100)
import ZenAndTheArtOfTrading/ZenLibrary/2 as l_zen
var g_strategy = "Strategy"
i_chkLong = input.bool(true, title = 'Long', inline ='1', group = g_strategy)
i_chkShort = input.bool(true, title = 'Short', inline='1', group= g_strategy)
i_startTime = input.time(title='Start Date', defval=timestamp('01 Jan 2020 00:00 +0100'), group=g_strategy, tooltip='Date & time to begin trading from')
i_endTime = input.time(title='End Date', defval=timestamp('1 Jan 2099 00:00 +0100'), group=g_strategy, tooltip='Date & time to stop trading')
i_longProfitPerc = input.float(title='Long TP (%)', minval=0.0, step=0.1, defval=0.5, inline='2', group= g_strategy) * 0.01
i_shortProfitPerc = input.float(title='Short TP (%)', minval=0.0, step=0.1, defval=0.5, inline='3', group= g_strategy) * 0.01
i_longStopPerc = input.float(title='Long SL (%)', minval=0.0, step=0.1, defval=0.4, inline='2', group= g_strategy) * 0.01
i_shortStopPerc = input.float(title='Short SL (%)', minval=0.0, step=0.1, defval=0.4, inline='3', group= g_strategy) * 0.01
var g_pause = "Pause trades"
i_tradePause = input.int(title= "For how many bars?", defval=0, minval = 0, group= g_pause, tooltip="Pauses trades for X bars after a closed trade\n0 = OFF")
i_tradePauseLoss = input.bool(title= "Only loosing trades", defval = true, inline = "4", group= g_pause)
i_tradeLossNum = input.int(title= "| How much?", defval=1, minval = 1, group= g_pause, inline = "4", tooltip="Number of loosing trades in a row")
var g_ema = "EMAs trend"
i_emaOpt = input.string(title = "Trend type", defval = "Ema cross", options = ["Ema cross", "Ema slow", "Ema fast"], group = g_ema, tooltip = "Ema cross - trend based on ema crosses, eg. fast above slow = long and vice versa,\nEma slow/fast - trend based on whether the close price is above/under selected ema")
i_emaFast = input.int(title = "Ema fast lenght", defval = 50, step = 5, group = g_ema)
i_emaSlow = input.int(title = "Ema slow lenght", defval = 200, step = 5, group = g_ema)
i_emaTrendBarsBack = input.int(title = "Valid cross?", defval = 350, step = 5, tooltip = "How many bars back is the cross still valid?\nWhen some of the Emas is selected as an Trend type then it counts the bars since the close price crossed above the selected ema", group = g_ema)
var g_macd = "MACD settings"
i_macdRes = input.timeframe(title = "MACD resolution", defval = "", group = g_macd)
i_macdFastLen = input.int(title="Fast Length", minval = 1, defval=12, group = g_macd)
i_macdSlowLen = input.int(title="Slow Length", minval = 1, defval=26, group = g_macd)
i_macdSignalLen = input.int(title="Signal Smoothing", minval = 1, maxval = 50, defval = 9, group = g_macd)
var g_hist = "Histogram peak finder"
i_histMin = input.float(title = "Min histogram value", defval = 0.00000, minval = 0.00000, group = g_hist, tooltip = "Minimum for a positive/negative histogram value that is taken into account.\nSet to zero if you want to turn it off.")
i_histHighestLookback = input.int(title = "Lookback period", defval = 10, minval = 1, group = g_hist)
i_useHistChk = input.bool(false, title = 'Compare with histogram average?', group = g_hist, tooltip = "Highest/Lowest hist bar - Current histogram value must be greater than 100% + X% times the average histogram")
i_histAvgLookback = input.int(title = "Avg histogram lenght", defval = 50, minval = 1, step = 5, tooltip = "Length of the histogram average, similar to MA length", group = g_hist)
i_aboveHist = input.int(title = "% above avg", defval = 50, minval = 1, step = 5, tooltip = "Histogram positive/value must be above the average * %", group = g_hist) * 0.01 + 1
var g_rsi = "RSI filter"
i_rsiChk = input.bool(false, "Use RSI Filter", group = g_rsi)
i_rsiRes = input.timeframe("", "TimeFrame", group = g_rsi)
i_rsiLen = input.int(14, "Lenght", group = g_rsi)
i_rsiMinLong = input.float(0.0, "Min for Long", minval = 0.0, maxval = 100.0, step = 0.5, group = g_rsi, inline = "6")
i_rsiMaxLong = input.float(70.0, "Max for Long", minval = 0.0, maxval = 100.0, step = 0.5, group = g_rsi, inline = "6")
i_rsiMinShort = input.float(30.0, "Min for Short", minval = 0.0, maxval = 100.0, step = 0.5, group = g_rsi, inline = "7")
i_rsiMaxShort = input.float(100.0, "Max for Short", minval = 0.0, maxval = 100.0, step = 0.5, group = g_rsi, inline = "7")
i_rsiDirectChk = input.bool(false, "RSI direction confirmation", group = g_rsi, tooltip = "Long only if its supported by rising RSI and Short only if its supported by falling RSI\nWorks only if Use RSI is ON")
i_rsiDirectLen = input.int(1, "Bars back for direction", minval = 1, group = g_rsi, tooltip = "Lookback period for RSI values")
var g_additional = "Pullback filter"
i_usePullbackChk = input.bool(false, title = 'Use Pullback filter', group = g_additional, tooltip = "This aims to chatch a possible swing low/high for a better quality position\nFor a long position it checks how many candles were in the opposite direction, so you don't enter the trade when it's been going up for a long time and vice versa")
i_pullbackCount = input.int(title="Lookback period", defval=2, minval = 1, group = g_additional)
i_pullbackBigger = input.int(title="More than", defval=2, minval = 1, group = g_additional, tooltip = "How many candles should be in the opposite direction?\nCan't be bigger than the lookback period")
var g_tester = 'Back tester table'
i_drawTester = input.bool(title='Show back tester', defval=true, group=g_tester, tooltip='Turn on/off inbuilt backtester display', inline = "backtester1")
i_testerPosition = input.string(title='', defval="Top right", options = ["Top right", "Top left", "Bottom right", "Bottom left"], group=g_tester, tooltip='Position of the backtester table', inline = "backtester1")
i_rr = input.float(title='R:R', defval=1.0, group=g_tester, tooltip='Risk:Reward profile')
startBalance = input.float(title='Starting Balance', defval=100.0, group=g_tester, tooltip='Your starting balance for the custom inbuilt tester system')
riskPerTrade = input.float(title='Risk Per Trade', defval=1.0, group=g_tester, tooltip='Your desired % risk per trade (as a whole number)')
var i_3Commas = '3Commas bot settings'
i_useComments = input.bool(false, "Show 3Commas bot comments", group = i_3Commas)
i_botIDLong = input(title="Long Bot ID", defval="", group = i_3Commas)
i_botIDShort = input(title="Short Bot ID", defval="", group = i_3Commas)
i_tokenID = input(title="Email Token", defval="", group = i_3Commas)
// Get strategy direction and set time
strategy.risk.allow_entry_in(i_chkLong and i_chkShort ? strategy.direction.all : i_chkLong ? strategy.direction.long : strategy.direction.short)
c_dateFilter = time >= i_startTime and time <= i_endTime // See if this bar's time happened within date filter
// Get Ema trend
c_emaFast = ta.ema(close, i_emaFast)
c_emaSlow = ta.ema(close, i_emaSlow)
c_emaCrossBull = ta.crossover(i_emaOpt == "Ema cross" ? c_emaFast : close, i_emaOpt == "Ema fast" ? c_emaFast : c_emaSlow)
c_emaCrossBear = ta.crossunder(i_emaOpt == "Ema cross" ? c_emaFast : close, i_emaOpt == "Ema fast" ? c_emaFast : c_emaSlow)
c_emaAbove = (i_emaOpt == "Ema cross" ? c_emaFast >= c_emaSlow : i_emaOpt == "Ema slow" ? close > c_emaSlow : close > c_emaFast)
c_emaUnder = (i_emaOpt == "Ema cross" ? c_emaFast < c_emaSlow : i_emaOpt == "Ema slow" ? close < c_emaSlow : close < c_emaFast)
c_crossBarsBackBull = ta.barssince(c_emaCrossBull)
c_crossBarsBackBear = ta.barssince(c_emaCrossBear)
// Get MACD histogram
f_rpSecurity(_symbol, _res, _src) =>
request.security(_symbol, _res, _src[barstate.isrealtime ? 1 : 0])
[_, _, c_hist] = ta.macd(f_rpSecurity("", i_macdRes, close), i_macdFastLen, i_macdSlowLen, i_macdSignalLen)
c_histBear = math.sum(c_hist > 0 ? (barstate.isrealtime ? c_hist[1] : c_hist[0]) : 0, i_histAvgLookback)
c_histBull = math.sum(c_hist < 0 ? math.abs(barstate.isrealtime ? c_hist[1] : c_hist[0]) : 0, i_histAvgLookback)
c_histBearAvg = (c_histBear / math.sum(c_hist > 0 ? 1 : 0, i_histAvgLookback))
c_histBullAvg = (c_histBull / math.sum(c_hist < 0 ? 1 : 0, i_histAvgLookback))
c_rsiSrc = f_rpSecurity("", i_rsiRes, close)
c_rsi = ta.rsi(c_rsiSrc, i_rsiLen)
// Sub-Condition calculations
c_histMinLong = math.abs(c_hist) > i_histMin
c_histMinShort = c_hist > i_histMin
c_aboveHistAvgLong = math.abs(c_hist) >= i_aboveHist * c_histBullAvg
c_aboveHistAvgShort = c_hist >= (i_aboveHist * c_histBearAvg)
c_histHighest = ta.highestbars(c_hist, i_histHighestLookback) == 0 or ta.highestbars(c_hist, i_histHighestLookback)[1] == 0
c_histLowest = ta.highestbars(math.abs(c_hist), i_histHighestLookback) == 0 or ta.lowestbars(math.abs(c_hist), i_histHighestLookback)[1] == 0
c_pullbackCountGreen = l_zen.getPullbackBarCount(i_pullbackCount, 1)
c_pullbackCountRed = l_zen.getPullbackBarCount(i_pullbackCount, -1)
c_rsiRising = ta.rising(c_rsi, i_rsiDirectLen)
c_rsiFalling = ta.falling(c_rsi, i_rsiDirectLen)
c_sinceLastTrade = ta.barssince(strategy.closedtrades > strategy.closedtrades[1])
c_sinceLastLossTrade = ta.barssince(strategy.losstrades > strategy.losstrades[1])
var c_countLosstrades = 0
switch
strategy.losstrades > strategy.losstrades[1] => c_countLosstrades += 1
strategy.wintrades > strategy.wintrades[1] => c_countLosstrades := 0
c_countLosstrades == i_tradeLossNum and c_sinceLastLossTrade > i_tradePause => c_countLosstrades := 0
c_emaCrossBull or c_emaCrossBear => c_countLosstrades := 0
// Final Long/Short conditions
c_longCondition = c_dateFilter and
(i_tradePauseLoss ? (i_tradePause != 0 ? c_countLosstrades < i_tradeLossNum : true) and (strategy.losstrades != 0 ? c_sinceLastLossTrade >= i_tradePause : true) : (strategy.closedtrades != 0 ? c_sinceLastTrade >= i_tradePause : true)) and
(c_emaAbove and (c_crossBarsBackBull <= i_emaTrendBarsBack)) and
(i_rsiChk ? (c_rsi >= i_rsiMinLong and c_rsi <= i_rsiMaxLong and (i_rsiDirectChk ? c_rsiRising : true)) : true) and
((c_hist < 0 and c_histMinLong ? c_histLowest : false) and (i_useHistChk ? c_aboveHistAvgLong : true)) and
(i_usePullbackChk ? (c_pullbackCountRed >= i_pullbackBigger) : true)
c_shortCondition = c_dateFilter and
(i_tradePauseLoss ? (i_tradePause != 0 ? c_countLosstrades < i_tradeLossNum : true) and (strategy.losstrades != 0 ? c_sinceLastLossTrade >= i_tradePause : true) : (strategy.closedtrades != 0 ? c_sinceLastTrade >= i_tradePause : true)) and
(c_emaUnder and (c_crossBarsBackBear <= i_emaTrendBarsBack)) and
(i_rsiChk ? (c_rsi >= i_rsiMinShort and c_rsi <= i_rsiMaxShort and (i_rsiDirectChk ? c_rsiFalling : true)) : true) and
((c_hist >= 0 and c_histMinShort ? c_histHighest : false) and (i_useHistChk ? c_aboveHistAvgShort : true)) and
(i_usePullbackChk ? (c_pullbackCountGreen >= i_pullbackBigger) : true)
c_longExitPrice = strategy.position_avg_price * (1 + i_longProfitPerc)
c_shortExitPrice = strategy.position_avg_price * (1 - i_shortProfitPerc)
c_longStopPrice = strategy.position_avg_price * (1 - i_longStopPerc)
c_shortStopPrice = strategy.position_avg_price * (1 + i_shortStopPerc)
if c_longCondition and strategy.opentrades == 0
strategy.entry(
id = "LONG open",
direction = strategy.long,
comment = i_useComments ? '{\n "action": "start_bot_and_start_deal",\n "message_type": "bot",\n "bot_id": ' + str.tostring(i_botIDLong) + ',\n "email_token": "' + str.tostring(i_tokenID) + '",\n "delay_seconds": 0}' : na)
strategy.exit(
id = "Long close",
from_entry = "LONG open",
limit = c_longExitPrice,
stop = c_longStopPrice,
when = strategy.opentrades != 0,
comment = i_useComments ? '{\n "action": "close_at_market_price_all_and_stop_bot",\n "message_type": "bot",\n "bot_id": ' + str.tostring(i_botIDLong) + ',\n "email_token": "' + str.tostring(i_tokenID) + '",\n "delay_seconds": 0}' : na)
if c_shortCondition and strategy.opentrades == 0
strategy.entry(
id = "SHORT open",
direction = strategy.short,
comment = i_useComments ? '{\n "action": "start_bot_and_start_deal",\n "message_type": "bot",\n "bot_id": ' + str.tostring(i_botIDShort) + ',\n "email_token": "' + str.tostring(i_tokenID) + '",\n "delay_seconds": 0}' : na)
strategy.exit(
id = "Short close",
from_entry = "SHORT open",
limit = c_shortExitPrice,
stop = c_shortStopPrice,
when = strategy.opentrades != 0,
comment = i_useComments ? '{\n "action": "close_at_market_price_all_and_stop_bot",\n "message_type": "bot",\n "bot_id": ' + str.tostring(i_botIDShort) + ',\n "email_token": "' + str.tostring(i_tokenID) + '",\n "delay_seconds": 0}' : na)
// Plotting emas
plot(c_emaFast, "Ema fast", color = color.new(#4db6ac, 40), linewidth = 2, display = display.none)
plot(c_emaSlow, "Ema slow", color = color.new(#f57c00, 40), linewidth = 2, display = display.none)
// --- BEGIN TESTER CODE --- //
// Declare performance tracking variables
var balance = startBalance
var maxBalance = 0.0
var totalWins = 0
var totalLoss = 0
// Detect winning trades
if strategy.wintrades != strategy.wintrades[1]
balance := balance + riskPerTrade / 100 * balance * i_rr
totalWins := totalWins + 1
if balance > maxBalance
maxBalance := balance
maxBalance
// Detect losing trades
if strategy.losstrades != strategy.losstrades[1]
balance := balance - riskPerTrade / 100 * balance
totalLoss := totalLoss + 1
// Prepare stats table
var table testTable = table.new(i_testerPosition == "Top right" ? position.top_right : i_testerPosition == "Top left" ? position.top_left : i_testerPosition == "Bottom right" ? position.bottom_right :position.bottom_left, 5, 2, border_width=2)
f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) =>
_cellText = _title + '\n' + _value
table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor)
// Draw stats table
var bgcolor = color.new(color.black, 0)
if i_drawTester
if barstate.islastconfirmedhistory
// Update table
dollarReturn = balance - startBalance
f_fillCell(testTable, 0, 0, 'Total Trades:', str.tostring(strategy.closedtrades), bgcolor, color.white)
f_fillCell(testTable, 0, 1, 'Win Rate:', str.tostring(l_zen.truncate(strategy.wintrades / strategy.closedtrades * 100, 2)) + '%', (strategy.wintrades / strategy.closedtrades * 100) >= 50 ? color.green : bgcolor, color.white)
f_fillCell(testTable, 1, 0, 'Starting:', '$' + str.tostring(startBalance), bgcolor, color.white)
f_fillCell(testTable, 1, 1, 'Ending:', '$' + str.tostring(l_zen.truncate(balance, 2)), balance > startBalance ? color.green : bgcolor, color.white)
// --- END BACKTESTER CODE --- //
|
Simple EMA Crossing Strategy TradeMath | https://www.tradingview.com/script/DRWHQo6J-simple-ema-crossing-strategy-trademath/ | TheHulkTrading | https://www.tradingview.com/u/TheHulkTrading/ | 210 | 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/
// © TheHulkTrading
// Simple EMA strategy for BTCUSDT, timeframe - 1H. Based on crossing EMA21 and EMA55
//@version=4
strategy("Simple EMA Crossing Strategy ", overlay=true)
//Percent for stop loss, recommended = 3%
percent_loss = input(3, minval=1, title="Stop Loss")
//Ema's
emaFast=ema(close,21)
emaSlow=ema(close,55)
//Long Contition is crossover ema21 and ema55
longCond = crossover(emaFast,emaSlow)
//Stop level based on input percent_loss, default = 3%
stop_level_long = strategy.position_avg_price*((100-percent_loss)/100)
//Take profit - x3 of percent loss, default = 9%
take_level_long = strategy.position_avg_price*((100+percent_loss*3)/100)
//Entries and exits
strategy.entry("Long", strategy.long, when=longCond)
strategy.exit("Stop Loss/TP","Long", stop=stop_level_long, limit = take_level_long)
|
Fractal Breakout Strategy [KL] | https://www.tradingview.com/script/agyP7x3R-Fractal-Breakout-Strategy-KL/ | DojiEmoji | https://www.tradingview.com/u/DojiEmoji/ | 800 | 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/
// © DojiEmoji
//@version=5
strategy("Fractal Strat [KL] ", overlay=true, pyramiding=1, initial_capital=1000000000, default_qty_type=strategy.percent_of_equity, default_qty_value=5)
var string ENUM_LONG = "Long"
var string GROUP_ENTRY = "Entry"
var string GROUP_TSL = "Stop loss"
var string GROUP_ORDER = "Order size and Profit taking"
backtest_timeframe_start = input.time(defval=timestamp("01 Apr 2000 13:30 +0000"), title="Backtest Start Time")
within_timeframe = time >= backtest_timeframe_start
// TSL: calculate the stop loss price. {
_multiple = input(2.0, title="ATR Multiplier for trailing stop loss", group=GROUP_TSL)
ATR_TSL = ta.atr(input(14, title="Length of ATR for trailing stop loss", group=GROUP_TSL, tooltip="Initial risk amount = atr(this length) x multiplier")) * _multiple
TSL_source = low
TSL_line_color = color.green
TSL_transp = 100
var stop_loss_price = float(0)
var float initial_entry_p = float(0)
var float risk_amt = float(0)
var float initial_order_size = float(0)
if strategy.position_size == 0 or not within_timeframe
TSL_line_color := color.black
stop_loss_price := TSL_source - ATR_TSL
else if strategy.position_size > 0
stop_loss_price := math.max(stop_loss_price, TSL_source - ATR_TSL)
TSL_transp := 0
plot(stop_loss_price, color=color.new(TSL_line_color, TSL_transp))
// } end of "TSL" block
// Profit taking {
var bool tp_mode = input(true, title="Take profit and different levels", group=GROUP_ORDER)
var float FIRST_LVL_PROFIT = input.float(1, title="First level profit", tooltip="Relative to risk. Example: entry at $10 and inital stop loss at $9. Taking first level profit at 1R means taking profits at $11", group=GROUP_ORDER)
var float SECOND_LVL_PROFIT = input.float(2, title="Second level profit", tooltip="Relative to risk. Example: entry at $10 and inital stop loss at $9. Taking second level profit at 2R means taking profits at $12", group=GROUP_ORDER)
var float THIRD_LVL_PROFIT = input.float(3, title="Third level profit", tooltip="Relative to risk. Example: entry at $10 and inital stop loss at $9. Taking third level profit at 3R means taking profits at $13", group=GROUP_ORDER)
// }
// Fractals {
// Modified from synapticEx's implementation: https://www.tradingview.com/script/cDCNneRP-Fractal-Support-Resistance-Fixed-Volume-2/
rel_vol_len = 6 // Relative volume is used; the middle candle has to have volume above the average (say sma over prior 6 bars)
rel_vol = ta.sma(volume, rel_vol_len)
_up = high[3]>high[4] and high[4]>high[5] and high[2]<high[3] and high[1]<high[2] and volume[3]>rel_vol[3]
_down = low[3]<low[4] and low[4]<low[5] and low[2]>low[3] and low[1]>low[2] and volume[3]>rel_vol[3]
fractal_resistance = high[3], fractal_support = low[3] // initialize
fractal_resistance := _up ? high[3] : fractal_resistance[1]
fractal_support := _down ? low[3] : fractal_support[1]
plot(fractal_resistance, "fractal_resistance", color=color.new(color.red,50), linewidth=2, style=plot.style_cross, offset =-3, join=false)
plot(fractal_support, "fractal_support", color=color.new(color.lime,50), linewidth=2, style=plot.style_cross, offset=-3, join=false)
// }
// ATR diversion test {
// Hypothesis testing (2-tailed):
//
// Null hypothesis (H0) and Alternative hypothesis (Ha):
// H0 : atr_fast equals atr_slow
// Ha : atr_fast not equals to atr_slow; implies atr_fast is either too low or too high
len_fast = input(5,title="Length of ATR (fast) for diversion test", group=GROUP_ENTRY)
atr_fast = ta.atr(len_fast)
atr_slow = ta.atr(input(50,title="Length of ATR (slow) for diversion test", group=GROUP_ENTRY, tooltip="This needs to be larger than Fast"))
// Calculate test statistic (test_stat)
std_error = ta.stdev(ta.tr, len_fast) / math.pow(len_fast, 0.5)
test_stat = (atr_fast - atr_slow) / std_error
// Compare test_stat against critical value defined by user in settings
//critical_value = input.float(1.645,title="Critical value", tooltip="Strategy uses 2-tailed test to compare atr_fast vs atr_slow. Null hypothesis (H0) is that both should equal. Based on the computed test statistic value, if absolute value of it is +/- this critical value, then H0 will be rejected.", group=GROUP_ENTRY)
conf_interval = input.string(title="Confidence Interval", defval="95%", options=["90%","95%","99%"], tooltip="Critical values of 1.645, 1.96, 2.58, for CI=90%/95%/99%, respectively; Under 2-tailed test to compare atr_fast vs atr_slow. Null hypothesis (H0) is that both should equal. Based on the computed test statistic value, if absolute value of it is +/- critical value, then H0 will be rejected.")
critical_value = conf_interval == "90%" ? 1.645 : conf_interval == "95%" ? 1.96 : 2.58
reject_H0_lefttail = test_stat < -critical_value
reject_H0_righttail = test_stat > critical_value
// } end of "ATR diversion test" block
// Entry Signals
entry_signal_long = close >= fractal_support and reject_H0_lefttail
// MAIN {
// Update the stop limit if strategy holds a position.
if strategy.position_size > 0
strategy.exit(ENUM_LONG, comment="SL", stop=stop_loss_price)
// Entry
if within_timeframe and entry_signal_long and strategy.position_size == 0
initial_entry_p := close
risk_amt := ATR_TSL
strategy.entry(ENUM_LONG, strategy.long)
var int TP_taken_count = 0
if tp_mode and close > strategy.position_avg_price
if close >= initial_entry_p + THIRD_LVL_PROFIT * risk_amt and TP_taken_count == 2
strategy.close(ENUM_LONG, comment="TP Lvl3", qty=math.floor(strategy.position_size / 3))
TP_taken_count := TP_taken_count + 1
else if close >= initial_entry_p + SECOND_LVL_PROFIT * risk_amt and TP_taken_count == 1
strategy.close(ENUM_LONG, comment="TP Lvl2", qty=math.floor(strategy.position_size / 3))
TP_taken_count := TP_taken_count + 1
else if close >= initial_entry_p + FIRST_LVL_PROFIT * risk_amt and TP_taken_count == 0
strategy.close(ENUM_LONG, comment="TP Lvl1", qty=math.floor(strategy.position_size / 3))
TP_taken_count := TP_taken_count + 1
// Alerts
_atr = ta.atr(14)
alert_helper(msg) =>
prefix = "[" + syminfo.root + "] "
suffix = "(P=" + str.tostring(close, "#.##") + "; atr=" + str.tostring(_atr, "#.##") + ")"
alert(str.tostring(prefix) + str.tostring(msg) + str.tostring(suffix), alert.freq_once_per_bar)
if strategy.position_size > 0 and ta.change(strategy.position_size)
if strategy.position_size > strategy.position_size[1]
alert_helper("BUY")
else if strategy.position_size < strategy.position_size[1]
alert_helper("SELL")
// Clean up - set the variables back to default values once no longer in use
if ta.change(strategy.position_size) and strategy.position_size == 0
TP_taken_count := 0
initial_entry_p := float(0)
risk_amt := float(0)
initial_order_size := float(0)
stop_loss_price := float(0)
// } end of MAIN block
|
Hull MA TimeFrame CrossOver | https://www.tradingview.com/script/KdC6xqb8-Hull-MA-TimeFrame-CrossOver/ | SeaSide420 | https://www.tradingview.com/u/SeaSide420/ | 917 | 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/
// © @SeaSide420
//@version=5
strategy('HullTimeFrameCrossOver', shorttitle='H&TF', overlay=true, currency="BTC",initial_capital=1, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_value=0.1, commission_type=strategy.commission.percent)
stfu = "Select Time Frame for Candle crossover (close>close[1]=buy else sell)"
ptt = "Recommended to use OPEN as source to avoid repainting (OPEN is a set value each candle, where as a CLOSE value changes with each tick for the duration of the candle)"
masmthng = "Select type of Moving Average"
prdtt = "Amount of candles back to use with calculation"
atrsnstt = "Basicly, adjusts ATR SL distance from candles"
tph = "Close order when user set % in Profit"
slh = "Close order when user set % in Loss"
btt = "If selected, Buying is allowed"
stt = "If selected, Selling is allowed"
res = input.timeframe(title='Candle X Resolution', defval='D', tooltip=stfu)
price = input(title='Source of Price', defval=open, tooltip=ptt)
smoothing = input.string(title="Moving Average Type", defval="HMA", options=["ALMA", "SMA", "EMA", "WMA", "HMA"], tooltip=masmthng)
MA_Period = input.int(title='Moving Average Period', defval=1000, minval=3, tooltip = prdtt)
atrsens = input.float(14, title='ATR sensitivity',tooltip=atrsnstt)
atrperiod = input.int(14, title='ATR Period', tooltip = prdtt)
TakeProfit = input(title='Take Profit (%)', defval=1000, tooltip=tph)
StopLoss = input(title='StopLoss (%)', defval=1000, tooltip=slh)
uatrh = "If selected, StopLoss will be the ATR line"
UseATRSL = input.bool(defval=false, title='Use ATR SL?', tooltip=uatrh)
AllowBuy = input.bool(defval=true, title='Allow Buy?', tooltip=btt)
AllowSell = input.bool(defval=true, title='Allow Sell?', tooltip=stt)
balance = strategy.initial_capital + strategy.netprofit
TP = TakeProfit / 100 * balance
SL = StopLoss / 100 * balance - StopLoss / 100 * balance * 2
ma_function(price, MA_Period) =>
switch smoothing
"ALMA" => ta.alma(price, MA_Period, 0.85, 6)
"SMA" => ta.sma(price, MA_Period)
"EMA" => ta.ema(price, MA_Period)
"WMA" => ta.wma(price, MA_Period)
=> ta.hma(price, MA_Period)
ma = ma_function(price, MA_Period)
ma0 = ma_function(price, 2)
ma1 = ma_function(price, MA_Period)
ma2 = ma_function(price[1], MA_Period)
D1 = request.security(syminfo.tickerid, res, price, barmerge.gaps_off, barmerge.lookahead_off)
xATR = ta.atr(atrperiod)
nLoss = atrsens * xATR
xATRTrailingStop = 0.0
iff_1 = price > nz(xATRTrailingStop[1], 0) ? price - nLoss : price + nLoss
iff_2 = price < nz(xATRTrailingStop[1], 0) and price[1] < nz(xATRTrailingStop[1], 0) ? math.min(nz(xATRTrailingStop[1]), price + nLoss) : iff_1
xATRTrailingStop := price > nz(xATRTrailingStop[1], 0) and price[1] > nz(xATRTrailingStop[1], 0) ? math.max(nz(xATRTrailingStop[1]), price - nLoss) : iff_2
pos = 0
iff_3 = price[1] > nz(xATRTrailingStop[1], 0) and price < nz(xATRTrailingStop[1], 0) ? -1 : nz(pos[1], 0)
pos := price[1] < nz(xATRTrailingStop[1], 0) and price > nz(xATRTrailingStop[1], 0) ? 1 : iff_3
above = ta.crossover(ma, xATRTrailingStop)
below = ta.crossover(xATRTrailingStop, ma)
longCondition = ma1 > ma2 and ma0 > D1 and ma0 > ma1
shortCondition = ma1 < ma2 and ma0 < D1 and ma0 < ma1
clr1 = price > D1 ? color.green : color.red
clr2 = ma1 > ma2 ? color.red : color.green
plot(ta.cross(ma1, ma2) ? ma1 : na, label.style_cross, color=clr2, linewidth=3)
plot(ta.cross(ma1, D1) ? ma1 : na, label.style_cross, color=clr1, linewidth=3)
plot(D1, color=clr1, title='C_X', linewidth=2)
plot(xATRTrailingStop, color=color.black, title='ATR SL', linewidth=3)
strategy.close('buy', when=strategy.openprofit > TP, comment='buy TP',alert_message='buy TP')
strategy.close('buy', when=strategy.openprofit < SL, comment='buy SL',alert_message='buy SL')
strategy.close('sell', when=strategy.openprofit > TP, comment='sell TP',alert_message='sell TP')
strategy.close('sell', when=strategy.openprofit < SL, comment='sell SL',alert_message='sell SL')
if UseATRSL
strategy.close_all(when=(price > xATRTrailingStop and above) or (price < xATRTrailingStop and below), comment='ATR SL',alert_message='ATR SL')
if AllowBuy and longCondition and above
strategy.entry('buy', strategy.long,comment='buy',alert_message='buy')
if AllowSell and shortCondition and below
strategy.entry('sell', strategy.short,comment='sell',alert_message='sell') |
Contrarian Scalping Counter Trend Bb Envelope Adx and Stochastic | https://www.tradingview.com/script/F0N0DW9A-Contrarian-Scalping-Counter-Trend-Bb-Envelope-Adx-and-Stochastic/ | exlux99 | https://www.tradingview.com/u/exlux99/ | 265 | 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/
// © exlux99
//@version=5
strategy("Contrarian Scalping Counter Trend",overlay=true)
//bollinger bands
length = input.int(20, minval=1, title="Length BB")
src = input(close, title="Source")
mult = input.float(2.0, minval=0.001, maxval=50, title="StdDev BB")
basis = ta.sma(src, length)
dev = mult * ta.stdev(src, length)
upper = basis + dev
lower = basis - dev
//envelope
len = input.int(20, title="Length Envelope", minval=1)
percent = input(1.0)
exponential = input(false)
envelope = exponential ? ta.ema(src, len) : ta.sma(src, len)
k = percent/100.0
upper_env = envelope * (1 + k)
lower_env = envelope * (1 - k)
//adx
adxlen = input(14, title="ADX Smoothing")
dilen = input(14, title="DI Length")
dirmov(len) =>
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)
plus = fixnan(100 * ta.rma(plusDM, len) / truerange)
minus = fixnan(100 * ta.rma(minusDM, len) / truerange)
[plus, minus]
adx(dilen, adxlen) =>
[plus, minus] = dirmov(dilen)
sum = plus + minus
adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), adxlen)
sig = adx(dilen, adxlen)
//stochastic
periodK = input.int(50, title="%K Length", minval=1)
smoothK = input.int(20, title="%K Smoothing", minval=1)
stock = ta.sma(ta.stoch(close, high, low, periodK), smoothK)
short=close> upper and close >upper_env and sig < 30 and stock > 50
long=close< lower and close <lower_env and sig < 30 and stock < 50
short_exit= close < lower or close<lower_env or stock <50
long_exit=close > lower or close>lower_env or stock >50
strategy.entry("short",strategy.short,when=short)
strategy.close("short",when=short_exit)
strategy.entry("long",strategy.long,when=long)
strategy.close('long',when=long_exit)
|
Multi MA Trend Following Strategy Template | https://www.tradingview.com/script/tzykpyCd-Multi-MA-Trend-Following-Strategy-Template/ | TradeAutomation | https://www.tradingview.com/u/TradeAutomation/ | 760 | 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="Multi MA Trend Following Strategy", shorttitle="Multi Trend", process_orders_on_close=true, overlay=true, commission_type=strategy.commission.cash_per_order, commission_value=1, slippage = 0, margin_short = 75, margin_long = 75, initial_capital = 1000000, default_qty_type=strategy.percent_of_equity, default_qty_value=100)
// Backtest Date Range Inputs //
StartTime = input.time(defval=timestamp('01 Jan 2019 05:00 +0000'), group="Date Range", title='Start Time')
EndTime = input.time(defval=timestamp('01 Jan 2099 00:00 +0000'), group="Date Range", title='End Time')
InDateRange = time>=StartTime and time<=EndTime
// Trend Selector //
TrendSelectorInput = input.string(title="Trend Selector", defval="JMA", group="Core Settings", options=["ALMA", "DEMA", "DSMA", "EMA", "HMA", "JMA", "KAMA", "Linear Regression (LSMA)", "RMA", "SMA", "SMMA", "Source", "SuperTrend", "TEMA", "TMA", "VAMA", "VIDYA", "VMA", "VWMA", "WMA", "WWMA", "ZLEMA"], tooltip="Select your moving average")
src = input.source(close, "Source", group="Core Settings", tooltip="This is the price source being used for the moving averages to calculate based on")
length = input.int(200, "MA Length", group="Core Settings", tooltip="This is the amount of historical bars being used for the moving averages to calculate based on", step=5)
LineWidth = input.int(2, "Line Width", group="Core Settings", tooltip="This is the width of the line plotted that represents the selected trend")
// Individual Moving Average / Regression Setting //
AlmaOffset = input.float(0.85, "ALMA Offset", group="Individual MA Settings", tooltip="This only applies when ALMA is selected")
AlmaSigma = input.float(6, "ALMA Sigma", group="Individual MA Settings", tooltip="This only applies when ALMA is selected")
ATRFactor = input.float(3, "ATR Multiplier For SuperTrend", group="Individual MA Settings", tooltip="This only applies when SuperTrend is selected")
ATRLength = input.int(12, "ATR Length For SuperTrend", group="Individual MA Settings", tooltip="This only applies when SuperTrend is selected")
ssfLength = input.int(20, "DSMA Super Smoother Filter Length", minval=1, defval=20, tooltip="This only applies when EDSMA is selected")
ssfPoles = input.int(2, "DSMA Super Smoother Filter Poles", options=[2, 3], tooltip="This only applies when EDSMA is selected")
JMApower = input.int(2, "JMA Power Parameter", group="Individual MA Settings", tooltip="This only applies when JMA is selected")
phase = input.int(-45, title="JMA Phase Parameter", step=10, minval=-110, maxval=110, group="Individual MA Settings", tooltip="This only applies when JMA is selected")
KamaAlpha = input.float(3, "KAMA's Alpha", minval=1,step=0.5, group="Individual MA Settings", tooltip="This only applies when KAMA is selected")
LinRegOffset = input.int(0, "Linear Regression Offset", group="Individual MA Settings", tooltip="This only applies when Linear Regression is selected")
VAMALookback =input.int(12, "VAMA Volatility lookback", group="Individual MA Settings", tooltip="This only applies when VAMA is selected")
// Trend Indicators in Library //
ALMA = ta.alma(src, length, AlmaOffset, AlmaSigma)
EMA = ta.ema(src, length)
HMA = ta.hma(src, length)
LinReg = ta.linreg(src, length, LinRegOffset)
RMA = ta.rma(src, length)
SMA = ta.sma(src, length)
VWMA = ta.vwma(src, length)
WMA = ta.wma(src, length)
// Additional Trend Indicators Written and/or Open Sourced //
//DEMA
de1 = ta.ema(src, length)
de2 = ta.ema(de1, length)
DEMA = 2 * de1 - de2
// Ehlers Deviation-Scaled Moving Average - DSMA [Everget]
PI = 2 * math.asin(1)
get2PoleSSF(src, length) =>
arg = math.sqrt(2) * PI / length
a1 = math.exp(-arg)
b1 = 2 * a1 * math.cos(arg)
c2 = b1
c3 = -math.pow(a1, 2)
c1 = 1 - c2 - c3
ssf = 0.0
ssf := c1 * src + c2 * nz(ssf[1]) + c3 * nz(ssf[2])
get3PoleSSF(src, length) =>
arg = PI / length
a1 = math.exp(-arg)
b1 = 2 * a1 * math.cos(1.738 * arg)
c1 = math.pow(a1, 2)
coef2 = b1 + c1
coef3 = -(c1 + b1 * c1)
coef4 = math.pow(c1, 2)
coef1 = 1 - coef2 - coef3 - coef4
ssf = 0.0
ssf := coef1 * src + coef2 * nz(ssf[1]) + coef3 * nz(ssf[2]) + coef4 * nz(ssf[3])
zeros = src - nz(src[2])
avgZeros = (zeros + zeros[1]) / 2
// Ehlers Super Smoother Filter
ssf = ssfPoles == 2
? get2PoleSSF(avgZeros, ssfLength)
: get3PoleSSF(avgZeros, ssfLength)
// Rescale filter in terms of Standard Deviations
stdev = ta.stdev(ssf, length)
scaledFilter = stdev != 0
? ssf / stdev
: 0
alpha1 = 5 * math.abs(scaledFilter) / length
EDSMA = 0.0
EDSMA := alpha1 * src + (1 - alpha1) * nz(EDSMA[1])
//JMA [Everget]
phaseRatio = phase < -100 ? 0.5 : phase > 100 ? 2.5 : phase / 100 + 1.5
beta = 0.45 * (length - 1) / (0.45 * (length - 1) + 2)
alpha = math.pow(beta, JMApower)
var JMA = 0.0
var e0 = 0.0
e0 := (1 - alpha) * src + alpha * nz(e0[1])
var e1 = 0.0
e1 := (src - e0) * (1 - beta) + beta * nz(e1[1])
var e2 = 0.0
e2 := (e0 + phaseRatio * e1 - nz(JMA[1])) * math.pow(1 - alpha, 2) + math.pow(alpha, 2) * nz(e2[1])
JMA := e2 + nz(JMA[1])
//KAMA
var KAMA = 0.0
fastAlpha = 2.0 / (KamaAlpha + 1)
slowAlpha = 2.0 / 31
momentum = math.abs(ta.change(src, length))
volatility = math.sum(math.abs(ta.change(src)), length)
efficiencyRatio = volatility != 0 ? momentum / volatility : 0
smoothingConstant = math.pow((efficiencyRatio * (fastAlpha - slowAlpha)) + slowAlpha, 2)
KAMA := nz(KAMA[1], src) + smoothingConstant * (src - nz(KAMA[1], src))
//SMMA
var SMMA = 0.0
SMMA := na(SMMA[1]) ? ta.sma(src, length) : (SMMA[1] * (length - 1) + src) / length
//SuperTrend
ATR = ta.atr(ATRLength)
Signal = ATRFactor*ATR
var SuperTrend = 0.0
SuperTrend := if src>SuperTrend[1] and src[1]>SuperTrend[1]
math.max(SuperTrend[1], src-Signal)
else if src<SuperTrend[1] and src[1]<SuperTrend[1]
math.min(SuperTrend[1], src+Signal)
else if src>SuperTrend[1]
src-Signal
else
src+Signal
//TEMA
t1 = ta.ema(src, length)
t2 = ta.ema(t1, length)
t3 = ta.ema(t2, length)
TEMA = 3 * (t1 - t2) + t3
//TMA
TMA = ta.sma(ta.sma(src, math.ceil(length / 2)), math.floor(length / 2) + 1)
//VAMA
mid=ta.ema(src,length)
dev=src-mid
vol_up=ta.highest(dev,VAMALookback)
vol_down=ta.lowest(dev,VAMALookback)
VAMA = mid+math.avg(vol_up,vol_down)
//VIDYA [KivancOzbilgic]
var VIDYA=0.0
VMAalpha=2/(length+1)
ud1=src>src[1] ? src-src[1] : 0
dd1=src<src[1] ? src[1]-src : 0
UD=math.sum(ud1,9)
DD=math.sum(dd1,9)
CMO=nz((UD-DD)/(UD+DD))
VIDYA := na(VIDYA[1]) ? ta.sma(src, length) : nz(VMAalpha*math.abs(CMO)*src)+(1-VMAalpha*math.abs(CMO))*nz(VIDYA[1])
//VMA [LazyBear]
sc = 1/length
pdm = math.max((src - src[1]), 0)
mdm = math.max((src[1] - src), 0)
var pdmS = 0.0
var mdmS = 0.0
pdmS := ((1 - sc)*nz(pdmS[1]) + sc*pdm)
mdmS := ((1 - sc)*nz(mdmS[1]) + sc*mdm)
s = pdmS + mdmS
pdi = pdmS/s
mdi = mdmS/s
var pdiS = 0.0
var mdiS = 0.0
pdiS := ((1 - sc)*nz(pdiS[1]) + sc*pdi)
mdiS := ((1 - sc)*nz(mdiS[1]) + sc*mdi)
d = math.abs(pdiS - mdiS)
s1 = pdiS + mdiS
var iS = 0.0
iS := ((1 - sc)*nz(iS[1]) + sc*d/s1)
hhv = ta.highest(iS, length)
llv = ta.lowest(iS, length)
d1 = hhv - llv
vi = (iS - llv)/d1
var VMA=0.0
VMA := na(VMA[1]) ? ta.sma(src, length) : sc*vi*src + (1 - sc*vi)*nz(VMA[1])
//WWMA
var WWMA=0.0
WWMA := (1/length)*src + (1-(1/length))*nz(WWMA[1])
//Zero Lag EMA
EMA1 = ta.ema(src,length)
EMA2 = ta.ema(EMA1,length)
Diff = EMA1 - EMA2
ZLEMA = EMA1 + Diff
// Trend Mapping and Plotting //
Trend = TrendSelectorInput == "ALMA" ? ALMA : TrendSelectorInput == "DEMA" ? DEMA : TrendSelectorInput == "DSMA" ? EDSMA : TrendSelectorInput == "EMA" ? EMA : TrendSelectorInput == "HMA" ? HMA : TrendSelectorInput == "JMA" ? JMA : TrendSelectorInput == "KAMA" ? KAMA : TrendSelectorInput == "Linear Regression (LSMA)" ? LinReg : TrendSelectorInput == "RMA" ? RMA : TrendSelectorInput == "SMA" ? SMA : TrendSelectorInput == "SMMA" ? SMMA : TrendSelectorInput == "Source" ? src : TrendSelectorInput == "SuperTrend" ? SuperTrend : TrendSelectorInput == "TEMA" ? TEMA : TrendSelectorInput == "TMA" ? TMA : TrendSelectorInput == "VAMA" ? VAMA : TrendSelectorInput == "VIDYA" ? VIDYA : TrendSelectorInput == "VMA" ? VMA : TrendSelectorInput == "VWMA" ? VWMA : TrendSelectorInput == "WMA" ? WMA : TrendSelectorInput == "WWMA" ? WWMA : TrendSelectorInput == "ZLEMA" ? ZLEMA : SMA
plot(Trend, color=(Trend>Trend[1]) ? color.green : (Trend<Trend[1]) ? color.red : (Trend==Trend[1]) ? color.gray : color.black, linewidth=LineWidth)
//Short & Long Options
Long = input.bool(true, "Model Long Trades")
Short = input.bool(false, "Model Short Trades")
//Increases Trend Accuracy
AccuTrend = (Trend*1000)
// Entry & Exit Functions //
if (InDateRange and Long==true)
strategy.entry("Long", strategy.long, when = ta.crossover(AccuTrend, AccuTrend[1]))
strategy.close("Long", when = ta.crossunder(AccuTrend, AccuTrend[1]))
if (InDateRange and Short==true)
strategy.entry("Short", strategy.short, when = ta.crossunder(AccuTrend, AccuTrend[1]))
strategy.close("Short", when = ta.crossover(AccuTrend, AccuTrend[1]))
if (not InDateRange)
strategy.close_all()
|
Correlation Strategy | https://www.tradingview.com/script/2JLkUO07-Correlation-Strategy/ | levieux | https://www.tradingview.com/u/levieux/ | 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/
// © levieux
//@version=5
strategy(title='Correlation Strategy', shorttitle='Correlation Strategy', 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)
supportLength = input.int(200, minval=1, title='Support Length')
supportSymbol = input.symbol('ETHUSDT', title='Correlated Symbol')
supportSource = input(hlc3, title='Price Source')
takeprofitLong = input.float(0.2, 'Take Profit Long', step=0.01)
takeprofitShort = input.float(0.15, 'Take Profit Short', step=0.01)
stoplossLong = input.float(0.1, 'Stop Loss Long', step=0.01)
stoplossShort = input.float(0.04, 'Stop Loss Short', step=0.01)
start = input.time(defval = timestamp("01 Jan 2016 00:00 +0000"), title = "Start Time")
end = input.time(defval = timestamp("31 Dec 2050 23:59 +0000"), title = "End Time")
supportTicker = request.security(supportSymbol, timeframe.period, supportSource, lookahead=barmerge.lookahead_off) //input(close, title="Source")
supportLine = ta.wma(supportTicker, supportLength)
window() => time >= start and time < end
if not window()
strategy.cancel_all()
supportLongPrice = close
supportShortPrice = close
if strategy.position_size > 0
supportLongPrice := supportLongPrice[1]
if strategy.position_size < 0
supportShortPrice := supportShortPrice[1]
longCondition = ta.rising(supportLine, 5) and window() and strategy.position_size <= 0
shortCondition = ta.falling(supportLine, 5) and window() and window() and strategy.position_size > 0
takeprofitLongCondition = takeprofitLong > 0 and window() and strategy.position_size > 0 and supportTicker > supportLongPrice * (1 + takeprofitLong)
stoplossLongCondition = stoplossLong > 0 and window() and strategy.position_size > 0 and supportTicker < supportLongPrice * (1 - stoplossLong)
takeprofitShortCondition = takeprofitShort > 0 and window() and strategy.position_size < 0 and supportTicker > supportShortPrice * (1 + takeprofitShort)
stoplossShortCondition = stoplossShort > 0 and window() and strategy.position_size < 0 and supportTicker < supportShortPrice * (1 - stoplossShort)
if longCondition
strategy.entry('Long', strategy.long)
supportLongPrice := supportTicker
if shortCondition
strategy.entry('Short', strategy.short)
supportShortPrice := supportTicker
if takeprofitLongCondition
strategy.close('Long')
if stoplossLongCondition
strategy.close('Long')
if takeprofitShortCondition
strategy.close('Short')
if stoplossShortCondition
strategy.close('Short')
///////////////////
// MONTHLY TABLE //
new_month = month(time) != month(time[1])
new_year = year(time) != year(time[1])
eq = strategy.equity
bar_pnl = eq / eq[1] - 1
bar_bh = (close-close[1])/close[1]
cur_month_pnl = 0.0
cur_year_pnl = 0.0
cur_month_bh = 0.0
cur_year_bh = 0.0
// Current Monthly P&L
cur_month_pnl := new_month ? 0.0 :
(1 + cur_month_pnl[1]) * (1 + bar_pnl) - 1
cur_month_bh := new_month ? 0.0 :
(1 + cur_month_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 Monthly P&Ls
var month_pnl = array.new_float(0)
var month_time = array.new_int(0)
var month_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_month_pnl[1]) and (new_month or end_time))
if (end_time[1])
array.pop(month_pnl)
array.pop(month_time)
array.push(month_pnl , cur_month_pnl[1])
array.push(month_time, time[1])
array.push(month_bh , cur_month_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])
// Monthly P&L Table
var monthly_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
monthly_table := table.new(position.bottom_right, columns = 14, rows = array.size(year_pnl) + 1, border_width = 1)
table.cell(monthly_table, 0, 0, "", bgcolor = #cccccc)
table.cell(monthly_table, 1, 0, "Jan", bgcolor = #cccccc)
table.cell(monthly_table, 2, 0, "Feb", bgcolor = #cccccc)
table.cell(monthly_table, 3, 0, "Mar", bgcolor = #cccccc)
table.cell(monthly_table, 4, 0, "Apr", bgcolor = #cccccc)
table.cell(monthly_table, 5, 0, "May", bgcolor = #cccccc)
table.cell(monthly_table, 6, 0, "Jun", bgcolor = #cccccc)
table.cell(monthly_table, 7, 0, "Jul", bgcolor = #cccccc)
table.cell(monthly_table, 8, 0, "Aug", bgcolor = #cccccc)
table.cell(monthly_table, 9, 0, "Sep", bgcolor = #cccccc)
table.cell(monthly_table, 10, 0, "Oct", bgcolor = #cccccc)
table.cell(monthly_table, 11, 0, "Nov", bgcolor = #cccccc)
table.cell(monthly_table, 12, 0, "Dec", bgcolor = #cccccc)
table.cell(monthly_table, 13, 0, "Year", bgcolor = #999999)
for yi = 0 to array.size(year_pnl) - 1
table.cell(monthly_table, 0, yi + 1, str.tostring(year(array.get(year_time, yi))), bgcolor = #cccccc)
y_color = getCellColor(array.get(year_pnl, yi), array.get(year_bh, yi))
table.cell(monthly_table, 13, yi + 1, str.tostring(math.round(array.get(year_pnl, yi) * 100)) + " (" + str.tostring(math.round(array.get(year_bh, yi) * 100)) + ")", bgcolor = y_color)
for mi = 0 to array.size(month_time) - 1
m_row = year(array.get(month_time, mi)) - year(array.get(year_time, 0)) + 1
m_col = month(array.get(month_time, mi))
m_color = getCellColor(array.get(month_pnl, mi), array.get(month_bh, mi))
table.cell(monthly_table, m_col, m_row, str.tostring(math.round(array.get(month_pnl, mi) * 100)) + " (" + str.tostring(math.round(array.get(month_bh, mi) * 100)) +")", bgcolor = m_color) |
CCI Level Zone | https://www.tradingview.com/script/5oyft5l1/ | Naruephat | https://www.tradingview.com/u/Naruephat/ | 83 | 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/
// © Naruephat
//@version=5
strategy("CCI Level Zone", overlay= false ,pyramiding = 0, default_qty_type = strategy.cash,initial_capital = 100, default_qty_value =100 , commission_value=0.1)
use_sma = input.bool( false , 'use sma( cci , len ) ' ,inline = 'u' )
len_sma = input.int( 200 , 'len' ,inline = 'u' )
GL = '<<<<[ Long ]>>>>>'
trad_Long = input.bool(true , 'Open Trad Long' ,inline = 'T' , group = GL)
level_CCI_ZON_L = input.int(30 , 'level_CCI_ZON' , step = 10,inline = 'CR', group = GL)
len_RSI_L = input.int(9 , 'len RSI Long' ,inline = 'CR', group = GL)
level_RSI_LongB = input.int(54 , 'cross B' ,inline = 'L', group = GL)
level_RSI_LongS = input.int(28 , 'cross S' ,inline = 'L', group = GL)
cross_invert_L = input.bool(true , 'invert' , inline = 'L' , group = GL)
GS = '<<<<[ Short ]>>>>>'
trad_Short = input.bool(true , 'Open Trad Short' ,inline = 'T' , group = GS)
level_CCI_ZON_S = input.int(-70 , 'level_CCI_ZON' , step = 10,inline = 'CR', group = GS)
len_RSI_S = input.int(13 , 'len RSI Long',inline = 'CR', group = GS)
level_RSI_ShortB = input.int(51 , 'cross B' , inline = 'S' , group = GS)
level_RSI_ShortS = input.int(39 , 'cross S' , inline = 'S' , group = GS)
cross_invert_S = input.bool(false , 'invert' , inline = 'S' , group = GS)
/////////////////////////////////////////////////////////[ Set Test Date ]/////////////////////////////////////////////////////////////////////////////////////////////////////
G0 = 'Set Test Date'
i_dateFilter = input.bool(false, "═════ Date Range Filtering ═════" ,group = G0)
i_fromYear = input.int(2020, "From Year ", minval = 1900 ,inline = 'd1',group = G0)
i_fromMonth = input.int(1, "From Month", minval = 1, maxval = 12,inline = 'd2',group = G0)
i_fromDay = input.int(15, "From Day ", minval = 1, maxval = 31,inline = 'd3',group = G0)
i_toYear = input.int(2023, "To Year ", minval = 1900,inline = 'd1',group = G0)
i_toMonth = input.int(12, "To Month", minval = 1, maxval = 12,inline = 'd2',group = G0)
i_toDay = input.int(31, "To Day ", minval = 1, maxval = 31,inline = 'd3',group = G0)
fromDate = timestamp(i_fromYear, i_fromMonth, i_fromDay, 00, 00)
toDate = time < timestamp(i_toYear, i_toMonth, i_toDay, 23, 59) ? time : timestamp(i_toYear, i_toMonth, i_toDay, 23, 59)
// เอา f_tradeDateIsAllowed() ไปใช้
f_tradeDateIsAllowed() => not i_dateFilter or (time >= fromDate and time <= toDate)
Win_Loss_Show = input.bool(true,'Show win loss', inline = 's')
// indicator
cci = ta.cci(ohlc4 , 1000)
sma_CCi = ta.sma(cci,len_sma)
rsi_Long = ta.rsi(close,len_RSI_L)
rsi_Short = ta.rsi(close,len_RSI_S)
sto = ta.stoch(close, high, low, 14)
// condition zone
zoneB_Long = cci > level_CCI_ZON_L and ( use_sma ? cci > sma_CCi : true )
zoneB_Short = cci < level_CCI_ZON_S and ( use_sma ? cci < sma_CCi : true )
/////////////////////////////////////////////////[ condition Long ]/////////////////////////////////////////////////
Con_Long = false
Con_close_Long = false
if cross_invert_L
Con_Long := zoneB_Long and ta.crossunder(rsi_Long , level_RSI_LongB)
Con_close_Long := ta.crossover(rsi_Long , level_RSI_LongS)
else
Con_Long := zoneB_Long and ta.crossover(rsi_Long , level_RSI_LongB)
Con_close_Long := ta.crossunder(rsi_Long , level_RSI_LongS)
// If conditions pass, remember this first. Find the opportunity to open the next order with stoch.
var con_L_perss = 0
if Con_Long and con_L_perss == 0
con_L_perss := 1
// clear con_L_perss
if strategy.position_avg_price != 0 or Con_close_Long
con_L_perss := 0
// END Condition Long
Open_Long = con_L_perss == 1 and ta.crossover(sto ,20)
/////////////////////////////////////////////////[ condition Short ]/////////////////////////////////////////////////
Con_Short = false
Con_close_Short = false
if cross_invert_S
Con_Short := zoneB_Short and ta.crossover(rsi_Short , level_RSI_ShortB)
Con_close_Short := ta.crossunder(rsi_Short , level_RSI_ShortS)
else
Con_Short := zoneB_Short and ta.crossunder(rsi_Short , level_RSI_ShortB)
Con_close_Short := ta.crossover(rsi_Short , level_RSI_ShortS)
// If conditions pass, remember this first. Find the opportunity to open the next order with stoch.
var con_S_perss = 0
if Con_Short and con_S_perss == 0
con_S_perss := 1
// clear con_S_perss
if strategy.position_avg_price != 0 or Con_close_Short
con_S_perss := 0
// END Condition
Open_Short = con_S_perss == 1 and ta.crossunder(sto, 65)
///////////////////////////////////////////////////////////////////////////////////////////////[
// this chang Alert message for u
textAlert_Long = 'textAlert Long '
textAlert_close_Long = 'textAlert Close Long '
textAlert_Short = 'textAlert_Short'
textAlert_Close_Short = 'textAlert_Close_Short'
if trad_Long
strategy.entry('L' ,strategy.long , when =f_tradeDateIsAllowed() and Open_Long , alert_message = textAlert_Long )
strategy.close('L' ,when = Con_close_Long , alert_message = textAlert_Long)
if trad_Short
strategy.entry('S', strategy.short,when =f_tradeDateIsAllowed() and Con_Short , alert_message = textAlert_Short)
strategy.close('S' ,when = Con_close_Short , alert_message = textAlert_Close_Short )
plot(cci , 'line cci', color = zoneB_Short ? color.purple : zoneB_Long ? color.green : color.new(color.gray, 50))
plot(use_sma ? sma_CCi : na, 'line hma CCi ', color = zoneB_Short ? color.purple : zoneB_Long ? color.green : color.new(color.gray, 50))
hline(350 ,'line level' , linestyle = hline.style_dotted ,color = color.new(color.green , 65 ))
hline(200 ,'line level' , linestyle = hline.style_dotted ,color = color.new(color.green , 65 ))
hline(100 ,'line level' , linestyle = hline.style_dotted ,color = color.new(color.green , 65 ))
hline(0 ,'line level' , linestyle = hline.style_dotted ,color = color.new(color.white , 50 ))
hline(-350 ,'line level' , linestyle = hline.style_dotted ,color = color.new(color.red ,65 ))
hline(-200 ,'line level' , linestyle = hline.style_dotted ,color = color.new(color.red ,65 ))
hline(-100 ,'line level' , linestyle = hline.style_dotted ,color = color.new(color.red ,65 ))
/////////////////////////////////////////////////////////[ Plot ]/////////////////////////////////////////////////////////////////////////////////////////////////////
var buy= 0.
var sell = 0.
if(ta.change(strategy.position_size) and strategy.position_size == 0)
buy := nz(strategy.closedtrades.entry_price(strategy.closedtrades-1))
sell := nz(strategy.closedtrades.exit_price(strategy.closedtrades-1))
var buy_SELL = 2
buy_SELL := strategy.position_size > 0 ? 0 : strategy.position_size < 0 ? 1 : 2
//plot(buy_SELL[1])
plotchar( Win_Loss_Show ? nz(buy_SELL[1]) == 1 and ta.change(strategy.position_size) and strategy.position_size == 0 and buy > sell : na ,location = location.top ,color = color.new(color.green, 0), char='☺' , size = size.small)
plotchar( Win_Loss_Show ? nz(buy_SELL[1]) == 1 and ta.change(strategy.position_size) and strategy.position_size == 0 and buy < sell : na ,location = location.top , color = color.new(color.red, 0), char='☹' , size = size.tiny)
plotchar( Win_Loss_Show ? nz(buy_SELL[1]) ==0 and ta.change(strategy.position_size) and strategy.position_size == 0 and buy < sell : na ,location = location.top ,color = color.new(color.green, 0), char='☺' , size = size.small)
plotchar( Win_Loss_Show ? nz(buy_SELL[1]) ==0 and ta.change(strategy.position_size) and strategy.position_size == 0 and buy > sell : na ,location = location.top , color = color.new(color.red, 0), char='☹' , size = size.tiny)
|
Super Breakout day trading | https://www.tradingview.com/script/scnNIACo-Super-Breakout-day-trading/ | beststockalert | https://www.tradingview.com/u/beststockalert/ | 118 | 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/
// © beststockalert
//@version=4
strategy(title="Super Breakout VFI", shorttitle = "Super BB-BO",default_qty_type = strategy.percent_of_equity,default_qty_value = 100, overlay=true)
source = close
length = input(130, title="VFI length")
coef = input(0.2)
vcoef = input(2.5, title="Max. vol. cutoff")
signalLength=input(5)
// session
pre = input( type=input.session, defval="0400-0935")
trade_session = input( type=input.session, defval="0945-1700")
use_trade_session = true
isinsession = use_trade_session ? not na(time('1', trade_session)) : true
is_newbar(sess) =>
t = time("D", sess)
not na(t) and (na(t[1]) or t > t[1])
is_session(sess) =>
not na(time(timeframe.period, sess))
preNew = is_newbar(pre)
preSession = is_session(pre)
float preLow = na
preLow := preSession ? preNew ? low : min(preLow[1], low) : preLow[1]
float preHigh = na
preHigh := preSession ? preNew ? high : max(preHigh[1], high) : preHigh[1]
// vfi 9lazybear
ma(x,y) => 0 ? sma(x,y) : x
typical=hlc3
inter = log( typical ) - log( typical[1] )
vinter = stdev(inter, 30 )
cutoff = coef * vinter * close
vave = sma( volume, length )[1]
vmax = vave * vcoef
vc = iff(volume < vmax, volume, vmax) //min( volume, vmax )
mf = typical - typical[1]
vcp = iff( mf > cutoff, vc, iff ( mf < -cutoff, -vc, 0 ) )
vfi = ma(sum( vcp , length )/vave, 3)
vfima=ema( vfi, signalLength )
//ema diff
ema20 = ema(close,20)
ema50 = ema(close,50)
diff = (ema20-ema50)*100/ema20
ediff = ema(diff,20)
//
basis = sma(source, 20)
dev = 1.5 * stdev(source, 20)
dev2 = 2 * stdev(source, 20)
upper = basis + dev
lower = basis - dev
ema9 = ema(source, 20)
ma5 = sma(source,5)
/// bar color
barColour = (open>=upper) ? color.green : (close>=upper) ? color.green : (close>basis) ? color.green : (open<lower) ? color.purple : color.blue
barcolor(color=barColour)
sell = crossunder(source, lower) or vfi>19 or vfima>19 or (low< sar(0.025,0.02,0.2) and close<ma5)
///
if (isinsession and source[2]>preHigh and (barssince(sell)>5 or (close>basis and close<dev2)) and ((crossover(source, upper) or (close[3]>upper and close>ema9 and (vfi >0 or vfima>0 ) and (vfi<14 or vfima<14)) ) and close <close[4]*1.16 and close <close[3]*1.14 ))
strategy.entry("Long", strategy.long)
if ( sell )
strategy.close("Long")
|
Portfolio Performance - Effects of Rebalancing | https://www.tradingview.com/script/nUz1gnht-Portfolio-Performance-Effects-of-Rebalancing/ | Skywalking2874 | https://www.tradingview.com/u/Skywalking2874/ | 54 | 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/
// © Skywalking2874
//@version=5
strategy("Portfolio Performance - Effects of Rebalancing", overlay=false, margin_long=100, margin_short=100, process_orders_on_close=true, max_bars_back=5000)
//****************************************************************** Define the time interval ******************************************************************//
entrytime = input.time(defval=timestamp("2021-12-16"), title="Entry Time", tooltip="Enter the starting date", confirm=true, group="Time Interval")
exittime = input.time(defval=timestamp("2021-12-17"), title="Exit Time", tooltip="Enter the ending date", confirm=true, group="Time Interval")
entrycondition = time >= entrytime and time < exittime
exitcondition = time >= exittime
strategy.entry("Buy", strategy.long, qty=100000/close, when=entrycondition)
strategy.close_all(when = exitcondition)
//****************************************************************** Define the second asset ******************************************************************//
second_asset_prefix = input.string(defval = "BATS", title = "Prefix", group="Second Asset", inline="Asset2")
second_asset_ticker = input.string(defval = "AGG", title="Ticker", group="Second Asset", inline="Asset2", tooltip="Input the prefix and ticker of the second asset that makes up the portfolio")
second_ticker = ticker.new(prefix = second_asset_prefix, ticker = second_asset_ticker, session = session.regular, adjustment = adjustment.dividends)
second_symbol = request.security(second_ticker, "D", close)
//****************************************************************** Define the portfolio weights ******************************************************************//
initial_investment = input.float(defval=100000, title="Initial Investment ($)", minval=0, step=0.1, tooltip="Input the dollar value of the inital investment", group="Portfolio")
portfolio_weight1 = input.float(defval=80.00, title="First Weight (%)", minval=0, maxval=100, step=0.1, inline="Asset1", group="Portfolio")/100.00
portfolio_weight2 = input.float(defval=20.00, title="Second Weight (%)", minval=0, maxval=100, step=0.1, tooltip="Input the weight of each asset relative to the portfolio", inline="Asset1", group="Portfolio")/100.00
//****************************************************************** Define the rebalancing thresholds ******************************************************************************//
high_threshold1 = input.float(defval=1, title="High (%)", minval=0.0, maxval=1000.00, step=0.1, tooltip="Input the low and high rebalancing thresholds", inline="threshold1", group="threshold 1")/100.00
low_threshold1 = input.float(defval=1, title="Low (%)", minval=0.0, maxval=1000.00, step=0.1, inline="threshold1", group="threshold 1")/100.00
high_threshold2 = input.float(defval=2.5, title="High (%)", minval=0.0, maxval=1000.00, step=0.1, tooltip="Input the low and high rebalancing thresholds", inline="threshold2", group="threshold 2")/100.00
low_threshold2 = input.float(defval=2.5, title="Low (%)", minval=0.0, maxval=1000.00, step=0.1, inline="threshold2", group="threshold 2")/100.00
high_threshold3 = input.float(defval=5, title="High (%)", minval=0.0, maxval=1000.00, step=0.1, tooltip="Input the low and high rebalancing thresholds", inline="threshold3", group="threshold 3")/100.00
low_threshold3 = input.float(defval=5, title="Low (%)", minval=0.0, maxval=1000.00, step=0.1, inline="threshold3", group="threshold 3")/100.00
high_threshold4 = input.float(defval=10, title="High (%)", minval=0.0, maxval=1000.00, step=0.1, tooltip="Input the low and high rebalancing thresholds", inline="threshold4", group="threshold 4")/100.00
low_threshold4 = input.float(defval=10, title="Low (%)", minval=0.0, maxval=1000.00, step=0.1, inline="threshold4", group="threshold 4")/100.00
high_threshold5 = input.float(defval=15, title="High (%)", minval=0.0, maxval=1000.00, step=0.1, tooltip="Input the low and high rebalancing thresholds", inline="threshold5", group="threshold 5")/100.00
low_threshold5 = input.float(defval=15, title="Low (%)", minval=0.0, maxval=1000.00, step=0.1, inline="threshold5", group="threshold 5")/100.00
high_threshold6 = input.float(defval=20, title="High (%)", minval=0.0, maxval=1000.00, step=0.1, tooltip="Input the low and high rebalancing thresholds", inline="threshold6", group="threshold 6")/100.00
low_threshold6 = input.float(defval=20, title="Low (%)", minval=0.0, maxval=1000.00, step=0.1, inline="threshold6", group="threshold 6")/100.00
high_threshold7 = input.float(defval=30, title="High (%)", minval=0.0, maxval=1000.00, step=0.1, tooltip="Input the low and high rebalancing thresholds", inline="threshold7", group="threshold 7")/100.00
low_threshold7 = input.float(defval=30, title="Low (%)", minval=0.0, maxval=1000.00, step=0.1, inline="threshold7", group="threshold 7")/100.00
//****************************************************************** Calculate %Return ******************************************************************//
trade_open_time = time >= strategy.opentrades.entry_time(strategy.opentrades-1) ? strategy.opentrades.entry_time(strategy.opentrades-1) : 2524608000000
bar_count = ta.barssince(time <= trade_open_time)
//threshold group 1
threshold_group_1_asset1_initial_holdings = bar_count > 0 ? int(initial_investment*portfolio_weight1/close[bar_count]) :int(initial_investment*portfolio_weight1/close)
threshold_group_1_asset2_initial_holdings = bar_count > 0 ? int(initial_investment*portfolio_weight2/second_symbol[bar_count]) : int(initial_investment*portfolio_weight2/second_symbol)
threshold_group_1_asset1_current_holdings = threshold_group_1_asset1_initial_holdings
threshold_group_1_asset2_current_holdings = threshold_group_1_asset2_initial_holdings
threshold_group_1_asset1_current_holdings := bar_count > 1 ? threshold_group_1_asset1_current_holdings[1] : threshold_group_1_asset1_initial_holdings
threshold_group_1_asset2_current_holdings := bar_count > 1 ? threshold_group_1_asset2_current_holdings[1] : threshold_group_1_asset2_initial_holdings
threshold_group_1_asset1_value = threshold_group_1_asset1_current_holdings*close
threshold_group_1_asset2_value = threshold_group_1_asset2_current_holdings*second_symbol
threshold_group_1_portfolio_value = threshold_group_1_asset1_value + threshold_group_1_asset2_value
threshold_group_1_asset1_weight = threshold_group_1_asset1_value/threshold_group_1_portfolio_value
threshold_group_1_asset2_weight = threshold_group_1_asset2_value/threshold_group_1_portfolio_value
threshold_group_1_delta1 = math.abs(threshold_group_1_asset1_value - (threshold_group_1_portfolio_value * portfolio_weight1))
threshold_group_1_delta2 = math.abs(threshold_group_1_asset2_value - (threshold_group_1_portfolio_value * portfolio_weight2))
threshold_group_1_number_of_assets_to_move1 = int(threshold_group_1_delta1/close)
threshold_group_1_number_of_assets_to_move2 = int(threshold_group_1_delta2/second_symbol)
if threshold_group_1_asset1_weight >= (portfolio_weight1+high_threshold1)
threshold_group_1_asset1_current_holdings:= threshold_group_1_asset1_current_holdings - threshold_group_1_number_of_assets_to_move1
threshold_group_1_asset2_current_holdings:= threshold_group_1_asset2_current_holdings + threshold_group_1_number_of_assets_to_move2
else if threshold_group_1_asset1_weight <= (portfolio_weight1-low_threshold1)
threshold_group_1_asset1_current_holdings:= threshold_group_1_asset1_current_holdings + threshold_group_1_number_of_assets_to_move1
threshold_group_1_asset2_current_holdings:= threshold_group_1_asset2_current_holdings - threshold_group_1_number_of_assets_to_move2
else
threshold_group_1_asset1_current_holdings:= threshold_group_1_asset1_current_holdings
threshold_group_1_asset2_current_holdings:= threshold_group_1_asset2_current_holdings
threshold_group_1_portfolio_percent_return = ((threshold_group_1_portfolio_value - threshold_group_1_portfolio_value[bar_count])/threshold_group_1_portfolio_value[bar_count])*100
//threshold group 2
threshold_group_2_asset1_initial_holdings = bar_count > 0 ? int(initial_investment*portfolio_weight1/close[bar_count]) :int(initial_investment*portfolio_weight1/close)
threshold_group_2_asset2_initial_holdings = bar_count > 0 ? int(initial_investment*portfolio_weight2/second_symbol[bar_count]) : int(initial_investment*portfolio_weight2/second_symbol)
threshold_group_2_asset1_current_holdings = threshold_group_2_asset1_initial_holdings
threshold_group_2_asset2_current_holdings = threshold_group_2_asset2_initial_holdings
threshold_group_2_asset1_current_holdings := bar_count > 1 ? threshold_group_2_asset1_current_holdings[1] : threshold_group_2_asset1_initial_holdings
threshold_group_2_asset2_current_holdings := bar_count > 1 ? threshold_group_2_asset2_current_holdings[1] : threshold_group_2_asset2_initial_holdings
threshold_group_2_asset1_value = threshold_group_2_asset1_current_holdings*close
threshold_group_2_asset2_value = threshold_group_2_asset2_current_holdings*second_symbol
threshold_group_2_portfolio_value = threshold_group_2_asset1_value + threshold_group_2_asset2_value
threshold_group_2_asset1_weight = threshold_group_2_asset1_value/threshold_group_2_portfolio_value
threshold_group_2_asset2_weight = threshold_group_2_asset2_value/threshold_group_2_portfolio_value
threshold_group_2_delta1 = math.abs(threshold_group_2_asset1_value - (threshold_group_2_portfolio_value * portfolio_weight1))
threshold_group_2_delta2 = math.abs(threshold_group_2_asset2_value - (threshold_group_2_portfolio_value * portfolio_weight2))
threshold_group_2_number_of_assets_to_move1 = int(threshold_group_2_delta1/close)
threshold_group_2_number_of_assets_to_move2 = int(threshold_group_2_delta2/second_symbol)
if threshold_group_2_asset1_weight >= (portfolio_weight1+high_threshold2)
threshold_group_2_asset1_current_holdings:= threshold_group_2_asset1_current_holdings - threshold_group_2_number_of_assets_to_move1
threshold_group_2_asset2_current_holdings:= threshold_group_2_asset2_current_holdings + threshold_group_2_number_of_assets_to_move2
else if threshold_group_2_asset1_weight <= (portfolio_weight1-low_threshold2)
threshold_group_2_asset1_current_holdings:= threshold_group_2_asset1_current_holdings + threshold_group_2_number_of_assets_to_move1
threshold_group_2_asset2_current_holdings:= threshold_group_2_asset2_current_holdings - threshold_group_2_number_of_assets_to_move2
else
threshold_group_2_asset1_current_holdings:= threshold_group_2_asset1_current_holdings
threshold_group_2_asset2_current_holdings:= threshold_group_2_asset2_current_holdings
threshold_group_2_portfolio_percent_return = ((threshold_group_2_portfolio_value - threshold_group_2_portfolio_value[bar_count])/threshold_group_2_portfolio_value[bar_count])*100
//threshold group 3
threshold_group_3_asset1_initial_holdings = bar_count > 0 ? int(initial_investment*portfolio_weight1/close[bar_count]) :int(initial_investment*portfolio_weight1/close)
threshold_group_3_asset2_initial_holdings = bar_count > 0 ? int(initial_investment*portfolio_weight2/second_symbol[bar_count]) : int(initial_investment*portfolio_weight2/second_symbol)
threshold_group_3_asset1_current_holdings = threshold_group_3_asset1_initial_holdings
threshold_group_3_asset2_current_holdings = threshold_group_3_asset2_initial_holdings
threshold_group_3_asset1_current_holdings := bar_count > 1 ? threshold_group_3_asset1_current_holdings[1] : threshold_group_3_asset1_initial_holdings
threshold_group_3_asset2_current_holdings := bar_count > 1 ? threshold_group_3_asset2_current_holdings[1] : threshold_group_3_asset2_initial_holdings
threshold_group_3_asset1_value = threshold_group_3_asset1_current_holdings*close
threshold_group_3_asset2_value = threshold_group_3_asset2_current_holdings*second_symbol
threshold_group_3_portfolio_value = threshold_group_3_asset1_value + threshold_group_3_asset2_value
threshold_group_3_asset1_weight = threshold_group_3_asset1_value/threshold_group_3_portfolio_value
threshold_group_3_asset2_weight = threshold_group_3_asset2_value/threshold_group_3_portfolio_value
threshold_group_3_delta1 = math.abs(threshold_group_3_asset1_value - (threshold_group_3_portfolio_value * portfolio_weight1))
threshold_group_3_delta2 = math.abs(threshold_group_3_asset2_value - (threshold_group_3_portfolio_value * portfolio_weight2))
threshold_group_3_number_of_assets_to_move1 = int(threshold_group_3_delta1/close)
threshold_group_3_number_of_assets_to_move2 = int(threshold_group_3_delta2/second_symbol)
if threshold_group_3_asset1_weight >= (portfolio_weight1+high_threshold3)
threshold_group_3_asset1_current_holdings:= threshold_group_3_asset1_current_holdings - threshold_group_3_number_of_assets_to_move1
threshold_group_3_asset2_current_holdings:= threshold_group_3_asset2_current_holdings + threshold_group_3_number_of_assets_to_move2
else if threshold_group_3_asset1_weight <= (portfolio_weight1-low_threshold3)
threshold_group_3_asset1_current_holdings:= threshold_group_3_asset1_current_holdings + threshold_group_3_number_of_assets_to_move1
threshold_group_3_asset2_current_holdings:= threshold_group_3_asset2_current_holdings - threshold_group_3_number_of_assets_to_move2
else
threshold_group_3_asset1_current_holdings:= threshold_group_3_asset1_current_holdings
threshold_group_3_asset2_current_holdings:= threshold_group_3_asset2_current_holdings
threshold_group_3_portfolio_percent_return = ((threshold_group_3_portfolio_value - threshold_group_3_portfolio_value[bar_count])/threshold_group_3_portfolio_value[bar_count])*100
//threshold group 4
threshold_group_4_asset1_initial_holdings = bar_count > 0 ? int(initial_investment*portfolio_weight1/close[bar_count]) :int(initial_investment*portfolio_weight1/close)
threshold_group_4_asset2_initial_holdings = bar_count > 0 ? int(initial_investment*portfolio_weight2/second_symbol[bar_count]) : int(initial_investment*portfolio_weight2/second_symbol)
threshold_group_4_asset1_current_holdings = threshold_group_4_asset1_initial_holdings
threshold_group_4_asset2_current_holdings = threshold_group_4_asset2_initial_holdings
threshold_group_4_asset1_current_holdings := bar_count > 1 ? threshold_group_4_asset1_current_holdings[1] : threshold_group_4_asset1_initial_holdings
threshold_group_4_asset2_current_holdings := bar_count > 1 ? threshold_group_4_asset2_current_holdings[1] : threshold_group_4_asset2_initial_holdings
threshold_group_4_asset1_value = threshold_group_4_asset1_current_holdings*close
threshold_group_4_asset2_value = threshold_group_4_asset2_current_holdings*second_symbol
threshold_group_4_portfolio_value = threshold_group_4_asset1_value + threshold_group_4_asset2_value
threshold_group_4_asset1_weight = threshold_group_4_asset1_value/threshold_group_4_portfolio_value
threshold_group_4_asset2_weight = threshold_group_4_asset2_value/threshold_group_4_portfolio_value
threshold_group_4_delta1 = math.abs(threshold_group_4_asset1_value - (threshold_group_4_portfolio_value * portfolio_weight1))
threshold_group_4_delta2 = math.abs(threshold_group_4_asset2_value - (threshold_group_4_portfolio_value * portfolio_weight2))
threshold_group_4_number_of_assets_to_move1 = int(threshold_group_4_delta1/close)
threshold_group_4_number_of_assets_to_move2 = int(threshold_group_4_delta2/second_symbol)
if threshold_group_4_asset1_weight >= (portfolio_weight1+high_threshold4)
threshold_group_4_asset1_current_holdings:= threshold_group_4_asset1_current_holdings - threshold_group_4_number_of_assets_to_move1
threshold_group_4_asset2_current_holdings:= threshold_group_4_asset2_current_holdings + threshold_group_4_number_of_assets_to_move2
else if threshold_group_4_asset1_weight <= (portfolio_weight1-low_threshold4)
threshold_group_4_asset1_current_holdings:= threshold_group_4_asset1_current_holdings + threshold_group_4_number_of_assets_to_move1
threshold_group_4_asset2_current_holdings:= threshold_group_4_asset2_current_holdings - threshold_group_4_number_of_assets_to_move2
else
threshold_group_4_asset1_current_holdings:= threshold_group_4_asset1_current_holdings
threshold_group_4_asset2_current_holdings:= threshold_group_4_asset2_current_holdings
threshold_group_4_portfolio_percent_return = ((threshold_group_4_portfolio_value - threshold_group_4_portfolio_value[bar_count])/threshold_group_4_portfolio_value[bar_count])*100
//threshold group 5
threshold_group_5_asset1_initial_holdings = bar_count > 0 ? int(initial_investment*portfolio_weight1/close[bar_count]) :int(initial_investment*portfolio_weight1/close)
threshold_group_5_asset2_initial_holdings = bar_count > 0 ? int(initial_investment*portfolio_weight2/second_symbol[bar_count]) : int(initial_investment*portfolio_weight2/second_symbol)
threshold_group_5_asset1_current_holdings = threshold_group_5_asset1_initial_holdings
threshold_group_5_asset2_current_holdings = threshold_group_5_asset2_initial_holdings
threshold_group_5_asset1_current_holdings := bar_count > 1 ? threshold_group_5_asset1_current_holdings[1] : threshold_group_5_asset1_initial_holdings
threshold_group_5_asset2_current_holdings := bar_count > 1 ? threshold_group_5_asset2_current_holdings[1] : threshold_group_5_asset2_initial_holdings
threshold_group_5_asset1_value = threshold_group_5_asset1_current_holdings*close
threshold_group_5_asset2_value = threshold_group_5_asset2_current_holdings*second_symbol
threshold_group_5_portfolio_value = threshold_group_5_asset1_value + threshold_group_5_asset2_value
threshold_group_5_asset1_weight = threshold_group_5_asset1_value/threshold_group_5_portfolio_value
threshold_group_5_asset2_weight = threshold_group_5_asset2_value/threshold_group_5_portfolio_value
threshold_group_5_delta1 = math.abs(threshold_group_5_asset1_value - (threshold_group_5_portfolio_value * portfolio_weight1))
threshold_group_5_delta2 = math.abs(threshold_group_5_asset2_value - (threshold_group_5_portfolio_value * portfolio_weight2))
threshold_group_5_number_of_assets_to_move1 = int(threshold_group_5_delta1/close)
threshold_group_5_number_of_assets_to_move2 = int(threshold_group_5_delta2/second_symbol)
if threshold_group_5_asset1_weight >= (portfolio_weight1+high_threshold5)
threshold_group_5_asset1_current_holdings:= threshold_group_5_asset1_current_holdings - threshold_group_5_number_of_assets_to_move1
threshold_group_5_asset2_current_holdings:= threshold_group_5_asset2_current_holdings + threshold_group_5_number_of_assets_to_move2
else if threshold_group_5_asset1_weight <= (portfolio_weight1-low_threshold5)
threshold_group_5_asset1_current_holdings:= threshold_group_5_asset1_current_holdings + threshold_group_5_number_of_assets_to_move1
threshold_group_5_asset2_current_holdings:= threshold_group_5_asset2_current_holdings - threshold_group_5_number_of_assets_to_move2
else
threshold_group_5_asset1_current_holdings:= threshold_group_5_asset1_current_holdings
threshold_group_5_asset2_current_holdings:= threshold_group_5_asset2_current_holdings
threshold_group_5_portfolio_percent_return = ((threshold_group_5_portfolio_value - threshold_group_5_portfolio_value[bar_count])/threshold_group_5_portfolio_value[bar_count])*100
//threshold group 6
threshold_group_6_asset1_initial_holdings = bar_count > 0 ? int(initial_investment*portfolio_weight1/close[bar_count]) :int(initial_investment*portfolio_weight1/close)
threshold_group_6_asset2_initial_holdings = bar_count > 0 ? int(initial_investment*portfolio_weight2/second_symbol[bar_count]) : int(initial_investment*portfolio_weight2/second_symbol)
threshold_group_6_asset1_current_holdings = threshold_group_6_asset1_initial_holdings
threshold_group_6_asset2_current_holdings = threshold_group_6_asset2_initial_holdings
threshold_group_6_asset1_current_holdings := bar_count > 1 ? threshold_group_6_asset1_current_holdings[1] : threshold_group_6_asset1_initial_holdings
threshold_group_6_asset2_current_holdings := bar_count > 1 ? threshold_group_6_asset2_current_holdings[1] : threshold_group_6_asset2_initial_holdings
threshold_group_6_asset1_value = threshold_group_6_asset1_current_holdings*close
threshold_group_6_asset2_value = threshold_group_6_asset2_current_holdings*second_symbol
threshold_group_6_portfolio_value = threshold_group_6_asset1_value + threshold_group_6_asset2_value
threshold_group_6_asset1_weight = threshold_group_6_asset1_value/threshold_group_6_portfolio_value
threshold_group_6_asset2_weight = threshold_group_6_asset2_value/threshold_group_6_portfolio_value
threshold_group_6_delta1 = math.abs(threshold_group_6_asset1_value - (threshold_group_6_portfolio_value * portfolio_weight1))
threshold_group_6_delta2 = math.abs(threshold_group_6_asset2_value - (threshold_group_6_portfolio_value * portfolio_weight2))
threshold_group_6_number_of_assets_to_move1 = int(threshold_group_6_delta1/close)
threshold_group_6_number_of_assets_to_move2 = int(threshold_group_6_delta2/second_symbol)
if threshold_group_6_asset1_weight >= (portfolio_weight1+high_threshold6)
threshold_group_6_asset1_current_holdings:= threshold_group_6_asset1_current_holdings - threshold_group_6_number_of_assets_to_move1
threshold_group_6_asset2_current_holdings:= threshold_group_6_asset2_current_holdings + threshold_group_6_number_of_assets_to_move2
else if threshold_group_6_asset1_weight <= (portfolio_weight1-low_threshold6)
threshold_group_6_asset1_current_holdings:= threshold_group_6_asset1_current_holdings + threshold_group_6_number_of_assets_to_move1
threshold_group_6_asset2_current_holdings:= threshold_group_6_asset2_current_holdings - threshold_group_6_number_of_assets_to_move2
else
threshold_group_6_asset1_current_holdings:= threshold_group_6_asset1_current_holdings
threshold_group_6_asset2_current_holdings:= threshold_group_6_asset2_current_holdings
threshold_group_6_portfolio_percent_return = ((threshold_group_6_portfolio_value - threshold_group_6_portfolio_value[bar_count])/threshold_group_6_portfolio_value[bar_count])*100
//threshold group 7
threshold_group_7_asset1_initial_holdings = bar_count > 0 ? int(initial_investment*portfolio_weight1/close[bar_count]) :int(initial_investment*portfolio_weight1/close)
threshold_group_7_asset2_initial_holdings = bar_count > 0 ? int(initial_investment*portfolio_weight2/second_symbol[bar_count]) : int(initial_investment*portfolio_weight2/second_symbol)
threshold_group_7_asset1_current_holdings = threshold_group_7_asset1_initial_holdings
threshold_group_7_asset2_current_holdings = threshold_group_7_asset2_initial_holdings
threshold_group_7_asset1_current_holdings := bar_count > 1 ? threshold_group_7_asset1_current_holdings[1] : threshold_group_7_asset1_initial_holdings
threshold_group_7_asset2_current_holdings := bar_count > 1 ? threshold_group_7_asset2_current_holdings[1] : threshold_group_7_asset2_initial_holdings
threshold_group_7_asset1_value = threshold_group_7_asset1_current_holdings*close
threshold_group_7_asset2_value = threshold_group_7_asset2_current_holdings*second_symbol
threshold_group_7_portfolio_value = threshold_group_7_asset1_value + threshold_group_7_asset2_value
threshold_group_7_asset1_weight = threshold_group_7_asset1_value/threshold_group_7_portfolio_value
threshold_group_7_asset2_weight = threshold_group_7_asset2_value/threshold_group_7_portfolio_value
threshold_group_7_delta1 = math.abs(threshold_group_7_asset1_value - (threshold_group_7_portfolio_value * portfolio_weight1))
threshold_group_7_delta2 = math.abs(threshold_group_7_asset2_value - (threshold_group_7_portfolio_value * portfolio_weight2))
threshold_group_7_number_of_assets_to_move1 = int(threshold_group_7_delta1/close)
threshold_group_7_number_of_assets_to_move2 = int(threshold_group_7_delta2/second_symbol)
if threshold_group_7_asset1_weight >= (portfolio_weight1+high_threshold7)
threshold_group_7_asset1_current_holdings:= threshold_group_7_asset1_current_holdings - threshold_group_7_number_of_assets_to_move1
threshold_group_7_asset2_current_holdings:= threshold_group_7_asset2_current_holdings + threshold_group_7_number_of_assets_to_move2
else if threshold_group_7_asset1_weight <= (portfolio_weight1-low_threshold7)
threshold_group_7_asset1_current_holdings:= threshold_group_7_asset1_current_holdings + threshold_group_7_number_of_assets_to_move1
threshold_group_7_asset2_current_holdings:= threshold_group_7_asset2_current_holdings - threshold_group_7_number_of_assets_to_move2
else
threshold_group_7_asset1_current_holdings:= threshold_group_7_asset1_current_holdings
threshold_group_7_asset2_current_holdings:= threshold_group_7_asset2_current_holdings
threshold_group_7_portfolio_percent_return = ((threshold_group_7_portfolio_value - threshold_group_7_portfolio_value[bar_count])/threshold_group_7_portfolio_value[bar_count])*100
//Base Asset
percent_return_base_asset = ((close - close[bar_count])/close[bar_count])*100
//****************************************************************** Plot ******************************************************************//
threshold1_return = input.bool(defval=true, title="Plot Threshold 1 Return", group="threshold 1")
threshold2_return = input.bool(defval=true, title="Plot Threshold 2 Return", group="threshold 2")
threshold3_return = input.bool(defval=true, title="Plot Threshold 3 Return", group="threshold 3")
threshold4_return = input.bool(defval=true, title="Plot Threshold 4 Return", group="threshold 4")
threshold5_return = input.bool(defval=true, title="Plot Threshold 5 Return", group="threshold 5")
threshold6_return = input.bool(defval=true, title="Plot Threshold 6 Return", group="threshold 6")
threshold7_return = input.bool(defval=true, title="Plot Threshold 7 Return", group="threshold 7")
trade_close_time = time >= strategy.closedtrades.entry_time(strategy.closedtrades-1) ? strategy.closedtrades.entry_time(strategy.closedtrades-1) : 2524608000000
transparant = color.rgb(0, 0, 0, 100)
//Color Palette
base_color = time >= trade_open_time ? color.new(#001eff, 0) : transparant
threshold_color1 = time >= trade_open_time ? color.new(#10B22D, 0) : transparant
threshold_color2 = time >= trade_open_time ? color.new(#00FF1E, 0) : transparant
threshold_color3 = time >= trade_open_time ? color.new(#FFFB00, 0) : transparant
threshold_color4 = time >= trade_open_time ? color.new(#ffa900, 0) : transparant
threshold_color5 = time >= trade_open_time ?color.new(#FF6600, 0) : transparant
threshold_color6 = time >= trade_open_time ? color.new(#FF0000, 0) : transparant
threshold_color7 = time >= trade_open_time ? color.new(#9C0000, 0) : transparant
plot(percent_return_base_asset, title="Return of Base Asset", color=base_color)
plot(threshold_group_1_portfolio_percent_return, title="Threshold 1 Percent Return", color=threshold1_return == true ? threshold_color1 : transparant)
plot(threshold_group_2_portfolio_percent_return, title="Threshold 2 Percent Return", color=threshold2_return == true ? threshold_color2 : transparant)
plot(threshold_group_3_portfolio_percent_return, title="Threshold 3 Percent Return", color=threshold3_return == true ? threshold_color3 : transparant)
plot(threshold_group_4_portfolio_percent_return, title="Threshold 4 Percent Return", color=threshold4_return == true ? threshold_color4 : transparant)
plot(threshold_group_5_portfolio_percent_return, title="Threshold 5 Percent Return", color=threshold5_return == true ? threshold_color5 : transparant)
plot(threshold_group_6_portfolio_percent_return, title="Threshold 6 Percent Return", color=threshold6_return == true ? threshold_color6 : transparant)
plot(threshold_group_7_portfolio_percent_return, title="Threshold 7 Percent Return", color=threshold7_return == true ? threshold_color7 : transparant)
|
Same high/low + DCA (only long) | https://www.tradingview.com/script/XPWpr6FI-Same-high-low-DCA-only-long/ | Cherepanov_V | https://www.tradingview.com/u/Cherepanov_V/ | 115 | 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/
// © cherepanovvsb
//@version=5
strategy("Reversal (only long)", overlay=true, margin_long=1, margin_short=1,initial_capital=1000,commission_type = strategy.commission.percent,commission_value =0.1,currency='USD', process_orders_on_close=true)
plotshape(low == low[1], style=shape.triangleup, location=location.belowbar, color=color.blue, title="1 Setup")
plotshape(low == low[1] and low[1]==low[2], style=shape.triangleup, location=location.belowbar, color=color.red, title="Triple Setup")
ATRlenght = input.int(title="ATR length for taking profit", defval=14, group="Strategy Settings")
rewardMultiplier= input.int(title="ATR multiplier", defval=5, group="Strategy Settings")
Volatility_length=input.int(title='Volatility length',defval=5,group="Strategy Settings")
Volatility_multiplier=input.float(title='Volatility multiplier',defval=0.5,step=0.1, group="Strategy Settings")
Candles_to_wait=input.int(title='How many candles to wait after placing orders grid?',defval=4,group="Strategy Settings")
// Get ATR
atr1 = ta.atr(ATRlenght)
//Get volatility values (not ATR)
float result = 0
for i = 0 to Volatility_length
result+=high[i]-low[i]
volatility=result*Volatility_multiplier/Volatility_length
//Validate entrance points
validlow = low [2]== low[1] and not na(atr1)
validlong = validlow and strategy.position_size == 0 and low[1]<low
// Calculate SL/TP
longStopPrice = low[1]-syminfo.mintick
longStopDistance = close - longStopPrice
longTargetPrice = close + (longStopDistance * rewardMultiplier)
//Assign all variables
var tradeStopPrice = 0.0
var tradeTargetPrice = 0.0
var point1=0.0
var point2=0.0
var point3=0.0
var point4=0.0
var contracts = int(strategy.initial_capital/close)/4
if validlong
tradeStopPrice := longStopPrice
tradeTargetPrice := longTargetPrice
point1:=low[1]+volatility
point2:=low[1]+volatility*0.75
point3:=low[1]+volatility*0.5
point4:=low[1]+volatility*0.25
strategy.entry ("Long1", strategy.long,limit=point1,qty=contracts, when=validlong)
strategy.entry ("Long2", strategy.long,limit=point2,qty=contracts, when=validlong)
strategy.entry ("Long3", strategy.long,limit=point3,qty=contracts, when=validlong)
strategy.entry ("Long4", strategy.long,limit=point4,qty=contracts, when=validlong)
stopcondition = ta.barssince(validlong) == Candles_to_wait
strategy.cancel("Long1",when=stopcondition)
strategy.cancel("Long2",when=stopcondition)
strategy.cancel("Long3",when=stopcondition)
strategy.cancel("Long4",when=stopcondition)
strategy.exit(id="Long Exit", limit=tradeTargetPrice, stop=tradeStopPrice, when=strategy.position_size > 0)
plot(strategy.position_size != 0 or validlong ? tradeStopPrice : na, title="Trade Stop Price", color=color.red, style=plot.style_linebr, linewidth=3)
plot(strategy.position_size != 0 or validlong ? tradeTargetPrice : na, title="Trade Target Price", color=color.green, style=plot.style_linebr, linewidth=3)
plot(strategy.position_size != 0? point1 : na, title="Long1", color=color.green, style=plot.style_linebr, transp=0)
plot(strategy.position_size != 0? point2 : na, title="Long2", color=color.green, style=plot.style_linebr, transp=0)
plot(strategy.position_size != 0? point3 : na, title="Long3", color=color.green, style=plot.style_linebr, transp=0)
plot(strategy.position_size != 0? point4 : na, title="Long4", color=color.green, style=plot.style_linebr, transp=0)
|
Configurable Multi MA Crossover Voting System | https://www.tradingview.com/script/yR0g4RzX-Configurable-Multi-MA-Crossover-Voting-System/ | levieux | https://www.tradingview.com/u/levieux/ | 55 | 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/
// © levieux
//@version=5
strategy(title='Configurable Multi MA Crossover Voting System', shorttitle='Configurable Multi MA Crossover Voting System', 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)
crossoverConfig= input.string(defval="2x4,3x5,4x6", title="Crossover Config")
source= input.source(high)
maType= input.string("WMA", title="Moving Average Type", options=["WMA","SMA","VWMA"])
atrPeriod= input(14, title="ATR Period")
profitAtr = input(10, title="Profit ATR x")
lossAtr = input(5, title="Loss ATR x")
ma(src,length,type) =>
float ma = switch type
"SMA" => ta.sma(src, length)
"WMA" => ta.wma(src, length)
"VWMA" => ta.vwma(src, length)
crossoverGroups= str.split(crossoverConfig, ",")
crossoverCount= array.size(crossoverGroups)
crossovers= array.new_string(crossoverCount)
positions= array.new_int(crossoverCount, 0)
longVotes= 0
for i= 0 to crossoverCount-1
crossover= str.tostring(array.get(crossoverGroups, i))
crossoverBoundaries= str.split(crossover, "x")
int fastLength= math.round(str.tonumber(array.get(crossoverBoundaries, 0)))
int slowLength= math.round(str.tonumber(array.get(crossoverBoundaries, 1)))
wmaFast= ma(source,fastLength,maType)
wmaSlow= ma(source,slowLength,maType)
if wmaFast>wmaSlow
longVotes:= longVotes + 1
array.set(positions, i, 1)
longCondition= longVotes==crossoverCount and strategy.position_size==0
//profitTicks = profitAtr*ta.atr(atrPeriod)/syminfo.mintick
//lossTicks = lossAtr*ta.atr(atrPeriod)/syminfo.mintick
profitPrice= close+profitAtr*ta.atr(atrPeriod)
lossPrice= close-lossAtr*ta.atr(atrPeriod)
if strategy.position_size>0
profitPrice:= profitPrice[1]
lossPrice:= lossPrice[1]
plot(profitPrice, color=color.green)
plot(lossPrice, color=color.red)
if longCondition and profitPrice>0
strategy.entry("Long", strategy.long)
if longVotes<crossoverCount and strategy.position_size>0 and (high>profitPrice or low<lossPrice)
strategy.close("Long")
longVotes:= 0 |
3 Indicator Strategy (StochRSI, MFI & EMA) With Safety Orders | https://www.tradingview.com/script/EpyniqHK-3-Indicator-Strategy-StochRSI-MFI-EMA-With-Safety-Orders/ | ggekko21 | https://www.tradingview.com/u/ggekko21/ | 219 | 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/
// © ggekko21
//@version=5
strategy("3 Indicator Strategy (StochRSI, MFI & EMA) With Safety Orders", shorttitle="StochRSI MFI EMA With Safety Orders", overlay=true, max_labels_count=500)
bal_group = "Balance/Risk Settings"
trade_group = "Trade Settings"
long_or_shorts = input.string(defval = "Both", title = "Long/Short", options = ["Longs Only", "Shorts Only", "Both"], group=trade_group)
// Balance & Risk inputs
starting_balance = input.float(defval=10000.0, title="Starting Balance", tooltip="The starting balance for the strategy", group=bal_group)
risk_per_trade = input.float(defval=1.0, minval = 0.01, maxval = 100, title="Risk Per Trade", tooltip="Risk per trade as a percentage of the equity", group=bal_group)
// TP/SL inputs
tpsl_group = "Take Profit / Stop Loss Settings"
tp_sl_type = input.string(defval = "Pips", title="Take Profit/Stop Loss Type", options = ["Pips", "Base Value", "Opposite Signal"], tooltip = "The type of TP/SL used to close the position.", group=tpsl_group)
rr_ratio = input.float(defval = 1.0, minval = 0.1, maxval = 10.0, title="Risk Reward Ratio", group=tpsl_group)
tpsl = input.float(defval = 10.0, minval = 0.1, maxval = 1000000, title="Min Profit/Loss to Close Trade", group=tpsl_group)
tpsl_percentage = input.float(defval = 1.0, minval = 0.01, maxval = 100, title = "Take Profit/Stop Loss Target Percentage", group=tpsl_group)
long_tp = input.float(1000, title="Long Take Profit (mintick)", group=tpsl_group)
long_sl = input.float(2000, title="Long Stop Loss (mintick)", group=tpsl_group)
short_tp = input.float(1000, title="Short Take Profit (mintick)", group=tpsl_group)
short_sl = input.float(2000, title="Short Stop Loss (mintick)", group=tpsl_group)
// Safety Order inputs
safety_group = "Safety Order Settings"
// First safety order price deviation.
safety_order_percent = input.float(defval = 2, title = "Safety Order Percent", group=safety_group, tooltip = "Percentage of price deviation to open the first safety order.")
// What increments do you want the safety order to increase by?
safety_order_mul = input.float(defval = 1, minval = 1, maxval = 10, title = "Safety Order Multiplier", group=safety_group, tooltip = "Multiplies the current position size for each safety order.")
// How many safety order steps?
safety_order_steps = input.int(defval = 5, minval = 1, maxval = 10, title = "Safety Order Max Steps", group=safety_group, tooltip = "Maximum number of safety orders before the trade is a loss.")
src = input.source(defval = close, title = "Source", group = "Strategy Settings")
// ==================================================================================================================== //
// ============================================= StochRSI ============================================================= //
// ==================================================================================================================== //
StochRSI_group = "Stochastic RSI Settings"
StochRSI_kvalue = input.int(1, "K", minval=1, group=StochRSI_group)
StochRSI_dvalue = input.int(1, "D", minval=1, group=StochRSI_group)
lengthRSI = input.int(100, "RSI Length", minval=1, group=StochRSI_group)
lengthStoch = input.int(100, "Stochastic Length", minval=1, group=StochRSI_group)
StochRSI_long = input.float(20, minval = 0, maxval = 50, title = "Stochastic RSI Long Signal", group=StochRSI_group)
StochRSI_short = input.float(80, minval = 50, maxval = 100, title = "Stochastic RSI Short Signal", group=StochRSI_group)
rsi1 = ta.rsi(src, lengthRSI)
kvalue = ta.sma(ta.stoch(rsi1, rsi1, rsi1, lengthStoch), StochRSI_kvalue)
stochrsi_d = ta.sma(kvalue, StochRSI_dvalue)
// ==================================================================================================================== //
// =============================================== MFI ================================================================ //
// ==================================================================================================================== //
MFI_length = input.int(title="MFI Length", defval=30, minval=1, maxval=2000, group="Money Flow Index Settings")
MFI = ta.mfi(src, MFI_length)
MFI_long = input.float(20, minval = 0, maxval = 50, title = "MFI Long Signal", group="Money Flow Index Settings")
MFI_short = input.float(80, minval = 50, maxval = 100, title = "MFI Short Signal", group="Money Flow Index Settings")
// EMA Indicator
EMA_length = input.int(100, title="EMA Length", group = "EMA Settings")
EMA_indicator = ta.ema(src, EMA_length)
// ==================================================================================================================== //
// ============================================ Apply Strategy ======================================================== //
// ==================================================================================================================== //
stochrsi_long = stochrsi_d < StochRSI_long
stochrsi_short = stochrsi_d > StochRSI_short
mfi_long = MFI < MFI_long
mfi_short = MFI > MFI_short
ema_long = close < EMA_indicator
ema_short = close > EMA_indicator
long_condition = stochrsi_long and mfi_long and ema_long
short_condition = stochrsi_short and mfi_short and ema_short
// ==================================================================================================================== //
// ========================================== Apply Safety Orders ===================================================== //
// ==================================================================================================================== //
varip float current_balance = starting_balance
varip float order_size = ((risk_per_trade/100) * current_balance)/open
varip int current_step = 0
varip float price_entry = close
upnl_percentage = (strategy.openprofit/math.abs(strategy.position_avg_price*strategy.position_size))*100
// Make sure strategy doesn't duplicate orders
if long_or_shorts == "Longs Only" or long_or_shorts == "Both"
if long_condition and strategy.position_size == 0
//label.new(bar_index, high, text=str.tostring(upnl_percentage, format=format.mintick))
order_size := ((risk_per_trade/100) * current_balance)/open
strategy.entry("Enter Long", strategy.long, qty=order_size)
price_entry := close
if long_or_shorts == "Shorts Only" or long_or_shorts == "Both"
if short_condition and strategy.position_size == 0
//label.new(bar_index, high, text=str.tostring(upnl_percentage, format=format.mintick))
order_size := ((risk_per_trade/100) * current_balance)/open
strategy.entry("Enter Short", strategy.short, qty=order_size)
price_entry := close
// Enter Safety Orders Here
if upnl_percentage <= -safety_order_percent
//if current_step < safety_order_steps
// Enter safety order here
order_qty = math.abs(strategy.position_size)// * safety_order_mul
//order_size := (((risk_per_trade/100) * current_balance)/open)*safety_order_mul*current_step
order_size := (((risk_per_trade/100) * strategy.equity)/open)*safety_order_mul
if strategy.position_size > 0 and current_step < safety_order_steps
strategy.order("Enter Long", strategy.long, qty=order_size)
current_step := current_step + 1
if strategy.position_size < 0 and current_step < safety_order_steps
//label.new(bar_index, high, text=str.tostring(strategy.position_size, format=format.mintick))
strategy.order("Enter Short", strategy.short, qty=order_size)
current_step := current_step + 1
else if current_step >= safety_order_steps
// Maximum number of safety orders reached, closing position.
if strategy.position_size > 0
strategy.close(id="Enter Long")
if strategy.position_size < 0
strategy.close(id="Enter Short")
current_step := 0
// Update Current Balance
if strategy.wintrades != strategy.wintrades[1]
current_balance := strategy.equity
if current_step >= safety_order_steps
current_step := 0
if strategy.losstrades != strategy.losstrades[1]
current_balance := strategy.equity
if current_step >= safety_order_steps
current_step := 0
// Take Profit/Stop Loss Type
if tp_sl_type == "Base Value"
if strategy.openprofit > tpsl*rr_ratio or strategy.openprofit <= -tpsl
if strategy.position_size > 0
strategy.close(id="Enter Long")
if strategy.position_size < 0
strategy.close(id="Enter Short")
current_step := current_step + 1
if tp_sl_type == "Pips"
strategy.exit(id="Exit Long", from_entry="Enter Long", profit=long_tp, loss=long_sl, qty_percent = 100)
strategy.exit(id="Exit Short", from_entry="Enter Short", profit=short_tp, loss=short_sl, qty_percent = 100)
if tp_sl_type == "Opposite Signal"
strategy.close(id="Enter Long", when = short_condition and strategy.position_size > 0)
strategy.close(id="Enter Short", when = long_condition and strategy.position_size < 0)
|
Ultimate Ichimoku Cloud Strategy | https://www.tradingview.com/script/boHD0HzE-Ultimate-Ichimoku-Cloud-Strategy/ | antondmt | https://www.tradingview.com/u/antondmt/ | 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/
// © antondmt
//@version=5
strategy("Ultimate Ichimoku Cloud Strategy", "UIC Strategy", true, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, process_orders_on_close = true)
// Inputs {
// Backtest Range
i_time_start = input.time(timestamp("2015-12-12T00:00:00"), "Start Date", group = "Backtest Range")
i_time_finish = input.time(timestamp("2022-12-12T00:00:00"), "Finish Date", group = "Backtest Range")
// Ichimoku Lines
i_show_conversion = input.bool(false, "Show Conversion Line (Tenkan Sen)", group = "Ichimoku Lines")
i_show_base = input.bool(false, "Show Base Line (Kijun Sen)", group = "Ichimoku Lines")
i_show_lagging = input.bool(false, "Show Lagging Span (Chikou Span)", group = "Ichimoku Lines")
i_show_span_A = input.bool(false, "Show Leading Span A (Senkou Span A)", group = "Ichimoku Lines")
i_show_span_B = input.bool(false, "Show Leading Span B (Senkou Span B)", group = "Ichimoku Lines")
i_show_all = input.bool(true, "Show All Lines", group = "Ichimoku Lines")
// Ichimoku Periods
i_conversion_line_period = input.int(9, "Conversion Period", 1, group = "Ichimoku Periods")
i_base_line_period = input.int(26, "Base Line Period", 1, group = "Ichimoku Periods")
i_leading_span_period = input.int(52, "Lagging Span Period", 1, group = "Ichimoku Periods")
i_displacement = input.int(26, "Displacement", 1, group = "Ichimoku Periods")
// Ichimoku Long Conditions
i_long_cond_1 = input.bool(true, "Conversion Crosses Base", "Conversion line crosses up on base line.", group = "Ichimoku Long Conditions")
i_long_cond_2 = input.bool(false, "Conversion Above Base", "Conversion line is above base line", group = "Ichimoku Long Conditions")
i_long_cond_3 = input.bool(true, "Positive Cloud", "Cloud has to be positive. Span A > Span B.", group = "Ichimoku Long Conditions")
i_long_cond_4 = input.bool(true, "Price Above Cloud", "Price has to be above the clouds.", group = "Ichimoku Long Conditions")
i_long_cond_5 = input.bool(true, "Positive Chikou", "Lagging span has to be higher than price at displacement.", group = "Ichimoku Long Conditions")
i_long_cond_6 = input.bool(true, "Price Above Conversion", "Price has to be higher than conversion line.", group = "Ichimoku Long Conditions")
i_long_cond_show = input.bool(false, "Show Condititons Visually", "Draws lines when condition is true.", group = "Ichimoku Long Conditions")
// Ichimoku Short Conditions
i_short_cond_1 = input.bool(true, "Base Crosses Conversion", "Base line crosses up on conversion line.", group = "Ichimoku Short Conditions")
i_short_cond_2 = input.bool(false, "Base Above Conversion", "Base line is above conversion line", group = "Ichimoku Short Conditions")
i_short_cond_3 = input.bool(true, "Negative Cloud", "Cloud has to be negative. Span B > Span A.", group = "Ichimoku Short Conditions")
i_short_cond_4 = input.bool(true, "Price Below Cloud", "Price has to be below the clouds.", group = "Ichimoku Short Conditions")
i_short_cond_5 = input.bool(true, "Negative Chikou", "Lagging span has to be lower than price at displacement.", group = "Ichimoku Short Conditions")
i_short_cond_6 = input.bool(true, "Price Below Base", "Price has to be lower than base line.", group = "Ichimoku Short Conditions")
i_short_cond_show = input.bool(false, "Show Condititons Visually", "Draws lines when condition is true.", group = "Ichimoku Short Conditions")
// Ichimoku Long Exit Conditions
i_sell_long_cond_1 = input.bool(true, "Base Crosses Conversion", "Base line crosses up on conversion line.", group = "Ichimoku Long Exit Conditions")
i_sell_long_cond_2 = input.bool(false, "Negative Chikou", "Lagging span is lower than price at displacement.", group = "Ichimoku Long Exit Conditions")
i_sell_long_cond_show = input.bool(false, "Show Condititons Visually", "Draws lines when condition is true.", group = "Ichimoku Long Exit Conditions")
// Ichimoku Short Exit Conditions
i_sell_short_cond_1 = input.bool(true, "Conversion Crosses Base", "Conversion line crosses up on base line.", group = "Ichimoku Short Exit Conditions")
i_sell_short_cond_2 = input.bool(false, "Positive Chikou", "Lagging span is higher than price at displacement.", group = "Ichimoku Short Exit Conditions")
i_sell_short_cond_show = input.bool(false, "Show Condititons Visually", "Draws lines when condition is true.", group = "Ichimoku Short Exit Conditions")
// Exits vs TP/SL
i_use_SLTP = input.bool(false, "Use SL and TP Instead of Exits", group = "Exits vs TP/SL")
i_TP = input.float(2, "Take Profit (%)", group = "Exits vs TP/SL")
i_SL = input.float(1, "Stop Loss (%)", group = "Exits vs TP/SL")
// }
// Ichimoku Calculations {
donchian(len) =>
math.avg(ta.lowest(len), ta.highest(len))
conversion_line = donchian(i_conversion_line_period)
base_line = donchian(i_base_line_period)
leading_span_A = math.avg(conversion_line, base_line)
leading_span_B = donchian(i_leading_span_period)
// }
// Entries and Exits Logic {
long_entry = false
if(i_long_cond_1 or i_long_cond_2 or i_long_cond_3 or i_long_cond_4 or i_long_cond_5 or i_long_cond_6)
long_entry := (i_long_cond_1 ? ta.crossover(conversion_line, base_line) : true)
and (i_long_cond_2 ? conversion_line > base_line : true)
and (i_long_cond_3 ? leading_span_A[i_displacement - 1] > leading_span_B[i_displacement - 1] : true)
and (i_long_cond_4 ? close > leading_span_A[i_displacement - 1] and close > leading_span_B[i_displacement - 1] : true)
and (i_long_cond_5 ? close > nz(close[i_displacement + 1], close) : true)
and (i_long_cond_6 ? close > conversion_line : true)
short_entry = false
if(i_short_cond_1 or i_short_cond_2 or i_short_cond_3 or i_short_cond_4 or i_short_cond_5)
short_entry := (i_short_cond_1 ? ta.crossunder(conversion_line, base_line) : true)
and (i_short_cond_2 ? base_line > conversion_line : true)
and (i_short_cond_3 ? leading_span_A[i_displacement - 1] < leading_span_B[i_displacement - 1] : true)
and (i_short_cond_4 ? close < leading_span_A[i_displacement - 1] and close < leading_span_B[i_displacement - 1] : true)
and (i_short_cond_5 ? close < nz(close[i_displacement + 1], close) : true)
and (i_short_cond_6 ? close < base_line : true)
long_exit = false
if(i_sell_long_cond_1 or i_sell_long_cond_2)
long_exit := (i_sell_long_cond_1 ? ta.crossunder(conversion_line, base_line) : true)
and (i_sell_long_cond_2 ? close < nz(close[i_displacement + 1], close) : true)
short_exit = false
if(i_sell_short_cond_1 or i_sell_short_cond_2)
short_exit := (i_sell_short_cond_1 ? ta.crossover(conversion_line, base_line) : true)
and (i_sell_short_cond_2 ? close > nz(close[i_displacement + 1], close) : true)
dateRange() =>
i_time_start <= time and time <= i_time_finish ? true : false
// }
// Entries and Exits {
if(strategy.position_size <= 0 and long_entry and dateRange())
strategy.entry("Long", strategy.long)
if(long_exit and not i_use_SLTP)
strategy.close("Long")
else if(i_use_SLTP)
strategy.exit("TP/SL", "Long", stop = strategy.position_avg_price * (1 - i_SL / 100), limit = strategy.position_avg_price * (1 + i_TP / 100))
if(strategy.position_size >= 0 and short_entry and dateRange())
strategy.entry("Short", strategy.short)
if(short_exit and not i_use_SLTP)
strategy.close("Short")
else if(i_use_SLTP)
strategy.exit("TP/SL", "Short", stop = strategy.position_avg_price * (1 + i_SL / 100), limit = strategy.position_avg_price * (1 - i_TP / 100))
// }
// Plots {
plot(i_show_all or i_show_conversion ? conversion_line : na, "Conversion Line (Tenkan Sen)", color.new(#0496ff, 0), 2)
plot(i_show_all or i_show_base ? base_line : na, "Base Line (Kijun Sen)", color.new(#991515, 0), 2)
plot(i_show_all or i_show_lagging ? close : na, "Lagging Span (Chikou Span)", color.new(color.yellow, 0), 2, offset = -i_displacement + 1)
span_A = plot(i_show_all or i_show_span_A ? leading_span_A : na, "Leading Span A (Senkou Span A)", color.new(color.green, 0), offset = i_displacement - 1)
span_B = plot(i_show_all or i_show_span_B ? leading_span_B : na, "Leading Span B (Senkou Span B)", color.new(color.red, 0), offset = i_displacement - 1)
fill(span_A, span_B, leading_span_A > leading_span_B ? color.new(color.green, 90) : color.new(color.red, 90), "Cloud Colors")
bgcolor(i_long_cond_show and long_entry ? color.new(color.green, 40) : na)
bgcolor(i_short_cond_show and short_entry ? color.new(color.red, 40) : na)
bgcolor(i_sell_long_cond_show and long_exit ? color.new(color.purple, 40) : na)
bgcolor(i_sell_short_cond_show and short_exit ? color.new(color.aqua, 40) : na)
// } |
Swing Trades Validator - The One Trader | https://www.tradingview.com/script/gR2ZgtWc-Swing-Trades-Validator-The-One-Trader/ | the_daily_trader | https://www.tradingview.com/u/the_daily_trader/ | 166 | 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/
// © the_daily_trader
//@version=5
// --------------------- Start of Code ---------------------
strategy("Swing Trades Validator", overlay=true, margin_long=100, pyramiding = 0)
// Indicator Display Checks
TakeProfitPercent = input.float(title="Profit Target %", defval=10, minval=1, step=0.05)
StopLossPercent = input.float(title="Stop Loss %", defval=10, minval=1, step=0.05)
pullbackchoice = input.bool(true, "Enhanced Entry Rules")
// EMAs
emaH = ta.ema(close, 8)
emaHyest = ta.ema(close[1], 8)
emaHyest1 = ta.ema(close[2], 8)
emaHyest2 = ta.ema(close[3], 8)
emaL = ta.ema(close, 21)
emaLyest = ta.ema(close[1], 21)
emaLyest1 = ta.ema(close[2], 21)
emaLyest2 = ta.ema(close[3], 21)
emaf = ta.ema(close, 50)
emath = ta.ema(close, 200)
emathhigh = ta.ema(high, 200)
emathlow = ta.ema(low, 200)
emaslowmonthly = request.security(syminfo.tickerid, "M", emaL) // Monthly 21ema
emafastmonthly = request.security(syminfo.tickerid, "M", emaH) // Monthly 8ema
emaslowweekly = request.security(syminfo.tickerid, "W", emaL) // Weekly 21ema
emafastweekly = request.security(syminfo.tickerid, "W", emaH) // Weekly 8ema
emaslowdaily = request.security(syminfo.tickerid, "D", emaL) // Daily 21ema
emafastdaily = request.security(syminfo.tickerid, "D", emaH) // Daily 8ema
emafdaily = request.security(syminfo.tickerid, "D", emaf) // Daily 50ema
emathdaily = request.security(syminfo.tickerid, "D", emath) // Daily ema
emathdailyhigh = request.security(syminfo.tickerid, "D", emathhigh) // Daily ema High
emathdailylow = request.security(syminfo.tickerid, "D", emathlow) // Daily ema Low
ema21yest = request.security(syminfo.tickerid, "D", emaLyest) // Daily 21ema 1 day ago
ema21yest1 = request.security(syminfo.tickerid, "D", emaLyest1) // Daily 21ema 2 days ago
ema21yest2 = request.security(syminfo.tickerid, "D", emaLyest2) // Daily 21ema 3 days ago
ema8yest = request.security(syminfo.tickerid, "D", emaHyest) // Daily 8ema 1 day ago
ema8yest1 = request.security(syminfo.tickerid, "D", emaHyest1) // Daily 8ema 2 days ago
ema8yest2 = request.security(syminfo.tickerid, "D", emaHyest2) // Daily 8ema 3 days ago
// Prices
monthopen = request.security(syminfo.tickerid, 'M', open, barmerge.gaps_off, barmerge.lookahead_on)
monthclose = request.security(syminfo.tickerid, 'M', close, barmerge.gaps_off, barmerge.lookahead_on)
weekopen = request.security(syminfo.tickerid, 'W', open, barmerge.gaps_off, barmerge.lookahead_on)
weekclose = request.security(syminfo.tickerid, 'W', close, barmerge.gaps_off, barmerge.lookahead_on)
dayopen = request.security(syminfo.tickerid, 'D', open, barmerge.gaps_off, barmerge.lookahead_on)
dayclose = request.security(syminfo.tickerid, 'D', close, barmerge.gaps_off, barmerge.lookahead_on)
threedayhigh = request.security(syminfo.tickerid, 'D', high[3], barmerge.gaps_off, barmerge.lookahead_on)
twodayhigh = request.security(syminfo.tickerid, 'D', high[2], barmerge.gaps_off, barmerge.lookahead_on)
yesthigh = request.security(syminfo.tickerid, 'D', high[1], barmerge.gaps_off, barmerge.lookahead_on)
yestlow = request.security(syminfo.tickerid, 'D', low[1], barmerge.gaps_off, barmerge.lookahead_on)
// Conditions
monthlybullish = emafastmonthly > emaslowmonthly
monthlybullishprice = close > emafastmonthly
monthlybullishcandle = monthclose > monthopen
weeklybullish = emafastweekly > emaslowweekly
weeklybullishprice = close > emafastweekly
weeklybullishcandle = weekclose > weekopen
realbullish = dayclose > emathdailyhigh
goldencross = emafdaily > emathdailyhigh
dailybullish1 = emafdaily > emathdaily
dailybullish2 = emafastdaily > emaslowdaily
dailybullishprice = close > emafastdaily
dailybullishcandle = dayclose > dayopen
ringlow = yestlow <= ema8yest
aggropullback = twodayhigh < threedayhigh
pullback = (pullbackchoice ? aggropullback : 0)
pullbackfailure = dayclose > yesthigh and yesthigh < twodayhigh or pullback
emasetup = ema8yest > ema21yest and ema8yest1 > ema21yest1 and ema8yest2 > ema21yest2
// Target Profit and Stop Loss Inputs
// Input parameters can be found at the beginning of the code
ProfitTarget = (close * (TakeProfitPercent / 100)) / syminfo.mintick
StopLoss = (close * (StopLossPercent / 100)) / syminfo.mintick
longCondition = monthlybullish and monthlybullishprice and monthlybullishcandle and weeklybullish and weeklybullishprice and weeklybullishcandle and dailybullish1 and dailybullish2 and dailybullishprice and dailybullishcandle and ringlow and pullbackfailure and emasetup and realbullish and goldencross
if (longCondition)
strategy.entry("Long", strategy.long)
strategy.exit ("Exit", "Long", profit = ProfitTarget, loss = StopLoss)
// -----------xxxxxxxxxxx------------- End of Code -----------xxxxxxxxxxx--------------- |
BTC/USD - RSI | https://www.tradingview.com/script/kXiR2rWs-BTC-USD-RSI/ | Rawadabdo | https://www.tradingview.com/u/Rawadabdo/ | 8 | 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/
// © Rawadabdo
// Ramy's Algorithm
//@version=5
strategy("BTC/USD - RSI", overlay=false, initial_capital = 5000)
// User input
length = input(title = "Length", defval=14, tooltip="RSI period")
first_buy_level = input(title = "Buy Level 1", defval=27, tooltip="Level where 1st buy triggers")
second_buy_level = input(title = "Buy Level 2", defval=18, tooltip="Level where 2nd buy triggers")
first_sell_level = input(title = "Sell Level 1", defval=68, tooltip="Level where 1st sell triggers")
second_sell_level = input(title = "Sell Level 2", defval=80, tooltip="Level where 2nd sell triggers")
takeProfit= input(title="target Pips", defval=2500, tooltip="Fixed pip stop loss distance")
stopLoss = input(title="Stop Pips", defval=5000, tooltip="Fixed pip stop loss distance")
lot = input(title = "Lot Size", defval = 1, tooltip="Trading Lot size")
// Get RSI
vrsi = ta.rsi(close, length)
// Entry Conditions
long1 = (vrsi <= first_buy_level and vrsi>second_buy_level)
long2 = (vrsi <= second_buy_level)
short1= (vrsi >= first_sell_level and vrsi<second_sell_level)
short2= (vrsi >= second_sell_level)
// Entry Orders
// Buy Orders
if (long1 and strategy.position_size == 0)
strategy.entry("Long", strategy.long, qty=lot, comment="Buy")
if (long2 and strategy.position_size == 0)
strategy.entry("Long", strategy.long, qty=lot, comment="Buy")
// Short Orders
if (short1 and strategy.position_size == 0)
strategy.entry("Short", strategy.short,qty=lot, comment="Sell")
if (short2 and strategy.position_size == 0)
strategy.entry("Short", strategy.short,qty=lot, comment="Sell")
// Exit our trade if our stop loss or take profit is hit
strategy.exit(id="Long Exit", from_entry="Long",qty = lot, profit=takeProfit, loss=stopLoss)
strategy.exit(id="Short Exit", from_entry="Short", qty = lot, profit=takeProfit, loss=stopLoss)
// plot data to the chart
hline(first_sell_level, "Overbought Zone", color=color.red, linestyle=hline.style_dashed, linewidth = 2)
hline(second_sell_level, "Overbought Zone", color=color.green, linestyle=hline.style_dashed, linewidth = 2)
hline(first_buy_level, "Oversold Zone", color=color.red, linestyle=hline.style_dashed, linewidth = 2)
hline(second_buy_level, "Oversold Zone", color=color.green, linestyle=hline.style_dashed, linewidth = 2)
plot (vrsi, title = "RSI", color = color.blue, linewidth=2)
|
Same high/low | https://www.tradingview.com/script/4GoyYO6B-Same-high-low/ | Cherepanov_V | https://www.tradingview.com/u/Cherepanov_V/ | 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/
// © cherepanovvsb
//@version=5
strategy("SHL", overlay=true, margin_long=100, margin_short=100,initial_capital=4,default_qty_type = strategy.cash,default_qty_value =40,commission_type = strategy.commission.percent,commission_value =0.04,currency="EUR")
atr = input.int(title="ATR length", defval=5)
plotshape(low == low[1], style=shape.triangleup, location=location.belowbar, color=color.blue, title="1 Setup")
plotshape(high==high[1], style=shape.triangledown, location=location.abovebar, color=color.blue, title="1 Setup")
plotshape(low == low[1] and low[1]==low[2], style=shape.triangleup, location=location.belowbar, color=color.red, title="Triple Setup")
plotshape(low==high[1] or low==high[2] or low==high[3] or low==high[4] or low==high[5] or low==high[6], style=shape.triangleup, location=location.belowbar, color=color.green, title="Mirror Setup")
plotshape(high==low[1] or high==low[2] or high==low[3] or high==low[4] or high==low[5] or high==low[6], style=shape.triangledown, location=location.abovebar, color=color.green, title="Mirror Setup")
barcolor(high-low>2*ta.atr(atr)? color.yellow:na)
|
Same high/low update | https://www.tradingview.com/script/ElZXBGj0-Same-high-low-update/ | Cherepanov_V | https://www.tradingview.com/u/Cherepanov_V/ | 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/
// © cherepanovvsb
//@version=5
strategy("SHL", overlay=true, margin_long=100, margin_short=100,initial_capital=100,default_qty_type = strategy.cash,default_qty_value =40,commission_type = strategy.commission.percent,commission_value =0.04,currency="EUR", process_orders_on_close=true)
atr = input.int(title="ATR length for abnormal candles", defval=5)
plotshape(low == low[1], style=shape.triangleup, location=location.belowbar, color=color.blue, title="1 Setup")
plotshape(high==high[1], style=shape.triangledown, location=location.abovebar, color=color.blue, title="1 Setup")
plotshape(low == low[1] and low[1]==low[2], style=shape.triangleup, location=location.belowbar, color=color.red, title="Triple Setup")
plotshape(low==high[1] or low==high[2] or low==high[3] or low==high[4] or low==high[5] or low==high[6], style=shape.triangleup, location=location.belowbar, color=color.green, title="Mirror Setup")
plotshape(high==low[1] or high==low[2] or high==low[3] or high==low[4] or high==low[5] or high==low[6], style=shape.triangledown, location=location.abovebar, color=color.green, title="Mirror Setup")
barcolor(high-low>2*ta.atr(atr)? color.yellow:na)
ATRlenght = input.int(title="ATR length for take profit", defval=14, group="Strategy Settings")
rewardMultiplier= input.int(title="ATR multiplier", defval=5, group="Strategy Settings")
// Get ATR
atr1 = ta.atr(ATRlenght)
validlow = low[1] == low[2] and not na(atr1)
validhigh = high[1]==high[2] and not na(atr1)
validlong = validlow and strategy.position_size == 0 and low[1]<low
validshort = validhigh and strategy.position_size == 0 and high[1]>high
// Calculate Entrance, SL/TP
longStopPrice = low[1]-syminfo.mintick
longStopDistance = close - longStopPrice
longTargetPrice = close + (longStopDistance * rewardMultiplier)
shortStopPrice = high[1]+syminfo.mintick
shortStopDistance = shortStopPrice - close
shortTargetPrice = close - (shortStopDistance * rewardMultiplier)
var tradeStopPrice = 0.0
var tradeTargetPrice = 0.0
if validlong
tradeStopPrice := longStopPrice
tradeTargetPrice := longTargetPrice
if validshort
tradeStopPrice := shortStopPrice
tradeTargetPrice := shortTargetPrice
strategy.entry ("Long", strategy.long,1, when=validlong)
strategy.entry ("Short", strategy.short,1, when=validshort)
strategy.exit(id="Long Exit", from_entry="Long", limit=tradeTargetPrice, stop=tradeStopPrice, when=strategy.position_size > 0)
strategy.exit(id="Short Exit", from_entry="Short", limit=tradeTargetPrice, stop=tradeStopPrice, when=strategy.position_size < 0)
plot(strategy.position_size != 0 or validlong or validshort ? tradeStopPrice : na, title="Trade Stop Price", color=color.red, style=plot.style_linebr, transp=0)
plot(strategy.position_size != 0 or validlong or validshort ? tradeTargetPrice : na, title="Trade Target Price", color=color.green, style=plot.style_linebr, transp=0) |
TPS - FX Trade | https://www.tradingview.com/script/2FTFsRhO/ | trademasterf | https://www.tradingview.com/u/trademasterf/ | 48 | 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/
// © MGULHANN
//@version=5
strategy("TPS - FX Trade", overlay=true)
laggingSpan2Periods = input.int(52, minval=1, title="Lead Look Back")
displacement = input.int(26, minval=1, title="Displacement")
pozyonu = input.bool(false,title="Sadece Long Yönlü Poz Aç")
// Stop Loss ve Kar Al Seviye Girişleri
TPLong = input.int(10000, minval = 30, title ="Long Kar Al Puanı", step=10)
SLLong = input.int(7500, minval = 30, title ="Long Zarar Durdur Puanı", step=10)
TPShort = input.int(20000, minval = 30, title ="Short Kar Al Puanı", step=10)
SLShort = input.int(7500, minval = 30, title ="Short Zarar Durdur Puanı", step=10)
donchian(len) => math.avg(ta.lowest(len), ta.highest(len))
leadLine = donchian(laggingSpan2Periods)
plot(leadLine, offset = displacement - 1, color=#EF9A9A,title="Lead2 Çizgisi")
buycross = ta.crossover(close,leadLine[displacement-1])
sellcross = ta.crossover(leadLine[displacement-1],close)
if (buycross) and (pozyonu == true) or buycross
strategy.entry("Long", strategy.long)
strategy.exit("Exit Long", "Long", profit=TPLong, loss=SLLong)
if (sellcross) and pozyonu == false
strategy.entry("Short", strategy.short)
strategy.exit("Exit Short", "Short", profit=TPShort, loss=SLShort)
|
Volume fight strategy | https://www.tradingview.com/script/alrI0TBw-volume-fight-strategy/ | Shuttle_Club | https://www.tradingview.com/u/Shuttle_Club/ | 544 | 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/
// © Shuttle_Club
//@version=5
strategy('Volume fight strategy', default_qty_type=strategy.cash, default_qty_value=10000, currency='USD', commission_value=0.04, calc_on_order_fills=false, calc_on_every_tick=false, initial_capital=10000)
direction = input.string('ANY', 'Direction', options=['LONG', 'SHORT', 'ANY'], tooltip='Select the direction of trade.\n\nВыберите направление торговли.')
ma = input.int(11, 'Search_range', minval=1, tooltip='The range of estimation of the predominance of bullish or bearish volume (quantity bars). The smaller the TF, the higher the range value should be used to filter out false signals.\n\nДиапазон оценки преобладания бычьего или медвежьего объема (количество баров). Чем меньше ТФ, тем выше следует использовать значение диапазона, чтобы отфильтровать ложные сигналы.')
delta = input.float(15, 'Smoothing_for_flat,%', step=0.5, minval=0, tooltip='Smoothing to reduce false signals and highlight the flat zone. If you set the percentage to zero, the flat zones will not be highlighted, but there will be much more false signals, since the indicator becomes very sensitive when the smoothing percentage decreases.\n\nСглаживание для уменьшения ложных сигналов и выделения зоны флета. Если выставить процент равным нулю, то зоны флета выделяться не будут, но будет гораздо больше ложных сигналов, так как индикатор становится очень чувствительным при снижении процента сглаживания')
bgshow = input.bool(true, 'Show background zones', tooltip='Show the color background of the current trading zone.\n\nПоказывать цветовой фон текущей торговой зоны.')
all_signal_show = input.bool(false, 'Show each setup in zone', tooltip='Show every signals into trading zone.\n\nПоказывать каждый сигнал внутри торговой зоны.')
///// CALCULATION
bull_vol = open < close ? volume : volume * (high - open) / (high - low) //determine the share of bullish volume
bear_vol = open > close ? volume : volume * (open - low) / (high - low) //determine the share of bearish volume
avg_bull_vol = ta.vwma(bull_vol, ma) //determine vwma
avg_bear_vol = ta.vwma(bear_vol, ma)
diff_vol = ta.sma(avg_bull_vol / volume - 1 - (avg_bear_vol / volume - 1), ma) //normalize and smooth the values
vol_flat = math.abs(avg_bull_vol + avg_bear_vol) / 2 //determine average value for calculation flat-filter
///// SIGNALS
up = int(na), up := nz(up[1])
dn = int(na), dn := nz(dn[1])
bull = avg_bull_vol > avg_bear_vol and vol_flat / avg_bull_vol < 1 - delta / 100 //determine up zones
bear = avg_bull_vol < avg_bear_vol and vol_flat / avg_bear_vol < 1 - delta / 100 //determine dn zones
if bull
up += 1, dn := 0
dn
if bear
dn += 1, up := 0
up
if not bull and not bear and all_signal_show
up := 0, dn := 0
dn
///// PLOTTING
plotshape(bull and up == 1, 'UP', location=location.bottom, style=shape.triangleup, color=color.new(color.green, 0), size=size.tiny)
plotshape(bear and dn == 1, 'DN', location=location.top, style=shape.triangledown, color=color.new(color.red, 0), size=size.tiny)
bgcolor(title='Trading zones', color=bgshow and avg_bull_vol > avg_bear_vol and vol_flat / avg_bull_vol < 1 - delta / 100 ? color.new(color.green, 85) : bgshow and avg_bull_vol < avg_bear_vol and vol_flat / avg_bear_vol < 1 - delta / 100 ? color.new(color.red, 85) : na)
plot(diff_vol, 'Volume difference', style=plot.style_area, color=avg_bull_vol > avg_bear_vol and vol_flat / avg_bull_vol < 1 - delta / 100 ? color.new(color.green, 0) : avg_bull_vol < avg_bear_vol and vol_flat / avg_bear_vol < 1 - delta / 100 ? color.new(color.red, 0) : color.new(color.gray, 50))
strategy.close('Short', comment='close', when=bull and up == 1)
strategy.close('Long', comment='close', when=bear and dn == 1)
strategy.entry('Long', strategy.long, when=direction != 'SHORT' and bull and up == 1)
strategy.entry('Short', strategy.short, when=direction != 'LONG' and bear and dn == 1)
if bull and up==1
alert('Bullish movement! LONG trading zone', alert.freq_once_per_bar_close)
if bear and dn==1
alert('Bearish movement! SHORT trading zone', alert.freq_once_per_bar_close)
|
Chandelier Exit - Strategy | https://www.tradingview.com/script/yca6gmSk-Chandelier-Exit-Strategy/ | melihtuna | https://www.tradingview.com/u/melihtuna/ | 719 | 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/
// © melihtuna
//@version=4
strategy("Chandelier Exit - Strategy",shorttitle="CE-STG" , overlay=true, default_qty_type=strategy.cash, default_qty_value=10000, initial_capital=10000, currency=currency.USD, commission_value=0.03, commission_type=strategy.commission.percent)
length = input(title="ATR Period", type=input.integer, defval=22)
mult = input(title="ATR Multiplier", type=input.float, step=0.1, defval=3.0)
showLabels = input(title="Show Buy/Sell Labels ?", type=input.bool, defval=false)
useClose = input(title="Use Close Price for Extremums ?", type=input.bool, defval=true)
highlightState = input(title="Highlight State ?", type=input.bool, defval=true)
atr = mult * atr(length)
longStop = (useClose ? highest(close, length) : highest(length)) - atr
longStopPrev = nz(longStop[1], longStop)
longStop := close[1] > longStopPrev ? max(longStop, longStopPrev) : longStop
shortStop = (useClose ? lowest(close, length) : lowest(length)) + 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
longStopPlot = plot(dir == 1 ? longStop : na, title="Long Stop", style=plot.style_linebr, linewidth=2, color=longColor)
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=longColor, transp=0)
plotshape(buySignal and showLabels ? longStop : na, title="Buy Label", text="Buy", location=location.absolute, style=shape.labelup, size=size.tiny, color=longColor, textcolor=color.white, transp=0)
shortStopPlot = plot(dir == 1 ? na : shortStop, title="Short Stop", style=plot.style_linebr, linewidth=2, color=shortColor)
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=shortColor, transp=0)
plotshape(sellSignal and showLabels ? shortStop : na, title="Sell Label", text="Sell", location=location.absolute, style=shape.labeldown, size=size.tiny, color=shortColor, textcolor=color.white, transp=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)
fill(midPricePlot, shortStopPlot, title="Short State Filling", color=shortFillColor)
long_short = input(true, "Long-Short",type=input.bool, group="Strategy Settings")
start = input(timestamp("2019-01-01"), "Date", type=input.time, group="Strategy Settings")
finish = input(timestamp("2025-01-01"), "Date", type=input.time, group="Strategy Settings")
window() => time >= start and time <= finish ? true : false
slRatio=input(5, "Manuel Stop Loss Ratio", type=input.float, minval=0, group="Strategy Settings")
tpRatio=input(20, "Take Profit Ratio", type=input.float, minval=0, group="Strategy Settings")
tsStartRatio=input(10, "Trailing Stop Start Ratio", type=input.float, minval=0, group="Strategy Settings")
tsRatio=input(5, "Trailing Stop Ratio", type=input.float, minval=1, group="Strategy Settings")
lastBuyPrice = strategy.position_avg_price
diffHiPriceRatio = (high-lastBuyPrice)/lastBuyPrice*100
diffLoPriceRatio = (close-lastBuyPrice)/lastBuyPrice*100
posHiRatio=0.0
posHiRatio:= strategy.position_size > 0 ? diffHiPriceRatio > posHiRatio[1] ? diffHiPriceRatio : posHiRatio[1] : 0
s_diffHiPriceRatio = (low-lastBuyPrice)/lastBuyPrice*100
s_diffLoPriceRatio = (close-lastBuyPrice)/lastBuyPrice*100
s_posHiRatio=0.0
s_posHiRatio:= strategy.position_size < 0 ? s_diffLoPriceRatio < s_posHiRatio[1] ? s_diffLoPriceRatio : s_posHiRatio[1] : 0
strategy.entry("LONG", strategy.long, when = window() and buySignal)
strategy.close("LONG", when = window() and sellSignal)
strategy.close("LONG", when = diffLoPriceRatio<(slRatio*(-1)), comment="STOP-LONG")
strategy.close("LONG", when = diffHiPriceRatio>tpRatio, comment="TAKE-PROFIT-LONG")
strategy.close("LONG", when = ((posHiRatio[1]>tsStartRatio) and (posHiRatio[1]-diffHiPriceRatio)>tsRatio), comment="TRAILING-STOP-LONG")
if long_short
strategy.entry("SHORT", strategy.short, when = window() and sellSignal)
strategy.close("SHORT", when = window() and buySignal)
strategy.close("SHORT", when = s_diffLoPriceRatio>(slRatio), comment="STOP-SHORT")
strategy.close("SHORT", when = s_diffHiPriceRatio<(tpRatio*(-1)), comment="TAKE-PROFIT-SHORT")
strategy.close("SHORT", when = ((s_posHiRatio[1]*(-1)>tsStartRatio) and ((s_posHiRatio[1]-s_diffLoPriceRatio))*(-1)>tsRatio), comment="TRAILING-STOP-SHORT") |
R3 ETF Strategy | https://www.tradingview.com/script/5CDSns2I-R3-ETF-Strategy/ | TradeAutomation | https://www.tradingview.com/u/TradeAutomation/ | 126 | 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="R3 ETF Strategy", shorttitle="R3 ETF Strategy", process_orders_on_close=true, overlay=true, commission_type=strategy.commission.cash_per_contract, commission_value=0.0035, initial_capital = 1000000, default_qty_type=strategy.percent_of_equity, default_qty_value=100)
// Backtest Date Range Inputs //
StartTime = input.time(defval=timestamp('01 Jan 2010 05:00 +0000'), title='Start Time')
EndTime = input.time(defval=timestamp('01 Jan 2099 00:00 +0000'), title='End Time')
InDateRange = time>=StartTime and time<=EndTime
// Calculations and Inputs //
RSILen = input.int(2, "RSI Length")
RSI = ta.rsi(close, RSILen)
TodaysMinRSI = input.int(10, "Today's Min RSI for Entry", tooltip = "The RSI must be below this number today to qualify for trade entry")
ExitRSI = input.int(70, "Exit RSI", tooltip = "The strategy will sell when the RSI crosses over this number")
Day3RSIMax = input.int(60, "Max RSI 3 Days Ago for Entry", tooltip = "The RSI must be below this number 3 days ago to qualify for trade entry")
EMAQualInput = input.bool(false, "Only enter trades when above qualifier EMA?", tooltip="When this is selected, a trade will only be entered when the price is above the EMA qualifier line.")
QEMA = ta.ema(close, input.int(200, "EMA Trade Qualifier Length"))
// Strategy Rules //
Rule1 = close>QEMA
Rule2 = RSI[3]<Day3RSIMax and RSI<TodaysMinRSI
Rule3 = RSI<RSI[1] and RSI[1]<RSI[2] and RSI[2]<RSI[3]
Exit = ta.crossover(RSI, ExitRSI)
// Plot //
plot(QEMA, "200 Day EMA")
// Entry & Exit Functions //
if (InDateRange and Rule1 and Rule2 and Rule3 and EMAQualInput==true)
strategy.entry("Long", strategy.long, alert_message="Long")
if (InDateRange and Rule2 and Rule3 and EMAQualInput==false)
strategy.entry("Long", strategy.long, alert_message="Long")
if (InDateRange)
strategy.close("Long", when = Exit, alert_message="Close Long")
if (not InDateRange)
strategy.close_all(alert_message="Out of Date Range") |
Automated Bitcoin (BTC) Investment Strategy from Wunderbit | https://www.tradingview.com/script/0mCr8Nfv-Automated-Bitcoin-BTC-Investment-Strategy-from-Wunderbit/ | Wunderbit | https://www.tradingview.com/u/Wunderbit/ | 674 | 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/
// © Wunderbit Trading
//@version=5
strategy('Automated Bitcoin (BTC) Investment Strategy', overlay=true, initial_capital=5000, pyramiding=0, currency='USD', default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=0.1)
//////////// Functions
Atr(p) =>
atr = 0.
Tr = math.max(high - low, math.max(math.abs(high - close[1]), math.abs(low - close[1])))
atr := nz(atr[1] + (Tr - atr[1]) / p, Tr)
atr
//TEMA
TEMA(series, length) =>
if length > 0
ema1 = ta.ema(series, length)
ema2 = ta.ema(ema1, length)
ema3 = ta.ema(ema2, length)
3 * ema1 - 3 * ema2 + ema3
else
na
tradeType = input.string('LONG', title='What trades should be taken : ', options=['LONG', 'SHORT', 'BOTH', 'NONE'])
///////////////////////////////////////////////////
/// INDICATORS
source = close
/// TREND
trend_type1 = input.string('TEMA', title='First Trend Line : ', options=['LSMA', 'TEMA', 'EMA', 'SMA'])
trend_type2 = input.string('LSMA', title='First Trend Line : ', options=['LSMA', 'TEMA', 'EMA', 'SMA'])
trend_type1_length = input(25, 'Length of the First Trend Line')
trend_type2_length = input(100, 'Length of the Second Trend Line')
leadLine1 = if trend_type1 == 'LSMA'
ta.linreg(close, trend_type1_length, 0)
else if trend_type1 == 'TEMA'
TEMA(close, trend_type1_length)
else if trend_type1 == 'EMA'
ta.ema(close, trend_type1_length)
else
ta.sma(close, trend_type1_length)
leadLine2 = if trend_type2 == 'LSMA'
ta.linreg(close, trend_type2_length, 0)
else if trend_type2 == 'TEMA'
TEMA(close, trend_type2_length)
else if trend_type2 == 'EMA'
ta.ema(close, trend_type2_length)
else
ta.sma(close, trend_type2_length)
p3 = plot(leadLine1, color=color.new(#53b987, 50), title='EMA', linewidth=1)
p4 = plot(leadLine2, color=color.new(#eb4d5c, 50), title='SMA', linewidth=1)
fill(p3, p4, color=leadLine1 > leadLine2 ? #53b987 : #eb4d5c, transp=60)
//Upward Trend
UT = ta.crossover(leadLine1, leadLine2)
DT = ta.crossunder(leadLine1, leadLine2)
// TP/ SL/ FOR LONG
// TAKE PROFIT AND STOP LOSS
long_tp1_inp = input.float(15, title='Long Take Profit 1 %', step=0.1) / 100
long_tp1_qty = input.int(20, title='Long Take Profit 1 Qty', step=1)
long_tp2_inp = input.float(30, title='Long Take Profit 2%', step=0.1) / 100
long_tp2_qty = input.int(20, title='Long Take Profit 2 Qty', step=1)
long_take_level_1 = strategy.position_avg_price * (1 + long_tp1_inp)
long_take_level_2 = strategy.position_avg_price * (1 + long_tp2_inp)
long_sl_input = input.float(5, title='stop loss in %', step=0.1) / 100
long_sl_input_level = strategy.position_avg_price * (1 - long_sl_input)
// Stop Loss
multiplier = input.float(3.5, 'SL Mutiplier', minval=1, step=0.1)
ATR_period = input.int(8, 'ATR period', minval=1, step=1)
// Strategy
//LONG STRATEGY CONDITION
SC = input(close, 'Source')
SL1 = multiplier * Atr(ATR_period) // Stop Loss
Trail1 = 0.0
iff_1 = SC > nz(Trail1[1], 0) ? SC - SL1 : SC + SL1
Trail1 := SC < nz(Trail1[1], 0) and SC[1] < nz(Trail1[1], 0) ? math.min(nz(Trail1[1], 0), SC + SL1) : iff_1
Trail1_high = ta.highest(Trail1, 50)
// iff(SC > nz(Trail1[1], 0) and SC[1] > nz(Trail1[1], 0), max(nz(Trail1[1], 0), SC - SL1),
entry_long = ta.crossover(leadLine1, leadLine2) and Trail1_high < close
exit_long = close < Trail1_high or ta.crossover(leadLine2, leadLine1) or close < long_sl_input_level
///// BACKTEST PERIOD ///////
testStartYear = input(2016, 'Backtest Start Year')
testStartMonth = input(1, 'Backtest Start Month')
testStartDay = input(1, 'Backtest Start Day')
testPeriodStart = timestamp(testStartYear, testStartMonth, testStartDay, 0, 0)
testStopYear = input(9999, 'Backtest Stop Year')
testStopMonth = input(12, 'Backtest Stop Month')
testStopDay = input(31, 'Backtest Stop Day')
testPeriodStop = timestamp(testStopYear, testStopMonth, testStopDay, 0, 0)
testPeriod() =>
time >= testPeriodStart and time <= testPeriodStop ? true : false
if testPeriod()
if tradeType == 'LONG' or tradeType == 'BOTH'
if strategy.position_size == 0 or strategy.position_size > 0
strategy.entry('long', strategy.long, comment='b8f60da7_ENTER-LONG_BINANCE_BTC/USDT_b8f60da7-BTC-Investment_4H', when=entry_long)
strategy.exit('TP1', 'long', qty_percent=long_tp1_qty, limit=long_take_level_1)
strategy.exit('TP2', 'long', qty_percent=long_tp2_qty, limit=long_take_level_2)
strategy.close('long', when=exit_long, comment='b8f60da7_EXIT-LONG_BINANCE_BTC/USDT_b8f60da7-BTC-Investment_4H')
// LONG POSITION
plot(strategy.position_size > 0 ? long_take_level_1 : na, style=plot.style_linebr, color=color.new(color.green, 0), linewidth=1, title='1st Long Take Profit')
plot(strategy.position_size > 0 ? long_take_level_2 : na, style=plot.style_linebr, color=color.new(color.green, 0), linewidth=1, title='2nd Long Take Profit')
plot(strategy.position_size > 0 ? Trail1_high : na, style=plot.style_linebr, color=color.new(color.red, 0), linewidth=1, title='Long Stop Loss')
|
Gann HiLo Activator Strategy | https://www.tradingview.com/script/PyFdxzcj-Gann-HiLo-Activator-Strategy/ | starbolt | https://www.tradingview.com/u/starbolt/ | 253 | 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/
// © starbolt
//@version=5
strategy('Gann HiLo Activator Strategy', overlay=true, pyramiding=0, default_qty_type=strategy.percent_of_equity, default_qty_value=20, initial_capital=1000, process_orders_on_close=true)
len = input.int(3, 'Length', step=1, minval=1)
displace = input.int(1, 'Offset', step=1, minval=0)
from_start = input(false, 'Begin from start?')
backtest_year = input(2017, 'From Year')
backtest_month = input.int(01, 'From Month', minval=1, maxval=12, step=1)
backtest_day = input.int(01, 'From Day', minval=1, maxval=31, step=1)
start_time = from_start ? 0 : timestamp(backtest_year, backtest_month, backtest_day, 00, 00)
float hilo = na
hi = ta.sma(high, len)
lo = ta.sma(low, len)
hilo := close > hi[displace] ? 1 : close < lo[displace] ? -1 : hilo[1]
ghla = hilo == -1 ? hi[displace] : lo[displace]
color = hilo == -1 ? color.red : color.green
buyCondition = hilo == 1 and hilo[1] == -1
sellCondition = hilo == -1 and hilo[1] == 1
if buyCondition and time >= start_time
strategy.entry('Long', strategy.long)
if sellCondition and time >= start_time
strategy.entry('Short', strategy.short)
plot(ghla, color=color, style=plot.style_cross)
|
Buy Monday, Exit Tuesday with Stop Loss and Take Profit | https://www.tradingview.com/script/dT5bJuH0-Buy-Monday-Exit-Tuesday-with-Stop-Loss-and-Take-Profit/ | processingclouds | https://www.tradingview.com/u/processingclouds/ | 213 | 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/
// © processingclouds
// @description Strategy to go long at end of Monday and exit by Tuesday close, or at stop loss or take profit percentages
//@version=5
strategy("Buy Monday, Exit Tuesday", "Mon-Tue Swings",overlay=true)
// ----- Inputs: stoploss %, takeProfit %
stopLossPercentage = input.float(defval=4.0, title='StopLoss %', minval=0.1, step=0.2) / 100
takeProfit = input.float(defval=3.0, title='Take Profit %', minval=0.3, step=0.2) / 100
// ----- Exit and Entry Conditions - Check current day and session time
isLong = dayofweek == dayofweek.monday and not na(time(timeframe.period, "1400-1601"))
isExit = dayofweek == dayofweek.tuesday and not na(time(timeframe.period, "1400-1601"))
// ----- Calculate Stoploss and Take Profit values
SL = strategy.position_avg_price * (1 - stopLossPercentage)
TP = strategy.position_avg_price * (1 + takeProfit)
// ----- Strategy Enter, and exit when conditions are met
strategy.entry("Enter Long", strategy.long, when=isLong)
if strategy.position_size > 0
strategy.close("Enter Long", isExit)
strategy.exit(id="Exit", stop=SL, limit=TP)
// ----- Plot Stoploss and TakeProfit lines
plot(strategy.position_size > 0 ? SL : na, style=plot.style_linebr, color=color.red, linewidth=2, title="StopLoss")
plot(strategy.position_size > 0 ? TP : na, style=plot.style_linebr, color=color.green, linewidth=2, title="TakeProfit")
|
STR:EMA Oscilator [Azzrael] | https://www.tradingview.com/script/fS0O2J8J-STR-EMA-Oscilator-Azzrael/ | Azzrael | https://www.tradingview.com/u/Azzrael/ | 354 | 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/
// © Azzrael
// Based on EMA and EMA Oscilator https://www.tradingview.com/script/qM9wm0PW-EMA-Oscilator-Azzrael/
// (EMA - close) + Std Dev + Factor = detecting oversell/overbuy
// Long only!
// Pyramiding - sometimes, depends on ...
// There 2 enter strategies in one script
// 1 - Classic, buy on entering to OverSell zone (more profitable ~> 70%)
// 2 - Crazy, buy on entering to OverBuy zone (catching trend and pyramiding, more net profit)
// Exit - crossing zero of (EMA - close)
//@version=5
strategy("STR:EMA Oscilator [Azzrael]", overlay=false,
initial_capital=1000,
default_qty_type=strategy.percent_of_equity,
default_qty_value=30,
pyramiding=3,
commission_type=strategy.commission.percent,
commission_value=0.1
)
ema_length = input.int(200, "Period", minval=2, step=10)
limit = input.float(1.7, "Factor", minval=1, step=0.1, maxval=10)
dno = input.string(defval="Buy on enter to OverSell", title="Model", options=["Buy on enter to OverSell", "Buy on enter to OverBuy"]) == "Buy on enter to OverSell"
dt_start = input.time(defval=timestamp('01 January 2001 00:00 +0000'), title='Start', group ="Backtest period")
dt_end = input.time(defval=timestamp('01 January 2030 00:00 +0000'), title='Finish', group ="Backtest period")
bar_in_period = time >= dt_start and time <= dt_end
v = close - ta.ema(close, ema_length)
dev = ta.stdev(v, ema_length)
k = dno ? -1 : 1
dev_limit = k*dev*limit
cond_long = barstate.isconfirmed and bar_in_period and (dno ? ta.crossunder(v, dev_limit) : ta.crossover(v, dev_limit))
cond_close = barstate.isconfirmed and bar_in_period and ta.cross(v, 0)
// dev visualization
sig_col = (dno and v <= dev_limit) or (not dno and v >= dev_limit) ? color.green : color.new(color.blue, 80)
plot(dev_limit, color=color.green)
plot(k*dev, color=color.new(color.blue, 60))
plot(v, color=sig_col )
hline(0)
// Make love not war
if cond_long
entry_name="b" + str.tostring(strategy.opentrades)
strategy.entry(entry_name, strategy.long)
if cond_close and strategy.position_size > 0
strategy.close_all("s")
if time >= dt_end or barstate.islastconfirmedhistory
strategy.close_all("last")
|
Volatility Breakout Strategy | https://www.tradingview.com/script/vzWeDyXd-Volatility-Breakout-Strategy/ | Dicargo_Beam | https://www.tradingview.com/u/Dicargo_Beam/ | 359 | 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/
// © Dicargo_Beam
//@version=5
strategy("Volatility Breakout Strategy", overlay=true, default_qty_type= strategy.percent_of_equity, default_qty_value=100)
k = input.float(0.6)
f_security(_sym, _res, _src) =>
request.security(_sym, _res, _src[barstate.isrealtime ? 1 : 0])[barstate.isrealtime ? 0 : 1]
o = f_security(syminfo.tickerid,"D",open)
h = f_security(syminfo.tickerid,"D",high)
l = f_security(syminfo.tickerid,"D",low)
c = f_security(syminfo.tickerid,"D",close)
var lp = 0.0
var sl = 0.0
var sp = 0.0
var sl2 = 0.0
if hour[1]-hour>1
lp := c+(h-l)*k
sl := (l+lp)/2
sp := c-(h-l)*k
sl2 := (h+sp)/2
longcond = lp < high
exit = hour[1]-hour>1 or close < sl
plot(lp,"Long Entry",color=color.yellow)
plot(sl,"Long StopLoss",color=color.red)
exit2 = hour[1]-hour>1 or close > sl2
shortcond = sp > low
shortopen = input.bool(false,"Short Postion Open??")
plot(shortopen? sp : na,"Short Entry",color=color.new(color.yellow,50))
plot(shortopen? sl2 : na,"Short StopLoss",color=color.new(color.red,50))
trend = input.bool(false,"Trend Following?")
longtrend = trend? lp/sl > sl2/sp : true
shorttrend = trend? lp/sl < sl2/sp : true
strategy.entry("Long", strategy.long,comment = "Long", when = longcond and strategy.opentrades == 0 and longtrend)
strategy.close("Long", comment="Long Exit", when = exit)
if shortopen
strategy.entry("Short", strategy.short,comment = "Short", when = shortcond and strategy.opentrades == 0 and shorttrend)
strategy.close("Short", comment="Short Exit", when = exit2)
var bg = 0
if hour[1]-hour>1
bg := bg + 1
bgcolor(bg/2== math.floor(bg/2) ? color.new(color.blue,95):na)
|
Follow The Ranging Hull | https://www.tradingview.com/script/gXpRI80z-Follow-The-Ranging-Hull/ | flygalaxies | https://www.tradingview.com/u/flygalaxies/ | 401 | 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/
// © flygalaxies
// Strategy based on the Follow Line Indicator by Dreadblitz, Hull Suite by InSilico and Range Filter Buy and Sell 5 min by guikroth
// Designed for the purpose of back testing
// Strategy:
// - When the Range Filter Color Changes, And the HULL Suite is in that direction, Enter In that direction
// - e.g Range Filter Changes color from red to green, and Hull Suite is in Green. Enter Long
// - e.g Range Filter Changes color from green to red, and Hull Suite is in red. Enter Short
//
// - When the Following Line Color Changes, And the HULL Suite is in that direction, Enter In that direction
// - e.g Following Line Changes color from red to green, and Hull Suite is in Green. Enter Long
// - e.g Following Line Changes color from green to red, and Hull Suite is in red. Enter Short
//
// Credits:
// Hull Suite by InSilico https://www.tradingview.com/u/InSilico/
// Range Filter Buy and Sell 5 min https://www.tradingview.com/u/guikroth/
// Follow Line Indicator by Dreadblitz https://www.tradingview.com/u/Dreadblitz/
//@version=5
strategy("Follow The Ranging Hull", overlay=true, initial_capital = 50000, process_orders_on_close = true)
/////////////////////////
// STRATEGY SETTINGS ///
///////////////////////
fromDate = input.time(title="From", defval=timestamp("01 Jan 2022 00:00 GMT+2"), inline="1", group="Date Range")
toDate = input.time(title="To", defval=timestamp("01 Jan 2022 23:00 GMT+2"), inline="1", group="Date Range")
inDate = time >= fromDate and time <= toDate
isStrategy = input.bool(title="IS STRATEGY", defval = false, group="Trading Rules")
isPointRule = input.bool(title="Apply Point Rule", defval = false, group="Trading Rules")
pointRulePoints = input.int(title="Points (The points that it uses to take profit)", defval = 80, group="Trading Rules")
////////////////////////////////////
// FOLLOWING, ENTRY, EXIT RULES ///
//////////////////////////////////
followLineUseATR = input.bool(title="Use ATR for the Following Line (if false, it will use the slow range filter)", defval = true, group="Following, Entry, Exit Rules")
followRngFilterEntry = input.bool(title="use Following line or Slow Range Filter as entry point", defval = false, group="Following, Entry, Exit Rules")
showStatusWindow = input.bool(title="Show Status Window (BETA)", defval = false, group="Following, Entry, Exit Rules")
hl = input.bool(defval = false, title = "Hide Labels", group = "Following, Entry, Exit Rules")
exitRule = input.session("Hull", title="Exit Rule", options=["Hull", "RangeFilter", "Following/SlowRangeFilter"], group="Following, Entry, Exit Rules")
////////////////////
// COLOR INPUTS ///
//////////////////
rngFilterColorUp = input.color(title="Fast Range Filter Color Up", defval = color.green, group="Range Filter Colors")
rngFilterColorDown = input.color(title="Fast Range Filter Color Down", defval = color.red, group="Range Filter Colors")
rngFilterColorUpSlow = input.color(title="Slow Range Filter Color Up", defval = color.green, group="Range Filter Colors")
rngFilterColorDownSlow = input.color(title="Slow Range Filter Color Down", defval = color.red, group="Range Filter Colors")
hullColorUp = input.color(title="Hull Color Up", defval = color.green, group="Hull Suite Colors")
hullColorDown = input.color(title="Hull Color Down", defval = color.red, group="Hull Suite Colors")
fliColorUp = input.color(title="Follow Line Color Up", defval = color.green, group="Following Line Colors")
fliColorDown = input.color(title="Follow Line Color Down", defval = color.red, group="Following Line Colors")
///////////////////////////
// Range Filter INPUTS ///
/////////////////////////
// Fast Inputs
src = input(defval=ohlc4, title="Range Filter Fast Source", group="Range Filter Fast")
per = input.int(defval=33, minval=1, title="Range Filter Fast Sampling Period", group="Range Filter Fast")
mult = input.float(defval=2.1, minval=0.1, title="Range Filter Fast Multiplier", group="Range Filter Fast", step=0.1)
// Slow Inputs
srcSlow = input(defval=ohlc4, title="Range Filter Slow Source", group="Range Filter Slow")
perSlow = input.int(defval=48, minval=1, title="Range Filter Slow Sampling Period", group="Range Filter Slow")
multSlow = input.float(defval=3.4, minval=0.1, title="Range Filter Slow Multiplier", group="Range Filter Slow", step=0.1)
/////////////////////////
// Hull Suite INPUTS ///
///////////////////////
srcHull = input(close, title="Source", group="Hull Suite")
modeSwitch = input.session("Ehma", title="Hull Variation", options=["Hma", "Thma", "Ehma"], group="Hull Suite")
length = input(55, title="Length(180-200 for floating S/R , 55 for swing entry)")
switchColor = input(true, "Color Hull according to trend?", group="Hull Suite")
visualSwitch = input(true, title="Show as a Band?", group="Hull Suite")
thicknesSwitch = input(1, title="Line Thickness", group="Hull Suite")
transpSwitch = input.int(40, title="Band Transparency",step=5, group="Hull Suite")
//////////////////////////
// FOLLOW LINE INPUTS ///
////////////////////////
BBperiod = input.int(defval = 21, title = "BB Period", minval = 1, group = "Following Line ")
BBdeviations = input.float(defval = 1.00, title = "BB Deviations", minval = 0.1, step=0.05, group = "Following Line ")
UseATRfilter = input.bool(defval = true, title = "ATR Filter", group = "Following Line ")
ATRperiod = input.int(defval = 5, title = "ATR Period", minval = 1, group = "Following Line ")
//////////////////////////
// Range Filter Logic ///
////////////////////////
// Fast
smoothrng(x, t, m) =>
wper = t * 2 - 1
avrng = ta.ema(math.abs(x - x[1]), t)
smoothrng = ta.ema(avrng, wper) * m
smoothrng
smrng = smoothrng(src, per, mult)
rngfilt(x, r) =>
rngfilt = x
rngfilt := x > nz(rngfilt[1]) ? x - r < nz(rngfilt[1]) ? nz(rngfilt[1]) : x - r :
x + r > nz(rngfilt[1]) ? nz(rngfilt[1]) : x + r
rngfilt
filt = rngfilt(src, smrng)
upward = 0.0
upward := filt > filt[1] ? nz(upward[1]) + 1 : filt < filt[1] ? 0 : nz(upward[1])
downward = 0.0
downward := filt < filt[1] ? nz(downward[1]) + 1 : filt > filt[1] ? 0 : nz(downward[1])
filtcolor = upward > 0 ? rngFilterColorUp : downward > 0 ? rngFilterColorDown : color.orange
filtplot = plot(filt, color=filtcolor, linewidth=3, title="Fast Range Filter ")
// Slow
smoothrngSlow(x, t, m) =>
wper = t * 2 - 1
avrng = ta.ema(math.abs(x - x[1]), t)
smoothrngSlow = ta.ema(avrng, wper) * m
smoothrngSlow
smrngSlow = smoothrngSlow(srcSlow, perSlow, multSlow)
rngfiltSlow(x, r) =>
rngfilt = x
rngfilt := x > nz(rngfilt[1]) ? x - r < nz(rngfilt[1]) ? nz(rngfilt[1]) : x - r :
x + r > nz(rngfilt[1]) ? nz(rngfilt[1]) : x + r
rngfilt
filtSlow = rngfiltSlow(srcSlow, smrngSlow)
upwardSlow = 0.0
upwardSlow := filtSlow > filtSlow[1] ? nz(upwardSlow[1]) + 1 : filtSlow < filtSlow[1] ? 0 : nz(upwardSlow[1])
downwardSlow = 0.0
downwardSlow := filtSlow < filtSlow[1] ? nz(downwardSlow[1]) + 1 : filtSlow > filtSlow[1] ? 0 : nz(downwardSlow[1])
filtcolorSlow = upwardSlow > 0 ? rngFilterColorUpSlow : downwardSlow > 0 ? rngFilterColorDownSlow : color.orange
filtplotSlow = plot(followLineUseATR == false ? filtSlow : na, color=filtcolorSlow, linewidth=3, title="Slow Range Filter")
////////////////////////
// Hull Suite Logic ///
//////////////////////
HMA(_srcHull, _length) => ta.wma(2 * ta.wma(_srcHull, _length / 2) - ta.wma(_srcHull, _length), math.round(math.sqrt(_length)))
EHMA(_srcHull, _length) => ta.ema(2 * ta.ema(_srcHull, _length / 2) - ta.ema(_srcHull, _length), math.round(math.sqrt(_length)))
THMA(_srcHull, _length) => ta.wma(ta.wma(_srcHull,_length / 3) * 3 - ta.wma(_srcHull, _length / 2) - ta.wma(_srcHull, _length), _length)
Mode(modeSwitch, src, len) =>
modeSwitch == "Hma" ? HMA(src, len) :
modeSwitch == "Ehma" ? EHMA(src, len) :
modeSwitch == "Thma" ? THMA(src, len/2) : na
_hull = Mode(modeSwitch, src, int(length))
HULL = _hull
MHULL = HULL[0]
SHULL = HULL[2]
// HIGHER TIMEFRAME HULL
HULL1 = request.security(syminfo.ticker, "1", _hull)
HULL5 = request.security(syminfo.ticker, "5", _hull)
HULL15 = request.security(syminfo.ticker, "15", _hull)
HULL3 = request.security(syminfo.ticker, "3", _hull)
hullColor = switchColor ? (HULL > HULL[2] ? hullColorUp : hullColorDown) : #ff9800
Fi1 = plot(MHULL, title="MHULL", color=hullColor, linewidth=thicknesSwitch, transp=50)
Fi2 = plot(visualSwitch ? SHULL : na, title="SHULL", color=hullColor, linewidth=thicknesSwitch, transp=50)
fill(Fi1, Fi2, title="Band Filler", color=hullColor, transp=transpSwitch)
/////////////////////////
// Follow Line Logic ///
///////////////////////
BBUpper=ta.sma (close,BBperiod)+ta.stdev(close, BBperiod)*BBdeviations
BBLower=ta.sma (close,BBperiod)-ta.stdev(close, BBperiod)*BBdeviations
TrendLine = 0.0
iTrend = 0.0
buy = 0.0
sell = 0.0
BBSignal = close>BBUpper? 1 : close<BBLower? -1 : 0
if BBSignal == 1 and UseATRfilter == 1
TrendLine:=low-ta.atr(ATRperiod)
if TrendLine<TrendLine[1]
TrendLine:=TrendLine[1]
if BBSignal == -1 and UseATRfilter == 1
TrendLine:=high+ta.atr(ATRperiod)
if TrendLine>TrendLine[1]
TrendLine:=TrendLine[1]
if BBSignal == 0 and UseATRfilter == 1
TrendLine:=TrendLine[1]
if BBSignal == 1 and UseATRfilter == 0
TrendLine:=low
if TrendLine<TrendLine[1]
TrendLine:=TrendLine[1]
if BBSignal == -1 and UseATRfilter == 0
TrendLine:=high
if TrendLine>TrendLine[1]
TrendLine:=TrendLine[1]
if BBSignal == 0 and UseATRfilter == 0
TrendLine:=TrendLine[1]
iTrend:=iTrend[1]
if TrendLine>TrendLine[1]
iTrend:=1
if TrendLine<TrendLine[1]
iTrend:=-1
buy:= iTrend[1]==-1 and iTrend==1 and followLineUseATR == true ? 1 : na
sell:= iTrend[1]==1 and iTrend==-1 and followLineUseATR == true ? 1 : na
plot(followLineUseATR == true ? TrendLine : na, color=iTrend > 0? fliColorUp : fliColorDown ,style=plot.style_line,linewidth=2,transp=0,title="Trend Line")
///////////////////////////
// STATUS WINDOW LOGIC ///
/////////////////////////
if(showStatusWindow == true )
var table statuswindow = table.new(position.top_right, 100, 100, border_width=2)
txt1 = "🡇 Hull 1 min 🡇"
table.cell(statuswindow, 1, 0, text=txt1, bgcolor=color.new(#000000, 50), text_color=color.white, text_size=size.small)
if(HULL1 > HULL1[2])
table.cell(statuswindow, 1, 1, text='', bgcolor=hullColorUp, text_color=color.white, text_size=size.small)
else
table.cell(statuswindow, 1, 1, text='', bgcolor=hullColorDown, text_color=color.white, text_size=size.small)
txt3 = "🡇 Hull 3 min 🡇"
table.cell(statuswindow, 2, 0, text=txt3, bgcolor=color.new(#000000, 50), text_color=color.white, text_size=size.small)
if(HULL3 > HULL3[2])
table.cell(statuswindow, 2, 1, text='', bgcolor=hullColorUp, text_color=color.white, text_size=size.small)
else
table.cell(statuswindow, 2, 1, text='', bgcolor=hullColorDown, text_color=color.white, text_size=size.small)
txt5 = "🡇 Hull 5 min 🡇"
table.cell(statuswindow, 3, 0, text=txt5, bgcolor=color.new(#000000, 50), text_color=color.white, text_size=size.small)
if(HULL5 > HULL5[2])
table.cell(statuswindow, 3, 1, text='', bgcolor=hullColorUp, text_color=color.white, text_size=size.small)
else
table.cell(statuswindow, 3, 1, text='', bgcolor=hullColorDown, text_color=color.white, text_size=size.small)
txt15 = "🡇 Hull 15 min 🡇"
table.cell(statuswindow, 4, 0, text=txt15, bgcolor=color.new(#000000, 50), text_color=color.white, text_size=size.small)
if(HULL15 > HULL15[2])
table.cell(statuswindow, 4, 1, text='', bgcolor=hullColorUp, text_color=color.white, text_size=size.small)
else
table.cell(statuswindow, 4, 1, text='', bgcolor=hullColorDown, text_color=color.white, text_size=size.small)
////////////////////////////////////////////
// ALERTS & LABELS BASED ON ENTRY POINT ///
//////////////////////////////////////////
plotshape((filtcolor[1] == rngFilterColorDown and filtcolor == rngFilterColorUp )and hl == false and HULL > HULL[2] ? TrendLine-ta.atr(8) :na, text='BUY', style= shape.labelup, location=location.absolute, color=color.blue, textcolor=color.white, offset=0, transp=0,size=size.auto)
plotshape((filtcolor[1] == rngFilterColorUp and filtcolor == rngFilterColorDown) and hl == false and HULL < HULL[2] ?TrendLine+ta.atr(8):na, text='SELL', style=shape.labeldown, location=location.absolute, color=color.red, textcolor=color.white, offset=0, transp=0,size=size.auto)
plotshape(followRngFilterEntry == true and followLineUseATR == true and buy == 1 and hl == false and HULL > HULL[2] ? TrendLine-ta.atr(8) :na, text='BUY', style= shape.labelup, location=location.absolute, color=color.blue, textcolor=color.white, offset=0, transp=0,size=size.auto)
plotshape(followRngFilterEntry == true and followLineUseATR == true and sell == 1 and hl == false and HULL < HULL[2] ? TrendLine+ta.atr(8):na, text='SELL', style=shape.labeldown, location=location.absolute, color=color.red, textcolor=color.white, offset=0, transp=0,size=size.auto)
plotshape(followRngFilterEntry == true and followLineUseATR == false and (filtcolorSlow[1] == rngFilterColorDownSlow and filtcolorSlow == rngFilterColorUpSlow) and hl == false and HULL > HULL[2] ? TrendLine-ta.atr(8) :na, text='BUY', style= shape.labelup, location=location.absolute, color=color.blue, textcolor=color.white, offset=0, transp=0,size=size.auto)
plotshape(followRngFilterEntry == true and followLineUseATR == false and (filtcolorSlow[1] == rngFilterColorUpSlow and filtcolorSlow == rngFilterColorDownSlow) and hl == false and HULL < HULL[2] ?TrendLine+ta.atr(8):na, text='SELL', style=shape.labeldown, location=location.absolute, color=color.red, textcolor=color.white, offset=0, transp=0,size=size.auto)
//////////////////////////////////
// STRATEGY ENTRY POINT LOGIC ///
////////////////////////////////
if(inDate and isStrategy)
// RANGE FILTER ENTRY LONG WITH HULL
if(filtcolor[1] == rngFilterColorDown and filtcolor == rngFilterColorUp)
strategy.entry("rngFiltLong", strategy.long, when = HULL > HULL[2])
// RANGE FILTER ENTRY SHORT WITH HULL
if(filtcolor[1] == rngFilterColorUp and filtcolor == rngFilterColorDown)
strategy.entry("rngFiltShort", strategy.short, when = HULL < HULL[2])
// FOLLOW LINE OR SLOW RANGE FILTER ENTRY, IF ENABLED
if(followRngFilterEntry == true)
if(followLineUseATR == true)
// FOLLOWING LINE ENTRY SHORT WITH HULL
if(buy == 1)
strategy.entry("fliLong", strategy.long, when = HULL > HULL[2])
// FOLLOWING LINE ENTRY SHORT WITH HULL
if(sell == 1)
strategy.entry("fliShort", strategy.short, when = HULL < HULL[2])
else
// SLOW RANGE FILTER ENTRY WITH HULL
if(filtcolorSlow[1] == rngFilterColorDownSlow and filtcolorSlow == rngFilterColorUpSlow)
strategy.entry("slowRngFiltLong", strategy.long, when = HULL > HULL[2])
// SLOW RANGE FILTER ENTRY SHORT WITH HULL
if(filtcolorSlow[1] == rngFilterColorUpSlow and filtcolorSlow == rngFilterColorDownSlow)
strategy.entry("slowRngFiltShort", strategy.short, when = HULL < HULL[2])
if(isPointRule)
strategy.exit('exitRngFiltLong', 'rngFiltLong', profit=pointRulePoints)
strategy.exit('exitRngFiltShort', 'rngFiltShort', profit=pointRulePoints)
strategy.exit('exitSlowRngFiltLong', 'slowRngFiltLong', profit=pointRulePoints)
strategy.exit('exitSlowRngFiltShort', 'slowRngFiltShort', profit=pointRulePoints)
strategy.exit('exitFliLong', 'fliLong', profit=pointRulePoints, when = sell == 1)
strategy.exit('exitFliShort', 'fliShort', profit=pointRulePoints , when = buy == 1)
closingRuleLong = exitRule == "Hull" ? HULL > HULL[2] : exitRule == "RangeFilter" ? (filtcolor[2] == rngFilterColorUp and filtcolor == rngFilterColorDown) : exitRule == "Following/SlowRangeFilter" ? followLineUseATR == false? (sell == 1): (filtcolor[2] == rngFilterColorUp and filtcolor == rngFilterColorDown): na
closingRuleShort = exitRule == "Hull" ? HULL > HULL[2] : exitRule == "RangeFilter" ? (filtcolor[1] == rngFilterColorDown and filtcolor == rngFilterColorUp) : exitRule == "Following/SlowRangeFilter" ? followLineUseATR == true ? (buy == 1) : (filtcolor[2] == rngFilterColorDown and filtcolor == rngFilterColorUp) : na
strategy.close("rngFiltLong", when = closingRuleLong)
strategy.close("rngFiltShort", when = closingRuleShort)
strategy.close("slowRngFiltLong", when = closingRuleLong)
strategy.close("slowRngFiltShort", when = closingRuleShort)
strategy.close("fliLong", when = closingRuleLong)
strategy.close("fliShort", when = closingRuleShort)
|
sma RSI & sudden buy and sell Strategy v1 | https://www.tradingview.com/script/zof6INTO-sma-RSI-sudden-buy-and-sell-Strategy-v1/ | samwillington | https://www.tradingview.com/u/samwillington/ | 67 | 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/
// © samwillington
//@version=5
strategy("sma RSI & sudden buy and sell Strategy v1", overlay=true)
price = close
length = input( 14 )
inst_length = input( 10 )
var rbc = 0
var float rsiBP = 0.0
var rsc = 0
var float rsiSP = 0.0
bars = input(10)
lookbackno2 = input.int(20)
rsi_buy = 0
rsi_sell = 0
//EMA inputs
input_ema20 = input.int(20)
ema20 = ta.ema(price, input_ema20)
input_ema50 = input.int(50)
ema50 = ta.ema(price, input_ema50)
input_ema100 = input.int(100)
ema100 = ta.ema(price, input_ema100)
input_ema200 = input.int(200)
ema200 = ta.ema(price, input_ema200)
input_ema400 = input.int(400)
ema400 = ta.ema(price, input_ema400)
input_ema800 = input.int(800)
ema800 = ta.ema(price, input_ema800)
vrsi = ta.rsi(price, length)
hi2 = ta.highest(price, lookbackno2)
lo2 = ta.lowest(price, lookbackno2)
buy_diff_rsi = vrsi - ta.rsi(close[1], length)
sell_diff_rsi = ta.rsi(close[1],length) - vrsi
//RSI high low
var int sudS = 0
var int sudB = 0
var float sudSO = 0.0
var float sudSC = 0.0
var float sudBO = 0.0
var float sudBC = 0.0
var sudBuy = 0
var sudSell = 0
var countB = 0
var countS = 0
var co_800 = false
var co_400 = false
var co_200 = false
var co_100 = false
var co_50 = false
var co_20 = false
co_800 := ta.crossover(price , ema800)
co_400 := ta.crossover(price , ema400)
co_200 := ta.crossover(price , ema200)
co_100 := ta.crossover(price , ema100)
co_50 := ta.crossover(price , ema50)
co_20 := ta.crossover(price , ema20)
if(ta.crossunder(price , ema20))
co_20 := false
if(ta.crossunder(price , ema50))
co_50 := false
if(ta.crossunder(price , ema100))
co_100 := false
if(ta.crossunder(price , ema200))
co_200 := false
if(ta.crossunder(price , ema400))
co_400 := false
if(ta.crossunder(price , ema800))
co_800 := false
if((price> ema800) and (price > ema400))
if(co_20)
if(co_50)
if(co_100)
if(co_200)
strategy.close("Sell")
strategy.entry("Buy", strategy.long, comment="spl Buy")
co_20 := false
co_50 := false
co_100 := false
co_200 := false
// too much rsi
if(vrsi > 90)
strategy.close("Buy")
strategy.entry("Sell", strategy.short, comment="RSI too overbuy")
if(vrsi < 10)
strategy.close("Sell")
strategy.entry("Buy", strategy.long, comment="RSI too oversold")
var sudbcount = 0 // counting no. of bars till sudden rise
var sudscount = 0 // counting no. of bars till sudden decrease
if(sudB == 1)
sudbcount := sudbcount + 1
if(sudS == 1)
sudscount := sudscount + 1
if((buy_diff_rsi > inst_length) and (hi2 > price))
sudB := 1
sudBO := open
sudBC := close
if((sell_diff_rsi > inst_length) )
sudS := 1
sudSO := open
sudSC := close
if(sudbcount == bars)
if(sudBC < price)
strategy.close("Sell")
strategy.entry("Buy", strategy.long, comment="sudd buy")
sudbcount := 0
sudB := 0
sudbcount := 0
sudB := 0
if(sudscount == bars)
if(sudSC > price)
strategy.close("Buy")
strategy.entry("Sell", strategy.short, comment="sudd sell")
sudscount := 0
sudS := 0
sudscount := 0
sudS := 0
over40 = input( 40 )
over60 = input( 60 )
sma =ta.sma(vrsi, length)
coo = ta.crossover(sma, over60)
cuu = ta.crossunder(sma, over40)
if (coo)
strategy.close("Sell")
strategy.entry("Buy", strategy.long, comment="modified buy")
if (cuu)
strategy.close("Buy")
strategy.entry("Sell", strategy.short, comment="modefied sell")
//plot(strategy.equity, title="equity", color=color.red, linewidth=2, style=plot.style_areabr) |
Range Filter - B&S Signals - 001 - edited | https://www.tradingview.com/script/YSjRCkXf-Range-Filter-B-S-Signals-001-edited/ | aXp9yH | https://www.tradingview.com/u/aXp9yH/ | 113 | 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/
// Credits to the original Script - Range Filter DonovanWall https://www.tradingview.com/script/lut7sBgG-Range-Filter-DW/
// This version is the old version of the Range Filter with less settings to tinker with
//@version=5
strategy(title='Range Filter - B&S Signals', shorttitle='RF - B&S Signals', initial_capital=1000, currency=currency.GBP, default_qty_value=100, default_qty_type=strategy.percent_of_equity, commission_type=strategy.commission.percent, commission_value=0.075, overlay=true)
i_startTime = input.time(defval=timestamp('01 Jan 2020 12:00 +0000'), title='Backtest Start')
i_endTime = input.time(defval=timestamp('01 Jan 2024 12:00 +0000'), title='Backtest End')
inDateRange = time >= i_startTime and time <= i_endTime
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
//Functions
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
longLossPerc = input.float(title='Long Stop Loss (%)', minval=0.0, step=0.1, defval=1) * 0.01
shortLossPerc = input.float(title='Short Stop Loss (%)', minval=0.0, step=0.1, defval=1) * 0.01
longTakePerc = input.float(title='Long Take(%)', minval=0.0, step=0.1, defval=1) * 0.01
shortTakePerc = input.float(title='Short Take (%)', minval=0.0, step=0.1, defval=1) * 0.01
emaLength = input.int(200, title="EMA Length")
// Determine stop loss price
//Range Size Function
rng_size(x, qty, n) =>
// AC = Cond_EMA(abs(x - x[1]), 1, n)
wper = n * 2 - 1
avrng = ta.ema(math.abs(x - x[1]), n)
AC = ta.ema(avrng, wper) * qty
rng_size = AC
rng_size
//Range Filter Function
rng_filt(x, rng_, n) =>
r = rng_
var rfilt = array.new_float(2, x)
array.set(rfilt, 1, array.get(rfilt, 0))
if x - r > array.get(rfilt, 1)
array.set(rfilt, 0, x - r)
if x + r < array.get(rfilt, 1)
array.set(rfilt, 0, x + r)
rng_filt1 = array.get(rfilt, 0)
hi_band = rng_filt1 + r
lo_band = rng_filt1 - r
rng_filt = rng_filt1
[hi_band, lo_band, rng_filt]
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
//Inputs
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
//Range Source
rng_src = input(defval=close, title='Swing Source')
//Range Period
rng_per = input.int(defval=20, minval=1, title='Swing Period')
//Range Size Inputs
rng_qty = input.float(defval=3.5, minval=0.0000001, title='Swing Multiplier')
//Bar Colors
use_barcolor = input(defval=false, title='Bar Colors On/Off')
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
//Definitions
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
//Range Filter Values
[h_band, l_band, filt] = rng_filt(rng_src, rng_size(rng_src, rng_qty, rng_per), rng_per)
//Direction Conditions
var fdir = 0.0
fdir := filt > filt[1] ? 1 : filt < filt[1] ? -1 : fdir
upward = fdir == 1 ? 1 : 0
downward = fdir == -1 ? 1 : 0
//Trading Condition
longCond = rng_src > filt and rng_src > rng_src[1] and upward > 0 or rng_src > filt and rng_src < rng_src[1] and upward > 0
shortCond = rng_src < filt and rng_src < rng_src[1] and downward > 0 or rng_src < filt and rng_src > rng_src[1] and downward > 0
CondIni = 0
CondIni := longCond ? 1 : shortCond ? -1 : CondIni[1]
longCondition = longCond and CondIni[1] == -1
shortCondition = shortCond and CondIni[1] == 1
//Colors
filt_color = upward ? #05ff9b : downward ? #ff0583 : #cccccc
bar_color = upward and rng_src > filt ? rng_src > rng_src[1] ? #05ff9b : #00b36b : downward and rng_src < filt ? rng_src < rng_src[1] ? #ff0583 : #b8005d : #cccccc
ema = ta.ema(close,emaLength)
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
//Outputs
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
longStopPrice = strategy.position_avg_price * (1 - longLossPerc)
shortStopPrice = strategy.position_avg_price * (1 + shortLossPerc)
longTakePrice = strategy.position_avg_price * (1 + longTakePerc)
shortTakePrice = strategy.position_avg_price * (1 - shortTakePerc)
//Filter Plot
filt_plot = plot(filt, color=filt_color, linewidth=3, title='Filter', transp=67)
//Band Plots
h_band_plot = plot(h_band, color=color.new(#05ff9b, 100), title='High Band')
l_band_plot = plot(l_band, color=color.new(#ff0583, 100), title='Low Band')
//Band Fills
fill(h_band_plot, filt_plot, color=color.new(#00b36b, 92), title='High Band Fill')
fill(l_band_plot, filt_plot, color=color.new(#b8005d, 92), title='Low Band Fill')
//Bar Color
barcolor(use_barcolor ? bar_color : na)
if inDateRange and close>ema
strategy.entry("Long", strategy.long, when=longCondition)
if inDateRange and close<ema
strategy.entry("Short", strategy.short, when=shortCondition)
plot(ema)
//Plot Buy and Sell Labels
plotshape(longCondition, title='Buy Signal', text='BUY', textcolor=color.white, style=shape.labelup, size=size.normal, location=location.belowbar, color=color.new(color.green, 0))
plotshape(shortCondition, title='Sell Signal', text='SELL', textcolor=color.white, style=shape.labeldown, size=size.normal, location=location.abovebar, color=color.new(color.red, 0))
//Alerts
alertcondition(longCondition, title='Buy Alert', message='BUY')
alertcondition(shortCondition, title='Sell Alert', message='SELL')
if strategy.position_size > 0
strategy.exit(id='Long', stop=longStopPrice, limit=longTakePrice)
if strategy.position_size < 0
strategy.exit(id='Short', stop=shortStopPrice, limit=shortTakePrice)
|
Compound Indicator Strategy - BTC/USDT 3h | https://www.tradingview.com/script/K2lxKgXy-Compound-Indicator-Strategy-BTC-USDT-3h/ | pcooma | https://www.tradingview.com/u/pcooma/ | 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/
// © pcooma
//@version=5
strategy("Compound Indicator Strategy - BTC/USDT 3h", shorttitle="Compound - BTC/USDT 3h", overlay=true, calc_on_order_fills=false, close_entries_rule = "FIFO", calc_on_every_tick=false, initial_capital = 1000,pyramiding = 999,precision = 4, process_orders_on_close=true, currency = currency.USD, default_qty_type = strategy.cash, default_qty_value = 33, commission_type = strategy.commission.percent, max_lines_count = 500, commission_value = 0.1)
//strategy("OPV6 - Up & Down Trend Trading Strategy - BNB/USDT 15min", shorttitle="OPV6 U&D - BNB 15min", overlay=true, calc_on_order_fills=false, close_entries_rule = "FIFO", calc_on_every_tick=false, initial_capital = 1000,pyramiding = 999,precision = 4, process_orders_on_close=false, currency = currency.USD, default_qty_type = strategy.cash, default_qty_value = 33, commission_type = strategy.commission.percent, max_lines_count = 500, commission_value = 0.1)
var show = input.string(title = "Show graph", options=['NONE','Compound Indicater','Co-variances'], defval='NONE')
//Values for calculation
price_average_previous_bar = (open + close)/2
price_average_current_bar = (high+low)/2
volume_average = ta.sma(volume,100)
ma_9 = ta.sma(close,9)
var float positive_signal = 0
//Volume Change Ocillator
var float cumVol = 0.
var float short = 0.0
var float long = 1.0
cumVol += nz(volume)
if barstate.islast and cumVol == 0
runtime.error("No volume is provided by the data vendor.")
shortlen = input.int(5, minval=1, title = "Short Length of volume change ocillator", group = "Volume Change Ocillator")
longlen = input.int(200, minval=1, title = "Long Length of volume change ocillator", group = "Volume Change Ocillator")
cal_method_osc = input.string(title = "Calculation method of volume change ocillator is", options=['EMA', 'SMA'], defval='SMA', group = "Volume Change Ocillator")
if cal_method_osc == 'SMA'
short := ta.sma(volume, shortlen)
long := ta.sma(volume, longlen)
else if cal_method_osc == 'EMA'
short := ta.ema(volume, shortlen)
long := ta.ema(volume, longlen)
osc = 100 * (short - long) / long
osc_crossunder_100 = ta.crossunder(osc,100)
osc_crossunder_200 = ta.crossunder(osc,200)
osc_crossunder_300 = ta.crossunder(osc,300)
osc_crossunder_400 = ta.crossunder(osc,400)
osc_crossunder_500 = ta.crossunder(osc,500)
osc_crossunder_600 = ta.crossunder(osc,600)
osc_crossunder_700 = ta.crossunder(osc,700)
osc_crossunder_800 = ta.crossunder(osc,800)
osc_crossunder_900 = ta.crossunder(osc,900)
osc_crossunder_1000 = ta.crossunder(osc,1000)
osc_crossover_100 = ta.crossover(osc,100)
osc_crossover_200 = ta.crossover(osc,200)
osc_crossover_300 = ta.crossover(osc,300)
osc_crossover_400 = ta.crossover(osc,400)
osc_crossover_500 = ta.crossover(osc,500)
osc_crossover_600 = ta.crossover(osc,600)
osc_crossover_700 = ta.crossover(osc,700)
osc_crossover_800 = ta.crossover(osc,800)
osc_crossover_900 = ta.crossover(osc,900)
osc_crossover_1000 = ta.crossover(osc,1000)
if open < close
if osc_crossover_100
positive_signal := positive_signal + 1
else if osc_crossunder_100
positive_signal := positive_signal - 1
else if osc_crossover_200
positive_signal := positive_signal + 1
else if osc_crossunder_200
positive_signal := positive_signal - 1
else if osc_crossover_300
positive_signal := positive_signal + 1
else if osc_crossunder_300
positive_signal := positive_signal - 1
else if osc_crossover_400
positive_signal := positive_signal + 1
else if osc_crossunder_400
positive_signal := positive_signal - 1
else if osc_crossover_500
positive_signal := positive_signal + 1
else if osc_crossunder_500
positive_signal := positive_signal - 1
else if osc_crossover_600
positive_signal := positive_signal + 1
else if osc_crossunder_600
positive_signal := positive_signal - 1
else if osc_crossover_700
positive_signal := positive_signal + 1
else if osc_crossunder_700
positive_signal := positive_signal - 1
else if osc_crossover_800
positive_signal := positive_signal + 1
else if osc_crossunder_800
positive_signal := positive_signal - 1
else if osc_crossover_900
positive_signal := positive_signal + 1
else if osc_crossunder_900
positive_signal := positive_signal - 1
else if osc_crossover_1000
positive_signal := positive_signal + 1
else if osc_crossunder_1000
positive_signal := positive_signal - 1
else if open > close
if osc_crossover_100
positive_signal := positive_signal - 1
else if osc_crossunder_100
positive_signal := positive_signal + 1
else if osc_crossover_200
positive_signal := positive_signal - 1
else if osc_crossunder_200
positive_signal := positive_signal + 1
else if osc_crossover_300
positive_signal := positive_signal - 1
else if osc_crossunder_300
positive_signal := positive_signal + 1
else if osc_crossover_400
positive_signal := positive_signal - 1
else if osc_crossunder_400
positive_signal := positive_signal + 1
else if osc_crossover_500
positive_signal := positive_signal - 1
else if osc_crossunder_500
positive_signal := positive_signal + 1
else if osc_crossover_600
positive_signal := positive_signal - 1
else if osc_crossunder_600
positive_signal := positive_signal + 1
else if osc_crossover_700
positive_signal := positive_signal - 1
else if osc_crossunder_700
positive_signal := positive_signal + 1
else if osc_crossover_800
positive_signal := positive_signal - 1
else if osc_crossunder_800
positive_signal := positive_signal + 1
else if osc_crossover_900
positive_signal := positive_signal - 1
else if osc_crossunder_900
positive_signal := positive_signal + 1
else if osc_crossover_1000
positive_signal := positive_signal - 1
else if osc_crossunder_1000
positive_signal := positive_signal + 1
// Momemtum Ocillator
src_mom_10 = input(close, title = "Source of MOM - 10", group = "Momentun Ocillator")
lb_mom_10 = 10
momm_10 = ta.change(src_mom_10)
f1_10(m_10) => m_10 >= 0.0 ? m_10 : 0.0
f2_10(m_10) => m_10 >= 0.0 ? 0.0 : -m_10
m1_10 = f1_10(momm_10)
m2_10 = f2_10(momm_10)
sm1_10 = math.sum(m1_10, lb_mom_10)
sm2_10 = math.sum(m2_10, lb_mom_10)
percent_10(nom_10, div_10) => 100 * nom_10 / div_10
chandeMO_10 = percent_10(sm1_10-sm2_10, sm1_10+sm2_10)
src_mom_50 = input(close, title = "Source of MOM - 50", group = "Momentun Ocillator")
lb_mom_50 = 50
momm_50 = ta.change(src_mom_50)
f1_50(m_50) => m_50 >= 0.0 ? m_50 : 0.0
f2_50(m_50) => m_50 >= 0.0 ? 0.0 : -m_50
m1_50 = f1_50(momm_50)
m2_50 = f2_50(momm_50)
sm1_50 = math.sum(m1_50, lb_mom_50)
sm2_50 = math.sum(m2_50, lb_mom_50)
percent_50(nom_50, div_50) => 100 * nom_50 / div_50
chandeMO_50 = percent_50(sm1_50-sm2_50, sm1_50+sm2_50)
src_mom_100 = input(close, title = "Source of MOM - 100", group = "Momentun Ocillator")
lb_mom_100 = 100
momm_100 = ta.change(src_mom_100)
f1_100(m_100) => m_100 >= 0.0 ? m_100 : 0.0
f2_100(m_100) => m_100 >= 0.0 ? 0.0 : -m_100
m1_100 = f1_100(momm_100)
m2_100 = f2_100(momm_100)
sm1_100 = math.sum(m1_100, lb_mom_100)
sm2_100 = math.sum(m2_100, lb_mom_100)
percent_100(nom_100, div_100) => 100 * nom_100 / div_100
chandeMO_100 = percent_100(sm1_100-sm2_100, sm1_100+sm2_100)
src_mom_200 = input(close, title = "Source of MOM - 200", group = "Momentun Ocillator")
lb_mom_200 = 200
momm_200 = ta.change(src_mom_200)
f1_200(m_200) => m_200 >= 0.0 ? m_200 : 0.0
f2_200(m_200) => m_200 >= 0.0 ? 0.0 : -m_200
m1_200 = f1_200(momm_200)
m2_200 = f2_200(momm_200)
sm1_200 = math.sum(m1_200, lb_mom_200)
sm2_200 = math.sum(m2_200, lb_mom_200)
percent_200(nom_200, div_200) => 100 * nom_200 / div_200
chandeMO_200 = percent_200(sm1_200-sm2_200, sm1_200+sm2_200)
//MOM graphs cross over and cross under each other
mom_10_crossover_50 = ta.crossover(chandeMO_10,chandeMO_50)
mom_10_crossover_100 = ta.crossover(chandeMO_10,chandeMO_100)
mom_10_crossover_200 = ta.crossover(chandeMO_10,chandeMO_200)
mom_50_crossover_100 = ta.crossover(chandeMO_50,chandeMO_100)
mom_50_crossover_200 = ta.crossover(chandeMO_50,chandeMO_200)
mom_100_crossover_200 = ta.crossover(chandeMO_100,chandeMO_200)
mom_10_crossunder_50 = ta.crossunder(chandeMO_10,chandeMO_50)
mom_10_crossunder_100 = ta.crossunder(chandeMO_10,chandeMO_100)
mom_10_crossunder_200 = ta.crossunder(chandeMO_10,chandeMO_200)
mom_50_crossunder_100 = ta.crossunder(chandeMO_50,chandeMO_100)
mom_50_crossunder_200 = ta.crossunder(chandeMO_50,chandeMO_200)
mom_100_crossunder_200 = ta.crossunder(chandeMO_100,chandeMO_200)
if mom_10_crossover_50 or mom_10_crossover_100 or mom_10_crossover_200 or mom_50_crossover_100 or mom_50_crossover_200 or mom_100_crossover_200
positive_signal := positive_signal + 1
if mom_10_crossunder_50 or mom_10_crossunder_100 or mom_10_crossunder_200 or mom_50_crossunder_100 or mom_50_crossunder_200 or mom_100_crossunder_200
positive_signal := positive_signal - 1
//MOM cross over and cross under different values
mom_10_crossover_val_10 = ta.crossover(chandeMO_10,10)
mom_10_crossover_val_20 = ta.crossover(chandeMO_10,20)
mom_10_crossover_val_30 = ta.crossover(chandeMO_10,30)
mom_10_crossover_val_40 = ta.crossover(chandeMO_10,40)
mom_10_crossover_val_50 = ta.crossover(chandeMO_10,50)
mom_10_crossover_val_60 = ta.crossover(chandeMO_10,60)
mom_10_crossover_val_70 = ta.crossover(chandeMO_10,70)
mom_10_crossover_val_80 = ta.crossover(chandeMO_10,80)
mom_10_crossover_val_90 = ta.crossover(chandeMO_10,90)
mom_10_crossover_val_100 = ta.crossover(chandeMO_10,100)
mom_10_crossunder_val_10 = ta.crossunder(chandeMO_10,10)
mom_10_crossunder_val_20 = ta.crossunder(chandeMO_10,20)
mom_10_crossunder_val_30 = ta.crossunder(chandeMO_10,30)
mom_10_crossunder_val_40 = ta.crossunder(chandeMO_10,40)
mom_10_crossunder_val_50 = ta.crossunder(chandeMO_10,50)
mom_10_crossunder_val_60 = ta.crossunder(chandeMO_10,60)
mom_10_crossunder_val_70 = ta.crossunder(chandeMO_10,70)
mom_10_crossunder_val_80 = ta.crossunder(chandeMO_10,80)
mom_10_crossunder_val_90 = ta.crossunder(chandeMO_10,90)
mom_10_crossunder_val_100 = ta.crossunder(chandeMO_10,100)
mom_50_crossover_val_10 = ta.crossover(chandeMO_50,4)
mom_50_crossover_val_20 = ta.crossover(chandeMO_50,8)
mom_50_crossover_val_30 = ta.crossover(chandeMO_50,12)
mom_50_crossover_val_40 = ta.crossover(chandeMO_50,16)
mom_50_crossover_val_50 = ta.crossover(chandeMO_50,20)
mom_50_crossover_val_60 = ta.crossover(chandeMO_50,24)
mom_50_crossover_val_70 = ta.crossover(chandeMO_50,28)
mom_50_crossover_val_80 = ta.crossover(chandeMO_50,32)
mom_50_crossover_val_90 = ta.crossover(chandeMO_50,36)
mom_50_crossover_val_100 = ta.crossover(chandeMO_50,40)
mom_50_crossunder_val_10 = ta.crossunder(chandeMO_50,-4)
mom_50_crossunder_val_20 = ta.crossunder(chandeMO_50,-8)
mom_50_crossunder_val_30 = ta.crossunder(chandeMO_50,-12)
mom_50_crossunder_val_40 = ta.crossunder(chandeMO_50,-16)
mom_50_crossunder_val_50 = ta.crossunder(chandeMO_50,-20)
mom_50_crossunder_val_60 = ta.crossunder(chandeMO_50,-24)
mom_50_crossunder_val_70 = ta.crossunder(chandeMO_50,-28)
mom_50_crossunder_val_80 = ta.crossunder(chandeMO_50,-32)
mom_50_crossunder_val_90 = ta.crossunder(chandeMO_50,-36)
mom_50_crossunder_val_100 = ta.crossunder(chandeMO_50,-40)
mom_100_crossover_val_10 = ta.crossover(chandeMO_100,3.5)
mom_100_crossover_val_20 = ta.crossover(chandeMO_100,7.0)
mom_100_crossover_val_30 = ta.crossover(chandeMO_100,10.5)
mom_100_crossover_val_40 = ta.crossover(chandeMO_100,14.0)
mom_100_crossover_val_50 = ta.crossover(chandeMO_100,17.5)
mom_100_crossover_val_60 = ta.crossover(chandeMO_100,21.0)
mom_100_crossover_val_70 = ta.crossover(chandeMO_100,24.5)
mom_100_crossover_val_80 = ta.crossover(chandeMO_100,28.0)
mom_100_crossover_val_90 = ta.crossover(chandeMO_100,31.5)
mom_100_crossover_val_100 = ta.crossover(chandeMO_100,35)
mom_100_crossunder_val_10 = ta.crossunder(chandeMO_100,-3.5)
mom_100_crossunder_val_20 = ta.crossunder(chandeMO_100,-7)
mom_100_crossunder_val_30 = ta.crossunder(chandeMO_100,-10.5)
mom_100_crossunder_val_40 = ta.crossunder(chandeMO_100,-14)
mom_100_crossunder_val_50 = ta.crossunder(chandeMO_100,-17.5)
mom_100_crossunder_val_60 = ta.crossunder(chandeMO_100,-21)
mom_100_crossunder_val_70 = ta.crossunder(chandeMO_100,-24.5)
mom_100_crossunder_val_80 = ta.crossunder(chandeMO_100,-28)
mom_100_crossunder_val_90 = ta.crossunder(chandeMO_100,-31.5)
mom_100_crossunder_val_100 = ta.crossunder(chandeMO_100,-35)
mom_200_crossover_val_10 = ta.crossover(chandeMO_200,2)
mom_200_crossover_val_20 = ta.crossover(chandeMO_200,4)
mom_200_crossover_val_30 = ta.crossover(chandeMO_200,6)
mom_200_crossover_val_40 = ta.crossover(chandeMO_200,8)
mom_200_crossover_val_50 = ta.crossover(chandeMO_200,10)
mom_200_crossover_val_60 = ta.crossover(chandeMO_200,12)
mom_200_crossover_val_70 = ta.crossover(chandeMO_200,14)
mom_200_crossover_val_80 = ta.crossover(chandeMO_200,16)
mom_200_crossover_val_90 = ta.crossover(chandeMO_200,18)
mom_200_crossover_val_100 = ta.crossover(chandeMO_200,20)
mom_200_crossunder_val_10 = ta.crossunder(chandeMO_200,-2)
mom_200_crossunder_val_20 = ta.crossunder(chandeMO_200,-4)
mom_200_crossunder_val_30 = ta.crossunder(chandeMO_200,-6)
mom_200_crossunder_val_40 = ta.crossunder(chandeMO_200,-8)
mom_200_crossunder_val_50 = ta.crossunder(chandeMO_200,-10)
mom_200_crossunder_val_60 = ta.crossunder(chandeMO_200,-12)
mom_200_crossunder_val_70 = ta.crossunder(chandeMO_200,-14)
mom_200_crossunder_val_80 = ta.crossunder(chandeMO_200,-16)
mom_200_crossunder_val_90 = ta.crossunder(chandeMO_200,-18)
mom_200_crossunder_val_100 = ta.crossunder(chandeMO_200,-20)
if mom_10_crossover_val_10 or mom_10_crossover_val_20 or mom_10_crossover_val_30 or mom_10_crossover_val_40 or mom_10_crossover_val_50 or mom_10_crossover_val_60 or mom_10_crossover_val_70 or mom_10_crossover_val_80 or mom_10_crossover_val_90 or mom_10_crossover_val_100 or mom_50_crossover_val_10 or mom_50_crossover_val_20 or mom_50_crossover_val_30 or mom_50_crossover_val_40 or mom_50_crossover_val_50 or mom_50_crossover_val_60 or mom_50_crossover_val_70 or mom_50_crossover_val_80 or mom_50_crossover_val_90 or mom_50_crossover_val_100 or mom_100_crossover_val_10 or mom_100_crossover_val_20 or mom_100_crossover_val_30 or mom_100_crossover_val_40 or mom_100_crossover_val_50 or mom_100_crossover_val_60 or mom_100_crossover_val_70 or mom_100_crossover_val_80 or mom_100_crossover_val_90 or mom_100_crossover_val_100 or mom_200_crossover_val_10 or mom_200_crossover_val_20 or mom_200_crossover_val_30 or mom_200_crossover_val_40 or mom_200_crossover_val_50 or mom_200_crossover_val_60 or mom_200_crossover_val_70 or mom_200_crossover_val_80 or mom_200_crossover_val_90 or mom_200_crossover_val_100
positive_signal := positive_signal + 1
if mom_10_crossunder_val_10 or mom_10_crossunder_val_20 or mom_10_crossunder_val_30 or mom_10_crossunder_val_40 or mom_10_crossunder_val_50 or mom_10_crossunder_val_60 or mom_10_crossunder_val_70 or mom_10_crossunder_val_80 or mom_10_crossunder_val_90 or mom_10_crossunder_val_100 or mom_50_crossunder_val_10 or mom_50_crossunder_val_20 or mom_50_crossunder_val_30 or mom_50_crossunder_val_40 or mom_50_crossunder_val_50 or mom_50_crossunder_val_60 or mom_50_crossunder_val_70 or mom_50_crossunder_val_80 or mom_50_crossunder_val_90 or mom_50_crossunder_val_100 or mom_100_crossunder_val_10 or mom_100_crossunder_val_20 or mom_100_crossunder_val_30 or mom_100_crossunder_val_40 or mom_100_crossunder_val_50 or mom_100_crossunder_val_60 or mom_100_crossunder_val_70 or mom_100_crossunder_val_80 or mom_100_crossunder_val_90 or mom_100_crossunder_val_100 or mom_200_crossunder_val_10 or mom_200_crossunder_val_20 or mom_200_crossunder_val_30 or mom_200_crossunder_val_40 or mom_200_crossunder_val_50 or mom_200_crossunder_val_60 or mom_200_crossunder_val_70 or mom_200_crossunder_val_80 or mom_200_crossunder_val_90 or mom_200_crossunder_val_100
positive_signal := positive_signal - 1
//Stochastic Indicator
period_of_stoch_ind = input.string (title = "Look back period of stochastic indicator", options=['10', '50','100','200'], defval='100', group = "Stochastic Indicator")
var int periodK = 0
var int smoothK = 0
var int periodD = 0
if period_of_stoch_ind == '10'
periodK := 10
smoothK := 1
periodD := 3
else if period_of_stoch_ind == '50'
periodK := 50
smoothK := 5
periodD := 5
else if period_of_stoch_ind == '100'
periodK := 100
smoothK := 10
periodD := 10
else if period_of_stoch_ind == '200'
periodK := 200
smoothK := 10
periodD := 10
k = ta.sma(ta.stoch(close, high, low, periodK), smoothK)
d = ta.sma(k, periodD)
// Graphs crossover and cross under each other
k_10 = ta.sma(ta.stoch(close, high, low, 10), 1)
d_10 = ta.sma(k, 3)
k_50 = ta.sma(ta.stoch(close, high, low, 50), 5)
d_50 = ta.sma(k, 5)
k_100 = ta.sma(ta.stoch(close, high, low, 100), 10)
d_100 = ta.sma(k, 10)
k_200 = ta.sma(ta.stoch(close, high, low, 200), 10)
d_200 = ta.sma(k, 10)
k_10_crossover_k_50 = ta.crossover(k_10,k_50)
k_10_crossover_k_100 = ta.crossover(k_10,k_100)
k_10_crossover_k_200 = ta.crossover(k_10,k_200)
k_50_crossover_k_100 = ta.crossover(k_50,k_100)
k_50_crossover_k_200 = ta.crossover(k_50,k_200)
k_100_crossover_k_200 = ta.crossover(k_100,k_200)
k_10_crossunder_k_50 = ta.crossunder(k_10,k_50)
k_10_crossunder_k_100 = ta.crossunder(k_10,k_100)
k_10_crossunder_k_200 = ta.crossunder(k_10,k_200)
k_50_crossunder_k_100 = ta.crossunder(k_50,k_100)
k_50_crossunder_k_200 = ta.crossunder(k_50,k_200)
k_100_crossunder_k_200 = ta.crossunder(k_100,k_200)
// Values cross over each other
var bool stochastic_10_buy = false
var bool stochastic_50_buy = false
var bool stochastic_100_buy = false
var bool stochastic_200_buy = false
if k_10 >= d_10
stochastic_10_buy := true
else
stochastic_10_buy := false
if k_50 >= d_50
stochastic_50_buy := true
else
stochastic_50_buy := false
if k_100 >= d_100
stochastic_100_buy := true
else
stochastic_100_buy := false
if k_200 >= d_200
stochastic_200_buy := true
else
stochastic_200_buy := false
if k_10_crossover_k_50 or k_10_crossover_k_100 or k_10_crossover_k_200 or k_50_crossover_k_100 or k_50_crossover_k_200 or k_100_crossover_k_200
positive_signal := positive_signal + 1
if k_10_crossunder_k_50 or k_10_crossunder_k_100 or k_10_crossunder_k_200 or k_50_crossunder_k_100 or k_50_crossunder_k_200 or k_100_crossunder_k_200
positive_signal := positive_signal - 1
if stochastic_10_buy == true or stochastic_50_buy == true or stochastic_100_buy == true or stochastic_100_buy == true
positive_signal := positive_signal + 1
if stochastic_10_buy == false or stochastic_50_buy == false or stochastic_100_buy == false or stochastic_100_buy == false
positive_signal := positive_signal - 1
//Multi timeframe RSI
src_rsi_10 = input(close, title = "Source of RSI - 10", group = "Relative Strength Index (RSI)", inline = "10")
lb_rsi_10 = 10
rsi_10 = ta.rsi(src_rsi_10,lb_rsi_10)
src_rsi_50 = input(close, title = "Source of RSI - 50", group = "Relative Strength Index (RSI)", inline = "50")
lb_rsi_50 = 50
rsi_50 = ta.rsi(src_rsi_50,lb_rsi_50)
src_rsi_100 = input(close, title = "Source of RSI - 100", group = "Relative Strength Index (RSI)", inline = "100")
lb_rsi_100 = 100
rsi_100 = ta.rsi(src_rsi_100,lb_rsi_100)
src_rsi_200 = input(close, title = "Source of RSI - 200", group = "Relative Strength Index (RSI)", inline = "200")
lb_rsi_200 = 200
rsi_200 = ta.rsi(src_rsi_200,lb_rsi_200)
//RSI Graphs cross eachother
rsi_10_crossover_rsi_50 = ta.crossover(rsi_10,rsi_50)
rsi_10_crossover_rsi_100 = ta.crossover(rsi_10,rsi_100)
rsi_10_crossover_rsi_200 = ta.crossover(rsi_10,rsi_200)
rsi_50_crossover_rsi_100 = ta.crossover(rsi_50,rsi_100)
rsi_50_crossover_rsi_200 = ta.crossover(rsi_50,rsi_200)
rsi_100_crossover_rsi_200 = ta.crossover(rsi_100,rsi_200)
rsi_10_crossunder_rsi_50 = ta.crossunder(rsi_10,rsi_50)
rsi_10_crossunder_rsi_100 = ta.crossunder(rsi_10,rsi_100)
rsi_10_crossunder_rsi_200 = ta.crossunder(rsi_10,rsi_200)
rsi_50_crossunder_rsi_100 = ta.crossunder(rsi_50,rsi_100)
rsi_50_crossunder_rsi_200 = ta.crossunder(rsi_50,rsi_200)
rsi_100_crossunder_rsi_200 = ta.crossunder(rsi_100,rsi_200)
if rsi_10_crossover_rsi_50 or rsi_10_crossover_rsi_100 or rsi_10_crossover_rsi_200 or rsi_50_crossover_rsi_100 or rsi_50_crossover_rsi_200 or rsi_100_crossover_rsi_200
positive_signal := positive_signal + 1
if rsi_10_crossunder_rsi_50 or rsi_10_crossunder_rsi_100 or rsi_10_crossunder_rsi_200 or rsi_50_crossunder_rsi_100 or rsi_50_crossunder_rsi_200 or rsi_100_crossunder_rsi_200
positive_signal := positive_signal - 1
//RSI crossing different values
rsi_10_crossover_val_0 = ta.cross(rsi_10,0)
rsi_10_crossover_val_10 = ta.crossover(rsi_10,10)
rsi_10_crossover_val_20 = ta.crossover(rsi_10,20)
rsi_10_crossover_val_30 = ta.crossover(rsi_10,30)
rsi_10_crossover_val_40 = ta.crossover(rsi_10,40)
rsi_10_crossover_val_50 = ta.crossover(rsi_10,50)
rsi_10_crossover_val_60 = ta.crossover(rsi_10,60)
rsi_10_crossover_val_70 = ta.crossover(rsi_10,70)
rsi_10_crossover_val_80 = ta.crossover(rsi_10,80)
rsi_10_crossover_val_90 = ta.crossover(rsi_10,90)
rsi_10_crossover_val_100 = ta.cross(rsi_10,100)
rsi_10_crossunder_val_0 = ta.cross(rsi_10,0)
rsi_10_crossunder_val_10 = ta.crossunder(rsi_10,10)
rsi_10_crossunder_val_20 = ta.crossunder(rsi_10,20)
rsi_10_crossunder_val_30 = ta.crossunder(rsi_10,30)
rsi_10_crossunder_val_40 = ta.crossunder(rsi_10,40)
rsi_10_crossunder_val_50 = ta.crossunder(rsi_10,50)
rsi_10_crossunder_val_60 = ta.crossunder(rsi_10,60)
rsi_10_crossunder_val_70 = ta.crossunder(rsi_10,70)
rsi_10_crossunder_val_80 = ta.crossunder(rsi_10,80)
rsi_10_crossunder_val_90 = ta.crossunder(rsi_10,90)
rsi_10_crossunder_val_100 = ta.cross(rsi_10,100)
if rsi_10_crossover_val_0 or rsi_10_crossover_val_10 or rsi_10_crossover_val_20 or rsi_10_crossover_val_30 or rsi_10_crossover_val_40 or rsi_10_crossover_val_50 or rsi_10_crossover_val_60 or rsi_10_crossover_val_70 or rsi_10_crossover_val_80 or rsi_10_crossover_val_90 or rsi_10_crossover_val_100
positive_signal := positive_signal + 1
if rsi_10_crossunder_val_0 or rsi_10_crossunder_val_10 or rsi_10_crossunder_val_20 or rsi_10_crossunder_val_30 or rsi_10_crossunder_val_40 or rsi_10_crossunder_val_50 or rsi_10_crossunder_val_60 or rsi_10_crossunder_val_70 or rsi_10_crossunder_val_80 or rsi_10_crossunder_val_90 or rsi_10_crossunder_val_100
positive_signal := positive_signal - 1
rsi_50_crossover_val_75 = ta.crossover(rsi_50,75)
rsi_50_crossover_val_70 = ta.crossover(rsi_50,70)
rsi_50_crossover_val_65 = ta.crossover(rsi_50,65)
rsi_50_crossover_val_60 = ta.crossover(rsi_50,60)
rsi_50_crossover_val_55 = ta.crossover(rsi_50,55)
rsi_50_crossover_val_50 = ta.crossover(rsi_50,50)
rsi_50_crossover_val_45 = ta.crossover(rsi_50,45)
rsi_50_crossover_val_40 = ta.crossover(rsi_50,40)
rsi_50_crossover_val_35 = ta.crossover(rsi_50,35)
rsi_50_crossover_val_30 = ta.crossover(rsi_50,30)
rsi_50_crossover_val_25 = ta.crossover(rsi_50,25)
rsi_50_crossunder_val_75 = ta.crossunder(rsi_50,75)
rsi_50_crossunder_val_70 = ta.crossunder(rsi_50,70)
rsi_50_crossunder_val_65 = ta.crossunder(rsi_50,65)
rsi_50_crossunder_val_60 = ta.crossunder(rsi_50,60)
rsi_50_crossunder_val_55 = ta.crossunder(rsi_50,55)
rsi_50_crossunder_val_50 = ta.crossunder(rsi_50,50)
rsi_50_crossunder_val_45 = ta.crossunder(rsi_50,45)
rsi_50_crossunder_val_40 = ta.crossunder(rsi_50,40)
rsi_50_crossunder_val_35 = ta.crossunder(rsi_50,35)
rsi_50_crossunder_val_30 = ta.crossunder(rsi_50,30)
rsi_50_crossunder_val_25 = ta.crossunder(rsi_50,25)
if rsi_50_crossover_val_75 or rsi_50_crossover_val_70 or rsi_50_crossover_val_65 or rsi_50_crossover_val_60 or rsi_50_crossover_val_55 or rsi_50_crossover_val_50 or rsi_50_crossover_val_45 or rsi_50_crossover_val_40 or rsi_50_crossover_val_35 or rsi_50_crossover_val_30 or rsi_50_crossover_val_25
positive_signal := positive_signal + 1
if rsi_50_crossunder_val_75 or rsi_50_crossunder_val_70 or rsi_50_crossunder_val_65 or rsi_50_crossunder_val_60 or rsi_50_crossunder_val_55 or rsi_50_crossunder_val_50 or rsi_50_crossunder_val_45 or rsi_50_crossunder_val_40 or rsi_50_crossunder_val_35 or rsi_50_crossunder_val_30 or rsi_50_crossunder_val_25
positive_signal := positive_signal - 1
rsi_100_crossover_val_65 = ta.crossover(rsi_100,65)
rsi_100_crossover_val_62 = ta.crossover(rsi_100,62)
rsi_100_crossover_val_59 = ta.crossover(rsi_100,59)
rsi_100_crossover_val_56 = ta.crossover(rsi_100,56)
rsi_100_crossover_val_53 = ta.crossover(rsi_100,53)
rsi_100_crossover_val_50 = ta.crossover(rsi_100,50)
rsi_100_crossover_val_47 = ta.crossover(rsi_100,47)
rsi_100_crossover_val_44 = ta.crossover(rsi_100,44)
rsi_100_crossover_val_41 = ta.crossover(rsi_100,41)
rsi_100_crossover_val_38 = ta.crossover(rsi_100,38)
rsi_100_crossover_val_35 = ta.crossover(rsi_100,35)
rsi_100_crossunder_val_65 = ta.crossunder(rsi_100,65)
rsi_100_crossunder_val_62 = ta.crossunder(rsi_100,62)
rsi_100_crossunder_val_59 = ta.crossunder(rsi_100,59)
rsi_100_crossunder_val_56 = ta.crossunder(rsi_100,56)
rsi_100_crossunder_val_53 = ta.crossunder(rsi_100,53)
rsi_100_crossunder_val_50 = ta.crossunder(rsi_100,50)
rsi_100_crossunder_val_47 = ta.crossunder(rsi_100,47)
rsi_100_crossunder_val_44 = ta.crossunder(rsi_100,44)
rsi_100_crossunder_val_41 = ta.crossunder(rsi_100,41)
rsi_100_crossunder_val_38 = ta.crossunder(rsi_100,38)
rsi_100_crossunder_val_35 = ta.crossunder(rsi_100,35)
if rsi_100_crossover_val_65 or rsi_100_crossover_val_62 or rsi_100_crossover_val_59 or rsi_100_crossover_val_56 or rsi_100_crossover_val_53 or rsi_100_crossover_val_50 or rsi_100_crossover_val_47 or rsi_100_crossover_val_44 or rsi_100_crossover_val_41 or rsi_100_crossover_val_38 or rsi_100_crossover_val_35
positive_signal := positive_signal + 1
if rsi_100_crossunder_val_65 or rsi_100_crossunder_val_62 or rsi_100_crossunder_val_59 or rsi_100_crossunder_val_56 or rsi_100_crossunder_val_53 or rsi_100_crossunder_val_50 or rsi_100_crossunder_val_47 or rsi_100_crossunder_val_44 or rsi_100_crossunder_val_41 or rsi_100_crossunder_val_38 or rsi_100_crossunder_val_35
positive_signal := positive_signal - 1
rsi_200_crossover_val_60 = ta.crossover(rsi_200,60)
rsi_200_crossover_val_58 = ta.crossover(rsi_200,58)
rsi_200_crossover_val_56 = ta.crossover(rsi_200,56)
rsi_200_crossover_val_54 = ta.crossover(rsi_200,54)
rsi_200_crossover_val_52 = ta.crossover(rsi_200,52)
rsi_200_crossover_val_50 = ta.crossover(rsi_200,50)
rsi_200_crossover_val_48 = ta.crossover(rsi_200,48)
rsi_200_crossover_val_46 = ta.crossover(rsi_200,46)
rsi_200_crossover_val_44 = ta.crossover(rsi_200,44)
rsi_200_crossover_val_42 = ta.crossover(rsi_200,42)
rsi_200_crossover_val_40 = ta.crossover(rsi_200,40)
rsi_200_crossunder_val_60 = ta.crossunder(rsi_200,60)
rsi_200_crossunder_val_58 = ta.crossunder(rsi_200,58)
rsi_200_crossunder_val_56 = ta.crossunder(rsi_200,56)
rsi_200_crossunder_val_54 = ta.crossunder(rsi_200,54)
rsi_200_crossunder_val_52 = ta.crossunder(rsi_200,52)
rsi_200_crossunder_val_50 = ta.crossunder(rsi_200,50)
rsi_200_crossunder_val_48 = ta.crossunder(rsi_200,48)
rsi_200_crossunder_val_46 = ta.crossunder(rsi_200,46)
rsi_200_crossunder_val_44 = ta.crossunder(rsi_200,44)
rsi_200_crossunder_val_42 = ta.crossunder(rsi_200,42)
rsi_200_crossunder_val_40 = ta.crossunder(rsi_200,40)
if rsi_200_crossover_val_60 or rsi_200_crossover_val_58 or rsi_200_crossover_val_56 or rsi_200_crossover_val_54 or rsi_200_crossover_val_52 or rsi_200_crossover_val_50 or rsi_200_crossover_val_48 or rsi_200_crossover_val_46 or rsi_200_crossover_val_44 or rsi_200_crossover_val_42 or rsi_200_crossover_val_40
positive_signal := positive_signal + 1
if rsi_200_crossunder_val_60 or rsi_200_crossunder_val_58 or rsi_200_crossunder_val_56 or rsi_200_crossunder_val_54 or rsi_200_crossunder_val_52 or rsi_200_crossunder_val_50 or rsi_200_crossunder_val_48 or rsi_200_crossunder_val_46 or rsi_200_crossunder_val_44 or rsi_200_crossunder_val_42 or rsi_200_crossunder_val_40
positive_signal := positive_signal - 1
//Multi timeframe money flow index (MFI)
src_mfi_10 = input(close, title = "Source of MFI - 10", group = "Money Flow Index (MFI)", inline = "10")
lb_mfi_10 = 10
mfi_10 = ta.mfi(src_mfi_10,lb_mfi_10)
src_mfi_50 = input(close, title = "Source of MFI - 50", group = "Money Flow Index (MFI)", inline = "50")
lb_mfi_50 = 50
mfi_50 = ta.mfi(src_mfi_50,lb_mfi_50)
src_mfi_100 = input(close, title = "Source of MFI - 100", group = "Money Flow Index (MFI)", inline = "100")
lb_mfi_100 = 100
mfi_100 = ta.mfi(src_mfi_100,lb_mfi_100)
src_mfi_200 = input(close, title = "Source of MFI - 200", group = "Money Flow Index (MFI)", inline = "200")
lb_mfi_200 = 200
mfi_200 = ta.mfi(src_mfi_200,lb_mfi_200)
//MFI Crossing over and under each other
mfi_10_crossover_mfi_50 = ta.crossover(mfi_10,mfi_50)
mfi_10_crossover_mfi_100 = ta.crossover(mfi_10,mfi_100)
mfi_10_crossover_mfi_200 = ta.crossover(mfi_10,mfi_200)
mfi_50_crossover_mfi_100 = ta.crossover(mfi_50,mfi_100)
mfi_50_crossover_mfi_200 = ta.crossover(mfi_50,mfi_200)
mfi_100_crossover_mfi_200 = ta.crossover(mfi_100,mfi_200)
mfi_10_crossunder_mfi_50 = ta.crossunder(mfi_10,mfi_50)
mfi_10_crossunder_mfi_100 = ta.crossunder(mfi_10,mfi_100)
mfi_10_crossunder_mfi_200 = ta.crossunder(mfi_10,mfi_200)
mfi_50_crossunder_mfi_100 = ta.crossunder(mfi_50,mfi_100)
mfi_50_crossunder_mfi_200 = ta.crossunder(mfi_50,mfi_200)
mfi_100_crossunder_mfi_200 = ta.crossunder(mfi_100,mfi_200)
if mfi_10_crossover_mfi_50 or mfi_10_crossover_mfi_100 or mfi_10_crossover_mfi_200 or mfi_50_crossover_mfi_100 or mfi_50_crossover_mfi_200 or mfi_100_crossover_mfi_200
positive_signal := positive_signal + 1
if mfi_10_crossunder_mfi_50 or mfi_10_crossunder_mfi_100 or mfi_10_crossunder_mfi_200 or mfi_50_crossunder_mfi_100 or mfi_50_crossunder_mfi_200 or mfi_100_crossunder_mfi_200
positive_signal := positive_signal - 1
//Valued cross over & under
mfi_10_crossover_val_0 = ta.cross(mfi_10,0)
mfi_10_crossover_val_10 = ta.crossover(mfi_10,10)
mfi_10_crossover_val_20 = ta.crossover(mfi_10,20)
mfi_10_crossover_val_30 = ta.crossover(mfi_10,30)
mfi_10_crossover_val_40 = ta.crossover(mfi_10,40)
mfi_10_crossover_val_50 = ta.crossover(mfi_10,50)
mfi_10_crossover_val_60 = ta.crossover(mfi_10,60)
mfi_10_crossover_val_70 = ta.crossover(mfi_10,70)
mfi_10_crossover_val_80 = ta.crossover(mfi_10,80)
mfi_10_crossover_val_90 = ta.crossover(mfi_10,90)
mfi_10_crossover_val_100 = ta.cross(mfi_10,100)
mfi_10_crossunder_val_0 = ta.cross(mfi_10,0)
mfi_10_crossunder_val_10 = ta.crossunder(mfi_10,10)
mfi_10_crossunder_val_20 = ta.crossunder(mfi_10,20)
mfi_10_crossunder_val_30 = ta.crossunder(mfi_10,30)
mfi_10_crossunder_val_40 = ta.crossunder(mfi_10,40)
mfi_10_crossunder_val_50 = ta.crossunder(mfi_10,50)
mfi_10_crossunder_val_60 = ta.crossunder(mfi_10,60)
mfi_10_crossunder_val_70 = ta.crossunder(mfi_10,70)
mfi_10_crossunder_val_80 = ta.crossunder(mfi_10,80)
mfi_10_crossunder_val_90 = ta.crossunder(mfi_10,90)
mfi_10_crossunder_val_100 = ta.cross(mfi_10,100)
if mfi_10_crossover_val_0 or mfi_10_crossover_val_10 or mfi_10_crossover_val_20 or mfi_10_crossover_val_30 or mfi_10_crossover_val_40 or mfi_10_crossover_val_50 or mfi_10_crossover_val_60 or mfi_10_crossover_val_70 or mfi_10_crossover_val_80 or mfi_10_crossover_val_90 or mfi_10_crossover_val_100
positive_signal := positive_signal + 1
if mfi_10_crossunder_val_0 or mfi_10_crossunder_val_10 or mfi_10_crossunder_val_20 or mfi_10_crossunder_val_30 or mfi_10_crossunder_val_40 or mfi_10_crossunder_val_50 or mfi_10_crossunder_val_60 or mfi_10_crossunder_val_70 or mfi_10_crossunder_val_80 or mfi_10_crossunder_val_90 or mfi_10_crossunder_val_100
positive_signal := positive_signal - 1
mfi_50_crossover_val_90 = ta.crossover(mfi_50,90)
mfi_50_crossover_val_82 = ta.crossover(mfi_50,82)
mfi_50_crossover_val_74 = ta.crossover(mfi_50,74)
mfi_50_crossover_val_66 = ta.crossover(mfi_50,66)
mfi_50_crossover_val_58 = ta.crossover(mfi_50,58)
mfi_50_crossover_val_50 = ta.crossover(mfi_50,50)
mfi_50_crossover_val_42 = ta.crossover(mfi_50,42)
mfi_50_crossover_val_34 = ta.crossover(mfi_50,34)
mfi_50_crossover_val_26 = ta.crossover(mfi_50,26)
mfi_50_crossover_val_18 = ta.crossover(mfi_50,18)
mfi_50_crossover_val_10 = ta.crossover(mfi_50,10)
mfi_50_crossunder_val_90 = ta.crossunder(mfi_50,90)
mfi_50_crossunder_val_82 = ta.crossunder(mfi_50,82)
mfi_50_crossunder_val_74 = ta.crossunder(mfi_50,74)
mfi_50_crossunder_val_66 = ta.crossunder(mfi_50,66)
mfi_50_crossunder_val_58 = ta.crossunder(mfi_50,58)
mfi_50_crossunder_val_50 = ta.crossunder(mfi_50,50)
mfi_50_crossunder_val_42 = ta.crossunder(mfi_50,42)
mfi_50_crossunder_val_34 = ta.crossunder(mfi_50,34)
mfi_50_crossunder_val_26 = ta.crossunder(mfi_50,26)
mfi_50_crossunder_val_18 = ta.crossunder(mfi_50,18)
mfi_50_crossunder_val_10 = ta.crossunder(mfi_50,10)
if mfi_50_crossover_val_90 or mfi_50_crossover_val_82 or mfi_50_crossover_val_74 or mfi_50_crossover_val_66 or mfi_50_crossover_val_58 or mfi_50_crossover_val_50 or mfi_50_crossover_val_42 or mfi_50_crossover_val_34 or mfi_50_crossover_val_26 or mfi_50_crossover_val_18 or mfi_50_crossover_val_10
positive_signal := positive_signal + 1
if mfi_50_crossunder_val_90 or mfi_50_crossunder_val_82 or mfi_50_crossunder_val_74 or mfi_50_crossunder_val_66 or mfi_50_crossunder_val_58 or mfi_50_crossunder_val_50 or mfi_50_crossunder_val_42 or mfi_50_crossunder_val_34 or mfi_50_crossunder_val_26 or mfi_50_crossunder_val_18 or mfi_50_crossunder_val_10
positive_signal := positive_signal - 1
mfi_100_crossover_val_85 = ta.crossover(mfi_100,85)
mfi_100_crossover_val_78 = ta.crossover(mfi_100,78)
mfi_100_crossover_val_71 = ta.crossover(mfi_100,71)
mfi_100_crossover_val_64 = ta.crossover(mfi_100,64)
mfi_100_crossover_val_57 = ta.crossover(mfi_100,57)
mfi_100_crossover_val_50 = ta.crossover(mfi_100,50)
mfi_100_crossover_val_43 = ta.crossover(mfi_100,43)
mfi_100_crossover_val_36 = ta.crossover(mfi_100,36)
mfi_100_crossover_val_29 = ta.crossover(mfi_100,29)
mfi_100_crossover_val_22 = ta.crossover(mfi_100,22)
mfi_100_crossover_val_15 = ta.crossover(mfi_100,15)
mfi_100_crossunder_val_85 = ta.crossunder(mfi_100,85)
mfi_100_crossunder_val_78 = ta.crossunder(mfi_100,78)
mfi_100_crossunder_val_71 = ta.crossunder(mfi_100,71)
mfi_100_crossunder_val_64 = ta.crossunder(mfi_100,64)
mfi_100_crossunder_val_57 = ta.crossunder(mfi_100,57)
mfi_100_crossunder_val_50 = ta.crossunder(mfi_100,50)
mfi_100_crossunder_val_43 = ta.crossunder(mfi_100,43)
mfi_100_crossunder_val_36 = ta.crossunder(mfi_100,36)
mfi_100_crossunder_val_29 = ta.crossunder(mfi_100,29)
mfi_100_crossunder_val_22 = ta.crossunder(mfi_100,22)
mfi_100_crossunder_val_15 = ta.crossunder(mfi_100,15)
if mfi_100_crossover_val_85 or mfi_100_crossover_val_78 or mfi_100_crossover_val_71 or mfi_100_crossover_val_64 or mfi_100_crossover_val_57 or mfi_100_crossover_val_50 or mfi_100_crossover_val_43 or mfi_100_crossover_val_36 or mfi_100_crossover_val_29 or mfi_100_crossover_val_22 or mfi_100_crossover_val_15
positive_signal := positive_signal + 1
if mfi_100_crossunder_val_85 or mfi_100_crossunder_val_78 or mfi_100_crossunder_val_71 or mfi_100_crossunder_val_64 or mfi_100_crossunder_val_57 or mfi_100_crossunder_val_50 or mfi_100_crossunder_val_43 or mfi_100_crossunder_val_36 or mfi_100_crossunder_val_29 or mfi_100_crossunder_val_22 or mfi_100_crossunder_val_15
positive_signal := positive_signal - 1
mfi_200_crossover_val_80 = ta.crossover(mfi_200,80)
mfi_200_crossover_val_74 = ta.crossover(mfi_200,74)
mfi_200_crossover_val_68 = ta.crossover(mfi_200,68)
mfi_200_crossover_val_62 = ta.crossover(mfi_200,62)
mfi_200_crossover_val_56 = ta.crossover(mfi_200,56)
mfi_200_crossover_val_50 = ta.crossover(mfi_200,50)
mfi_200_crossover_val_44 = ta.crossover(mfi_200,44)
mfi_200_crossover_val_38 = ta.crossover(mfi_200,38)
mfi_200_crossover_val_32 = ta.crossover(mfi_200,32)
mfi_200_crossover_val_26 = ta.crossover(mfi_200,26)
mfi_200_crossover_val_20 = ta.crossover(mfi_200,20)
mfi_200_crossunder_val_80 = ta.crossunder(mfi_200,80)
mfi_200_crossunder_val_74 = ta.crossunder(mfi_200,74)
mfi_200_crossunder_val_68 = ta.crossunder(mfi_200,68)
mfi_200_crossunder_val_62 = ta.crossunder(mfi_200,62)
mfi_200_crossunder_val_56 = ta.crossunder(mfi_200,56)
mfi_200_crossunder_val_50 = ta.crossunder(mfi_200,50)
mfi_200_crossunder_val_44 = ta.crossunder(mfi_200,44)
mfi_200_crossunder_val_38 = ta.crossunder(mfi_200,38)
mfi_200_crossunder_val_32 = ta.crossunder(mfi_200,32)
mfi_200_crossunder_val_26 = ta.crossunder(mfi_200,26)
mfi_200_crossunder_val_20 = ta.crossunder(mfi_200,20)
if mfi_200_crossover_val_80 or mfi_200_crossover_val_74 or mfi_200_crossover_val_68 or mfi_200_crossover_val_62 or mfi_200_crossover_val_56 or mfi_200_crossover_val_50 or mfi_200_crossover_val_44 or mfi_200_crossover_val_38 or mfi_200_crossover_val_32 or mfi_200_crossover_val_26 or mfi_200_crossover_val_20
positive_signal := positive_signal + 1
if mfi_200_crossunder_val_80 or mfi_200_crossunder_val_74 or mfi_200_crossunder_val_68 or mfi_200_crossunder_val_62 or mfi_200_crossunder_val_56 or mfi_200_crossunder_val_50 or mfi_200_crossunder_val_44 or mfi_200_crossunder_val_38 or mfi_200_crossunder_val_32 or mfi_200_crossunder_val_26 or mfi_200_crossunder_val_20
positive_signal := positive_signal - 1
//Multi timeframe relative volatility index (RVI)
src_rvi_10 = input(close,title = "Source of RVI-10 is", group = "Revative Volatility Index (RVI)", inline = '10')
lb_rvi_10 = 10
cal_method_rvi_10 = input.string(title = "& calculation method is", options=['EMA', 'SMA'], defval='EMA', group = "Revative Volatility Index (RVI)", inline = '10')
stddev_rvi_10 = ta.stdev(src_rvi_10, lb_rvi_10)
var float upper_rvi_10 = 0
var float lower_rvi_10 = 0
if cal_method_rvi_10 == "EMA"
upper_rvi_10 := ta.ema(ta.change(src_rvi_10) <= 0 ? 0 : stddev_rvi_10, lb_rvi_10)
lower_rvi_10 := ta.ema(ta.change(src_rvi_10) > 0 ? 0 : stddev_rvi_10, lb_rvi_10)
else if cal_method_rvi_10 == "SMA"
upper_rvi_10 := ta.sma(ta.change(src_rvi_10) <= 0 ? 0 : stddev_rvi_10, lb_rvi_10)
lower_rvi_10 := ta.sma(ta.change(src_rvi_10) > 0 ? 0 : stddev_rvi_10, lb_rvi_10)
rvi_10 = upper_rvi_10 / (upper_rvi_10 + lower_rvi_10) * 100
src_rvi_50 = input(close,title = "Source of RVI-50 is", group = "Revative Volatility Index (RVI)", inline = '50')
lb_rvi_50 = 50
cal_method_rvi_50 = input.string(title = "& calculation method is", options=['EMA', 'SMA'], defval='EMA', group = "Revative Volatility Index (RVI)", inline = '50')
stddev_rvi_50 = ta.stdev(src_rvi_50, lb_rvi_50)
var float upper_rvi_50 = 0
var float lower_rvi_50 = 0
if cal_method_rvi_50 == "EMA"
upper_rvi_50 := ta.ema(ta.change(src_rvi_50) <= 0 ? 0 : stddev_rvi_50, lb_rvi_50)
lower_rvi_50 := ta.ema(ta.change(src_rvi_50) > 0 ? 0 : stddev_rvi_50, lb_rvi_50)
else if cal_method_rvi_50 == "SMA"
upper_rvi_50 := ta.sma(ta.change(src_rvi_50) <= 0 ? 0 : stddev_rvi_50, lb_rvi_50)
lower_rvi_50 := ta.sma(ta.change(src_rvi_50) > 0 ? 0 : stddev_rvi_50, lb_rvi_50)
rvi_50 = upper_rvi_50 / (upper_rvi_50 + lower_rvi_50) * 100
src_rvi_100 = input(close,title = "Source of RVI-100 is", group = "Revative Volatility Index (RVI)", inline = '100')
lb_rvi_100 = 100
cal_method_rvi_100 = input.string(title = "& calculation method is", options=['EMA', 'SMA'], defval='EMA', group = "Revative Volatility Index (RVI)", inline = '100')
stddev_rvi_100 = ta.stdev(src_rvi_100, lb_rvi_100)
var float upper_rvi_100 = 0
var float lower_rvi_100 = 0
if cal_method_rvi_100 == "EMA"
upper_rvi_100 := ta.ema(ta.change(src_rvi_100) <= 0 ? 0 : stddev_rvi_100, lb_rvi_100)
lower_rvi_100 := ta.ema(ta.change(src_rvi_100) > 0 ? 0 : stddev_rvi_100, lb_rvi_100)
else if cal_method_rvi_100 == "SMA"
upper_rvi_100 := ta.sma(ta.change(src_rvi_100) <= 0 ? 0 : stddev_rvi_100, lb_rvi_100)
lower_rvi_100 := ta.sma(ta.change(src_rvi_100) > 0 ? 0 : stddev_rvi_100, lb_rvi_100)
rvi_100 = upper_rvi_100 / (upper_rvi_100 + lower_rvi_100) * 100
src_rvi_200 = input(close,title = "Source of RVI-200 is", group = "Revative Volatility Index (RVI)", inline = '200')
lb_rvi_200 = 200
cal_method_rvi_200 = input.string(title = "& calculation method is", options=['EMA', 'SMA'], defval='EMA', group = "Revative Volatility Index (RVI)", inline = '200')
stddev_rvi_200 = ta.stdev(src_rvi_200, lb_rvi_200)
var float upper_rvi_200 = 0
var float lower_rvi_200 = 0
if cal_method_rvi_200 == "EMA"
upper_rvi_200 := ta.ema(ta.change(src_rvi_200) <= 0 ? 0 : stddev_rvi_200, lb_rvi_200)
lower_rvi_200 := ta.ema(ta.change(src_rvi_200) > 0 ? 0 : stddev_rvi_200, lb_rvi_200)
else if cal_method_rvi_200 == "SMA"
upper_rvi_200 := ta.sma(ta.change(src_rvi_200) <= 0 ? 0 : stddev_rvi_200, lb_rvi_200)
lower_rvi_200 := ta.sma(ta.change(src_rvi_200) > 0 ? 0 : stddev_rvi_200, lb_rvi_200)
rvi_200 = upper_rvi_200 / (upper_rvi_200 + lower_rvi_200) * 100
//RVI Crossing over and under each other
rvi_10_crossover_rvi_50 = ta.crossover(rvi_10,rvi_50)
rvi_10_crossover_rvi_100 = ta.crossover(rvi_10,rvi_100)
rvi_10_crossover_rvi_200 = ta.crossover(rvi_10,rvi_200)
rvi_50_crossover_rvi_100 = ta.crossover(rvi_50,rvi_100)
rvi_50_crossover_rvi_200 = ta.crossover(rvi_50,rvi_200)
rvi_100_crossover_rvi_200 = ta.crossover(rvi_100,rvi_200)
rvi_10_crossunder_rvi_50 = ta.crossunder(rvi_10,rvi_50)
rvi_10_crossunder_rvi_100 = ta.crossunder(rvi_10,rvi_100)
rvi_10_crossunder_rvi_200 = ta.crossunder(rvi_10,rvi_200)
rvi_50_crossunder_rvi_100 = ta.crossunder(rvi_50,rvi_100)
rvi_50_crossunder_rvi_200 = ta.crossunder(rvi_50,rvi_200)
rvi_100_crossunder_rvi_200 = ta.crossunder(rvi_100,rvi_200)
if rvi_10_crossover_rvi_50 or rvi_10_crossover_rvi_100 or rvi_10_crossover_rvi_200 or rvi_50_crossover_rvi_100 or rvi_50_crossover_rvi_200 or rvi_100_crossover_rvi_200
positive_signal := positive_signal + 1
if rvi_10_crossunder_rvi_50 or rvi_10_crossunder_rvi_100 or rvi_10_crossunder_rvi_200 or rvi_50_crossunder_rvi_100 or rvi_50_crossunder_rvi_200 or rvi_100_crossunder_rvi_200
positive_signal := positive_signal - 1
//RVI crossing different values
rvi_10_crossover_val_0 = ta.cross(rvi_10,0)
rvi_10_crossover_val_10 = ta.crossover(rvi_10,10)
rvi_10_crossover_val_20 = ta.crossover(rvi_10,20)
rvi_10_crossover_val_30 = ta.crossover(rvi_10,30)
rvi_10_crossover_val_40 = ta.crossover(rvi_10,40)
rvi_10_crossover_val_50 = ta.crossover(rvi_10,50)
rvi_10_crossover_val_60 = ta.crossover(rvi_10,60)
rvi_10_crossover_val_70 = ta.crossover(rvi_10,70)
rvi_10_crossover_val_80 = ta.crossover(rvi_10,80)
rvi_10_crossover_val_90 = ta.crossover(rvi_10,90)
rvi_10_crossover_val_100 = ta.cross(rvi_10,100)
rvi_10_crossunder_val_0 = ta.cross(rvi_10,0)
rvi_10_crossunder_val_10 = ta.crossunder(rvi_10,10)
rvi_10_crossunder_val_20 = ta.crossunder(rvi_10,20)
rvi_10_crossunder_val_30 = ta.crossunder(rvi_10,30)
rvi_10_crossunder_val_40 = ta.crossunder(rvi_10,40)
rvi_10_crossunder_val_50 = ta.crossunder(rvi_10,50)
rvi_10_crossunder_val_60 = ta.crossunder(rvi_10,60)
rvi_10_crossunder_val_70 = ta.crossunder(rvi_10,70)
rvi_10_crossunder_val_80 = ta.crossunder(rvi_10,80)
rvi_10_crossunder_val_90 = ta.crossunder(rvi_10,90)
rvi_10_crossunder_val_100 = ta.cross(rvi_10,100)
if rvi_10_crossover_val_0 or rvi_10_crossover_val_10 or rvi_10_crossover_val_20 or rvi_10_crossover_val_30 or rvi_10_crossover_val_40 or rvi_10_crossover_val_50 or rvi_10_crossover_val_60 or rvi_10_crossover_val_70 or rvi_10_crossover_val_80 or rvi_10_crossover_val_90 or rvi_10_crossover_val_100
positive_signal := positive_signal + 1
if rvi_10_crossunder_val_0 or rvi_10_crossunder_val_10 or rvi_10_crossunder_val_20 or rvi_10_crossunder_val_30 or rvi_10_crossunder_val_40 or rvi_10_crossunder_val_50 or rvi_10_crossunder_val_60 or rvi_10_crossunder_val_70 or rvi_10_crossunder_val_80 or rvi_10_crossunder_val_90 or rvi_10_crossunder_val_100
positive_signal := positive_signal - 1
rvi_50_crossover_val_75 = ta.crossover(rvi_50,75)
rvi_50_crossover_val_70 = ta.crossover(rvi_50,70)
rvi_50_crossover_val_65 = ta.crossover(rvi_50,65)
rvi_50_crossover_val_60 = ta.crossover(rvi_50,60)
rvi_50_crossover_val_55 = ta.crossover(rvi_50,55)
rvi_50_crossover_val_50 = ta.crossover(rvi_50,50)
rvi_50_crossover_val_45 = ta.crossover(rvi_50,45)
rvi_50_crossover_val_40 = ta.crossover(rvi_50,40)
rvi_50_crossover_val_35 = ta.crossover(rvi_50,35)
rvi_50_crossover_val_30 = ta.crossover(rvi_50,30)
rvi_50_crossover_val_25 = ta.crossover(rvi_50,25)
rvi_50_crossunder_val_75 = ta.crossunder(rvi_50,75)
rvi_50_crossunder_val_70 = ta.crossunder(rvi_50,70)
rvi_50_crossunder_val_65 = ta.crossunder(rvi_50,65)
rvi_50_crossunder_val_60 = ta.crossunder(rvi_50,60)
rvi_50_crossunder_val_55 = ta.crossunder(rvi_50,55)
rvi_50_crossunder_val_50 = ta.crossunder(rvi_50,50)
rvi_50_crossunder_val_45 = ta.crossunder(rvi_50,45)
rvi_50_crossunder_val_40 = ta.crossunder(rvi_50,40)
rvi_50_crossunder_val_35 = ta.crossunder(rvi_50,35)
rvi_50_crossunder_val_30 = ta.crossunder(rvi_50,30)
rvi_50_crossunder_val_25 = ta.crossunder(rvi_50,25)
if rvi_50_crossover_val_75 or rvi_50_crossover_val_70 or rvi_50_crossover_val_65 or rvi_50_crossover_val_60 or rvi_50_crossover_val_55 or rvi_50_crossover_val_50 or rvi_50_crossover_val_45 or rvi_50_crossover_val_40 or rvi_50_crossover_val_35 or rvi_50_crossover_val_30 or rvi_50_crossover_val_25
positive_signal := positive_signal + 1
if rvi_50_crossunder_val_75 or rvi_50_crossunder_val_70 or rvi_50_crossunder_val_65 or rvi_50_crossunder_val_60 or rvi_50_crossunder_val_55 or rvi_50_crossunder_val_50 or rvi_50_crossunder_val_45 or rvi_50_crossunder_val_40 or rvi_50_crossunder_val_35 or rvi_50_crossunder_val_30 or rvi_50_crossunder_val_25
positive_signal := positive_signal - 1
rvi_100_crossover_val_70 = ta.crossover(rvi_100,70)
rvi_100_crossover_val_66 = ta.crossover(rvi_100,66)
rvi_100_crossover_val_62 = ta.crossover(rvi_100,62)
rvi_100_crossover_val_58 = ta.crossover(rvi_100,58)
rvi_100_crossover_val_54 = ta.crossover(rvi_100,54)
rvi_100_crossover_val_50 = ta.crossover(rvi_100,50)
rvi_100_crossover_val_46 = ta.crossover(rvi_100,46)
rvi_100_crossover_val_42 = ta.crossover(rvi_100,42)
rvi_100_crossover_val_38 = ta.crossover(rvi_100,38)
rvi_100_crossover_val_34 = ta.crossover(rvi_100,34)
rvi_100_crossover_val_30 = ta.crossover(rvi_100,30)
rvi_100_crossunder_val_70 = ta.crossunder(rvi_100,70)
rvi_100_crossunder_val_66 = ta.crossunder(rvi_100,66)
rvi_100_crossunder_val_62 = ta.crossunder(rvi_100,62)
rvi_100_crossunder_val_58 = ta.crossunder(rvi_100,58)
rvi_100_crossunder_val_54 = ta.crossunder(rvi_100,54)
rvi_100_crossunder_val_50 = ta.crossunder(rvi_100,50)
rvi_100_crossunder_val_46 = ta.crossunder(rvi_100,46)
rvi_100_crossunder_val_42 = ta.crossunder(rvi_100,42)
rvi_100_crossunder_val_38 = ta.crossunder(rvi_100,38)
rvi_100_crossunder_val_34 = ta.crossunder(rvi_100,34)
rvi_100_crossunder_val_30 = ta.crossunder(rvi_100,30)
if rvi_100_crossover_val_70 or rvi_100_crossover_val_66 or rvi_100_crossover_val_62 or rvi_100_crossover_val_58 or rvi_100_crossover_val_54 or rvi_100_crossover_val_50 or rvi_100_crossover_val_46 or rvi_100_crossover_val_42 or rvi_100_crossover_val_38 or rvi_100_crossover_val_34 or rvi_100_crossover_val_30
positive_signal := positive_signal + 1
if rvi_100_crossunder_val_70 or rvi_100_crossunder_val_66 or rvi_100_crossunder_val_62 or rvi_100_crossunder_val_58 or rvi_100_crossunder_val_54 or rvi_100_crossunder_val_50 or rvi_100_crossunder_val_46 or rvi_100_crossunder_val_42 or rvi_100_crossunder_val_38 or rvi_100_crossunder_val_34 or rvi_100_crossunder_val_30
positive_signal := positive_signal - 1
rvi_200_crossover_val_65 = ta.crossover(rvi_200,65)
rvi_200_crossover_val_62 = ta.crossover(rvi_200,62)
rvi_200_crossover_val_59 = ta.crossover(rvi_200,59)
rvi_200_crossover_val_56 = ta.crossover(rvi_200,56)
rvi_200_crossover_val_53 = ta.crossover(rvi_200,53)
rvi_200_crossover_val_50 = ta.crossover(rvi_200,50)
rvi_200_crossover_val_47 = ta.crossover(rvi_200,47)
rvi_200_crossover_val_44 = ta.crossover(rvi_200,44)
rvi_200_crossover_val_41 = ta.crossover(rvi_200,41)
rvi_200_crossover_val_38 = ta.crossover(rvi_200,38)
rvi_200_crossover_val_35 = ta.crossover(rvi_200,35)
rvi_200_crossunder_val_65 = ta.crossunder(rvi_200,65)
rvi_200_crossunder_val_62 = ta.crossunder(rvi_200,62)
rvi_200_crossunder_val_59 = ta.crossunder(rvi_200,59)
rvi_200_crossunder_val_56 = ta.crossunder(rvi_200,56)
rvi_200_crossunder_val_53 = ta.crossunder(rvi_200,53)
rvi_200_crossunder_val_50 = ta.crossunder(rvi_200,50)
rvi_200_crossunder_val_47 = ta.crossunder(rvi_200,47)
rvi_200_crossunder_val_44 = ta.crossunder(rvi_200,44)
rvi_200_crossunder_val_41 = ta.crossunder(rvi_200,41)
rvi_200_crossunder_val_38 = ta.crossunder(rvi_200,38)
rvi_200_crossunder_val_35 = ta.crossunder(rvi_200,35)
if rvi_200_crossover_val_65 or rvi_200_crossover_val_62 or rvi_200_crossover_val_59 or rvi_200_crossover_val_56 or rvi_200_crossover_val_53 or rvi_200_crossover_val_50 or rvi_200_crossover_val_47 or rvi_200_crossover_val_44 or rvi_200_crossover_val_41 or rvi_200_crossover_val_38 or rvi_200_crossover_val_35
positive_signal := positive_signal + 1
if rvi_200_crossunder_val_65 or rvi_200_crossunder_val_62 or rvi_200_crossunder_val_59 or rvi_200_crossunder_val_56 or rvi_200_crossunder_val_53 or rvi_200_crossunder_val_50 or rvi_200_crossunder_val_47 or rvi_200_crossunder_val_44 or rvi_200_crossunder_val_41 or rvi_200_crossunder_val_38 or rvi_200_crossunder_val_35
positive_signal := positive_signal - 1
//Balance of power
bop = ((((close - open) / (high - low))*100)+50)
cal_method_bop_10 = input.string(title = "BOP-10 cal method is", options=['EMA', 'SMA'], defval='EMA', group = "Balance of Power (BOP)")
cal_method_bop_50 = input.string(title = "BOP-50 cal method is", options=['EMA', 'SMA'], defval='EMA', group = "Balance of Power (BOP)")
cal_method_bop_100 = input.string(title = "BOP-100 cal method is", options=['EMA', 'SMA'], defval='EMA', group = "Balance of Power (BOP)")
cal_method_bop_200 = input.string(title = "BOP-200 cal method is", options=['EMA', 'SMA'], defval='EMA', group = "Balance of Power (BOP)")
var float bop_10 = 0
var float bop_50 = 0
var float bop_100 = 0
var float bop_200 = 0
if cal_method_bop_10 == "SMA"
bop_10 := ta.sma(bop,10)
else if cal_method_bop_10 == "EMA"
bop_10 := ta.ema(bop,10)
if cal_method_bop_50 == "SMA"
bop_50 := ta.sma(bop,50)
else if cal_method_bop_50 == "EMA"
bop_50 := ta.ema(bop,50)
if cal_method_bop_100 == "SMA"
bop_100 := ta.sma(bop,100)
else if cal_method_bop_100 == "EMA"
bop_100 := ta.ema(bop,100)
if cal_method_bop_200 == "SMA"
bop_200 := ta.sma(bop,200)
else if cal_method_bop_200 == "EMA"
bop_200 := ta.ema(bop,200)
//BOP Crossing over and under each other
bop_10_crossover_bop_50 = ta.crossover(bop_10,bop_50)
bop_10_crossover_bop_100 = ta.crossover(bop_10,bop_100)
bop_10_crossover_bop_200 = ta.crossover(bop_10,bop_200)
bop_50_crossover_bop_100 = ta.crossover(bop_50,bop_100)
bop_50_crossover_bop_200 = ta.crossover(bop_50,bop_200)
bop_100_crossover_bop_200 = ta.crossover(bop_100,bop_200)
bop_10_crossunder_bop_50 = ta.crossunder(bop_10,bop_50)
bop_10_crossunder_bop_100 = ta.crossunder(bop_10,bop_100)
bop_10_crossunder_bop_200 = ta.crossunder(bop_10,bop_200)
bop_50_crossunder_bop_100 = ta.crossunder(bop_50,bop_100)
bop_50_crossunder_bop_200 = ta.crossunder(bop_50,bop_200)
bop_100_crossunder_bop_200 = ta.crossunder(bop_100,bop_200)
if bop_10_crossover_bop_50 or bop_10_crossover_bop_100 or bop_10_crossover_bop_200 or bop_50_crossover_bop_100 or bop_50_crossover_bop_200 or bop_100_crossover_bop_200
positive_signal := positive_signal + 1
if bop_10_crossunder_bop_50 or bop_10_crossunder_bop_100 or bop_10_crossunder_bop_200 or bop_50_crossunder_bop_100 or bop_50_crossunder_bop_200 or bop_100_crossunder_bop_200
positive_signal := positive_signal - 1
//BOP crossing different values
bop_10_crossover_val_0 = ta.cross(bop_10,0)
bop_10_crossover_val_10 = ta.crossover(bop_10,10)
bop_10_crossover_val_20 = ta.crossover(bop_10,20)
bop_10_crossover_val_30 = ta.crossover(bop_10,30)
bop_10_crossover_val_40 = ta.crossover(bop_10,40)
bop_10_crossover_val_50 = ta.crossover(bop_10,50)
bop_10_crossover_val_60 = ta.crossover(bop_10,60)
bop_10_crossover_val_70 = ta.crossover(bop_10,70)
bop_10_crossover_val_80 = ta.crossover(bop_10,80)
bop_10_crossover_val_90 = ta.crossover(bop_10,90)
bop_10_crossover_val_100 = ta.cross(bop_10,100)
bop_10_crossunder_val_0 = ta.cross(bop_10,0)
bop_10_crossunder_val_10 = ta.crossunder(bop_10,10)
bop_10_crossunder_val_20 = ta.crossunder(bop_10,20)
bop_10_crossunder_val_30 = ta.crossunder(bop_10,30)
bop_10_crossunder_val_40 = ta.crossunder(bop_10,40)
bop_10_crossunder_val_50 = ta.crossunder(bop_10,50)
bop_10_crossunder_val_60 = ta.crossunder(bop_10,60)
bop_10_crossunder_val_70 = ta.crossunder(bop_10,70)
bop_10_crossunder_val_80 = ta.crossunder(bop_10,80)
bop_10_crossunder_val_90 = ta.crossunder(bop_10,90)
bop_10_crossunder_val_100 = ta.cross(bop_10,100)
if bop_10_crossover_val_0 or bop_10_crossover_val_10 or bop_10_crossover_val_20 or bop_10_crossover_val_30 or bop_10_crossover_val_40 or bop_10_crossover_val_50 or bop_10_crossover_val_60 or bop_10_crossover_val_70 or bop_10_crossover_val_80 or bop_10_crossover_val_90 or bop_10_crossover_val_100
positive_signal := positive_signal + 1
if bop_10_crossunder_val_0 or bop_10_crossunder_val_10 or bop_10_crossunder_val_20 or bop_10_crossunder_val_30 or bop_10_crossunder_val_40 or bop_10_crossunder_val_50 or bop_10_crossunder_val_60 or bop_10_crossunder_val_70 or bop_10_crossunder_val_80 or bop_10_crossunder_val_90 or bop_10_crossunder_val_100
positive_signal := positive_signal - 1
bop_50_crossover_val_80 = ta.crossover(bop_50,80)
bop_50_crossover_val_74 = ta.crossover(bop_50,74)
bop_50_crossover_val_68 = ta.crossover(bop_50,68)
bop_50_crossover_val_62 = ta.crossover(bop_50,62)
bop_50_crossover_val_56 = ta.crossover(bop_50,56)
bop_50_crossover_val_50 = ta.crossover(bop_50,50)
bop_50_crossover_val_44 = ta.crossover(bop_50,44)
bop_50_crossover_val_38 = ta.crossover(bop_50,38)
bop_50_crossover_val_32 = ta.crossover(bop_50,32)
bop_50_crossover_val_26 = ta.crossover(bop_50,26)
bop_50_crossover_val_20 = ta.crossover(bop_50,20)
bop_50_crossunder_val_80 = ta.crossunder(bop_50,80)
bop_50_crossunder_val_74 = ta.crossunder(bop_50,74)
bop_50_crossunder_val_68 = ta.crossunder(bop_50,68)
bop_50_crossunder_val_62 = ta.crossunder(bop_50,62)
bop_50_crossunder_val_56 = ta.crossunder(bop_50,56)
bop_50_crossunder_val_50 = ta.crossunder(bop_50,50)
bop_50_crossunder_val_44 = ta.crossunder(bop_50,44)
bop_50_crossunder_val_38 = ta.crossunder(bop_50,38)
bop_50_crossunder_val_32 = ta.crossunder(bop_50,32)
bop_50_crossunder_val_26 = ta.crossunder(bop_50,26)
bop_50_crossunder_val_20 = ta.crossunder(bop_50,20)
if bop_50_crossover_val_80 or bop_50_crossover_val_74 or bop_50_crossover_val_68 or bop_50_crossover_val_62 or bop_50_crossover_val_56 or bop_50_crossover_val_50 or bop_50_crossover_val_44 or bop_50_crossover_val_38 or bop_50_crossover_val_32 or bop_50_crossover_val_26 or bop_50_crossover_val_20
positive_signal := positive_signal + 1
if bop_50_crossunder_val_80 or bop_50_crossunder_val_74 or bop_50_crossunder_val_68 or bop_50_crossunder_val_62 or bop_50_crossunder_val_56 or bop_50_crossunder_val_50 or bop_50_crossunder_val_44 or bop_50_crossunder_val_38 or bop_50_crossunder_val_32 or bop_50_crossunder_val_26 or bop_50_crossunder_val_20
positive_signal := positive_signal - 1
bop_100_crossover_val_75 = ta.crossover(bop_100,75)
bop_100_crossover_val_70 = ta.crossover(bop_100,70)
bop_100_crossover_val_65 = ta.crossover(bop_100,65)
bop_100_crossover_val_60 = ta.crossover(bop_100,60)
bop_100_crossover_val_55 = ta.crossover(bop_100,55)
bop_100_crossover_val_50 = ta.crossover(bop_100,50)
bop_100_crossover_val_45 = ta.crossover(bop_100,45)
bop_100_crossover_val_40 = ta.crossover(bop_100,40)
bop_100_crossover_val_35 = ta.crossover(bop_100,35)
bop_100_crossover_val_30 = ta.crossover(bop_100,30)
bop_100_crossover_val_25 = ta.crossover(bop_100,25)
bop_100_crossunder_val_75 = ta.crossunder(bop_100,75)
bop_100_crossunder_val_70 = ta.crossunder(bop_100,70)
bop_100_crossunder_val_65 = ta.crossunder(bop_100,65)
bop_100_crossunder_val_60 = ta.crossunder(bop_100,60)
bop_100_crossunder_val_55 = ta.crossunder(bop_100,55)
bop_100_crossunder_val_50 = ta.crossunder(bop_100,50)
bop_100_crossunder_val_45 = ta.crossunder(bop_100,45)
bop_100_crossunder_val_40 = ta.crossunder(bop_100,40)
bop_100_crossunder_val_35 = ta.crossunder(bop_100,35)
bop_100_crossunder_val_30 = ta.crossunder(bop_100,30)
bop_100_crossunder_val_25 = ta.crossunder(bop_100,25)
if bop_100_crossover_val_75 or bop_100_crossover_val_70 or bop_100_crossover_val_65 or bop_100_crossover_val_60 or bop_100_crossover_val_55 or bop_100_crossover_val_50 or bop_100_crossover_val_45 or bop_100_crossover_val_40 or bop_100_crossover_val_35 or bop_100_crossover_val_30 or bop_100_crossover_val_25
positive_signal := positive_signal + 1
if bop_100_crossunder_val_75 or bop_100_crossunder_val_70 or bop_100_crossunder_val_65 or bop_100_crossunder_val_60 or bop_100_crossunder_val_55 or bop_100_crossunder_val_50 or bop_100_crossunder_val_45 or bop_100_crossunder_val_40 or bop_100_crossunder_val_35 or bop_100_crossunder_val_30 or bop_100_crossunder_val_25
positive_signal := positive_signal - 1
bop_200_crossover_val_70 = ta.crossover(bop_200,70)
bop_200_crossover_val_66 = ta.crossover(bop_200,66)
bop_200_crossover_val_62 = ta.crossover(bop_200,62)
bop_200_crossover_val_58 = ta.crossover(bop_200,58)
bop_200_crossover_val_54 = ta.crossover(bop_200,54)
bop_200_crossover_val_50 = ta.crossover(bop_200,50)
bop_200_crossover_val_46 = ta.crossover(bop_200,46)
bop_200_crossover_val_42 = ta.crossover(bop_200,42)
bop_200_crossover_val_38 = ta.crossover(bop_200,38)
bop_200_crossover_val_34 = ta.crossover(bop_200,34)
bop_200_crossover_val_30 = ta.crossover(bop_200,30)
bop_200_crossunder_val_70 = ta.crossunder(bop_200,70)
bop_200_crossunder_val_66 = ta.crossunder(bop_200,66)
bop_200_crossunder_val_62 = ta.crossunder(bop_200,62)
bop_200_crossunder_val_58 = ta.crossunder(bop_200,58)
bop_200_crossunder_val_54 = ta.crossunder(bop_200,54)
bop_200_crossunder_val_50 = ta.crossunder(bop_200,50)
bop_200_crossunder_val_46 = ta.crossunder(bop_200,46)
bop_200_crossunder_val_42 = ta.crossunder(bop_200,42)
bop_200_crossunder_val_38 = ta.crossunder(bop_200,38)
bop_200_crossunder_val_34 = ta.crossunder(bop_200,34)
bop_200_crossunder_val_30 = ta.crossunder(bop_200,30)
if bop_200_crossover_val_70 or bop_200_crossover_val_66 or bop_200_crossover_val_62 or bop_200_crossover_val_58 or bop_200_crossover_val_54 or bop_200_crossover_val_50 or bop_200_crossover_val_46 or bop_200_crossover_val_42 or bop_200_crossover_val_38 or bop_200_crossover_val_34 or bop_200_crossover_val_30
positive_signal := positive_signal + 1
if bop_200_crossunder_val_70 or bop_200_crossunder_val_66 or bop_200_crossunder_val_62 or bop_200_crossunder_val_58 or bop_200_crossunder_val_54 or bop_200_crossunder_val_50 or bop_200_crossunder_val_46 or bop_200_crossunder_val_42 or bop_200_crossunder_val_38 or bop_200_crossunder_val_34 or bop_200_crossunder_val_30
positive_signal := positive_signal - 1
//Simple moving average (SMA)
src_sma_10= input(close,title = "Source of SMA-10 is", group = "Simple moving average (SMA)")
sma_10 = ta.sma(src_sma_10,10)
src_sma_50= input(close,title = "Source of SMA-50 is", group = "Simple moving average (SMA)")
sma_50 = ta.sma(src_sma_50,50)
src_sma_100= input(close,title = "Source of SMA-100 is", group = "Simple moving average (SMA)")
sma_100 = ta.sma(src_sma_100,100)
src_sma_200= input(close,title = "Source of SMA-200 is", group = "Simple moving average (SMA)")
sma_200 = ta.sma(src_sma_200,200)
//SMA Crossing over and under each other
sma_10_crossover_sma_50 = ta.crossover(sma_10,sma_50)
sma_10_crossover_sma_100 = ta.crossover(sma_10,sma_100)
sma_10_crossover_sma_200 = ta.crossover(sma_10,sma_200)
sma_50_crossover_sma_100 = ta.crossover(sma_50,sma_100)
sma_50_crossover_sma_200 = ta.crossover(sma_50,sma_200)
sma_100_crossover_sma_200 = ta.crossover(sma_100,sma_200)
sma_10_crossunder_sma_50 = ta.crossunder(sma_10,sma_50)
sma_10_crossunder_sma_100 = ta.crossunder(sma_10,sma_100)
sma_10_crossunder_sma_200 = ta.crossunder(sma_10,sma_200)
sma_50_crossunder_sma_100 = ta.crossunder(sma_50,sma_100)
sma_50_crossunder_sma_200 = ta.crossunder(sma_50,sma_200)
sma_100_crossunder_sma_200 = ta.crossunder(sma_100,sma_200)
if sma_10_crossover_sma_50 or sma_10_crossover_sma_100 or sma_10_crossover_sma_200 or sma_50_crossover_sma_100 or sma_50_crossover_sma_200 or sma_100_crossover_sma_200
positive_signal := positive_signal + 1
if sma_10_crossunder_sma_50 or sma_10_crossunder_sma_100 or sma_10_crossunder_sma_200 or sma_50_crossunder_sma_100 or sma_50_crossunder_sma_200 or sma_100_crossunder_sma_200
positive_signal := positive_signal - 1
//Exponential Moving average (EMA)
src_ema_10= input(close,title = "Source of EMA-10 is", group = "Exponential Moving average (EMA)")
ema_10 = ta.ema(src_ema_10,10)
src_ema_50= input(close,title = "Source of EMA-50 is", group = "Exponential Moving average (EMA)")
ema_50 = ta.ema(src_ema_50,50)
src_ema_100= input(close,title = "Source of EMA-100 is", group = "Exponential Moving average (EMA)")
ema_100 = ta.ema(src_ema_100,100)
src_ema_200= input(close,title = "Source of EMA-200 is", group = "Exponential Moving average (EMA)")
ema_200 = ta.ema(src_ema_200,200)
//EMA Crossing over and under each other
ema_10_crossover_ema_50 = ta.crossover(ema_10,ema_50)
ema_10_crossover_ema_100 = ta.crossover(ema_10,ema_100)
ema_10_crossover_ema_200 = ta.crossover(ema_10,ema_200)
ema_50_crossover_ema_100 = ta.crossover(ema_50,ema_100)
ema_50_crossover_ema_200 = ta.crossover(ema_50,ema_200)
ema_100_crossover_ema_200 = ta.crossover(ema_100,ema_200)
ema_10_crossunder_ema_50 = ta.crossunder(ema_10,ema_50)
ema_10_crossunder_ema_100 = ta.crossunder(ema_10,ema_100)
ema_10_crossunder_ema_200 = ta.crossunder(ema_10,ema_200)
ema_50_crossunder_ema_100 = ta.crossunder(ema_50,ema_100)
ema_50_crossunder_ema_200 = ta.crossunder(ema_50,ema_200)
ema_100_crossunder_ema_200 = ta.crossunder(ema_100,ema_200)
if ema_10_crossover_ema_50 or ema_10_crossover_ema_100 or ema_10_crossover_ema_200 or ema_50_crossover_ema_100 or ema_50_crossover_ema_200 or ema_100_crossover_ema_200
positive_signal := positive_signal + 1
if ema_10_crossunder_ema_50 or ema_10_crossunder_ema_100 or ema_10_crossunder_ema_200 or ema_50_crossunder_ema_100 or ema_50_crossunder_ema_200 or ema_100_crossunder_ema_200
positive_signal := positive_signal - 1
//SAR indicator
start = input(0.02, title = "SAR Start value", group = "SAR")
increment = input(0.02, title = "SAR Incremental value", group = "SAR")
maximum = input(0.2, title = "SAR Max Value", group = "SAR")
out = ta.sar(start, increment, maximum)
if out <= close
positive_signal := positive_signal + 1
if out > close
positive_signal := positive_signal - 1
//SUper trend
atrPeriod = input(10, "ATR Length", group = "Super Trend")
factor = input.float(3.0, "Factor", step = 0.01, group = "Super Trend")
[supertrend, direction] = ta.supertrend(factor, atrPeriod)
if direction < 0
positive_signal := positive_signal + 1
else
positive_signal := positive_signal - 1
//Bollinger bands
var source_of_billinger_bands = input(defval = close, title = "Source of Bollinger bands will be", group = "Bollinger bands")
var look_back_period_of_billinger_bands = input.int(defval = 5, title = "Look back period of Bollinger bands will be", group = "Bollinger bands")
[middle_bb, upper_bb, lower_bb] = ta.bb(source_of_billinger_bands, look_back_period_of_billinger_bands, 1)
if close>middle_bb
positive_signal := positive_signal + math.floor(close/upper_bb) + 1
else if close<=middle_bb
positive_signal := positive_signal - math.floor(close/lower_bb) - 1
//Center of Gravity
cog_10 = ta.cog(close, 10)
sma_cog_10 = ta.sma(cog_10,3)
if cog_10>sma_cog_10
positive_signal := positive_signal + 1
else if cog_10<=sma_cog_10
positive_signal := positive_signal - 1
//End of calculations for positive signal
hl_period = input.int(defval = 50,title = "look back period")
//price_indicator_corelation = ta.correlation(positive_signal, close, hl_period)
signal_average = ta.sma(positive_signal/100,hl_period)
signal_high = ta.highest(positive_signal/100,hl_period)
signal_low = ta.lowest(positive_signal/100,hl_period)
var float co_variance_positive_signal_and_signal_high_high = 0
var float co_variance_positive_signal_and_signal_low_high = 0
a = array.new_float(0)
b = array.new_float(0)
c = array.new_float(0)
e = array.new_float(0)
//f = array.new_float(0)
for i = 0 to 10
array.push(a, positive_signal[i])
array.push(b, ((close+open)/2)[i])
array.push(c, signal_high[i])
array.push(e, signal_low[i])
co_variance_price_and_positive_signal = math.round(array.covariance(a, b)/100, 5)
co_variance_price_and_positive_signal_high = ta.highest(co_variance_price_and_positive_signal,5)
co_variance_positive_signal_and_signal_high = math.round(array.covariance(a, c), 5)
co_variance_positive_signal_and_signal_low = math.round(array.covariance(a, e), 5)
highest_val_co_variance_positive_signal_and_signal_high = ta.highest(co_variance_positive_signal_and_signal_high,5)
lowest_val_co_variance_positive_signal_and_signal_high = ta.lowest(co_variance_positive_signal_and_signal_high,5)
highest_val_co_variance_positive_signal_and_signal_low = ta.highest(co_variance_positive_signal_and_signal_low,5)
lowest_val_co_variance_positive_signal_and_signal_low = ta.lowest(co_variance_positive_signal_and_signal_low,5)
if co_variance_positive_signal_and_signal_high > 0
co_variance_positive_signal_and_signal_high_high := highest_val_co_variance_positive_signal_and_signal_high
else if co_variance_positive_signal_and_signal_high <= 0
co_variance_positive_signal_and_signal_high_high := lowest_val_co_variance_positive_signal_and_signal_high
if co_variance_positive_signal_and_signal_low > 0
co_variance_positive_signal_and_signal_low_high := highest_val_co_variance_positive_signal_and_signal_low
else if co_variance_positive_signal_and_signal_low <= 0
co_variance_positive_signal_and_signal_low_high := lowest_val_co_variance_positive_signal_and_signal_low
//signal generation
var use_point_1_cutoff_value = input.bool(defval = true, title = "Use Group 1 positive value", group = "Applicability of Co-variance and it’s values ", inline = 'Group 1')
var point_1_positive_cutoff_value = input.float(defval = 1, step = 0.1, minval = 0, title = "& value is", group = "Applicability of Co-variance and it’s values ", inline = 'Group 1')
//var point_1_negative_cutoff_value = input.float(defval = -0.5, step = 0.1, maxval = 0, title = "& negative value is", group = "Applicability of Co-variance and it’s values ", inline = 'Group 1')
var use_point_2_cutoff_value = input.bool(defval = true, title = "Use Group 2 positive value", group = "Applicability of Co-variance and it’s values ", inline = 'Group 2')
var point_2_positive_cutoff_value = input.float(defval = 1, step = 0.1, minval = 0, title = "& value is", group = "Applicability of Co-variance and it’s values ", inline = 'Group 2')
//var point_2_negative_cutoff_value = input.float(defval = -0.5, step = 0.1, maxval = 0, title = "& negative value is", group = "Applicability of Co-variance and it’s values ", inline = 'Group 2')
var use_point_3_cutoff_value = input.bool(defval = true, title = "Use Group 3 positive value", group = "Applicability of Co-variance and it’s values ", inline = 'Group 3')
var point_3_positive_cutoff_value = input.float(defval = 1, step = 0.1, minval = 0, title = "& value is", group = "Applicability of Co-variance and it’s values ", inline = 'Group 3')
//var point_3_negative_cutoff_value = input.float(defval = -0.5, step = 0.1, maxval = 0, title = "& negative value is", group = "Applicability of Co-variance and it’s values ", inline = 'Group 3')
var use_point_4_cutoff_value = input.bool(defval = true, title = "Use Group 4 negative value", group = "Applicability of Co-variance and it’s values ", inline = 'Group 4')
//var point_4_positive_cutoff_value = input.float(defval = 1, step = 0.1, minval = 0, title = "Group 4 positive value is", group = "Applicability of Co-variance and it’s values ", inline = 'Group 4')
var point_4_negative_cutoff_value = input.float(defval = -0.5, step = 0.1, maxval = 0, title = "& value is", group = "Applicability of Co-variance and it’s values ", inline = 'Group 4')
var use_point_5_cutoff_value = input.bool(defval = true, title = "Use Group 5 positive value", group = "Applicability of Co-variance and it’s values ", inline = 'Group 5')
var point_5_positive_cutoff_value = input.float(defval = 1, step = 0.1, minval = 0, title = "& value is", group = "Applicability of Co-variance and it’s values ", inline = 'Group 5')
//var point_5_negative_cutoff_value = input.float(defval = -0.5, step = 0.1, maxval = 0, title = "& negative value is", group = "Applicability of Co-variance and it’s values ", inline = 'Group 5')
var use_point_6_cutoff_value = input.bool(defval = true, title = "Use Group 6 negative value", group = "Applicability of Co-variance and it’s values ", inline = 'Group 6')
//var point_6_positive_cutoff_value = input.float(defval = 1, step = 0.1, minval = 0, title = "Group 6 positive value is", group = "Applicability of Co-variance and it’s values ", inline = 'Group 6')
var point_6_negative_cutoff_value = input.float(defval = -0.5, step = 0.1, maxval = 0, title = "& value is", group = "Applicability of Co-variance and it’s values ", inline = 'Group 6')
var use_point_7_cutoff_value = input.bool(defval = true, title = "Use Group 7 positive value", group = "Applicability of Co-variance and it’s values ", inline = 'Group 7')
var point_7_positive_cutoff_value = input.float(defval = 1, step = 0.1, minval = 0, title = "& value is", group = "Applicability of Co-variance and it’s values ", inline = 'Group 7')
//var point_7_negative_cutoff_value = input.float(defval = -0.5, step = 0.1, maxval = 0, title = "& negative value is", group = "Applicability of Co-variance and it’s values ", inline = 'Group 7')
var use_point_8_cutoff_value = input.bool(defval = true, title = "Use Group 8 negative value", group = "Applicability of Co-variance and it’s values ", inline = 'Group 8')
//var point_8_positive_cutoff_value = input.float(defval = 1, step = 0.1, minval = 0, title = "Group 8 positive value is", group = "Applicability of Co-variance and it’s values ", inline = 'Group 8')
var point_8_negative_cutoff_value = input.float(defval = -0.5, step = 0.1, maxval = 0, title = "& value is", group = "Applicability of Co-variance and it’s values ", inline = 'Group 8')
var use_point_9_cutoff_value = input.bool(defval = true, title = "Use Group 9 positive value", group = "Applicability of Co-variance and it’s values ", inline = 'Group 9')
var point_9_positive_cutoff_value = input.float(defval = 1, step = 0.1, minval = 0, title = "& value is", group = "Applicability of Co-variance and it’s values ", inline = 'Group 9')
//var point_9_negative_cutoff_value = input.float(defval = -0.5, step = 0.1, maxval = 0, title = "& negative value is", group = "Applicability of Co-variance and it’s values ", inline = 'Group 9')
var use_point_10_cutoff_value = input.bool(defval = true, title = "Use Group 10 negative value", group = "Applicability of Co-variance and it’s values ", inline = 'Group 10')
//var point_10_positive_cutoff_value = input.float(defval = 1, step = 0.1, minval = 0, title = "Group 10 positive value is", group = "Applicability of Co-variance and it’s values ", inline = 'Group 10')
var point_10_negative_cutoff_value = input.float(defval = -0.5, step = 0.1, maxval = 0, title = "& value is", group = "Applicability of Co-variance and it’s values ", inline = 'Group 10')
price_rising = ta.rising(ta.sma(close,9),5)
price_falling = ta.falling(ta.sma(close,9),5)
var bool point_one = false
var bool point_two = false
var bool point_three = false
var bool point_four = false
var bool point_five = false
var bool point_six = false
var bool point_seven = false
var bool point_eight = false
var bool point_nine = false
var bool point_ten = false
if co_variance_price_and_positive_signal[1] == co_variance_price_and_positive_signal_high[1] and co_variance_price_and_positive_signal < co_variance_price_and_positive_signal_high and co_variance_price_and_positive_signal >= point_1_positive_cutoff_value and price_falling
point_one := true
else
point_one := false
if co_variance_price_and_positive_signal[1] == co_variance_price_and_positive_signal_high[1] and co_variance_price_and_positive_signal < co_variance_price_and_positive_signal_high and co_variance_price_and_positive_signal >= point_2_positive_cutoff_value and price_rising
point_two := true
else
point_two := false
if co_variance_positive_signal_and_signal_high[1] == co_variance_positive_signal_and_signal_high_high[1] and co_variance_positive_signal_and_signal_high < co_variance_positive_signal_and_signal_high_high and co_variance_positive_signal_and_signal_high >= point_3_positive_cutoff_value and price_rising
point_three := true
else
point_three := false
if co_variance_positive_signal_and_signal_high[1] == co_variance_positive_signal_and_signal_high_high[1] and co_variance_positive_signal_and_signal_high > co_variance_positive_signal_and_signal_high_high and co_variance_positive_signal_and_signal_high <= point_4_negative_cutoff_value and price_rising
point_four := true
else
point_four := false
if co_variance_positive_signal_and_signal_low[1] == co_variance_positive_signal_and_signal_low_high[1] and co_variance_positive_signal_and_signal_low < co_variance_positive_signal_and_signal_low_high and co_variance_positive_signal_and_signal_low >= point_5_positive_cutoff_value and price_falling
point_five := true
else
point_five := false
if co_variance_positive_signal_and_signal_low[1] == co_variance_positive_signal_and_signal_low_high[1] and co_variance_positive_signal_and_signal_low > co_variance_positive_signal_and_signal_low_high and co_variance_positive_signal_and_signal_low <= point_6_negative_cutoff_value and price_falling
point_six := true
else
point_six := false
if co_variance_positive_signal_and_signal_high[1] == co_variance_positive_signal_and_signal_high_high[1] and co_variance_positive_signal_and_signal_high < co_variance_positive_signal_and_signal_high_high and co_variance_positive_signal_and_signal_high >= point_7_positive_cutoff_value and price_falling
point_seven := true
else
point_seven := false
if co_variance_positive_signal_and_signal_high[1] == co_variance_positive_signal_and_signal_high_high[1] and co_variance_positive_signal_and_signal_high > co_variance_positive_signal_and_signal_high_high and co_variance_positive_signal_and_signal_high <= point_8_negative_cutoff_value and price_falling
point_eight := true
else
point_eight := false
if co_variance_positive_signal_and_signal_low[1] == co_variance_positive_signal_and_signal_low_high[1] and co_variance_positive_signal_and_signal_low < co_variance_positive_signal_and_signal_low_high and co_variance_positive_signal_and_signal_low >= point_9_positive_cutoff_value and price_rising
point_nine := true
else
point_nine := false
if co_variance_positive_signal_and_signal_low[1] == co_variance_positive_signal_and_signal_low_high[1] and co_variance_positive_signal_and_signal_low > co_variance_positive_signal_and_signal_low_high and co_variance_positive_signal_and_signal_low <= point_10_negative_cutoff_value and price_rising
point_ten := true
else
point_ten := false
//Trading Arrangement
// Generate sell signal
var bool sell_comand = false
var factor_of_supertrend_to_determine_sell_comand = input.int(defval = 3, title = "Factor of supertrend to determine sell comand", group = "Determination of sell command")
var artperiod_of_supertrend_to_determine_sell_comand = input.int(defval = 10, title = "artPeriod of supertrend to determine sell comand", group = "Determination of sell command")
[pinesupertrend, pinedirection] = ta.supertrend(factor_of_supertrend_to_determine_sell_comand, artperiod_of_supertrend_to_determine_sell_comand)
plot(pinedirection < 0 ? pinesupertrend : na, "Up direction", color = color.green, style=plot.style_linebr)
plot(pinedirection < 0? na : pinesupertrend, "Down direction", color = color.red, style=plot.style_linebr)
if pinedirection[1] < 0 and pinedirection > 0
sell_comand := true
else if pinedirection > 0 and (point_two == true or point_three == true)
sell_comand := true
else
sell_comand := false
//Intermediate selling count & Count of open trades
var int open_trades = 0
var int x = 0
if strategy.position_size == 0
open_trades := 0
else if strategy.position_size[1] == 0 and strategy.position_size > 0
open_trades := 1
else if strategy.position_size[1] < strategy.position_size
open_trades := open_trades + 1
else if strategy.position_size[1] > strategy.position_size and strategy.position_size > 0
open_trades := open_trades - 1
else
open_trades := open_trades
if strategy.position_size[1] < strategy.position_size and strategy.position_size[1] > 0
x := open_trades
else if strategy.position_size[1] < strategy.position_size and strategy.position_size[1] == 0
x := 1
else if strategy.position_size[1] > strategy.position_size and strategy.position_size > 0
x := x - 1
else if strategy.position_size[1] > strategy.position_size and strategy.position_size == 0
x := 0
else
x := x
// Max count of open trades
var float max_open_trades = 0
if strategy.opentrades > max_open_trades
max_open_trades := strategy.opentrades
else
max_open_trades := max_open_trades
// Contrall Selling
var bool int_selling = false
if strategy.opentrades == strategy.opentrades [1]
int_selling := true
else if strategy.opentrades == strategy.opentrades [1] - 1
int_selling := false
// Calculation of profit precentage
var profit_precentage = input.int(defval=3, title = "Profit precentage will be")
var profit_precentage_intermidiate = input.int(defval=1, title = "Intermediate selling minimum profit precentage will be")
var float cal_profit_precentage = 0
if strategy.position_size == 0
cal_profit_precentage := na
else if strategy.position_size > 0
cal_profit_precentage := (profit_precentage/100) + 1
else
cal_profit_precentage := cal_profit_precentage
//Open trades entry price
var float result = 0
for i = 0 to strategy.opentrades-1
result := strategy.opentrades.entry_price(i)
var int y = 0
var int z = 0
if strategy.position_size[1] > 0 and strategy.position_size == 0
y := 0
z := 0
else if strategy.position_size[1] == 0 and strategy.position_size > 0
y := 1
z := 1
else if strategy.position_size[1] > strategy.position_size and strategy.position_size[1] > 0 and strategy.position_size > 0
y := y - 1
z := z + 1
else if strategy.position_size[1] < strategy.position_size and strategy.position_size[1] > 0 and strategy.position_size > 0
z := z + 1
y := y + 1
m = result
// Fund management - r value calculation
var int_cap = input.float(defval = 1000, title = "Cumilative Investment", group = "Fund Management")
var int_val_prc = input.float(defval = 15, title = "Value of first purchase will be", tooltip = "Minimum value of initial purchase will be 15USDT", group = "Fund Management", inline = "Investment")
int_val_allocation = input.string( title="", options=['% of cumilative investment', 'USDT'], defval='USDT', group = "Fund Management", inline = "Investment")
var piramiding = input.int(defval = 35, title = "Numbers of pararal entries", group = "Fund Management")
var r = input.float(defval = 5, title = "r starting value", group = "Input parameters for fund management")
var r_change_input = input.int(defval = 1, title = "Initiative value for r change", group = "Input parameters for fund management")
var r_finetune = input.bool(defval = false, title = "Use r = 0.001 to finetune r value", group = "Input parameters for fund management")
var float int_val_3 = 0
var float installment_2 = 0
var float installment_3 = 0
var float installment_4 = 0
var float r_f = 0
var float int_val = 0
if int_cap * int_val_prc/100 <= 15 and int_val_allocation != "USDT"
int_val := 15
if int_val_prc <= 15 and int_val_allocation == "USDT"
int_val := 15
if int_cap * int_val_prc/100 > 15 and int_val_allocation != "USDT"
int_val := int_cap * int_val_prc/100
if int_val_prc > 15 and int_val_allocation == "USDT"
int_val := int_val_prc
var float r_change = 0
if r_finetune == false
r_change := r_change_input
else if r_finetune == true
r_change := 0.001
for i = 0 to piramiding+2 by 1
if i == 0
int_val_3 := int_val
if i <= piramiding
installment_2 := int_val_3*math.pow((1 + r/100),i)
if i >= 0 and i < piramiding+1
installment_3 := installment_3 + installment_2
if i == piramiding+1
installment_4 := installment_3 - installment_3[1]
if installment_4 < int_cap
r := r + r_change
else if installment_4 > int_cap
r := r - r_change
else
r := r
if r[1] < r
r_f := r[1]
plot(r_f, title = "Calculated R value", color = color.new(color.white,100))
//Fund Management
var float total_investment = int_cap
if strategy.position_size[1] >0 and strategy.position_size == 0
total_investment := int_cap + strategy.netprofit
else
total_investment := total_investment
// Stratergy possition size
var float last_purchase = 0
if strategy.position_size[1] < strategy.position_size and strategy.position_size[1] == 0
last_purchase := strategy.position_size
else if strategy.position_size[1] < strategy.position_size and strategy.position_size[1] > 0
last_purchase := (strategy.position_size - strategy.position_size[1])
else if strategy.position_size == 0
last_purchase := 0
else
last_purchase := last_purchase
//Quantity Calculation
var purchaseing_method = input.string(title = "Value of Purchas will be", options=['Equal amounts','Incremental amounts'], defval='Equal amounts')
var dev_of_equal_amounts = input.string(title = "Value of Purchas will be", options=['Equal amounts with fixed USDT','Equal amounts with fixed entries'], defval='Equal amounts with fixed USDT')
var r_value = input.float(defval = 3.259, title = "Calculated r value")
var float value_of_purchase = 0
var float initial_quantity = 0
if purchaseing_method == 'Equal amounts' and dev_of_equal_amounts == 'Equal amounts with fixed entries' and y <= piramiding + 1
value_of_purchase := (total_investment/(piramiding + 1))
else if purchaseing_method == 'Equal amounts' and dev_of_equal_amounts == 'Equal amounts with fixed USDT' and y <= piramiding + 1
value_of_purchase := total_investment / (piramiding + 1)
if purchaseing_method == 'Incremental amounts' and int_val_allocation == '% of cumilative investment' and y <= piramiding + 1
value_of_purchase := (total_investment * (int_val_prc/100))* math.pow((1+(r_value/100)),y)
else if purchaseing_method == 'Incremental amounts' and int_val_allocation == 'USDT' and y <= piramiding + 1
value_of_purchase := (int_val_prc)* math.pow((1 + (r_value/100)),y)
quantity = value_of_purchase/close[1]
//Enter Coustom comand to perform buy and sell actions link with webhook
string buy_comment = "BUY"
string sell_comment = "SELL"
//Trading
if ((point_one == true )) and strategy.position_size == 0 and strategy.opentrades <= piramiding - 1 and sell_comand == false
strategy.entry("long", strategy.long, comment = buy_comment, qty = quantity)
else if ((point_one == true or point_five == true or point_six == true or point_seven == true) and ma_9 < strategy.position_avg_price *.99 and strategy.position_size > 0 ) and strategy.opentrades <= piramiding - 1 and sell_comand == false
strategy.entry("long", strategy.long, comment = buy_comment, qty = quantity)
if (sell_comand==true) and strategy.position_avg_price * cal_profit_precentage < ma_9
strategy.close("long", qty = strategy.position_size, comment = sell_comment)
//intermediate selling
if ((sell_comand==true) and m * (1 + profit_precentage_intermidiate/100) < ma_9 and strategy.position_avg_price * 0.98 > ma_9) and int_selling == true
strategy.close("long", qty = last_purchase[x], comment = sell_comment)
//Graphs
//color change
var hidden_color = color.new(color.white,100)
var color1 = color.blue
var color2 = color.orange
var color3 = color.white
var color4 = color.green
if show == "Compound Indicater"
color1 := color.blue
else
color1 := color.new(color.blue,100)
if show == "Co-variances"
color2 := color.orange
color3 := color.yellow
color4 := color.green
else
color2 := color.new(color.orange,100)
color3 := color.new(color.yellow,100)
color4 := color.new(color.green,100)
plot(strategy.position_avg_price, title = "Strategy Position Average Price", color = color.green, style = plot.style_circles)
plot(strategy.position_avg_price* cal_profit_precentage, title = "Strategy Profit Line", color = color.yellow, style = plot.style_circles)
plot(strategy.opentrades, title = "open trades", color = color.new(color.white,100))
plot(strategy.netprofit, title = "Cumilative Profits", color = color.new(color.white,100))
plot(total_investment, title = "Total Investment", color = color.new(color.white,100))
plot(result, title = "Entry Price", color = color.new(color.white,100))
plot(last_purchase, title = "Last purchase", color = color.new(color.white,100))
plot(y, title = "Y", color = color.new(color.white,100))
plot(value_of_purchase, title = "value_of_purchase", color = color.new(color.white,100))
plot(max_open_trades, title = "Max Opentrades", color = color.new(color.red,100))
plot(m, title = "m value", color = color.new(color.yellow,100))
//plot(pq, title = "pq value", color = color.new(color.yellow,100))
plot(positive_signal/1000, title = "Compound Indicater", color = color1)
plot((co_variance_price_and_positive_signal), title = "CV between Price & Signal", color = color2)
plot((co_variance_positive_signal_and_signal_high), title = "CV between Higher values & Signal", color = color3)
plot((co_variance_positive_signal_and_signal_low), title = "CV between Lower values & Signal", color = color4)
//Shapes
plotshape(ma_9<strategy.position_avg_price *.99 ? point_one == true:na, title = "End of Major downtrend", style = shape.arrowdown, color = color.orange, location = location.abovebar, size = size.large, text = "1")
plotshape(((sell_comand==true) and strategy.position_avg_price * cal_profit_precentage < ma_9) or ((sell_comand==true) and m * cal_profit_precentage < ma_9 and strategy.position_avg_price * 0.98 > ma_9)? point_two == true:na, title = "End of Major uptrend", style = shape.arrowdown, color = color.red, location = location.abovebar, size = size.large, text = "2")
plotshape(((sell_comand==true) and strategy.position_avg_price * cal_profit_precentage < ma_9) or ((sell_comand==true) and m * cal_profit_precentage < ma_9 and strategy.position_avg_price * 0.98 > ma_9)? point_three == true:na, title = "End of intermidiate uptrend", style = shape.arrowdown, color = color.white, location = location.abovebar, size = size.large, text = "3")
plotshape(ma_9<strategy.position_avg_price *.99 ? point_five == true:na, title = "End of intermidiate downtrend", style = shape.arrowdown, color = color.green, location = location.abovebar, size = size.large, text = "5")
plotshape(ma_9<strategy.position_avg_price *.99 ? point_six == true:na, title = "End of intermidiate downtrend", style = shape.arrowdown, color = color.olive, location = location.abovebar, size = size.large, text = "6")
plotshape(ma_9<strategy.position_avg_price *.99 ? point_seven == true:na, title = "End of intermidiate downtrend", style = shape.arrowdown, color = color.teal, location = location.abovebar, size = size.large, text = "7")
//plotshape(point_four == true, title = "4", style = shape.arrowdown, color = color.navy, location = location.abovebar, size = size.large, text = "4")
//plotshape(point_eight == true, title = "8", style = shape.arrowdown, color = color.gray, location = location.abovebar, size = size.large, text = "8")
//plotshape(point_nine == true, title = "9", style = shape.arrowdown, color = color.purple, location = location.abovebar, size = size.large, text = "9")
//plotshape(point_ten == true, title = "10", style = shape.arrowdown, color = color.maroon, location = location.abovebar, size = size.large, text = "10")
|
BTC Cap Dominance RSI Strategy | https://www.tradingview.com/script/r2LyZ0JA/ | chanu_lev10k | https://www.tradingview.com/u/chanu_lev10k/ | 118 | 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/
// © chanu_lev10k
//@version=5
strategy("BTC Cap Dominance RSI Strategy", overlay=false)
// Inputs
src = input.source(title='Source', defval=hlc3)
res = input.timeframe(title='Resolution', defval='1D')
len = input.int(defval=7, title='Length')
isdomin = input.bool(title='Use Combination of Dominance RSI ?', defval=true)
bullLevel = input.float(title='Bull Level', defval=56, step=1.0, maxval=100, minval=0)
bearLevel = input.float(title='Bear Level', defval=37, step=1.0, maxval=100, minval=0)
highlightBreakouts = input(title='Highlight Bull/Bear Breakouts ?', defval=true)
// BTC Cap Dominance RSI Definition
totalcap = request.security('CRYPTOCAP:TOTAL', res, src)
altcoincap = request.security('CRYPTOCAP:TOTAL2', res, src)
bitcoincap = totalcap - altcoincap
dominance = bitcoincap / totalcap
domin_f(res, len) =>
n = ta.rsi(bitcoincap, len)
t = (ta.rsi(bitcoincap, len) + ta.rsi(dominance, len))/2
isdomin ? t : n
tot_rsi = domin_f(res, len)
// Plot
rcColor = tot_rsi > bullLevel ? #0ebb23 : tot_rsi < bearLevel ? #ff0000 : #f4b77d
maxBand = hline(100, title='Max Level', linestyle=hline.style_dotted, color=color.white)
hline(0, title='Zero Level', linestyle=hline.style_dotted)
minBand = hline(0, title='Min Level', linestyle=hline.style_dotted, color=color.white)
bullBand = hline(bullLevel, title='Bull Level', linestyle=hline.style_dotted)
bearBand = hline(bearLevel, title='Bear Level', linestyle=hline.style_dotted)
fill(bullBand, bearBand, color=color.new(color.purple, 95))
bullFillColor = tot_rsi > bullLevel and highlightBreakouts ? color.green : na
bearFillColor = tot_rsi < bearLevel and highlightBreakouts ? color.red : na
fill(maxBand, bullBand, color=color.new(bullFillColor, 80))
fill(minBand, bearBand, color=color.new(bearFillColor, 80))
plot(tot_rsi, title='BTC Cap Dominance RSI', linewidth=2, color=rcColor)
plot(ta.rsi(bitcoincap, len), title='BTC Cap RSI', linewidth=1, color=color.new(color.purple, 0))
plot(ta.rsi(dominance, len), title='BTC Dominance RSI', linewidth=1, color=color.new(color.blue, 0))
// Long Short conditions
longCondition = ta.crossover(tot_rsi, bullLevel)
if longCondition
strategy.entry('Long', strategy.long)
shortCondition = ta.crossunder(tot_rsi, bearLevel)
if shortCondition
strategy.entry('Short', strategy.short) |
BTC WaveTrend R:R=1:1.5 | https://www.tradingview.com/script/P1BEGIzN/ | TrendCrypto2022 | https://www.tradingview.com/u/TrendCrypto2022/ | 392 | 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/
// ©TrendCrypto2022
//@version=5
strategy("4 - BTC WaveTrend R:R=1:1.5", overlay=true)
//WaveTrend indicator - author LazyBear
n1 = input(10, "Channel Length", group = "Set up WaveTrend")
n2 = input(21, "Average Length", group = "Set up WaveTrend")
oblv1 = input(60, "Over Bought Lv 1", group = "Set up WaveTrend")
oblv2 = input(53, "Over Bought Lv 2", group = "Set up WaveTrend")
oslv1 = input(-60, "Over Sold Lv 1", group = "Set up WaveTrend")
oslv2 = input(-53, "Over Sold Lv 2", group = "Set up WaveTrend")
ap = hlc3
esa = ta.ema(ap, n1)
d = ta.ema(math.abs(ap - esa), n1)
ci = (ap - esa) / (0.015 * d)
tci = ta.ema(ci, n2)
wt1 = tci
wt2 = ta.sma(wt1,4)
//Strategy
limitwt1 = input(20, "Limit value WT1 to open entry long", group = "Set up risk : reward")
buy = ta.crossover(wt1, wt2) and wt1 < limitwt1
if (buy)
strategy.entry("Long", strategy.long)
//Set up risk : reward
rr = input(1.5, "Risk : Reward", group = "Set up risk : reward")
var float stoplosslevel = na
if buy and strategy.position_size==0
stoplosslevel := math.min(low, low[1], low[2])
takeprofitlevel = strategy.position_avg_price + rr*(strategy.position_avg_price-stoplosslevel)
strategy.exit("Long", limit = takeprofitlevel, stop=stoplosslevel, comment="TP/SL")
//Plot SL and TP
p1=plot(strategy.position_size > 0 ? stoplosslevel : na, color=color.red, style=plot.style_linebr, title="SL")
p2=plot(strategy.position_size > 0 ? takeprofitlevel : na, color=color.lime, style=plot.style_linebr, title="TP")
p3=plot(strategy.position_size > 0 ? strategy.position_avg_price : na, color=color.silver, style=plot.style_linebr, title="Entry")
fill(p1, p3, color=color.red, transp = 90)
fill(p2, p3, color=color.green, transp = 90)
|
Top 40 High Low Strategy for SPY, 5min | https://www.tradingview.com/script/3BFuBf4F-Top-40-High-Low-Strategy-for-SPY-5min/ | PtGambler | https://www.tradingview.com/u/PtGambler/ | 638 | 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/
// © platsn
//
// *****************************************************************************************************************************************************************************************************
//@version=5
strategy("Top 40 High Low Strategy", overlay=true, pyramiding=0, initial_capital=5000, commission_type=strategy.commission.cash_per_contract, commission_value = 0.09)
// ******************** Period **************************************
startY = input(title='Start Year', defval=2011, group = "Trading window")
startM = input.int(title='Start Month', defval=1, minval=1, maxval=12, group = "Trading window")
startD = input.int(title='Start Day', defval=1, minval=1, maxval=31, group = "Trading window")
finishY = input(title='Finish Year', defval=2050, group = "Trading window")
finishM = input.int(title='Finish Month', defval=12, minval=1, maxval=12, group = "Trading window")
finishD = input.int(title='Finish Day', defval=31, minval=1, maxval=31, group = "Trading window")
timestart = timestamp(startY, startM, startD, 00, 00)
timefinish = timestamp(finishY, finishM, finishD, 23, 59)
t1 = time(timeframe.period, "0930-1500:23456")
t2 = time(timeframe.period, "0930-1600:23456")
window = time >= timestart and time <= timefinish and t1 ? true : false
window2 = time >= timestart and time <= timefinish and t2 ? true : false
// *****************************************************
isSPY = input.bool(defval=true,title="Options trading only", group = "Trading Options")
SPY_option = input.int(defval=10,title="# of options per trade", group = "Trading Options")
reinvest = input.bool(defval=false,title="Reinvest profit?", group = "Trading Options")
trade_trailing = input.bool(defval=true, title = "Trade Trailing SL after PT", group = "Trading Options")
trailing_stop = false
TS = 0
trade_earlyExit = input.bool(defval=true, title= "Take Profit early based on Top 40 overbought/oversold", group="Trading Options")
trade_expiry = input.bool(defval=true, title="Trade same/1 day expiry, exits EOD Mon/Wed/Fri; exits 1/2 Tues/Thurs", group="Trading Options")
src = close
// ***************************************************************************************************** Daily ATR *****************************************************
// // Inputs
atrlen = input.int(14, minval=1, title="ATR period", group = "ATR")
iPercent = input.float(130, minval=0, step=10, title="% ATR to use for SL / PT", group = "ATR")
// // Logic
percentage = iPercent * 0.01
atr = ta.rma(ta.tr, atrlen)
datrp = atr * percentage
// plot(datr,"Daily ATR")
// plot(atr, "ATR")
// plot(datrp, "ATR for SL/PT")
// ***************************************************************************************************************** MACD ************************
// Getting inputs
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="SMA", options=["SMA", "EMA"], group = "MACD")
sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"], group = "MACD")
// Plot colors
// col_macd = input(#2962FF, "MACD Line ", group="Color Settings", inline="MACD")
// col_signal = input(#FF6D00, "Signal Line ", group="Color Settings", inline="Signal")
// col_grow_above = input(#26A69A, "Above Grow", group="Histogram", inline="Above")
// col_fall_above = input(#B2DFDB, "Fall", group="Histogram", inline="Above")
// col_grow_below = input(#FFCDD2, "Below Grow", group="Histogram", inline="Below")
// col_fall_below = input(#FF5252, "Fall", group="Histogram", inline="Below")
// Calculating
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
macd_bull = hist > hist[1]
macd_bear = hist < hist[1]
// plot(macd_bull?1:0, "MACD bull")
// plot(macd_bear?1:0, "MACD bear")
macd_cross = ta.cross(macd,signal)
// **************************************************************************************************************** Linear Regression *************************
//Input
clen = input.int(defval = 48, minval = 1, title = "Linear Regression Period", group = "Linear Regression")
slen = input.int(defval=5, minval=1, title="LR Slope Period" , group = "Linear Regression")
glen = input.int(defval=14, minval=1, title="LR Signal Period", group = "Linear Regression")
LR_thres = input.float(18.8, minval=0, step=0.1, title="LR Threshold for Ranging vs Trending" , group = "Linear Regression")
//Linear Regression Curve
lrc = ta.linreg(src, clen, 0)
//Linear Regression Slope
lrs = (lrc-lrc[1])/1
//Smooth Linear Regression Slope
slrs = ta.ema(lrs, slen)
//Signal Linear Regression Slope
alrs = ta.sma(slrs, glen)
up_accel = lrs > alrs and lrs > 0
down_accel = lrs < alrs and lrs < 0
zero_accel = not(up_accel) and not(down_accel)
LR_upTrend = slrs > 0
LR_downTrend = slrs < 0
LR_ranging = math.abs(slrs)*100 <= LR_thres
LR_trending = math.abs(slrs)*100 > LR_thres
LR_bull = slrs > slrs[1]
LR_bear = slrs < slrs[1]
// plot(slrs*100, "LR slope")
// plot(LR_trending?1:0, "LR Trending")
plotchar(not(LR_trending[1]) and LR_trending and LR_upTrend, char="⇗", color=color.green, location = location.belowbar, size = size.small)
plotchar(not(LR_trending[1]) and LR_trending and LR_downTrend, char="⇘", color=color.red, location = location.abovebar, size = size.small)
plotchar(LR_trending[1] and not(LR_trending), char="⇒", color=color.gray, location = location.abovebar, size = size.small)
// *************************************************************************************************************************** Stochastic RSI ********************************
// Stochastic Main Parameters
smoothK = input.int(3, minval=1, title='Stoch K', group = "Stochastic RSI")
smoothD = input.int(3, minval=1, title='Stoch D', group = "Stochastic RSI")
lengthRSI = input.int(14, "RSI Length", minval=1, group = "Stochastic RSI")
lengthStoch = input.int(14, "Stochastic Length", minval=1, group = "Stochastic RSI")
rsi = ta.rsi(src, lengthRSI)
k = ta.sma(ta.stoch(rsi, rsi, rsi, lengthStoch), smoothK)
d = ta.sma(k, smoothD)
stoch_long = k < 10
stoch_short = k > 90
stoch_bottom = k[2] >= k[1] and k > k[1]
stoch_top = k[2] <= k[1] and k < k[1]
// *************************************************************************************************************************** RSI **********************
rsi_bull = rsi > rsi[1]
rsi_bear = rsi < rsi[1]
// plot(rsi,"RSI")
// plot(rsi_bull? 1:0, "RSI Bull")
// plot(rsi_bear?1:0, "RSI Bear")
// ********************************************************************************************************** High Low Index *****************************************************
// original author --> © LonesomeTheBlue
// changed list of 40 tickers to top 40 SPY holdings
timeFrame = input.timeframe(defval = '5', title = "Time Frame", group = "High Low Index")
length = input.int(defval = 15, title = "Length", minval = 1, group = "High Low Index")
source = input.string(defval = "High/Low", title = "Source", options = ["High/Low", "Close"], group = "High Low Index")
smoothLength = input.int(defval = 10, title = "Smoothing Length", minval = 1, group = "High Low Index")
// showRecordHighPercent = input.bool(defval = true, title = "Record High Percent", group = "High Low Index")
// showTable= input.bool(defval = true, title = "Show Table", inline = "table", group = "High Low Index")
// textsize = input.string(defval = size.tiny, title = " | Text Size", options = [size.tiny, size.small, size.normal], inline = "table", group = "High Low Index")
// showEma = input.bool(defval = true, title = "EMA", inline = "ema", group = "High Low Index")
emaLength = input.int(defval = 9, title = "EMA Length", minval = 1, group = "High Low Index")
symbol1 = input.symbol(defval = "AAPL", group = "Symbols")
symbol2 = input.symbol(defval = "MSFT", group = "Symbols")
symbol3 = input.symbol(defval = "AMZN", group = "Symbols")
symbol4 = input.symbol(defval = "GOOG", group = "Symbols")
symbol5 = input.symbol(defval = "FB", group = "Symbols")
symbol6 = input.symbol(defval = "TSLA", group = "Symbols")
symbol7 = input.symbol(defval = "NVDA", group = "Symbols")
symbol8 = input.symbol(defval = "BRK.B", group = "Symbols")
symbol9 = input.symbol(defval = "JPM", group = "Symbols")
symbol10 = input.symbol(defval = "UNH", group = "Symbols")
symbol11 = input.symbol(defval = "JNJ", group = "Symbols")
symbol12 = input.symbol(defval = "HD", group = "Symbols")
symbol13 = input.symbol(defval = "PG", group = "Symbols")
symbol14 = input.symbol(defval = "V", group = "Symbols")
symbol15 = input.symbol(defval = "PFE", group = "Symbols")
symbol16 = input.symbol(defval = "BAC", group = "Symbols")
symbol17 = input.symbol(defval = "MA", group = "Symbols")
symbol18 = input.symbol(defval = "ADBE", group = "Symbols")
symbol19 = input.symbol(defval = "DIS", group = "Symbols")
symbol20 = input.symbol(defval = "NFLX", group = "Symbols")
symbol21 = input.symbol(defval = "TMO", group = "Symbols")
symbol22 = input.symbol(defval = "XOM", group = "Symbols")
symbol23 = input.symbol(defval = "CRM", group = "Symbols")
symbol24 = input.symbol(defval = "CSCO", group = "Symbols")
symbol25 = input.symbol(defval = "COST", group = "Symbols")
symbol26 = input.symbol(defval = "ABT", group = "Symbols")
symbol27 = input.symbol(defval = "PEP", group = "Symbols")
symbol28 = input.symbol(defval = "ABBV", group = "Symbols")
symbol29 = input.symbol(defval = "KO", group = "Symbols")
symbol30 = input.symbol(defval = "PYPL", group = "Symbols")
symbol31 = input.symbol(defval = "CVX", group = "Symbols")
symbol32 = input.symbol(defval = "CMCSA", group = "Symbols")
symbol33 = input.symbol(defval = "LLY", group = "Symbols")
symbol34 = input.symbol(defval = "QCOM", group = "Symbols")
symbol35 = input.symbol(defval = "NKE", group = "Symbols")
symbol36 = input.symbol(defval = "VZ", group = "Symbols")
symbol37 = input.symbol(defval = "WMT", group = "Symbols")
symbol38 = input.symbol(defval = "INTC", group = "Symbols")
symbol39 = input.symbol(defval = "ACN", group = "Symbols")
symbol40 = input.symbol(defval = "AVGO", group = "Symbols")
HighsLows = array.new_int(40, 0)
getHighLow(length)=>
highest_ = ta.highest(length)[1]
lowest_ = ta.lowest(length)[1]
int ret = 0
if na(highest_)
ret := 2
else
bool h_ = ((source == "High/Low" ? high : close) > highest_)
bool l_ = ((source == "High/Low" ? low : close) < lowest_)
ret := h_ ? 1 : l_ ? -1 : 0
ret
getHLindexForTheSymbol(symbol, timeFrame, length, index)=>
highlow = request.security(symbol, timeFrame, getHighLow(length))
array.set(HighsLows, index, na(highlow) ? 2 : highlow)
getHLindexForTheSymbol(symbol1, timeFrame, length, 0)
getHLindexForTheSymbol(symbol2, timeFrame, length, 1)
getHLindexForTheSymbol(symbol3, timeFrame, length, 2)
getHLindexForTheSymbol(symbol4, timeFrame, length, 3)
getHLindexForTheSymbol(symbol5, timeFrame, length, 4)
getHLindexForTheSymbol(symbol6, timeFrame, length, 5)
getHLindexForTheSymbol(symbol7, timeFrame, length, 6)
getHLindexForTheSymbol(symbol8, timeFrame, length, 7)
getHLindexForTheSymbol(symbol9, timeFrame, length, 8)
getHLindexForTheSymbol(symbol10, timeFrame, length, 9)
getHLindexForTheSymbol(symbol11, timeFrame, length, 10)
getHLindexForTheSymbol(symbol12, timeFrame, length, 11)
getHLindexForTheSymbol(symbol13, timeFrame, length, 12)
getHLindexForTheSymbol(symbol14, timeFrame, length, 13)
getHLindexForTheSymbol(symbol15, timeFrame, length, 14)
getHLindexForTheSymbol(symbol16, timeFrame, length, 15)
getHLindexForTheSymbol(symbol17, timeFrame, length, 16)
getHLindexForTheSymbol(symbol18, timeFrame, length, 17)
getHLindexForTheSymbol(symbol19, timeFrame, length, 18)
getHLindexForTheSymbol(symbol20, timeFrame, length, 19)
getHLindexForTheSymbol(symbol21, timeFrame, length, 20)
getHLindexForTheSymbol(symbol22, timeFrame, length, 21)
getHLindexForTheSymbol(symbol23, timeFrame, length, 22)
getHLindexForTheSymbol(symbol24, timeFrame, length, 23)
getHLindexForTheSymbol(symbol25, timeFrame, length, 24)
getHLindexForTheSymbol(symbol26, timeFrame, length, 25)
getHLindexForTheSymbol(symbol27, timeFrame, length, 26)
getHLindexForTheSymbol(symbol28, timeFrame, length, 27)
getHLindexForTheSymbol(symbol29, timeFrame, length, 28)
getHLindexForTheSymbol(symbol30, timeFrame, length, 29)
getHLindexForTheSymbol(symbol31, timeFrame, length, 30)
getHLindexForTheSymbol(symbol32, timeFrame, length, 31)
getHLindexForTheSymbol(symbol33, timeFrame, length, 32)
getHLindexForTheSymbol(symbol34, timeFrame, length, 33)
getHLindexForTheSymbol(symbol35, timeFrame, length, 34)
getHLindexForTheSymbol(symbol36, timeFrame, length, 35)
getHLindexForTheSymbol(symbol37, timeFrame, length, 36)
getHLindexForTheSymbol(symbol38, timeFrame, length, 37)
getHLindexForTheSymbol(symbol39, timeFrame, length, 38)
getHLindexForTheSymbol(symbol40, timeFrame, length, 39)
highs = 0
total = 0
for x = 0 to 39
highs += (array.get(HighsLows, x) == 1 ? 1 : 0)
total += (array.get(HighsLows, x) == 1 or array.get(HighsLows, x) == -1 ? 1 : 0)
// calculate & show Record High Percent / High Low Index / EMA
var float RecordHighPercent = 50
RecordHighPercent := total == 0 ? RecordHighPercent : 100 * highs / total
HighLowIndex = ta.sma(RecordHighPercent, smoothLength)
// hline0 = hline(0, linestyle = hline.style_dotted)
// hline50 = hline(50, linestyle = hline.style_dotted)
// hline100 = hline(100, linestyle = hline.style_dotted)
// fill(hline0, hline50, color = color.rgb(255, 0, 0, 75))
// fill(hline50, hline100, color = color.rgb(0, 255, 0, 75))
// plot(showRecordHighPercent ? RecordHighPercent : na, color = showRecordHighPercent ? #9598a1 : na)
// plot(showEma ? ta.ema(HighLowIndex, emaLength) : na, color = showEma ? color.red : na, title = "EMA line")
// plot(HighLowIndex, color = color.blue, linewidth = 2, title = "High Low Index Line")
HLIma = ta.ema(HighLowIndex, emaLength)
peak = HighLowIndex[2] <= HighLowIndex[1] and HighLowIndex < HighLowIndex[1]
dip = HighLowIndex[2] >= HighLowIndex[1] and HighLowIndex > HighLowIndex[1]
HL_bull = HighLowIndex > HighLowIndex[1]
HL_bear = HighLowIndex < HighLowIndex[1]
HLma_bull = ta.crossover(HLIma, 50) and HL_bull
HLma_bear = ta.crossunder(HLIma,50) and HL_bear
// plot(HL_bull?1:0, "HL Bull")
// plot(HL_bear?1:0, "HL Bear")
HL_cross = ta.cross(HighLowIndex,HLIma)
// ***************************************************************************************************************************************** SL & PT ***********************************
RR = input.float(2.0, minval = 1, step = 0.1, title="Reward to Risk Ratio", group = "Trading Options")
SL_offset = input.int(15, minval=-100, maxval = 100, title ="% Stop loss reduction(+ve)/increase(-ve)", group = "Trading Options")
barsSinceLastEntry()=>
strategy.opentrades > 0 ? (bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades-1)) : na
// plot(barsSinceLastEntry(),"BSLE")
inLong = false
inShort = false
last_high = high[1]
last_low = low[1]
long_SL = last_low - datrp
short_SL = last_high + datrp
long_PT = last_high + math.abs(high[1]-low[1])
short_PT = last_low - math.abs(high[1]-low[1])
long_CT_PT = long_PT
short_CT_PT = short_PT
last_entry = strategy.opentrades.entry_price(strategy.opentrades-1)
L_risk = last_entry - long_SL
S_risk = short_SL - last_entry
if strategy.opentrades > 0 and not(trailing_stop)
long_SL := math.min(long_SL[barsSinceLastEntry()], last_low)
short_SL := math.max(short_SL[barsSinceLastEntry()], last_high)
L_risk := last_entry - long_SL
S_risk := short_SL - last_entry
long_PT := last_entry + (last_entry - long_SL) * RR
short_PT := last_entry - (short_SL - last_entry) * RR
long_CT_PT := last_entry + (last_entry - long_SL) * (RR/3)
short_CT_PT := last_entry - (short_SL - last_entry) * (RR/3)
long_SL := long_SL + (L_risk * SL_offset * 0.01)
short_SL := short_SL - (S_risk * SL_offset * 0.01)
if strategy.opentrades.size(0) > 0 and barsSinceLastEntry() > 0
inLong := true
else if strategy.opentrades.size(0) < 0 and barsSinceLastEntry() > 0
inShort := true
else
long_PT := last_high + math.abs(high-long_SL)
short_PT := last_low - math.abs(short_SL-low)
// **************************************************************************************************************************************** Trade Pauses ****************************************
bool trade_pause = false
bool trade_pause2 = false
no_longat10 = input.bool(true, title="No entry between 10:05 - 10:20 (Statistically bad trades)", group = "Trading Options")
// if math.abs(close - open) > atr
// trade_pause := true
// else
// trade_pause := false
if no_longat10 and time(timeframe.period, "1000-1030:23456")
trade_pause2 := true
else
trade_pause2 := false
// ************************************************************************************************************************************ Entry conditions **************************
L_entry1 = macd_bull and HL_bull and LR_trending and up_accel and HighLowIndex < 96
S_entry1 = macd_bear and HL_bear and LR_trending and down_accel and HighLowIndex > 4
// ************************************************************************************************************************************** Exit Conditions ********************************
exit0 = true
L_exit1 = (HighLowIndex[1] > 99 and HighLowIndex < 99)
S_exit1 = (HighLowIndex[1] < 1 and HighLowIndex > 1)
L_exit2 = S_entry1
S_exit2 = L_entry1
// ************************************************************************************************************************************ Entry and Exit orders *****************************
option_multiplier = input.float(0.007, title="Multiplier for trading options (adjust to approx. options P&L)", step=0.001, group = "Trading Options")
profit = strategy.netprofit
trade_amount = math.floor(strategy.initial_capital / close)
if isSPY
if strategy.netprofit > 0 and reinvest and strategy.closedtrades.profit(strategy.closedtrades-1) > 0
trade_amount := math.floor(strategy.initial_capital * option_multiplier) * (SPY_option + math.floor((profit/strategy.initial_capital)*10))
else
trade_amount := math.floor(strategy.initial_capital * option_multiplier) * SPY_option
if not(trade_pause) and not(trade_pause2) and strategy.opentrades == 0
strategy.entry("Long", strategy.long, trade_amount, when = L_entry1 and window, comment="Long")
strategy.entry("Short", strategy.short, trade_amount, when = S_entry1 and window, comment = "Short")
if not(trade_trailing) and window
strategy.exit("Exit", "Long", stop= long_SL, limit = long_PT, comment = "Exit Long SL/PT hit")
strategy.exit("Exit", "Short", stop= short_SL, limit = short_PT, comment = "Exit Short SL/PT hit")
if strategy.opentrades.profit(strategy.opentrades-1) > 0 and trade_earlyExit
strategy.close("Long", when = L_exit1 or L_exit2, comment = "Exit - Take profit")
strategy.close("Short", when = S_exit1 or S_exit2, comment = "Exit - Take profit")
// *************** Trailing SL *******************************************
if trade_trailing and (high > long_PT or TS[1] == 1) and window2
long_SL := math.max(long_SL[1], low - datrp)
trailing_stop := true
strategy.exit("Exit", "Long", when = exit0 and window2, stop= long_SL, comment = "Exit Long Trailing SL")
if trade_trailing and not(trailing_stop) and window
strategy.exit("Exit", "Long", stop= long_SL, comment = "Exit Long SL/PT hit")
if trade_trailing and (low < short_PT or TS[1] == 1) and window2
short_SL := math.min(short_SL[1], high + datrp)
trailing_stop := true
strategy.exit("Exit", "Short", when= exit0 and window2, stop= short_SL, comment = "Exit Short Trailing SL")
if trade_trailing and not(trailing_stop) and window
strategy.exit("Exit", "Short", stop= short_SL, comment = "Exit Short SL/PT hit")
if trade_expiry
if time(timeframe.period, "1550-1555:246")
strategy.close_all()
if time(timeframe.period, "1550-1555:35")
strategy.close("Long", qty_percent = 50, comment="Close 1/2 EOD")
strategy.close("Short", qty_percent = 50, comment="Close 1/2 EOD")
strategy.cancel_all(when=time(timeframe.period, "1555-1600:23456"))
// plot(trailing_stop? 1:0, "Trailing stop ON")
if strategy.opentrades == 0
trailing_stop := false
TS := trailing_stop? 1:0
SSL = plot(short_SL,title = "Short SL", color= inShort ? color.red: color.new(color.red,100), linewidth = 3)
LSL = plot(long_SL,title = "Long SL", color= inLong ? color.red: color.new(color.red,100), linewidth = 3)
LPT = plot(long_PT,title = "Long PT", color= inLong ? color.green: color.new(color.green,100), linewidth = 3)
SPT = plot(short_PT,title = "Short PT", color= inShort ? color.green: color.new(color.green,100), linewidth = 3)
LE = plot(last_entry, title = "Last entry", color = strategy.opentrades > 0 ? color.gray : color.new(color.gray,100))
// plot(L_risk, title = "Risk Long")
// plot(S_risk, title = "Risk Short")
fill(LPT, LE, color = strategy.opentrades.size(0) > 0 ? color.new(color.green,90) : na)
fill(LE, LSL, color = strategy.opentrades.size(0) > 0 ? color.new(color.red,90): na)
fill(SPT, LE, color = strategy.opentrades.size(0) < 0 ? color.new(color.green,90) : na)
fill(LE, SSL, color = strategy.opentrades.size(0) < 0 ? color.new(color.red,90) : na)
|
Rainbow Oscillator [Strategy] | https://www.tradingview.com/script/d41r2H25-Rainbow-Oscillator-Strategy/ | businessduck | https://www.tradingview.com/u/businessduck/ | 92 | 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/
// © businessduck
//@version=5
strategy("Rainbow Oscillator [Strategy]", overlay=false, margin_long=100, margin_short=100, initial_capital = 2000)
bool trendFilter = input.bool(true, 'Use trend filter')
float w1 = input.float(0.33, 'RSI Weight', 0, 1, 0.01)
float w2 = input.float(0.33, 'CCI Weight', 0, 1, 0.01)
float w3 = input.float(0.33, 'Stoch Weight', 0, 1, 0.01)
int fastPeriod = input.int(16, 'Ocillograph Fast Period', 4, 60, 1)
int slowPeriod = input.int(22, 'Ocillograph Slow Period', 4, 60, 1)
int oscillographSamplePeriod = input.int(8, 'Oscillograph Samples Period', 1, 30, 1)
int oscillographSamplesCount = input.int(2, 'Oscillograph Samples Count', 0, 4, 1)
string oscillographMAType = input.string("RMA", "Oscillograph Samples Type", options = ["EMA", "SMA", "RMA", "WMA"])
int levelPeriod = input.int(26, 'Level Period', 2, 100)
int levelOffset = input.int(0, 'Level Offset', 0, 200, 10)
float redunant = input.float(0.5, 'Level Redunant', 0, 1, 0.01)
int levelSampleCount = input.int(2, 'Level Smooth Samples', 0, 4, 1)
string levelType = input.string("RMA", "Level MA type", options = ["EMA", "SMA", "RMA", "WMA"])
perc(current, prev) => ((current - prev) / prev) * 100
smooth(value, type, period) =>
float ma = switch type
"EMA" => ta.ema(value, period)
"SMA" => ta.sma(value, period)
"RMA" => ta.rma(value, period)
"WMA" => ta.wma(value, period)
=>
runtime.error("No matching MA type found.")
float(na)
getSample(value, samples, type, period) =>
float ma = switch samples
0 => value
1 => smooth(value, type, period)
2 => smooth(smooth(value, type, period), type, period)
3 => smooth(smooth(smooth(value, type, period), type, period), type, period)
4 => smooth(smooth(smooth(smooth(value, type, period), type, period), type, period), type, period)
float takeProfit = input.float(5, "% Take profit", 0.8, 100, step = 0.1) / 100
float stopLoss = input.float(2, "% Stop Loss", 0.8, 100, step = 0.1) / 100
float magicFast = w2 * ta.cci(close, fastPeriod) + w1 * (ta.rsi(close, fastPeriod) - 50) + w3 * (ta.stoch(close, high, low, fastPeriod) - 50)
float magicSlow = w2 * ta.cci(close, slowPeriod) + w1 * (ta.rsi(close, slowPeriod) - 50) + w3 * (ta.stoch(close, high, low, slowPeriod) - 50)
float sampledMagicFast = getSample(magicFast, oscillographSamplesCount, oscillographMAType, oscillographSamplePeriod)
float sampledMagicSlow = getSample(magicSlow, oscillographSamplesCount, oscillographMAType, oscillographSamplePeriod)
float lastUpperValue = 0
float lastLowerValue = 0
if (magicFast > 0)
lastUpperValue := math.max(magicFast, magicFast[1])
else
lastUpperValue := math.max(0, lastUpperValue[1]) * redunant
if (magicFast <= 0)
lastLowerValue := math.min(magicFast, magicFast[1])
else
lastLowerValue := math.min(0, lastLowerValue[1]) * redunant
float level1up = getSample( (magicFast >= 0 ? magicFast : lastUpperValue) / 4, levelSampleCount, levelType, levelPeriod) + levelOffset
float level2up = getSample( (magicFast >= 0 ? magicFast : lastUpperValue) / 2, levelSampleCount, levelType, levelPeriod) + levelOffset
float level3up = getSample( magicFast >= 0 ? magicFast : lastUpperValue, levelSampleCount, levelType, levelPeriod) + levelOffset
float level4up = getSample( (magicFast >= 0 ? magicFast : lastUpperValue) * 2, levelSampleCount, levelType, levelPeriod) + levelOffset
float level1low = getSample( (magicFast <= 0 ? magicFast : lastLowerValue) / 4, levelSampleCount, levelType, levelPeriod) - levelOffset
float level2low = getSample( (magicFast <= 0 ? magicFast : lastLowerValue) / 2, levelSampleCount, levelType, levelPeriod) - levelOffset
float level3low = getSample( magicFast <= 0 ? magicFast : lastLowerValue, levelSampleCount, levelType, levelPeriod) - levelOffset
float level4low = getSample( (magicFast <= 0 ? magicFast : lastLowerValue) * 2, levelSampleCount, levelType, levelPeriod) - levelOffset
var transparent = color.new(color.white, 100)
var overbough4Color = color.new(color.red, 75)
var overbough3Color = color.new(color.orange, 75)
var overbough2Color = color.new(color.yellow, 75)
var oversold4Color = color.new(color.teal, 75)
var oversold3Color = color.new(color.blue, 75)
var oversold2Color = color.new(color.aqua, 85)
upperPlotId1 = plot(level1up, 'Upper1', transparent)
upperPlotId2 = plot(level2up, 'Upper2', transparent)
upperPlotId3 = plot(level3up, 'Upper3', transparent)
upperPlotId4 = plot(level4up, 'Upper4', transparent)
fastColor = color.new(color.teal, 60)
slowColor = color.new(color.red, 60)
fastPlotId = plot(sampledMagicFast, 'fast', color = fastColor)
slowPlotId = plot(sampledMagicSlow, 'slow', color = slowColor)
lowerPlotId1 = plot(level1low, 'Lower1', transparent)
lowerPlotId2 = plot(level2low, 'Lower2', transparent)
lowerPlotId3 = plot(level3low, 'Lower3', transparent)
lowerPlotId4 = plot(level4low, 'Lower4', transparent)
fill(upperPlotId4, upperPlotId3, overbough4Color)
fill(upperPlotId3, upperPlotId2, overbough3Color)
fill(upperPlotId2, upperPlotId1, overbough2Color)
fill(lowerPlotId4, lowerPlotId3, oversold4Color)
fill(lowerPlotId3, lowerPlotId2, oversold3Color)
fill(lowerPlotId2, lowerPlotId1, oversold2Color)
upTrend = sampledMagicFast > sampledMagicFast[1]
buySignal = ((upTrend or not trendFilter) and ta.crossunder(sampledMagicSlow, sampledMagicFast)) ? sampledMagicSlow : na
sellSignal = ((not upTrend or not trendFilter) and ta.crossover(sampledMagicSlow, sampledMagicFast)) ? sampledMagicSlow : na
diff = sampledMagicSlow - sampledMagicFast
fill(fastPlotId, slowPlotId, upTrend ? fastColor : slowColor)
plot(buySignal, color = color.aqua, style = plot.style_circles, linewidth = 4)
plot(sellSignal, color = color.red, style = plot.style_circles, linewidth = 4)
// longCondition = upTrend != upTrend[1] and upTrend
long_take_level = strategy.position_avg_price * (1 + takeProfit)
long_stop_level = strategy.position_avg_price * (1 - stopLoss)
short_take_level = strategy.position_avg_price * (1 - takeProfit)
short_stop_level = strategy.position_avg_price * (1 + stopLoss)
strategy.close(id="Long", when=sellSignal, comment = "Exit")
strategy.close(id="Short", when=buySignal, comment = "Exit")
strategy.entry("Long", strategy.long, when=buySignal)
strategy.entry("Short", strategy.short, when=sellSignal)
strategy.exit("Take Profit/ Stop Loss","Long", stop=long_stop_level, limit=long_take_level)
strategy.exit("Take Profit/ Stop Loss","Short", stop=short_stop_level, limit=short_take_level)
// plot(long_stop_level, color=color.red, overlay=true)
// plot(long_take_level, color=color.green)
|
VuManChu Cipher B + Divergences Strategy | https://www.tradingview.com/script/T85iFvQj-VuManChu-Cipher-B-Divergences-Strategy/ | nattichai001 | https://www.tradingview.com/u/nattichai001/ | 466 | 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/
// © vumanchu
//@version=4
// Thanks to dynausmaux for the code
// Thanks to falconCoin for https://www.tradingview.com/script/KVfgBvDd-Market-Cipher-B-Free-version-with-Buy-and-sell/ inspired me to start this.
// Thanks to LazyBear for WaveTrend Oscillator https://www.tradingview.com/script/2KE8wTuF-Indicator-WaveTrend-Oscillator-WT/
// Thanks to RicardoSantos for https://www.tradingview.com/script/3oeDh0Yq-RS-Price-Divergence-Detector-V2/
// Thanks to LucemAnb for Plain Stochastic Divergence https://www.tradingview.com/script/FCUgF8ag-Plain-Stochastic-Divergence/
// Thanks to andreholanda73 for MFI+RSI Area https://www.tradingview.com/script/UlGZzUAr/
// I especially want to thank TradingView for its platform that facilitates development and learning.
//
// CIRCLES & TRIANGLES:
// - LITTLE CIRCLE: They appear at all WaveTrend wave crossings.
// - GREEN CIRCLE: The wavetrend waves are at the oversold level and have crossed up (bullish).
// - RED CIRCLE: The wavetrend waves are at the overbought level and have crossed down (bearish).
// - GOLD/ORANGE CIRCLE: When RSI is below 20, WaveTrend waves are below or equal to -80 and have crossed up after good bullish divergence (DONT BUY WHEN GOLD CIRCLE APPEAR).
// - None of these circles are certain signs to trade. It is only information that can help you.
// - PURPLE TRIANGLE: Appear when a bullish or bearish divergence is formed and WaveTrend waves crosses at overbought and oversold points.
//
// NOTES:
// - I am not an expert trader or know how to program pine script as such, in fact it is my first indicator only to study and all the code is copied and modified from other codes that are published in TradingView.
// - I am very grateful to the entire TV community that publishes codes so that other newbies like me can learn and present their results. This is an attempt to imitate Market Cipher B.
// - Settings by default are for 4h timeframe, divergences are more stronger and accurate. Haven't tested in all timeframes, only 2h and 4h.
// - If you get an interesting result in other timeframes I would be very grateful if you would comment your configuration to implement it or at least check it.
//
// CONTRIBUTIONS:
// - Tip/Idea: Add higher timeframe analysis for bearish/bullish patterns at the current timeframe.
// + Bearish/Bullish FLAG:
// - MFI+RSI Area are RED (Below 0).
// - Wavetrend waves are above 0 and crosses down.
// - VWAP Area are below 0 on higher timeframe.
// - This pattern reversed becomes bullish.
// - Tip/Idea: Check the last heikinashi candle from 2 higher timeframe
// + Bearish/Bullish DIAMOND:
// - HT Candle is red
// - WT > 0 and crossed down
// study(title = 'VuManChu B Divergences', shorttitle = 'VMC Cipher_B_Divergences')
// PARAMETERS {
// WaveTrend
wtShow = input(true, title = 'Show WaveTrend', type = input.bool)
wtBuyShow = input(true, title = 'Show Buy dots', type = input.bool)
wtGoldShow = input(true, title = 'Show Gold dots', type = input.bool)
wtSellShow = input(true, title = 'Show Sell dots', type = input.bool)
wtDivShow = input(true, title = 'Show Div. dots', type = input.bool)
vwapShow = input(true, title = 'Show Fast WT', type = input.bool)
wtChannelLen = input(9, title = 'WT Channel Length', type = input.integer)
wtAverageLen = input(12, title = 'WT Average Length', type = input.integer)
wtMASource = input(hlc3, title = 'WT MA Source', type = input.source)
wtMALen = input(3, title = 'WT MA Length', type = input.integer)
// WaveTrend Overbought & Oversold lines
obLevel = input(53, title = 'WT Overbought Level 1', type = input.integer)
obLevel2 = input(60, title = 'WT Overbought Level 2', type = input.integer)
obLevel3 = input(100, title = 'WT Overbought Level 3', type = input.integer)
osLevel = input(-53, title = 'WT Oversold Level 1', type = input.integer)
osLevel2 = input(-60, title = 'WT Oversold Level 2', type = input.integer)
osLevel3 = input(-75, title = 'WT Oversold Level 3', type = input.integer)
// Divergence WT
wtShowDiv = input(true, title = 'Show WT Regular Divergences', type = input.bool)
wtShowHiddenDiv = input(false, title = 'Show WT Hidden Divergences', type = input.bool)
showHiddenDiv_nl = input(true, title = 'Not apply OB/OS Limits on Hidden Divergences', type = input.bool)
wtDivOBLevel = input(45, title = 'WT Bearish Divergence min', type = input.integer)
wtDivOSLevel = input(-65, title = 'WT Bullish Divergence min', type = input.integer)
// Divergence extra range
wtDivOBLevel_addshow = input(true, title = 'Show 2nd WT Regular Divergences', type = input.bool)
wtDivOBLevel_add = input(15, title = 'WT 2nd Bearish Divergence', type = input.integer)
wtDivOSLevel_add = input(-40, title = 'WT 2nd Bullish Divergence 15 min', type = input.integer)
// RSI+MFI
rsiMFIShow = input(true, title = 'Show MFI', type = input.bool)
rsiMFIperiod = input(60,title = 'MFI Period', type = input.integer)
rsiMFIMultiplier = input(150, title = 'MFI Area multiplier', type = input.float)
rsiMFIPosY = input(2.5, title = 'MFI Area Y Pos', type = input.float)
// RSI
rsiShow = input(false, title = 'Show RSI', type = input.bool)
rsiSRC = input(close, title = 'RSI Source', type = input.source)
rsiLen = input(14, title = 'RSI Length', type = input.integer)
rsiOversold = input(30, title = 'RSI Oversold', minval = 50, maxval = 100, type = input.integer)
rsiOverbought = input(60, title = 'RSI Overbought', minval = 0, maxval = 50, type = input.integer)
// Divergence RSI
rsiShowDiv = input(false, title = 'Show RSI Regular Divergences', type = input.bool)
rsiShowHiddenDiv = input(false, title = 'Show RSI Hidden Divergences', type = input.bool)
rsiDivOBLevel = input(60, title = 'RSI Bearish Divergence min', type = input.integer)
rsiDivOSLevel = input(30, title = 'RSI Bullish Divergence min', type = input.integer)
// RSI Stochastic
stochShow = input(true, title = 'Show Stochastic RSI', type = input.bool)
stochUseLog = input(true, title=' Use Log?', type = input.bool)
stochAvg = input(false, title='Use Average of both K & D', type = input.bool)
stochSRC = input(close, title = 'Stochastic RSI Source', type = input.source)
stochLen = input(14, title = 'Stochastic RSI Length', type = input.integer)
stochRsiLen = input(14, title = 'RSI Length ', type = input.integer)
stochKSmooth = input(3, title = 'Stochastic RSI K Smooth', type = input.integer)
stochDSmooth = input(3, title = 'Stochastic RSI D Smooth', type = input.integer)
// Divergence stoch
stochShowDiv = input(false, title = 'Show Stoch Regular Divergences', type = input.bool)
stochShowHiddenDiv = input(false, title = 'Show Stoch Hidden Divergences', type = input.bool)
// Schaff Trend Cycle
tcLine = input(false, title="Show Schaff TC line", type=input.bool)
tcSRC = input(close, title = 'Schaff TC Source', type = input.source)
tclength = input(10, title="Schaff TC", type=input.integer)
tcfastLength = input(23, title="Schaff TC Fast Lenght", type=input.integer)
tcslowLength = input(50, title="Schaff TC Slow Length", type=input.integer)
tcfactor = input(0.5, title="Schaff TC Factor", type=input.float)
// Sommi Flag
sommiFlagShow = input(false, title = 'Show Sommi flag', type = input.bool)
sommiShowVwap = input(false, title = 'Show Sommi F. Wave', type = input.bool)
sommiVwapTF = input('720', title = 'Sommi F. Wave timeframe', type = input.string)
sommiVwapBearLevel = input(0, title = 'F. Wave Bear Level (less than)', type = input.integer)
sommiVwapBullLevel = input(0, title = 'F. Wave Bull Level (more than)', type = input.integer)
soomiFlagWTBearLevel = input(0, title = 'WT Bear Level (more than)', type = input.integer)
soomiFlagWTBullLevel = input(0, title = 'WT Bull Level (less than)', type = input.integer)
soomiRSIMFIBearLevel = input(0, title = 'Money flow Bear Level (less than)', type = input.integer)
soomiRSIMFIBullLevel = input(0, title = 'Money flow Bull Level (more than)', type = input.integer)
// Sommi Diamond
sommiDiamondShow = input(false, title = 'Show Sommi diamond', type = input.bool)
sommiHTCRes = input('60', title = 'HTF Candle Res. 1', type = input.string)
sommiHTCRes2 = input('240', title = 'HTF Candle Res. 2', type = input.string)
soomiDiamondWTBearLevel = input(0, title = 'WT Bear Level (More than)', type = input.integer)
soomiDiamondWTBullLevel = input(0, title = 'WT Bull Level (Less than)', type = input.integer)
// macd Colors
macdWTColorsShow = input(false, title = 'Show MACD Colors', type = input.bool)
macdWTColorsTF = input('240', title = 'MACD Colors MACD TF', type = input.string)
darkMode = input(false, title = 'Dark mode', type = input.bool)
// Colors
colorRed = #ff0000
colorPurple = #e600e6
colorGreen = #3fff00
colorOrange = #e2a400
colorYellow = #ffe500
colorWhite = #ffffff
colorPink = #ff00f0
colorBluelight = #31c0ff
colorWT1 = #90caf9
colorWT2 = #0d47a1
colorWT2_ = #131722
colormacdWT1a = #4caf58
colormacdWT1b = #af4c4c
colormacdWT1c = #7ee57e
colormacdWT1d = #ff3535
colormacdWT2a = #305630
colormacdWT2b = #310101
colormacdWT2c = #132213
colormacdWT2d = #770000
// } PARAMETERS
// FUNCTIONS {
// Divergences
f_top_fractal(src) => src[4] < src[2] and src[3] < src[2] and src[2] > src[1] and src[2] > src[0]
f_bot_fractal(src) => src[4] > src[2] and src[3] > src[2] and src[2] < src[1] and src[2] < src[0]
f_fractalize(src) => f_top_fractal(src) ? 1 : f_bot_fractal(src) ? -1 : 0
f_findDivs(src, topLimit, botLimit, useLimits) =>
fractalTop = f_fractalize(src) > 0 and (useLimits ? src[2] >= topLimit : true) ? src[2] : na
fractalBot = f_fractalize(src) < 0 and (useLimits ? src[2] <= botLimit : true) ? src[2] : na
highPrev = valuewhen(fractalTop, src[2], 0)[2]
highPrice = valuewhen(fractalTop, high[2], 0)[2]
lowPrev = valuewhen(fractalBot, src[2], 0)[2]
lowPrice = valuewhen(fractalBot, low[2], 0)[2]
bearSignal = fractalTop and high[2] > highPrice and src[2] < highPrev
bullSignal = fractalBot and low[2] < lowPrice and src[2] > lowPrev
bearDivHidden = fractalTop and high[2] < highPrice and src[2] > highPrev
bullDivHidden = fractalBot and low[2] > lowPrice and src[2] < lowPrev
[fractalTop, fractalBot, lowPrev, bearSignal, bullSignal, bearDivHidden, bullDivHidden]
// RSI+MFI
f_rsimfi(_period, _multiplier, _tf) => security(syminfo.tickerid, _tf, sma(((close - open) / (high - low)) * _multiplier, _period) - rsiMFIPosY)
// WaveTrend
f_wavetrend(src, chlen, avg, malen, tf) =>
tfsrc = security(syminfo.tickerid, tf, src)
esa = ema(tfsrc, chlen)
de = ema(abs(tfsrc - esa), chlen)
ci = (tfsrc - esa) / (0.015 * de)
wt1 = security(syminfo.tickerid, tf, ema(ci, avg))
wt2 = security(syminfo.tickerid, tf, sma(wt1, malen))
wtVwap = wt1 - wt2
wtOversold = wt2 <= osLevel
wtOverbought = wt2 >= obLevel
wtCross = cross(wt1, wt2)
wtCrossUp = wt2 - wt1 <= 0
wtCrossDown = wt2 - wt1 >= 0
wtCrosslast = cross(wt1[2], wt2[2])
wtCrossUplast = wt2[2] - wt1[2] <= 0
wtCrossDownlast = wt2[2] - wt1[2] >= 0
[wt1, wt2, wtOversold, wtOverbought, wtCross, wtCrossUp, wtCrossDown, wtCrosslast, wtCrossUplast, wtCrossDownlast, wtVwap]
// Schaff Trend Cycle
f_tc(src, length, fastLength, slowLength) =>
ema1 = ema(src, fastLength)
ema2 = ema(src, slowLength)
macdVal = ema1 - ema2
alpha = lowest(macdVal, length)
beta = highest(macdVal, length) - alpha
gamma = (macdVal - alpha) / beta * 100
gamma := beta > 0 ? gamma : nz(gamma[1])
delta = gamma
delta := na(delta[1]) ? delta : delta[1] + tcfactor * (gamma - delta[1])
epsilon = lowest(delta, length)
zeta = highest(delta, length) - epsilon
eta = (delta - epsilon) / zeta * 100
eta := zeta > 0 ? eta : nz(eta[1])
stcReturn = eta
stcReturn := na(stcReturn[1]) ? stcReturn : stcReturn[1] + tcfactor * (eta - stcReturn[1])
stcReturn
// Stochastic RSI
f_stochrsi(_src, _stochlen, _rsilen, _smoothk, _smoothd, _log, _avg) =>
src = _log ? log(_src) : _src
rsi = rsi(src, _rsilen)
kk = sma(stoch(rsi, rsi, rsi, _stochlen), _smoothk)
d1 = sma(kk, _smoothd)
avg_1 = avg(kk, d1)
k = _avg ? avg_1 : kk
[k, d1]
// MACD
f_macd(src, fastlen, slowlen, sigsmooth, tf) =>
fast_ma = security(syminfo.tickerid, tf, ema(src, fastlen))
slow_ma = security(syminfo.tickerid, tf, ema(src, slowlen))
macd = fast_ma - slow_ma,
signal = security(syminfo.tickerid, tf, sma(macd, sigsmooth))
hist = macd - signal
[macd, signal, hist]
// MACD Colors on WT
f_macdWTColors(tf) =>
hrsimfi = f_rsimfi(rsiMFIperiod, rsiMFIMultiplier, tf)
[macd, signal, hist] = f_macd(close, 28, 42, 9, macdWTColorsTF)
macdup = macd >= signal
macddown = macd <= signal
macdWT1Color = macdup ? hrsimfi > 0 ? colormacdWT1c : colormacdWT1a : macddown ? hrsimfi < 0 ? colormacdWT1d : colormacdWT1b : na
macdWT2Color = macdup ? hrsimfi < 0 ? colormacdWT2c : colormacdWT2a : macddown ? hrsimfi < 0 ? colormacdWT2d : colormacdWT2b : na
[macdWT1Color, macdWT2Color]
// Get higher timeframe candle
f_getTFCandle(_tf) =>
_open = security(heikinashi(syminfo.tickerid), _tf, open, barmerge.gaps_off, barmerge.lookahead_on)
_close = security(heikinashi(syminfo.tickerid), _tf, close, barmerge.gaps_off, barmerge.lookahead_on)
_high = security(heikinashi(syminfo.tickerid), _tf, high, barmerge.gaps_off, barmerge.lookahead_on)
_low = security(heikinashi(syminfo.tickerid), _tf, low, barmerge.gaps_off, barmerge.lookahead_on)
hl2 = (_high + _low) / 2.0
newBar = change(_open)
candleBodyDir = _close > _open
[candleBodyDir, newBar]
// Sommi flag
f_findSommiFlag(tf, wt1, wt2, rsimfi, wtCross, wtCrossUp, wtCrossDown) =>
[hwt1, hwt2, hwtOversold, hwtOverbought, hwtCross, hwtCrossUp, hwtCrossDown, hwtCrosslast, hwtCrossUplast, hwtCrossDownlast, hwtVwap] = f_wavetrend(wtMASource, wtChannelLen, wtAverageLen, wtMALen, tf)
bearPattern = rsimfi < soomiRSIMFIBearLevel and
wt2 > soomiFlagWTBearLevel and
wtCross and
wtCrossDown and
hwtVwap < sommiVwapBearLevel
bullPattern = rsimfi > soomiRSIMFIBullLevel and
wt2 < soomiFlagWTBullLevel and
wtCross and
wtCrossUp and
hwtVwap > sommiVwapBullLevel
[bearPattern, bullPattern, hwtVwap]
f_findSommiDiamond(tf, tf2, wt1, wt2, wtCross, wtCrossUp, wtCrossDown) =>
[candleBodyDir, newBar] = f_getTFCandle(tf)
[candleBodyDir2, newBar2] = f_getTFCandle(tf2)
bearPattern = wt2 >= soomiDiamondWTBearLevel and
wtCross and
wtCrossDown and
not candleBodyDir and
not candleBodyDir2
bullPattern = wt2 <= soomiDiamondWTBullLevel and
wtCross and
wtCrossUp and
candleBodyDir and
candleBodyDir2
[bearPattern, bullPattern]
// } FUNCTIONS
// CALCULATE INDICATORS {
// RSI
rsi = rsi(rsiSRC, rsiLen)
rsiColor = rsi <= rsiOversold ? colorGreen : rsi >= rsiOverbought ? colorRed : colorPurple
// RSI + MFI Area
rsiMFI = f_rsimfi(rsiMFIperiod, rsiMFIMultiplier, timeframe.period)
rsiMFIColor = rsiMFI > 0 ? #3ee145 : #ff3d2e
// Calculates WaveTrend
[wt1, wt2, wtOversold, wtOverbought, wtCross, wtCrossUp, wtCrossDown, wtCross_last, wtCrossUp_last, wtCrossDown_last, wtVwap] = f_wavetrend(wtMASource, wtChannelLen, wtAverageLen, wtMALen, timeframe.period)
// Stochastic RSI
[stochK, stochD] = f_stochrsi(stochSRC, stochLen, stochRsiLen, stochKSmooth, stochDSmooth, stochUseLog, stochAvg)
// Schaff Trend Cycle
tcVal = f_tc(tcSRC, tclength, tcfastLength, tcslowLength)
// Sommi flag
[sommiBearish, sommiBullish, hvwap] = f_findSommiFlag(sommiVwapTF, wt1, wt2, rsiMFI, wtCross, wtCrossUp, wtCrossDown)
//Sommi diamond
[sommiBearishDiamond, sommiBullishDiamond] = f_findSommiDiamond(sommiHTCRes, sommiHTCRes2, wt1, wt2, wtCross, wtCrossUp, wtCrossDown)
// macd colors
[macdWT1Color, macdWT2Color] = f_macdWTColors(macdWTColorsTF)
// WT Divergences
[wtFractalTop, wtFractalBot, wtLow_prev, wtBearDiv, wtBullDiv, wtBearDivHidden, wtBullDivHidden] = f_findDivs(wt2, wtDivOBLevel, wtDivOSLevel, true)
[wtFractalTop_add, wtFractalBot_add, wtLow_prev_add, wtBearDiv_add, wtBullDiv_add, wtBearDivHidden_add, wtBullDivHidden_add] = f_findDivs(wt2, wtDivOBLevel_add, wtDivOSLevel_add, true)
[wtFractalTop_nl, wtFractalBot_nl, wtLow_prev_nl, wtBearDiv_nl, wtBullDiv_nl, wtBearDivHidden_nl, wtBullDivHidden_nl] = f_findDivs(wt2, 0, 0, false)
wtBearDivHidden_ = showHiddenDiv_nl ? wtBearDivHidden_nl : wtBearDivHidden
wtBullDivHidden_ = showHiddenDiv_nl ? wtBullDivHidden_nl : wtBullDivHidden
wtBearDivColor = (wtShowDiv and wtBearDiv) or (wtShowHiddenDiv and wtBearDivHidden_) ? colorRed : na
wtBullDivColor = (wtShowDiv and wtBullDiv) or (wtShowHiddenDiv and wtBullDivHidden_) ? colorGreen : na
wtBearDivColor_add = (wtShowDiv and (wtDivOBLevel_addshow and wtBearDiv_add)) or (wtShowHiddenDiv and (wtDivOBLevel_addshow and wtBearDivHidden_add)) ? #9a0202 : na
wtBullDivColor_add = (wtShowDiv and (wtDivOBLevel_addshow and wtBullDiv_add)) or (wtShowHiddenDiv and (wtDivOBLevel_addshow and wtBullDivHidden_add)) ? #1b5e20 : na
// RSI Divergences
[rsiFractalTop, rsiFractalBot, rsiLow_prev, rsiBearDiv, rsiBullDiv, rsiBearDivHidden, rsiBullDivHidden] = f_findDivs(rsi, rsiDivOBLevel, rsiDivOSLevel, true)
[rsiFractalTop_nl, rsiFractalBot_nl, rsiLow_prev_nl, rsiBearDiv_nl, rsiBullDiv_nl, rsiBearDivHidden_nl, rsiBullDivHidden_nl] = f_findDivs(rsi, 0, 0, false)
rsiBearDivHidden_ = showHiddenDiv_nl ? rsiBearDivHidden_nl : rsiBearDivHidden
rsiBullDivHidden_ = showHiddenDiv_nl ? rsiBullDivHidden_nl : rsiBullDivHidden
rsiBearDivColor = (rsiShowDiv and rsiBearDiv) or (rsiShowHiddenDiv and rsiBearDivHidden_) ? colorRed : na
rsiBullDivColor = (rsiShowDiv and rsiBullDiv) or (rsiShowHiddenDiv and rsiBullDivHidden_) ? colorGreen : na
// Stoch Divergences
[stochFractalTop, stochFractalBot, stochLow_prev, stochBearDiv, stochBullDiv, stochBearDivHidden, stochBullDivHidden] = f_findDivs(stochK, 0, 0, false)
stochBearDivColor = (stochShowDiv and stochBearDiv) or (stochShowHiddenDiv and stochBearDivHidden) ? colorRed : na
stochBullDivColor = (stochShowDiv and stochBullDiv) or (stochShowHiddenDiv and stochBullDivHidden) ? colorGreen : na
// Small Circles WT Cross
signalColor = wt2 - wt1 > 0 ? color.red : color.lime
// Buy signal.
buySignal = wtCross and wtCrossUp and wtOversold
buySignalDiv = (wtShowDiv and wtBullDiv) or
(wtShowDiv and wtBullDiv_add) or
(stochShowDiv and stochBullDiv) or
(rsiShowDiv and rsiBullDiv)
buySignalDiv_color = wtBullDiv ? colorGreen :
wtBullDiv_add ? color.new(colorGreen, 60) :
rsiShowDiv ? colorGreen : na
// Sell signal
sellSignal = wtCross and wtCrossDown and wtOverbought
sellSignalDiv = (wtShowDiv and wtBearDiv) or
(wtShowDiv and wtBearDiv_add) or
(stochShowDiv and stochBearDiv) or
(rsiShowDiv and rsiBearDiv)
sellSignalDiv_color = wtBearDiv ? colorRed :
wtBearDiv_add ? color.new(colorRed, 60) :
rsiBearDiv ? colorRed : na
// Gold Buy
lastRsi = valuewhen(wtFractalBot, rsi[2], 0)[2]
wtGoldBuy = ((wtShowDiv and wtBullDiv) or (rsiShowDiv and rsiBullDiv)) and
wtLow_prev <= osLevel3 and
wt2 > osLevel3 and
wtLow_prev - wt2 <= -5 and
lastRsi < 30
// } CALCULATE INDICATORS
// DRAW {
bgcolor(darkMode ? color.new(#000000, 80) : na)
zLine = plot(0, color = color.new(colorWhite, 50))
// MFI BAR
rsiMfiBarTopLine = plot(rsiMFIShow ? -95 : na, title = 'MFI Bar TOP Line', transp = 100)
rsiMfiBarBottomLine = plot(rsiMFIShow ? -99 : na, title = 'MFI Bar BOTTOM Line', transp = 100)
fill(rsiMfiBarTopLine, rsiMfiBarBottomLine, title = 'MFI Bar Colors', color = rsiMFIColor, transp = 75)
// WT Areas
plot(wtShow ? wt1 : na, style = plot.style_area, title = 'WT Wave 1', color = macdWTColorsShow ? macdWT1Color : colorWT1, transp = 0)
plot(wtShow ? wt2 : na, style = plot.style_area, title = 'WT Wave 2', color = macdWTColorsShow ? macdWT2Color : darkMode ? colorWT2_ : colorWT2 , transp = 20)
// VWAP
plot(vwapShow ? wtVwap : na, title = 'VWAP', color = colorYellow, style = plot.style_area, linewidth = 2, transp = 45)
// MFI AREA
rsiMFIplot = plot(rsiMFIShow ? rsiMFI: na, title = 'RSI+MFI Area', color = rsiMFIColor, transp = 20)
fill(rsiMFIplot, zLine, rsiMFIColor, transp = 40)
// WT Div
plot(series = wtFractalTop ? wt2[2] : na, title = 'WT Bearish Divergence', color = wtBearDivColor, linewidth = 2, offset = -2)
plot(series = wtFractalBot ? wt2[2] : na, title = 'WT Bullish Divergence', color = wtBullDivColor, linewidth = 2, offset = -2)
// WT 2nd Div
plot(series = wtFractalTop_add ? wt2[2] : na, title = 'WT 2nd Bearish Divergence', color = wtBearDivColor_add, linewidth = 2, offset = -2)
plot(series = wtFractalBot_add ? wt2[2] : na, title = 'WT 2nd Bullish Divergence', color = wtBullDivColor_add, linewidth = 2, offset = -2)
// RSI
plot(rsiShow ? rsi : na, title = 'RSI', color = rsiColor, linewidth = 2, transp = 25)
// RSI Div
plot(series = rsiFractalTop ? rsi[2] : na, title='RSI Bearish Divergence', color = rsiBearDivColor, linewidth = 1, offset = -2)
plot(series = rsiFractalBot ? rsi[2] : na, title='RSI Bullish Divergence', color = rsiBullDivColor, linewidth = 1, offset = -2)
// Stochastic RSI
stochKplot = plot(stochShow ? stochK : na, title = 'Stoch K', color = color.new(#21baf3, 0), linewidth = 2)
stochDplot = plot(stochShow ? stochD : na, title = 'Stoch D', color = color.new(#673ab7, 60), linewidth = 1)
stochFillColor = stochK >= stochD ? color.new(#21baf3, 75) : color.new(#673ab7, 60)
fill(stochKplot, stochDplot, title='KD Fill', color=stochFillColor)
// Stoch Div
plot(series = stochFractalTop ? stochK[2] : na, title='Stoch Bearish Divergence', color = stochBearDivColor, linewidth = 1, offset = -2)
plot(series = stochFractalBot ? stochK[2] : na, title='Stoch Bullish Divergence', color = stochBullDivColor, linewidth = 1, offset = -2)
// Schaff Trend Cycle
plot(tcLine ? tcVal : na, color = color.new(#673ab7, 25), linewidth = 2, title = "Schaff Trend Cycle 1")
plot(tcLine ? tcVal : na, color = color.new(colorWhite, 50), linewidth = 1, title = "Schaff Trend Cycle 2")
// Draw Overbought & Oversold lines
//plot(obLevel, title = 'Over Bought Level 1', color = colorWhite, linewidth = 1, style = plot.style_circles, transp = 85)
plot(obLevel2, title = 'Over Bought Level 2', color = colorWhite, linewidth = 1, style = plot.style_stepline, transp = 85)
plot(obLevel3, title = 'Over Bought Level 3', color = colorWhite, linewidth = 1, style = plot.style_circles, transp = 95)
//plot(osLevel, title = 'Over Sold Level 1', color = colorWhite, linewidth = 1, style = plot.style_circles, transp = 85)
plot(osLevel2, title = 'Over Sold Level 2', color = colorWhite, linewidth = 1, style = plot.style_stepline, transp = 85)
// Sommi flag
plotchar(sommiFlagShow and sommiBearish ? 108 : na, title = 'Sommi bearish flag', char='⚑', color = colorPink, location = location.absolute, size = size.tiny, transp = 0)
plotchar(sommiFlagShow and sommiBullish ? -108 : na, title = 'Sommi bullish flag', char='⚑', color = colorBluelight, location = location.absolute, size = size.tiny, transp = 0)
plot(sommiShowVwap ? ema(hvwap, 3) : na, title = 'Sommi higher VWAP', color = colorYellow, linewidth = 2, style = plot.style_line, transp = 15)
// Sommi diamond
plotchar(sommiDiamondShow and sommiBearishDiamond ? 108 : na, title = 'Sommi bearish diamond', char='◆', color = colorPink, location = location.absolute, size = size.tiny, transp = 0)
plotchar(sommiDiamondShow and sommiBullishDiamond ? -108 : na, title = 'Sommi bullish diamond', char='◆', color = colorBluelight, location = location.absolute, size = size.tiny, transp = 0)
// Circles
plot(wtCross ? wt2 : na, title = 'Buy and sell circle', color = signalColor, style = plot.style_circles, linewidth = 3, transp = 15)
plotchar(wtBuyShow and buySignal ? -107 : na, title = 'Buy circle', char='·', color = colorGreen, location = location.absolute, size = size.small, transp = 50)
plotchar(wtSellShow and sellSignal ? 105 : na , title = 'Sell circle', char='·', color = colorRed, location = location.absolute, size = size.small, transp = 50)
plotchar(wtDivShow and buySignalDiv ? -106 : na, title = 'Divergence buy circle', char='•', color = buySignalDiv_color, location = location.absolute, size = size.small, offset = -2, transp = 15)
plotchar(wtDivShow and sellSignalDiv ? 106 : na, title = 'Divergence sell circle', char='•', color = sellSignalDiv_color, location = location.absolute, size = size.small, offset = -2, transp = 15)
plotchar(wtGoldBuy and wtGoldShow ? -106 : na, title = 'Gold buy gold circle', char='•', color = colorOrange, location = location.absolute, size = size.small, offset = -2, transp = 15)
// } DRAW
len = input(14)
th = input(20)
TrueRange = max(max(high-low, abs(high-nz(close[1]))), abs(low-nz(close[1])))
DirectionalMovementPlus = high-nz(high[1]) > nz(low[1])-low ? max(high-nz(high[1]), 0): 0
DirectionalMovementMinus = nz(low[1])-low > high-nz(high[1]) ? 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 = abs(DIPlus-DIMinus) / (DIPlus+DIMinus)*100
ADX = sma(DX, len)
plot(ADX, color=color.white, title="ADX")
// ALERTS {
// BUY
// alertcondition(buySignal, 'Buy (Big green circle)', 'Green circle WaveTrend Oversold')
// alertcondition(buySignalDiv, 'Buy (Big green circle + Div)', 'Buy & WT Bullish Divergence & WT Overbought')
// alertcondition(wtGoldBuy, 'GOLD Buy (Big GOLDEN circle)', 'Green & GOLD circle WaveTrend Overbought')
// alertcondition(sommiBullish or sommiBullishDiamond, 'Sommi bullish flag/diamond', 'Blue flag/diamond')
// alertcondition(wtCross and wtCrossUp, 'Buy (Small green dot)', 'Buy small circle')
// SELL
// alertcondition(sommiBearish or sommiBearishDiamond, 'Sommi bearish flag/diamond', 'Purple flag/diamond')
// alertcondition(sellSignal, 'Sell (Big red circle)', 'Red Circle WaveTrend Overbought')
// alertcondition(sellSignalDiv, 'Sell (Big red circle + Div)', 'Buy & WT Bearish Divergence & WT Overbought')
// alertcondition(wtCross and wtCrossDown, 'Sell (Small red dot)', 'Sell small circle')
// } ALERTS
f_RelVol(_value, _length) =>
min_value = lowest(_value, _length)
max_value = highest(_value, _length)
stoch(_value, max_value, min_value, _length) / 100
rsi1LengthInput = input(100, minval=1, title="RSI Length", group="RSI Settings")
rsi1SourceInput = input(close, "Source", group="RSI Settings")
rsi2LengthInput = input(25, minval=1, title="RSI Length", group="RSI Settings")
rsi2SourceInput = input(close, "Source", group="RSI Settings")
price = close
length = input(10, minval=1)
DER_avg = input(5, 'Average', minval=1, inline='DER', group='Directional Energy Ratio')
smooth = input(3, 'Smoothing', minval=1, inline='DER', group='Directional Energy Ratio')
v_calc = input('Relative', 'Calculation', options=['Relative', 'Full', 'None'], group='Volume Parameters')
vlookbk = input(20, 'Lookback (for Relative)', minval=1, group='Volume Parameters')
uprsi1 = rma(max(change(rsi1SourceInput), 0), rsi1LengthInput)
uprsi2 = rma(max(change(rsi2SourceInput), 0), rsi2LengthInput)
downrsi1 = rma(-min(change(rsi1SourceInput), 0), rsi1LengthInput)
downrsi2 = rma(-min(change(rsi2SourceInput), 0), rsi2LengthInput)
rsi1 = downrsi1 == 0 ? 100 : uprsi1 == 0 ? 0 : 100 - (100 / (1 + uprsi1 / downrsi1))
rsi2 = downrsi2 == 0 ? 100 : uprsi2 == 0 ? 0 : 100 - (100 / (1 + uprsi2 / downrsi2))
vola =
v_calc == 'None' or na(volume) ? 1 :
v_calc == 'Relative' ? f_RelVol(volume, vlookbk) :
volume
R = (highest(1) - lowest(1)) / 2 // R is the 2-bar average bar range
sr = change(price) / R // calc ratio of change to R
rsr = max(min(sr, 1), -1) // ensure ratio is restricted to +1/-1 in case of big moves
c = rsr * vola // add volume accel
c_plus = max(c, 0) // calc directional vol-accel energy
c_minus = -min(c, 0)
// plot(c_plus)
// plot(c_minus)
dem = wma(c_plus, length) / wma(vola, length) //average directional energy ratio
sup = wma(c_minus, length) / wma(vola, length)
// plot(vola, 'Vol Accel')
adp = 1 * wma(dem, DER_avg)
asp = 1 * wma(sup, DER_avg)
anp = adp - asp
anp_s = wma(anp, smooth)
// plot(rsi1, "RSI", color=#FF0033)
rsi1UpperBand = hline(70, "RSI Upper Band", color=#787B86)
// hline(50, "RSI Middle Band", color=color.new(#787B86, 50))
rsi1LowerBand = hline(30, "RSI Lower Band", color=#787B86)
// plot(rsi2, "RSI", color=#FFFF00)
rsi2UpperBand = hline(70, "RSI Upper Band", color=#787B86)
// hline(50, "RSI Middle Band", color=color.new(#787B86, 50))
rsi2LowerBand = hline(30, "RSI Lower Band", color=#787B86)
c_adp = color.new(color.aqua, 50)
c_asp = color.new(color.orange, 50)
c_zero = color.new(color.yellow, 70)
c_fd = color.new(color.green, 80)
c_fs = color.new(color.red, 80)
c_up = color.new(#33ff00, 0)
c_dn = color.new(#ff1111, 0)
up = anp_s >= 0
strategy(title='VMC', shorttitle='VMC', overlay=true, precision=3, commission_value=0.025, default_qty_type=strategy.cash, default_qty_value=10000, initial_capital=10000)
//=== Buy/Sell ===
closeStatus = strategy.openprofit > 0 ? 'win' : 'lose'
// long_entry = (signalColor == color.lime and wtCross and up)
// long_exit_entry = (signalColor == color.red or sellSignal or sellSignalDiv)
// short_entry = (signalColor == color.red and wtCross and not up)
// short_exit_entry = (signalColor == color.lime or buySignal or buySignalDiv)
long_entry = wt2 < wt1 //and up and rsi2 > rsi1
long_exit_entry = signalColor == color.red or sellSignal or sellSignalDiv
short_entry = wt2 > wt1 //and not up and rsi2 < rsi1
short_exit_entry = signalColor == color.lime or buySignal or buySignalDiv
alertcondition(long_entry, 'Buy', 'Long entry')
alertcondition(long_exit_entry, 'Buy', 'Long exit')
alertcondition(short_entry, 'Sell', 'Short entry')
alertcondition(short_exit_entry, 'Sell', 'Short exit')
strategy.entry('long', strategy.long, when=long_entry)
strategy.close('long', when=long_exit_entry, comment=closeStatus)
strategy.entry('short', strategy.short, when=short_entry)
strategy.close('short', when=short_exit_entry, comment=closeStatus)
// stopPer = input(100, title='Stop Loss %', type=input.float) / 100
// takePer = input(100, title='Take Profit %', type=input.float) / 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) |
5 Minute Scalping Strategy | https://www.tradingview.com/script/6iDU009f-5-Minute-Scalping-Strategy/ | Coachman0912 | https://www.tradingview.com/u/Coachman0912/ | 347 | 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/
// © pluckyCraft54926
//@version=5
strategy("5 Minute Scalp", overlay=true, margin_long=100, margin_short=100)
fast_length = input(title="Fast Length", defval=12)
slow_length = input(title="Slow Length", defval=26)
src = input(title="Source", defval=close)
signal_length = input.int(title="Signal Smoothing", minval = 1, maxval = 50, defval = 9)
sma_source = input.string(title="Oscillator MA Type", defval="EMA", options=["SMA", "EMA"])
sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"])
// Plot colors
col_macd = input(#2962FF, "MACD Line ", group="Color Settings", inline="MACD")
col_signal = input(#FF6D00, "Signal Line ", group="Color Settings", inline="Signal")
col_grow_above = input(#26A69A, "Above Grow", group="Histogram", inline="Above")
col_fall_above = input(#B2DFDB, "Fall", group="Histogram", inline="Above")
col_grow_below = input(#FFCDD2, "Below Grow", group="Histogram", inline="Below")
col_fall_below = input(#FF5252, "Fall", group="Histogram", inline="Below")
// Calculating
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
hist_1m = request.security(syminfo.tickerid,"1",hist [barstate.isrealtime ? 1 : 0])
hline(0, "Zero Line", color=color.new(#787B86, 50))
////////////////////////////////////////////////////
//plotting emas on the chart
len1 = input.int(9, minval=1, title="Length")
src1 = input(close, title="Source")
offset1 = input.int(title="Offset", defval=0, minval=-500, maxval=500)
out1 = ta.ema(src1, len1)
plot(out1, title="EMA9", color=color.blue, offset=offset1)
len2 = input.int(50, minval=1, title="Length")
src2 = input(close, title="Source")
offset2 = input.int(title="Offset", defval=0, minval=-500, maxval=500)
out2 = ta.ema(src2, len2)
plot(out2, title="EMA50", color=color.yellow, offset=offset2)
len3 = input.int(200, minval=1, title="Length")
src3 = input(close, title="Source")
offset3 = input.int(title="Offset", defval=0, minval=-500, maxval=500)
out3 = ta.ema(src3, len3)
plot(out3, title="EMA200", color=color.white, offset=offset3)
//////////////////////////////////////////////////////////////////
//Setting up the BB
/////////////////////////////////////////////////////////////
srcBB = hist_1m
lengthBBLong = input.int(94,title = "LengthBB Long", minval=1)
lengthBBShort = input.int(83,title = "LengthBB Short", minval=1)
multBB = input.float(2.0, minval=0.001, maxval=50, title="StdDev")
basisBBLong = ta.sma(srcBB, lengthBBLong)
basisBBShort = ta.sma(srcBB, lengthBBShort)
devBBLong = multBB * ta.stdev(srcBB, lengthBBLong)
devBBShort = multBB * ta.stdev(srcBB, lengthBBShort)
upperBB = basisBBShort + devBBShort
lowerBB = basisBBLong - devBBLong
offsetBB = input.int(0, "Offset", minval = -500, maxval = 500)
/////////////////////////////////////////
//aetting up rsi
///////////////////////////////////////////
rsilengthlong = input.int(defval = 11, title = "Rsi Length Long", minval = 1)
rlong=ta.rsi(close,rsilengthlong)
rsilengthshort = input.int(defval = 29, title = "Rsi Length Short", minval = 1)
rshort=ta.rsi(close,rsilengthshort)
///////////////////////////
//Only taking long and shorts, if RSI is above 51 or bellow 49
rsilong = rlong >= 51
rsishort = rshort <= 49
//////////////////////////////////////
//only taking trades if all 3 emas are in the correct order
long = out1 > out2 and out2 > out3
short = out1 < out2 and out2 < out3
/////////////////////////////////////
///////////////////////////////////////////
//setting up TP and SL
TP = input.float(defval = 0.5, title = "Take Profit %",step = 0.1) / 100
SL = input.float(defval = 0.3, title = "Stop Loss %", step = 0.1) / 100
longCondition = hist_1m <= lowerBB
longhight = input(defval=-10,title = "MacdTick Low")
if (longCondition and long and rsilong and hist_1m <= longhight)
strategy.entry("Long", strategy.long)
if (strategy.position_size>0)
longstop = strategy.position_avg_price * (1-SL)
longprofit = strategy.position_avg_price * (1+TP)
strategy.exit(id ="close long",from_entry="Long",stop=longstop,limit=longprofit)
shortCondition = hist_1m >= upperBB
shorthight = input(defval=35,title = "MacdTick High")
if (shortCondition and short and rsishort and hist_1m >= shorthight)
strategy.entry("short ", strategy.short)
shortstop = strategy.position_avg_price * (1+SL)
shortprofit = strategy.position_avg_price * (1-TP)
if (strategy.position_size<0)
strategy.exit(id ="close short",stop=shortstop,limit=shortprofit)
|
EMA Cloud Intraday Strategy | https://www.tradingview.com/script/bRU5AT0T-EMA-Cloud-Intraday-Strategy/ | rwestbrookjr | https://www.tradingview.com/u/rwestbrookjr/ | 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/
// © rwestbrookjr
//@version=5
strategy("EMA Cloud Intraday Strategy", overlay=true, margin_long=100, margin_short=100, process_orders_on_close=true)
i_trdQty = input.int(100, "Trade Quantity", minval = 1)
pbTrig = input.float(1.00, "Pull Back Trigger", minval = 0.01)
session = time(timeframe.period, "0930-1555:23456")
validSession=(na(session) ? 0 : 1)
fastLen = input(title = "Fast EMA Length", defval = 9)
slowLen = input(title = "Slow EMA Length", defval = 20)
fastEMA = ta.ema(close, fastLen)
slowEMA = ta.ema(close, slowLen)
fema = plot(fastEMA, title = "FastEMA", color = color.green, linewidth = 1, style = plot.style_line)
sema = plot(slowEMA, title = "SlowEMA", color = color.red, linewidth = 1, style = plot.style_line)
Bull = fastEMA > slowEMA
Bear = fastEMA < slowEMA
fill(fema, sema, color = fastEMA > slowEMA ? color.new(#417505, 50) : color.new(#890101, 50), title = "Cloud")
longCondition = close > fastEMA and close[1] > fastEMA and validSession == 1
if (longCondition)
strategy.entry("Long_Entry", strategy.long, qty=i_trdQty)
longExit = (close < fastEMA and close[1] < fastEMA) or close < (close[1] - pbTrig) or validSession == 0
if (longExit)
strategy.close("Long_Entry")
//strategy.exit("exit", "My Long Entry Id", trail_points=1.5, trail_offset=0)
shortCondition = close < fastEMA and close[1] < fastEMA and validSession == 1
if (shortCondition)
strategy.entry("Short_Entry", strategy.short, qty=i_trdQty)
shortExit = (close > fastEMA and close[1] > fastEMA) or close > (close[1] + pbTrig) or validSession == 0
if (shortExit)
strategy.close("Short_Entry")
//strategy.exit("exit", "My Short Entry Id", trail_points=1.5, trail_offset=0)
// Close all trades at end of trading day
barOpenTime = time
tt=timestamp(year(time), month(time), dayofmonth(time), hour(time), 2)
if ( hour(time) == 15 and minute(time) > 50 )
strategy.close("Short_Entry", comment="SCM")
if ( hour(time) == 15 and minute(time) > 50 )
strategy.close("Long_Entry", comment="SCM")
if validSession == 0// and strategy.opentrades != 0
//if strategy.opentrades > 0
strategy.close_all(comment="SC")
//if strategy.opentrades < 0
//strategy.close("Short_Entry", comment="SC")
|
MACD Willy Strategy | https://www.tradingview.com/script/ahZBgyN5-MACD-Willy-Strategy/ | PtGambler | https://www.tradingview.com/u/PtGambler/ | 303 | 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/
// © platsn
//@version=5
strategy("MACD Willy Strategy", overlay=true, pyramiding=1, initial_capital=10000)
// ******************** Trade Period **************************************
startY = input(title='Start Year', defval=2011, group = "Trading window")
startM = input.int(title='Start Month', defval=1, minval=1, maxval=12, group = "Trading window")
startD = input.int(title='Start Day', defval=1, minval=1, maxval=31, group = "Trading window")
finishY = input(title='Finish Year', defval=2050, group = "Trading window")
finishM = input.int(title='Finish Month', defval=12, minval=1, maxval=12, group = "Trading window")
finishD = input.int(title='Finish Day', defval=31, minval=1, maxval=31, group = "Trading window")
timestart = timestamp(startY, startM, startD, 00, 00)
timefinish = timestamp(finishY, finishM, finishD, 23, 59)
// t1 = time(timeframe.period, "0945-1545:23456")
// window = time >= timestart and time <= timefinish and t1 ? true : false
// t2 = time(timeframe.period, "0930-1555:23456")
// window2 = time >= timestart and time <= timefinish and t2 ? true : false
leverage = input.float(1, title="Leverage (if applicable)", step=0.1, group = "Trading Options")
reinvest = input.bool(defval=false,title="Reinvest profit", group = "Trading Options")
reinvest_percent = input.float(defval=20, title = "Reinvest percentage", group="Trading Options")
// entry_lookback = input.int(defval=10, title="Lookback period for entry condition", group = "Trading Options")
// -------------------------------------------- Data Source --------------------------------------------
src = input(title="Source", defval=close)
// ***************************************************************************************************** Daily ATR *****************************************************
atrlen = input.int(14, minval=1, title="ATR period", group = "Daily ATR")
iPercent = input.float(5, minval=1, maxval=100, step=0.1, title="% ATR to use for SL / PT", group = "Daily ATR")
percentage = iPercent * 0.01
datr = request.security(syminfo.tickerid, "1D", ta.rma(ta.tr, atrlen))
datrp = datr * percentage
// plot(datr,"Daily ATR")
// plot(datrp, "Daily % ATR")
//*********************************************************** VIX volatility index ****************************************
VIX = request.security("VIX", timeframe.period, close)
vix_thres = input.float(20.0, "VIX Threshold for entry", step=0.5, group="VIX Volatility Index")
// ************************************************ Volume ******************************************************
vol_len = input(50, 'Volume MA Period')
avg_vol = ta.sma(volume, vol_len)
//-------------------------------------------------------- Moving Average ------------------------------------
emalen1 = input.int(200, minval=1, title='EMA', group= "Moving Averages")
ema1 = ta.ema(src, emalen1)
// ------------------------------------------ MACD ------------------------------------------
// Getting inputs
fast_length = input(title="Fast Length", defval=12)
slow_length = input(title="Slow Length", defval=26)
signal_length = input.int(title="Signal Smoothing", minval = 1, maxval = 50, defval = 9)
sma_source = input.string(title="Oscillator MA Type", defval="EMA", options=["SMA", "EMA"])
sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"])
// Plot colors
col_macd = input(#2962FF, "MACD Line ", group="Color Settings", inline="MACD")
col_signal = input(#FF6D00, "Signal Line ", group="Color Settings", inline="Signal")
col_grow_above = input(#26A69A, "Above Grow", group="Histogram", inline="Above")
col_fall_above = input(#B2DFDB, "Fall", group="Histogram", inline="Above")
col_grow_below = input(#FFCDD2, "Below Grow", group="Histogram", inline="Below")
col_fall_below = input(#FF5252, "Fall", group="Histogram", inline="Below")
// Calculating
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
// ---------------------------------------- William %R --------------------------------------
w_length = input.int(defval=34, minval=1)
w_upper = ta.highest(w_length)
w_lower = ta.lowest(w_length)
w_output = 100 * (close - w_upper) / (w_upper - w_lower)
fast_period = input(defval=5, title='Smoothed %R Length')
slow_period = input(defval=13, title='Slow EMA Length')
w_fast_ma = ta.wma(w_output,fast_period)
w_slow_ma = ta.ema(w_output,slow_period)
// ------------------------------------------------ Entry Conditions ----------------------------------------
L_entry1 = close > ema1 and hist > 0 and w_fast_ma > w_slow_ma
S_entry1 = close < ema1 and hist < 0 and w_fast_ma < w_slow_ma
// -------------------------------------------------- Entry -----------------------------------------------
profit = strategy.netprofit
trade_amount = math.floor(strategy.initial_capital*leverage / close)
if strategy.netprofit > 0 and reinvest
trade_amount := math.floor((strategy.initial_capital+(profit*reinvest_percent*0.01))*leverage / close)
else
trade_amount := math.floor(strategy.initial_capital*leverage/ close)
if L_entry1 //and window
strategy.entry("Long", strategy.long, trade_amount)
alert(message= "Long Signal", freq= alert.freq_once_per_bar_close)
if S_entry1 //and window
strategy.entry("Short", strategy.short, trade_amount)
alert(message= "Short Signal", freq= alert.freq_once_per_bar_close)
// --------------------------------------------------- Exit Conditions -------------------------------------
L_exit1 = hist < 0 and w_fast_ma < w_slow_ma and w_fast_ma < -20
S_exit1 = hist > 0 and w_fast_ma > w_slow_ma and w_fast_ma > -80
// ----------------------------------------------------- Exit ---------------------------------------------
if L_exit1 //and window2
strategy.close("Long")
alert(message= "Long Exit Signal", freq= alert.freq_once_per_bar_close)
if S_exit1 //and window2
strategy.close("Short")
alert(message= "Short Exit Signal", freq= alert.freq_once_per_bar_close)
// if time(timeframe.period, "1530-1600:23456")
// strategy.close_all() |
[VJ]First Candle Strategy | https://www.tradingview.com/script/82Ylt2lz-VJ-First-Candle-Strategy/ | vikris | https://www.tradingview.com/u/vikris/ | 212 | 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/
// © vikris
//@version=4
strategy("[VJ]First Candle Strategy", overlay = true,calc_on_every_tick = true,default_qty_type=strategy.percent_of_equity,default_qty_value=100,initial_capital=750,commission_type=strategy.commission.percent,
commission_value=0.02)
// ********** Strategy inputs - Start **********
// Used for intraday handling
// Session value should be from market start to the time you want to square-off
// your intraday strategy
// Important: The end time should be at least 2 minutes before the intraday
// square-off time set by your broker
var i_marketSession = input(title="Market session", type=input.session,
defval="0915-1455", confirm=true)
// Make inputs that set the take profit % (optional)
longProfitPerc = input(title="Long Take Profit (%)",
type=input.float, minval=0.0, step=0.1, defval=1) * 0.01
shortProfitPerc = input(title="Short Take Profit (%)",
type=input.float, minval=0.0, step=0.1, defval=1) * 0.01
// Set stop loss level with input options (optional)
longLossPerc = input(title="Long Stop Loss (%)",
type=input.float, minval=0.0, step=0.1, defval=0.5) * 0.01
shortLossPerc = input(title="Short Stop Loss (%)",
type=input.float, minval=0.0, step=0.1, defval=0.5) * 0.01
// ********** Strategy inputs - End **********
// ********** Supporting functions - Start **********
// A function to check whether the bar or period is in intraday session
barInSession(sess) => time(timeframe.period, sess) != 0
// Figure out take profit price
longExitPrice = strategy.position_avg_price * (1 + longProfitPerc)
shortExitPrice = strategy.position_avg_price * (1 - shortProfitPerc)
// Determine stop loss price
longStopPrice = strategy.position_avg_price * (1 - longLossPerc)
shortStopPrice = strategy.position_avg_price * (1 + shortLossPerc)
// ********** Supporting functions - End **********
// ********** Strategy - Start **********
// See if intraday session is active
bool intradaySession = barInSession(i_marketSession)
// Trade only if intraday session is active
//=================Strategy logic goes in here===========================
// If start of the daily session changed, then it's first bar of the new session
isNewDay = time("D") != time("D")[1]
var firstBarCloseValue = close
var firstBarOpenValue = open
if isNewDay
firstBarCloseValue := close
firstBarOpenValue := open
greenCandle = firstBarOpenValue < firstBarCloseValue
redCandle = firstBarOpenValue > firstBarCloseValue
buy = redCandle
sell = greenCandle
// plot(firstBarCloseValue)
// plot(firstBarOpenValue)
//Final Long/Short Condition
longCondition = buy
shortCondition =sell
//Long Strategy - buy condition and exits with Take profit and SL
if (longCondition and intradaySession)
stop_level = longStopPrice
profit_level = longExitPrice
strategy.entry("My Long Entry Id", strategy.long)
strategy.exit("TP/SL", "My Long Entry Id", stop=stop_level, limit=profit_level)
//Short Strategy - sell condition and exits with Take profit and SL
if (shortCondition and intradaySession)
stop_level = shortStopPrice
profit_level = shortExitPrice
strategy.entry("My Short Entry Id", strategy.short)
strategy.exit("TP/SL", "My Short Entry Id", stop=stop_level, limit=profit_level)
// Square-off position (when session is over and position is open)
squareOff = (not intradaySession) and (strategy.position_size != 0)
strategy.close_all(when = squareOff, comment = "Square-off")
// ********** Strategy - End ********** |
Estrategia Larry Connors [JoseMetal] | https://www.tradingview.com/script/H4ciolWP/ | JoseMetal | https://www.tradingview.com/u/JoseMetal/ | 491 | 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/
// © JoseMetal
//@version=5
// Descripción de la estrategia:
// + LONG:
// El precio debe estar por encima de la SMA lenta.
// Cuando una vela cierra en la zona de sobreventa del RSI, la siguiente vela cierra fuera de la zona de sobreventa y el precio de cierre está POR DEBAJO de la SMA rápida = abre LONG.
// Se cierra cuando una vela cierra POR ENCIMA de la SMA rápida.
// - SHORT:
// El precio debe estar POR DEBAJO de la SMA lenta.
// Cuando una vela cierra en la zona de sobrecompra del RSI, la siguiente vela cierra fuera de la zona de sobrecompra y el precio de cierre está POR ENCIMA de la SMA rápida = abre SHORT.
// Se cierra cuando una vela cierra POR DEBAJO de la SMA rápida.
// *La estrategia de Larry Connor NO utiliza un Stop Loss o Take Profit fijo, como él dijo, eso reduce el rendimiento significativamente
//== Constantes
c_blanco = color.rgb(255, 255, 255, 0)
c_negro = color.rgb(0, 0, 0, 0)
c_amarillo_radiactivo = color.rgb(255, 255, 0, 0)
c_cian_radiactivo = color.rgb(0, 255, 255, 0)
c_verde_radiactivo = color.rgb(0, 255, 0, 0)
c_verde = color.rgb(0, 128, 0, 0)
c_verde_oscuro = color.rgb(0, 80, 0, 0)
c_rojo_radiactivo = color.rgb(255, 0, 0, 0)
c_rojo = color.rgb(128, 0, 0, 0)
c_rojo_oscuro = color.rgb(80, 0, 0, 0)
c_naranja_oscuro = color.rgb(200, 120, 0, 0)
noneColor = color.new(color.white, 100)
max_float = 10000000000.0
//== Funciones
//== Declarar estrategia y período de testeo
strategy("Larry Connors Strategy [JoseMetal]", shorttitle="Larry Connors Strategy [JoseMetal]", overlay=true, initial_capital=10000, pyramiding=0, default_qty_value=10, default_qty_type=strategy.percent_of_equity, commission_type=strategy.commission.percent, commission_value=0.0, max_labels_count=500, max_bars_back=1000)
GRUPO_per_pruebas = "Período de pruebas"
fecha_inicio = input.time(0, "• Fecha de inicio", group=GRUPO_per_pruebas, tooltip="Las fechas son inclusivas") // timestamp("1 Jan 2000")
fecha_fin_usar = input.bool(false, "Fecha de finalización", group=GRUPO_per_pruebas, inline="fecha_finalizacion")
fecha_fin = input.time(timestamp("1 Jan 2999"), "", group=GRUPO_per_pruebas, inline="fecha_finalizacion")
vela_en_fecha = time >= fecha_inicio and (fecha_fin_usar ? time <= fecha_fin : true)
posicion_abierta = strategy.position_size != 0
LONG_abierto = strategy.position_size > 0
SHORT_abierto = strategy.position_size < 0
GRUPO_P = "Posiciones"
P_permitir_LONGS = input.bool(title="¿LONGS?", group=GRUPO_P, defval=true, inline="pos_activadas")
P_permitir_SHORTS = input.bool(title="¿SHORTS?", group=GRUPO_P, defval=true, inline="pos_activadas")
GRUPO_TPSL = "Stop Loss y Take Profit (ATR)"
TPSL_SL_ATR_usar = input.bool(false, "¿Usar Stop Loss? / Mult. ATR", group=GRUPO_TPSL, inline="stop_loss")
TPSL_SL_ATR_mult = input.float(3.1, "", group=GRUPO_TPSL, minval=0.1, step=0.1, inline="stop_loss", tooltip="Si está activado, se usará el ATR multiplicado por éste valor como Stop Loss")
TPSL_TP_ATR_usar = input.bool(false, "¿Usar Take Profit? / Mult. ATR", group=GRUPO_TPSL, inline="take_profit")
TPSL_TP_ATR_mult = input.float(3.1, "", group=GRUPO_TPSL, minval=0.1, step=0.1, inline="take_profit", tooltip="Si está activado, se usará el ATR multiplicado por éste valor como Take Profit")
GRUPO_BE = "Break Even (ATR)"
usar_be = input.bool(false, "¿Proteger posiciones? (Break Even)", group=GRUPO_BE)
TPSL_break_even_req_mult = input.float(title="• Mult. para BREAK EVEN y STOP LOSS", group=GRUPO_BE, defval=1.0, minval=0.0, step=0.1, inline="be", tooltip="Cuando el precio avance a nuestro favor y llegue éste ATR, el Stop Loss se moverá a BREAK EVEN, de modo que la operación quede protegida.\nEl 'nivel de stop loss' nos permite que el stop se mueva aún más a favor de nuestro precio de entrada para además asegurar ganancias")
TPSL_break_even_mult = input.float(title="", group=GRUPO_BE, defval=0.8, minval=0.0, step=0.1, inline="be")
GRUPO_general = "General"
mostrar_color_velas = input.bool(title="Colorear velas", defval=true, group=GRUPO_general)
mostrar_color_velas_2 = input.bool(title="Marcar velas neutras", defval=true, group=GRUPO_general)
//== Inputs de indicadores
// Medias móviles
GRUPO_MAs = "MAs"
MA_SALIDA_tipo = input.string(title="• (Media de salida) Tipo / Fuente / Long.", group=GRUPO_MAs, defval="SMA", options=["SMA", "EMA", "WMA", "HMA"], inline="ma_salida")
MA_SALIDA_fuente = input.source(title="", group=GRUPO_MAs, defval=close, inline="ma_salida")
MA_SALIDA_length = input.int(title="", group=GRUPO_MAs, defval=10, minval=1, inline="ma_salida")
MA_SALIDA = ta.sma(MA_SALIDA_fuente, MA_SALIDA_length)
MA_TENDENCIA_tipo = input.string(title="• (Media de tendencia) Tipo / Fuente / Long.", group=GRUPO_MAs, defval="SMA", options=["SMA", "EMA", "WMA", "HMA"], inline="ma_tendencia")
MA_TENDENCIA_fuente = input.source(title="", group=GRUPO_MAs, defval=close, inline="ma_tendencia")
MA_TENDENCIA_length = input.int(title="", group=GRUPO_MAs, defval=200, minval=1, inline="ma_tendencia")
MA_TENDENCIA = ta.sma(MA_TENDENCIA_fuente, MA_TENDENCIA_length)
if (MA_SALIDA_tipo == "EMA")
MA_SALIDA := ta.ema(MA_SALIDA_fuente, MA_SALIDA_length)
else if (MA_SALIDA_tipo == "WMA")
MA_SALIDA := ta.wma(MA_SALIDA_fuente, MA_SALIDA_length)
else if (MA_SALIDA_tipo == "HMA")
MA_SALIDA := ta.hma(MA_SALIDA_fuente, MA_SALIDA_length)
if (MA_TENDENCIA_tipo == "EMA")
MA_TENDENCIA := ta.ema(MA_TENDENCIA_fuente, MA_TENDENCIA_length)
else if (MA_TENDENCIA_tipo == "WMA")
MA_TENDENCIA := ta.wma(MA_TENDENCIA_fuente, MA_TENDENCIA_length)
else if (MA_TENDENCIA_tipo == "HMA")
MA_TENDENCIA := ta.hma(MA_TENDENCIA_fuente, MA_TENDENCIA_length)
// RSI
GRUPO_RSI = "RSI"
RSI_src = input.source(title="• Fuente / Longitud", group=GRUPO_RSI, defval=close, inline="rsi_calc")
RSI_length = input.int(title="", group=GRUPO_RSI, defval=2, minval=1, inline="rsi_calc")
RSI = ta.rsi(RSI_src, RSI_length)
RSI_nivel_os = input.int(title="• Sobreventa / Sobrecompra", group=GRUPO_RSI, defval=5, minval=0, maxval=99, inline="rsi_niveles")
RSI_nivel_ob = input.int(title="", group=GRUPO_RSI, defval=95, minval=1, maxval=100, inline="rsi_niveles")
// ATR
GRUPO_ATR = "ATR"
ATR_referencia = input.source(title="• Referencia / Longitud", group=GRUPO_ATR, defval=close, inline="atr_calc") // La fuente no se aplica al cálculo del ATR, es para el posicionamiento respecto al precio en el gráfico
ATR_length = input.int(title="", group=GRUPO_ATR, defval=7, minval=1, inline="atr_calc")
ATR = ta.atr(ATR_length)
ATR_sl = ATR * TPSL_SL_ATR_mult
ATR_tp = ATR * TPSL_TP_ATR_mult
ATR_be_req = ATR * TPSL_break_even_req_mult
ATR_be = ATR * TPSL_break_even_mult
ATR_LONG_sl = ATR_referencia - ATR_sl // De forma contraria el inferior se puede usar como STOP LOSS o TRAILING STOP
ATR_LONG_tp = ATR_referencia + ATR_tp // El ATR sobre las velas se puede usar como TAKE PROFIT
ATR_SHORT_sl = ATR_referencia + ATR_sl // ""
ATR_SHORT_tp = ATR_referencia - ATR_tp // Para Shorts es al revés
ATR_LONG_break_even_req = ATR_referencia + ATR_be_req
ATR_SHORT_break_even_req = ATR_referencia - ATR_be_req
ATR_LONG_break_even = ATR_referencia + ATR_be
ATR_SHORT_break_even = ATR_referencia - ATR_be
//== Cálculo de condiciones
cierre_sobre_MA_SALIDA = close > MA_SALIDA
tendencia_alcista = close > MA_TENDENCIA
RSI_en_sobreventa = RSI < RSI_nivel_os
RSI_en_sobrecompra = RSI > RSI_nivel_ob
//== Salida de posiciones
exit_LONG_conditions = cierre_sobre_MA_SALIDA
exit_SHORT_conditions = not cierre_sobre_MA_SALIDA
if (LONG_abierto and exit_LONG_conditions)
strategy.close("Abrir Long")
if (SHORT_abierto and exit_SHORT_conditions)
strategy.close("Abrir Short")
//== Entrada de posiciones (deben cumplirse todas para entrar)
LONG_condition_1 = tendencia_alcista
LONG_condition_2 = not cierre_sobre_MA_SALIDA // Vela con cierre bajo la media rápida
LONG_condition_3 = RSI_en_sobreventa[1] and not RSI_en_sobreventa // Sobreventa en la vela anterior y ya no en la actual
all_LONG_conditions = LONG_condition_1 and LONG_condition_2 and LONG_condition_3
entrar_en_LONG = P_permitir_LONGS and all_LONG_conditions and vela_en_fecha and not LONG_abierto
SHORT_condition_1 = not tendencia_alcista
SHORT_condition_2 = cierre_sobre_MA_SALIDA // Vela con cierre sobre la media rápida
SHORT_condition_3 = RSI_en_sobrecompra[1] and not RSI_en_sobrecompra // Sobrecompra en la vela anterior y ya no en la actual
all_SHORT_conditions = SHORT_condition_1 and SHORT_condition_2 and SHORT_condition_3
entrar_en_SHORT = P_permitir_SHORTS and all_SHORT_conditions and vela_en_fecha and not SHORT_abierto
var LONG_stop_loss = 0.0
var LONG_take_profit = max_float
var LONG_break_even_req = 0.0
var LONG_break_even = 0.0
var SHORT_stop_loss = max_float
var SHORT_take_profit = 0.0
var SHORT_break_even_req = 0.0
var SHORT_break_even = 0.0
var en_be = false
if (not posicion_abierta)
en_be := false
LONG_stop_loss := 0.0
LONG_take_profit := max_float
SHORT_stop_loss := max_float
SHORT_take_profit := 0.0
if (not posicion_abierta)
if (entrar_en_LONG)
if (TPSL_SL_ATR_usar)
LONG_stop_loss := ATR_LONG_sl
if (TPSL_TP_ATR_usar)
LONG_take_profit := ATR_LONG_tp
if (usar_be)
LONG_break_even_req := ATR_LONG_break_even_req
LONG_break_even := ATR_LONG_break_even
strategy.entry("Abrir Long", strategy.long)
strategy.exit("Cerrar Long", "Abrir Long", stop=TPSL_SL_ATR_usar ? LONG_stop_loss : na, limit=TPSL_TP_ATR_usar ? LONG_take_profit : na)
else if (entrar_en_SHORT)
if (TPSL_SL_ATR_usar)
SHORT_stop_loss := ATR_SHORT_sl
if (TPSL_TP_ATR_usar)
SHORT_take_profit := ATR_SHORT_tp
if (usar_be)
SHORT_break_even_req := ATR_SHORT_break_even_req
SHORT_break_even := ATR_SHORT_break_even
strategy.entry("Abrir Short", strategy.short)
strategy.exit("Cerrar Short", "Abrir Short", stop=TPSL_SL_ATR_usar ? SHORT_stop_loss : na, limit=TPSL_TP_ATR_usar ? SHORT_take_profit : na)
// Proteger operativa (Break Even)
if (usar_be and not en_be)
if (LONG_abierto and LONG_stop_loss < LONG_break_even and close > LONG_break_even_req)
LONG_stop_loss := LONG_break_even
strategy.exit("Cerrar Long", "Abrir Long", stop=LONG_stop_loss, limit=TPSL_TP_ATR_usar ? LONG_take_profit : na)
en_be := true
else if (SHORT_abierto and SHORT_stop_loss > SHORT_break_even and close < SHORT_break_even_req)
SHORT_stop_loss := SHORT_break_even
strategy.exit("Cerrar Short", "Abrir Short", stop=SHORT_stop_loss, limit=TPSL_TP_ATR_usar ? SHORT_take_profit : na)
en_be := true
//== Ploteo en pantalla
// SMAs
plot(MA_SALIDA, "Media de salida", color=color.aqua, linewidth=2)
plot(MA_TENDENCIA, "Media tendencial", color=tendencia_alcista ? #00a800 : #ca0000, linewidth=4)
// Color de fondo
bgcolor = entrar_en_LONG ? color.new(color.green, 85) : entrar_en_SHORT ? color.new(color.red, 85) : color.new(color.black, 100)
bgcolor(bgcolor)
// Color de las velas según sobrecompra/sobreventa del RSI
color_velas = mostrar_color_velas ? (RSI_en_sobreventa ? c_verde_radiactivo : RSI_en_sobrecompra ? c_rojo_radiactivo : mostrar_color_velas_2 ? c_negro : na) : na
barcolor(color_velas)
// Precio de compra, Stop Loss, Take Profit, Break Even...
avg_position_price_plot = plot(posicion_abierta ? strategy.position_avg_price : na, color=color.new(color.white, 25), style=plot.style_linebr, linewidth=2, title="Precio Entrada")
break_even_req_plot = plot(posicion_abierta and usar_be and not en_be ? (LONG_abierto ? LONG_break_even_req : SHORT_break_even_req) : na, color=color.new(color.blue, 25), style=plot.style_linebr, linewidth=1, title="Nivel requerido para activar 'Break Even'")
break_even_plot = plot(posicion_abierta and usar_be and not en_be ? (LONG_abierto ? LONG_break_even : SHORT_break_even) : na, color=color.new(color.aqua, 25), style=plot.style_linebr, linewidth=1, title="Nivel de 'Break Even'")
LONG_sl_plot = plot(LONG_abierto and LONG_stop_loss > 0.0 ? LONG_stop_loss : na, color=en_be ? color.new(color.aqua, 25) : color.new(color.red, 25), style=plot.style_linebr, linewidth=3, title="Long Stop Loss")
LONG_tp_plot = plot(LONG_abierto and LONG_take_profit < max_float ? LONG_take_profit : na, color=color.new(color.lime, 25), style=plot.style_linebr, linewidth=3, title="LONG Take Profit")
fill(avg_position_price_plot, LONG_sl_plot, color=color.new(color.maroon, 85))
fill(avg_position_price_plot, LONG_tp_plot, color=color.new(color.olive, 85))
SHORT_sl_plot = plot(SHORT_abierto and SHORT_stop_loss < max_float ? SHORT_stop_loss : na, color=en_be ? color.new(color.aqua, 25) : color.new(color.red, 25), style=plot.style_linebr, linewidth=3, title="Short Stop Loss")
SHORT_tp_plot = plot(SHORT_abierto and SHORT_take_profit > 0.0 ? SHORT_take_profit : na, color=color.new(color.lime, 25), style=plot.style_linebr, linewidth=3, title="SHORT Take Profit")
fill(avg_position_price_plot, SHORT_sl_plot, color=color.new(color.maroon, 85))
fill(avg_position_price_plot, SHORT_tp_plot, color=color.new(color.olive, 85))
|
EMA bands + leledc + bollinger bands trend following strategy v2 | https://www.tradingview.com/script/RqcLxyIW-EMA-bands-leledc-bollinger-bands-trend-following-strategy-v2/ | readysetliqd | https://www.tradingview.com/u/readysetliqd/ | 275 | 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/
// © danielx888
// Credits to Joy_Bangla for the Leledc exhaustion bar code
// Credits to VishvaP for the 34 EMA bands code
// Credits to SlumdogTrader for the BB exhaustion code (edited for functionality)
// Credits to Juanc2316 for his code for BB Keltner Squeeze
//
// Update Notes : added strategy close conditions before every entry for more accurate
// backtesting results when considering for slippage and fees, readability adjustments
//@version=5
strategy(title='EMA bands + leledc + bollinger bands trend catching strategy w/ countertrend scalp',
shorttitle='Trend Pooristics', overlay=true, initial_capital = 1000, commission_value= 0.036,
pyramiding= 0, default_qty_type= strategy.percent_of_equity, default_qty_value= 100,
margin_long=0, margin_short=0, max_bars_back=200)
//USER INPUTS {
//INPUT: OPEN
i_EMAlength = input.int (34, 'EMA Length', minval=1, step=1)
s_needLong = input.bool (true, title = "Enable middle EMA band breakout: Long", group="Open Conditions")
s_needShort = input.bool (true, title = "Enable middle EMA band breakdown: Short", group="Open Conditions")
s_longBounce = input.bool (false, 'Enable middle EMA band bounce re-entry: Long', tooltip='Works best when early close conditions are used', group= 'Open Conditions')
s_shortBounce = input.bool (false, 'Enable middle EMA band bounce re-entry: Short', tooltip='Works best when early close conditions are used', group= 'Open Conditions')
s_alwaysLong = input.bool (false, title = "Enable default positioning: Long", tooltip='Does not work with "Enable default positioning: Short" also selected. Works best when early close conditions are used', group = 'Open Conditions')
s_alwaysShort = input.bool (false, title = "Enable default positioning: Short", tooltip='Does not work with "Enable default positioning: Long" also selected. Works best when early close conditions are used', group = 'Open Conditions')
i_topMBmult = input.float (1, 'Top middle band multiplier', 0.1,3,step=0.1,group='Open Conditions')
i_botMBmult = input.float (1, 'Bottom middle band multiplier',0.1,3,step=0.1,group='Open Conditions')
s_useSlowEMA = input.bool (false, title='Use slow EMA filter',tooltip='Condition does not apply to counter-trend trades', group='Open Conditions')
i_slowEMAlen = input.int (200, title='Slow EMA Length', step=1, minval=1, group='Open Conditions')
//INPUT: CLOSE
i_midClose = input.string('Opposite band', 'Close on crosses through middle EMA bands', tooltip='Selecting "Delayed bars inside" will closing positions after specified amount of candles close in between the middle EMA bands without breaking out', options=['Nearest band', 'Opposite band', 'Delayed bars inside'], group='Close Conditions')
i_numBars = input.int (4, 'Delayed close no. of bars', minval=1, maxval=10, step=1, group='Close Conditions')
s_useLele = input.bool (false, 'Close on Leledc bars', group='Close Conditions')
i_whichLele = input.string('First', 'Which Leledc bar?', options=['First', 'Second', 'Third', 'Fourth', 'Fifth'], group='Close Conditions')
s_useBBExtend = input.bool (false, 'Close on Bollinger Band exhaustion bars', tooltip='Bollinger Band Exhaustion bars are candles that close back inside the Bollinger Bands when RSI is overbought or oversold. Settings for both can be changed under the -Bollinger Bands Exhaustion Bar Settings- header.', group='Close Conditions')
i_whichBBext = input.string('First', 'Which BB exhaustion bar?', options=['First', 'Second', 'Third'], group='Close Conditions')
s_buySellClose = input.bool (false, 'Close on loss of Buy/Sell zone', group='Close Conditions')
s_whichBuySellBars = input.string('Inner', 'Which Buy/Sell zone?', options=['Inner', 'Outer'], group='Close Conditions')
//INPUT: COUNTER-TREND TRADES
s_needCTlong = input.bool (false, "Enable counter-trend trades: Long", tooltip='Does not work with "Enable default positioning: Short" selected', group="Counter Trade Settings")
i_CTlongType = input.string('Leledc', title = 'Trigger', options=['Leledc', 'BB Exhaustion'], group='Counter Trade Settings')
s_needCTshort = input.bool (false, "Enable counter-trend trades: Short", tooltip='Does not work with "Enable default positioning: Long" selected"', group="Counter Trade Settings")
i_CTshortType = input.string('Leledc', 'Trigger', options=['Leledc', 'BB Exhaustion'], group='Counter Trade Settings')
i_ctLeleBuySell = input.string('Inner', 'Leledc/BB must be outside which Buy/Sell zone to open', options=['Inner', 'Outer'], group="Counter Trade Settings")
i_CTlongCloseCond = input.string('Cross Top Middle Band','Closing conditions for counter-trend longs', tooltip='-Cross- type close conditions market close position on candle closes above selected region \n\n-Touch- type enable trailing limit orders that follow the selected region', options=['Cross Outer Buy Zone', 'Cross Inner Buy Zone', 'Touch Inner Buy Zone', 'Cross Bottom Middle Band', 'Touch Bottom Middle Band', 'Cross Top Middle Band', 'Touch Top Middle Band', 'Cross Inner Sell Zone', 'Touch Inner Sell Zone', 'Cross Outer Sell Zone', 'Touch Outer Sell Zone', 'First Leledc', 'First BB Exhaustion'], group='Counter Trade Settings')
i_CTshortCloseCond = input.string('First Leledc','Closing conditions for counter-trend shorts', tooltip='-Cross- type close conditions market close position on candle closes below selected region \n\n-Touch- type enable trailing limit orders that follow the selected region',options=['Cross Outer Sell Zone', 'Cross Inner Sell Zone', 'Touch Inner Sell Zone', 'Cross Top Middle Band', 'Touch Top Middle Band', 'Cross Bottom Middle Band', 'Touch Bottom Middle Band', 'Cross Inner Buy Zone', 'Touch Inner Buy Zone', 'Cross Outer Buy Zone', 'Touch Outer Buy Zone', 'First Leledc', 'First BB Exhaustion'], group='Counter Trade Settings')
i_CTlongSL = input.float (10, 'Flat stop-loss % for counter-trend longs', 0, 100, 0.1, 'Input 0 to disable stop-loss for counter-trend trades. Enabling stop-loss will not apply to middle band breakout, bounce, or default positional trades',group='Counter Trade Settings')
i_CTshortSL = input.float (10, 'Flat stop-loss % for counter-trend shorts', 0, 100, 0.1, 'Input 0 to disable stop-loss for counter-trend trades. Enabling stop-loss will not apply to middle band breakout, bounce, or default positional trades',group='Counter Trade Settings')
//INPUT: KELTNER BUY/SELL ZONES
s_keltnerBuySell = input.bool (false, 'Use Keltner channel multiples for "Buy/Sell Zones"',tooltip='Enables inputting custom multiples and a different/smoother calculation of "Buy/Sell Zones". Default calculation is a multiple of EMA band highs and lows', group='Keltner Buy/Sell Zones')
i_mult = input.float (5.0, "Outer Multiplier", tooltip='Only for "Buy/Sell Zones" calculated by Keltner channels', group='Keltner Buy/Sell Zones')
i_innerMult = input.float (3.0, "Inner Multiplier", tooltip='Only for "Buy/Sell Zones" calculated by Keltner channels', group='Keltner Buy/Sell Zones')
//INPUT: VOLATILITY SQUEEZE FILTER
s_squeezeFilter = input.bool (false, 'Filter out trades during BB-Keltner squeezes', group= 'BB-Keltner squeze')
i_bbCondition = input.string('At Least One', title='Bollinger Band Crossover Condition', options=['Both', 'At Least One'], group= 'BB-Keltner squeze')
i_bbSqueezeLength = input.int (30, minval=1, title='BB Length', group= 'BB-Keltner squeze')
i_ktSqueezeLength = input.int (18, minval=1, title='Keltner Length', group= 'BB-Keltner squeze')
s_useRes = input.bool (false, 'Use current timeframe', group= 'BB-Keltner squeze')
res = (s_useRes ? '' :input.timeframe('360', 'Resolution for BB-Keltner squeeze', group= 'BB-Keltner squeze'))
i_B2mult = input.float (2, minval=0.001, maxval=50, title='BB Standard Deviation', group= 'BB-Keltner squeze')
i_Kmult = input.float (1.5, title='Keltner Range', group= 'BB-Keltner squeze')
//INPUT: BOLLINGER BANDS EXHAUSTION BARS
i_BBlength = input.int (20, minval=1, title='Bollinger Bands SMA Period Length', group='Bollinger Bands Exhaustion Bar Settings')
i_BBmult = input.float (1.8, minval=0.001, maxval=50, title='Bollinger Bands Standard Deviation', group='Bollinger Bands Exhaustion Bar Settings')
i_RSIlength = input.int (8, minval=1, step=1, title='RSI Period Length', group='Bollinger Bands Exhaustion Bar Settings')
i_RSIos = input.int (30, minval=0, maxval=50, step=1,title='RSI Oversold Value', group='Bollinger Bands Exhaustion Bar Settings')
i_RSIob = input.int (70, minval=50, maxval=100, step=1, title='RSI Overbought value', group='Bollinger Bands Exhaustion Bar Settings')
i_srcBB = input.source(close, title='Source', group='Bollinger Bands Exhaustion Bar Settings')
//INPUT: LELEDC
i_leleVol = input.bool (false, 'Require Volume breakout for Leledc bars', group='Leledc Exhaustion Bar Settings')
i_volMult = input.float (1.5,'Volume Multiplier', 0.1,20,0.1, group='Leledc Exhaustion Bar Settings')
i_majLen = input.int (30, 'Highest / Lowest', group='Leledc Exhaustion Bar Settings')
i_majQual = input.int (6, 'Bar count no', group='Leledc Exhaustion Bar Settings')
i_closeVal = input.int (4, 'Close', group='Leledc Exhaustion Bar Settings')
i_bindexSindex = input.int (1, 'bindexSindex', group='Leledc Exhaustion Bar Settings')
//INPUT: VISUAL ELEMENTS
s_trendColor = input.bool (false, 'Enable Trend Bar Color', tooltip='Color bars green when above mid bands, red when below, and gray when inside. Dark green and dark red bars signal a position is kept open from the delayed close settings.', group='Visual Elements')
s_showBuySell = input.bool (true, 'Show "Buy/Sell Zones"', group='Visual Elements')
s_showEMA = input.bool (false, 'Show EMA', group='Visual Elements')
s_showMiddleBands = input.bool (true, 'Show middle EMA bands', group='Visual Elements')
s_showSlowEMA = input.bool (false, 'Show Slow EMA', group='Visual Elements')
s_showMaj = input.bool (true, 'Show Leledc Exhausion Bars', group='Visual Elements')
s_switch1 = input.bool (true, 'Enable Bollinger Bands exhaustion bar coloring', group='Visual Elements')
s_switch2 = input.bool (false, 'Enable Bollinger bands exhaustion bar background coloring', tooltip='Enabling this can help visualize when dialing in Bollinger Bands and RSI settings', group='Visual Elements')
s_colorBuySellBars = input.bool (false, 'Enable Buy/Sell zone failure bar coloring', group='Visual Elements')
s_squeezeBG = input.bool (true, 'Enable volatility squeeze (BB-Keltner) background coloring', group='Visual Elements')
//}
//VARIABLES: EMA and slowEMA CALC {
EMA = ta.ema(close, i_EMAlength)
slowEMA = ta.ema(close, i_slowEMAlen)
plot(s_showSlowEMA ? slowEMA : na)
//}
//*****************************
// SlumdogTrader's Bollinger Bands + RSI Double Strategy - Profit Trailer
//====================================================================================================//{
//BB VARIABLES
BBbasis = ta.sma(i_srcBB, i_BBlength)
BBdev = i_BBmult * ta.stdev(i_srcBB, i_BBlength)
BBupper = BBbasis + BBdev
BBlower = BBbasis - BBdev
//RSI VARIABLES
vrsi = ta.rsi(i_srcBB, i_RSIlength)
RSIoverSold = vrsi < i_RSIos
RSIoverBought = vrsi > i_RSIob
//BB EXHAUSTION BAR COLOR VARIABLE
OSOBcolor =
RSIoverBought and i_srcBB[1] > BBupper and i_srcBB < BBupper ? color.yellow :
RSIoverSold and i_srcBB[1] < BBlower and i_srcBB > BBlower ? color.blue :
na
//====================================================================================================//
//}
//KELTNER SELL ZONE {
rangema = s_keltnerBuySell ? ta.rma(high - low, i_EMAlength) : 0.0
kt_outersell(_ma) =>
upper = EMA + _ma * i_mult
upper
kt_innersell(_ma) =>
inner_upper = EMA + _ma * i_innerMult
inner_upper
kt_outerbuy(_ma) =>
lower = EMA - _ma * i_mult
lower
kt_innerbuy(_ma) =>
inner_lower = EMA - _ma * i_innerMult
inner_lower
//}
//*****************************
// BB-Keltner Squeeze-FVBO-2.0
// Modified by Juan C for FVBO Strategy, some source code from Trader-Elisa
//====================================================================================================//{
//VARIABLES FOR HTF SOURCES
rp_security(_sym, _res, _src) =>
request.security(_sym, _res, _src[barstate.ishistory ? 0 : 1], gaps=barmerge.gaps_on)
srcClose = rp_security(syminfo.tickerid, res, close)
srcHigh = rp_security(syminfo.tickerid, res, high)
srcLow = rp_security(syminfo.tickerid, res, low)
//SQUEEZE BOLLINGER BANDS
B2basis = ta.sma(srcClose, i_bbSqueezeLength)
B2dev = i_B2mult * ta.stdev(srcClose, i_bbSqueezeLength)
B2upper = B2basis + B2dev
B2lower = B2basis - B2dev
//SQUEEZE KELTNER CHANNELS
Kma = ta.ema(srcClose, i_ktSqueezeLength)
Krange = srcHigh - srcLow
Krangema = ta.ema(Krange, i_ktSqueezeLength)
Kupper = Kma + Krangema * i_Kmult
Klower = Kma - Krangema * i_Kmult
//DEFINE SQUEEZE
var bool squeezing = false
if s_squeezeFilter
if i_bbCondition == 'Both' and s_useRes
squeezing := B2upper <= Kupper and B2lower >= Klower ? true : false
squeezing
else if i_bbCondition == 'At Least One' and s_useRes
squeezing := B2upper <= Kupper or B2lower >= Klower ? true : false
squeezing
else if i_bbCondition == 'Both'
squeezing :=
B2upper[ta.barssince(not srcClose == barstate.isrealtime)] <= Kupper[ta.barssince(not srcClose == barstate.isrealtime)] and
B2lower[ta.barssince(not srcClose == barstate.isrealtime)] >= Klower[ta.barssince(not srcClose == barstate.isrealtime)] ? true : false
squeezing
else
squeezing :=
B2upper[ta.barssince(not srcClose == barstate.isrealtime)] <= Kupper[ta.barssince(not srcClose == barstate.isrealtime)] or
B2lower[ta.barssince(not srcClose == barstate.isrealtime)] >= Klower[ta.barssince(not srcClose == barstate.isrealtime)] ? true : false
squeezing
//VISUAL
cross_over_color = (squeezing ? color.new(color.aqua, 90) : na)
bgcolor(s_squeezeBG ? cross_over_color : na)
bgcolor(s_switch2 ? color.new(OSOBcolor,70) : na)
//}
//*****************************
// © Joy_Bangla Leledc Exhaustion V4
//====================================================================================================//{
//min = input(false, 'Minor Leledc Exhaustion Bar :: Show')
//min_qual = input(5, 'Minor Leledc Exhausion Bar :: Bar count no')
//min_len = input(5, 'Minor Leledc Exhausion Bar :: Bar count no')
leleVol = volume > ta.sma(volume,100)*i_volMult
lele(qual, len) =>
bindex = 0
sindex = 0
bindex := nz(bindex[i_bindexSindex], 0)
sindex := nz(sindex[i_bindexSindex], 0)
ret = 0
if close > close[i_closeVal]
bindex += 1
bindex
if close < close[i_closeVal]
sindex += 1
sindex
if i_leleVol and not leleVol
ret := 0
ret
else
if bindex > qual and close < open and high >= ta.highest(high, len)
bindex := 0
ret := -1
ret
if sindex > qual and close > open and low <= ta.lowest(low, len)
sindex := 0
ret := 1
ret
return_1 = ret
return_1
major = lele(i_majQual, i_majLen)
//minor = lele(min_qual, min_len)
plotchar(s_showMaj ? major == -1 ? high : na : na, char='•', location=location.absolute, color=color.new(color.red, 0), size=size.small)
plotchar(s_showMaj ? major == 1 ? low : na : na, char='•', location=location.absolute, color=color.new(color.lime, 0), size=size.small)
//plotchar(min ? minor == 1 ? high : na : na, char='x', location=location.absolute, color=color.new(color.red, 0), size=size.small)
//plotchar(min ? minor == -1 ? low : na : na, char='x', location=location.absolute, color=color.new(color.lime, 0), size=size.small)
//leledcMajorBullish = major == 1 ? low : na
//leledcMajorBearish = major == -1 ? high : na
//leledcMinorBullish = minor == 1 ? low : na
//leledcMinorBearish = minor == -1 ? high : na
//==============================================//
//alertcondition(leledcMajorBullish, title='Major Bullish Leledc', message='Major Bullish Leledc')
//alertcondition(leledcMajorBearish, title='Major Bearish Leledc', message='Major Bearish Leledc')
//alertcondition(leledcMinorBullish, title='Minor Bullish Leledc', message='Minor Bullish Leledc')
//alertcondition(leledcMinorBearish, title='Minor Bearish Leledc', message='Minor Bearish Leledc')
//====================================================================================================//
//}
//*****************************
// © VishvaP 34 EMA Bands v2
//====================================================================================================//{
//BUILD EMA MIDDLE BANDS
highShortEMA = ta.ema(high, i_EMAlength)
lowShortEMA = ta.ema(low, i_EMAlength)
middleBandTop = (highShortEMA - EMA) * i_topMBmult + EMA
middleBandBot = (lowShortEMA - EMA) * i_botMBmult + EMA
//==============================================//
//1D Bands [Not Used]
//bandsHigh = highShortEMA * math.phi
//bandsLow = lowShortEMA * math.rphi
//==============================================//
//INNER BUY/SELL ZONES
shortbandsHigh = s_keltnerBuySell ? kt_innersell(rangema) : ((highShortEMA - EMA) * math.phi * i_topMBmult) * math.pi + EMA
shortbandsLow = s_keltnerBuySell ? kt_innerbuy(rangema) : (-(EMA - lowShortEMA) * math.phi * i_botMBmult) * math.pi + EMA
//SMOOTH INNER
shortbandsHighEMA = ta.wma(shortbandsHigh, 8)
shortbandsLowEMA = ta.wma(shortbandsLow, 8)
//==============================================//
//OUTER BUY/SELL ZONES
phiExtensionHigh = s_keltnerBuySell ? kt_outersell(rangema) : ((highShortEMA - EMA) * math.phi * i_topMBmult) * (math.phi + 4) + EMA
phiExtensionLow = s_keltnerBuySell ? kt_outerbuy(rangema) : (-(EMA - lowShortEMA) * math.phi * i_botMBmult) * (math.phi + 4) + EMA
//SMOOTH OUTER
phiExtensionHighEMA = ta.wma(phiExtensionHigh, 8)
phiExtensionLowEMA = ta.wma(phiExtensionLow, 8)
//==============================================//
//PLOT MIDDLE BANDS AND EMA
highP1 = plot(s_showMiddleBands ? middleBandTop : na, color = color.new(color.blue, 100), title = "Top median zone")
lowP1 = plot(s_showMiddleBands ? middleBandBot : na, color = color.new(color.blue, 100), title = "Bottom median zone")
plot(s_showEMA ? EMA : na, color = color.new(color.gray, 0), title = "EMA")
//1D bands [not used]
//highP2 = plot(bandsHigh)
//lowP2 = plot(bandsLow)
//PLOT BUY/SELL ZONES
highP3 = plot(s_showBuySell ? shortbandsHighEMA : na, color = color.new(color.yellow, 100), title = "Lower sell zone")
lowP3 = plot(s_showBuySell ? shortbandsLowEMA : na, color = color.new(color.teal, 100), title = "Higher buy zone")
phiPlotHigh = plot(s_showBuySell ? phiExtensionHighEMA : na, color = color.new(color.red, 100), title = "Top sell zone")
phiPlotLow = plot(s_showBuySell ? phiExtensionLowEMA : na, color = color.new(color.green, 100), title = "Bottom buy zone")
//==============================================//
//BUY/SELL ZONE AND MIDDLE BAND COLOR FILLS
fill(phiPlotHigh, highP3, color.new(color.red, 85), title = "Sell zone")
fill(lowP3, phiPlotLow, color.new(color.green, 85), title = "Buy zone")
fill(highP1, lowP1, color.new(color.gray, 70), title = "Median zone")
//====================================================================================================//
//}
//ASSIGN BANDS FOR COUNTERTREND ENTRIES {
float CTbandTop = na
float CTbandBottom = na
if i_ctLeleBuySell == 'Inner'
CTbandTop := shortbandsHighEMA
CTbandBottom := shortbandsLowEMA
else
CTbandTop := phiExtensionHighEMA
CTbandBottom := phiExtensionLowEMA
//}
//BUILD VARIABLES FOR CROSSES {
crossUpTopMB = open < middleBandTop and close > middleBandTop
wiggleUpTopMB = open > middleBandTop and close > middleBandTop and close[1] <= middleBandTop[1]
crossDownTopMB = open > middleBandTop and close < middleBandTop
wiggleDownTopMB = open < middleBandTop and close < middleBandTop and close[1] >= middleBandTop[1]
crossUpBotMB = open < middleBandBot and close > middleBandBot
wiggleUpBotMB = open > middleBandBot and close > middleBandBot and close[1] <= middleBandBot[1]
crossDownBotMB = open > middleBandBot and close < middleBandBot
wiggleDownBotMB = open < middleBandBot and close < middleBandBot and close[1] >= middleBandBot[1]
crossUpBotInnerRB = open < shortbandsLowEMA and close > shortbandsLowEMA
wiggleUpBotInnerRB = open > shortbandsLowEMA and close > shortbandsLowEMA and close[1] <= shortbandsLowEMA[1]
crossUpBotOuterRB = open < phiExtensionLowEMA and close > phiExtensionLowEMA
wiggleUpBotOuterRB = open > phiExtensionLowEMA and close > phiExtensionLowEMA and close[1] <= phiExtensionLowEMA[1]
crossUpTopInnerRB = open < shortbandsHighEMA and close > shortbandsHighEMA
wiggleUpTopInnerRB = open > shortbandsHighEMA and close > shortbandsHighEMA and close[1] <= shortbandsHighEMA[1]
crossUpTopOuterRB = open < phiExtensionHighEMA and close > phiExtensionHighEMA
wiggleUpTopOuterRB = open > phiExtensionHighEMA and close > phiExtensionHighEMA and close[1] <= phiExtensionHighEMA[1]
crossDownBotInnerRB = open > shortbandsLowEMA and close < shortbandsLowEMA
wiggleDownBotInnerRB = open < shortbandsLowEMA and close < shortbandsLowEMA and close[1] >= shortbandsLowEMA[1]
crossDownBotOuterRB = open > phiExtensionLowEMA and close < phiExtensionLowEMA
wiggleDownBotOuterRB = open < phiExtensionLowEMA and close < phiExtensionLowEMA and close[1] >= phiExtensionLowEMA[1]
crossDownTopInnerRB = open > shortbandsHighEMA and close < shortbandsHighEMA
wiggleDownTopInnerRB = open < shortbandsHighEMA and close < shortbandsHighEMA and close[1] >= shortbandsHighEMA[1]
crossDownTopOuterRB = open > phiExtensionHighEMA and close < phiExtensionHighEMA
wiggleDownTopOuterRB = open < phiExtensionHighEMA and close < phiExtensionHighEMA and close[1] >= phiExtensionHighEMA[1]
//}
//VARIABLES FOR BOUNCES {
longBounce =
not s_longBounce ? false :
s_squeezeFilter ? open > middleBandTop and close > middleBandTop and low < middleBandTop and squeezing == false :
open > middleBandTop and close > middleBandTop and low < middleBandTop
shortBounce =
not s_shortBounce ? false :
s_squeezeFilter ? open < middleBandBot and close < middleBandBot and high > middleBandBot and squeezing == false :
open < middleBandBot and close < middleBandBot and high > middleBandBot
//}
//BUILD VARIABLES FOR CLOSING CONDITIONS {
CTlongCloseCond =
i_CTlongCloseCond == 'Cross Inner Sell Zone' ? (crossUpTopInnerRB or wiggleUpTopInnerRB) :
i_CTlongCloseCond == 'Cross Outer Sell Zone' ? (crossUpTopOuterRB or wiggleUpTopOuterRB) :
i_CTlongCloseCond == 'Cross Top Middle Band' ? (crossUpTopMB or wiggleUpTopMB) :
i_CTlongCloseCond == 'Cross Bottom Middle Band' ? (crossUpBotMB or wiggleUpBotMB) :
i_CTlongCloseCond == 'Cross Inner Buy Zone' ? (crossUpBotInnerRB or wiggleUpBotInnerRB) :
i_CTlongCloseCond == 'Cross Outer Buy Zone' ? (crossUpBotOuterRB or crossUpBotOuterRB) :
i_CTlongCloseCond == 'First Leledc' ? major == -1 :
i_CTlongCloseCond == 'First BB Exhaustion' ? OSOBcolor == color.yellow :
na
CTlongTP =
i_CTlongCloseCond == 'Touch Inner Buy Zone' ? shortbandsLowEMA :
i_CTlongCloseCond == 'Touch Top Middle Band' ? middleBandTop :
i_CTlongCloseCond == 'Touch Bottom Middle Band' ? middleBandBot :
i_CTlongCloseCond == 'Touch Inner Sell Zone' ? shortbandsHighEMA :
i_CTlongCloseCond == 'Touch Outer Sell Zone' ? phiExtensionHighEMA :
na
CTshortCloseCond =
i_CTshortCloseCond == 'Cross Inner Buy Zone' ? (crossDownBotInnerRB or wiggleDownBotInnerRB) :
i_CTshortCloseCond == 'Cross Outer Buy Zone' ? (crossDownBotOuterRB or wiggleDownBotOuterRB) :
i_CTshortCloseCond == 'Cross Bottom Middle Band' ? (crossDownBotMB or wiggleDownBotMB) :
i_CTshortCloseCond == 'Cross Top Middle Band' ? (crossDownTopMB or wiggleDownTopMB) :
i_CTshortCloseCond == 'Cross Inner Sell Zone' ? (crossDownTopInnerRB or wiggleDownTopInnerRB) :
i_CTshortCloseCond == 'Cross Outer Sell Zone' ? (crossDownTopOuterRB or crossDownTopOuterRB) :
i_CTshortCloseCond == 'First Leledc' ? major == 1 :
i_CTshortCloseCond == 'First BB Exhaustion' ? OSOBcolor == color.blue :
na
CTshortTP =
i_CTshortCloseCond == 'Touch Inner Sell Zone' ? shortbandsHighEMA :
i_CTshortCloseCond == 'Touch Bottom Middle Band' ? middleBandBot :
i_CTshortCloseCond == 'Touch Top Middle Band' ? middleBandTop :
i_CTshortCloseCond == 'Touch Inner Buy Zone' ? shortbandsLowEMA :
i_CTshortCloseCond == 'Touch Outer Buy Zone' ? phiExtensionLowEMA :
na
shortMidBreak =
s_squeezeFilter ? (crossDownBotMB or wiggleDownBotMB) and squeezing == false :
crossDownBotMB or wiggleDownBotMB
longMidBreak =
s_squeezeFilter ? (crossUpTopMB or wiggleUpTopMB) and squeezing == false :
crossUpTopMB or wiggleUpTopMB
//}
//BASIC STRATEGY POSITIONS OPEN
//LONGS OPEN {
if s_needLong
if s_useSlowEMA
if longMidBreak and close > slowEMA and open < middleBandTop
strategy.close('Short', comment='Close Short')
strategy.close('Counter Trend Short', comment='Close CT Short')
strategy.close('Default Short', comment='Close Default Short')
strategy.entry('Long', strategy.long)
else if longMidBreak
strategy.close('Short', comment='Close Short')
strategy.close('Counter Trend Short', comment='Close CT Short')
strategy.close('Default Short', comment='Close Default Short')
strategy.entry('Long', strategy.long)
if strategy.position_size == 0 and longBounce
if s_useSlowEMA
if close > slowEMA
strategy.close('Short', comment='Close Short')
strategy.close('Counter Trend Short', comment='Close CT Short')
strategy.close('Default Short', comment='Close Default Short')
strategy.entry('Long', strategy.long)
else
strategy.close('Short', comment='Close Short')
strategy.close('Counter Trend Short', comment='Close CT Short')
strategy.close('Default Short', comment='Close Default Short')
strategy.entry('Long', strategy.long)
//}
//SHORTS OPEN {
if s_needShort
if s_useSlowEMA
if shortMidBreak and close < slowEMA and open > middleBandBot
strategy.close('Long', comment='Close Long')
strategy.close('Counter Trend Long', comment='Close CT Long')
strategy.close('Default Long', comment='Close Default Long')
strategy.entry('Short', strategy.short)
else if shortMidBreak
strategy.close('Long', comment='Close Long')
strategy.close('Counter Trend Long', comment='Close CT Long')
strategy.close('Default Long', comment='Close Default Long')
strategy.entry('Short', strategy.short)
if strategy.position_size == 0 and shortBounce
if s_useSlowEMA
if close < slowEMA
strategy.close('Long', comment='Close Long')
strategy.close('Counter Trend Long', comment='Close CT Long')
strategy.close('Default Long', comment='Close Default Long')
strategy.entry('Short', strategy.short)
else
strategy.close('Long', comment='Close Long')
strategy.close('Counter Trend Long', comment='Close CT Long')
strategy.close('Default Long', comment='Close Default Long')
strategy.entry('Short', strategy.short)
//}
//COUNT LELEDC BARS BETWEEN CURRENT BAR AND POSITION OPEN {
//VARIABLES
int countLongLele = 0
int countShortLele = 0
int numLele = switch i_whichLele
'First' => 1
'Second' => 2
'Third' => 3
'Fourth' => 4
'Fifth' => 5
int i = 0
//COUNT LELES FOR LONGS
if strategy.position_size > 0
if s_useLele and numLele > 1
while i <= 200
if strategy.position_size[i] <= 0
break
if bar_index[i] == 0
break
if major[i] == -1
countLongLele += 1
if countLongLele == numLele
break
i += 1
//COUNT LELES FOR SHORTS
if strategy.position_size < 0
if s_useLele and numLele > 1
while i <= 200
if strategy.position_size[i] >= 0
break
if bar_index[i] == 0
break
if major[i] == 1
countShortLele += 1
if countShortLele == numLele
break
i += 1
//}
//COUNT BB EXHAUSTION BARS BETWEEN CURRENT BAR AND POSITION OPEN {
//VARIABLES
int countLongBBs = 0
int countShortBBs = 0
int numBBs = switch i_whichBBext
'First' => 1
'Second' => 2
'Third' => 3
int n = 0
//COUNT BB BARS FOR LONGS
if strategy.position_size > 0
if s_useBBExtend and numBBs > 1
while n <= 200
if strategy.position_size[n] <= 0
break
if bar_index[n] == 0
break
if OSOBcolor[n] == color.yellow
countLongBBs += 1
if countLongBBs == numBBs
break
n+= 1
//COUNT BB BARS FOR SHORTS
if strategy.position_size < 0
if s_useBBExtend and numBBs > 1
while n <= 200
if strategy.position_size[n] >= 0
break
if bar_index[n] == 0
break
if OSOBcolor[n] == color.blue
countShortBBs += 1
if countShortBBs == numBBs
break
n+= 1
//}
//VARIABLES: CONDITIONS OF LOSS OF BUY/SELL ZONES {
var bool crossUpRB = false
var bool wiggleUpRB = false
var bool crossDownRB = false
var bool wiggleDownRB = false
if s_whichBuySellBars == 'Inner'
crossUpRB := crossUpBotInnerRB
wiggleUpRB := wiggleUpBotInnerRB
crossDownRB := crossDownTopInnerRB
wiggleDownRB := wiggleDownTopInnerRB
else
crossUpRB := crossUpBotOuterRB
wiggleUpRB := wiggleUpBotOuterRB
crossDownRB := crossDownTopOuterRB
wiggleDownRB := wiggleDownTopOuterRB
//}
//VARIABLES: reverBarColor {
reverBarColor = crossDownRB or (wiggleDownRB and not crossDownRB[1]) ? color.orange :
crossUpRB or (wiggleUpRB and not crossUpRB[1]) ? color.purple :
na
//}
//FUNCTION: isAllMid() {
//return true after specified number of bars (i_numBars) closes inside the mid bands but no breakout
inMid = close > middleBandBot and close < middleBandTop and open > middleBandBot and open < middleBandTop
isAllMid() =>
AllMid = true
for t = 0 to i_numBars by 1
if longMidBreak[t] or shortMidBreak[t]
AllMid := false
AllMid
//}
//BASIC STRATEGY POSITIONS CLOSE
//LONGS CLOSE {
if strategy.position_size > 0
if s_buySellClose
if reverBarColor == color.orange
strategy.close('Long', comment = 'Close Long')
if s_useBBExtend and numBBs == 1
if OSOBcolor == color.yellow
strategy.close('Long', comment = 'Close Long')
if s_needCTshort and i_CTshortType == 'BB Exhaustion'
if open > CTbandTop
strategy.close('Long', comment='Close Long')
strategy.close('Counter Trend Long', comment='Close CT Long')
strategy.close('Default Long', comment='Close Default Long')
strategy.entry('Counter Trend Short', comment = 'CT Short', direction=strategy.short)
if s_useBBExtend and numBBs > 1
if countLongBBs == numBBs
strategy.close('Long', comment = 'Close Long')
if s_needCTshort and i_CTshortType == 'BB Exhaustion'
if open > CTbandTop
strategy.close('Long', comment='Close Long')
strategy.close('Counter Trend Long', comment='Close CT Long')
strategy.close('Default Long', comment='Close Default Long')
strategy.entry('Counter Trend Short', comment = 'CT Short', direction=strategy.short)
if s_useLele and numLele == 1
if major == -1
strategy.close('Long', comment = 'Close Long')
if s_needCTshort and i_CTshortType == 'Leledc'
if high > CTbandTop
strategy.close('Long', comment='Close Long')
strategy.close('Counter Trend Long', comment='Close CT Long')
strategy.close('Default Long', comment='Close Default Long')
strategy.entry('Counter Trend Short', comment = 'CT Short', direction=strategy.short)
if s_useLele and numLele > 1
if countLongLele == numLele
strategy.close('Long', comment = 'Close Long')
if s_needCTshort and i_CTshortType == 'Leledc'
if high > CTbandTop
strategy.close('Long', comment='Close Long')
strategy.close('Counter Trend Long', comment='Close CT Long')
strategy.close('Default Long', comment='Close Default Long')
strategy.entry('Counter Trend Short', comment = 'CT Short', direction=strategy.short)
if i_midClose == 'Nearest band'
if crossDownTopMB or wiggleDownTopMB
strategy.close('Long', comment = 'Close Long')
if i_midClose == 'Opposite band'
if crossDownBotMB or wiggleDownBotMB
strategy.close('Long', comment = 'Close Long')
if i_midClose == 'Delayed bars inside'
if crossDownBotMB or wiggleDownBotMB
strategy.close('Long', comment = 'Close Long')
if isAllMid()
if open[i_numBars] > middleBandTop and close[i_numBars] < middleBandTop and inMid
strategy.close('Long', comment = 'Close Long')
//}
//SHORTS CLOSE {
if strategy.position_size < 0
if s_buySellClose
if reverBarColor == color.purple
strategy.close('Short', comment = 'Close Short')
if s_useBBExtend and numBBs == 1
if OSOBcolor == color.blue
strategy.close('Short', comment = 'Close Short')
if s_needCTlong and i_CTlongType == 'BB Exhaustion'
if open < CTbandBottom
strategy.close('Short', comment='Close Short')
strategy.close('Counter Trend Short', comment='Close CT Short')
strategy.close('Default Short', comment='Close Default Short')
strategy.entry('Counter Trend Long', comment = 'CT Long', direction=strategy.long)
if s_useBBExtend and numBBs > 1
if countShortBBs == numBBs
strategy.close('Short', comment = 'Close Short')
if s_needCTlong and i_CTlongType == 'BB Exhaustion'
if open < CTbandBottom
strategy.close('Short', comment='Close Short')
strategy.close('Counter Trend Short', comment='Close CT Short')
strategy.close('Default Short', comment='Close Default Short')
strategy.entry(id='Counter Trend Long', comment = 'CT Long', direction=strategy.long)
if s_useLele and numLele == 1
if major == 1
strategy.close('Short', comment = 'Close Short')
if s_needCTlong and i_CTlongType == 'Leledc'
if low < CTbandBottom
strategy.close('Short', comment='Close Short')
strategy.close('Counter Trend Short', comment='Close CT Short')
strategy.close('Default Short', comment='Close Default Short')
strategy.entry(id='Counter Trend Long', comment= 'CT Long', direction=strategy.long)
if s_useLele and numLele > 1
if countShortLele == numLele
strategy.close('Short', comment = 'Close Short')
if s_needCTlong and i_CTlongType == 'Leledc'
if low < CTbandBottom
strategy.close('Short', comment='Close Short')
strategy.close('Counter Trend Short', comment='Close CT Short')
strategy.close('Default Short', comment='Close Default Short')
strategy.entry(id='Counter Trend Long', comment= 'CT Long', direction=strategy.long)
if i_midClose == 'Nearest band'
if crossUpBotMB or wiggleUpBotMB
strategy.close('Short', comment = 'Close Short')
if i_midClose == 'Opposite band'
if crossUpTopMB or wiggleUpTopMB
strategy.close('Short', comment = 'Close Short')
if i_midClose == 'Delayed bars inside'
if crossUpTopMB or wiggleUpTopMB
strategy.close('Short', comment = 'Close Short')
if isAllMid()
if open[i_numBars] < middleBandBot and close[i_numBars] > middleBandBot and inMid
strategy.close('Short', comment = 'Close Short')
//}
//COUNTER TREND STRATEGY POSITIONS OPEN AND CLOSE {
//VARIABLES FOR CT STOP LOSSES
CTlongSL = strategy.position_avg_price * (1 - i_CTlongSL / 100)
CTshortSL = strategy.position_avg_price * (1 + i_CTshortSL / 100)
//CT LONGS OPEN
if s_needCTlong and strategy.position_size == 0 and (not s_squeezeFilter or not squeezing)
if i_CTlongType == 'Leledc'
if major == 1
if low < CTbandBottom
strategy.close('Short', comment='Close Short')
strategy.close('Counter Trend Short', comment='Close CT Short')
strategy.close('Default Short', comment='Close Default Short')
strategy.entry('Counter Trend Long', comment = 'CT Long', direction = strategy.long)
else
if OSOBcolor == color.blue
strategy.close('Short', comment='Close Short')
strategy.close('Counter Trend Short', comment='Close CT Short')
strategy.close('Default Short', comment='Close Default Short')
strategy.entry('Counter Trend Long', comment = 'CT Long', direction = strategy.long)
//CT LONGS CLOSED
if strategy.position_size > 0 and strategy.opentrades.entry_id(strategy.opentrades - 1) == 'Counter Trend Long'
if i_CTlongSL > 0
if na(CTlongTP)
strategy.exit(id='Counter Trend Long', stop=CTlongSL, comment = 'CT Long SL')
else
strategy.exit(id='Counter Trend Long', stop=CTlongSL, limit=CTlongTP, comment = 'CT Long TP/SL')
else if i_CTlongSL == 0
strategy.exit(id='Counter Trend Long', limit=CTlongTP, comment = 'CT Long TP')
if CTlongCloseCond
strategy.close(id='Counter Trend Long', comment = 'Close CT Long')
//CT SHORTS OPEN
if s_needCTshort and strategy.position_size == 0 and (not s_squeezeFilter or not squeezing)
if i_CTshortType == 'Leledc'
if major == -1
if high > CTbandTop
strategy.close('Long', comment='Close Long')
strategy.close('Counter Trend Long', comment='Close CT Long')
strategy.close('Default Long', comment='Close Default Long')
strategy.entry('Counter Trend Short', comment = 'CT Short', direction=strategy.short)
else
if OSOBcolor == color.yellow
strategy.close('Long', comment='Close Long')
strategy.close('Counter Trend Long', comment='Close CT Long')
strategy.close('Default Long', comment='Close Default Long')
strategy.entry('Counter Trend Short', comment= 'CT Short', direction=strategy.short)
//CT SHORTS CLOSE
if strategy.position_size < 0 and strategy.opentrades.entry_id(strategy.opentrades - 1) == 'Counter Trend Short'
if i_CTshortSL > 0
if na(CTshortTP)
strategy.exit(id='Counter Trend Short', stop=CTshortSL, comment = 'CT Short SL')
else
strategy.exit(id='Counter Trend Short', stop=CTshortSL, limit=CTshortTP, comment = 'CT Short TP/SL')
else if i_CTshortSL == 0
strategy.exit(id='Counter Trend Short', limit=CTshortTP, comment = 'CT Short TP')
if CTshortCloseCond
strategy.close(id='Counter Trend Short', comment = "Close CT Short")
//}
//DEFAULT POSITIONING STRATEGY OPENS {
if s_alwaysLong and not s_alwaysShort and strategy.position_size == 0
if s_useSlowEMA
if close > slowEMA
strategy.entry(id='Default Long', comment = 'Default Long', direction=strategy.long)
else
strategy.entry(id='Default Long', comment='Default Long', direction=strategy.long)
if s_alwaysShort and not s_alwaysLong and strategy.position_size == 0
if s_useSlowEMA
if close < slowEMA
strategy.entry(id='Default Short', comment = 'Default Short', direction=strategy.short)
else
strategy.entry(id='Default Short', comment='Default Short', direction=strategy.short)
//}
//SET BAR COLORS {
var colorBar = color.new(color.white, 50)
if s_trendColor
if s_switch1
if s_colorBuySellBars
if reverBarColor == color.purple or reverBarColor == color.orange
colorBar := reverBarColor
else if OSOBcolor == color.yellow or OSOBcolor == color.blue
colorBar := OSOBcolor
else if close > middleBandTop
if (s_alwaysShort or s_needCTshort) and strategy.position_size < 0
colorBar := color.new(color.red, 0)
else
colorBar := color.new(color.green, 0)
else if close < middleBandBot
if (s_alwaysLong or s_needCTlong) and strategy.position_size > 0
colorBar := color.new(color.green, 0)
else
colorBar := color.new(color.red, 0)
else if strategy.position_size > 0 and (i_midClose == 'Delayed bars inside' or i_midClose == 'Opposite band')
colorBar := color.new(#0a6136, 20)
else if strategy.position_size < 0 and (i_midClose == 'Delayed bars inside' or i_midClose == 'Opposite band')
colorBar := color.new(#600008, 20)
else
colorBar := color.new(color.gray, 0)
else
if OSOBcolor == color.yellow or OSOBcolor == color.blue
colorBar := OSOBcolor
else if close > middleBandTop
if (s_alwaysShort or s_needCTshort) and strategy.position_size < 0
colorBar := color.new(color.red, 0)
else
colorBar := color.new(color.green, 0)
else if close < middleBandBot
if (s_alwaysLong or s_needCTlong) and strategy.position_size > 0
colorBar := color.new(color.green, 0)
else
colorBar := color.new(color.red, 0)
else if strategy.position_size > 0 and (i_midClose == 'Delayed bars inside' or i_midClose == 'Opposite band')
colorBar := color.new(#0a6136, 20)
else if strategy.position_size < 0 and (i_midClose == 'Delayed bars inside' or i_midClose == 'Opposite band')
colorBar := color.new(#600008, 20)
else
colorBar := color.new(color.gray, 0)
else if s_colorBuySellBars
if reverBarColor == color.purple or reverBarColor == color.orange
colorBar := reverBarColor
else if close > middleBandTop
if (s_alwaysShort or s_needCTshort) and strategy.position_size < 0
colorBar := color.new(color.red, 0)
else
colorBar := color.new(color.green, 0)
else if close < middleBandBot
if (s_alwaysLong or s_needCTlong) and strategy.position_size > 0
colorBar := color.new(color.green, 0)
else
colorBar := color.new(color.red, 0)
else if strategy.position_size > 0 and (i_midClose == 'Delayed bars inside' or i_midClose == 'Opposite band')
colorBar := color.new(#0a6136, 20)
else if strategy.position_size < 0 and (i_midClose == 'Delayed bars inside' or i_midClose == 'Opposite band')
colorBar := color.new(#600008, 20)
else
colorBar := color.new(color.gray, 0)
else
if close > middleBandTop
if (s_alwaysShort or s_needCTshort) and strategy.position_size < 0
colorBar := color.new(color.red, 0)
else
colorBar := color.new(color.green, 0)
else if close < middleBandBot
if (s_alwaysLong or s_needCTlong) and strategy.position_size > 0
colorBar := color.new(color.green, 0)
else
colorBar := color.new(color.red, 0)
else if strategy.position_size > 0 and (i_midClose == 'Delayed bars inside' or i_midClose == 'Opposite band')
colorBar := color.new(#0a6136, 20)
else if strategy.position_size < 0 and (i_midClose == 'Delayed bars inside' or i_midClose == 'Opposite band')
colorBar := color.new(#600008, 20)
else
colorBar := color.new(color.gray, 0)
else if s_switch1
if s_colorBuySellBars
if reverBarColor == color.purple or reverBarColor == color.orange
colorBar := reverBarColor
else if OSOBcolor == color.yellow or OSOBcolor == color.blue
colorBar := OSOBcolor
else
colorBar := na
else
if OSOBcolor == color.yellow or OSOBcolor == color.blue
colorBar := OSOBcolor
else
colorBar := na
else if s_colorBuySellBars
if reverBarColor == color.purple or reverBarColor == color.orange
colorBar := reverBarColor
else
colorBar := na
else
colorBar := na
barcolor(colorBar)
//} |
Mean reversion | https://www.tradingview.com/script/SzsLYlho-Mean-reversion/ | stormis | https://www.tradingview.com/u/stormis/ | 92 | 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/
// © stormis
// Based on strategy by hackertrader (original idea by QuantpT)
//@version=5
strategy(title="Mean reversion", shorttitle="MeanRev", precision=16 , overlay=true)
moveLimit = input(70)
maLength = input(200)
ma = ta.sma(close, maLength)
downBar = open > close
isThreeDown = downBar and downBar[1] and downBar[2]
isThreeUp = not downBar and not downBar[1] and not downBar[2]
isBigMoveDown = ((open - close) / (0.001 + high - low)) > moveLimit / 100.0
isBigMoveUp = ((close - open) / (0.001 + high - low)) > moveLimit / 100.0
isLongBuy = isThreeDown and isBigMoveDown
isLongExit = close > high[1]
isShortBuy = isThreeUp and isBigMoveUp
isShortExit = close < low[1]
strategy.entry("Entry Long", strategy.long, when=isLongBuy)
strategy.close("Entry Long", when=isLongExit)
strategy.entry("Entry Short", strategy.short, when=close < ma and isShortBuy)
strategy.close("Entry Short", when=isShortExit)
plot(ma, color=color.gray) |
Nifty & BN 2 Candle Theory Back Testing and Alert Notification | https://www.tradingview.com/script/rloZrXAT-Nifty-BN-2-Candle-Theory-Back-Testing-and-Alert-Notification/ | abdullabashaa | https://www.tradingview.com/u/abdullabashaa/ | 396 | 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
//---------------------------//2 Candle Theorey + Golden Crossover\\------------------------------\\
strategy('2 Candle Theorey V2', process_orders_on_close=true, overlay = true)
//---------------------------------//Options\\---------------------------------\\
showsession = input.bool(defval=false, title='', inline='Session', group='Timefilter')
session2 = input.session(defval='1430-1000', title='Session Timings(to avoid trades)', inline='Session', group='Timefilter')
profitMultiplier = input.float(defval=2.0, minval=0.1,step=0.1, maxval=10.0, title='Risk to Reward', group='Main Settings', tooltip='Modify Risk to Reward for Take Profit')
volumecutoff = input.float(defval=50000, minval= 10000 , step= 1000, maxval=1000000, title='Volume Cutoff', tooltip='Modify Volume Cutoff ex: 2 Candles with Volume above 50k for Entry Condition', group='Main Settings')
showVolumeColor = input.bool(defval=true,title='', group='Main Settings', inline='Color')
color volumeColorInput = input.color(color.new(color.yellow,20), " Show High Volume Candles", group='Main Settings', tooltip='Change Canlde Color for Candles above Volume Cutoff', inline='Color')
var g_filter = 'Filter Settings'
emaFilter = input.int(title='EMA Filter', defval=0, group=g_filter, tooltip='EMA length to filter trades - set to zero to disable')
i_startTime = input.time(title='Start Date Filter', defval=timestamp('01 Jan 2000 13:30 +0000'), group=g_filter, tooltip='Date & time to begin trading from')
i_endTime = input.time(title='End Date Filter', defval=timestamp('1 Jan 2099 19:30 +0000'), group=g_filter, tooltip='Date & time to stop trading')
// Backtester Settings
var g_tester = 'Backtester Settings'
startBalance = input.float(title='Starting Balance', defval=10000.0, group=g_tester, tooltip='Your starting balance for the custom inbuilt tester system')
riskPerTrade = input.float(title='Risk Per Trade', defval=1.0, group=g_tester, tooltip='Your desired % risk per trade (as a whole number)')
drawTester = input.bool(title='Draw Backtester', defval=true, group=g_tester, tooltip='Turn on/off inbuilt backtester display')
//-----------------------------// Custom Functions \\---------------------------------\\
// Custom function to truncate (cut) excess decimal places
truncate(_number, _decimalPlaces) =>
_factor = math.pow(10, _decimalPlaces)
int(_number * _factor) / _factor
//---------------------------------//EMA Filter\\---------------------------------\\
ema = ta.ema(close, emaFilter == 0 ? 1 : emaFilter)
//---------------------------------//RSI Code\\---------------------------------\\
marsi(sourcersi, lengthrsi, typersi) =>
switch typersi
"SMA" => ta.sma(sourcersi, lengthrsi)
"Bollinger Bands" => ta.sma(sourcersi, lengthrsi)
"EMA" => ta.ema(sourcersi, lengthrsi)
"SMMA (RMA)" => ta.rma(sourcersi, lengthrsi)
"WMA" => ta.wma(sourcersi, lengthrsi)
"VWMA" => ta.vwma(sourcersi, lengthrsi)
rsiLengthInput = input.int(14, minval=1, title="RSI Length", group="RSI Settings")
rsiSourceInput = input.source(close, "Source", group="RSI Settings")
maTypeInput = input.string("SMA", title="MA Type", options=["SMA", "Bollinger Bands", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="RSI Settings")
maLengthInput = input.int(14, title="MA Length", group="RSI Settings")
bbMultInput = input.float(2.0, minval=0.001, maxval=50, title="BB StdDev", group="RSI Settings")
up0 = ta.rma(math.max(ta.change(rsiSourceInput), 0), rsiLengthInput)
down0 = ta.rma(-math.min(ta.change(rsiSourceInput), 0), rsiLengthInput)
rsi = down0 == 0 ? 100 : up0 == 0 ? 0 : 100 - (100 / (1 + up0 / down0))
rsiMA = marsi(rsi, maLengthInput, maTypeInput)
isBB = maTypeInput == "Bollinger Bands"
//---------------------------------//PSAR Code\\---------------------------------\\
start0 = input(0.02)
increment0 = input(0.02)
maximum0 = input(0.2, "Max Value")
out = ta.sar(start0, increment0, maximum0)
plot(out, "ParabolicSAR", style=plot.style_cross, color=#2962FF)
//---------------------------------//Supertrend Code\\---------------------------------\\
length = input(title='ATR Period', defval=10, group="Supertrend Settings")
mult = input.float(title='ATR Multiplier', step=0.1, defval=2, group="Supertrend Settings")
src = input(title='Source', defval=close, group="Supertrend Settings")
wicks = input(title='Take Wicks into Account ?', defval=true, group="Supertrend Settings")
showLabels = input(title='Show Buy/Sell Labels ?', defval=true, group="Supertrend Settings")
highlightState = input(title='Highlight State ?', defval=true, group="Supertrend Settings")
atr = mult * ta.atr(length)
highPrice = wicks ? high : close
lowPrice = wicks ? low : close
doji4price = open == close and open == low and open == high
longStop = src - atr
longStopPrev = nz(longStop[1], longStop)
if longStop > 0
if doji4price
longStop := longStopPrev
longStop
else
longStop := lowPrice[1] > longStopPrev ? math.max(longStop, longStopPrev) : longStop
longStop
else
longStop := longStopPrev
longStop
shortStop = src + atr
shortStopPrev = nz(shortStop[1], shortStop)
if shortStop > 0
if doji4price
shortStop := shortStopPrev
shortStop
else
shortStop := highPrice[1] < shortStopPrev ? math.min(shortStop, shortStopPrev) : shortStop
shortStop
else
shortStop := shortStopPrev
shortStop
var int dir = 1
dir := dir == -1 and highPrice > shortStopPrev ? 1 : dir == 1 and lowPrice < 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))
//plotshape(buySignal and showLabels ? longStop : na, title='Buy Label', text='Buy', location=location.absolute, style=shape.labelup, size=size.tiny, color=color.new(longColor, 0), textcolor=color.new(color.white, 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))
//plotshape(sellSignal and showLabels ? shortStop : na, title='Sell Label', text='Sell', location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.new(shortColor, 0), textcolor=color.new(color.white, 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)
changeCond = dir != dir[1]
//---------------------------------//VMA Code\\---------------------------------\\
lenvma = input.int(20, "Length", minval=1, group="VMA Settings")
srcvma = input(close, "Source", group="VMA Settings")
mavma = ta.vwma(srcvma, lenvma)
offsetvma = input.int(0, "Offset", minval = -500, maxval = 500, group="VMA Settings")
plot(mavma, title="VWMA", color=#2962FF, offset = offsetvma)
//---------------------------------//VWAP Code\\---------------------------------\\
// Inputs
vwap_show = input(true, title='Show VWAP', group = "VWAP Settings")
vwapOffset = input(title='VWAP offset', defval=0, group = "VWAP Settings")
start = request.security(syminfo.tickerid, 'D', time)
newSession = start > start[1] ? 1 : 0
vwapsum = 0.0
volumesum = 0.0
vwapsum := newSession[1] ? hlc3 * volume : vwapsum[1] + hlc3 * volume
volumesum := newSession[1] ? volume : volumesum[1] + volume
vwap_now = vwapsum / volumesum
plot(vwap_now, color=color.new(color.white, 0), title='VWAP')
//---------------------------------//Logic\\---------------------------------\\
// Check Sessions to avoid trades
session = time('1', session2 + string(':1234567'), str.tostring(syminfo.timezone))//'GMT+5:30')
sessioncond = showsession ? not session : true
// See if this bar's time happened within date filter
dateFilter = time >= i_startTime and time <= i_endTime
// Check EMA Filter
emaFilterLong = emaFilter == 0 or close > ema
emaFilterShort = emaFilter == 0 or close < ema
// Check RSI
rsiFilterLong = rsi > 50 and rsi <= 80
rsiFilterShort = rsi < 40 and rsi >= 20
// Check VWAP
vwapFilterLong = close > vwap_now
vwapFilterShort = close < vwap_now
// Check Supertrend
supertrendFilterLong = close > longStop
supertrendFilterShort = close < shortStop
// Check VMA
vmaFilterLong = close > mavma
vmaFilterShort = close < mavma
// Check PSAR
psarFilterLong = close > out
psarFilterShort = close < out
// Check Volume
volumeFilter = volume[1] > volumecutoff and volume > volumecutoff //and barColor == barColor[1]
volumeLongCond = close > open and close[1] > open[1]
volumeShortCond = close < open and close[1] < open[1]
volumeLongEntry = volumeFilter and volumeLongCond
volumeShortEntry = volumeFilter and volumeShortCond
// Determine if we have a valid setup
validLongSetup = rsiFilterLong and vwapFilterLong and supertrendFilterLong and vmaFilterLong and psarFilterLong and volumeFilter and volumeLongCond and emaFilterLong and sessioncond
validShortSetup = rsiFilterShort and vwapFilterShort and supertrendFilterShort and vmaFilterShort and psarFilterShort and volumeFilter and volumeShortCond and emaFilterShort and sessioncond
// Check if we have confirmation for our setup
validLongEntry = validLongSetup and strategy.position_size == 0 and dateFilter and barstate.isconfirmed
validShortEntry = validShortSetup and strategy.position_size == 0 and dateFilter and barstate.isconfirmed
// Highlight candles above Volume Cutoff if true
barcolor(showVolumeColor? volume>volumecutoff ? volumeColorInput : na : na, title='Big Volume Candles')
//---------------------------------// Golden Cross Code\\---------------------------\\
// Golden Cross Conditions
supertrendCrossBull = ta.crossover(longStop,vwap_now)
supertrendCrossBear = ta.crossunder(shortStop,vwap_now)
vmaCrossBull = ta.crossover(mavma,vwap_now)
vmaCrossBear = ta.crossunder(mavma,vwap_now)
// Golden Cross
validGoldenCrossBullSetup = supertrendCrossBull and vmaCrossBull and volumeLongEntry and rsiFilterLong//and validLongEntry
validGoldenCrossBearSetup = supertrendCrossBear and vmaCrossBear and volumeShortEntry and rsiFilterShort//and validShortEntry
//---------------------------------// Strategy Execution \\-------------------------\\
float sl = na
float tp = na
sl := nz(sl[1], 0.0)
tp := nz(tp[1], 0.0)
if validLongEntry and strategy.position_size <= 0
strategy.entry('Long Entry', strategy.long, when=validLongEntry)
sl := low[1]
sl
alert(message= "2 Candle Theorey Long Entry", freq=alert.freq_once_per_bar_close)
if validShortEntry and strategy.position_size >= 0
strategy.entry('Short Entry', strategy.short, when=validShortEntry)
sl := high[1]
sl
alert(message= "2 Candle Theorey Short Entry", freq=alert.freq_once_per_bar_close)
if validGoldenCrossBullSetup and strategy.position_size <= 0
strategy.entry('Golden Cross Long Entry', strategy.long, when=validGoldenCrossBullSetup)
sl := low[1]
sl
alert(message= "Golden Cross Long Entry", freq=alert.freq_once_per_bar_close)
if validGoldenCrossBearSetup and strategy.position_size >= 0
strategy.entry('Golden Cross Short Entry', strategy.short, when=validGoldenCrossBearSetup)
sl := high[1]
sl
alert(message= "Golden Cross Short Entry", freq=alert.freq_once_per_bar_close)
if sl != 0.0
if strategy.position_size > 0
tp := strategy.position_avg_price + (strategy.position_avg_price - sl) * profitMultiplier
strategy.exit(id='Exit', limit=tp, stop=sl)
if strategy.position_size < 0
tp := strategy.position_avg_price - (sl - strategy.position_avg_price) * profitMultiplier
strategy.exit(id='Exit', limit=tp, stop=sl)
//---------------------------------//Plots\\---------------------------------\\
// Draw trade data
plot(validLongEntry or validShortEntry ? sl : na, title='Trade Stop Price', color=color.new(color.red, 0), style=plot.style_linebr)
plot(validLongEntry or validShortEntry ? tp : na, title='Trade Target Price', color=color.new(color.green, 0), style=plot.style_linebr)
// Draw EMA if it's enabled
plot(emaFilter == 0 ? na : ema, color=emaFilterLong ? color.green : color.red, linewidth=2, title='EMA')
// Draw Golden Cross Setups
plotchar(validGoldenCrossBullSetup,"Bull Golden Cross",'🚀',location.abovebar,offset=0,size=size.small)
plotchar(validGoldenCrossBearSetup,"Bear Golden Cross",'🚀',location.belowbar,offset=0,size=size.small)
//---------------------------------//Dashbaord\\---------------------------------\\
// --- BEGIN TESTER CODE --- //
// Declare performance tracking variables
var balance = startBalance
var drawdown = 0.0
var maxDrawdown = 0.0
var maxBalance = 0.0
var totalPips = 0.0
var totalWins = 0
var totalLoss = 0
// Detect winning trades
if strategy.wintrades != strategy.wintrades[1]
balance += riskPerTrade / 100 * balance * profitMultiplier
//totalPips += math.abs(t_entry - t_target)
totalWins += 1
if balance > maxBalance
maxBalance := balance
maxBalance
// Detect losing trades
if strategy.losstrades != strategy.losstrades[1]
balance -= riskPerTrade / 100 * balance
//totalPips -= math.abs(t_entry - t_stop)
totalLoss += 1
// Update drawdown
drawdown := balance / maxBalance - 1
if drawdown < maxDrawdown
maxDrawdown := drawdown
maxDrawdown
// ProfitFactor returns the strategy's current profit factor,
ProfitFactor = strategy.grossprofit / strategy.grossloss
maxloss = math.round(maxDrawdown*(-100))
winrate = (strategy.wintrades / strategy.closedtrades) * 100
initbalance = startBalance
// Prepare stats table
var table testTable = table.new(position.bottom_right, 5, 3, border_width=1)
f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) =>
_cellText = _title + '\n' + _value
table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor)
// Draw stats table
var bgcolor = color.new(color.black, 0)
if drawTester
if barstate.islastconfirmedhistory
// Update table
dollarReturn = balance - startBalance
f_fillCell(testTable, 0, 0, 'Backtester by EtherMatt', str.tostring(syminfo.tickerid) , color.blue, color.white)
f_fillCell(testTable, 0, 1, '2 Candle Theory V2', str.tostring(timeframe.period) + 'M' , color.blue, color.white)
f_fillCell(testTable, 1, 0, 'Total Trades:', str.tostring(strategy.closedtrades), bgcolor, color.white)
f_fillCell(testTable, 1, 1, 'Win Rate:', str.tostring(truncate(winrate, 2)) + '%', winrate > 40 ? color.green : color.red, color.white)// bgcolor, color.white)
f_fillCell(testTable, 2, 0, 'Starting:', '$' + str.tostring(startBalance), bgcolor, color.white)
f_fillCell(testTable, 2, 1, 'Ending:', '$' + str.tostring(truncate(balance, 2)), balance > initbalance ? color.green : color.red, color.white)
f_fillCell(testTable, 3, 0, 'Profit Factor:', str.tostring(truncate(ProfitFactor, 2)), ProfitFactor > 0 ? color.green : color.red, color.white)
f_fillCell(testTable, 3, 1, 'Consec. Loss:', str.tostring(maxloss), maxloss <= 5 ? color.green : color.red, color.white)//color.new(color.red,50), bgcolor, color.white)
f_fillCell(testTable, 4, 0, 'Return:', (dollarReturn > 0 ? '+' : '') + str.tostring(truncate(dollarReturn / startBalance * 100, 2)) + '%', dollarReturn > 0 ? color.green : color.red, color.white)
f_fillCell(testTable, 4, 1, 'Max DD:', str.tostring(truncate(maxDrawdown * 100, 2)) + '%', color.red, color.white)
|
Short Selling EMA Cross (By Coinrule) | https://www.tradingview.com/script/qDkU6QLs-Short-Selling-EMA-Cross-By-Coinrule/ | Coinrule | https://www.tradingview.com/u/Coinrule/ | 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/
// © Coinrule
//@version=5
strategy("Short Selling EMA Cross (By Coinrule)", overlay=true, initial_capital = 10000, default_qty_value = 30, default_qty_type = strategy.percent_of_equity, commission_type=strategy.commission.percent, commission_value=0.1)
// EMAs
fastEMA = ta.ema(close, 20)
slowEMA = ta.ema(close, 50)
// Conditions
goShortCondition1 = ta.crossunder(fastEMA, slowEMA)
timePeriod = time >= timestamp(syminfo.timezone, 2021, 12, 1, 0, 0)
notInTrade = strategy.position_size <= 0
strategyDirection = strategy.direction.short
if (goShortCondition1 and timePeriod and notInTrade)
stopLoss = high * 1.16
takeProfit = low * 0.92
strategy.entry("short", strategy.short)
strategy.exit("exit","short", stop=stopLoss, limit=takeProfit)
plot(fastEMA, color=color.blue)
plot(slowEMA, color=color.yellow)
|
Scalping Support Resistance Strategy | https://www.tradingview.com/script/gp332Dao-Scalping-Support-Resistance-Strategy/ | HPotter | https://www.tradingview.com/u/HPotter/ | 2,444 | 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/
// © HPotter
TradeLong(Level, Take, Stop, ID, symbol, balance) =>
strategy.cancel_all()
msg = ROI.MsgDoLongMKT(ID, symbol, balance)
strategy.entry("Long", strategy.long, stop = Level, alert_message = msg)
msg := ROI.MsgDoLongMKT(ID, symbol, 0)
strategy.exit('Exit', 'Long', limit = Level+Take, stop = Level - Stop, alert_message = msg)
TradeShort(Level, Take, Stop, ID, symbol,balance) =>
strategy.cancel_all()
msg = ROI.MsgDoShortMKT(ID, symbol, balance)
strategy.entry("Short", strategy.short, stop = Level, alert_message = msg)
msg := ROI.MsgDoShortMKT(ID, symbol, 0)
strategy.exit('Exit', 'Short', limit = Level-Take, stop = Level + Stop, alert_message = msg)
//@version=5
strategy("Iron Support Resistance Automat", shorttitle="Iron SRA", overlay = true, calc_on_order_fills = true)
import HPotter/RouterOrdersIron/1 as ROI
symbol = input.string("BTC")
ID = input.string("")
balance = input.float(20, minval=12)
TakePercent= input.float(1, minval=0.00001)
StopPercent= input.float(1, minval=0.00001)
LookBack = input.int(10)
PointBack = input.int(5)
ShowBackTest = input.bool(false)
var Green = color.new(color.green, 0)
var Red = color.new(color.red, 0)
var Blue = color.new(color.blue, 0)
var Work = ShowBackTest
if barstate.islastconfirmedhistory or barstate.isrealtime
Work := true
LLS = ta.lowest(hlc3, LookBack)
Level = LLS[PointBack]
var line lineLevel = na
clr = close > Level ? Red : Green
line.delete(lineLevel)
lineLevel := line.new(bar_index-LookBack, LLS[LookBack], bar_index, Level, color = clr)
Take = Level * TakePercent / 100
Stop = Level * StopPercent / 100
if Work and strategy.position_size == 0
if close < Level
TradeLong(Level, Take, Stop, ID, symbol, balance)
if close > Level
TradeShort(Level, Take, Stop, ID, symbol, balance)
barcolor(strategy.position_size < 0 ? Red : strategy.position_size > 0 ? Green: Blue) |
Profitable Contrarian scalping | https://www.tradingview.com/script/05fyXYfr-Profitable-Contrarian-scalping/ | Jaerevan47 | https://www.tradingview.com/u/Jaerevan47/ | 112 | 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/
// © Jaerevan47
//@version=5
strategy("Smooth VWMA scalping contrarian", overlay = true, default_qty_type = strategy.percent_of_equity, default_qty_value = 100)
length1 = input(5, title = "Length1")
length2 = input(200, title = "Length2")
length3 = input(20, title = "Stop length")
vwma1 = ta.vwma(ta.sma(close,5), length1)
vwma2 = ta.vwma(ta.sma(close,5), length2)
vwma3 = ta.vwma(ta.sma(close, 5), length3)
plot(vwma1)
plot(vwma2, color = color.white)
if ta.crossover(vwma1, vwma2)
strategy.entry("Short", strategy.short)
if ta.crossunder(vwma1, vwma3)
strategy.close("Short")
if ta.crossunder(vwma1, vwma2)
strategy.entry("Long", strategy.long)
if ta.crossover(vwma1, vwma3)
strategy.close("Long") |
Dillon's Double VWAP Strategy | https://www.tradingview.com/script/EIIqFB0g-Dillon-s-Double-VWAP-Strategy/ | jordanfray | https://www.tradingview.com/u/jordanfray/ | 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/
// © jordanfray
//@version=5
strategy(title="Double VWAP Strategy", overlay=true, max_bars_back=5000, default_qty_type=strategy.percent_of_equity, default_qty_value=100,initial_capital=100000, commission_type=strategy.commission.percent, commission_value=0.05, backtest_fill_limits_assumption=2)
// Indenting Classs
indent_1 = " "
indent_2 = " "
indent_3 = " "
indent_4 = " "
// Group Titles
group_one_title = "VWAP Settings"
group_two_title = "ADX Settings"
group_three_title = "Entry Settings"
group_four_title = "Limit Entries"
// Input Tips
adx_thresholdToolTip = "The minumn ADX value to allow opening a postion"
adxCancelToolTip= "You can optionally set a different lower value for ADX that will allow entries even if below the trigger threshold."
close_early_toopTip = "Enabling this will cause entries to close if/when the price crosses the VWAP to the other outer band."
ladderInToolTip = "Enable this to use the laddering settings below."
emaDistanceToolTip = "Disable opening trades when the price is too close to the above EMA."
// Colors
ocean_blue = color.new(#0C6090,0)
sky_blue = color.new(#00A5FF,0)
green = color.new(#2DBD85,0)
red = color.new(#E02A4A,0)
light_blue = color.new(#00A5FF,90)
light_green = color.new(#2DBD85,90)
light_red = color.new(#E02A4A,90)
light_yellow = color.new(#FFF900,90)
white = color.new(#ffffff,0)
transparent = color.new(#000000,100)
// Strategy Settings
anchor = input.string(defval="Session", title="Anchor Period", options=["Session", "Week", "Month", "Quarter", "Year"], group=group_one_title)
src = input.source(defval=close, title="VWAP Source", group=group_one_title)
multiplier_inner = input.float(defval=1.0, step=.1, title="Inner Bands Multiplier", group=group_one_title)
multiplier_outer = input.float(defval=2.1, step=.1, title="Outer Bands Multiplier", group=group_one_title)
adx_len = input.int(defval=14, title="ADX Smoothing", group=group_two_title)
di_len = input.int(defval=14, title="DI Length", group=group_two_title)
adx_threshold = input.int(defval=30, title="ADX Threshold", group=group_two_title, tooltip=adx_thresholdToolTip)
enableLaddering = input.bool(defval=true, title="Ladder Into Positions", tooltip=ladderInToolTip, group=group_two_title)
ladderRungs = input.int(defval=3, minval=2, maxval=4, step=1, title=indent_4+"Ladder Rungs", group=group_two_title)
ladderStep = input.float(defval=.25, title=indent_4+"Ladder Step (%)", step=.1, group=group_two_title)/100
stop_loss_val = input.float(defval=5.0, title="Stop Loss (%)", step=0.1, group=group_three_title)/100
take_profit_val = input.float(defval=10.5, title="Take Profit (%)", step=0.1, group=group_three_title)/100
long_entry_limit_lookback = input.int(defval=1, title="Long Entry Limit Lookback", minval=1, step=1, group=group_three_title)
short_entry_limit_lookback = input.int(defval=1, title="Short Entry Limit Lookback", minval=1, step=1, group=group_three_title)
start_trailing_after = input.float(defval=3, title="Start Trailing After (%)", step=0.1, group=group_three_title)/100
trail_behind = input.float(defval=4, title="Trail Behind (%)", step=0.1, group=group_three_title)/100
close_early = input.bool(defval=false, title="Close early if price crosses outer VWAP band", tooltip=close_early_toopTip)
enableEmaFilter = input.bool(defval=true, title="Use EMA Filter", group=group_four_title)
emaFilterTimeframe = input.timeframe(defval="240", title=indent_4+"Timeframe", group=group_four_title)
emaFilterLength = input.int(defval=100, minval=1, step=10, title=indent_4+"Length", group=group_four_title)
emaFilterSource = input.source(defval=hl2, title=indent_4+"Source", group=group_four_title)
enableEmaDistanceFilter = input.bool(defval=true, title="Use EMA Distance Filter", group=group_four_title)
emaDistanceThreshold = input.float(defval=2.0, title=indent_4+"EMA Min Distance (%)", group=group_four_title, tooltip=emaDistanceToolTip)
useTimeFilter = input.bool(defval=true, title="Use Time Session Filter", group=group_four_title)
timeSession = input.session(defval="1400-2200", title=indent_4+"Time Session To Ignore Trades", group=group_four_title)
// Calculate and plot VWAP bands
float vwap_val = na
float upper_inner_band_value = na
float lower_inner_band_value = na
float upper_outer_band_value = na
float lower_outer_band_value = na
var cumVol = 0.
cumVol += nz(volume)
if barstate.islast and cumVol == 0
runtime.error("No volume is provided by the data vendor.")
computeVWAP(src, isNewPeriod, stDevMultiplier) =>
var float sum_src_vol = na
var float sum_vol = na
var float sum_src_src_vol = na
sum_src_vol := isNewPeriod ? src * volume : src * volume + sum_src_vol[1]
sum_vol := isNewPeriod ? volume : volume + sum_vol[1]
sum_src_src_vol := isNewPeriod ? volume * math.pow(src, 2) : volume * math.pow(src, 2) + sum_src_src_vol[1]
_vwap = sum_src_vol / sum_vol
variance = sum_src_src_vol / sum_vol - math.pow(_vwap, 2)
variance := variance < 0 ? 0 : variance
standard_deviation = math.sqrt(variance)
lower_band_value = _vwap - standard_deviation * stDevMultiplier
upper_band_value = _vwap + standard_deviation * stDevMultiplier
[_vwap, lower_band_value, upper_band_value]
timeChange(period) =>
ta.change(time(period))
isNewPeriod = switch anchor
"Session" => timeChange("D")
"Week" => timeChange("W")
"Month" => timeChange("M")
"Quarter" => timeChange("3M")
"Year" => timeChange("12M")
=> false
[inner_vwap, inner_bottom, inner_top] = computeVWAP(src, isNewPeriod, multiplier_inner)
[outer_vwap, outer_bottom, outer_top] = computeVWAP(src, isNewPeriod, multiplier_outer)
vwap_val := inner_vwap
upper_inner_band_value := inner_top
lower_inner_band_value := inner_bottom
upper_outer_band_value := outer_top
lower_outer_band_value := outer_bottom
// Calculate and plot ADX
dirmov(len) =>
up = ta.change(high)
down = -ta.change(low)
plus_dm = na(up) ? na : (up > down and up > 0 ? up : 0)
minus_dm = na(down) ? na : (down > up and down > 0 ? down : 0)
true_range = ta.rma(ta.tr, len)
plus = fixnan(100 * ta.rma(plus_dm, len) / true_range)
minus = fixnan(100 * ta.rma(minus_dm, len) / true_range)
[plus, minus]
adx(di_len, adx_len) =>
[plus, minus] = dirmov(di_len)
sum = plus + minus
adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), adx_len)
adx_val = adx(di_len, adx_len)
plot(adx_val, title="ADX")
// Calculate and Plot Macro EMA
ema_filter = ta.ema(emaFilterSource, emaFilterLength)
ema_filter_smoothed = request.security(syminfo.tickerid, emaFilterTimeframe, ema_filter[barstate.isrealtime ? 1 : 0])
distance_from_EMA = ((close - ema_filter_smoothed)/close)*100
if distance_from_EMA < 0
distance_from_EMA := distance_from_EMA * -1
plot(enableEmaFilter ? ema_filter_smoothed: na, title="EMA Macro Filter", style=plot.style_stepline, linewidth=2, color=sky_blue, editable=true)
// Calculate if bars are in restricted time period
isInSession(sess) =>
na(time(timeframe.period, sess,"GMT-6")) == false
withinTime = (useTimeFilter and not isInSession(timeSession)) or not useTimeFilter
// Calulate Ladder Entries
long_ladder_1_limit_price = close - (close * 1 * ladderStep)
long_ladder_2_limit_price = close - (close * 2 * ladderStep)
long_ladder_3_limit_price = close - (close * 3 * ladderStep)
long_ladder_4_limit_price = close - (close * 4 * ladderStep)
short_ladder_1_limit_price = close + (close * 1 * ladderStep)
short_ladder_2_limit_price = close + (close * 2 * ladderStep)
short_ladder_3_limit_price = close + (close * 3 * ladderStep)
short_ladder_4_limit_price = close + (close * 4 * ladderStep)
var position_qty = strategy.equity/close
if enableLaddering
position_qty := (strategy.equity/close) / ladderRungs
else
position_qty := strategy.equity/close
plot(position_qty, color=white)
// Calculate entry and exit values
limit_order_long_price = ta.lowest(hl2, long_entry_limit_lookback)
limit_order_short_price = ta.highest(hl2, short_entry_limit_lookback)
long_start_trailing_val = strategy.position_avg_price + (strategy.position_avg_price * start_trailing_after)
short_start_trailing_val = strategy.position_avg_price - (strategy.position_avg_price * start_trailing_after)
long_trail_behind_val = close - (strategy.position_avg_price * (trail_behind/100))
short_trail_behind_val = close + (strategy.position_avg_price * (trail_behind/100))
currently_in_a_long_postion = strategy.position_size > 0
currently_in_a_short_postion = strategy.position_size < 0
long_profit_target = strategy.position_avg_price * (1 + take_profit_val)
short_profit_target = strategy.position_avg_price * (1 - take_profit_val)
long_stop_loss = strategy.position_avg_price * (1.0 - stop_loss_val)
short_stop_loss = strategy.position_avg_price * (1 + stop_loss_val)
bars_since_entry = currently_in_a_long_postion or currently_in_a_short_postion ? bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades - 1) + 1 : 5
long_run_up = ta.highest(high, bars_since_entry)
short_run_up = ta.lowest(low, bars_since_entry)
long_trailing_stop = currently_in_a_long_postion and bars_since_entry > 0 and long_run_up > long_start_trailing_val ? long_run_up - (long_run_up * trail_behind) : long_stop_loss
short_trailing_stop = currently_in_a_short_postion and bars_since_entry > 0 and short_run_up < short_start_trailing_val ? short_run_up + (short_run_up * trail_behind) : short_stop_loss
// Entry Criteria
price_far_enough_away_from_ema = distance_from_EMA > emaDistanceThreshold
adx_is_below_threshold = adx_val < adx_threshold
price_closed_below_VWAP_upper_outer_band = close < upper_outer_band_value
price_closed_above_VWAP_lower_outer_band = close > lower_outer_band_value
price_crossed_up_VWAP_upper_outer_band = ta.crossover(high,upper_outer_band_value)
price_crossed_down_VWAP_lower_outer_band = ta.crossunder(low, lower_outer_band_value)
price_above_ema_filter = close > ema_filter_smoothed
price_below_ema_filter = close < ema_filter_smoothed
//Trade Restirctions
no_trades_allowed = not withinTime or not adx_is_below_threshold or not price_far_enough_away_from_ema
// Enter trades when...
long_conditions_met = enableEmaFilter ? price_above_ema_filter and not currently_in_a_short_postion and withinTime and adx_is_below_threshold and price_crossed_down_VWAP_lower_outer_band and price_closed_above_VWAP_lower_outer_band : not currently_in_a_long_postion and withinTime and adx_is_below_threshold and price_crossed_down_VWAP_lower_outer_band and price_closed_above_VWAP_lower_outer_band
short_conditions_met = enableEmaFilter ? price_below_ema_filter and not currently_in_a_long_postion and withinTime and adx_is_below_threshold and price_crossed_up_VWAP_upper_outer_band and price_closed_below_VWAP_upper_outer_band : not currently_in_a_short_postion and withinTime and adx_is_below_threshold and price_crossed_up_VWAP_upper_outer_band and price_closed_below_VWAP_upper_outer_band
// Take Profit When...
price_closed_below_short_trailing_stop = ta.cross(close, short_trailing_stop)
price_hit_short_entry_profit_target = low > short_profit_target
price_closed_above_long_entry_trailing_stop = ta.cross(close, long_trailing_stop)
price_hit_long_entry_profit_target = high > long_profit_target
long_position_take_profit = close_early ? price_crossed_up_VWAP_upper_outer_band or price_closed_above_long_entry_trailing_stop or price_hit_long_entry_profit_target : price_closed_above_long_entry_trailing_stop or price_hit_long_entry_profit_target
short_position_take_profit = close_early ? price_crossed_down_VWAP_lower_outer_band or price_closed_below_short_trailing_stop or price_hit_short_entry_profit_target : price_closed_below_short_trailing_stop or price_hit_short_entry_profit_target
// Cancel limir order if...
cancel_long_condition = no_trades_allowed
cancel_short_condition = no_trades_allowed
// Long Entry
if enableLaddering
if ladderRungs == 2
strategy.entry(id="Long Ladder 1", direction=strategy.long, qty=position_qty, limit=long_ladder_1_limit_price, when=long_conditions_met)
strategy.entry(id="Long Ladder 2", direction=strategy.long, qty=position_qty, limit=long_ladder_2_limit_price, when=long_conditions_met)
else if ladderRungs == 3
strategy.entry(id="Long Ladder 1", direction=strategy.long, qty=position_qty, limit=long_ladder_1_limit_price, when=long_conditions_met)
strategy.entry(id="Long Ladder 2", direction=strategy.long, qty=position_qty, limit=long_ladder_2_limit_price, when=long_conditions_met)
strategy.entry(id="Long Ladder 3", direction=strategy.long, qty=position_qty, limit=long_ladder_3_limit_price, when=long_conditions_met)
else if ladderRungs == 4
strategy.entry(id="Long Ladder 1", direction=strategy.long, qty=position_qty, limit=long_ladder_1_limit_price, when=long_conditions_met)
strategy.entry(id="Long Ladder 2", direction=strategy.long, qty=position_qty, limit=long_ladder_2_limit_price, when=long_conditions_met)
strategy.entry(id="Long Ladder 3", direction=strategy.long, qty=position_qty, limit=long_ladder_3_limit_price, when=long_conditions_met)
strategy.entry(id="Long Ladder 4", direction=strategy.long, qty=position_qty, limit=long_ladder_4_limit_price, when=long_conditions_met)
strategy.exit(id="Close Long Ladder 1", from_entry="Long Ladder 1", stop=long_trailing_stop, limit=long_profit_target, when=long_position_take_profit)
strategy.exit(id="Close Long Ladder 2", from_entry="Long Ladder 2", stop=long_trailing_stop, limit=long_profit_target, when=long_position_take_profit)
strategy.exit(id="Close Long Ladder 3", from_entry="Long Ladder 3", stop=long_trailing_stop, limit=long_profit_target, when=long_position_take_profit)
strategy.exit(id="Close Long Ladder 4", from_entry="Long Ladder 4", stop=long_trailing_stop, limit=long_profit_target, when=long_position_take_profit)
strategy.cancel(id="Long Ladder 1", when=cancel_long_condition)
strategy.cancel(id="Long Ladder 2", when=cancel_long_condition)
strategy.cancel(id="Long Ladder 3", when=cancel_long_condition)
strategy.cancel(id="Long Ladder 4", when=cancel_long_condition)
else
strategy.entry(id="Long", direction=strategy.long, qty=position_qty, when=long_conditions_met)
strategy.exit(id="Close Long", from_entry="Long", stop=long_stop_loss, limit=long_profit_target, when=long_position_take_profit)
strategy.cancel(id="Long", when=cancel_long_condition)
// short Entry
if enableLaddering
if ladderRungs == 2
strategy.entry(id="short Ladder 1", direction=strategy.short, qty=position_qty, limit=short_ladder_1_limit_price, when=short_conditions_met)
strategy.entry(id="short Ladder 2", direction=strategy.short, qty=position_qty, limit=short_ladder_2_limit_price, when=short_conditions_met)
else if ladderRungs == 3
strategy.entry(id="short Ladder 1", direction=strategy.short, qty=position_qty, limit=short_ladder_1_limit_price, when=short_conditions_met)
strategy.entry(id="short Ladder 2", direction=strategy.short, qty=position_qty, limit=short_ladder_2_limit_price, when=short_conditions_met)
strategy.entry(id="short Ladder 3", direction=strategy.short, qty=position_qty, limit=short_ladder_3_limit_price, when=short_conditions_met)
else if ladderRungs == 4
strategy.entry(id="short Ladder 1", direction=strategy.short, qty=position_qty, limit=short_ladder_1_limit_price, when=short_conditions_met)
strategy.entry(id="short Ladder 2", direction=strategy.short, qty=position_qty, limit=short_ladder_2_limit_price, when=short_conditions_met)
strategy.entry(id="short Ladder 3", direction=strategy.short, qty=position_qty, limit=short_ladder_3_limit_price, when=short_conditions_met)
strategy.entry(id="short Ladder 4", direction=strategy.short, qty=position_qty, limit=short_ladder_4_limit_price, when=short_conditions_met)
strategy.exit(id="Close short Ladder 1", from_entry="short Ladder 1", stop=short_trailing_stop, limit=short_profit_target, when=short_position_take_profit)
strategy.exit(id="Close short Ladder 2", from_entry="short Ladder 2", stop=short_trailing_stop, limit=short_profit_target, when=short_position_take_profit)
strategy.exit(id="Close short Ladder 3", from_entry="short Ladder 3", stop=short_trailing_stop, limit=short_profit_target, when=short_position_take_profit)
strategy.exit(id="Close short Ladder 4", from_entry="short Ladder 4", stop=short_trailing_stop, limit=short_profit_target, when=short_position_take_profit)
strategy.cancel(id="short Ladder 1", when=cancel_short_condition)
strategy.cancel(id="short Ladder 2", when=cancel_short_condition)
strategy.cancel(id="short Ladder 3", when=cancel_short_condition)
strategy.cancel(id="short Ladder 4", when=cancel_short_condition)
else
strategy.entry(id="short", direction=strategy.short, qty=position_qty, when=short_conditions_met)
strategy.exit(id="Close short", from_entry="short", stop=short_stop_loss, limit=short_profit_target, when=short_position_take_profit)
strategy.cancel(id="short", when=cancel_short_condition)
// Plot entry lines & values
center_VWAP_line = plot(vwap_val, title="VWAP", linewidth=1, color=green)
upper_inner_band = plot(upper_inner_band_value, title="Upper Inner Band", linewidth=1, color=sky_blue)
lower_inner_band = plot(lower_inner_band_value, title="Lower Inner Band", linewidth=1, color=sky_blue)
upper_outer_band = plot(upper_outer_band_value, title="Upper Outer Band", linewidth=2, color=ocean_blue)
lower_outer_band = plot(lower_outer_band_value, title="Lower Outer Band", linewidth=2, color=ocean_blue)
fill(upper_outer_band, lower_outer_band, title="VWAP Bands Fill", color=light_blue)
plotshape(long_conditions_met ? close : na, title="Long Entry Symbol", color=green, style=shape.triangleup, location=location.abovebar)
plotshape(short_conditions_met ? close : na, title="Short Entry Symbol", color=red, style=shape.triangledown, location=location.belowbar)
long_trailing_stop_line = plot(long_trailing_stop, style=plot.style_stepline, editable=false, color=currently_in_a_long_postion ? long_trailing_stop > strategy.position_avg_price ? green : red : transparent)
short_trailing_stop_line = plot(short_trailing_stop, style=plot.style_stepline, editable=false, color=currently_in_a_short_postion ? short_trailing_stop < strategy.position_avg_price ? green : red : transparent)
bars_since_entry_int = plot(bars_since_entry, editable=false, title="Bars Since Entry", color=green)
entry = plot(strategy.position_avg_price, editable=false, title="Entry", style=plot.style_stepline, color=currently_in_a_long_postion or currently_in_a_short_postion ? color.blue : transparent, linewidth=1)
fill(entry,long_trailing_stop_line, editable=false, color=currently_in_a_long_postion ? long_trailing_stop > strategy.position_avg_price ? light_green : light_red : transparent)
fill(entry,short_trailing_stop_line, editable=false, color=currently_in_a_short_postion ? short_trailing_stop < strategy.position_avg_price ? light_green : light_red : transparent)
bgcolor(title="No Trades Allowed", color=no_trades_allowed ? light_red : light_green)
//long_run_up_line = plot(long_run_up, style=plot.style_stepline, editable=false, color=currently_in_a_long_postion ? green : transparent)
//short_run_up_line = plot(short_run_up, style=plot.style_stepline, editable=false, color=currently_in_a_short_postion ? green : transparent) |
Elliot Wave - Impulse Strategy | https://www.tradingview.com/script/Wk4oeQHa-Elliot-Wave-Impulse-Strategy/ | UnknownUnicorn36161431 | https://www.tradingview.com/u/UnknownUnicorn36161431/ | 172 | 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("Elliot Wave - Impulse Strategy", shorttitle="EW - Impulse Strategy", overlay=true, process_orders_on_close = true, calc_on_order_fills = true, calc_on_every_tick = true, pyramiding = 0, default_qty_type = strategy.percent_of_equity, default_qty_value = 75, commission_type = strategy.commission.percent, commission_value = 0.04, initial_capital = 100, max_lines_count=500, max_labels_count=500)
show_sl_invalidation_labels = input.bool( true, "Show 'invalidated at SL' Labels", group = "General" )
i_use_time_limited_backtesting = input.bool( false, "Use Time-Limited Backtesting", group = "Time-Limit BackTesting (0 = disable)" )
startDay = input.int(0, "Start Day", minval = 0, maxval = 31, group = "Time-Limit BackTesting (0 = disable)")
startMonth = input.int(0, "Start Month", minval = 0, maxval = 12, group = "Time-Limit BackTesting (0 = disable)")
startYear = input.int(0, "Start Year", minval = 0, maxval = 2100, group = "Time-Limit BackTesting (0 = disable)")
endDay = input.int(0, "End Day", minval = 0, maxval = 31, group = "Time-Limit BackTesting (0 = disable)")
endMonth = input.int(0, "End Month", minval = 0, maxval = 12, group = "Time-Limit BackTesting (0 = disable)")
endYear = input.int(0, "End Year", minval = 0, maxval = 2100, group = "Time-Limit BackTesting (0 = disable)")
//source = input(close, group = "Elliot Waves Options")
source = close
zigzagLength = input.int(2, minval=2, step=1, group = "Elliot Waves Options")
errorPercent = input.int(10, minval=2, step=1, maxval=20, group = "Elliot Waves Options")
entryPercent = input.int(10, minval=10, step=1, maxval=100, group = "Elliot Waves Options")
zigzagWidth = input.int(2, step=1, minval=1, group = "Elliot Waves Options")
zigzagStyle = input.string(line.style_solid, options=[line.style_dashed, line.style_dotted, line.style_solid], group = "Elliot Waves Options")
target2reach = input.string("TP4 (3.236 fibo)", options=["TP1 (1.618 fibo)", "TP2 (2.0 fibo)", "TP3 (2.618 fibo)", "TP4 (3.236 fibo)"], group = "Elliot Waves Options")
waitForConfirmation = true
i_use_crsi = input.bool( true, "Trade by cRSI direction", group = "cRSI Options" )
i_show_crsi = input.bool( false, "Show cRSI Pivots", group = "cRSI Options" )
i_i_len = input( 1, "cRSI EMA period", group = "cRSI Options" )
i_src = input.source( close, 'cRSI Source', group = "cRSI Options" )
i_use_mesa = input.bool( true, "Open trades by MESA Pivots", group = "MESA Pivots Options" )
i_show_mesa = input.bool( false, "Show MESA Pivots", group = "MESA Pivots Options" )
offsetNum = input( 0, "MESA offset", group = "MESA Pivots Options")
pivot_zone_upper = input( 0.4, "MESA pivot zone upper", group = "MESA Pivots Options" )
pivot_zone_lower = input( -0.4, "MESA pivot zone lower", group = "MESA Pivots Options" )
var cRSI_high_extreme_found = 0.0
var cRSI_high_extreme_valid = true
var cRSI_low_extreme_found = 0.0
var cRSI_low_extreme_valid = true
var last_cRSI_extreme = ""
var cRSI_trend_direction = ""
var last_trade_ts = time
var min_trade_gap_minutes = 2
inDateRange = true
// Look if the close time of the current bar falls inside the date range
if i_use_time_limited_backtesting and startDay != 0 and startMonth != 0 and startYear != 0 and endDay != 0 and endMonth != 0 and endYear != 0
inDateRange := ( time >= timestamp( syminfo.timezone, startYear, startMonth, startDay, 0, 0 ) ) and ( time < timestamp( syminfo.timezone, endYear, endMonth, endDay, 0, 0 ) )
//------------------------------------------------------------------------------
// MESA calculations from the MESA indicator
//------------------------------------------------------------------------------
// Basic
//------------------------------------------------------------------------------
DomCycle = 15
RealPart = 0.0
ImagPart = 0.0
for J = 0 to DomCycle - 1
Weight = (close[J] + close[J] + high[J] + low[J]) * 10000
if DomCycle != 0
RealPart := RealPart + math.cos(90 * J / DomCycle) * Weight * 2
ImagPart := ((ImagPart + math.sin(90 * J / DomCycle) * Weight) + (ImagPart + math.sin(180 * J / DomCycle) * Weight)) / 2
Phase = ((math.atan(ImagPart / RealPart)) - 0.685) * 100
//------------------------------------------------------------------------------
//Pivot
//------------------------------------------------------------------------------
ph_mesa = ta.pivothigh(Phase, 1, 1)
pl_mesa = ta.pivotlow(Phase, 1, 1)
out_zone = Phase[2] < pivot_zone_lower or Phase[2] > pivot_zone_upper
plotshape(i_show_mesa and ph_mesa and out_zone ? ph_mesa : na, title = "Pivot High", color=#f23737, style = shape.circle, location = location.abovebar, offset = -1, size = size.tiny)
plotshape(i_show_mesa and pl_mesa and out_zone ? pl_mesa : na, title = "Pivot Low", color=#169788, style = shape.circle, location = location.belowbar, offset = -1, size = size.tiny)
//------------------------------------------------------------------------------
// cRSI indicator code
//------------------------------------------------------------------------------
crsi = 0.0
vibration = 10
torque = 0.618 / (vibration + 1)
phasingLag = (vibration - 1) / 0.618
rsi = ta.rsi(i_src, i_i_len)
crsi := torque * (2 * rsi - rsi[phasingLag]) + (1 - torque) * nz(crsi[1])
float osc = crsi
float ph = ta.highestbars(high, i_i_len) == 0 ? osc : na
float pl = ta.lowestbars(low, i_i_len) == 0 ? osc : na
var int dir = 0
dir := ph and na(pl) ? 1 : pl and na(ph) ? -1 : dir
var max_array_size = 10
var arr_zz = array.new_float(0)
older_zz = array.copy(arr_zz)
dirchanged = ta.change(dir)
add_to_zigzag(_id, float value, int bindex) =>
array.unshift(_id, bindex)
array.unshift(_id, value)
if array.size(_id) > max_array_size
array.pop(_id)
array.pop(_id)
update_zigzag(_id, float value, int bindex, int dir) =>
if array.size(_id) == 0
add_to_zigzag(_id, value, bindex)
else
if dir == 1 and value > array.get(_id, 0) or dir == -1 and value < array.get(_id, 0)
array.set(_id, 0, value)
array.set(_id, 1, bindex)
0.
if ph or pl
if dirchanged
add_to_zigzag(arr_zz, dir == 1 ? ph : pl, bar_index)
else
update_zigzag(arr_zz, dir == 1 ? ph : pl, bar_index, dir)
if array.size(arr_zz) >= 6
// Variables
var label label_zz = na
// Bools for or
bool bool_or_1 = array.get(arr_zz, 0) != array.get(older_zz, 0)
bool bool_or_2 = array.get(arr_zz, 1) != array.get(older_zz, 1)
// Bools for and
bool bool_n_1 = array.get(arr_zz, 2) == array.get(older_zz, 2)
bool bool_n_2 = array.get(arr_zz, 3) == array.get(older_zz, 3)
// Bools for more than and less than
bool bool_0_mt_4 = array.get(arr_zz, 0) > array.get(arr_zz, 4)
bool bool_0_lt_4 = array.get(arr_zz, 0) < array.get(arr_zz, 4)
if bool_or_1 or bool_or_2
if bool_n_1 and bool_n_2
label.delete(label_zz)
str_label = dir == 1 ? bool_0_mt_4 ? '▼' : '◍' :
bool_0_lt_4 ? '▲' : '◍'
col_label = dir == 1 ? bool_0_mt_4 ? color.red : color.teal :
bool_0_lt_4 ? color.teal : color.red
if i_show_crsi
label_zz := label.new(bar_index, high, text = str_label, color = color.new(color.blue, 100), textcolor = col_label, style=dir == 1 ? label.style_label_down : label.style_label_up )
if dir == 1
cRSI_high_extreme_found := close
cRSI_low_extreme_found := 0.0
last_cRSI_extreme := "high"
else
cRSI_low_extreme_found := close
cRSI_high_extreme_found := 0.0
last_cRSI_extreme := "low"
if i_use_crsi and last_cRSI_extreme == "high" and cRSI_high_extreme_found > 0.0
cRSI_trend_direction := "sell"
if i_use_crsi and last_cRSI_extreme == "low" and cRSI_low_extreme_found > 0.0
cRSI_trend_direction := "buy"
var order_prices = array.new_float(3, 0.0) // entry price
array.push(order_prices, 0.0) // exit price
array.push(order_prices, 0.0) // stop price
var order_types = array.new_string(1, "") // order type
var our_active_orders_count = array.new_int(1, 0)
max_pivot_size = 10
zigzagColor = color.black
showZigZag = true
var zigzagpivots = array.new_float(0)
var zigzagpivotbars = array.new_int(0)
var zigzagpivotdirs = array.new_int(0)
var waveLinesArray = array.new_line(2)
var targetLabels = array.new_label(0)
var targetLines = array.new_line(0)
var wavelines = array.new_line(0)
transparent = color.new(#FFFFFF, 100)
err_min = (100-errorPercent)/100
err_max = (100+errorPercent)/100
entry_range = (entryPercent)/100
var patterncount = array.new_int(2,0)
pivots(length)=>
float phigh = ta.highestbars(high, length) == 0 ? high : na
float plow = ta.lowestbars(low, length) == 0 ? low : na
dir = 0
dir := phigh and na(plow) ? 1 : plow and na(phigh) ? -1 : dir[1]
[dir, phigh, plow]
zigzag(length, zigzagpivots, zigzagpivotbars, zigzagpivotdirs)=>
[dir, phigh, plow] = pivots(length)
dirchanged = ta.change(dir)
if(phigh or plow)
value = (dir == 1? phigh : plow)
bar = bar_index
if(not dirchanged and array.size(zigzagpivots) >=1)
pivot = array.shift(zigzagpivots)
pivotbar = array.shift(zigzagpivotbars)
pivotdir = array.shift(zigzagpivotdirs)
value:= value*pivotdir < pivot*pivotdir? pivot : value
bar:= value*pivotdir < pivot*pivotdir? pivotbar : bar
if(array.size(zigzagpivots) >=2)
LastPoint = array.get(zigzagpivots,1)
dir := dir*value > dir*LastPoint? dir*2 : dir
array.unshift(zigzagpivots, value = value)
array.unshift(zigzagpivotbars, bar)
array.unshift(zigzagpivotdirs, dir)
if(array.size(zigzagpivots) > max_pivot_size)
array.pop(zigzagpivots)
array.pop(zigzagpivotbars)
array.pop(zigzagpivotdirs)
draw_zigzag(zigzagpivots, zigzagpivotbars, zigzagcolor, zigzagwidth, zigzagstyle, showZigZag)=>
if(array.size(zigzagpivots) > 2 and showZigZag)
for i=0 to array.size(zigzagpivots)-2
y1 = array.get(zigzagpivots, i)
y2 = array.get(zigzagpivots, i+1)
x1 = array.get(zigzagpivotbars, i)
x2 = array.get(zigzagpivotbars, i+1)
zline = line.new(x1=x1, y1=y1,
x2 = x2, y2=y2,
color=zigzagcolor, width=zigzagwidth, style=zigzagstyle)
//////////////////////////////////// Draw Lines with labels //////////////////////////////////////////////////
f_drawLinesWithLabels(target, lbl, linecolor)=>
timeDiffEnd = time - time[10]
timeDiffLabel = time - time[5]
line_x1 = time
line_x2 = time+timeDiffEnd
label_x = time+timeDiffLabel
targetLine = line.new(x1=line_x1, y1=target, x2=line_x2, y2=target, color=linecolor, xloc=xloc.bar_time)
targetLabel = label.new(x=label_x, y=target, text=lbl + " : "+str.tostring(target), xloc=xloc.bar_time, style=label.style_none, textcolor=color.black, size=size.normal)
[targetLine,targetLabel]
//////////////////////////////////// Delete Lines with labels //////////////////////////////////////////////////
f_deleteLinesWithLabels(targetLine, targetLabel)=>
line.delete(targetLine)
label.delete(targetLabel)
ew_impulse(zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagWidth, zigzagStyle, showZigZag, waveLinesArray, targetLines, targetLabels)=>
start = waitForConfirmation? 1: 0
waveFound = false
if(array.size(zigzagpivots) >= 3+start and showZigZag)
Point2 = array.get(zigzagpivots, start)
Point2Bar = array.get(zigzagpivotbars, start)
Point2Dir = array.get(zigzagpivotdirs, start)
Point1 = array.get(zigzagpivots, start+1)
Point1Bar = array.get(zigzagpivotbars, start+1)
Point1Dir = array.get(zigzagpivotdirs, start+1)
Point0 = array.get(zigzagpivots, start+2)
Point0Bar = array.get(zigzagpivotbars, start+2)
Point0Dir = array.get(zigzagpivotdirs, start+2)
W1Length = math.abs(Point1-Point0)
W2Length = math.abs(Point2-Point1)
r2 = W2Length/W1Length
existingW1 = array.get(waveLinesArray, 0)
existingW2 = array.get(waveLinesArray, 1)
existing0 = line.get_y1(existingW1)
existing1 = line.get_y1(existingW2)
existing2 = line.get_y2(existingW2)
dir_crsi = 0
if i_use_crsi
if cRSI_trend_direction != ""
if cRSI_trend_direction == "buy"
dir_crsi := 1
else if cRSI_trend_direction == "sell"
dir_crsi := -1
else
dir_crsi := Point0 > Point1 ? -1 : 1
else
dir_crsi := Point0 > Point1 ? -1 : 1
else
dir_crsi := Point0 > Point1? -1 : 1
dir = Point0 > Point1? -1 : 1
//label.new(bar_index, high, cRSI_trend_direction + ", " + str.tostring( dir_crsi ) + " / " + str.tostring( dir ) )
if dir_crsi == dir
entry = Point2 + dir*entry_range*W2Length
stop = Point0
tstop = Point2 - dir*entry_range*W2Length
target1 = Point2 + dir*1.618*W2Length
target2 = Point2 + dir*2.0*W2Length
target3 = Point2 + dir*2.618*W2Length
target4 = Point2 + dir*3.236*W2Length
stopColor = dir == 1? color.red : color.green
targetColor = dir == 1? color.green : color.red
ignore = false
patternMatched = false
dirMatched = false
if(existing0 == Point0 or existing1 == Point1 or existing2 == Point2)
ignore := true
if(r2 > 0.50*err_min and r2 < 0.50*err_max) or (r2 > 0.618*err_min and r2 < 0.618*err_max) or
(r2 > 0.764*err_min and r2 < 0.764*err_max) or (r2 > 0.854*err_min and r2 < 0.854*err_max)
patternMatched := true
if(Point1Dir == 2 and Point2Dir == -1) or (Point1Dir == -2 and Point2Dir == 1)
dirMatched := true
directionColor = Point1 > Point2 ? color.green : color.red
if(not ignore and patternMatched and dirMatched)
w1 = line.new(y1=Point0, y2=Point1, x1=Point0Bar, x2=Point1Bar, color=directionColor, width=zigzagWidth, style=zigzagStyle)
w2 = line.new(y1=Point1, y2=Point2, x1=Point1Bar, x2=Point2Bar, color=directionColor, width=zigzagWidth, style=zigzagStyle)
array.set(waveLinesArray,0,w1)
array.set(waveLinesArray,1,w2)
if(array.size(targetLines) > 0)
for i=0 to array.size(targetLines)-1
line.delete(array.shift(targetLines))
for i=0 to array.size(targetLabels)-1
label.delete(array.shift(targetLabels))
[entryLine,entryLabel] = f_drawLinesWithLabels(entry, "Entry", color.blue)
[stopLine,stopLabel] = f_drawLinesWithLabels(stop, "Stop", stopColor)
[tstopLine,tstopLabel] = f_drawLinesWithLabels(tstop, "T.Stop", stopColor)
[t1Line,t1Label] = f_drawLinesWithLabels(target1, "Target - 1", targetColor)
[t2Line,t2Label] = f_drawLinesWithLabels(target2, "Target - 2", targetColor)
[t3Line,t3Label] = f_drawLinesWithLabels(target3, "Target - 3", targetColor)
[t4Line,t4Label] = f_drawLinesWithLabels(target4, "Target - 4", targetColor)
// store info for a new trade and also cancel any old ones, since we found a new wave here
if strategy.opentrades > 0
if strategy.opentrades.entry_id( strategy.opentrades - 1 ) == "Buy"
if close >= strategy.opentrades.entry_price( strategy.opentrades - 1 )
strategy.close( "Buy", comment = "close buy (new wave), profit" )
else
strategy.close( "Buy", comment = "close buy (new wave), loss" )
if strategy.opentrades.entry_id( strategy.opentrades - 1 ) == "Sell"
if close <= strategy.opentrades.entry_price( strategy.opentrades - 1 )
strategy.close( "Sell", comment = "close sell (new wave), profit" )
else
strategy.close( "Sell", comment = "close sell (new wave), loss" )
tradeType = ( Point1 > Point2 ? "Buy" : "Sell" )
array.set(order_prices, 0, entry)
target_real = switch target2reach
"TP1 (1.618 fibo)" => target1
"TP2 (2.0 fibo)" => target2
"TP3 (2.618 fibo)" => target3
"TP4 (3.236 fibo)" => target4
array.set(order_prices, 1, target_real)
array.set(order_prices, 2, stop)
array.set(order_types, 0, tradeType)
array.set( our_active_orders_count, 0, 0 )
array.unshift(targetLines, entryLine)
array.unshift(targetLines, stopLine)
array.unshift(targetLines, tstopLine)
array.unshift(targetLines, t1Line)
array.unshift(targetLines, t2Line)
array.unshift(targetLines, t3Line)
array.unshift(targetLines, t4Line)
array.unshift(targetLabels, entryLabel)
array.unshift(targetLabels, stopLabel)
array.unshift(targetLabels, tstopLabel)
array.unshift(targetLabels, t1Label)
array.unshift(targetLabels, t2Label)
array.unshift(targetLabels, t3Label)
array.unshift(targetLabels, t4Label)
count_index = dir==1?0:1
array.set(patterncount, count_index, array.get(patterncount, count_index)+1)
waveFound := true
if(existing0 == Point0 and existing1 == Point1 and existing2 == Point2) and waveFound[1]
line.delete(existingW1)
line.delete(existingW2)
array.set(patterncount, count_index, array.get(patterncount, count_index)-1)
waveFound
zigzag(zigzagLength, zigzagpivots, zigzagpivotbars, zigzagpivotdirs)
waveFormed = ew_impulse(zigzagpivots, zigzagpivotbars, zigzagpivotdirs, zigzagWidth, zigzagStyle, showZigZag, waveLinesArray, targetLines, targetLabels)
var stats = table.new(position = position.top_right, columns = 3, rows = max_pivot_size+2, border_width = 1)
trade_type = array.get(order_types, 0)
entry_price = array.get(order_prices, 0)
exit_price = array.get(order_prices, 1)
stop_price = array.get(order_prices, 2)
// close trades when price reaches our target
exit_bool = array.get( our_active_orders_count, 0 ) > 0 and (trade_type == "Buy" ? close >= exit_price : close <= exit_price )
//label.new(bar_index, high, trade_type + ", " + str.tostring( close ) + " / " + str.tostring( exit_price ) )
if exit_price > 0 and strategy.opentrades > 0 and exit_bool
strategy.close( trade_type, comment = trade_type + " TP reached" )
array.set(order_prices, 0, 0.0)
array.set(order_prices, 1, 0.0)
array.set(order_prices, 2, 0.0)
array.set(order_types, 0, "")
array.set( our_active_orders_count, 0, 0 )
// remove trades from internal cache when they reach SL
sl_bool = array.get( our_active_orders_count, 0 ) > 0 and (trade_type == "Buy" ? close <= stop_price : close >= stop_price )
//label.new(bar_index, high, trade_type + ", " + str.tostring( close ) + " / " + str.tostring( exit_price ) )
if stop_price > 0 and strategy.opentrades > 0 and sl_bool
array.set(order_prices, 0, 0.0)
array.set(order_prices, 1, 0.0)
array.set(order_prices, 2, 0.0)
array.set(order_types, 0, "")
array.set( our_active_orders_count, 0, 0 )
// open trades when the price reached our entry
entry_bool = array.get( our_active_orders_count, 0 ) == 0 and (trade_type == "Buy" ? close <= entry_price : close >= entry_price )
if entry_price > 0 and ( strategy.opentrades == 0 or strategy.opentrades.entry_id( strategy.opentrades - 1 ) != trade_type ) and entry_bool
// check if we're also using MESA to wait for a better entry
// first check that we've not beyond our SL...
if i_use_mesa and (trade_type == "Buy" ? close <= stop_price : close >= stop_price )
// SL reached, invalidate this trade and mark it on chart
array.set(order_prices, 0, 0.0)
array.set(order_prices, 1, 0.0)
array.set(order_prices, 2, 0.0)
array.set(order_types, 0, "")
array.set( our_active_orders_count, 0, 0 )
if inDateRange and show_sl_invalidation_labels
label.new(bar_index, high, trade_type + " invalidated at SL", color = color.white, textcolor = color.black )
// now check that we have a better entry through MESa
if ( inDateRange and ( time - last_trade_ts ) / 1000 >= ( 60 * min_trade_gap_minutes ) and ( not i_use_mesa or ( trade_type == "Buy" and ( ( ph_mesa and out_zone ) ? ph_mesa : na ) ) or ( trade_type == "Sell" and ( ( pl_mesa and out_zone ) ? pl_mesa : na ) ) ) )
label.new(bar_index, high, str.tostring(( time - last_trade_ts ) / 1000) + " / " + str.tostring( 60 * min_trade_gap_minutes ) )
strategy.entry( trade_type, trade_type == "Buy" ? strategy.long : strategy.short )
strategy.exit( trade_type, stop = stop_price, comment = "closed by SL" )
array.set( our_active_orders_count, 0, 1 )
last_trade_ts := time
if trade_type == "Buy"
cRSI_low_extreme_found := 0.0
else
cRSI_high_extreme_found := 0.0
if(barstate.islast)
table.cell(table_id = stats, column = 1, row = 0 , text = "Bullish", bgcolor=color.black, text_color=color.white)
table.cell(table_id = stats, column = 2, row = 0 , text = "Bearish", bgcolor=color.black, text_color=color.white)
dtColor = color.white
for type = 1 to (array.size(patterncount)/2)
for direction = 0 to 1
count_index = (type*2 - 2) + direction
row = type
column = direction+1
txt = str.tostring(array.get(patterncount, count_index))
table.cell(table_id = stats, column = column, row = row, text = txt, bgcolor=dtColor)
// Exit open market position when date range ends
if (not inDateRange)
strategy.close_all() |
DELAYED FIBO | https://www.tradingview.com/script/HlQUq5AS/ | drhakankilic | https://www.tradingview.com/u/drhakankilic/ | 47 | 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/
// © drhakankilic
//@version=5
strategy("FIBONACCI BANDS Long Strategy", shorttitle="FBANDS L Strategy", overlay=true, pyramiding=1, initial_capital = 1000, default_qty_type = strategy.cash, default_qty_value = 1000,
process_orders_on_close=true, commission_value=0.075, max_bars_back=500, max_lines_count=500, currency = 'USD')
// === Date === {
//Backtest dates
fromDay = input.int(defval=1, title='From Day',minval=1,maxval=31)
fromMonth = input.int(defval=1, title='From Month',minval=1,maxval=12)
fromYear = input.int(defval=2020, title='From Year')
thruDay = input.int(defval=1, title='Thru Day',minval=1,maxval=31)
thruMonth = input.int(defval=1, title='Thru Month',minval=1,maxval=12)
thruYear = input.int(defval=2112, title='Thru Year')
showDate = true // input(defval=true, title="Show Date Range")
start = timestamp(fromYear, fromMonth, fromDay, 00, 00) // backtest start window
finish = timestamp(thruYear, thruMonth, thruDay, 23, 59) // backtest finish window
window() => // create function "within window of time"
time >= start and time <= finish ? true : false
// }
// === Line === {
sumd(series, distance) =>
sumd = 0.0
for i = 0 to distance
sumd := sumd + series[i]
sumd
ldistance_level = input.int(title="long distance level", defval=2)
sdistance_level = input.int(title="short distance level", defval=1)
lsumV = sumd(volume,ldistance_level+sdistance_level)
ssumV = sumd(volume,sdistance_level)
lsumV:=lsumV-ssumV
vrate = ssumV/lsumV
vrate_level = input.float(title="vrate level", defval=0.1)
vt = close*(vrate>vrate_level?1:0)
if(vt==0)
vt:=vt[1]
// plot(vt, color=color.blue, title="MPT")
// plot(close, color=color.red,title="PRICE")
// }
// === FIBONACCI BANDS === {
EMAperiod = input.int(14, title='EMAperiod', minval=1, maxval=500, group="Fibonacci")
ATRperiod = input.int(14, title='ATRperiod', minval=1, maxval=500, group="Fibonacci")
EMA = ta.ema(close, EMAperiod)
TR1 = math.max(high - low, math.abs(high - close[1]))
TR = math.max(TR1, math.abs(low - close[1]))
ATR = ta.sma(TR, ATRperiod)
F2 = input(defval=1.618, title='Fibonacci Ratio 2', group="Fibonacci")
F3 = input(defval=2.618, title='Fibonacci Ratio 3', group="Fibonacci")
F4 = input(defval=4.236, title='Fibonacci Ratio 4', group="Fibonacci")
R1 = ATR
R2 = ATR * F2
R3 = ATR * F3
R4 = ATR * F4
FIBOTOP4 = EMA + R4
FIBOTOP3 = EMA + R3
FIBOTOP2 = EMA + R2
FIBOTOP1 = EMA + R1
FIBOBOT1 = EMA - R1
FIBOBOT2 = EMA - R2
FIBOBOT3 = EMA - R3
FIBOBOT4 = EMA - R4
plot(FIBOTOP4, title='FIBOTOP4', linewidth=1, color=color.new(color.orange, 0))
plot(FIBOTOP3, title='FIBOTOP3', linewidth=1, color=color.new(color.aqua, 20))
plot(FIBOTOP2, title='FIBOTOP2', linewidth=1, color=color.new(color.gray, 40))
plot(FIBOTOP1, title='FIBOTOP1', linewidth=1, color=color.new(color.purple, 40))
plot(FIBOBOT1, title='FIBOBOT1', linewidth=1, color=color.new(color.green, 40))
plot(FIBOBOT2, title='FIBOBOT2', linewidth=1, color=color.new(color.yellow, 40))
plot(FIBOBOT3, title='FIBOBOT3', linewidth=1, color=color.new(color.blue, 20))
plot(FIBOBOT4, title='FIBOBOT4', linewidth=1, color=color.new(color.aqua, 0))
// plot(EMA[1], style=plot.style_cross, title='EMA', color=color.new(color.red, 0))
prefmS = input.string(title="FiboLong", options=["cross_FIBOBOT1(green)", "cross_FIBOBOT2(yellow)", "cross_FIBOBOT3(blue)", "cross_FIBOBOT4(aqua)", "Disable"] , defval="cross_FIBOBOT2(yellow)", group="Long")
_prefmS = false
if (prefmS == "cross_FIBOBOT1(green)" )
_prefmS := ta.crossunder(vt, FIBOBOT1)
if (prefmS == "cross_FIBOBOT2(yellow)" )
_prefmS := ta.crossunder(vt, FIBOBOT2)
if (prefmS == "cross_FIBOBOT3(blue)" )
_prefmS := ta.crossunder(vt, FIBOBOT3)
if (prefmS == "cross_FIBOBOT4(aqua)" )
_prefmS := ta.crossunder(vt, FIBOBOT4)
if (prefmS == "Disable" )
_prefmS := low<low[1] or low>low[1]
// }
longs= _prefmS
//
// === Bot Codes === {
enterlong = input("Long Code", title='Long Enter', group="Long Code")
exitlong = input("Long Exit Code", title='Long Exit', group="Long Code")
// }
// === Extra === {
tpslacL= input(true, title="TakeProfit StopLoss Aktif Et", group="ðŸ³Long")
// }
////////////////////////////////////////////////////////////////////////////////////////////TPSL
// === TP SL === {
per(pcnt) =>
strategy.position_size > 0 and tpslacL ? math.round(pcnt / 100 * strategy.position_avg_price / syminfo.mintick) : float(na)
trof = 0
stoplossL = input.float(title=" Stop loss", defval= 1.9, minval=0.1, step=0.1, group="ðŸ³Long")
tpL = input.float(title=" Take profit", defval= 0.7, minval=0.1, step=0.1, group="ðŸ³Long")
// }
////////////////////////////////////////////////////////////////////////////////////////////
strategy.entry("AL", strategy.long, when= longs and window(), alert_message=enterlong, comment="Long")
strategy.close("AL", when= ta.cross(vt, FIBOTOP3), alert_message = exitlong, comment="Cross")
strategy.exit("AL", profit = per(tpL), loss = per(stoplossL), trail_points=per(tpL+0.1) , trail_offset=trof, alert_message = exitlong, comment="TPorSL")
|
AryaN | https://www.tradingview.com/script/uYWw9T8d-AryaN/ | sandipkindo | https://www.tradingview.com/u/sandipkindo/ | 16 | 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/
// © sandipkindo
//@version=5
strategy("My strategyP", overlay=true, margin_long=100, margin_short=100)
longCondition = ta.crossover(ta.ema(close, 5), ta.ema(close, 10))
if (longCondition)
strategy.entry("Buy", strategy.long)
shortCondition = ta.crossunder(ta.ema(close, 6), ta.ema(close, 11))
if (shortCondition)
strategy.entry("Sell" , strategy.short)
|
COT + ema + aux ticker | https://www.tradingview.com/script/85z5jM3u/ | Fanoooo | https://www.tradingview.com/u/Fanoooo/ | 74 | 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/
// © Noldo
//@version=4
strategy("COT + ema + aux ticker", overlay=true, default_qty_type = strategy.percent_of_equity, default_qty_value = 10)
src = close
bFX = false
startDate = input(title="Start Date", type=input.integer,
defval=1, minval=1, maxval=31)
startMonth = input(title="Start Month", type=input.integer,
defval=1, minval=1, maxval=12)
startYear = input(title="Start Year", type=input.integer,
defval=2010, minval=1800, maxval=2100)
afterStartDate = (time >= timestamp(syminfo.timezone,
startYear, startMonth, startDate, 0, 0))
string ticket00 = input(defval='EUR', type=input.string, options=["AUD","GBP","CAD","EUR","JPY","CHF","NZD","USD"], title='1st', group='Tickets:', inline='T0')
string ticket01 = input(defval='EUR', type=input.string, options=["AUD","GBP","CAD","EUR","JPY","CHF","NZD","USD"],title='2nd', group='Tickets:', inline='T0')
usecot = input(title="COT ON/OFF", type=input.bool, defval=true)
useema = input(title="EMA ON/OFF", type=input.bool, defval=true)
len = input(4, minval=1, title="Length")
srcsma = input(close, title="Source")
offset = input(title="Offset COT", defval=0, minval=0, maxval=10)
out = ema(srcsma, len)
useaux1 = input(title="Aux 1 ON/OFF", type=input.bool, defval=true)
auxinv1 = input(title="Aux 1 inv.", type=input.bool, defval=false)
lenaux1 = input( 4, minval=1, title="Ema aux 1 period.")
auxsma1 = input(title="AUX Symbol", type=input.symbol, defval="DELL")
s1 = security(auxsma1, "W", close)
outaux1 = ema(s1, lenaux1)
useaux2 = input(title="Aux 2 ON/OFF", type=input.bool, defval=true)
auxinv2 = input(title="Aux 2 inv.", type=input.bool, defval=false)
lenaux2 = input( 4, minval=1, title="Ema aux 2 period.")
auxsma2 = input(title="AUX 2 Symbol", type=input.symbol, defval="DELL")
s2 = security(auxsma2, "W", close)
outaux2 = ema(s2, lenaux2)
//Can't set bFX as an input because plot and legend titles require literals
// INPUTS
sCalc = "MARKETS"
// ***** MARKET TYPES *****
// Financial Markets (Commercial)
bTotal = (sCalc == "MARKETS")
sHead = "QUANDL:CFTC/"
sLong = "_F_L_ALL|4"
sShort = "_F_L_ALL|5"
iWidth = 2
// Non-Commercials (Speculators)
bTotal2 = (sCalc == "NON-COMS")
sHead2 = "QUANDL:CFTC/"
sLong2 = "_F_L_ALL|1"
sShort2 = "_F_L_ALL|2"
iWidth2 = 2
//***** CFTC MARKET CODES *****
// 1 - Futures
sCode1 =
ticket00 == "AUD" ? "232741" :
ticket00 == "GBP" ? "096742" :
ticket00 == "CAD" ? "090741" :
ticket00 == "EUR" ? "099741" :
ticket00 == "JPY" ? "097741" :
ticket00 == "CHF" ? "092741" :
ticket00 == "NZD" ? "112741" :
ticket00 == "USD" ? "098662" :
""
sCode2 =
ticket01 == "AUD" ? "232741" :
ticket01 == "GBP" ? "096742" :
ticket01 == "CAD" ? "090741" :
ticket01 == "EUR" ? "099741" :
ticket01 == "JPY" ? "097741" :
ticket01 == "CHF" ? "092741" :
ticket01 == "NZD" ? "112741" :
ticket01 == "USD" ? "098662" :
""
//Titles
sTitle1 = "1st Ticker"
// COT CFTC Auto Generation Codes
//Data functions
dLong(asCode) => security(sHead + asCode + (sLong), "W", close[0 + offset] - close[1 + offset], lookahead=barmerge.lookahead_on)
dShort(asCode) => security(sHead +asCode + (sShort), "W", close[0 + offset] - close[1 + offset], lookahead=barmerge.lookahead_on)
// COMMERCIALS 1 ticker
_pos_coms1_short = dShort(sCode1)
_pos_coms1_long = dLong (sCode1)
net_com1 = _pos_coms1_long - _pos_coms1_short
// COMMERCIALS 2 ticker
sTitle2 = "2nd Ticker"
dLong2(asCode2) => security(sHead + asCode2 + (sLong), "W", close[0 + offset] - close[1 + offset], lookahead=barmerge.lookahead_on)
dShort2(asCode2) => security(sHead +asCode2 + (sShort), "W", close[0 + offset] - close[1 + offset], lookahead=barmerge.lookahead_on)
_pos_coms2_long = dLong2(sCode2)
_pos_coms2_short = dShort2(sCode2)
net_com2 = _pos_coms2_long - _pos_coms2_short
buy = false
sell = false
//if(not useaux1)
// buy := (net_com1 > 0) and (net_com2 < 0) and (out[0] > out[1]) and afterStartDate
// sell := (net_com1 < 0) and (net_com2 > 0) and (out[0] < out[1]) and afterStartDate
// Plot data
buy_aux1 = false
buy_aux2 = false
sell_aux1 = false
sell_aux2 = false
buy_cot = ((net_com1 > 0) and (net_com2 < 0) and usecot) or (not usecot)
sell_cot = ((net_com1 < 0) and (net_com2 > 0) and usecot) or (not usecot)
buy_ema = ((out[0] > out[1]) and useema) or (not useema)
sell_ema = ((out[0] < out[1]) and useema) or (not useema)
if(auxinv1)
buy_aux1 := ((outaux1[0]<outaux1[1]) and useaux1) or (not useaux1)
sell_aux1 := ((outaux1[0]>outaux1[1]) and useaux1) or not useaux1
if not auxinv1
buy_aux1:= ((outaux1[0]>outaux1[1]) and useaux1) or not useaux1
sell_aux1 := ((outaux1[0]<outaux1[1]) and useaux1) or not useaux1
if auxinv2
buy_aux2 := ((outaux2[0]<outaux2[1]) and useaux2) or not useaux2
sell_aux2 := ((outaux2[0]>outaux2[1]) and useaux2) or not useaux2
if not auxinv2
buy_aux2:= ((outaux2[0]>outaux2[1]) and useaux2) or not useaux2
sell_aux2 := ((outaux2[0]<outaux2[1]) and useaux2) or not useaux2
buy := buy_cot and buy_ema and buy_aux1 and buy_aux2 and afterStartDate
sell := sell_cot and sell_ema and sell_aux1 and sell_aux2 and afterStartDate
if (sell)
strategy.entry("Short", strategy.short, qty = 100000)
strategy.exit("SL-TP Short","Short",stop = high[0])
if (buy)
strategy.entry("Long", strategy.long, qty = 100000)
strategy.exit("SL-TP Long","Long",stop = low[0])
//if close[0] < close[1] or close[0] > close[1]
// strategy.close("Short")
// strategy.close("Long")
if strategy.openprofit > 0
strategy.close("Short")
strategy.close("Long")
plotshape(buy, style=shape.triangleup, location=location.belowbar, offset=0, color=color.green, size = size.small)
plotshape(sell, style=shape.triangledown, location=location.abovebar, offset=0, color=color.red, size = size.small)
|
RELATIVE VALUE TRADE MANAGEMENT WEBHOOK | https://www.tradingview.com/script/jGXUH6bN/ | ExpensiveJok | https://www.tradingview.com/u/ExpensiveJok/ | 40 | 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/
// © ExpensiveJok
// The purpose of this script is send orders and provide stops levels for our relative trades.
//@version=5
strategy("RELATIVES MANAGEMENT", overlay=true, margin_long=100, margin_short=100, initial_capital = 1000, precision = 8)
//---------------------------------------------------------------- TIPS ---------------------------------------------------------------------------
long_tick_tip = "This is the EXACT ticker name of the active you want to be LONG. It is important add the exchange, or market, for a correct work. Example : BINANCE:SUSHIUSDTPERP"
short_tick_tip = "This is the EXACT ticker name of the active you want to be SHORT. It is important add the exchange, or market, for a correct work. Example : BINANCE:IOTXUSDTPERP"
time_frame_tip = "Select the timeframe for the orders. Also it is the timeframe of the RELATIVE GRAPH that you can deploy."
lvl_in_tip = "It is the entry level based in the relative graph."
lvl_out_tip = "It is the STOP LOSS level based in the relative graph."
lvl_tp_tip = "It is the TAKE PROFIT level based in the relative graph."
qty_type_tip= "It allows you to select the type of risk for the order. You can choose between a permanent qty (in dollars or other currency) or a percent of your equity."
qty_tip = "It is the quantity you will lose if the STOP LOSS is triggered."
qty_exit_tip= "It is the close percent of the order if the TAKE PROFIT is triggered."
id_long_tip = "If you have a current open position write here the LONG side ID in case that you want to close the signal via STOPs. If your position is not open leave it in blank."
id_short_tip= "If you have a current open position write here the SHORT side ID in case that you want to close the signal via STOPs. If your position is not open leave it in blank."
//---------------------------------------------------------------- INPUTS ----------------------------------------------------------------------------
long_tick = input.string(title = "Ticker Long" , defval = "", tooltip = long_tick_tip , group = "-- ACTIVES --")
short_tick = input.string(title = "Ticker Short" , defval = "", tooltip = short_tick_tip , group = "-- ACTIVES --")
time_frame = input.string(title = "Timeframe" , defval = "4h", options = ["15min", "1h", "4h", "D", "W"], tooltip = time_frame_tip, group = "-- ACTIVES --")
lvl_in = input.float(title = "Nivel de entrada", defval = 0, step = 1, minval = 0, tooltip = lvl_in_tip , group = "-- LEVELS --")
lvl_out = input.float(title = "Nivel de SL" , defval = 0, step = 1, minval = 0, tooltip = lvl_out_tip , group = "-- LEVELS --")
lvl_tp = input.float(title = "Nivel de TP" , defval = 0, step = 1, minval = 0, tooltip = lvl_tp_tip , group = "-- LEVELS --")
leverage= input.int (title = "Leverage", defval = 1, minval = 1 , group = "-- MONEY MANAGEMENT --")
qty_type= input.string (title = "Risk", defval = "Money Amount", options = ["Money Amount", "Equity Percent"] , tooltip = qty_type_tip, group = "-- MONEY MANAGEMENT --")
qty = input.int (title = "Quantity risk" , defval = 10, minval = 1 , tooltip = qty_tip , group = "-- MONEY MANAGEMENT --")
qty_exit= input.int (title = "Order close percent" , defval = 100, minval = 1, step = 1 , tooltip = qty_exit_tip, group = "-- MONEY MANAGEMENT --")
//DATE
date_in = input.time (title = "Date of beginning" , defval = timestamp("1 Jul 2020 00:00 +0300") , group = "-- DATES --")
date_out = input.time (title = "Date of ending" , defval = timestamp("20 Jul 2022 00:00 +0300") , group = "-- DATES --")
//ZIGNALY
id_long = input.string(title = "Long ID", defval = "", tooltip = id_long_tip , group = "-- IDs --")
id_short= input.string(title = "Short ID",defval = "", tooltip = id_short_tip , group = "-- IDs --")
//TABLE
table_on = input.bool(title = "Deploy Table", defval = true , group = "-- DATA --")
table_bg_c = input.color(defval = color.gray, title = "Table Background Color")
table_txt_c = input.color(defval = color.white, title = "Text Color")
table_pos = input.string(defval = "Top Right", title = "Table Position", options = ["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left",
"Bottom Center", "Bottom Right"])
//---------------------------------------------------------------- PROCESS ----------------------------------------------------------------------------
confirm = barstate.isconfirmed ? 0 : 1
//------------- RELATIVES GRAPH
time_scale = switch time_frame
"15min" => "15"
"1h" => "60"
"4h" => "240"
"D" => "1D"
"W" =>"1W"
// I request the OHLC values to draw the graph in the same window.
// ACTIVES REQUEST
ohlc_side_long() =>
o = request.security(symbol = long_tick, timeframe = time_scale, expression = open[confirm], gaps = barmerge.gaps_on)
h = request.security(symbol = long_tick, timeframe = time_scale, expression = high[confirm], gaps = barmerge.gaps_on)
l = request.security(symbol = long_tick, timeframe = time_scale, expression = low[confirm], gaps = barmerge.gaps_on)
c = request.security(symbol = long_tick, timeframe = time_scale, expression =close[confirm], gaps = barmerge.gaps_on)
[o,h,l,c]
ohlc_side_short() =>
o = request.security(symbol = short_tick, timeframe = time_scale, expression = open[confirm], gaps = barmerge.gaps_on)
h = request.security(symbol = short_tick, timeframe = time_scale, expression = high[confirm], gaps = barmerge.gaps_on)
l = request.security(symbol = short_tick, timeframe = time_scale, expression = low[confirm], gaps = barmerge.gaps_on)
c = request.security(symbol = short_tick, timeframe = time_scale, expression =close[confirm], gaps = barmerge.gaps_on)
[o,h,l,c]
[open_long, high_long, low_long, close_long] = ohlc_side_long()
[open_short, high_short, low_short, close_short]= ohlc_side_short()
open_graph = open_long / open_short
high_graph = high_long / high_short
low_graph = low_long / low_short
close_graph = close_long/ close_short
//------------------ STOPS
stop_dif= (lvl_in - lvl_out) < 0 ? (lvl_in - lvl_out) * (-1) : (lvl_in - lvl_out) //Difference in points between the entry point and the stop.
stop_per= (stop_dif * 100) / lvl_in //Percentage difference between the entry point and the stop.
//---------------- CONTRACTS
contracts = if qty_type == "Money Amount"
((100 * qty) / (((lvl_in - lvl_out) < 0 ? (lvl_in - lvl_out) *(-1) : (lvl_in - lvl_out)) * 100 / lvl_in)) / close //lvl in - lvl out *100/lvl in is the % that I loss. With that % I can calculate the total value in the operation and then divide it by the close to find out the number of contracts.
else if qty_type == "Equity Percent"
(100 * (strategy.equity * qty/100)) / (((lvl_in - lvl_out) < 0 ? (lvl_in - lvl_out) *(-1) : (lvl_in - lvl_out)) * 100 / lvl_in) / close
//---------------- RISK/REWARD
rr = ((lvl_tp - lvl_in) < 0 ? ((lvl_tp - lvl_in)*(-1)) : (lvl_tp - lvl_in)) / ((lvl_in - lvl_out) < 0 ? ((lvl_in - lvl_out) *(-1)) : (lvl_in - lvl_out))
//---------------------------------------------------------------- CONDITIONS -------------------------------------------------------------------------
//----- DATE
in_date = time >= date_in and time <= date_out
//----- FILLED CONDITION
filled = if (lvl_in != 0) and (lvl_out != 0)
true
else
false
//------ ORDERS STUFF
bought = strategy.position_size > 0
sold = strategy.position_size < 0
correct_side = if syminfo.tickerid == long_tick
"Long"
else if syminfo.tickerid == short_tick
"Short"
else if syminfo.tickerid != long_tick and syminfo.tickerid != short_tick
"Invalid ticker"
long = ((ta.crossunder(close_graph, lvl_in) or ta.crossover (close_graph, lvl_in))) and filled and not bought and not sold and correct_side == "Long" and in_date
short = ((ta.crossover (close_graph, lvl_in) or ta.crossunder(close_graph, lvl_in))) and filled and not bought and not sold and correct_side == "Short" and in_date
//That is an identifier for the orders.
id_in = long ? ("Long" + " " + str.tostring(syminfo.ticker)) : short ? ("Short" + " " + str.tostring(syminfo.ticker)) : "None"
id_out = bought ? ("Long exit" + " " + str.tostring(syminfo.ticker)) : sold ? ("Short exit" + " " + str.tostring(syminfo.ticker)) : "None"
//Set the SL and TP levels
sl = lvl_out != 0 ? lvl_out : na
tp = lvl_tp != 0 ? lvl_tp : na
// I use Zignaly as a exchange but here you must set the correct JSON msg for your webhook.
// ------------- ZIGNALY --------------------
string zig_quote= '"'
string zig_coma = ","
string zig_sep = ":"
string system_key = "XXXXXXXXXxx_YOUR KEY_xxXXXXXXXXX"
contracts_zig = (((contracts * (long ? close_long : short? close_short : na)) / leverage) * 100) / strategy.equity
string side = (long) ? "Long" : (short) ? "Short" : "Flat"
string price_zig = long ? str.tostring(close_long) : short ? str.tostring(close_short) : na
string ticker = str.substring(syminfo.ticker, 0, end_pos = str.pos(syminfo.ticker, "PERP")) // Remove the PERP string in all tickers. That is optional, cheeck if you need it.
// ------ IDs -----
if id_long != ""
id_long := id_long
else if id_long == ""
id_long := str.tostring(syminfo.ticker)
if id_short != ""
id_short := id_short
else if id_short == ""
id_short := str.tostring(syminfo.ticker)
id_zig = (long or bought) ? id_long : (short or sold) ? id_short : "Error. Unopened order."
entry_msg = zig_quote + "key" + zig_quote + zig_sep + zig_quote + system_key + zig_quote + zig_coma +
zig_quote + "type" + zig_quote + zig_sep + zig_quote + "entry" + zig_quote + zig_coma +
zig_quote + "exchange" + zig_quote + zig_sep + zig_quote + "zignaly" + zig_quote + zig_coma +
zig_quote + "exchangeAccountType" + zig_quote + zig_sep + zig_quote + "futures" + zig_quote + zig_coma +
zig_quote + "pair" + zig_quote + zig_sep + zig_quote + ticker + zig_quote + zig_coma +
zig_quote + "orderType" + zig_quote + zig_sep + zig_quote + "limit" + zig_quote + zig_coma +
zig_quote + "limitPrice" + zig_quote + zig_sep + zig_quote + price_zig + zig_quote + zig_coma +
zig_quote + "side" + zig_quote + zig_sep + zig_quote + str.tostring(side) + zig_quote + zig_coma +
zig_quote + "leverage" + zig_quote + zig_sep + zig_quote + str.tostring(leverage) + zig_quote + zig_coma +
zig_quote + "positionSizePercentage" + zig_quote + zig_sep + zig_quote + str.tostring(contracts_zig) + zig_quote + zig_coma +
zig_quote + "signalId" + zig_quote + zig_sep + zig_quote + id_zig + zig_quote
exit_msg = zig_quote + "key" + zig_quote + zig_sep + zig_quote + system_key + zig_quote + zig_coma +
zig_quote + "type" + zig_quote + zig_sep + zig_quote + "exit" + zig_quote + zig_coma +
zig_quote + "exchange" + zig_quote + zig_sep + zig_quote + "zignaly" + zig_quote + zig_coma +
zig_quote + "exchangeAccountType" + zig_quote + zig_sep + zig_quote + "futures" + zig_quote + zig_coma +
zig_quote + "pair" + zig_quote + zig_sep + zig_quote + ticker + zig_quote + zig_coma +
zig_quote + "orderType" + zig_quote + zig_sep + zig_quote + "market" + zig_quote + zig_coma +
zig_quote + "signalId" + zig_quote + zig_sep + zig_quote + id_zig + zig_quote + zig_coma
update_msg = zig_quote + "key" + zig_quote + zig_sep + zig_quote + system_key + zig_quote + zig_coma +
zig_quote + "type" + zig_quote + zig_sep + zig_quote + "update" + zig_quote + zig_coma +
zig_quote + "exchange" + zig_quote + zig_sep + zig_quote + "zignaly" + zig_quote + zig_coma +
zig_quote + "exchangeAccountType" + zig_quote + zig_sep + zig_quote + "futures" + zig_quote + zig_coma +
zig_quote + "pair" + zig_quote + zig_sep + zig_quote + ticker + zig_quote + zig_coma +
zig_quote + "signalId" + zig_quote + zig_sep + zig_quote + id_zig + zig_quote + zig_coma +
zig_quote + "reduceTargetpercentage" + zig_quote + zig_sep + zig_quote + str.tostring(qty_exit) + zig_quote
//--------- POSITIONS
if long
strategy.entry(id = id_in, direction = strategy.long, qty = contracts, alert_message = entry_msg)
if bought
strategy.exit(id = id_out, from_entry = id_in, qty_percent = qty_exit, limit = tp, stop = sl, alert_loss = exit_msg, alert_profit = update_msg)
if short
strategy.entry(id = id_in, direction = strategy.short, qty = contracts, alert_message = entry_msg)
if bought
strategy.exit(id = id_out, from_entry = id_in, qty_percent = qty_exit, limit = tp, stop = sl, alert_loss = exit_msg, alert_profit = update_msg)
//---------------------------------------------------------------- PLOTS ----------------------------------------------------------------------------
//-----RELATIVE GRAPHIC
plotbar(open_graph, high_graph, low_graph, close_graph, title = "Relative Graphic", color = color.gray, editable = true)
//-----LEVELS
hline(lvl_in != 0? lvl_in : na, title = "Entry", color = color.purple, editable = true)
hline(sl, title = "Stop Loss" , color = color.yellow , editable = true)
hline(tp, title = "Take Profit" , color = color.green , editable = true)
//----------- TABLE
t_position = switch table_pos
"Top Left" => position.top_left
"Top Center" => position.top_center
"Top Right" => position.top_right
"Middle Left" => position.middle_left
"Middle Center" => position.middle_center
"Middle Right" => position.middle_right
"Bottom Left" => position.bottom_left
"Bottom Center" => position.bottom_center
"Bottom Right" => position.bottom_right
stuff_table = table.new(position = t_position, columns = 2, rows = 5, bgcolor = table_bg_c, frame_width = 0, border_width = 5, border_color = color.black)
if table_on
table.cell(stuff_table, column = 0, row = 0, text = "Ticker side:" , text_color = table_txt_c, text_halign = text.align_left)
table.cell(stuff_table, column = 1, row = 0, text = correct_side , text_color = table_txt_c, text_halign = text.align_left)
table.cell(stuff_table, column = 0, row = 1, text = "Actual Ticker:", text_color = table_txt_c, text_halign = text.align_left)
table.cell(stuff_table, column = 1, row = 1, text = syminfo.tickerid, text_color = table_txt_c, text_halign = text.align_left)
table.cell(stuff_table, column = 0, row = 2, text = "Signal id:" , text_color = table_txt_c, text_halign = text.align_left)
table.cell(stuff_table, column = 1, row = 2, text = id_zig , text_color = table_txt_c, text_halign = text.align_left)
table.cell(stuff_table, column = 0, row = 3, text = "R/R:" , text_color = table_txt_c, text_halign = text.align_left)
table.cell(stuff_table, column = 1, row = 3, text = str.tostring(rr), text_color = table_txt_c, text_halign = text.align_left)
table.cell(stuff_table, column = 0, row = 4, text = "Contracts:" , text_color = table_txt_c, text_halign = text.align_left)
table.cell(stuff_table, column = 1, row = 4, text = str.tostring(contracts), text_color = table_txt_c, text_halign = text.align_left)
|