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
Trenbolone Strategy
https://www.tradingview.com/script/YfOfZWrz/
LeSif
https://www.tradingview.com/u/LeSif/
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/ // © KivancOzbilgic //@version=4 strategy("Trenbolone Strategy", overlay = true) 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=true) barcoloring = input(title="Bar Coloring On/Off ?", type=input.bool, defval=true) 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_linebr, linewidth=2, color=color.green) 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="Buy", text="Buy", location=location.absolute, style=shape.labelup, size=size.tiny, color=color.green, textcolor=color.white, transp=0) dnPlot = plot(trend == 1 ? na : dn, title="Down Trend", style=plot.style_linebr, linewidth=2, color=color.red) 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="Sell", text="Sell", 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.green : color.white) : color.white shortFillColor = highlighting ? (trend == -1 ? color.red : color.white) : color.white fill(mPlot, upPlot, title="UpTrend Highligter", color=longFillColor) fill(mPlot, dnPlot, title="DownTrend Highligter", color=shortFillColor) FromMonth = input(defval = 9, title = "From Month", minval = 1, maxval = 12) FromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31) FromYear = input(defval = 2018, title = "From Year", minval = 999) ToMonth = input(defval = 1, title = "To Month", minval = 1, maxval = 12) ToDay = input(defval = 1, title = "To Day", minval = 1, maxval = 31) ToYear = input(defval = 9999, title = "To Year", minval = 999) start = timestamp(FromYear, FromMonth, FromDay, 00, 00) finish = timestamp(ToYear, ToMonth, ToDay, 23, 59) window() => time >= start and time <= finish ? true : false longCondition = buySignal if (longCondition) strategy.entry("BUY", strategy.long, when = window()) shortCondition = sellSignal if (shortCondition) strategy.entry("SELL", strategy.short, when = window()) buy1 = barssince(buySignal) sell1 = barssince(sellSignal) color1 = buy1[1] < sell1[1] ? color.green : buy1[1] > sell1[1] ? color.red : na barcolor(barcoloring ? color1 : na)
Strategy: Combo Z Score
https://www.tradingview.com/script/FdB306iT-Strategy-Combo-Z-Score/
jroche1973
https://www.tradingview.com/u/jroche1973/
122
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/ // © jroche1973 //@version=4 strategy("Strategy: Combo Z Score", precision=6, overlay=false, pyramiding=100, calc_on_order_fills=true) Length = input(266) //252 v_StdDevs = input(defval = 2.0, title="VIX Z Std Dev") m_StdDevs = input(defval = 2.0, title="MOVE Z Std Dev") show_m = input(type=input.bool, title="Show MOVE", defval=true) show_v = input(type=input.bool, title="Show VIX", defval=true) show_o = input(type=input.bool, title="Show Oil/Oil Vol", defval=true) show_ema = input(type=input.bool, title="Apply EMA", defval=true) l_ema = input( title="EMA Length", defval=100) //strat_all = input(type=input.bool, title="Start both M and V", defval=true) //strat_v = input(type=input.bool, title="Start both Vix only", defval=false) //strat_m = input(type=input.bool, title="Start both Move only", defval=false) _bb_mult = input(title="BB mult", type=input.float, defval=2) _bb_range = input(title="BB mean range", type=input.integer, defval=20) //src = input(close) MOVE = security("TVC:MOVE", timeframe.period, close) VIX = security("VIX", timeframe.period, close) VVIX = security("VVIX", timeframe.period, close) OILVIX = security("CBOE:OVX", timeframe.period, close) USO = security("TVC:USOIL", timeframe.period, close) //USO = security("WTI", timeframe.period, close) startDateTime = input(type=input.time, defval=timestamp("1 Jan 2007 09:30"), title="Start Date", group="Strategy Date Range", tooltip="Specifies the start date and time from which " + "the strategy simulates buy and sell trades.") [_bb_mid, _bb_hig, _bb_low] = bb(close, _bb_range, _bb_mult) _bb_percent = (close - _bb_low) / (_bb_hig - _bb_low) s_ema = ema(close, l_ema) //Proxy of M of Move ie alt VVIX iVIX = 1/VIX //MOVE calcs divM = MOVE/iVIX m_basis = sma(divM, Length) m_zscore = (divM - m_basis) / stdev(divM, Length) iOILVIX = 1/OILVIX divO = USO/iOILVIX o_basis = sma(divO, Length) o_zscore = (divO - o_basis) / stdev(divO, Length) plot(show_m? m_zscore: na, color=color.new(#55FF55, 0)) plot(show_o? o_zscore: na, color=color.new(#ebbd14, 0)) //plot( _bb_percent , color = color.new(color.yellow,0)) hline(m_StdDevs, color=color.white, linestyle=hline.style_dotted) hline(-1 * m_StdDevs, color=color.white, linestyle=hline.style_dotted) color o_color = o_zscore < 0 ? color.new(color.white, 70): color.new(color.yellow, 70) //we want white if not active color ob_color = o_zscore < 0 and _bb_percent > 0.5 ? color.new(color.white, 70): color.new(color.yellow, 70) //we want white if not active color m_color = m_zscore < 0 ? color.new(color.white, 70): color.new(color.blue, 70) //we want white if not active color mb_color = m_zscore < 0 and _bb_percent > 0.5 ? color.new(color.white, 70): color.new(color.blue, 70) //we want white if not active use_b = _bb_percent < 0.5 ? true: false bgcolor(show_o and use_b ? color.new(o_color,70) : color.new(color.white, 70)) // we want whatever color our status stipulates if 'on' or white if 'off' bgcolor(show_m and use_b ? color.new(m_color,70) : color.new(color.white, 70)) // we want whatever color our status stipulates if 'on' or white if 'off' //VIX Calcs divV = VIX/VVIX v_basis = sma(divV, Length) v_zscore = (divV - v_basis) / stdev(divV, Length) plot(show_v? v_zscore: na, color=color.new(#7d070c, 0)) hline(v_StdDevs, color=color.white, linestyle=hline.style_dotted) hline(-1 * v_StdDevs, color=color.white, linestyle=hline.style_dotted) color v_color = v_zscore < 0 ? color.new(color.white, 70): color.new(color.red, 70) //we want white if not active bgcolor(show_v and use_b? color.new(v_color,70) : color.new(color.white, 70)) // we want whatever color our status stipulates if 'on' or white if 'off' //Strategy Testing long_all = m_zscore < 0 and v_zscore < 0 and o_zscore < 0 and _bb_percent > 0.5 ? true : false long_vix = v_zscore < 0 and _bb_percent > 0.5 long_move = m_zscore < 0 and _bb_percent > 0.5 long_oil = o_zscore < 0 and _bb_percent > 0.5 short_all = m_zscore > 0 and v_zscore > 0 and o_zscore > 0 and _bb_percent < 0.5 ? true : false short_vix = v_zscore > 0 and _bb_percent < 0.5 short_move = m_zscore > 0 and _bb_percent < 0.5 short_oil = o_zscore > 0 and _bb_percent < 0.5 if show_ema if time >= startDateTime and time <= timenow //if m_zscore and v_zscore > 0 and %b <.05 then enter short if show_v and show_m and show_o if m_zscore > 0 and v_zscore > 0 and o_zscore > 0 and _bb_percent < 0.5 and close < s_ema //short strategy.entry("sell", strategy.short, 100, when=strategy.position_size > 0) //open short position strategy.close("close long", when=long_all) //close all long positions else //long strategy.entry("buy", strategy.long, 100, when=strategy.position_size <= 0) //open long position strategy.close("close short", when=short_all) //close all short positions else if show_m and show_v == false and show_o == false if m_zscore > 0 and _bb_percent < 0.5 and close < s_ema //short strategy.entry("sell", strategy.short, 100, when=strategy.position_size > 0) strategy.close("close long", when=long_move) else //long strategy.entry("buy", strategy.long, 100, when=strategy.position_size <= 0) strategy.close("close short", when=short_move) else if show_v and show_m == false and show_o == false if v_zscore > 0 and _bb_percent < 0.5 and close < s_ema //short strategy.entry("sell", strategy.short, 100, when=strategy.position_size > 0) strategy.close("close long", when=long_vix) else //long strategy.entry("buy", strategy.long, 100, when=strategy.position_size <= 0) strategy.close("close short", when=short_vix) else if show_o and show_v == false and show_m == false if o_zscore > 0 and _bb_percent < 0.5 and close < s_ema //short strategy.entry("sell", strategy.short, 100, when=strategy.position_size > 0) strategy.close("close long", when=long_move) else //long strategy.entry("buy", strategy.long, 100, when=strategy.position_size <= 0) strategy.close("close short", when=short_move) else if show_v and show_m and show_o == false if v_zscore > 0 and m_zscore > 0 and _bb_percent < 0.5 and close < s_ema //short strategy.entry("sell", strategy.short, 100, when=strategy.position_size > 0) strategy.close("close long", when=long_vix) else //long strategy.entry("buy", strategy.long, 100, when=strategy.position_size <= 0) strategy.close("close short", when=short_vix) else if show_v and show_o and show_m == false if v_zscore > 0 and o_zscore > 0 and _bb_percent < 0.5 and close < s_ema //short strategy.entry("sell", strategy.short, 100, when=strategy.position_size > 0) strategy.close("close long", when=long_vix) else //long strategy.entry("buy", strategy.long, 100, when=strategy.position_size <= 0) strategy.close("close short", when=short_vix) else if show_o and show_m and show_v == false if o_zscore > 0 and m_zscore > 0 and _bb_percent < 0.5 and close < s_ema //short strategy.entry("sell", strategy.short, 100, when=strategy.position_size > 0) strategy.close("close long", when=long_vix) else //long strategy.entry("buy", strategy.long, 100, when=strategy.position_size <= 0) strategy.close("close short", when=short_vix) else if time >= startDateTime and time <= timenow //if m_zscore and v_zscore > 0 and %b <.05 then enter short if show_v and show_m and show_o if m_zscore > 0 and v_zscore > 0 and o_zscore > 0 and _bb_percent < 0.5 //short strategy.entry("sell", strategy.short, 100, when=strategy.position_size > 0) //open short position strategy.close("close long", when=long_all) //close all long positions else //long strategy.entry("buy", strategy.long, 100, when=strategy.position_size <= 0) //open long position strategy.close("close short", when=short_all) //close all short positions else if show_m and show_v == false and show_o == false if m_zscore > 0 and _bb_percent < 0.5 //short strategy.entry("sell", strategy.short, 100, when=strategy.position_size > 0) strategy.close("close long", when=long_move) else //long strategy.entry("buy", strategy.long, 100, when=strategy.position_size <= 0) strategy.close("close short", when=short_move) else if show_v and show_m == false and show_o == false if v_zscore > 0 and _bb_percent < 0.5 //short strategy.entry("sell", strategy.short, 100, when=strategy.position_size > 0) strategy.close("close long", when=long_vix) else //long strategy.entry("buy", strategy.long, 100, when=strategy.position_size <= 0) strategy.close("close short", when=short_vix) else if show_o and show_v == false and show_m == false if o_zscore > 0 and _bb_percent < 0.5 //short strategy.entry("sell", strategy.short, 100, when=strategy.position_size > 0) strategy.close("close long", when=long_move) else //long strategy.entry("buy", strategy.long, 100, when=strategy.position_size <= 0) strategy.close("close short", when=short_move) else if show_v and show_m and show_o == false if v_zscore > 0 and m_zscore > 0 and _bb_percent < 0.5 //short strategy.entry("sell", strategy.short, 100, when=strategy.position_size > 0) strategy.close("close long", when=long_vix) else //long strategy.entry("buy", strategy.long, 100, when=strategy.position_size <= 0) strategy.close("close short", when=short_vix) else if show_v and show_o and show_m == false if v_zscore > 0 and o_zscore > 0 and _bb_percent < 0.5 //short strategy.entry("sell", strategy.short, 100, when=strategy.position_size > 0) strategy.close("close long", when=long_vix) else //long strategy.entry("buy", strategy.long, 100, when=strategy.position_size <= 0) strategy.close("close short", when=short_vix) else if show_o and show_m and show_v == false if o_zscore > 0 and m_zscore > 0 and _bb_percent < 0.5 //short strategy.entry("sell", strategy.short, 100, when=strategy.position_size > 0) strategy.close("close long", when=long_vix) else //long strategy.entry("buy", strategy.long, 100, when=strategy.position_size <= 0) strategy.close("close short", when=short_vix)
Crypto High Potential Strategy
https://www.tradingview.com/script/GR95wVXg/
maxencetajet
https://www.tradingview.com/u/maxencetajet/
175
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © maxencetajet //@version=5 strategy("HA_RSI", overlay=true, initial_capital=1000, default_qty_type=strategy.fixed, default_qty_value=0.5, slippage=25) closeHA = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close) risk = input.float(2, title="Risk per Trade %", group="Money Management") _x = input.bool(false, title="do not take too small positions", group="Money Management", tooltip="This parameter is used to avoid positions that have a stoploss that is too short and that the spreads of the broker take all the gains") security = input.float(50, title='min of pips (00001.00) for each position', group="Money Management") riskt = risk / 100 + 1 useDateFilter = input.bool(true, title="Filter Date Range of Backtest", group="Backtest Time Period") backtestStartDate = input.time(timestamp("1 June 2022"), title="Start Date", group="Backtest Time Period", tooltip="This start date is in the time zone of the exchange " + "where the chart's instrument trades. It doesn't use the time " + "zone of the chart or of your computer.") backtestEndDate = input.time(timestamp("1 July 2022"), title="End Date", group="Backtest Time Period", tooltip="This end date is in the time zone of the exchange " + "where the chart's instrument trades. It doesn't use the time " + "zone of the chart or of your computer.") inTradeWindow = not useDateFilter or (time >= backtestStartDate and time < backtestEndDate) swingHighV = input.int(10, title="Swing High", group="Stop Loss", tooltip="Number of candles in which the parameter targets the highest") swingLowV = input.int(10, title="Swing Low", group="Stop Loss", tooltip="Number of candles in which the parameter targets the lowest point") emaV = input.int(200, title="Ema Period", group="EMA") rsiV = input.int(14, title="RSI Period", group="RSI") start = input(0.02, group="Parabolic SAR") increment = input(0.02, group="Parabolic SAR") maximum = input(0.2, "Max Value", group="Parabolic SAR") ema = ta.ema(closeHA, emaV) rsi = ta.rsi(closeHA, rsiV) SAR = ta.sar(start, increment, maximum) myColor = SAR < low?color.green:color.red longcondition = closeHA > ema and rsi > 50 and closeHA[1] > SAR and closeHA[1] < SAR[1] shortcondition = closeHA < ema and rsi < 50 and closeHA[1] < SAR and closeHA[1] > SAR[1] float risk_long = na float risk_short = na float stopLoss = na float entry_price = na float takeProfit = na risk_long := risk_long[1] risk_short := risk_short[1] swingHigh = ta.highest(closeHA, swingHighV) swingLow = ta.lowest(closeHA, swingLowV) lotB = (strategy.equity*riskt-strategy.equity)/(closeHA - swingLow) lotS = (strategy.equity*riskt-strategy.equity)/(swingHigh - closeHA) if strategy.position_size == 0 and longcondition and inTradeWindow risk_long := (close - swingLow) / close minp = close - swingLow if _x if minp > security strategy.entry("long", strategy.long, qty=lotB, comment="Buy " + str.tostring(close) + "") else strategy.entry("long", strategy.long, qty=lotB, comment="Buy " + str.tostring(close) + "") if strategy.position_size == 0 and shortcondition and inTradeWindow risk_short := (swingHigh - close) / close minp = swingHigh - close if _x if minp > security strategy.entry("short", strategy.short, qty=lotS, comment="Sell " + str.tostring(close) + "") else strategy.entry("short", strategy.short, qty=lotS, comment="Sell " + str.tostring(close) + "") if strategy.position_size > 0 stopLoss := strategy.position_avg_price * (1 - risk_long) entry_price := strategy.position_avg_price strategy.exit("long exit", "long", stop = stopLoss) if strategy.position_size < 0 stopLoss := strategy.position_avg_price * (1 + risk_short) entry_price := strategy.position_avg_price strategy.exit("short exit", "short", stop = stopLoss) if closeHA[1] < SAR and close > strategy.position_avg_price strategy.close("long", comment="Exit Long") if closeHA[1] > SAR and close < strategy.position_avg_price strategy.close("short", comment="Exit Short") p_ep = plot(entry_price, color=color.new(color.white, 0), linewidth=2, style=plot.style_linebr, title='entry price') p_sl = plot(stopLoss, color=color.new(color.red, 0), linewidth=2, style=plot.style_linebr, title='stopLoss') fill(p_sl, p_ep, color.new(color.red, transp=85)) plot(SAR, "ParabolicSAR", style=plot.style_circles, color=myColor, linewidth=1) plot(ema, color=color.white, linewidth=2, title="EMA") colorresult = strategy.netprofit > 0 ? color.green : color.red profitprc = strategy.netprofit / strategy.initial_capital * 100 periodzone = (backtestEndDate - backtestStartDate) / 3600 / 24 / 1000 var tbl = table.new(position.top_right, 4, 2, border_width=3) table.cell(tbl, 0, 0, "Symbole", bgcolor = #9B9B9B, width = 6, height = 6) table.cell(tbl, 1, 0, "Net Profit", bgcolor = #9B9B9B, width = 6, height = 6) table.cell(tbl, 2, 0, "Trades", bgcolor = #9B9B9B, width = 6, height = 6) table.cell(tbl, 3, 0, "Period", bgcolor = #9B9B9B, width = 6, height = 6) table.cell(tbl, 0, 1, str.tostring(syminfo.ticker), bgcolor = #E8E8E8, width = 6, height = 6) table.cell(tbl, 1, 1, str.tostring(profitprc, format.mintick) + " %", bgcolor = colorresult, width = 6, height = 6) table.cell(tbl, 2, 1, str.tostring(strategy.closedtrades), bgcolor = colorresult, width = 6, height = 6) table.cell(tbl, 3, 1, str.tostring(periodzone) + " day", bgcolor = colorresult, width = 6, height = 6)
Swing Trading SPX Correlation
https://www.tradingview.com/script/RnxKPE7s-Swing-Trading-SPX-Correlation/
exlux99
https://www.tradingview.com/u/exlux99/
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/ // © exlux99 //@version=5 strategy("Swing Trading SPX Correlation") S4 = 'INDEX:S5TH'//input.symbol(title='ABOVE 200', defval='INDEX:S5TH') P4 = request.security(S4, 'D', close) lengthMA = input.int(100, minval=1) reaction = input.int(2, minval=1, maxval=5) MA4 = ta.vwma(P4, lengthMA) direction4 = 0 direction4 := ta.rising(MA4, reaction) ? 1 : ta.falling(MA4, reaction) ? -1 : nz(direction4[1]) //change_direction= change(direction2,1) pcol4 = direction4 > 0 ? color.lime : direction4 < 0 ? color.red : na pula_long = direction4 > direction4[1] and direction4 > 0 pula_short= direction4 < direction4[1] and direction4 < 0 plot(MA4, linewidth=4, color=pcol4) long = direction4 > 0 and direction4[1] < 0 short = direction4 < 0 and direction4[1] > 0 strategy.entry("long",strategy.long,when=long) strategy.close("long",when=short) //strategy.entry('short',strategy.short,when=short)
Linear Regression MA - Strategy
https://www.tradingview.com/script/jBgKMbWU-Linear-Regression-MA-Strategy/
lazy_capitalist
https://www.tradingview.com/u/lazy_capitalist/
37
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/ // © lazy_capitalist //@version=5 strategy('Linear Regression MA', overlay=true, initial_capital=10000) datesGroup = "Date Info" startMonth = input.int(defval = 1, title = "Start Month", minval = 1, maxval = 12, group=datesGroup) startDay = input.int(defval = 1, title = "Start Day", minval = 1, maxval = 31, group=datesGroup) startYear = input.int(defval = 2022, title = "Start Year", minval = 1970, group=datesGroup) averagesGroup = "Averages" lrLineInput = input.int(title="Linear Regression Line", defval=55, minval = 1, group=averagesGroup) lrMAInput = input.int(title="Linear Regression MA", defval=55, minval = 1, group=averagesGroup) emaInput = input.int(title="EMA Length", defval=55, minval = 1, group=averagesGroup) tradesGroup = "Execute Trades" executeLongInput = input.bool(title="Execute Long Trades", defval=true) executeShortInput = input.bool(title="Execute Short Trades", defval=true) executeStopLoss = input.bool(title="Execute Stop Loss", defval=true) fourHrSMAExpr = ta.sma(close, 200) fourHrMA = request.security(symbol=syminfo.tickerid, timeframe="240", expression=fourHrSMAExpr) bullish = close > fourHrMA ? true : false maxProfitInput = input.float( title="Max Profit (%)", defval=10.0, minval=0.0) * 0.01 stopLossPercentageInput = input.float( title="Stop Loss (%)", defval=1.75, minval=0.0) * 0.01 start = timestamp(startYear, startMonth, startDay, 00, 00) // backtest start window window() => time >= start ? true : false // create function "within window of time" showDate = input(defval = true, title = "Show Date Range") lrLine = ta.linreg(close, lrLineInput, 0) lrMA = ta.sma(lrLine, lrMAInput) ema = ta.ema(close, emaInput) longEntry = ema < lrMA longExit = lrMA < ema shortEntry = lrMA < ema shortExit = ema < lrMA maxProfitLong = strategy.opentrades.entry_price(0) * (1 + maxProfitInput) maxProfitShort = strategy.opentrades.entry_price(0) * (1 - maxProfitInput) stopLossPriceShort = strategy.position_avg_price * (1 + stopLossPercentageInput) stopLossPriceLong = strategy.position_avg_price * (1 - stopLossPercentageInput) if(executeLongInput and bullish) strategy.entry( id="long_entry", direction=strategy.long, when=longEntry and window(), qty=10, comment="long_entry") strategy.close( id="long_entry", when=longExit, comment="long_exit") // strategy.close( id="long_entry", when=maxProfitLong <= close, comment="long_exit_mp") if(executeShortInput and not bullish) strategy.entry( id="short_entry", direction=strategy.short, when=shortEntry and window(), qty=10, comment="short_entry") strategy.close( id="short_entry", when=shortExit, comment="short_exit") // strategy.close( id="short_entry", when=maxProfitShort <= close, comment="short_exit_mp") if(strategy.position_size > 0 and executeStopLoss) strategy.exit( id="long_entry", stop=stopLossPriceLong, comment="exit_long_SL") strategy.exit( id="short_entry", stop=stopLossPriceShort, comment="exit_short_SL") // plot(series=lrLine, color=color.green) plot(series=lrMA, color=color.red) plot(series=ema, color=color.blue)
EMA SCALPEUR SHORT
https://www.tradingview.com/script/co9okhUj/
ElPonzito
https://www.tradingview.com/u/ElPonzito/
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/ // © YukalMoon //@version=5 strategy(title="EMA SCALPEUR", overlay=true, initial_capital = 1000) //// input controls EMA_L = input.int (title = "EMA_L", defval = 9, minval = 1, maxval = 100, step =1) EMA_L2 = input.int (title = "EMA_L2", defval = 26, minval = 1, maxval = 100, step =1) EMA_S = input.int (title = "EMA_S", defval = 100, minval = 1, maxval = 100, step =1) EMA_S2 = input.int (title = "EMA_S2", defval = 55, minval = 1, maxval = 100, step =1) /// mise en place de ema shortest = ta.ema(close, 9) short = ta.ema(close, 26) longer = ta.ema(close, 100) longest = ta.ema(close, 55) plot(shortest, color = color.red) plot(short, color = color.orange) plot(longer, color = color.aqua) plot(longest, color = color.yellow) plot(close) //// trading indicators EMA1 = ta.ema (close,EMA_L) EMA2 = ta.ema (close,EMA_L2) EMA3 = ta.ema (close, EMA_S) EMA4 = ta.ema (close, EMA_S2) buy = ta.crossover(EMA1, EMA2) //sell = ta.crossunder(EMA1, EMA2) buyexit = ta.crossunder(EMA3, EMA4) //sellexit = ta.crossover(EMA3, EMA4) /////strategy strategy.entry ("long", strategy.short, when = buy, comment = "ENTER-SHORT") //strategy.entry ("short", strategy.short, when = sell, comment = "ENTER-SHORT") ///// market exit strategy.close ("long", when = buyexit, comment = "EXIT-SHORT") //strategy.close ("short", when = sellexit, comment = "EXIT-SHORT")
ComiCo - Joel on Crypto - MACD Scalping
https://www.tradingview.com/script/qFUfwnfb-ComiCo-Joel-on-Crypto-MACD-Scalping/
bkomoroczy
https://www.tradingview.com/u/bkomoroczy/
105
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ //@version=5 strategy(title="ComiCo - Joel on Crypto - MACD Scalping", shorttitle="ComiCo - Joel on Crypto - MACD Scalping", overlay=false, default_qty_type = strategy.percent_of_equity, default_qty_value=100, margin_long=1./50*100, margin_short=1./50*100, pyramiding = 14) //Get High impact USD related economic news from MyFxBook converted to Pinescript's matching formats var EventNameTypes = array.from("ISM Manufacturing PMI", "ADP Employment Change", "Markit Services/Composite PMI", "Markit Manufacturing PMI", "Balance of Trade", "Jobless Claims", "ISM Non-Manufacturing PMI", "Non Farm Payrolls", "CPI", "Inflation Rate", "Fed Chair", "Retail Sales", "Michigan Consumer Sentiment", "Treasury Secretary", "Existing Home Sales", "Durable Goods Orders", "Fed Interest Rate Decision", "GDP", "Goods Trade Balance", "New Home Sales", "Personal Income/Spending", "FOMC Minutes", "Fed Press Conference", "FakeTypeForTesting") var EventTypeAvoidance = array.new_bool(array.size(EventNameTypes), false) var EventTimestamps = array.from(timestamp(2021, 01, 04, 12, 45, 00), timestamp(2021, 01, 05, 13, 00, 00), timestamp(2021, 01, 06, 11, 15, 00), timestamp(2021, 01, 06, 12, 45, 00), timestamp(2021, 01, 07, 11, 30, 00), timestamp(2021, 01, 07, 11, 30, 00), timestamp(2021, 01, 07, 13, 00, 00), timestamp(2021, 01, 08, 11, 30, 00), timestamp(2021, 01, 13, 11, 30, 00), timestamp(2021, 01, 14, 11, 30, 00), timestamp(2021, 01, 14, 15, 30, 00), timestamp(2021, 01, 15, 11, 30, 00), timestamp(2021, 01, 15, 13, 00, 00), timestamp(2021, 01, 19, 13, 00, 00), timestamp(2021, 01, 21, 11, 30, 00), timestamp(2021, 01, 22, 12, 45, 00), timestamp(2021, 01, 22, 12, 45, 00), timestamp(2021, 01, 22, 13, 00, 00), timestamp(2021, 01, 27, 11, 30, 00), timestamp(2021, 01, 27, 17, 00, 00), timestamp(2021, 01, 27, 17, 30, 00), timestamp(2021, 01, 28, 11, 30, 00), timestamp(2021, 01, 28, 11, 30, 00), timestamp(2021, 01, 28, 11, 30, 00), timestamp(2021, 01, 28, 13, 00, 00), timestamp(2021, 01, 29, 11, 30, 00), timestamp(2021, 01, 29, 13, 00, 00), timestamp(2021, 02, 01, 12, 45, 00), timestamp(2021, 02, 01, 13, 00, 00), timestamp(2021, 02, 03, 11, 15, 00), timestamp(2021, 02, 03, 12, 45, 00), timestamp(2021, 02, 03, 13, 00, 00), timestamp(2021, 02, 04, 11, 30, 00), timestamp(2021, 02, 05, 11, 30, 00), timestamp(2021, 02, 05, 11, 30, 00), timestamp(2021, 02, 10, 11, 30, 00), timestamp(2021, 02, 10, 17, 00, 00), timestamp(2021, 02, 11, 11, 30, 00), timestamp(2021, 02, 12, 13, 00, 00), timestamp(2021, 02, 17, 11, 30, 00), timestamp(2021, 02, 17, 17, 00, 00), timestamp(2021, 02, 18, 11, 30, 00), timestamp(2021, 02, 19, 12, 45, 00), timestamp(2021, 02, 19, 12, 45, 00), timestamp(2021, 02, 19, 13, 00, 00), timestamp(2021, 02, 23, 13, 00, 00), timestamp(2021, 02, 24, 13, 00, 00), timestamp(2021, 02, 24, 13, 00, 00), timestamp(2021, 02, 25, 11, 30, 00), timestamp(2021, 02, 25, 11, 30, 00), timestamp(2021, 02, 26, 11, 30, 00), timestamp(2021, 02, 26, 11, 30, 00), timestamp(2021, 02, 26, 13, 00, 00), timestamp(2021, 03, 01, 12, 45, 00), timestamp(2021, 03, 01, 13, 00, 00), timestamp(2021, 03, 03, 11, 15, 00), timestamp(2021, 03, 03, 12, 45, 00), timestamp(2021, 03, 03, 13, 00, 00), timestamp(2021, 03, 04, 11, 30, 00), timestamp(2021, 03, 04, 15, 05, 00), timestamp(2021, 03, 05, 11, 30, 00), timestamp(2021, 03, 05, 11, 30, 00), timestamp(2021, 03, 10, 11, 30, 00), timestamp(2021, 03, 11, 11, 30, 00), timestamp(2021, 03, 12, 13, 00, 00), timestamp(2021, 03, 16, 10, 30, 00), timestamp(2021, 03, 17, 16, 00, 00), timestamp(2021, 03, 17, 16, 30, 00), timestamp(2021, 03, 18, 10, 30, 00), timestamp(2021, 03, 22, 11, 00, 00), timestamp(2021, 03, 22, 12, 00, 00), timestamp(2021, 03, 23, 12, 00, 00), timestamp(2021, 03, 23, 14, 00, 00), timestamp(2021, 03, 24, 10, 30, 00), timestamp(2021, 03, 24, 11, 45, 00), timestamp(2021, 03, 24, 11, 45, 00), timestamp(2021, 03, 24, 12, 00, 00), timestamp(2021, 03, 25, 10, 30, 00), timestamp(2021, 03, 26, 09, 30, 00), timestamp(2021, 03, 26, 09, 30, 00), timestamp(2021, 03, 26, 11, 00, 00), timestamp(2021, 03, 31, 09, 15, 00), timestamp(2021, 04, 01, 09, 30, 00), timestamp(2021, 04, 01, 10, 45, 00), timestamp(2021, 04, 01, 11, 00, 00), timestamp(2021, 04, 02, 09, 30, 00), timestamp(2021, 04, 05, 10, 45, 00), timestamp(2021, 04, 05, 11, 00, 00), timestamp(2021, 04, 07, 09, 30, 00), timestamp(2021, 04, 07, 15, 00, 00), timestamp(2021, 04, 08, 09, 30, 00), timestamp(2021, 04, 08, 13, 00, 00), timestamp(2021, 04, 13, 09, 30, 00), timestamp(2021, 04, 14, 13, 00, 00), timestamp(2021, 04, 15, 09, 30, 00), timestamp(2021, 04, 15, 09, 30, 00), timestamp(2021, 04, 16, 11, 00, 00), timestamp(2021, 04, 22, 09, 30, 00), timestamp(2021, 04, 22, 11, 00, 00), timestamp(2021, 04, 23, 10, 45, 00), timestamp(2021, 04, 23, 10, 45, 00), timestamp(2021, 04, 23, 11, 00, 00), timestamp(2021, 04, 26, 09, 30, 00), timestamp(2021, 04, 28, 09, 30, 00), timestamp(2021, 04, 28, 15, 00, 00), timestamp(2021, 04, 28, 15, 30, 00), timestamp(2021, 04, 29, 09, 30, 00), timestamp(2021, 04, 29, 09, 30, 00), timestamp(2021, 04, 30, 09, 30, 00), timestamp(2021, 04, 30, 11, 00, 00), timestamp(2021, 05, 03, 10, 45, 00), timestamp(2021, 05, 03, 11, 00, 00), timestamp(2021, 05, 03, 15, 20, 00), timestamp(2021, 05, 04, 09, 30, 00), timestamp(2021, 05, 05, 09, 15, 00), timestamp(2021, 05, 05, 10, 45, 00), timestamp(2021, 05, 05, 11, 00, 00), timestamp(2021, 05, 06, 09, 30, 00), timestamp(2021, 05, 07, 09, 30, 00), timestamp(2021, 05, 12, 09, 30, 00), timestamp(2021, 05, 13, 09, 30, 00), timestamp(2021, 05, 14, 09, 30, 00), timestamp(2021, 05, 14, 11, 00, 00), timestamp(2021, 05, 19, 15, 00, 00), timestamp(2021, 05, 20, 09, 30, 00), timestamp(2021, 05, 21, 10, 45, 00), timestamp(2021, 05, 21, 10, 45, 00), timestamp(2021, 05, 21, 11, 00, 00), timestamp(2021, 05, 25, 11, 00, 00), timestamp(2021, 05, 27, 09, 30, 00), timestamp(2021, 05, 27, 09, 30, 00), timestamp(2021, 05, 28, 09, 30, 00), timestamp(2021, 05, 28, 09, 30, 00), timestamp(2021, 05, 28, 11, 00, 00), timestamp(2021, 06, 01, 10, 45, 00), timestamp(2021, 06, 01, 11, 00, 00), timestamp(2021, 06, 03, 09, 15, 00), timestamp(2021, 06, 03, 09, 30, 00), timestamp(2021, 06, 03, 10, 45, 00), timestamp(2021, 06, 03, 11, 00, 00), timestamp(2021, 06, 04, 08, 00, 00), timestamp(2021, 06, 04, 09, 30, 00), timestamp(2021, 06, 08, 09, 30, 00), timestamp(2021, 06, 10, 09, 30, 00), timestamp(2021, 06, 10, 09, 30, 00), timestamp(2021, 06, 11, 11, 00, 00), timestamp(2021, 06, 15, 09, 30, 00), timestamp(2021, 06, 16, 15, 00, 00), timestamp(2021, 06, 16, 15, 30, 00), timestamp(2021, 06, 17, 09, 30, 00), timestamp(2021, 06, 22, 11, 00, 00), timestamp(2021, 06, 22, 15, 00, 00), timestamp(2021, 06, 23, 10, 45, 00), timestamp(2021, 06, 23, 10, 45, 00), timestamp(2021, 06, 23, 11, 00, 00), timestamp(2021, 06, 24, 09, 30, 00), timestamp(2021, 06, 24, 09, 30, 00), timestamp(2021, 06, 24, 09, 30, 00), timestamp(2021, 06, 25, 09, 30, 00), timestamp(2021, 06, 25, 11, 00, 00), timestamp(2021, 06, 30, 09, 15, 00), timestamp(2021, 07, 01, 09, 30, 00), timestamp(2021, 07, 01, 10, 45, 00), timestamp(2021, 07, 01, 11, 00, 00), timestamp(2021, 07, 02, 09, 30, 00), timestamp(2021, 07, 02, 09, 30, 00), timestamp(2021, 07, 06, 10, 45, 00), timestamp(2021, 07, 06, 11, 00, 00), timestamp(2021, 07, 07, 15, 00, 00), timestamp(2021, 07, 08, 09, 30, 00), timestamp(2021, 07, 13, 09, 30, 00), timestamp(2021, 07, 14, 13, 00, 00), timestamp(2021, 07, 15, 09, 30, 00), timestamp(2021, 07, 15, 10, 30, 00), timestamp(2021, 07, 16, 09, 30, 00), timestamp(2021, 07, 16, 11, 00, 00), timestamp(2021, 07, 22, 09, 30, 00), timestamp(2021, 07, 22, 11, 00, 00), timestamp(2021, 07, 23, 10, 45, 00), timestamp(2021, 07, 23, 10, 45, 00), timestamp(2021, 07, 26, 11, 00, 00), timestamp(2021, 07, 27, 09, 30, 00), timestamp(2021, 07, 28, 09, 30, 00), timestamp(2021, 07, 28, 15, 00, 00), timestamp(2021, 07, 28, 15, 30, 00), timestamp(2021, 07, 29, 09, 30, 00), timestamp(2021, 07, 29, 09, 30, 00), timestamp(2021, 07, 30, 09, 30, 00), timestamp(2021, 07, 30, 11, 00, 00), timestamp(2021, 08, 02, 10, 45, 00), timestamp(2021, 08, 02, 11, 00, 00), timestamp(2021, 08, 04, 09, 15, 00), timestamp(2021, 08, 04, 10, 45, 00), timestamp(2021, 08, 04, 11, 00, 00), timestamp(2021, 08, 05, 09, 30, 00), timestamp(2021, 08, 05, 09, 30, 00), timestamp(2021, 08, 06, 09, 30, 00), timestamp(2021, 08, 11, 09, 30, 00), timestamp(2021, 08, 12, 09, 30, 00), timestamp(2021, 08, 13, 11, 00, 00), timestamp(2021, 08, 17, 12, 30, 00), timestamp(2021, 08, 17, 17, 30, 00), timestamp(2021, 08, 18, 18, 00, 00), timestamp(2021, 08, 19, 12, 30, 00), timestamp(2021, 08, 23, 13, 45, 00), timestamp(2021, 08, 23, 13, 45, 00), timestamp(2021, 08, 23, 14, 00, 00), timestamp(2021, 08, 24, 14, 00, 00), timestamp(2021, 08, 25, 12, 30, 00), timestamp(2021, 08, 26, 12, 30, 00), timestamp(2021, 08, 27, 12, 30, 00), timestamp(2021, 08, 27, 12, 30, 00), timestamp(2021, 08, 27, 14, 00, 00), timestamp(2021, 08, 27, 14, 00, 00), timestamp(2021, 09, 01, 12, 15, 00), timestamp(2021, 09, 01, 13, 45, 00), timestamp(2021, 09, 01, 14, 00, 00), timestamp(2021, 09, 02, 12, 30, 00), timestamp(2021, 09, 02, 12, 30, 00), timestamp(2021, 09, 03, 12, 30, 00), timestamp(2021, 09, 03, 13, 45, 00), timestamp(2021, 09, 03, 14, 00, 00), timestamp(2021, 09, 09, 12, 30, 00), timestamp(2021, 09, 14, 12, 30, 00), timestamp(2021, 09, 16, 12, 30, 00), timestamp(2021, 09, 16, 12, 30, 00), timestamp(2021, 09, 17, 14, 00, 00), timestamp(2021, 09, 22, 14, 00, 00), timestamp(2021, 09, 22, 18, 00, 00), timestamp(2021, 09, 22, 18, 30, 00), timestamp(2021, 09, 23, 12, 30, 00), timestamp(2021, 09, 23, 13, 45, 00), timestamp(2021, 09, 23, 13, 45, 00), timestamp(2021, 09, 24, 14, 00, 00), timestamp(2021, 09, 27, 12, 30, 00), timestamp(2021, 09, 28, 12, 30, 00), timestamp(2021, 09, 28, 14, 00, 00), timestamp(2021, 09, 29, 14, 45, 00), timestamp(2021, 09, 30, 12, 30, 00), timestamp(2021, 10, 01, 12, 30, 00), timestamp(2021, 10, 01, 13, 45, 00), timestamp(2021, 10, 01, 14, 00, 00), timestamp(2021, 10, 01, 14, 00, 00), timestamp(2021, 10, 05, 12, 30, 00), timestamp(2021, 10, 05, 13, 45, 00), timestamp(2021, 10, 05, 14, 00, 00), timestamp(2021, 10, 06, 12, 15, 00), timestamp(2021, 10, 07, 12, 30, 00), timestamp(2021, 10, 08, 12, 30, 00), timestamp(2021, 10, 13, 12, 30, 00), timestamp(2021, 10, 13, 18, 00, 00), timestamp(2021, 10, 14, 12, 30, 00), timestamp(2021, 10, 15, 12, 30, 00), timestamp(2021, 10, 15, 14, 00, 00), timestamp(2021, 10, 21, 12, 30, 00), timestamp(2021, 10, 21, 14, 00, 00), timestamp(2021, 10, 22, 13, 45, 00), timestamp(2021, 10, 22, 13, 45, 00), timestamp(2021, 10, 22, 15, 00, 00), timestamp(2021, 10, 26, 14, 00, 00), timestamp(2021, 10, 27, 12, 30, 00), timestamp(2021, 10, 27, 12, 30, 00), timestamp(2021, 10, 28, 12, 30, 00), timestamp(2021, 10, 28, 12, 30, 00), timestamp(2021, 10, 29, 12, 30, 00), timestamp(2021, 10, 29, 14, 00, 00), timestamp(2021, 11, 01, 13, 45, 00), timestamp(2021, 11, 01, 14, 00, 00), timestamp(2021, 11, 03, 12, 15, 00), timestamp(2021, 11, 03, 13, 45, 00), timestamp(2021, 11, 03, 14, 00, 00), timestamp(2021, 11, 03, 18, 00, 00), timestamp(2021, 11, 03, 18, 30, 00), timestamp(2021, 11, 04, 12, 30, 00), timestamp(2021, 11, 04, 12, 30, 00), timestamp(2021, 11, 05, 12, 30, 00), timestamp(2021, 11, 08, 15, 30, 00), timestamp(2021, 11, 09, 14, 00, 00), timestamp(2021, 11, 10, 13, 30, 00), timestamp(2021, 11, 10, 13, 30, 00), timestamp(2021, 11, 12, 15, 00, 00), timestamp(2021, 11, 16, 13, 30, 00), timestamp(2021, 11, 18, 13, 30, 00), timestamp(2021, 11, 22, 15, 00, 00), timestamp(2021, 11, 23, 14, 45, 00), timestamp(2021, 11, 23, 14, 45, 00), timestamp(2021, 11, 24, 13, 30, 00), timestamp(2021, 11, 24, 13, 30, 00), timestamp(2021, 11, 24, 13, 30, 00), timestamp(2021, 11, 24, 15, 00, 00), timestamp(2021, 11, 24, 15, 00, 00), timestamp(2021, 11, 24, 15, 00, 00), timestamp(2021, 11, 24, 19, 00, 00), timestamp(2021, 11, 29, 20, 05, 00), timestamp(2021, 11, 30, 15, 00, 00), timestamp(2021, 12, 01, 13, 15, 00), timestamp(2021, 12, 01, 14, 45, 00), timestamp(2021, 12, 01, 15, 00, 00), timestamp(2021, 12, 01, 15, 00, 00), timestamp(2021, 12, 02, 13, 30, 00), timestamp(2021, 12, 03, 13, 30, 00), timestamp(2021, 12, 03, 14, 45, 00), timestamp(2021, 12, 03, 15, 00, 00), timestamp(2021, 12, 07, 13, 30, 00), timestamp(2021, 12, 09, 13, 30, 00), timestamp(2021, 12, 10, 13, 30, 00), timestamp(2021, 12, 10, 15, 00, 00), timestamp(2021, 12, 15, 13, 30, 00), timestamp(2021, 12, 15, 19, 00, 00), timestamp(2021, 12, 15, 19, 30, 00), timestamp(2021, 12, 16, 13, 30, 00), timestamp(2021, 12, 16, 14, 45, 00), timestamp(2021, 12, 16, 14, 45, 00), timestamp(2021, 12, 22, 15, 00, 00), timestamp(2021, 12, 23, 13, 30, 00), timestamp(2021, 12, 23, 13, 30, 00), timestamp(2021, 12, 23, 13, 30, 00), timestamp(2021, 12, 23, 15, 00, 00), timestamp(2021, 12, 23, 15, 00, 00), timestamp(2021, 12, 29, 13, 30, 00), timestamp(2021, 12, 30, 13, 30, 00), timestamp(2022, 01, 03, 14, 45, 00), timestamp(2022, 01, 04, 15, 00, 00), timestamp(2022, 01, 05, 13, 15, 00), timestamp(2022, 01, 05, 14, 45, 00), timestamp(2022, 01, 05, 19, 00, 00), timestamp(2022, 01, 06, 13, 30, 00), timestamp(2022, 01, 06, 13, 30, 00), timestamp(2022, 01, 06, 15, 00, 00), timestamp(2022, 01, 07, 13, 30, 00), timestamp(2022, 01, 11, 15, 00, 00), timestamp(2022, 01, 12, 13, 30, 00), timestamp(2022, 01, 13, 13, 30, 00), timestamp(2022, 01, 14, 13, 30, 00), timestamp(2022, 01, 14, 15, 00, 00), timestamp(2022, 01, 20, 13, 30, 00), timestamp(2022, 01, 20, 15, 00, 00), timestamp(2022, 01, 24, 14, 45, 00), timestamp(2022, 01, 24, 14, 45, 00), timestamp(2022, 01, 26, 13, 30, 00), timestamp(2022, 01, 26, 15, 00, 00), timestamp(2022, 01, 26, 19, 00, 00), timestamp(2022, 01, 26, 19, 30, 00), timestamp(2022, 01, 27, 13, 30, 00), timestamp(2022, 01, 27, 13, 30, 00), timestamp(2022, 01, 27, 13, 30, 00), timestamp(2022, 01, 28, 13, 30, 00), timestamp(2022, 01, 28, 15, 00, 00), timestamp(2022, 02, 01, 14, 45, 00), timestamp(2022, 02, 01, 15, 00, 00), timestamp(2022, 02, 02, 13, 15, 00), timestamp(2022, 02, 03, 13, 30, 00), timestamp(2022, 02, 03, 14, 45, 00), timestamp(2022, 02, 03, 15, 00, 00), timestamp(2022, 02, 04, 13, 30, 00), timestamp(2022, 02, 08, 13, 30, 00), timestamp(2022, 02, 10, 13, 30, 00), timestamp(2022, 02, 10, 13, 30, 00), timestamp(2022, 02, 11, 15, 00, 00), timestamp(2022, 02, 16, 13, 30, 00), timestamp(2022, 02, 16, 19, 00, 00), timestamp(2022, 02, 17, 13, 30, 00), timestamp(2022, 02, 18, 15, 00, 00), timestamp(2022, 02, 22, 14, 45, 00), timestamp(2022, 02, 22, 14, 45, 00), timestamp(2022, 02, 24, 13, 30, 00), timestamp(2022, 02, 24, 13, 30, 00), timestamp(2022, 02, 24, 15, 00, 00), timestamp(2022, 02, 25, 13, 30, 00), timestamp(2022, 02, 25, 13, 30, 00), timestamp(2022, 02, 25, 15, 00, 00), timestamp(2022, 02, 28, 13, 30, 00), timestamp(2022, 03, 01, 14, 45, 00), timestamp(2022, 03, 01, 15, 00, 00), timestamp(2022, 03, 02, 13, 15, 00), timestamp(2022, 03, 02, 15, 00, 00), timestamp(2022, 03, 03, 13, 30, 00), timestamp(2022, 03, 03, 14, 45, 00), timestamp(2022, 03, 03, 15, 00, 00), timestamp(2022, 03, 03, 15, 00, 00), timestamp(2022, 03, 04, 13, 30, 00), timestamp(2022, 03, 08, 13, 30, 00), timestamp(2022, 03, 10, 13, 30, 00), timestamp(2022, 03, 10, 13, 30, 00), timestamp(2022, 03, 11, 15, 00, 00), timestamp(2022, 03, 16, 12, 30, 00), timestamp(2022, 03, 16, 18, 00, 00), timestamp(2022, 03, 16, 18, 30, 00), timestamp(2022, 03, 17, 12, 30, 00), timestamp(2022, 03, 18, 14, 00, 00), timestamp(2022, 03, 21, 16, 00, 00), timestamp(2022, 03, 23, 12, 00, 00), timestamp(2022, 03, 23, 14, 00, 00), timestamp(2022, 03, 24, 12, 30, 00), timestamp(2022, 03, 24, 12, 30, 00), timestamp(2022, 03, 24, 13, 45, 00), timestamp(2022, 03, 24, 13, 45, 00), timestamp(2022, 03, 25, 14, 00, 00), timestamp(2022, 03, 28, 12, 30, 00), timestamp(2022, 03, 30, 12, 15, 00), timestamp(2022, 03, 31, 12, 30, 00), timestamp(2022, 03, 31, 12, 30, 00), timestamp(2022, 04, 01, 12, 30, 00), timestamp(2022, 04, 01, 13, 45, 00), timestamp(2022, 04, 01, 14, 00, 00), timestamp(2022, 04, 05, 12, 30, 00), timestamp(2022, 04, 05, 13, 45, 00), timestamp(2022, 04, 05, 14, 00, 00), timestamp(2022, 04, 06, 18, 00, 00), timestamp(2022, 04, 07, 12, 30, 00), timestamp(2022, 04, 12, 12, 30, 00), timestamp(2022, 04, 14, 12, 30, 00), timestamp(2022, 04, 14, 12, 30, 00), timestamp(2022, 04, 14, 14, 00, 00), timestamp(2022, 04, 20, 14, 00, 00), timestamp(2022, 04, 21, 12, 30, 00), timestamp(2022, 04, 21, 15, 00, 00), timestamp(2022, 04, 21, 17, 00, 00), timestamp(2022, 04, 22, 13, 45, 00), timestamp(2022, 04, 22, 13, 45, 00), timestamp(2022, 04, 26, 12, 30, 00), timestamp(2022, 04, 26, 14, 00, 00), timestamp(2022, 04, 27, 12, 30, 00), timestamp(2022, 04, 28, 12, 30, 00), timestamp(2022, 04, 28, 12, 30, 00), timestamp(2022, 04, 29, 12, 30, 00), timestamp(2022, 04, 29, 14, 00, 00), timestamp(2022, 05, 02, 13, 45, 00), timestamp(2022, 05, 02, 14, 00, 00), timestamp(2022, 05, 04, 12, 15, 00), timestamp(2022, 05, 04, 12, 30, 00), timestamp(2022, 05, 04, 13, 45, 00), timestamp(2022, 05, 04, 14, 00, 00), timestamp(2022, 05, 04, 18, 00, 00), timestamp(2022, 05, 04, 18, 30, 00), timestamp(2022, 05, 05, 12, 30, 00), timestamp(2022, 05, 06, 12, 30, 00), timestamp(2022, 05, 11, 12, 30, 00), timestamp(2022, 05, 12, 12, 30, 00), timestamp(2022, 05, 13, 14, 00, 00), timestamp(2022, 05, 17, 12, 30, 00), timestamp(2022, 05, 17, 18, 00, 00), timestamp(2022, 05, 19, 12, 30, 00), timestamp(2022, 05, 19, 14, 00, 00), timestamp(2022, 05, 24, 13, 45, 00), timestamp(2022, 05, 24, 13, 45, 00), timestamp(2022, 05, 24, 14, 00, 00), timestamp(2022, 05, 24, 16, 20, 00), timestamp(2022, 05, 25, 12, 30, 00), timestamp(2022, 05, 25, 18, 00, 00), timestamp(2022, 05, 26, 12, 30, 00), timestamp(2022, 05, 26, 12, 30, 00), timestamp(2022, 05, 27, 12, 30, 00), timestamp(2022, 05, 27, 12, 30, 00), timestamp(2022, 05, 27, 14, 00, 00), timestamp(2022, 06, 01, 13, 45, 00), timestamp(2022, 06, 01, 14, 00, 00), timestamp(2022, 06, 02, 12, 15, 00), timestamp(2022, 06, 02, 12, 30, 00), timestamp(2022, 06, 03, 12, 30, 00), timestamp(2022, 06, 03, 13, 45, 00), timestamp(2022, 06, 03, 14, 00, 00), timestamp(2022, 06, 07, 12, 30, 00), timestamp(2022, 06, 09, 12, 30, 00), timestamp(2022, 06, 10, 12, 30, 00), timestamp(2022, 06, 10, 14, 00, 00), timestamp(2022, 06, 15, 12, 30, 00), timestamp(2022, 06, 15, 18, 00, 00), timestamp(2022, 06, 15, 18, 30, 00), timestamp(2022, 06, 16, 12, 30, 00), timestamp(2022, 06, 17, 12, 45, 00), timestamp(2022, 06, 21, 14, 00, 00), timestamp(2022, 06, 22, 13, 30, 00), timestamp(2022, 06, 23, 12, 30, 00), timestamp(2022, 06, 23, 13, 45, 00), timestamp(2022, 06, 23, 13, 45, 00), timestamp(2022, 06, 23, 14, 00, 00), timestamp(2022, 06, 24, 14, 00, 00), timestamp(2022, 06, 24, 14, 00, 00), timestamp(2022, 06, 27, 12, 30, 00), timestamp(2022, 06, 28, 12, 30, 00), timestamp(2022, 06, 29, 13, 00, 00), timestamp(2022, 06, 30, 12, 30, 00), timestamp(2022, 06, 30, 12, 30, 00), timestamp(2022, 07, 01, 14, 00, 00), timestamp(2022, 07, 06, 14, 00, 00), timestamp(2022, 07, 06, 18, 00, 00), timestamp(2022, 07, 07, 12, 30, 00), timestamp(2022, 07, 07, 12, 30, 00), timestamp(2022, 07, 08, 12, 30, 00), timestamp(2022, 07, 13, 12, 30, 00), timestamp(2022, 07, 13, 12, 30, 00), timestamp(2022, 07, 14, 12, 30, 00), timestamp(2022, 07, 15, 12, 30, 00), timestamp(2022, 07, 15, 14, 00, 00), timestamp(2022, 07, 20, 14, 00, 00), timestamp(2022, 07, 21, 12, 30, 00), timestamp(2022, 07, 26, 14, 00, 00), timestamp(2022, 07, 27, 12, 30, 00), timestamp(2022, 07, 27, 12, 30, 00), timestamp(2022, 07, 27, 18, 00, 00), timestamp(2022, 07, 27, 18, 30, 00), timestamp(2022, 07, 28, 12, 30, 00), timestamp(2022, 07, 28, 12, 30, 00), timestamp(2022, 07, 29, 12, 30, 00), timestamp(2022, 07, 29, 14, 00, 00), timestamp(2022, 08, 01, 14, 00, 00), timestamp(2022, 08, 03, 14, 00, 00), timestamp(2022, 08, 04, 12, 30, 00), timestamp(2022, 08, 04, 12, 30, 00), timestamp(2022, 08, 05, 12, 30, 00), timestamp(2022, 08, 10, 12, 30, 00), timestamp(2022, 08, 10, 12, 30, 00), timestamp(2022, 08, 11, 12, 30, 00), timestamp(2022, 08, 12, 14, 00, 00), timestamp(2022, 08, 17, 12, 30, 00), timestamp(2022, 08, 17, 18, 00, 00), timestamp(2022, 08, 18, 12, 30, 00), timestamp(2022, 08, 18, 14, 00, 00), timestamp(2022, 08, 23, 14, 00, 00), timestamp(2022, 08, 24, 12, 30, 00), timestamp(2022, 08, 25, 12, 30, 00), timestamp(2022, 08, 25, 12, 30, 00), timestamp(2022, 08, 26, 12, 30, 00), timestamp(2022, 08, 26, 12, 30, 00), timestamp(2022, 08, 26, 14, 00, 00), timestamp(2022, 08, 26, 14, 00, 00), timestamp(2022, 08, 31, 12, 15, 00), timestamp(2022, 09, 01, 12, 30, 00), timestamp(2022, 09, 01, 14, 00, 00), timestamp(2022, 09, 02, 12, 30, 00), timestamp(2022, 09, 06, 14, 00, 00), timestamp(2022, 09, 07, 12, 30, 00), timestamp(2022, 09, 08, 12, 30, 00), timestamp(2022, 09, 13, 12, 30, 00), timestamp(2022, 09, 13, 12, 30, 00), timestamp(2022, 09, 15, 12, 30, 00), timestamp(2022, 09, 15, 12, 30, 00), timestamp(2022, 09, 16, 14, 00, 00), timestamp(2022, 09, 21, 14, 00, 00), timestamp(2022, 09, 21, 18, 00, 00), timestamp(2022, 09, 21, 18, 30, 00), timestamp(2022, 09, 22, 12, 30, 00), timestamp(2022, 09, 23, 18, 00, 00), timestamp(2022, 09, 27, 12, 30, 00), timestamp(2022, 09, 27, 14, 00, 00), timestamp(2022, 09, 28, 12, 30, 00), timestamp(2022, 09, 28, 14, 15, 00), timestamp(2022, 09, 29, 12, 30, 00), timestamp(2022, 09, 30, 12, 30, 00), timestamp(2022, 09, 30, 14, 00, 00), timestamp(2022, 10, 03, 14, 00, 00), timestamp(2022, 10, 05, 12, 15, 00), timestamp(2022, 10, 05, 12, 30, 00), timestamp(2022, 10, 05, 14, 00, 00), timestamp(2022, 10, 06, 12, 30, 00), timestamp(2022, 10, 07, 12, 30, 00), timestamp(2022, 10, 12, 18, 00, 00), timestamp(2022, 10, 13, 12, 30, 00), timestamp(2022, 10, 13, 12, 30, 00), timestamp(2022, 10, 13, 12, 30, 00), timestamp(2022, 10, 14, 12, 30, 00), timestamp(2022, 10, 14, 14, 00, 00), timestamp(2022, 10, 20, 12, 30, 00), timestamp(2022, 10, 20, 14, 00, 00), timestamp(2022, 10, 26, 12, 30, 00), timestamp(2022, 10, 26, 14, 00, 00), timestamp(2022, 10, 27, 12, 30, 00), timestamp(2022, 10, 27, 12, 30, 00), timestamp(2022, 10, 27, 12, 30, 00), timestamp(2022, 10, 28, 12, 30, 00), timestamp(2022, 10, 28, 14, 00, 00), timestamp(2022, 11, 01, 14, 00, 00), timestamp(2022, 11, 02, 12, 15, 00), timestamp(2022, 11, 02, 18, 00, 00), timestamp(2022, 11, 02, 18, 30, 00), timestamp(2022, 11, 03, 12, 30, 00), timestamp(2022, 11, 03, 12, 30, 00), timestamp(2022, 11, 03, 14, 00, 00), timestamp(2022, 11, 04, 12, 30, 00), timestamp(2022, 11, 10, 13, 30, 00), timestamp(2022, 11, 10, 13, 30, 00), timestamp(2022, 11, 10, 13, 30, 00), timestamp(2022, 11, 11, 15, 00, 00), timestamp(2022, 11, 16, 13, 30, 00), timestamp(2022, 11, 17, 13, 30, 00), timestamp(2022, 11, 18, 15, 00, 00), timestamp(2022, 11, 23, 13, 30, 00), timestamp(2022, 11, 23, 13, 30, 00), timestamp(2022, 11, 23, 15, 00, 00), timestamp(2022, 11, 23, 15, 00, 00), timestamp(2022, 11, 23, 19, 00, 00), timestamp(2022, 11, 30, 13, 15, 00), timestamp(2022, 11, 30, 13, 30, 00), timestamp(2022, 11, 30, 13, 30, 00), timestamp(2022, 11, 30, 18, 30, 00), timestamp(2022, 12, 01, 13, 30, 00), timestamp(2022, 12, 01, 13, 30, 00), timestamp(2022, 12, 01, 15, 00, 00), timestamp(2022, 12, 02, 13, 30, 00), timestamp(2022, 12, 05, 15, 00, 00), timestamp(2022, 12, 06, 13, 30, 00), timestamp(2022, 12, 08, 13, 30, 00), timestamp(2022, 12, 09, 15, 00, 00), timestamp(2022, 12, 13, 13, 30, 00), timestamp(2022, 12, 13, 13, 30, 00), timestamp(2022, 12, 14, 19, 00, 00), timestamp(2022, 12, 14, 19, 30, 00), timestamp(2022, 12, 15, 13, 30, 00), timestamp(2022, 12, 15, 13, 30, 00), timestamp(2022, 12, 21, 15, 00, 00), timestamp(2022, 12, 22, 13, 30, 00), timestamp(2022, 12, 23, 13, 30, 00), timestamp(2022, 12, 23, 13, 30, 00), timestamp(2022, 12, 23, 15, 00, 00), timestamp(2022, 12, 23, 15, 00, 00), timestamp(2022, 12, 27, 13, 30, 00), timestamp(2022, 12, 29, 13, 30, 00), timestamp(2023, 01, 04, 15, 00, 00), timestamp(2023, 01, 04, 19, 00, 00), timestamp(2023, 01, 05, 13, 15, 00), timestamp(2023, 01, 05, 13, 30, 00), timestamp(2023, 01, 05, 13, 30, 00), timestamp(2023, 01, 06, 13, 30, 00), timestamp(2023, 01, 06, 15, 00, 00), timestamp(2023, 01, 10, 14, 00, 00), timestamp(2023, 01, 12, 13, 30, 00), timestamp(2023, 01, 12, 13, 30, 00), timestamp(2023, 01, 12, 13, 30, 00), timestamp(2023, 01, 13, 15, 00, 00), timestamp(2023, 01, 18, 13, 30, 00), timestamp(2023, 01, 19, 13, 30, 00), timestamp(2023, 01, 20, 15, 00, 00), timestamp(2023, 01, 26, 13, 30, 00), timestamp(2023, 01, 26, 13, 30, 00), timestamp(2023, 01, 26, 13, 30, 00), timestamp(2023, 01, 26, 15, 00, 00), timestamp(2023, 01, 27, 13, 30, 00), timestamp(2023, 01, 27, 15, 00, 00), timestamp(2023, 02, 01, 13, 15, 00), timestamp(2023, 02, 01, 15, 00, 00), timestamp(2023, 02, 01, 19, 00, 00), timestamp(2023, 02, 01, 19, 30, 00), timestamp(2023, 02, 02, 13, 30, 00), timestamp(2023, 02, 03, 13, 30, 00), timestamp(2023, 02, 03, 15, 00, 00), timestamp(2023, 02, 07, 13, 30, 00), timestamp(2023, 02, 07, 17, 40, 00), timestamp(2023, 02, 09, 13, 30, 00), timestamp(2023, 02, 10, 15, 00, 00), timestamp(2023, 02, 14, 13, 30, 00), timestamp(2023, 02, 14, 13, 30, 00), timestamp(2023, 02, 15, 13, 30, 00), timestamp(2023, 02, 16, 13, 30, 00), timestamp(2023, 02, 21, 15, 00, 00), timestamp(2023, 02, 22, 19, 00, 00), timestamp(2023, 02, 23, 13, 30, 00), timestamp(2023, 02, 24, 13, 30, 00), timestamp(2023, 02, 24, 15, 00, 00), timestamp(2023, 02, 24, 15, 00, 00), timestamp(2023, 02, 27, 13, 30, 00), timestamp(2023, 02, 28, 13, 30, 00), timestamp(2023, 03, 01, 15, 00, 00), timestamp(2023, 03, 02, 13, 30, 00), timestamp(2023, 03, 03, 15, 00, 00), timestamp(2023, 03, 07, 15, 00, 00), timestamp(2023, 03, 08, 13, 15, 00), timestamp(2023, 03, 08, 13, 30, 00), timestamp(2023, 03, 09, 13, 30, 00), timestamp(2023, 03, 10, 13, 30, 00), timestamp(2023, 03, 15, 12, 30, 00), timestamp(2023, 03, 16, 12, 30, 00), timestamp(2023, 03, 17, 14, 00, 00), timestamp(2023, 03, 21, 14, 00, 00), timestamp(2023, 03, 22, 18, 00, 00), timestamp(2023, 03, 22, 18, 30, 00), timestamp(2023, 03, 23, 12, 30, 00), timestamp(2023, 03, 23, 14, 00, 00), timestamp(2023, 03, 24, 12, 30, 00), timestamp(2023, 03, 28, 12, 30, 00), timestamp(2023, 03, 30, 12, 30, 00), timestamp(2023, 03, 31, 12, 30, 00), timestamp(2023, 03, 31, 14, 00, 00), timestamp(2023, 04, 03, 14, 00, 00), timestamp(2023, 04, 05, 12, 15, 00), timestamp(2023, 04, 05, 12, 30, 00), timestamp(2023, 04, 05, 14, 00, 00), timestamp(2023, 04, 06, 12, 30, 00), timestamp(2023, 04, 07, 12, 30, 00), timestamp(2023, 04, 12, 12, 30, 00), timestamp(2023, 04, 12, 12, 30, 00), timestamp(2023, 04, 12, 18, 00, 00), timestamp(2023, 04, 13, 12, 30, 00), timestamp(2023, 04, 14, 12, 30, 00), timestamp(2023, 04, 14, 14, 00, 00), timestamp(2023, 04, 20, 12, 30, 00), timestamp(2023, 04, 20, 14, 00, 00), timestamp(2023, 04, 25, 14, 00, 00), timestamp(2023, 04, 26, 12, 30, 00), timestamp(2023, 04, 26, 12, 30, 00), timestamp(2023, 04, 27, 12, 30, 00), timestamp(2023, 04, 27, 12, 30, 00), timestamp(2023, 04, 28, 12, 30, 00), timestamp(2023, 04, 28, 14, 00, 00), timestamp(2023, 05, 01, 14, 00, 00), timestamp(2023, 05, 03, 12, 15, 00), timestamp(2023, 05, 03, 14, 00, 00), timestamp(2023, 05, 03, 18, 00, 00), timestamp(2023, 05, 03, 18, 30, 00), timestamp(2023, 05, 04, 12, 30, 00), timestamp(2023, 05, 04, 12, 30, 00), timestamp(2023, 05, 05, 12, 30, 00), timestamp(2023, 05, 10, 12, 30, 00), timestamp(2023, 05, 10, 12, 30, 00), timestamp(2023, 05, 11, 12, 30, 00), timestamp(2023, 05, 12, 14, 00, 00), timestamp(2023, 05, 16, 12, 30, 00), timestamp(2023, 05, 18, 12, 30, 00), timestamp(2023, 05, 18, 14, 00, 00), timestamp(2023, 05, 19, 15, 00, 00), timestamp(2023, 05, 23, 14, 00, 00), timestamp(2023, 05, 24, 18, 00, 00), timestamp(2023, 05, 25, 12, 30, 00), timestamp(2023, 05, 26, 12, 30, 00), timestamp(2023, 05, 26, 12, 30, 00), timestamp(2023, 05, 26, 12, 30, 00), timestamp(2023, 05, 26, 14, 00, 00), timestamp(2023, 06, 01, 12, 15, 00), timestamp(2023, 06, 01, 12, 30, 00), timestamp(2023, 06, 01, 14, 00, 00), timestamp(2023, 06, 02, 12, 30, 00), timestamp(2023, 06, 07, 12, 30, 00), timestamp(2023, 06, 08, 12, 30, 00), timestamp(2023, 06, 13, 12, 30, 00), timestamp(2023, 06, 13, 12, 30, 00), timestamp(2023, 06, 14, 18, 00, 00), timestamp(2023, 06, 14, 18, 30, 00), timestamp(2023, 06, 15, 12, 30, 00), timestamp(2023, 06, 15, 12, 30, 00), timestamp(2023, 06, 16, 14, 00, 00), timestamp(2023, 06, 22, 12, 30, 00), timestamp(2023, 06, 22, 14, 00, 00), timestamp(2023, 06, 27, 12, 30, 00), timestamp(2023, 06, 27, 14, 00, 00), timestamp(2023, 06, 28, 12, 30, 00), timestamp(2023, 06, 29, 12, 30, 00), timestamp(2023, 06, 30, 12, 30, 00), timestamp(2023, 06, 30, 14, 00, 00), timestamp(2023, 07, 03, 14, 00, 00), timestamp(2023, 07, 05, 18, 00, 00), timestamp(2023, 07, 06, 12, 15, 00), timestamp(2023, 07, 06, 12, 30, 00), timestamp(2023, 07, 06, 12, 30, 00), timestamp(2023, 07, 07, 12, 30, 00), timestamp(2023, 07, 12, 12, 30, 00), timestamp(2023, 07, 12, 12, 30, 00), timestamp(2023, 07, 13, 12, 30, 00), timestamp(2023, 07, 14, 14, 00, 00), timestamp(2023, 07, 18, 12, 30, 00), timestamp(2023, 07, 20, 12, 30, 00), timestamp(2023, 07, 20, 14, 00, 00), timestamp(2023, 07, 26, 14, 00, 00), timestamp(2023, 07, 26, 18, 00, 00), timestamp(2023, 07, 26, 18, 30, 00), timestamp(2023, 07, 27, 12, 30, 00), timestamp(2023, 07, 27, 12, 30, 00), timestamp(2023, 07, 27, 12, 30, 00), timestamp(2023, 07, 27, 12, 30, 00), timestamp(2023, 07, 28, 12, 30, 00), timestamp(2023, 07, 28, 14, 00, 00), timestamp(2023, 08, 01, 14, 00, 00), timestamp(2023, 08, 02, 12, 15, 00), timestamp(2023, 08, 03, 12, 30, 00), timestamp(2023, 08, 04, 12, 30, 00), timestamp(2023, 08, 08, 12, 30, 00), timestamp(2023, 08, 10, 12, 30, 00), timestamp(2023, 08, 10, 12, 30, 00), timestamp(2023, 08, 10, 12, 30, 00), timestamp(2023, 08, 11, 14, 00, 00), timestamp(2023, 08, 15, 12, 30, 00), timestamp(2023, 08, 16, 18, 00, 00), timestamp(2023, 08, 17, 12, 30, 00), timestamp(2023, 08, 22, 14, 00, 00), timestamp(2023, 08, 23, 14, 00, 00), timestamp(2023, 08, 24, 12, 30, 00), timestamp(2023, 08, 24, 12, 30, 00), timestamp(2023, 08, 25, 14, 00, 00), timestamp(2023, 08, 25, 14, 05, 00), timestamp(2023, 08, 30, 12, 15, 00), timestamp(2023, 08, 30, 12, 30, 00), timestamp(2023, 08, 31, 12, 30, 00), timestamp(2023, 08, 31, 12, 30, 00), timestamp(2023, 09, 01, 12, 30, 00), timestamp(2023, 09, 01, 14, 00, 00), timestamp(2023, 09, 07, 12, 30, 00), timestamp(2023, 09, 13, 12, 30, 00), timestamp(2023, 09, 13, 12, 30, 00), timestamp(2023, 09, 14, 12, 30, 00), timestamp(2023, 09, 14, 12, 30, 00), timestamp(2023, 09, 15, 14, 00, 00), timestamp(2023, 09, 20, 18, 00, 00), timestamp(2023, 09, 20, 18, 30, 00), timestamp(2023, 09, 21, 12, 30, 00), timestamp(2023, 09, 21, 14, 00, 00), timestamp(2023, 09, 26, 14, 00, 00), timestamp(2023, 09, 27, 12, 30, 00), timestamp(2023, 09, 28, 12, 30, 00), timestamp(2023, 09, 28, 20, 00, 00), timestamp(2023, 09, 29, 12, 30, 00), timestamp(2023, 09, 29, 12, 30, 00), timestamp(2023, 09, 29, 14, 00, 00), timestamp(2023, 10, 02, 14, 00, 00), timestamp(2023, 10, 02, 15, 00, 00), timestamp(2023, 10, 04, 12, 15, 00), timestamp(2023, 10, 05, 12, 30, 00), timestamp(2023, 10, 06, 12, 30, 00), timestamp(2023, 10, 11, 18, 00, 00), timestamp(2023, 10, 12, 12, 30, 00), timestamp(2023, 10, 12, 12, 30, 00), timestamp(2023, 10, 12, 12, 30, 00), timestamp(2023, 10, 13, 14, 00, 00), timestamp(2023, 10, 17, 12, 30, 00), timestamp(2023, 10, 19, 12, 30, 00), timestamp(2023, 10, 19, 14, 00, 00), timestamp(2023, 10, 25, 14, 00, 00), timestamp(2023, 10, 26, 12, 30, 00), timestamp(2023, 10, 26, 12, 30, 00), timestamp(2023, 10, 26, 12, 30, 00), timestamp(2023, 10, 26, 12, 30, 00), timestamp(2023, 10, 27, 12, 30, 00), timestamp(2023, 10, 27, 14, 00, 00), timestamp(2023, 11, 01, 12, 15, 00), timestamp(2023, 11, 01, 14, 00, 00), timestamp(2023, 11, 01, 18, 00, 00), timestamp(2023, 11, 01, 18, 30, 00), timestamp(2023, 11, 02, 12, 30, 00), timestamp(2023, 11, 03, 12, 30, 00), timestamp(2023, 11, 09, 13, 30, 00), timestamp(2023, 11, 10, 15, 00, 00), timestamp(2023, 11, 14, 13, 30, 00), timestamp(2023, 11, 14, 13, 30, 00), timestamp(2023, 11, 15, 13, 30, 00), timestamp(2023, 11, 16, 13, 30, 00), timestamp(2023, 11, 21, 15, 00, 00), timestamp(2023, 11, 22, 13, 30, 00), timestamp(2023, 11, 22, 15, 00, 00), timestamp(2023, 11, 22, 19, 00, 00), timestamp(2122, 12, 06, 15, 30, 00)) var EventNames = array.from("Markit Manufacturing PMI", "ISM Manufacturing PMI", "ADP Employment Change", "Markit Services/Composite PMI", "Balance of Trade", "Jobless Claims", "ISM Non-Manufacturing PMI", "Non Farm Payrolls", "Inflation Rate", "Jobless Claims", "Fed Chair", "Retail Sales", "Michigan Consumer Sentiment", "Treasury Secretary", "Jobless Claims", "Markit Services/Composite PMI", "Markit Manufacturing PMI", "Existing Home Sales", "Durable Goods Orders", "Fed Interest Rate Decision", "Fed Press Conference", "GDP", "Goods Trade Balance", "Jobless Claims", "New Home Sales", "Personal Income/Spending", "Michigan Consumer Sentiment", "Markit Manufacturing PMI", "ISM Manufacturing PMI", "ADP Employment Change", "Markit Services/Composite PMI", "ISM Non-Manufacturing PMI", "Jobless Claims", "Non Farm Payrolls", "Balance of Trade", "Inflation Rate", "Fed Chair", "Jobless Claims", "Michigan Consumer Sentiment", "Retail Sales", "FOMC Minutes", "Jobless Claims", "Markit Manufacturing PMI", "Markit Services/Composite PMI", "Existing Home Sales", "Fed Chair", "New Home Sales", "Fed Chair", "Durable Goods Orders", "Jobless Claims", "Personal Income/Spending", "Goods Trade Balance", "Michigan Consumer Sentiment", "Markit Manufacturing PMI", "ISM Manufacturing PMI", "ADP Employment Change", "Markit Services/Composite PMI", "ISM Non-Manufacturing PMI", "Jobless Claims", "Fed Chair", "Non Farm Payrolls", "Balance of Trade", "Inflation Rate", "Jobless Claims", "Michigan Consumer Sentiment", "Retail Sales", "Fed Interest Rate Decision", "Fed Press Conference", "Jobless Claims", "Fed Chair", "Existing Home Sales", "New Home Sales", "Fed Chair", "Durable Goods Orders", "Markit Services/Composite PMI", "Markit Manufacturing PMI", "Fed Chair", "Jobless Claims", "Personal Income/Spending", "Goods Trade Balance", "Michigan Consumer Sentiment", "ADP Employment Change", "Jobless Claims", "Markit Manufacturing PMI", "ISM Manufacturing PMI", "Non Farm Payrolls", "Markit Services/Composite PMI", "ISM Non-Manufacturing PMI", "Balance of Trade", "FOMC Minutes", "Jobless Claims", "Fed Chair", "Inflation Rate", "Fed Chair", "Jobless Claims", "Retail Sales", "Michigan Consumer Sentiment", "Jobless Claims", "Existing Home Sales", "Markit Manufacturing PMI", "Markit Services/Composite PMI", "New Home Sales", "Durable Goods Orders", "Goods Trade Balance", "Fed Interest Rate Decision", "Fed Press Conference", "GDP", "Jobless Claims", "Personal Income/Spending", "Michigan Consumer Sentiment", "Markit Manufacturing PMI", "ISM Manufacturing PMI", "Fed Chair", "Balance of Trade", "ADP Employment Change", "Markit Services/Composite PMI", "ISM Non-Manufacturing PMI", "Jobless Claims", "Non Farm Payrolls", "Inflation Rate", "Jobless Claims", "Retail Sales", "Michigan Consumer Sentiment", "FOMC Minutes", "Jobless Claims", "Markit Services/Composite PMI", "Markit Manufacturing PMI", "Existing Home Sales", "New Home Sales", "Durable Goods Orders", "Jobless Claims", "Goods Trade Balance", "Personal Income/Spending", "Michigan Consumer Sentiment", "Markit Manufacturing PMI", "ISM Manufacturing PMI", "ADP Employment Change", "Jobless Claims", "Markit Services/Composite PMI", "ISM Non-Manufacturing PMI", "Fed Chair", "Non Farm Payrolls", "Balance of Trade", "Inflation Rate", "Jobless Claims", "Michigan Consumer Sentiment", "Retail Sales", "Fed Interest Rate Decision", "Fed Press Conference", "Jobless Claims", "Existing Home Sales", "Fed Chair", "Markit Manufacturing PMI", "Markit Services/Composite PMI", "New Home Sales", "Jobless Claims", "Durable Goods Orders", "Goods Trade Balance", "Personal Income/Spending", "Michigan Consumer Sentiment", "ADP Employment Change", "Jobless Claims", "Markit Manufacturing PMI", "ISM Manufacturing PMI", "Balance of Trade", "Non Farm Payrolls", "Markit Services/Composite PMI", "ISM Non-Manufacturing PMI", "FOMC Minutes", "Jobless Claims", "Inflation Rate", "Fed Chair", "Jobless Claims", "Fed Chair", "Retail Sales", "Michigan Consumer Sentiment", "Jobless Claims", "Existing Home Sales", "Markit Manufacturing PMI", "Markit Services/Composite PMI", "New Home Sales", "Durable Goods Orders", "Goods Trade Balance", "Fed Interest Rate Decision", "Fed Press Conference", "GDP", "Jobless Claims", "Personal Income/Spending", "Michigan Consumer Sentiment", "Markit Manufacturing PMI", "ISM Manufacturing PMI", "ADP Employment Change", "Markit Services/Composite PMI", "ISM Non-Manufacturing PMI", "Jobless Claims", "Balance of Trade", "Non Farm Payrolls", "Inflation Rate", "Jobless Claims", "Michigan Consumer Sentiment", "Retail Sales", "Fed Chair", "FOMC Minutes", "Jobless Claims", "Markit Manufacturing PMI", "Markit Services/Composite PMI", "Existing Home Sales", "New Home Sales", "Durable Goods Orders", "Jobless Claims", "Personal Income/Spending", "Goods Trade Balance", "Michigan Consumer Sentiment", "Fed Chair", "ADP Employment Change", "Markit Manufacturing PMI", "ISM Manufacturing PMI", "Balance of Trade", "Jobless Claims", "Non Farm Payrolls", "Markit Services/Composite PMI", "ISM Non-Manufacturing PMI", "Jobless Claims", "Inflation Rate", "Retail Sales", "Jobless Claims", "Michigan Consumer Sentiment", "Existing Home Sales", "Fed Interest Rate Decision", "Fed Press Conference", "Jobless Claims", "Markit Manufacturing PMI", "Markit Services/Composite PMI", "New Home Sales", "Durable Goods Orders", "Goods Trade Balance", "Fed Chair", "Fed Chair", "Jobless Claims", "Personal Income/Spending", "Markit Manufacturing PMI", "Michigan Consumer Sentiment", "ISM Manufacturing PMI", "Balance of Trade", "Markit Services/Composite PMI", "ISM Non-Manufacturing PMI", "ADP Employment Change", "Jobless Claims", "Non Farm Payrolls", "Inflation Rate", "FOMC Minutes", "Jobless Claims", "Retail Sales", "Michigan Consumer Sentiment", "Jobless Claims", "Existing Home Sales", "Markit Services/Composite PMI", "Markit Manufacturing PMI", "Fed Chair", "New Home Sales", "Durable Goods Orders", "Goods Trade Balance", "GDP", "Jobless Claims", "Personal Income/Spending", "Michigan Consumer Sentiment", "Markit Manufacturing PMI", "ISM Manufacturing PMI", "ADP Employment Change", "Markit Services/Composite PMI", "ISM Non-Manufacturing PMI", "Fed Interest Rate Decision", "Fed Press Conference", "Jobless Claims", "Balance of Trade", "Non Farm Payrolls", "Fed Chair", "Fed Chair", "Jobless Claims", "Inflation Rate", "Michigan Consumer Sentiment", "Retail Sales", "Jobless Claims", "Existing Home Sales", "Markit Manufacturing PMI", "Markit Services/Composite PMI", "Jobless Claims", "Durable Goods Orders", "Goods Trade Balance", "Michigan Consumer Sentiment", "New Home Sales", "Personal Income/Spending", "FOMC Minutes", "Fed Chair", "Fed Chair", "ADP Employment Change", "Markit Manufacturing PMI", "Fed Chair", "ISM Manufacturing PMI", "Jobless Claims", "Non Farm Payrolls", "Markit Services/Composite PMI", "ISM Non-Manufacturing PMI", "Balance of Trade", "Jobless Claims", "Inflation Rate", "Michigan Consumer Sentiment", "Retail Sales", "Fed Interest Rate Decision", "Fed Press Conference", "Jobless Claims", "Markit Manufacturing PMI", "Markit Services/Composite PMI", "Existing Home Sales", "Durable Goods Orders", "Personal Income/Spending", "Jobless Claims", "New Home Sales", "Michigan Consumer Sentiment", "Goods Trade Balance", "Jobless Claims", "Markit Manufacturing PMI", "ISM Manufacturing PMI", "ADP Employment Change", "Markit Services/Composite PMI", "FOMC Minutes", "Balance of Trade", "Jobless Claims", "ISM Non-Manufacturing PMI", "Non Farm Payrolls", "Fed Chair", "Inflation Rate", "Jobless Claims", "Retail Sales", "Michigan Consumer Sentiment", "Jobless Claims", "Existing Home Sales", "Markit Services/Composite PMI", "Markit Manufacturing PMI", "Goods Trade Balance", "New Home Sales", "Fed Interest Rate Decision", "Fed Press Conference", "Jobless Claims", "Durable Goods Orders", "GDP", "Personal Income/Spending", "Michigan Consumer Sentiment", "Markit Manufacturing PMI", "ISM Manufacturing PMI", "ADP Employment Change", "Jobless Claims", "Markit Services/Composite PMI", "ISM Non-Manufacturing PMI", "Non Farm Payrolls", "Balance of Trade", "Jobless Claims", "Inflation Rate", "Michigan Consumer Sentiment", "Retail Sales", "FOMC Minutes", "Jobless Claims", "Existing Home Sales", "Markit Manufacturing PMI", "Markit Services/Composite PMI", "GDP", "Jobless Claims", "New Home Sales", "Personal Income/Spending", "Durable Goods Orders", "Michigan Consumer Sentiment", "Goods Trade Balance", "Markit Manufacturing PMI", "ISM Manufacturing PMI", "ADP Employment Change", "Fed Chair", "Jobless Claims", "Markit Services/Composite PMI", "ISM Non-Manufacturing PMI", "Fed Chair", "Non Farm Payrolls", "Balance of Trade", "Inflation Rate", "Jobless Claims", "Michigan Consumer Sentiment", "Retail Sales", "Fed Interest Rate Decision", "Fed Press Conference", "Jobless Claims", "Existing Home Sales", "Fed Chair", "Fed Chair", "New Home Sales", "Durable Goods Orders", "Jobless Claims", "Markit Services/Composite PMI", "Markit Manufacturing PMI", "Michigan Consumer Sentiment", "Goods Trade Balance", "ADP Employment Change", "Jobless Claims", "Personal Income/Spending", "Non Farm Payrolls", "Markit Manufacturing PMI", "ISM Manufacturing PMI", "Balance of Trade", "Markit Services/Composite PMI", "ISM Non-Manufacturing PMI", "FOMC Minutes", "Jobless Claims", "Inflation Rate", "Retail Sales", "Jobless Claims", "Michigan Consumer Sentiment", "Existing Home Sales", "Jobless Claims", "Fed Chair", "Fed Chair", "Markit Manufacturing PMI", "Markit Services/Composite PMI", "Durable Goods Orders", "New Home Sales", "Goods Trade Balance", "GDP", "Jobless Claims", "Personal Income/Spending", "Michigan Consumer Sentiment", "Markit Manufacturing PMI", "ISM Manufacturing PMI", "ADP Employment Change", "Balance of Trade", "Markit Services/Composite PMI", "ISM Non-Manufacturing PMI", "Fed Interest Rate Decision", "Fed Press Conference", "Jobless Claims", "Non Farm Payrolls", "Inflation Rate", "Jobless Claims", "Michigan Consumer Sentiment", "Retail Sales", "Fed Chair", "Jobless Claims", "Existing Home Sales", "Markit Services/Composite PMI", "Markit Manufacturing PMI", "New Home Sales", "Fed Chair", "Durable Goods Orders", "FOMC Minutes", "GDP", "Jobless Claims", "Goods Trade Balance", "Personal Income/Spending", "Michigan Consumer Sentiment", "Markit Manufacturing PMI", "ISM Manufacturing PMI", "ADP Employment Change", "Jobless Claims", "Non Farm Payrolls", "Markit Services/Composite PMI", "ISM Non-Manufacturing PMI", "Balance of Trade", "Jobless Claims", "Inflation Rate", "Michigan Consumer Sentiment", "Retail Sales", "Fed Interest Rate Decision", "Fed Press Conference", "Jobless Claims", "Fed Chair", "Existing Home Sales", "Fed Chair", "Jobless Claims", "Markit Manufacturing PMI", "Markit Services/Composite PMI", "Fed Chair", "Michigan Consumer Sentiment", "New Home Sales", "Durable Goods Orders", "Goods Trade Balance", "Fed Chair", "Personal Income/Spending", "Jobless Claims", "ISM Manufacturing PMI", "ISM Non-Manufacturing PMI", "FOMC Minutes", "Balance of Trade", "Jobless Claims", "Non Farm Payrolls", "Inflation Rate", "CPI", "Jobless Claims", "Retail Sales", "Michigan Consumer Sentiment", "Existing Home Sales", "Jobless Claims", "New Home Sales", "Durable Goods Orders", "Goods Trade Balance", "Fed Interest Rate Decision", "Fed Press Conference", "GDP", "Jobless Claims", "Personal Income/Spending", "Michigan Consumer Sentiment", "ISM Manufacturing PMI", "ISM Non-Manufacturing PMI", "Balance of Trade", "Jobless Claims", "Non Farm Payrolls", "CPI", "Inflation Rate", "Jobless Claims", "Michigan Consumer Sentiment", "Retail Sales", "FOMC Minutes", "Jobless Claims", "Existing Home Sales", "New Home Sales", "Durable Goods Orders", "Jobless Claims", "GDP", "Personal Income/Spending", "Goods Trade Balance", "Michigan Consumer Sentiment", "Fed Chair", "ADP Employment Change", "Jobless Claims", "ISM Manufacturing PMI", "Non Farm Payrolls", "ISM Non-Manufacturing PMI", "Balance of Trade", "Jobless Claims", "Inflation Rate", "CPI", "Retail Sales", "Jobless Claims", "Michigan Consumer Sentiment", "Existing Home Sales", "Fed Interest Rate Decision", "Fed Press Conference", "Jobless Claims", "Fed Chair", "Durable Goods Orders", "New Home Sales", "Goods Trade Balance", "Fed Chair", "Jobless Claims", "Personal Income/Spending", "Michigan Consumer Sentiment", "ISM Manufacturing PMI", "ADP Employment Change", "Balance of Trade", "ISM Non-Manufacturing PMI", "Jobless Claims", "Non Farm Payrolls", "FOMC Minutes", "Inflation Rate", "Jobless Claims", "CPI", "Retail Sales", "Michigan Consumer Sentiment", "Jobless Claims", "Existing Home Sales", "Goods Trade Balance", "New Home Sales", "Durable Goods Orders", "Jobless Claims", "GDP", "Personal Income/Spending", "Michigan Consumer Sentiment", "ISM Manufacturing PMI", "ADP Employment Change", "Fed Interest Rate Decision", "Fed Press Conference", "Balance of Trade", "Jobless Claims", "ISM Non-Manufacturing PMI", "Non Farm Payrolls", "CPI", "Inflation Rate", "Jobless Claims", "Michigan Consumer Sentiment", "Retail Sales", "Jobless Claims", "Existing Home Sales", "Durable Goods Orders", "Jobless Claims", "New Home Sales", "Michigan Consumer Sentiment", "FOMC Minutes", "ADP Employment Change", "GDP", "Goods Trade Balance", "Fed Chair", "Jobless Claims", "Personal Income/Spending", "ISM Manufacturing PMI", "Non Farm Payrolls", "ISM Non-Manufacturing PMI", "Balance of Trade", "Jobless Claims", "Michigan Consumer Sentiment", "CPI", "Inflation Rate", "Fed Interest Rate Decision", "Fed Press Conference", "Jobless Claims", "Retail Sales", "Existing Home Sales", "Jobless Claims", "Personal Income/Spending", "Durable Goods Orders", "Michigan Consumer Sentiment", "New Home Sales", "Goods Trade Balance", "Jobless Claims", "ISM Manufacturing PMI", "FOMC Minutes", "ADP Employment Change", "Jobless Claims", "Balance of Trade", "Non Farm Payrolls", "ISM Non-Manufacturing PMI", "Fed Chair", "Jobless Claims", "Inflation Rate", "CPI", "Michigan Consumer Sentiment", "Retail Sales", "Jobless Claims", "Existing Home Sales", "Jobless Claims", "Goods Trade Balance", "Durable Goods Orders", "New Home Sales", "Personal Income/Spending", "Michigan Consumer Sentiment", "ADP Employment Change", "ISM Manufacturing PMI", "Fed Interest Rate Decision", "Fed Press Conference", "Jobless Claims", "Non Farm Payrolls", "ISM Non-Manufacturing PMI", "Balance of Trade", "Fed Chair", "Jobless Claims", "Michigan Consumer Sentiment", "CPI", "Inflation Rate", "Retail Sales", "Jobless Claims", "Existing Home Sales", "FOMC Minutes", "Jobless Claims", "Personal Income/Spending", "New Home Sales", "Michigan Consumer Sentiment", "Durable Goods Orders", "Goods Trade Balance", "ISM Manufacturing PMI", "Jobless Claims", "ISM Non-Manufacturing PMI", "Fed Chair", "ADP Employment Change", "Balance of Trade", "Jobless Claims", "Non Farm Payrolls", "Retail Sales", "Jobless Claims", "Michigan Consumer Sentiment", "Existing Home Sales", "Fed Interest Rate Decision", "Fed Press Conference", "Jobless Claims", "New Home Sales", "Durable Goods Orders", "Goods Trade Balance", "Jobless Claims", "Personal Income/Spending", "Michigan Consumer Sentiment", "ISM Manufacturing PMI", "ADP Employment Change", "Balance of Trade", "ISM Non-Manufacturing PMI", "Jobless Claims", "Non Farm Payrolls", "Inflation Rate", "CPI", "FOMC Minutes", "Jobless Claims", "Retail Sales", "Michigan Consumer Sentiment", "Jobless Claims", "Existing Home Sales", "New Home Sales", "Goods Trade Balance", "Durable Goods Orders", "Jobless Claims", "GDP", "Personal Income/Spending", "Michigan Consumer Sentiment", "ISM Manufacturing PMI", "ADP Employment Change", "ISM Non-Manufacturing PMI", "Fed Interest Rate Decision", "Fed Press Conference", "Jobless Claims", "Balance of Trade", "Non Farm Payrolls", "Inflation Rate", "CPI", "Jobless Claims", "Michigan Consumer Sentiment", "Retail Sales", "Jobless Claims", "Existing Home Sales", "Fed Chair", "New Home Sales", "FOMC Minutes", "Jobless Claims", "Goods Trade Balance", "Personal Income/Spending", "Durable Goods Orders", "Michigan Consumer Sentiment", "ADP Employment Change", "Jobless Claims", "ISM Manufacturing PMI", "Non Farm Payrolls", "Balance of Trade", "Jobless Claims", "Inflation Rate", "CPI", "Fed Interest Rate Decision", "Fed Press Conference", "Retail Sales", "Jobless Claims", "Michigan Consumer Sentiment", "Jobless Claims", "Existing Home Sales", "Durable Goods Orders", "New Home Sales", "Goods Trade Balance", "Jobless Claims", "Personal Income/Spending", "Michigan Consumer Sentiment", "ISM Manufacturing PMI", "FOMC Minutes", "ADP Employment Change", "Balance of Trade", "Jobless Claims", "Non Farm Payrolls", "Inflation Rate", "CPI", "Jobless Claims", "Michigan Consumer Sentiment", "Retail Sales", "Jobless Claims", "Existing Home Sales", "New Home Sales", "Fed Interest Rate Decision", "Fed Press Conference", "Jobless Claims", "Durable Goods Orders", "Goods Trade Balance", "GDP", "Personal Income/Spending", "Michigan Consumer Sentiment", "ISM Manufacturing PMI", "ADP Employment Change", "Jobless Claims", "Non Farm Payrolls", "Balance of Trade", "Jobless Claims", "Inflation Rate", "CPI", "Michigan Consumer Sentiment", "Retail Sales", "FOMC Minutes", "Jobless Claims", "Existing Home Sales", "New Home Sales", "Durable Goods Orders", "Jobless Claims", "Michigan Consumer Sentiment", "Fed Chair", "ADP Employment Change", "Goods Trade Balance", "Jobless Claims", "Personal Income/Spending", "Non Farm Payrolls", "ISM Manufacturing PMI", "Jobless Claims", "Inflation Rate", "CPI", "Retail Sales", "Jobless Claims", "Michigan Consumer Sentiment", "Fed Interest Rate Decision", "Fed Press Conference", "Jobless Claims", "Existing Home Sales", "New Home Sales", "Durable Goods Orders", "Jobless Claims", "Fed Chair", "Personal Income/Spending", "Goods Trade Balance", "Michigan Consumer Sentiment", "ISM Manufacturing PMI", "Fed Chair", "ADP Employment Change", "Jobless Claims", "Non Farm Payrolls", "FOMC Minutes", "Jobless Claims", "Inflation Rate", "CPI", "Michigan Consumer Sentiment", "Retail Sales", "Jobless Claims", "Existing Home Sales", "New Home Sales", "Goods Trade Balance", "Durable Goods Orders", "GDP", "Jobless Claims", "Personal Income/Spending", "Michigan Consumer Sentiment", "ADP Employment Change", "ISM Manufacturing PMI", "Fed Interest Rate Decision", "Fed Press Conference", "Jobless Claims", "Non Farm Payrolls", "Jobless Claims", "Michigan Consumer Sentiment", "CPI", "Inflation Rate", "Retail Sales", "Jobless Claims", "Existing Home Sales", "Durable Goods Orders", "Michigan Consumer Sentiment", "FOMC Minutes", "FakeTypeForTesting") // Getting inputs fastMA1_switch = input.string(title="Fast moving average (MA)", defval="EMA" ,options=["SMA","EMA","DEMA","TEMA" ]) slowMA1_switch = input.string(title="Slow moving average (MA)", defval="EMA" ,options=["SMA","EMA","DEMA","TEMA" ]) fast_length1 = input(title="Fast MA length", defval=50) slow_length1 = input(title="Slow MA length", defval=200) counterTrendMAangleMin = input(title="counterTrendMAangleMin -- exp.", defval=3) MAangleDiffMin = input(title="MAangleDiffMin -- exp.", defval=3) showMA = input.bool(title="Show MA -- exp.", defval=false) displayMA = showMA ? display.all : display.none fast_length = input(title="MACD Fast Length", defval=12) slow_length = input(title="MACD Slow Length", defval=26) signal_length = input.int(title="MACD Signal Smoothing", minval = 1, maxval = 50, defval = 9) src = input(title="MACD Source", defval=close) i_switch = input.string(title="Tick Highlight", defval="Moving average" ,options=["Moving average","Fixed value" ]) i_switch2 = input.string(title="Tick Source", defval="Highest bar" ,options=["Highest bar","Average","Last bar"]) signal_lengthup = input.int(title="Upticks Avg. Length", minval = 1, maxval = 5000, defval = 72) signal_lengthdown = input.int(title="Downticks Avg. Length", minval = 1, maxval = 5000, defval = 72) Orig_signal_lengthMA = input.float(title="Ticks Avg. Multiplier", minval = 0, maxval = 5000, defval = 1.39, step = 0.01) sma_source = "EMA" sma_signal = "EMA" // Plot colors col_grow_above = #26A69A col_fall_above =#B2DFDB col_grow_below = #FFCDD2 col_fall_below = #FF5252 // 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) time_macd=timeframe.period=="1"?"1": timeframe.period=="3"?"1": timeframe.period=="5"?"1": timeframe.period=="15"?"3":timeframe.period=="30"?"5":timeframe.period=="60"?"15":timeframe.period=="120"?"30":timeframe.period=="240"?"60":timeframe.period=="D"?"240":timeframe.period=="W"?"D":timeframe.period=="M"?"W":timeframe.period=="12M"?"M":timeframe.period macd = fast_ma - slow_ma macd1=request.security(syminfo.tickerid, time_macd, macd) signal = sma_signal == "SMA" ? ta.sma(macd1, signal_length) : ta.ema(macd1, signal_length) fastMAsignal = (0.0) fastMA1 = switch fastMA1_switch "SMA" => fastMAsignal:= ta.sma(close,fast_length1) "EMA" => fastMAsignal:= ta.ema(close,fast_length1) "DEMA" => ema1 = ta.ema(close,fast_length1) ema2 = ta.ema(ema1,fast_length1) fastMAsignal:= 2 * ema1 - ema2 "TEMA" => ema1 = ta.ema(close, fast_length1) ema2 = ta.ema(ema1, fast_length1) ema3 = ta.ema(ema2, fast_length1) fastMAsignal:= 3 * (ema1 - ema2) + ema3 => runtime.error("No matching MA type found.") float(na) plot(fastMAsignal, "fast MA", color=color.orange, linewidth=2, display=displayMA) slowMAsignal = (0.0) slowMA1 = switch slowMA1_switch "SMA" => slowMAsignal:= ta.sma(close,slow_length1) "EMA" => slowMAsignal:= ta.ema(close,slow_length1) "DEMA" => ema1 = ta.ema(close,slow_length1) ema2 = ta.ema(ema1,slow_length1) slowMAsignal:= 2 * ema1 - ema2 "TEMA" => ema1 = ta.ema(close, slow_length1) ema2 = ta.ema(ema1, slow_length1) ema3 = ta.ema(ema2, slow_length1) slowMAsignal:= 3 * (ema1 - ema2) + ema3 => runtime.error("No matching MA type found.") float(na) plot(slowMAsignal, "slow MA", color=color.aqua, linewidth=2, display=displayMA) var TradeCounter = 0 FirstCount = input.int(title = "First trade after EMA cross", minval = 1, maxval = 1000, defval = 1)-1 LastCount = input.int(title = "Last trade after EMA cross", minval = 1, maxval = 1000, defval = 19)-1 var TradeGroupCounter = 0 MaxTradeGroups = input.int(title = "Max No. of trade groups after EMA cross", minval = 1, maxval = 100, defval = 100) bullOrig = fastMA1>slowMA1 bearOrig = fastMA1<slowMA1 bull = bullOrig bear = bearOrig // get the MA ratio MA_ratio = math.abs(((fastMA1/slowMA1) > 0 ? (fastMA1/slowMA1) : (slowMA1/fastMA1)) - 1.0) plot(MA_ratio * 100 , "MA ratio (%)", display = display.data_window) ReverseDetectedTrend = input.bool(title="experimental (leave unchecked) -- Reverse Detected Trend", defval = false, group = "order parameters") if ReverseDetectedTrend bull := bearOrig bear := bullOrig ReverseOn_FastMAdirChange = input.bool(title="experimental (leave unchecked) -- Reverse Detected Trend on fast MA direction change", defval = false, group = "order parameters") ReverseOn_AndOnMAdiff = input.bool(title="experimental (leave unchecked) -- And on MA difference", defval = false, group = "order parameters") ReverseOn_MAdiffBiggerThan = input.float(title="MA difference bigger than (%)", minval = 0, maxval = 100, defval = 0.0, step = 0.05, group = "order parameters") / 100 SqueezeIf_MAdiff = input.bool(title="experimental (leave unchecked) -- Squeeze TP and SL if...", defval = false, group = "order parameters") SqueezeIf_SmallerThan = input.float(title="MA difference smaller than", minval = 0, maxval = 100, defval = 0.00, step = 0.05, group = "order parameters") / 100 var tradeSessionReversed = false var MAdiffSqueezed = false var MinMAdiffExceeded = false if bullOrig != bullOrig[1] // or bearOrig != bearOrig[1] TradeCounter := 0 TradeGroupCounter := 0 tradeSessionReversed := false MAdiffSqueezed := false MinMAdiffExceeded := false CountCriteriaToTrade = FirstCount <= TradeCounter and TradeCounter <= LastCount if strategy.opentrades == 0 and strategy.opentrades[1] > 0 TradeGroupCounter := TradeGroupCounter + 1 MaxTradeGroupsCriteria = TradeGroupCounter < MaxTradeGroups plot(TradeGroupCounter, "TradeGroupCounter", display = display.data_window) hist = request.security(syminfo.tickerid, time_macd, macd1 - signal) fastMAinc = fastMA1 - fastMA1[1] fastMAincPos = fastMAinc > 0 plot(fastMAinc, "fastMAinc", display = display.data_window) plot(fastMAincPos ? 1 : 0, "fastMAincPos", color=color.new(#f84f4f, 100), display = display.data_window) if not tradeSessionReversed if bullOrig == bullOrig[1] if ReverseOn_FastMAdirChange if (fastMAincPos != fastMAincPos[1]) bull := bearOrig bear := bullOrig tradeSessionReversed := true if ReverseOn_AndOnMAdiff if ReverseOn_MAdiffBiggerThan < MA_ratio bull := bearOrig bear := bullOrig tradeSessionReversed := true else bull := bullOrig bear := bearOrig tradeSessionReversed := false else bull := bearOrig bear := bullOrig tradeSessionReversed := true plot(tradeSessionReversed ? 1 : 0, "tradeSessionReversed", color=color.new(#f84f4f, 100), display = display.data_window) ReverseOn_signal_lengthMA = input.float(title="If reversed: Ticks Avg. Multiplier", minval = 0, maxval = 5000, defval = 1.39, step = 0.01, group = "order parameters") signal_lengthMA = tradeSessionReversed ? ReverseOn_signal_lengthMA : Orig_signal_lengthMA f() => [hist[4],hist[3],hist[2],hist[1], hist] ss=request.security(syminfo.tickerid, time_macd, hist, barmerge.gaps_on,barmerge.lookahead_off) [ss5,ss4,ss3,ss2,ss1]=request.security(syminfo.tickerid, time_macd, f(), barmerge.gaps_on,barmerge.lookahead_off) a = array.from(ss5,ss4,ss3,ss2,ss1) s3=i_switch2=="Highest bar"?(ss>0? array.max(a, 0) : array.min(a, 0)):i_switch2=="Average"?array.avg(a):i_switch2=="Last bar"?ss1:0 saa=timeframe.period == '1'? ss:s3 saa2=timeframe.period == '1'? ss:s3*signal_lengthMA colorss=(s3>=0 ? (s3[1] < s3 ? col_grow_above : col_fall_above) : (s3[1] < s3 ? col_grow_below : col_fall_below)) saadown = saa2 saaup = saa2 saadown:=saa>=0? saa2:saadown[1] saaup:=saa<0? saa2:saaup[1] verr=ta.ema(saadown,signal_lengthup) dowww=ta.ema(saaup,signal_lengthdown) ss22=plot(verr, title="Avg. Cloud Upper 1", color=color.new(color.white, 100)) ss33=plot(dowww, title="Avg. Cloud Lower 1", color=color.new(color.white, 100)) fill(ss22, ss33, color.new(color.white, 93), title="Avg. Cloud Background") fixeduptick = input(title="Fixed Uptick Value", defval=30) fixeddowntick = input(title="Fixed Downtick Value", defval=-30) minl = i_switch=="Fixed value"? fixeduptick : verr maxl = i_switch=="Fixed value"? fixeddowntick : dowww plot(minl, title="Avg. Cloud Upper 2", color=color.new(color.white, 81)) plot(maxl, title="Avg. Cloud Lower 2", color=color.new(color.white, 81)) colors2= s3<=minl and s3>=maxl ? #2a2e39 : colorss coro2=s3>0? bull ? #2a2e39 : colors2 : bear ? #2a2e39: colors2 plot(saa, title="Histogram", style=plot.style_columns, color=coro2) actOnFirstN_min = input.int(title = "Act on the first N signal (min)" , defval = 1, minval = 1) actOnFirstN_max = input.int(title = "Act on the first N signal (max)" , defval = 6, minval = 1) minMAdiff = input.float(title = "Min. MA difference (%)", defval = 0.82, step = 0.01) / 100 maxMAdiff = input.float(title = "Max. MA difference (%)", defval = 3.1, step = 0.1) / 100 if not MinMAdiffExceeded if minMAdiff < MA_ratio MinMAdiffExceeded := true if not MAdiffSqueezed and SqueezeIf_MAdiff if MinMAdiffExceeded if MA_ratio < SqueezeIf_SmallerThan MAdiffSqueezed := true plot(MAdiffSqueezed ? 1 : 0, "MAdiffSqueezed", color=color.new(#f84f4f, 100), display = display.data_window) LimitDiff = input.float(title="Limit Price Difference (%) (0-> market order)", minval = 0, maxval = 10, defval = 0.0, step = 0.01, group = "order parameters") / 100 Show_TPSL = input.bool(title = "Show TP and SL? (only works if the strategy is in the main graph)", defval = false, group = "order parameters") TPSL_linewidth = input.int(title="linewidth of the TP and SL lines", minval = 1, maxval = 10, defval = 1, group = "order parameters") Orig_TP = input.float(title="Take Profit - from market price (%)", minval = 0, maxval = 10, defval = 0.9, step = 0.05, group = "order parameters") / 100 ReverseOn_TP = input.float(title="If reversed: TP (%)", minval = 0, maxval = 10, defval = 0.9, step = 0.05, group = "order parameters") / 100 SqueezeIf_TP = input.float(title="If squeezed: TP (%)", minval = 0, maxval = 10, defval = 0.9, step = 0.05, group = "order parameters") / 100 TP = MAdiffSqueezed ? SqueezeIf_TP : tradeSessionReversed ? ReverseOn_TP : Orig_TP col_TP = input.color(color.green, "TP color", group = "order parameters") Orig_SL = input.float(title="Stop Loss - from market price (%)", minval = 0, maxval = 10, defval = 1.3, step = 0.05, group = "order parameters") / 100 ReverseOn_SL = input.float(title="If reversed: SL (%)", minval = 0, maxval = 10, defval = 1.3, step = 0.05, group = "order parameters") / 100 SqueezeIf_SL = input.float(title="If squeezed: SL (%)", minval = 0, maxval = 10, defval = 1.3, step = 0.05, group = "order parameters") / 100 SL = MAdiffSqueezed ? SqueezeIf_SL : tradeSessionReversed ? ReverseOn_SL : Orig_SL col_SL = input.color(color.red, "SL color", group = "order parameters") TrStop = input.bool(title="Use Trailing Stop? -- experimental", defval = false, group = "order parameters") TrTrigger = input.float(title="Trailing Stop - trigger price (%)", minval = 0, maxval = 10, defval = 0.65, step = 0.05, group = "order parameters") / 100 TrOffset = input.float(title="Trailing Stop - stop distance (%)", minval = 0, maxval = 10, defval = 0.1, step = 0.01, group = "order parameters") / 100 maxCountertrendDiff = input.float(title="Max. counter trend diff. (%) -- experimental", minval = 0, maxval = 100, defval = 100, step = 0.05, group = "order parameters") / 100 // Big thanks to © FloppyDisque for sharing the Time Filter part, that got reused in the following section: // Time Filter { // Beginning / End date filter { g_time = "Time Filter" timeZone = input.string("GMT-4", "Time Zone", group = g_time, tooltip = "GMT and UTC is the same thing \nMatch this setting to bottom right time", options = ["GMT-10", "GMT-9", "GMT-8", "GMT-7", "GMT-6", "GMT-5", "GMT-4", "GMT-3", "GMT+0", "GMT+1", "GMT+2", "GMT+3", "GMT+4", "GMT+5", "GMT+6", "GMT+7", "GMT+8", "GMT+9", "GMT+10", "GMT+10:30", "GMT+11", "GMT+12", "GMT+13", "GMT+13:45"]) startTimeIn = input.time(timestamp("01 Jan 2000"), "Start Date Filter", group = g_time, tooltip = "Changing timezone at bottom right of chart will change start time\nSet chart timezone to your prefered time first, then change indicator setting") endTimeIn = input.time(timestamp("01 Jan 2099"), "End Date Filter", group = g_time) startTimeYear = year (startTimeIn, timeZone) startTimeMonth = month (startTimeIn, timeZone) startTimeDay = dayofmonth(startTimeIn, timeZone) endTimeYear = year (endTimeIn, timeZone) endTimeMonth = month (endTimeIn, timeZone) endTimeDay = dayofmonth(endTimeIn, timeZone) startTime = timestamp(timeZone, startTimeYear, startTimeMonth, startTimeDay) endTime = timestamp(timeZone, endTimeYear, endTimeMonth, endTimeDay) inDate = time >= startTime and time <= endTime //} // Weekdays Filter { useWeek = input.bool(true, "Use Weekdays Filter?", group = g_time, tooltip = "Disable to allow all weekdays, Enable to choose certain days") useMon = input.bool(true, "Mon  ", inline = "Days", group = g_time) useTue = input.bool(true, "Tue  ", inline = "Days", group = g_time) useWed = input.bool(true, "Wed  ", inline = "Days", group = g_time) useThu = input.bool(true, "Thu  ", inline = "Days", group = g_time) useFri = input.bool(true, "Fri  ", inline = "Days", group = g_time) useSat = input.bool(false, "Sat  ", inline = "Days", group = g_time) useSun = input.bool(true, "Sun", inline = "Days", group = g_time) inWeek = if useWeek and useMon and dayofweek(time, timeZone) == dayofweek.monday true else if useWeek and useTue and dayofweek(time, timeZone) == dayofweek.tuesday true else if useWeek and useWed and dayofweek(time, timeZone) == dayofweek.wednesday true else if useWeek and useThu and dayofweek(time, timeZone) == dayofweek.thursday true else if useWeek and useFri and dayofweek(time, timeZone) == dayofweek.friday true else if useWeek and useSat and dayofweek(time, timeZone) == dayofweek.saturday true else if useWeek and useSun and dayofweek(time, timeZone) == dayofweek.sunday true else if not(useWeek) true //} // Session Filter { isInSess(_sess) => time(timeframe.period, _sess, timeZone) useSess = input.bool(true, "Use Session Filter?", group = g_time) timeSess1 = input.session("0130-1145", "Time Session", group = g_time) inSess1 = isInSess(timeSess1) useSess2 = input.bool(true, "Use 2ND Session Filter?", group = g_time) timeSess2 = input.session("1300-0000", "Time Session 2", group = g_time) inSess2 = isInSess(timeSess2) useSessFri = input.bool(true, "Use 'Friday' Filter?", group = g_time) timeSessFri = input.session("0000-2030", "Friday Session", group = g_time) inSessFri = isInSess(timeSessFri) useSessFriSatClose = input.bool(false, "Close all at the end of the Friday/Saturday Session?", group = g_time) timeSessFriClose = input.session("0000-0000", "Friday Session Close (0000-0000 : inactive)", group = g_time) timeSessSatClose = input.session("0000-0000", "Saturday Session Close (0000-0000 : inactive)", group = g_time) inSessFriClose = isInSess(timeSessFriClose) inSessSatClose = isInSess(timeSessSatClose) useSessSun = input.bool(true, "Use 'Sunday' Filter?", group = g_time) timeSessSun = input.session("2145-0000", "Sunday Session", group = g_time) inSessSun = isInSess(timeSessSun) inSess = if useSess and inSess1 true else if useSess2 and inSess2 true else if not (useSess) true if dayofweek(time, timeZone) == dayofweek.friday and useSessFri inSess := inSess and inSessFri if dayofweek(time, timeZone) == dayofweek.sunday and useSessSun inSess := inSess and inSessSun //} // Prepare Time Filter --- USE VARIABLE -->"inTime"<-- AS TIME FILTER IN ANY CODE { inTime = inDate and inWeek and inSess //bgcolor(inTime ? color.new(color.blue, 90) : na, title = "Time Filter") //} //} // News effect avoidance EventTypeAvoidance_00 = input.bool(defval=false, title="ISM Manufacturing PMI", group="News effect avoidance") EventTypeAvoidance_01 = input.bool(defval=true, title="ADP Employment Change", group="News effect avoidance") EventTypeAvoidance_02 = input.bool(defval=false, title="Markit Services/Composite PMI", group="News effect avoidance") EventTypeAvoidance_03 = input.bool(defval=false, title="Markit Manufacturing PMI", group="News effect avoidance") EventTypeAvoidance_04 = input.bool(defval=false, title="Balance of Trade", group="News effect avoidance") EventTypeAvoidance_05 = input.bool(defval=true, title="Jobless Claims", group="News effect avoidance") EventTypeAvoidance_06 = input.bool(defval=false, title="ISM Non-Manufacturing PMI", group="News effect avoidance") EventTypeAvoidance_07 = input.bool(defval=true, title="Non Farm Payrolls", group="News effect avoidance") EventTypeAvoidance_08 = input.bool(defval=true, title="CPI", group="News effect avoidance") EventTypeAvoidance_09 = input.bool(defval=true, title="Inflation Rate", group="News effect avoidance") EventTypeAvoidance_10 = input.bool(defval=true, title="Fed Chair", group="News effect avoidance") EventTypeAvoidance_11 = input.bool(defval=false, title="Retail Sales", group="News effect avoidance") EventTypeAvoidance_12 = input.bool(defval=false, title="Michigan Consumer Sentiment", group="News effect avoidance") EventTypeAvoidance_13 = input.bool(defval=true, title="Treasury Secretary", group="News effect avoidance") EventTypeAvoidance_14 = input.bool(defval=false, title="Existing Home Sales", group="News effect avoidance") EventTypeAvoidance_15 = input.bool(defval=false, title="Durable Goods Orders", group="News effect avoidance") EventTypeAvoidance_16 = input.bool(defval=true, title="Fed Interest Rate Decision", group="News effect avoidance") EventTypeAvoidance_17 = input.bool(defval=true, title="GDP", group="News effect avoidance") EventTypeAvoidance_18 = input.bool(defval=false, title="Goods Trade Balance", group="News effect avoidance") EventTypeAvoidance_19 = input.bool(defval=false, title="New Home Sales", group="News effect avoidance") EventTypeAvoidance_20 = input.bool(defval=false, title="Personal Income/Spending", group="News effect avoidance") EventTypeAvoidance_21 = input.bool(defval=true, title="FOMC Minutes", group="News effect avoidance") EventTypeAvoidance_22 = input.bool(defval=true, title="Fed Press Conference", group="News effect avoidance") array.set(EventTypeAvoidance, 0, EventTypeAvoidance_00) array.set(EventTypeAvoidance, 1, EventTypeAvoidance_01) array.set(EventTypeAvoidance, 2, EventTypeAvoidance_02) array.set(EventTypeAvoidance, 3, EventTypeAvoidance_03) array.set(EventTypeAvoidance, 4, EventTypeAvoidance_04) array.set(EventTypeAvoidance, 5, EventTypeAvoidance_05) array.set(EventTypeAvoidance, 6, EventTypeAvoidance_06) array.set(EventTypeAvoidance, 7, EventTypeAvoidance_07) array.set(EventTypeAvoidance, 8, EventTypeAvoidance_08) array.set(EventTypeAvoidance, 9, EventTypeAvoidance_09) array.set(EventTypeAvoidance, 10, EventTypeAvoidance_10) array.set(EventTypeAvoidance, 11, EventTypeAvoidance_11) array.set(EventTypeAvoidance, 12, EventTypeAvoidance_12) array.set(EventTypeAvoidance, 13, EventTypeAvoidance_13) array.set(EventTypeAvoidance, 14, EventTypeAvoidance_14) array.set(EventTypeAvoidance, 15, EventTypeAvoidance_15) array.set(EventTypeAvoidance, 16, EventTypeAvoidance_16) array.set(EventTypeAvoidance, 17, EventTypeAvoidance_17) array.set(EventTypeAvoidance, 18, EventTypeAvoidance_18) array.set(EventTypeAvoidance, 19, EventTypeAvoidance_19) array.set(EventTypeAvoidance, 20, EventTypeAvoidance_20) array.set(EventTypeAvoidance, 21, EventTypeAvoidance_21) array.set(EventTypeAvoidance, 22, EventTypeAvoidance_22) avoidance_TimeBeforeNews = 1000 * 60 * input.float(title="suspend trading X minutes before the news event", defval=80, step = 10, group="News effect avoidance") avoidance_TimeAfterNews = 1000 * 60 * input.float(title="continue trading X minutes after the news event", defval=120, step=10, group="News effect avoidance") currentTime = time(timeframe.period) lastEvent = array.binary_search_leftmost(EventTimestamps, currentTime) nextEvent = lastEvent + 1 lastEventName = array.get(EventNames, lastEvent) lastEventTypeIndex = array.indexof(EventNameTypes, lastEventName) nextEventName = array.get(EventNames, nextEvent) nextEventTypeIndex = array.indexof(EventNameTypes, nextEventName) avoidTrading = ((array.get(EventTimestamps, lastEvent) + avoidance_TimeAfterNews) > currentTime and array.get(EventTypeAvoidance, lastEventTypeIndex)) or ((array.get(EventTimestamps, nextEvent) - avoidance_TimeBeforeNews) < currentTime and array.get(EventTypeAvoidance, nextEventTypeIndex)) // test out what if trades are closed before news. closeIfAvoidTrading = input.bool(title="experimental (leave unchecked) -- Close all trades when trading is suspended before news", defval=false, group="News effect avoidance") if avoidTrading and closeIfAvoidTrading strategy.close_all() inTime := inTime and (not avoidTrading) bgcolor(inTime ? color.new(color.blue, 90) : na, title = "Time Filter") // automated trading specific part autoTradeMode = input.string(title="Automated trading service", defval="None" ,options=["None","aleeert","TTA" ], group = "Automated Trading") // aleeert specific part aleeert_key = input.string(title="aleeert userkey", defval="", group = "aleeert") aleeert_slot_id = input.string(title="aleeert slot_id", defval="", group = "aleeert") aleeert_tradingPair_override = "" aleeert_tradingPair_override := input.string(title="aleeert trading pair override (original if empty)", defval="", group = "aleeert") aleeert_tradingPair = aleeert_tradingPair_override == "" ? syminfo.ticker : aleeert_tradingPair_override aleeert_leverage = input.int(title="aleeert leverage", defval=50, minval = 1, maxval = 1000, group = "aleeert") aleeert_tradeSize_percent = input.float(title = "aleeert trade size (%)", defval = 2.0, step = 0.1, minval = 0.0, maxval = 100.0, group = "aleeert") aleeert_buy_order_precondition = "if short: " + aleeert_tradingPair + ", close, 100%, - " + ", " + aleeert_slot_id + ", " + aleeert_key aleeert_buy_order_entry = aleeert_tradingPair + "(x" + str.tostring((aleeert_leverage), '#') + ")" + ", cancel-buy, " + str.tostring((aleeert_tradeSize_percent), '#.##') + "%, market" + ", " + aleeert_slot_id + ", " + aleeert_key aleeert_buy_order_exit = aleeert_tradingPair + "(x" + str.tostring((aleeert_leverage), '#') + ")" + ", tpsl, -, " + str.tostring((close), '#.##') + "+" + str.tostring((TP*100), '#.##') + "%(100%)" + " | " + str.tostring((close), '#.##') + "-" + str.tostring((SL*100), '#.##') + "%(100%)" + ", " + aleeert_slot_id + ", " + aleeert_key // trail_price = close * (1 + TrTrigger), trail_offset = (close * TrOffset) / syminfo.mintick, aleeert_buy_order_trstop = aleeert_tradingPair + ", sell, 100%, " + str.tostring((close * (1 + TrTrigger)), '#.##') + ":" + str.tostring((TrOffset*100), '#.###') + "%(TS)" + ", " + aleeert_slot_id + ", " + aleeert_key aleeert_buy_order_command = aleeert_buy_order_precondition + "; " + aleeert_buy_order_entry + "; " + aleeert_buy_order_exit aleeert_buy_order_w_trstop_command = aleeert_buy_order_entry + "; " + aleeert_buy_order_exit + "; " + aleeert_buy_order_trstop aleeert_sell_order_precondition = "if long: " + aleeert_tradingPair + ", close, 100%, - " + ", " + aleeert_slot_id + ", " + aleeert_key aleeert_sell_order_entry = aleeert_tradingPair + "(x" + str.tostring((aleeert_leverage), '#') + ")" + ", cancel-sell, " + str.tostring((aleeert_tradeSize_percent), '#.##') + "%, market" + ", " + aleeert_slot_id + ", " + aleeert_key aleeert_sell_order_exit = aleeert_tradingPair + "(x" + str.tostring((aleeert_leverage), '#') + ")" + ", tpsl, -, " + str.tostring((close), '#.##') + "-" + str.tostring((TP*100), '#.##') + "%(100%)" + " | " + str.tostring((close), '#.##') + "+" + str.tostring((SL*100), '#.##') + "%(100%)" + ", " + aleeert_slot_id + ", " + aleeert_key aleeert_sell_order_trstop = aleeert_tradingPair + ", buy, 100%, " + str.tostring((close * (1 - TrTrigger)), '#.##') + ":" + str.tostring((TrOffset*100), '#.###') + "%(TS)" + ", " + aleeert_slot_id + ", " + aleeert_key aleeert_sell_order_command = aleeert_sell_order_precondition + "; " + aleeert_sell_order_entry + "; " + aleeert_sell_order_exit aleeert_sell_order_w_trstop_command = aleeert_sell_order_entry + "; " + aleeert_sell_order_exit + "; " + aleeert_sell_order_trstop aleeert_positon_close_command = aleeert_tradingPair + ", close, 100%, -, " + aleeert_slot_id + ", " + aleeert_key aleeert_positon_close_w_trstop_command = aleeert_tradingPair + ", cancel-close, 100%, -, " + aleeert_slot_id + ", " + aleeert_key // TTA specfic part TTA_tradingPair_override = "" TTA_tradingPair_override := input.string(title="TTA trading pair override (original if empty)", defval="", group = "TradingView to Anywhere (TTA)") TTA_tradingPair = TTA_tradingPair_override == "" ? syminfo.ticker : TTA_tradingPair_override TTA_tradeSize_percent = input.float(title = "TTA trade size (%)", defval = 2.0, step = 0.1, minval = 0.0, maxval = 100.0, group = "TradingView to Anywhere (TTA)") // trade command examples // buy BTCUSD q=1% sl=19000.00 tp=20000.00 // buy BTCUSD sl=19040.00 tp=20040.00 modify TTA_buy_order_entry = "buy " + TTA_tradingPair + " q=" + str.tostring((TTA_tradeSize_percent), '#.##') + "%" + " sl=" + str.tostring((close * (1 - SL)), '#.##') + " tp=" + str.tostring((close * (1 + TP)), '#.##') TTA_buy_order_exit = "buy " + TTA_tradingPair + " sl=" + str.tostring((close * (1 - SL)), '#.##') + " tp=" + str.tostring((close * (1 + TP)), '#.##') + " modify" TTA_sell_order_entry = "sell " + TTA_tradingPair + " q=" + str.tostring((TTA_tradeSize_percent), '#.##') + "%" + " sl=" + str.tostring((close * (1 + SL)), '#.##') + " tp=" + str.tostring((close * (1 - TP)), '#.##') TTA_sell_order_exit = "sell " + TTA_tradingPair + " sl=" + str.tostring((close * (1 + SL)), '#.##') + " tp=" + str.tostring((close * (1 - TP)), '#.##') + " modify" TTA_buy_order_command = TTA_buy_order_entry + "\n" + TTA_buy_order_exit TTA_sell_order_command = TTA_sell_order_entry + "\n" + TTA_sell_order_exit // general part buy_order_command = "" sell_order_command = "" positon_close_command = "" switch autoTradeMode "aleeert" => if TrStop buy_order_command := aleeert_buy_order_w_trstop_command sell_order_command := aleeert_sell_order_w_trstop_command positon_close_command := aleeert_positon_close_w_trstop_command else buy_order_command := aleeert_buy_order_command sell_order_command := aleeert_sell_order_command positon_close_command := aleeert_positon_close_command "TTA" => buy_order_command := TTA_buy_order_command sell_order_command := TTA_sell_order_command "None" => buy_order_command := "" sell_order_command := "" => buy_order_command := "" sell_order_command := "" runtime.error("No trade mode") float(na) var NthSignal = 0 actOnCoro2 = actOnFirstN_min <= NthSignal + 1 and NthSignal + 1 <= actOnFirstN_max uniquePostfix = ""// + "_" + str.tostring(time) enterShort = "enter short" + uniquePostfix exitShort = "exit short" + uniquePostfix enterLong = "enter long" + uniquePostfix exitLong = "exit long" + uniquePostfix var minBuyPrice = -1.0 var maxSellPrice = -1.0 var maxPyramiding = strategy.opentrades if strategy.position_size == 0 minBuyPrice := -1.0 maxSellPrice := -1.0 nextBuyAllowed = true if minBuyPrice != -1 nextBuyAllowed := minBuyPrice <= close nextSellAllowed = true if maxSellPrice != -1 nextSellAllowed := maxSellPrice >= close var actualTP = 0.0 var actualSL = 0.0 if #2a2e39 != coro2 and MaxTradeGroupsCriteria NthSignal := NthSignal + 1 //TradeCounter := TradeCounter + 1 if bull and CountCriteriaToTrade and minMAdiff < MA_ratio and MA_ratio < maxMAdiff and actOnCoro2 if nextBuyAllowed and inTime and CountCriteriaToTrade LimitPrice = close * (1 - LimitDiff) if LimitDiff != 0 strategy.entry(enterLong, strategy.long, limit = LimitPrice, alert_message = buy_order_command) if LimitDiff == 0 strategy.entry(enterLong, strategy.long, alert_message = buy_order_command) if TrStop actualTP := close * (1 + TP) actualSL := close * (1 - SL) strategy.exit(exitLong, enterLong, limit = actualTP, stop = actualSL, trail_price = close * (1 + TrTrigger), trail_offset = (close * TrOffset) / syminfo.mintick, alert_message = "", alert_profit = positon_close_command, alert_loss = positon_close_command) else actualTP := close * (1 + TP) actualSL := close * (1 - SL) strategy.exit(exitLong, enterLong, limit = actualTP, stop = actualSL, alert_message = "", alert_profit = positon_close_command, alert_loss = positon_close_command) maxSellPrice := -1.0 if minBuyPrice == -1.0 or (minBuyPrice / (1 - maxCountertrendDiff)) <= close minBuyPrice := close * (1 - maxCountertrendDiff) TradeCounter := TradeCounter + 1 if bear and minMAdiff < MA_ratio and MA_ratio < maxMAdiff and actOnCoro2 if nextSellAllowed and inTime and CountCriteriaToTrade LimitPrice = close * (1 + LimitDiff) if LimitDiff != 0 strategy.entry(enterShort, strategy.short, limit = LimitPrice, alert_message = sell_order_command) if LimitDiff == 0 strategy.entry(enterShort, strategy.short, alert_message = sell_order_command) if TrStop actualTP := close * (1 - TP) actualSL := close * (1 + SL) strategy.exit(exitShort, enterShort, limit = actualTP, stop = actualSL, trail_price = close * (1 - TrTrigger), trail_offset = (close * TrOffset) / syminfo.mintick, alert_message = "", alert_profit = positon_close_command, alert_loss = positon_close_command) else actualTP := close * (1 - TP) actualSL := close * (1 + SL) strategy.exit(exitShort, enterShort, limit = actualTP, stop = actualSL, alert_message = "", alert_profit = positon_close_command, alert_loss = positon_close_command) minBuyPrice := -1.0 if maxSellPrice == -1.0 or (maxSellPrice / (1 + maxCountertrendDiff)) <= close maxSellPrice := close * (1 + maxCountertrendDiff) TradeCounter := TradeCounter + 1 else NthSignal := 0 if tradeSessionReversed != tradeSessionReversed[1] and tradeSessionReversed strategy.close_all(alert_message = positon_close_command) if MAdiffSqueezed and not MAdiffSqueezed[1] if bull actualTP := close * (1 + TP) actualSL := close * (1 - SL) strategy.exit(exitLong, enterLong, limit = actualTP, stop = actualSL, alert_message = "", alert_profit = positon_close_command, alert_loss = positon_close_command) if bear actualTP := close * (1 - TP) actualSL := close * (1 + SL) strategy.exit(exitShort, enterShort, limit = actualTP, stop = actualSL, alert_message = "", alert_profit = positon_close_command, alert_loss = positon_close_command) TPSL_visible = Show_TPSL and (strategy.opentrades != 0 or (strategy.opentrades == 0 and strategy.opentrades[1] != 0)) plot((TPSL_visible ? actualTP : na), "TP", col_TP, TPSL_linewidth, style = plot.style_linebr) plot((TPSL_visible ? actualSL : na), "SL", col_SL, TPSL_linewidth, style = plot.style_linebr) plot(strategy.opentrades, "OpenTrades", display = display.data_window) if useSessFriSatClose and ( ((dayofweek(time, timeZone) == dayofweek.friday) and (inSessFriClose[1] and not inSessFriClose)) or ((dayofweek(time, timeZone) == dayofweek.saturday) and (inSessSatClose[1] and not inSessSatClose)) ) // run once, at the end of the session, on Fridays strategy.cancel_all() strategy.close_all(alert_message = positon_close_command) //alertcondition(#2a2e39 != coro2 , title='MACD Tick Alert', message='Joel on Crypto - MACD Tick Alert')
EMA SCALPEUR LONG V2
https://www.tradingview.com/script/k9GGLkkN/
ElPonzito
https://www.tradingview.com/u/ElPonzito/
14
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/ // © YukalMoon //@version=5 strategy(title="EMA SCALPEUR", overlay=true, initial_capital = 1000) //// input controls EMA_L = input.int (title = "EMA_L", defval = 9, minval = 1, maxval = 100, step =1) EMA_L2 = input.int (title = "EMA_L2", defval = 26, minval = 1, maxval = 100, step =1) EMA_S = input.int (title = "EMA_S", defval = 100, minval = 1, maxval = 100, step =1) EMA_S2 = input.int (title = "EMA_S2", defval = 55, minval = 1, maxval = 100, step =1) /// mise en place de ema shortest = ta.ema(close, 9) short = ta.ema(close, 26) longer = ta.ema(close, 100) longest = ta.ema(close, 55) plot(shortest, color = color.red) plot(short, color = color.orange) plot(longer, color = color.aqua) plot(longest, color = color.yellow) plot(close) //// trading indicators EMA1 = ta.ema (close,EMA_L) EMA2 = ta.ema (close,EMA_L2) EMA3 = ta.ema (close, EMA_S) EMA4 = ta.ema (close, EMA_S2) buy = ta.crossover(EMA1, EMA2) //sell = ta.crossunder(EMA1, EMA2) buyexit = ta.crossunder(EMA3, EMA4) //sellexit = ta.crossover(EMA3, EMA4) /////strategy strategy.entry ("long", strategy.long, when = buy, comment = "EXIT-LONG") //strategy.entry ("short", strategy.short, when = sell, comment = "ENTER-SHORT") ///// market exit strategy.close ("long", when = buyexit, comment = "ENTER-LONG") //strategy.close ("short", when = sellexit, comment = "EXIT-SHORT")
EMA SCALPEUR + RSi - SHORT
https://www.tradingview.com/script/RYWVzMa5/
ElPonzito
https://www.tradingview.com/u/ElPonzito/
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/ // © YukalMoon //@version=5 strategy(title="EMA SCALPEUR", overlay=true, initial_capital = 1000) //// input controls EMA_L = input.int (title = "EMA_L", defval = 9, minval = 1, maxval = 100, step =1) EMA_L2 = input.int (title = "EMA_L2", defval = 26, minval = 1, maxval = 100, step =1) EMA_S = input.int (title = "EMA_S", defval = 100, minval = 1, maxval = 100, step =1) EMA_S2 = input.int (title = "EMA_S2", defval = 55, minval = 1, maxval = 100, step =1) RSI1 = input.int (title = "RSI", defval = 5, minval = 1, maxval = 20 , step = 1) /// mise en place de ema RSI = ta.rsi(close, RSI1) shortest = ta.ema(close, 9) short = ta.ema(close, 26) longer = ta.ema(close, 100) longest = ta.ema(close, 55) plot(shortest, color = color.red) plot(short, color = color.orange) plot(longer, color = color.aqua) plot(longest, color = color.yellow) plot(close) //// trading indicators EMA1 = ta.ema (close,EMA_L) EMA2 = ta.ema (close,EMA_L2) EMA3 = ta.ema (close, EMA_S) EMA4 = ta.ema (close, EMA_S2) //buy = ta.crossover(EMA1, EMA2) and RSI > 60 and RSI <70 sell = ta.crossunder(EMA1, EMA2) and RSI > 40 //buyexit = ta.crossunder(EMA3, EMA4) sellexit = ta.crossover(EMA3, EMA4) /////strategy strategy.entry ("short", strategy.short, when = sell, comment = "ENTER-SHORT") ///// market exit strategy.close ("short", when = sellexit, comment = "EXIT-SHORT")
sonu1997
https://www.tradingview.com/script/FGELufUr-sonu1997/
Sonu1997
https://www.tradingview.com/u/Sonu1997/
16
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/ // © Sonu1997 //@version=4 //@version=5 strategy('moving average strategy', overlay=true) ema50 =ema(close, 50) ema200 =ema(close, 200) long = ema50 > ema200 short = ema50 < ema200 strategy.entry('long', strategy.long, 100, 0, when=long) strategy.entry('short', strategy.short, 100, 0, when=short) strategy.close('long', when=short) strategy.close('short', when=long)
Short Swing Bearish MACD Cross (By Coinrule)
https://www.tradingview.com/script/2bqf38Tw-Short-Swing-Bearish-MACD-Cross-By-Coinrule/
Coinrule
https://www.tradingview.com/u/Coinrule/
125
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("Shorting Bearish MACD Cross with Price Below EMA 450 (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 slowEMA = ta.ema(close, 450) // MACD [macdLine, signalLine, histogramLine] = ta.macd(close, 11, 26, 9) // Conditions goShortCondition1 = ta.crossunder(macdLine, signalLine) goShortCondition2 = slowEMA > close timePeriod = time >= timestamp(syminfo.timezone, 2021, 12, 1, 0, 0) notInTrade = strategy.position_size <= 0 strategyDirection = strategy.direction.short if (goShortCondition1 and goShortCondition2 and timePeriod and notInTrade) stopLoss = high * 1.04 takeProfit = low * 0.92 strategy.entry("Short", strategy.short) strategy.exit("exit","Short", stop=stopLoss, limit=takeProfit) plot(slowEMA, color=color.green)
Chirag Strategy SMA with StopLoss
https://www.tradingview.com/script/nRZlZdgm-Chirag-Strategy-SMA-with-StopLoss/
chiragchopra91
https://www.tradingview.com/u/chiragchopra91/
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/ // © chiragchopra91 //@version=4 strategy(title='Chirag Strategy SMA', shorttitle='CHIRAGSMA', overlay=true) plot(sma(close,10), color=color.green, linewidth=2) plot(sma(close,13), color=color.red, linewidth=2) longCondition = crossover(sma(close, 10), sma(close, 13)) shortCondition = crossover(sma(close, 13), sma(close, 10)) // Set stop loss level with input options longLossPerc = input(title="Long Stop Loss (%)", type=input.float, minval=0.0, step=0.1, defval=1) * 0.01 shortLossPerc = input(title="Short Stop Loss (%)", type=input.float, minval=0.0, step=0.1, defval=1) * 0.01 longStopPrice = strategy.position_avg_price * (1 - longLossPerc) shortStopPrice = strategy.position_avg_price * (1 + shortLossPerc) if longCondition if strategy.position_size < 0 strategy.close('Short', comment="SHORT EXIT") strategy.entry('Long', strategy.long, comment="BUY") if shortCondition if strategy.position_size > 0 strategy.close('Long', comment="BUY EXIT") strategy.entry('Short', strategy.short, comment="SHORT") if strategy.position_size > 0 strategy.exit('LONG SL', stop=longStopPrice, comment="LONG SL EXIT") if strategy.position_size < 0 strategy.exit('SHORT SL', stop=shortStopPrice, comment="SHORT SL EXIT") plot(longStopPrice, title="Long StopLoss", color=color.red) plot(shortStopPrice, title="Short StopLoss", color=color.red)
Stoch cross
https://www.tradingview.com/script/DFz3eA1B/
utanico
https://www.tradingview.com/u/utanico/
29
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/ // © utanico //@version=4 strategy(title="Stochastic", overlay=true, shorttitle="Stoch") periodK = input(35, title="K", minval=1) periodD = input(21, title="D", minval=1) smoothK = input(21, title="Smooth", minval=1) startYear = input(type=input.integer, title = "開始年", defval = 2020) startMonth = input(type=input.integer, title = "開始月", defval = 1) startDay = input(type=input.integer, title = "開始日", defval = 1) endYear = input(type=input.integer, title = "終了年", defval = 2030) endMonth = input(type=input.integer, title = "終了月", defval = 12) endDay = input(type=input.integer, title = "終了日", defval = 31) //開始日時 test_start = timestamp(startYear, startMonth, startDay, 00, 00) //終了日時 test_end = timestamp(endYear, endMonth, endDay, 00, 00) //テスト期間の指定 is_test = test_start <= time and time <= test_end k = sma(stoch(close, high, low, periodK), smoothK) d = sma(k, periodD) if (is_test) if (k > d) strategy.entry("Stoch_LE", strategy.long, comment="Stoch_LE") //if (strategy.opentrades > 0 and k < d) //strategy.close("Stoch_LE",comment="CloseLONG") if (k < d) strategy.entry("Stoch_SE", strategy.short, comment="Stoch_SE") //if (strategy.opentrades < 0 and k > d) //strategy.close("Stoch_SE",comment="CloseShort")
[Pt] Premarket Breakout Strategy
https://www.tradingview.com/script/0LJUxO7T-Pt-Premarket-Breakout-Strategy/
PtGambler
https://www.tradingview.com/u/PtGambler/
529
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © PtGambler //@version=5 strategy("[Pt] Premarket Breakout Strategy", shorttitle="PM Break Strategy", overlay=true, pyramiding=1, initial_capital=4000, commission_type=strategy.commission.cash_per_contract, slippage = 3) // ******************** 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_session = input.session("0945-1545", "Entry Session", group="Sessions") t1 = time(timeframe.period, t1_session) window = time >= timestart and time <= timefinish and t1 ? true : false margin_req = input.float(11, title="Margin Requirement / Leverage", step=0.1, group = "Trading Options") reinvest = input.bool(defval=false,title="Reinvest profit", group = "Trading Options") reinvest_percent = input.float(defval=100, title = "Reinvest percentage", group="Trading Options") //------------------------------------------------------------------------------------- profit = strategy.netprofit trade_amount = math.floor(strategy.initial_capital*margin_req / close) BSLE() => strategy.opentrades > 0 ? (bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades-1)) : na BSLEx() => strategy.opentrades == 0 ? (bar_index - strategy.closedtrades.exit_bar_index(strategy.closedtrades-1)) : na if strategy.netprofit > 0 and reinvest trade_amount := math.floor((strategy.initial_capital+(profit*reinvest_percent*0.01))*margin_req/ close) else trade_amount := math.floor(strategy.initial_capital*margin_req / close) // ***************************************************************************************************** Daily ATR ***************************************************** atrlen = input.int(14, minval=1, title="ATR period", group = "Daily ATR") iPercent = input.float(1.6, minval=0.01, maxval=100, step=0.2, 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 atr = ta.rma(ta.tr, atrlen) // --------------------------------------------- Pre-market Session HL ------------------------------------==== pm_session = input.session("0900-0930", "Pre-Market Session", group="Sessions") pm_t = time(timeframe.period, pm_session) var pm_h = 0.0 var pm_l = 9999.9 if pm_t pm_h := high > pm_h ? high : pm_h pm_l := low < pm_l ? low : pm_l pm_range = pm_h - pm_l bgcolor(pm_t?color.new(color.white,95):na) // ------------------------------------------------ Stochastic RSI -------------------------------------------------------- string TT_stochLen = "For 1 min time frame, use default 14." + "\nFor 5 min time frame, use 3." smoothK = input.int(3, "K", minval=1, group = "Stochastic RSI") smoothD = input.int(3, "D", minval=1, group = "Stochastic RSI") lengthRSI = input.int(14, "RSI Length", minval=1, group = "Stochastic RSI", tooltip = TT_stochLen) lengthStoch = input.int(14, "Stochastic Length", minval=1, group = "Stochastic RSI", tooltip = TT_stochLen) src = input(close, title="RSI Source") rsi1 = ta.rsi(src, lengthRSI) k = ta.sma(ta.stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK) d = ta.sma(k, smoothD) // -------------------------------------------------------- RSI MA Cross ----------------------------------------------------- ma(source, length, type) => switch type "SMA" => ta.sma(source, length) "Bollinger Bands" => ta.sma(source, length) "EMA" => ta.ema(source, length) "SMMA (RMA)" => ta.rma(source, length) "WMA" => ta.wma(source, length) "VWMA" => ta.vwma(source, length) len = input.int(14, minval=1, title="RSI Length", group="RSI Settings") len2 = input.int(3, title="Smooth period", group="RSI Settings") maType = input.string("SMA", title="MA Type", options=["SMA", "Bollinger Bands", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="RSI Settings") malen = input.int(100, title="MA Length", group="RSI Settings") up = ta.rma(math.max(ta.change(src), 0), len) down = ta.rma(-math.min(ta.change(src), 0), len) rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down)) rsiSM = ta.sma(rsi,len2) rsiMA = ma(rsi, malen, maType) rsi_bull = rsiSM > rsiMA and rsi > 50 and rsi > rsiSM rsi_bear = rsiSM < rsiMA and rsi < 50 and rsi < rsiSM // --------------------------------------------- Define Trend - PM HL breakout ------------------------------------------------------------------- var trend = 0 // reset trend at PM if pm_t trend := 0 else trend := trend == 0 ? (close > pm_h ? 1 : close < pm_l ? -1 : 0) : trend plot(trend,"Trade direction") //--------------------------------------------------------------------------------------------------------------- stoch_h_limit = input.int(82, "Stochastic K must be above before entry", group="Entry parameters") stoch_l_limit = input.int(18, "Stochastic K must be above before entry", group="Entry parameters") plot(time(timeframe.period, "0930-1600:23456") or pm_t? pm_h : high, title="PM High", color= time(timeframe.period, "0930-1600:23456") or pm_t? color.blue : color.new(color.black,100), linewidth=2, trackprice = true) plot(time(timeframe.period, "0930-1600:23456") or pm_t? pm_l : low, title="PM Low", color= time(timeframe.period, "0930-1600:23456") or pm_t? color.orange : color.new(color.black,100), linewidth=2, trackprice = true) // ------------------------------------------------------------ Entry -------------------------------------------- var traded = false L_entry1 = trend == 1 and traded == false and d[1] < stoch_l_limit and ta.crossover(k,d) S_entry1 = trend == -1 and traded == false and d[1] > stoch_h_limit and ta.crossunder(k,d) if L_entry1 and window strategy.entry("Long", strategy.long,trade_amount) traded := true if S_entry1 and window strategy.entry("Short", strategy.short,trade_amount) traded := true // ------------------------------------------------------------- SL & PT ------------------------------------------- RRR = input.float(2.0, "Reward to Risk Ratio", step=0.1, group="Trading Options") entry_price = strategy.opentrades.entry_price(0) L_SL = entry_price > pm_h ? pm_l - datrp : entry_price - pm_range - datrp S_SL = entry_price < pm_l ? pm_h + datrp : entry_price + pm_range + datrp L_risk = entry_price - L_SL S_risk = S_SL - entry_price L_PT = entry_price + L_risk * RRR S_PT = entry_price - S_risk * RRR p0 = plot(strategy.opentrades.size(0) == 0 ? close : entry_price, "Entry Price", color= strategy.opentrades.size(0) == 0 ? na : color.gray, linewidth=1) p1 = plot(strategy.opentrades.size(0) > 0? L_SL : low, "Long SL", color= (t1 or pm_t) and strategy.opentrades.size(0) > 0 and BSLE() > 0? color.red : color.new(color.black,100), linewidth=3) p2 = plot(strategy.opentrades.size(0) > 0? L_PT : high, "Long PT", color= (t1 or pm_t) and strategy.opentrades.size(0) > 0 and BSLE() > 0? color.green : color.new(color.black,100), linewidth=3) p3 = plot(strategy.opentrades.size(0) < 0? S_SL : high, "Long SL", color= (t1 or pm_t) and strategy.opentrades.size(0) < 0 and BSLE() > 0? color.red : color.new(color.black,100), linewidth=3) p4 = plot(strategy.opentrades.size(0) < 0? S_PT : low, "Long PT", color= (t1 or pm_t) and strategy.opentrades.size(0) < 0 and BSLE() > 0? color.green : color.new(color.black,100), linewidth=3) fill(p1, p0, color.new(color.red,95)) fill(p2, p0, color.new(color.green,95)) fill(p3, p0, color.new(color.red,95)) fill(p4, p0, color.new(color.green,95)) // ------------------------------------------ Exit ---------------------------------------------------------- L_exit1 = d > 80 and strategy.opentrades.profit(0) <=0 and rsi_bear S_exit1 = d < 20 and strategy.opentrades.profit(0) <=0 and rsi_bull if strategy.opentrades.size(0) > 0 strategy.exit("Exit", "Long", limit=L_PT, stop=L_SL) if L_exit1 strategy.close("Long", comment="Exit Early") if strategy.opentrades.size(0) < 0 strategy.exit("Exit", "Short", limit=S_PT, stop=S_SL) if S_exit1 strategy.close("Short", comment="Exit Early") if time(timeframe.period, "1555-1600:23456") or time(timeframe.period, "0755-0800:23456") strategy.close_all() traded := false pm_h := 0.0 pm_l := 9999.9
Double Bollinger Binary Options
https://www.tradingview.com/script/0KqFN1vc-Double-Bollinger-Binary-Options/
Trade_by_DB
https://www.tradingview.com/u/Trade_by_DB/
63
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/ // © Trade_by_DB //@version=5 strategy("Double Bollinger Binary Options", overlay=true, margin_long=100, margin_short=100) // Bollinger bands #1 (20,2) length1 = input.int(20, minval=1) src1 = input(close, title="Source") mult1 = input.float(2.0, minval=0.001, maxval=50, title="StdDev") basis1 = ta.sma(src1, length1) dev1 = mult1 * ta.stdev(src1, length1) upper1 = basis1 + dev1 lower1 = basis1 - dev1 //Bollinger bands #2 length2 = input.int(20, minval=1) src2 = input(close, title="Source") mult2 = input.float(3.0, minval=0.001, maxval=50, title="StdDev") basis2 = ta.sma(src2, length2) dev2 = mult2 * ta.stdev(src2, length2) upper2 = basis2 + dev2 lower2 = basis2 - dev2 //Buy Condition buy = close < lower2 and ta.rsi(close,14) <=20 sell = close > upper2 and ta.rsi(close,14) >=80 // plotshape(buy, style = shape.arrowup , color = color.green, location = location.belowbar) // plotshape(sell, style = shape.arrowdown , color = color.red, location = location.abovebar) if (buy) strategy.entry("CALL", strategy.long) if (sell) strategy.entry("PUT", strategy.short)
meta-capitulation
https://www.tradingview.com/script/t7RRJhPX-meta-capitulation/
serafimovkliment
https://www.tradingview.com/u/serafimovkliment/
22
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/ // © serafimovkliment // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © serafimovkliment //@version=5 strategy("7 period sma diff") sma_p = 30 diff = (ta.sma(close, sma_p) - low)/ta.sma(close, sma_p) is_oversold = (diff) > 0.25 val = is_oversold ? 1 : 0 local_max = 0.0 for over_days = 1 to 200 tmp = val[over_days] * (low - open[over_days-1])/open[over_days-1] * 100 if (local_max > tmp) local_max := tmp drawdown_if_oversold_yesterday = local_max sum = ta.cum(val) n = 34 over_past_2_years = ((sum - sum[n])/n)*100 plot(over_past_2_years) plot(val, color = color.red) plot(-drawdown_if_oversold_yesterday, color = color.green)
SPX Scalping Strategy
https://www.tradingview.com/script/wsykXMkv-SPX-Scalping-Strategy/
connor2279
https://www.tradingview.com/u/connor2279/
142
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/ // USE HEIEN ASHI, 1 min, SPX 500 USD OANDA // © connor2279 //@version=5 strategy(title="SPX Strategy", shorttitle="SPXS", overlay=true) //SMA len1 = 10 src1 = input(close, title="SMA Source #1") out1 = ta.sma(src1, len1) plot(out1, title="SMA #1", color=close >= out1 ? color.lime : color.red, linewidth=2) data_over = ta.crossover(close, out1) dataO = close >= out1 data_under = ta.crossunder(close, out1) dataU = close < out1 bgcolor(color=ta.crossover(close, out1) ? color.new(color.lime, 90) : na) bgcolor(color=ta.crossunder(close, out1) ? color.new(color.red, 90) : na) //Norm MacD sma = 12 lma = 21 tsp = 10 np = 50 sh = ta.ema(close,sma) lon= ta.ema(close,lma) ratio = math.min(sh,lon)/math.max(sh,lon) Mac = ratio - 1 if(sh>lon) Mac := 2-ratio - 1 else Mac := ratio - 1 MacNorm = ((Mac-ta.lowest(Mac, np)) /(ta.highest(Mac, np)-ta.lowest(Mac, np)+.000001)*2)- 1 MacNorm2 = MacNorm if(np<2) MacNorm2 := Mac else MacNorm2 := MacNorm Trigger = ta.wma(MacNorm2, tsp) trigger_above = Trigger >= MacNorm trigger_under = Trigger < MacNorm plotshape(ta.crossover(Trigger, MacNorm2), style=shape.triangledown, color=color.red) plotshape(ta.crossunder(Trigger, MacNorm2), style=shape.triangledown, color=color.lime) //RSI / SMA RSI swr=input(true,title="RSI") src = close len = 14 srs = 50 up = ta.rma(math.max(ta.change(src), 0), len) down = ta.rma(-math.min(ta.change(src), 0), len) rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down)) mr = ta.sma(rsi,srs) rsi_above = rsi >= mr rsi_under = rsi < mr //All buySignal = rsi_above and trigger_under and dataO shortSignal = rsi_under and trigger_above and dataU bgcolor(color=buySignal ? color.new(color.lime,97) : na) bgcolor(color=shortSignal ? color.new(color.red, 97) : na) sellSignal = ta.cross(close, out1) or ta.cross(Trigger, MacNorm2) or ta.cross(rsi, mr) if (buySignal) strategy.entry("LONG", strategy.long, 1) if (shortSignal) strategy.entry("SHORT", strategy.short, 1) // Submit exit orders strategy.close("LONG", when=sellSignal) strategy.close("SHORT", when=sellSignal)
Buy/Sell on the levels
https://www.tradingview.com/script/DPx9VRI9-Buy-Sell-on-the-levels/
Arivadis
https://www.tradingview.com/u/Arivadis/
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/ // © svatvlad1993 //@version=5 strategy("test for more freq","BUY/SELL test for more freq",pyramiding=100 , overlay=true, currency=currency.USDT, commission_type=strategy.commission.percent, commission_value=0.05,initial_capital=5000, margin_long=10, margin_short=10, max_lines_count = 500, max_labels_count = 500, max_bars_back = 5000)//, default_qty_type=strategy.percent_of_equity, default_qty_value=4) // tail-resistance for buy var last_min = low[0] var last_max = high[0] var permission_for_buy = 0 lowest0 = ta.lowest(low,100) highest0 = ta.highest(high,100) if close > last_max if lowest0 != 0 last_min := lowest0 else last_min := close - (close * 0.02) last_max := high permission_for_buy := 1 if close < last_min last_min := low if highest0 != 0 last_max := highest0 else last_max := close + (close * 0.02) permission_for_buy := 0 plot_diaps1 = plot(permission_for_buy != 0? na : last_max, title='Max',color=color.new(#ff0000, 95),style=plot.style_cross,trackprice=true ) plot_diaps2 = plot(permission_for_buy != 0? na : last_min, title='Min',color=color.new(#ff0000, 95),style=plot.style_cross,trackprice=true ) plot_diaps3 = plot(permission_for_buy != 1? na : last_max, title='max',color=color.new(color.green, 95),style=plot.style_cross,trackprice=true ) plot_diaps4 = plot(permission_for_buy != 1? na : last_min, title='min',color=color.new(color.green, 95),style=plot.style_cross,trackprice=true ) fill(plot_diaps1, plot_diaps2,color=color.new(#ff0000, 95)) fill(plot_diaps3, plot_diaps4,color=color.new(color.green, 95)) //Supertrend atrPeriod = input(10, "ATR Length") factor = input.float(2.5, "Factor", step = 0.01) [supertrend, direction] = ta.supertrend(factor, atrPeriod) bodyMiddle = plot((open + close) / 2, display=display.none) upTrend = plot(direction < 0 ? supertrend : na, "Up Trend", color = color.teal, style=plot.style_linebr) downTrend = plot(direction < 0? na : supertrend, "Down Trend", color = color.maroon, style=plot.style_linebr) fill(bodyMiddle, upTrend, color.new(color.teal, 75), fillgaps=false) fill(bodyMiddle, downTrend, color.new(color.maroon, 75), fillgaps=false) // levels sell/buy var float[] price_to_sellBue = array.from(1.01, 1.02, 1.03, 1.04, 1.05, 1.06, 1.071, 1.082, 1.093, 1.104, 1.115, 1.126, 1.137, 1.148, 1.159, 1.171, 1.183, 1.195, 1.207, 1.219, 1.231, 1.243, 1.255, 1.268, 1.281, 1.294, 1.307, 1.32, 1.333, 1.346, 1.359, 1.373, 1.387, 1.401, 1.415, 1.429, 1.443, 1.457, 1.472, 1.487, 1.502, 1.517, 1.532, 1.547, 1.562, 1.578, 1.594, 1.61, 1.626, 1.642, 1.658, 1.675, 1.692, 1.709, 1.726, 1.743, 1.76, 1.778, 1.796, 1.814, 1.832, 1.85, 1.869, 1.888, 1.907, 1.926, 1.945, 1.964, 1.984, 2.004, 2.024, 2.044, 2.064, 2.085, 2.106, 2.127, 2.148, 2.169, 2.191, 2.213, 2.235, 2.257, 2.28, 2.303, 2.326, 2.349, 2.372, 2.396, 2.42, 2.444, 2.468, 2.493, 2.518, 2.543, 2.568, 2.594, 2.62, 2.646, 2.672, 2.699, 2.726, 2.753, 2.781, 2.809, 2.837, 2.865, 2.894, 2.923, 2.952, 2.982, 3.012, 3.042, 3.072, 3.103, 3.134, 3.165, 3.197, 3.229, 3.261, 3.294, 3.327, 3.36, 3.394, 3.428, 3.462, 3.497, 3.532, 3.567, 3.603, 3.639, 3.675, 3.712, 3.749, 3.786, 3.824, 3.862, 3.901, 3.94, 3.979, 4.019) var float[] count_of_orders = array.from(2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0) //loops for sale/buy for i = 0 to 139 if array.get(price_to_sellBue, i) >= open[0] and array.get(price_to_sellBue, i) <= close[0] and direction[0] < 0 and permission_for_buy != 0 if array.get(count_of_orders, i) > 0 strategy.order(str.tostring(i), strategy.long, 15) g = array.get(count_of_orders, i) array.set(count_of_orders, i, g - 2) break var SELL_amount = 0 var strategy_short = 0 for i = 0 to 139 if array.get(price_to_sellBue, i) <= open[0] and array.get(price_to_sellBue, i) >= close[0] for j = 0 to i-1 if array.get(count_of_orders, j) != 2 strategy_short := strategy_short + 1 array.set(count_of_orders, j, 2) SELL_amount := SELL_amount + 15 strategy.order(str.tostring(strategy_short),strategy.short, SELL_amount) SELL_amount := 0 break // добавить SMA и продавать при низходящем тренде plot(strategy.equity)
Directional Movement Index
https://www.tradingview.com/script/snP0MRjI-Directional-Movement-Index/
wojak_bogdanoff
https://www.tradingview.com/u/wojak_bogdanoff/
375
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/ // ©wojak_bogdanoff // @version=5 // Directional Movement Index (DMI) strategy(title="Directional Movement Index", shorttitle="DMI︎", overlay=true, pyramiding=1, calc_on_every_tick=false, calc_on_order_fills=false, initial_capital=100.0, default_qty_type=strategy.percent_of_equity, default_qty_value=100.0, commission_type=strategy.commission.percent, commission_value=0.1, slippage=1) trade_type = input.string(defval = "Long/Short", title="Position Type", options=["Long/Short", "Long"], group='Trading Settings') strategy_type = 'DMI' start_date = input.time(title='Testing Start Date', defval=timestamp("2017-01-01T00:00:00"), group='Trading Settings') finish_date = input.time(title='Testing End Date', defval=timestamp("2025-01-01T00:00:00"), group='Trading Settings') _testperiod = time >= start_date and time <= finish_date _check = _testperiod // --- (Start) Ichimoku kinko Hyo ------------------------------------------- // Credits : LonesomeTheBlue middleDonchian(Length) => lower = ta.lowest(Length), upper = ta.highest(Length) math.avg(upper, lower) conversionPeriods = input.int(defval=9, minval=1, group='Ichimoku Kinko Hyo - Settings') basePeriods = input.int(defval=26, minval=1, group='Ichimoku Kinko Hyo - Settings') laggingSpan2Periods = input.int(defval=52, minval=1, group='Ichimoku Kinko Hyo - Settings') displacement = input.int(defval=26, minval=1, group='Ichimoku Kinko Hyo - Settings') Tenkan = middleDonchian(conversionPeriods) Kijun = middleDonchian(basePeriods) xChikou = close SenkouA = middleDonchian(laggingSpan2Periods) SenkouB = (Tenkan[basePeriods-displacement] + Kijun[basePeriods-displacement]) / 2 plot(Tenkan, color=color.red, title="Tenkan", linewidth=2, display=display.all) plot(Kijun, color=color.blue, title="Kijun", linewidth=2, display=display.all) plot(xChikou, color= color.lime , title="Chikou", offset = -displacement, display=display.all) A = plot(SenkouA, color=color.new(color.red,70), title="SenkouA", offset=displacement, display=display.none) B = plot(SenkouB, color=color.new(color.green,70), title="SenkouB", offset=displacement, display=display.none) fill(A, B, color= (SenkouA > SenkouB) ? color.new(color.red,90) : color.new(color.green,90), title='Kumo Cloud') // --- (End) Ichimoku kinko Hyo --------------------------------------------- // // --- (Start) Ichimoku conditions ------------------------------------------ // Credits : ThermalWinds red_kumo_cloud = SenkouA[displacement] > SenkouB[displacement] // Verified green_kumo_cloud = SenkouA[displacement] < SenkouB[displacement] // Verified red_kumo_cloud_future = SenkouA > SenkouB // Verified green_kumo_cloud_future = SenkouA < SenkouB // Verified close_crosses_kijun = close > Kijun and close[1] < Kijun[1] // Verified tenkan_over_kijun = Tenkan > Kijun // Verified tenkan_below_kijun_tenkan_up_kijun_flat = (Tenkan < Kijun) and (ta.change(Tenkan, 1) > 0) and (Kijun[0] == Kijun[1]) // Verified [close_middle_bb, close_upper_bb, close_lower_bb] = ta.bb(series=close, length=20, mult=1) chikou_open_space = (xChikou < close_lower_bb[displacement] and xChikou < SenkouA[2*displacement] and xChikou < SenkouB[2*displacement] and xChikou < 2*low[displacement]) or (xChikou > close_upper_bb[displacement] and xChikou > SenkouA[2*displacement] and xChikou > SenkouB[2*displacement] and xChikou > 2*high[displacement]) // Verified future_senkouB_up_flat = green_kumo_cloud_future and (ta.change(SenkouB, 1) > 0 or SenkouB[0] == SenkouB[1]) // Verified tenkan_in_cloud = (Tenkan < SenkouA[displacement] and Tenkan > SenkouB[displacement]) or (Tenkan > SenkouA[displacement] and Tenkan < SenkouB[displacement]) // Verified kijun_in_cloud = (Kijun < SenkouA[displacement] and Kijun > SenkouB[displacement]) or (Kijun > SenkouA[displacement] and Kijun < SenkouB[displacement]) // Verified price_in_green_cloud = green_kumo_cloud and ((open < SenkouB[displacement] and open > SenkouA[displacement]) or (high < SenkouB[displacement] and high > SenkouA[displacement]) or (low < SenkouB[displacement] and low > SenkouA[displacement]) or (close < SenkouB[displacement] and close > SenkouA[displacement])) // Verified price_in_red_cloud = red_kumo_cloud and ((open < SenkouA[displacement] and open > SenkouB[displacement]) or (high < SenkouA[displacement] and high > SenkouB[displacement]) or (low < SenkouA[displacement] and low > SenkouB[displacement]) or (close < SenkouA[displacement] and close > SenkouB[displacement])) // Verified price_in_cloud = price_in_green_cloud or price_in_red_cloud // Verified chikou_in_cloud = (green_kumo_cloud[displacement] and (xChikou < SenkouB[2*displacement] and xChikou > SenkouA[2*displacement])) or (red_kumo_cloud[displacement] and (xChikou < SenkouA[2*displacement] and xChikou > SenkouB[2*displacement])) // Verified price_tenkan_kijun_chikou_not_in_cloud = (not tenkan_in_cloud) and (not kijun_in_cloud) and (not price_in_cloud) and (not chikou_in_cloud) // Verified cloud_thickness = math.abs(SenkouA[displacement] - SenkouB[displacement]) percent_thick_cloud = green_kumo_cloud ? (cloud_thickness * 100) / SenkouA[displacement] : (cloud_thickness * 100) / SenkouB[displacement] thickness_threshold = 14, thickest_cloud = ta.highest(percent_thick_cloud, 10000) thick_cloud = percent_thick_cloud >= (thickest_cloud * (thickness_threshold/100)) // Verified price_tenkan_kijun_chikou_in_thick_cloud = (not price_tenkan_kijun_chikou_not_in_cloud) and thick_cloud // Verified proximity_mult = 0.001 // 0.1 % tenkan_middle_bb = Tenkan + (Tenkan*0), tenkan_upper_bb = Tenkan + (Tenkan*proximity_mult), tenkan_lower_bb = Tenkan + (Tenkan*-proximity_mult) kijun_middle_bb = Kijun + (Kijun*0), kijun_upper_bb = Kijun + (Kijun*proximity_mult), kijun_lower_bb = Kijun + (Kijun*-proximity_mult) price_near_tenkan = (open < tenkan_upper_bb and open > tenkan_lower_bb) or (high < tenkan_upper_bb and high > tenkan_lower_bb) or (low < tenkan_upper_bb and low > tenkan_lower_bb) or (close < tenkan_upper_bb and close > tenkan_lower_bb) price_near_kijun = (open < kijun_upper_bb and open > kijun_lower_bb) or (high < kijun_upper_bb and high > kijun_lower_bb) or (low < kijun_upper_bb and low > kijun_lower_bb) or (close < kijun_upper_bb and close > kijun_lower_bb) price_near_tenkan_kijun = price_near_tenkan or price_near_kijun cloud_thickness_future = math.abs(SenkouA[0] - SenkouB[0]) percent_thick_cloud_future = green_kumo_cloud_future ? (cloud_thickness_future * 100) / SenkouA[0] : (red_kumo_cloud_future ? (cloud_thickness_future * 100) / SenkouB[0] : na) thickness_threshold_future = 0.20 thin_cloud = percent_thick_cloud_future <= thickness_threshold_future red_2_green_cloud = (SenkouA[displacement+1] > SenkouB[displacement+1]) and (SenkouA[displacement+0] < SenkouB[displacement+0]) green_2_red_cloud = (SenkouA[displacement+1] < SenkouB[displacement+1]) and (SenkouA[displacement+0] > SenkouB[displacement+0]) close_above_cloud = close > SenkouA[displacement] and close > SenkouB[displacement] close_below_kijun = close < Kijun tenkan_crossover_kijun = ta.crossover(Tenkan, Kijun) tenkan_over_cloud = Tenkan > SenkouA[displacement] and Tenkan > SenkouB[displacement] tenkan_over_red_cloud = red_kumo_cloud and tenkan_over_cloud kijun_crosses_red_cloud = red_kumo_cloud and ta.crossover(Kijun, SenkouA[displacement]) // --- (End) Ichimoku conditions -------------------------------------------- // // --- (Start) Directional Movement Index (DMI) ----------------------------- // dmi_adxSmoothing = input.int(14, title="ADX Smoothing", minval=1, maxval=50, group='ADX / DMI - Setting') dmi_len = input.int(7, minval=1, title="DI Length", group='ADX / DMI - Setting') dmi_up = ta.change(high) dmi_down = -ta.change(low) dmi_plusDM = na(dmi_up) ? na : (dmi_up > dmi_down and dmi_up > 0 ? dmi_up : 0) dmi_minusDM = na(dmi_down) ? na : (dmi_down > dmi_up and dmi_down > 0 ? dmi_down : 0) dmi_rma = ta.rma(ta.tr, dmi_len) dmi_plus = fixnan(100 * ta.rma(dmi_plusDM, dmi_len) / dmi_rma) dmi_minus = fixnan(100 * ta.rma(dmi_minusDM, dmi_len) / dmi_rma) dmi_sum = dmi_plus + dmi_minus dmi_adx = 100 * ta.rma(math.abs(dmi_plus - dmi_minus) / (dmi_sum == 0 ? 1 : dmi_sum), dmi_adxSmoothing) plot(dmi_adx, color=#F50057, title="ADX", display=display.none) plot(dmi_plus, color=#2962FF, title="+DI", display=display.none) plot(dmi_minus, color=#FF6D00, title="-DI", display=display.none) dmi_consld_limit=input.int(defval=25, title='Consolidation ADX', group='ADX / DMI - Setting') dmi_consld=dmi_adx<=dmi_consld_limit dmi_strong_up=dmi_adx>dmi_consld_limit and dmi_plus>dmi_minus dmi_strong_down=dmi_adx>dmi_consld_limit and dmi_plus<dmi_minus barcolor(dmi_consld ? color.new(color.black,0) : na, title='Consolidation region', display=display.none) barcolor(dmi_strong_up ? color.new(color.green,0) : na, title='Uptrend Region') barcolor(dmi_strong_down ? color.new(color.red,0) : na, title='Downtrend Region') dmi_long_e = (not dmi_strong_up[1] and dmi_strong_up[0]) dmi_long_x = (dmi_strong_up[1] and not dmi_strong_up[0]) or (thick_cloud and green_kumo_cloud) dmi_short_e = (not dmi_strong_down[1]) and dmi_strong_down[0] dmi_short_x = (dmi_strong_down[1] and not dmi_strong_down[0]) or green_kumo_cloud // --- (End) Directional Movement Index (DMI) ------------------------------- // // --- Trade Conditions ----------------------------------------------------- // var is_long_open=false, var is_short_open=false long_e = strategy_type == "DMI" ? dmi_long_e : na long_x = strategy_type == "DMI" ? dmi_long_x : na short_e = strategy_type == "DMI" ? dmi_short_e : na short_x = strategy_type == "DMI" ? dmi_short_x : na long_e_color = input.color(defval=color.new(color.teal,0), title='Long Entry', group='Signals Style - Setting', inline='il1') long_x_color = input.color(defval=color.new(color.purple,0), title='Long Exit', group='Signals Style - Setting', inline='il1') is_trade_bar = (long_e and not is_long_open) or (long_x and is_long_open) barcolor(color=is_trade_bar ? na : (close>open ? color.new(color.green,90) : color.new(color.red,90)), title='Trade Bars') barcolor(color=(trade_type == 'Long' or trade_type == 'Long/Short') ? long_e and not is_long_open ? long_e_color : na : na, title="Long - Entry Bar", editable=false) barcolor(color=(trade_type == 'Long' or trade_type == 'Long/Short') ? long_x and is_long_open ? long_x_color : na : na, title="Long - Exit Bar", editable=false) plotshape((trade_type == 'Long' or trade_type == 'Long/Short') ? long_e and not is_long_open : na, text="B", textcolor=color.white, style=shape.labelup, color=long_e_color, size=size.tiny, location=location.belowbar, title="Long - Entry Labels") plotshape((trade_type == 'Long' or trade_type == 'Long/Short') ? long_x and is_long_open : na, text="S", textcolor=color.white, style=shape.labeldown, color=long_x_color, size=size.tiny, location=location.abovebar, title="Long - Exit Labels") plotshape((trade_type == 'Short' or trade_type == 'Long/Short') ? short_e and not is_short_open : na, text="E", textcolor=color.black, style=shape.labeldown, color=color.new(color.yellow,30), size=size.tiny, location=location.abovebar, title="Short - Entry Labels", editable=false) plotshape((trade_type == 'Short' or trade_type == 'Long/Short') ? short_x and is_short_open : na, text="X", textcolor=color.black, style=shape.labeldown, color=color.new(color.orange,30), size=size.tiny, location=location.abovebar, title="Short - Exit Labels", editable=false) if long_e and not is_long_open is_long_open:=true if long_x and is_long_open is_long_open:=false if short_e and not is_short_open is_short_open:=true if short_x and is_short_open is_short_open:=false // --- Trade Executions ----------------------------------------------------- // if trade_type == "Long/Short" and _check strategy.entry("Long", strategy.long, comment=" ", when=long_e and _testperiod) strategy.close("Long", comment=" ", when=long_x and _testperiod) strategy.entry("Short", strategy.short, comment=" ", when=short_e and _testperiod) strategy.close("Short", comment=" ", when=short_x and _testperiod) if trade_type == "Long" and _check strategy.entry("Long", strategy.long, comment=" ", when=long_e and _testperiod) strategy.close("Long", comment=" ", when=long_x and _testperiod)
Bjorgum Double Tap
https://www.tradingview.com/script/rLkjr2sQ-Bjorgum-Double-Tap/
Bjorgum
https://www.tradingview.com/u/Bjorgum/
4,553
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/ // © Bjorgum // ________________________________________________________________ // |\______________________________________________________________/| // || ________________ || // || ___ __ )_____(_)___________________ ____ ________ ___ || // || __ __ |____ /_ __ \_ ___/_ __ `/ / / /_ __ `__ \ || // || _ /_/ /____ / / /_/ / / _ /_/ // /_/ /_ / / / / / || // || /_____/ ___ / \____//_/ _\__, / \__,_/ /_/ /_/ /_/ || // || /___/ /____/ || // ||______________________________________________________________|| // |/______________________________________________________________\| //@version=5 // @strategy_alert_message {{strategy.order.alert_message}} strategy( title = "Bjorgum Double Tap", shorttitle = "Bj Double Tap", overlay = true, max_lines_count = 500, max_labels_count = 500, precision = 3, default_qty_type = strategy.cash, commission_value = 0.04, commission_type = strategy.commission.percent, slippage = 1, currency = currency.USD, default_qty_value = 1000, initial_capital = 1000) // ══════════════════════════════════ // // —————> Immutable Constants <—————— // // ══════════════════════════════════ // string useStratTip = "Enables or disables the strategy tester allowing a change between either an indicator or a strategy." string dLongTip = "Detect long setups." string dShortTip = "Detect short setups." string FLIPTip = "Allow entry in the opposite bias while already in a position." string startTip = "Start date & time to begin backtest period. Useful for beginning new bot. eg. Set time to now to make broker emulator in a flat position with the proper starting captial before setting alerts" string endTip = "End date & time to stop searching for setups for back testing." string tolTip = "The difference in height allowable for the signifcant points of the pattern expressed as a percent of the pattern height. Example: The points can vary in height by 15% of the pattern height from one another." string lenTip = "The length used to calcuate significant points to form pivots for pattern detection. Example: The highest or lowest point in 50 bars." string fibTip = "The fib target extension projected from the neckline of the pattern in the direction of the pattern bias expressed as a percent. Example: 100% is a 1:1 measurment of the height from the pattern neckline." string stopPerTip = "The fib extension of the pattern height measured from the point of invalidation. Example: 0% would be the high point of a double top. 50% would be halfway between the top and the neckline." string offsetTip = "The number of bars lines are extended into the future during an ongoing pattern." string atrStopTip = "Enables an ATR trailing stop once the target extension is breached. NOTE: This disables a take profit order in the strategy format." string atrLenTip = "The number of bars used in the ATR calculation." string atrMultTip = "The multiplier of the ATR value to subtract from the swing low or swing high point. Example: 1 is 100% of the ATR, 2 is 2x the ATR value." string lookbackTip = "The number of bars to look back to find a swing high or swing low to be used in the trailing stop calculation. Example: 1 ATR subtracted from the lowest point in 5 bars. 1 would use the lowest point within the last bar." string tableTip = "Show the data table for trade limit levels during an active trade. (table will only show when a pattern is present on the chart, or in bar replay)." string labelTip = "Updates the double top/bottom label with 'Success' or 'Failure' and updates color based on the outcome of the pattern." string thirdTip = "Where would you like to send your alerts?" string pPhraseTip = "A custom passphrase to authenticate your json message with a touch more security." string aTronKeyTip = "The name of your Alertatron API keys. (Add the ticker in brackets). Example: MyKeys(XBTUSD)." string tickerTip = "The ticker to be traded when using Trading Connector" string LongTip = "3Commas start long deal bot keys." string LongEndTip = "3Commas end long deal bot keys." string ShortTip = "3Commas start short deal bot keys." string ShortEndTip = "3Commas end short deal bot keys." string dt = "Double Top" string db = "Double Bottom" string suc = " - Success" string fail = " - Failure" string winStr = "Target reached! 💰" string loseStr = "Stopped out... 🤷‍♂" string tabPerc = "{0, number, #.##}\n({1, number, #.##}%)" string tcStop = "slmod slprice={0} tradeid={1}" string dExit = "'{'\"content\": \"```Bjorgum {0}\\n\\n\\t'{{ticker}}' '{{interval}}'\\n\\n\\t{1}```\"'}'" string S1 = "tiny" , string P1 = "top" string S2 = "small" , string P2 = "middle" string S3 = "normal" , string P3 = "bottom" string S4 = "large" , string P4 = "left" string S5 = "huge" , string P5 = "center" string S6 = "auto" , string P6 = "right" var string tnB = "" , string A1 = "Custom Json" string altStr = "" , string A2 = "Trading Connector" string tUp = "" , string A3 = "Alertatron" string dCordWin = "" , string A4 = "3Commas" string dCordLose = "" , string A5 = "Discord" float pos = strategy.position_size int sync = bar_index bool confirm = barstate.isconfirmed var int dir = na var float lmt = na var float stp = na string altExit = na bool FLAT = pos == 0 bool LONG = pos > 0 bool SHORT = pos < 0 var int tradeId = 0 color col1 = color.new(#b2b5be, 15) color col2 = color.new(#b2b5be, 87) color col3 = color.new(#ffffff, 0) color col4 = color.new(#17ff00, 15) color col5 = color.new(#ff0000, 15) color col6 = color.new(#ff5252, 0) var matrix<float> logs = matrix.new<float> (5, 3) var line [] zLines = array.new_line (5) var line [] tLines = array.new_line (5) var line [] bLines = array.new_line (5) var label[] bullLb = array.new_label () var label[] bearLb = array.new_label () int timeStart = timestamp("01 Jan 2000") int timeEnd = timestamp("01 Jan 2099") // ══════════════════════════════════ // // —————————> User Input <——————————— // // ══════════════════════════════════ // string GRP1 = "════  Detection and Trade Parameters  ════" bool useStrat = input.bool (true , "Use Strategy" , group= GRP1, tooltip= useStratTip) bool dLong = input.bool (true , "Detect Bottoms" , group= GRP1, tooltip= dLongTip ) bool dShort = input.bool (true , "Detect Tops" , group= GRP1, tooltip= dShortTip ) bool FLIP = input.bool (true , "Flip Trades" , group= GRP1, tooltip= FLIPTip ) float tol = input.float (15 , "Pivot Tolerance" , group= GRP1, tooltip= tolTip , minval= 1) int len = input.int (50 , "Pivot Length" , group= GRP1, tooltip= lenTip , minval= 1) float fib = input.float (100 , "Target Fib" , group= GRP1, tooltip= fibTip , minval= 0) int stopPer = input.int (0 , "Stop Loss Fib" , group= GRP1, tooltip= stopPerTip ) int offset = input.int (30 , "Line Offset" , group= GRP1, tooltip= offsetTip , minval= 0) string GRP2 = "═══════════ Time Filter ═══════════" int startTime = input.time(timeStart , "Start Filter" , group= GRP2, tooltip= startTip) int endTime = input.time(timeEnd , "End Filter" , group= GRP2, tooltip= endTip ) string GRP3 = "══════════ Trailing Stop ══════════" bool atrStop = input.bool (false , "Use Trail Stop" , group= GRP3, tooltip= atrStopTip ) int atrLength = input.int (14 , "ATR Length" , group= GRP3, tooltip= atrLenTip , minval= 1) float atrMult = input.float (1 , "ATR Multiplier" , group= GRP3, tooltip= atrMultTip , minval= 0) int lookback = input.int (5 , "Swing Lookback" , group= GRP3, tooltip= lookbackTip, minval= 1) string GRP5 = "════════════ Colors ════════════" color col = input.color (col1 , "Lines        " , group= GRP5, inline= "41") color zCol = input.color (col3 , "Patterns       " , group= GRP5, inline= "42") int hWidth = input.int (1 , "" , group= GRP5, inline= "41", minval= 1) int zWidth = input.int (1 , "" , group= GRP5, inline= "42", minval= 1) color colf = input.color (col2 , "Stop Fill" , group= GRP5) color tCol = input.color (col4 , "Target Color" , group= GRP5) color sCol = input.color (col5 , "Stop Color" , group= GRP5) color trailCol = input.color (col6 , "Trail Color" , group= GRP5) string GRP6 = "═════════  Table and Label  ═════════" bool showTable = input.bool (true , "Show Table" , group= GRP6, tooltip= tableTip) bool setLab = input.bool (true , "Update Label" , group= GRP6, tooltip= labelTip) string labSize = input.string("small" , "Label Text Size" , group= GRP6, options= [S1, S2, S3, S4, S5, S6]) string textSize = input.string("normal" , "Table Text Size" , group= GRP6, options= [S1, S2, S3, S4, S5, S6]) string tableYpos = input.string("bottom" , "Table Position" , group= GRP6, options= [P1, P2, P3]) string tableXpos = input.string("right" , "" , group= GRP6, options= [P4, P5, P6]) string GRP7 = "══════════ Alert Strings ══════════" string thirdParty = input.string(A1 , "3rd Party" , group= GRP7, tooltip= thirdTip, options= [A1, A2, A3, A4, A5]) string pPhrase = input.string("1234" , "Json Passphrase" , group= GRP7, tooltip= pPhraseTip ) string aTronKey = input.string("myKeys" , "Alertatron Key" , group= GRP7, tooltip= aTronKeyTip) string tcTicker = input.string("" , "TC Ticker" , group= GRP7, tooltip= tickerTip ) string c3Long = input.string("" , "3Comma Long" , group= GRP7, tooltip= LongTip ) string c3LongEnd = input.string("" , "3Comma Long End" , group= GRP7, tooltip= LongEndTip ) string c3Short = input.string("" , "3Comma Short" , group= GRP7, tooltip= ShortTip ) string c3ShortEnd = input.string("" , "3Comma Short End", group= GRP7, tooltip= ShortEndTip) // ══════════════════════════════════ // // ————> Variable Calculations <————— // // ══════════════════════════════════ // bool dif = stopPer != 0 int set = sync + offset float atr = ta.atr (14) float sLow = ta.lowest (lookback) - (atr * atrMult) float sHigh = ta.highest (lookback) + (atr * atrMult) float pivHigh = ta.highest (len) float pivLows = ta.lowest (len) float hbar = ta.highestbars (len) float lbar = ta.lowestbars (len) // ══════════════════════════════════ // // ———> Functional Declarations <———— // // ══════════════════════════════════ // High(m) => float result = (m == 1 ? high : low) Low(m) => float result = (m == 1 ? low : high) perD(_p) => float result = (_p - close) / close * 100 _coords(_x, _i) => x = matrix.get (_x, _i, 0) y = matrix.get (_x, _i, 1) [int(x), y] _arrayLoad(_x, _max, _val) => array.unshift (_x, _val) if array.size (_x) > _max array.pop (_x) _matrixPush(_mx, _max, _row) => matrix.add_row(_mx, matrix.rows (_mx), _row) if matrix.rows (_mx) > _max matrix.remove_row (_mx, 0) _mxLog(_cond, _x, _y) => float[] _row = array.from (sync, _y, 0) if _cond _matrixPush (_x, 5, _row) _mxUpdate(_cond, _dir, _x, y) => int m = _dir ? 1 : -1 int _end = matrix.rows (_x) -1 if _cond and y * m > matrix.get (_x, _end, 1) * m matrix.set (_x, _end, 0, sync) matrix.set (_x, _end, 1, y) _extend(_x, _len) => for l in _x line.set_x2(l, _len) _hLine(_l, x2, y2, y3, y4, y5, _t) => line l1 = line.new (x2 , y2, set, y2, color= col, width= hWidth) line l2 = line.new (x2 , y4, set, y4, color= col, width= hWidth) array.set (_l , 3, l1) array.set (_l , 2, l2) array.set (_l , 1, line.new (x2 , y3, set, y3, color= col, width= hWidth)) array.set (_l , 0, line.new (sync-1, _t, set, _t, color= col, width= hWidth)) linefill.new (l1 , l2, colf) if stopPer != 0 array.set (_l, 4, line.new (sync-1, y5, set, y5, color= col, width= hWidth)) _zLine(x1, y1, x2, y2, x3, y3, x4, y4) => array.set (zLines, 3, line.new (x1, y1, x2 , y2 , color= zCol, width= zWidth)) array.set (zLines, 2, line.new (x2, y2, x3 , y3 , color= zCol, width= zWidth)) array.set (zLines, 1, line.new (x3, y3, x4 , y4 , color= zCol, width= zWidth)) array.set (zLines, 0, line.new (x4, y4, sync, close, color= zCol, width= zWidth)) _label(x, y, m) => m > 0 ? _arrayLoad (bearLb, 1, label.new (x, y, dt, color= color(na), style= label.style_label_down, textcolor= col, size= labSize)) : _arrayLoad (bullLb, 1, label.new (x, y, db, color= color(na), style= label.style_label_up, textcolor= col, size= labSize)) _labelUpdate(_x, _y, m) => if (_x or _y) and setLab label lab = array.get (m > 0 ? bearLb : bullLb, 0) string oStr = (m > 0 ? dt : db) string nStr = oStr + (_x ? suc : fail) label.set_text (lab, nStr) label.set_textcolor (lab, _x ? tCol : sCol) _atrTrail(_cond, _lt, _s, m) => var float _stop = na var bool _flag = na var bool _trail = na _flag := _cond _stop := _s _trail := _flag ? false : _trail if atrStop and useStrat if _lt _flag := false _trail := true _stop := m == -1 ? _lt ? sLow : math.max(_stop, sLow) : _stop _stop := m == 1 ? _lt ? sHigh : math.min(_stop, sHigh) : _stop if High(m) * m > _stop * m _flag := true _trail := false [_flag, _stop, _trail] _inTrade(_cond, _x, _e, m) => var bool _flag = na var float _stop = na var float _limit = na line l1 = array.get (_x, 0) float lp = line.get_price(l1, sync) line l2 = array.get (_x, dif ? 4 : 2) float ls = line.get_price(l2, sync) bool win = Low (m) * m <= lp * m and not _e bool lose = High(m) * m >= ls * m and not _e _flag := _cond _stop := _e ? ls : _stop _limit := _e ? lp : _limit if win or lose _flag := true _extend (_x , sync) _labelUpdate (win , lose, m) line.set_color (win ? l1 : l2, win ? tCol : sCol) array.fill (_x , na) array.fill (zLines, na) [_f, _s, _t] = _atrTrail (_flag , win , _stop, m) _flag := atrStop ? _f : _flag _stop := _t and _s * m < _stop * m and confirm ? _s : _stop [_flag, _stop, _t, _limit] _double(_cond, _l, _x, m) => var bool _flag = na int _rows = matrix.rows (_x) _flag := _cond if _flag [x1, y1] = _coords (_x , _rows - 5) [x2, y2] = _coords (_x , _rows - 4) [x3, y3] = _coords (_x , _rows - 3) [x4, y4] = _coords (_x , _rows - 2) bool traded = matrix.get (_x , _rows - 2, 2) float height = math.avg (y2 , y4) - y3 float _high = y2 + height * (tol/ 100) float _low = y2 - height * (tol/ 100) float _t = y3 - height * (fib/ 100) float y5 = y2 * m < y4 * m ? y2 : y4 float y6 = y2 * m > y4 * m ? y2 : y4 float y7 = y6 - height *(stopPer/100) bool result = y1*m < y3*m and y4*m <= _high*m and y4*m >= _low*m and close*m < y3*m and not (close[1]*m < y3*m) and not traded if result and _flag and (m > 0 ? dShort : dLong) _hLine (_l, x2, y5, y3, y6, y7, _t) _zLine (x1, y1, x2, y2, x3, y3, x4, y4) _label (x4, y6, m) matrix.set (_x, _rows - 2, 2, 1) _flag := false _flag _scan(_l, _x, m) => var bool _cond = true _cond := _double (_cond, _l, _x, m) bool enter = _cond[1] and not _cond [f,s,t,l] = _inTrade (_cond, _l, enter, m) _cond := f _extend(_l, set) [f,s,t,l] _populate(_n, _x, _i, _col) => for [i, _a] in _x if not na(_a) table.cell(table_id = _n, column = _i , row = i, bgcolor = na , text = _a, text_color = _col, text_size = textSize) // ══════════════════════════════════ // // ————————> Logical Order <————————— // // ══════════════════════════════════ // dir := not hbar ? 1 : not lbar ? 0 : dir bool dirUp = dir != dir[1] and dir bool dirDn = dir != dir[1] and not dir bool setUp = not hbar and dir bool setDn = not lbar and not dir _mxLog (dirUp or dirDn, logs, dirUp ? pivHigh : pivLows) _mxUpdate (setUp or setDn, dir, logs, setUp ? pivHigh : pivLows) [bear,ss,ts,sl] = _scan(tLines, logs, 1) [bull,ls,tl,ll] = _scan(bLines, logs, -1) bool st = SHORT ? ts : false bool lt = LONG ? tl : false bool sell = bear[1] and not bear bool buy = bull[1] and not bull color ssCol = st or st[1] ? trailCol : na color lsCol = lt or lt[1] ? trailCol : na bool longEntry = buy and (FLAT or (SHORT and FLIP)) bool shortEntry = sell and (FLAT or (LONG and FLIP)) bool dateFilter = time >= startTime and time <= endTime tradeId += longEntry or shortEntry ? 1 : 0 lmt := atrStop ? na : shortEntry ? sl : longEntry ? ll : lmt stp := shortEntry or SHORT and atrStop ? ss : longEntry or LONG and atrStop ? ls : stp plot (atrStop ? ss : na, "Short Stop", ssCol, style= plot.style_linebr) plot (atrStop ? ls : na, "Long Stop", lsCol, style= plot.style_linebr) bgcolor (not dateFilter ? color.new(color.red,80) : na, title= "Filter Color") // ══════════════════════════════════ // // —————————> Data Display <————————— // // ══════════════════════════════════ // if showTable string tls = bull ? na : str.format(tabPerc, ls, perD(ls)) string tss = bear ? na : str.format(tabPerc, ss, perD(ss)) string tll = bull ? na : str.format(tabPerc, ll, perD(ll)) string tsl = bear ? na : str.format(tabPerc, sl, perD(sl)) string[] titles = array.from(na, bull ? na : "Bullish", bear ? na : "Bearish") string[] stops = array.from("Stop" , tls, tss) string[] limtis = array.from("Target", tll, tsl) table bjTab = table.new(tableYpos + "_" + tableXpos, 3, 3, border_color= color.new(color.gray, 60), border_width= 1) if not bear or not bull _populate(bjTab, titles, 0, color.white) _populate(bjTab, stops, 1, color.red) if not (na(ll) or lt) or not (na(sl) or st) _populate(bjTab, limtis, 2, color.green) // ══════════════════════════════════ // // ——————> String Variables <———————— // // ══════════════════════════════════ // bool cSon = thirdParty == A1 bool tCon = thirdParty == A2 bool aTron = thirdParty == A3 bool c3 = thirdParty == A4 bool dCord = thirdParty == A5 if cSon and useStrat string json = "'{' \n \"passphrase\": \"{0}\", \n \"time\": '\"{{timenow}}\"', \n \"ticker\": '\"{{ticker}}\"', \n \"plot\": '{' \n \"stop_price\": {1, number, #.########}, \n \"limit_price\": {2, number, #.########} \n '}', \n \"strategy\": '{' \n \"position_size\": '{{strategy.position_size}}', \n \"order_action\": '\"{{strategy.order.action}}\"', \n \"market_position\": '\"{{strategy.market_position}}\"', \n \"market_position_size\": '{{strategy.market_position_size}}', \n \"prev_market_position\": '\"{{strategy.prev_market_position}}\"', \n \"prev_market_position_size\": '{{strategy.prev_market_position_size}}' \n '}' \n'}'" altStr := str.format(json, pPhrase, stp, lmt) if tCon and useStrat string tcTrade = "'{{strategy.order.action}}' tradesymbol={0} tradeid={1}" + (atrStop ? "" : ' tpprice={2, number, #.########}') + ' slprice={3, number, #.########}' altStr := str.format(tcTrade, tcTicker, tradeId, lmt, stp) tUp := str.format(tcStop, stp, tradeId) if aTron and useStrat string altEnt = aTronKey + " '{'\ncancel(which=all);\nmarket(position='{{strategy.position_size}}');\n" string altEnd = "'}'\n#bot" string altBrkt = (atrStop ? "stopOrder(" : "stopOrTakeProfit(") + (atrStop ? "" : "tp=@{0, number, #.########}, ") + (atrStop ? "offset=@" : "sl=@") + "{1, number, #.########}, position=0, reduceOnly=true" + (atrStop ? ", tag=trail" : "") + ");\n" string enter = altEnt + altBrkt + altEnd string exit = altEnt + altEnd altStr := str.format(enter, lmt, stp) altExit := na(altExit) ? exit : altExit string stopUpdate = aTronKey + " '{'\ncancel(which=tagged, tag=trail);\n" + altBrkt + altEnd tUp := atrStop ? str.format(stopUpdate, lmt, stp) : tUp if dCord and useStrat tnB := longEntry ? db : shortEntry ? dt : tnB string postTrade = "'{'\"content\": \"```🚨 Bjorgum {0} detected 🚨\\n\\n\\t'{{ticker}}' '{{interval}}'\\n\\n\\t" + (atrStop ? "" : "🎯 Target: {1, number, #.########}\\n\\t") + "🛑 Stop: {2, number, #.########}```\"'}'" altStr := str.format(postTrade, tnB, lmt, stp) dCordWin := str.format(dExit, tnB, winStr) dCordLose := str.format(dExit, tnB, loseStr) if c3 and useStrat c3Long := SHORT and buy ? str.format("[{0}, {1}]", c3ShortEnd, c3Long) : c3Long c3Short := LONG and sell ? str.format("[{0}, {1}]", c3LongEnd, c3Short) : c3Short // ══════════════════════════════════ // // ——————> Strategy Execution <—————— // // ══════════════════════════════════ // strategy.entry("Long" , strategy.long , comment= "Long", when= useStrat and longEntry and dateFilter, alert_message= c3 ? c3Long : altStr) strategy.entry("Short", strategy.short, comment= "Short", when= useStrat and shortEntry and dateFilter, alert_message= c3 ? c3Short : altStr) strategy.exit("Long Exit", "Long", stop = stp, limit = lmt, comment = "L Exit", alert_message = c3 ? c3LongEnd : aTron ? altExit : tCon ? "closelong" : dCord ? na : altStr, alert_profit = dCord ? dCordWin : na, alert_loss = dCord ? dCordLose : na) strategy.exit("Short Exit", "Short", stop = stp, limit = lmt, comment = "S Exit", alert_message = c3 ? c3ShortEnd : aTron ? altExit : tCon ? "closeshort" : dCord ? na : altStr, alert_profit = dCord ? dCordWin : na, alert_loss = dCord ? dCordLose : na) // ══════════════════════════════════ // // —————> Alert Functionality <—————— // // ══════════════════════════════════ // if (lt and ls != ls[1] or st and ss != ss[1]) and (tCon or aTron) alert(tUp, alert.freq_once_per_bar_close) if not useStrat and (buy or sell) alert((buy ? db : dt) + ' Detected', alert.freq_once_per_bar) // ____ __ _ ____ // ( __)( ( \( \ // ) _) / / ) D ( // (____)\_)__)(____/
RSITrendStrategy
https://www.tradingview.com/script/DNoWMfpD-RSITrendStrategy/
email_analysts
https://www.tradingview.com/u/email_analysts/
143
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/ // © email_analysts // This code gives indication on the chart to go long or short based on RSI crossover strategy. //Default value has been taken as 5 and 11, with 6 being used to identify highs & lows. //@version=4 strategy("RSITrendStrategy", overlay=false) len1 = input(title="MA 1", defval = 5) len2 = input(title="MA 1", defval = 11) len3 = input(title="MA 1", defval = 6) h1 = hline(30.) h2 = hline(70.) ///fill(h1, h2, color = color.new(color.blue, 80)) sh = rsi(close, len1) ln = rsi(close, len2) rs = rsi(close, len3) p1 = plot(sh, color = color.red) p2 = plot(ln, color = color.green) p3 = plot(rs, color = color.white) mycol = sh > ln ? color.lime : color.red fill(p1, p2, color = mycol) buy = (sh[1] < ln[1] and sh > ln and rs[1] < 30) if (buy) strategy.entry("long", strategy.long) sell = (sh[1] > ln[1] and sh < ln and rs[1] > 70) if (sell) strategy.entry("short", strategy.short)
I11L Long Put/Call Ratio Inversion
https://www.tradingview.com/script/EmtrWuhL/
I11L
https://www.tradingview.com/u/I11L/
149
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/ // © I11L //@version=5 strategy("I11L Long Put/Call Ratio Inversion", overlay=false, pyramiding=1, default_qty_value=10000, initial_capital=10000, default_qty_type=strategy.cash) SL = input.float(0.01,step=0.01) CRV = input.float(3) TP = SL * CRV len = input.int(30,"Lookback period in Days",step=10) ratio_sma_lookback_len = input.int(20,step=10) mult = input.float(1.5,"Standard Deviation Multiple") ratio_sma = ta.sma(request.security("USI:PCC","D",close),ratio_sma_lookback_len) median = ta.sma(ratio_sma,len) standartDeviation = ta.stdev(ratio_sma,len) upperDeviation = median + mult*standartDeviation lowerDeviation = median - mult*standartDeviation isBuy = ta.crossunder(ratio_sma, upperDeviation)// and close < buyZone isCloseShort = (ratio_sma > median and strategy.position_size < 0) isSL = (strategy.position_avg_price * (1.0 - SL) > low and strategy.position_size > 0) or (strategy.position_avg_price * (1.0 + SL) < high and strategy.position_size < 0) isSell = ta.crossover(ratio_sma,lowerDeviation) isTP = strategy.position_avg_price * (1 + TP) < high if(isBuy) strategy.entry("Long", strategy.long) if(isCloseShort) strategy.exit("Close Short",limit=close) if(isSL) strategy.exit("SL",limit=close) if(isTP) strategy.exit("TP",limit=close) plot(ratio_sma,color=color.white) plot(median,color=color.gray) plot(upperDeviation,color=color.rgb(0,255,0,0)) plot(lowerDeviation,color=color.rgb(255,0,0,0)) bgcolor(isBuy?color.rgb(0,255,0,90):na) bgcolor(isSell?color.rgb(255,0,0,90):na)
VXD Supercycle
https://www.tradingview.com/script/RcxGYEvM-VXD-Supercycle/
Vvaz_
https://www.tradingview.com/u/Vvaz_/
397
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/ // © Vvaz_ //@version=5 //This Strategy Combined the following indicators and conditioning by me //Rolling VWAP , ATR , RSI , EMA , SMA //Subhag form Subhag Ghosh //OB PPDD Form Super OrderBlock / FVG / BoS Tools by makuchaku & eFe strategy("VXD Supercycle", "VXD", overlay=true , initial_capital=100 ,currency = currency.USD , pyramiding = 1 ,process_orders_on_close= true) // Strategy Setting uselong = input.bool(title="Open Buy?", defval = true , group='═══════════ Strategy Setting ═══════════') useshort = input.bool(title="Open Sell?", defval = true , group='═══════════ Strategy Setting ═══════════') useRSIC =input.bool(title="Use RSI Condition?", defval = true , group='═══════════ Strategy Setting ═══════════') usefilter =input.bool(title="Use Filter Condition?", defval = true , group='═══════════ Strategy Setting ═══════════', tooltip = 'Excute Order when subhag is following a trend.') riskPer = input.int(10, "Lost per trade($)", minval = 1, group='═══════════ Strategy Setting ═══════════', tooltip = 'เจ๊งได้เท่าไหร่?(ต่อ 1 ไม้นะ)') useSL = input.bool(title="Use TP/SL?", defval = true , inline='Set', group='═══════════ Strategy Setting ═══════════') usetpcl = input.color(defval=color.new(color.orange,0), title='Color', inline='Set', group='═══════════ Strategy Setting ═══════════') rrPer = input.float(3.00, "Risk:Reward", minval = 1, step=0.1, group='═══════════ Strategy Setting ═══════════') TPper = input.float(50, "Equity % Take Profit", minval = 0.1, step=5, group='═══════════ Strategy Setting ═══════════', tooltip='Take a snack and let profit run.') // INPUT BACKTEST RANGE var string BTR1 = '════════ INPUT BACKTEST TIME RANGE ════════' i_startTime = input.time(defval = timestamp("01 Jan 1945 00:00 +0000"), title = "Start", inline="timestart", group=BTR1) i_endTime = input.time(defval = timestamp("01 Jan 2074 23:59 +0000"), title = "End", inline="timeend", group=BTR1) timeCond = (time > i_startTime) and (time < i_endTime) //////////////////////////////////// function MA ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ma(source, length, type) => type == "SMA" ? ta.sma(source, length) : type == "EMA" ? ta.ema(source, length) : type == "SMMA (RMA)" ? ta.rma(source, length) : type == "WMA" ? ta.wma(source, length) : type == "VWMA" ? ta.vwma(source, length) : na //////////////////////////////// RVWAP ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// import PineCoders/ConditionalAverages/1 as pc var string GRP2 = '═══════════ VWAP Setting ═══════════' var string TT_MINBARS = "The minimum number of last values to keep in the moving window, even if these values are outside the time period. This avoids situations where a large time gap between two bars would cause the time window to be empty." int MS_IN_MIN = 60 * 1000 int MS_IN_HOUR = MS_IN_MIN * 60 int MS_IN_DAY = MS_IN_HOUR * 24 float srcInput = input.source(close, "Source", tooltip = "The source used to calculate the VWAP. The default is the average of the high, low and close prices.", group = GRP2) int minBarsInput = input.int(21, "Min Bars", group = GRP2, tooltip = TT_MINBARS) timeStep() => // @function Determines a time period from the chart's timeframe. // @returns (int) A value of time in milliseconds that is appropriate for the current chart timeframe. To be used in the RVWAP calculation. int tfInMs = timeframe.in_seconds() * 1000 float step = switch tfInMs <= MS_IN_MIN => MS_IN_HOUR tfInMs <= MS_IN_MIN * 5 => MS_IN_HOUR * 4 tfInMs <= MS_IN_HOUR => MS_IN_DAY * 1 tfInMs <= MS_IN_HOUR * 4 => MS_IN_DAY * 3 tfInMs <= MS_IN_HOUR * 12 => MS_IN_DAY * 7 tfInMs <= MS_IN_DAY => MS_IN_DAY * 30.4375 tfInMs <= MS_IN_DAY * 7 => MS_IN_DAY * 90 => MS_IN_DAY * 365 int result = int(step) // RVWAP float rollingVWAP = pc.totalForTimeWhen(srcInput * volume, timeStep(), true, minBarsInput) / pc.totalForTimeWhen(volume, timeStep(), true, minBarsInput) ///////////////////////// ATR ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Periods = input.int(title="ATR Period", defval=12 ,group='═══════════ ATR Setting ═══════════') Multiplier = input.float(title="ATR Multiplier", step=0.1, defval=2.4,group='═══════════ ATR Setting ═══════════') [supertrend, direction] = ta.supertrend(Multiplier, Periods) ///////////////////////// RSI ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// LengthRSI = input.int(25,'RSI', minval=1, group='═══════════ RSI Setting ═══════════') LengthRSIMA = input.int(14,'RSI-MA', minval=1, group='═══════════ RSI Setting ═══════════', tooltip = 'RSI MA corss 50 Trigger Order') ///////////////////////// MA ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// useMA = input.bool(title="Use VWAP?", defval = true , group='═══════════ MA Setting ═══════════', tooltip = 'Use VWAP trend line') LengthMA = input.int(21,'EMA', minval=1, group='═══════════ MA Setting ═══════════', tooltip = 'Act as Trend line') sma2cl = input.color(defval=color.new(color.yellow,0), title='EMA Slow', group='═══════════ MA Setting ═══════════' ,inline = 'sma200') LengthMA2 = input.int(200,'SMA', minval=1, group='═══════════ MA Setting ═══════════' ,inline = 'sma200') float MA_1 = ta.ema(close, LengthMA) MA_2 = ta.sma(close, LengthMA2) SourceOpen = (open + close[1]) / 2 Candleopen = ta.ema(SourceOpen,25) Bodycolor = Candleopen > Candleopen[1] ? color.green : color.red ////////////////////////// Subhag form Subhag Ghosh ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// length = input.int(100, minval=1, group='═══════════ Subhag Setting ═══════════') smoothing = input.int(17, minval=1, group='═══════════ Subhag Setting ═══════════') // Regression Lines linreg = ta.ema(ta.linreg(close, length, 0),smoothing) //COLOR of Regression Line hullColor = linreg > linreg[3] ? color.green :linreg < linreg[3] ? color.red : color.yellow /////////////////////////////// define trend ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// trendL = useMA and ta.cum(nz(volume)) != 0 ? rollingVWAP : MA_1 upTrend = direction < 0 ? supertrend : linreg[3] downTrend = direction < 0 ? linreg : supertrend fastl = ta.ema(close,2) greenzone = (fastl > trendL) and (direction < 0) and (close > linreg) and (Bodycolor == color.green) redzone = (fastl < trendL) and (direction > 0 ) and (close < linreg) and (Bodycolor == color.red) greenzoneB = (fastl > trendL) and (direction < 0) and (hullColor == color.green) and (Bodycolor == color.green) redzoneB = (fastl < trendL) and (direction > 0 ) and (hullColor == color.red) and (Bodycolor == color.red) //plotMA and candle zonecl = greenzone ? color.green : redzone ? color.red : color.yellow main1 = plot(trendL , title="EMA Fast" , color=zonecl , linewidth=1) main2 = plot(MA_2 , title="EMA Slow" , color=sma2cl , linewidth=2) //-------------------------------NSDT HAMA Candels plotbar(linreg[3], upTrend, downTrend, linreg, color=color.new(hullColor,60), title='Configure Bars') ////////////////////////////////// OB PPDD Form Super OrderBlock / FVG / BoS Tools by makuchaku & eFe ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// plotPVT = input.bool(defval=true, title='Plot Pivots', group='═══════════ Pivots ═══════════') pivotLookup = input.int(defval=5, minval=1, maxval=8,title='Pivot Lookup', group='═══════════ Pivots ═══════════', tooltip='Minimum = 1, Maximum = 8') pivotsizing = input.int(defval=50, minval=1, maxval=100,title='Pivot bars back for sizing', group='═══════════ Pivots ═══════════', tooltip='Minimum = 1, Maximum = 100') plotInThePast = input(false, "Plot When Pivot is Detected" ,group='═══════════ Pivots ═══════════') pvtTopColor = input.color(defval=color.new(color.lime,10), title='Pivot Top Color', group='═══════════ Pivots ═══════════', inline='PVT Top Color') pvtBottomColor = input.color(defval=color.new(color.red,10), title='Pivot Bottom Color', group='═══════════ Pivots ═══════════', inline='PVT Top Color') plotRJB = input.bool(defval=true, title='Plot RJB', group='═══════════ Rejection Blocks ═══════════', inline='RJB sets') bosBoxFlag = input.bool(title='Box Length Manually', defval=false, group='═══════════ Rejection Blocks ═══════════', tooltip='If activated the BoS Boxes will not extend unitl crossed by price. Instead will extend by the amount of bars choosen in the "Set BoS Box Length Manually" option') bosBoxLength = input.int(title='Box Length Manually', defval=3, minval=1, maxval=5, group='═══════════ Rejection Blocks ═══════════', tooltip='If "Set BoS Box Length Manually" is marked, choose by how many bars. Minimum = 1, Maximum = 5') rjbBullColor = input.color(defval=color.new(color.green,70), title='Bullish RJB Color', inline='Set Custom Color', group='═══════════ Rejection Blocks ═══════════') rjbBearColor = input.color(defval=color.new(color.red, 70), title='Bearish RJB Color', inline='Set Custom Color', group='═══════════ Rejection Blocks ═══════════') rjbBoxBorder = input.string(defval=line.style_solid, title='RJB Box Border Style', options=[line.style_dashed, line.style_dotted, line.style_solid], group='═══════════ Rejection Blocks ═══════════', tooltip='To disable border, set Border Width below to 0') rjbBorderTransparency = input.int(defval=100, title='RJB Border Box Transparency', minval=0, maxval=100, group='═══════════ Rejection Blocks ═══════════') rjbMaxBoxSet = input.int(defval=100, title='Maximum RJB Box Displayed', minval=1, maxval=100, group='═══════════ Rejection Blocks ═══════════', tooltip='Minimum = 1, Maximum = 100') filterMitRJB = input.bool(defval=true, title='Custom Color Mitigated RJB', group='═══════════ Rejection Blocks ═══════════') mitRJBColor = input.color(defval=color.new(color.gray, 90), title='Mitigated RJB Color', group='═══════════ Rejection Blocks ═══════════', inline='Set Custom Color Mit RJB', tooltip='Set to 100 to make mitigated RJB disappear') plotHVB = input.bool(defval=true, title='Plot HVB', group='═══════════ High Volume Bar ═══════════', tooltip='A candle where the average volume is higher than last few bars.') hvbBullColor = input.color(defval=color.new(color.green,0), title='Bullish HVB Color', inline='Set Custom Color', group='═══════════ High Volume Bar ═══════════') hvbBearColor = input.color(defval=color.new(color.orange,0), title='Bearish HVB Color', inline='Set Custom Color', group='═══════════ High Volume Bar ═══════════') hvbEMAPeriod = input.int(defval=6, minval=1, title='Volume EMA Period', group='═══════════ High Volume Bar ═══════════') hvbMultiplier = input.float(defval=1.2, title='Volume Multiplier', minval=1, maxval=100, group='═══════════ High Volume Bar ═══════════') plotPPDD = input.bool(defval=true, title="Plot PPDD OB's", group='═══════════ Qualitative indicators ═══════════', tooltip='Premium Premium Discount Discount (PPDD) is an OB formed after liquidity sweep. It will show up by default as a circle (Bull green / Bear red). Also PPDD1 (by deafult maked with a x-cross ⨯) which is a weak OB formed after liquidity sweep, that fails to completely engulf the high/low, but closes beyond the trapped candles open price.') ppddBullColor = input.color(defval=color.new(color.green,0), title="Bullish PPDD OB's Color", group='═══════════ Qualitative indicators ═══════════', inline='PPDD Bull') ppddBearColor = input.color(defval=color.new(color.red,0), title="Bearish PPDD OB's Color", group='═══════════ Qualitative indicators ═══════════', inline='PPDD Bear') //labels plotLabelRJB = input.bool(defval=false, title='Plot RJB Label', inline='RJB label', group='═══════════ Label Options ═══════════') rjbLabelColor = input.color(defval=color.gray, title='Color', inline='RJB label', group='═══════════ Label Options ═══════════') rjbLabelSize = input.string(defval=size.tiny, title="Size", options=[size.huge, size.large, size.small, size.tiny, size.auto, size.normal], inline='RJB label', group='═══════════ Label Options ═══════════') //Box Types var int _rjb = 3 var int _bos = 4 //Box Labels var string _rjbLabel = "RJB" var string _plus = "+" var string _minus = "-" var string _empty = "" //Box Arrays var box[] _bearBoxesRJB = array.new_box() var box[] _bullBoxesRJB = array.new_box() //Functions isUp(index) => close[index] > open[index] isDown(index) => close[index] < open[index] isObUp(index) => isDown(index + 1) and isUp(index) and close[index] > high[index + 1] isObDown(index) => isUp(index + 1) and isDown(index) and close[index] < low[index + 1] isFvgUp(index) => (low[index] > high[index + 2]) isFvgDown(index) => (high[index] < low[index + 2]) //Function to Calculte Box Length _controlBox(_boxes, _high, _low, _type) => if array.size(_boxes) > 0 for i = array.size(_boxes) - 1 to 0 by 1 _box = array.get(_boxes, i) _boxLow = box.get_bottom(_box) _boxHigh = box.get_top(_box) _boxRight = box.get_right(_box) if bosBoxFlag and _type == _bos if na or (bar_index + bosBoxLength - 1 == _boxRight and not((_high > _boxLow and _low < _boxLow) or (_high > _boxHigh and _low < _boxHigh))) box.set_right(_box, bar_index + bosBoxLength - 1) else if (filterMitRJB and _type == _rjb) if na or (bar_index == _boxRight and not((_high > _boxLow and _low < _boxLow) or (_high > _boxHigh and _low < _boxHigh))) box.set_right(_box, bar_index + 1) else if _type == _rjb box.set_bgcolor(_box, mitRJBColor) box.set_border_color(_box, mitRJBColor) else if na or (bar_index == _boxRight and not((_high > _boxLow and _low < _boxLow) or (_high > _boxHigh and _low < _boxHigh))) box.set_right(_box, bar_index + 1) //////////////////// Rejection Block ////////////////// if plotRJB isDownRjbObCondition = isObDown(1) isDownRjb1 = isDownRjbObCondition and (high[1] < (close[2] + 0.2*(high[2]-close[2]))) // RJB is on trapped's wick and <50% of the wick was covered by signal isDownRjb2 = isDownRjbObCondition and (high[1] > high[2]) // RJB is on signal's wick if isDownRjb1 and plotRJB _bearboxRJB = box.new(left=bar_index-2, top=high[2], right=bar_index, bottom=close[2], bgcolor=rjbBearColor, border_color=color.new(rjbBearColor, rjbBorderTransparency), border_style=rjbBoxBorder, border_width=1, text = plotLabelRJB ? _rjbLabel + _minus : _empty, text_halign=text.align_right, text_valign=text.align_bottom, text_size=rjbLabelSize, text_color=rjbLabelColor) if array.size(_bearBoxesRJB) > rjbMaxBoxSet box.delete(array.shift(_bearBoxesRJB)) array.push(_bearBoxesRJB, _bearboxRJB) if isDownRjb2 and plotRJB _bearboxRJB = box.new(left=bar_index-1, top=high[1], right=bar_index, bottom=open[1], bgcolor=rjbBearColor, border_color=color.new(rjbBearColor, rjbBorderTransparency), border_style=rjbBoxBorder, border_width=1, text=plotLabelRJB ? _rjbLabel + _minus : _empty, text_halign=text.align_right, text_valign=text.align_bottom, text_size=rjbLabelSize, text_color=rjbLabelColor) if array.size(_bearBoxesRJB) > rjbMaxBoxSet box.delete(array.shift(_bearBoxesRJB)) array.push(_bearBoxesRJB, _bearboxRJB) //Bullish RJB Box Plotting if plotRJB isUpRjbObCondition = isObUp(1) isUpRjb1 = isUpRjbObCondition and (low[1] > (close[2] - 0.2*(close[2]-low[2]))) // RJB is on trapped's wick and <50% of the wick was covered by signal isUpRjb2 = isUpRjbObCondition and (low[1] < low[2]) // RJB is on signal's wick if isUpRjb1 and plotRJB _bullboxRJB = box.new(left=bar_index-2, top=close[2], right=bar_index, bottom=low[2], bgcolor=rjbBullColor, border_color=color.new(rjbBullColor, rjbBorderTransparency), border_style=rjbBoxBorder, border_width=1, text = plotLabelRJB ? _rjbLabel + _plus : _empty, text_halign=text.align_right, text_valign=text.align_bottom, text_size=rjbLabelSize, text_color=rjbLabelColor) if array.size(_bullBoxesRJB) > rjbMaxBoxSet box.delete(array.shift(_bullBoxesRJB)) array.push(_bullBoxesRJB, _bullboxRJB) if isUpRjb2 and plotRJB _bullboxRJB = box.new(left=bar_index-1, top=open[1], right=bar_index, bottom=low[1], bgcolor=rjbBullColor, border_color=color.new(rjbBullColor, rjbBorderTransparency), border_style=rjbBoxBorder, border_width=1, text=plotLabelRJB ? _rjbLabel + _plus : _empty, text_halign=text.align_right, text_valign=text.align_bottom, text_size=rjbLabelSize, text_color=rjbLabelColor) if array.size(_bullBoxesRJB) > rjbMaxBoxSet box.delete(array.shift(_bullBoxesRJB)) array.push(_bullBoxesRJB, _bullboxRJB) if plotRJB _controlBox(_bearBoxesRJB, high, low, _rjb) _controlBox(_bullBoxesRJB, high, low, _rjb) //////////////////// Pivots //////////////////// hih = ta.pivothigh(high, pivotLookup, pivotLookup) lol = ta.pivotlow(low , pivotLookup, pivotLookup) top = ta.valuewhen(hih, high[pivotLookup], 0) bottom = ta.valuewhen(lol, low [pivotLookup], 0) pvtop = plot(top, offset=plotInThePast ? 0 : -pivotLookup , linewidth=1, color=(top != top[1] ? na : (plotPVT ? pvtTopColor : na)), title="Pivot Top") pvdow = plot(bottom, offset=plotInThePast ? 0 : -pivotLookup, linewidth=1, color=(bottom != bottom[1] ? na : (plotPVT ? pvtBottomColor : na)), title="Pivot Bottom") //////////////////// Premium Premium & Discount Discount ////////////////// premiumPremium = plotPPDD and isObDown(0) and ((math.max(high, high[1]) > top and close < top) or (math.max(high, high[1]) > top[1] and close < top[1])) discountDiscount = plotPPDD and isObUp(0) and ((math.min(low, low[1]) < bottom and close > bottom) or (math.min(low, low[1]) < bottom[1] and close > bottom[1])) plotshape(premiumPremium, "Bearish PPDD OB", style=shape.circle , location=location.abovebar, color=ppddBearColor, size=size.tiny) plotshape(discountDiscount, "Bullish PPDD OB", style=shape.circle , location=location.belowbar, color=ppddBullColor, size=size.tiny) premiumPremium1 = plotPPDD and (isUp(1) and isDown(0) and close[0] < open[1]) and ((math.max(high, high[1]) > top and close < top) or (math.max(high, high[1]) > top[1] and close < top[1])) and not premiumPremium discountDiscount1 = plotPPDD and (isDown(1) and isUp(0) and close[0] > open[1]) and ((math.min(low, low[1]) < bottom and close > bottom) or (math.min(low, low[1]) < bottom[1] and close > bottom[1])) and not discountDiscount plotshape(premiumPremium1, "Bearish PPDD Weak OB", style=shape.xcross, location=location.abovebar, color=ppddBearColor, size=size.tiny) plotshape(discountDiscount1, "Bullish PPDD Weak OB", style=shape.xcross, location=location.belowbar, color=ppddBullColor, size=size.tiny) ////////////////// High Volume Bars ////////////////// volEma = ta.sma(volume, hvbEMAPeriod) isHighVolume = volume > (hvbMultiplier * volEma) barcolor(plotHVB and isUp(0) and isHighVolume ? hvbBullColor : na, title="Bullish HVB") barcolor(plotHVB and isDown(0) and isHighVolume ? hvbBearColor : na, title="Bearish HVB") ////////////////////////////////// Strategy condition //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// openoncel = strategy.opentrades == 0 or (strategy.opentrades.entry_id(0) == 'Short2') openonces = strategy.opentrades == 0 or (strategy.opentrades.entry_id(0) == 'long2') exitshort = (fastl > trendL) and (direction < 0) and (close > top) and (close > linreg) exitlong = (fastl < trendL) and (direction > 0) and (close < bottom) and (close < linreg) //sizing highest = ta.highest(top,pivotsizing) lowest = ta.lowest(bottom,pivotsizing) lotsbull = math.abs((riskPer ) / (close - lowest)) lotsbear = math.abs((riskPer ) / (highest - close)) ////condition for RSI rsibb = ta.rsi(close,LengthRSI) rsiMA = ma(rsibb, LengthRSIMA, "SMA") rsibuy1 = ta.crossover(rsiMA,50) and (rsibb > rsiMA) and useRSIC and (close > top) and greenzone and timeCond rsibuy2 = ta.crossover(rsiMA,50) and (rsibb > rsiMA) and useRSIC and (close > top) and greenzoneB and timeCond rsisell1 = ta.crossunder(rsiMA,50) and (rsibb < rsiMA) and useRSIC and (close < bottom) and redzone and timeCond rsisell2 = ta.crossunder(rsiMA,50) and (rsibb < rsiMA) and useRSIC and (close < bottom) and redzoneB and timeCond //condition for trend LongCondition = (close > supertrend) and openoncel and (close > top) and greenzone and timeCond ShortCondition = ( close < supertrend) and openonces and (close < bottom) and redzone and timeCond LongConditionB = (close > supertrend) and openoncel and (close > top) and greenzoneB and timeCond ShortConditionB = ( close < supertrend) and openonces and (close < bottom) and redzoneB and timeCond position_size = strategy.position_size actionbull = usefilter == true ? (rsibuy2 or LongConditionB) : (rsibuy1 or LongCondition) actionbear = usefilter == true ? (rsisell2 or ShortConditionB) : (ShortCondition or rsisell1) changetbull = ta.change(actionbull) ,changetbear = ta.change(actionbear) ,buyprice = 0.0 ,sellprice = 0.0 ,mapast = 0.0 ,slprice = 0.0 ,openprice = strategy.opentrades.entry_price(0),sl_percent_bear = 0.0,sl_percent_bull = 0.0 , onetrade = 0 buyprice := position_size >= 0 ? changetbull ? openprice : buyprice[1] : na sellprice := position_size <= 0 ? changetbear ? openprice : sellprice[1] : na mapast := changetbull ? MA_2 : changetbear ? MA_2 : mapast[1] onetrade := TPper == 100 ? (changetbull ? 1 : changetbear ? -1 : onetrade[1]) : 0 slprice := changetbull ? lowest : changetbear ? highest : slprice[1] sl_percent_bull := changetbull ? (buyprice - lowest)/buyprice : (position_size > 0) ? sl_percent_bull[1] :(position_size < 0) ? 0.0 : 0.0 takeProfitBull = buyprice * (1 + (sl_percent_bull*rrPer)) sl_percent_bear := changetbear ? (highest - sellprice) / sellprice : (position_size < 0) ? sl_percent_bear[1] :(position_size > 0) ? 0.0 : 0.0 takeProfitBear = sellprice * (1 - (sl_percent_bear*rrPer)) plot(useSL and changetbull ? takeProfitBull : useSL and changetbear ? takeProfitBear : na , 'TP',usetpcl,style=plot.style_linebr , linewidth=1 ) plot(useSL and changetbull ? slprice : useSL and changetbear ? slprice : na , 'SL',usetpcl,style=plot.style_linebr , linewidth=1 ) string Alert_OpenLong ='Long Entry! on '+syminfo.ticker+'\n Buy@'+str.tostring(close)+'\n Size = '+str.tostring(lotsbull)+'\n SL = '+str.tostring(slprice) string Alert_OpenShort ='Short Entry! on '+syminfo.ticker+'\n Sell@'+str.tostring(close)+'\n Size = '+str.tostring(lotsbear)+'\n SL = '+str.tostring(slprice) string Alert_LongTP ='TP Long on '+syminfo.ticker+' @'+str.tostring(takeProfitBull)+' Size = '+str.tostring((position_size * (TPper/100))) string Alert_ShortTP ='TP Short on '+syminfo.ticker+' @'+str.tostring(takeProfitBear)+' Size = '+str.tostring((position_size * (TPper/100))) var message_closelong = 'Tailing Stop Long!!!' var message_closeshort = 'Tailing Stop Short!!!' string Alert_StopLosslong ='StopLoss Long! on '+syminfo.ticker+' @'+str.tostring(slprice) string Alert_StopLossshort = 'StopLoss Short! on '+syminfo.ticker+' @'+str.tostring(slprice) // exit order if (exitlong == true ) strategy.close('long2', comment='TailingStop-L', alert_message=message_closelong) if (exitshort == true ) strategy.close('Short2', comment='TailingStop-S', alert_message=message_closeshort) // long if (uselong == true) and changetbull and (onetrade[1] != 1) strategy.entry('long2', strategy.long ,qty =lotsbull , comment='Long', alert_message=Alert_OpenLong) // Short if (useshort == true) and changetbear and (onetrade[1] != -1) strategy.entry('Short2', strategy.short ,qty =lotsbear, comment='Short', alert_message=Alert_OpenShort) //TPSL if (position_size > 0) and useSL and (low < buyprice) strategy.exit('TPSLB','long2', comment='SL', stop =slprice , alert_message=Alert_StopLosslong) else if (position_size > 0) and useSL and (low > buyprice) strategy.exit('TPSLB','long2', comment='TP',limit=takeProfitBull , alert_message=Alert_LongTP , qty_percent=TPper) else strategy.cancel('TPSLB') if (position_size < 0) and useSL and (high > sellprice) strategy.exit('TPSLS','Short2',comment= 'SL', stop=slprice , alert_message=Alert_StopLossshort) else if (position_size < 0) and useSL and (high < sellprice) strategy.exit('TPSLS','Short2',comment= 'TP',limit=takeProfitBear , alert_message=Alert_ShortTP, qty_percent=TPper) else strategy.cancel('TPSLS') ////////////////////////////////// By Vvaz_ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
ema strategy
https://www.tradingview.com/script/L4o5RzWV-ema-strategy/
Sijj
https://www.tradingview.com/u/Sijj/
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/ // © Sijj //@version=5 strategy("ema strategy", overlay = true) ema = ta.ema(close, 5) e = ta.ema(close, 200) rsi = ta.rsi(close, 2) cond1 = close[1] < open[1] * 0.9999 and close[1] < ema and rsi < 10 cond2 = close[1] > open[1] * 1.0001 and close[1] > ema and rsi > 90 plot(ema) plotshape(cond1, style = shape.triangleup, location = location.belowbar, color = color.lime, text = "Buy" ) plotshape(cond2, style = shape.triangledown, location = location.abovebar, color = color.red, text = "Sell" ) pos = strategy.position_size strategy.entry("Buy", strategy.long,qty = strategy.opentrades > 0 ? pos*2 : 1000, when = cond1 ) strategy.close("Buy",comment = "Exit", when = strategy.openprofit > 1 or strategy.opentrades > 5)
Gap Reversion Strategy
https://www.tradingview.com/script/sef1hUMe-Gap-Reversion-Strategy/
TradeAutomation
https://www.tradingview.com/u/TradeAutomation/
304
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="Gap Reversion Strategy", shorttitle="Gap Reversion Strategy", process_orders_on_close=false, overlay=true, pyramiding=0, commission_type=strategy.commission.cash_per_order, commission_value=1, slippage = 1, 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 2010 06:00 +0000'), group="Backtest Date Range", title='Start Time') EndTime = input.time(defval=timestamp('01 Jan 2099 00:00 +0000'), group="Backtest Date Range", title='End Time') InDateRange = time>=StartTime and time<=EndTime // Wilder's RSI // lenrsi=input.int(2, title="RSI-length", group="RSI Settings") src = input.source(close, title="RSI Source", group="RSI Settings") RSI = ta.rsi(src, lenrsi) // VIX Volatility Warning Indicator & Filter // vix = request.security("CBOE:VIX", "60", high) mean = ta.sma(vix, 350) SquaredDifference = math.pow(vix-mean, 2) VolWarningLength = input.int(5, "Sustain Volatility Filter For X Bars", group="Volatility Filter Settings") SquaredDifferenceThreshold = input.int(500, "Variance Threshold", group="Volatility Filter Settings") VolatilityWarning = ta.highest(SquaredDifference, VolWarningLength)<SquaredDifferenceThreshold EarlyWarningInput = input.bool(false, "Use VIX Variance Filter?", group="Volatility Filter Settings", tooltip="This will prevent new signals from entering trades when the VIX is unusually high") ReversionFilter = EarlyWarningInput == true ? VolatilityWarning : close>0 // Long Entry Rules // ReversionRule = RSI<input.float(20, "RSI Long Qualifier", tooltip="The selected RSI / reversion indicator value must be below this input after a gap down to place a trade", group="Trade Entry/Exit Settings", step=5) GapPerc = (1-(input.float(.25, "Minimum Gap % of Price", step=.1, group="Limit Entry Price Settings", minval=0)*.01)) GapDown = open<close[1]*GapPerc var float LongEntryLimit=na PercLimit = (close*GapPerc)*(1-input.float(1, "Price % Entry Limit (close-gap-%)", tooltip="When the strategy issues a long buy signal, a limit order is generated at this % below the prior day's close price minus Gap % input", step=.1, minval=0, group="Limit Entry Price Settings")*.01) ATRLimit = (close*GapPerc)-(ta.atr(input.int(5, "ATR Length"))*input.float(20, "ATR Long Entry Limit (close-gap-%ofATR)", tooltip="When the strategy issues a long buy signal, a limit order is generated at this % of ATR below the prior day's close price minus Gap % input",step=5, minval=0, group="Limit Entry Price Settings")*.01) LimitInput = input.bool(false, "Use % of ATR entry limit instead of % of price entry limit?", group="Limit Entry Price Settings") Limit = LimitInput == true ? ATRLimit : PercLimit LongEntryLimit := ReversionRule==true ? Limit : na LongExit = RSI>input.float(70, "RSI Indicator Exit Value", tooltip="The strategy will exit the long position when the Reversion Indicator crosses over this value", group="Trade Entry/Exit Settings", step=5) // Stop // StopPercInput = 1-(input.float(99, "Stop %", step=0.25, group="Trade Entry/Exit Settings")*.01) PercStop = strategy.position_avg_price*StopPercInput // Entry and Exit Functions // if (InDateRange) strategy.entry("Long", strategy.long, limit=LongEntryLimit, when = ReversionRule==true and ReversionFilter, alert_message="Buy") strategy.exit("Exit", "Long", stop=PercStop, alert_message="Sell") strategy.cancel_all(when = GapDown==false) strategy.close("Long", when = LongExit, alert_message="Sell") if (not InDateRange) strategy.close_all()
BUY/SELL on the levels only
https://www.tradingview.com/script/okTkQZnL-BUY-SELL-on-the-levels-only/
Arivadis
https://www.tradingview.com/u/Arivadis/
52
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © svatvlad1993 //@version=5 strategy("test for more freq","BUY/SELL test for more freq",pyramiding=100 , overlay=true, currency=currency.USDT, commission_type=strategy.commission.percent, commission_value=0.05,initial_capital=5000, margin_long=10, margin_short=10, max_lines_count = 500, max_labels_count = 500, max_bars_back = 5000)//, default_qty_type=strategy.percent_of_equity, default_qty_value=4) // tail-resistance for buy var last_min = low[0] var last_max = high[0] var permission_for_buy = 0 lowest0 = ta.lowest(low,100) highest0 = ta.highest(high,100) if close > last_max if lowest0 != 0 last_min := lowest0 else last_min := close - (close * 0.02) last_max := high permission_for_buy := 1 if close < last_min last_min := low if highest0 != 0 last_max := highest0 else last_max := close + (close * 0.02) permission_for_buy := 0 plot_diaps1 = plot(permission_for_buy != 0? na : last_max, title='Max',color=color.new(#ff0000, 95),style=plot.style_cross,trackprice=true ) plot_diaps2 = plot(permission_for_buy != 0? na : last_min, title='Min',color=color.new(#ff0000, 95),style=plot.style_cross,trackprice=true ) plot_diaps3 = plot(permission_for_buy != 1? na : last_max, title='max',color=color.new(color.green, 95),style=plot.style_cross,trackprice=true ) plot_diaps4 = plot(permission_for_buy != 1? na : last_min, title='min',color=color.new(color.green, 95),style=plot.style_cross,trackprice=true ) fill(plot_diaps1, plot_diaps2,color=color.new(#ff0000, 95)) fill(plot_diaps3, plot_diaps4,color=color.new(color.green, 95)) //Supertrend atrPeriod = input(10, "ATR Length") factor = input.float(2.5, "Factor", step = 0.01) [supertrend, direction] = ta.supertrend(factor, atrPeriod) bodyMiddle = plot((open + close) / 2, display=display.none) upTrend = plot(direction < 0 ? supertrend : na, "Up Trend", color = color.teal, style=plot.style_linebr) downTrend = plot(direction < 0? na : supertrend, "Down Trend", color = color.maroon, style=plot.style_linebr) fill(bodyMiddle, upTrend, color.new(color.teal, 75), fillgaps=false) fill(bodyMiddle, downTrend, color.new(color.maroon, 75), fillgaps=false) // levels sell/buy var float[] price_to_sellBue = array.from(1.01, 1.02, 1.03, 1.04, 1.05, 1.06, 1.071, 1.082, 1.093, 1.104, 1.115, 1.126, 1.137, 1.148, 1.159, 1.171, 1.183, 1.195, 1.207, 1.219, 1.231, 1.243, 1.255, 1.268, 1.281, 1.294, 1.307, 1.32, 1.333, 1.346, 1.359, 1.373, 1.387, 1.401, 1.415, 1.429, 1.443, 1.457, 1.472, 1.487, 1.502, 1.517, 1.532, 1.547, 1.562, 1.578, 1.594, 1.61, 1.626, 1.642, 1.658, 1.675, 1.692, 1.709, 1.726, 1.743, 1.76, 1.778, 1.796, 1.814, 1.832, 1.85, 1.869, 1.888, 1.907, 1.926, 1.945, 1.964, 1.984, 2.004, 2.024, 2.044, 2.064, 2.085, 2.106, 2.127, 2.148, 2.169, 2.191, 2.213, 2.235, 2.257, 2.28, 2.303, 2.326, 2.349, 2.372, 2.396, 2.42, 2.444, 2.468, 2.493, 2.518, 2.543, 2.568, 2.594, 2.62, 2.646, 2.672, 2.699, 2.726, 2.753, 2.781, 2.809, 2.837, 2.865, 2.894, 2.923, 2.952, 2.982, 3.012, 3.042, 3.072, 3.103, 3.134, 3.165, 3.197, 3.229, 3.261, 3.294, 3.327, 3.36, 3.394, 3.428, 3.462, 3.497, 3.532, 3.567, 3.603, 3.639, 3.675, 3.712, 3.749, 3.786, 3.824, 3.862, 3.901, 3.94, 3.979, 4.019) var float[] count_of_orders = array.from(2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0) //loops for sale/buy for i = 0 to 139 if array.get(price_to_sellBue, i) >= open[0] and array.get(price_to_sellBue, i) <= close[0] and direction[0] < 0 and permission_for_buy != 0 if array.get(count_of_orders, i) > 0 strategy.order(str.tostring(i), strategy.long, 15) g = array.get(count_of_orders, i) array.set(count_of_orders, i, g - 2) break var SELL_amount = 0 var strategy_short = 0 for i = 0 to 139 if array.get(price_to_sellBue, i) <= open[0] and array.get(price_to_sellBue, i) >= close[0] for j = 0 to i-1 if array.get(count_of_orders, j) != 2 strategy_short := strategy_short + 1 array.set(count_of_orders, j, 2) SELL_amount := SELL_amount + 15 strategy.order(str.tostring(strategy_short),strategy.short, SELL_amount) SELL_amount := 0 break // добавить SMA и продавать при низходящем тренде plot(strategy.equity)
Cheat Code- Example 1; Short-Term; Follow the Trend
https://www.tradingview.com/script/IBh9X53T-Cheat-Code-Example-1-Short-Term-Follow-the-Trend/
CheatCode1
https://www.tradingview.com/u/CheatCode1/
302
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/ // © cpirkk //@version=5 //SUBSCRIBE TO CHEAT CODE!!! // // // //SUBSCRIBE TO CHEAT CODE!!! strategy("Cheat Codes Example", overlay = true) //RSI rsi = ta.rsi(close, 14) //ENTRY LC1 = ta.crossover(ta.sma(close,21), ta.sma(close,100)) LC2 = ta.sma(close, 200) > close if (LC1) and (LC2) strategy.entry("BULL CALL", strategy.long) SC1 = ta.sma(close, 200) < close SC2 = ta.crossunder(rsi, 55) if (SC1) and (SC2) strategy.entry("BEAR CALL", strategy.short) // BEST PAIRINGS: // BTC: 10M // MATIC: 10M // ETH: 10M // FIL: 10M // :)
AlphaTrend For ProfitView
https://www.tradingview.com/script/jVZbfu5m-AlphaTrend-For-ProfitView/
treigen
https://www.tradingview.com/u/treigen/
230
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // author © KivancOzbilgic // developer © KivancOzbilgic // pv additions, simplification and strategy conversion @ treigen //@version=5 strategy('AlphaTrend For ProfitView', overlay=true, calc_on_every_tick=true, process_orders_on_close=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=0.1, initial_capital=1000) coeff = input.float(1.5, 'Multiplier', step=0.1) AP = input(15, 'Common Period') ATR = ta.sma(ta.tr, AP) novolumedata = input(title='Change calculation (no volume data)?', defval=false) canshort = input.bool(true, title="Allow shorting") i_startTime = input.time(defval = timestamp("01 Jan 2014 00:00 +0000"), title = "Backtesting Start Time", inline="timestart", group='Backtesting') i_endTime = input.time(defval = timestamp("01 Jan 2100 23:59 +0000"), title = "Backtesting End Time", inline="timeend", group='Backtesting') timeCond = (time > i_startTime) and (time < i_endTime) pv_ex = input.string('', title='Exchange', tooltip='Leave empty to use the chart ticker instead (Warning: May differ from actual market name in some instances)', group='PV Settings') pv_sym = input.string('', title='Symbol', tooltip='Leave empty to use the chart ticker instead (Warning: May differ from actual market name in some instances)', group='PV Settings') pv_acc = input.string("", title="Account", group='PV Settings') pv_alert_long = input.string("", title="PV Alert Name Longs", group='PV Settings') pv_alert_short = input.string("", title="PV Alert Name Shorts", group='PV Settings') pv_alert_test = input.bool(false, title="Test Alerts", tooltip="Will immediately execute the alerts, so you may see what it sends. The first line on these test alerts will be excluded from any real alert triggers" ,group='PV Settings') upT = low - ATR * coeff downT = high + ATR * coeff AlphaTrend = 0.0 AlphaTrend := (novolumedata ? ta.rsi(close, AP) >= 50 : ta.mfi(hlc3, AP) >= 50) ? upT < nz(AlphaTrend[1]) ? nz(AlphaTrend[1]) : upT : downT > nz(AlphaTrend[1]) ? nz(AlphaTrend[1]) : downT k1 = plot(AlphaTrend, color=color.new(#0022FC, 0), linewidth=3) k2 = plot(AlphaTrend[2], color=color.new(#FC0400, 0), linewidth=3) buySignalk = ta.crossover(AlphaTrend, AlphaTrend[2]) sellSignalk = ta.crossunder(AlphaTrend, AlphaTrend[2]) var exsym = "" if barstate.isfirst exsym := pv_ex == "" ? "" : "ex=" + pv_ex + "," exsym := pv_sym == "" ? exsym : exsym + "sym=" + pv_sym + "," if barstate.isconfirmed and timeCond if strategy.position_size <= 0 and buySignalk strategy.entry("Long", strategy.long) alert(pv_alert_long + "(" + exsym + "acc=" + pv_acc + ")", alert.freq_once_per_bar_close) if strategy.position_size >= 0 and sellSignalk strategy.entry("Short", strategy.short, when=canshort) strategy.close("Long", when=not canshort) alert(pv_alert_short + "(" + exsym + "acc=" + pv_acc + ")", alert.freq_once_per_bar_close) // Only used for testing/debugging alert messages if pv_alert_test alert("<![Alert Test]!>\n" + pv_alert_long + "(" + exsym + "acc=" + pv_acc + ")", alert.freq_once_per_bar) alert("<![Alert Test]!>\n" + pv_alert_short + "(" + exsym + "acc=" + pv_acc + ")", alert.freq_once_per_bar)
[TH] Volatility Breakout
https://www.tradingview.com/script/lNDnJO17/
dokang
https://www.tradingview.com/u/dokang/
191
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/ // © dokang //@version=5 password = input.string("Your Password", title="Password", confirm = true) strategy("[TH] Volatility Breakout", overlay=true, initial_capital = 10000, currency = currency.KRW, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, process_orders_on_close = true, pyramiding = 2) import dokang/TradingHook/1 as TH if timeframe.period != "D" runtime.error("This strategy is only available in 1-day timeframe.") height = high-low k = input.float(0.5, minval = 0.0, step = 0.1) entry_price = close+height*k plot(entry_price, color = color.yellow, linewidth=2, offset = 1) var inTrade = false if barstate.islastconfirmedhistory inTrade := true if inTrade strategy.entry("Buy", strategy.long, stop = entry_price, alert_message = TH.buy_message(password, order_name = "Volatility Breakout Buy")) strategy.close("Buy", comment = "Sell",alert_message = TH.sell_message(password, "100%", order_name = "Volatility Breakout Sell"))
PB Trend Scalper
https://www.tradingview.com/script/KBT0Lc1W-PB-Trend-Scalper/
PatrickGwynBuckley
https://www.tradingview.com/u/PatrickGwynBuckley/
121
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/ // © PatrickGwynBuckley //@version=5 //var initialCapital = strategy.equity strategy("PB Trend Scalper", "PB Trend Scalper", overlay = true) shortma = input.int(55, title="quick ma's") longma = input.int(100, title="long ma's") ema55h = ta.ema(high, shortma) ema55l = ta.ema(low, shortma) ema200h = ta.rma(high, longma) ema200l = ta.rma(low, longma) stock = ta.stoch(close, high, low, 14) lev = input.int(3, title="leverage") hhVal = input.int(170, title="Highest high period") llVal = input.int(170, title="Lowest low period") hh = ta.highest(high, hhVal) ll = ta.lowest(low, llVal) //plot(stock) plot(hh, color=color.new(color.green, 50)) plot(ll, color=color.new(color.red, 50)) var float downtrade = 0 p = input.float(3.0, title="no trade zone") l = 3 emadistlong = ema200h + ((ema200h/100)*p) emadistshort = ema200l - ((ema200h/100)*p) plot(ema55h) plot(ema55l) ntl = plot(emadistlong, color=color.new(color.red, 10)) nts = plot(emadistshort, color=color.new(color.red, 10)) fill(ntl, nts, color=color.new(color.red, 90)) //position size EntryPrice = close //positionValue = initialCapital positionSize = (strategy.equity*lev) / EntryPrice //plot(strategy.equity) //standard short if ema55h < ema200l and close[2] < ema55l and close[1] > ema55l and high[1] < ema55h and close < ema55h and ema55h < emadistshort and strategy.opentrades == 0// and stock > 85 strategy.entry("short", strategy.short, qty=positionSize, comment="short") downtrade := 1 //reset count if (ta.crossunder(ema55h, ema200l)) and downtrade == 1 downtrade := 0 //standard long if ema55l > ema200h and close[2] > ema55h and close[1] < ema55h and low[1] > ema55l and close > ema55l and ema55l > emadistlong and strategy.opentrades <= 1// and stock < 15 strategy.entry("long", strategy.long, qty=positionSize, comment="long") downtrade := 0 //RESET COUNT ON MA CROSS if (ta.crossover(ema55l, ema200h)) and downtrade == 0 downtrade := 1 longclose2 = low < ll[1] or low < emadistshort //close < open and open<open[1] and open[2] < open[3] and open[3] < emadistshort//close < ta.lowest(low, 20)// shortclose2 = high > hh[1] or high>emadistlong//close > open and open>open[1] and open[2]>open[3] and open[3] > emadistlong//high > emadistlong//close > ta.highest(high, 20)// sl = 3.5 tp = input.float(6.9, title="take profit %") tp2 = 10 strategy.exit("long exit", "long", profit = (strategy.position_avg_price*(tp)))//, loss = (strategy.position_avg_price*(sl))) strategy.close("long", when = longclose2, comment = "long exit") //strategy.close("long", when = (downtrade == 1), comment = "long exit") //strategy.exit("long exit", "long2", profit = (strategy.position_avg_price*(tp2)))//, loss = (strategy.position_avg_price*(sl))) //strategy.close ("long2", when = longclose2, comment = "long exit") //strategy.close("long", when = (downtrade == 1), comment = "long exit") strategy.exit("short exit", "short", profit = (strategy.position_avg_price*(tp)))//, loss = (strategy.position_avg_price*(sl)))//, loss = 300) strategy.close("short", when = shortclose2, comment = "short exit") //strategy.close("short", when = (downtrade == 0), comment = "short exit") //strategy.exit("short exit", "short2", profit = (strategy.position_avg_price*(tp2)))//, loss = (strategy.position_avg_price*(sl))) //strategy.close ("short2", when = shortclose2, comment = "short exit") //strategy.close("short2", when = (downtrade == 0), comment = "short exit") //if (strategy.exit("long exit", "long")) //downtrade := 1 //else // downtrade := 0
EMA_TREND_CATCHER
https://www.tradingview.com/script/GzquH4OR/
pernath
https://www.tradingview.com/u/pernath/
141
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/ // © pernath //@version=5 strategy("TREND_CATCHER", overlay=true, commission_value=0.05, commission_type=strategy.commission.percent, initial_capital=1000) //#####variables############## profit_short=input(title='profit_short', defval=27) stop_short=input(title='stop_short', defval=2) stop_long=input(title='stop_long', defval=3) profit_long=input(title='profit_long', defval=35) media_1=input(title='media_1', defval=55) media_2=input(title='media_2', defval=100) resta_medias=input(title='resta_medias', defval=0) resta_medias2=input(title='resta_medias2', defval=0) RSI_periodos=input(title='RSI_periodos', defval=42) //###############VARIABLES################### //#####Alert##### id_bot = "" email_token = "" long_open ="" long_close ="" short_open ="" short_close ="" //# {{strategy.order.alert_message}} //############################# //############################# //###############EMA##############/ //plot(ta.ema(close, 1), title='ema 5', color=color.white) plot(ta.ema(close, 12), title='ema 12', color=color.white) plot(ta.ema(close, 25), title='ema 25', color=color.white) plot(ta.ema(close, 30), title='ema 30', color=color.white, linewidth=1) plot(ta.ema(close, 40), title='ema 40', color=color.white, linewidth=1) plot(ta.ema(close, 55), title='ema 55', color=color.orange, linewidth=1) plot(ta.ema(close, 100), title='ema 100', color=color.red, linewidth=1) plot(ta.ema(close, 200), title='ema 200', color=color.white, linewidth=3) //#############################/ //######VISUAL############# EMA50 = ta.ema(close, 55) EMA100 = ta.ema(close, 100) estado_medias=EMA50-EMA100 a = plot(EMA50, title="EMA(50)", color=color.orange, linewidth=1 ) b = plot(EMA100, title="EMA(100)", color=color.red, linewidth=1 ) var color col = na col := estado_medias>resta_medias ? color.green : color.red fill(a,b,color=col,transp=40) //######VISUAL############# Go_Short=(ta.crossunder(ta.ema(close,100),ta.ema(close,200))) Go_Long=((ta.crossover(ta.ema(close,55),ta.ema(close,100))and(ta.ema(close,12)>ta.ema(close,200)))) strategy.close("enter long", (Go_Short),alert_message=long_open) cancelar_short=((ta.crossunder(ta.ema(close,25),ta.ema(close,6)))) if Go_Short strategy.entry("enter short", strategy.short,1, alert_message=short_open) strategy.exit("cerrar short", "enter short", 1, profit=close*profit_short/100/syminfo.mintick, loss=close*stop_short/100/syminfo.mintick, alert_message=short_close) strategy.close("enter short", (Go_Long),alert_message=short_close) cancelar=((ta.crossunder(ta.ema(close,12),ta.ema(close,30)))) if Go_Long strategy.entry("enter long", strategy.long,1,alert_message=long_open) strategy.exit("cerrar long", "enter long", 1, profit=close*profit_long/100/syminfo.mintick, loss=close*stop_long/100/syminfo.mintick, alert_message=long_close) strategy.close("enter short", (cancelar_short),alert_message=short_close) strategy.close("enter long", (cancelar),alert_message=long_close) //posiciones abiertas bgcolor((strategy.position_size > 0 or strategy.position_size < 0) ? color.blue : na, transp=70)
Bollinger Bands + EMA 9
https://www.tradingview.com/script/Ff0DNTh1-Bollinger-Bands-EMA-9/
D499
https://www.tradingview.com/u/D499/
394
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/ // © D499 // -D4- //@version=5 strategy("Bollinger Bands + EMA 9", overlay = true, initial_capital = 1000, process_orders_on_close=true, default_qty_type = strategy.fixed) // Risk management inputs max_risk_percentage = input.float(1, "Max Risk (%)", 0.01, 99, 0.01, group = "Risk Management") riskType = input.string("%", title="Risk Type", options = ["%", "$"], group = "Risk Management") // Calculate Indicators bb_upper = ta.sma(close, 20) + 2 * ta.stdev(close, 20) bb_lower = ta.sma(close, 20) - 2 * ta.stdev(close, 20) ema = ta.ema(close, 9) // Define bull_candle and bear_candle candles bull_candle = close > open bear_candle = close < open // Check if entry signal is flashed and calculate order size barsSinceLastEntry() => strategy.opentrades > 0 ? bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades - 1) : na percent2money(price, percent) => price * percent / 100 * syminfo.pointvalue calcPositionSize(entry, stop_size) => risk = if riskType == "% from equity" strategy.equity * max_risk_percentage / 100 else max_risk_percentage risk / percent2money(entry, stop_size) stop = 0.0 entry = 0.0 tp = 0.0 if close[1] < bb_lower and bull_candle and strategy.position_size == 0 stop := low[1] entry := close tp := ema stop_size = (entry - stop) / stop order_size = calcPositionSize(close, stop_size) strategy.entry("LONG", strategy.long, math.abs(order_size)) if close[1] > bb_upper and bear_candle and strategy.position_size == 0 stop := high[1] entry := close tp := ema stop_size = (stop - entry) / stop order_size = calcPositionSize(close, stop_size) strategy.entry("SHORT", strategy.short, math.abs(order_size)) if strategy.position_size > 0 strategy.exit("LONG", limit = ema[barsSinceLastEntry()], stop = low[barsSinceLastEntry()+1], comment_profit = "✅", comment_loss = "❌") if strategy.position_size < 0 strategy.exit("SHORT", limit = ema[barsSinceLastEntry()], stop = high[barsSinceLastEntry()+1], comment_profit = "✅", comment_loss = "❌") // Plot Indicators plot(bb_upper, color=color.red) plot(bb_lower, color=color.green) plot(ema, color = color.white) // Plot trade visualization longEntryPlot = plot(strategy.position_size > 0 ? strategy.position_avg_price : na, color=color.new(color.white, 85), style=plot.style_linebr) longTargetPlot = plot(strategy.position_size > 0 ? ema[barsSinceLastEntry()] : na, color=color.new(color.green, 85), style=plot.style_linebr) longStopPlot = plot(strategy.position_size > 0 ? low[barsSinceLastEntry()+1] : na, color=color.new(color.red, 85), style=plot.style_linebr) fill(longEntryPlot, longTargetPlot, color=color.new(color.green, 85), editable=true) fill(longEntryPlot, longStopPlot, color=color.new(color.red, 85), editable=true) shortEntryPlot = plot(strategy.position_size < 0 ? strategy.position_avg_price : na, color=color.new(color.white, 85), style=plot.style_linebr) shortTargetPlot = plot(strategy.position_size < 0 ? ema[barsSinceLastEntry()] : na, color=color.new(color.green, 85), style=plot.style_linebr) shortStopPlot = plot(strategy.position_size < 0 ? high[barsSinceLastEntry()+1] : na, color=color.new(color.red, 85), style=plot.style_linebr) fill(shortEntryPlot, shortTargetPlot, color=color.new(color.green, 85), editable=true) fill(shortEntryPlot, shortStopPlot, color=color.new(color.red, 85), editable=true)
AlphaTrend Strategy
https://www.tradingview.com/script/uvkI3QJC/
only_fibonacci
https://www.tradingview.com/u/only_fibonacci/
644
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // author © KivancOzbilgic // developer © KivancOzbilgic //@version=5 strategy('AlphaTrend', shorttitle='AT', overlay=true, format=format.price, precision=2) coeff = input.float(1, 'Multiplier', step=0.1) AP = input(14, 'Common Period') ATR = ta.sma(ta.tr, AP) src = input(close) showsignalsk = input(title='Show Signals?', defval=true) novolumedata = input(title='Change calculation (no volume data)?', defval=false) upT = low - ATR * coeff downT = high + ATR * coeff AlphaTrend = 0.0 AlphaTrend := (novolumedata ? ta.rsi(src, AP) >= 50 : ta.mfi(hlc3, AP) >= 50) ? upT < nz(AlphaTrend[1]) ? nz(AlphaTrend[1]) : upT : downT > nz(AlphaTrend[1]) ? nz(AlphaTrend[1]) : downT color1 = AlphaTrend > AlphaTrend[2] ? #00E60F : AlphaTrend < AlphaTrend[2] ? #80000B : AlphaTrend[1] > AlphaTrend[3] ? #00E60F : #80000B k1 = plot(AlphaTrend, color=color.new(#0022FC, 0), linewidth=3) k2 = plot(AlphaTrend[2], color=color.new(#FC0400, 0), linewidth=3) fill(k1, k2, color=color1) buySignalk = ta.crossover(AlphaTrend, AlphaTrend[2]) sellSignalk = ta.crossunder(AlphaTrend, AlphaTrend[2]) K1 = ta.barssince(buySignalk) K2 = ta.barssince(sellSignalk) O1 = ta.barssince(buySignalk[1]) O2 = ta.barssince(sellSignalk[1]) //plotshape(buySignalk and showsignalsk and O1 > K2 ? AlphaTrend[2] * 0.9999 : na, title='BUY', text='BUY', location=location.absolute, style=shape.labelup, size=size.tiny, color=color.new(#0022FC, 0), textcolor=color.new(color.white, 0)) //plotshape(sellSignalk and showsignalsk and O2 > K1 ? AlphaTrend[2] * 1.0001 : na, title='SELL', text='SELL', location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.new(color.maroon, 0), textcolor=color.new(color.white, 0)) longCondition = buySignalk and showsignalsk and O1 > K2 if (longCondition) strategy.entry("BUY", strategy.long, comment = "BUY ENTRY") shortCondition = sellSignalk and showsignalsk and O2 > K1 if (shortCondition ) strategy.entry("SELL", strategy.short, comment = "SELL ENTRY") // alertcondition(buySignalk and O1 > K2, title='Potential BUY Alarm', message='BUY SIGNAL!') // alertcondition(sellSignalk and O2 > K1, title='Potential SELL Alarm', message='SELL SIGNAL!') // alertcondition(buySignalk[1] and O1[1] > K2, title='Confirmed BUY Alarm', message='BUY SIGNAL APPROVED!') // alertcondition(sellSignalk[1] and O2[1] > K1, title='Confirmed SELL Alarm', message='SELL SIGNAL APPROVED!') // alertcondition(ta.cross(close, AlphaTrend), title='Price Cross Alert', message='Price - AlphaTrend Crossing!') // alertcondition(ta.crossover(low, AlphaTrend), title='Candle CrossOver Alarm', message='LAST BAR is ABOVE ALPHATREND') // alertcondition(ta.crossunder(high, AlphaTrend), title='Candle CrossUnder Alarm', message='LAST BAR is BELOW ALPHATREND!') // alertcondition(ta.cross(close[1], AlphaTrend[1]), title='Price Cross Alert After Bar Close', message='Price - AlphaTrend Crossing!') // alertcondition(ta.crossover(low[1], AlphaTrend[1]), title='Candle CrossOver Alarm After Bar Close', message='LAST BAR is ABOVE ALPHATREND!') // alertcondition(ta.crossunder(high[1], AlphaTrend[1]), title='Candle CrossUnder Alarm After Bar Close', message='LAST BAR is BELOW ALPHATREND!')
Steven Primo's bollinger bands strategy
https://www.tradingview.com/script/vudV7MDh/
EduardoMattje
https://www.tradingview.com/u/EduardoMattje/
146
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/ // © EduardoMattje //@version=5 strategy("Steven Primo Bollinger Band", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100, process_orders_on_close=true, max_labels_count=500) // Constants var TRANSP = 5 var LONG = strategy.direction.long var SHORT = strategy.direction.short var ALL = strategy.direction.all var S_BOLLINGER = "Bollinger settings" var S_SETUP = "Setup settings" // Inputs src = math.log(input.source(close, "Price source", group=S_BOLLINGER)) var bollingerLength = input.int(20, "Bollinger length", minval=3, group=S_BOLLINGER, inline=S_BOLLINGER) var mult = input.float(0.382, "Standard deviation", minval=0.0, step=0.1, group=S_BOLLINGER, inline=S_BOLLINGER) var orderDirection = input.string(LONG, "Order direction", options=[LONG, SHORT, ALL], group=S_SETUP) var useTrailingStop = input.bool(false, "Use trailing stop", group=S_SETUP) var consecutiveCloses = input.int(5, "Consecutive closes for the setup", minval=1, group=S_SETUP, inline=S_SETUP) var extension = input.int(100, "Extension (%)", minval=100, group=S_SETUP, inline=S_SETUP) / 100.0 // Getting the BB [middle, upper, lower] = ta.bb(src, bollingerLength, mult) middle := math.exp(middle) upper := math.exp(upper) lower := math.exp(lower) // Plotting the BB var colorAtTheLimits = color.new(color.yellow, TRANSP) var colorAtTheMiddle = color.new(color.blue, TRANSP) plot(middle, "Middle band", colorAtTheMiddle, display=display.none) plot(upper, "Upper band", colorAtTheLimits) plot(lower, "Lower band", colorAtTheLimits) // MA setup // BB setup longComparison() => close >= upper shortComparison() => close <= lower var countLong = 0 var countShort = 0 incCount(count, comparison) => if comparison if count == 0 and comparison[1] 0 else count + 1 else 0 countLong := incCount(countLong, longComparison()) countShort := incCount(countShort, shortComparison()) // Pivot setup pivotHigh = ta.pivothigh(1, 1) pivotLow = ta.pivotlow(1, 1) pivotInRange(pivot, count) => ta.barssince(pivot) < count pvHighInRange = pivotInRange(pivotHigh, countLong) pvLowInRange = pivotInRange(pivotLow, countShort) // Entry price epLong = fixnan(pivotHigh) + syminfo.mintick epShort = fixnan(pivotLow) - syminfo.mintick // Stop price getRange(currentPrice, pivot, cond, tickMod) => if cond currentPrice else fixnan(pivot) + syminfo.mintick * tickMod var stopLong = 0.0 var stopShort = 0.0 stopLong := epShort stopShort := epLong // Target price getTarget(stopPrice, entryPrice) => totalTicks = (entryPrice - stopPrice) * extension entryPrice + totalTicks var targetLong = 0.0 var targetShort = 0.0 targetLong := getTarget(stopLong, epLong) targetShort := getTarget(stopShort, epShort) // Entry condition canBuy = countLong >= consecutiveCloses and pvHighInRange and high < epLong canSell = countShort >= consecutiveCloses and pvLowInRange and low > epShort // Entry orders inMarket = strategy.opentrades != 0 var plotTarget = 0.0 var plotStop = 0.0 strategy.risk.allow_entry_in(orderDirection) if not inMarket if canBuy plotTarget := targetLong plotStop := stopLong strategy.entry("long", strategy.long, stop=epLong, comment="Entry long") else if canSell plotTarget := targetShort plotStop := stopShort strategy.entry("short", strategy.short, stop=epShort, comment="Entry short") else strategy.cancel("long") strategy.cancel("short") // Exit orders strategy.exit("long", "long", stop=stopLong, limit=targetLong, comment="Exit long") strategy.exit("short", "short", stop=stopShort, limit=targetShort, comment="Exit short") else countLong := 0 countShort := 0 // Trailing stop if useTrailingStop and inMarket if strategy.position_entry_name == "long" strategy.exit("long", "long", stop=stopLong, limit=plotTarget, comment="Exit long", when=stopLong > plotStop) plotStop := stopLong else strategy.exit("short", "short", stop=stopShort, limit=plotTarget, comment="Exit short", when=stopShort < plotStop) plotStop := stopShort // Plot exit plotCond(price) => inMarket ? price : inMarket[1] ? price[1] : na plot(plotCond(plotStop), "Stop loss", color.red, style=plot.style_linebr) plot(plotCond(plotTarget), "Target", color.teal, style=plot.style_linebr)
Traling.SL.Target
https://www.tradingview.com/script/4jxYYaGU-Traling-SL-Target/
Sharad_Gaikwad
https://www.tradingview.com/u/Sharad_Gaikwad/
733
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/ // © Sharad_Gaikwad //@version=5 strategy("Traling.SL.Target", overlay=true, process_orders_on_close = true, max_labels_count = 500) // << Parameters section { _1 = input.bool(title = "━━━━━━━ ↓ Pivot parameters for trade ↓ ━━━━━━━", defval = false) fast_len = input.int(title = 'Fast len', defval = 20) slow_len = input.int(title = 'Slow len', defval = 50) label_bg_color = input.color(title = 'BG color for ongoing trade SL/Target label', defval=color.white) sl_target_method = input.string(title = 'Method to be used for SL/Target trailing', defval='% Based Target and SL', options = ['% Based Target and SL','Fix point Based Target and SL']) _2 = input.bool(title = "━━━━━━━ ↓ % Based Target and SL ↓ ━━━━━━━", defval = true) initial_profit_percent = input.float(title = 'Inital profit %', defval = 1) / 100 initial_sl_percent = input.float(title = 'Inital SL %', defval = 1) / 100 initiate_trailing_percent = input.float(title = 'Initiate trailing %', defval = 0.5, tooltip = 'Initiate trailing of target and SL after change in price in % after taking trade') / 100 trail_profit_percent = input.float(title = 'Trail profit by %', defval = 0.3) / 100 trail_sl_percent = input.float(title = 'Trail SL by %', defval = 0.3) / 100 _3 = input.bool(title = "━━━━━━━ ↓ Fix point Based Target and SL ↓ ━━━━━━━", defval = false) initial_profit_points = input.float(title = 'Inital profit target points', defval = 100) initial_sl_points = input.float(title = 'Inital SL points', defval = 50) initiate_trailing_points = input.float(title = 'Initiate trailing points', defval = 60, tooltip = 'Initiate trailing of target and SL after change in price in points after taking trade') trail_profit_points = input.float(title = 'Trail profit by points', defval = 25) trail_sl_points = input.float(title = 'Trail SL by %', defval = 30) // } Parameters section >> // } << Common function { tab = table.new(position=position.bottom_right, columns=7, rows=200,frame_color = color.yellow, frame_width = 1) msg(int row, int col, string msg_str, clr=color.blue) => table.cell(table_id=tab, column=col, row=row, text=msg_str, text_color=clr) getVal(val) => ret_val = na(val) ? 0 : val t(val) => str.tostring(val, "0.00") timeToString(int _t) => str.tostring(dayofmonth(_t), '00') + '/' + str.tostring(month(_t), '00') + '/' + str.tostring(year(_t), '0000') + ' ' + str.tostring(hour(_t), '00') + ':' + str.tostring(minute(_t), '00') + ':' + str.tostring(second(_t), '00') // } Common functions>> // Variable declarations { percent_based = sl_target_method == '% Based Target and SL' ? true : false var initial_long_entry_price = float(na) var initial_short_entry_price = float(na) var long_target = float(na) var long_sl = float(na) var short_target = float(na) var short_sl = float(na) var long_entry_price = float(na) var short_entry_price = float(na) var initial_long_percent_target = float(na) var initial_long_percent_sl = float(na) var initial_long_point_target = float(na) var initial_long_point_sl = float(na) var initial_short_percent_target = float(na) var initial_short_percent_sl = float(na) var initial_short_point_target = float(na) var initial_short_point_sl = float(na) var is_long = bool(na) var is_short = bool(na) var trail_long_iteration = int(na) var trail_short_iteration = int(na) // } // derive important variable values // Strategy logic fast_ema = ta.ema(close, fast_len) slow_ema = ta.ema(close, slow_len) plot(fast_ema, color = color.red) plot(slow_ema, color = color.green) go_long = ta.crossover(fast_ema, slow_ema) and strategy.position_size == 0 go_short = ta.crossunder(fast_ema, slow_ema) and strategy.position_size == 0 // barcolor(ph ? color.purple : na, offset = -lb) // barcolor(pl ? color.yellow : na, offset = -lb) // barcolor(ph ? color.white : na) // barcolor(pl ? color.blue : na) // //trailing logic for long long_trailing_point = percent_based ? (close >= long_entry_price + (long_entry_price * initiate_trailing_percent)) : (close >= long_entry_price + initiate_trailing_points) short_trailing_point = percent_based ? (close <= short_entry_price - (short_entry_price * initiate_trailing_percent)) : (close >= short_entry_price - initiate_trailing_points) if(is_long and long_trailing_point) // initial_long_percent_target = initial_long_percent_target + (initial_long_percent_target * trail_profit_percent) // initial_long_percent_sl = initial_long_percent_sl - (initial_long_percent_sl * trail_sl_percent) // initial_long_point_target = initial_long_point_target + trail_profit_points // initial_long_point_sl = initial_long_point_sl - trail_sl_points trail_long_iteration := trail_long_iteration + 1 long_target := percent_based ? (long_target + (long_target * trail_profit_percent)) : (long_target + trail_profit_points) long_sl := percent_based ? (long_sl + (long_sl * trail_sl_percent)) : (long_sl + trail_sl_points) long_entry_price := percent_based ? (long_entry_price + (long_entry_price * initiate_trailing_percent)) : (long_entry_price + initiate_trailing_points) if(is_short and short_trailing_point) // initial_short_percent_target = initial_short_percent_target - (initial_short_percent_target * trail_profit_percent) // initial_short_percent_sl = initial_short_percent_sl + (initial_short_percent_sl * trail_sl_percent) // initial_short_point_target = initial_short_point_target - trail_profit_points // initial_short_point_sl = initial_short_point_sl + trail_sl_points trail_short_iteration := trail_short_iteration + 1 short_target := percent_based ? (short_target - (short_target * trail_profit_percent)) : (short_target - trail_profit_points) short_sl := percent_based ? (short_sl - (short_sl * trail_sl_percent)) : (short_sl - trail_sl_points) short_entry_price := percent_based ? (short_entry_price - (short_entry_price * initiate_trailing_percent)) : (short_entry_price - initiate_trailing_points) if(go_long) is_long := true is_short := false trail_long_iteration := 0 trail_short_iteration := 0 initial_long_entry_price := close long_entry_price := close initial_long_percent_target := close + (close * initial_profit_percent) initial_long_percent_sl := close - (close * initial_sl_percent) initial_long_point_target := close + initial_profit_points initial_long_point_sl := close - initial_sl_points long_target := percent_based ? initial_long_percent_target : initial_long_point_target long_sl := percent_based ? initial_long_percent_sl : initial_long_point_sl strategy.entry(id = 'Long', direction = strategy.long) if(go_short) is_long := false is_short := true trail_long_iteration := 0 trail_short_iteration := 0 initial_short_entry_price := close short_entry_price := close initial_short_percent_target := close - (close * initial_profit_percent) initial_short_percent_sl := close + (close * initial_sl_percent) initial_short_point_target := close - initial_profit_points initial_short_point_sl := close + initial_sl_points short_target := percent_based ? initial_short_percent_target : initial_short_point_target short_sl := percent_based ? initial_short_percent_sl : initial_short_point_sl strategy.entry(id = 'Short', direction = strategy.short) method = percent_based ? '% Based' : 'Fixed Points' long_tooltip = 'Long @ ' + timeToString(time) + '\n' + 'Method : ' + method + '\n' + 'Initial Trade Price: ' + t(initial_long_entry_price) + '\n' + 'Inital Target : ' + t(long_target) + '\n' + 'Inital SL : ' + t(long_sl) short_tooltip = 'Short @ ' + timeToString(time) + '\n' + 'Method : ' + method + '\n' + 'Initial Trade Price: ' + t(initial_short_entry_price) + '\n' + 'Inital Target : ' + t(short_target) + '\n' + 'Inital SL : ' + t(short_sl) label.new(go_long ? bar_index : na, go_long ? bar_index : na, style = label.style_diamond, yloc = yloc.belowbar, color = color.green, size=size.tiny, tooltip = long_tooltip) label.new(go_short ? bar_index : na, go_short ? bar_index : na, style = label.style_diamond, yloc = yloc.abovebar, color = color.red, size=size.tiny, tooltip = short_tooltip) trail_long_tooltip = 'Trail @ ' + timeToString(time) + '\n' + 'Iteration no : ' + t(trail_long_iteration) + '\n' + 'New Target : ' + t(long_target) + '\n' + 'New SL : ' + t(long_sl) trail_short_tooltip = 'Trail @ ' + timeToString(time) + '\n' + 'Iteration no : ' + t(trail_short_iteration) + '\n' + 'New Target : ' + t(short_target) + '\n' + 'New SL : ' + t(short_sl) label.new(is_long and long_trailing_point and strategy.position_size > 0 ? bar_index : na, is_long and long_trailing_point and strategy.position_size > 0 ? bar_index : na, text = str.tostring(trail_long_iteration), style = label.style_circle, textcolor = color.white, yloc = yloc.belowbar, color = color.green, size=size.tiny, tooltip = trail_long_tooltip) label.new(is_short and short_trailing_point and strategy.position_size < 0 ? bar_index : na, is_short and short_trailing_point and strategy.position_size < 0 ? bar_index : na, text = str.tostring(trail_short_iteration), style = label.style_circle, textcolor = color.white, yloc = yloc.abovebar, color = color.red, size=size.tiny, tooltip = trail_short_tooltip) strategy.close(id = 'Long', when = close <= long_sl, comment = 'SL') strategy.close(id = 'Short', when = close >= short_sl, comment = 'SL') strategy.close(id = 'Long', when = close >= long_target, comment = 'Target') strategy.close(id = 'Short', when = close <= short_target, comment = 'Target') no_of_labels = 1 label_q(_array, _val) => array.push(_array, _val) _return = array.shift(_array) var target_label = float(na) var sl_label = float(na) if(strategy.position_size > 0) target_label := long_target sl_label := long_sl else if(strategy.position_size < 0) target_label := short_target sl_label := short_sl else target_label := float(na) sl_label := float(na) var label[] target_array = array.new_label(no_of_labels) label.delete(label_q(target_array, label.new(bar_index, target_label, "Target:"+t(target_label), style = label.style_label_down, color = label_bg_color, size=size.small, textcolor = color.green))) var label[] sl_array = array.new_label(no_of_labels) label.delete(label_q(sl_array, label.new(bar_index, sl_label, "SL:"+t(sl_label), style = label.style_label_up, color = label_bg_color, size=size.small, textcolor = color.red)))
BB KANNEMAN
https://www.tradingview.com/script/HQxSGkEi/
samuelkanneman
https://www.tradingview.com/u/samuelkanneman/
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/ // © samuelkanneman //@version=5 strategy('MI_BB ', overlay=true) i_startTime = input.time(title='Start Date Filter', defval=timestamp('01 Nov 2020 13:30 +0000'), tooltip='Date & time to begin trading from') i_endTime = input.time(title='End Date Filter', defval=timestamp('1 Nov 2022 19:30 +0000'), tooltip='Date & time to stop trading') dateFilter = time >= i_startTime and time <= i_endTime longitud = input(20, title='Longitud') Desv = input.float(2.0, title='Desvio estandar', step=0.1) fuente = input(close, title='Fuente') TakeP = input.float(5.0, title='Take Profit', step=0.1) StopL = input.float(1.0, title='Stop Loss', step=0.1) var SL = 0.0 var TP = 0.0 [banda_central, banda_sup, banda_inf] = ta.bb(fuente, longitud, Desv) comprado = strategy.position_size > 0 vendido = strategy.position_size < 0 if not vendido and not comprado and dateFilter // Short if close >= banda_sup //cantidad= (strategy.equity/close) strategy.entry('venta', strategy.short) SL := close * (1 + StopL / 100) TP := close*(1-TakeP/100) //Long else if close <= banda_inf //cantidad= (strategy.equity/close) strategy.entry('compra', strategy.long) SL := close * (1 - StopL / 100) TP := close*(1+TakeP/100) //cierrres short if close <= TP and vendido strategy.close ("venta" , comment="Salto TP") if close <= banda_inf and vendido strategy.close ("venta" , comment="Banda Inferior") if close >= SL and vendido strategy.close ("venta" , comment="Salto SL") //cierre long if close >= TP and comprado strategy.close ("compra" , comment="Salto TP") if close >= banda_sup and comprado strategy.close ("compra" , comment="Banda Superior") if close <= SL and comprado strategy.close ("compra" , comment="Salto SL") p1 = plot(banda_central) p2 = plot(banda_sup) p3 = plot(banda_inf) fill(p2, p3, transp=90)
ROoT
https://www.tradingview.com/script/jubSkjKS-ROoT/
realisticDove62527
https://www.tradingview.com/u/realisticDove62527/
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/ // © realisticDove62527 //@version=5 strategy("ROoT", overlay=true, margin_long=1, margin_short=1) longCondition = ta.crossover(ta.sma(close, 5), ta.vwap(hlc3)) if (longCondition) strategy.entry("BUY", strategy.long) shortCondition = ta.crossunder(ta.sma(close, 5), ta.vwap(hlc3)) if (shortCondition) strategy.entry("SELL", strategy.short) stoploss = ta.ema(close, 9)
Simple_Pyramiding
https://www.tradingview.com/script/t6cNLqDN-Simple-Pyramiding/
A3Sh
https://www.tradingview.com/u/A3Sh/
90
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/ // © A3Sh //@version=5 strategy("Simple_Pyramiding", overlay=true, pyramiding=99, initial_capital=500, default_qty_type=strategy.percent_of_equity, commission_type=strategy.commission.percent, commission_value=0.075, close_entries_rule='FIFO') // Study of a Simple DCA strategy that opens a position every day at a specified time. // A position is opened at the start time of the Timeframe. // Positions exit individually when the take profit level is triggered. // Option to activate Stop Loss and/or Position exit at the end of the Timeframe // Backtest Window start_time = input.time(defval=timestamp("01 April 2021 20:00"), group = "Backtest Window", title="Start Time") end_time = input.time(defval=timestamp("01 Aug 2022 20:00"), group = "Backtest Window", title="End Time") window() => time >= start_time and time <= end_time // Inputs posCount = input.int (6, group = "Risk", title = "Max Amount of DCA Entries") takeProfit = input.float (2.5, group = "Risk", title = "Take Profit %") slSwitch = input.bool (true, group = "Risk", title = "Activate Stop Loss") stopLoss = input.float (9, group = "Risk", title = "Stop Loss %") sessionTime = input.session("1800-1700", group = "DCA Settings", title = "DCA Order Timeframe", tooltip="Open order at the start/If ativated, close order at the end") exitDCA = input.bool (false, group = "DCA Settings", title = "Exit DCA Entry at end of Timeframe") // Order size based on max amount of pyramid orders q = (strategy.equity / posCount) / open // Timeframe for opening and closing a DCA order // example taken from https://stackoverflow.com/questions/69230164/pinescript-basic-question-open-a-trade-at-a-set-time-each-day t = time("D", sessionTime) isStart = na(t[1]) and not na(t) or t[1] < t isEnd = na(t) and not na(t[1]) or t[1] < t bgcolor(t ? color.new(color.blue,95) : na, title = " TimeFrame Color") // Create DCA Entries entry_price = 0.0 if isStart and window() for i = 0 to strategy.opentrades if strategy.opentrades == i entry_price := close entry_id = "PE_" + str.tostring(i + 1) strategy.entry(id = entry_id, direction=strategy.long, limit=entry_price, qty=q) if strategy.opentrades == posCount break //Exit DCA Entries when take profit or stop loss is triggered if strategy.opentrades > 0 and window() for i = 0 to strategy.opentrades exit_from = "PE_" + str.tostring(i + 1) exit_id = "Exit_" + str.tostring(i + 1) strategy.exit(id= exit_id, from_entry= exit_from, profit = close * takeProfit / 100 / syminfo.mintick, loss = slSwitch ? close * stopLoss /100 / syminfo.mintick :na) //Exit DCA Entries at end of DCA Timeframe if strategy.opentrades > 0 and exitDCA and isEnd and window() for i = 0 to strategy.opentrades exit_from = "PE_" + str.tostring(i + 1) exit_id = "Exit_" + str.tostring(i + 1) strategy.exit(id= exit_id, from_entry= exit_from, stop = close)
Infiten Slope Strategy
https://www.tradingview.com/script/pzZu13Q1-Infiten-Slope-Strategy/
spiritualhealer117
https://www.tradingview.com/u/spiritualhealer117/
60
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/ // © spiritualhealer117 //@version=4 strategy("Infiten Slope Strategy", overlay=false,calc_on_every_tick = true, default_qty_type=strategy.percent_of_equity, default_qty_value = 100) // //TIME RESTRICT FOR BACKTESTING { // inDateRange = (time >= timestamp(syminfo.timezone, 2003, // 1, 1, 0, 0)) and // (time < timestamp(syminfo.timezone, 2021, 5, 25, 0, 0)) // //} //OPTIMAL PARAMETERS { daysback = 30 volumesens = 1.618 //} //Calculating Exhaustion and Exhaustion Moving Average { clh = close+low+high exhaustion = (clh-sma(clh,daysback))/sma(clh,daysback) exhaustionSma = sma(exhaustion,daysback) //} //Long Term Moving Averages for sell signals { red = sma(close,300) white = sma(close,150) blue = sma(close,50) plot(red,color=color.red) plot(white,color=color.white) plot(blue,color=color.blue) //} //MACD Calculation { 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) // 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 //} //SIGMOID Bottom { timeAdjust = 300/sma(close,500) //} //RSI bottom { len = input(14, minval=1, title="Length") up = rma(max(change(src), 0), len) down = rma(-min(change(close), 0), len) rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down)) //} //Entry and exit conditions { //Sell conditions bigVolume = sma(volume,30)*volumesens sellcond1 = crossunder(exhaustion,exhaustionSma) and volume > bigVolume sellcond2 = crossunder(macd,signal) and volume > bigVolume midtermsellcond1 = crossunder(blue,white) longtermsellcond1 = white < red //Buy conditions buycond = crossover(exhaustion,exhaustionSma) and not longtermsellcond1 buycond2 = rsi < 30 buycond3 = crossover(blue,white) and longtermsellcond1 //} //Backtest Run Buy/Sell Commands { strategy.entry("buycond",true, when=buycond and bigVolume) strategy.entry("buycond2",true, when=buycond2 and bigVolume) strategy.close_all(when=sellcond1,comment="short term sell signal 1") strategy.close_all(when=midtermsellcond1, comment="mid term sell signal 1") strategy.close_all(when=longtermsellcond1, comment="long term sell signal 1") strategy.close_all(when=sellcond2, comment="short term sell signal 2") plot(strategy.position_size) //Sell on last tested day (only for data collection) //strategy.close_all(when=not inDateRange) //}
Moving Average Crossover Strategy
https://www.tradingview.com/script/Ip667jzb-Moving-Average-Crossover-Strategy/
Decam9
https://www.tradingview.com/u/Decam9/
216
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/ // © Decam9 //@version=5 strategy(title = "Moving Average Crossover", shorttitle = "MA Crossover Strategy", overlay=true, initial_capital = 100000,default_qty_type = strategy.percent_of_equity, default_qty_value = 10) //Moving Average Inputs EMA1 = input.int(title="Fast EMA", group = "Moving Averages:", inline = "EMAs", defval=5, minval = 1) isDynamicEMA = input.bool(title = "Dynamic Exponential Moving Average?", defval = true, inline = "EMAs", group = "Moving Averages:", tooltip = "Changes the source of the MA based on trend") SMA1 = input.int(title = "Slow SMA", group = "Moving Averages:", inline = "SMAs", defval = 10, minval = 1) isDynamicSMA = input.bool(title = "Dynamic Simple Moving Average?", defval = false, inline = "SMAs", group = "Moving Averages:", tooltip = "Changes the source of the MA based on trend") SMA2 = input.int(title="Trend Determining SMA", group = "Moving Averages:", inline = "MAs", defval=13, minval = 1) //Moving Averages Trend = ta.sma(close, SMA2) Fast = ta.ema(isDynamicEMA ? (close > Trend ? low : high) : close, EMA1) Slow = ta.sma(isDynamicSMA ? (close > Trend ? low : high) : close, SMA1) //Allowed Entries islong = input.bool(title = "Long", group = "Allowed Entries:", inline = "Entries",defval = true) isshort = input.bool(title = "Short", group = "Allowed Entries:", inline = "Entries", defval= true) //Entry Long Conditions buycond = input.string(title="Buy when", group = "Entry Conditions:", inline = "Conditions",defval="Fast-Slow Crossing", options=["Fast-Slow Crossing", "Fast-Trend Crossing","Slow-Trend Crossing"]) intrendbuy = input.bool(title = "In trend", defval = true, group = "Entry Conditions:", inline = "Conditions", tooltip = "In trend if price is above SMA 2") //Entry Short Conditions sellcond = input.string(title="Sell when", group = "Entry Conditions:", inline = "Conditions2",defval="Fast-Slow Crossing", options=["Fast-Slow Crossing", "Fast-Trend Crossing","Slow-Trend Crossing"]) intrendsell = input.bool(title = "In trend",defval = true, group = "Entry Conditions:", inline = "Conditions2", tooltip = "In trend if price is below SMA 2?") //Exit Long Conditions closebuy = input.string(title="Close long when", group = "Exit Conditions:", defval="Fast-Slow Crossing", options=["Fast-Slow Crossing", "Fast-Trend Crossing","Slow-Trend Crossing"]) //Exit Short Conditions closeshort = input.string(title="Close short when", group = "Exit Conditions:", defval="Fast-Slow Crossing", options=["Fast-Slow Crossing", "Fast-Trend Crossing","Slow-Trend Crossing"]) //Filters filterlong =input.bool(title = "Long Entries", inline = 'linefilt', group = 'Apply Filters to', defval = true) filtershort =input.bool(title = "Short Entries", inline = 'linefilt', group = 'Apply Filters to', defval = true) filterend =input.bool(title = "Exits", inline = 'linefilt', group = 'Apply Filters to', defval = true) usevol =input.bool(title = "", inline = 'linefiltvol', group = 'Relative Volume Filter:', defval = false) rvol = input.int(title = "Volume >", inline = 'linefiltvol', group = 'Relative Volume Filter:', defval = 1) len_vol = input.int(title = "Avg. Volume Over Period", inline = 'linefiltvol', group = 'Relative Volume Filter:', defval = 30, minval = 1, tooltip="The current volume must be greater than N times the M-period average volume.") useatr =input.bool(title = "", inline = 'linefiltatr', group = 'Volatility Filter:', defval = false) len_atr1 = input.int(title = "ATR", inline = 'linefiltatr', group = 'Volatility Filter:', defval = 5, minval = 1) len_atr2 = input.int(title = "> ATR", inline = 'linefiltatr', group = 'Volatility Filter:', defval = 30, minval = 1, tooltip="The N-period ATR must be greater than the M-period ATR.") usersi =input.bool(title = "", inline = 'linersi', group = 'Overbought/Oversold Filter:', defval = false) rsitrhs1 = input.int(title = "", inline = 'linersi', group = 'Overbought/Oversold Filter:', defval = 0, minval=0, maxval=100) rsitrhs2 = input.int(title = "< RSI (14) <", inline = 'linersi', group = 'Overbought/Oversold Filter:', defval = 100, minval=0, maxval=100, tooltip="RSI(14) must be in the range between N and M.") issl = input.bool(title = "SL", inline = 'linesl1', group = 'Stop Loss / Take Profit:', defval = false) slpercent = input.float(title = ", %", inline = 'linesl1', group = 'Stop Loss / Take Profit:', defval = 10, minval=0.0) istrailing = input.bool(title = "Trailing", inline = 'linesl1', group = 'Stop Loss / Take Profit:', defval = false) istp = input.bool(title = "TP", inline = 'linetp1', group = 'Stop Loss / Take Profit:', defval = false) tppercent = input.float(title = ", %", inline = 'linetp1', group = 'Stop Loss / Take Profit:', defval = 20) //Conditions for Crossing fscrossup = ta.crossover(Fast,Slow) fscrossdw = ta.crossunder(Fast,Slow) ftcrossup = ta.crossover(Fast,Trend) ftcrossdw = ta.crossunder(Fast,Trend) stcrossup = ta.crossover(Slow,Trend) stcrossdw = ta.crossunder(Slow,Trend) //Defining in trend uptrend = Fast >= Slow and Slow >= Trend downtrend = Fast <= Slow and Slow <= Trend justCrossed = ta.cross(Fast,Slow) or ta.cross(Slow,Trend) //Entry Signals crosslong = if intrendbuy (buycond =="Fast-Slow Crossing" and uptrend ? fscrossup:(buycond =="Fast-Trend Crossing" and uptrend ? ftcrossup:(buycond == "Slow-Trend Crossing" and uptrend ? stcrossup : na))) else (buycond =="Fast-Slow Crossing"?fscrossup:(buycond=="Fast-Trend Crossing"?ftcrossup:stcrossup)) crossshort = if intrendsell (sellcond =="Fast-Slow Crossing" and downtrend ? fscrossdw:(sellcond =="Fast-Trend Crossing" and downtrend ? ftcrossdw:(sellcond == "Slow-Trend Crossing" and downtrend ? stcrossdw : na))) else (sellcond =="Fast-Slow Crossing"?fscrossdw:(buycond=="Fast-Trend Crossing"?ftcrossdw:stcrossdw)) crossexitlong = (closebuy =="Fast-Slow Crossing"?fscrossdw:(closebuy=="Fast-Trend Crossing"?ftcrossdw:stcrossdw)) crossexitshort = (closeshort =="Fast-Slow Crossing"?fscrossup:(closeshort=="Fast-Trend Crossing"?ftcrossup:stcrossup)) // Filters rsifilter = usersi?(ta.rsi(close,14) > rsitrhs1 and ta.rsi(close,14) < rsitrhs2):true volatilityfilter = useatr?(ta.atr(len_atr1) > ta.atr(len_atr2)):true volumefilter = usevol?(volume > rvol*ta.sma(volume,len_vol)):true totalfilter = volatilityfilter and volumefilter and rsifilter //Filtered signals golong = crosslong and islong and (filterlong?totalfilter:true) goshort = crossshort and isshort and (filtershort?totalfilter:true) endlong = crossexitlong and (filterend?totalfilter:true) endshort = crossexitshort and (filterend?totalfilter:true) // Entry price and TP startprice = ta.valuewhen(condition=golong or goshort, source=close, occurrence=0) pm = golong?1:goshort?-1:1/math.sign(strategy.position_size) takeprofit = startprice*(1+pm*tppercent*0.01) // fixed stop loss stoploss = startprice * (1-pm*slpercent*0.01) // trailing stop loss if istrailing and strategy.position_size>0 stoploss := math.max(close*(1 - slpercent*0.01),stoploss[1]) else if istrailing and strategy.position_size<0 stoploss := math.min(close*(1 + slpercent*0.01),stoploss[1]) if golong and islong strategy.entry("long", strategy.long ) if goshort and isshort strategy.entry("short", strategy.short) if endlong strategy.close("long") if endshort strategy.close("short") // Exit via SL or TP strategy.exit(id="sl/tp long", from_entry="long", stop=issl?stoploss:na, limit=istp?takeprofit:na) strategy.exit(id="sl/tp short",from_entry="short",stop=issl?stoploss:na, limit=istp?takeprofit:na)
Optimised RSI strategy for Reversals (by Coinrule)
https://www.tradingview.com/script/yVT696NT-Optimised-RSI-strategy-for-Reversals-by-Coinrule/
Coinrule
https://www.tradingview.com/u/Coinrule/
62
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/ // © Coinrule //@version=4 strategy(shorttitle='MARSI',title='Moving Average', overlay=true, initial_capital=1000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100) //Backtest dates 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 = 2020, title = "From Year", type = input.integer, minval = 1970) thruMonth = input(defval = 1, title = "Thru Month", type = input.integer, minval = 1, maxval = 12) thruDay = input(defval = 1, title = "Thru Day", type = input.integer, minval = 1, maxval = 31) thruYear = input(defval = 2112, title = "Thru Year", type = input.integer, minval = 1970) showDate = input(defval = true, title = "Show Date Range", type = input.bool) 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" //MA inputs and calculations inshort=input(9, title='MA short period') MAshort= sma(close, inshort) // RSI inputs and calculations lengthRSI = input(14, title = 'RSI period', minval=1) RSI = rsi(close, lengthRSI) //Entry strategy.entry(id="long", long = true, when = MAshort<close and RSI<40 and window()) //Exit longLossPerc = input(title="Long Stop Loss (%)", type=input.float, minval=0.0, step=0.1, defval=1.5) * 0.01 longTakePerc = input(title="Long Take Profit (%)", type=input.float, minval=0.0, step=0.1, defval=3) * 0.01 longSL = strategy.position_avg_price * (1 - longLossPerc) longTP = strategy.position_avg_price * (1 + longTakePerc) if (strategy.position_size > 0 and window()) strategy.exit(id="TP/SL", stop=longSL, limit=longTP) bgcolor(color = showDate and window() ? color.gray : na, transp = 90) plot(MAshort, color=color.purple, linewidth=4)
Parabolic SAR Heikin Ashi MTF Candle Scalper
https://www.tradingview.com/script/U7uneSDz-Parabolic-SAR-Heikin-Ashi-MTF-Candle-Scalper/
exlux99
https://www.tradingview.com/u/exlux99/
169
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("SAR HA MTF Scalper ", overlay=true) timeframe=input.timeframe('15', "Resolution") close_mtf = request.security(ticker.heikinashi(syminfo.tickerid), timeframe, close) open_mtf = request.security(ticker.heikinashi(syminfo.tickerid), timeframe, open) high_mtf = request.security(ticker.heikinashi(syminfo.tickerid), timeframe, high) low_mtf = request.security(ticker.heikinashi(syminfo.tickerid), timeframe, low) //////////////// // The same on Pine pine_sar(start, inc, max) => var float result = na var float maxMin = na var float acceleration = na var bool isBelow = na bool isFirstTrendBar = false if bar_index == 1 if close_mtf > close_mtf[1] isBelow := true maxMin := high_mtf result := low_mtf[1] else isBelow := false maxMin := low_mtf result := high_mtf[1] isFirstTrendBar := true acceleration := start result := result + acceleration * (maxMin - result) if isBelow if result > low_mtf isFirstTrendBar := true isBelow := false result := math.max(high_mtf, maxMin) maxMin := low_mtf acceleration := start else if result < high_mtf isFirstTrendBar := true isBelow := true result := math.min(low_mtf, maxMin) maxMin := high_mtf acceleration := start if not isFirstTrendBar if isBelow if high_mtf > maxMin maxMin := high_mtf acceleration := math.min(acceleration + inc, max) else if low_mtf < maxMin maxMin := low_mtf acceleration := math.min(acceleration + inc, max) if isBelow result := math.min(result, low_mtf[1]) if bar_index > 1 result := math.min(result, low_mtf[2]) else result := math.max(result, high_mtf[1]) if bar_index > 1 result := math.max(result, high_mtf[2]) result //////////////// start = input.float(0.05, step=0.01) increment = input.float(0.02,step=0.01) maximum = input.float(0.2, "Max Value",step=0.01) out = pine_sar(start,increment,maximum) long = close_mtf[1] > out short = close_mtf[1] < out entry_time = input.session(title='Entry time', defval='0900-1000') exit_time = input.session(title='Exit time', defval='1200-1600') BarInSession(sess) => not na(time(timeframe.period, sess)) entry_candle_time = BarInSession(entry_time) exit_candle_time = BarInSession(exit_time) if(entry_candle_time) strategy.entry("long",strategy.long,when=long) strategy.entry("short",strategy.short,when=short) if(exit_candle_time) strategy.close_all()
Oversold RSI with tight SL Strategy (by Coinrule)
https://www.tradingview.com/script/Fuzmd3jp-Oversold-RSI-with-tight-SL-Strategy-by-Coinrule/
Coinrule
https://www.tradingview.com/u/Coinrule/
94
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/ // © brodieCoinrule //@version=4 strategy(shorttitle='Oversold RSI with tight SL',title='Oversold RSI with tight SL Strategy (by Coinrule)', overlay=true, initial_capital = 1000, process_orders_on_close=true, default_qty_type = strategy.percent_of_equity, default_qty_value = 50, commission_type=strategy.commission.percent, commission_value=0.1) //Backtest dates 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 = 2020, title = "From Year", type = input.integer, minval = 1970) thruMonth = input(defval = 1, title = "Thru Month", type = input.integer, minval = 1, maxval = 12) thruDay = input(defval = 1, title = "Thru Day", type = input.integer, minval = 1, maxval = 31) thruYear = input(defval = 2112, title = "Thru Year", type = input.integer, minval = 1970) showDate = input(defval = true, title = "Show Date Range", type = input.bool) 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" perc_change(lkb) => overall_change = ((close[0] - close[lkb]) / close[lkb]) * 100 // RSI inputs and calculations lengthRSI = 14 RSI = rsi(close, lengthRSI) oversold= input(30) //Entry strategy.entry(id="long", long = true, when = RSI< oversold and window()) //Exit Stop_loss= ((input (1))/100) Take_profit= ((input (7)/100)) longStopPrice = strategy.position_avg_price * (1 - Stop_loss) longTakeProfit = strategy.position_avg_price * (1 + Take_profit) strategy.close("long", when = close < longStopPrice or close > longTakeProfit and window())
DaveStrat
https://www.tradingview.com/script/zMD0MU0U-DaveStrat/
DrWiggleWurms
https://www.tradingview.com/u/DrWiggleWurms/
27
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/ // © David Frausto Pena //@version=5 strategy("DaveStrat") if bar_index < 10000 goindicator = ta.change(ta.sma(ta.sma(close,25),3)) dropindicator = ta.change(ta.sma(ta.sma(close,100),3)) strategy.entry("buy", strategy.long, 10, when=((goindicator)-dropindicator) > 0.0) if ta.sma(close,3)-ta.sma(close,25)<0 strategy.entry("sell", strategy.short, 10, when=dropindicator-goindicator > 0) plot(ta.change(ta.sma(ta.sma(close,25),3)),"50madeltasmooth", color.green) plot(ta.change(ta.sma(ta.sma(close,100),3)),"100madeltasmooth", color.red)
RSI KANNEMAN
https://www.tradingview.com/script/3sdpWdnv/
samuelkanneman
https://www.tradingview.com/u/samuelkanneman/
64
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/ // © samuelkanneman //@version=4 strategy("RSI KANNEMAN") //////Entrada/////// i_startTime = input(title="Start Date Filter", defval=timestamp("01 Nov 2020 13:30 +0000"), type=input.time, tooltip="Date & time to begin trading from") i_endTime = input(title="End Date Filter", defval=timestamp("1 Nov 2022 19:30 +0000"), type=input.time, tooltip="Date & time to stop trading") sobrecompra= input(70, title="Sobre Compra", type=input.integer ,minval=50, maxval=100 ) sobreventa= input(30, title="Sobre Venta", type=input.integer ,minval=0, maxval=50 ) l1=hline(sobrecompra) l2=hline(sobreventa, color=color.purple) periodos= input(14, title="Periodos", type=input.integer ,minval=1, maxval=50 ) periodos_media= input(14, title="Logintud media movil", type=input.integer ,minval=1, maxval=200 ) var SL =0.0 var TP=0.0 StopLoss = input(2.0, title="SL %", step=0.2) TakeProfit = input(5.0, title="TP %", step=0.2) //////Proceso/////// mi_rsi=rsi(close,periodos) mm_rsi=sma(mi_rsi,periodos_media) Es_compra= crossover(mm_rsi,sobreventa) Es_venta= crossunder(mm_rsi,sobrecompra) comprado= strategy.position_size > 0 vendido = strategy.position_size < 0 //time to test dateFilter = time >= i_startTime and time <= i_endTime //timePeriod = time >= timestamp(syminfo.timezone, 2020, 11, 1, 0, 0) // long if (not comprado and Es_compra and dateFilter ) // realizar long cantidad = strategy.equity/hlc3 strategy.entry ("compra", strategy.long , cantidad) SL := close*(1-(StopLoss/100)) TP := close*(1+(TakeProfit/100)) if close >= TP strategy.close ("compra" , comment="Salto TP") if (comprado and Es_venta ) strategy.close ("compra" , comment="Sobre Venta") if close <= SL strategy.close ("compra" , comment="Salto SL") // short if (not vendido and Es_venta and dateFilter ) // realizar short cantidad = strategy.equity/hlc3 strategy.entry ("venta", strategy.short , cantidad) SL := close*(1+(StopLoss/100)) TP := close*(1-(TakeProfit/100)) if close <= TP strategy.close ("venta" , comment="Salto TP") if (vendido and Es_compra ) strategy.close ("venta" , comment="Sobre Compra") if close >= SL strategy.close ("venta" , comment="Salto SL") ///////Salida////// fill(l1,l2) plot(mi_rsi) plot(mm_rsi, color=color.yellow) bgcolor(Es_compra ? color.blue : na , transp=0) bgcolor(Es_venta ? color.red : na , transp=0) // 1d 70 22 5 4 3 15 6 meses //1h 70 20 6 4 5 7 1 mese //15m 70 20 5 4 4 7 1 semana
EMA Mean Reversion Strategy
https://www.tradingview.com/script/Xt7AXMUD-EMA-Mean-Reversion-Strategy/
jordanfray
https://www.tradingview.com/u/jordanfray/
235
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="EMA Mean Reversion 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 = "    " // Tooltips longEntryToolTip = "When the percentage that the price is away from the selected EMA reaches this point, a long postion will open." shortEntryToolTip = "When the percentage that the price is away from the selected EMA reaches this point, a short postion will open." closeEntryToolTip = "When the percentage that the price is away from the selected EMA reaches this point, open postion will close." ladderInToolTip = "Enable this to use the laddering settings below." cancelEntryToolTip = "When the percentage that the price is away from the selected EMA reaches this point, any unfilled entries will be canceled." // Group Titles group_one_title = "EMA Settings" group_two_title = "Entry Settings" // Colors blue = color.new(#00A5FF,0) lightBlue = color.new(#00A5FF,90) green = color.new(#2DBD85,0) gray_80 = color.new(#7F7F7F,80) gray_60 = color.new(#7F7F7F,60) gray_40 = color.new(#7F7F7F,40) white = color.new(#ffffff,0) red = color.new(#E02A4A,0) transparent = color.new(#000000,100) // Strategy Settings EMAtimeframe = input.timeframe(defval="", title="Timeframe", group=group_one_title) EMAlength = input.int(defval=200, minval=1, title="Length", group=group_one_title) EMAtype = input.string(defval="EMA", options = ["EMA", "SMA", "RMA", "WMA"], title="Type", group=group_one_title) EMAsource = input.source(defval=close, title="Source", group=group_one_title) openLongEntryAbove = input.float(defval=9, title="Long Position Entry Trigger", tooltip=longEntryToolTip, group=group_two_title) openEntryEntryAbove = input.float(defval=9, title="Short Position Entry Trigger", tooltip=shortEntryToolTip, group=group_two_title) closeEntryBelow = input.float(defval=1.0, title="Close Position Trigger", tooltip=closeEntryToolTip, group=group_two_title) cancelEntryBelow = input.float(defval=4, title="Cancel Unfilled Entries Trigger", tooltip=cancelEntryToolTip, group=group_two_title) enableLaddering = input.bool(defval=true, title="Ladder Into Positions", tooltip=ladderInToolTip, group=group_two_title) ladderRungs = input.int(defval=4, minval=2, maxval=4, step=1, title=indent_4+"Ladder Rungs", group=group_two_title) ladderStep = input.float(defval=.5, title=indent_4+"Ladder Step (%)", step=.1, group=group_two_title)/100 stop_loss_val = input.float(defval=4.0, title="Stop Loss (%)", step=0.1, group=group_two_title)/100 start_trailing_after = input.float(defval=1, title="Start Trailing After (%)", step=0.1, group=group_two_title)/100 trail_behind = input.float(defval=1, title="Trail Behind (%)", step=0.1, group=group_two_title)/100 // Calculate trailing stop values long_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) long_stop_loss = strategy.position_avg_price * (1.0 - stop_loss_val) short_start_trailing_val = strategy.position_avg_price - (strategy.position_avg_price * start_trailing_after) short_trail_behind_val = close + (strategy.position_avg_price * trail_behind) short_stop_loss = strategy.position_avg_price * (1 + stop_loss_val) // Calulate EMA EMA = switch EMAtype "EMA" => ta.ema(EMAsource, EMAlength) "SMA" => ta.sma(EMAsource, EMAlength) "RMA" => ta.rma(EMAsource, EMAlength) "WMA" => ta.wma(EMAsource, EMAlength) => na EMA_ = EMAtimeframe == timeframe.period ? EMA : request.security(syminfo.ticker, EMAtimeframe, EMA[1], lookahead = barmerge.lookahead_on) plot(EMA_, title="EMA", linewidth=2, color=blue, editable=true) EMA_cloud_upper_band_val = EMA_ + (EMA_ * openLongEntryAbove/100) EMA_cloud_lower_band_val = EMA_ - (EMA_ * openLongEntryAbove/100) EMA_cloud_upper_band = plot(EMA_cloud_upper_band_val, title="EMA Cloud Upper Band", color=blue) EMA_cloud_lower_band = plot(EMA_cloud_lower_band_val, title="EMA Cloud Upper Band", color=blue) fill(EMA_cloud_upper_band, EMA_cloud_lower_band, editable=false, color=lightBlue) distance_from_EMA = ((close - EMA_)/close)*100 if distance_from_EMA < 0 distance_from_EMA := distance_from_EMA * -1 // 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) //plot(strategy.equity, color=green) // Entry Conditions currently_in_a_postion = strategy.position_size != 0 currently_in_a_long_postion = strategy.position_size > 0 currently_in_a_short_postion = strategy.position_size < 0 average_price = strategy.position_avg_price bars_since_entry = currently_in_a_postion ? bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades - 1) + 1 : 5 long_run_up = ta.highest(high, bar_index == 0 ? 5000: bars_since_entry) long_run_up_line = plot(long_run_up, style=plot.style_stepline, editable=false, color=currently_in_a_long_postion ? green : transparent) start_trailing_long_entry = currently_in_a_long_postion and long_run_up > long_start_trailing_val long_trailing_stop = start_trailing_long_entry ? long_run_up - (long_run_up * trail_behind) : long_stop_loss 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_run_up = ta.lowest(low, bar_index == 0 ? 5000: bars_since_entry) short_run_up_line = plot(short_run_up, style=plot.style_stepline, editable=false, color=currently_in_a_short_postion ? green : transparent) start_trailing_short_entry = currently_in_a_short_postion and short_run_up < short_start_trailing_val short_trailing_stop = start_trailing_short_entry ? short_run_up + (short_run_up * trail_behind) : short_stop_loss 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) long_conditions_met = distance_from_EMA > openLongEntryAbove and close < EMA_ and not currently_in_a_postion short_conditions_met = distance_from_EMA > openEntryEntryAbove and close > EMA_ and not currently_in_a_postion close_long_entries = distance_from_EMA <= closeEntryBelow or close <= long_trailing_stop close_short_entries = distance_from_EMA <= closeEntryBelow or close >= short_trailing_stop cancel_entries = distance_from_EMA <= cancelEntryBelow plotshape(long_conditions_met ? close : na, style=shape.diamond, title="Long Conditions Met" ) plotshape(short_conditions_met ? close : na, style=shape.diamond, title="Short Conditions Met" ) plot(average_price,style=plot.style_stepline, editable=false, color=currently_in_a_postion ? blue : transparent) // 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_trailing_stop, when=close_long_entries) strategy.exit(id="Close Long Ladder 2", from_entry="Long Ladder 2", stop=long_trailing_stop, limit=long_trailing_stop, when=close_long_entries) strategy.exit(id="Close Long Ladder 3", from_entry="Long Ladder 3", stop=long_trailing_stop, limit=long_trailing_stop, when=close_long_entries) strategy.exit(id="Close Long Ladder 4", from_entry="Long Ladder 4", stop=long_trailing_stop, limit=long_trailing_stop, when=close_long_entries) strategy.cancel(id="Long Ladder 1", when=cancel_entries) strategy.cancel(id="Long Ladder 2", when=cancel_entries) strategy.cancel(id="Long Ladder 3", when=cancel_entries) strategy.cancel(id="Long Ladder 4", when=cancel_entries) else strategy.entry(id="Long", direction=strategy.long, qty=100, when=long_conditions_met) strategy.exit(id="Close Long", from_entry="Long", stop=long_stop_loss, limit=EMA_, when=close_long_entries) strategy.cancel(id="Long", when=cancel_entries) // 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=EMA_, when=close_short_entries) strategy.exit(id="Close Short Ladder 2", from_entry="Short Ladder 2", stop=short_trailing_stop, limit=EMA_, when=close_short_entries) strategy.exit(id="Close Short Ladder 3", from_entry="Short Ladder 3", stop=short_trailing_stop, limit=EMA_, when=close_short_entries) strategy.exit(id="Close Short Ladder 4", from_entry="Short Ladder 4", stop=short_trailing_stop, limit=EMA_, when=close_short_entries) strategy.cancel(id="Short Ladder 1", when=cancel_entries) strategy.cancel(id="Short Ladder 2", when=cancel_entries) strategy.cancel(id="Short Ladder 3", when=cancel_entries) strategy.cancel(id="Short Ladder 4", when=cancel_entries) else strategy.entry(id="Short", direction=strategy.short, when=short_conditions_met) strategy.exit(id="Close Short", from_entry="Short", limit=EMA_, when=close_short_entries) strategy.cancel(id="Short", when=cancel_entries)
"NoSKi Hammer/Star /w angle of ema Backtester %
https://www.tradingview.com/script/WhoYlLEh-NoSKi-Hammer-Star-w-angle-of-ema-Backtester/
noski1
https://www.tradingview.com/u/noski1/
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/ // © noski1 //@version=5 strategy(title='"NoSKi Hammer Star Backtester %', shorttitle='Noski HnS BT %', overlay=true, commission_type=strategy.commission.percent, commission_value=0.075, initial_capital = 10000, currency=currency.USD, default_qty_type= strategy.percent_of_equity, default_qty_value=100) // Import Zen library import ZenAndTheArtOfTrading/ZenLibrary/5 as zen // -------------------------------------------------------------------------------- //------- Inputs--------// // -------------------------------------------------------------------------------- //Time Period FromMonth = input.int(defval=1, title='From Month', minval=1, maxval=12) FromDay = input.int(defval=9, title='From Day', minval=1, maxval=31) FromYear = input.int(defval=2019, title='From Year', minval=2018) ToMonth = input.int(defval=1, title='To Month', minval=1, maxval=12) ToDay = input.int(defval=1, title='To Day', minval=1, maxval=31) ToYear = input.int(defval=9999, title='To Year', minval=2017) start = timestamp(FromYear, FromMonth, FromDay, 00, 00) finish = timestamp(ToYear, ToMonth, ToDay, 23, 59) window() => time >= start and time <= finish ? true : false // Take Profit SL inputs tp_inp = input.int(14, title='Take Profit %', group = "Take Profit/Stop Loss Settings")/100 //input.int(defval = 1, title = "Take Profit %", minval = 1)/100 sl_inp = input.int(2, title='Stop Loss %', group = "Take Profit/Stop Loss Settings")/100 //input.int(defval = 1, title = "Stop Loss %", minval = 1)/100 //Once order at a time order = input.bool(title="One Position at a time", defval=true, group="Order Sizing") //Hammer and star inputs fibLevel = input.float(title="Fib Level", defval=0.333, group="Hammer and Stars") colorFilter = input.bool(title="Color Filter", defval=false, group="Hammer and Stars") aatrFilter = input.float(title="ATR Filter", defval=0.1, group="Hammer and Stars") //angle inputs src = input(title='Source', defval=close, group="Angle of EMA") guide_pos = input.float(title='Guides Position', defval=45, group="Angle of EMA") guide_neg = input(title='Guides Position', defval=-45, group="Angle of EMA") //price2bar_ratio = input(title='Price To Bar Ratio', defval=20.0, group="Angle of EMA") // Should be the same as that of the Chart p2br = input(title='Price To Bar Ratio', defval=20.0, group="Angle of EMA") // Should be the same as that of the Chart threshold = input(title='Threshold', defval=1.0, group="Angle of EMA") show_bg = input(title='Show Negative Slope Zone', defval=true, group="Angle of EMA") smal = input(title='Average angle over how many bars', defval=20, group="Angle of EMA") emafilter = input.int(title="EMA length", defval=20, group= "EMA") //Swing High/Low filter var g_hl = "High/Low Filter" lookback = input.int(title="Swing High/Low Lookback", defval=10, tooltip="How many bars to look back for swing high/low", group=g_hl) useHlFilter = input.bool(title="Use Swing High/Low Filter?", defval=false, tooltip="Turns on/off the swing high/low filter", group=g_hl) // Filter Settings var g_filter = "Entry Candle ATR Size" atrMinFilterSize = input.float(title=">= ATR Filter", defval=0.0, minval=0.0, group=g_filter, tooltip="Minimum size of entry candle compared to ATR") atrMaxFilterSize = input.float(title="<= ATR Filter", defval=3.0, minval=0.0, group=g_filter, tooltip="Maximum size of entry candle compared to ATR") //emaFilter = input.int(title="EMA Filter", defval=0, group=g_filter, tooltip="EMA length to filter trades - set to zero to disable") price2bar_ratio = request.security(syminfo.tickerid, "D", close) * 0.000025 * p2br // -------------------------------------------------------------------------------- // Hammer and Candles // -------------------------------------------------------------------------------- // Check our ATR filter atr = ta.atr(14) candleSize = high - low atrFilterCheck = candleSize >= atr * aatrFilter // Calculate fibonacci level for current candle bullFib = (low - high) * fibLevel + high bearFib = (high - low) * fibLevel + low // Determine which price source closes or opens highest/lowest lowestBody = close < open ? close : open highestBody = close > open ? close : open // Determine if we have a valid hammer or shooting star candle hammerCandle = lowestBody >= bullFib and (not colorFilter or close > open) and atrFilterCheck starCandle = highestBody <= bearFib and (not colorFilter or close < open) and atrFilterCheck // Get swing high/low filter swingHighFilter = not useHlFilter or (high == ta.highest(high, lookback) or high[1] == ta.highest(high, lookback)) swingLowFilter = not useHlFilter or (low == ta.lowest(low, lookback) or low[1] == ta.lowest(low, lookback)) // -------------------------------------------------------------------------------- // EMA Angle Functions // -------------------------------------------------------------------------------- ema = ta.ema(close, emafilter) get_slope(ema, price2bar_ratio) => 180.0 / (2 * math.asin(1)) * math.atan(ta.change(ema) / price2bar_ratio) // Logic slope = get_slope(ema, price2bar_ratio) rise = false rise := slope - slope[1] > threshold ? true : slope - slope[1] < -threshold ? false : nz(rise[1]) prefall = false prefall := not rise or slope - slope[1] > 0 ? false : rise and slope - slope[1] < 0 ? true : nz(prefall[1]) prerise = false prerise := rise or slope - slope[1] < 0 ? false : not rise and slope - slope[1] > 0 ? true : nz(prerise[1]) sma = ta.sma(slope, smal) // Angle Buy Sell Filter emapos = sma > guide_pos emaneg = sma < guide_neg // -------------------------------------------------------------------------------- // ATR Settings // -------------------------------------------------------------------------------- // Check ATR filter atrMinFilter = high - low >= (atrMinFilterSize * atr) or atrMinFilterSize == 0.0 atrMaxFilter = high - low <= (atrMaxFilterSize * atr) or atrMaxFilterSize == 0.0 atrFilter = atrMinFilter and atrMaxFilter and not na(atr) var int inTrade = 0 order1 = not order or inTrade ==0 // -------------------------------------------------------------------------------- // Combined Buy and Sell signals // -------------------------------------------------------------------------------- buy = hammerCandle and emapos and atrFilter and swingLowFilter and barstate.isconfirmed and order1// inTrade == 0 sell = starCandle and emaneg and atrFilter and swingHighFilter and barstate.isconfirmed and order1//inTrade == 0 inpStopLoss = strategy.position_avg_price * (1 - sl_inp) inpTakeProfit = strategy.position_avg_price * (1 + tp_inp) if strategy.position_size < 0 inpStopLoss := strategy.position_avg_price * (1 + sl_inp) inpTakeProfit := strategy.position_avg_price * (1 - tp_inp) // -------------------------------------------------------------------------------- // View // -------------------------------------------------------------------------------- plotshape(buy, style=shape.triangleup, location=location.belowbar, color=color.new(color.green, 0), text = "Long", title='Long', textcolor = color.green) plotshape(sell, style=shape.triangledown, location=location.abovebar, color=color.new(color.red, 0), text = "Short", title='Short', textcolor = color.red) bgcolor(sma > guide_pos ? color.new(color.green, 85) : na) // highlighting bg when ema angle > 45 bgcolor(sma < guide_neg ? color.new(color.red, 85) : na) plot(ema, title="EMA", color=color.yellow, linewidth=2) strategy.entry("Long", direction= strategy.long, when= buy and window()) strategy.entry("Short", direction= strategy.short, when= sell and window()) strategy.exit("Long Exit", from_entry="Long", when=strategy.position_size > 0, limit = inpTakeProfit, stop = inpStopLoss) strategy.exit("Short Exit", from_entry="Short", when=strategy.position_size < 0, limit = inpTakeProfit, stop = inpStopLoss)
Best TradingView Strategy - For NASDAQ and DOW30 and other Index
https://www.tradingview.com/script/wv68sDys-Best-TradingView-Strategy-For-NASDAQ-and-DOW30-and-other-Index/
The_Bigger_Bull
https://www.tradingview.com/u/The_Bigger_Bull/
324
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_Bigger_Bull //@version=5 strategy("Best TradingView Strategy", overlay=true, margin_long=0, margin_short=0) //Bollinger Bands source1 = close length1 = input.int(9, minval=1) mult1 = input.float(2.0, minval=0.001, maxval=50) basis1 = ta.sma(source1, length1) dev1 = mult1 * ta.stdev(source1, length1) upper1 = basis1 + dev1 lower1 = basis1 - dev1 //buyEntry = ta.crossover(source1, lower1) //sellEntry = ta.crossunder(source1, upper1) //RSI ma(source, length, type) => switch type "SMA" => ta.sma(source, length) "Bollinger Bands" => ta.sma(source, length) "EMA" => ta.ema(source, length) "SMMA (RMA)" => ta.rma(source, length) "WMA" => ta.wma(source, length) "VWMA" => ta.vwma(source, length) 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="MA Settings") maLengthInput = input.int(14, title="MA Length", group="MA Settings") bbMultInput = input.float(2.0, minval=0.001, maxval=50, title="BB StdDev", group="MA Settings") up = ta.rma(math.max(ta.change(rsiSourceInput), 0), rsiLengthInput) down = ta.rma(-math.min(ta.change(rsiSourceInput), 0), rsiLengthInput) rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down)) rsiMA = ma(rsi, maLengthInput, maTypeInput) isBB = maTypeInput == "Bollinger Bands" //plot(rsi, "RSI", color=#7E57C2) //plot(rsiMA, "RSI-based MA", color=color.yellow) rsiUpperBand = hline(70, "RSI Upper Band", color=#787B86) hline(50, "RSI Middle Band", color=color.new(#787B86, 50)) rsiLowerBand = hline(30, "RSI Lower Band", color=#787B86) fill(rsiUpperBand, rsiLowerBand, color=color.rgb(126, 87, 194, 90), title="RSI Background Fill") bbUpperBand = plot(isBB ? rsiMA + ta.stdev(rsi, maLengthInput) * bbMultInput : na, title = "Upper Bollinger Band", color=color.green) bbLowerBand = plot(isBB ? rsiMA - ta.stdev(rsi, maLengthInput) * bbMultInput : na, title = "Lower Bollinger Band", color=color.green) fill(bbUpperBand, bbLowerBand, color= isBB ? color.new(color.green, 90) : na, title="Bollinger Bands Background Fill") //ADX adxlen = input(14, title="ADX Smoothing") dilen = input(14, title="DI Length") dirmov(len) => up1 = ta.change(high) down1 = -ta.change(low) plusDM = na(up1) ? na : (up1 > down1 and up1 > 0 ? up1 : 0) minusDM = na(down1) ? na : (down1 > up1 and down1 > 0 ? down1 : 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) out = ta.sma(close,14) sma1=ta.sma(close,42) ema200=ta.ema(close,200) longCondition = (out>sma1) and ta.crossover(source1, lower1) if (longCondition ) strategy.entry("long", strategy.long) shortCondition = (out<sma1) and ta.crossunder(source1, lower1) if (shortCondition ) strategy.entry("short", strategy.short) stopl=strategy.position_avg_price-50 tptgt=strategy.position_avg_price+100 stopshort=strategy.position_avg_price+50 tptgtshort=strategy.position_avg_price-100 strategy.exit("longclose","long",trail_offset=50,trail_points=200,when=ta.crossover(sma1,out)) strategy.exit("shortclose","short",trail_offset=50,trail_points=200,when=ta.crossover(out,sma1)) //if strategy.position_avg_price<0 plot(sma1 , color=color.blue) plot(out, color=color.green) //plot(ema200,color=color.red)
Take profit Multi timeframe
https://www.tradingview.com/script/9lzBKqhc/
TrendCrypto2022
https://www.tradingview.com/u/TrendCrypto2022/
654
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(title = "Take profit Multi timeframe", overlay = true, pyramiding=0,initial_capital = 10000, default_qty_type= strategy.fixed, default_qty_value =1, calc_on_order_fills=false, slippage=0,commission_type=strategy.commission.percent,commission_value=0) //Input takepercent = input.bool(title="Take profit %", defval=true , group="Set up take profit") takemtf = input.bool(title="Take profit Multi timeframe", defval=false , group="Set up take profit") //Paste your strategy at here. This is example strategy: I use WaveTrend indicator //WaveTrend indicator n1 = input(10, "Channel Length", group="Example Strategy") n2 = input(21, "Average Length", group="Example Strategy") oblv1 = input(60, "Over Bought Lv 1", group="Example Strategy") oblv2 = input(53, "Over Bought Lv 2", group="Example Strategy") oslv1 = input(-60, "Over Sold Lv 1", group="Example Strategy") oslv2 = input(-53, "Over Sold Lv 2", group="Example Strategy") 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 buy = ta.crossover(wt1, wt2) and wt1 < -20 closebuy = ta.crossunder(wt1, wt2) and wt1 > 0 if buy strategy.entry("Long", strategy.long) //Set up take profit % percent(pcnt) => strategy.position_size != 0 ? math.round(pcnt / 100 * strategy.position_avg_price / syminfo.mintick) : float(na) TP1 =input.float(3, title="TP1 %", step=0.1, group="Take profit %", inline = "1") TP2 =input.float(5, title="TP2 %", step=1, group="Take profit %", inline = "1") TP3 =input.float(8, title="TP3 %", step=1, group="Take profit %", inline = "2") TP4 =input.float(10, title="TP4 %", step=1, group="Take profit %", inline = "2") SL =input.float(5, title="Stop Loss %", step=1, group="Take profit %") qty1 =input.float(5, title="% Close At TP1", step=1, group="Take profit %", inline = "3") qty2 =input.float(5, title="% Close At TP2", step=1, group="Take profit %", inline = "3") qty3 =input.float(5, title="% Close At TP3", step=1, group="Take profit %", inline = "4") qty4 =input.float(5, title="% Close At TP4", step=1, group="Take profit %", inline = "4") lossSTL = percent(SL) //Set up take profit at higher TF ema_len1 = input.int(title='EMA1', defval=100, group='Take profit Mtf') ema_len2 = input.int(title='EMA2', defval=200, group='Take profit Mtf') src = close tf1 = input.timeframe(title='Timeframe 1', defval='240', group='Take profit Mtf') tf2 = input.timeframe(title='Timeframe 2', defval='D', group='Take profit Mtf') htf_ma1 = ta.ema(src, ema_len1) htf_ma2 = ta.ema(src, ema_len2) ema1 = request.security(syminfo.tickerid, tf1, htf_ma1) ema2 = request.security(syminfo.tickerid, tf1, htf_ma2) ema3 = request.security(syminfo.tickerid, tf2, htf_ma1) ema4 = request.security(syminfo.tickerid, tf2, htf_ma2) //Set up take profit multi timeframe a = array.from((ema1), (ema2), (ema3), (ema4)) tpmtf1 = array.min(a) tpmtf2 = array.min(a, 2) tpmtf3 = array.min(a, 3) tpmtf4 = array.min(a, 4) //Set up exit long_sl_lv = strategy.position_avg_price - lossSTL*syminfo.mintick if takepercent == true strategy.exit("TP1%", "Long", qty_percent = qty1, profit = percent(TP1), loss = lossSTL) strategy.exit("TP2%", "Long", qty_percent = qty2, profit = percent(TP2), loss = lossSTL) strategy.exit("TP3%", "Long", qty_percent = qty3, profit = percent(TP3), loss = lossSTL) strategy.exit("TP4%", "Long", qty_percent = qty3, profit = percent(TP4), loss = lossSTL) strategy.close_all(when= closebuy, comment="Close All") if takemtf == true and array.max(a, 1) > strategy.position_avg_price strategy.exit("TP1Mtf", "Long", qty_percent = qty1, limit = tpmtf1, stop = long_sl_lv) strategy.exit("TP2Mtf", "Long", qty_percent = qty2, limit = tpmtf2, stop = long_sl_lv) strategy.exit("TP3Mtf", "Long", qty_percent = qty3, limit = tpmtf3, stop = long_sl_lv) strategy.close_all(when= closebuy, comment="Close All") // Plot TP & SL long_tp1_lv = strategy.position_avg_price + percent(TP1)*syminfo.mintick long_tp2_lv = strategy.position_avg_price + percent(TP2)*syminfo.mintick long_tp3_lv = strategy.position_avg_price + percent(TP3)*syminfo.mintick long_tp4_lv = strategy.position_avg_price + percent(TP4)*syminfo.mintick plot(strategy.position_size > 0 ? long_sl_lv : na, color=color.red, style=plot.style_linebr, title="SL Long") plot(strategy.position_size > 0 ? long_tp1_lv : na, color=color.lime, style=plot.style_linebr, title="Long TP1%") plot(strategy.position_size > 0 ? long_tp2_lv : na, color=color.lime, style=plot.style_linebr, title="Long TP2%") plot(strategy.position_size > 0 ? long_tp3_lv : na, color=color.lime, style=plot.style_linebr, title="Long TP3%") plot(strategy.position_size > 0 ? long_tp4_lv : na, color=color.lime, style=plot.style_linebr, title="Long TP4%") plot(strategy.position_size > 0 ? tpmtf1 : na, color=color.orange, style=plot.style_linebr, title="Long TP1Mtf", display = display.none) plot(strategy.position_size > 0 ? tpmtf2 : na, color=color.orange, style=plot.style_linebr, title="Long TP2Mtf", display = display.none) plot(strategy.position_size > 0 ? tpmtf3 : na, color=color.orange, style=plot.style_linebr, title="Long TP3Mtf", display = display.none) //Plot Resistant in higher TF plotema1 = plot(ema1, color=color.new(color.silver, 0), style=plot.style_line, linewidth=1, offset=0, title='Ema100 4h', display=display.none) plotema2 = plot(ema2, color=color.new(color.silver, 0), style=plot.style_line, linewidth=1, offset=0, title='Ema200 4h', display=display.none) plotema3 = plot(ema3, color=color.new(color.orange, 20), style=plot.style_line, linewidth=1, offset=0, title='Ema100 D', display=display.none) plotema4 = plot(ema4, color=color.new(color.orange, 20), style=plot.style_line, linewidth=1, offset=0, title='Ema200 D', display=display.none) //Label TP _x = timenow + math.round(ta.change(time) * 2) var label labelema1 = na label.delete(labelema1) labelema1 := label.new(x=_x, y=ema1, text='Ema' + str.tostring(ema_len1) + ' ' + str.tostring(tf1) + ': ' + str.tostring(math.round(ema1,4)) + '', color=color.new(#000000, 100), textcolor = color.yellow, size=size.small, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price) var label labelema2 = na label.delete(labelema2) labelema2 := label.new(x=_x, y=ema2, text='Ema' + str.tostring(ema_len2) + ' ' + str.tostring(tf1) + ': ' + str.tostring(math.round(ema2,4)) + '', color=color.new(#000000, 100), textcolor = color.yellow, size=size.small, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price) var label labelema3 = na label.delete(labelema3) labelema3 := label.new(x=_x, y=ema3, text='Ema' + str.tostring(ema_len1) + ' ' + str.tostring(tf2) + ': ' + str.tostring(math.round(ema3,4)) + '', color=color.new(#000000, 100), textcolor = color.yellow, size=size.small, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price) var label labelema4 = na label.delete(labelema4) labelema4 := label.new(x=_x, y=ema4, text='Ema' + str.tostring(ema_len2) + ' ' + str.tostring(tf2) + ': ' + str.tostring(math.round(ema4,4)) + '', color=color.new(#000000, 100), textcolor = color.yellow, size=size.small, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price) if strategy.position_size > 0 var label labellongtp1 = na label.delete(labellongtp1) labellongtp1 := label.new(x=_x, y=long_tp1_lv, text='TP1: ' + str.tostring(math.round(long_tp1_lv,2)) + '', color=color.new(#000000, 100), textcolor = color.lime, size=size.small, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price) var label labellongtp2 = na label.delete(labellongtp2) labellongtp2 := label.new(x=_x, y=long_tp2_lv, text='TP2: ' + str.tostring(math.round(long_tp2_lv,2)) + '', color=color.new(#000000, 100), textcolor = color.lime, size=size.small, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price) var label labellongtp3 = na label.delete(labellongtp3) labellongtp3 := label.new(x=_x, y=long_tp3_lv, text='TP3: ' + str.tostring(math.round(long_tp3_lv,2)) + '', color=color.new(#000000, 100), textcolor = color.lime, size=size.small, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price) var label labellongtp4 = na label.delete(labellongtp4) labellongtp4 := label.new(x=_x, y=long_tp4_lv, text='TP4: ' + str.tostring(math.round(long_tp4_lv,2)) + '', color=color.new(#000000, 100), textcolor = color.lime, size=size.small, style=label.style_label_left, xloc=xloc.bar_time, yloc=yloc.price)
Grid HW
https://www.tradingview.com/script/FPvqHjY8-Grid-HW/
Lionkind
https://www.tradingview.com/u/Lionkind/
39
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/ // © Lionkind //@version=5 strategy("Grid HW", overlay = true, margin_long = 1, margin_short = 1) // Fix 35k price as starting point and 1% as a distance sprice=input.price(40500,"Starting price") gridpercent=input(1,"Percent") // calculate the % of the 10 layers p1=((gridpercent*1)/100) p2=((gridpercent*2)/100) p3=((gridpercent*3)/100) p4=((gridpercent*4)/100) p5=((gridpercent*5)/100) p6=((gridpercent*6)/100) p7=((gridpercent*7)/100) p8=((gridpercent*8)/100) p9=((gridpercent*9)/100) p10=((gridpercent*10)/100) //set buy prices b1=sprice-(sprice*p1) b2=sprice-(sprice*p2) b3=sprice-(sprice*p3) b4=sprice-(sprice*p4) b5=sprice-(sprice*p5) b6=sprice-(sprice*p6) b7=sprice-(sprice*p7) b8=sprice-(sprice*p8) b9=sprice-(sprice*p9) b10=sprice-(sprice*p10) //set sell prices s1=b1+(sprice*p1) s2=b2+(sprice*p1) s3=b3+(sprice*p1) s4=b4+(sprice*p1) s5=b5+(sprice*p1) s6=b6+(sprice*p1) s7=b7+(sprice*p1) s8=b8+(sprice*p1) s9=b9+(sprice*p1) s10=b10+(sprice*p1) //Long conditions lc1=close<b1 lc2=close<b2 lc3=close<b3 lc4=close<b4 lc5=close<b5 lc6=close<b6 lc7=close<b7 lc8=close<b8 lc9=close<b9 lc10=close<b10 //exit conditions ec1=close>s1 ec2=close>s2 ec3=close>s3 ec4=close>s4 ec5=close>s5 ec6=close>s6 ec7=close>s7 ec8=close>s8 ec9=close>s9 ec10=close>s10 //long orders if (lc1) strategy.entry("b1", strategy.long, when=(lc1)) if (lc2) strategy.entry("b2", strategy.long, when=(lc2)) if (lc3) strategy.entry("b3", strategy.long, when=(lc3)) if (lc4) strategy.entry("b4", strategy.long, when=(lc4)) if (lc5) strategy.entry("b5", strategy.long, when=(lc5)) if (lc6) strategy.entry("b6", strategy.long, when=(lc6)) if (lc7) strategy.entry("b7", strategy.long, when=(lc7)) if (lc8) strategy.entry("b8", strategy.long, when=(lc8)) if (lc9) strategy.entry("b9", strategy.long, when=(lc9)) if (lc10) strategy.entry("b10", strategy.long, when=(lc10)) //exit orders if (ec1) strategy.exit("b1", when=(ec1), limit=1) if (ec2) strategy.exit("b2", when=(ec2), limit=1) if (ec3) strategy.exit("b3", when=(ec3), limit=1) if (ec4) strategy.exit("b4", when=(ec4), limit=1) if (ec5) strategy.exit("b5", when=(ec5), limit=1) if (ec6) strategy.exit("b6", when=(ec6), limit=1) if (ec7) strategy.exit("b7", when=(ec7), limit=1) if (ec8) strategy.exit("b8", when=(ec8), limit=1) if (ec9) strategy.exit("b9", when=(ec9), limit=1) if (ec10) strategy.exit("b10", when=(ec10), limit=1) plot(b1,color=color.green) plot(s1, color=color.red) plot(b2, color=color.purple)
Swing Stock designed for Monthly/Yearly Trading
https://www.tradingview.com/script/qki6JIO1-Swing-Stock-designed-for-Monthly-Yearly-Trading/
exlux99
https://www.tradingview.com/u/exlux99/
96
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(title="World Indicators Testing", overlay=true, calc_on_every_tick=true ) // Personal Consumption Expenditures // FRED/PCE // Real Retail and Food Services Sales // FRED/RRSFS // Leading Index for the United States // FRED/USSLIND // All Employees: Total Nonfarm Payrolls // FRED/PAYEMS // Real Gross Domestic Product // FRED/GDPC1 // Gross Domestic Product // FRED/GDP pce= request.quandl('FRED/PCE', barmerge.gaps_off,0) long_pce = pce>pce[1] short_pce =pce<pce[1] rrfss=request.quandl('FRED/RRSFS', barmerge.gaps_off,0) long_rrfss = rrfss>rrfss[1] short_rrfss = rrfss<rrfss[1] li=request.quandl('FRED/USSLIND', barmerge.gaps_off,0) long_li = li>0 short_li = li<0 ae=request.quandl('FRED/PAYEMS', barmerge.gaps_off,0) long_ae= ae>ae[1] short_ae = ae<ae[1] rgdp=request.quandl('FRED/GDPC1', barmerge.gaps_off,0) long_rgdp = rgdp>rgdp[1] short_rgdp = rgdp<rgdp[1] gdp=request.quandl('FRED/GDP', barmerge.gaps_off,0) long_gdp=gdp>gdp[1] short_gdp=gdp<gdp[1] long= long_rgdp or long_gdp //or long_rrfss short = short_gdp or short_rgdp// or short_rrfss fromDay = input.int(defval=1, title='From Day', minval=1, maxval=31, group="Time Condition") fromMonth = input.int(defval=1, title='From Month', minval=1, maxval=12, group="Time Condition") fromYear = input.int(defval=2000, title='From Year', minval=1970, group="Time Condition") //monday and session // To Date Inputs toDay = input.int(defval=31, title='To Day', minval=1, maxval=31, group="Time Condition") toMonth = input.int(defval=12, title='To Month', minval=1, maxval=12, group="Time Condition") toYear = input.int(defval=2025, title='To Year', minval=1970, group="Time Condition") 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",strategy.long,when=long ) strategy.entry('short',strategy.short,when=short) if(not time_cond) strategy.close_all()
TriautoETF(TQQQ) Short Strategy B1
https://www.tradingview.com/script/onbI61K2/
BBcom
https://www.tradingview.com/u/BBcom/
26
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/ // © BBcom //@version=5 strategy("TriautoETF(TQQQ) Short Strategy B1","TSSB1", overlay = true) // QQQ QQQ1 = request.security("QQQ","D", ta.hma(close, 2)) QQQ2 = request.security("QQQ","D", ta.vwma(close, 193)) QQQ3 = request.security("QQQ","D", ta.ema(close, 9)) QQQ4 = request.security("QQQ","D", ta.ema(close, 14)) // 基準線表示 ShortLine = ta.vwma(close,193) plot(ShortLine,title="Short Line",color=color.purple,linewidth=2) // 売買の注文 strategy.entry(id = "Entry", direction = strategy.short, when = ta.crossover(QQQ2, QQQ1) ,comment="Short") strategy.close(id = "Entry", when = ta.crossover(QQQ3, QQQ4) or ta.crossover(QQQ3, QQQ2) , comment="Close")
RSI+PA+PrTP
https://www.tradingview.com/script/UDKe3HCN-RSI-PA-PrTP/
A3Sh
https://www.tradingview.com/u/A3Sh/
93
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 // © A3Sh // RSI Strategy that buys the dips, uses Price Averaging and Pyramiding. // When the price drops below specified percentages of the price (8 PA layers), new entries are openend to average the price of the assets. // Open entries are closed by a specified take profit. // Entries can be reopened, after closing and consequently crossing a PA layer again. // This strategy is based on the RSI+PA+DCA strategy I created earlier. The difference is the way the Take Profit is calculated. // Instead of directly connecting the take profit limit to the decreasing average price level with an X percent above the average price, // the take profit is calculated for a part on the decreasing average price and for another part on the deduction // of the profits of the individual closed positions. // The Take Profit Limit drop less significant then the average price level and the full position only completely exits // when enough individual closed positions made up for the losses. // This makes it less risky and more conservative and great for a long term trading strategy // RSI code is adapted from the build in Relative Strength Index indicator // MA Filter and RSI concept adapted from the Optimized RSI Buy the Dips strategy, by Coinrule // https://www.tradingview.com/script/Pm1WAtyI-Optimized-RSI-Strategy-Buy-The-Dips-by-Coinrule/ // Pyramiding entries code adapted from Pyramiding Entries on Early Trends startegy, by Coinrule // Pyramiding entries code adapted from Pyramiding Entries on Early Trends startegy, by Coinrule // https://www.tradingview.com/script/7NNJ0sXB-Pyramiding-Entries-On-Early-Trends-by-Coinrule/ // Plot entry layers code adapted from HOWTO Plot Entry Price by vitvlkv // https://www.tradingview.com/script/bHTnipgY-HOWTO-Plot-Entry-Price/ strategy(title='RSI+PA+PTP', pyramiding=16, overlay=true, initial_capital=400, default_qty_type=strategy.percent_of_equity, default_qty_value=15, commission_type=strategy.commission.percent, commission_value=0.075, close_entries_rule='FIFO') port = input.float(12, group = "Risk", title='Portfolio % Used To Open The 8 Positions', step=0.1, minval=0.1, maxval=100) q = strategy.equity / 100 * port / open // Long position PA entry layers. Percentage from the entry price of the the first long ps2 = input.float(2, group = "Long Position Entry Layers", title='2nd Long Entry %', step=0.1) ps3 = input.float(3, group = "Long Position Entry Layers", title='3rd Long Entry %', step=0.1) ps4 = input.float(5, group = "Long Position Entry Layers", title='4th Long Entry %', step=0.1) ps5 = input.float(10, group = "Long Position Entry Layers", title='5th Long Entry %', step=0.1) ps6 = input.float(16, group = "Long Position Entry Layers", title='6th Long Entry %', step=0.1) ps7 = input.float(25, group = "Long Position Entry Layers" ,title='7th Long Entry %', step=0.1) ps8 = input.float(40, group = "Long Position Entry Layers", title='8th Long Entry %', step=0.1) // Calculate Moving Averages plotMA = input.bool(group = "Moving Average Filter", title='Plot Moving Average', defval=false) movingaverage_signal = ta.sma(close, input(100, group = "Moving Average Filter", title='MA Length')) plot (plotMA ? movingaverage_signal : na, color = color.new (color.green, 0)) // RSI inputs and calculations rsiLengthInput = input.int(14, minval=1, title="RSI Length", group="RSI Settings") rsiSourceInput = input.source(close, "Source", group="RSI Settings") up = ta.rma(math.max(ta.change(rsiSourceInput), 0), rsiLengthInput) down = ta.rma(-math.min(ta.change(rsiSourceInput), 0), rsiLengthInput) rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down)) overSold = input.int(29, title="Oversold, Trigger to Enter First Position", group = "RSI Settings") // Long trigger (co) co = ta.crossover(rsi, overSold) and close < movingaverage_signal // Store values to create and plot the different PA layers long1 = ta.valuewhen(co, close, 0) long2 = ta.valuewhen(co, close - close / 100 * ps2, 0) long3 = ta.valuewhen(co, close - close / 100 * ps3, 0) long4 = ta.valuewhen(co, close - close / 100 * ps4, 0) long5 = ta.valuewhen(co, close - close / 100 * ps5, 0) long6 = ta.valuewhen(co, close - close / 100 * ps6, 0) long7 = ta.valuewhen(co, close - close / 100 * ps7, 0) long8 = ta.valuewhen(co, close - close / 100 * ps8, 0) eps1 = 0.00 eps1 := na(eps1[1]) ? na : eps1[1] eps2 = 0.00 eps2 := na(eps2[1]) ? na : eps2[1] eps3 = 0.00 eps3 := na(eps3[1]) ? na : eps3[1] eps4 = 0.00 eps4 := na(eps4[1]) ? na : eps4[1] eps5 = 0.00 eps5 := na(eps5[1]) ? na : eps5[1] eps6 = 0.00 eps6 := na(eps6[1]) ? na : eps6[1] eps7 = 0.00 eps7 := na(eps7[1]) ? na : eps7[1] eps8 = 0.00 eps8 := na(eps8[1]) ? na : eps8[1] plot(strategy.position_size > 0 ? eps1 : na, title='Long entry 1', style=plot.style_linebr) plot(strategy.position_size > 0 ? eps2 : na, title='Long entry 2', style=plot.style_linebr) plot(strategy.position_size > 0 ? eps3 : na, title='Long entry 3', style=plot.style_linebr) plot(strategy.position_size > 0 ? eps4 : na, title='Long entry 4', style=plot.style_linebr) plot(strategy.position_size > 0 ? eps5 : na, title='Long entry 5', style=plot.style_linebr) plot(strategy.position_size > 0 ? eps6 : na, title='Long entry 6', style=plot.style_linebr) plot(strategy.position_size > 0 ? eps7 : na, title='Long entry 7', style=plot.style_linebr) plot(strategy.position_size > 0 ? eps8 : na, title='Long entry 8', style=plot.style_linebr) // Take Profit Settings ProfitTarget_Percent = input.float(3.0, group = "Take Profit Settings", title='Take Profit % (Per Position)') ProfitTarget_Percent_All = input.float(4.0, group = "Take Profit Settings", title='Take Profit % (Exit All, Progressive Take Profit Limit') TakeProfitProgression = input.float(12, group = "Take Profit Settings", title='Take Profit Progression', tooltip = 'Progression is defined by the position size. By default 12% of the start equity (portfolio) is used to open a position, see Risk. This same % percentage is used to calculate the profit amount that will be deducted from the Take Profit Limit.') entryOn = input.bool (true, group = "Take Profit Settings", title='New entries affect Take Profit limit', tooltip = 'This option changes the behaviour of the Progressive Take Profit. When switchted on, the difference between the former and current original Take Profit is deducted from the Progressive Take Profit. When switchted off, the Progressive Take Profit is only affected by the profit deduction or each closed position.') avPricePlot = input.bool (false, group = "Take Profit Settings", title='Plot Average Price (FIFO)') // Original Take Profit Limit tpLimit = strategy.position_avg_price + (strategy.position_avg_price / 100 * ProfitTarget_Percent_All) // Create variables to calculate the Take Profit Limit Progresssion var endVal = 0.0 var startVal = 0.0 // The value at the the start of the loop is the value of the end of the previous loop startVal := endVal // Set variable to the original Take Profit Limit when the first position opens. if strategy.position_size > 0 and strategy.position_size[1] ==0 endVal := tpLimit // Everytime a specific position opens, the difference of the previous (original) Take Profit price and the current (original) Take Profit price will be deducted from the Progressive Take Profit Limit // This feature can be toggled on and off in the settings panel. By default it is toggled on. entryAmount = 0.0 for i = 1 to strategy.opentrades entryAmount := i if entryOn and strategy.position_size > 0 and strategy.opentrades[1] == (entryAmount) and strategy.opentrades == (entryAmount + 1) endVal := startVal - (tpLimit[1] - tpLimit) // Everytime a specific position closes, the amount of profit from that specific position will be deducted from the Progressive Take Profit Limit. exitAmount = 0.0 for id = 1 to strategy.opentrades exitAmount := id if strategy.opentrades[1] ==(exitAmount + 1) and strategy.opentrades == (exitAmount) endVal := startVal - (TakeProfitProgression / 100 * strategy.opentrades.entry_price (id - 1) / 100 * ProfitTarget_Percent ) // The Final Take Profit Price tpn = (strategy.position_avg_price + (strategy.position_avg_price / 100 * ProfitTarget_Percent_All)) - (strategy.position_avg_price + (strategy.position_avg_price / 100 * ProfitTarget_Percent_All) - endVal) plot (strategy.position_size > 0 ? tpn : na, title = "Take Profit Limit", color=color.new(color.red, 0), style = plot.style_linebr, linewidth = 1) // Plot position average price as reference plot (avPricePlot ? strategy.position_avg_price : na, title= "Average price", color = color.new(color.white, 0), style = plot.style_linebr, linewidth = 1) // When to trigger the Take Profit per position or the Progressive Take Profit tpl1 = close < tpn ? eps1 + close * (ProfitTarget_Percent / 100) : tpn tpl2 = close < tpn ? eps2 + close * (ProfitTarget_Percent / 100) : tpn tpl3 = close < tpn ? eps3 + close * (ProfitTarget_Percent / 100) : tpn tpl4 = close < tpn ? eps4 + close * (ProfitTarget_Percent / 100) : tpn tpl5 = close < tpn ? eps5 + close * (ProfitTarget_Percent / 100) : tpn tpl6 = close < tpn ? eps6 + close * (ProfitTarget_Percent / 100) : tpn tpl7 = close < tpn ? eps7 + close * (ProfitTarget_Percent / 100) : tpn tpl8 = close < tpn ? eps8 + close * (ProfitTarget_Percent / 100) : tpn // Submit Entry Orders if co and strategy.opentrades == 0 eps1 := long1 eps2 := long2 eps3 := long3 eps4 := long4 eps5 := long5 eps6 := long6 eps7 := long7 eps8 := long8 strategy.entry('Long1', strategy.long, q) if strategy.opentrades == 1 strategy.entry('Long2', strategy.long, q, limit=eps2) if strategy.opentrades == 2 strategy.entry('Long3', strategy.long, q, limit=eps3) if strategy.opentrades == 3 strategy.entry('Long4', strategy.long, q, limit=eps4) if strategy.opentrades == 4 strategy.entry('Long5', strategy.long, q, limit=eps5) if strategy.opentrades == 5 strategy.entry('Long6', strategy.long, q, limit=eps6) if strategy.opentrades == 6 strategy.entry('Long7', strategy.long, q, limit=eps7) if strategy.opentrades == 7 strategy.entry('Long8', strategy.long, q, limit=eps8) // Submit Exit orders if strategy.position_size > 0 strategy.exit(id='Exit 1', from_entry='Long1', limit=tpl1) strategy.exit(id='Exit 2', from_entry='Long2', limit=tpl2) strategy.exit(id='Exit 3', from_entry='Long3', limit=tpl3) strategy.exit(id='Exit 4', from_entry='Long4', limit=tpl4) strategy.exit(id='Exit 5', from_entry='Long5', limit=tpl5) strategy.exit(id='Exit 6', from_entry='Long6', limit=tpl6) strategy.exit(id='Exit 7', from_entry='Long7', limit=tpl7) strategy.exit(id='Exit 8', from_entry='Long8', limit=tpl8) // Make sure that all open limit orders are canceled after exiting all the positions longClose = strategy.position_size[1] > 0 and strategy.position_size == 0 ? 1 : 0 if longClose strategy.cancel_all()
"Sell in May, buy in September"-Strategy
https://www.tradingview.com/script/C2qlt3mi-Sell-in-May-buy-in-September-Strategy/
DynamicSignalLab
https://www.tradingview.com/u/DynamicSignalLab/
76
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © DynamicSignalLab //@version=5 strategy("Sell in May, buy in September Strategy", overlay=false) longCondition = month==9 closecondition = month==5 if longCondition strategy.entry("long", strategy.long) if closecondition strategy.close("long", when=closecondition)
Solution Zigma - Fibonacci Impulse
https://www.tradingview.com/script/k1GLeZco-Solution-Zigma-Fibonacci-Impulse/
ZoomerXeus
https://www.tradingview.com/u/ZoomerXeus/
2,619
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/ // © ZoomerXeus //@version=5 strategy("Solution Zigma", overlay=true, calc_on_every_tick=true) import ZoomerXeus/AutoFiboRetrace/2 as autoFibo // Input Data ord_con_1 = 'Original (Zigma Candle + CE + Subhag)' ord_con_2 = 'Original Extra (Zigma Candle with DMI + CE + Subhag)' ord_con_3 = 'Original 0 (Zigma + CE)' ord_con_4 = 'Original 0 Extra (Zigma with DMI + CE)' ord_con_5 = 'Original Combination (Combo since Original to Original 0)' fibo_level_source = input.string('0.5', 'Fibonaci Level source', options=['0.786', '0.618', '0.5', '0.382', '0.236'], group="General (Default setting for Binance's BTCUSDTPERP)") fibo_level_session = input.timeframe('60', 'Timeframe', options=["W", "D", "240", "60", "30", "15", "5", "1"], group="General (Default setting for Binance's BTCUSDTPERP)") fibo_lookback_length = input.int(12, 'Fibonaci lookback Length', minval=1, step=1, group="General (Default setting for Binance's BTCUSDTPERP)") isShowCandleMode = input.bool(true, 'Show Candle Mode', group="General (Default setting for Binance's BTCUSDTPERP)") //Alex Orekhov (everget)'s Chandelier Exit isShowFilterIndicator_ce = input.bool(false, 'Show On Chart', group="Alex Orekhov (everget)'s Chandelier Exit (Filter)") ce_length = input.int(1, 'ATR Chandelier Exit Length', minval=1, step=1, group="Alex Orekhov (everget)'s Chandelier Exit (Filter)") ce_mult = input.float(3.0, 'ATR Chandelier Exit Multiply', minval=0.1, step=0.1, group="Alex Orekhov (everget)'s Chandelier Exit (Filter)") // Subhag + TSD + EWO original by subhagghosh and edit by Pumpith isShowFilterIndicator_subh = input.bool(false, 'Show On Chart', group="Subhag + TSD + EWO original by subhagghosh and edit by Pumpith (Filter)") fast_length = input(title='Fast Length', defval=3, group="Subhag + TSD + EWO original by subhagghosh and edit by Pumpith (Filter)") slow_length = input(title='Slow Length', defval=10, group="Subhag + TSD + EWO original by subhagghosh and edit by Pumpith (Filter)") src_sh = input(title='Source', defval=close, group="Subhag + TSD + EWO original by subhagghosh and edit by Pumpith (Filter)") res_60 = input('60', title='Higher Time Frame 1', group="Subhag + TSD + EWO original by subhagghosh and edit by Pumpith (Filter)") rsi_period = input.int(14, title='RSI period', minval=1, step=1, group="Subhag + TSD + EWO original by subhagghosh and edit by Pumpith (Filter)") source = input(close, group="Subhag + TSD + EWO original by subhagghosh and edit by Pumpith (Filter)") length = input.int(100, minval=1, group="Subhag + TSD + EWO original by subhagghosh and edit by Pumpith (Filter)") offset = input.int(0, minval=0, group="Subhag + TSD + EWO original by subhagghosh and edit by Pumpith (Filter)") smoothing = input.int(17, minval=1, group="Subhag + TSD + EWO original by subhagghosh and edit by Pumpith (Filter)") mtf_val = input.timeframe('', 'Resolution', group="Subhag + TSD + EWO original by subhagghosh and edit by Pumpith (Filter)") p = input.string('Lime', 'Up Color', options=['Red', 'Lime', 'Orange', 'Teal', 'Yellow', 'White', 'Black'], group="Subhag + TSD + EWO original by subhagghosh and edit by Pumpith (Filter)") q = input.string('Red', 'Down Color', options=['Red', 'Lime', 'Orange', 'Teal', 'Yellow', 'White', 'Black'], group="Subhag + TSD + EWO original by subhagghosh and edit by Pumpith (Filter)") switchColor = input(true, 'Color Regression according to trend?', group="Subhag + TSD + EWO original by subhagghosh and edit by Pumpith (Filter)") candleCol = input(false, title='Color candles based on Hull\'s Trend?', group="Subhag + TSD + EWO original by subhagghosh and edit by Pumpith (Filter)") visualSwitch = input(true, title='Show as a Band?', group="Subhag + TSD + EWO original by subhagghosh and edit by Pumpith (Filter)") thicknesSwitch = input(1, title='Line Thickness', group="Subhag + TSD + EWO original by subhagghosh and edit by Pumpith (Filter)") transpSwitch = input.int(40, title='Band Transparency', step=5, group="Subhag + TSD + EWO original by subhagghosh and edit by Pumpith (Filter)") n1 = input.int(10, 'Channel Length', group="Subhag + TSD + EWO original by subhagghosh and edit by Pumpith (Filter)") n2 = input.int(21, 'Average Length', group="Subhag + TSD + EWO original by subhagghosh and edit by Pumpith (Filter)") over_bought_level = input.int(53, 'Over Bought Level', group="Subhag + TSD + EWO original by subhagghosh and edit by Pumpith (Filter)") over_sold_level = input.int(-53, 'Over Sold Level', group="Subhag + TSD + EWO original by subhagghosh and edit by Pumpith (Filter)") sma1length = input(5, group="Subhag + TSD + EWO original by subhagghosh and edit by Pumpith (Filter)") sma2length = input(35, group="Subhag + TSD + EWO original by subhagghosh and edit by Pumpith (Filter)") UsePercent = input(title='Show Dif as percent of current Candle', defval=true, group="Subhag + TSD + EWO original by subhagghosh and edit by Pumpith (Filter)") conditionType = input.string(ord_con_4, "Open order type", options=[ord_con_1, ord_con_2, ord_con_3, ord_con_4, ord_con_5]) order_size = input.float(0.001, 'Order Size', minval=0.001, step=0.1, tooltip="order size 1:Price e.g 1:38000(BTCUSDTPERP)", group="Alert Message and order Management") leverage_mult = input.int(10, 'Leverage Size', minval=1, step=1, group="Alert Message and order Management") close_order_type = input.string('Condition', 'Close Order Option', options=['RR', 'Condition'], group="Alert Message and order Management") rrUseAutoSL = input.bool(false, 'Use auto Calculate Stoploss', group="Alert Message and order Management") rrAutoSLType = input.string('Zigma Swing H/L', "Open order type", options=['Zigma Swing H/L', 'Candle Swing H/L'], group="Alert Message and order Management") rrAutoSLCalLength = input.int(5, 'Auto SL Calculate Length', tooltip="Use for fing Lowest and Highest.", step=1, minval=1, group="Alert Message and order Management") SLPer = input.float(1.00, "RR Stoploss percent", minval = 0.1, step=0.1, group="Alert Message and order Management")/100 rrPer = input.float(2.00, "RR ratio", minval = 0.1, step=0.1, group="Alert Message and order Management") msg_open_long = input.string('Open Long', 'Alert Message Long', group="Alert Message and order Management") msg_open_short = input.string('Open Short', 'Alert Message Short', group="Alert Message and order Management") msg_close_long = input.string('Close Long', 'Alert Message Close Long', group="Alert Message and order Management") msg_close_short = input.string('Close Short', 'Alert Message Close Short', group="Alert Message and order Management") // -------------------------------------------- Fibonacci Impulse ----------------------------------------------------- [FL236M, FL382M, FL500M, FL618M, FL786M, FL0,FL236, FL382, FL500, FL618, FL786, FL1000, FL1236, FL1382, FL1500, FL1618, FL1786, FL2] = request.security(syminfo.tickerid, fibo_level_session, autoFibo.original(fibo_lookback_length, low, high), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off) src = switch fibo_level_source '0.618' => FL618 '0.786' => FL786 '0.5' => FL500 '0.382' => FL382 '0.236' => FL236 //src = switch fibo_level_source // '0.618' => FL618 // '0.786' => FL786 // '0.5' => FL500 // '0.382' => FL382 // '0.236' => FL236 // CDC Impulse candle data open_p = ta.ema(src, 26) close_p = ta.ema(src, 12) high_p = ta.highest(close_p, 4) low_p = ta.lowest(close_p, 4) // ------------------------------ controller ----------------------------------- // tradingview's DMI setDMI () => float diplus = 0.0 float diminus = 0.0 float adx = 0.0 [diplus_4h, diminus_4h, adx_4h] = request.security(syminfo.tickerid, "240", ta.dmi(14, 14), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off) [diplus_1h, diminus_1h, adx_1h] = request.security(syminfo.tickerid, "60", ta.dmi(14, 14), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off) [diplus_15m, diminus_15m, adx_15m] = request.security(syminfo.tickerid, "15", ta.dmi(14, 14), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off) if fibo_level_session == 'LongTrade(4H)' diplus := diplus_4h diminus := diminus_4h adx := adx_4h else if fibo_level_session == 'MediumTrade(1H)' diplus := diplus_1h diminus := diminus_1h adx := adx_1h else diplus := diplus_15m diminus := diminus_15m adx := adx_15m [diplus, diminus, adx] [diplus, diminus, adx] = setDMI() // Alex Orekhov (everget)'s Chandelier Exit atr = ce_mult * ta.atr(ce_length) longStop = ta.highest(ce_length) - atr longStopPrev = nz(longStop[1], longStop) longStop := close[1] > longStopPrev ? math.max(longStop, longStopPrev) : longStop shortStop = ta.lowest(ce_length) + atr shortStopPrev = nz(shortStop[1], shortStop) shortStop := close[1] < shortStopPrev ? math.min(shortStop, shortStopPrev) : shortStop var int dir = 1 dir := close > shortStopPrev ? 1 : close < longStopPrev ? -1 : dir // Subhag + TSD + EWO original by subhagghosh and edit by Pumpith ///////////////////////////////////////////////////////////////////// // Check Trend Strength ha_t = syminfo.tickerid col_red = #ff0000 col_green = #00ff00 TSB = true TSS = false trend_60 = request.security(ha_t, res_60, (ta.ema(src_sh, fast_length) - ta.ema(src_sh, slow_length)) / src_sh * 100) prev_trend_60 = request.security(ha_t, res_60, (ta.ema(src_sh[5], fast_length) - ta.ema(src_sh[5], slow_length)) / src_sh[5] * 100) trend_status_60 = trend_60 > prev_trend_60 /////////////////////////////////////////////////////////////////// //End of checking stength myrsi = ta.rsi(close, rsi_period) rsi1 = ta.crossunder(myrsi, 70) rsi2 = myrsi > 75 // Regression Lines cc(x) => x == 'Red' ? color.red : x == 'Lime' ? color.lime : x == 'Orange' ? color.orange : x == 'Teal' ? color.teal : x == 'Yellow' ? color.yellow : x == 'Black' ? color.black : color.white data(x) => ta.ema(request.security(syminfo.tickerid, mtf_val != '' ? mtf_val : timeframe.period, x), smoothing) linreg = data(ta.linreg(source, length, offset)) linreg_p = data(ta.linreg(source, length, offset + 1)) // Regression End //################################## // TSD //################################## //// Indicators // Blue Wave 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) // MFI mfi_upper = math.sum(volume * (ta.change(hlc3) <= 0 ? 0 : hlc3), 58) mfi_lower = math.sum(volume * (ta.change(hlc3) >= 0 ? 0 : hlc3), 58) _mfi_rsi(mfi_upper, mfi_lower) => if mfi_lower == 0 100 if mfi_upper == 0 0 100.0 - 100.0 / (1.0 + mfi_upper / mfi_lower) mf = _mfi_rsi(mfi_upper, mfi_lower) mfi = (mf - 50) * 3 //// Plots mfi_color = mfi > 0 ? #4CAF50 : #FF5252 dot_color = wt1 < wt2 ? #FF0000 : #4CAF50 //################################## // EWO //################################## //@author Koryu //src = input(close, title="source") sma_1 = ta.sma(src, sma1length) sma_2 = ta.sma(src, sma2length) sma_3 = ta.sma(src, sma1length) sma_4 = ta.sma(src, sma2length) smadif = UsePercent ? (sma_1 - sma_2) / src * 100 : sma_3 - sma_4 //col=smadif <= 0 ? red : green //plot(smadif, color=col, style=histogram, linewidth=2) //----------------------------------------------- Plot & Order -----------------------------------------------// // fibonacci impulse candle_color = open_p < close_p ? color.new(color.green, isShowCandleMode ? 60 : 100) : (open_p > close_p ? color.new(color.red, isShowCandleMode ? 60 : 100) : color.new(color.white, isShowCandleMode ? 60 : 100)) line_color = open_p < close_p ? color.new(color.green, isShowCandleMode ? 100 : 0) : (open_p > close_p ? color.new(color.red, isShowCandleMode ? 100 : 0) : color.new(color.white, isShowCandleMode ? 100 : 0)) plotcandle(open_p, high_p, low_p, close_p, "Fibo Level Candle", color=candle_color, wickcolor=candle_color, bordercolor=candle_color) //plot(close > open_p ? open_p : na, title='Zigma Bull impulse', style=plot.style_linebr, linewidth=2, color=color.lime) //plot(close < open_p ? open_p : na, title='Zigma Bear impulse', style=plot.style_linebr, linewidth=2, color=color.red) var color longColor = color.green var color shortColor = color.red // Sunhag hullColor = switchColor ? linreg > linreg[1] ? #00ff00 : #ff0000 : #ff9800 //PLOT Fi1 = plot(isShowFilterIndicator_subh ? linreg : na, title='Regression Line', color=hullColor, linewidth=thicknesSwitch, transp=50) Fi2 = plot(visualSwitch and isShowFilterIndicator_subh ? linreg[3] : na, title='RL', color=hullColor, linewidth=thicknesSwitch, transp=50) fill(Fi1, Fi2, title='Band Filler', color=hullColor, transp=transpSwitch) // CE longStopPlot = plot(isShowFilterIndicator_ce ? (dir == 1 ? longStop : na) : na, title='Long Stop', style=plot.style_linebr, linewidth=2, color=color.new(longColor, 0)) buySignal = dir == 1 and dir[1] == -1 plotshape(buySignal and isShowFilterIndicator_ce ? longStop : na, title='Long Stop Start', location=location.absolute, style=shape.circle, size=size.tiny, color=color.new(longColor, 0)) shortStopPlot = plot(isShowFilterIndicator_ce ? (dir == 1 ? na : shortStop) : na, title='Short Stop', style=plot.style_linebr, linewidth=2, color=color.new(shortColor, 0)) sellSignal = dir == -1 and dir[1] == 1 plotshape(sellSignal and isShowFilterIndicator_ce ? shortStop : na, title='Short Stop Start', location=location.absolute, style=shape.circle, size=size.tiny, color=color.new(shortColor, 0)) midPricePlot = plot(ohlc4, title='', style=plot.style_circles, linewidth=0, display=display.none, editable=false) //-----------------------------------------------------------------------------------------------------------// //----------------------------------------------- order -----------------------------------------------// position_avg_price = strategy.position_avg_price position_size = strategy.position_size //*************************** Indicator Condition *****************************// // Fibonacci Impulse fibo_impulse_bear_over = ta.crossunder(close, open_p) fibo_impulse_bull_over = ta.crossover(close, open_p) // DMI dmi_Bull = diplus >= 25 and diplus > adx dmi_Bear = diminus >= 25 and diminus > adx // CE ce_bull_rejection = dir == 1 and dir[1] != 1 ce_bear_rejection = dir != 1 and dir[1] == 1 ce_bull_controll = dir == 1 ce_bear_controll = dir != 1 // subhag sh_bull = close > linreg and close > linreg[3] sh_bear = close < linreg and close < linreg[3] //*************************** END Indicator Condition *****************************// //*************** Original ***************// LongCondition = fibo_impulse_bull_over and (ce_bull_controll or ce_bull_rejection) and sh_bull and position_size == 0.0 ShortCondition = fibo_impulse_bear_over and (ce_bear_controll or ce_bear_rejection) and sh_bear and position_size == 0.0 //***************************************// //*************** Original Extra ***************// LongCondition_extra = fibo_impulse_bull_over and dmi_Bull and (ce_bull_controll or ce_bull_rejection) and sh_bull and position_size == 0.0 ShortCondition_extra = fibo_impulse_bear_over and dmi_Bear and (ce_bear_controll or ce_bear_rejection) and sh_bear and position_size == 0.0 //***************************************// //*************** Original 0 ***************// LongCondition_std1 = fibo_impulse_bull_over and (ce_bull_controll or ce_bull_rejection) and position_size == 0.0 ShortCondition_std1 = fibo_impulse_bear_over and (ce_bear_controll or ce_bear_rejection) and position_size == 0.0 //***************************************// //*************** Original 0 Extra ***************// LongCondition_std1extra = fibo_impulse_bull_over and dmi_Bull and (ce_bull_controll or ce_bull_rejection) and position_size == 0.0 ShortCondition_std1extra = fibo_impulse_bear_over and dmi_Bear and (ce_bear_controll or ce_bear_rejection) and position_size == 0.0 //***************************************// //*************** Original Combination ***************// LongCondition_Comb = LongCondition or LongCondition_extra or LongCondition_std1 or LongCondition_std1extra ShortCondition_Comb = ShortCondition or ShortCondition_extra or ShortCondition_std1 or ShortCondition_std1extra //***************************************// // plot Label plotshape(conditionType == 'Original (Zigma Candle + CE + Subhag)' ? LongCondition : na, title='Buy Signal Label', text='Buy', location=location.belowbar, style=shape.labelup, size=size.tiny, color=color.lime, textcolor=color.new(color.white, 0)) plotshape(conditionType == 'Original (Zigma Candle + CE + Subhag)' ? ShortCondition : na, title='Sell Signal Label', text='Sell', location=location.abovebar, style=shape.labeldown, size=size.tiny, color=color.red, textcolor=color.new(color.white, 0)) plotshape(conditionType == 'Original Extra (Zigma Candle with DMI + CE + Subhag)' ? LongCondition_extra : na, title='Buy Signal Label', text='Buy', location=location.belowbar, style=shape.labelup, size=size.tiny, color=color.lime, textcolor=color.new(color.white, 0)) plotshape(conditionType == 'Original Extra (Zigma Candle with DMI + CE + Subhag)' ? ShortCondition_extra : na, title='Sell Signal Label', text='Sell', location=location.abovebar, style=shape.labeldown, size=size.tiny, color=color.red, textcolor=color.new(color.white, 0)) plotshape(conditionType == 'Original 0 (Zigma + CE)' ? LongCondition_std1 : na, title='Buy Signal Label', text='Buy', location=location.belowbar, style=shape.labelup, size=size.tiny, color=color.lime, textcolor=color.new(color.white, 0)) plotshape(conditionType == 'Original 0 (Zigma + CE)' ? ShortCondition_std1 : na, title='Sell Signal Label', text='Sell', location=location.abovebar, style=shape.labeldown, size=size.tiny, color=color.red, textcolor=color.new(color.white, 0)) plotshape(conditionType == 'Original 0 Extra (Zigma with DMI + CE)' ? LongCondition_std1extra : na, title='Buy Signal Label', text='Buy', location=location.belowbar, style=shape.labelup, size=size.tiny, color=color.lime, textcolor=color.new(color.white, 0)) plotshape(conditionType == 'Original 0 Extra (Zigma with DMI + CE)' ? ShortCondition_std1extra : na, title='Sell Signal Label', text='Sell', location=location.abovebar, style=shape.labeldown, size=size.tiny, color=color.red, textcolor=color.new(color.white, 0)) plotshape(conditionType == 'Original Combination (Combo since Original to Original 0)' ? LongCondition_Comb : na, title='Buy Signal Label', text='Buy', location=location.belowbar, style=shape.labelup, size=size.tiny, color=color.lime, textcolor=color.new(color.white, 0)) plotshape(conditionType == 'Original Combination (Combo since Original to Original 0)' ? ShortCondition_Comb : na, title='Sell Signal Label', text='Sell', location=location.abovebar, style=shape.labeldown, size=size.tiny, color=color.red, textcolor=color.new(color.white, 0)) // open order if conditionType == 'Original (Zigma Candle + CE + Subhag)' strategy.order('Long', strategy.long, order_size*leverage_mult, when=LongCondition, alert_message=msg_open_long) strategy.order('Short', strategy.short, order_size*leverage_mult, when=ShortCondition, alert_message=msg_open_short) else if conditionType == 'Original Extra (Zigma Candle with DMI + CE + Subhag)' strategy.order('Long', strategy.long, order_size*leverage_mult, when=LongCondition_extra, alert_message=msg_open_long) strategy.order('Short', strategy.short, order_size*leverage_mult, when=ShortCondition_extra, alert_message=msg_open_short) else if conditionType == 'Original 0 (Zigma + CE)' strategy.order('Long', strategy.long, order_size*leverage_mult, when=LongCondition_std1, alert_message=msg_open_long) strategy.order('Short', strategy.short, order_size*leverage_mult, when=ShortCondition_std1, alert_message=msg_open_short) else if conditionType == 'Original 0 Extra (Zigma with DMI + CE)' strategy.order('Long', strategy.long, order_size*leverage_mult, when=LongCondition_std1extra, alert_message=msg_open_long) strategy.order('Short', strategy.short, order_size*leverage_mult, when=ShortCondition_std1extra, alert_message=msg_open_short) else if conditionType == 'Original Combination (Combo since Original to Original 0)' strategy.order('Long', strategy.long, order_size*leverage_mult, when=LongCondition_Comb, alert_message=msg_open_long) strategy.order('Short', strategy.short, order_size*leverage_mult, when=ShortCondition_Comb, alert_message=msg_open_short) // exit order // sltp float auto_sl_high = 0.0 float auto_sl_low = 0.0 if rrAutoSLType == 'Zigma Swing H/L' auto_sl_high := ta.highest(high_p, rrAutoSLCalLength) auto_sl_low := ta.lowest(low_p, rrAutoSLCalLength) else auto_sl_high := ta.highest(high, rrAutoSLCalLength) auto_sl_low := ta.lowest(low, rrAutoSLCalLength) float sl_percent_bull = 0.0 float sl_percent_bear = 0.0 sl_percent_bull_auto = sl_percent_bull[1] == 0.0 and position_size != 0 ? (position_avg_price - auto_sl_low)/position_avg_price : (position_size != 0 ? sl_percent_bull[1] : 0.0) sl_percent_bull_fix = sl_percent_bull[1] == 0.0 and position_size != 0 ? SLPer : 0.0 sl_percent_bull := rrUseAutoSL ? sl_percent_bull_auto : sl_percent_bull_fix stopPriceBull = position_avg_price * (1 - sl_percent_bull) takeProfitBull = position_avg_price * (1 + (sl_percent_bull*rrPer)) sl_percent_bear_auto = sl_percent_bear[1] == 0.0 and position_size != 0 ? (auto_sl_high - position_avg_price) / position_avg_price : (position_size != 0 ? sl_percent_bear[1] : 0.0) sl_percent_bear_fix = sl_percent_bear[1] == 0.0 and position_size != 0 ? SLPer : 0.0 sl_percent_bear := rrUseAutoSL ? sl_percent_bear_auto : sl_percent_bear_fix stopPriceBear = position_avg_price * (1 + sl_percent_bear) takeProfitBear = position_avg_price * (1 - (sl_percent_bear*rrPer)) plot(close_order_type == 'RR' ? (position_size < 0 ? stopPriceBear : stopPriceBull) : na, "Short's SL Line", style=plot.style_linebr, color=color.red) plot(close_order_type == 'RR' ? (position_size < 0 ? takeProfitBear : takeProfitBull) : na, "Short's TP Line", style=plot.style_linebr, color=color.green) // Condition closeLongCondition = (ta.crossunder(close, open_p) or close < open_p) and (ce_bear_controll or ce_bear_rejection) closeShortCondition = (ta.crossover(close, open_p) or close > open_p) and (ce_bull_controll or ce_bull_rejection) // Plot Label //plotshape(conditionType == 'Original (Zigma Candle + CE + Subhag)' ? closeLongCondition : na, title='Close Buy Signal Label', text='Close Buy', location=location.belowbar, style=shape.labelup, size=size.tiny, color=color.lime, textcolor=color.new(color.white, 0)) //plotshape(conditionType == 'Original (Zigma Candle + CE + Subhag)' ? closeLongCondition : na, title='Close Sell Signal Label', text='Close Sell', location=location.abovebar, style=shape.labeldown, size=size.tiny, color=color.red, textcolor=color.new(color.white, 0)) // //plotshape(conditionType == 'Original Extra (Zigma Candle with DMI + CE + Subhag)' ? closeLongCondition : na, title='Close Buy Signal Label', text='Close Buy', location=location.belowbar, style=shape.labelup, size=size.tiny, color=color.lime, textcolor=color.new(color.white, 0)) //plotshape(conditionType == 'Original Extra (Zigma Candle with DMI + CE + Subhag)' ? closeLongCondition : na, title='Close Sell Signal Label', text='Close Sell', location=location.abovebar, style=shape.labeldown, size=size.tiny, color=color.red, textcolor=color.new(color.white, 0)) // //plotshape(conditionType == 'Standard 1 (Zigma + CE)' ? closeLongCondition : na, title='Close Buy Signal Label', text='Close Buy', location=location.belowbar, style=shape.labelup, size=size.tiny, color=color.lime, textcolor=color.new(color.white, 0)) //plotshape(conditionType == 'Standard 1 (Zigma + CE)' ? closeLongCondition : na, title='Close Sell Signal Label', text='Close Sell', location=location.abovebar, style=shape.labeldown, size=size.tiny, color=color.red, textcolor=color.new(color.white, 0)) if conditionType == 'Original (Zigma Candle + CE + Subhag)' or conditionType == 'Original Extra (Zigma Candle with DMI + CE + Subhag)' or conditionType == 'Original 0 (Zigma + CE)' or conditionType == 'Original 0 Extra (Zigma with DMI + CE)' or conditionType == 'Original Combination (Combo since Original to Original 0)' if close_order_type == 'RR' strategy.exit('Exit Long', 'Long', stop=stopPriceBull,limit=takeProfitBull, alert_message=msg_close_long) strategy.exit('Exit Short', 'Short', stop=stopPriceBear,limit=takeProfitBear, alert_message=msg_close_short) else strategy.close('Long', when=closeLongCondition, qty_percent=100, alert_message=msg_close_long) strategy.close('Short', when=closeShortCondition, qty_percent=100, alert_message=msg_close_short) // เงื่อนไขการเข้าแบบใหม่ให้ใช้ตัว CE กับ Impulse Candle เป็นตัว trigger แล้วแต่กรณีหากอยู่เหนือ IC ให้ใช้ CE
Triple Supertrend with EMA and ADX strategy
https://www.tradingview.com/script/ChaVrUF9-Triple-Supertrend-with-EMA-and-ADX-strategy/
kunjandetroja
https://www.tradingview.com/u/kunjandetroja/
224
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/ // ©kunjandetroja //@version=5 strategy('Triple Supertrend with EMA and ADX', overlay=true) m1 = input.float(1,"ATR Multi",minval = 1,maxval= 6,step=0.5,group='ST 1') m2 = input.float(2,"ATR Multi",minval = 1,maxval= 6,step=0.5,group='ST 2') m3 = input.float(3,"ATR Multi",minval = 1,maxval= 6,step=0.5,group='ST 3') p1 = input.int(10,"ATR Multi",minval = 5,maxval= 25,step=1,group='ST 1') p2 = input.int(15,"ATR Multi",minval = 5,maxval= 25,step=1,group='ST 2') p3 = input.int(20,"ATR Multi",minval = 5,maxval= 25,step=1,group='ST 3') len_EMA = input.int(200,"EMA Len",minval = 5,maxval= 250,step=1) len_ADX = input.int(14,"ADX Len",minval = 1,maxval= 25,step=1) len_Di = input.int(14,"Di Len",minval = 1,maxval= 25,step=1) adx_above = input.float(25,"adx filter",minval = 1,maxval= 50,step=0.5) var bool long_position = false adx_filter = input.bool(false, "Add Adx & EMA filter") renetry = input.bool(true, "Allow Reentry") f_getColor_Resistance(_dir, _color) => _dir == 1 and _dir == _dir[1] ? _color : na f_getColor_Support(_dir, _color) => _dir == -1 and _dir == _dir[1] ? _color : na [superTrend1, dir1] = ta.supertrend(m1, p1) [superTrend2, dir2] = ta.supertrend(m2, p2) [superTrend3, dir3] = ta.supertrend(m3, p3) EMA = ta.ema(close, len_EMA) [diplus,diminus,adx] = ta.dmi(len_Di,len_ADX) // ADX Filter adxup = adx > adx_above and close > EMA adxdown = adx > adx_above and close < EMA sum_dir = dir1 + dir2 + dir3 dir_long = if(adx_filter == false) sum_dir == -3 else sum_dir == -3 and adxup dir_short = if(adx_filter == false) sum_dir == 3 else sum_dir == 3 and adxdown Exit_long = dir1 == 1 and dir1 != dir1[1] Exit_short = dir1 == -1 and dir1 != dir1[1] // BuySignal = dir_long and dir_long != dir_long[1] // SellSignal = dir_short and dir_short != dir_short[1] // if BuySignal // label.new(bar_index, low, 'Long', style=label.style_label_up) // if SellSignal // label.new(bar_index, high, 'Short', style=label.style_label_down) longenter = if(renetry == false) dir_long and long_position == false else dir_long shortenter = if(renetry == false) dir_short and long_position == true else dir_short if longenter long_position := true if shortenter long_position := false strategy.entry('BUY', strategy.long, when=longenter) strategy.entry('SELL', strategy.short, when=shortenter) strategy.close('BUY', Exit_long) strategy.close('SELL', Exit_short) buy1 = ta.barssince(dir_long) sell1 = ta.barssince(dir_short) colR1 = f_getColor_Resistance(dir1, color.red) colS1 = f_getColor_Support(dir1, color.green) colR2 = f_getColor_Resistance(dir2, color.orange) colS2 = f_getColor_Support(dir2, color.yellow) colR3 = f_getColor_Resistance(dir3, color.blue) colS3 = f_getColor_Support(dir3, color.maroon) plot(superTrend1, 'R1', colR1, linewidth=2) plot(superTrend1, 'S1', colS1, linewidth=2) plot(superTrend2, 'R1', colR2, linewidth=2) plot(superTrend2, 'S1', colS2, linewidth=2) plot(superTrend3, 'R1', colR3, linewidth=2) plot(superTrend3, 'S1', colS3, linewidth=2) // // Intraday only // var int new_day = na // var int new_month = na // var int new_year = na // var int close_trades_after_time_of_day = na // if dayofmonth != dayofmonth[1] // new_day := dayofmonth // if month != month[1] // new_month := month // if year != year[1] // new_year := year // close_trades_after_time_of_day := timestamp(new_year,new_month,new_day,15,15) // strategy.close_all(time > close_trades_after_time_of_day)
trading YM based on pair trading
https://www.tradingview.com/script/MjGR4Ful-trading-YM-based-on-pair-trading/
hkorange2007
https://www.tradingview.com/u/hkorange2007/
42
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © hkorange2007 //@version=5 strategy("pair trading") symbol1 = input.symbol("YM1!") symbol2 = input.symbol("NQ1!") security1Close = request.security(symbol1, timeframe.period, close) security2Open = request.security(symbol2, timeframe.period, open) security2High = request.security(symbol2, timeframe.period, high) security2Low = request.security(symbol2, timeframe.period, low) security2Close = request.security(symbol2, timeframe.period, close) ratio = security1Close / security2Close ratioSma = ta.sma(ratio, 200) diff = security1Close - security2Close * ratioSma [middle, upper, lower] = ta.bb(diff, 20, 2) plot(diff) plot(middle, color = color.orange) plot(upper, color = color.orange) plot(lower, color = color.orange) long = ta.crossunder(diff, lower) exitLong = ta.crossover(diff, middle) short = ta.crossover(diff, upper) exitShort = ta.crossunder(diff, middle) if long and strategy.position_size == 0 strategy.entry("enter long", strategy.long, 1) if short and strategy.position_size == 0 strategy.entry("enter short", strategy.short, 1) if (exitLong and strategy.position_size > 0) or (exitShort and strategy.position_size < 0) strategy.close_all()
CCI + EMA with RSI Cross Strategy
https://www.tradingview.com/script/DfHcH2NT-CCI-EMA-with-RSI-Cross-Strategy/
rwestbrookjr
https://www.tradingview.com/u/rwestbrookjr/
133
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("CCI + EMA with RSI Cross Strategy", overlay=true, margin_long=100, margin_short=100, process_orders_on_close=true) //EMA fastLen = input(title='Fast EMA Length', defval=9, group='EMA Settings') slowLen = input(title='Slow EMA Length', defval=20, group='EMA Settings') fastEMA = ta.ema(close, fastLen) slowEMA = ta.ema(close, slowLen) fema = plot(fastEMA, title='FastEMA', color=color.new(color.green, 0), linewidth=1, style=plot.style_line) sema = plot(slowEMA, title='SlowEMA', color=color.new(color.red, 0), linewidth=1, style=plot.style_line) fill(fema, sema, color=fastEMA > slowEMA ? color.new(#417505, 50) : color.new(#890101, 50), title='Cloud') // Bull and Bear Alerts //Bull = ta.crossover(fastEMA, slowEMA) Bull = fastEMA > slowEMA //Bear = ta.crossunder(fastEMA, slowEMA) Bear = fastEMA < slowEMA //RSIs rsiLength1Input = input.int(9, minval=1, title="Fast RSI Length", group="RSI Settings") rsiSource1Input = input.source(close, "Fast RSI Source", group="RSI Settings") rsiLength2Input = input.int(20, minval=1, title="Slow RSI Length", group="RSI Settings") rsiSource2Input = input.source(close, "Slow RSI Source", group="RSI Settings") up1 = ta.rma(math.max(ta.change(rsiSource1Input), 0), rsiLength1Input) down1 = ta.rma(-math.min(ta.change(rsiSource1Input), 0), rsiLength1Input) rsi = down1 == 0 ? 100 : up1 == 0 ? 0 : 100 - (100 / (1 + up1 / down1)) up2 = ta.rma(math.max(ta.change(rsiSource2Input), 0), rsiLength2Input) down2 = ta.rma(-math.min(ta.change(rsiSource2Input), 0), rsiLength2Input) rsi2 = down2 == 0 ? 100 : up2 == 0 ? 0 : 100 - (100 / (1 + up2 / down2)) rsiBull = rsi > rsi2 and rsi > rsi[1] rsiBear = rsi < rsi2 and rsi < rsi[1] //CCI cciLength = input.int(title='CCI Length', group='CCI Settings', defval=20, minval=1) src = input(hlc3, title='CCI Source', group='CCI Settings') ma = ta.sma(src, cciLength) cci = (src - ma) / (0.015 * ta.dev(src, cciLength)) cciCut = input.int(title = 'CCI Cutoff', group='CCI Settings', defval = 50) cciBull = cci > cciCut cciBear = cci < cciCut * -1 //Trail Stop Setup trstp = input.float(title="Trail Loss ($)", group='Stop Settings', minval = 0.0, step = 0.01, defval = 0.67) longStop = 0.0, shortStop = 0.0 longStop := if Bull or strategy.position_size > 0 stopValue = slowEMA - trstp math.max(stopValue, longStop[1]) else 0.0 shortStop := if Bear or strategy.position_size < 0 stopValue = slowEMA + trstp math.min(stopValue, shortStop[1]) else 999999 plotshape(title='Short Stop', series=shortStop != 999999 and strategy.opentrades > 0 and strategy.position_size < 0 ? shortStop : na, style=shape.cross, color=color.yellow, location=location.absolute) plotshape(title='Long Stop', series=longStop != 0.0 and strategy.opentrades > 0 and strategy.position_size > 0 ? longStop : na,style=shape.cross, color=color.yellow, location=location.absolute) //Session Setup open_session=input.session(title='Session',group='Session Settings', defval="0930-1545") session = time("1", open_session) validSession=(na(session) ? 0 : 1) //Trade Signals //longCondition = Bull and cci > cciCut and ta.crossover(rsi,rsi2) and validSession longCondition = cciBull and ta.crossover(rsi,rsi2) and close > slowEMA and validSession //longCondition = cciBull and ta.crossover(rsi,rsi2) and Bull and validSession if (longCondition) strategy.entry("Long", strategy.long, 100) //longExit = close > strategy.opentrades.entry_price(0) + 1.5 or close < strategy.opentrades.entry_price(0) - 0.75 longExit = close < longStop or not validSession //longExit = ta.crossunder(low,longStop) or not validSession if (longExit) strategy.close("Long") //shortCondition = Bear and cci < (cciCut*-1) and ta.crossunder(rsi,rsi2) and validSession shortCondition = cciBear and ta.crossunder(rsi,rsi2) and close < slowEMA and validSession //shortCondition = cciBear and ta.crossunder(rsi,rsi2) and Bear and validSession if (shortCondition) strategy.entry("Short", strategy.short, 100) //shortExit = close < strategy.opentrades.entry_price(0) - 1.5 or close > strategy.opentrades.entry_price(0) + 0.75 shortExit = close > shortStop or not validSession //shortExit = ta.crossover(high, shortStop) or not validSession if (shortExit) strategy.close("Short")
5 Minute EMA Cross Strategy
https://www.tradingview.com/script/1QBCl9Kv-5-Minute-EMA-Cross-Strategy/
jordanfray
https://www.tradingview.com/u/jordanfray/
199
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="5 Minute EMA 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) max_bars_back(time, 5000) // Indenting Classs indent_1 = " " indent_2 = "  " indent_3 = "   " indent_4 = "    " // Group Titles group_one_title = "EMA Settings" group_two_title = "Entry Settings" group_three_title = "Trade Filters" // Input Tips 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,85) light_green = color.new(#2DBD85,85) light_red = color.new(#E02A4A,85) light_yellow = color.new(#FFF900,85) white = color.new(#ffffff,0) light_gray = color.new(#000000,70) transparent = color.new(#000000,100) // Strategy Settings - EMA fast_EMA_length = input.int(defval=20, minval=1, title="Fast Length", group=group_one_title) fast_EMA_type = input.string(defval="EMA", options = ["EMA", "SMA", "RMA", "WMA"], title=indent_4+"Type", group=group_one_title) fast_EMA_source = input.source(defval=close, title=indent_4+"Source", group=group_one_title) fast_EMA = switch fast_EMA_type "EMA" => ta.ema(fast_EMA_source, fast_EMA_length) "SMA" => ta.sma(fast_EMA_source, fast_EMA_length) "RMA" => ta.rma(fast_EMA_source, fast_EMA_length) "WMA" => ta.wma(fast_EMA_source, fast_EMA_length) => na plot(fast_EMA, title="Fast EMA", linewidth=1, color=green, editable=true) slow_EMA_length = input.int(defval=100, minval=1, title="Slow Length", group=group_one_title) slow_EMA_type = input.string(defval="EMA", options = ["EMA", "SMA", "RMA", "WMA"], title=indent_4+"Type", group=group_one_title) slow_EMA_source = input.source(defval=close, title=indent_4+"Source", group=group_one_title) slow_EMA = switch slow_EMA_type "EMA" => ta.ema(slow_EMA_source, slow_EMA_length) "SMA" => ta.sma(slow_EMA_source, slow_EMA_length) "RMA" => ta.rma(slow_EMA_source, slow_EMA_length) "WMA" => ta.wma(slow_EMA_source, slow_EMA_length) => na plot(slow_EMA, title="Slow EMA", linewidth=1, color=sky_blue, editable=true) // EMA Macro Filter enable_EMA_filter = input.bool(defval=false, title="Use EMA Filter", group=group_three_title) EMA_filter_timeframe = input.timeframe(defval="", title=indent_4+"Timeframe", group=group_three_title) EMA_filter_length = input.int(defval=300, minval=1, step=10, title=indent_4+"Length", group=group_three_title) EMA_filter_source = input.source(defval=hl2, title=indent_4+"Source", group=group_three_title) ema_filter = ta.ema(EMA_filter_source, EMA_filter_length) ema_filter_smoothed = request.security(syminfo.tickerid, EMA_filter_timeframe, ema_filter[barstate.isrealtime ? 1 : 0], gaps=barmerge.gaps_on) plot(enable_EMA_filter ? ema_filter_smoothed: na, title="EMA Macro Filter", linewidth=2, color=white, editable=true) // Entry Settings stop_loss_val = input.float(defval=2.0, title="Stop Loss (%)", step=0.1, group=group_two_title)/100 take_profit_val = input.float(defval=2.0, title="Take Profit (%)", step=0.1, group=group_two_title)/100 long_entry_limit_lookback = input.int(defval=3, title="Long Entry Limit Lookback", minval=1, step=1, group=group_two_title) short_entry_limit_lookback = input.int(defval=3, title="Short Entry Limit Lookback", minval=1, step=1, group=group_two_title) limit_order_long_price = ta.lowest(low, long_entry_limit_lookback) limit_order_short_price = ta.highest(high, short_entry_limit_lookback) start_trailing_after = input.float(defval=1, title="Start Trailing After (%)", step=0.1, group=group_two_title)/100 trail_behind = input.float(defval=1, title="Trail Behind (%)", step=0.1, group=group_two_title)/100 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) long_stop_loss = strategy.position_avg_price * (1.0 - stop_loss_val) short_profit_target = strategy.position_avg_price * (1 - take_profit_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 plot(bars_since_entry, editable=false, title="Bars Since Entry", color=green) long_run_up = ta.highest(high, 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 // long_run_up_line = plot(long_run_up, style=plot.style_stepline, editable=false, color=currently_in_a_long_postion ? green : transparent) 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_run_up = ta.lowest(low, bars_since_entry) 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 // short_run_up_line = plot(short_run_up, style=plot.style_stepline, editable=false, color=currently_in_a_short_postion ? green : 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) // Trade Conditions fast_EMA_cross_down_slow_EMA = ta.crossunder(fast_EMA,slow_EMA) fast_EMA_cross_up_slow_EMA = ta.crossover(fast_EMA,slow_EMA) plotshape(fast_EMA_cross_down_slow_EMA ? close : na, title="Short Entry Symbol", color=red, style=shape.triangledown, location=location.belowbar) plotshape(fast_EMA_cross_up_slow_EMA ? close : na, title="Long Entry Symbol", color=green, style=shape.triangleup, location=location.abovebar) fast_EMA_is_above_slow_EMA = fast_EMA > slow_EMA fast_EMA_is_below_slow_EMA = fast_EMA < slow_EMA ema_macro_filter_longs_only = fast_EMA > ema_filter_smoothed and slow_EMA > ema_filter_smoothed ema_macro_filter_shorts_only = fast_EMA < ema_filter_smoothed and slow_EMA < ema_filter_smoothed long_position_take_profit = ta.cross(close, long_trailing_stop) or close > long_profit_target short_position_take_profit = ta.cross(close, short_trailing_stop) or close > short_profit_target long_conditions_met = enable_EMA_filter ? ema_macro_filter_longs_only and fast_EMA_cross_up_slow_EMA and fast_EMA_is_above_slow_EMA and not currently_in_a_short_postion : fast_EMA_cross_up_slow_EMA and not currently_in_a_short_postion short_conditions_met = enable_EMA_filter ? ema_macro_filter_shorts_only and fast_EMA_cross_down_slow_EMA and fast_EMA_is_below_slow_EMA and not currently_in_a_long_postion : fast_EMA_cross_down_slow_EMA and fast_EMA_is_below_slow_EMA and not currently_in_a_long_postion // Long Entry strategy.entry(id="Long", direction=strategy.long, limit=limit_order_long_price, when=long_conditions_met) strategy.cancel(id="Cancel Long", when=ta.crossover(fast_EMA,slow_EMA)) strategy.exit(id="Close Long", from_entry="Long", stop=long_trailing_stop, limit=long_profit_target, when=long_position_take_profit) // Short Entry strategy.entry(id="Short", direction=strategy.short, limit=limit_order_short_price, when=short_conditions_met) strategy.cancel(id="Cancel Short", when=ta.crossunder(fast_EMA,slow_EMA)) strategy.exit(id="Close Short", from_entry="Short", stop=short_trailing_stop, limit=short_profit_target, when=short_position_take_profit) 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) //ltp = plot(currently_in_a_long_postion ? long_profit_target : na, style=plot.style_stepline, title="Take Profit", color=currently_in_a_long_postion ? green : transparent, linewidth=1) //lsl = plot(currently_in_a_long_postion ? long_stop_loss : na, style=plot.style_stepline, title="Take Profit", color=currently_in_a_long_postion ? red : transparent, linewidth=1) //fill(entry,ltp, color= currently_in_a_long_postion ? light_green : light_red) //fill(entry,lsl, color= currently_in_a_long_postion ? light_red : light_green) //stp = plot(currently_in_a_short_postion ? short_profit_target : na, style=plot.style_stepline, title="Take Profit", color=currently_in_a_short_postion ? green : transparent, linewidth=1) //ssl = plot(currently_in_a_short_postion ? short_stop_loss : na, style=plot.style_stepline, title="Take Profit", color=currently_in_a_short_postion ? red : transparent, linewidth=1) //fill(entry,stp, color= currently_in_a_short_postion ? light_green : light_red) //fill(entry,ssl, color= currently_in_a_short_postion ? light_red : light_green)
EMA Stoch Strategy For ProfitView
https://www.tradingview.com/script/tO1EpDDS-EMA-Stoch-Strategy-For-ProfitView/
treigen
https://www.tradingview.com/u/treigen/
137
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ //@version=5 strategy(title="EMA Stoch Strategy For ProfitView", overlay=true, calc_on_every_tick=true, process_orders_on_close=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=0.1, initial_capital=1000) // Take profit & stop loss TakeProfitPercent = input.float(defval = 0.0, title="Take Profit (%) [0 = Disabled]",minval = 0, step=.25,group='TP / SL') StopLossPercent = input.float(defval = 0.0, title="Stop Loss (%) [0 = Disabled]",minval = 0, step=.25,group='TP / SL') // Stoch lenghtStoch = input.int(14, "Stochastic Length", minval=1,group='Stochastic') smoothK = input.int(1, title="K Smoothing", minval=1,group='Stochastic') periodD = input.int(3, title="D Smoothing", minval=1,group='Stochastic') lenghtRSI= input.int(0, "RSI Length [0 = Disabled]", tooltip="If enabled, use Stoch Rsi. If disabled, use plain Stoch", minval=0, inline="rsi",group='Stochastic') src = input(close, title="", inline="rsi",group='Stochastic') rsi1 = lenghtRSI > 0 ? ta.rsi(src, lenghtRSI) : na k = lenghtRSI > 0 ? ta.sma(ta.stoch(rsi1, rsi1, rsi1, lenghtStoch), smoothK) : ta.sma(ta.stoch(close, high, low, lenghtStoch), smoothK) d = ta.sma(k, periodD) plot(k, title="K", color=color.new(#2962FF, 100)) plot(d, title="D", color=color.new(#FF6D00, 100)) bgcolor(color=color.from_gradient(k, 0, 100, color.new(#2962FF, 100), color.new(#2962FF, 90)), title="K BG") bgcolor(color=color.from_gradient(d, 0, 100, color.new(#FF6D00, 100), color.new(#FF6D00, 90)), title="D BG") // EMA len1= input(200,title='Length EMA ',group='EMA', inline="ema") src1= input(close,title='',group='EMA', inline="ema") ema1= ta.ema(src1,len1) plot(ema1,title='EMA',color= color.blue ,linewidth=2) // Signals LongVal= input(20,title='Stoch below/cross this value for Long signals',group='Signal Options') scegliLong= input.string('Stoch Below Value', options= ['Stoch Below Value' , 'K&D Cross Below Value' , 'Stoch CrossUp the Value'] , title='Long Signal Type') long1= scegliLong == 'Stoch Below Value' ? k < LongVal and d < LongVal and close > ema1 : na long2= scegliLong == 'K&D Cross Below Value' ? ta.cross(k,d) and k < LongVal and d < LongVal and close > ema1 : na long3= scegliLong == 'Stoch CrossUp the Value' ? ta.crossover(k,LongVal) and close > ema1 : na shortVal= input(80,title='Stoch above/cross this value for Short signals',group='Signal Options') scegliShort= input.string('Stoch Above Value', options= ['Stoch Above Value' , 'K&D Cross Above Value' , 'Stoch CrossDown the Value'] , title='Short Signal Type' ) short1= scegliShort == 'Stoch Above Value' ? k > shortVal and d > shortVal and close < ema1 : na short2= scegliShort == 'K&D Cross Above Value' ? ta.cross(k,d) and k > shortVal and d > shortVal and close < ema1 : na short3= scegliShort == 'Stoch CrossDown the Value' ? ta.crossunder(k,shortVal) and close < ema1 : na i_startTime = input.time(defval = timestamp("01 Jan 2014 00:00 +0000"), title = "Backtesting Start Time", inline="timestart", group='Backtesting') i_endTime = input.time(defval = timestamp("01 Jan 2100 23:59 +0000"), title = "Backtesting End Time", inline="timeend", group='Backtesting') timeCond = (time > i_startTime) and (time < i_endTime) pv_ex = input.string("deribit-testnet", title="Exchange", group='PV Settings') pv_sym = input.string("btc-perpetual", title="Symbol", group='PV Settings') pv_acc = input.string("", title="Account", group='PV Settings') pv_alert_long = input.string("", title="PV Alert Name Longs", group='PV Settings') pv_alert_short = input.string("", title="PV Alert Name Shorts", group='PV Settings') pv_alert_cancel = input.string("", title="PV Alert Name TP/SL", group='PV Settings') pv_lev = input.float(0.0, title="Leverage", minval=0.0, step=0.1, tooltip="Optional parameter for PV use. Does not affect backtest. Add leverage=_mylev to your PV order entry line if you want to specify it", group='PV Settings') profit_abs = (close * (TakeProfitPercent / 100)) stop_abs = (close * (StopLossPercent / 100)) ProfitTarget = TakeProfitPercent > 0 ? profit_abs / syminfo.mintick : na LossTarget = StopLossPercent > 0 ? stop_abs / syminfo.mintick : na // Position entry and alerts var entryprice = 0.0 var profitprice = 0.0 var stopprice = 0.0 var is_long = false var is_short = false is_tpsl_hit = (is_long and ((TakeProfitPercent > 0 and high > profitprice[1]) or (StopLossPercent > 0 and low < stopprice[1]))) or (is_short and ((TakeProfitPercent > 0 and low < profitprice[1]) or (StopLossPercent > 0 and high > stopprice[1]))) exsym = pv_ex == "" ? "" : "ex=" + pv_ex + "," exsym := pv_sym == "" ? exsym : exsym + "sym=" + pv_sym + "," if timeCond and not is_tpsl_hit and barstate.isconfirmed if ((long1 or long2 or long3) and not is_long) strategy.entry("Long", strategy.long) strategy.exit("Exit Long (TP/SL)", from_entry = "Long" , profit = ProfitTarget, loss = LossTarget) entryprice := close profitprice := entryprice+profit_abs stopprice := entryprice-stop_abs is_long := true is_short := false tpsl_str = TakeProfitPercent > 0 ? ",mytp=" + str.tostring(profitprice) : "" tpsl_str := StopLossPercent > 0 ? tpsl_str + ",mysl=" + str.tostring(stopprice) : tpsl_str alert(pv_alert_long + "(" + exsym + "acc=" + pv_acc + tpsl_str + ",mylev=" + str.tostring(pv_lev) + ")", alert.freq_once_per_bar_close) if ((short1 or short2 or short3) and not is_short) strategy.entry("Short", strategy.short) strategy.exit("Exit Short (TP/SL)", from_entry = "Short", profit = ProfitTarget, loss = LossTarget) entryprice := close profitprice := entryprice-profit_abs stopprice := entryprice+stop_abs is_long := false is_short := true tpsl_str = TakeProfitPercent > 0 ? ",mytp=" + str.tostring(profitprice) : "" tpsl_str := StopLossPercent > 0 ? tpsl_str + ",mysl=" + str.tostring(stopprice) : tpsl_str alert(pv_alert_short + "(" + exsym + "acc=" + pv_acc + tpsl_str + ",mylev=" + str.tostring(pv_lev) + ")", alert.freq_once_per_bar_close) if (is_tpsl_hit) alert(pv_alert_cancel + "(" + exsym + "acc=" + pv_acc + ")", alert.freq_once_per_bar) is_long := false is_short := false plot(entryprice, title="Entry Price", color=strategy.opentrades > 0 ? color.gray : color.new(color.gray, 100)) plot(profitprice, title="Profit Price", color=strategy.opentrades > 0 and TakeProfitPercent > 0 ? color.green : color.new(color.green, 100)) plot(stopprice, title="Stop Price", color=strategy.opentrades > 0 and StopLossPercent > 0? color.red : color.new(color.red, 100))
Oversold RSI with Tight Stop-Loss Strategy (by Coinrule)
https://www.tradingview.com/script/iQLEgsGT-Oversold-RSI-with-Tight-Stop-Loss-Strategy-by-Coinrule/
Coinrule
https://www.tradingview.com/u/Coinrule/
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/ // © brodieCoinrule //@version=4 strategy(shorttitle='Oversold RSI with tight SL',title='Oversold RSI with tight SL Strategy (by Coinrule)', overlay=true, initial_capital = 1000, process_orders_on_close=true, default_qty_type = strategy.percent_of_equity, default_qty_value = 50, commission_type=strategy.commission.percent, commission_value=0.1) //Backtest dates 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 = 2020, title = "From Year", type = input.integer, minval = 1970) thruMonth = input(defval = 1, title = "Thru Month", type = input.integer, minval = 1, maxval = 12) thruDay = input(defval = 1, title = "Thru Day", type = input.integer, minval = 1, maxval = 31) thruYear = input(defval = 2112, title = "Thru Year", type = input.integer, minval = 1970) showDate = input(defval = true, title = "Show Date Range", type = input.bool) 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" perc_change(lkb) => overall_change = ((close[0] - close[lkb]) / close[lkb]) * 100 // RSI inputs and calculations lengthRSI = 14 RSI = rsi(close, lengthRSI) oversold= input(30) //Entry strategy.entry(id="long", long = true, when = RSI< oversold and window()) //Exit Stop_loss= ((input (1))/100) Take_profit= ((input (7)/100)) longStopPrice = strategy.position_avg_price * (1 - Stop_loss) longTakeProfit = strategy.position_avg_price * (1 + Take_profit) strategy.close("long", when = close < longStopPrice or close > longTakeProfit and window())
stoch supertrd atr 200ma
https://www.tradingview.com/script/ofwFdl2A-stoch-supertrd-atr-200ma/
SamaaraDas
https://www.tradingview.com/u/SamaaraDas/
39
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/ // © araamas //@version=5 strategy("stoch supertrd atr 200ma", overlay=true, shorttitle="STOCH SUPTR ATR MA", process_orders_on_close=true, max_bars_back=5000) ema_condition = input.bool(defval=true, title="ema needed?", tooltip="You can choose whether to include the Ema in the buy and sell conditions") atrPeriod = input(10, "ATR Length") factor = input.float(3.0, "Factor", step = 0.01) [supertrend, direction] = ta.supertrend(factor, atrPeriod) // bodyMiddle = plot((open + close) / 2, display=display.none) // upTrend = plot(direction < 0 ? supertrend : na, "Up Trend", color = color.green, style=plot.style_linebr) // downTrend = plot(direction < 0? na : supertrend, "Down Trend", color = color.red, style=plot.style_linebr) period = input.int(defval=200, title="ema period") ema = ta.ema(close, period) // plot(ema, title="200 ema", color=color.yellow) b = input.int(defval=14, title="length k%") d = input.int(defval=3, title="smoothing k%") s = input.int(defval=3, title="smoothing d%") smooth_k = ta.sma(ta.stoch(close, high, low, b), d) smooth_d = ta.sma(smooth_k, s) //////////////////////////////////////////////////////////////////////////////// length = input.int(title="Length", defval=12, minval=1) smoothing = input.string(title="Smoothing", defval="SMA", options=["RMA", "SMA", "EMA", "WMA"]) m = input(1.5, "Multiplier") src1 = input(high) src2 = input(low) pline = input(true, "Show Price Lines") col1 = input(color.blue, "ATR Text Color") col2 = input(color.teal, "Low Text Color",inline ="1") col3 = input(color.red, "High Text Color",inline ="2") collong = input(color.teal, "Low Line Color",inline ="1") colshort = input(color.red, "High Line Color",inline ="2") ma_function(source, length) => if smoothing == "RMA" ta.rma(source, length) else if smoothing == "SMA" ta.sma(source, length) else if smoothing == "EMA" ta.ema(source, length) else ta.wma(source, length) a = ma_function(ta.tr(true), length) * m x = ma_function(ta.tr(true), length) * m + src1 x2 = src2 - ma_function(ta.tr(true), length) * m p1 = plot(x, title = "ATR Short Stop Loss", color=color.blue) p2 = plot(x2, title = "ATR Long Stop Loss", color= color.blue) /////////////////////////////////////////////////////////////////////////////////////////////// shortCondition = high < ema and direction == 1 and smooth_k > 80 or (ema_condition == false and direction == 1 and smooth_k > 80) if (shortCondition) and strategy.position_size == 0 strategy.entry("sell", strategy.short) longCondition = low > ema and direction == -1 and smooth_k < 20 or (ema_condition == false and direction == -1 and smooth_k < 20) if (longCondition) and strategy.position_size == 0 strategy.entry("buy", strategy.long) x2_val = x2[bar_index - strategy.opentrades.entry_bar_index(0)] g = (strategy.opentrades.entry_price(0) - x2_val) * 2 // tp for buy x_val = x[bar_index - strategy.opentrades.entry_bar_index(0)] k = (x_val - strategy.opentrades.entry_price(0)) * 2 //tp for sell activate_breakeven_sl_price = strategy.opentrades.entry_price(0) + (strategy.opentrades.entry_price(0) - x2_val) //price to activate sl for buy sl_breakeven_price_activated = ta.highest(high, strategy.position_size == 0 ? nz(strategy.opentrades.entry_bar_index(0), 1):bar_index - strategy.opentrades.entry_bar_index(0)) > activate_breakeven_sl_price ? true:false //checks if 1:1 ratio has been reached activate_breakeven_sl_price1 = strategy.opentrades.entry_price(0) - (x_val - strategy.opentrades.entry_price(0)) //price to activate sl for buy sl_breakeven_price_activated1 = ta.lowest(high, strategy.position_size == 0 ? nz(strategy.opentrades.entry_bar_index(0), 1):bar_index - strategy.opentrades.entry_bar_index(0)) < activate_breakeven_sl_price1 ? true:false //checks if 1:1 ratio has been reached if strategy.position_size > 0 strategy.exit(id="buy exit", from_entry="buy",limit=strategy.opentrades.entry_price(0) + g, stop=sl_breakeven_price_activated ? strategy.opentrades.entry_price(0):x2_val) if strategy.position_size < 0 strategy.exit(id="sell exit", from_entry="sell",limit=strategy.opentrades.entry_price(0) - k, stop=sl_breakeven_price_activated1 ? strategy.opentrades.entry_price(0):x_val) plot(strategy.position_size > 0 ? strategy.opentrades.entry_price(0) + g:na, color=color.green, style=plot.style_linebr, title="takeprofit line") //to plot tp line for buy plot(strategy.position_size > 0 and sl_breakeven_price_activated == false ? x2_val:na, color=color.red, style=plot.style_linebr, title="stoploss line") //to plot sl line for buy plot(sl_breakeven_price_activated and strategy.position_size > 0 ? strategy.opentrades.entry_price(0):na, color=color.maroon, style=plot.style_linebr, linewidth=2, title="stoploss line breakeven") //to plot breakeven sl for buy plot(strategy.position_size < 0 ? strategy.opentrades.entry_price(0) - k:na, color=color.green, style=plot.style_linebr, title="takeprofit line") //to plot tp line for sell plot(strategy.position_size < 0 and sl_breakeven_price_activated1 == false ? x_val:na, color=color.red, style=plot.style_linebr, title="stoploss line") //to plot sl line for sell plot(sl_breakeven_price_activated1 and strategy.position_size < 0 ? strategy.opentrades.entry_price(0):na, color=color.maroon, style=plot.style_linebr, linewidth=2, title="stoploss line breakeven") //to plot breakeven sl for sell
Stochastic Moving Average
https://www.tradingview.com/script/OnubkkNF-Stochastic-Moving-Average/
LucasVivien
https://www.tradingview.com/u/LucasVivien/
335
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/ // © LucasVivien // Since this Strategy may have its stop loss hit within the opening candle, consider turning on 'Recalculate : After Order is filled' in the strategy settings, in the "Properties" tabs //@version=5 strategy("Stochastic Moving Average", shorttitle="Stoch. EMA", overlay=true, default_qty_type= strategy.cash, initial_capital=10000, default_qty_value=100) //============================================================================== //============================== USER INPUT ================================ //============================================================================== var g_tradeSetup = "     Trade Setup" activateLongs = input.bool (title="Long Trades" , defval=true , inline="A1", group=g_tradeSetup, tooltip="") activateShorts = input.bool (title="Short Trades" , defval=true , inline="A1", group=g_tradeSetup, tooltip="") rr = input.float(title="Risk : Reward" , defval=1.1 , minval=0, maxval=100 , step=0.1, inline="" , group=g_tradeSetup, tooltip="") RiskEquity = input.bool (title="Risk = % Equity    ", defval=false , inline="A2", group=g_tradeSetup, tooltip="Set stop loss size as a percentage of 'Initial Capital' -> Strategy Parameter -> Properties tab (Low liquidity markets will affect will prevent to get an exact amount du to gaps)") riskPrctEqui = input.float(title="" , defval=1 , minval=0, maxval=100 , step=0.1, inline="A2", group=g_tradeSetup, tooltip="") RiskUSD = input.bool (title="Risk = $ Amount   " , defval=true , inline="A3", group=g_tradeSetup, tooltip="Set stop loss size as a fixed Base currency amount (Low liquidity markets will affect will prevent to get an exact amount du to gaps)") riskUSD = input.float(title="" , defval=200 , minval=0, maxval=1000000, step=100, inline="A3", group=g_tradeSetup, tooltip="") var g_stopLoss = "     Stop Loss" atrMult = input.float(title="ATR Multiplier", defval=3 , minval=0, maxval=100 , step=0.1, tooltip="", inline="", group=g_stopLoss) atrLen = input.int (title="ATR Lookback" , defval=14, minval=0, maxval=1000, step=1 , tooltip="", inline="", group=g_stopLoss) var g_stochastic = "     Stochastic" Klen = input.int (title="K%" , defval=14, minval=0, maxval=1000, step=1, inline="S2", group=g_stochastic, tooltip="") Dlen = input.int (title=" D%" , defval=2 , minval=0, maxval=1000, step=1, inline="S2", group=g_stochastic, tooltip="") OBstochLvl = input.int (title="OB" , defval=80, minval=0, maxval=100 , step=1, inline="S1", group=g_stochastic, tooltip="") OSstochLvl = input.int (title=" OS" , defval=20, minval=0, maxval=100 , step=1, inline="S1", group=g_stochastic, tooltip="") OBOSlookback = input.int (title="Stoch. OB/OS lookback", defval=0 , minval=0, maxval=100 , step=1, inline="" , group=g_stochastic, tooltip="This option allow to look 'x' bars back for a value of the Stochastic K line to be overbought or oversold when detecting an entry signal (if 0, looks only at current bar. if 1, looks at current and previous and so on)") OBOSlookbackAll = input.bool (title="All must be OB/OS" , defval=false , inline="" , group=g_stochastic, tooltip="If turned on, all bars within the Stochastic K line lookback period must be overbought or oversold to return a true signal") entryColor = input.color(title="   " , defval=#00ffff , inline="S3", group=g_stochastic, tooltip="") baseColor = input.color(title="  " , defval=#333333 , inline="S3", group=g_stochastic, tooltip="Will trun to designated color when stochastic gets to opposite extrem zone of current trend / Number = transparency") transp = input.int (title="   " , defval=50, minval=0, maxval=100, step=10, inline="S3", group=g_stochastic, tooltip="") var g_ema = "     Exp. Moving Average" ema1len = input.int (title="Fast EMA     ", defval=4 , minval=0, maxval=1000, step=1, inline="E1", group=g_ema, tooltip="") ema2len = input.int (title="Slow EMA     ", defval=40, minval=0, maxval=1000, step=1, inline="E2", group=g_ema, tooltip="") ema1col = input.color(title="     " , defval=#0066ff , inline="E1", group=g_ema, tooltip="") ema2col = input.color(title="     " , defval=#0000ff , inline="E2", group=g_ema, tooltip="") var g_referenceMarket ="     Reference Market" refMfilter = input.bool (title="Reference Market Filter", defval=false , inline="", group=g_referenceMarket) market = input.symbol (title="Market" , defval="BINANCE:BTCUSDT", inline="", group=g_referenceMarket) res = input.timeframe(title="Timeframe" , defval="30" , inline="", group=g_referenceMarket) len = input.int (title="EMA Length" , defval=50 , inline="", group=g_referenceMarket) var g_alertMessages ="     3Commas Alert Messages" openLongAlertMessage = input.string(title="Open Long Alert Message" , defval="", group=g_alertMessages, tooltip="Paste ''Message for deal start signal'' from long bot") openShortAlertMessage = input.string(title="Open Short Alert Message" , defval="", group=g_alertMessages, tooltip="Paste ''Message for deal start signal'' from short bot") closeLongAlertMessage = input.string(title="Close Long Alert Message" , defval="", group=g_alertMessages, tooltip="Paste ''Message to close order at Market Price'' from long bot") closeShortAlertMessage = input.string(title="Close Short Alert Message", defval="", group=g_alertMessages, tooltip="Paste ''Message to close order at Market Price'' from short bot") //============================================================================== //========================== FILTERS & SIGNALS ============================= //============================================================================== //------------------------------ Stochastic -------------------------------- K = ta.stoch(close, high, low, Klen) D = ta.sma(K, Dlen) stochBullCross = ta.crossover(K, D) stochBearCross = ta.crossover(D, K) OSstoch = false OBstoch = false for i = 0 to OBOSlookback if K[i] < OSstochLvl OSstoch := true else if OBOSlookbackAll OSstoch := false for i = 0 to OBOSlookback if K[i] > OBstochLvl OBstoch := true else if OBOSlookbackAll OBstoch := false //---------------------------- Moving Averages ----------------------------- ema1 = ta.ema(close, ema1len) ema2 = ta.ema(close, ema2len) emaBull = ema1 > ema2 emaBear = ema1 < ema2 //---------------------------- Price source -------------------------------- bullRetraceZone = (close < ema1 and close >= ema2) bearRetraceZone = (close > ema1 and close <= ema2) //--------------------------- Reference market ----------------------------- ema = ta.ema(close, len) emaHTF = request.security(market, res, ema [barstate.isconfirmed ? 0 : 1]) closeHTF = request.security(market, res, close[barstate.isconfirmed ? 0 : 1]) bullRefMarket = (closeHTF > emaHTF or closeHTF[1] > emaHTF[1]) bearRefMarket = (closeHTF < emaHTF or closeHTF[1] < emaHTF[1]) //-------------------------- SIGNAL VALIDATION ----------------------------- validLong = stochBullCross and OSstoch and emaBull and bullRetraceZone and activateLongs and (refMfilter ? bullRefMarket : true) and strategy.position_size == 0 validShort = stochBearCross and OBstoch and emaBear and bearRetraceZone and activateShorts and (refMfilter ? bearRefMarket : true) and strategy.position_size == 0 //============================================================================== //=========================== STOPS & TARGETS ============================== //============================================================================== // SL & TP calculation SLdist = ta.atr(atrLen) * atrMult longSL = close - SLdist longSLDist = close - longSL longTP = close + (longSLDist * rr) shortSL = close + SLdist shortSLDist = shortSL - close shortTP = close - (shortSLDist * rr) var SLsaved = 0.0 var TPsaved = 0.0 if validLong or validShort SLsaved := validLong ? longSL : validShort ? shortSL : na TPsaved := validLong ? longTP : validShort ? shortTP : na // SL & TP hits var longSLTPhit = false var shortSLTPhit = false if strategy.position_size[1] > 0 and strategy.position_size == 0 and (high >= TPsaved or low <= SLsaved) longSLTPhit := true else longSLTPhit := false if strategy.position_size[1] < 0 and strategy.position_size == 0 and (low <= TPsaved or high >= SLsaved) shortSLTPhit := true else shortSLTPhit := false //============================================================================== //========================== STRATEGY COMMANDS ============================= //============================================================================== if validLong strategy.entry("Long", strategy.long, qty = RiskEquity ? ((riskPrctEqui/100)*strategy.equity)/longSLDist : RiskUSD ? riskUSD/longSLDist : na) if validShort strategy.entry("Short", strategy.short, qty = RiskEquity ? ((riskPrctEqui/100)*strategy.equity)/shortSLDist : RiskUSD ? riskUSD/shortSLDist : na) strategy.exit(id="Long Exit" , from_entry="Long" , limit=TPsaved, stop=SLsaved, when=strategy.position_size > 0) strategy.exit(id="Short Exit", from_entry="Short", limit=TPsaved, stop=SLsaved, when=strategy.position_size < 0) //============================================================================== //================================ ALERTS ================================== //============================================================================== if validLong alert(openLongAlertMessage , alert.freq_once_per_bar_close) if validShort alert(openShortAlertMessage , alert.freq_once_per_bar_close) if longSLTPhit alert(closeLongAlertMessage , alert.freq_once_per_bar) if shortSLTPhit alert(closeShortAlertMessage, alert.freq_once_per_bar) //============================================================================== //============================= CHART PLOTS ================================ //============================================================================== //---------------------------- Stops & Targets ----------------------------- plot(strategy.position_size != 0 or (strategy.position_size[1] != 0 and strategy.position_size == 0) ? SLsaved : na, color=color.red , style=plot.style_linebr) plot(strategy.position_size != 0 or (strategy.position_size[1] != 0 and strategy.position_size == 0) ? TPsaved : na, color=color.green, style=plot.style_linebr) //--------------------------------- EMAs ----------------------------------- l1 = plot(ema1, color=ema1col, linewidth=2) l2 = plot(ema2, color=ema2col, linewidth=2) //-------------------------- Stochastic gradient --------------------------- fill(l1, l2, color.new(color.from_gradient(K, OSstochLvl, OBstochLvl, emaBull ? entryColor : emaBear ? baseColor : na, emaBull ? baseColor : emaBear ? entryColor : na), transp)) //---------------------------- Trading Signals ----------------------------- plotshape(validLong, color=color.green, location=location.belowbar, style=shape.xcross, size=size.small) plotshape(validShort, color=color.red , location=location.abovebar, style=shape.xcross, size=size.small) //---------------------------- Reference Market ---------------------------- bgcolor(bullRefMarket and refMfilter ? color.new(color.green,90) : na) bgcolor(bearRefMarket and refMfilter ? color.new(color.red ,90) : na)
Rudy's BB with Martingale
https://www.tradingview.com/script/474pfFba-Rudy-s-BB-with-Martingale/
RudyTheGreenBull
https://www.tradingview.com/u/RudyTheGreenBull/
122
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/ // © rudolfcicko2011 //@version=5 strategy("Rudy BB with Martingala", overlay=true, margin_long=100, margin_short=100) base_contract_size= input.float(0.01, 'Base Contract Size') lastTradeProfit() => strategy.closedtrades.profit(strategy.closedtrades-1) + strategy.closedtrades.commission(strategy.closedtrades-1) amountOfLastNegativeProfits() => result = 0 i = strategy.closedtrades - 1 while strategy.closedtrades.profit(i) < 0 result+=1 i-=1 result ma200 = ta.ema(close, 200) [middle, upper, lower] = ta.bb(close, 20, 2) plot(ma200, "MA200", color=color.green) plot(middle, "Middle BB", color=color.purple) plot(upper, "Upper BB", color=color.purple) plot(lower, "Lower BB", color=color.purple) amount_buy = lastTradeProfit() < 0 ? base_contract_size * amountOfLastNegativeProfits() : 0.01 strategy.entry("bb buy", strategy.long, amount_buy, when=close < lower) strategy.close("bb buy", when=close>=upper) plotchar(strategy.openprofit, "Current profit", "", location = location.top) plotchar(amountOfLastNegativeProfits(), "Amount of last negative profits", "", location = location.top)
MA cross strategy
https://www.tradingview.com/script/yL42H3Gp-MA-cross-strategy/
Glenn234
https://www.tradingview.com/u/Glenn234/
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/ // © Glenn234 //@version=5 strategy("MA cross strategy", shorttitle="macs", overlay=true) // Create indicator's shortSMA = ta.sma(close, 10) longSMA = ta.sma(close, 30) rsi = ta.rsi(close, 14) atr = ta.atr(14) // Crossover conditions longCondition = ta.crossover(shortSMA, longSMA) shortCondition = ta.crossunder(shortSMA, longSMA) // trade conditions if (longCondition) stopLoss = low - atr * 2 takeProfit = high + atr * 2 strategy.entry("long", strategy.long, 100, when = rsi > 50) strategy.exit("exit", "long", stop=stopLoss, limit=takeProfit) if (shortCondition) stopLoss = high + atr * 2 takeProfit = low - atr * 2 strategy.entry("short", strategy.short, 100, when = rsi < 50) strategy.exit("exit", "short", stop=stopLoss, limit=takeProfit) // Plot SMA to chart plot(shortSMA, color=color.red, title="Short SMA") plot(longSMA, color=color.green, title="Long SMA")
GENESIS
https://www.tradingview.com/script/pgYRZCYi/
genesisjgonzalezh
https://www.tradingview.com/u/genesisjgonzalezh/
35
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © genesisjgonzalezh //@version=5 strategy("GENESIS", overlay=true) lenght1= (20) lenght2= (50) ema1= ta.ema(close, lenght1) ema2 = ta.ema(close, lenght2) long = ta.crossover(ema1,ema2) short = ta.crossover(ema2,ema1) LongSignal = ta.crossover (ema1,ema2) ShortSignal = ta.crossunder (ema1,ema2) plotshape(LongSignal , title="Señal para Long", color= color.green, location=location.belowbar, size=size.tiny, text="Long", textcolor=color.white) plotshape(ShortSignal , title="Señal para Short", color= color.red, location=location.abovebar, size=size.tiny, text="Short", textcolor=color.white) strategy.entry("long", strategy.long, when = long) strategy.exit("Exit", "Long", profit = 10, loss = 2) strategy.entry("short", strategy.short, when = short) strategy.exit("Exit", "short", profit = 10, loss = 2)
GRID SPOT TRADING ALGORITHM - GRID BOT TRADING STRATEGY
https://www.tradingview.com/script/LK1zL4D8-GRID-SPOT-TRADING-ALGORITHM-GRID-BOT-TRADING-STRATEGY/
thequantscience
https://www.tradingview.com/u/thequantscience/
1,044
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © thequantscience // ██████╗ ██████╗ ██╗██████╗ ███████╗██████╗ ██████╗ ████████╗ █████╗ ██╗ ██████╗ ██████╗ ██████╗ ██╗████████╗██╗ ██╗███╗ ███╗ // ██╔════╝ ██╔══██╗██║██╔══██╗ ██╔════╝██╔══██╗██╔═══██╗╚══██╔══╝ ██╔══██╗██║ ██╔════╝ ██╔═══██╗██╔══██╗██║╚══██╔══╝██║ ██║████╗ ████║ // ██║ ███╗██████╔╝██║██║ ██║ ███████╗██████╔╝██║ ██║ ██║ ███████║██║ ██║ ███╗██║ ██║██████╔╝██║ ██║ ███████║██╔████╔██║ // ██║ ██║██╔══██╗██║██║ ██║ ╚════██║██╔═══╝ ██║ ██║ ██║ ██╔══██║██║ ██║ ██║██║ ██║██╔══██╗██║ ██║ ██╔══██║██║╚██╔╝██║ // ╚██████╔╝██║ ██║██║██████╔╝ ███████║██║ ╚██████╔╝ ██║ ██║ ██║███████╗╚██████╔╝╚██████╔╝██║ ██║██║ ██║ ██║ ██║██║ ╚═╝ ██║ // ╚═════╝ ╚═╝ ╚═╝╚═╝╚═════╝ ╚══════╝╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝ initial_grid_amount = 10000 //@version=5 strategy( title = 'Grid Spot Trading Algorithm - The Quant Science™', overlay = true, calc_on_every_tick = true, initial_capital = initial_grid_amount, commission_type = strategy.commission.percent, commission_value = 0.10, pyramiding = 20, default_qty_type = strategy.percent_of_equity, close_entries_rule = 'ANY' ) /////////////////////////////// Design by The Quant Science ™ //////////////////////////////////// //---------------------------------------------------------------------------------------------------------- //------------------------------------- Grid Spot Trading Algorithm ---------------------------------------- //---------------------------------------------------------------------------------------------------------- // HOW IT WORKS: 3Commas Grid Bot Strategy for spot asset, based on multiple dinamic trigger start condition. //---------------------------------------------------------------------------------------------------------- // SET UP: Select the high price, select the low price, select the trigger entry condition. // Extra feature: adjust date range. //---------------------------------------------------------------------------------------------------------- // Upgrade 2.00 (2022.30.07) // Upgrade 3.00 (2022.11.11) // Upgrade 4.00 (2022.20.01) /////////////////////////////// ALGORITHM BACKTEST SOURCE CODE //////////////////////////////////// startDate = input.int(title="Start date: ", defval=1, minval=1, maxval=31, group = '############# BACKTESTING PERIOD #############') startMonth = input.int(title="Start month: ", defval=1, minval=1, maxval=12, group = '############# BACKTESTING PERIOD #############') startYear = input.int(title="Start year: ", defval=2022, minval=1800, maxval=2100, group = '############# BACKTESTING PERIOD #############') endDate = input.int(title="End date: ", defval=31, minval=1, maxval=31, group = '############# BACKTESTING PERIOD #############') endMonth = input.int(title="End month: ", defval=12, minval=1, maxval=12, group = '############# BACKTESTING PERIOD #############') endYear = input.int(title="End year: ", defval=2022, minval=1800, maxval=2100, group = '############# BACKTESTING PERIOD #############') inDateRange = (time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0)) and (time < timestamp(syminfo.timezone, endYear, endMonth, endDate, 0, 0)) // ######################################################################################################### high_price = input.price( defval = 0.00, title = 'High price: ', group = " ################# HIGH PRICE GRID ################ ", confirm = true, tooltip = "Top grid price." ) low_price = input.price( defval = 0.00, title = 'Low price: ', group = " ################# LOW PRICE GRID ################# ", confirm = true, tooltip = "Bottom grid price." ) ten_grid = input.bool( defval = false, title = "Grid: 10", group = " ############## GRID CONFIGURATION ############## ", tooltip = "Create a 10 levels grid.", confirm = true ) tewnty_grid = input.bool( defval = false, title = "Grid: 20", group = " ############## GRID CONFIGURATION ############## ", tooltip = "Create a 20 levels grid.", confirm = true ) grid_destroyer = input.bool( defval = false, title = "Active grid destroyer", group = " ############ STOP LOSS CONFIGURATION ############ ", tooltip = "Destroy the grid when price crossunder the stop loss level.", confirm = false ) stop_level = input.price( defval = 0.00, title = 'Destroy level: ', group = " ############ STOP LOSS CONFIGURATION ############ ", confirm = false, tooltip = "Stop loss price level. Always set this value below the low price grid." ) // ######################################################################################################### grid_range = high_price - low_price var float grid_1 = 0 var float grid_2 = 0 var float grid_3 = 0 var float grid_4 = 0 var float grid_5 = 0 var float grid_6 = 0 var float grid_7 = 0 var float grid_8 = 0 var float grid_9 = 0 var float grid_10 = 0 var float grid_11 = 0 var float grid_12 = 0 var float grid_13 = 0 var float grid_14 = 0 var float grid_15 = 0 var float grid_16 = 0 var float grid_17 = 0 var float grid_18 = 0 var float grid_19 = 0 var float grid_20 = 0 var float factor = 0 if ten_grid == true factor := grid_range / 9 grid_1 := (high_price) grid_2 := (high_price - (factor * 1)) grid_3 := (high_price - (factor * 2)) grid_4 := (high_price - (factor * 3)) grid_5 := (high_price - (factor * 4)) grid_6 := (high_price - (factor * 5)) grid_7 := (high_price - (factor * 6)) grid_8 := (high_price - (factor * 7)) grid_9 := (high_price - (factor * 8)) grid_10 := (low_price) if tewnty_grid == true factor := grid_range / 19 grid_1 := (high_price) grid_2 := (high_price - (factor * 1)) grid_3 := (high_price - (factor * 2)) grid_4 := (high_price - (factor * 3)) grid_5 := (high_price - (factor * 4)) grid_6 := (high_price - (factor * 5)) grid_7 := (high_price - (factor * 6)) grid_8 := (high_price - (factor * 7)) grid_9 := (high_price - (factor * 8)) grid_10 := (high_price - (factor * 9)) grid_11 := (high_price - (factor * 10)) grid_12 := (high_price - (factor * 11)) grid_13 := (high_price - (factor * 12)) grid_14 := (high_price - (factor * 13)) grid_15 := (high_price - (factor * 14)) grid_16 := (high_price - (factor * 15)) grid_17 := (high_price - (factor * 16)) grid_18 := (high_price - (factor * 17)) grid_19 := (high_price - (factor * 18)) grid_20 := (low_price) // ######################################################################################################### var tb = table.new(position.bottom_left, 1, 1, bgcolor = color.new(color.blue, 90)) if barstate.isfirst table.cell(tb, 0, 0, 'Developed by The Quant Science™' ,text_size = size.normal ,text_color = color.new(color.blue, 20)) // ######################################################################################################### long_1 = ta.crossunder(low, grid_1) and inDateRange long_2 = ta.crossunder(low, grid_2) and inDateRange long_3 = ta.crossunder(low, grid_3) and inDateRange long_4 = ta.crossunder(low, grid_4) and inDateRange long_5 = ta.crossunder(low, grid_5) and inDateRange long_6 = ta.crossunder(low, grid_6) and inDateRange long_7 = ta.crossunder(low, grid_7) and inDateRange long_8 = ta.crossunder(low, grid_8) and inDateRange long_9 = ta.crossunder(low, grid_9) and inDateRange long_10 = ta.crossunder(low, grid_10) and inDateRange long_11 = ta.crossunder(low, grid_11) and inDateRange long_12 = ta.crossunder(low, grid_12) and inDateRange long_13 = ta.crossunder(low, grid_13) and inDateRange long_14 = ta.crossunder(low, grid_14) and inDateRange long_15 = ta.crossunder(low, grid_15) and inDateRange long_16 = ta.crossunder(low, grid_16) and inDateRange long_17 = ta.crossunder(low, grid_17) and inDateRange long_18 = ta.crossunder(low, grid_18) and inDateRange long_19 = ta.crossunder(low, grid_19) and inDateRange last_long = ta.crossunder(low, low_price) and inDateRange // ######################################################################################################### // Change the default trigger start condition with your personal and custom start condition // Code the condition inside the local function below. // Define a indicator condition or another specific condition ..... // Example with RSI calculating on close bar, and last 14 previous bar data rsi = ta.rsi(close, 14) // Create a local function for the trigger start condition TriggerGrid() => trigger_rsi = ta.crossover(rsi, 75) and inDateRange // Define the specific condition trigger_rsi trigger_entry = TriggerGrid() // Assign the condition to the "trigger_entry" variable // ANOTHER EASY EXAMPLE WITH OVERSOLD RSI CONDITION .... //TriggerGrid() => //trigger_rsi = ta.crossunder(rsi, 35) // Crossunder the RSI 35 value... //trigger_rsi //trigger_entry = TriggerGrid() // Assign the condition to the "trigger_entry" variable // ######################################################################################################### var float lots = 0 if ten_grid == true and inDateRange lots := (initial_grid_amount / close) / 10 if trigger_entry and strategy.opentrades == 0 strategy.order(id = "O #1", direction = strategy.long, qty = lots, limit = grid_6) strategy.order(id = "O #2", direction = strategy.long, qty = lots, limit = grid_7) strategy.order(id = "O #3", direction = strategy.long, qty = lots, limit = grid_8) strategy.order(id = "O #4", direction = strategy.long, qty = lots, limit = grid_9) strategy.order(id = "O #5", direction = strategy.long, qty = lots, limit = grid_10) if close < grid_6 and ten_grid == true strategy.cancel("O #1") if close < grid_7 and ten_grid == true strategy.cancel("O #2") if close < grid_8 and ten_grid == true strategy.cancel("O #3") if close < grid_9 and ten_grid == true strategy.cancel("O #4") if close < grid_10 and ten_grid == true strategy.cancel("O #5") if grid_5 and ten_grid == true strategy.exit( id = "C #1", from_entry = "O #1", qty = 100, limit = grid_5 ) if grid_4 and ten_grid == true strategy.exit( id = "C #2", from_entry = "O #2", qty = 100, limit = grid_4 ) if grid_3 and ten_grid == true strategy.exit( id = "C #3", from_entry = "O #3", qty = 100, limit = grid_3 ) if grid_2 and ten_grid == true strategy.exit( id = "C #4", from_entry = "O #4", qty = 100, limit = grid_2 ) if grid_1 strategy.exit( id = "C #5", from_entry = "O #5", qty = 100, limit = grid_1 ) if ten_grid == true and grid_destroyer == true if ta.crossunder(low, stop_level) strategy.close_all(" Grid Destroyed !!! ") if tewnty_grid == true and inDateRange lots := (initial_grid_amount / close) / 20 if trigger_entry and strategy.opentrades == 0 strategy.order(id = "O #1", direction = strategy.long, qty = lots, limit = grid_11) strategy.order(id = "O #2", direction = strategy.long, qty = lots, limit = grid_12) strategy.order(id = "O #3", direction = strategy.long, qty = lots, limit = grid_13) strategy.order(id = "O #4", direction = strategy.long, qty = lots, limit = grid_14) strategy.order(id = "O #5", direction = strategy.long, qty = lots, limit = grid_15) strategy.order(id = "O #6", direction = strategy.long, qty = lots, limit = grid_16) strategy.order(id = "O #7", direction = strategy.long, qty = lots, limit = grid_17) strategy.order(id = "O #8", direction = strategy.long, qty = lots, limit = grid_18) strategy.order(id = "O #9", direction = strategy.long, qty = lots, limit = grid_19) strategy.order(id = "O #10", direction = strategy.long, qty = lots, limit = grid_20) if close < grid_11 and tewnty_grid == true strategy.cancel("O #1") if close < grid_12 and tewnty_grid == true strategy.cancel("O #2") if close < grid_13 and tewnty_grid == true strategy.cancel("O #3") if close < grid_14 and tewnty_grid == true strategy.cancel("O #4") if close < grid_15 and tewnty_grid == true strategy.cancel("O #5") if close < grid_16 and tewnty_grid == true strategy.cancel("O #6") if close < grid_17 and tewnty_grid == true strategy.cancel("O #7") if close < grid_18 and tewnty_grid == true strategy.cancel("O #8") if close < grid_19 and tewnty_grid == true strategy.cancel("O #9") if close < grid_20 and tewnty_grid == true strategy.cancel("O #10") if grid_10 and tewnty_grid == true strategy.exit( id = "C #1", from_entry = "O #1", qty = 100, limit = grid_10 ) if grid_9 and tewnty_grid == true strategy.exit( id = "C #2", from_entry = "O #2", qty = 100, limit = grid_9 ) if grid_8 and tewnty_grid == true strategy.exit( id = "C #3", from_entry = "O #3", qty = 100, limit = grid_8 ) if grid_7 and tewnty_grid == true strategy.exit( id = "C #4", from_entry = "O #4", qty = 100, limit = grid_7 ) if grid_6 and tewnty_grid == true strategy.exit( id = "C #5", from_entry = "O #5", qty = 100, limit = grid_6 ) if grid_5 and tewnty_grid == true strategy.exit( id = "C #6", from_entry = "O #6", qty = 100, limit = grid_5 ) if grid_4 and tewnty_grid == true strategy.exit( id = "C #7", from_entry = "O #7", qty = 100, limit = grid_4 ) if grid_3 and tewnty_grid == true strategy.exit( id = "C #8", from_entry = "O #8", qty = 100, limit = grid_3 ) if grid_2 and tewnty_grid == true strategy.exit( id = "C #9", from_entry = "O #9", qty = 100, limit = grid_2 ) if grid_1 and tewnty_grid == true strategy.exit( id = "C #10", from_entry = "O #10", qty = 100, limit = grid_1 ) if tewnty_grid == true and grid_destroyer == true if ta.crossunder(low, stop_level) strategy.close_all(" Grid Destroyed !!! ") // ######################################################################################################### var float new_ten_grid_1 = 0 var float new_ten_grid_2 = 0 var float new_ten_grid_3 = 0 var float new_ten_grid_4 = 0 var float new_ten_grid_5 = 0 var float new_ten_grid_6 = 0 var float new_ten_grid_7 = 0 var float new_ten_grid_8 = 0 var float new_ten_grid_9 = 0 var float new_ten_grid_10 = 0 var float grid_destroyed_ten = 0 if ten_grid == true new_ten_grid_1 := grid_1 new_ten_grid_2 := grid_2 new_ten_grid_3 := grid_3 new_ten_grid_4 := grid_4 new_ten_grid_5 := grid_5 new_ten_grid_6 := grid_6 new_ten_grid_7 := grid_7 new_ten_grid_8 := grid_8 new_ten_grid_9 := grid_9 new_ten_grid_10 := grid_10 if grid_destroyer == true grid_destroyed_ten := stop_level else if ten_grid == false new_ten_grid_1 := na new_ten_grid_2 := na new_ten_grid_3 := na new_ten_grid_4 := na new_ten_grid_5 := na new_ten_grid_6 := na new_ten_grid_7 := na new_ten_grid_8 := na new_ten_grid_9 := na new_ten_grid_10 := na if grid_destroyer == false grid_destroyed_ten := na fill(plot(new_ten_grid_1, color = color.new(color.green, 90)), plot(new_ten_grid_2, color = color.new(color.green, 90)), color = color.new(color.green, 90)) fill(plot(new_ten_grid_2, color = color.new(color.green, 85)), plot(new_ten_grid_3, color = color.new(color.green, 85)), color = color.new(color.green, 85)) fill(plot(new_ten_grid_3, color = color.new(color.green, 80)), plot(new_ten_grid_4, color = color.new(color.green, 80)), color = color.new(color.green, 80)) fill(plot(new_ten_grid_4, color = color.new(color.green, 70)), plot(new_ten_grid_5, color = color.new(color.green, 70)), color = color.new(color.green, 70)) fill(plot(new_ten_grid_5, color = color.new(color.green, 60)), plot(new_ten_grid_6, color = color.new(color.green, 60)), color = color.new(color.green, 60)) fill(plot(new_ten_grid_6, color = color.new(color.red, 60)), plot(new_ten_grid_7, color = color.new(color.red, 60)), color = color.new(color.red, 60)) fill(plot(new_ten_grid_7, color = color.new(color.red, 70)), plot(new_ten_grid_8, color = color.new(color.red, 70)), color = color.new(color.red, 70)) fill(plot(new_ten_grid_8, color = color.new(color.red, 80)), plot(new_ten_grid_9, color = color.new(color.red, 80)), color = color.new(color.red, 80)) fill(plot(new_ten_grid_9, color = color.new(color.red, 85)), plot(new_ten_grid_10, color = color.new(color.red, 85)), color = color.new(color.red, 85)) plot(grid_destroyed_ten, color = color.new(color.red, 80), linewidth = 10) // ######################################################################################################### var float new_twenty_grid_1 = 0 var float new_twenty_grid_2 = 0 var float new_twenty_grid_3 = 0 var float new_twenty_grid_4 = 0 var float new_twenty_grid_5 = 0 var float new_twenty_grid_6 = 0 var float new_twenty_grid_7 = 0 var float new_twenty_grid_8 = 0 var float new_twenty_grid_9 = 0 var float new_twenty_grid_10 = 0 var float new_twenty_grid_11 = 0 var float new_twenty_grid_12 = 0 var float new_twenty_grid_13 = 0 var float new_twenty_grid_14 = 0 var float new_twenty_grid_15 = 0 var float new_twenty_grid_16 = 0 var float new_twenty_grid_17 = 0 var float new_twenty_grid_18 = 0 var float new_twenty_grid_19 = 0 var float new_twenty_grid_20 = 0 var float grid_destroyed_twenty = 0 if tewnty_grid == true new_twenty_grid_1 := grid_1 new_twenty_grid_2 := grid_2 new_twenty_grid_3 := grid_3 new_twenty_grid_4 := grid_4 new_twenty_grid_5 := grid_5 new_twenty_grid_6 := grid_6 new_twenty_grid_7 := grid_7 new_twenty_grid_8 := grid_8 new_twenty_grid_9 := grid_9 new_twenty_grid_10 := grid_10 new_twenty_grid_11 := grid_11 new_twenty_grid_12 := grid_12 new_twenty_grid_13 := grid_13 new_twenty_grid_14 := grid_14 new_twenty_grid_15 := grid_15 new_twenty_grid_16 := grid_16 new_twenty_grid_17 := grid_17 new_twenty_grid_18 := grid_18 new_twenty_grid_19 := grid_19 new_twenty_grid_20 := grid_20 if grid_destroyer == true grid_destroyed_twenty := stop_level else if tewnty_grid == false new_twenty_grid_1 := na new_twenty_grid_2 := na new_twenty_grid_3 := na new_twenty_grid_4 := na new_twenty_grid_5 := na new_twenty_grid_6 := na new_twenty_grid_7 := na new_twenty_grid_8 := na new_twenty_grid_9 := na new_twenty_grid_10 := na new_twenty_grid_11 := na new_twenty_grid_12 := na new_twenty_grid_13 := na new_twenty_grid_14 := na new_twenty_grid_15 := na new_twenty_grid_16 := na new_twenty_grid_17 := na new_twenty_grid_18 := na new_twenty_grid_19 := na new_twenty_grid_20 := na if grid_destroyer == false grid_destroyed_twenty := na fill(plot(new_twenty_grid_1, color = color.new(color.green, 90)), plot(new_twenty_grid_2, color = color.new(color.green, 90)), color = color.new(color.green, 90)) fill(plot(new_twenty_grid_2, color = color.new(color.green, 85)), plot(new_twenty_grid_3, color = color.new(color.green, 85)), color = color.new(color.green, 85)) fill(plot(new_twenty_grid_3, color = color.new(color.green, 80)), plot(new_twenty_grid_4, color = color.new(color.green, 80)), color = color.new(color.green, 80)) fill(plot(new_twenty_grid_4, color = color.new(color.green, 70)), plot(new_twenty_grid_5, color = color.new(color.green, 70)), color = color.new(color.green, 70)) fill(plot(new_twenty_grid_5, color = color.new(color.green, 60)), plot(new_twenty_grid_6, color = color.new(color.green, 60)), color = color.new(color.green, 60)) fill(plot(new_twenty_grid_6, color = color.new(color.green, 60)), plot(new_twenty_grid_7, color = color.new(color.green, 60)), color = color.new(color.green, 60)) fill(plot(new_twenty_grid_7, color = color.new(color.green, 70)), plot(new_twenty_grid_8, color = color.new(color.green, 70)), color = color.new(color.green, 70)) fill(plot(new_twenty_grid_8, color = color.new(color.green, 80)), plot(new_twenty_grid_9, color = color.new(color.green, 80)), color = color.new(color.green, 80)) fill(plot(new_twenty_grid_9, color = color.new(color.green, 85)), plot(new_twenty_grid_10, color = color.new(color.green, 85)), color = color.new(color.green, 85)) fill(plot(new_twenty_grid_10, color = color.new(color.red, 90)), plot(new_twenty_grid_11, color = color.new(color.red, 90)), color = color.new(color.red, 90)) fill(plot(new_twenty_grid_11, color = color.new(color.red, 85)), plot(new_twenty_grid_12, color = color.new(color.red, 85)), color = color.new(color.red, 85)) fill(plot(new_twenty_grid_12, color = color.new(color.red, 80)), plot(new_twenty_grid_13, color = color.new(color.red, 80)), color = color.new(color.red, 80)) fill(plot(new_twenty_grid_13, color = color.new(color.red, 70)), plot(new_twenty_grid_14, color = color.new(color.red, 70)), color = color.new(color.red, 70)) fill(plot(new_twenty_grid_14, color = color.new(color.red, 60)), plot(new_twenty_grid_15, color = color.new(color.red, 60)), color = color.new(color.red, 60)) fill(plot(new_twenty_grid_15, color = color.new(color.red, 60)), plot(new_twenty_grid_16, color = color.new(color.red, 60)), color = color.new(color.red, 60)) fill(plot(new_twenty_grid_16, color = color.new(color.red, 70)), plot(new_twenty_grid_17, color = color.new(color.red, 70)), color = color.new(color.red, 70)) fill(plot(new_twenty_grid_17, color = color.new(color.red, 80)), plot(new_twenty_grid_18, color = color.new(color.red, 80)), color = color.new(color.red, 80)) fill(plot(new_twenty_grid_18, color = color.new(color.red, 85)), plot(new_twenty_grid_19, color = color.new(color.red, 85)), color = color.new(color.red, 85)) fill(plot(new_twenty_grid_19, color = color.new(color.red, 85)), plot(new_twenty_grid_20, color = color.new(color.red, 85)), color = color.new(color.red, 85)) plot(grid_destroyed_twenty, color = color.new(color.red, 80), linewidth = 10) // #########################################################################################################
Pivot Moving Average steteggy
https://www.tradingview.com/script/wmydQuP4-Pivot-Moving-Average-steteggy/
prakashbariya333
https://www.tradingview.com/u/prakashbariya333/
316
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/ // © LonesomeThecolor.blue //@version=4 strategy("Pivot Moving Average Strategy", overlay =true, max_lines_count = 500, shorttitle="PMAS") lb = input(5, title="Left Bars", minval = 1) rb = input(5, title="Right Bars", minval = 1) trad_amount = input(100, title="Trad Amount", minval = 1) minimum_profite = input(-2, title="Minimum Profite") showsupres = input(true, title="Support/Resistance", inline = "srcol") supcol = input(color.lime, title ="", inline = "srcol") rescol = input(color.red, title ="", inline = "srcol") srlinestyle = input(line.style_dotted, title = "Line Style/Width", options = [line.style_solid, line.style_dashed, line.style_dotted], inline ="style") srlinewidth = input(1, title = "", minval = 1, maxval = 5, inline ="style") changebarcol = input(true, title="Change Bar Color", inline = "bcol") bcolup = input(color.blue, title ="", inline = "bcol") bcoldn = input(color.black, title ="", inline = "bcol") length = input(14, title="Chopiness Bars", minval=1) atrPeriod = input(10, "ATR Length") factor = input(3.0, "Factor", step = 0.01) ph = pivothigh(lb, rb) pl = pivotlow(lb, rb) hl = iff(ph, 1, iff(pl, -1, na)) // Trend direction zz = iff(ph, ph, iff(pl, pl, na)) // similar to zigzag but may have multiple highs/lows zz :=iff(pl and hl == -1 and valuewhen(hl, hl, 1) == -1 and pl > valuewhen(zz, zz, 1), na, zz) zz :=iff(ph and hl == 1 and valuewhen(hl, hl, 1) == 1 and ph < valuewhen(zz, zz, 1), na, zz) hl := iff(hl==-1 and valuewhen(hl, hl, 1)==1 and zz > valuewhen(zz, zz, 1), na, hl) hl := iff(hl==1 and valuewhen(hl, hl, 1)==-1 and zz < valuewhen(zz, zz, 1), na, hl) zz := iff(na(hl), na, zz) findprevious()=> // finds previous three points (b, c, d, e) ehl = iff(hl==1, -1, 1) loc1 = 0.0, loc2 = 0.0, loc3 = 0.0, loc4 = 0.0 xx = 0 for x=1 to 1000 if hl[x]==ehl and not na(zz[x]) loc1 := zz[x] xx := x + 1 break ehl := hl for x=xx to 1000 if hl[x]==ehl and not na(zz[x]) loc2 := zz[x] xx := x + 1 break ehl := iff(hl==1, -1, 1) for x=xx to 1000 if hl[x]==ehl and not na(zz[x]) loc3 := zz[x] xx := x + 1 break ehl := hl for x=xx to 1000 if hl[x]==ehl and not na(zz[x]) loc4 := zz[x] break [loc1, loc2, loc3, loc4] float a = na, float b = na, float c = na, float d = na, float e = na if not na(hl) [loc1, loc2, loc3, loc4] = findprevious() a := zz b := loc1 c := loc2 d := loc3 e := loc4 _hh = zz and (a > b and a > c and c > b and c > d) _ll = zz and (a < b and a < c and c < b and c < d) _hl = zz and ((a >= c and (b > c and b > d and d > c and d > e)) or (a < b and a > c and b < d)) _lh = zz and ((a <= c and (b < c and b < d and d < c and d < e)) or (a > b and a < c and b > d)) plotshape(_hl, text="HL", title="Higher Low", style=shape.labelup, color=color.lime, textcolor=color.black, location=location.belowbar, offset = -rb) plotshape(_hh, text="HH", title="Higher High", style=shape.labeldown, color=color.lime, textcolor=color.black, location=location.abovebar, offset = -rb) plotshape(_ll, text="LL", title="Lower Low", style=shape.labelup, color=color.red, textcolor=color.white, location=location.belowbar, offset = -rb) plotshape(_lh, text="LH", title="Lower High", style=shape.labeldown, color=color.red, textcolor=color.white, location=location.abovebar, offset = -rb) float res = na, float sup = na res := iff(_lh, zz, res[1]) sup := iff(_hl, zz, sup[1]) var int trend = na trend := iff(close > res, 1, iff(close < sup, -1, nz(trend[1]))) res := iff((trend == 1 and _hh) or (trend == -1 and _lh), zz, res) sup := iff((trend == 1 and _hl) or (trend == -1 and _ll), zz, sup) rechange = res != res[1] suchange = sup != sup[1] var line resline = na var line supline = na if showsupres if rechange line.set_x2(resline, bar_index) line.set_extend(resline, extend = extend.none) resline := line.new(x1 = bar_index - rb, y1 = res, x2 = bar_index, y2 = res, color = rescol, extend = extend.right, style = srlinestyle, width = srlinewidth) if suchange line.set_x2(supline, bar_index) line.set_extend(supline, extend = extend.none) supline := line.new(x1 = bar_index - rb, y1 = sup, x2 = bar_index, y2 = sup, color = supcol, extend = extend.right, style = srlinestyle, width = srlinewidth) barcolor(color = iff(changebarcol, iff(trend == 1, bcolup, bcoldn), na)) var float chopiness = na, float rsi = na var bool movingAverageTrad = na, bool movingAverageUpTrad = na, bool movingAverageDownTrad = na, bool highVolume = na var float ema3 = na, float ema5 = na, float ema8 = na, float ema13 = na, float ema21 = na, float ema34 = na, float ema55 = na, float ema100 = na // ema200 = security(syminfo.tickerid, "D", ema(close, 200), barmerge.gaps_off, barmerge.lookahead_on) ema200 = ema(close, 200) movingAverageTrad := ema200 < close ema3 := ema(close, 3) ema5 := ema(close, 5) ema8 := ema(close, 8) ema13 := ema(close, 13) ema21 := ema(close, 21) ema34 := ema(close, 34) ema55 := ema(close, 55) ema100 := ema(close, 100) movingAverageUpTrad := ema3 > ema5 and ema5 > ema8 and ema8 > ema13 and ema13 > ema21 and ema21 > ema34 and ema34 > ema200 movingAverageDownTrad := ema3 < ema5 and ema5 < ema8 and ema8 < ema13 and ema13 < ema21 and ema21 < ema34 and ema34 < ema200 highVolume := ema(volume, 14) < volume chopiness := 100 * log10(sum(atr(1), length) / (highest(length) - lowest(length))) / log10(length) rsiT = rsi(close, 14) rsi := security(syminfo.tickerid, "60", rsiT, barmerge.gaps_off, barmerge.lookahead_on) [middle, upper, lower] = bb(close,length=20, mult=2) stdev = stdev(close, 14) [supertrendT, directionT] = supertrend(factor, atrPeriod) [supertrend, direction] = security(syminfo.tickerid, "60", [supertrendT, directionT], barmerge.gaps_off, barmerge.lookahead_on) plot(ema3, "ema3", color=color.red) plot(ema5, "ema5", color=color.blue) plot(ema8, "ema8", color=color.orange) plot(ema13, "ema13", color=color.yellow) plot(ema21, "ema21", color=color.red) plot(ema34, "ema34", color=color.blue) plot(ema55, "ema55", color=color.red, linewidth=2) // plot(ema200, "ema200D", color=color.red) var bool buy = na, bool sell = na, bool closeFull = na, bool closeHaft = na buy := trend == 1 and movingAverageUpTrad and direction < 0// and stdev > stdev[1] sell := trend != 1 and movingAverageDownTrad and direction > 0// and stdev > stdev[1] var float entryPrice = na, bool isOpenPosition = false, string position = na, string closeComments = na if cross(ema3, ema8) closeFull := true else if (position[1]== "SELL" and ema3 > ema5 and strategy.openprofit < minimum_profite) closeFull := true else if (position[1]== "BUY" and ema3 < ema5 and strategy.openprofit < minimum_profite) closeFull := true else closeFull := false if not na(position[1]) position := closeFull ? na : position[1] entryPrice := closeFull ? na : entryPrice[1] else if buy position := "BUY" entryPrice := (close[1] + open[1])/2 else if sell position := "SELL" entryPrice := (close[1] + open[1])/2 if buy or sell line.new(x1 = bar_index - rb, y1 = entryPrice, x2 = bar_index, y2 = entryPrice, color = supcol, extend = extend.none, color=color.red, style = line.style_solid, width = 1) if isOpenPosition[1] isOpenPosition := closeFull ? false : isOpenPosition[1] else if position == "SELL" and rsi[1] < rsi[2] and supertrendT != supertrendT[1] isOpenPosition := true else if position == "BUY" and rsi[1] > rsi[2] and supertrendT != supertrendT[1] isOpenPosition := true if strategy.openprofit < minimum_profite closeComments := "Exit" else closeComments := "Trailing Stop" message = '{"symbol":"{{ticker}}","action":"' + tostring(position) +'","quantity":"{{strategy.order.contracts}}"}' if position== "SELL" and isOpenPosition and not isOpenPosition[1] strategy.entry("Short", strategy.short, trad_amount, alert_message = message) if position== "BUY" and isOpenPosition and not isOpenPosition[1] strategy.entry("Long", strategy.long, trad_amount, alert_message = message) if closeFull and isOpenPosition[1] messageClose = '{"symbol":"{{ticker}}","close":' + tostring(closeFull) + '}' strategy.close(position, comment = closeComments, alert_message = messageClose)
[MACLEN] TRUE RANGE
https://www.tradingview.com/script/D1I2A8CJ-MACLEN-TRUE-RANGE/
MaclenMtz
https://www.tradingview.com/u/MaclenMtz/
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/ // © MaclenMtz //@version=5 strategy("[MACLEN] Rangos", shorttitle="Rangos [https://t.me/Bitcoin_Maclen]", overlay=false, slippage=0, initial_capital=1000, currency=currency.USD, default_qty_type=strategy.fixed, default_qty_value=0.1, pyramiding=5, commission_type=strategy.commission.percent, commission_value=0.08) //------WINDOW---------- i_startTime = input.time(defval = timestamp("01 Jan 2022 00:00 -0700"), title = "Start Time", group = "Backtest Window") i_endTime = input.time(defval = timestamp("31 Dec 2025 00:00 -0700"), title = "End Time") window = time >= i_startTime and time <= i_endTime //----------------------------- sube = close>close[1] ? ta.tr : 0 baja = close<close[1] ? ta.tr : 0 corto = input(10, group="Configuración") largo = input(30) suavizado = input(10) fastDiff = ta.wma(sube, corto) - ta.wma(baja,corto) slowDiff = ta.wma(sube, largo) - ta.wma(baja, largo) ind = ta.wma(fastDiff - slowDiff, suavizado) iColor = ind>0 ? color.green : ind<0 ? color.red : color.black plot(ind, color=iColor) plot(0, color=color.white) long = ind[1]<ind and ind[2]<ind[1] and ind<0 short = ind[1]>ind and ind[2]>ind[1] and ind>0 plotshape(long and not long[1], style = shape.xcross, color=color.green, location=location.bottom, size=size.tiny) plotshape(short and not short[1], style = shape.xcross, color=color.red, location=location.top, size=size.tiny) //Apalancamiento lev = input.int(2) //Contratos capital = input(defval=1000, title="Capital Inicial", group="Gestión de Riesgo") contrato1 = (capital*lev)/(16*close) c1 = contrato1 c2 = contrato1 c3 = contrato1*2 c4 = contrato1*4 c5 = contrato1*8 //cap_enopentrade = strategy.opentrades == 1 ? c1: strategy.opentrades == 2 ? c1+c2: strategy.opentrades == 3 ? c1+c2+c3: strategy.opentrades == 4 ? c1+c2+c3+c4: strategy.opentrades == 5 ? c1+c2+c3+c4+c5 : 0 change = math.round((close-strategy.position_avg_price)/strategy.position_avg_price * 100,2) var float used = 0 porc_tp = input.float(6.5, step=0.1) safe = input.float(-6.0, step=0.1) sl = input.float(-5.0, title="StopLoss", step=0.1) //----------------Strategy--------------------------- if strategy.opentrades == 0 and long and not long[1] and window strategy.entry('BUY', strategy.long, qty=c1, comment="Buy") used := used + (c1*close) if strategy.opentrades == 1 and long and not long[1] and window and change<safe strategy.entry('SAFE1', strategy.long, qty=c2, comment="Safe1") used := used + (c2*close) if strategy.opentrades == 2 and long and not long[1] and window and change<safe strategy.entry('SAFE2', strategy.long, qty=c3, comment="Safe2") used := used + (c3*close) if strategy.opentrades == 3 and long and not long[1] and window and change<safe strategy.entry('SAFE3', strategy.long, qty=c4, comment="Safe3") used := used + (c4*close) if strategy.opentrades == 4 and long and not long[1] and window and change<safe strategy.entry('SAFE4', strategy.long, qty=c5, comment="Safe4") used := used + (c5*close) min_prof = strategy.openprofit>0 if (short and min_prof) strategy.close_all(comment="Close (Profit= "+ str.tostring(math.round(change,2)*lev)+"%)") used := 0 if math.abs(strategy.openprofit) >= (used/lev) strategy.close_all(comment="LIQ") used := 0 if change<=sl strategy.close_all(comment="SL") used := 0 //plot (strategy.openprofit) //plot(strategy.position_size) //plot(change) //plot(used/lev) var table display = table.new(position.top_right,1,1) labelText = "Open P/L= " + str.tostring(math.round(strategy.openprofit,2)) + "\n" + "Price Change = " + str.tostring(change) + "%" + "\n" + "Capital Usado = " + str.tostring(used/lev) table.cell(display,0,0, labelText, text_size=size.normal)
Hulk Strategy x35 Leverage 5m chart w/Alerts
https://www.tradingview.com/script/oGUYuz4N-Hulk-Strategy-x35-Leverage-5m-chart-w-Alerts/
npietronuto1
https://www.tradingview.com/u/npietronuto1/
1,504
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/ // © npietronuto1 //@version=5 strategy("Hulk Scalper x35 Leverage", shorttitle = "Smash Pullback Strat", overlay=true, initial_capital=100, default_qty_type=strategy.percent_of_equity, default_qty_value=100) //------------------------------------------------------------------------------------------------------------------------------------------------------------------------ //RSI rsiLength = input.int(20) RsiTopInput = input.int(2) RsiBotInput = input.int(-2) // toprsiLine = hline(RsiTopInput, title = "Rsi Top Line", linestyle = hline.style_solid) // botrsiLine = hline(RsiBotInput, title = "Rsi Bottom Line", linestyle = hline.style_solid) rsi = ta.rsi(close, rsiLength) rsiWeighted = rsi - 50 //Zeros Rsi to look nicer //------------------------------------------------------------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 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) ADXfilterlevel = input.int(33, title = "ADX filter amount") // plot(sig, color=color.red, title="ADX") //------------------------------------------------------------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------------------------------------------------------------ //MACD FastMacdLength = input.int(12, group = "MACD") SlowMacdLength = input.int(26, group = "MACD") SignalLength = input.int(11, group = "MACD") MacdTickAmountNeeded = input.float(5.45, title = "Tick Amount for entry", group = "MACD") res = input.timeframe("1", group = "MACD") // bullishgrow_col = input.color(defval = #3179f5) // bullishweaken_col = input.color(defval = #00e1ff) // bearishweaken_col = input.color(defval = #ff01f1) // bearishgrow_col = input.color(defval = #9d00e5) [FastMacd, SlowMacd, Macdhist] = ta.macd(close, FastMacdLength, SlowMacdLength, SignalLength) //Pull MACD from Lower timeframe MACD = request.security(syminfo.tickerid, res, Macdhist, gaps = barmerge.gaps_on) //Grow and Fall Color // getgrow_fall_col(Value) => // if Value >= 0 // if Value >= Value[1] // color.new(bullishgrow_col, transp = 10) // else if Value <= Value[1] // color.new(bullishweaken_col, transp = 10) // else if Value <= 0 // if Value <= Value[1] // color.new(bearishgrow_col, transp = 10) // else if Value >= Value[1] // color.new(bearishweaken_col, transp = 10) //CONDITIONS that check if MACD is overbought or oversold MACDisAboveBand = MACD > MacdTickAmountNeeded MACDisBelowBand = MACD < MacdTickAmountNeeded*-1 //Plot // plot(MACD, style = plot.style_columns, color = getgrow_fall_col(MACD)) //------------------------------------------------------------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------------------------------------------------------------ //EMAs //Inputs EmaFastLength = input.int(50, title = "Ema Fast Length") EmaSlowLength = input.int(200, title = "Ema Slow Length") StrongUpTrendCol = input.color(color.rgb(74, 255, 163)) //WeakUptrend = input.color(color.rgb(74, 255, 163, 50)) StrongDownTrendCol = input.color(color.rgb(255, 71, 84)) //WeakDownTrend = input.color(color.rgb(255, 71, 84, 50)) //Calculations emaFast= ta.ema(close, EmaFastLength) emaSlow= ta.ema(close, EmaSlowLength) emaDist=emaFast-emaSlow EmaLengthFraction = emaDist/4 emafrac5 = emaSlow + EmaLengthFraction emafrac4 = emaSlow + EmaLengthFraction*2 emafrac3 = emaSlow + EmaLengthFraction*3 emafrac2 = emaSlow + EmaLengthFraction*4 UptrendCol_DowntrendCol= emaFast>=emaSlow ? StrongUpTrendCol:StrongDownTrendCol //Plot ema1p = plot(emaFast, color = color.new(#000000, transp = 100)) ema2p = plot(emafrac2, color = color.new(#000000, transp = 100)) ema3p = plot(emafrac3, color = color.new(#000000, transp = 100)) ema4p = plot(emafrac4, color = color.new(#000000, transp = 100)) ema5p = plot(emafrac5, color = color.new(#000000, transp = 100)) ema6p = plot(emaSlow, color = color.new(#000000, transp = 100)) fill(ema2p,ema3p, color = color.new(UptrendCol_DowntrendCol, 70)) fill(ema3p,ema4p, color = color.new(UptrendCol_DowntrendCol, 60)) fill(ema4p,ema5p, color = color.new(UptrendCol_DowntrendCol, 50)) fill(ema5p,ema6p, color = color.new(UptrendCol_DowntrendCol, 40)) //Conditons FastEma_above_SlowEma = emaFast > emaSlow FastEma_below_SlowEma = emaFast < emaSlow emaCrossEvent = ta.crossover(emaFast, emaSlow) or ta.crossover(emaSlow, emaFast) //------------------------------------------------------------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------------------------------------------------------------ //Trade Cap per EMA X //Inputs MaxTrades_PerCross_Checkbox = input.bool(true, "Limit Trades Per Cross", group = "Filters") TrdCount = 0//Variable that keeps current trade count if(TrdCount[1] > 0)//Passes variable on to current candle TrdCount := TrdCount[1] //Reset trade count if EMAs X emaXevent = ta.crossover(emaFast, emaSlow) or ta.crossover(emaSlow, emaFast) // Check for EMA cross if(emaXevent) TrdCount := 0 //Conditions MaxTrades = input.int(6) IsMaxTrades_BelowCap = TrdCount[1] < MaxTrades //Condition that applies max trade count if(not MaxTrades_PerCross_Checkbox) IsMaxTrades_BelowCap := true //------------------------------------------------------------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------------------------------------------------------------ //STRATEGY LOGIC //Parameters TakeProfitInput = input.float(0.0135, title = "Take Profit %", group = "TP/SL") StopLossInput = input.float(0.011, title = "Stop Loss %", group = "TP/SL") //TP/SL calculations Long_takeProfit = close * (1 + TakeProfitInput) Long_stopLoss = close * (1 - StopLossInput) Short_takeProfit = close * (1 - TakeProfitInput) Short_stopLoss = close * (1 + StopLossInput) //LONG and Short LongConditionPt1 = close > emaSlow and MACDisBelowBand and sig > ADXfilterlevel LongConditionPt2 = FastEma_above_SlowEma and IsMaxTrades_BelowCap and strategy.position_size == 0 //Checks if Rsi Inbetween Lines LongConditionPt3 = rsiWeighted < RsiTopInput and rsiWeighted > RsiBotInput ShortConditionPt1 = close < emaSlow and MACDisAboveBand and sig > ADXfilterlevel ShortConditionPt2 = FastEma_below_SlowEma and IsMaxTrades_BelowCap and strategy.position_size == 0 //Checks if Rsi Inbetween Lines ShortConditionPt3 = rsiWeighted < RsiTopInput and rsiWeighted > RsiBotInput // longCondition = FastEma_above_SlowEma and MACDisBelowBand and IsMaxTrades_BelowCap and rsiWeighted < RsiTopInput and strategy.position_size == 0 longCondition = LongConditionPt1 and LongConditionPt2 and LongConditionPt3 if(longCondition) strategy.entry("long", strategy.long) strategy.exit("exit", "long", limit = Long_takeProfit, stop = Long_stopLoss) TrdCount := TrdCount + 1//ADD to Max Trades Count alert("Go Long with TP at" + str.tostring(Long_takeProfit) + "and SL at" + str.tostring(Long_stopLoss), alert.freq_once_per_bar_close) shortCondition = ShortConditionPt1 and ShortConditionPt2 and ShortConditionPt3 if(shortCondition ) strategy.entry("short", strategy.short) strategy.exit("exit", "short", limit = Short_takeProfit, stop = Short_stopLoss) TrdCount := TrdCount + 1 //ADD to Max Trades Count alert("Go Short with TP at" + str.tostring(Short_takeProfit) + "and SL at" + str.tostring(Short_stopLoss), alert.freq_once_per_bar_close)
Strategy LinReg ST@RL
https://www.tradingview.com/script/TtTraOYt/
RegisL76
https://www.tradingview.com/u/RegisL76/
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/ // © RegisL76 // strategy based on an original idea of @KivancOzbilgic (SuperTrend) and DevLucem (@LucemAnb) (Lin Reg ++) // // TradingView version : a special credit goes to - KivancOzbilgic and @LucemAnb which inspired me a lot to improve this indicator/Strategy. // // ******************** // // © RegisL76 // // V 1780.0 // ******************** // // V1.0 publiée 27/03/2022 (v845) // V2.0 publiée 03/04/2022 (v921) // V3.0 publiée 06/04/2022 (v927) // V4.0 publiée 04/05/2022 (v938) // V5.0 publiée 20/04/2023 (v1574) // V6.0 publiée 28/06/2023 (v1780) // TradingView Pine V5 // //@version=5 // TradingView Pine V5 // // *********************************************************************************************************************************************************************************************************** // // ********************************************* Parametres Par Defaut Optimisés Pour BTC/USDT Perp Binance TF= 1m 3m 5m 15m 30m H1 H2 H3 H4 Daily Weekly *************************************************** // // *********************************************************************************************************************************************************************************************************** // strategy('Strategy LinReg ST@RL',shorttitle='LinRegST@RL', overlay=true, margin_long=70,margin_short=70,commission_value=0.04, default_qty_value=80,initial_capital=1000,default_qty_type= strategy.percent_of_equity, currency=currency.USD,pyramiding=0, calc_on_order_fills=false,calc_on_every_tick=false,process_orders_on_close=false,max_labels_count=500,max_lines_count=500,max_bars_back=0) // ****************************************************************************************************************************************** // // Parametres par defaut pour BTC/USDT Perp Binance TF=H1 // // *************************************************** LINEAR REGRESSION INPUTS ************************************************************* // THANKS = input.string('THANKS i -->>', tooltip= 'If you use this strategy and you are satisfied with the trading results,\n you may donate to me via paypal to [email protected]\n Thanks in advance !!!\n Have good winning trades and enjoy !' , confirm=true, group='CONFIRMATION NEEDED') CONFIG = input.string('CONFIG-->>',tooltip='MEMO -->>' +'\nDef BTCUSDT Perp : Low - ?? - ?? - ?? - ?? - REGULAR : ALL TF !' +'\n---------------------------------------------------------------' +'\n1m BTCUSDT Perp : Low - 115 - 3 - 3.3 - 1 - REGULAR' +'\n3m BTCUSDT Perp : Low - 142 - 0 - 3.9 - 1 - REGULAR' +'\n5m BTCUSDT Perp : Low - 169 - 1 - 2.3 - 1 - REGULAR' +'\n15m BTCUSDT Perp : Low - 167 - 0 - 0.6 - 6 - REGULAR' +'\n30m BTCUSDT Perp : Low - 115 - 2 - 0.9 - 7 - REGULAR' +'\nH1 BTCUSDT Perp : Low - 196 - 3 - 2.2 - 1 - REGULAR' +'\nH2 BTCUSDT Perp : Low - 70 - 7 - 2.2 - 3 - REGULAR' +'\nH3 BTCUSDT Perp : Low - 75 - 2 - 2.0 - 3 - REGULAR' +'\nH4 BTCUSDT Perp : Low - 23 - 2 - 1.6 - 4 - REGULAR' +'\nD BTCUSDT Perp : Low - 52 - 2 - 1.7 - 9 - REGULAR' +'\nW BTCUSDT Perp : Low - 14 - 0 - 0.7 - 5 - REGULAR' +'\nONLY FOR : ' +'\n1m 3m 5m 15m 30m H2 H3 H4 DAILY WEEKLY' +'\nIF "CONF AUTO"', confirm=true, group='CONFIRMATION NEEDED') NOTA = input.string('READ i -->>',tooltip='Inputs Marked With * Influence The Result Of The Stategy !',confirm=true, group='CONFIRMATION NEEDED') // *********************************************************************************************************************** // buy_only = input (false, 'BUY ONLY*', tooltip ='[Buy only] & [Sell only] both checked or both unchecked = [BUY + SELL]' , group='For All TF', inline='ALLTF') sell_only = input (false, 'SELL ONLY*', tooltip ='[Buy only] & [Sell only] both checked or both unchecked = [BUY + SELL]' , group='For All TF', inline='ALLTF') // **************************************************** STOP LOSS Inputs ************************************************* // sl1 = input.float (1.5, 'STOP LOSS* % ' , minval=0.2,maxval=10,step=0.05, tooltip='Stop Loss : 0 to 10 % of Position Size, 100% with X10 [Default Value For All TimeFrame]' , group='For All TF') slX10 = input.bool (true,'STOP LOSS* X 10', tooltip='Stop Loss X10 Multiplier' , group='For All TF', inline='SL') no_sl = input.bool (false,'DISABLE* STOP LOSS', tooltip='Checked=Disable Exit by Stop Loss' , group='For All TF') // **************************************************** TAKE PROFIT Inputs *********************************************** // tp1 = input.float (4.35, 'TAKE PROFIT* % ' ,minval=0.2,maxval=10,step=0.05, tooltip='Take Profit : 0 to 10 % of Position Size, 100% with X10 [Default Value For All TimeFrame]' , group='For All TF') tpX10 = input.bool (true,'TAKE PROFIT* X 10', tooltip='Take Profit X10 Multiplier' , group='For All TF', inline='TP') no_tp = input.bool (false,'DISABLE* TAKE PROFIT', tooltip='Checked=Disable Exit by Take Profit' , group='For All TF') // **************************************************** DISPLAY Inputs *************************************************** // line_thick = input.int (2, 'Line LR Thickness', minval=1, maxval=4, group='COMMON INPUTS DISPLAY', inline='LR') signals = input.string('All', 'Line LR Signals Display', options=['All','Last 500 Bars'], group='COMMON INPUTS DISPLAY', inline='LR') color_up = input.color (color.new(#82fc00,0),'Up Color' , group='COMMON INPUTS DISPLAY', inline='COLOR') color_down = input.color (color.new(#ff0000,0),'Down Color', group='COMMON INPUTS DISPLAY', inline='COLOR') y_Pos_factor = input.float (3.0, 'Label Y Position Factor', minval=0.0,maxval=20.0,step=0.25, group='COMMON INPUTS DISPLAY') show_trade_info = input (true, 'Show Trade Infos', tooltip='Display Or Not The Trade Infos Label', group='COMMON INPUTS DISPLAY', inline='INFO') show_full_info = input (false, 'Show Full Infos Label', tooltip='Display Full Or Simple Trade Infos Label', group='COMMON INPUTS DISPLAY', inline='INFO') barscolors = input (true, 'Trend Bars Colors', tooltip='Displays Or Not The Color Of The Candles According To The Trend Of The Strategy, Instead Of The Standard Colors' , group='COMMON INPUTS DISPLAY', inline='INFO') trans_Col_bg = input.float (88, 'Trend Background Transparency', minval=86, maxval=90, step=1, group='COMMON INPUTS DISPLAY') show_sl_line = input.bool (true, 'Show SL Line', group='COMMON INPUTS DISPLAY', inline='SL-TP') show_tp_line = input.bool (true, 'Show TP Line', tooltip='Show TP / SL Lines & Backgrounds', group='COMMON INPUTS DISPLAY', inline='SL-TP') showIntermedSignal= input.bool(true, 'Show intermediate Signals', tooltip='Show intermediate Signals', group='ALERT MESSAGES') showBuySignal = input.bool(true, 'Show Buy Signals', tooltip='Show Buy Signals', group='ALERT MESSAGES') showSellSignal = input.bool(true, 'Show Sell Signals', tooltip='Show Sell Signals', group='ALERT MESSAGES') showTpSignal = input.bool(true, 'Show Exit TP Signals', tooltip='Show Exit TP Signals', group='ALERT MESSAGES') showSlSignal = input.bool(true, 'Show Exit SL Signals', tooltip='Show Exit SL Signals', group='ALERT MESSAGES') showExitSignal = input.bool(true, 'Show Exit Signals', tooltip='Show Exit Signals', group='ALERT MESSAGES') source = input (low, 'COMMON SOURCE*',tooltip='(Default is "LOW")', group='DEFAULT FOR ALL TF') conf_auto = input.bool (true,'CONF AUTO 1m 3m 5m 15m 30m H1 H2 H3 H4 DAILY WEEKLY*', tooltip='CONF AUTO Only For Timeframe 1m 3m 5m 15m 30m H1 H2 H3 H4 DAILY WEEKLY, ELSE ALL OTHER TF = DEF CONF !', confirm=true, group='DEFAULT FOR ALL TF') // ------------------------------------------------------------------------------------------------- // // Parametres defaut pour ALL Time Frame = DEFAUT Futures BTC/USDT Perp : Low - ?? - ?? - ?? - ?? - REGULAR // Default // // ------------------------------------------------------------------------------------------------- // length_Def = input.int (75, 'DEFAULT LENGTH* --', minval=1, group='COMMON DEFAULT CONFIG FOR ALL TF, EXCEPT IF CONF AUTO',inline='DEFAULT CONF') offset_Def = input.int (2, 'DEFAULT OFFSET* --', minval=0, group='COMMON DEFAULT CONFIG FOR ALL TF, EXCEPT IF CONF AUTO',inline='DEFAULT CONF') dev_Def = input.float (2.0, 'DEFAULT DEVIATION*', minval=0.1, step=0.1, group='COMMON DEFAULT CONFIG FOR ALL TF, EXCEPT IF CONF AUTO',inline='DEFAULT CONF') smoothing_Def = input.int (3, 'DEFAULT SMOOTHING*', minval=1, group='COMMON DEFAULT CONFIG FOR ALL TF, EXCEPT IF CONF AUTO',inline='DEFAULT CONF') reversal_Def = input (false, 'DEFAULT REVERSAL* ', group='COMMON DEFAULT CONFIG FOR ALL TF, EXCEPT IF CONF AUTO',inline='DEFAULT CONF', tooltip='Reversal = Reversal Strategy Method (Buy = Sell & Sell = Buy) ! May Be Better (Or Not !) Than The Regular Strategy !') // ------------------------------------------------------------------------------------------------- // // *********************************************************************************************************************** // // Parametres de base pour Time Frame = 1m Futures BTC/USDT Perp : Low - 115 - 3 - 3.3 - 1 - REGULAR - CONF AUTO 1m ! - // // *********************************************************************************************************************** // length_1m = input.int (115, 'LENGTH 1m* --', minval=1, group='CONFIG ONLY FOR 1m, IF CONF AUTO', inline='1m') offset_1m = input.int (3, 'OFFSET 1m* -----' , minval=0, group='CONFIG ONLY FOR 1m, IF CONF AUTO', inline='1m') dev_1m = input.float (3.3, 'DEVIATION 1m*', minval=0.1, step=0.1, group='CONFIG ONLY FOR 1m, IF CONF AUTO', inline='1m') smoothing_1m = input.int (1, 'SMOOTHING 1m*', minval=1, group='CONFIG ONLY FOR 1m, IF CONF AUTO', inline='1m') reversal_1m = input (false,'REVERSAL 1m*', group='CONFIG ONLY FOR 1m, IF CONF AUTO', inline='1m', tooltip='Reversal = Reversal Strategy Method (Buy = Sell & Sell = Buy) ! May Be Better (Or Not !) Than The Regular Strategy !') // *********************************************************************************************************************** // // Parametres de base pour Time Frame = 3m Futures BTC/USDT Perp : Low - 142 - 0 - 3.9 - 1 - REGULAR - CONF AUTO 3m ! - // // *********************************************************************************************************************** // length_3m = input.int (142, 'LENGTH 3m* --', minval=1, group='CONFIG ONLY FOR 3m, IF CONF AUTO', inline='3m') offset_3m = input.int (0, 'OFFSET 3m* -----' , minval=0, group='CONFIG ONLY FOR 3m, IF CONF AUTO', inline='3m') dev_3m = input.float (3.9, 'DEVIATION 3m*', minval=0.1, step=0.1, group='CONFIG ONLY FOR 3m, IF CONF AUTO', inline='3m') smoothing_3m = input.int (1, 'SMOOTHING 3m*', minval=1, group='CONFIG ONLY FOR 3m, IF CONF AUTO', inline='3m') reversal_3m = input (false,'REVERSAL 3m*', group='CONFIG ONLY FOR 3m, IF CONF AUTO', inline='3m', tooltip='Reversal = Reversal Strategy Method (Buy = Sell & Sell = Buy) ! May Be Better (Or Not !) Than The Regular Strategy !') // *********************************************************************************************************************** // // Parametres de base pour Time Frame = 5m Futures BTC/USDT Perp : Low - 169 - 1 - 2.3 - 1 - REGULAR - CONF AUTO 5m ! - // // *********************************************************************************************************************** // length_5m = input.int (169, 'LENGTH 5m* --', minval=1, group='CONFIG ONLY FOR 5m, IF CONF AUTO', inline='5m') offset_5m = input.int (1, 'OFFSET 5m* -----' , minval=0, group='CONFIG ONLY FOR 5m, IF CONF AUTO', inline='5m') dev_5m = input.float (2.3, 'DEVIATION 5m*', minval=0.1, step=0.1, group='CONFIG ONLY FOR 5m, IF CONF AUTO', inline='5m') smoothing_5m = input.int (1, 'SMOOTHING 5m*', minval=1, group='CONFIG ONLY FOR 5m, IF CONF AUTO', inline='5m') reversal_5m = input (false, 'REVERSAL 5m*', group='CONFIG ONLY FOR 5m, IF CONF AUTO', inline='5m', tooltip='Reversal = Reversal Strategy Method (Buy = Sell & Sell = Buy) ! May Be Better (Or Not !) Than The Regular Strategy !') // *********************************************************************************************************************** // // Parametres de base pour Time Frame = 15m Futures BTC/USDT Perp : Low - 167 - 0 - 0.6 - 6 - REGULAR - CONF AUTO 15m ! - // // *********************************************************************************************************************** // length_15m = input.int (167, 'LENGTH 15m* --', minval=1, group='CONFIG ONLY FOR 15m, IF CONF AUTO', inline='15m') offset_15m = input.int (0, 'OFFSET 15m* -----' , minval=0, group='CONFIG ONLY FOR 15m, IF CONF AUTO', inline='15m') dev_15m = input.float (0.6, 'DEVIATION 15m*', minval=0.1, step=0.1, group='CONFIG ONLY FOR 15m, IF CONF AUTO', inline='15m') smoothing_15m = input.int (6, 'SMOOTHING 15m*', minval=1, group='CONFIG ONLY FOR 15m, IF CONF AUTO', inline='15m') reversal_15m = input (false, 'REVERSAL 15m*', group='CONFIG ONLY FOR 15m, IF CONF AUTO', inline='15m', tooltip='Reversal = Reversal Strategy Method (Buy = Sell & Sell = Buy) ! May Be Better (Or Not !) Than The Regular Strategy !') // *********************************************************************************************************************** // // Parametres de base pour Time Frame = 30m Futures BTC/USDT Perp : Low - 115 - 2 - 0.9 - 7 - REGULAR - CONF AUTO 30m ! - // // *********************************************************************************************************************** // length_30m = input.int (115, 'LENGTH 30m* --', minval=1, group='CONFIG ONLY FOR 30m, IF CONF AUTO', inline='30m') offset_30m = input.int (2, 'OFFSET 30m* -----' , minval=0, group='CONFIG ONLY FOR 30m, IF CONF AUTO', inline='30m') dev_30m = input.float (0.9, 'DEVIATION 30m*', minval=0.1, step=0.1, group='CONFIG ONLY FOR 30m, IF CONF AUTO', inline='30m') smoothing_30m = input.int (7, 'SMOOTHING 30m*', minval=1, group='CONFIG ONLY FOR 30m, IF CONF AUTO', inline='30m') reversal_30m = input (false, 'REVERSAL 30m*', group='CONFIG ONLY FOR 30m, IF CONF AUTO', inline='30m', tooltip='Reversal = Reversal Strategy Method (Buy = Sell & Sell = Buy) ! May Be Better (Or Not !) Than The Regular Strategy !') // ------------------------------------------------------------------------------------------------- // // Parametres de base pour Time Frame = H1 Futures BTC/USDT Perp : Low - 196 - 3 - 2.2 - 1 - REGULAR - CONF AUTO H1 ! - // // ------------------------------------------------------------------------------------------------- // length_H1 = input.int (196, 'LENGTH H1* --', minval=1, group='CONFIG ONLY FOR H1, IF CONF AUTO', inline='H1') offset_H1 = input.int (3, 'OFFSET H1* -----', minval=0, group='CONFIG ONLY FOR H1, IF CONF AUTO', inline='H1') dev_H1 = input.float (2.2, 'DEVIATION H1*', minval=0.1, step=0.1, group='CONFIG ONLY FOR H1, IF CONF AUTO', inline='H1') smoothing_H1 = input.int (1, 'SMOOTHING H1*', minval=1, group='CONFIG ONLY FOR H1, IF CONF AUTO', inline='H1') reversal_H1 = input (false, 'REVERSAL H1*', group='CONFIG ONLY FOR H1, IF CONF AUTO', inline='H1', tooltip='Reversal = Reversal Strategy Method (Buy = Sell & Sell = Buy) ! May Be Better (Or Not !) Than The Regular Strategy !') // *********************************************************************************************************************** // // Parametres de base pour Time Frame = H2 Futures BTC/USDT Perp : Low - 70 - 7 - 2.2 - 3 - REGULAR - CONF AUTO H2 ! - // // *********************************************************************************************************************** // length_H2 = input.int (70, 'LENGTH H2* --', minval=1, group='CONFIG ONLY FOR H2, IF CONF AUTO', inline='H2') offset_H2 = input.int (7, 'OFFSET H2* -----' , minval=0, group='CONFIG ONLY FOR H2, IF CONF AUTO', inline='H2') dev_H2 = input.float (2.2, 'DEVIATION H2*', minval=0.1, step=0.1, group='CONFIG ONLY FOR H2, IF CONF AUTO', inline='H2') smoothing_H2 = input.int (3, 'SMOOTHING H2*', minval=1, group='CONFIG ONLY FOR H2, IF CONF AUTO', inline='H2') reversal_H2 = input (false, 'REVERSAL _H2*', group='CONFIG ONLY FOR H2, IF CONF AUTO', inline='H2', tooltip='Reversal = Reversal Strategy Method (Buy = Sell & Sell = Buy) ! May Be Better (Or Not !) Than The Regular Strategy !') // *********************************************************************************************************************** // // Parametres de base pour Time Frame = H3 Futures BTC/USDT Perp : Low - 75 - 2 - 2.0 - 3 - REGULAR - CONF AUTO H3 ! - // // *********************************************************************************************************************** // length_H3 = input.int (75, 'LENGTH H3* --', minval=1, group='CONFIG ONLY FOR H3, IF CONF AUTO', inline='H3') offset_H3 = input.int (2, 'OFFSET H3* -----' , minval=0, group='CONFIG ONLY FOR H3, IF CONF AUTO', inline='H3') dev_H3 = input.float (2.0, 'DEVIATION H3*', minval=0.1, step=0.1, group='CONFIG ONLY FOR H3, IF CONF AUTO', inline='H3') smoothing_H3 = input.int (3, 'SMOOTHING H3*', minval=1, group='CONFIG ONLY FOR H3, IF CONF AUTO', inline='H3') reversal_H3 = input (false, 'REVERSAL H3*', group='CONFIG ONLY FOR H3, IF CONF AUTO', inline='H2', tooltip='Reversal = Reversal Strategy Method (Buy = Sell & Sell = Buy) ! May Be Better (Or Not !) Than The Regular Strategy !') // *********************************************************************************************************************** // // Parametres de base pour Time Frame = H4 Futures BTC/USDT Perp : Low - 23 - 2 - 1.6 - 4 - REGULAR - CONF AUTO H4 ! - // // *********************************************************************************************************************** // length_H4 = input.int (23, 'LENGTH H4* --', minval=1, group='CONFIG ONLY FOR H4, IF CONF AUTO', inline='H4') offset_H4 = input.int (2, 'OFFSET H4* -----' , minval=0, group='CONFIG ONLY FOR H4, IF CONF AUTO', inline='H4') dev_H4 = input.float (1.6, 'DEVIATION H4*', minval=0.1, step=0.1, group='CONFIG ONLY FOR H4, IF CONF AUTO', inline='H4') smoothing_H4 = input.int (4, 'SMOOTHING H4*', minval=1, group='CONFIG ONLY FOR H4, IF CONF AUTO', inline='H4') reversal_H4 = input (false, 'REVERSAL H4*', group='CONFIG ONLY FOR H4, IF CONF AUTO', inline='H4', tooltip='Reversal = Reversal Strategy Method (Buy = Sell & Sell = Buy) ! May Be Better (Or Not !) Than The Regular Strategy !') // *********************************************************************************************************************** // // Parametres de base pour Time Frame = D Futures BTC/USDT Perp : Low - 52 - 2 - 1.7 - 9 - REGULAR - CONF AUTO D ! - // // *********************************************************************************************************************** // length_D = input.int (52, 'LENGTH Daily* --', minval=1, group='CONFIG ONLY FOR DAILY, IF CONF AUTO', inline='DAILY') offset_D = input.int (2, 'OFFSET Daily* -----' , minval=0, group='CONFIG ONLY FOR DAILY, IF CONF AUTO', inline='DAILY') dev_D = input.float (1.7, 'DEVIATION Daily*', minval=0.1, step=0.1,group='CONFIG ONLY FOR DAILY, IF CONF AUTO', inline='DAILY') smoothing_D = input.int (9, 'SMOOTHING Daily*', minval=1, group='CONFIG ONLY FOR DAILY, IF CONF AUTO', inline='DAILY') reversal_D = input (false, 'REVERSAL Daily*', group='CONFIG ONLY FOR DAILY, IF CONF AUTO', inline='DAILY', tooltip='Reversal = Reversal Strategy Method (Buy = Sell & Sell = Buy) ! May Be Better (Or Not !) Than The Regular Strategy !') // *********************************************************************************************************************** // // Parametres de base pour Time Frame = W Futures BTC/USDT Perp : Low - 14 - 0 - 0.7 - 5 - REGULAR - CONF AUTO W ! - // // *********************************************************************************************************************** // length_W = input.int (14, 'LENGTH Weekly* --', minval=1, group='CONFIG ONLY FOR WEEKLY, IF CONF AUTO', inline='WEEKLY') offset_W = input.int (0, 'OFFSET Weekly* -----' , minval=0, group='CONFIG ONLY FOR WEEKLY, IF CONF AUTO', inline='WEEKLY') dev_W = input.float (0.7, 'DEVIATION Weekly*', minval=0.1, step=0.1, group='CONFIG ONLY FOR WEEKLY, IF CONF AUTO', inline='WEEKLY') smoothing_W = input.int (5, 'SMOOTHING Weekly*', minval=1, group='CONFIG ONLY FOR WEEKLY, IF CONF AUTO', inline='WEEKLY') reversal_W = input (false, 'REVERSAL Weekly*', group='CONFIG ONLY FOR WEEKLY, IF CONF AUTO', inline='WEEKLY', tooltip='Reversal = Reversal Strategy Method (Buy = Sell & Sell = Buy) ! May Be Better (Or Not !) Than The Regular Strategy !') // ********************************************************************************************************************************************* // // Default Conf // smoothing=smoothing_Def loop=length_Def dev=dev_Def conf='[CONF DEF]' // Default Conf // reversal=reversal_Def if (timeframe.period =='1') and conf_auto smoothing:=smoothing_1m loop:=length_1m dev:=dev_1m conf:='[CONF 1m]' reversal:=reversal_1m if (timeframe.period =='3') and conf_auto smoothing:=smoothing_3m loop:=length_3m dev:=dev_3m conf:='[CONF 3m]' reversal:=reversal_3m if (timeframe.period =='5') and conf_auto smoothing:=smoothing_5m loop:=length_5m dev:=dev_5m conf:='[CONF 5m]' reversal:=reversal_5m if (timeframe.period =='15') and conf_auto smoothing:=smoothing_15m loop:=length_15m dev:=dev_15m conf:='[CONF 15m]' reversal:=reversal_15m if (timeframe.period =='30') and conf_auto smoothing:=smoothing_30m loop:=length_30m dev:=dev_30m conf:='[CONF 30m]' reversal:=reversal_30m if timeframe.period =='60' and conf_auto smoothing:=smoothing_H1 loop:=length_H1 dev:=dev_H1 conf:='[CONF H1]' reversal:=reversal_H1 if timeframe.period =='120' and conf_auto smoothing:=smoothing_H2 loop:=length_H2 dev:=dev_H2 conf:='[CONF H2]' reversal:=reversal_H2 if timeframe.period =='180' and conf_auto smoothing:=smoothing_H3 loop:=length_H3 dev:=dev_H3 conf:='[CONF H3]' reversal:=reversal_H3 if timeframe.period =='240' and conf_auto smoothing:=smoothing_H4 loop:=length_H4 dev:=dev_H4 conf:='[CONF H4]' reversal:=reversal_H4 if timeframe.period =='D' and conf_auto smoothing:=smoothing_D loop:=length_D dev:=dev_D conf:='[CONF D]' reversal:=reversal_D if timeframe.period =='W' and conf_auto smoothing:=smoothing_W loop:=length_W dev:=dev_W conf:='[CONF W]' reversal:=reversal_W data(x) => ta.sma(request.security(syminfo.tickerid,timeframe.period, x), smoothing) // ********************************************************************************************************************************************* // // Default Conf // linreg = data(ta.linreg(source, length_Def, offset_Def)) linreg_p = data(ta.linreg(source, length_Def, offset_Def + 1)) if (timeframe.period =='1') and conf_auto linreg := data(ta.linreg(source, length_1m, offset_1m)) linreg_p := data(ta.linreg(source, length_1m, offset_1m + 1)) if (timeframe.period =='3') and conf_auto linreg := data(ta.linreg(source, length_3m, offset_3m)) linreg_p := data(ta.linreg(source, length_3m, offset_3m + 1)) if timeframe.period =='5' and conf_auto linreg := data(ta.linreg(source, length_5m, offset_5m)) linreg_p := data(ta.linreg(source, length_5m, offset_5m + 1)) if timeframe.period =='15' and conf_auto linreg := data(ta.linreg(source, length_15m, offset_15m)) linreg_p := data(ta.linreg(source, length_15m, offset_15m + 1)) if timeframe.period =='30' and conf_auto linreg := data(ta.linreg(source, length_30m, offset_30m)) linreg_p := data(ta.linreg(source, length_30m, offset_30m + 1)) if timeframe.period =='60' and conf_auto linreg := data(ta.linreg(source, length_H1, offset_H1)) linreg_p := data(ta.linreg(source, length_H1, offset_H1 + 1)) if timeframe.period =='120' and conf_auto linreg := data(ta.linreg(source, length_H2, offset_H2)) linreg_p := data(ta.linreg(source, length_H2, offset_H2 + 1)) if timeframe.period =='180' and conf_auto linreg := data(ta.linreg(source, length_H3, offset_H3)) linreg_p := data(ta.linreg(source, length_H3, offset_H3 + 1)) if timeframe.period =='240' and conf_auto linreg := data(ta.linreg(source, length_H4, offset_H4)) linreg_p := data(ta.linreg(source, length_H4, offset_H4 + 1)) if timeframe.period =='D' and conf_auto linreg := data(ta.linreg(source, length_D, offset_D)) linreg_p := data(ta.linreg(source, length_D, offset_D + 1)) if timeframe.period =='W' and conf_auto linreg := data(ta.linreg(source, length_W, offset_W)) linreg_p := data(ta.linreg(source, length_W, offset_W + 1)) // ********************************************************************************************************************************************* // x = bar_index slope = linreg - linreg_p intercept = linreg - x * slope deviationSum = 0.0 for i = 0 to loop - 1 by 1 deviationSum += math.pow(source[i] - (slope * (x - i) + intercept), 2) deviationSum // Default Conf // deviation = math.sqrt(deviationSum / length_Def) x1 = x - length_Def y1 = slope * (x - length_Def) + intercept lengthHist=length_Def if (timeframe.period =='1') and conf_auto deviation := math.sqrt(deviationSum / length_1m) x1 := x - length_1m y1 := slope * (x - length_1m) + intercept lengthHist:=length_1m if (timeframe.period =='3') and conf_auto deviation := math.sqrt(deviationSum / length_3m) x1 := x - length_3m y1 := slope * (x - length_3m) + intercept lengthHist:=length_3m if (timeframe.period =='5') and conf_auto deviation := math.sqrt(deviationSum / length_5m) x1 := x - length_5m y1 := slope * (x - length_5m) + intercept lengthHist:=length_5m if (timeframe.period =='15') and conf_auto deviation := math.sqrt(deviationSum / length_15m) x1 := x - length_15m y1 := slope * (x - length_15m) + intercept lengthHist:=length_15m if (timeframe.period =='30') and conf_auto deviation := math.sqrt(deviationSum / length_30m) x1 := x - length_30m y1 := slope * (x - length_30m) + intercept lengthHist:=length_30m if timeframe.period =='60' and conf_auto deviation := math.sqrt(deviationSum / length_H1) x1 := x - length_H1 y1 := slope * (x - length_H1) + intercept lengthHist:=length_H1 if timeframe.period =='120' and conf_auto deviation := math.sqrt(deviationSum / length_H2) x1 := x - length_H2 y1 := slope * (x - length_H2) + intercept lengthHist:=length_H2 if timeframe.period =='180' and conf_auto deviation := math.sqrt(deviationSum / length_H3) x1 := x - length_H3 y1 := slope * (x - length_H3) + intercept lengthHist:=length_H3 if timeframe.period =='240' and conf_auto deviation := math.sqrt(deviationSum / length_H4) x1 := x - length_H4 y1 := slope * (x - length_H4) + intercept lengthHist:=length_H4 if timeframe.period =='D' and conf_auto deviation := math.sqrt(deviationSum / length_D) x1 := x - length_D y1 := slope * (x - length_D) + intercept lengthHist:=length_D if timeframe.period =='W' and conf_auto deviation := math.sqrt(deviationSum / length_W) x1 := x - length_W y1 := slope * (x - length_W) + intercept lengthHist:=length_W x2 = x y2 = linreg // ********************************************************************************************************************************************* // b = line(na) dp = line(na) dm = line(na) bHist = line(na) dpHist = line(na) dmHist = line(na) bHist1 = line(na) dpHist1= line(na) dmHist1= line(na) b := line.new(x1, y1, x2, y2, xloc.bar_index, extend.right, color.white,style=line.style_dashed, width=line_thick) line.delete(b[1]) bHist := line.new(x1[lengthHist], y1[lengthHist], x2[lengthHist], y2[lengthHist], xloc.bar_index, extend.none, color.white,style=line.style_dashed, width=line_thick) line.delete(bHist[1]) bHist1 := line.new(x1[lengthHist*2], y1[lengthHist*2], x2[lengthHist*2], y2[lengthHist*2], xloc.bar_index, extend.none, color.white,style=line.style_dashed, width=line_thick) line.delete(bHist1[1]) dp := line.new(x1, deviation * dev + y1, x2, deviation * dev + y2, xloc.bar_index, extend.right, color_up,style=line.style_dashed, width=line_thick) line.delete(dp[1]) dpHist := line.new(x1[lengthHist], deviation * dev + y1[lengthHist], x2[lengthHist], deviation * dev + y2[lengthHist], xloc.bar_index, extend.none, color_up,style=line.style_dashed, width=line_thick) line.delete(dpHist[1]) dpHist1 := line.new(x1[lengthHist*2], deviation * dev + y1[lengthHist*2], x2[lengthHist*2], deviation * dev + y2[lengthHist*2], xloc.bar_index, extend.none, color_up,style=line.style_dashed, width=line_thick) line.delete(dpHist1[1]) dm := line.new(x1, -deviation * dev + y1, x2, -deviation * dev + y2, xloc.bar_index, extend.right, color_down,style=line.style_dashed, width=line_thick) line.delete(dm[1]) dmHist := line.new(x1[lengthHist], -deviation * dev + y1[lengthHist], x2[lengthHist], -deviation * dev + y2[lengthHist], xloc.bar_index, extend.none, color_down,style=line.style_dashed, width=line_thick) line.delete(dmHist[1]) dmHist1 := line.new(x1[lengthHist*2], -deviation * dev + y1[lengthHist*2], x2[lengthHist*2], -deviation * dev + y2[lengthHist*2], xloc.bar_index, extend.none, color_down,style=line.style_dashed, width=line_thick) line.delete(dmHist1[1]) // ********************************************************************************************************************************************* // // Signaux dm_current = -deviation * dev + y2 dp_current = deviation * dev + y2 // *** Linear Regression Buy & Sell Signal Regular Mode *** // sell = ta.crossunder (close, dm_current) buy = ta.crossover (close, dp_current) // ********************************************************************************************************************************************* // plotshape(not reversal ? buy : na, title='BUY', style=shape.triangleup, location=location.top,color=color.new(#00ff00,0),size=size.tiny, text='Buy', textcolor=color.new(#87a4f1, 0),show_last=signals == 'All' ? 99999999 : 500) if not reversal and buy line.new(bar_index, high, bar_index, low, xloc=xloc.bar_index, extend=extend.left, color=color.new(#00ff00,0), style=line.style_solid, width=1) plotshape(not reversal ? sell : na, title='SELL', style=shape.triangledown,location=location.top,color=color.new(#ff0000,0) ,size=size.tiny, text='Sell', textcolor=color.new(#87a4f1, 0),show_last=signals == 'All' ? 99999999 : 500) if not reversal and sell line.new(bar_index, high, bar_index, low, xloc=xloc.bar_index, extend=extend.left, color=color.new(#ff0000,0), style=line.style_solid, width=1) plotshape(reversal ? buy : na, title='SELL Rv', style=shape.triangledown,location=location.top,color=color.new(#ff0000,0),size=size.tiny, text='Sell\nRv',textcolor=color.new(#87a4f1, 0),show_last=signals == 'All' ? 99999999 : 500) if reversal and buy line.new(bar_index, high, bar_index, low, xloc=xloc.bar_index, extend=extend.left, color=color.new(#ff0000,0), style=line.style_solid, width=1) plotshape(reversal ? sell: na, title='BUY Rv', style=shape.triangleup, location=location.top,color=color.new(#00ff00,0) ,size=size.tiny, text='Buy\nRv', textcolor=color.new(#87a4f1, 0),show_last=signals == 'All' ? 99999999 : 500) if reversal and sell line.new(bar_index, high, bar_index, low, xloc=xloc.bar_index, extend=extend.left, color=color.new(#00ff00,0), style=line.style_solid, width=1) // ******************************************************************************** // // *** Define F_print_last function For Current Trade Infos *** // f_print_last(_offsetx, _offsety, _lab_styl, _bkg_color, _text, _color_text, _size) => // *** Create label *** //. var _label = label(na) label.delete(_label) _label := label.new(bar_index+_offsetx, _offsety, _text, xloc.bar_index, yloc.price, _bkg_color, _lab_styl, _color_text, _size, text.align_center) _label // ******************************************************************************** // // *** Define F_print2 function For Trades Infos *** // f_print2(_offsetx, _offsety, _lab_styl, _bkg_color, _text, _color_text, _size) => // *** Create label *** //. var _label = label(na) // label.delete(_label) // permanent label // _label := label.new(bar_index + _offsetx, _offsety, _text, xloc.bar_index, yloc.price, _bkg_color, _lab_styl, _color_text, _size, text.align_center) _label // ******************************************************************************** // // [Buy Only] & [Sell Only]' both checked or no checked = [BUY + SELL] // if (sell_only and buy_only) or (not sell_only and not buy_only) sell_only:=false buy_only:=false // ******************************************************************************** // // Gestion Des Multiplicateurs Stop Loss // // Managing Stop Loss Multipliers // sl=sl1 if slX10 and sl>0 sl:=sl1*10 if no_sl sl:=0 // *************************************** // stp_loss_enable=bool(na) if sl==0 stp_loss_enable:=false else stp_loss_enable:=true // *************************************** // // Gestion Des Multiplicateurs Take Profit // // Managing Take Profit Multipliers // tp=tp1 if tpX10 and tp>0 tp:=tp1*10 if no_tp tp:=0 // *************************************** // tp_enable=bool(na) if tp==0 tp_enable:=false else tp_enable:=true // ******************************************************************************************************************** // trend = -1 trend := nz(trend[1], trend) // ************************************************ LINEAR REGRESSION METHODE ***************************************** // // Trend == 1 --> Long If Not Reverse // if not reversal trend := trend == -1 and buy ? 1 : trend == 1 and sell ? -1 : trend else trend := trend == 1 and buy ? -1 : trend == -1 and sell ? 1 : trend changeCond = trend != trend[1] // ********************************************************************************************************************* // var no_bar=int(0) varip int no_trend =0 // Varip // var last_trend=int(na) //-------------------------// no_bar:=no_bar+1 last_trend:=no_bar-no_trend varip trade = float(0) //-------------------------// if changeCond no_trend := no_bar // ******************************************************************************** // var buySignal=bool(na) if not reversal buySignal:= changeCond and trend == 1 else buySignal:= changeCond and trend == -1 // ******************************************************************************** // var sellSignal = bool(na) if not reversal sellSignal:= changeCond and trend == -1 else sellSignal:= changeCond and trend == 1 // ******************************************************************************** // var bool sl_lg =na var bool sl_sh =na var bool stop_loss =na var bool tp_lg =na var bool tp_sh =na var bool take_profit =na // ********************************************************************************************************** // // Gestion des Numeros de Trade, En Accord Avec La Liste Des Transactions Du testeur De Strategie TradindView // // Management of Trade Numbers, In Accordance With The TradindView Strategy tester's Transactions List // // ********************************************************************************************************** // // ********************************************************************************************************** // // ************************** modifying this section is not recommended ! *********************************** // // ********************************************************************************************************** // if (changeCond and not sell_only and not buy_only) and trade==0 // ************************************ // trade:=trade+1 // ************************************ // else if (changeCond and not sell_only and not buy_only) // ************************************ // trade:=trade+1 if trade==0 and not reversal and buySignal and buy_only // ************************************ // trade:=trade+1 if trade==0 and not reversal and sellSignal and sell_only // ************************************ // trade:=trade+1 if trade==0 and reversal and buySignal and sell_only // ************************************ // trade:=trade+1 if trade==0 and reversal and sellSignal and buy_only // ************************************ // trade:=trade+1 // ********************************************************************************************************** // // ******************************************************************************** // // ******************************* STRATEGY *************************************** // // ******************************************************************************** // var str_lg=bool(na) var str_sh=bool(na) // !!! Varip -> start_price!!! varip start_price=float(na) // varip // //**************************************************************************// // Trend == 1 --> Long Normal if trend == 1 and changeCond and not reversal and not str_lg str_lg:=true str_sh:=false start_price:=close sl_lg:=false sl_sh:=false tp_lg:=false tp_sh:=false // Trend == -1 --> Short Normal if trend == -1 and changeCond and not reversal and not str_sh str_lg:=false str_sh:=true start_price:=close sl_lg:=false sl_sh:=false tp_lg:=false tp_sh:=false //**************************************************************************// // Trend == -1 -->Short Reversal if trend == -1 and changeCond and reversal and not str_sh str_lg:=false str_sh:=true start_price:=close sl_lg:=false sl_sh:=false tp_lg:=false tp_sh:=false // Trend == 1 --> Long Reversal if trend == 1 and changeCond and reversal and not str_lg str_lg:=true str_sh:=false start_price:=close sl_lg:=false sl_sh:=false tp_lg:=false tp_sh:=false // **************************************************************************************************************************************************** // // ************************************************ Strategy Entry LG - SH - LG Rev - SH Rev ********************************************************** // // **************************************************************************************************************************************************** // if not reversal and str_lg and not sell_only and buySignal strategy.entry('Lg', strategy.long, comment = 'Lg '+str.format('{0,number,#}',trade)) stop_loss:=false take_profit:=false if not reversal and str_sh and not buy_only and sellSignal strategy.entry('Sh', strategy.short,comment = 'Sh '+str.format('{0,number,#}',trade)) stop_loss:=false take_profit:=false if reversal and str_lg and not sell_only and sellSignal strategy.entry('Lg Rev', strategy.long,comment = 'Lg Rev '+str.format('{0,number,#}',trade)) stop_loss:=false take_profit:=false if reversal and str_sh and not buy_only and buySignal strategy.entry('Sh Rev', strategy.short,comment = 'Sh Rev '+str.format('{0,number,#}',trade)) stop_loss:=false take_profit:=false //**************************************************************************// // Difference De Prix % // // Price difference % // d_per100=(close-close[last_trend])/math.max(close,close[last_trend]) var txt_end_trade=string(na) total_days=string(na) //**************************************************************************// if str.tonumber(timeframe.period)<=240 total_days:='\nHist '+str.format('{0,number,#.#} ', (bar_index*str.tonumber(timeframe.period)/1440)) +' DAYS' if timeframe.period=='D' total_days:='\nHist '+str.format('{0,number,#.#} ', (bar_index)) +' DAYS' if timeframe.period=='W' total_days:='\nHist '+str.format('{0,number,#.#} ', (bar_index*7)) +' DAYS' if timeframe.period=='M' total_days:='\nHist '+str.format('{0,number,#.#} ', (bar_index*30.4375)) +' DAYS' if timeframe.period!='M' and timeframe.period!='W' and timeframe.period!='D' and (str.tonumber(timeframe.period)>240 or str.tonumber(timeframe.period)<1) total_days:='\nHist ???' + ' DAYS' //**************************************************************************// since_days=string(na) since=bar_index-bar_index[last_trend] // si le script s'exécute sur la barre précédant immédiatement la barre en temps réel if barstate.islastconfirmedhistory since:=bar_index-bar_index[last_trend] //**************************************************************************// if str.tonumber(timeframe.period)<=240 since_days:='\nSince '+str.format('{0,number,#.#} ', (since*str.tonumber(timeframe.period)/1440)) +' DAYS' if timeframe.period=='D' since_days:='\nSince '+str.format('{0,number,#.#} ', (since)) +' DAYS' if timeframe.period=='W' since_days:='\nSince '+str.format('{0,number,#.#} ', (since*7)) +' DAYS' if timeframe.period=='M' since_days:='\nSince '+str.format('{0,number,#.#} ', (since*30.4375)) +' DAYS' if timeframe.period!='M' and timeframe.period!='W' and timeframe.period!='D' and (str.tonumber(timeframe.period)>240 or str.tonumber(timeframe.period)<1) since_days:='\nSince ???' + ' DAYS' //**************************************************************************// SizePosUsd=string(na) SizePosBtc =float(na) if trade>=1 SizePosUsd:=strategy.account_currency+str.tostring(strategy.position_size*start_price,format =' #.##') SizePosBtc:=strategy.position_size PnlFlag=string(na) GreenCircle =string('🟢') RedCircle =string('🔴') WhiteCircle =string('⚪') if strategy.opentrades.profit(0)<0 PnlFlag:=RedCircle else if strategy.opentrades.profit(0)>0 PnlFlag:=GreenCircle else PnlFlag:=WhiteCircle if show_full_info txt_end_trade:='# '+str.format('{0,number,#}',trade) + ' ' + PnlFlag + '\n<last # '+str.format('{0,number,#}',trade[last_trend]) + '\n<' + syminfo.basecurrency +str.format(' {0,number,#.########} ',strategy.position_size) + '\n<' + SizePosUsd + '\nSL ' + str.format('{0,number,#.###}',sl)+'%'+ ' TP ' +str.format('{0,number,#.###}',tp)+'%' + '\n<E ' + str.format('{0,number,#.########} ' + strategy.account_currency,close[last_trend]) + '\n=C ' + str.format('{0,number,#.########} ' + strategy.account_currency,close) + '\nd ' + str.format('{0,number,#.########} ' + strategy.account_currency,close-close[last_trend]) + '\n%d ' + str.format('{0,number,#.##%}',d_per100) + '\n=PnL '+ str.format('{0,number,#.##} ' + strategy.account_currency ,strategy.opentrades.profit(0)) + '\nCom ' + str.format('{0,number,-#.## }' + strategy.account_currency ,strategy.opentrades.commission(0)*2) + total_days + since_days else txt_end_trade:='# '+str.format('{0,number,#}',trade) + ' ' + PnlFlag + '\n<' + syminfo.basecurrency +str.format(' {0,number,#.########} ',strategy.position_size) + '\n<' + SizePosUsd + '\n%d ' + str.format('{0,number,#.##%}',d_per100) + '\nPnL ' + str.format('{0,number,#.##} ' + strategy.account_currency ,strategy.opentrades.profit(0)) + '\nCom ' + str.format('{0,number,-#.## }' + strategy.account_currency ,strategy.opentrades.commission(0)*2) + since_days // ************************************ // // Label Horizontal Position Setting // atr = ta.sma(ta.tr, loop) high_pos=ohlc4 + (y_Pos_factor * atr) low_pos=ohlc4 - (y_Pos_factor * atr) // ************************************ // var f2=label(na) if trade==0 label.delete(f2) pnl_color=color(na) if strategy.opentrades.profit(0)<0 pnl_color:=color.new(#080808, 0) else if strategy.opentrades.profit(0)>0 pnl_color:=color.new(#ffffff,0) else pnl_color:=color.new(#fbe78c, 0) varip trade_dir=string(na) // **************************************************************************************************************** // // *** Ordre Des Parametres Pour F_Print2 : (_Offsetx,_Offsety,_Lab_styl,_Bkg_color,_Text,_Color_text,_Size) *** // // *** Order Of Parameters For F_Print2: (_Offsetx, _Offsety, _Lab_styl, _Bkg_color, _Text, _Color_text, _Size) *** // // **************************************************************************************************************** // // ---------------------------------------------------------------------------- txt_end_trade:=txt_end_trade +'\n'+str.format_time(time, "yyyy-MM-dd", "UTC")+'\ntrig='+str.format_time(time, "HH:mm", "UTC")+'\nUTC ' // ---------------------------------------------------------------------------- // Alert Intermediat Buy / Sell if ta.crossunder (close, dm_current) and not reversal and showIntermedSignal alert('\nIntermediate BUY Signal\n'+txt_end_trade, alert.freq_all) if ta.crossover (close, dp_current) and not reversal and showIntermedSignal alert('\nIntermediate SELL Signal\n'+txt_end_trade, alert.freq_all) if ta.crossunder (close, dm_current) and reversal and showIntermedSignal alert('\nIntermediate SELL Signal Rev.\n'+txt_end_trade, alert.freq_all) if ta.crossover (close, dp_current) and reversal and showIntermedSignal alert('\nIntermediate BUY Signal Rev.\n'+txt_end_trade, alert.freq_all) // ---------------------------------------------------------------------------- if buySignal and show_trade_info and not reversal and not sell_only f2:=f_print2( 1,high_pos,label.style_label_down, color.new(#65ff65, 40), 'Lg '+txt_end_trade, pnl_color, size.normal) trade_dir:='Lg ' if buySignal and not reversal and not sell_only if showBuySignal alert('\nBUY Signal\n'+txt_end_trade, alert.freq_all) trade_dir:='Lg ' // ---------------------------------------------------------------------------- if buySignal and show_trade_info and reversal and not buy_only f2:=f_print2( 1,low_pos,label.style_label_up, color.new(#ff6565, 40), 'ShRv '+txt_end_trade, pnl_color, size.normal) trade_dir:='ShRv ' if buySignal and reversal and not buy_only if showSellSignal alert('\nSELL Rev. SIGNAL\n'+txt_end_trade, alert.freq_all) trade_dir:='ShRv ' // ---------------------------------------------------------------------------- if sellSignal and show_trade_info and not reversal and not buy_only f2:=f_print2( 1,low_pos,label.style_label_up, color.new(#ff6565,40), 'Sh '+txt_end_trade, pnl_color, size.normal) trade_dir:='Sh ' if sellSignal and not reversal and not buy_only if showSellSignal alert('\nSELL SIGNAL\n'+txt_end_trade, alert.freq_all) trade_dir:='Sh ' // ---------------------------------------------------------------------------- if sellSignal and show_trade_info and reversal and not sell_only f2:=f_print2( 1,high_pos,label.style_label_down, color.new(#65ff65,40), 'LgRv '+txt_end_trade, pnl_color, size.normal) trade_dir:='LgRv ' if sellSignal and reversal and not sell_only if showBuySignal alert('\nBUY Rev. SIGNAL\n'+txt_end_trade, alert.freq_all) trade_dir:='LgRv ' // ---------------------------------------------------------------------------- // ********************************************************************************************************************************************************** // // CALCUL des valeurs de Stop Loss et Take Profit // // ********************************************************************************************************************************************************** // // Stop Loss & Take Profit calculés en pourcentage de la taille de la Position // FORMULE De CALCUL du : TP_SL_usd = ((E_usd x SIZE_btc x TP_SL_% / 100) +- (E_usd x SIZE_btc)) / SIZE_btc // Les Valeurs des Commissions d'Entrée & de Sortie sont prises en Compte ! SLLgValUsd= ( ( (start_price*SizePosBtc) - (start_price*SizePosBtc*sl/100) ) / SizePosBtc )+strategy.opentrades.commission(0) SLShValUsd= ( ( (start_price*SizePosBtc) + (start_price*SizePosBtc*sl/100) ) / SizePosBtc )-strategy.opentrades.commission(0) TPLgValUsd= ( ( (start_price*SizePosBtc) + (start_price*SizePosBtc*tp/100) ) / SizePosBtc )+strategy.opentrades.commission(0) TPShValUsd= ( ( (start_price*SizePosBtc) - (start_price*SizePosBtc*tp/100) ) / SizePosBtc )-strategy.opentrades.commission(0) // ********************************************************************************************************************************************************** // // ********************************************************************************************************************************************************** // // ********************************************************************* STOP LOSS ************************************************************************** // // ********************************************************************************************************************************************************** // // SIGNAL SL if close <= SLLgValUsd and stp_loss_enable and str_lg and not sell_only sl_lg := true stop_loss:=true if close >= SLShValUsd and stp_loss_enable and str_sh and not buy_only sl_sh := true stop_loss:=true // **************************************************************************************************************** // // *** Ordre Des Parametres Pour F_Print2 : (_Offsetx,_Offsety,_Lab_styl,_Bkg_color,_Text,_Color_text,_Size) *** // // *** Order Of Parameters For F_Print2: (_Offsetx, _Offsety, _Lab_styl, _Bkg_color, _Text, _Color_text, _Size) *** // // **************************************************************************************************************** // varip sl_price=float(na) // varip // if sl_lg and stp_loss_enable and not reversal and show_trade_info and str_lg and not sell_only f2:=f_print2( 0,low_pos,label.style_label_up, color.new(#00aaff,40), 'SL LG '+txt_end_trade, pnl_color, size.normal) trade_dir:='Null ' if sl_lg and stp_loss_enable and not reversal and str_lg strategy.close('Lg', comment = 'STOP LOSS LG '+str.format('{0,number,#}',trade),immediately = true) if showSlSignal alert('\nSTOP LOSS LG\n'+txt_end_trade, alert.freq_all) str_lg:=false str_sh:=false sl_price:=close trade_dir:='Null ' // ******************************************************************************** // if sl_sh and stp_loss_enable and not reversal and show_trade_info and str_sh and not buy_only f2:=f_print2( 0,high_pos,label.style_label_down, color.new(#fbea7f, 40), 'SL SH '+txt_end_trade, pnl_color, size.normal) trade_dir:='Null ' if sl_sh and stp_loss_enable and not reversal and str_sh strategy.close('Sh', comment = 'STOP LOSS SH '+str.format('{0,number,#}',trade),immediately = true) if showSlSignal alert('\nSTOP LOSS SH\n'+txt_end_trade, alert.freq_all) str_lg:=false str_sh:=false sl_price:=close trade_dir:='Null ' // ******************************************************************************** // // ******************************************************************************** // if sl_lg and stp_loss_enable and reversal and show_trade_info and str_lg and not sell_only f2:=f_print2( 0,low_pos,label.style_label_up, color.new(#00aaff,40), 'SL LGRv '+txt_end_trade, pnl_color, size.normal) trade_dir:='Null ' if sl_lg and stp_loss_enable and reversal and str_lg strategy.close('Lg Rev', comment = 'STOP LOSS LG Rev. '+str.format('{0,number,#}',trade),immediately = true) if showSlSignal alert('\nSTOP LOSS LG Rev.\n'+txt_end_trade, alert.freq_all) str_lg:=false str_sh:=false sl_price:=close trade_dir:='Null ' // ******************************************************************************** // if sl_sh and stp_loss_enable and reversal and show_trade_info and str_sh and not buy_only f2:=f_print2( 0,high_pos,label.style_label_down, color.new(#fbea7f, 40), 'SL SHRv '+txt_end_trade, pnl_color, size.normal) trade_dir:='Null ' if sl_sh and stp_loss_enable and reversal and str_sh strategy.close('Sh Rev', comment = 'STOP LOSS SH Rev. '+str.format('{0,number,#}',trade),immediately = true) if showSlSignal alert('\nSTOP LOSS SH Rev.\n'+txt_end_trade, alert.freq_all) str_lg:=false str_sh:=false sl_price:=close trade_dir:='Null ' // ********************************************************************************************************************************************************** // // ********************************************************************* TAKE PROFIT ************************************************************************ // // ********************************************************************************************************************************************************** // // SIGNAL TP if close >= TPLgValUsd and tp_enable and str_lg and not sell_only tp_lg := true take_profit:=true if close <= TPShValUsd and tp_enable and str_sh and not buy_only tp_sh := true take_profit:=true // **************************************************************************************************************** // // *** Ordre Des Parametres Pour F_Print2 : (_Offsetx,_Offsety,_Lab_styl,_Bkg_color,_Text,_Color_text,_Size) *** // // *** Order Of Parameters For F_Print2: (_Offsetx, _Offsety, _Lab_styl, _Bkg_color, _Text, _Color_text, _Size) *** // // **************************************************************************************************************** // varip tp_price=float(na) //varip // if tp_lg and tp_enable and not reversal and show_trade_info and str_lg and not sell_only f2:=f_print2( 0,low_pos,label.style_label_up, color.new(#00ffdd, 40), 'TP LG '+txt_end_trade, pnl_color, size.normal) trade_dir:='Null ' if tp_lg and tp_enable and not reversal and str_lg strategy.close('Lg', comment = 'TAKE PROFIT LG '+str.format('{0,number,#}',trade),immediately = true) if showTpSignal alert('\nTAKE PROFIT LG\n'+txt_end_trade, alert.freq_all) str_lg:=false str_sh:=false tp_price:=close trade_dir:='Null ' // ******************************************************************************** // if tp_sh and tp_enable and not reversal and show_trade_info and str_sh and not buy_only f2:=f_print2( 0,high_pos,label.style_label_down, color.new(#ff5f00,40), 'TP SH '+txt_end_trade, pnl_color, size.normal) trade_dir:='Null ' if tp_sh and tp_enable and not reversal and str_sh strategy.close('Sh', comment = 'TAKE PROFIT SH '+str.format('{0,number,#}',trade),immediately = true) if showTpSignal alert('\nTAKE PROFIT SH\n'+txt_end_trade, alert.freq_all) str_lg:=false str_sh:=false tp_price:=close trade_dir:='Null ' // ******************************************************************************** // // ******************************************************************************** // if tp_lg and tp_enable and reversal and show_trade_info and str_lg and not sell_only f2:=f_print2( 0,low_pos,label.style_label_up, color.new(#00ffdd, 40), 'TP LGRv '+txt_end_trade, pnl_color, size.normal) trade_dir:='Null ' if tp_lg and tp_enable and reversal and str_lg strategy.close('Lg Rev', comment = 'TAKE PROFIT LG Rev. '+str.format('{0,number,#}',trade),immediately = true) if showTpSignal alert('\nTAKE PROFIT LG Rev.\n'+txt_end_trade, alert.freq_all) str_lg:=false str_sh:=false tp_price:=close trade_dir:='Null ' // ******************************************************************************** // if tp_sh and tp_enable and reversal and show_trade_info and str_sh and not buy_only f2:=f_print2( 0,high_pos,label.style_label_down, color.new(#ff5f00,40), 'TP SHRv'+txt_end_trade, pnl_color, size.normal) trade_dir:='Null ' if tp_sh and tp_enable and reversal and str_sh strategy.close('Sh Rev', comment = 'TAKE PROFIT SH Rev. '+str.format('{0,number,#}',trade),immediately = true) if showTpSignal alert('\nTAKE PROFIT SH Rev.\n'+txt_end_trade, alert.freq_all) str_lg:=false str_sh:=false tp_price:=close trade_dir:='Null ' // ********************************************************************************************************************************************************** // // EXIT // // ********************************************************************************************************************************************************** // if changeCond and sellSignal and not reversal and buy_only and show_trade_info and not stop_loss and not take_profit f2:=f_print2( 0,low_pos,label.style_label_up, color.new(#f47ff2, 40), 'ExLg '+txt_end_trade, pnl_color, size.normal) stop_loss:=false take_profit:=false trade_dir:='Null ' if changeCond and sellSignal and not reversal and buy_only strategy.close('Lg',comment = 'Exit Lg '+str.format('{0,number,#}',trade), immediately=true) if showExitSignal alert('\nEXIT LG\n'+txt_end_trade, alert.freq_all) stop_loss:=false take_profit:=false trade:=trade+1 trade_dir:='Null ' str_lg:=false str_sh:=false // ********************************************************************************************************************************************************** // if changeCond and buySignal and not reversal and sell_only and show_trade_info and not stop_loss and not take_profit f2:=f_print2( 0,high_pos,label.style_label_down, color.new(#8bfcc7, 40), 'ExSh '+txt_end_trade, pnl_color, size.normal) stop_loss:=false take_profit:=false trade_dir:='Null ' if changeCond and buySignal and not reversal and sell_only strategy.close('Sh', comment = 'Exit Sh '+str.format('{0,number,#}',trade), immediately=true) if showExitSignal alert('\nEXIT SH\n'+txt_end_trade, alert.freq_all) stop_loss:=false take_profit:=false trade:=trade+1 trade_dir:='Null ' str_lg:=false str_sh:=false // ********************************************************************************************************************************************************** // // ********************************************************************************************************************************************************** // if changeCond and sellSignal and reversal and sell_only and show_trade_info and not stop_loss and not take_profit f2:=f_print2( 0,high_pos,label.style_label_down, color.new(#8bfcc7,40), 'ExShRv '+txt_end_trade, pnl_color, size.normal) stop_loss:=false take_profit:=false trade_dir:='Null ' if changeCond and sellSignal and reversal and sell_only strategy.close('Sh Rev', comment = 'Exit Sh Rev '+str.format('{0,number,#}',trade), immediately=true) if showExitSignal alert('\nEXIT SH REV.\n'+txt_end_trade, alert.freq_all) stop_loss:=false take_profit:=false trade:=trade+1 trade_dir:='Null ' str_lg:=false str_sh:=false // ********************************************************************************************************************************************************** // if changeCond and buySignal and reversal and buy_only and show_trade_info and not stop_loss and not take_profit f2:=f_print2( 0,low_pos,label.style_label_up, color.new(#f47ff2,40), 'ExLgRv '+txt_end_trade, pnl_color, size.normal) stop_loss:=false take_profit:=false trade_dir:='Null ' if changeCond and buySignal and reversal and buy_only strategy.close('Lg Rev', comment = 'Exit Lg Rev '+str.format('{0,number,#}',trade), immediately=true) if showExitSignal alert('\n'+'EXIT LG REV.\n'+txt_end_trade, alert.freq_all) stop_loss:=false take_profit:=false trade:=trade+1 trade_dir:='Null ' str_lg:=false str_sh:=false // ********************************************* Candle Colors According To Trend Direction ***************************************************************** // barcolor (not reversal and trend == -1 and barscolors and not buy_only and not stop_loss and not take_profit ? color.new(#ff0000, 55) : not reversal and trend == 1 and barscolors and not sell_only and not stop_loss and not take_profit ? color.new(#00ff00, 55) : reversal and trend == -1 and barscolors and not buy_only and not stop_loss and not take_profit ? color.new(#ff0000, 55) : reversal and trend == 1 and barscolors and not sell_only and not stop_loss and not take_profit ? color.new(#00ff00, 55) : barscolors ? color.new(#2a2a2c, 55) : na ) // ********************************************************************************************************************************************************** // shp_color =color.new(na,100) if not take_profit and not stop_loss if str_lg and (linreg >= linreg[1]) shp_color:=not sell_only ? color.new(#00ff00,0) : color.new(#00ff00,80) if str_lg and (linreg < linreg[1]) shp_color:=not sell_only ? color.new(#eaff00,0) : color.new(#eaff00,80) // ------------------------------------------------------------------------------------------------- // if str_sh and (linreg < linreg[1]) shp_color:=not buy_only ? color.new(#ff0000,0) : color.new(#ff0000,80) if str_sh and (linreg >= linreg[1]) shp_color:=not buy_only ? color.new(#ff9100,0) : color.new(#ff9100,80) plot(linreg, 'Regression Line', color= shp_color,linewidth=2,style=plot.style_line) plotshape(str_lg ? linreg : na, 'Lg PnL Line',style=shape.square,location=location.bottom,color=str_lg and (close>=start_price) ? color.new(#00ff00, 20) : str_lg and (close<start_price) ? color.new(#ff0000, 20) : na,size=size.tiny) plotshape(str_sh ? linreg : na, 'Sh PnL Line',style=shape.square,location=location.bottom,color=str_sh and (close<start_price) ? color.new(#00ff00, 20) : str_sh and (close>=start_price) ? color.new(#ff0000, 20) : na,size=size.tiny) // ********************************************************************* Stop Loss Indicator ************************************************************************************ // sl_lg_price=SLLgValUsd if show_sl_line and stp_loss_enable and not sell_only and sl_lg sl_lg_price:=sl_price sl_sh_price=SLShValUsd if show_sl_line and stp_loss_enable and not buy_only and sl_sh sl_sh_price:=sl_price sl_line_lg=plot(show_sl_line and stp_loss_enable and not sell_only and (str_lg or sl_lg) and not stop_loss ? sl_lg_price : na, title='Stop loss Lg Line', style=plot.style_linebr, linewidth=2, color=color.new(#ff0000,0),offset=1) sl_line_sh=plot(show_sl_line and stp_loss_enable and not buy_only and (str_sh or sl_sh) and not stop_loss ? sl_sh_price : na, title='Stop loss Sh Line', style=plot.style_linebr, linewidth=2, color=color.new(#ff0000,0),offset=1) // ********************************************************************* Take Profit Indicator ************************************************************************************ // tp_lg_price=TPLgValUsd if show_tp_line and tp_enable and not sell_only and tp_lg tp_lg_price:=tp_price tp_sh_price=TPShValUsd if show_tp_line and tp_enable and not buy_only and tp_sh tp_sh_price:=tp_price tp_line_lg=plot(show_tp_line and tp_enable and not sell_only and (str_lg or tp_lg) and not take_profit ? tp_lg_price : na, title='Take Profit Lg Line', style=plot.style_linebr, linewidth=2, color=color.new(#00ff00,0),offset=1) tp_line_sh=plot(show_tp_line and tp_enable and not buy_only and (str_sh or tp_sh) and not take_profit ? tp_sh_price : na, title='Take Profit Sh Line', style=plot.style_linebr, linewidth=2, color=color.new(#00ff00,0),offset=1) // ********************************************************************* Entry Price Indicator ********************************************************************************** // start_price_lg=plot(start_price , title='Start Price Lg Line', style=plot.style_stepline_diamond, linewidth=2, color=not changeCond and not sell_only and (str_lg or sl_lg or tp_lg) and not stop_loss and not take_profit ? color.new(color.white,0) : na,trackprice=false,offset=1) start_price_sh=plot(start_price , title='Start Price Sh Line', style=plot.style_stepline_diamond, linewidth=2, color=not changeCond and not buy_only and (str_sh or sl_sh or tp_sh) and not stop_loss and not take_profit ? color.new(color.white,0) : na,trackprice=false,offset=1) // ********************************************************************* Stop Loss Background *********************************************************************************** // fill(start_price_lg, sl_line_lg , title='Stop Long Background', color=show_sl_line and stp_loss_enable and not sell_only and not stop_loss ? color.new(#ff4fb3,90): na) fill(start_price_sh, sl_line_sh , title='Stop Short Background', color=show_sl_line and stp_loss_enable and not buy_only and not stop_loss ? color.new(#ff4fb3,90): na) // ******************************************************************* Take Profit Background *********************************************************************************** // fill(start_price_lg, tp_line_lg , title='TP Long Background', color=show_tp_line and tp_enable and not sell_only and not take_profit ? color.new(#00ff00,90): na) fill(start_price_sh, tp_line_sh , title='TP Short Background', color=show_tp_line and tp_enable and not buy_only and not take_profit ? color.new(#00ff00,90): na) // dmline & dpline dmline=plot(dm_current,'dm_current',color=str_lg or str_sh ? color.new(#00ff00, 0) : color.new(#217d21, 0),style=plot.style_line,linewidth=1) dpline=plot(dp_current,'dp_current',color=str_lg or str_sh ? color.new(#ff0000, 0) : color.new(#852727, 0),style=plot.style_line,linewidth=1) // ******************************************************************* Take Profit Background *********************************************************************************** // var f1=label(na) if trade==0 or barstate.ishistory label.delete(f1) // ******************************************************************* Label Current Position *************************************************************** // // ***************************************************************************************************************** // // *** Ordre Des Parametres Pour F_Print_last : (_Offsetx,_Offsety,_Lab_styl,_Bkg_color,_Text,_Color_text,_Size) *** // // *** Order Of Parameters For F_Print_last: (_Offsetx, _Offsety, _Lab_styl, _Bkg_color, _Text, _Color_text, _Size) // // ***************************************************************************************************************** // // f1:=f_print_last(8,close,label.style_label_left, strategy.openprofit>=0 ? color.new(#aaffaa,50) : strategy.openprofit<0 ? color.new(#ff7777,50) : color.new(#cccccc,80), trade_dir+txt_end_trade+'\n'+conf, pnl_color, size.normal) // ********************************************************************************************************************************************************** // // ********************************************************************************************************************************************************** // // ************************************************************************ END CODE ************************************************************************ // // ********************************************************************************************************************************************************** // // ********************************************************************************************************************************************************** //
Trendelicious Strategy
https://www.tradingview.com/script/l2QjZKrb-Trendelicious-Strategy/
levieux
https://www.tradingview.com/u/levieux/
93
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='Trendelicious Strategy', shorttitle='Trendelicious 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) length=input(defval=30) price=input(defval=hl2, title="Price Source") aggressiveMode=input(defval=false,title="Aggressive Mode") start = input.time(defval = timestamp("01 Jan 1900 00:00 +0000"), title = "Start Time") end = input.time(defval = timestamp("31 Dec 2050 23:59 +0000"), title = "End Time") window() => time >= start and time < end if not window() strategy.cancel_all() isUptrend(price,length,aggressiveMode) => uptrend= false PP= (ta.highest(price,length)+ta.lowest(price,length))/2 ppChange= ta.change(PP,1) ppFlat= ppChange==0 priceOverPP=ta.crossover(price,PP) priceUnderPP=ta.crossunder(price,PP) risingPrice= ta.rising(price,5) risingPP= ta.rising(PP,5) fallingPrice= ta.falling(price,5) fallingPP= ta.falling(PP,5) uptrendCondition1= price>PP and (ppChange>0 or (ppChange==0 and aggressiveMode)) and (ppChange[1]>0 or (ppChange[1]==0 and aggressiveMode)) and ppChange[2]>=0 and ppChange[3]>=0 uptrendCondition2= (priceOverPP or risingPrice) and ppFlat and aggressiveMode uptrendCondition3= risingPrice and fallingPP and aggressiveMode downtrendCondition1= price < PP and (ppChange<0 or (ppChange==0 and aggressiveMode)) and (ppChange[1]<0 or (ppChange[1]==0 and aggressiveMode)) and ppChange[2]<=0 and ppChange[3]<=0 downtrendCondition2= (priceUnderPP or fallingPrice) and ppFlat and aggressiveMode downtrendCondition3= fallingPrice and risingPP and aggressiveMode if uptrendCondition1 or uptrendCondition2 or uptrendCondition3 uptrend:= true else if downtrendCondition1 or downtrendCondition2 or downtrendCondition3 uptrend:= false else uptrend:= uptrend[1] [PP,uptrend] [trendline,uptrend]= isUptrend(price,length,aggressiveMode) baseLinePlot = plot((open + close) / 2, display=display.none) upTrendPlot = plot(uptrend ? trendline : na, "Up Trend", color = color.green, style=plot.style_linebr) downTrendPlot = plot(not uptrend ? trendline : na, "Down Trend", color = color.red, style=plot.style_linebr) fill(baseLinePlot, upTrendPlot, color.new(color.green, 90), fillgaps=false) fill(baseLinePlot, downTrendPlot, color.new(color.red, 90), fillgaps=false) buyCondition= window() and uptrend and uptrend[1] and strategy.position_size<=0 sellCondition= window() and not uptrend and not uptrend[1] and strategy.position_size>=0 firstTradePrice= close-close firstTradePrice:= nz(firstTradePrice[1],0) if buyCondition strategy.entry("Long", strategy.long) if firstTradePrice==0 firstTradePrice:= close else if sellCondition strategy.close("Long") end_time= time_close>timenow end_time:= time_close + (time_close - time_close[1]) > timenow or barstate.islastconfirmedhistory precision= 0 if end_time netprofit=math.round(strategy.netprofit,precision) netprofitPercent=math.round(100*netprofit/strategy.initial_capital,precision) bhprofit= math.round((strategy.initial_capital/firstTradePrice)*close-strategy.initial_capital,precision) bhprofitPercent= math.round(100*bhprofit/strategy.initial_capital,precision) openprofit=math.round(strategy.openprofit,precision) trades= strategy.closedtrades wins= strategy.wintrades losses= strategy.losstrades winColor= color.new(color.green, transp = 20) loseColor= color.new(color.red, transp = 20) neutralColor= color.new(color.silver, transp = 70) testTable = table.new(position = position.bottom_right, columns = 2, rows = 4, border_width = 1) table.cell(table_id = testTable, column = 0, row = 0, text = "Net Profit", bgcolor = #cccccc) table.cell(table_id = testTable, column = 1, row = 0, text = str.tostring(netprofit)+"\n"+str.tostring(netprofitPercent)+" %", bgcolor= netprofit>0?winColor:loseColor) table.cell(table_id = testTable, column = 0, row = 1, text = "Buy & Hold", bgcolor = #cccccc) table.cell(table_id = testTable, column = 1, row = 1, text = str.tostring(bhprofit)+"\n"+str.tostring(bhprofitPercent)+" %", bgcolor= bhprofitPercent>0?winColor:loseColor) table.cell(table_id = testTable, column = 0, row = 2, text = "Win / Loss", bgcolor = #cccccc) table.cell(table_id = testTable, column = 1, row = 2, text = str.tostring(wins)+" / "+str.tostring(losses), bgcolor=neutralColor) table.cell(table_id = testTable, column = 0, row = 3, text = "Open PnL", bgcolor = #cccccc) table.cell(table_id = testTable, column = 1, row = 3, text = str.tostring(openprofit), bgcolor= openprofit==0?neutralColor:openprofit>0?winColor:loseColor)
Trading the Equity Curve Position Sizing Example
https://www.tradingview.com/script/md5jT8X2-Trading-the-Equity-Curve-Position-Sizing-Example/
shardison
https://www.tradingview.com/u/shardison/
69
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/ // © shardison //@version=5 //EXPLANATION //"Trading the equity curve" as a risk management method is the //process of acting on trade signals depending on whether a system’s performance //is indicating the strategy is in a profitable or losing phase. //The point of managing equity curve is to minimize risk in trading when the equity curve is in a downtrend. //This strategy has two modes to determine the equity curve downtrend: //By creating two simple moving averages of a portfolio's equity curve - a short-term //and a longer-term one - and acting on their crossings. If the fast SMA is below //the slow SMA, equity downtrend is detected (smafastequity < smaslowequity). //The second method is by using the crossings of equity itself with the longer-period SMA (equity < smasloweequity). //When "Reduce size by %" is active, the position size will be reduced by a specified percentage //if the equity is "under water" according to a selected rule. If you're a risk seeker, select "Increase size by %" //- for some robust systems, it could help overcome their small drawdowns quicker. strategy("Use Trading the Equity Curve Postion Sizing", shorttitle="TEC", default_qty_type = strategy.percent_of_equity, default_qty_value = 10, initial_capital = 100000) //TRADING THE EQUITY CURVE INPUTS useTEC = input.bool(true, title="Use Trading the Equity Curve Position Sizing") defulttraderule = useTEC ? false: true initialsize = input.float(defval=10.0, title="Initial % Equity") slowequitylength = input.int(25, title="Slow SMA Period") fastequitylength = input.int(9, title="Fast SMA Period") seedequity = 100000 * .10 if strategy.equity == 0 seedequity else strategy.equity slowequityseed = strategy.equity > seedequity ? strategy.equity : seedequity fastequityseed = strategy.equity > seedequity ? strategy.equity : seedequity smaslowequity = ta.sma(slowequityseed, slowequitylength) smafastequity = ta.sma(fastequityseed, fastequitylength) equitycalc = input.bool(true, title="Use Fast/Slow Avg", tooltip="Fast Equity Avg is below Slow---otherwise if unchecked uses Slow Equity Avg below Equity") sizeadjstring = input.string("Reduce size by (%)", title="Position Size Adjustment", options=["Reduce size by (%)","Increase size by (%)"]) sizeadjint = input.int(50, title="Increase/Decrease % Equity by:") equitydowntrendavgs = smafastequity < smaslowequity slowequitylessequity = strategy.equity < smaslowequity equitymethod = equitycalc ? equitydowntrendavgs : slowequitylessequity if sizeadjstring == ("Reduce size by (%)") sizeadjdown = initialsize * (1 - (sizeadjint/100)) else sizeadjup = initialsize * (1 + (sizeadjint/100)) c = close qty = 100000 * (initialsize / 100) / c if useTEC and equitymethod if sizeadjstring == "Reduce size by (%)" qty := (strategy.equity * (initialsize / 100) * (1 - (sizeadjint/100))) / c else qty := (strategy.equity * (initialsize / 100) * (1 + (sizeadjint/100))) / c //EXAMPLE TRADING STRATEGY INPUTS CMO_Length = input.int(defval=9, minval=1, title='Chande Momentum Length') CMO_Signal = input.int(defval=10, minval=1, title='Chande Momentum Signal') chandeMO = ta.cmo(close, CMO_Length) cmosignal = ta.sma(chandeMO, CMO_Signal) SuperTrend_atrPeriod = input.int(10, "SuperTrend ATR Length") SuperTrend_Factor = input.float(3.0, "SuperTrend Factor", step = 0.01) Momentum_Length = input.int(12, "Momentum Length") price = close mom0 = ta.mom(price, Momentum_Length) mom1 = ta.mom( mom0, 1) [supertrend, direction] = ta.supertrend(SuperTrend_Factor, SuperTrend_atrPeriod) stupind = (direction < 0 ? supertrend : na) stdownind = (direction < 0? na : supertrend) //TRADING CONDITIONS longConditiondefault = ta.crossover(chandeMO, cmosignal) and (mom0 > 0 and mom1 > 0 and close > stupind) and defulttraderule if (longConditiondefault) strategy.entry("DefLong", strategy.long, qty=qty) shortConditiondefault = ta.crossunder(chandeMO, cmosignal) and (mom0 < 0 and mom1 < 0 and close < stdownind) and defulttraderule if (shortConditiondefault) strategy.entry("DefShort", strategy.short, qty=qty) longCondition = ta.crossover(chandeMO, cmosignal) and (mom0 > 0 and mom1 > 0 and close > stupind) and useTEC if (longCondition) strategy.entry("AdjLong", strategy.long, qty = qty) shortCondition = ta.crossunder(chandeMO, cmosignal) and (mom0 < 0 and mom1 < 0 and close < stdownind) and useTEC if (shortCondition) strategy.entry("AdjShort", strategy.short, qty = qty) plot(strategy.equity) plot(smaslowequity, color=color.new(color.red, 0)) plot(smafastequity, color=color.new(color.green, 0))
SRJ RSI Outperformer Strategy
https://www.tradingview.com/script/Yea5fzK5-SRJ-RSI-Outperformer-Strategy/
Sapt_Jash
https://www.tradingview.com/u/Sapt_Jash/
20
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/ // © Sapt_Jash //@version=5 strategy("SRJ RSI Outperformer Strategy", overlay=true) srcperiod1 = input.int(14, minval=1, title="Length Of Fast RSI") srcperiod2 = input.int(28, minval=1, title="Length Of Slow RSI") srcperiod3 = input.int(14, minval=1, title="Length Of Moving Average") srcperiod4 = input.int(100, minval=1, title="Length Of Deciding Moving Average") srcperiod5 = input.int(20, minval=1, title="Target Profit Percentage") srcperiod6 = input.int(10, minval=1, title="Stoploss Percentage") rsi1 = ta.rsi(close, srcperiod1) rsi2 = ta.rsi(close, srcperiod2) divergence1 = (rsi2/rsi1) divergence2 = (rsi1/divergence1) ma1 = ta.sma(rsi1, srcperiod3) ma2 = ta.sma(divergence2, srcperiod3) //Long Conditions// longcondition = (ta.crossover(ma2, ma1) and (close > ta.sma(close, srcperiod4))) //Exit onditions// exitcondition = (ta.crossunder(ma2, ma1) or (ta.crossunder(close, ta.sma(close, srcperiod4)))) if (longcondition) strategy.entry("Long Entry", strategy.long) if (exitcondition) strategy.exit("Long Exit", profit = close * (1+(srcperiod5/100)), loss = close * (1-(srcperiod6/100)))
Villa Dinamic Pivot Supertrend Strategy
https://www.tradingview.com/script/HCdMhEcU-Villa-Dinamic-Pivot-Supertrend-Strategy/
VILIO_Trading
https://www.tradingview.com/u/VILIO_Trading/
57
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/ // © evillalobos1123 //@version=5 strategy("Villa Dinamic Pivot Supertrend Strategy", overlay=true, calc_on_every_tick = true, default_qty_type = strategy.fixed) //INPUTS ema_b = input.bool(false, "Use Simple EMA Filter", group = "Strategy Inputs") ema_b_ang = input.bool(true, "Use DEMA Angle Filter", group = "Strategy Inputs") dema_b = input.bool(true, "Use DEMA Filter", group = "Strategy Inputs") st_sig = input.bool(false, "Take Every Supertrend Signal" , group = "Strategy Inputs") take_p = input.bool(true, "Stop Loss at Supertrend", group = "Strategy Inputs") din_tp = input.bool(false, "2 Steps Take Profit", group = "Strategy Inputs") move_sl = input.bool(true, "Move SL", group = "Strategy Inputs") sl_atr = input.float(2.5, "Stop Loss ATR Multiplier", group = "Strategy Inputs") tp_atr = input.float(4, "Take Profit ATR Multiplier", group = "Strategy Inputs") din_tp_qty = input.int(50, "2 Steps TP qty%", group = "Strategy Inputs") dema_a_filter = input.float(0, "DEMA Angle Threshold (+ & -)", group = "Strategy Inputs") dema_a_look = input.int(1, "DEMA Angle Lookback", group = "Strategy Inputs") dr_test = input.string("Backtest", "Testing", options = ["Backtest", "Forwardtest", "All"], group = "Strategy Inputs") test_act = input.string('Forex', 'Market', options = ['Forex', 'Stocks'], group = "Strategy Inputs") not_in_trade = strategy.position_size == 0 //Backtesting date range start_year = input.int(2021, "Backtesting start year", group = "BT Date Range") start_month = input.int(1, "Backtesting start month", group = "BT Date Range") start_date = input.int(1, "Backtesting start day", group = "BT Date Range") end_year = input.int(2021, "Backtesting end year", group = "BT Date Range") end_month = input.int(12, "Backtesting end month", group = "BT Date Range") end_date = input.int(31, "Backtesting end day", group = "BT Date Range") bt_date_range = (time >= timestamp(syminfo.timezone, start_year, start_month, start_date, 0, 0)) and (time < timestamp(syminfo.timezone, end_year, end_month, end_date, 0, 0)) //Forward testing date range start_year_f = input.int(2022, "Forwardtesting start year", group = "FT Date Range") start_month_f = input.int(1, "Forwardtesting start month", group = "FT Date Range") start_date_f = input.int(1, "Forwardtesting start day", group = "FT Date Range") end_year_f = input.int(2022, "Forwardtesting end year", group = "FT Date Range") end_month_f = input.int(03, "Forwardtesting end month", group = "FT Date Range") end_date_f = input.int(26, "Forwardtesting end day", group = "FT Date Range") ft_date_range = (time >= timestamp(syminfo.timezone, start_year_f, start_month_f, start_date_f, 0, 0)) and (time < timestamp(syminfo.timezone, end_year_f, end_month_f, end_date_f, 0, 0)) //date condition date_range_cond = if dr_test == "Backtest" bt_date_range else if dr_test == "Forwardtest" ft_date_range else true //INDICATORS //PIVOT SUPERTREND prd = input.int(2, "PVT ST Pivot Point Period", group = "Pivot Supertrend") Factor=input.float(3, "PVT ST ATR Factor", group = "Pivot Supertrend") Pd=input.int(9 , "PVT ST ATR Period", group = "Pivot Supertrend") // get Pivot High/Low float ph = ta.pivothigh(prd, prd) float pl = ta.pivotlow(prd, prd) // calculate the Center line using pivot points var float center = na float lastpp = ph ? ph : pl ? pl : na if lastpp if na(center) center := lastpp else //weighted calculation center := (center * 2 + lastpp) / 3 // upper/lower bands calculation Up = center - (Factor * ta.atr(Pd)) Dn = center + (Factor * ta.atr(Pd)) // get the trend float TUp = na float TDown = na Trend = 0 TUp := close[1] > TUp[1] ? math.max(Up, TUp[1]) : Up TDown := close[1] < TDown[1] ? math.min(Dn, TDown[1]) : Dn Trend := close > TDown[1] ? 1: close < TUp[1]? -1: nz(Trend[1], 1) Trailingsl = Trend == 1 ? TUp : TDown // check and plot the signals bsignal = Trend == 1 and Trend[1] == -1 ssignal = Trend == -1 and Trend[1] == 1 //get S/R levels using Pivot Points float resistance = na float support = na support := pl ? pl : support[1] resistance := ph ? ph : resistance[1] //DEMA dema_ln = input.int(200, "DEMA Len", group = 'D-EMAs') dema_src = input.source(close, "D-EMAs Source", group = 'D-EMAs') ema_fd = ta.ema(dema_src, dema_ln) dema = (2*ema_fd)-(ta.ema(ema_fd,dema_ln)) //EMA ema1_l = input.int(21, "EMA 1 Len", group = 'D-EMAs') ema2_l = input.int(50, "EMA 2 Len", group = 'D-EMAs') ema3_l = input.int(200, "EMA 3 Len", group = 'D-EMAs') ema1 = ta.ema(dema_src, ema1_l) ema2 = ta.ema(dema_src, ema2_l) ema3 = ta.ema(dema_src, ema3_l) //Supertrend Periods = input.int(21, "ST ATR Period", group = "Normal Supertrend") src_st = input.source(hl2, "ST Supertrend Source", group = "Normal Supertrend") Multiplier = input.float(2.0 , "ST ATR Multiplier", group = "Normal Supertrend") changeATR= true atr2 = ta.sma(ta.tr, Periods) atr3= changeATR ? ta.atr(Periods) : atr2 up=src_st-(Multiplier*atr3) up1 = nz(up[1],up) up := close[1] > up1 ? math.max(up,up1) : up dn=src_st+(Multiplier*atr3) dn1 = nz(dn[1], dn) dn := close[1] < dn1 ? math.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 buySignal = trend == 1 and trend[1] == -1 sellSignal = trend == -1 and trend[1] == 1 //ATR atr = ta.atr(14) ///CONDITIONS //BUY /// ema simple ema_cond_b = if ema_b ema1 > ema2 and ema2 > ema3 else true ///ema angle div_ang = if test_act == 'Forex' 0.0001 else 1 dema_angle_rad = math.atan((dema - dema[dema_a_look])/div_ang) dema_angle = dema_angle_rad * (180/math.pi) dema_ang_cond_b = if ema_b_ang if dema_angle >= dema_a_filter true else false else true ///ema distance dema_cond_b = if dema_b close > dema else true //supertrends ///if pivot buy sig or (st buy sig and pivot. trend = 1) pvt_cond_b = bsignal st_cond_b = if st_sig buySignal and Trend == 1 else false st_entry_cond = pvt_cond_b or st_cond_b ///stop loss tp sl_b = if take_p if trend == 1 up else close - (atr * sl_atr) else close - (atr * sl_atr) tp_b = if take_p if trend == 1 close + ((close - up) * (tp_atr / sl_atr)) else close + (atr * tp_atr) else close + (atr * tp_atr) //position size init_cap = strategy.equity pos_size_b = math.round((init_cap * .01) / (close - sl_b)) ent_price = strategy.opentrades.entry_price(strategy.opentrades - 1) var sl_b_n = 0.0 var tp_b_n = 0.0 longCondition = (ema_cond_b and dema_cond_b and dema_ang_cond_b and st_entry_cond and date_range_cond and not_in_trade) if (longCondition) strategy.entry("Long", strategy.long, qty = pos_size_b) sl_b_n := sl_b tp_b_n := tp_b ent_price := strategy.opentrades.entry_price(strategy.opentrades - 1) if (up[1] < ent_price and up >= ent_price and trend[0] == 1) if din_tp strategy.close("Long", qty_percent = din_tp_qty) if move_sl sl_b_n := ent_price strategy.exit("Exit", "Long", stop =sl_b_n, limit = tp_b_n) //sell ///ema simple ema_cond_s = if ema_b ema1 < ema2 and ema2 < ema3 else true //ema distance dema_cond_s = if dema_b close < dema else true //dema angle dema_ang_cond_s = if ema_b_ang if dema_angle <= -(dema_a_filter) true else false else true //supertrends ///if pivot buy sig or (st buy sig and pivot. trend = 1) pvt_cond_s = ssignal st_cond_s = if st_sig sellSignal and Trend == -1 else false st_entry_cond_s = pvt_cond_s or st_cond_s ///stop loss tp sl_s = if take_p if trend == -1 dn else close + (atr * sl_atr) else close + (atr * sl_atr) tp_s = if take_p if trend == -1 close - ((dn - close) * (tp_atr / sl_atr)) else close - (atr * tp_atr) else close - (atr * tp_atr) shortCondition = (ema_cond_s and dema_cond_s and dema_ang_cond_s and date_range_cond and st_entry_cond_s and not_in_trade) pos_size_s = math.round((init_cap * .01) / (sl_s - close)) var sl_s_n = 0.0 var tp_s_n = 0.0 if (shortCondition) strategy.entry("Short", strategy.short, qty = pos_size_s) sl_s_n := sl_s tp_s_n := tp_s if (dn[1] > ent_price and dn <= ent_price and trend[0] == -1) if din_tp strategy.close("Short", qty_percent = din_tp_qty) if move_sl sl_s_n := ent_price strategy.exit("Exit", "Short", stop = sl_s_n, limit = tp_s_n)
TradeIQ Darvas Box Backtest
https://www.tradingview.com/script/Zqti4oAK-TradeIQ-Darvas-Box-Backtest/
xxy_theone
https://www.tradingview.com/u/xxy_theone/
75
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/ // © xxy_theone // https://www.youtube.com/watch?v=YYxlnFOX9sQ // This strategy script has been made to backtest the strategy explained in the video above //@version=5 strategy(shorttitle = "Darvas Box Test", title="TradeIQ Darvas Box Test", overlay=true, pyramiding=0, default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=100, currency=currency.USD) // === INPUT BACKTEST RANGE === var GRP1 = "Backtest Range" fromDate = input.time(timestamp("7 Mar 2022 00:00 +0000"), "From", group=GRP1) toDate = input.time(timestamp("19 Mar 2022 23:59 +0000"), "To", group=GRP1) window() => // create function "within window of time" time >= fromDate and time <= toDate ? true : false var GRP3 = "Darvas Box" boxp=input(5, "Box Length", group=GRP3) LL = ta.lowest(low,boxp) k1=ta.highest(high,boxp) k2=ta.highest(high,boxp-1) k3=ta.highest(high,boxp-2) NH = ta.valuewhen(high>k1[1],high,0) box1 =k3<k2 TopBox = ta.valuewhen(ta.barssince(high>k1[1])==boxp-2 and box1, NH, 0) BottomBox = ta.valuewhen(ta.barssince(high>k1[1])==boxp-2 and box1, LL, 0) plot(TopBox, linewidth=3, color=color.green, title="TBbox") plot(BottomBox, linewidth=3, color=color.red, title="BBbox") var GRP4 = "MavilimW" fmal=input(3,"First Moving Average length", group=GRP4) smal=input(5,"Second Moving Average length", group=GRP4) tmal=fmal+smal Fmal=smal+tmal Ftmal=tmal+Fmal Smal=Fmal+Ftmal M1= ta.wma(close, fmal) M2= ta.wma(M1, smal) M3= ta.wma(M2, tmal) M4= ta.wma(M3, Fmal) M5= ta.wma(M4, Ftmal) MAVW= ta.wma(M5, Smal) col1= MAVW>MAVW[1] col3= MAVW<MAVW[1] colorM = col1 ? color.blue : col3 ? color.red : color.yellow plot(MAVW, color=colorM, linewidth=2, title="MAVW") var GRP5 = "Relative Vigor Index" len = input.int(10, title="Length", minval=1, group=GRP5) rvi = math.sum(ta.swma(close-open), len)/math.sum(ta.swma(high-low),len) sig = ta.swma(rvi) offset = input.int(0, "Offset", minval = -500, maxval = 500, group=GRP5) //plot(rvi, color=#008000, title="RVGI", offset = offset) //plot(sig, color=#FF0000, title="Signal", offset = offset) var longStopSet = false long = ta.crossover(close,TopBox) and close > MAVW ? true : false longClose = strategy.opentrades.profit(strategy.opentrades-1)>0 and ta.crossunder(rvi,sig) ? true : false strategy.entry("Long Position", strategy.long, when = long and window() and strategy.position_size==0 and strategy.closedtrades<100) if(longStopSet==false and strategy.position_size > 0) strategy.exit("exit", "Long Position", stop=BottomBox) longStopSet := true if(strategy.position_size==0) longStopSet := false strategy.close("Long Position", when = longClose) var shortStopSet = false short = ta.crossunder(close,BottomBox) and close < MAVW ? true : false shortClose = strategy.opentrades.profit(strategy.opentrades-1)>0 and ta.crossover(rvi,sig) ? true : false strategy.entry("Short Position", strategy.short, when = short and window() and strategy.position_size==0 and strategy.closedtrades<100) if(shortStopSet==false and strategy.position_size < 0) strategy.exit("exit", "Short Position", stop=TopBox) shortStopSet := true if(strategy.position_size==0) shortStopSet := false strategy.close("Short Position", when = shortClose)
Loft Strategy V4
https://www.tradingview.com/script/Laq4rDWw-Loft-Strategy-V4/
BigCoinHunter
https://www.tradingview.com/u/BigCoinHunter/
529
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/ // © BigCoinHunter // ____ _ _____ _ _ _ _ // | _ \(_) / ____| (_) | | | | | | // | |_) |_ __ _| | ___ _ _ __ | |__| |_ _ _ __ | |_ ___ _ __ // | _ <| |/ _` | | / _ \| | '_ \| __ | | | | '_ \| __/ _ \ '__| // | |_) | | (_| | |___| (_) | | | | | | | | |_| | | | | || __/ | // |____/|_|\__, |\_____\___/|_|_| |_|_| |_|\__,_|_| |_|\__\___|_| // __/ | // |___/ //@version=5 strategy(title='Loft Strategy V4', overlay=true, pyramiding=0, default_qty_type=strategy.cash, default_qty_value=100, initial_capital=10000, currency=currency.USD, commission_value=0.05, commission_type=strategy.commission.percent, process_orders_on_close=true) //-------------- fetch user inputs ------------------ gain = input.float(title="Kalman Gain:", defval=100.0, minval=1, maxval=10000.0, step=1) src = input(defval=close, title='Source:') stopPercentBase = input.float(title='Beginning Approach(%)', defval=5.0, minval=0.1, maxval=30.0, step=0.1) stopPercentMin = input.float(title='Final Approach(%)', defval=1.0, minval=0.1, maxval=30.0, step=0.1) downStep = input.float(title='Approach Decrease Step', defval=0.001, minval=0.0, maxval = 5, step=0.001) //stopPercentDeviation = input.float(title="Approach Deviation", defval=1.0, minval=0.1, maxval = 5.0, step=0.1) baseOrderQty = input.float(title="Base Order Quantity", defval=100.0, minval=0.001) maxOrderCount = input.int(title="Max Safe Order Attemp", defval=4, minval=1) priceDeviation = input.float(title="Safe Order Deviation", defval=3, minval=1.0, step=0.1) profitDeviation = input.float(title="Profit Deviation", defval=1.0, minval=1.0, maxval=10, step=0.1) maxTakeProfit = input.float(title="Max Take Profit(%)", defval=25.0, maxval=100, step=0.1) maxOrderQty = input.float(title="Max Order Quantity", defval=10000.0, minval=0.01) baseTP1 = input.float(title="TP1(%)", defval=1.0, minval=0.0, maxval=100.0, step=0.1, inline="0") qt1 = input.int(title="QT1(%):", defval=40, minval=1, maxval=100, step=5, inline="0") baseTP2 = input.float(title="TP2(%)", defval=3.0, minval=0.0, maxval=100.0, step=0.1, inline="1") qt2 = input.int(title="QT2(%):", defval=30, minval=1, maxval=100, step=5, inline="1") baseTP3 = input.float(title="TP3(%)", defval=5.0, minval=0.0, maxval=100.0, step=0.1, inline="2") qt3 = input.int(title="QT3(%):", defval=30, minval=1, maxval=100, step=5, inline="2") initialStopLoss = input.float(title="Stop Loss(%)", defval=0.0, minval=0.0, maxval=100.0, step=0.1) longEntry = input.bool(defval=true, title= 'Long Entry', inline="3") shortEntry = input.bool(defval=true, title='Short Entry', inline="3") useSafeStop2 = input.bool(defval = true, title="Safe Stop After TP2", inline="6") useSafeStop1 = input.bool(defval = false, title="Safe Stop After TP1", inline="6") //---------- backtest range setup ------------ fromDay = input.int(defval = 1, title = "From Date:", minval = 1, maxval = 31, inline="4") fromMonth = input.int(defval = 1, title = "/", minval = 1, maxval = 12, inline="4") fromYear = input.int(defval = 2021, title = "/", minval = 2010, inline="4") toDay = input.int(defval = 30, title = "To__ Date:", minval = 1, maxval = 31, inline="5") toMonth = input.int(defval = 12, title = "/", minval = 1, maxval = 12, inline="5") toYear = input.int(defval = 2022, title = "/", minval = 2010, inline="5") //------------ time interval setup ----------- start = timestamp(fromYear, fromMonth, fromDay, 00, 00) // backtest start window finish = timestamp(toYear, toMonth, toDay, 23, 59) // backtest finish window window() => time >= start and time <= finish ? true : false // create function "within window of time" //------- define the order comments ------ enterLongComment = "" exitLongComment = "" enterShortComment = "" exitShortComment = "" longTPSL = "" longTP = "" longSL = "" shortTPSL = "" shortTP = "" shortSL = "" //--------- Define global variables ----------- var bool long = true var bool stoppedOutLong = false var bool stoppedOutShort = false var float kf = 0.0 var float velo = 0.0 var float orderQty = baseOrderQty var float stopLoss = initialStopLoss var bool isProfit = false var int barindex = 1 var int winCounter = 0 var int winCounterBuffer = 0 var int failCounter = 0 var float tp1 = baseTP1 var float tp2 = baseTP2 var float tp3 = baseTP3 var bool isTakeTP1 = false var bool isTakeTP2 = false var bool isTakeTP3 = false var bool isLastProfit = true var float stopPercentMax = stopPercentBase var float stopPercent = stopPercentBase var float stopLine = 0.0 var labelColor = color.blue //------ kalman filter calculation -------- dk = src - nz(kf[1], src) smooth = nz(kf[1], src) + dk * math.sqrt(gain / 10000 * 2) velo := nz(velo[1], 0) + gain / 10000 * dk kf := smooth + velo //--------- calculate the loft stopLoss line --------- //stopPercentMax := isLastProfit ? stopPercentBase : (stopPercentBase * stopPercentDeviation) if long == true stopLine := kf - (kf * (stopPercent / 100)) if long[1] == true and stopLine <= stopLine[1] stopLine := stopLine[1] else if (long[1] == true) stopPercent := stopPercent - downStep if(stopPercent < stopPercentMin) stopPercent := stopPercentMin if(kf < stopLine) long := false stopPercent := stopPercentMax stopLine := kf + (kf * (stopPercent / 100)) else stopLine := kf + (kf * (stopPercent / 100)) if long[1] == false and stopLine >= stopLine[1] stopLine := stopLine[1] else if(long[1] == false) stopPercent := stopPercent - downStep if(stopPercent < stopPercentMin) stopPercent := stopPercentMin if(kf > stopLine) long := true stopPercent := stopPercentMax stopLine := kf - (kf * (stopPercent / 100)) //------------------- determine buy and sell points --------------------- buySignall = window() and long and (not stoppedOutLong) sellSignall = window() and (not long) and (not stoppedOutShort) if longEntry and shortEntry if buySignall and baseTP1 <= 0.0 if strategy.position_size < 0 if close < strategy.position_avg_price isLastProfit := true else if strategy.position_size == 0 if strategy.wintrades > winCounter //strategy.wintrades[ barindex ] isLastProfit := true else isLastProfit := false else if sellSignall and baseTP1 <= 0.0 if strategy.position_size > 0 if close > strategy.position_avg_price isLastProfit := true else if strategy.position_size == 0 if strategy.wintrades > winCounter //strategy.wintrades[ barindex ] isLastProfit := true else isLastProfit := false else if isTakeTP2 == true isLastProfit := true else isLastProfit := false else if longEntry if sellSignall winCounterBuffer := winCounter if buySignall if winCounter > winCounterBuffer isLastProfit := true else isLastProfit := false else if shortEntry if buySignall winCounterBuffer := winCounter if sellSignall if winCounter > winCounterBuffer isLastProfit := true else isLastProfit := false //------------- set the deviations ------------ var float maxOrderSize = (baseOrderQty * math.pow(priceDeviation, maxOrderCount - 1)) if buySignall or sellSignall if isLastProfit == false orderQty := orderQty * priceDeviation tp1 := tp1 * profitDeviation tp2 := tp2 * profitDeviation tp3 := tp3 * profitDeviation tp1 := math.min(tp1, maxTakeProfit) tp2 := math.min(tp2, maxTakeProfit) tp3 := math.min(tp3, maxTakeProfit) if orderQty > maxOrderSize failCounter := failCounter + 1 orderQty := baseOrderQty tp1 := baseTP1 tp2 := baseTP2 tp3 := baseTP3 else orderQty := baseOrderQty tp1 := baseTP1 tp2 := baseTP2 tp3 := baseTP3 // ----------------- put debug labels ------------------- if orderQty == maxOrderSize labelColor := color.red else labelColor := isLastProfit ? color.lime : color.yellow if longEntry and shortEntry if buySignall or sellSignall label.new( x=bar_index, y=high, text="Qty:"+str.tostring(math.min(orderQty, maxOrderQty))+" | Worst Case:"+str.tostring(failCounter) ,color = labelColor ) else if longEntry if buySignall label.new( x=bar_index, y=high, text="Qty:"+str.tostring(math.min(orderQty, maxOrderQty))+" | Worst Case:"+str.tostring(failCounter) ,color = labelColor ) else if shortEntry if sellSignall label.new( x=bar_index, y=high, text="Qty:"+str.tostring(math.min(orderQty, maxOrderQty))+" | Worst Case:"+str.tostring(failCounter) ,color = labelColor ) //---------- execute the strategy ----------------- nz(orderQty, baseOrderQty) if longEntry and shortEntry if long strategy.close_all( when = buySignall, comment = exitShortComment) strategy.entry("LONG", strategy.long, when = buySignall, qty=math.min(orderQty, maxOrderQty), comment = enterLongComment) stoppedOutLong := true stoppedOutShort := false else strategy.close_all(when=sellSignall, comment = exitLongComment) strategy.entry("SHORT", strategy.short, when = sellSignall, qty=math.min(orderQty, maxOrderQty), comment = enterShortComment) stoppedOutLong := false stoppedOutShort := true else if(longEntry) strategy.entry("LONG", strategy.long, when = buySignall, qty=math.min(orderQty, maxOrderQty), comment = enterLongComment) strategy.close("LONG", when = sellSignall, comment = exitLongComment) if long stoppedOutLong := true stoppedOutShort := false else stoppedOutLong := false stoppedOutShort := true else if(shortEntry) strategy.entry("SHORT", strategy.short, when = sellSignall, qty=math.min(orderQty, maxOrderQty), comment = enterShortComment) strategy.close("SHORT", when = buySignall, comment = exitShortComment) if not long stoppedOutShort := true stoppedOutLong := false else stoppedOutShort := false stoppedOutLong := true //--------- calculate the TP/SL entries ----------- longProfitPrice1 = strategy.position_avg_price * (1 + tp1 * 0.01) longProfitPrice2 = strategy.position_avg_price * (1 + tp2 * 0.01) longProfitPrice3 = strategy.position_avg_price * (1 + tp3 * 0.01) shortProfitPrice1 = strategy.position_avg_price * (1 - tp1 * 0.01) shortProfitPrice2 = strategy.position_avg_price * (1 - tp2 * 0.01) shortProfitPrice3 = strategy.position_avg_price * (1 - tp3 * 0.01) longStopPrice = strategy.position_avg_price * (1 - stopLoss * 0.01) shortStopPrice = strategy.position_avg_price * (1 + stopLoss * 0.01) shortSafeStopPrice2 = strategy.position_avg_price * (1 - 0.2 * 0.01) longSafeStopPrice2 = strategy.position_avg_price * (1 + 0.2 * 0.01) longSafeStopPrice1 = stopLine shortSafeStopPrice1 = stopLine //----------- calculate TP quantity values ----------- takeQty1 = math.min(orderQty, maxOrderQty) * qt1 / 100 takeQty2 = math.min(orderQty, maxOrderQty) * qt2 / 100 takeQty3 = math.min(orderQty, maxOrderQty) * qt3 / 100 //----------------- take profit and stop loss processes ----------------- if strategy.position_size > 0 if close > longProfitPrice1 and tp1 > 0 and isTakeTP1 == false strategy.close(id="LONG", qty=takeQty1, comment = "longTP 1") isTakeTP1 := true if close > longProfitPrice2 and tp2 > 0 and isTakeTP2 == false strategy.close(id="LONG", qty=takeQty2, comment = "longTP 2") isTakeTP2 := true if close > longProfitPrice3 and tp3 > 0 and isTakeTP3 == false strategy.close(id="LONG", qty=takeQty3, comment = "longTP 3") isTakeTP3 := true if isTakeTP2 == true and useSafeStop2 strategy.exit(id="LONG", stop=longSafeStopPrice2, comment = "Long Safe Stop2") if isTakeTP1 == true and useSafeStop1 strategy.exit(id="LONG", stop=longSafeStopPrice1, comment = "Long Safe Stop1") if strategy.position_size < 0 if close < shortProfitPrice1 and tp1 > 0 and isTakeTP1 == false strategy.close(id="SHORT", qty=takeQty1, comment = "Short TP 1") isTakeTP1 := true if close < shortProfitPrice2 and tp2 > 0 and isTakeTP2 == false strategy.close(id="SHORT", qty=takeQty2, comment = "Short TP 2") isTakeTP2 := true if close < shortProfitPrice3 and tp3 > 0 and isTakeTP3 == false strategy.close(id="SHORT", qty=takeQty3, comment = "Short TP 3") isTakeTP3 := true if isTakeTP2 == true and useSafeStop2 strategy.exit(id="SHORT", stop=shortSafeStopPrice2, comment = "Short Safe Stop2") if isTakeTP1 == true and useSafeStop1 strategy.exit(id="SHORT", stop=shortSafeStopPrice1, comment = "Short Safe Stop1") if(initialStopLoss>0.0) if ( strategy.position_size > 0 ) strategy.exit(id="LONG", stop=longStopPrice, comment = "Long Stop Loss") else if ( strategy.position_size < 0 ) strategy.exit(id="SHORT", stop=shortStopPrice, comment = "Short Stop Loss") if buySignall or sellSignall isTakeTP1 := false isTakeTP2 := false isTakeTP3 := false winCounter := strategy.wintrades //------------- plot charts --------------------- lineColor1 = long ? color.green : color.red lineColor2 = long ? color.aqua : color.fuchsia kalmanPlot = plot(kf, color=lineColor1, linewidth=3, title = "Kalman Filter") stopPlot = plot(stopLine, color=lineColor2, linewidth=2, title = "Stop Loss Line")
TICK strategy for SPY options
https://www.tradingview.com/script/5NpphIlt-TICK-strategy-for-SPY-options/
PtGambler
https://www.tradingview.com/u/PtGambler/
474
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("TICK strategy for SPY", overlay=false, pyramiding=3, initial_capital=5000, commission_type=strategy.commission.cash_per_contract, commission_value = 0.0625) // ******************** 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 trade_options = input.bool(defval=true,title="Trading Options only", group = "Trading Options") option_amt = input.int(defval=10,title="# of options per trade", group = "Trading Options") option_multiplier = input.float(0.007, title="Multiplier for trading options (adjust to approx. options P&L)", step=0.001, 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") daily_max = input.float(1200, title="Stop trading after Max daily profit", group="Trading Options") // ***************************************************************************************************** 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") // ***************************************************** TICK Indictor ***************************************************** malen1 = input.int(5, title = "Fast EMA period", group = "TICK Indicator") malen2 = input.int(21, title = "Slow EMA period", group = "TICK Indicator") malen3 = input.int(21, title = "Hull MA period", group = "TICK Indicator") malen4 = input.int(5, title = "Hull MA Smoothing", group = "TICK Indicator") //get TICK data // tickO = request.security("USI:TICK", timeframe.period, open) tickC = request.security("USI:TICK", timeframe.period, close) tickAVG = ta.ema(tickC,malen1) tickAVG_L = ta.ema(tickC,malen2) f_hma(_src, _length) => _return = ta.wma(2 * ta.wma(_src, _length / 2) - ta.wma(_src, _length), math.round(math.sqrt(_length))) _return tickHMA = f_hma(tickC, malen3) tickHMA_MA = ta.ema(tickHMA, malen4) tick_bull = tickAVG > tickAVG[1] tick_bear = tickAVG < tickAVG[1] //Plot Tick data plot(tickC, title='TICK', color = color.new(color.white,30) , style=plot.style_line, linewidth = 1) //color = tickC > 0 ? color.green : color.red plot(tickAVG, title='TICK 9 EMA', color = color.yellow, style=plot.style_line, linewidth = 1) plot(tickAVG_L, title='TICK 21 EMA', color = color.new(color.red,70), style=plot.style_line, linewidth = 1) plot(tickHMA, title='TICK 21 HMA', color = color.blue, style=plot.style_line, linewidth = 2) plot(tickHMA_MA, title='TICK HMA Smoothed', color = color.purple, style=plot.style_line, linewidth = 2) hline(0, color=color.white, linewidth = 1, linestyle = hline.style_solid) hline(1000, color=color.green, linestyle=hline.style_solid, linewidth = 2) hline(500, color=color.gray, linestyle=hline.style_dashed) hline(-1000, color=color.red, linestyle=hline.style_solid, linewidth = 2) hline(-500, color=color.gray, linestyle=hline.style_dashed) // plotshape(ta.crossunder(tickHMA,tickAVG) ,"Cross down", color=color.red, style=shape.triangledown, location = location.top, size =size.tiny) // plotshape(ta.crossover(tickHMA,tickAVG) ,"Cross up", color=color.green, style=shape.triangleup, location = location.bottom, size =size.tiny) plotshape(ta.crossunder(tickHMA,tickHMA_MA) ,"Cross down", color=color.red, style=shape.triangledown, location = location.top, size =size.small) plotshape(ta.crossover(tickHMA,tickHMA_MA) ,"Cross up", color=color.green, style=shape.triangleup, location = location.bottom, size =size.small) tick_revUp = tickHMA[2] >= tickHMA[1] and tickHMA > tickHMA[1] tick_revDown = tickHMA[2] <= tickHMA[1] and tickHMA < tickHMA[1] plotshape(tick_revDown,"Cross down", color=color.orange, style=shape.triangledown, location = location.top, size =size.tiny) plotshape(tick_revUp ,"Cross up", color=color.blue, style=shape.triangleup, location = location.bottom, size =size.tiny) //Background bgcolor(tickAVG_L > 0 ? color.green : color.red, transp=90) bgcolor(tickC > 499 ? color.green : na, transp=70) bgcolor(tickC < -499 ? color.red : na, transp=70) bgcolor(tickC > 999 ? color.green : na, transp=30) bgcolor(tickC < -999 ? color.red : na, transp=30) lbR = input(title='Pivot Lookback Right', defval=0, group = "TICK Divergence") lbL = input(title='Pivot Lookback Left', defval=2, group = "TICK Divergence") rangeUpper = input(title='Max of Lookback Range', defval=60, group = "TICK Divergence") rangeLower = input(title='Min of Lookback Range', defval=5, group = "TICK Divergence") plotBull = input(title='Plot Bullish', defval=true, group = "TICK Divergence") plotHiddenBull = input(title='Plot Hidden Bullish', defval=true, group = "TICK Divergence") plotBear = input(title='Plot Bearish', defval=true, group = "TICK Divergence") plotHiddenBear = input(title='Plot Hidden Bearish', defval=false, group = "TICK Divergence") bearColor = color.red bullColor = color.green hiddenBullColor = color.new(color.green, 80) hiddenBearColor = color.new(color.red, 80) textColor = color.white noneColor = color.new(color.white, 100) plFound = na(ta.pivotlow(tickC, lbL, lbR)) ? false : true phFound = na(ta.pivothigh(tickC, lbL, lbR)) ? false : true _inRange(cond) => bars = ta.barssince(cond == true) rangeLower <= bars and bars <= rangeUpper //----------------------------------------------- TICK Divergence ------------------------------- // Regular Bullish // Osc: Higher Low oscHL = tickC[lbR] > ta.valuewhen(plFound, tickC[lbR], 1) and _inRange(plFound[1]) // Price: Lower Low priceLL = low[lbR] < ta.valuewhen(plFound, low[lbR], 1) bullCond = plotBull and priceLL and oscHL and plFound plot(plFound ? tickC[lbR] : na, offset=-lbR, title='Regular Bullish', linewidth=2, color=bullCond ? bullColor : noneColor, transp=0) plotshape(bullCond ? tickC[lbR] : na, offset=-lbR, title='Regular Bullish Label', text=' Bull ', style=shape.labelup, location=location.absolute, color=color.new(bullColor, 0), textcolor=color.new(textColor, 0)) //------------------------------------------------------------------------------ // Hidden Bullish // Osc: Lower Low oscLL = tickC[lbR] < ta.valuewhen(plFound, tickC[lbR], 1) and _inRange(plFound[1]) // Price: Higher Low priceHL = low[lbR] > ta.valuewhen(plFound, low[lbR], 1) hiddenBullCond = plotHiddenBull and priceHL and oscLL and plFound plot(plFound ? tickC[lbR] : na, offset=-lbR, title='Hidden Bullish', linewidth=2, color=hiddenBullCond ? hiddenBullColor : noneColor, transp=0) plotshape(hiddenBullCond ? tickC[lbR] : na, offset=-lbR, title='Hidden Bullish Label', text=' H Bull ', style=shape.labelup, location=location.absolute, color=color.new(bullColor, 0), textcolor=color.new(textColor, 0)) //------------------------------------------------------------------------------ // Regular Bearish // Osc: Lower High oscLH = tickC[lbR] < ta.valuewhen(phFound, tickC[lbR], 1) and _inRange(phFound[1]) // Price: Higher High priceHH = high[lbR] > ta.valuewhen(phFound, high[lbR], 1) bearCond = plotBear and priceHH and oscLH and phFound plot(phFound ? tickC[lbR] : na, offset=-lbR, title='Regular Bearish', linewidth=2, color=bearCond ? bearColor : noneColor, transp=0) plotshape(bearCond ? tickC[lbR] : na, offset=-lbR, title='Regular Bearish Label', text=' Bear ', style=shape.labeldown, location=location.absolute, color=color.new(bearColor, 0), textcolor=color.new(textColor, 0)) //------------------------------------------------------------------------------ // Hidden Bearish // Osc: Higher High oscHH = tickC[lbR] > ta.valuewhen(phFound, tickC[lbR], 1) and _inRange(phFound[1]) // Price: Lower High priceLH = high[lbR] < ta.valuewhen(phFound, high[lbR], 1) hiddenBearCond = plotHiddenBear and priceLH and oscHH and phFound plot(phFound ? tickC[lbR] : na, offset=-lbR, title='Hidden Bearish', linewidth=2, color=hiddenBearCond ? hiddenBearColor : noneColor, transp=0) plotshape(hiddenBearCond ? tickC[lbR] : na, offset=-lbR, title='Hidden Bearish Label', text=' H Bear ', style=shape.labeldown, location=location.absolute, color=color.new(bearColor, 0), textcolor=color.new(textColor, 0)) //-------------------------------------------------------- RSI ------------------------------------ src = close rsi_len = input.int(14, minval=1, title="RSI Length", group = "RSI") rsi_ma_len = input.int(1, minval=1, title="RSI Signal Length", group = "RSI") rsi_up = ta.rma(math.max(ta.change(src), 0), rsi_len) rsi_down = ta.rma(-math.min(ta.change(src), 0), rsi_len) rsi = rsi_down == 0 ? 100 : rsi_up == 0 ? 0 : 100 - (100 / (1 + rsi_up / rsi_down)) rsi_ma = ta.sma(rsi,rsi_ma_len) rsi_avg = math.avg(rsi,rsi_ma) rsi_bull = rsi_avg > rsi_avg[1] rsi_bear = rsi_avg < rsi_avg[1] rsi_thres = input.int(20,"RSI Overbought/Oversold levels +/- from 50", group = "RSI") //-------------------------------------------------------- Moving Average ------------------------------------ emalen1 = input.int(8, minval=1, title='Fast EMA', group= "Moving Averages") ema1 = ta.ema(src, emalen1) //------------------------------------------------------------------------------------- profit = strategy.netprofit trade_amount = math.floor(strategy.initial_capital / close) BSLE()=> strategy.opentrades > 0 ? (bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades-1)) : na min_hold = input.int(6,"Minimum bars to hold order", group = "Trading Options") if trade_options if strategy.netprofit > 0 and reinvest// and strategy.closedtrades.profit(strategy.closedtrades-1) > 0 trade_amount := math.floor(strategy.initial_capital * option_multiplier) * (option_amt + math.floor(((profit*reinvest_percent*0.01)/strategy.initial_capital)*10)) else trade_amount := math.floor(strategy.initial_capital * option_multiplier) * option_amt // -------------------- daily_profit = 0.0 for i = 0 to strategy.closedtrades-1 if strategy.closedtrades.exit_time(i) > time_tradingday daily_profit += strategy.closedtrades.profit(i) // plot(daily_profit, "Daily P/L") pause_trade1 = daily_profit > daily_max trade_amount := pause_trade1 ? 1 : trade_amount L_entry0 = ta.crossover(tickHMA, tickHMA_MA) and rsi_avg > 50 and rsi < 50 + rsi_thres and VIX > vix_thres and tickAVG > 0 //and close > ema1 S_entry0 = ta.crossunder(tickHMA,tickHMA_MA) and rsi_avg < 50 and rsi > 50 - rsi_thres and VIX > vix_thres and tickAVG < 0 //and close < ema1 L_entry1 = L_entry0 and close > ema1 S_entry1 = S_entry0 and close < ema1 L_entry2 = strategy.opentrades == 0 and ta.barssince(L_entry0) < 2 and close > ema1 S_entry2 = strategy.opentrades == 0 and ta.barssince(S_entry0) < 2 and close < ema1 long_SL = low[1] - datrp short_SL = high[1] + datrp if strategy.opentrades > 0 long_SL := math.min(long_SL[BSLE()], low[1] - datrp) short_SL := math.max(short_SL[BSLE()], high[1] + datrp) L_exit1 = tickHMA < tickHMA_MA and rsi_bear S_exit1 = tickHMA > tickHMA_MA and rsi_bull L_exit2 = bearCond S_exit2 = bullCond trade_amount_long = trade_amount trade_amount_short = trade_amount if (L_entry1) and window and barstate.isconfirmed //and not(pause_trade1) strategy.entry("Long", strategy.long, trade_amount_long) if (S_entry1) and window and barstate.isconfirmed //and not(pause_trade1) strategy.entry("Short", strategy.short, trade_amount_short) if L_entry2 and not(L_entry1) and window and barstate.isconfirmed //and not(pause_trade1) strategy.entry("Long2", strategy.long, trade_amount_long, comment="Long 2") if (S_entry2) and not(S_entry2) and window and barstate.isconfirmed //and not(pause_trade1) strategy.entry("Short2", strategy.short, trade_amount_short, comment="Short 2" ) if BSLE() > min_hold and window2 and barstate.isconfirmed strategy.exit("Exit", "Long", stop = long_SL, comment = "Stopped out") strategy.exit("Exit", "Short", stop = short_SL, comment = "Stopped out") strategy.close("Long", when = L_exit1 or L_exit2) strategy.close("Short", when = S_exit1 or S_exit2) if window2 and barstate.isconfirmed strategy.exit("Exit2", "Long2", stop = long_SL, comment = "Stopped out") strategy.exit("Exit2", "Short2", stop = short_SL, comment = "Stopped out") strategy.close("Long2", when = L_exit1 or L_exit2) strategy.close("Short2", when = S_exit1 or S_exit2) if time(timeframe.period, "1550-1600:23456") strategy.close_all()
TICK Scalping strategy, SPY 1 min
https://www.tradingview.com/script/yiBwexdm-TICK-Scalping-strategy-SPY-1-min/
PtGambler
https://www.tradingview.com/u/PtGambler/
1,138
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 // How it works: // When trading the indices, many rely on the TICK for market directions. This strategy is a trend following strategy that uses a combination of conditions using the following indicators: // - TICK // - RSI // - VIX volatility index // - EMA // For entries, the conditions are: // 1. TICK moving average crossover with a delayed signal line // 2. Bullish or bearish RSI signal, RSI > 50 for bullish , < 50 for bearish // 3. VIX must be above a certain threshold to take advantage of high market volatility // 4. Price must be on top of EMA line for long, and below for short // 5. Price has not moved significantly already (this delta can be set) // For exits, there are 3 scenarios: // 1. Stop loss set by a percentage of the daily ATR value // 2. Trend changes on the TICK and the RSI // 3. Bearish or bullish divergence on price with TICK // This strategy automatically signal to close all trades at 3:50 pm EST at the end of the day. // Extras: // - There is an option to show P/L for reinvesting profits //@version=5 strategy("TICK strategy, SPY 1 min", overlay=false, pyramiding=3, initial_capital=5000, commission_type=strategy.commission.cash_per_contract, commission_value = 0.0625) indicator_only = input.bool(false,"Use As Indicator Only", tooltip = "Disables strategy signals") // ******************** 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, "0930-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 trade_options = input.bool(defval=true,title="Trading Options only", group = "Trading Options") option_amt = input.int(defval=10,title="# of options per trade", group = "Trading Options") option_multiplier = input.float(0.007, title="Multiplier for trading options (adjust to approx. options P&L)", step=0.001, 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") trade_TICKdiverg = input.bool(true, title="Trade with TICK divergences", group = "Trading Options") diverg_lookback = input.int(defval=5, title="TICK divergence lookback period (only if trading TICK divergence", group = "Trading Options") trade_optimal = input.bool(true, title="Trade with optimal Stochastic", group = "Trading Options") entry_lookback = input.int(defval=12, title="Lookback period for entry condition, waiting for Stochastic", group = "Trading Options") k_entry_thres = input.int(defval=0, title="Stochastic RSI k value offset from 50 for entry threshold (ie. 10 means long entry under k=60", group = "Trading Options") trade_chase = input.bool(true, title="Trade with Chasing entries", group = "Trading Options") chase_lookback = input.int(defval=10, title="Chase entry lookback period", group = "Trading Options") k_chase_thres = input.int(defval=30, title="Stochastic RSI k value offset from 50 for chase entry threshold (ie. 30 means long entry under k=80", group = "Trading Options") trade_PT = input.bool(true, title="Trade with Price Target", group = "Trading Options") no_longat10 = input.bool(false, title="No entry between 10 - 10:30", group = "Trading Options") hold_ON = input.bool(true, title="Hold 1/2 position overnight on Tues/Thurs", group = "Trading Options") // ***************************************************************************************************** Daily ATR ***************************************************** atrlen = input.int(4, minval=1, title="ATR period", group = "Daily ATR") SL_atr_perc = input.float(9, minval=1, maxval=100, step=0.5, title="% ATR to use for SL", group = "Daily ATR") PT_atr_perc = input.float(17.5, minval=1, maxval=100, step=0.5, title="% ATR to use for PT (only if trading w/ PT)", group = "Daily ATR") SL_atr = SL_atr_perc * 0.01 PT_atr = PT_atr_perc * 0.01 datr = request.security(syminfo.tickerid, "1D", ta.rma(ta.tr, atrlen)) d_SL_atr = datr * SL_atr d_PT_atr = datr * PT_atr // plot(datr,"Daily ATR") // plot(d_SL_atr, "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") // ***************************************************** TICK Indictor ***************************************************** malen1 = input.int(21, title = "Fast EMA period", group = "TICK Indicator") malen2 = input.int(102, title = "Slow EMA period", group = "TICK Indicator") malen3 = input.int(135, title = "Hull MA period", group = "TICK Indicator") malen4 = input.int(25, title = "Hull MA Smoothing", group = "TICK Indicator") //get TICK data // tickO = request.security("USI:TICK", timeframe.period, open) tickH = request.security("USI:TICK", "5", high) tickC = request.security("USI:TICK", "5", close) tickL = request.security("USI:TICK", "5", low) tickAVG = ta.ema(tickC,malen1) tickAVG_L = ta.ema(tickC,malen2) f_hma(_src, _length) => _return = ta.wma(2 * ta.wma(_src, _length / 2) - ta.wma(_src, _length), math.round(math.sqrt(_length))) _return tickHMA = f_hma(tickC, malen3) tickHMA_MA = ta.sma(tickHMA, malen4) tick_bull = tickAVG > tickAVG[5] tick_bear = tickAVG < tickAVG[5] //Plot Tick data plot(barstate.isconfirmed? tickC : na, title='TICK', color = color.new(color.white,30) , style=plot.style_line, linewidth = 1) //color = tickC > 0 ? color.green : color.red plot(tickAVG, title='TICK 9 EMA', color = color.yellow, style=plot.style_line, linewidth = 1) plot(tickAVG_L, title='TICK 21 EMA', color = color.new(color.red,70), style=plot.style_line, linewidth = 1) plot(tickHMA, title='TICK 21 HMA', color = color.blue, style=plot.style_line, linewidth = 2) plot(tickHMA_MA, title='TICK HMA Smoothed', color = color.purple, style=plot.style_line, linewidth = 2) hline(0, color=color.white, linewidth = 1, linestyle = hline.style_solid) hline(1000, color=color.green, linestyle=hline.style_solid, linewidth = 2) hline(500, color=color.gray, linestyle=hline.style_dashed) hline(-1000, color=color.red, linestyle=hline.style_solid, linewidth = 2) hline(-500, color=color.gray, linestyle=hline.style_dashed) // plotshape(ta.crossunder(tickHMA,tickAVG) ,"Cross down", color=color.red, style=shape.triangledown, location = location.top, size =size.tiny) // plotshape(ta.crossover(tickHMA,tickAVG) ,"Cross up", color=color.green, style=shape.triangleup, location = location.bottom, size =size.tiny) plotshape(ta.crossunder(tickHMA,tickHMA_MA) ,"Cross down", color=color.red, style=shape.triangledown, location = location.top, size =size.tiny) plotshape(ta.crossover(tickHMA,tickHMA_MA) ,"Cross up", color=color.green, style=shape.triangleup, location = location.bottom, size =size.tiny) //Background bgcolor(tickAVG_L > 0 ? color.new(color.green, 90) : color.new(color.red, 90)) bgcolor(tickC > 499 ? color.new(color.green, 70) : na) bgcolor(tickC < -499 ? color.new(color.red, 70) : na) bgcolor(tickC > 999 ?color.new(color.green,30) : na) bgcolor(tickC < -999 ? color.new(color.red,30) : na) lbR = input(title='Pivot Lookback Right', defval=5, group = "TICK Divergence") lbL = input(title='Pivot Lookback Left', defval=10, group = "TICK Divergence") rangeUpper = input(title='Max of Lookback Range', defval=300, group = "TICK Divergence") rangeLower = input(title='Min of Lookback Range', defval=25, group = "TICK Divergence") plotBull = input(title='Plot Bullish', defval=true, group = "TICK Divergence") plotHiddenBull = input(title='Plot Hidden Bullish', defval=false, group = "TICK Divergence") plotBear = input(title='Plot Bearish', defval=true, group = "TICK Divergence") plotHiddenBear = input(title='Plot Hidden Bearish', defval=false, group = "TICK Divergence") bearColor = color.red bullColor = color.green hiddenBullColor = color.new(color.green, 80) hiddenBearColor = color.new(color.red, 80) textColor = color.white noneColor = color.new(color.white, 100) plFound = na(ta.pivotlow(tickC, lbL, lbR)) ? false : true phFound = na(ta.pivothigh(tickC, lbL, lbR)) ? false : true _inRange(cond) => bars = ta.barssince(cond == true) rangeLower <= bars and bars <= rangeUpper //----------------------------------------------- TICK Divergence ------------------------------- // Regular Bullish // Osc: Higher Low oscHL = tickC[lbR] > ta.valuewhen(plFound, tickC[lbR], 1) and _inRange(plFound[1]) // Price: Lower Low priceLL = low[lbR] < ta.valuewhen(plFound, low[lbR], 1) bullCond = plotBull and priceLL and oscHL and plFound plot(plFound ? tickC[lbR] : na, offset=-lbR, title='Regular Bullish', linewidth=2, color=bullCond ? bullColor : noneColor) plotshape(bullCond ? tickC[lbR] : na, offset=-lbR, title='Regular Bullish Label', text=' Bull ', style=shape.labelup, location=location.absolute, color=color.new(bullColor, 0), textcolor=color.new(textColor, 0)) //------------------------------------------------------------------------------ // Hidden Bullish // Osc: Lower Low oscLL = tickC[lbR] < ta.valuewhen(plFound, tickC[lbR], 1) and _inRange(plFound[1]) // Price: Higher Low priceHL = low[lbR] > ta.valuewhen(plFound, low[lbR], 1) hiddenBullCond = plotHiddenBull and priceHL and oscLL and plFound plot(plFound ? tickC[lbR] : na, offset=-lbR, title='Hidden Bullish', linewidth=2, color=hiddenBullCond ? hiddenBullColor : noneColor) plotshape(hiddenBullCond ? tickC[lbR] : na, offset=-lbR, title='Hidden Bullish Label', text=' H Bull ', style=shape.labelup, location=location.absolute, color=color.new(bullColor, 0), textcolor=color.new(textColor, 0)) //------------------------------------------------------------------------------ // Regular Bearish // Osc: Lower High oscLH = tickC[lbR] < ta.valuewhen(phFound, tickC[lbR], 1) and _inRange(phFound[1]) // Price: Higher High priceHH = high[lbR] > ta.valuewhen(phFound, high[lbR], 1) bearCond = plotBear and priceHH and oscLH and phFound plot(phFound ? tickC[lbR] : na, offset=-lbR, title='Regular Bearish', linewidth=2, color=bearCond ? bearColor : noneColor) plotshape(bearCond ? tickC[lbR] : na, offset=-lbR, title='Regular Bearish Label', text=' Bear ', style=shape.labeldown, location=location.absolute, color=color.new(bearColor, 0), textcolor=color.new(textColor, 0)) //------------------------------------------------------------------------------ // Hidden Bearish // Osc: Higher High oscHH = tickC[lbR] > ta.valuewhen(phFound, tickC[lbR], 1) and _inRange(phFound[1]) // Price: Lower High priceLH = high[lbR] < ta.valuewhen(phFound, high[lbR], 1) hiddenBearCond = plotHiddenBear and priceLH and oscHH and phFound plot(phFound ? tickC[lbR] : na, offset=-lbR, title='Hidden Bearish', linewidth=2, color=hiddenBearCond ? hiddenBearColor : noneColor) plotshape(hiddenBearCond ? tickC[lbR] : na, offset=-lbR, title='Hidden Bearish Label', text=' H Bear ', style=shape.labeldown, location=location.absolute, color=color.new(bearColor, 0), textcolor=color.new(textColor, 0)) //-------------------------------------------------------- RSI ------------------------------------ src = close //request.security(syminfo.ticker, "5",close) rsi_len = input.int(70, minval=1, title="RSI Length", group = "RSI") rsi_ma_len = input.int(6, minval=1, title="RSI Signal Length", group = "RSI") rsi_up = ta.rma(math.max(ta.change(src), 0), rsi_len) rsi_down = ta.rma(-math.min(ta.change(src), 0), rsi_len) rsi = rsi_down == 0 ? 100 : rsi_up == 0 ? 0 : 100 - (100 / (1 + rsi_up / rsi_down)) rsi_ma = ta.wma(rsi,rsi_ma_len) rsi_avg = rsi_ma//math.avg(rsi,rsi_ma) rsi_bull = rsi_avg > rsi_avg[1] rsi_bear = rsi_avg < rsi_avg[1] rsi_thres = input.int(15,"RSI Overbought/Oversold levels +/- from 50", group = "RSI") rsi_len2 = input.int(14, minval=1, title="Fast RSI Length", group = "RSI") rsi_up2 = ta.rma(math.max(ta.change(src), 0), rsi_len2) rsi_down2 = ta.rma(-math.min(ta.change(src), 0), rsi_len2) rsi2 = rsi_down2 == 0 ? 100 : rsi_up2 == 0 ? 0 : 100 - (100 / (1 + rsi_up2 / rsi_down2)) //-------------------------------------------------------- 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_stoch = ta.rsi(src, lengthRSI) k = ta.sma(ta.stoch(rsi_stoch, rsi_stoch, rsi_stoch, lengthStoch), smoothK) d = ta.sma(k, smoothD) //-------------------------------------------------------- Moving Average ------------------------------------ ma_src = close emalen1 = input.int(20, minval=1, title='Filtering EMA', group= "Moving Averages") ema1 = ta.ema(ma_src, emalen1) //------------------------------------------------------------- Trade options ------------------------ profit = strategy.netprofit trade_amount = math.floor(strategy.initial_capital / close) BSLE()=> strategy.opentrades > 0 ? (bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades-1)) : na BSLExit()=> strategy.opentrades == 0 ? (bar_index - strategy.closedtrades.exit_bar_index(strategy.closedtrades-1)) : na min_hold = input.int(6,"Minimum bars to hold order", group = "Trading Options") if trade_options if strategy.netprofit > 0 and reinvest// and strategy.closedtrades.profit(strategy.closedtrades-1) > 0 trade_amount := math.floor(strategy.initial_capital * option_multiplier) * (option_amt + math.floor(((profit*reinvest_percent*0.01)/strategy.initial_capital)*10)) else trade_amount := math.floor(strategy.initial_capital * option_multiplier) * option_amt // **************************************************************************************************************************************** Trade Pauses **************************************** bool trade_pause = false bool trade_pause2 = false trade_pause := false if no_longat10 and time(timeframe.period, "1000-1030:23456") trade_pause2 := true else trade_pause2 := false // ---------------------------------------------------------------- Entry Conditions ------------------------------------------------------------ L_entry0 = ta.crossover(tickHMA, tickHMA_MA) and rsi_avg > 50 and rsi < 50 + rsi_thres and VIX > vix_thres and tickAVG > 0 and close > ema1 S_entry0 = ta.crossunder(tickHMA,tickHMA_MA) and rsi_avg < 50 and rsi > 50 - rsi_thres and VIX > vix_thres and tickAVG < 0 and close < ema1 L_entry1 = L_entry0 S_entry1 = S_entry0 BSL = ta.barssince(L_entry0) BSS = ta.barssince(S_entry0) // plot(BSL, "Bars since long entry condition") // plot(BSS, "Bars since short entry condition") if trade_optimal and strategy.opentrades == 0 if BSL < entry_lookback L_entry1 := k < 50 + k_entry_thres and k > k[1] else L_entry1 := L_entry0 if BSS < entry_lookback S_entry1 := k > 50 - k_entry_thres and k < k[1] else S_entry1 := S_entry0 // plotshape(L_entry0 ,"Long entry condition", color=color.blue, style=shape.triangleup, location = location.bottom, size =size.tiny) // plotshape(S_entry0 ,"Short entry condition", color=color.orange, style=shape.triangledown, location = location.top, size =size.tiny) L_entry2 = bullCond and tickHMA > tickHMA_MA and rsi > rsi_ma and VIX > vix_thres and tickAVG > 0 and close > ema1 S_entry2 = bearCond and tickHMA < tickHMA_MA and rsi < rsi_ma and VIX > vix_thres and tickAVG < 0 and close < ema1 L_entry3 = BSLExit() < chase_lookback and close > close[BSLExit()] and tickHMA > tickHMA_MA and tickHMA > tickHMA[1] and rsi_avg > 50 and rsi < 50 + rsi_thres and VIX > vix_thres and tickAVG > tickAVG[1] and close > ema1 and k < 50 + k_chase_thres S_entry3 = BSLExit() < chase_lookback and close < close[BSLExit()] and tickHMA < tickHMA_MA and tickHMA < tickHMA[1] and rsi_avg < 50 and rsi > 50 - rsi_thres and VIX > vix_thres and tickAVG < tickAVG[1] and close < ema1 and k > 50 - k_chase_thres if not indicator_only if L_entry1 and window and not(trade_pause) and not(trade_pause2) and barstate.isconfirmed strategy.entry("Long", strategy.long, trade_amount, comment="Long") if trade_TICKdiverg and L_entry2 and window and not(trade_pause) and not(trade_pause2) and barstate.isconfirmed and strategy.opentrades == 0 //limit to 1 entry, ignoring pyramiding strategy.entry("Long", strategy.long, trade_amount, comment="Long, TICK divergence") if trade_chase and L_entry3 and window and not(trade_pause) and not(trade_pause2) and barstate.isconfirmed and strategy.opentrades == 0 //limit to 1 entry, ignoring pyramiding strategy.entry("Long", strategy.long, trade_amount, comment="Long, Chase") if S_entry1 and window and not(trade_pause) and not(trade_pause2) and barstate.isconfirmed strategy.entry("Short", strategy.short, trade_amount, comment="Short") if trade_TICKdiverg and S_entry2 and window and not(trade_pause) and not(trade_pause2) and barstate.isconfirmed and strategy.opentrades == 0 //limit to 1 entry, ignoring pyramiding strategy.entry("Short", strategy.short, trade_amount, comment="Short, TICK divergence") if trade_chase and S_entry3 and window and not(trade_pause) and not(trade_pause2) and barstate.isconfirmed and strategy.opentrades == 0 //limit to 1 entry, ignoring pyramiding strategy.entry("Short", strategy.short, trade_amount, comment="Short, Chase") // ---------------------------------------------------------------- SL / PT ------------------------------------------------------------------- long_SL = ta.lowest(low,5) - d_SL_atr short_SL = ta.highest(high,5) + d_SL_atr if strategy.opentrades > 0 long_SL := math.min(long_SL[BSLE()], low[1] - d_SL_atr) short_SL := math.max(short_SL[BSLE()], high[1] + d_SL_atr) // plot(long_SL, "Long SL") // plot(short_SL,"Short SL") long_PT = close + d_PT_atr short_PT = close - d_PT_atr if strategy.opentrades > 0 long_PT := strategy.opentrades.entry_price(0) + d_PT_atr short_PT := strategy.opentrades.entry_price(0) - d_PT_atr // ---------------------------------------------------------------- Exit Conditions ------------------------------------------------------------ L_exit1 = tickHMA < tickHMA_MA and rsi_bear S_exit1 = tickHMA > tickHMA_MA and rsi_bull L_exit2 = bearCond S_exit2 = bullCond L_exit3 = tickH > 1000 S_exit3 = tickL < -1000 L_exit4 = strategy.opentrades.profit(strategy.opentrades-1) > 0 and tickHMA < tickHMA[1] and rsi2 < 50 S_exit4 = strategy.opentrades.profit(strategy.opentrades-1) > 0 and tickHMA > tickHMA[1] and rsi2 > 50 if BSLE() > min_hold and window2 if trade_PT strategy.exit("Exit", "Long", stop = long_SL, limit = long_PT, comment = "SL/PT hit") strategy.exit("Exit", "Short", stop = short_SL, limit = short_PT, comment = "SL/PT hit") else strategy.exit("Exit", "Long", stop = long_SL, comment = "SL hit") strategy.exit("Exit", "Short", stop = short_SL, comment = "SL hit") strategy.close("Long", when = L_exit1, comment = "Exit, TICK/RSI reversal") strategy.close("Short", when = S_exit1, comment = "Exit, TICK/RSI reversal") strategy.close("Long", when = L_exit2, comment = "Exit, Bearish Divergence") strategy.close("Short", when = S_exit2, comment = "Exit, Bullish Divergence") strategy.close("Long", when = L_exit3, comment = "Exit, TICK overbought") strategy.close("Short", when = S_exit3, comment = "Exit, TICK oversold") // strategy.close("Long", when = L_exit4, comment = "Exit, TICK/RSI reversal 2") // strategy.close("Short", when = S_exit4, comment = "Exit, TICK/RSI reversal 2") if hold_ON if time(timeframe.period, "1550-1551:246") strategy.close_all() if time(timeframe.period, "1550-1551:35") strategy.close("Long", qty_percent = 50, comment="Close 1/2 EOD") strategy.close("Short", qty_percent = 50, comment="Close 1/2 EOD") else if time(timeframe.period, "1550-1551:23456") strategy.close_all()
GAS Backtest
https://www.tradingview.com/script/yRCm3hFR/
windlu
https://www.tradingview.com/u/windlu/
52
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ //@version=5 strategy("GAS Backtest",overlay=true, initial_capital=10000, process_orders_on_close=false) startDate = input.time(title="Start Date", defval=timestamp("5 Mar 2022 00:00 +0800")) endDate = input.time(title="Start Date", defval=timestamp("5 Mar 2022 00:00 +0800")) gridPct = input.float(title="Grid PCT", defval=1, minval = 0.1, step = 0.25, maxval = 100) maxOrder = input.int(title="Max Order", defval=2, minval=1) initBuy = input.bool(title="Grid Reward Only",defval=true) userVol = input.float(title="Grid Vol (optional)",defval=0) refGrid = input.float(title="Ref. Grid (optional)",defval=0, minval=0) userSetting = input.bool(title="Apply User setting",defval=false) today = input.bool(title="Today Only",defval=true) if today startDate := timenow - ( timenow + 28800000 ) % 86400000 - 1800000 endDate := timenow if userSetting switch syminfo.ticker "SOLUSD" => gridPct := 1 maxOrder := 5 userVol := 1 refGrid := 45 => startDate := time + 120000 if timeframe.period != "1" startDate := time + 120000 pct = 1 + gridPct / 100.0 gridLine = open vol = 0.0 ratio = 2 sellCount = 0 buyCount = 0 gain = 0.0 var label labelName = na if labelName[1] != na label.delete(labelName[1]) if time > startDate and time <= endDate vol := vol[1] gridLine := gridLine[1] pct := pct[1] if hour != 16 or minute != 0 buyCount := buyCount[1] sellCount := sellCount[1] gain := gain[1] nt = math.max( math.floor( math.log( high / gridLine ) / math.log( pct ) ), 0) nt := math.min( nt , maxOrder) //highLine = gridLine * math.pow(pct,nt) highLine = gridLine if nt != 0 prePrice = highLine for i = 1 to nt highLine := math.ceil( highLine * pct / syminfo.mintick ) * syminfo.mintick gain += ( highLine - prePrice ) * vol prePrice := highLine gain := math.round( gain * 100 ) * 0.01 sellCount += nt nb = math.min( math.ceil( math.log( low / gridLine ) / math.log( pct ) ), 0) nb := math.max( nb , -1 * maxOrder) //lowLine = gridLine * math.pow(pct,nb) lowLine = gridLine if nb != 0 for i = 1 to -1*nb lowLine := math.floor( lowLine / pct / syminfo.mintick ) * syminfo.mintick buyCount -= nb if ( highLine != gridLine ) and ( lowLine != gridLine ) gridLine := ( highLine - gridLine ) > ( gridLine - lowLine ) ? lowLine : highLine else if highLine != gridLine gridLine := highLine else if lowLine != gridLine gridLine := lowLine if ( gridLine != gridLine[1] ) buyPrice = gridLine sellPrice = gridLine strategy.cancel_all() for i = 1 to maxOrder //sellPrice := sellPrice * pct sellPrice := math.ceil( sellPrice * pct / syminfo.mintick ) * syminfo.mintick strategy.order( str.format("Sell{0}",i), strategy.short, vol, limit=sellPrice) //buyPrice := buyPrice / pct buyPrice := math.floor( buyPrice / pct / syminfo.mintick ) * syminfo.mintick strategy.order( str.format("Buy{0}",i), strategy.long, vol, limit=buyPrice) else if time == startDate //label.new(bar_index, high, syminfo.ticker ) if refGrid != 0 n = math.floor( math.log( gridLine / refGrid ) / math.log( pct ) ) line1 = refGrid line2 = line1 for i = 1 to ( n >= 0 ? n+1 : -1*n ) line2 := line1 line1 := if n >= 0 math.ceil( line1 * pct / syminfo.mintick ) * syminfo.mintick else math.floor( line1 / pct / syminfo.mintick ) * syminfo.mintick // line1 = refGrid * math.pow( pct, n ) // line2 = line1 * pct h = high l = low i = 1 while true if ( line1 <= h ) and ( line1 >= l ) gridLine := line1 break if ( line2 <= h ) and ( line2 >= l ) gridLine := line2 break h := high[i] > h ? high[i] : h l := low[i] < l ? low[i] : l i += 1 botBound = gridLine / 1.1 topBound = gridLine * 1.1 nb = math.floor( math.log( gridLine / botBound ) / math.log( pct ) ) vol := gridLine / pct * ( 1 - math.pow( 1/pct, math.max(nb,0) ) ) / ( 1 - 1/pct) nt = math.floor( math.log( topBound / gridLine ) / math.log( pct ) ) if nt < 0 vol -= gridLine / pct * ( 1 - math.pow( 1/pct, -1 - nt) ) / ( 1 - 1/pct ) nt := 0 if initBuy == false if nb < 0 nt -= -1 - nb vol += nt * close else vol += gridLine * ( 1 - math.pow( pct, nt ) ) / ( 1 - pct) if nb < 0 vol -= gridLine * ( 1 - math.pow( pct, -1*nb ) ) / ( 1 - pct ) if userVol == 0 vol := strategy.equity / vol else if userVol > 0 vol := userVol else vol := -1 * userVol * gridPct if initBuy == false strategy.order("init", strategy.long, nt*vol) buyPrice = gridLine sellPrice = gridLine for i = 1 to maxOrder sellPrice := sellPrice * pct strategy.order( str.format("Sell{0}",i), strategy.short, vol, limit=sellPrice) buyPrice := buyPrice / pct strategy.order( str.format("Buy{0}",i), strategy.long, vol, limit=buyPrice) if time == endDate strategy.cancel_all() //plot(line1, color= color.red) //plot(line2) //plot(pct * 100 -10) //plot(syminfo.mintick) if today and ( time >= startDate ) and bar_index >= last_bar_index-1 labelName := label.new(x=bar_index+80, y=high*1.002, text = str.format("Buy : {0}\nSell : {1}\nGain : {2}",buyCount,sellCount,gain), style=label.style_label_center, textcolor = color.white) plot( time >= startDate and time <= endDate? gridLine : na , color = color.yellow, style = plot.style_stepline ) //plot(close)
VOLLY PRICE CONVERGE
https://www.tradingview.com/script/dmQs0fRa-VOLLY-PRICE-CONVERGE/
Celar
https://www.tradingview.com/u/Celar/
9
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/ // © Celar //@version=5 strategy("VOLLY PRICE CONVERGE", default_qty_type= strategy.percent_of_equity ) base_sma = ta.sma(close, 10) vol_sma5 = ta.hma(volume, 15) price_sma5 = ta.hma(close, 15) ma50 = ta.sma(close, 50) ma20 = ta.sma(close, 20) int vol_indicator = na int price_indicator = na if vol_sma5 > vol_sma5[1] vol_indicator := 1 else vol_indicator := 0 if price_sma5 > price_sma5[1] price_indicator := 1 else price_indicator := 0 signal = vol_indicator + price_indicator colour = signal == 2 ? #00802b : signal == 1 ? #cc2900 : color.white bank_roll = strategy.equity qty = bank_roll/close strategy.entry("Long", strategy.long, qty, when = signal == 2 and close > base_sma) // Generate a full exit bracket (profit 10 points, loss 5 points per contract) from the entry named "Long". strategy.close("Long", when = signal == 1 or signal == 0 or close < base_sma )
Kahlman HullMA / WT Cross Strategy
https://www.tradingview.com/script/1Im3kKwi/
pigsq
https://www.tradingview.com/u/pigsq/
509
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/ // WT CROSS @author [LazyBear] // Kahlman HullMA / WT Cross Strategy ©author [pigsq] //@version=5 strategy("Kahlman HullMA / WT Cross Strategy", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=100) //Inputs _1 = input(false, '|| LONG TP SETTINGS ||') long = input(true, 'Long On') LongprofitPercent = input.float(10, "TP1 Profit Percent", minval = 0, maxval = 100, step = 5, tooltip="Percentage of balance to be taken for take profit 1-2.") LongprofitPercent2 = input.float(15, "TP2 Profit Percent", minval = 0, maxval = 100, step = 5, tooltip="Percentage of balance to be taken for take profit 1-2.") takeprofitLong = input.float(8.9, "Long Take Profit 1", minval = 0.1, step = 0.1, tooltip="Long take profit 1 percent setting")/100 var tp2L = "tp2L" takeprofit2Long = input.float(13.6, "Long Take Profit 2", minval = 0.1, step = 0.1, tooltip="Long take profit 2 percent setting. / Close TP2", inline=tp2L)/100 tp2OnOffL = input(true, 'On', inline=tp2L) var tp3L = "tp3L" takeprofit3Long = input.float(13.6, "Long Take Profit 3", minval = 0.1, step = 0.1, tooltip="Long take profit 3 percent setting. / Close TP3", inline=tp3L)/100 tp3OnOffL = input(false, 'On', inline=tp3L) src_long = input.string(title='Long TP1 Source', defval="hc2", options=["hc2", "co2", "hco3", "hlo3", "ho2", "lo2", "open", "close", "hlc3", "hl2", "ohlc4", "hlcc4", "low", "high"], tooltip="TP1 up or down control. Close process if selected 'source' is less than TP1") src_long2 = input.string(title='Long TP2 Source', defval="hc2", options=["hc2", "co2", "hco3", "hlo3", "ho2", "lo2", "open", "close", "hlc3", "hl2", "ohlc4", "hlcc4", "low", "high"], tooltip="TP2 up or down control. Close process if selected 'source' is less than TP2") _2 = input(false, '|| SHORT TP SETTINGS ||') short = input(true, 'Short On') ShortprofitPercent = input.float(50, "TP1 Profit Percent", minval = 0, maxval = 100, step = 5, tooltip="Percentage of balance to be taken for take profit 1-2.") ShortprofitPercent2 = input.float(70, "TP2 Profit Percent", minval = 0, maxval = 100, step = 5, tooltip="Percentage of balance to be taken for take profit 1-2.") takeprofitShort = input.float(8.2, "Short Take Profit 1", minval = 0.1, step = 0.1, tooltip="Short take profit 1 percent setting")/100 var tp2S = "tp2S" takeprofit2Short = input.float(13.4, "Short Take Profit 2", minval = 0.1, step = 0.1, tooltip="Short take profit 2 percent setting. / Close TP3", inline=tp2S)/100 tp2OnOffS = input(true, 'On', inline=tp2S) var tp3S = "tp3S" takeprofit3Short = input.float(13.9, "Short Take Profit 3", minval = 0.1, step = 0.1, tooltip="Short take profit 3 percent setting. / Close TP3", inline=tp3S)/100 tp3OnOffS = input(false, 'On', inline=tp3S) src_short = input.string(title='Short TP1 Source', defval="lc2", options=["lc2", "lco3", "hco3", "hc2", "co2", "hlo3", "lo2", "ho2", "close", "hlc3", "hl2", "ohlc4", "hlcc4", "low", "high", "open"], tooltip="TP1 up or down control. Close process if selected 'source' is greater than TP1") src_short2 = input.string(title='Short TP2 Source', defval="lco3", options=["lc2", "lco3", "hco3", "hc2", "co2", "hlo3", "lo2", "ho2", "close", "hlc3", "hl2", "ohlc4", "hlcc4", "low", "high", "open"], tooltip="TP2 up or down control. Close process if selected 'source' is greater than TP2") _3 = input(false, '|| STOP LOSS SETTINGS ||') stoplossLong = input.float(7.1, "Long", minval = 0.1, step = 0.1, tooltip="Stop loss percent(Red line)")/100 stoplossShort = input.float(7.9, "Short", minval = 0.1, step = 0.1)/100 _4 = input(false, '|| TRAILING STOP SETTINGS ||') trailingSLOnOff = input(true, 'Long Trailing SL On', tooltip="Trailing stop loss mode.") trailingStopChangeL = input(true, 'Change Line', tooltip="On: If price is greater than TP1. Off: If price is greater than Long Position Check.") trailingPercent = input.float(3.6, "Long", minval = 0.1, step = 0.1, tooltip="Trailing stop loss percent. Note: Activated if greater than TP1. Otherwise, the stop level is the value on a bottom line.(Yellow dot line)")/100 trailingSLOnOff2 = input(false, 'Short Trailing SL On', tooltip="Trailing stop loss mode.") trailingStopChangeS = input(true, 'Change Line', tooltip="On: If price is greater than TP1. Off: If price is greater than Short Position Check.") trailingPercent2 = input.float(3.4, "Short", minval = 0.1, step = 0.1, tooltip="Trailing stop loss percent. Note: Activated if greater than TP1. Otherwise, the stop level is the value on a bottom line.(Yellow dot line)")/100 _5 = input(false, '|| POSITION CHECK SETTINGS ||') LongpositionCheckOnOff = input(true, 'Long Position Check On', tooltip="Long Position check mode. Depends on TP1 percentage. It works as a '%X' / 'Senstive Value'.") src_LongpositionCheck = input.string(title='Source', defval="co2", options=["hco3", "lco3", "hc2", "lc2", "co2", "ho2", "lo2", "hlo3", "close", "open", "hl2", "hlc3", "ohlc4", "hlcc4", "low", "high"], tooltip="Long check senstive up or down control. Close process if selected 'source' is less than Position Check Line(Yellow solid line)") LongpositionCheck = input.float(1.7, "Senstive", minval = 1, step = 0.01) ShortpositionCheckOnOff = input(true, 'Short Position Check On', tooltip="Short Position check mode. It works as a '%X' / 'Senstive Value'.") src_ShortpositionCheck = input.string(title='Source', defval="low", options=["lco3", "hco3", "lc2", "hc2", "co2", "lo2", "ho2", "hlo3", "close", "open", "hl2", "hlc3", "ohlc4", "hlcc4", "low", "high"], tooltip="Short check senstive up or down control. Close process if selected 'source' is greater than Position Check Line(Yellow solid line)") ShortpositionCheck = input.float(1.4, "Senstive", minval = 1, step = 0.01) //Long TP1 source float source_long = switch src_long "hc2" => (high + close)/2 "hco3" => (high + close + open)/3 "co2" => (open + close)/2 "hlo3" => (open + high + low)/3 "ho2" => (open + high)/2 "lo2" => (low + open)/2 "lc2" => (low + close)/2 "lco3" => (low + close + open)/3 "open" => open "close" => close "hlc3" => hlc3 "hl2" => hl2 "ohlc4" => ohlc4 "hlcc4" => hlcc4 "low" => low "high" => high //Long TP2 source float source_long2 = switch src_long2 "hc2" => (high + close)/2 "hco3" => (high + close + open)/3 "co2" => (open + close)/2 "lc2" => (low + close)/2 "lco3" => (low + close + open)/3 "hlo3" => (open + high + low)/3 "lo2" => (open + low)/2 "ho2" => (high + open)/2 "open" => open "close" => close "hlc3" => hlc3 "hl2" => hl2 "ohlc4" => ohlc4 "hlcc4" => hlcc4 "low" => low "high" => high //Short TP1 source float source_short = switch src_short "lc2" => (low + close)/2 "lco3" => (low + close + open)/3 "co2" => (open + close)/2 "hlo3" => (open + high + low)/3 "lo2" => (open + low)/2 "ho2" => (high + open)/2 "hc2" => (high + close)/2 "hco3" => (high + close + open)/3 "close" => close "hlc3" => hlc3 "hl2" => hl2 "ohlc4" => ohlc4 "hlcc4" => hlcc4 "low" => low "high" => high "open" => open //Short TP2 source float source_short2 = switch src_short2 "lc2" => (low + close)/2 "lco3" => (low + close + open)/3 "co2" => (open + close)/2 "hlo3" => (open + high + low)/3 "lo2" => (open + low)/2 "ho2" => (high + open)/2 "hc2" => (high + close)/2 "hco3" => (high + close + open)/3 "close" => close "hlc3" => hlc3 "hl2" => hl2 "ohlc4" => ohlc4 "hlcc4" => hlcc4 "low" => low "high" => high "open" => open //Long position check source float source_CheckLong = switch src_LongpositionCheck "hco3" => (high + close + open)/3 "lco3" => (low + close + open)/3 "hc2" => (high + close)/2 "lc2" => (low + close)/2 "hlo3" => (open + high + low)/3 "co2" => (open + close)/2 "ho2" => (open + high)/2 "lo2" => (low + open)/2 "close" => close "hl2" => hl2 "hlc3" => hlc3 "ohlc4" => ohlc4 "hlcc4" => hlcc4 "low" => low "high" => high "open" => open //Short position check source float source_CheckShort = switch src_ShortpositionCheck "lco3" => (low + close + open)/3 "hco3" => (high + close + open)/3 "lc2" => (low + close)/2 "hc2" => (high + close)/2 "hlo3" => (open + high + low)/3 "co2" => (open + close)/2 "lo2" => (open + low)/2 "ho2" => (high + open)/2 "close" => close "hl2" => hl2 "hlc3" => hlc3 "ohlc4" => ohlc4 "hlcc4" => hlcc4 "high" => high "open" => open "low" => low // WT Cross Setup _6 = input(false, '|| WT CROSS SETTINGS ||') var wtlong = "WT LONG" n1L = input(6, 'Channel Length') n2L = input(23, 'Average Length') apL = input.string(title='Source', defval='hlc3', options=["hc2", "hco3", "lc2", "lco3", "co2", "hlo3", "lo2", "close", "hlc3", "hl2", "ohlc4", "hlcc4", "low", "high", "open"]) float apL_src = switch apL "hc2" => (high + close)/2 "hco3" => (high + close + open)/3 "lc2" => (low + close)/2 "lco3" => (low + close + open)/3 "co2" => (open + close)/2 "hlo3" => (open + high + low)/3 "lo2" => (open + low)/2 "close" => close "hlc3" => hlc3 "hl2" => hl2 "ohlc4" => ohlc4 "hlcc4" => hlcc4 "low" => low "high" => high "open" => open esaL = ta.ema(apL_src, n1L) rL = ta.ema(math.abs(apL_src - esaL), n1L) ciL = (apL_src - esaL) / (0.015 * rL) tciL = ta.ema(ciL, n2L) wt1L = tciL wt2L = ta.sma(wt1L, 4) // WT SHORT var wtshort = "WT SHORT" n1S = input(8, 'Channel Length') n2S = input(19, 'Average Length') apS = input.string(title='Source', defval='hlc3', options=["hc2", "hco3", "lc2", "lco3", "co2", "hlo3", "lo2", "close", "hlc3", "hl2", "ohlc4", "hlcc4", "low", "high", "open"]) float apS_src = switch apS "hc2" => (high + close)/2 "hco3" => (high + close + open)/3 "lc2" => (low + close)/2 "lco3" => (low + close + open)/3 "co2" => (open + close)/2 "hlo3" => (open + high + low)/3 "lo2" => (open + low)/2 "close" => close "hlc3" => hlc3 "hl2" => hl2 "ohlc4" => ohlc4 "hlcc4" => hlcc4 "low" => low "high" => high "open" => open esaS = ta.ema(apS_src, n1S) rS = ta.ema(math.abs(apS_src - esaS), n1S) ciS = (apS_src - esaS) / (0.015 * rS) tciS = ta.ema(ciS, n2S) wt1S = tciS wt2S = ta.sma(wt1S, 4) // Hull Kahlman Setup _7 = input(false, '|| HULLMA SETTINGS ||') hull_source = input.string(title='Source', defval='hl2', options=["hc2", "hco3", "lc2", "lco3", "co2", "hlo3", "lo2", "close", "hlc3", "hl2", "ohlc4", "hlcc4", "low", "high", "open"]) lengthhull = input(24, 'Lookback') gain = input(10000, 'Gain') float hull_src = switch hull_source "hc2" => (high + close)/2 "hco3" => (high + close + open)/3 "lc2" => (low + close)/2 "lco3" => (low + close + open)/3 "co2" => (open + close)/2 "hlo3" => (open + high + low)/3 "lo2" => (open + low)/2 "close" => close "hlc3" => hlc3 "hl2" => hl2 "ohlc4" => ohlc4 "hlcc4" => hlcc4 "low" => low "high" => high "open" => open hma(_hull_src, _lengthhull) => ta.wma((2 * ta.wma(_hull_src, _lengthhull / 2)) - ta.wma(_hull_src, _lengthhull), math.round(math.sqrt(_lengthhull))) hma3(_hull_src, _lengthhull) => p = lengthhull / 2 ta.wma(ta.wma(close, p / 3) * 3 - ta.wma(close, p / 2) - ta.wma(close, p), p) kahlman(x, g) => kf = 0.0 dk = x - nz(kf[1], x) smooth = nz(kf[1], x) + dk * math.sqrt(g / 10000 * 2) velo = 0.0 velo := nz(velo[1], 0) + g / 10000 * dk kf := smooth + velo kf a = kahlman(hma(hull_src, lengthhull), gain) b = kahlman(hma3(hull_src, lengthhull), gain) c = b > a ? color.lime : color.red crossdn = a > b and a[1] < b[1] crossup = b > a and b[1] < a[1] p1hma = plot(a, color=color.new(c, 75), linewidth=1, title='Long Plot') p2hma = plot(b, color=color.new(c, 75), linewidth=1, title='Short Plot') fill(p1hma, p2hma, color=color.new(c, 75), title='Fill') //Stoch RSI Settings _8 = input(false, '|| STOCH RSI SETTINGS ||') rsistochOnOff = input(true, 'Stoch RSI', tooltip="Stoch RSI On/Off") smoothK = input.int(2, "K", minval=1) smoothD = input.int(3, "D", minval=1) lengthRSI = input.int(13, "RSI Length", minval=1) lengthStoch = input.int(13, "Stochastic Length", minval=1) src = input.string(title='RSI Source', defval='hl2', options=["hc2", "hco3", "lc2", "lco3", "co2", "hlo3", "lo2", "close", "hlc3", "hl2", "ohlc4", "hlcc4", "low", "high", "open"]) float src_src = switch src "hc2" => (high + close)/2 "hco3" => (high + close + open)/3 "lc2" => (low + close)/2 "lco3" => (low + close + open)/3 "co2" => (open + close)/2 "hlo3" => (open + high + low)/3 "lo2" => (open + low)/2 "close" => close "hlc3" => hlc3 "hl2" => hl2 "ohlc4" => ohlc4 "hlcc4" => hlcc4 "low" => low "high" => high "open" => open rsi1 = ta.rsi(src_src, lengthRSI) k = ta.sma(ta.stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK) d = ta.sma(k, smoothD) LStoch = rsistochOnOff ? k > d:close SStoch = rsistochOnOff ? k < d:close //Vol Setup _15 = input(false, '|| VOLUME SETTINGS ||') volumeonoff = input(true, 'On/Off') volume_f = input.float(0.6, title="Mult.", minval = 0, step = 0.1) sma_length = input.int(3, title="Sma volume lenght", minval = 1) vwma_length = input.int(3, title="Vwma volume lenght", minval = 1) wma_length = input.int(4, title="Wma volume lenght", minval = 1) vol = ((ta.sma(volume, sma_length) + ta.vwma(volume, vwma_length) + ta.wma(volume, wma_length)) / 3) * volume_f volEntry = volumeonoff ? volume > vol:volume _16 = input(false, '|| ADX SETTINGS ||') adxon = input(false, 'On') adxlen = input(14, title="ADX Smoothing") dilen = input(14, title="DI Length") adxBuyLevel = input(20, title="Buy Level") 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) ADXEntry = if adxon sig > adxBuyLevel else sig < 100 // Wunderbit Settings _9 = input(false, '|| WUNDERBIT SETTINGS ||') var wunder = "Wunderbit Comments" longentryComment = input("ENTER-LONG", title = "Long Entry Comment", group=wunder) longexitComment = input("EXIT-LONG", title = "Long Exit Comment", group=wunder) shortentryComment = input("ENTER-SHORT", title = "Short Entry Comment", group=wunder) shortexitComment = input("EXIT-SHORT", title = "Short Exit Comment", group=wunder) // Date Setup _10 = input(false, '|| DATE & DATE RANGE SETTINGS ||') startDate = input.time(timestamp("1 Jan 2020 00:00 +0000"), "Start Date") endDate = input.time(timestamp("1 Jan 9999 03:00 +0000"), "End Date") var rangeL = "LONG" sessionOnOff = input(true, 'Long/Time Range & Weekdays On/Off', tooltip="Start Date and End Date not inclueded", group=rangeL) timeSession = input.session("0000-0000", 'Time Range', group=rangeL) d_monday = input.bool(title="Monday", defval=true, inline="D1", group=rangeL) d_tuesday = input.bool(title="Tuesday", defval=true, inline="D1", group=rangeL) d_wednesday = input.bool(title="Wednesday", defval=true, inline="D1", group=rangeL) d_thursday = input.bool(title="Thursday", defval=true, inline="D2", group=rangeL) d_friday = input.bool(title="Friday", defval=true, inline="D2", group=rangeL) d_saturday = input.bool(title="Saturday", defval=false, inline="D2", group=rangeL) d_sunday = input.bool(title="Sunday", defval=true, tooltip="Trade days?", inline="D2", group=rangeL) days = d_sunday ? "1" : "" days := days + (d_monday ? "2" : "") days := days + (d_tuesday ? "3" : "") days := days + (d_wednesday ? "4" : "") days := days + (d_thursday ? "5" : "") days := days + (d_friday ? "6" : "") days := days + (d_saturday ? "7" : "") strategyTime = time >= startDate and time <= endDate ? true : false inSession(session) => if sessionOnOff na(time(timeframe.period, session + ":" + days)) == false and strategyTime else strategyTime // For Short var rangeS = "SHORT" sessionOnOff2 = input(false, 'Short/Time Range & Weekdays On/Off', tooltip="Start Date and End Date not inclueded", group=rangeS) timeSession2 = input.session("0300-0300", 'Time Range', group=rangeS) d_monday2 = input.bool(title="Monday", defval=true, inline="D3", group=rangeS) d_tuesday2 = input.bool(title="Tuesday", defval=true, inline="D3", group=rangeS) d_wednesday2 = input.bool(title="Wednesday", defval=true, inline="D3", group=rangeS) d_thursday2 = input.bool(title="Thursday", defval=true, inline="D4", group=rangeS) d_friday2 = input.bool(title="Friday", defval=true, inline="D4", group=rangeS) d_saturday2 = input.bool(title="Saturday", defval=true, inline="D4", group=rangeS) d_sunday2 = input.bool(title="Sunday", defval=true, tooltip="Trade days?", inline="D4", group=rangeS) days2 = d_sunday2 ? "1" : "" days2 := days2 + (d_monday2 ? "2" : "") days2 := days2 + (d_tuesday2 ? "3" : "") days2 := days2 + (d_wednesday2 ? "4" : "") days2 := days2 + (d_thursday2 ? "5" : "") days2 := days2 + (d_friday2 ? "6" : "") days2 := days2 + (d_saturday2 ? "7" : "") inSession2(session2) => if sessionOnOff2 na(time(timeframe.period, session2 + ":" + days2)) == false and time >= startDate and time <= endDate else time >= startDate and time <= endDate ? true : false // SL-TP Setups longConditionDirection = strategy.position_size >= 0 shortConditionDirection = strategy.position_size <= 0 // Long Line Setup exitSL = if longConditionDirection strategy.position_avg_price * (1 - stoplossLong) else strategy.position_avg_price * (1 + stoplossShort) exitTP = if longConditionDirection strategy.position_avg_price * (1 + takeprofitLong) else strategy.position_avg_price * (1 - takeprofitShort) exitTP2 = if longConditionDirection strategy.position_avg_price * (1 + takeprofit2Long) else strategy.position_avg_price * (1 - takeprofit2Short) exitTP3 = if longConditionDirection strategy.position_avg_price * (1 + takeprofit3Long) else strategy.position_avg_price * (1 - takeprofit3Short) positionCheckLong = if LongpositionCheckOnOff longConditionDirection ? strategy.position_avg_price * (1 + takeprofitLong/LongpositionCheck):na positionCheckShort = if ShortpositionCheckOnOff shortConditionDirection ? strategy.position_avg_price * (1 - takeprofitShort/ShortpositionCheck):na // Long-Short Condition Setup longCondition = crossup and ta.crossover(wt1L,wt2L) and LStoch or crossup and ta.crossover(wt1L[1],wt2L[1]) and LStoch or crossup and ta.crossover(wt1L[2],wt2L) and LStoch shortCondition = crossdn and ta.crossunder(wt1S,wt2S) and SStoch // Trailing Long Stop Setup trailingStopChangeL1 = trailingStopChangeL ? high >= exitTP or high[1] >= exitTP: high >= positionCheckLong or high[1] >= positionCheckLong priceStopL = 0.0 priceStopL := if longConditionDirection and trailingStopChangeL1 and trailingSLOnOff stopMeasure = close * (1 - trailingPercent) math.max(stopMeasure, priceStopL[1]) else if longConditionDirection exitSL // Trailing Short Stop Setup trailingStopChangeS1 = trailingStopChangeS ? low <= exitTP or low[1] <= exitTP: low <= positionCheckShort or low[1] <= positionCheckShort priceStopS = 0.0 priceStopS := if shortConditionDirection and trailingStopChangeS1 and trailingSLOnOff2 stopMeasure = close * (1 + trailingPercent2) math.min(stopMeasure, priceStopS[1]) else if shortConditionDirection exitSL // Position Check Control positionCheckLong2 = high >= positionCheckLong and ta.crossunder(wt1L,wt2L) and source_CheckLong < positionCheckLong or high >= positionCheckLong and ta.crossunder(wt1S,wt2S) and source_CheckLong < positionCheckLong or high >= positionCheckLong and a > b and source_CheckLong < positionCheckLong and wt1L < wt2L and not volEntry or high >= positionCheckLong and a > b and source_CheckLong < positionCheckLong and wt1S < wt2S and not volEntry or high >= positionCheckLong and crossdn and source_CheckLong < positionCheckLong positionCheckShort2 = low <= positionCheckShort and ta.crossover(wt1S,wt2S) and source_CheckShort > positionCheckShort or low <= positionCheckShort and ta.crossover(wt1L,wt2L) and source_CheckShort > positionCheckShort or low <= positionCheckShort and a < b and source_CheckShort > positionCheckShort and wt1S > wt2S and not volEntry or low <= positionCheckShort and a < b and source_CheckShort > positionCheckShort and wt1L > wt2L and not volEntry or low <= positionCheckShort and crossup and source_CheckShort > positionCheckShort // TP's Control longTStop = high >= exitTP and source_long <= exitTP or high >= exitTP2 and source_long2 <= exitTP2 or high >= exitTP2 and a > b shortTStop = low <= exitTP and source_short >= exitTP or low <= exitTP2 and source_short2 >= exitTP2 or low <= exitTP2 and a < b // Long-Short Condition Close longConditionExit = if high <= strategy.position_avg_price or high >= positionCheckLong shortCondition or positionCheckLong2 shortConditionExit = if low >= strategy.position_avg_price or low <= positionCheckShort longCondition or positionCheckShort2 if strategyTime if longConditionDirection and longCondition and long and volEntry and ADXEntry if inSession(sessionOnOff ? timeSession:na) strategy.entry("LONG", strategy.long, comment=longentryComment) strategy.exit("LONG", stop=priceStopL, qty_percent=tp2OnOffL ? LongprofitPercent:100, limit=exitTP, comment=longexitComment) if tp2OnOffL strategy.exit("LONG1", stop=priceStopL, qty_percent=tp3OnOffL ? LongprofitPercent2:100, limit=exitTP2, comment=longexitComment) if tp3OnOffL strategy.exit("LONG2", stop=priceStopL, qty_percent=100, limit=exitTP3, comment=longexitComment) if longConditionExit or longTStop strategy.close("LONG", comment=longexitComment) if shortConditionDirection and shortCondition and short and volEntry and ADXEntry if inSession2(sessionOnOff2 ? timeSession2:na) strategy.entry("SHORT", strategy.short, comment=shortentryComment) strategy.exit("SHORT", stop=priceStopS, qty_percent=tp2OnOffS ? ShortprofitPercent:100, limit=exitTP, comment=shortexitComment) if tp2OnOffS strategy.exit("SHORT1", stop=priceStopS, qty_percent=tp3OnOffS ? ShortprofitPercent2:100, limit=exitTP2, comment=shortexitComment) if tp3OnOffS strategy.exit("SHORT2", stop=priceStopS, qty_percent=100, limit=exitTP3, comment=shortexitComment) if shortConditionExit or shortTStop strategy.close("SHORT", comment=shortexitComment) // SL-TP Lines LSTP2Lines = longConditionDirection ? tp2OnOffL ? exitTP2:na:shortConditionDirection ? tp2OnOffS ? exitTP2:na:na LSTP3Lines = longConditionDirection ? tp3OnOffL ? tp2OnOffL ? exitTP3:na:na:shortConditionDirection ? tp3OnOffS ? tp2OnOffS ? exitTP3:na:na:na plot(exitTP, title='Long/Short TP1', color=color.lime, style=plot.style_linebr, linewidth=1) plot(LSTP2Lines, title='Long/Short TP2', color=color.lime, style=plot.style_linebr, linewidth=1) plot(LSTP3Lines, title='Long/Short TP3', color=color.lime, style=plot.style_linebr, linewidth=1) // L/S Stop Loss Lines plot(exitSL, title='Long/Short SL', color=color.red, style=plot.style_linebr, linewidth=1) // Position Check Lines PositionCheckColors = LongpositionCheckOnOff and positionCheckLong ? color.yellow : ShortpositionCheckOnOff and positionCheckShort ? color.yellow:na PositionCheckLines = LongpositionCheckOnOff and longConditionDirection ? positionCheckLong : ShortpositionCheckOnOff and shortConditionDirection ? positionCheckShort:na plot(PositionCheckLines, title='Long/Short Position Check', color=PositionCheckColors, style=plot.style_linebr, linewidth=1) // Trailing Stop Lines TrailingStopLines = trailingSLOnOff ? longConditionDirection and trailingStopChangeL1 ? priceStopL:na:na TrailingStopLines2 = trailingSLOnOff2 ? shortConditionDirection and trailingStopChangeS1 ? priceStopS:na:na plot(TrailingStopLines, title='Long Trailing Stop', color=color.yellow, style=plot.style_circles, linewidth=1) plot(TrailingStopLines2, title='Short Trailing Stop', color=color.yellow, style=plot.style_circles, linewidth=1) // Date Range Background Color // bgcolor(sessionOnOff ? inSession(timeSession) ? color.rgb(91, 255, 0, 95):na:na, title="Long Time Range Bg Color") // bgcolor(sessionOnOff2 ? inSession2(timeSession2) ? color.rgb(91, 255, 0, 95):na:na, title="Short Time Range Bg Color")
Golden Swing Strategy - Souradeep Dey
https://www.tradingview.com/script/23YZfW0R-Golden-Swing-Strategy-Souradeep-Dey/
rajm14
https://www.tradingview.com/u/rajm14/
46
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © rajm14 //@version=5 strategy(title = "Golden Swing Strategy - Souradeep Dey", shorttitle = "GSS", overlay = true, process_orders_on_close = true, default_qty_type = strategy.cash, default_qty_value=100000, currency = currency.USD) // Indicator - RSI - 20 rsiSrc = input(defval = close, title = "RSI Source") rsiLen = input.int(defval = 20, title = "RSI Length", minval = 0, maxval = 200, step = 1) rsi = ta.rsi(rsiSrc, rsiLen) //plot(rsi) // Indicator - Stochastic (55,34,21) kLength = input.int(defval = 55, title="Stoch %K Length", minval=1) kSmooth = input.int(defval = 34, title="Stoch %K Smoothing", minval=1) dLength = input.int(defval = 21, title="Stoch %D Smoothing", minval=1) kLine = ta.sma(ta.stoch(close, high, low, kLength), kSmooth) dLine = ta.sma(kLine, dLength) // plot(kLine, color=color.red) // plot(dLine, color=color.green) // Indicator - ATR(5) atrLength = input(5, "ATR Length") atr = ta.atr(5) // plot(atr) // Indicator - SuperTrend(10,2) atrPeriod = input(10, "SuperTrend ATR Length") stSrc = hl2 stfactor = input.float(2.0, "SuperTrend Multiplier", step = 0.1) stAtr = ta.atr(atrPeriod) [supertrend, direction] = ta.supertrend(stfactor, atrPeriod) bodyMiddle = (open + close) / 2 upTrend = direction < 0 ? supertrend : na downTrend = direction < 0? na : supertrend // plot(bodyMiddle, display=display.none) // plot(upTrend) // plot(downTrend) // Indicator - Bollinger Bands (20,2) bblength = input.int(defval = 20, title = "BB Length") bbsource = input(defval = close, title = "BB Source") bbStdDev = input.float(defval = 2.0, title = "BB Std Dev", step = 0.1) bbmultiplier = bbStdDev * ta.stdev(bbsource, bblength) bbMband = ta.sma(bbsource, bblength) bbUband = bbMband + bbmultiplier bbLband = bbMband - bbmultiplier // plot (bbUband, color = color.red, linewidth = 2) // plot (bbMband, color = color.black, linewidth = 2) // plot (bbLband, color = color.green, linewidth = 2) // Trade Entry LongEntry = rsi >= 50 and kLine > dLine and low < supertrend and direction < 0 and supertrend < bbMband ShortEntry = rsi <= 50 and kLine < dLine and high > supertrend and direction > 0 and supertrend > bbMband plotshape(LongEntry, style = shape.triangleup, text = "Long", location = location.belowbar, size = size.large, color = color.green) plotshape(ShortEntry, style = shape.triangledown, text = "Short", location = location.abovebar, size = size.large, color = color.red) //Trade execution if LongEntry strategy.entry(id = "Buy", direction = strategy.long, limit = close * .5 * atr) closelong = close >= strategy.position_avg_price * 2.2 * atr stoplong = close <= strategy.position_avg_price * 1.1 * atr if closelong strategy.close(id = "Buy") if stoplong strategy.close(id = "Buy") if ShortEntry strategy.entry(id = "Sell", direction = strategy.long, limit = close * .5 * atr) closeshort = close <= strategy.position_avg_price * 2.2 * atr stopshort = close >= strategy.position_avg_price * 1.1 * atr if closeshort strategy.close(id = "Sell") if stopshort strategy.close(id = "Sell")
Madri
https://www.tradingview.com/script/vwazHzfd/
Mdemoio
https://www.tradingview.com/u/Mdemoio/
71
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/ // © Mdemoio //@version=4 strategy("Madri", shorttitle="Madri", overlay=true) // Version 1.1 ///////////// RSI RSIlength = input(2,title="A") RSIoverSold = 45 RSIoverBought = 40 price = close vrsi = rsi(price, RSIlength) ///////////// Bollinger Bands BBlength = input(150, minval=1,title="B") BBmult = 2// input(2.0, minval=0.001, maxval=50,title="Bollinger Bands Standard Deviation") BBbasis = sma(price, BBlength) BBdev = BBmult * stdev(price, BBlength) BBupper = BBbasis + BBdev BBlower = BBbasis - BBdev source = close buyEntry = crossover(source, BBlower) sellEntry = crossunder(source, BBupper) ///////////// Colors //switch1=input(true, title="Enable Bar Color?") //switch2=input(true, title="Enable Background Color?") //TrendColor = RSIoverBought and (price[1] > BBupper and price < BBupper) and BBbasis < BBbasis[1] ? red : RSIoverSold and (price[1] < BBlower and price > BBlower) and BBbasis > BBbasis[1] ? green : na //barcolor(switch1?TrendColor:na) //bgcolor(switch2?TrendColor:na,transp=50) ///////////// RSI + Bollinger Bands Strategy if (not na(vrsi)) if (crossover(vrsi, RSIoverSold) and crossover(source, BBlower)) strategy.entry("RSI_BB_L", strategy.long, stop=BBlower, oca_type=strategy.oca.cancel, comment="Buy") else strategy.cancel(id="RSI_BB_L") if (crossunder(vrsi, RSIoverBought) and crossunder(source, BBupper)) strategy.entry("RSI_BB_S", strategy.short, stop=BBupper, oca_type=strategy.oca.cancel, comment="Sell") else strategy.cancel(id="RSI_BB_S") //plot(strategy.equity, title="equity", color=red, linewidth=2, style=areabr)
The strategy example. Close position by timeout
https://www.tradingview.com/script/Tqq1lFCS-The-strategy-example-Close-position-by-timeout/
adolgov
https://www.tradingview.com/u/adolgov/
132
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/ // © adolgov //@version=5 strategy("The strategy example. Close position by timeout", overlay=true, margin_long=100, margin_short=100, process_orders_on_close=true) longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28)) if (longCondition) strategy.entry("My Long Entry Id", strategy.long) shortCondition = ta.crossunder(ta.sma(close, 14), ta.sma(close, 28)) if (shortCondition) strategy.entry("My Short Entry Id", strategy.short) closePositionAfter(timeoutS)=> if strategy.opentrades > 0 for i = 0 to strategy.opentrades-1 if time - strategy.opentrades.entry_time(i) >= timeoutS*1000 entry = strategy.opentrades.entry_id(i) strategy.close(entry, comment = str.format("Close \"{0}\" by timeout {1}s", entry, timeoutS)) closePositionAfter(120) // close position after 120 sec
SIMPLE CANDLESTICK PATTERN ALGO BACKTESTING - TESLA 4H
https://www.tradingview.com/script/XT7qjACu-SIMPLE-CANDLESTICK-PATTERN-ALGO-BACKTESTING-TESLA-4H/
thequantscience
https://www.tradingview.com/u/thequantscience/
220
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © TheQuantScience //@version=5 strategy("SimpleBarPattern_LongOnly", overlay=true, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, currency = currency.EUR, initial_capital = 1000, commission_type = strategy.commission.percent, commission_value = 0.03) // Make input options that configure backtest date range startDate = input.int(title="Start Date", defval=1, minval=1, maxval=31) startMonth = input.int(title="Start Month", defval=1, minval=1, maxval=12) startYear = input.int(title="Start Year", defval=2017, minval=1800, maxval=2100) endDate = input.int(title="End Date", defval=8, minval=1, maxval=31) endMonth = input.int(title="End Month", defval=3, minval=1, maxval=12) endYear = input.int(title="End Year", defval=2022, minval=1800, maxval=2100) // 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)) // Setting Conditions ConditionA = low < open ConditionB = low < low[1] ConditionC = close > open ConditionD = close > open[1] and close > close[1] FirstCondition = ConditionA and ConditionB SecondCondition = ConditionC and ConditionD IsLong = FirstCondition and SecondCondition TakeProfit_long = input(4.00) StopLoss_long = input(4.00) Profit = TakeProfit_long*close/100/syminfo.mintick Loss = StopLoss_long*close/100/syminfo.mintick EntryCondition = IsLong and inDateRange // Trade Entry&Exit Condition if EntryCondition and strategy.opentrades == 0 strategy.entry(id = 'Open_Long', direction = strategy.long) strategy.exit(id = "Close_Long", from_entry = 'Open_Long', profit = Profit, loss = Loss)
EDMA Scalping Strategy (Exponentially Deviating Moving Average)
https://www.tradingview.com/script/CJesxF5m-EDMA-Scalping-Strategy-Exponentially-Deviating-Moving-Average/
MightyZinger
https://www.tradingview.com/u/MightyZinger/
1,589
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/ // © MightyZinger //@version=5 strategy('EDMA Scalping Strategy (Exponentially Deviating Moving Average)', shorttitle='MZ EDMA Strategy', overlay=true, initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=5, calc_on_every_tick=false, commission_type=strategy.commission.percent, commission_value=0.1) import MightyZinger/Chikou/3 as filter ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// ///// Source Options ////// ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// // ─── Different Sources Options List ───► [ string SRC_Tv = 'Use traditional TradingView Sources ' string SRC_Wc = '(open+close+3(high+low))/8' string SRC_Wo = 'close+high+low-2*open' string SRC_Wu = '(close+5(high+low)-7(open))/4' string SRC_Wi = '(open+close+5(high+low))/12' string SRC_Exi = 'close>open ? high : low' string SRC_Exj = 'Heiken-ashi(close>open) ? high : low' string src_grp = 'Source Parameters' // ●───────── Inputs ─────────● { diff_src = input.string(SRC_Exi, '→ Different Sources Options', options=[SRC_Tv, SRC_Wc, SRC_Wo, SRC_Wu, SRC_Wi, SRC_Exi, SRC_Exj], group=src_grp) i_sourceSetup = input.source(close, 'Tradingview Source Setup', group=src_grp) i_Sym = input.bool(true, 'Apply Symmetrically Weighted Moving Average at the price source (May Result Repainting)', group=src_grp) // Heikinashi Candles for calculations f_ha_open() => haopen = float(na) haopen := na(haopen[1]) ? (open + close) / 2 : (nz(haopen[1]) + nz(ohlc4[1])) / 2 haopen h_open = f_ha_open() // Get Source src_o = diff_src == SRC_Wc ? (open+close+3*(high+low))/8 : diff_src == SRC_Wo ? close+high+low-2*open : diff_src == SRC_Wu ? (close+5*(high+low)-7*(open))/4 : diff_src == SRC_Wi ? (open+close+5*(high+low))/12 : diff_src == SRC_Exi ? (close > open ? high : low) : diff_src == SRC_Exj ? (ohlc4 > h_open ? high : low) : i_sourceSetup src_f = i_Sym ? ta.swma(src_o) : src_o // Symmetrically Weighted Moving Average? ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// string grp1 = 'MA Parameters' edma_Length = input.int(20, title='MA Length:', group=grp1) i_Symmetrical = input(true, '‍ Apply Symmetrically Weighted Moving Average at EDMA') ema1_Length = input.int(20, title='EMA 1 Length:', group=grp1) show_ema1 = input(true, '‍ Show EMA 1') ema2_Length = input.int(40, title='EMA 2 Length:', group=grp1) show_ema2 = input(false, '‍ Show EMA 2') string grp2 = 'Chikou Filter Parameters' c_len = input.int(25, title='Chikou Period (Displaced Source)', group=grp2) c_bull_col = input.color(color.green, 'Bull Color  ', group = grp2, inline='c_col') c_bear_col = input.color(color.red, 'Bear Color  ', group = grp2, inline='c_col') c_rvsl_col = input.color(color.yellow, 'Consollidation/Reversal Color  ', group = grp2, inline='c_col') string grp3 = 'EMA Color Settings' ema1_col = input.color(#2962FF, 'EMA 1 Color  ', group = grp3, inline='e_col') ema2_col = input.color(#FF6D00, 'EMA 2 Color  ', group = grp3, inline='e_col') string grp4 = 'ETrade Parameters' showSignals = input.bool(true, title='Show Cross Alerts', group=grp4) conf_chk = input.bool(false, title='Use Chikou Filter for Confirmation', group=grp4) ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// // EDMA Function f_edma(src, len)=> var hexp = float(na) // Initiallizing Variables var lexp = float(na) var _hma = float(na) var _edma = float(na) float smoothness = 1.0 // Increasing smoothness will result in MA same as EMA h_len = int(len/1.5) // Length to be used in final calculation of Hull Moving Average // Defining Exponentially Expanding Moving Line hexp := na(hexp[1]) ? src : src >= hexp[1] ? src : hexp[1] + (src - hexp[1]) * (smoothness / (len + 1)) // Defining Exponentially Contracting Moving Line lexp := na(lexp[1]) ? hexp : src <= lexp[1] ? hexp : lexp[1] + (src - lexp[1]) * (smoothness / (len + 1)) // Calculating Hull Moving Average of resulted Exponential Moving Line with 3/2 of total length _hma := ta.wma(2 * ta.wma(lexp, h_len / 2) - ta.wma(lexp, h_len), math.round(math.sqrt(h_len))) _edma := _hma // EDMA will be equal to resulted smoothened Hull Moving Average _edma ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// edma = i_Symmetrical ? ta.swma(f_edma(src_f, edma_Length)) : f_edma(src_f, edma_Length) ema1 = ta.ema(src_f, ema1_Length) ema2 = ta.ema(src_f, ema2_Length) // Calling Chikou filter function from library to obtaing dynamic color of EDMA Band and also Chikou Trend [edma_col, _trend] = filter.chikou(src_f, c_len, high, low, c_bull_col, c_bear_col, c_rvsl_col) edma_plot = plot(edma, title='EDMA', color= edma_col , linewidth=4) // Plotting EDMA with dynamic color from Chikou Filter Function ema1_plot = plot(show_ema1 ? ema1 : na, title='EMA 1', color= ema1_col , linewidth=3) ema2_plot = plot(show_ema2 ? ema2 : na, title='EMA 2', color= ema2_col , linewidth=3) fill(ema1_plot , edma_plot, title = "Background", color = color.new(edma_col,70)) // Filling the bands inbetween EMA and EDMA ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// // Trade Signals and Alerts L1 = ema2 > edma // Weak Uptrend Condition L2 = ema1 > edma // Strong Uptrend Condition L3 = _trend == 1 // Chikou Filter Uptrend Condition S1 = ema2 < edma // Weak Downtrend Condition S2 = ema1 < edma // Strong Downtrend Condition S3 = _trend == -1 // Chikou Filter Downtrend Condition // Setting confirmation conditional operator for Chikou Filter weak_up = conf_chk ? L1 and L3 : L1 strong_up = conf_chk ? L2 and L3 : L2 weak_dn = conf_chk ? S1 and S3 : S1 strong_dn = conf_chk ? S2 and S3 : S2 // Defining condition equivalent to Crossover & Crossunder bool[] signal_a = array.from(weak_up, strong_up, weak_dn, strong_dn) var swing_a = array.new_int(2) f_signal()=> for i = 0 to 1 var sig = 0 if array.get(signal_a, i) and sig <= 0 sig := 1 if array.get(signal_a, i+2) and sig >= 0 sig := -1 array.set(swing_a, i, sig) f_signal() buy_weak = array.get(swing_a, 0) == 1 and array.get(swing_a, 0)[1] != 1 buy_strong = array.get(swing_a, 1) == 1 and array.get(swing_a, 1)[1] != 1 sell_weak = array.get(swing_a, 0) == -1 and array.get(swing_a, 0)[1] != -1 sell_strong = array.get(swing_a, 1) == -1 and array.get(swing_a, 1)[1] != -1 // Plotting Signals on Chart //atrOver = 0.7 * ta.atr(5) // Atr to place alert shape on chart //plotshape(showSignals and buy_strong ? (low - atrOver) : na, style=shape.triangleup, color=color.new(color.green, 30), location=location.absolute, text='Buy', size=size.small) //plotshape(showSignals and sell_strong ? (high + atrOver) : na, style=shape.triangledown, color=color.new(color.red, 30), location=location.absolute, text='Sell', size=size.small) strategy.close('sell', when = buy_strong) strategy.entry("buy", strategy.long, when = buy_strong) strategy.close('buy', when = sell_strong) strategy.entry("sell", strategy.short, when = sell_strong)
PCT Trailing Stoploss-Strategy
https://www.tradingview.com/script/VMKVjZNl-PCT-Trailing-Stoploss-Strategy/
Thumpyr
https://www.tradingview.com/u/Thumpyr/
44
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/ // © Thumpyr //@version=5 ///////////////////////////////////////////////////////////////////////////////////////////// // Comment out Strategy Line and remove // from Indicator line to turn into Indicator ////// // Do same for alertConidction at bottom ////// ///////////////////////////////////////////////////////////////////////////////////////////// strategy("PCT Trailing Stoploss-Strategy", shorttitle="PCT Trailing Stoploss- Strategy", overlay=true, margin_long=100, margin_short=100) //indicator(title="PCT Trailing Stoploss- Indicator", shorttitle="PCT Trailing Stoploss - Indicator", timeframe="", timeframe_gaps=true, overlay=true)// sellLow=input.float(.035, minval=0, title="Stop Loss Loss: 1% = .01", group="Sell Settings") trailStopArm=input.float(.0065, minval=0, title="Trailing Stop Arm: 1%=.01", group="Sell Settings") trailStopPct=input.float(.003, minval=0, title="Trailing Stop Trigger: 1%=.01 ", group="Sell Settings") ///////////////////////////////////////////////// // Indicators // ///////////////////////////////////////////////// ema1Len = input.int(14, minval=1, title=" ema 1 Length", group="Trend Line Settings") ema1Src = input(close, title="ema 1 Source", group="Trend Line Settings") ema1 = ta.ema(ema1Src, ema1Len) plot(ema1, title="EMA", color=color.blue) ema2Len = input.int(22, minval=1, title=" ema 2 Length", group="Trend Line Settings") ema2Src = input(close, title="ema 2 Source", group="Trend Line Settings") ema2 = ta.ema(ema2Src, ema2Len) plot(ema2, title="EMA", color=color.orange) ema3Len = input.int(200, minval=1, title=" ema 3 Length", group="Trend Line Settings") ema3Src = input(close, title="ema 2 Source", group="Trend Line Settings") ema3 = ta.ema(ema3Src, ema3Len) plot(ema3, title="EMA", color=color.gray) ///////////////////////////// //// Buy Conditions //// ///////////////////////////// alertBuy = ta.crossover(ema1,ema2) and close>ema3 //////////////////////////////////////////////////////////////////// //// Filter redundant Buy Signals if Sell has not happened //// //////////////////////////////////////////////////////////////////// var lastsignal = 0 showAlertBuy = 0 if(alertBuy and lastsignal !=1) showAlertBuy := 1 lastsignal := 1 buyAlert= showAlertBuy > 0 ////////////////////////////////////////////////////////////////// //// Track Conditions at buy Signal //// ////////////////////////////////////////////////////////////////// alertBuyValue = ta.valuewhen(buyAlert, close,0) alertSellValueLow = alertBuyValue - (alertBuyValue*sellLow) //////////////////////////////////////////////////////////// ///// Trailing Stop ///// //////////////////////////////////////////////////////////// var TSLActive=0 //Check to see if TSL has been activated var TSLTriggerValue=0.0 //Initial and climbing value of TSL var TSLStop = 0.0 //Sell Trigger var TSLRunning =0 //Continuously check each bar to raise TSL or not // Check if a Buy has been triggered and set initial value for TSL // if buyAlert TSLTriggerValue := alertBuyValue+(alertBuyValue*trailStopArm) TSLActive := 0 TSLRunning :=1 TSLStop := TSLTriggerValue - (TSLTriggerValue*trailStopPct) // Check that Buy has triggered and if Close has reached initial TSL// // Keeps from setting Sell Signal before TSL has been armed w/TSLActive// beginTrail=TSLRunning==1 and TSLActive==0 and close>alertBuyValue+(alertBuyValue*trailStopArm) and ta.crossover(close,TSLTriggerValue) if beginTrail TSLTriggerValue :=close TSLActive :=1 TSLStop :=TSLTriggerValue - (TSLTriggerValue*trailStopPct) // Continuously check if TSL needs to increase and set new value // runTrail= TSLActive==1 and (ta.crossover(close,TSLTriggerValue) or close>=TSLTriggerValue) if runTrail TSLTriggerValue :=close TSLStop :=TSLTriggerValue - (TSLTriggerValue*trailStopPct) // Verify that TSL is active and trigger when close cross below TSL Stop// TSL=TSLActive==1 and (ta.crossunder(close,TSLStop) or (close[1]>TSLStop and close<TSLStop)) // Plot point of inital arming of TSL// TSLTrigger=TSLActive==1 and TSLActive[1]==0 plotshape(TSLTrigger, title='TSL Armed', location=location.abovebar, color=color.new(color.blue, 0), size=size.small, style=shape.cross, text='TSL Armed') //////////////////////////////////////////////////////////// // Plots used for troubleshooting and verification of TSL // //////////////////////////////////////////////////////////// //plot(TSLActive,"Trailing Stop", color=#f48fb1) //plot(TSLRunning,"Trailing Stop", color=#f48fb1) //plot(TSLTriggerValue,"Trailing Stop Trigger", color.new(color=#ec407a, transp = TSLRunning==1 ? 0 : 100)) //plot(TSLStop,"Trailing Stop", color.new(color=#f48fb1, transp = TSLRunning==1 ? 0 : 100))// //////////////////////////////////////////////////////////// ///// Sell Conditions /////// //////////////////////////////////////////////////////////// Sell1 = TSL Sell2 = ta.crossunder(close,alertSellValueLow) alertSell= Sell1 or Sell2 //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// //// Remove Redundant Signals //// //////////////////////////////////////////////////////////// showAlertSell = 0 if(alertSell and lastsignal != -1) showAlertSell := 1 lastsignal := -1 sellAlert= showAlertSell > 0 if sellAlert TSLActive :=0 TSLRunning :=0 ///////////////////////////////////////// // Plot Buy and Sell Shapes on Chart // ///////////////////////////////////////// plotshape(buyAlert, title='Buy', location=location.belowbar, color=color.new(color.green, 0), size=size.small, style=shape.triangleup, text='Buy') plotshape(sellAlert, title='Sell', location=location.abovebar, color=color.new(color.red, 0), size=size.small, style=shape.triangledown, text='Sell') ///////////////////////////////////////////////////////////////////////////////////////////// // Remove // to setup for Indicator // ///////////////////////////////////////////////////////////////////////////////////////////// //Alerts //alertcondition(title='Buy Alert', condition=buyAlert, message='Buy Conditions are Met') //alertcondition(title='Sell Alert', condition=sellAlert, message='Sell Conditions are Met') ///////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// //// Comment out this section if setup as Indicator //// //////////////////////////////////////////////////////////// longCondition = buyAlert if (longCondition) strategy.entry("Buy", strategy.long) alert(message='Buy', freq=alert.freq_once_per_bar_close) shortCondition = sellAlert if (shortCondition) strategy.close_all(sellAlert,"Sell") alert(message='Sell', freq=alert.freq_once_per_bar_close) /////////////////////////////////////////////////////////////
RSI_Boll-TP/SL
https://www.tradingview.com/script/wAztQq30-RSI-Boll-TP-SL/
BigCoinHunter
https://www.tradingview.com/u/BigCoinHunter/
84
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/ // © BigCoinHunter //@version=5 strategy(title="RSI_Boll-TP/SL", overlay=true, pyramiding=0, default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=1000, currency=currency.USD, commission_value=0.05, commission_type=strategy.commission.percent, process_orders_on_close=true) //----------- get the user inputs -------------- //---------- RSI ------------- price = input(close, title="Source") RSIlength = input.int(defval=6,title="RSI Length") RSIoverSold = input.int(defval=50, title="RSI OverSold", minval=1) RSIoverBought = input.int(defval=50, title="RSI OverBought", minval=1) //------- Bollinger Bands ----------- BBlength = input.int(defval=200, title="Bollinger Period Length", minval=1) BBmult = input.float(defval=2.0, minval=0.001, maxval=50, step=0.1, title="Bollinger Bands Standard Deviation") BBbasis = ta.sma(price, BBlength) BBdev = BBmult * ta.stdev(price, BBlength) BBupper = BBbasis + BBdev BBlower = BBbasis - BBdev source = close buyEntry = ta.crossover(source, BBlower) sellEntry = ta.crossunder(source, BBupper) plot(BBbasis, color=color.aqua, title="Bollinger Bands SMA Basis Line") p1 = plot(BBupper, color=color.silver, title="Bollinger Bands Upper Line") p2 = plot(BBlower, color=color.silver, title="Bollinger Bands Lower Line") fill(plot1=p1, plot2=p2, title="Bollinger BackGround", color=color.new(color.aqua,90), fillgaps=false, editable=true) //---------- input TP/SL --------------- tp = input.float(title="Take Profit:", defval=0.0, minval=0.0, maxval=100.0, step=0.1) * 0.01 sl = input.float(title="Stop Loss: ", defval=0.0, minval=0.0, maxval=100.0, step=0.1) * 0.01 longEntry = input.bool(defval=true, title= 'Long Entry', inline="11") shortEntry = input.bool(defval=true, title='Short Entry', inline="11") //---------- backtest range setup ------------ 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 = 2021, title = "From Year", minval = 2010) toDay = input.int(defval = 30, title = "To Day", minval = 1, maxval = 31) toMonth = input.int(defval = 12, title = "To Month", minval = 1, maxval = 12) toYear = input.int(defval = 2022, title = "To Year", minval = 2010) //------------ time interval setup ----------- start = timestamp(fromYear, fromMonth, fromDay, 00, 00) // backtest start window finish = timestamp(toYear, toMonth, toDay, 23, 59) // backtest finish window window() => time >= start and time <= finish ? true : false // create function "within window of time" //------- define the global variables ------ var bool long = true var bool stoppedOutLong = false var bool stoppedOutShort = false //--------- Colors --------------- TrendColor = RSIoverBought and (price[1] > BBupper and price < BBupper) and BBbasis < BBbasis[1] ? color.red : RSIoverSold and (price[1] < BBlower and price > BBlower) and BBbasis > BBbasis[1] ? color.green : na //bgcolor(switch2?(color.new(TrendColor,50)):na) //--------- calculate the input/output points ----------- longProfitPrice = strategy.position_avg_price * (1 + tp) // tp -> take profit percentage longStopPrice = strategy.position_avg_price * (1 - sl) // sl -> stop loss percentage shortProfitPrice = strategy.position_avg_price * (1 - tp) shortStopPrice = strategy.position_avg_price * (1 + sl) //---------- RSI + Bollinger Bands Strategy ------------- vrsi = ta.rsi(price, RSIlength) rsiCrossOver = ta.crossover(vrsi, RSIoverSold) rsiCrossUnder = ta.crossunder(vrsi, RSIoverBought) BBCrossOver = ta.crossover(source, BBlower) BBCrossUnder = ta.crossunder(source, BBupper) if (not na(vrsi)) if rsiCrossOver and BBCrossOver long := true if rsiCrossUnder and BBCrossUnder long := false //------------------- determine buy and sell points --------------------- buySignall = window() and long and (not stoppedOutLong) sellSignall = window() and (not long) and (not stoppedOutShort) //---------- execute the strategy ----------------- if(longEntry and shortEntry) if long strategy.entry("LONG", strategy.long, when = buySignall, comment = "ENTER LONG") stoppedOutLong := true stoppedOutShort := false else strategy.entry("SHORT", strategy.short, when = sellSignall, comment = "ENTER SHORT") stoppedOutLong := false stoppedOutShort := true else if(longEntry) strategy.entry("LONG", strategy.long, when = buySignall) strategy.close("LONG", when = sellSignall) if long stoppedOutLong := true else stoppedOutLong := false else if(shortEntry) strategy.entry("SHORT", strategy.short, when = sellSignall) strategy.close("SHORT", when = buySignall) if not long stoppedOutShort := true else stoppedOutShort := false //----------------- take profit and stop loss ----------------- if(tp>0.0 and sl>0.0) if ( strategy.position_size > 0 ) strategy.exit(id="LONG", limit=longProfitPrice, stop=longStopPrice, comment="Long TP/SL Trigger") else if ( strategy.position_size < 0 ) strategy.exit(id="SHORT", limit=shortProfitPrice, stop=shortStopPrice, comment="Short TP/SL Trigger") else if(tp>0.0) if ( strategy.position_size > 0 ) strategy.exit(id="LONG", limit=longProfitPrice, comment="Long TP Trigger") else if ( strategy.position_size < 0 ) strategy.exit(id="SHORT", limit=shortProfitPrice, comment="Short TP Trigger") else if(sl>0.0) if ( strategy.position_size > 0 ) strategy.exit(id="LONG", stop=longStopPrice, comment="Long SL Trigger") else if ( strategy.position_size < 0 ) strategy.exit(id="SHORT", stop=shortStopPrice, comment="Short SL Trigger")
OTT-Stoch-TP/SL
https://www.tradingview.com/script/jPEIOqzL-OTT-Stoch-TP-SL/
BigCoinHunter
https://www.tradingview.com/u/BigCoinHunter/
177
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/ // © BigCoinHunter //@version=5 strategy(title='OTT-Stoch-TP/SL', overlay=true, pyramiding=0, default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=1000, currency=currency.USD, commission_value=0.05, commission_type=strategy.commission.percent, process_orders_on_close=true) //-------------- fetch user inputs ------------------ src = input(defval=close, title='OTT source') src1 = input(defval=close, title="Stoch OTT source") ottFastPercent = input.float(title='OTT Fast Percent(%):', defval=3.0, minval=0.1, maxval=30.0, step=0.1) ottSlowPercent = input.float(title='OTT Slow Percent(%):', defval=10.0, minval=0.1, maxval=30.0, step=0.1) ottFastLength = input.int(title="OTT Fast Length:", defval=1, minval=1) ottSlowLength = input.int(title="OTT Slow Length:", defval=1, minval=1) periodK = input.int(defval=500, title="%K Length", minval=1, step=10) smoothK = input.int(defval=200, title="%K Smoothing", minval=1, step=10) stochLength=input.int(defval=2, title="Stoch OTT Period", minval=1) stochPercent=input.float(defval=0.5, title="Stoch OTT Percent", step=0.1, minval=0) mav = input.string(title="Moving Average Type", defval="SMA", options=["SMA", "EMA", "WMA", "TMA", "VAR", "WWMA", "ZLEMA", "TSF"]) tp = input.float(title="Take Profit:", defval=0.0, minval=0.0, maxval=100.0, step=0.1) * 0.01 sl = input.float(title="Stop Loss: ", defval=0.0, minval=0.0, maxval=100.0, step=0.1) * 0.01 //showsupport = input.bool(title="Show Support Line?", defval=true) stoch = input.bool(title="evaluate Stoch OTT", defval=false) longEntry = input.bool(defval=true, title= 'Long Entry', inline="11") shortEntry = input.bool(defval=true, title='Short Entry', inline="11") //---------- backtest range setup ------------ 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 = 2021, title = "From Year", minval = 2010) toDay = input.int(defval = 30, title = "To Day", minval = 1, maxval = 31) toMonth = input.int(defval = 12, title = "To Month", minval = 1, maxval = 12) toYear = input.int(defval = 2022, title = "To Year", minval = 2010) //------------ time interval setup ----------- start = timestamp(fromYear, fromMonth, fromDay, 00, 00) // backtest start window finish = timestamp(toYear, toMonth, toDay, 23, 59) // backtest finish window window() => time >= start and time <= finish ? true : false // create function "within window of time" //-------- calculate the OTT lines ---------- Var_Func(src,length)=> valpha=2/(length+1) vud1=src>src[1] ? src-src[1] : 0 vdd1=src<src[1] ? src[1]-src : 0 vUD=math.sum(vud1,9) vDD=math.sum(vdd1,9) vCMO=nz((vUD-vDD)/(vUD+vDD)) VAR=0.0 VAR:=nz(valpha*math.abs(vCMO)*src)+(1-valpha*math.abs(vCMO))*nz(VAR[1]) //VAR=Var_Func(src,length) Wwma_Func(src,length)=> wwalpha = 1/ length WWMA = 0.0 WWMA := wwalpha*src + (1-wwalpha)*nz(WWMA[1]) //WWMA=Wwma_Func(src,length) Zlema_Func(src,length)=> zxLag = length/2==math.round(length/2) ? length/2 : (length - 1) / 2 zxEMAData = (src + (src - src[zxLag])) ZLEMA = ta.ema(zxEMAData, length) //ZLEMA=Zlema_Func(src,length) Tsf_Func(src,length)=> lrc = ta.linreg(src, length, 0) lrc1 = ta.linreg(src,length,1) lrs = (lrc-lrc1) TSF = ta.linreg(src, length, 0)+lrs //TSF=Tsf_Func(src,length) getMA(src, length) => ma = 0.0 if mav == "SMA" ma := ta.sma(src, length) ma if mav == "EMA" ma := ta.ema(src, length) ma if mav == "WMA" ma := ta.wma(src, length) ma if mav == "TMA" ma := ta.sma(ta.sma(src, math.ceil(length / 2)), math.floor(length / 2) + 1) ma if mav == "VAR" ma := Var_Func(src,length) ma if mav == "WWMA" ma := Wwma_Func(src,length) ma if mav == "ZLEMA" ma := Zlema_Func(src,length) ma if mav == "TSF" ma := Tsf_Func(src,length) ma ma //-------- OTT line calculation -------- MAvg1=getMA(src, ottFastLength) fark1=MAvg1*ottFastPercent*0.01 longStop1 = MAvg1 - fark1 longStopPrev1 = nz(longStop1[1], longStop1) longStop1 := MAvg1 > longStopPrev1 ? math.max(longStop1, longStopPrev1) : longStop1 shortStop1 = MAvg1 + fark1 shortStopPrev1 = nz(shortStop1[1], shortStop1) shortStop1 := MAvg1 < shortStopPrev1 ? math.min(shortStop1, shortStopPrev1) : shortStop1 dir1 = 1 dir1 := nz(dir1[1], dir1) dir1 := dir1 == -1 and MAvg1 > shortStopPrev1 ? 1 : dir1 == 1 and MAvg1 < longStopPrev1 ? -1 : dir1 MT1 = dir1==1 ? longStop1: shortStop1 OTTFast=MAvg1>MT1 ? MT1*(200+ottFastPercent)/200 : MT1*(200-ottFastPercent)/200 MAvg2=getMA(src, ottSlowLength) fark2=MAvg2*ottSlowPercent*0.01 longStop2 = MAvg2 - fark2 longStopPrev2 = nz(longStop2[1], longStop2) longStop2 := MAvg2 > longStopPrev2 ? math.max(longStop2, longStopPrev2) : longStop2 shortStop2 = MAvg2 + fark2 shortStopPrev2 = nz(shortStop2[1], shortStop2) shortStop2 := MAvg2 < shortStopPrev2 ? math.min(shortStop2, shortStopPrev2) : shortStop2 dir2 = 1 dir2 := nz(dir2[1], dir2) dir2 := dir2 == -1 and MAvg2 > shortStopPrev2 ? 1 : dir2 == 1 and MAvg2 < longStopPrev2 ? -1 : dir2 MT2 = dir2==1 ? longStop2: shortStop2 OTTSlow=MAvg2>MT2 ? MT2*(200+ottSlowPercent)/200 : MT2*(200-ottSlowPercent)/200 //-------- Stoch OTT calculation ---------- Var_Func1(src1,length)=> valpha1=2/(length+1) vud11=src1>src1[1] ? src1-src1[1] : 0 vdd11=src1<src1[1] ? src1[1]-src1 : 0 vUD1=math.sum(vud11,9) vDD1=math.sum(vdd11,9) vCMO1=nz((vUD1-vDD1)/(vUD1+vDD1)) VAR1=0.0 VAR1:=nz(valpha1*math.abs(vCMO1)*src1)+(1-valpha1*math.abs(vCMO1))*nz(VAR1[1]) VAR1=Var_Func1(src1,stochLength) k = Var_Func1(ta.stoch(close, high, low, periodK), smoothK) k1=k+1000 VAR2=Var_Func(k1,stochLength) MAvg3=Var_Func(k1, stochLength) fark3=MAvg3*stochPercent*0.01 longStop3 = MAvg3 - fark3 longStopPrev3 = nz(longStop3[1], longStop3) longStop3 := MAvg3 > longStopPrev3 ? math.max(longStop3, longStopPrev3) : longStop3 shortStop3 = MAvg3 + fark3 shortStopPrev3 = nz(shortStop3[1], shortStop3) shortStop3 := MAvg3 < shortStopPrev3 ? math.min(shortStop3, shortStopPrev3) : shortStop3 dir3 = 1 dir3 := nz(dir3[1], dir3) dir3 := dir3 == -1 and MAvg3 > shortStopPrev3 ? 1 : dir3 == 1 and MAvg3 < longStopPrev3 ? -1 : dir3 MT3 = dir3==1 ? longStop3: shortStop3 OTTStoch=MAvg3>MT3 ? MT3*(200+stochPercent)/200 : MT3*(200-stochPercent)/200 //------- define the global variables ------ var bool long = true var bool stoppedOutLong = false var bool stoppedOutShort = false //-------- determine the market direction -------- if OTTFast > OTTSlow long := true else if OTTFast < OTTSlow long := false //--------- calculate the input/output points ----------- longProfitPrice = strategy.position_avg_price * (1 + tp) // tp -> take profit percentage longStopPrice = strategy.position_avg_price * (1 - sl) // sl -> stop loss percentage shortProfitPrice = strategy.position_avg_price * (1 - tp) shortStopPrice = strategy.position_avg_price * (1 + sl) //------------------- determine buy and sell points --------------------- buySignall = false sellSignall = false if stoch == false buySignall := window() and long and (not stoppedOutLong) sellSignall := window() and (not long) and (not stoppedOutShort) else buySignall := window() and long and (not stoppedOutLong) and ( k1 > OTTStoch ) sellSignall := window() and (not long) and (not stoppedOutShort) and ( k1 < OTTStoch ) //---------- execute the strategy ----------------- if(longEntry and shortEntry) if long strategy.entry("LONG", strategy.long, when = buySignall, comment = "ENTER LONG") stoppedOutLong := true stoppedOutShort := false else strategy.entry("SHORT", strategy.short, when = sellSignall, comment = "ENTER SHORT") stoppedOutLong := false stoppedOutShort := true else if(longEntry) strategy.entry("LONG", strategy.long, when = buySignall) strategy.close("LONG", when = sellSignall) if long stoppedOutLong := true else stoppedOutLong := false else if(shortEntry) strategy.entry("SHORT", strategy.short, when = sellSignall) strategy.close("SHORT", when = buySignall) if not long stoppedOutShort := true else stoppedOutShort := false //----------------- take profit and stop loss ----------------- if(tp>0.0 and sl>0.0) if ( strategy.position_size > 0 ) strategy.exit(id="LONG", limit=longProfitPrice, stop=longStopPrice, comment="Long TP/SL Trigger") else if ( strategy.position_size < 0 ) strategy.exit(id="SHORT", limit=shortProfitPrice, stop=shortStopPrice, comment="Short TP/SL Trigger") else if(tp>0.0) if ( strategy.position_size > 0 ) strategy.exit(id="LONG", limit=longProfitPrice, comment="Long TP Trigger") else if ( strategy.position_size < 0 ) strategy.exit(id="SHORT", limit=shortProfitPrice, comment="Short TP Trigger") else if(sl>0.0) if ( strategy.position_size > 0 ) strategy.exit(id="LONG", stop=longStopPrice, comment="Long SL Trigger") else if ( strategy.position_size < 0 ) strategy.exit(id="SHORT", stop=shortStopPrice, comment="Short SL Trigger") //------------- plot charts --------------------- lineColor1 = long ? color.green : color.red lineColor2 = long ? color.aqua : color.fuchsia light_green=#08ff12 light_red=#fe0808 plot(nz(OTTFast), color=light_green, linewidth=3, title="OTT Fast") plot(nz(OTTSlow), color=light_red, linewidth=3, title="OTT Slow")
RSI_OTT - TP/SL
https://www.tradingview.com/script/njyiMUdB-RSI-OTT-TP-SL/
BigCoinHunter
https://www.tradingview.com/u/BigCoinHunter/
249
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/ // © BigCoinHunter //@version=5 strategy(title="RSI_OTT-TP/SL", overlay=true, pyramiding=0, default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=1000, currency=currency.USD, commission_value=0.05, commission_type=strategy.commission.percent, process_orders_on_close=true) //----------- get the user inputs -------------- //---------- RSI ------------- price = input(close, title="Source") RSIlength = input.int(defval=6,title="RSI Length") RSIoverSold = input.int(defval=50, title="RSI OverSold", minval=1) RSIoverBought = input.int(defval=50, title="RSI OverBought", minval=1) //------- OTT Bands ---------------- src = close length=input.int(defval=1, title="OTT Period", minval=1) percent=input.float(defval=5, title="OTT Percent", step=0.1, minval=0.001) mav = input.string(title="OTT MA Type", defval="VAR", options=["SMA", "EMA", "WMA", "TMA", "VAR", "WWMA", "ZLEMA", "TSF"]) ottUpperPercent = input.float(title="OTT Upper Line Coeff", defval=0.01, minval = 0.001, step=0.001) ottLowerPercent = input.float(title="OTT Lower Line Coeff", defval=0.01, minval = 0.001, step=0.001) Var_Func(src,length)=> valpha=2/(length+1) vud1=src>src[1] ? src-src[1] : 0 vdd1=src<src[1] ? src[1]-src : 0 vUD=math.sum(vud1,9) vDD=math.sum(vdd1,9) vCMO=nz((vUD-vDD)/(vUD+vDD)) VAR=0.0 VAR:=nz(valpha*math.abs(vCMO)*src)+(1-valpha*math.abs(vCMO))*nz(VAR[1]) VAR=Var_Func(src,length) Wwma_Func(src,length)=> wwalpha = 1/ length WWMA = 0.0 WWMA := wwalpha*src + (1-wwalpha)*nz(WWMA[1]) WWMA=Wwma_Func(src,length) Zlema_Func(src,length)=> zxLag = length/2==math.round(length/2) ? length/2 : (length - 1) / 2 zxEMAData = (src + (src - src[zxLag])) ZLEMA = ta.ema(zxEMAData, length) ZLEMA=Zlema_Func(src,length) Tsf_Func(src,length)=> lrc = ta.linreg(src, length, 0) lrc1 = ta.linreg(src,length,1) lrs = (lrc-lrc1) TSF = ta.linreg(src, length, 0)+lrs TSF=Tsf_Func(src,length) getMA(src, length) => ma = 0.0 if mav == "SMA" ma := ta.sma(src, length) ma if mav == "EMA" ma := ta.ema(src, length) ma if mav == "WMA" ma := ta.wma(src, length) ma if mav == "TMA" ma := ta.sma(ta.sma(src, math.ceil(length / 2)), math.floor(length / 2) + 1) ma if mav == "VAR" ma := VAR ma if mav == "WWMA" ma := WWMA ma if mav == "ZLEMA" ma := ZLEMA ma if mav == "TSF" ma := TSF ma ma MAvg=getMA(src, length) fark=MAvg*percent*0.01 longStop = MAvg - fark longStopPrev = nz(longStop[1], longStop) longStop := MAvg > longStopPrev ? math.max(longStop, longStopPrev) : longStop shortStop = MAvg + fark shortStopPrev = nz(shortStop[1], shortStop) shortStop := MAvg < shortStopPrev ? math.min(shortStop, shortStopPrev) : shortStop dir = 1 dir := nz(dir[1], dir) dir := dir == -1 and MAvg > shortStopPrev ? 1 : dir == 1 and MAvg < longStopPrev ? -1 : dir MT = dir==1 ? longStop: shortStop OTT=MAvg>MT ? MT*(200+percent)/200 : MT*(200-percent)/200 light_green=#08ff12 light_red=#fe0808 OTTupper = nz(OTT[2])*(1+ottUpperPercent) OTTlower = nz(OTT[2])*(1-ottLowerPercent) p1 = plot(OTTupper, color=light_green, linewidth=1, title="OTT UPPER") p2 = plot(nz(OTT[2]), color=color.new(color.yellow,0), linewidth=1, title="OTT MIDDLE") p3 = plot(OTTlower, color=light_red, linewidth=1, title="OTT LOWER") fill(plot1=p1, plot2=p3, title="OTT Background", color=color.new(color.aqua,90), fillgaps=false, editable=true) buyEntry = ta.crossover(src, OTTlower) sellEntry = ta.crossunder(src, OTTupper) //---------- input TP/SL --------------- tp = input.float(title="Take Profit:", defval=0.0, minval=0.0, maxval=100.0, step=0.1) * 0.01 sl = input.float(title="Stop Loss: ", defval=0.0, minval=0.0, maxval=100.0, step=0.1) * 0.01 isEntryLong = input.bool(defval=true, title= 'Long Entry', inline="11") isEntryShort = input.bool(defval=true, title='Short Entry', inline="11") //---------- backtest range setup ------------ 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 = 2021, title = "From Year", minval = 2010) toDay = input.int(defval = 30, title = "To Day", minval = 1, maxval = 31) toMonth = input.int(defval = 12, title = "To Month", minval = 1, maxval = 12) toYear = input.int(defval = 2022, title = "To Year", minval = 2010) //------------ time interval setup ----------- start = timestamp(fromYear, fromMonth, fromDay, 00, 00) // backtest start window finish = timestamp(toYear, toMonth, toDay, 23, 59) // backtest finish window window() => time >= start and time <= finish ? true : false // create function "within window of time" //------- define the global variables ------ var bool long = true var bool stoppedOutLong = false var bool stoppedOutShort = false //--------- Colors --------------- //TrendColor = RSIoverBought and (price[1] > BBupper and price < BBupper) and BBbasis < BBbasis[1] ? color.red : RSIoverSold and (price[1] < BBlower and price > BBlower) and BBbasis > BBbasis[1] ? color.green : na //bgcolor(switch2?(color.new(TrendColor,50)):na) //--------- calculate the input/output points ----------- longProfitPrice = strategy.position_avg_price * (1 + tp) // tp -> take profit percentage longStopPrice = strategy.position_avg_price * (1 - sl) // sl -> stop loss percentage shortProfitPrice = strategy.position_avg_price * (1 - tp) shortStopPrice = strategy.position_avg_price * (1 + sl) //---------- RSI + Bollinger Bands Strategy ------------- vrsi = ta.rsi(price, RSIlength) rsiCrossOver = ta.crossover(vrsi, RSIoverSold) rsiCrossUnder = ta.crossunder(vrsi, RSIoverBought) OTTCrossOver = ta.crossover(src, OTTlower) OTTCrossUnder = ta.crossunder(src, OTTupper) if (not na(vrsi)) if rsiCrossOver and OTTCrossOver long := true if rsiCrossUnder and OTTCrossUnder long := false //------- define the global variables ------ buySignall = false sellSignall = false //------------------- determine buy and sell points --------------------- buySignall := window() and long and (not stoppedOutLong) sellSignall := window() and (not long) and (not stoppedOutShort) //---------- execute the strategy ----------------- if(isEntryLong and isEntryShort) if long strategy.entry("LONG", strategy.long, when = buySignall, comment = "ENTER LONG") stoppedOutLong := true stoppedOutShort := false else strategy.entry("SHORT", strategy.short, when = sellSignall, comment = "ENTER SHORT") stoppedOutLong := false stoppedOutShort := true else if(isEntryLong) strategy.entry("LONG", strategy.long, when = buySignall) strategy.close("LONG", when = sellSignall) if long stoppedOutLong := true else stoppedOutLong := false else if(isEntryShort) strategy.entry("SHORT", strategy.short, when = sellSignall) strategy.close("SHORT", when = buySignall) if not long stoppedOutShort := true else stoppedOutShort := false //----------------- take profit and stop loss ----------------- if(tp>0.0 and sl>0.0) if ( strategy.position_size > 0 ) strategy.exit(id="LONG", limit=longProfitPrice, stop=longStopPrice, comment="Long TP/SL Trigger") else if ( strategy.position_size < 0 ) strategy.exit(id="SHORT", limit=shortProfitPrice, stop=shortStopPrice, comment="Short TP/SL Trigger") else if(tp>0.0) if ( strategy.position_size > 0 ) strategy.exit(id="LONG", limit=longProfitPrice, comment="Long TP Trigger") else if ( strategy.position_size < 0 ) strategy.exit(id="SHORT", limit=shortProfitPrice, comment="Short TP Trigger") else if(sl>0.0) if ( strategy.position_size > 0 ) strategy.exit(id="LONG", stop=longStopPrice, comment="Long SL Trigger") else if ( strategy.position_size < 0 ) strategy.exit(id="SHORT", stop=shortStopPrice, comment="Short SL Trigger")
EMA Strat
https://www.tradingview.com/script/NFFIcgFf-EMA-Strat/
swagmoneytrader
https://www.tradingview.com/u/swagmoneytrader/
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/ // © ericdwyang //@version=5 strategy("EMA Strat", overlay=true, margin_long=100, margin_short=100) // EMA Variables emaInput = input(21, "Length") ema = ta.ema(close, emaInput) // Variable Declaration p = 0 start = false // Start Date yearInput = input(2000, "Year") if (time >= timestamp(2000,01,01,01,01)) start := true // Check first candle relative to EMA if (close > ema and start == true) p += 1 strategy.entry("Long", strategy.long, comment = "Entry") // Candle close above EMA (p + 1, count reset to 0) above = close[1] > ema[1] if (above) p += 1 // Candle close below EMA (reset p to 0, count -1) below = close < ema if (below) p := 0 strategy.close("Long", comment = "Flat") // // Exit Position // if (redCount == -2) // strategy.close("Long", comment = "Flat") // goLong = p[1] == 0 and p == 1 // flatten = p == 0 // // Restablish long // if (goLong and start == true) // strategy.entry("Long", strategy.long, comment = "Entry") plot(p) plot(ema)
Stairs Gain Strategy - MG
https://www.tradingview.com/script/tpSocClH/
trademasterf
https://www.tradingview.com/u/trademasterf/
76
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 //İchimoku Leading Span 2 Hesaplaması ve Girişleri strategy("Stairs Gain Strategy - MG", overlay=true, margin_long=100, margin_short=100) laggingSpan2Periods = input.int(52, minval=1, title="Leading Periot") displacement = input.int(1, minval=1, title="Displacement") donchian(len) => math.avg(ta.lowest(len), ta.highest(len)) leadLine2 = donchian(laggingSpan2Periods) p2 = plot(leadLine2, offset = displacement - 1, color=#EF9A9A, title="Leading Span B") // İşlem Tekrarını Filtrele filtreUygula = input.bool(true,title="Pozisyon Sıra Filtresi Uygula") //Kar Al / Zarar Durdur Seviyeleri Girişleri zararDurdurmaYuzde = input.float(1.0, title='Zarar Durdurma %', step=0.01) / 100 karAlmaYuzde = input.float(2.0, title='Kar Alma %', step=0.01) / 100 //ATR Hesaplaması atrCarpani = input.float(0.3, title="ATR Çarpanı", step= 0.01) atrDegeri = ta.atr(14) * atrCarpani //ATR Değer Girişleri atrbuyukdeger = input.float(0.01, title="ATR Üst Limit", step=0.01) atrkucukdeger = input.float(0.06, title="ATR Alt Limit", step=0.01) //Buy ve Sell Şartları buycross = ta.crossover(close,leadLine2[displacement-1]) ? atrDegeri > atrbuyukdeger : strategy.position_size == 0 sellcross = ta.crossover(leadLine2[displacement-1],close) ? atrDegeri < atrkucukdeger : strategy.position_size == 0 //KONTROL var sonPozisyonYonu = 0 //Son kapanan pozisyon long ise degiskenin degerini 1 olarak ata if strategy.position_size[1] > 0 and strategy.position_size == 0 sonPozisyonYonu := 1 //Son kapanan pozisyon short ise degiskenin degerini -1 olarak ata if strategy.position_size[1] < 0 and strategy.position_size == 0 sonPozisyonYonu := -1 //eger filtre uygulama seçiliyse ve son pozisyon yönü long ise 'longFiltreSonuc' degiskenine false degeri ata ve bir sonraki pozisyonun long olmasını engelle longFiltreSonuc = filtreUygula ? sonPozisyonYonu == 1 ? false : true : true //eger filtre uygulama seçiliyse ve son pozisyon yönü short ise 'shortFiltreSonuc' degiskenine false degeri ata ve bir sonraki pozisyonun short olmasını engelle shortFiltreSonuc = filtreUygula ? sonPozisyonYonu == -1 ? false : true : true //LONG GİRİŞ strategy.entry("Long", strategy.long, when=buycross and longFiltreSonuc) longKarAl = strategy.position_avg_price * (1 + karAlmaYuzde) longZararDurdur = strategy.position_avg_price * (1 - zararDurdurmaYuzde) strategy.exit("Long Exit","Long",limit=longKarAl, stop=longZararDurdur) //SHORT GİRİŞ strategy.entry("Short", strategy.short, when=sellcross and shortFiltreSonuc) shortKarAl = strategy.position_avg_price * (1 - karAlmaYuzde) shortZararDurdur = strategy.position_avg_price * (1 + zararDurdurmaYuzde) strategy.exit("Short Exit","Short",limit=shortKarAl, stop=shortZararDurdur) //Kar Al ve Zarar Durdur Seviyelerinin Grafikte İşaretlenmesi plot(strategy.position_size != 0 ? strategy.position_avg_price : na, color=color.navy, linewidth=2, style=plot.style_linebr, title="İşleme Giriş Seviyesi") plot(strategy.position_size > 0 ? longKarAl : na, color=color.green, linewidth=2, style=plot.style_linebr, title="Long Kar Alım Seviyesi") plot(strategy.position_size > 0 ? longZararDurdur : na, color=color.red, linewidth=2, style=plot.style_linebr, title="Long Zarar Durdurma Seviyesi") plot(strategy.position_size < 0 ? shortKarAl : na, color=color.green, linewidth=2, style=plot.style_linebr, title="Short Kar Alım Seviyesi") plot(strategy.position_size < 0 ? shortZararDurdur : na, color=color.red, linewidth=2, style=plot.style_linebr, title="Short Zarar Durdurma Seviyesi") //plotshape(buycross,size=size.small,style=shape.labelup,location=location.belowbar,color=color.green,text="Al", offset = displacement-1, textcolor=color.white) //plotshape(sellcross,size=size.small,style=shape.labeldown,location=location.abovebar,color=color.red,text="Sat", offset = displacement-1, textcolor=color.white)
Loft Strategy V1
https://www.tradingview.com/script/hMzmBTWO-Loft-Strategy-V1/
BigCoinHunter
https://www.tradingview.com/u/BigCoinHunter/
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/ // © BigCoinHunter //@version=5 strategy(title='Loft Strategy V1', overlay=true, pyramiding=0, default_qty_type=strategy.fixed, default_qty_value=100, initial_capital=100000, currency=currency.USD, commission_value=0.05, commission_type=strategy.commission.percent, process_orders_on_close=true) //-------------- fetch user inputs ------------------ gain = input.float(title="Kalman Gain:", defval=1.0, minval=1.0, maxval=5000.0, step=100.0) src = input(defval=close, title='Source:') stopPercentMax = input.float(title='Beginning Approach(%):', defval=2.0, minval=0.1, maxval=30.0, step=0.1) stopPercentMin = input.float(title='Final Approach(%): ', defval=0.5, minval=0.1, maxval=30.0, step=0.1) downStep = input.float(title='Approach Decrease Step:', defval=0.005, minval=0.0, maxval = 5, step=0.005) tp = input.float(title="Take Profit:", defval=1.5, minval=0.0, maxval=100.0, step=0.1) * 0.01 sl = input.float(title="Stop Loss: ", defval=0.0, minval=0.0, maxval=100.0, step=0.1) * 0.01 longEntry = input.bool(defval=true, title= 'Long Entry', inline="11") shortEntry = input.bool(defval=true, title='Short Entry', inline="11") //---------- backtest range setup ------------ 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 = 2021, title = "From Year", minval = 2010) toDay = input.int(defval = 30, title = "To Day", minval = 1, maxval = 31) toMonth = input.int(defval = 12, title = "To Month", minval = 1, maxval = 12) toYear = input.int(defval = 2022, title = "To Year", minval = 2010) //------------ time interval setup ----------- start = timestamp(fromYear, fromMonth, fromDay, 00, 00) // backtest start window finish = timestamp(toYear, toMonth, toDay, 23, 59) // backtest finish window window() => time >= start and time <= finish ? true : false // create function "within window of time" //------- define the global variables ------ enterLongComment = "ENTER LONG" exitLongComment = "EXIT LONG" enterShortComment = "ENTER SHORT" exitShortComment = "EXIT SHORT" longTPSL = "Long TP/SL" longTP = "Long TP" longSL = "Long SL" shortTPSL = "Short TP/SL" shortTP = "Short TP" shortSL = "Short SL" var bool long = true var bool stoppedOutLong = false var bool stoppedOutShort = false var float kf = 0.0 var float velo = 0.0 //------ kalman filter calculation -------- dk = src - nz(kf[1], src) smooth = nz(kf[1], src) + dk * math.sqrt(gain / 10000 * 2) velo := nz(velo[1], 0) + gain / 10000 * dk kf := smooth + velo //--------- calculate the loft stopLoss line --------- var stopPercent = stopPercentMax var stopLoss = kf - kf * (stopPercent /100) if long == true stopLoss := kf - (kf * (stopPercent / 100)) if long[1] == true and stopLoss <= stopLoss[1] stopLoss := stopLoss[1] else if (long[1] == true) stopPercent := stopPercent - downStep if(stopPercent < stopPercentMin) stopPercent := stopPercentMin if(kf < stopLoss) long := false stopPercent := stopPercentMax stopLoss := kf + (kf * (stopPercent / 100)) else stopLoss := kf + (kf * (stopPercent / 100)) if long[1] == false and stopLoss >= stopLoss[1] stopLoss := stopLoss[1] else if(long[1] == false) stopPercent := stopPercent - downStep if(stopPercent < stopPercentMin) stopPercent := stopPercentMin if(kf > stopLoss) long := true stopPercent := stopPercentMax stopLoss := kf - (kf * (stopPercent / 100)) //--------- calculate the input/output points ----------- longProfitPrice = strategy.position_avg_price * (1 + tp) // tp -> take profit percentage longStopPrice = strategy.position_avg_price * (1 - sl) // sl -> stop loss percentage shortProfitPrice = strategy.position_avg_price * (1 - tp) shortStopPrice = strategy.position_avg_price * (1 + sl) //------------------- determine buy and sell points --------------------- buySignall = window() and long and (not stoppedOutLong) sellSignall = window() and (not long) and (not stoppedOutShort) //---------- execute the strategy ----------------- if(longEntry and shortEntry) if long strategy.entry("LONG", strategy.long, when = buySignall, comment = enterLongComment) stoppedOutLong := true stoppedOutShort := false else strategy.entry("SHORT", strategy.short, when = sellSignall, comment = enterShortComment) stoppedOutLong := false stoppedOutShort := true else if(longEntry) strategy.entry("LONG", strategy.long, when = buySignall, comment = enterLongComment) strategy.close("LONG", when = sellSignall, comment = exitLongComment) if long stoppedOutLong := true else stoppedOutLong := false else if(shortEntry) strategy.entry("SHORT", strategy.short, when = sellSignall, comment = enterShortComment) strategy.close("SHORT", when = buySignall, comment = exitShortComment) if not long stoppedOutShort := true else stoppedOutShort := false //----------------- take profit and stop loss ----------------- if(tp>0.0 and sl>0.0) if ( strategy.position_size > 0 ) strategy.exit(id="LONG", limit=longProfitPrice, stop=longStopPrice, comment = longTPSL) else if ( strategy.position_size < 0 ) strategy.exit(id="SHORT", limit=shortProfitPrice, stop=shortStopPrice, comment = shortTPSL) else if(tp>0.0) if ( strategy.position_size > 0 ) strategy.exit(id="LONG", limit=longProfitPrice, comment = longTP) else if ( strategy.position_size < 0 ) strategy.exit(id="SHORT", limit=shortProfitPrice, comment = shortTP) else if(sl>0.0) if ( strategy.position_size > 0 ) strategy.exit(id="LONG", stop=longStopPrice, comment = longSL) else if ( strategy.position_size < 0 ) strategy.exit(id="SHORT", stop=shortStopPrice, comment = shortSL) //------------- plot charts --------------------- lineColor1 = long ? color.green : color.red lineColor2 = long ? color.aqua : color.fuchsia kalmanLine = plot(kf, color=lineColor1, linewidth=3, title = "Kalman Filter") stopLine = plot(stopLoss, color=lineColor2, linewidth=2, title = "Stop Loss Line")
AC- MY SCRIPT1
https://www.tradingview.com/script/9xwZvkWt-AC-MY-SCRIPT1/
CryptoACking
https://www.tradingview.com/u/CryptoACking/
59
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/ // © arjunji4u //@version=5 strategy('AC- MY SCRIPT1', 'AC- MS1', overlay=true) src = input(close, title='Source') length = input.int(4, 'OTT Period', minval=1) percent = input.float(4.2, 'OTT Percent', step=0.1, minval=0) showsupport = input(title='Show Support Line?', defval=true) showsignalsk = input(title='Show Support Line Crossing Signals?', defval=true) showsignalsc = input(title='Show Price/OTT Crossing Signals?', defval=false) highlight = input(title='Show OTT Color Changes?', defval=false) showsignalsr = input(title='Show OTT Color Change Signals?', defval=false) highlighting = input(title='Highlighter On/Off ?', defval=true) mav = input.string(title='Moving Average Type', defval='VAR', options=['SMA', 'EMA', 'WMA', 'TMA', 'VAR', 'WWMA', 'ZLEMA', 'TSF']) Var_Func(src, length) => valpha = 2 / (length + 1) vud1 = src > src[1] ? src - src[1] : 0 vdd1 = src < src[1] ? src[1] - src : 0 vUD = math.sum(vud1, 9) vDD = math.sum(vdd1, 9) vCMO = nz((vUD - vDD) / (vUD + vDD)) VAR = 0.0 VAR := nz(valpha * math.abs(vCMO) * src) + (1 - valpha * math.abs(vCMO)) * nz(VAR[1]) VAR VAR = Var_Func(src, length) Wwma_Func(src, length) => wwalpha = 1 / length WWMA = 0.0 WWMA := wwalpha * src + (1 - wwalpha) * nz(WWMA[1]) WWMA WWMA = Wwma_Func(src, length) Zlema_Func(src, length) => zxLag = length / 2 == math.round(length / 2) ? length / 2 : (length - 1) / 2 zxEMAData = src + src - src[zxLag] ZLEMA = ta.ema(zxEMAData, length) ZLEMA ZLEMA = Zlema_Func(src, length) Tsf_Func(src, length) => lrc = ta.linreg(src, length, 0) lrc1 = ta.linreg(src, length, 1) lrs = lrc - lrc1 TSF = ta.linreg(src, length, 0) + lrs TSF TSF = Tsf_Func(src, length) getMA(src, length) => ma = 0.0 if mav == 'SMA' ma := ta.sma(src, length) ma if mav == 'EMA' ma := ta.ema(src, length) ma if mav == 'WMA' ma := ta.wma(src, length) ma if mav == 'TMA' ma := ta.sma(ta.sma(src, math.ceil(length / 2)), math.floor(length / 2) + 1) ma if mav == 'VAR' ma := VAR ma if mav == 'WWMA' ma := WWMA ma if mav == 'ZLEMA' ma := ZLEMA ma if mav == 'TSF' ma := TSF ma ma MAvg = getMA(src, length) fark = MAvg * percent * 0.01 longStop = MAvg - fark longStopPrev = nz(longStop[1], longStop) longStop := MAvg > longStopPrev ? math.max(longStop, longStopPrev) : longStop shortStop = MAvg + fark shortStopPrev = nz(shortStop[1], shortStop) shortStop := MAvg < shortStopPrev ? math.min(shortStop, shortStopPrev) : shortStop dir = 1 dir := nz(dir[1], dir) dir := dir == -1 and MAvg > shortStopPrev ? 1 : dir == 1 and MAvg < longStopPrev ? -1 : dir MT = dir == 1 ? longStop : shortStop OTT = MAvg > MT ? MT * (200 + percent) / 200 : MT * (200 - percent) / 200 plot(showsupport ? MAvg : na, color=color.new(#0585E1, 0), linewidth=2, title='Support Line') OTTC = highlight ? OTT[2] > OTT[3] ? color.green : color.red : #B800D9 pALL = plot(nz(OTT[2]), color=OTTC, linewidth=2, title='OTT', transp=0) alertcondition(ta.cross(OTT[2], OTT[3]), title='Color ALARM', message='OTT Has Changed Color!') alertcondition(ta.crossover(OTT[2], OTT[3]), title='GREEN ALERT', message='OTT GREEN BUY SIGNAL!') alertcondition(ta.crossunder(OTT[2], OTT[3]), title='RED ALERT', message='OTT RED SELL SIGNAL!') alertcondition(ta.cross(MAvg, OTT[2]), title='Cross Alert', message='OTT - Support Line Crossing!') alertcondition(ta.crossover(MAvg, OTT[2]), title='Crossover Alarm', message='Support Line BUY SIGNAL!') alertcondition(ta.crossunder(MAvg, OTT[2]), title='Crossunder Alarm', message='Support Line SELL SIGNAL!') alertcondition(ta.cross(src, OTT[2]), title='Price Cross Alert', message='OTT - Price Crossing!') alertcondition(ta.crossover(src, OTT[2]), title='Price Crossover Alarm', message='PRICE OVER OTT - BUY SIGNAL!') alertcondition(ta.crossunder(src, OTT[2]), title='Price Crossunder Alarm', message='PRICE UNDER OTT - SELL SIGNAL!') buySignalk = ta.crossover(MAvg, OTT[2]) plotshape(buySignalk and showsignalsk ? OTT * 0.995 : na, title='Buy', text='Buy', location=location.absolute, style=shape.labelup, size=size.tiny, color=color.new(color.green, 0), textcolor=color.new(color.white, 0)) sellSignallk = ta.crossunder(MAvg, OTT[2]) plotshape(sellSignallk and showsignalsk ? OTT * 1.005 : na, title='Sell', text='Sell', location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.new(color.red, 0), textcolor=color.new(color.white, 0)) buySignalc = ta.crossover(src, OTT[2]) plotshape(buySignalc and showsignalsc ? OTT * 0.995 : na, title='Buy', text='Buy', location=location.absolute, style=shape.labelup, size=size.tiny, color=color.new(color.green, 0), textcolor=color.new(color.white, 0)) sellSignallc = ta.crossunder(src, OTT[2]) plotshape(sellSignallc and showsignalsc ? OTT * 1.005 : na, title='Sell', text='Sell', location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.new(color.red, 0), textcolor=color.new(color.white, 0)) mPlot = plot(ohlc4, title='', style=plot.style_circles, linewidth=0, display=display.none) longFillColor = highlighting ? MAvg > OTT ? color.green : na : na shortFillColor = highlighting ? MAvg < OTT ? color.red : na : na fill(mPlot, pALL, title='UpTrend Highligter', color=longFillColor, transp=90) fill(mPlot, pALL, title='DownTrend Highligter', color=shortFillColor, transp=90) buySignalr = ta.crossover(OTT[2], OTT[3]) plotshape(buySignalr and showsignalsr ? OTT * 0.995 : na, title='Buy', text='Buy', location=location.absolute, style=shape.labelup, size=size.tiny, color=color.new(color.green, 0), textcolor=color.new(color.white, 0)) sellSignallr = ta.crossunder(OTT[2], OTT[3]) plotshape(sellSignallr and showsignalsr ? OTT * 1.005 : na, title='Sell', text='Sell', location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.new(color.red, 0), textcolor=color.new(color.white, 0)) showscr = input(true, title='Show Screener Label') posX_scr = input(20, title='Pos. Label x-axis') posY_scr = input(1, title='Pos. Size Label y-axis') colinput = input.string(title='Label Color', defval='Blue', options=['White', 'Black', 'Red', 'Green', 'Yellow', 'Blue']) col = color.gray if colinput == 'White' col := color.white col if colinput == 'Black' col := color.black col if colinput == 'Red' col := color.red col if colinput == 'Green' col := color.green col if colinput == 'Yellow' col := color.yellow col if colinput == 'Blue' col := color.blue col dummy0 = input(true, title='=Backtest Inputs=') 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=2005, title='From Year', minval=2005) ToDay = input.int(defval=1, title='To Day', minval=1, maxval=31) ToMonth = input.int(defval=1, title='To Month', minval=1, maxval=12) ToYear = input.int(defval=9999, title='To Year', minval=2006) Start = timestamp(FromYear, FromMonth, FromDay, 00, 00) Finish = timestamp(ToYear, ToMonth, ToDay, 23, 59) Timerange() => time >= Start and time <= Finish ? true : false if buySignalk strategy.entry('Long', strategy.long, when=Timerange()) if sellSignallk strategy.entry('Short', strategy.short, when=Timerange()) t1 = input.symbol('NIFTY', title='Symbol 01') t2 = input.symbol('S68', title='Symbol 02') t3 = input.symbol('1000SHIBUSDTPERP', title='Symbol 03') t4 = input.symbol('1INCHUSDTPERP', title='Symbol 04') t5 = input.symbol('ALGOUSDTPERP', title='Symbol 05') t6 = input.symbol('ALICEUSDTPERP', title='Symbol 06') t7 = input.symbol('ALPHAUSDTPERP', title='Symbol 07') t8 = input.symbol('ANTUSDTPERP', title='Symbol 08') t9 = input.symbol('API3USDTPERP', title='Symbol 09') t10 = input.symbol('ARUSDTPERP', title='Symbol 10') t11 = input.symbol('ARPAUSDTPERP', title='Symbol 11') t12 = input.symbol('AUDIOUSDTPERP', title='Symbol 12') t13 = input.symbol('', title='Symbol 13') t14 = input.symbol('', title='Symbol 14') t15 = input.symbol('', title='Symbol 15') t16 = input.symbol('', title='Symbol 16') t17 = input.symbol('', title='Symbol 17') t18 = input.symbol('', title='Symbol 18') t19 = input.symbol('', title='Symbol 19') t20 = input.symbol('', title='Symbol 20') t21 = input.symbol('', title='Symbol 21') t22 = input.symbol('', title='Symbol 22') t23 = input.symbol('', title='Symbol 23') t24 = input.symbol('', title='Symbol 24') t25 = input.symbol('', title='Symbol 25') t26 = input.symbol('', title='Symbol 26') t27 = input.symbol('', title='Symbol 27') t28 = input.symbol('', title='Symbol 28') t29 = input.symbol('', title='Symbol 29') t30 = input.symbol('', title='Symbol 30') t31 = input.symbol('', title='Symbol 31') t32 = input.symbol('', title='Symbol 32') t33 = input.symbol('', title='Symbol 33') t34 = input.symbol('', title='Symbol 34') t35 = input.symbol('', title='Symbol 35') t36 = input.symbol('', title='Symbol 36') t37 = input.symbol('', title='Symbol 37') t38 = input.symbol('', title='Symbol 38') t39 = input.symbol('', title='Symbol 39') t40 = input.symbol('', title='Symbol 40') OTTs(percent, length) => Up = MAvg - MAvg * percent * 0.01 Dn = MAvg + MAvg * percent * 0.01 TrendUp = 0.0 TrendUp := MAvg[1] > TrendUp[1] ? math.max(Up, TrendUp[1]) : Up TrendDown = 0.0 TrendDown := MAvg[1] < TrendDown[1] ? math.min(Dn, TrendDown[1]) : Dn Trend = 0.0 Trend := MAvg > TrendDown[1] ? 1 : MAvg < TrendUp[1] ? -1 : nz(Trend[1], 1) Tsl = Trend == 1 ? TrendUp : TrendDown S_Buy = Trend == 1 ? 1 : 0 S_Sell = Trend != 1 ? 1 : 0 [Trend, Tsl] [Trend, Tsl] = OTTs(percent, length) TrendReversal = Trend != Trend[1] [t01, s01] = request.security(t1, timeframe.period, OTTs(percent, length)) [t02, s02] = request.security(t2, timeframe.period, OTTs(percent, length)) [t03, s03] = request.security(t3, timeframe.period, OTTs(percent, length)) [t04, s04] = request.security(t4, timeframe.period, OTTs(percent, length)) [t05, s05] = request.security(t5, timeframe.period, OTTs(percent, length)) [t06, s06] = request.security(t6, timeframe.period, OTTs(percent, length)) [t07, s07] = request.security(t7, timeframe.period, OTTs(percent, length)) [t08, s08] = request.security(t8, timeframe.period, OTTs(percent, length)) [t09, s09] = request.security(t9, timeframe.period, OTTs(percent, length)) [t010, s010] = request.security(t10, timeframe.period, OTTs(percent, length)) [t011, s011] = request.security(t11, timeframe.period, OTTs(percent, length)) [t012, s012] = request.security(t12, timeframe.period, OTTs(percent, length)) [t013, s013] = request.security(t13, timeframe.period, OTTs(percent, length)) [t014, s014] = request.security(t14, timeframe.period, OTTs(percent, length)) [t015, s015] = request.security(t15, timeframe.period, OTTs(percent, length)) [t016, s016] = request.security(t16, timeframe.period, OTTs(percent, length)) [t017, s017] = request.security(t17, timeframe.period, OTTs(percent, length)) [t018, s018] = request.security(t18, timeframe.period, OTTs(percent, length)) [t019, s019] = request.security(t19, timeframe.period, OTTs(percent, length)) [t020, s020] = request.security(t20, timeframe.period, OTTs(percent, length)) [t021, s021] = request.security(t21, timeframe.period, OTTs(percent, length)) [t022, s022] = request.security(t22, timeframe.period, OTTs(percent, length)) [t023, s023] = request.security(t23, timeframe.period, OTTs(percent, length)) [t024, s024] = request.security(t24, timeframe.period, OTTs(percent, length)) [t025, s025] = request.security(t25, timeframe.period, OTTs(percent, length)) [t026, s026] = request.security(t26, timeframe.period, OTTs(percent, length)) [t027, s027] = request.security(t27, timeframe.period, OTTs(percent, length)) [t028, s028] = request.security(t28, timeframe.period, OTTs(percent, length)) [t029, s029] = request.security(t29, timeframe.period, OTTs(percent, length)) [t030, s030] = request.security(t30, timeframe.period, OTTs(percent, length)) [t031, s031] = request.security(t31, timeframe.period, OTTs(percent, length)) [t032, s032] = request.security(t22, timeframe.period, OTTs(percent, length)) [t033, s033] = request.security(t33, timeframe.period, OTTs(percent, length)) [t034, s034] = request.security(t34, timeframe.period, OTTs(percent, length)) [t035, s035] = request.security(t35, timeframe.period, OTTs(percent, length)) [t036, s036] = request.security(t36, timeframe.period, OTTs(percent, length)) [t037, s037] = request.security(t37, timeframe.period, OTTs(percent, length)) [t038, s038] = request.security(t38, timeframe.period, OTTs(percent, length)) [t039, s039] = request.security(t39, timeframe.period, OTTs(percent, length)) [t040, s040] = request.security(t40, timeframe.period, OTTs(percent, length)) tr01 = t01 != t01[1] up01 = t01 == 1 dn01 = t01 == -1 tr02 = t02 != t02[1] up02 = t02 == 1 dn02 = t02 == -1 tr03 = t03 != t03[1] up03 = t03 == 1 dn03 = t03 == -1 tr04 = t04 != t04[1] up04 = t04 == 1 dn04 = t04 == -1 tr05 = t05 != t05[1] up05 = t05 == 1 dn05 = t05 == -1 tr06 = t06 != t06[1] up06 = t06 == 1 dn06 = t06 == -1 tr07 = t07 != t07[1] up07 = t07 == 1 dn07 = t07 == -1 tr08 = t08 != t08[1] up08 = t08 == 1 dn08 = t08 == -1 tr09 = t09 != t09[1] up09 = t09 == 1 dn09 = t09 == -1 tr010 = t010 != t010[1] up010 = t010 == 1 dn010 = t010 == -1 tr011 = t011 != t011[1] up011 = t011 == 1 dn011 = t011 == -1 tr012 = t012 != t012[1] up012 = t012 == 1 dn012 = t012 == -1 tr013 = t013 != t013[1] up013 = t013 == 1 dn013 = t013 == -1 tr014 = t014 != t014[1] up014 = t014 == 1 dn014 = t014 == -1 tr015 = t015 != t015[1] up015 = t015 == 1 dn015 = t015 == -1 tr016 = t016 != t016[1] up016 = t016 == 1 dn016 = t016 == -1 tr017 = t017 != t017[1] up017 = t017 == 1 dn017 = t017 == -1 tr018 = t018 != t018[1] up018 = t018 == 1 dn018 = t018 == -1 tr019 = t019 != t019[1] up019 = t019 == 1 dn019 = t019 == -1 tr020 = t020 != t020[1] up020 = t020 == 1 dn020 = t020 == -1 tr021 = t021 != t021[1] up021 = t021 == 1 dn021 = t021 == -1 tr022 = t022 != t022[1] up022 = t022 == 1 dn022 = t022 == -1 tr023 = t023 != t023[1] up023 = t023 == 1 dn023 = t023 == -1 tr024 = t024 != t024[1] up024 = t024 == 1 dn024 = t024 == -1 tr025 = t025 != t025[1] up025 = t025 == 1 dn025 = t025 == -1 tr026 = t026 != t026[1] up026 = t026 == 1 dn026 = t026 == -1 tr027 = t027 != t027[1] up027 = t027 == 1 dn027 = t027 == -1 tr028 = t028 != t028[1] up028 = t028 == 1 dn028 = t028 == -1 tr029 = t029 != t029[1] up029 = t029 == 1 dn029 = t029 == -1 tr030 = t030 != t030[1] up030 = t030 == 1 dn030 = t030 == -1 tr031 = t031 != t031[1] up031 = t031 == 1 dn031 = t031 == -1 tr032 = t032 != t032[1] up032 = t032 == 1 dn032 = t032 == -1 tr033 = t033 != t033[1] up033 = t033 == 1 dn033 = t033 == -1 tr034 = t034 != t034[1] up034 = t034 == 1 dn034 = t034 == -1 tr035 = t035 != t035[1] up035 = t035 == 1 dn035 = t035 == -1 tr036 = t036 != t036[1] up036 = t036 == 1 dn036 = t036 == -1 tr037 = t037 != t037[1] up037 = t037 == 1 dn037 = t037 == -1 tr038 = t038 != t038[1] up038 = t038 == 1 dn038 = t038 == -1 tr039 = t039 != t039[1] up039 = t039 == 1 dn039 = t039 == -1 tr040 = t040 != t040[1] up040 = t040 == 1 dn040 = t040 == -1 pot_label = 'Potential Reversal: \n' pot_label := tr01 ? pot_label + t1 + '\n' : pot_label pot_label := tr02 ? pot_label + t2 + '\n' : pot_label pot_label := tr03 ? pot_label + t3 + '\n' : pot_label pot_label := tr04 ? pot_label + t4 + '\n' : pot_label pot_label := tr05 ? pot_label + t5 + '\n' : pot_label pot_label := tr06 ? pot_label + t6 + '\n' : pot_label pot_label := tr07 ? pot_label + t7 + '\n' : pot_label pot_label := tr08 ? pot_label + t8 + '\n' : pot_label pot_label := tr09 ? pot_label + t9 + '\n' : pot_label pot_label := tr010 ? pot_label + t10 + '\n' : pot_label pot_label := tr011 ? pot_label + t11 + '\n' : pot_label pot_label := tr012 ? pot_label + t12 + '\n' : pot_label pot_label := tr013 ? pot_label + t13 + '\n' : pot_label pot_label := tr014 ? pot_label + t14 + '\n' : pot_label pot_label := tr015 ? pot_label + t15 + '\n' : pot_label pot_label := tr016 ? pot_label + t16 + '\n' : pot_label pot_label := tr017 ? pot_label + t17 + '\n' : pot_label pot_label := tr018 ? pot_label + t18 + '\n' : pot_label pot_label := tr019 ? pot_label + t19 + '\n' : pot_label pot_label := tr020 ? pot_label + t20 + '\n' : pot_label pot_label := tr021 ? pot_label + t21 + '\n' : pot_label pot_label := tr022 ? pot_label + t22 + '\n' : pot_label pot_label := tr023 ? pot_label + t23 + '\n' : pot_label pot_label := tr024 ? pot_label + t24 + '\n' : pot_label pot_label := tr025 ? pot_label + t25 + '\n' : pot_label pot_label := tr026 ? pot_label + t26 + '\n' : pot_label pot_label := tr027 ? pot_label + t27 + '\n' : pot_label pot_label := tr028 ? pot_label + t28 + '\n' : pot_label pot_label := tr029 ? pot_label + t29 + '\n' : pot_label pot_label := tr030 ? pot_label + t30 + '\n' : pot_label pot_label := tr031 ? pot_label + t31 + '\n' : pot_label pot_label := tr032 ? pot_label + t32 + '\n' : pot_label pot_label := tr033 ? pot_label + t33 + '\n' : pot_label pot_label := tr034 ? pot_label + t34 + '\n' : pot_label pot_label := tr035 ? pot_label + t35 + '\n' : pot_label pot_label := tr036 ? pot_label + t36 + '\n' : pot_label pot_label := tr037 ? pot_label + t37 + '\n' : pot_label pot_label := tr038 ? pot_label + t38 + '\n' : pot_label pot_label := tr039 ? pot_label + t39 + '\n' : pot_label pot_label := tr040 ? pot_label + t40 + '\n' : pot_label scr_label = 'Confirmed Reversal: \n' scr_label := tr01[1] ? scr_label + t1 + '\n' : scr_label scr_label := tr02[1] ? scr_label + t2 + '\n' : scr_label scr_label := tr03[1] ? scr_label + t3 + '\n' : scr_label scr_label := tr04[1] ? scr_label + t4 + '\n' : scr_label scr_label := tr05[1] ? scr_label + t5 + '\n' : scr_label scr_label := tr06[1] ? scr_label + t6 + '\n' : scr_label scr_label := tr07[1] ? scr_label + t7 + '\n' : scr_label scr_label := tr08[1] ? scr_label + t8 + '\n' : scr_label scr_label := tr09[1] ? scr_label + t9 + '\n' : scr_label scr_label := tr010[1] ? scr_label + t10 + '\n' : scr_label scr_label := tr011[1] ? scr_label + t11 + '\n' : scr_label scr_label := tr012[1] ? scr_label + t12 + '\n' : scr_label scr_label := tr013[1] ? scr_label + t13 + '\n' : scr_label scr_label := tr014[1] ? scr_label + t14 + '\n' : scr_label scr_label := tr015[1] ? scr_label + t15 + '\n' : scr_label scr_label := tr016[1] ? scr_label + t16 + '\n' : scr_label scr_label := tr017[1] ? scr_label + t17 + '\n' : scr_label scr_label := tr018[1] ? scr_label + t18 + '\n' : scr_label scr_label := tr019[1] ? scr_label + t19 + '\n' : scr_label scr_label := tr020[1] ? scr_label + t20 + '\n' : scr_label scr_label := tr021[1] ? scr_label + t21 + '\n' : scr_label scr_label := tr022[1] ? scr_label + t22 + '\n' : scr_label scr_label := tr023[1] ? scr_label + t23 + '\n' : scr_label scr_label := tr024[1] ? scr_label + t24 + '\n' : scr_label scr_label := tr025[1] ? scr_label + t25 + '\n' : scr_label scr_label := tr026[1] ? scr_label + t26+ '\n' : scr_label scr_label := tr027[1] ? scr_label + t27 + '\n' : scr_label scr_label := tr028[1] ? scr_label + t28 + '\n' : scr_label scr_label := tr029[1] ? scr_label + t29 + '\n' : scr_label scr_label := tr030[1] ? scr_label + t30 + '\n' : scr_label scr_label := tr031[1] ? scr_label + t31 + '\n' : scr_label scr_label := tr032[1] ? scr_label + t32 + '\n' : scr_label scr_label := tr033[1] ? scr_label + t33 + '\n' : scr_label scr_label := tr034[1] ? scr_label + t34 + '\n' : scr_label scr_label := tr035[1] ? scr_label + t35 + '\n' : scr_label scr_label := tr036[1] ? scr_label + t36 + '\n' : scr_label scr_label := tr037[1] ? scr_label + t37 + '\n' : scr_label scr_label := tr038[1] ? scr_label + t38 + '\n' : scr_label scr_label := tr039[1] ? scr_label + t39 + '\n' : scr_label scr_label := tr040[1] ? scr_label + t40 + '\n' : scr_label up_label = 'Uptrend: \n' up_label := up01[1] ? up_label + t1 + '\n' : up_label up_label := up02[1] ? up_label + t2 + '\n' : up_label up_label := up03[1] ? up_label + t3 + '\n' : up_label up_label := up04[1] ? up_label + t4 + '\n' : up_label up_label := up05[1] ? up_label + t5 + '\n' : up_label up_label := up06[1] ? up_label + t6 + '\n' : up_label up_label := up07[1] ? up_label + t7 + '\n' : up_label up_label := up08[1] ? up_label + t8 + '\n' : up_label up_label := up09[1] ? up_label + t9 + '\n' : up_label up_label := up010[1] ? up_label + t10 + '\n' : up_label up_label := up011[1] ? up_label + t11 + '\n' : up_label up_label := up012[1] ? up_label + t12 + '\n' : up_label up_label := up013[1] ? up_label + t13 + '\n' : up_label up_label := up014[1] ? up_label + t14 + '\n' : up_label up_label := up015[1] ? up_label + t15 + '\n' : up_label up_label := up016[1] ? up_label + t16 + '\n' : up_label up_label := up017[1] ? up_label + t17 + '\n' : up_label up_label := up018[1] ? up_label + t18 + '\n' : up_label up_label := up019[1] ? up_label + t19 + '\n' : up_label up_label := up020[1] ? up_label + t20 + '\n' : up_label up_label := up021[1] ? up_label + t21 + '\n' : up_label up_label := up022[1] ? up_label + t22 + '\n' : up_label up_label := up023[1] ? up_label + t23 + '\n' : up_label up_label := up024[1] ? up_label + t24 + '\n' : up_label up_label := up025[1] ? up_label + t25 + '\n' : up_label up_label := up026[1] ? up_label + t26 + '\n' : up_label up_label := up027[1] ? up_label + t27 + '\n' : up_label up_label := up028[1] ? up_label + t28 + '\n' : up_label up_label := up029[1] ? up_label + t29 + '\n' : up_label up_label := up030[1] ? up_label + t30 + '\n' : up_label up_label := up031[1] ? up_label + t31 + '\n' : up_label up_label := up032[1] ? up_label + t32 + '\n' : up_label up_label := up033[1] ? up_label + t33 + '\n' : up_label up_label := up034[1] ? up_label + t34 + '\n' : up_label up_label := up035[1] ? up_label + t35 + '\n' : up_label up_label := up036[1] ? up_label + t36 + '\n' : up_label up_label := up037[1] ? up_label + t37 + '\n' : up_label up_label := up038[1] ? up_label + t38 + '\n' : up_label up_label := up039[1] ? up_label + t39 + '\n' : up_label up_label := up040[1] ? up_label + t40 + '\n' : up_label dn_label = 'Downtrend: \n' dn_label := dn01[1] ? dn_label + t1 + '\n' : dn_label dn_label := dn02[1] ? dn_label + t2 + '\n' : dn_label dn_label := dn03[1] ? dn_label + t3 + '\n' : dn_label dn_label := dn04[1] ? dn_label + t4 + '\n' : dn_label dn_label := dn05[1] ? dn_label + t5 + '\n' : dn_label dn_label := dn06[1] ? dn_label + t6 + '\n' : dn_label dn_label := dn07[1] ? dn_label + t7 + '\n' : dn_label dn_label := dn08[1] ? dn_label + t8 + '\n' : dn_label dn_label := dn09[1] ? dn_label + t9 + '\n' : dn_label dn_label := dn010[1] ? dn_label + t10 + '\n' : dn_label dn_label := dn011[1] ? dn_label + t11 + '\n' : dn_label dn_label := dn012[1] ? dn_label + t12 + '\n' : dn_label dn_label := dn013[1] ? dn_label + t13 + '\n' : dn_label dn_label := dn014[1] ? dn_label + t14 + '\n' : dn_label dn_label := dn015[1] ? dn_label + t15 + '\n' : dn_label dn_label := dn016[1] ? dn_label + t16 + '\n' : dn_label dn_label := dn017[1] ? dn_label + t17 + '\n' : dn_label dn_label := dn018[1] ? dn_label + t18 + '\n' : dn_label dn_label := dn019[1] ? dn_label + t19 + '\n' : dn_label dn_label := dn020[1] ? dn_label + t20 + '\n' : dn_label dn_label := dn021[1] ? dn_label + t21 + '\n' : dn_label dn_label := dn022[1] ? dn_label + t22 + '\n' : dn_label dn_label := dn023[1] ? dn_label + t23 + '\n' : dn_label dn_label := dn024[1] ? dn_label + t24 + '\n' : dn_label dn_label := dn025[1] ? dn_label + t25 + '\n' : dn_label dn_label := dn026[1] ? dn_label + t26 + '\n' : dn_label dn_label := dn027[1] ? dn_label + t27 + '\n' : dn_label dn_label := dn028[1] ? dn_label + t28 + '\n' : dn_label dn_label := dn029[1] ? dn_label + t29 + '\n' : dn_label dn_label := dn030[1] ? dn_label + t30 + '\n' : dn_label dn_label := dn031[1] ? dn_label + t31 + '\n' : dn_label dn_label := dn032[1] ? dn_label + t32 + '\n' : dn_label dn_label := dn033[1] ? dn_label + t33 + '\n' : dn_label dn_label := dn034[1] ? dn_label + t34 + '\n' : dn_label dn_label := dn035[1] ? dn_label + t35 + '\n' : dn_label dn_label := dn036[1] ? dn_label + t36 + '\n' : dn_label dn_label := dn037[1] ? dn_label + t37 + '\n' : dn_label dn_label := dn038[1] ? dn_label + t38 + '\n' : dn_label dn_label := dn039[1] ? dn_label + t39 + '\n' : dn_label dn_label := dn040[1] ? dn_label + t40 + '\n' : dn_label f_colorscr(_valscr) => _valscr ? #00000000 : na f_printscr(_txtscr) => var _lblscr = label(na) label.delete(_lblscr) _lblscr := label.new(time + (time - time[1]) * posX_scr, ohlc4[posY_scr], _txtscr, xloc.bar_time, yloc.price, f_colorscr(showscr), textcolor=showscr ? col : na, size=size.normal, style=label.style_label_center) _lblscr f_printscr(scr_label + '\n' + pot_label + '\n' + up_label + '\n' + dn_label)
Chanu Delta RSI Strategy
https://www.tradingview.com/script/VhxmxGuq/
chanu_lev10k
https://www.tradingview.com/u/chanu_lev10k/
85
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © chanu_lev10k //@version=5 strategy(title='Chanu Delta RSI Strategy', overlay=false) // Inputs sym_ref = input.symbol(title='BTCUSD reference market', defval='BYBIT:BTCUSDT') sym_amp = input.symbol(title='BTCUSD large amplitude market', defval='COINBASE:BTCUSD') src = input.source(title='Source', defval=close) res = input.timeframe(title='Resolution', defval='') isnorm = input.bool(title='Use Normalization of Chanu Delta ?', defval=true, tooltip='By dividing the original Chanu Delta value by the price of the reference Bitcoin market, it allows the Chanu Delta strategy to be universally used in the long term despite Bitcoin price fluctuations.') len = input.int(defval=4, title='Length of Chanu Delta RSI') bullLevel = input.int(title='Bull Level', defval=63, maxval=100, minval=0) bearLevel = input.int(title='Bear Level', defval=30, maxval=100, minval=0) highlightBreakouts = input(title='Highlight Bull/Bear Breakouts ?', defval=true) // Chanu Delta RSI Definition delta_f(res, src) => d = request.security(sym_amp, res, src) - request.security(sym_ref, res, src) n = d / request.security(sym_ref, res, src) * 100000 isnorm ? n : d delta = delta_f(res, src) delta_rsi = ta.rsi(delta, len) // Plot rcColor = delta_rsi > bullLevel ? #0ebb23 : delta_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 = delta_rsi > bullLevel and highlightBreakouts ? color.green : na bearFillColor = delta_rsi < bearLevel and highlightBreakouts ? color.red : na fill(maxBand, bullBand, color=color.new(bullFillColor, 80)) fill(minBand, bearBand, color=color.new(bearFillColor, 80)) plot(delta_rsi, title='Chanu Delta RSI', linewidth=2, color=rcColor) // Long Short conditions longCondition = ta.crossover(delta_rsi, bullLevel) if longCondition strategy.entry('Long', strategy.long) shortCondition = ta.crossunder(delta_rsi, bearLevel) if shortCondition strategy.entry('Short', strategy.short)
DayTradingFutures Cross-Strategy
https://www.tradingview.com/script/71UyePo4-DayTradingFutures-Cross-Strategy/
james4392010
https://www.tradingview.com/u/james4392010/
173
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/ // © james4392010 //@version=4 strategy(title="DayTradingFutures Cross-Strategy", overlay=true) // === GENERAL INPUTS === 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=true) //highlighting = input(title="Highlighter On/Off ?", type=input.bool, defval=true) 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 wmaFastSource = input(defval = close, title = "Fast WMA Source") wmaFastLength = input(defval = 5, title = "Fast WMA Period") wmaSlowSource = input(defval = close, title = "Slow WMA Source") wmaSlowLength = input(defval = 20, title = "Slow WMA Period") wmaDirectionSource = input(defval = close, title = "Trend 50 Period Source") wmaDirectionLength = input(defval = 50, title = "Trend 50 Period") timeinrange(res, sess) => time(res, sess) != 0 // === SERIES SETUP === /// a couple of ma's.. wmaFast = wma(close, 5) wmaSlow = wma(close, 20) wmaDirection = wma(close, 50) // === PLOTTING === fast = plot(series=wmaFast, color=color.white, linewidth=2) slow = plot(series=wmaSlow, color=color.yellow, linewidth=2) direction = plot(series=wmaDirection, color=color.red, linewidth=2) // === INPUT BACKTEST RANGE === //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 = 2022, title = "From Year", minval = 2022) // To Date Inputs //toDay = input(defval = 1, title = "To Day", minval = 1, maxval = 31) //toMonth = input(defval = 1, title = "To Month", minval = 1, maxval = 12) //toYear = input(defval = 2022, title = "To Year", minval = 2022) //startDate = timestamp(fromYear, fromMonth, fromDay) //finishDate = timestamp(toYear, toMonth, toDay) //inDateRange= (time >= fromDay, fromMonth, fromYear and time <= toDay, toMonth, toYear) // === FUNCTION EXAMPLE === //inDateRange = (time >= fromDay, fromMonth, fromYear) and (time <= toDay, toMonth, toYear) // === LOGIC === enterLong = crossover(wmaFast, wmaSlow) and close > wmaDirection and timeinrange(timeframe.period, "0900-1430") enterShort = crossunder(wmaFast, wmaSlow) and close < wmaDirection and timeinrange(timeframe.period, "0900-1430") //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_linebr, linewidth=2, color=color.green) buySignal = enterLong //plotshape(enterLong ? up : na, title="UpTrend Begins", location=location.absolute, style=shape.circle, size=size.tiny, color=color.green) plotshape(enterLong and showsignals ? up : na, title="Buy", text="Buy", location=location.absolute, style=shape.labelup, size=size.tiny, color=color.green, textcolor=color.white) //dnPlot = plot(trend == 1 ? na : dn, title="Down Trend", style=plot.style_linebr, linewidth=2, color=color.red) sellSignal = enterShort //plotshape(enterShort ? dn : na, title="DownTrend Begins", location=location.absolute, style=shape.circle, size=size.tiny, color=color.red) plotshape(enterShort and showsignals ? dn : na, title="Sell", text="Sell", location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.red, textcolor=color.white) //mPlot = plot(ohlc4, title="", style=plot.style_circles, linewidth=0) //longFillColor = highlighting ? (trend == 1 ? color.green : color.white) : color.white //shortFillColor = highlighting ? (trend == -1 ? color.red : color.white) : color.white //fill(mPlot, upPlot, title="UpTrend Highligter", color=longFillColor) //fill(mPlot, dnPlot, title="DownTrend Highligter", color=shortFillColor) alertcondition(buySignal, title="Buy", message="Buy!") alertcondition(sellSignal, title="Sell", message="Sell!") //changeCond = trend != trend[1] //alertcondition(changeCond, title="SuperTrend Direction Change", message="SuperTrend has changed direction!") // Entry for strategy // //tp=input(25,title="TakeProfit") //sl=input(40,title="StopLoss") //strategy.entry("Long",1, when=enterLong) //strategy.exit("Exit",profit=tp,loss=sl) //strategy.exit("TakeProfit",profit=tp) //strategy.exit("StopLoss",loss=sl) //strategy.entry("Short",1, when=enterShort) //strategy.exit("Exit",profit=tp,loss=sl) //strategy.exit("TakeProfit",profit=tp) //strategy.exit("StopLoss",loss=sl) //strategy.exit("Exit", wmaFastwmaSlow) //Buy and Sell Signals //strategy.close_all(when =not timeinrange(timeframe.period, "1000-1430")) // === FILL ==== fill (fast, slow, color = wmaSlow > wmaDirection ? color.green : color.red) //fill(when=enterLong, tp, color = color.new(color.green, 90), title = "Profit area") //fill(when=enterLong, sl, color = color.new(color.red, 90), title = "Loss area") //fill(when=enterShort, tp, color = color.new(color.green, 90), title = "Profit area") //fill(when=enterShort, sl, color = color.new(color.red, 90), title = "Loss area")
Follow the Crypto Shorts
https://www.tradingview.com/script/gllD36NB-Follow-the-Crypto-Shorts/
xtradernet
https://www.tradingview.com/u/xtradernet/
44
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/ // © xtradernet //@version=4 // This script allows to backtest the impact of variations in the number of BTCUSD Shorts Positions on its price. strategy("Follow the Crypto Shorts", shorttitle="FollowBTCShorts", overlay=true) length = input(50, type=input.integer, title="BTC Shorts SMA Length") expr = sma(close, length) BTCShorts = security("BTCUSDSHORTS", "D", close) BTCShortsMA = security("BTCUSDSHORTS", "D", expr) if crossunder(BTCShorts, BTCShortsMA) strategy.entry("Long", strategy.long, comment="Shorts Out") strategy.close("Long", when=crossover(BTCShorts, BTCShortsMA), comment="Shorts In")
Bollinger Stop Strategy
https://www.tradingview.com/script/jCFatPh6-bollinger-stop-strategy/
ROBO_Trading
https://www.tradingview.com/u/ROBO_Trading/
661
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/ // © ROBO_Trading //@version=5 strategy(title = "Bollinger Stop Strategy", shorttitle = "BBStop", overlay = true, default_qty_type = strategy.percent_of_equity, initial_capital = 10000, default_qty_value = 100, commission_value = 0.1) //Settings long = input(true) short = input(true) length = input.int(20, minval=1) mult = input.float(2.0, minval=0.001, maxval=50) source = input(close) showbb = input(true, title = "Show Bollinger Bands") showof = input(true, title = "Show Offset") startTime = input.time(defval = timestamp("01 Jan 2000 00:00 +0000"), title = "Start Time", inline = "time1") finalTime = input.time(defval = timestamp("31 Dec 2099 23:59 +0000"), title = "Final Time", inline = "time1") //Bollinger Bands basis = ta.sma(source, length) dev = mult * ta.stdev(source, length) upper = basis + dev lower = basis - dev //Show indicator offset = showof ? 1 : 0 colorBasis = showbb ? color.gray : na colorUpper = showbb ? color.blue : na colorLower = showbb ? color.blue : na colorBands = showbb ? color.blue : na p0 = plot(basis, "Basis", color = colorBasis, offset = offset) p1 = plot(upper, "Upper", color = colorUpper, offset = offset) p2 = plot(lower, "Lower", color = colorLower, offset = offset) fill(p1, p2, title = "Background", color = colorBands, transp = 90) //Trading truetime = time > startTime and time < finalTime if basis > 0 and truetime if long strategy.entry("Long", strategy.long, stop = upper, when = truetime) if short strategy.entry("Short", strategy.short, stop = lower, when = truetime) if long == false strategy.exit("Exit", "Short", stop = upper) if short == false strategy.exit("Exit", "Long", stop = lower) if time > finalTime strategy.close_all()
Overnight Gap Analysis
https://www.tradingview.com/script/rEZ9Pggd-Overnight-Gap-Analysis/
TradeAutomation
https://www.tradingview.com/u/TradeAutomation/
150
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="Overnight Gap Analysis", shorttitle="Overnight Gap Analysis", process_orders_on_close=true, calc_on_every_tick=false, overlay=true, commission_type=strategy.commission.cash_per_order, commission_value=1, slippage=0, initial_capital = 100000, default_qty_type=strategy.percent_of_equity, default_qty_value=100) // Default settings are for a 1 hour chart in a market that has 7 bars per day. The number of bars on the chart per day must be adjusted with an input for the script to work on other types of charts/markets. // Script Date Range Inputs StartTime = input.time(defval=timestamp('01 Jan 2010 05:00 +0000'), group="Script Date Range Settings", title='Start Time') EndTime = input.time(defval=timestamp('01 Jan 2099 00:00 +0000'), group="Script Date Range Settings", title='End Time') InDateRange = time>=StartTime and time<=EndTime // Identifies the Last Bar of the Day var todaybarcount = 0 todaybarcount := close and not ta.change(time_tradingday) ? todaybarcount + 1 : ta.change(time_tradingday) ? 1 : todaybarcount[1] // Calculates Trigger and Filter Criteria LongTrigger = todaybarcount==input.int(7, "Number of Bars on Your Chart Per Day", tooltip="This is used to identify the last bar of the day. A Long order is placed on the close of this bar") EMAFilterInput = input.bool(false, "Only Enter Trade if Above EMA?") EMAFilter = close>ta.ema(close, input.int(1400, "EMA Qual Length")) EnteredLastBar = ta.crossover(strategy.position_size, 0.5) ? 1 : 0 // Entry and Exit Functions if (InDateRange and EMAFilterInput==true) strategy.entry("Long", strategy.long, when = LongTrigger and EMAFilter, alert_message="Buy") if (InDateRange and EMAFilterInput==false) strategy.entry("Long", strategy.long, when = LongTrigger, alert_message="Buy") if (InDateRange) strategy.close("Long", when = EnteredLastBar==1)