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
EMA+RSI Pump & Drop Swing Sniper (SL+TP) - Strategy
https://www.tradingview.com/script/83Ijv4aU-EMA-RSI-Pump-Drop-Swing-Sniper-SL-TP-Strategy/
mmoiwgg
https://www.tradingview.com/u/mmoiwgg/
391
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/ // Β© mmoiwgg //@version=4 strategy(title="EMA+RSI Pump & Drop Swing Sniper (With Alerts & SL+TP) - Strategy", shorttitle="EMA+RSI Swing Strategy", overlay=true) emaLength = input(title="EMA Length", type=input.integer, defval=50, minval=0) emarsiSource = input(close, title="EMA+RSI Source") condSource = input(high, title="Long+Short Condition Source") emaVal = ema(emarsiSource, emaLength) rsiLength = input(title="RSI Length", type=input.integer, defval=25, minval=0) rsiVal = rsi(emarsiSource, rsiLength) //Safety emaLength2 = input(title="Safety EMA Length", type=input.integer, defval=70, minval=0) emaSource2 = input(close, title="Safety EMA Source") ema = ema(emaSource2, emaLength2) emaColorSource2 = close emaBSource2 = close // Backtest+Dates FromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12) FromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31) FromYear = input(defval = 2019, title = "From Year", minval = 2017) 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 = 2017) showDate = input(defval = true, title = "Show Date Range", type = input.bool) start = timestamp(FromYear, FromMonth, FromDay, 00, 00) // backtest start window finish = timestamp(ToYear, ToMonth, ToDay, 23, 59) // backtest end window window() => time >= start and time <= finish ? true : false // create function - add window() to entry/exit/close // Conditions exit_long = crossover(emaVal, condSource) longCond = crossunder(emaVal, condSource) and close > ema //Stoploss + TakeProfit sl = input(0.051, step=0.001, title="Stop Loss") tp = input(0.096, step=0.001, title="Take Profit") // Plots Colors colors = emarsiSource > emaVal and rsiVal > 14 ? color.green : color.red emaColorSource = input(close, title="Line Color Source") emaBSource = input(close, title="Line Color B Source") // Plots plot(ema, color=emaColorSource2[1] > ema and emaBSource2 > ema ? color.green : color.red, linewidth=1) plot(emaVal, color=emaColorSource[1] > emaVal and emaBSource > emaVal ? color.green : color.red, linewidth=3) plotcandle(open, high, low, close, color=colors) //Strategy Entry+Exits strategy.entry("long",1,when=window() and longCond) strategy.close("long",when=window() and exit_long) strategy.exit("long tp/sl", "long", profit = close * tp / syminfo.mintick, loss = close * sl / syminfo.mintick)
Fibonacci EMA averages (21, 34, 55, 89, 144)
https://www.tradingview.com/script/8qUg9GwB-Fibonacci-EMA-averages-21-34-55-89-144/
h311m4n
https://www.tradingview.com/u/h311m4n/
54
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/ // Β© h311m4n //@version=4 strategy("Fibonacci EMA averages",overlay=true) ema21 = 21 ema34 = 34 ema55 = 55 ema89 = 89 ema144 = 144 ema_21 = ema(close, ema21) ema_34 = ema(close, ema34) ema_55 = ema(close, ema55) ema_89 = ema(close, ema89) ema_144 = ema(close, ema144) plot(ema_21, color=color.red) plot(ema_34, color=color.yellow) plot(ema_55, color=color.green) plot(ema_89, color=color.blue) plot(ema_144, color=color.fuchsia)
All in One Strategy no RSI Label - For higher dollar crypto
https://www.tradingview.com/script/DxZ60Wla-All-in-One-Strategy-no-RSI-Label-For-higher-dollar-crypto/
Solutions1978
https://www.tradingview.com/u/Solutions1978/
345
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ //@version=4 // β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•— β–ˆβ–ˆβ•— //β–ˆβ–ˆβ•”β•β•β•β•β•β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β•β•β•β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β•šβ•β•β–ˆβ–ˆβ•”β•β•β•β–ˆβ–ˆβ•”β•β•β•β•β•β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•— β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β•šβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•”β• //β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β• β•šβ–ˆβ–ˆβ–ˆβ–ˆβ•”β• //β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β• β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β•β•β• β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•— β•šβ–ˆβ–ˆβ•”β• //β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β• β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β• β–ˆβ–ˆβ•‘ // β•šβ•β•β•β•β•β•β•šβ•β• β•šβ•β•β•šβ•β•β•β•β•β•β•β•šβ•β• β•šβ•β• β•šβ•β• β•šβ•β•β•β•β•β•β•β•šβ•β•β•β•β•β• β•šβ•β•β•β•β•β• β•šβ•β• //β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•— β–ˆβ–ˆβ•— β–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— //β–ˆβ–ˆβ•”β•β•β•β•β•β–ˆβ–ˆβ•”β•β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β•šβ•β•β–ˆβ–ˆβ•”β•β•β•β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β•β•β•β–ˆβ–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β•šβ•β•β•β•β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•— //β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β–ˆβ–ˆβ•— β–ˆβ–ˆβ•‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β•šβ–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β•β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β• //β•šβ•β•β•β•β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘β•šβ•β•β•β•β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β•šβ•β•β•β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β• β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•— //β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β• β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ•‘ β•šβ–ˆβ–ˆβ–ˆβ–ˆβ•‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β• β–ˆβ–ˆβ•‘ β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β• //β•šβ•β•β•β•β•β•β• β•šβ•β•β•β•β•β• β•šβ•β•β•β•β•β•β• β•šβ•β•β•β•β•β• β•šβ•β• β•šβ•β• β•šβ•β•β•β•β•β• β•šβ•β• β•šβ•β•β•β•β•šβ•β•β•β•β•β•β• β•šβ•β• β•šβ•β•β•β•β• β•šβ•β• β•šβ•β•β•β•β• strategy(shorttitle='Ain1 No Label',title='All in One Strategy no RSI Label', overlay=true, scale=scale.left, initial_capital = 1000, process_orders_on_close=true, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type=strategy.commission.percent, commission_value=0.18, calc_on_every_tick=true) kcolor = color.new(#0094FF, 60) dcolor = color.new(#FF6A00, 60) // ----------------- Strategy Inputs ------------------------------------------------------------- //Backtest dates with auto finish date of today start = input(defval = timestamp("01 April 2021 00:00 -0500"), title = "Start Time", type = input.time) finish = input(defval = timestamp("31 December 2021 00:00 -0600"), title = "End Time", type = input.time) window() => time >= start and time <= finish ? true : false // create function "within window of time" // Strategy Selection - Long, Short, or Both stratinfo = input(true, "Long/Short for Mixed Market, Long for Bull, Short for Bear") strat = input(title="Trade Types", defval="Long/Short", options=["Long Only", "Long/Short", "Short Only"]) strat_val = strat == "Long Only" ? 1 : strat == "Long/Short" ? 0 : -1 // Risk Management Inputs sl= input(10.0, "Stop Loss %", minval = 0, maxval = 100, step = 0.01) stoploss = sl/100 tp = input(20.0, "Target Profit %", minval = 0, maxval = 100, step = 0.01) TargetProfit = tp/100 useXRSI = input(false, "Use RSI crossing back, select only one strategy") useCRSI = input(false, "Use Tweaked Connors RSI, select only one") RSIInfo = input(true, "These are the RSI Strategy Inputs, RSI Length applies to MACD, set OB and OS to 45 for using Stoch and EMA strategies.") length = input(14, "RSI Length", minval=1) overbought= input(62, "Overbought") oversold= input(35, "Oversold") cl1 = input(3, "Connor's MA Length 1", minval=1, step=1) cl2 = input(20, "Connor's MA Lenght 2", minval=1, step=1) cl3 = input(50, "Connor's MA Lenght 3", minval=1, step=1) // MACD and EMA Inputs useMACD = input(false, "Use MACD Only, select only one strategy") useEMA = input(false, "Use EMA Only, select only one strategy (EMA uses Stochastic inputs too)") MACDInfo=input(true, "These are the MACD strategy variables") fastLength = input(5, minval=1, title="EMA Fast Length") slowLength = input(10, minval=1, title="EMA Slow Length") ob_min = input(52, "Overbought Lookback Minimum Value", minval=0, maxval=200) ob_lb = input(25, "Overbought Lookback Bars", minval=0, maxval=100) os_min = input(50, "Oversold Lookback Minimum Value", minval=0, maxval=200) os_lb = input(35, "Oversold Lookback Bars", minval=0, maxval=100) source = input(title="Source", type=input.source, defval=close) RSI = rsi(source, length) // Price Movement Inputs PriceInfo = input(true, "Price Change Percentage Cross Check Inputs for all Strategies, added logic to avoid early sell") lkbk = input(5,"Max Lookback Period") // EMA and SMA Background Inputs useStoch = input(false, "Use Stochastic Strategy, choose only one") StochInfo = input(true, "Stochastic Strategy Inputs") smoothK = input(3, "K", minval=1) smoothD = input(3, "D", minval=1) k_mode = input("SMA", "K Mode", options=["SMA", "EMA", "WMA"]) high_source = input(high,"High Source") low_source= input(low,"Low Source") HTF = input("","Curernt or Higher time frame only", type=input.resolution) // Selections to show or hide the overlays showZones = input(true, title="Show Bullish/Bearish Zones") showStoch = input(true, title="Show Stochastic Overlays") showRSIBS = input(true, title="Show RSI Buy Sell Zones") showMACD = input(true, title="Show MACD") color_bars=input(true, "Color Bars") // ------------------ Dynamic RSI Calculation ---------------------------------------- AvgHigh(src,cnt,val) => total = 0.0 count = 0 for i = 0 to cnt if src[i] > val count := count + 1 total := total + src[i] round(total / count) RSI_high = AvgHigh(RSI, ob_lb, ob_min) AvgLow(src,cnt,val) => total = 0.0 count = 0 for i = 0 to cnt if src[i] < val count := count + 1 total := total + src[i] round(total / count) RSI_low = AvgLow(RSI, os_lb, os_min) // ------------------ Price Percentage Change Calculation ----------------------------------------- perc_change(lkbk) => overall_change = ((close[0] - open[lkbk]) / open[lkbk]) * 100 highest_high = 0.0 lowest_low = 0.0 for i = lkbk to 0 highest_high := i == lkbk ? high : high[i] > high[(i + 1)] ? high[i] : highest_high[1] lowest_low := i == lkbk ? low : low[i] < low[(i + 1)] ? low[i] : lowest_low[1] start_to_high = ((highest_high - open[lkbk]) / open[lkbk]) * 100 start_to_low = ((lowest_low - open[lkbk]) / open[lkbk]) * 100 previous_to_high = ((highest_high - open[1])/open[1])*100 previous_to_low = ((lowest_low-open[1])/open[1])*100 previous_bar = ((close[1]-open[1])/open[1])*100 [overall_change, start_to_high, start_to_low, previous_to_high, previous_to_low, previous_bar] // Call the function [overall, to_high, to_low, last_high, last_low, last_bar] = perc_change(lkbk) // Plot the function //plot(overall*50, color=color.white, title='Overall Percentage Change', linewidth=3) //plot(to_high*50, color=color.green,title='Percentage Change from Start to High', linewidth=2) //plot(to_low*50, color=color.red, title='Percentage Change from Start to Low', linewidth=2) //plot(last_high*100, color=color.teal, title="Previous to High", linewidth=2) //plot(last_low*100, color=color.maroon, title="Previous to Close", linewidth=2) //plot(last_bar*100, color=color.orange, title="Previous Bar", linewidth=2) //hline(0, title='Center Line', color=color.orange, linewidth=2) true_dip = overall < 0 and to_high > 0 and to_low < 0 and last_high > 0 and last_low < 0 and last_bar < 0 true_peak = overall > 0 and to_high > 0 and to_low > 0 and last_high > 0 and last_low < 0 and last_bar > 0 alertcondition(true_dip, title='True Dip', message='Dip') alertcondition(true_peak, title='True Peak', message='Peak') // ------------------ Background Colors based on EMA Indicators ----------------------------------- // Uses standard lengths of 9 and 21, if you want control delete the constant definition and uncomment the inputs haClose(gap) => (open[gap] + high[gap] + low[gap] + close[gap]) / 4 rsi_ema = rsi(haClose(0), length) v2 = ema(rsi_ema, length) v3 = 2 * v2 - ema(v2, length) emaA = ema(rsi_ema, fastLength) emaFast = 2 * emaA - ema(emaA, fastLength) emaB = ema(rsi_ema, slowLength) emaSlow = 2 * emaB - ema(emaB, slowLength) //plot(rsi_ema, color=color.white, title='RSI EMA', linewidth=3) //plot(v2, color=color.green,title='v2', linewidth=2) //plot(v3, color=color.red, title='v3', linewidth=2) //plot(emaFast, color=color.teal, title="EMA Fast", linewidth=2) //plot(emaSlow, color=color.maroon, title="EMA Slow", linewidth=2) EMABuy = crossunder(emaFast, v2) and window() EMASell = crossover(emaFast, emaSlow) and window() alertcondition(EMABuy, title='EMA Buy', message='EMA Buy Condition') alertcondition(EMASell, title='EMA Sell', message='EMA Sell Condition') // bullish signal rule: bullishRule =emaFast > emaSlow // bearish signal rule: bearishRule =emaFast < emaSlow // current trading State ruleState = 0 ruleState := bullishRule ? 1 : bearishRule ? -1 : nz(ruleState[1]) ruleColor = ruleState==1 ? color.new(color.blue, 90) : ruleState == -1 ? color.new(color.red, 90) : ruleState == 0 ? color.new(color.gray, 90) : na bgcolor(showZones ? ruleColor : na, title="Bullish/Bearish Zones") // ------------------ Stochastic Indicator Overlay ----------------------------------------------- // Calculation // Use highest highs and lowest lows h_high = highest(high_source ,lkbk) l_low = lowest(low_source ,lkbk) stoch = stoch(RSI, RSI_high, RSI_low, length) k = k_mode=="EMA" ? ema(stoch, smoothK) : k_mode=="WMA" ? wma(stoch, smoothK) : sma(stoch, smoothK) d = sma(k, smoothD) k_c = change(k) d_c = change(d) kd = k - d // Plot signalColor = k>oversold and d<overbought and k>d and k_c>0 and d_c>0 ? kcolor : k<overbought and d>oversold and k<d and k_c<0 and d_c<0 ? dcolor : na kp = plot(showStoch ? k : na, "K", color=kcolor) dp = plot(showStoch ? d : na, "D", color=dcolor) fill(kp, dp, color = signalColor, title="K-D") signalUp = showStoch ? not na(signalColor) and kd>0 : na signalDown = showStoch ? not na(signalColor) and kd<0 : na //plot(signalUp ? kd : na, "Signal Up", color=kcolor, transp=90, style=plot.style_columns) //plot(signalDown ? (kd+100) : na , "Signal Down", color=dcolor, transp=90, style=plot.style_columns, histbase=100) //StochBuy = crossover(k, d) and kd>0 and to_low<0 and window() //StochSell = crossunder(k,d) and kd<0 and to_high>0 and window() StochBuy = crossover(k, d) and window() StochSell = crossunder(k, d) and window() alertcondition(StochBuy, title='Stoch Buy', message='K Crossing D') alertcondition(StochSell, title='Stoch Sell', message='D Crossing K') // -------------- Add Price Movement ------------------------- // Calculations h1 = vwma(high, length) l1 = vwma(low, length) hp = h_high[1] lp = l_low[1] // Plot var plot_color=#353535 var sig = 0 if (h1 >hp) sig:=1 plot_color:=color.lime else if (l1 <lp) sig:=-1 plot_color:=color.maroon //plot(1,title = "Price Movement Bars", style=plot.style_columns,color=plot_color) //plot(sig,title="Signal 1 or -1",display=display.none) // --------------------------------------- RSI Plot ---------------------------------------------- // Plot Oversold and Overbought Lines over = hline(oversold, title="Oversold", color=color.green) under = hline(overbought, title="Overbought", color=color.red) fillcolor = color.new(#9915FF, 90) fill(over, under, fillcolor, title="Band Background") // Show RSI and EMA crosses with arrows and RSI Color (tweaked Connors RSI) // Improves strategy setting ease by showing where EMA 5 crosses EMA 10 from above to confirm overbought conditions or trend reversals // This shows where you should enter shorts or exit longs // Tweaked Connors RSI Calculation connor_ob = overbought connor_os = oversold ma1 = sma(close,cl1) ma2 = sma(close, cl2) ma3 = sma(close, cl3) // Buy Sell Zones using tweaked Connors RSI (RSI values of 80 and 20 for Crypto as well as ma3, ma20, and ma50 are the tweaks) RSI_SELL = ma1 > ma2 and open > ma3 and RSI >= connor_ob and true_peak and window() RSI_BUY = ma2 < ma3 and ma3 > close and RSI <= connor_os and true_dip and window() alertcondition(RSI_BUY, title='Connors Buy', message='Connors RSI Buy') alertcondition(RSI_SELL, title='Connors Sell', message='Connors RSI Sell') // Color Definition col = useCRSI ? (close > ma2 and close < ma3 and RSI <= connor_os ? color.lime : close < ma2 and close > ma3 and RSI <= connor_ob ? color.red : color.yellow ) : color.yellow // Plot colored RSI Line plot(RSI, title="RSI", linewidth=3, color=col) //------------------- MACD Strategy ------------------------------------------------- [macdLine, signalLine, _] = macd(close, fastLength, slowLength, length) bartrendcolor = macdLine > signalLine and k > 50 and RSI > 50 ? color.teal : macdLine < signalLine and k < 50 and RSI < 50 ? color.maroon : macdLine < signalLine ? color.yellow : color.gray barcolor(color = color_bars ? bartrendcolor : na) MACDBuy = macdLine>signalLine and RSI<RSI_low and overall<0 and window() MACDSell = macdLine<signalLine and RSI>RSI_high and overall>0 and window() //plotshape(showMACD ? MACDBuy: na, title = "MACD Buy", style = shape.arrowup, text = "MACD Buy", color=color.green, textcolor=color.green, size=size.small) //plotshape(showMACD ? MACDSell: na, title = "MACD Sell", style = shape.arrowdown, text = "MACD Sell", color=color.red, textcolor=color.red, size=size.small) MACColor = MACDBuy ? color.new(color.teal, 50) : MACDSell ? color.new(color.maroon, 50) : na bgcolor(showMACD ? MACColor : na, title ="MACD Signals") // -------------------------------- Entry and Exit Logic ------------------------------------ // Entry Logic XRSI_OB = crossunder(RSI, overbought) and overall<0 and window() RSI_OB = RSI>overbought and true_peak and window() XRSI_OS = crossover(RSI, oversold) and overall>0 and window() RSI_OS = RSI<oversold and true_dip and window() alertcondition(XRSI_OB, title='Reverse RSI Sell', message='RSI Crossing back under OB') alertcondition(XRSI_OS, title='Reverse RSI Buy', message='RSI Crossing back over OS') alertcondition(RSI_OS, title='RSI Buy', message='RSI Crossover OS') alertcondition(RSI_SELL, title='RSI Sell', message='RSI Crossunder OB') // Strategy Entry and Exit with built in Risk Management GoLong = strategy.position_size==0 and strat_val > -1 and rsi_ema > RSI and k < d ? (useXRSI ? XRSI_OS : useMACD ? MACDBuy : useCRSI ? RSI_BUY : useStoch ? StochBuy : RSI_OS) : false GoShort = strategy.position_size==0 and strat_val < 1 and rsi_ema < RSI and d < k ? (useXRSI ? XRSI_OB : useMACD ? MACDSell : useCRSI ? RSI_SELL : useStoch ? StochSell : RSI_OB) : false if (GoLong) strategy.entry("LONG", strategy.long) if (GoShort) strategy.entry("SHORT", strategy.short) longStopPrice = strategy.position_avg_price * (1 - stoploss) longTakePrice = strategy.position_avg_price * (1 + TargetProfit) shortStopPrice = strategy.position_avg_price * (1 + stoploss) shortTakePrice = strategy.position_avg_price * (1 - TargetProfit) //plot(series=(strategy.position_size > 0) ? longTakePrice : na, color=color.green, style=plot.style_circles, linewidth=3, title="Long Take Profit") //plot(series=(strategy.position_size < 0) ? shortTakePrice : na, color=color.green, style=plot.style_circles, linewidth=3, title="Short Take Profit") //plot(series=(strategy.position_size > 0) ? longStopPrice : na, color=color.red, style=plot.style_cross, linewidth=2, title="Long Stop Loss") //plot(series=(strategy.position_size < 0) ? shortStopPrice : na, color=color.red, style=plot.style_cross, linewidth=2, title="Short Stop Loss") if (strategy.position_size > 0) strategy.exit(id="Exit Long", from_entry = "LONG", stop = longStopPrice, limit = longTakePrice) if (strategy.position_size < 0) strategy.exit(id="Exit Short", from_entry = "SHORT", stop = shortStopPrice, limit = shortTakePrice) CloseLong = strat_val > -1 and strategy.position_size > 0 and rsi_ema > RSI and d > k ? (useXRSI ? XRSI_OB : useMACD ? MACDSell : useCRSI ? RSI_SELL : RSI_OB) : false if(CloseLong) strategy.close("LONG") CloseShort = strat_val < 1 and strategy.position_size < 0 and rsi_ema < RSI and k > d ? (useXRSI ? XRSI_OS : useMACD ? MACDBuy : useCRSI ? RSI_BUY : RSI_OS) : false if(CloseShort) strategy.close("SHORT")
Yusram Mount MaV - Day MaV CrossOver Strgty
https://www.tradingview.com/script/pwk0oi8y/
dadashkadir
https://www.tradingview.com/u/dadashkadir/
215
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© dadashkadir //@version=4 strategy("Mount MaV - Day MaV CrossOver Strgty", shorttitle="Yusram Str.", overlay=true) src = input(title= "Kaynak", type=input.source, defval=close) mav = input(title="Hareketli Ortlama Tipi", defval="SMA", options=["SMA", "EMA", "WMA"]) Gbar = input(title="GΓΌnlΓΌk Bar SayΔ±sΔ±", defval=7, minval=1, maxval=999) Abar = input(title="AylΔ±k Bar SayΔ±sΔ±", defval=5, minval=1, maxval=999) //displacement = input(20, minval=1, title="Displacement") getMA(src, length) => ma = 0.0 if mav == "SMA" ma := sma(src, length) ma if mav == "EMA" ma := ema(src, length) ma if mav == "WMA" ma := wma(src, length) ma ma long = "M" //AylΔ±k ln = security(syminfo.ticker, long, src) lnma = getMA(ln, Abar) gnma = getMA(src, Gbar) col1= gnma>gnma[1] col3= gnma<gnma[1] colorM = col1 ? color.green : col3 ? color.navy : color.yellow l1 = plot(lnma, title="MhO", trackprice = true, style=plot.style_line, color=color.red, linewidth=3) l2 = plot(gnma, title="DhO", trackprice = true, style=plot.style_line, color=colorM, linewidth=3) fill(l1, l2, color = lnma < gnma ? color.green : color.red, title="GΓΆlgelendirme", transp=90) zamanaralik = input (2020, title="Backtest BaşlangΔ±Γ§ Tarihi") al = crossover (gnma, lnma) and zamanaralik <= year sat = crossover (lnma, gnma) and zamanaralik <= year plotshape(al, title = "Giriş", text = 'Al', style = shape.labelup, location = location.belowbar, color= color.green, textcolor = color.white, transp = 0, size = size.tiny) plotshape(sat, title = "Γ‡Δ±kış", text = 'Sat', style = shape.labeldown, location = location.abovebar, color= color.red, textcolor = color.white, transp = 0, size = size.tiny) FromDay = input(defval = 1, title = "Str. Başlama Tarihi GΓΌn", minval = 1, maxval = 31) FromMonth = input(defval = 1, title = "Str. Başlama Tarihi Ay", minval = 1, maxval = 12) FromYear = input(defval = 2015, title = "Str. Başlama Tarihi YΔ±l", minval = 2005) ToDay = input(defval = 1, title = "Str. Bitiş Tarihi GΓΌn", minval = 1, maxval = 31) ToMonth = input(defval = 1, title = "Str. Bitiş Tarihi Ay", minval = 1, maxval = 12) ToYear = input(defval = 9999, title = "Str. Bitiş Tarihi YΔ±l", 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 al strategy.entry("Al", strategy.long, when=Timerange()) if sat strategy.entry("Sat", strategy.short, when=Timerange())
ChBrkOutStrategySMA
https://www.tradingview.com/script/Q68bqBap-ChBrkOutStrategySMA/
anshuanshu333
https://www.tradingview.com/u/anshuanshu333/
45
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/ // Β© anshuanshu333 //@version=4 strategy("ChBrkOutStrategySMA", overlay=true, initial_capital = 200000) length = input(title="Length", type=input.integer, minval=1, maxval=1000, defval=7) fastSMA = sma(close,9) slowSMA = sma(close,21) upBound = highest(high, length) downBound = lowest(low, length) boundLongEntry = ((close >= upBound) or (high >= upBound)) and fastSMA>slowSMA and (close > open) boundShortEntry =((close <= downBound) or (low <= downBound)) and fastSMA<slowSMA and (close <open) u=plot(upBound, title = "Upper Bound",color=color.blue, linewidth=1) l=plot(downBound, title = "Lower Bound",color=color.red, linewidth=1) plot(fastSMA,title = "Fast SMA", color = color.red, linewidth =2) plot(slowSMA,title = "Slow SMA" ,color = color.green, linewidth =1) fill(u,l, transp=95) plot(avg(upBound,downBound), title = "Avg", color=color.gray,linewidth =1) if (boundLongEntry ) strategy.entry("LE", long = true) if (boundShortEntry) strategy.entry("SE", long = false) SmaLongExit = crossunder(fastSMA,slowSMA) SmaShortExit = crossover(fastSMA,slowSMA) //Close TRades if (strategy.position_size > 0) strategy.close(id="LE",when= SmaLongExit) if (strategy.position_size < 0) strategy.close(id="SE",when= SmaShortExit)
KSR Strategy
https://www.tradingview.com/script/N2c1PkLs-KSR-Strategy/
greadandfear
https://www.tradingview.com/u/greadandfear/
948
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/ // Β© askkuldeeprandhawa //@version=4 strategy("KSR Strategy", overlay=true) par1=input(10) par2=input(20) ema1=ema(close,par1) ema2=ema(close,par2) buy=ema1>ema2 sell=ema2<ema1 mycolor= iff(buy,color.green,iff(sell,color.blue,color.red)) barcolor(color=mycolor) ema100=ema(close,100) ibuy=crossover(ema1,ema2) iSell=crossunder(ema1,ema2) varp=tostring(close[1]) plotshape(ibuy, "Up Arrow", shape.triangleup, location.belowbar, color.green, 0, 0,"Buy" , color.green, true, size.tiny) plotshape(iSell, "Down Arrow", shape.triangledown, location.abovebar, color.red, 0, 0, "Sell", color.red, true, size.tiny) crossed =crossover(ema(close,par1), ema(close,par2)) if crossed l = label.new(bar_index, na, tostring(close), color=color.green, textcolor=color.white, style=label.style_labelup, yloc=yloc.belowbar) crossed2 =crossunder(ema(close,par1), ema(close,par2)) if crossed2 l = label.new(bar_index, na, tostring(close), color=color.red, textcolor=color.white, style=label.style_labeldown, yloc=yloc.abovebar) plot(ema(close,par1),"EMA Short",color=color.white) plot(ema(close,par2),"EMA Long",color=color.orange) longCondition = crossover(ema(close, par1), ema(close, par2)) if (longCondition) strategy.entry("My Long Entry Id", strategy.long) shortCondition = crossunder(ema(close, par1), ema(close, par2)) if (shortCondition) strategy.entry("My Short Entry Id", strategy.short) ma1_len = input(title="MA1", type=input.integer, defval=8, minval=1, maxval=100, step=1) ma2_len = input(title="MA2", type=input.integer, defval=12, minval=1, maxval=100, step=1) o = ema(open, ma1_len) c = ema(close, ma1_len) h = ema(high, ma1_len) l = ema(low, ma1_len) tim1=input('D',"Short Time") tim2=input('W',"Long Time") ema_p=input(title="EMA Period", type=input.integer, defval=16, minval=1, maxval=100, step=1) refma = ema(close, ema_p) plot(refma, title="EMA" , linewidth=1, color=close < refma ? color.orange : color.blue) ha_t = heikinashi(syminfo.tickerid) ha_o = security(ha_t, tim2, o) ha_c = security(ha_t, tim2, c) ha_h = security(ha_t, tim2, h) ha_l = security(ha_t, tim2, l) o2 = ema(ha_o, ma2_len) c2 = ema(ha_c, ma2_len) h2 = ema(ha_h, ma2_len) l2 = ema(ha_l, ma2_len) ha_col = ha_c > ha_o ? color.red : color.green plotshape(true, style=shape.circle, color=ha_c > ha_o ? color.green : color.red, location=location.bottom) ha_t1 = heikinashi(syminfo.tickerid) ha_o1 = security(ha_t1, tim1, o) ha_c1 = security(ha_t1, tim1, c) ha_h1 = security(ha_t1, tim1, h) ha_l1 = security(ha_t1, tim1, l) o3 = ema(ha_o1, ma2_len) c3 = ema(ha_c1, ma2_len) h3 = ema(ha_h1, ma2_len) l3 = ema(ha_l1, ma2_len) ha_col1 = ha_c1 > ha_o1 ? color.red : color.green plotshape(true, style=shape.circle, color=ha_c1 > ha_o1 ? color.green : color.red, location=location.top)
Bear & Bull Zone Signal Strategy
https://www.tradingview.com/script/r8SlI9zT-Bear-Bull-Zone-Signal-Strategy/
Solutions1978
https://www.tradingview.com/u/Solutions1978/
321
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ //@version=4 strategy(shorttitle='BBZS',title='Bear & Bull Zone Signal Strategy', overlay=true, initial_capital = 1000, process_orders_on_close=true, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type=strategy.commission.percent, commission_value=0.18, calc_on_every_tick=true) kcolor = #0094FF dcolor = #FF6A00 // ----------------- Strategy Inputs ------------------------------------------------------------- //Backtest dates with auto finish date of today start = input(defval = timestamp("01 April 2021 00:00 -0500"), title = "Start Time", type = input.time) finish = input(defval = timestamp("31 December 2021 00:00 -0600"), title = "Start Time", type = input.time) window() => time >= start and time <= finish ? true : false // create function "within window of time" // Strategy Selection - Long, Short, or Both strat = input(title="Strategy", defval="Long/Short", options=["Long Only", "Long/Short", "Short Only"]) strat_val = strat == "Long Only" ? 1 : strat == "Long/Short" ? 0 : -1 // Risk Management Inputs sl= input(10.0, "Stop Loss %", minval = 0, maxval = 100, step = 0.01) stoploss = sl/100 tp = input(20.0, "Target Profit %", minval = 0, maxval = 100, step = 0.01) TargetProfit = tp/100 // RSI and Stochastic Inputs length = input(14, "RSI Length", minval=1) source = input(title="RSI Source", type=input.source, defval=close) overbought= input(62, "Overbought") oversold= input(35, "Oversold") look_back = input(9,"Look Back Bars") high_source = input(high,"High Source") low_source= input(low,"Low Source") // EMA and SMA Background Inputs smoothK = input(3, "K", minval=1) smoothD = input(3, "D", minval=1) k_mode = input("SMA", "K Mode", options=["SMA", "EMA", "WMA"]) // MACD Inputs fastLength = input(5, minval=1, title="EMA Fast Length") slowLength = input(10, minval=1, title="EMA Slow Length") // Selections to show or hide the overlays showZones = input(true, title="Show Bullish/Bearish Zones") showStoch = input(true, title="Show Stochastic Overlays") // ------------------ Background Colors based on EMA Indicators ----------------------------------- // Uses standard lengths of 9 and 21, if you want control delete the constant definition and uncomment the inputs haClose(gap) => (open[gap] + high[gap] + low[gap] + close[gap]) / 4 rsi_ema = rsi(haClose(0), length) v2 = ema(rsi_ema, length) v3 = 2 * v2 - ema(v2, length) emaA = ema(rsi_ema, fastLength) emaFast = 2 * emaA - ema(emaA, fastLength) emaB = ema(rsi_ema, slowLength) emaSlow = 2 * emaB - ema(emaB, slowLength) // bullish signal rule: bullishRule =emaFast > emaSlow // bearish signal rule: bearishRule =emaFast < emaSlow // current trading State ruleState = 0 ruleState := bullishRule ? 1 : bearishRule ? -1 : nz(ruleState[1]) bgcolor(showZones ? ( ruleState==1 ? color.blue : ruleState==-1 ? color.red : color.gray ) : na , title=" Bullish/Bearish Zones", transp=95) // ------------------ Stochastic Indicator Overlay ----------------------------------------------- // Calculation // Use highest highs and lowest lows h_high = highest(high_source ,look_back) l_low = lowest(low_source ,look_back) RSI = rsi(source, length) stoch = stoch(RSI, RSI, RSI, length) k = k_mode=="EMA" ? ema(stoch, smoothK) : k_mode=="WMA" ? wma(stoch, smoothK) : sma(stoch, smoothK) d = sma(k, smoothD) k_c = change(k) d_c = change(d) kd = k - d // Plot signalColor = k>oversold and d<overbought and k>d and k_c>0 and d_c>0 ? kcolor : k<overbought and d>oversold and k<d and k_c<0 and d_c<0 ? dcolor : na kp = plot(showStoch ? k : na, "K", transp=80, color=kcolor) dp = plot(showStoch ? d : na, "D", transp=80, color=dcolor) fill(kp, dp, color = signalColor, title="K-D", transp=88) signalUp = showStoch ? not na(signalColor) and kd>0 : na signalDown = showStoch ? not na(signalColor) and kd<0 : na plot(signalUp ? kd : na, "Signal Up", color=kcolor, transp=90, style=plot.style_columns) plot(signalDown ? (kd+100) : na , "Signal Down", color=dcolor, transp=90, style=plot.style_columns, histbase=100) // -------------- Add Price Movement to Strategy for better visualization ------------------------- // Calculations h1 = vwma(high, length) l1 = vwma(low, length) hp = h_high[1] lp = l_low[1] // Plot var plot_color=#353535 var sig = 0 if (h1 >hp) sig:=1 plot_color:=color.lime else if (l1 <lp) sig:=-1 plot_color:=color.maroon bgcolor(plot_color, transp=75) // --------------------------------------- RSI Plot ---------------------------------------------- // Plot Oversold and Overbought Lines over = hline(oversold, title="Oversold", color=color.green) under = hline(overbought, title="Overbought", color=color.red) fill(over, under, color=#9915FF, transp=90, title="Band Background") // Plot colored RSI Line plot(RSI, title="RSI", linewidth=3, color=color.yellow) //---------------- Signal Trigger Definitions ----------------------------------------- SignalA = bearishRule and signalDown and window() SignalB = bullishRule and signalDown and window() SignalC = bearishRule and signalUp and window() SignalD = bullishRule and signalUp and window() //---------------- Signal Alerts ------------------------------------------------------ //alertcondition(SignalA, title='Bear & Signal Down', message='Bearish Down') //alertcondition(SignalB, title='Bull & Signal Down', message='Bullish Down') //alertcondition(SignalC, title='Bear & Signal Up', message='Bearish Up') //alertcondition(SignalD, title='Bull & Signal Up', message='Bullish Up') //---------------- Fibonacci Sanity Check of Signals --------------------------------- sma24 = sma(close, 24) sma38 = sma(close, 38) sma50 = sma(close, 50) sma62 = sma(close, 62) sma76 = sma(close, 76) sma100 = sma(close, 100) sma236 = sma(close, 236) sma382= sma(close, 382) sma500 = sma(close, 500) sma618 = sma(close, 618) sma764 = sma(close, 764) sma1000 = sma(close, 1000) ema24 = ema(close, 24) ema38 = ema(close, 38) ema50 = ema(close, 50) ema62 = ema(close, 62) ema76 = ema(close, 76) ema100 = ema(close, 100) ema236 = ema(close, 236) ema382= ema(close, 382) ema500 = ema(close, 500) ema618 = ema(close, 618) ema764 = ema(close, 764) ema1000 = ema(close, 1000) Higher50 = close > sma50 or close > ema50 Lower50 = close < sma50 or close < ema50 Higher100 = close > sma100 or close > ema100 Lower100 = close < sma100 or close < ema100 Higher236 = close > sma236 or close > ema236 Lower236 = close < sma236 or close < ema236 Higher500 = close > sma500 or close > ema500 Lower500 = close < sma500 or close < ema500 Higher1000 = close > sma1000 or close > ema1000 Lower1000 = close < sma1000 or close < ema1000 // ------------------------------------- Alerts and Entry Strategy ---------------------------- GoLong = strat_val > -1 ? (SignalC or SignalD and ((Higher50 or Higher100 or Higher236 or Higher500 or Higher1000) and not (Higher50[1] or Higher100[1] or Higher236[1] or Higher500[1] or Higher1000[1]))) : false //alertcondition(GoLong, title='True Long Signal', message='Go Long') GoShort = strat_val < 1 ? (SignalA or SignalB and ((Lower50 or Lower100 or Lower236 or Lower500 or Lower1000) and not (Lower50[1] or Lower100[1] or Lower236[1] or Lower500[1] or Lower1000[1]))) : false //alertcondition(GoShort, title='True Short Signal', message='Go Short') // ------------------------------------- Backtesting of Strategy -------------------------------- convert_percent_to_points(percent) => strategy.position_size != 0 ? round(percent * strategy.position_avg_price / syminfo.mintick) : float(na) setup_percent(percent) => convert_percent_to_points(percent) if (GoLong) strategy.entry("LONG", strategy.long) strategy.exit(id="Exit Long", from_entry = "LONG", loss=setup_percent(stoploss), profit=setup_percent(TargetProfit)) CloseLong = strat_val > -1 ? strategy.position_size > 0 and GoShort : false if(CloseLong) strategy.close("LONG") if (GoShort) strategy.entry("SHORT", strategy.short) strategy.exit(id="Exit Short", from_entry = "SHORT", loss=setup_percent(stoploss), profit=setup_percent(TargetProfit)) CloseShort = strat_val < 1 ? strategy.position_size < 0 and GoLong : false if(CloseShort) strategy.close("SHORT")
DEMA/EMA & VOL (Short strategy)
https://www.tradingview.com/script/HgyuhGYO-DEMA-EMA-VOL-Short-strategy/
Qorbanjf
https://www.tradingview.com/u/Qorbanjf/
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/ // Β© Qorbanjf //@version=4 // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© Qorbanjf //@version=4 strategy("Qorban: DEMA/EMA & VOL Short ONLY", shorttitle="DEMA/EMA & VOL SHORT", overlay=true, initial_capital=10000, default_qty_value=10000) // DEMA length = input(10, minval=1, title="DEMA LENGTH") src = input(close, title="Source") e1 = ema(src, length) e2 = ema(e1, length) dema1 = 2 * e1 - e2 plot(dema1, "DEMA", color=color.yellow) //EMA len = input(25, minval=1, title="EMA Length") srb = input(close, title="Source") offset = input(title="Offset", type=input.integer, defval=0, minval=-500, maxval=500) ema1 = ema(srb, len) plot(ema1, title="EMA", color=color.blue, offset=offset) // get ATR VALUE atr = atr(14) //ATRP (Average True Price in precentage) // Inputs atrTimeFrame = input("D", title="ATR Timeframe", type=input.resolution) atrLookback = input(defval=14,title="ATR Lookback Period",type=input.integer) useMA = input(title = "Show Moving Average?", type = input.bool, defval = true) maType = input(defval="EMA", options=["EMA", "SMA"], title = "Moving Average Type") maLength = input(defval = 20, title = "Moving Average Period", minval = 1) slType = input(title="Stop Loss ATR / %", type=input.float, defval=5.0, step=0.1) slMulti = input(title="SL Multiplier", type=input.float, defval=1.0, step=0.1) minimumProfitPercent = input(title="Minimum profit %", type=input.float, defval=20.00) // ATR Logic // atrValue = atr(atrLookback) // atrp = (atrValue/close)*100 // plot(atrp, color=color.white, linewidth=2, transp = 30) atrValue = security(syminfo.tickerid, atrTimeFrame, atr(atrLookback)) atrp = (atrValue/close)*100 // Moving Average Logic ma(maType, src, length) => maType == "EMA" ? ema(src, length) : sma(src, length) //Ternary Operator (if maType equals EMA, then do ema calc, else do sma calc) maFilter = security(syminfo.tickerid, atrTimeFrame, ma(maType, atrp, maLength)) // Determine percentage of open profit var entry = 0.0 distanceProfit = low - entry distanceProfitPercent = distanceProfit / entry //Determin if we have a long entry signal OR a sell position signal profitSignal = minimumProfitPercent == 0.0 or distanceProfitPercent >= minimumProfitPercent shortSignal = crossunder(dema1, ema1) and atrp > maFilter and strategy.position_size == 0 and not na(atr) exitSignal = profitSignal and strategy.position_size !=0 and crossover(dema1, ema1) // === INPUT BACKTEST RANGE === //FromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12) //FromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31) //FromYear = input(defval = 2017, title = "From Year", minval = 2000) //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 = 2017) //Invert trade direction & flipping //tradInvert = input(defval = false, title = "invert trade direction") //MOM_MR = input(defval=1, title = "MOM = 1 / MR = -1", minval=-1, maxval=1) //plots=input(false, title="Show plots?") // Get stop loss (in pips AND percentage distance) shortStop = highest(high, 4) - (atr * slMulti) shortStopPercent = close - (close * slMulti) // Save long stop & target prices (used for drawing data to the chart & deetermining profit) var shortStopSaved = 0.0 var shortTargetSaved = 0.0 enterShort = false if shortSignal shortStopSaved := slType ? shortStop : shortStopPercent enterShort:= true entry := close // long conditions //enterLong = crossover(dema1, ema1) and atrp < maFilter //exitSignal => crossunder(dema1, ema1) //Enter trades when conditions are met strategy.entry("short", strategy.short, when=enterShort, comment="SHORT") //place exit orders (only executed after trades are active) strategy.exit(id="Short exit", from_entry="short", limit=exitSignal ? close : na, stop=shortStopSaved, when=strategy.position_size > 0, comment="end short") //short strategy //goShort() => crossunder(dema1, ema1) and atrp > maFilter //KillShort() => crossover(dema1, ema1) //strategy.entry("SHORT", strategy.short, when = goShort()) //strategy.close("COVER", when = KillShort())
4-Hour Stochastic EMA Trend
https://www.tradingview.com/script/dU7AQYp7/
slymnturkoglu
https://www.tradingview.com/u/slymnturkoglu/
31
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/ // Β© slymnturkoglu //@version=4 strategy("Stochastic") //study(title="Stochastic", shorttitle="Stoch", format=format.price, precision=2, resolution="") period1 = 5 period2 = 15 period3 = 50 ma1 = ema(close, period1) ma2 = ema(close, period2) ma3 = ema(close, period3) periodK=13 periodD=15 smoothK=5 k = sma(stoch(close, high, low, periodK), smoothK) d = sma(k, periodD) buyCondition = crossover(k, d) and crossover(ma1, ma3) and crossover(ma2, ma3) sellCondition = crossunder(k, d) and crossunder(ma1, ma3) and crossunder(ma2, ma3) strategy.entry("long", strategy.long, 1000, alert_message="LongAlert", when=buyCondition) strategy.close("long", alert_message="CloseAlert", when=sellCondition) //study("Stochastic EMA Trend", overlay=false) plot(close) plot(ma1, color=color.blue, linewidth=3, title="EMA period 5") plot(ma2, color=color.green,linewidth=3, title="EMA period 15") plot(ma3, color=color.yellow,linewidth=3, title="EMA period 50") plot(d, color=color.red,linewidth=3, title="d") plot(k, color=color.blue,linewidth=3, title="k")
Stable Coin - Arbitraje
https://www.tradingview.com/script/MGSpgtvW-Stable-Coin-Arbitraje/
aguspina
https://www.tradingview.com/u/aguspina/
167
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/ // Β© aguspina //@version=4 strategy("Stable Coin - Arbitraje", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=100000, currency=currency.USD, commission_type=strategy.commission.percent, commission_value=0.001, calc_on_every_tick=true) strategy.risk.allow_entry_in(strategy.direction.long) ///// Backtest Start Date ///// startDate = input(title="Start Date", type=input.integer, defval=1, minval=1, maxval=31) startMonth = input(title="Start Month", type=input.integer, defval=1, minval=1, maxval=12) startYear = input(title="Start Year", type=input.integer, defval=2021, minval=1800, maxval=2100) lowPrice = input(title="Low Price", type=input.float, defval=0.9997) highPrice = input(title="High Price", type=input.float, defval=1.0003) afterStartDate = (time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0)) shouldOpenLong = close <= lowPrice if (afterStartDate and shouldOpenLong) strategy.entry(id="LONG", long=true, limit=lowPrice) strategy.exit(id="LONG", limit=highPrice)
MACD Trendprediction Strategy V1
https://www.tradingview.com/script/p6meJyu3/
moritz1301
https://www.tradingview.com/u/moritz1301/
245
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/ // Β© moritz1301 //@version=4 strategy("MACD Trendprediction Strategy V1", shorttitle="MACD TPS", overlay=true) sma = input(12,title='DEMA Courte') lma = input(26,title='DEMA Longue') tsp = input(9,title='Signal') dolignes = input(true,title="Lignes") MMEslowa = ema(close,lma) MMEslowb = ema(MMEslowa,lma) DEMAslow = ((2 * MMEslowa) - MMEslowb ) MMEfasta = ema(close,sma) MMEfastb = ema(MMEfasta,sma) DEMAfast = ((2 * MMEfasta) - MMEfastb) LigneMACDZeroLag = (DEMAfast - DEMAslow) MMEsignala = ema(LigneMACDZeroLag, tsp) MMEsignalb = ema(MMEsignala, tsp) Lignesignal = ((2 * MMEsignala) - MMEsignalb ) MACDZeroLag = (LigneMACDZeroLag - Lignesignal) bgcolor(LigneMACDZeroLag<Lignesignal ? color.red : color.green) if (LigneMACDZeroLag>Lignesignal) strategy.entry("Buy", strategy.long, comment="BUY") if (LigneMACDZeroLag<Lignesignal) strategy.close("Buy", strategy.long, comment="SELL")
BTC_ISHIMOKU
https://www.tradingview.com/script/QeOSspqw-btc-ishimoku/
IntelTrading
https://www.tradingview.com/u/IntelTrading/
104
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/ // Β© Alferow //@version=4 strategy("BTC_ISHIMOKU", overlay=true, initial_capital=1000, commission_value=0.25, default_qty_type=strategy.percent_of_equity, default_qty_value=100) period_max = input(20, minval = 1) period_med = input(10, minval = 1) period_min = input(16, minval = 1) Lmax = highest(high, period_max) Smax = lowest(low, period_max) Lmed = highest(high, period_med) Smed = lowest(low, period_med) Lmin = highest(high, period_min) Smin = lowest(low, period_min) HL1 = (Lmax + Smax + Lmed + Smed)/4 HL2 = (Lmed + Smed + Lmin + Smin)/4 p1 = plot(HL1, color = color.red, linewidth = 2) p2 = plot(HL2, color = color.green, linewidth = 2) fill(p1, p2, color = HL1 < HL2 ? color.green : color.red, transp = 90) start = timestamp(input(2020, minval=1), 01, 01, 00, 00) finish = timestamp(input(2025, minval=1),01, 01, 00, 00) trig = time > start and time < finish ? true : false strategy.entry("Long", true, when = crossover(HL2, HL1) and trig) // strategy.entry("Short", false, when = crossunder(HL2, HL1) and trig) strategy.close("Long", when = crossunder(HL2, HL1) and trig)
buy down and sell high trend 200 sma and ma cross
https://www.tradingview.com/script/P34cPRhX-buy-down-and-sell-high-trend-200-sma-and-ma-cross/
willi130503
https://www.tradingview.com/u/willi130503/
37
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/ // Β© willi130503 //@version=4 strategy(title = "buy down and sell high trend 200 sma ma cross ") conditionForBuy = open > high[1] strategy.entry("long", true, 1, limit = low, when = conditionForBuy) // enter long using limit order at low price of current bar if conditionForBuy is true strategy.cancel("long", when = not conditionForBuy) // cancel the entry order with name "long" if conditionForBuy is false short = sma(close, 9) long = sma(close, 21) long200 = sma(close, 200) plot(short, color = color.red) plot(long, color = color.green) plot(long200, color = color.white) plot(cross(short, long) ? short : na, style = plot.style_cross, linewidth = 4)
Sentiment Oscillator
https://www.tradingview.com/script/ODMCwcDG-Sentiment-Oscillator/
dannylimardi
https://www.tradingview.com/u/dannylimardi/
276
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/ // Β© dannylimardi //@version=4 strategy("Sentiment Oscillator with Backtest", "Sentiment Oscillator", overlay=false, initial_capital=100, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=0.08) //Inputs msLen = input(49, type=input.integer, title="Market Sentiment Lookback Length", group="Parameters") emaLen1 = input(40, type=input.integer, title="Fast EMA Length", group="Parameters") emaLen2 = input(204, type=input.integer, title="Slow EMA Length", group="Parameters") signalLen = input(20, type=input.integer, title="Signal Length", group="Parameters") showMs = input(false, type=input.bool, title="Show Market Sentiment Line?", group="Plots") showHist = input(true, type=input.bool, title="Show Momentum Histogram?", group="Plots") showMacd = input(true, type=input.bool, title="Show MACD Line?", group="Plots") showSignal = input(true, type=input.bool, title="Show Signal Line?", group="Plots") showDots = input(true, type=input.bool, title="Plot Dots when MACD and Signal Line cross?", group="Plots") showCpv = input(false, type=input.bool, title="[Show Change/Volume of Each Bar?]", group="Plots") showEma1 = input(false, type=input.bool, title="[Show Fast EMA?]", group="Plots") showEma2 = input(false, type=input.bool, title="[Show Slow EMA?]", group="Plots") longStrategy = input(true, type=input.bool, title="Backtest Long Strategy?", group="Long Strategy") entryVar1 = input(title="Long Entry Variable 1",defval="Histogram", options=["Market Sentiment", "Fast EMA", "Slow EMA", "MACD", "Signal Line", "Histogram"], group="Long Strategy") entryCond = input(title="Long Entry Condition", defval="Crossing Over", options=["Crossing Over", "Crossing Under"], group="Long Strategy") entryVar2 = input(title="Long Entry Variable 2", defval="Zero Line", options=["Market Sentiment", "Fast EMA", "Slow EMA", "MACD", "Signal Line", "Histogram", "Zero Line"], group="Long Strategy") exitVar1 = input(title="Long Exit Variable 1",defval="MACD", options=["Market Sentiment", "Fast EMA", "Slow EMA", "MACD", "Signal Line", "Histogram"], group="Long Strategy") exitCond = input(title="Long Exit Condition", defval="Crossing Under", options=["Crossing Over", "Crossing Under"], group="Long Strategy") exitVar2 = input(title="Long Exit Variable 2", defval="Zero Line", options=["Market Sentiment", "Fast EMA", "Slow EMA", "MACD", "Signal Line", "Histogram", "Zero Line"], group="Long Strategy") useCPV = input(false, type=input.bool, title="Use Alternate Calculation Method?", group="Other Settings", tooltip="If checked, the Market Sentiment will be the EMA of Change Per Volume of each bar, instead of the default calculation method (Price Change EMA divided by Volume EMA). The alternate method may be slightly more responsive, but will result in bigger fluctuations when there is a huge change in volume. If this method is checked, I recommend changing the Long Exit Strategy to 'Signal Line Crossing Under Zero'.") mcTheme = input(false, type=input.bool, title="Use Alternate Color Scheme?", group="Other Settings", tooltip="If checked, the MACD, Signal, and Histogram will all be plotted as areas and histograms") //Calculations priceChange = close - close[1] changePerVolume = (priceChange/volume) * 10000000 // (The 1000000 doesn't have any significance, it's just to avoid color-change errors when the values are too small.) priceChangeEma = ema(priceChange, msLen) volumeEma = ema(volume, msLen) marketSentiment = useCPV ? ema(changePerVolume, msLen) : priceChangeEma/volumeEma * 1000000000 msEma1 = ema(marketSentiment, emaLen1) msEma2 = ema(marketSentiment, emaLen2) macd = msEma1-msEma2 signal = ema(macd, signalLen) hist = macd-signal //Strategy Function and String Definitions var entryVar1_ = 0.0 var entryVar2_ = 0.0 var exitVar1_ = 0.0 var exitVar2_ = 0.0 if entryVar1 == "Market Sentiment" entryVar1_ := marketSentiment else if entryVar1 == "Fast EMA" entryVar1_ := msEma1 else if entryVar1 =="Slow EMA" entryVar1_ := msEma2 else if entryVar1 == "MACD" entryVar1_ := macd else if entryVar1 == "Signal Line" entryVar1_ := signal else if entryVar1 == "Histogram" entryVar1_ := hist if entryVar2 == "Market Sentiment" entryVar2_ := marketSentiment else if entryVar2 == "Fast EMA" entryVar2_ := msEma1 else if entryVar2 =="Slow EMA" entryVar2_ := msEma2 else if entryVar2 == "MACD" entryVar2_ := macd else if entryVar2 == "Signal Line" entryVar2_ := signal else if entryVar2 == "Histogram" entryVar2_ := hist else if entryVar2 == "Zero Line" entryVar2_ := 0 if exitVar1 == "Market Sentiment" exitVar1_ := marketSentiment else if exitVar1 == "Fast EMA" exitVar1_ := msEma1 else if exitVar1 =="Slow EMA" exitVar1_ := msEma2 else if exitVar1 == "MACD" exitVar1_ := macd else if exitVar1 == "Signal Line" exitVar1_ := signal else if exitVar1 == "Histogram" exitVar1_ := hist if exitVar2 == "Market Sentiment" exitVar2_ := marketSentiment else if exitVar2 == "Fast EMA" exitVar2_ := msEma1 else if exitVar2 =="Slow EMA" exitVar2_ := msEma2 else if exitVar2 == "MACD" exitVar2_ := macd else if exitVar2 == "Signal Line" exitVar2_ := signal else if exitVar2 == "Histogram" exitVar2_ := hist else if exitVar2 == "Zero Line" exitVar2_ := 0 entryCond_(entryVar1_, entryVar2_) => if entryCond == "Crossing Over" crossover(entryVar1_, entryVar2_) else if entryCond == "Crossing Under" crossunder(entryVar1_, entryVar2_) exitCond_(exitVar1_, exitVar2_) => if exitCond == "Crossing Over" crossover(exitVar1_, exitVar2_) if exitCond == "Crossing Under" crossunder(exitVar1_, exitVar2_) longEntry = entryCond_(entryVar1_, entryVar2_) longExit = exitCond_(exitVar1_, exitVar2_) up = crossover(macd, signal) down = crossunder(macd, signal) greenDot = up ? valuewhen(up, signal, 0) : na redDot = down ? valuewhen(down, signal, 0) : na //Plot colors col_grow_above = #26A69A col_grow_below = #FFCDD2 col_fall_above = #B2DFDB col_fall_below = #EF5350 col_macd = #0094ff col_signal = #ff6a00 //Drawings plot(showMacd ? macd : na, title="MACD", color=mcTheme ? #6f62e3 : col_macd, transp=mcTheme ? 15 : 0, style=mcTheme ? plot.style_histogram : plot.style_line) plot(showSignal ? signal : na, title="Signal", color=mcTheme ? (signal > 0 ? color.blue : color.orange) : col_signal, transp=mcTheme ? 85 : 0, style=mcTheme ? plot.style_area : plot.style_line) plot(showHist ? hist : na, title="Histogram", style=mcTheme ? plot.style_columns : plot.style_area, color=mcTheme ? (hist > 0 ? color.teal : color.red) : (hist>=0 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below)), transp=mcTheme ? 15 : 20) plot(showDots ? greenDot : na, color=color.lime, style=plot.style_circles, linewidth=5, transp=40) plot(showDots ? redDot : na, color=color.red, style=plot.style_circles, linewidth=5, transp=40) plot(0, color=color.white, transp=80) plot(showEma1 ? msEma1 : na, color=color.aqua) plot(showEma2 ? msEma2 : na, color=color.yellow) plot(showMs ? marketSentiment : na, color=color.lime) plot(showCpv ? changePerVolume : na, color=changePerVolume > changePerVolume[1] ? color.teal : color.red) // if longEntry and valuewhen(longEntry, bar_index, 1) < valuewhen(longExit, bar_index, 0) // label.new(bar_index, signal, "BUY", yloc=yloc.price, style=label.style_none, color=color.green, textcolor=color.blue) // if longExit and valuewhen(longExit, bar_index, 1) < valuewhen(longEntry, bar_index, 0) // label.new(bar_index, signal, "SELL", yloc=yloc.price, style=label.style_none, color=color.red, textcolor=color.red) //Strategy if longStrategy strategy.entry("Buy", strategy.long, when=longEntry) strategy.close("Buy", when=longExit)
Simple way to BEAT the market [STRATEGY]
https://www.tradingview.com/script/vrFq8cGn-Simple-way-to-BEAT-the-market-STRATEGY/
TraderHalai
https://www.tradingview.com/u/TraderHalai/
445
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/ // // @author Sunil Halai // // This script has been created to demonstrate the effectiveness of using market regime filters in your trading strategy, and how they can improve your returns and lower your drawdowns // // This strategy adds a simple filter (The historical volatility filter, which can be found on my trading profile) to a traditional buy and hold strategy of the index SPY. There are other filters // that could also be added included a long term moving average / percentile rank filter / ADX filter etc, to improve the returns further. // // Feel free to use some of the market filters in my trading profile to improve and refine your strategies further, or make a copy and play around with the code yourself. This is just // a simple example for demo purposes. // //@version=4 strategy(title = "Simple way to beat the market [STRATEGY]", shorttitle = "Beat The Market [STRATEGY]", overlay=true, initial_capital=100000, default_qty_type=strategy.percent_of_equity, currency="USD", default_qty_value=100) upperExtreme = input(title = "Upper percentile filter (Do not trade above this number)", type = input.integer, defval = 95) lookbackPeriod = input(title = "Lookback period", type = input.integer, defval = 100) annual = 365 per = timeframe.isintraday or timeframe.isdaily and timeframe.multiplier == 1 ? 1 : 7 hv = lookbackPeriod * stdev(log(close / close[1]), 10) * sqrt(annual / per) filtered = hv >= percentile_nearest_rank(hv, 100, upperExtreme) if(not(filtered)) strategy.entry("LONG", strategy.long) else strategy.close("LONG")
5-10-20 Cross
https://www.tradingview.com/script/2kbxQKu3-5-10-20-Cross/
aadilpatel07
https://www.tradingview.com/u/aadilpatel07/
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/ // Β© aadilpatel07 //@version=4 strategy("5-10-20 Cross", overlay=true) src = close, len1 = input(5, minval=1, title="EMA 1") len2 = input(10, minval=1, title="EMA 2") len3 = input(20, minval=1, title="EMA 3") mult = input(type=input.float, defval=2) len = input(type=input.integer, defval=14) [superTrend, dir] = supertrend(mult, len) ema1 = ema(src, len1) ema2 = ema(src, len2) ema3 = ema(src, len3) //EMA Color col1 = color.lime col2 = color.blue col3 = color.red //EMA Plots plot(series=ema1,color=col1, title="EMA1") plot(series=ema2,color=col2, title="EMA2") plot(series=ema3,color=col3, title="EMA3") //plot SuperTrend colResistance = dir == 1 and dir == dir[1] ? color.new(color.red, 100) : color.new(color.green, 100) colSupport = dir == -1 and dir == dir[1] ? color.new(color.green, 0) : color.new(color.green, 10) plot(superTrend, color = colResistance, linewidth=1) plot(superTrend, color = colSupport, linewidth=1) //longCondition = crossover(ema1, ema2) and crossover(ema1,ema3) and crossover(ema2,ema3) longCondition = ema1 > ema2 and ema1 > ema3 and ema2 > ema3 and ema2 < ema1 and dir == -1 if (longCondition) strategy.entry("My Long Entry Id", strategy.long) //shortCondition = crossover(ema2, ema1) and crossover(ema3,ema1) and crossover(ema3,ema2) shortCondition = ema1 < ema2 and ema1 < ema3 and ema2 < ema3 and ema2 > ema1 and dir == 1 if (shortCondition) strategy.entry("My Short Entry Id", strategy.short)
PSAR w/ Extras
https://www.tradingview.com/script/6L628c5A-PSAR-w-Extras/
qweporiuqwer
https://www.tradingview.com/u/qweporiuqwer/
123
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/ // Β© qweporiuqwer //@version=4 strategy("PSAR w/ Extras", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=1000, commission_type=strategy.commission.percent, commission_value=0.25) psar = sar(0.02, 0.02, 0.2) // these are default values var startTime = input(title="Start Date", type=input.time, defval=timestamp("01 Jan 2018 00:00")) psarLong = crossunder(psar, close) psarShort = crossover(psar, close) buyCondition = psarLong sellCondition = psarShort trailingStopArm = 5 trailingStopCatch = 1 if time > startTime strategy.entry("Long", true, when=buyCondition) strategy.exit("exit", "Long", trail_points = close * (trailingStopArm * 0.01) / syminfo.mintick, trail_offset = close * (trailingStopCatch * 0.01) / syminfo.mintick) plot(psar, style=plot.style_circles, linewidth=2) plot(ema(close, 50), color = color.red)
Wave Trend w/ VWMA overlay
https://www.tradingview.com/script/Tts2YhVP-Wave-Trend-w-VWMA-overlay/
jadamcraig
https://www.tradingview.com/u/jadamcraig/
333
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at // https://mozilla.org/MPL/2.0/ // // Created by jadamcraig // // This strategy benefits from extracts taken from the following // studies/authors. Thank you for developing and sharing your ideas in an open // way! // * Wave Trend Strategy by thomas.gigure // * cRSI + Waves Strategy with VWMA overlay by Dr_Roboto // //@version=4 //============================================================================== //============================================================================== overlay = true // plots VWMA (need to close and re-add) //overlay = false // plots Wave Trend (need to close and re-add) strategy("Wave Trend w/ VWMA overlay", overlay=overlay) baseQty = input(defval=1, title="Base Quantity", type=input.float, minval=1) useSessions = input(defval=true, title="Limit Signals to Trading Sessions?") sess1_startHour = input(defval=8, title="Session 1: Start Hour", type=input.integer, minval=0, maxval=23) sess1_startMinute = input(defval=25, title="Session 1: Start Minute", type=input.integer, minval=0, maxval=59) sess1_stopHour = input(defval=10, title="Session 1: Stop Hour", type=input.integer, minval=0, maxval=23) sess1_stopMinute = input(defval=25, title="Session 1: Stop Minute", type=input.integer, minval=0, maxval=59) sess2_startHour = input(defval=12, title="Session 2: Start Hour", type=input.integer, minval=0, maxval=23) sess2_startMinute = input(defval=55, title="Session 2: Start Minute", type=input.integer, minval=0, maxval=59) sess2_stopHour = input(defval=14, title="Session 2: Stop Hour", type=input.integer, minval=0, maxval=23) sess2_stopMinute = input(defval=55, title="Session 2: Stop Minute", type=input.integer, minval=0, maxval=59) sess1_closeAll = input(defval=false, title="Close All at End of Session 1") sess2_closeAll = input(defval=true, title="Close All at End of Session 2") //============================================================================== //============================================================================== // Volume Weighted Moving Average (VWMA) //============================================================================== //============================================================================== plotVWMA = overlay // check if volume is available for this equity useVolume = input( title="VWMA: Use Volume (uncheck if equity does not have volume)", defval=true) vwmaLen = input(defval=21, title="VWMA: Length", type=input.integer, minval=1, maxval=200) vwma = vwma(close, vwmaLen) vwma_high = vwma(high, vwmaLen) vwma_low = vwma(low, vwmaLen) if not(useVolume) vwma := wma(close, vwmaLen) vwma_high := wma(high, vwmaLen) vwma_low := wma(low, vwmaLen) // +1 when above, -1 when below, 0 when inside vwmaSignal(priceOpen, priceClose, vwmaHigh, vwmaLow) => sig = 0 color = color.gray if priceClose > vwmaHigh sig := 1 color := color.green else if priceClose < vwmaLow sig := -1 color := color.red else sig := 0 color := color.gray [sig,color] [vwma_sig, vwma_color] = vwmaSignal(open, close, vwma_high, vwma_low) priceAboveVWMA = vwma_sig == 1 ? true : false priceBelowVWMA = vwma_sig == -1 ? true : false // plot(priceAboveVWMA?2.0:0,color=color.blue) // plot(priceBelowVWMA?2.0:0,color=color.maroon) //bandTrans = input(defval=70, title="VWMA Band Transparancy (100 invisible)", // type=input.integer, minval=0, maxval=100) //fillTrans = input(defval=70, title="VWMA Fill Transparancy (100 invisible)", // type=input.integer, minval=0, maxval=100) bandTrans = 60 fillTrans = 60 // ***** Plot VWMA ***** highband = plot(plotVWMA?fixnan(vwma_high):na, title='VWMA High band', color = vwma_color, linewidth=1, transp=bandTrans) lowband = plot(plotVWMA?fixnan(vwma_low):na, title='VWMA Low band', color = vwma_color, linewidth=1, transp=bandTrans) fill(lowband, highband, title='VWMA Band fill', color=vwma_color, transp=fillTrans) plot(plotVWMA?vwma:na, title='VWMA', color = vwma_color, linewidth=3, transp=bandTrans) //============================================================================== //============================================================================== // Wave Trend //============================================================================== //============================================================================== plotWaveTrend = not(overlay) n1 = input(10, "Wave Trend: Channel Length") n2 = input(21, "Wave Trend: Average Length") obLevel1 = input(60, "Wave Trend: Over Bought Level 1") obLevel2 = input(53, "Wave Trend: Over Bought Level 2") osLevel1 = input(-60, "Wave Trend: Over Sold Level 1") osLevel2 = input(-53, "Wave Trend: Over Sold Level 2") ap = hlc3 esa = ema(ap, n1) d = ema(abs(ap - esa), n1) ci = (ap - esa) / (0.015 * d) tci = ema(ci, n2) wt1 = tci wt2 = sma(wt1,4) plot(plotWaveTrend?0:na, color=color.gray) plot(plotWaveTrend?obLevel1:na, color=color.red) plot(plotWaveTrend?osLevel1:na, color=color.green) plot(plotWaveTrend?obLevel2:na, color=color.red, style=3) plot(plotWaveTrend?osLevel2:na, color=color.green, style=3) plot(plotWaveTrend?wt1:na, color=color.green) plot(plotWaveTrend?wt2:na, color=color.red, style=3) plot(plotWaveTrend?wt1-wt2:na, color=color.blue, transp=80) //============================================================================== //============================================================================== // Order Management //============================================================================== //============================================================================== // Define Long and Short Conditions longCondition = crossover(wt1, wt2) shortCondition = crossunder(wt1, wt2) // Define Quantities orderQty = baseQty * 2 if (longCondition) if (vwma_sig == 1) if ( strategy.position_size >= (baseQty * 4 * -1) and strategy.position_size < 0 ) orderQty := baseQty * 4 + abs(strategy.position_size) else orderQty := baseQty * 4 else if (vwma_sig == 0) if ( strategy.position_size >= (baseQty * 2 * -1) and strategy.position_size < 0 ) orderQty := baseQty * 2 + abs(strategy.position_size) else orderQty := baseQty * 2 else if (vwma_sig == -1) if ( strategy.position_size >= (baseQty * 1 * -1) and strategy.position_size < 0 ) orderQty := baseQty * 1 + abs(strategy.position_size) else orderQty := baseQty * 1 else if (shortCondition) if (vwma_sig == -1) if ( strategy.position_size <= (baseQty * 4) and strategy.position_size > 0 ) orderQty := baseQty * 4 + strategy.position_size else orderQty := baseQty * 4 else if (vwma_sig == 0) if ( strategy.position_size <= (baseQty * 2) and strategy.position_size > 2 ) orderQty := baseQty * 2 + strategy.position_size else orderQty := baseQty * 2 else if (vwma_sig == 1) if ( strategy.position_size <= (baseQty * 1) and strategy.position_size > 0 ) orderQty := baseQty * 1 + strategy.position_size else orderQty := baseQty * 1 // Determine if new trades are permitted newTrades = false if (useSessions) if ( hour == sess1_startHour and minute >= sess1_startMinute ) newTrades := true else if ( hour > sess1_startHour and hour < sess1_stopHour ) newTrades := true else if ( hour == sess1_stopHour and minute < sess1_stopMinute ) newTrades := true else if ( hour == sess2_startHour and minute >= sess2_startMinute ) newTrades := true else if ( hour > sess2_startHour and hour < sess2_stopHour ) newTrades := true else if ( hour == sess2_stopHour and minute < sess2_stopMinute ) newTrades := true else newTrades := false else newTrades := true // Long Signals if ( longCondition and newTrades ) strategy.order("Buy", strategy.long, orderQty) // Short Signals if ( shortCondition and newTrades ) strategy.order("Sell", strategy.short, orderQty) // Close open position at end of Session 1, if enabled if (sess1_closeAll and hour == sess1_stopHour and minute >= sess1_stopMinute ) strategy.close_all() // Close open position at end of Session 2, if enabled if (sess2_closeAll and hour == sess2_stopHour and minute >= sess2_stopMinute ) strategy.close_all()
Stoch-RSI 4h/1h/15min
https://www.tradingview.com/script/s6my45QC-Stoch-RSI-4h-1h-15min/
MoonFlag
https://www.tradingview.com/u/MoonFlag/
376
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/ // Β© MoonFlag //@version=4 strategy(title="(Stoch/RSI/RVSI/MACD/TimeframeConfluence)", overlay=true, precision=2, initial_capital=100, commission_type=strategy.commission.percent, commission_value=0.07, default_qty_type = strategy.percent_of_equity, default_qty_value=100, pyramiding=1, calc_on_order_fills=false, calc_on_every_tick = false) Pair = input(title="Trading Pair (For reference only)", type=input.string, defval="DOGE") Wunderbit = input(title="Use strategy comments below (paste below for webhooks bots)", defval=false) Enter_Long = input(title="Enter Long ", type=input.string, defval="") Exit_Long = input(title="Exit Long ", type=input.string, defval="") Enter_Short = input(title="Enter Short ", type=input.string, defval="") Exit_Short = input(title="Exit Short ", type=input.string, defval="") Longs = input(title='Include Long Trades', defval = true) Shorts = input(title='Include Short Trades', defval = true) useMACDRVSI = input(title="Use MACD/RVSI", defval=true) MACDonBuySell = true//input(title="MACDonBuySell", defval=true) resolution = input(title="MACD/RVSI Confluence Resolution", type=input.resolution, defval="15") avl = 5 l1 = 10 maFast =3 maSlow =10 nv = cum((change(close)) * volume) av = ema(nv, avl) RVSI = rsi(av, l1) xSlow = ema(RVSI, maSlow) xFast = ema(RVSI, maFast) xSlowR=security(syminfo.tickerid, resolution, xSlow) xFastR=security(syminfo.tickerid, resolution, xFast) histRVSI_R = xFastR - xSlowR src = close signal_length = 9 sma_source = false sma_signal = false fast_ma = sma_source ? sma(src, maFast) : ema(src, maFast) slow_ma = sma_source ? sma(src, maSlow) : ema(src, maSlow) macd = fast_ma - slow_ma macd_R = security(syminfo.tickerid, resolution, macd) signal = sma_signal ? sma(macd, signal_length) : ema(macd, signal_length) signal_R = security(syminfo.tickerid, resolution, signal) histMACD_R = macd_R - signal_R var maxMACD =0. var maxRVSI =0. var minMACD =0. var minRVSI =0. if (maxRVSI < histRVSI_R) maxRVSI := histRVSI_R if (minRVSI > histRVSI_R) minRVSI := histRVSI_R if (maxMACD < histMACD_R) maxMACD := histMACD_R if (minMACD > histMACD_R) minMACD := histMACD_R if maxRVSI < -1*minRVSI maxRVSI := -1*minRVSI if maxMACD < -1*minMACD maxMACD := -1*minMACD bothSameSign = false if ((histRVSI_R * histMACD_R) > 0) bothSameSign := true bothSignalsCombined = bothSameSign?(((histRVSI_R/maxRVSI)+(histMACD_R/maxMACD))/2):na var maxBoth =0. var minBoth =0. if (maxBoth < bothSignalsCombined) maxBoth := bothSignalsCombined if (minBoth > bothSignalsCombined) minBoth := bothSignalsCombined if maxBoth < -1*minBoth maxBoth := -1*minBoth buyBackground = color.green regular = #0000FF sellBackground = color.red color notrading = na sessioncolor = regular buyRVSIMACD = false sellRVSIMACD = false if (bothSignalsCombined > 0) sessioncolor := buyBackground buyRVSIMACD := true//useMACDRVSI if (bothSignalsCombined < 0) sessioncolor := sellBackground sellRVSIMACD := true//useMACDRVSI bgcolor(bothSignalsCombined != 0? sessioncolor:na, title="MACD/RVSI Confluence", transp=85) RSIclause = input(title="RSI clause", defval=true)//, inline="RSI2", group="RSI2") timeframeRSI = input(title="Timeframe RSI", type=input.resolution, defval="5" ) rsi_Longs__Crossover = 31//input(title="RSI Longs Crossover %", type=input.float, defval=31, maxval=100, minval=1, step=1) // how much (percentage) can price fall before exiting the trade rsi_Shorts_Crossunder = 69//input(title="RSI Shorts Crossunder %", type=input.float, defval=69, maxval=100, minval=1, step=1) // how much (percentage) can price fall before exiting the trade useRSI2 = true RSItimeframe2chart = false RSIlength2 = 14//input(title="Length RSI", defval=14)//, inline="RSI2", group="RSI2") RSIsrc2 = close RSIsmaLength2 = 3//input(title="RSI SMA Length", defval=3)//, inline="RSI2 sma", group="RSI2") RSIup2 = rma(max(change(RSIsrc2), 0), RSIlength2) RSIdown2 = rma(-min(change(RSIsrc2), 0), RSIlength2) RSI2 = RSIdown2 == 0 ? 100 : RSIup2 == 0 ? 0 : 100 - (100 / (1 + RSIup2 / RSIdown2)) RSIplot2 = security(syminfo.tickerid, timeframeRSI, RSI2[barstate.isrealtime ? 1 : 0], gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)[barstate.isrealtime ? 0 : 1] RSIsma2 = sma(RSIplot2, RSIsmaLength2) var RSIprevious =0. if RSIprevious == 0. RSIprevious:=-1 if crossunder (RSIsma2, rsi_Shorts_Crossunder) RSIprevious:= -1 if crossover (RSIsma2, rsi_Longs__Crossover) RSIprevious:= 1 var RSIonUpwards = false var RSIonDownwards = false RSIonUpwards := false RSIonDownwards := false if RSIclause and RSIprevious == 1 RSIonUpwards := true if RSIclause and RSIprevious == -1 RSIonDownwards := true if not RSIclause RSIonUpwards := true RSIonDownwards := true lookback1 = 4//input(title="lookback 1", type=input.integer, defval=4) lookback2 = 8//input(title="lookback 2", type=input.integer, defval=8) BuyComment_Long = Pair + " Long" BuyComment_Short = Pair + " Short" SellCommentTP_Long = "Take Profit" SellCommentTP_Short = "Take Profit" SellCommentTrend_Long = "Trend Shift" SellCommentTrend_Short = "Trend Shift" SellCommentTrailStopLoss_Long = "Trail StopLoss" SellCommentTrailStopLoss_Short = "Trail StopLoss" SellCommentRisingStopLoss_Long = "Ramp StopLoss" SellCommentRisingStopLoss_Short = "Ramp StopLoss" if Wunderbit BuyComment_Long := Enter_Long SellCommentTP_Long := Exit_Long BuyComment_Short := Enter_Short SellCommentTP_Short := Exit_Short SellCommentTrend_Long := SellCommentTP_Long SellCommentTrailStopLoss_Long := SellCommentTP_Long SellCommentRisingStopLoss_Long := SellCommentTP_Long SellCommentTrend_Short := SellCommentTP_Short SellCommentTrailStopLoss_Short := SellCommentTP_Short SellCommentRisingStopLoss_Short := SellCommentTP_Short timeframe1 = timeframe.period//input(title="Fast Stoch Timeframe ", type=input.resolution, defval="15" ) timeframe2 = input(group="Stochastic",title="Slow Stoch Timeframe (should be approx 4X present timeframe", type=input.resolution, defval="60" ) // get input i_length = input(group="Stochastic", title="Stochastic Length", minval=1, defval=18) i_k = input(group="Stochastic", title="Stochastic %K", minval=1, defval=2) i_d = input(group="Stochastic", title="Stochastic %D", minval=1, defval=10) i_sellThreshold_Longs = input(group="Stochastic Buy/Sell", title="LONGS: Stoch Sell/Close Threshold", type=input.float, defval=85.0, maxval=100, minval=0.0, step=5) i_buyThreshold_Longs = input(group="Stochastic Buy/Sell", title="LONGS: Stoch Buy/Open Threshold", type=input.float, defval=40.0, maxval=100, minval=0.0, step=5) i_sellThreshold_Shorts = input(group="Stochastic Buy/Sell", title="SHORTS: Stoch Sell/Close Threshold", type=input.float, defval=30.0, maxval=100, minval=0.0, step=5) i_buyThreshold_Shorts = input(group="Stochastic Buy/Sell", title="SHORTS: Stoch Buy/Open Threshold", type=input.float, defval=50.0, maxval=100, minval=0.0, step=5) stopLossLine = input(group="Trade Settings",title='Ramp Stop Loss Line % per candle', step=0.01,defval = 0.15 )/100 long_sl_inp = input(group="Trade Settings",title='Ramp Stop Loss Start %' , step=0.1 ,defval = 3.5 )/100 long_stop_level =0.0 long_stop_level :=long_stop_level[1] stopLineLongLevel = 0. stopLineLongLevel :=stopLineLongLevel[1] i_trailStopPercent = input(group="Trade Settings", title="Trailing Stop Percent", type=input.float, defval=3, maxval=100, minval=0.1, step=0.5)/100 i_takeProfit = input(group="Trade Settings", title="Take Profit", type=input.float, defval=2.5, maxval=100, minval=0.1, step=0.5)/100 sto = stoch(close, high, low, i_length) K = sma(sto, i_k) D = sma(K, i_d) stoch_A = security(syminfo.tickerid, timeframe1, D) stoch_B = security(syminfo.tickerid, timeframe2, D) stoch_A_upTrend = stoch_A > stoch_A[1] stoch_A_downTrend = stoch_A < stoch_A[1] stoch_B_upTrend = (stoch_B[lookback1] >= stoch_B[lookback2]) stoch_B_downTrend = (stoch_B[lookback1] <= stoch_B[lookback2]) var recentHigh = 0.0 var entryPrice = 0.0 var trailStop = 0.0 if Longs and barstate.isconfirmed if strategy.position_size == 0 if (stoch_A < i_buyThreshold_Longs) and stoch_A_upTrend and stoch_B_upTrend if RSIonUpwards if useMACDRVSI==false or (MACDonBuySell?buyRVSIMACD:(not sellRVSIMACD)) entryPrice := close recentHigh := close trailStop := (close * (1-i_trailStopPercent)) long_stop_level := entryPrice * (1 - long_sl_inp) stopLineLongLevel :=long_stop_level strategy.entry(id="Long", long=strategy.long, comment=BuyComment_Long) if strategy.position_size > 0 if close > recentHigh recentHigh := close trailStop := (recentHigh * (1-i_trailStopPercent)) strategy.exit(id="Long", stop=trailStop, comment=SellCommentTrailStopLoss_Long) //if (D[1] >= 80) and (D < 80) // strategy.close(id="Long", comment=SellCommentTrend) if crossunder(stoch_A, i_sellThreshold_Longs) // and barstate.isconfirmed and strategy.position_size > 0 strategy.close(id="Long", comment=SellCommentTrend_Long) if close > (entryPrice * (1+i_takeProfit)) //and barstate.isconfirmed and strategy.position_size > 0 strategy.close(id="Long", comment=SellCommentTP_Long) //if strategy.position_size > 0 stopLineLongLevel := stopLineLongLevel* (1+ stopLossLine) if close < stopLineLongLevel //and barstate.isconfirmed and strategy.position_size > 0 strategy.close(id="Long", comment=SellCommentRisingStopLoss_Long ) //else if Shorts and barstate.isconfirmed if strategy.position_size == 0 if (stoch_A > i_buyThreshold_Shorts) and stoch_A_downTrend and stoch_B_downTrend if RSIonDownwards if useMACDRVSI==false or (MACDonBuySell?sellRVSIMACD:(not buyRVSIMACD)) entryPrice := close recentHigh := close trailStop := (close * (1+i_trailStopPercent)) long_stop_level := entryPrice * (1 + long_sl_inp) stopLineLongLevel :=long_stop_level strategy.entry(id="Short", long=strategy.short, comment=BuyComment_Short) if strategy.position_size < 0 if close < recentHigh recentHigh := close trailStop := (recentHigh * (1+i_trailStopPercent)) strategy.exit(id="Short", stop=trailStop, comment=SellCommentTrailStopLoss_Short) if crossover(stoch_A, (i_sellThreshold_Shorts)) strategy.close(id="Short", comment=SellCommentTrend_Short) if close < (entryPrice * (1-i_takeProfit)) strategy.close(id="Short", comment=SellCommentTP_Short) stopLineLongLevel := stopLineLongLevel* (1 - stopLossLine) if close > stopLineLongLevel strategy.close(id="Short", comment=SellCommentRisingStopLoss_Short ) plot(strategy.position_size != 0 ? stopLineLongLevel : na, style=plot.style_linebr, color=color.red, linewidth=1, title="Ramp StopLoss") //plot(K, title="%K", color=color.blue, linewidth=1) //plot(stoch_A, title="Stoch A", color=color.orange, linewidth=1) //plot(stoch_B, title="Stoch B", color= stoch_B_upTrend ? color.green : color.red, style=plot.style_stepline) //upperBand = hline(i_sellThreshold, title="Upper Limit", linestyle=hline.style_dashed) //middleBand = hline(50, title="Midline", linestyle=hline.style_dotted) //lowerBand = hline(i_buyThreshold, title="Lower Limit", linestyle=hline.style_dashed) //fill(lowerBand, upperBand, color=color.purple, transp=75) //bgC = color.black //if strategy.position_size != 0 // bgC := color.green //bgcolor(bgC)
cRSI + Waves Strategy with VWMA overlay + sessions and order qty
https://www.tradingview.com/script/qqq7zKvk-cRSI-Waves-Strategy-with-VWMA-overlay-sessions-and-order-qty/
jadamcraig
https://www.tradingview.com/u/jadamcraig/
159
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/ // Β© Dr_Roboto; forked May 7, 2021 by jadamcraig // //@version=4 // // This indicator uses the cyclic smoothed Relative Strength Index (cRSI) instead of the traditional Relative Strength Index (RSI). See below for more info on the benefits to the cRSI. // // [b]My key contributions[/b] // 1) A Weighted Moving Average (WMA) to track the general trend of the cRSI signal. This is very helpful in determining when the equity switches from bullish to bearish, which can be used to determine buy/sell points. // This is then is used to color the region between the upper and lower cRSI bands (green above, red below). // 2) An attempt to detect the motive (impulse) and corrective and waves. Corrective waves are indicated A, B, C, D, E, F, G. F and G waves are not technically Elliot Waves, but the way I detect waves it is really hard // to always get it right. Once and a while you could actually see G and F a second time. Motive waves are identified as s (strong) and w (weak). Strong waves have a peak above the cRSI upper band and weak waves have a peak below the upper band. // 3) My own divergence indicator for bull, hidden bull, bear, and hidden bear. I was not able to replicate the TradingView style of drawing a line from peak to peak, but for this indicator I think in the end it makes the chart cleaner. // 4) I have also added "alert conditions" for most of the key events. Select the equity you want (such as: SPX) and the desired timeframe (such as: D). // Go to the TradingView "Alerts" tab (click the alarm clock icon) --> Create Alert (alarm clock with a +) --> Change the first condition drop down to "Cyclic Smoothed RSI with Motive-Corrective Wave Indicator" --> in the // drop down below that select the alert that you want (such as: Bull - cRSI Above WMA). You will want to give the alert a good name that includes the ticker name and time frame, for example "SPX 1D: Bull - cRSI above WMA" // // There is a latency issue with an indicator like this that is based on moving averages. That means they tend to trigger right after key events. Perfect timing is not possible strictly with these indicators, but they do work // very well "on average." However, my implementation has minimal latency as peaks (tops/bottoms) only require one bar to detect. // // As a bit of an Easter Egg, this code can be tweaked and run as a strategy to get buy/sell signals. I use this code for both my indicator and for trading strategy. Just copy and past it into a new strategy script and just // change it from study to something like. // strategy("cRSI + Waves Strategy with VWMA overlay", overlay=overlay) // The buy/sell code is at the end and just needs to be uncommented. I make no promises or guarantees about how good it is as a strategy, but it gives you some code and ideas to work with. // // [b]Tuning[/b] // 1) Volume Weighted Moving Average (VWMA): This is a β€œhidden strategy” feature implemented that will display the high-low bands of the VWMA on the price chart if run the code using β€œoverlay = true”. // - [Use Volume for VWMA] If the equity does not have volume, then the VWMA will not show up. Uncheck this box and it will use the regular WMA (no volume). // - [VWMA Length] defines how far back the WMA averages price. // // 2) cRSI (Black line in the indicator) // - [CRSI Dominate Cycle Length] Increase to length that amount of time a band (upper/lower) stays high/low after a peak. Reduce the value to shorten the time. Just increment it up/down to see the effect. // - [CRSI Moving Average Length] defines how far back the SMA averages the cRSI. This affects the purple line in the indicator. // - [CRSI Top/Bottom Detector Lookback] defines how many bars back the peak detector looks to determine if a peak has occurred. For example, a top is detected like this: current-bar down relative to the 1-bar-back, // 1-bar-back up relative to 2-bars-back (look back = 1), c) 2-bars-back up relative to 3-bars-back (lookback = 2), and d) 3-bars-back up relative to 4-bars-back (lookback = 3). I hope that makes sense. There are // only 2 options for this setting: 2 or 3 bars. 2 bars will be able to detect small peaks but create more β€œfalse” peaks that may not be meaningful. 3 bars will be more robust but can miss short duration peaks. // // 3) Waves // - The check boxes are self explanatory for which labels they turn on and off on the plot. // // 4) Divergence Indicators // - The check boxes are self explanatory for which labels they turn on and off on the plot. // // [b]Hints[/b] // - The most common parameter to change is the [CRSI Top/Bottom Detector Lookback]. Different stocks will have different levels of strength in their peaks. A setting of 2 may generate too many corrective waves. // - Different times scales will give you different wave counts. This is to be expected. A conunter impulse wave inside a corrective wave may actually go above the cRSI WMA on a smaller time frame. You may need to increase it one or two levels to see large waves. // - Just because you see divergence (bear or hidden bear) does not mean a price is going to go down. Often price continues to rise through bears, so take note and that is normal. Bulls are usually pretty good indicators especially if you see them on C,E,G waves. // // // --------------------------------------- // cyclic smoothed RSI (cRSI) indicator // --------------------------------------- // The β€œcore” code for the cyclic smoothed RSI (cRSI) indicator was written by Lars von Theinen and is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/. Copyright (C) 2017 CC BY, // whentotrade / Lars von Thienen. For more details on the cRSI Indicator: https://www.tradingview.com/script/TmqiR1jp-RSI-cyclic-smoothed-v2/ // // The cyclic smoothed RSI indicator is an enhancement of the classic RSI, adding // 1) additional smoothing according to the market vibration, // 2) adaptive upper and lower bands according to the cyclic memory and // 3) using the current dominant cycle length as input for the indicator. // It is much more responsive to market moves than the basic RSI. The indicator uses the dominant cycle as input to optimize signal, smoothing, and cyclic memory. To get more in-depth information on the cyclic-smoothed // RSI indicator, please read Decoding The Hidden Market Rhythm - Part 1: Dynamic Cycles (2017), Chapter 4: "Fine-tuning technical indicators." You need to derive the dominant cycle as input parameter for the cycle length as described in chapter 4. //================================================================================================================================= //================================================================================================================================= overlay = true // plots VWMA (need to close and re-added) // overlay = false // plots cRSI (need to close and re-added) strategy("cRSI + Waves Strategy with VWMA overlay + sessions and order qty", overlay=overlay) //================================================================================================================================= //================================================================================================================================= // Disables cRSI and VWMA plotting so debug data can be plotted // DEBUG = true DEBUG = false maxOrderSize = input(defval=4, title="Max Order Size", type=input.integer, minval=2) useSessions = input(defval=true, title="Limit Signals to Trading Sessions?") sess1_startHour = input(defval=3, title="Session 1: Start Hour", type=input.integer, minval=0, maxval=23) sess1_startMinute = input(defval=57, title="Session 1: Start Minute", type=input.integer, minval=0, maxval=59) sess1_stopHour = input(defval=10, title="Session 1: Stop Hour", type=input.integer, minval=0, maxval=23) sess1_stopMinute = input(defval=30, title="Session 1: Stop Minute", type=input.integer, minval=0, maxval=59) sess2_startHour = input(defval=12, title="Session 2: Start Hour", type=input.integer, minval=0, maxval=23) sess2_startMinute = input(defval=57, title="Session 2: Start Minute", type=input.integer, minval=0, maxval=59) sess2_stopHour = input(defval=14, title="Session 2: Stop Hour", type=input.integer, minval=0, maxval=23) sess2_stopMinute = input(defval=57, title="Session 2: Stop Minute", type=input.integer, minval=0, maxval=59) sess1_closeAll = input(defval=false, title="Close All at End of Session 1") sess2_closeAll = input(defval=true, title="Close All at End of Session 2") //================================================================================================================================= //================================================================================================================================= // Helper Functions //================================================================================================================================= //================================================================================================================================= // function to convert bool to int b2i(bval) => ival = bval ? 1 : 0 // function to look for a price in the lookback that is recently above the current price recentAbove(in, thresh, lookback) => found = false for i=0 to lookback if in[i] >= thresh found := true break if found res = true else res = false // is value rising or falling based on history isRisingFalling(in, lookback) => cntThresh = round(lookback*0.6) // majority = greater than 50% cntUp = 0 cntDown = 0 rising = false falling = false // count up the times it is above or below the current value for i=1 to lookback if in[0] > in[i] cntUp := cntUp + 1 else if in[0] < in[i] cntDown := cntDown + 1 // rising if cntUp > cntThresh rising := true else rising := false // falling if cntDown > cntThresh falling := true else falling := false // flat flat = not(rising) and not(falling) // if flat, then select preivous value for rising and falling if flat rising := rising[1] falling := falling[1] // return tuple [rising,falling,flat] // Do the last several prices form a top isTop(price, lookback) => if lookback == 3 // 3 prices back -> 3rd check helps ensure there was a down trend, but can miss some small reversals // up->up->down if (price[2] > price[3]) and (price[1] > price[2]) and (price[0] < price[1]) top = true else top = false else // 2 places back // up->down if (price[1] > price[2]) and (price[0] < price[1]) top = true else top = false // Do the last several prices form a bottom isBottom(price, lookback) => if lookback == 3 // 3 prices back -> 3rd check helps ensure there was a down trend, but can miss some small reversals // down->down->up if (price[2] < price[3]) and (price[1] < price[2]) and (price[0] > price[1]) bottom = true else bottom = false else // 2 prices back // down->up if (price[1] < price[2]) and (price[0] > price[1]) bottom = true else bottom = false // function to filter multiple signals in a row filterSignal(signalFlag, lookback) => signalFlagFilt = signalFlag for i = 1 to lookback signalFlagFilt := signalFlagFilt[0] == true and signalFlagFilt[i] == true ? false : signalFlagFilt //================================================================================================================================= //================================================================================================================================= // Price Movement //================================================================================================================================= //================================================================================================================================= priceRising = close[0] >= close[1] and close[1] >= close[2] priceFalling = close[0] <= close[1] and close[1] <= close[2] // plot(priceRising?1.0:0,color=color.green) // plot(priceFalling?1.0:0,color=color.red) //================================================================================================================================= //================================================================================================================================= // Volume Weighted Moving Average (VWMA) //================================================================================================================================= //================================================================================================================================= plotVWMA = overlay and not(DEBUG) // check if volume is available for this equity useVolume = input(title="Use Volume for VWMA (uncheck if equity does not have volume)", defval=true) vwmaLen = input(defval=21, title="VWMA Length", type=input.integer, minval=1, maxval=200) vwma = vwma(close, vwmaLen) vwma_high = vwma(high, vwmaLen) vwma_low = vwma(low, vwmaLen) if not(useVolume) vwma := wma(close, vwmaLen) vwma_high := wma(high, vwmaLen) vwma_low := wma(low, vwmaLen) // +1 when above, -1 when below, 0 when inside vwmaSignal(priceOpen, priceClose, vwmaHigh, vwmaLow) => sig = 0 color = color.gray if priceClose > vwmaHigh sig := 1 color := color.green else if priceClose < vwmaLow sig := -1 color := color.red else sig := 0 color := color.gray [sig,color] [vwma_sig, vwma_color] = vwmaSignal(open, close, vwma_high, vwma_low) priceAboveVWMA = vwma_sig == 1 ? true : false priceBelowVWMA = vwma_sig == -1 ? true : false // plot(priceAboveVWMA?2.0:0,color=color.blue) // plot(priceBelowVWMA?2.0:0,color=color.maroon) // bandTrans = input(defval=70, title="VWMA Band Transparancy (100 invisible)", type=input.integer, minval=0, maxval=100) // fillTrans = input(defval=70, title="VWMA Fill Transparancy (100 invisible)", type=input.integer, minval=0, maxval=100) bandTrans = 70 fillTrans = 70 // ***** Plot VWMA ***** highband = plot(plotVWMA?fixnan(vwma_high):na, title='VWMA High band', color = vwma_color, linewidth=1, transp=bandTrans) lowband = plot(plotVWMA?fixnan(vwma_low):na, title='VWMA Low band', color = vwma_color, linewidth=1, transp=bandTrans) fill(lowband, highband, title='VWMA Band fill', color=vwma_color, transp=fillTrans) plot(plotVWMA?vwma:na, title='VWMA', color = vwma_color, linewidth=3, transp=bandTrans) //================================================================================================================================= //================================================================================================================================= // Moving Average Convergence Divergence (MACD) //================================================================================================================================= //================================================================================================================================= [macdLine, signalLine, histLine] = macd(close, 12, 26, 9) // Is the histogram rising or falling histLineRising = histLine[0] >= histLine[1] and histLine[1] >= histLine[2] histLineFalling = histLine[0] <= histLine[1] and histLine[1] <= histLine[2] // Did the histogram cross over zero histLineCrossNeg2Pos = histLine[0] >= 0.0 and histLine[1] < 0.0 histLineCrossPos2Neg = histLine[0] <= 0.0 and histLine[1] > 0.0 // plot(histLineRising?1.0:0,color=color.green) // plot(histLineFalling?1.0:0,color=color.red) // plot(histLineCrossNeg2Pos?1.0:0,color=color.green) // plot(histLineCrossPos2Neg?1.0:0,color=color.red) //================================================================================================================================= //================================================================================================================================= // Cyclic Smoothed Relative Strength Index (cRSI) //================================================================================================================================= //================================================================================================================================= plotCRSI = not(overlay) and not(DEBUG) //src = input(title="cRSI Source", defval=close) src = close domcycle = input(10, minval=5, title="cRSI Dominant Cycle Length (persist after high/low)") //12 crsi = 0.0 cyclelen = domcycle / 2 vibration = 10 leveling = 10.0 cyclicmemory = domcycle * 2 //set min/max ranges? torque = 2.0 / (vibration + 1) phasingLag = (vibration - 1) / 2.0 up = rma(max(change(src), 0), cyclelen) down = rma(-min(change(src), 0), cyclelen) rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - 100 / (1 + up / down) crsi := torque * (2 * rsi - rsi[phasingLag]) + (1 - torque) * nz(crsi[1]) // there is a bug that can cause the lower bound to be bigger than the upper bound with a value of 999999.0 // lmax = -999999.0 // lmin = 999999.0 lmax = 0.0 // don't konw why, but this fixes the bug lmin = 0.0 for i = 0 to cyclicmemory - 1 by 1 if nz(crsi[i], -999999.0) > lmax lmax := nz(crsi[i]) lmax else if nz(crsi[i], 999999.0) < lmin lmin := nz(crsi[i]) lmin mstep = (lmax - lmin) / 100 aperc = leveling / 100 crsiLowband = 0.0 for steps = 0 to 100 by 1 testvalue = lmin + mstep * steps above = 0 below = 0 for m = 0 to cyclicmemory - 1 by 1 below := below + iff(crsi[m] < testvalue, 1, 0) below ratio = below / cyclicmemory if ratio >= aperc crsiLowband := testvalue break else continue crsiHighband = 0.0 for steps = 0 to 100 by 1 testvalue = lmax - mstep * steps above = 0 for m = 0 to cyclicmemory - 1 by 1 above := above + iff(crsi[m] >= testvalue, 1, 0) above ratio = above / cyclicmemory if ratio >= aperc crsiHighband := testvalue break else continue //================================================================================================================================= //================================================================================================================================= // cRSI moving average //================================================================================================================================= //================================================================================================================================= crsiMaLen = input(title="cRSI Moving Average Length", defval=50, minval=0, step=5, type=input.integer) // crsiSMA = sma(crsi,crsiMaLen) // crsiEMA = ema(crsi,crsiMaLen) crsiWMA = wma(crsi,crsiMaLen) // plot(crsiSMA, "CRSI SMA", color.red, linewidth=2) // plot(crsiEMA, "CRSI EMA", color.green, linewidth=2) // plot(crsiWMA, "CRSI WMA", color.fuchsia, linewidth=2) //================================================================================================================================= //================================================================================================================================= // cRSI Feature Analysis //================================================================================================================================= //================================================================================================================================= // Crossing of upper band crsiAboveHighband = crsi >= crsiHighband crsiBelowHighband = not(crsiAboveHighband) crsiCrossAboveHighband = crsiAboveHighband[0] and crsiBelowHighband[1] ? true : false crsiCrossBelowHighband = crsiBelowHighband[0] and crsiAboveHighband[1] ? true : false // plot(crsiAboveHighband?2.0:0,color=color.black) // plot(crsiBelowHighband?2.25:0,color=color.red) // plot(crsiCrossAboveHighband?2.5:0,color=color.green) // plot(crsiCrossBelowHighband?2.75:0,color=color.blue) //----------------------------------------------------------------------------- // Crossing of lower band crsiAboveLowband = crsi >= crsiLowband crsiBelowLowband = not(crsiAboveLowband) crsiCrossAboveLowband = crsiAboveLowband[0] and crsiBelowLowband[1] ? true : false crsiCrossBelowLowband = crsiBelowLowband[0] and crsiAboveLowband[1] ? true : false // plot(crsiAboveLowband?1.0:0,color=color.black) // plot(crsiBelowLowband?1.25:0,color=color.red) // plot(crsiCrossAboveLowband?1.5:0,color=color.green) // plot(crsiCrossBelowLowband?1.75:0,color=color.blue) //----------------------------------------------------------------------------- // Crossing of WMA crsiAboveWMA = crsi >= crsiWMA crsiBelowWMA = not(crsiAboveWMA) crsiCrossAboveWMA = crsiAboveWMA[0] and crsiBelowWMA[1] ? true : false crsiCrossBelowWMA = crsiBelowWMA[0] and crsiAboveWMA[1] ? true : false // plot(crsiAboveWMA?1.0:0,color=color.black) // plot(crsiBelowWMA?1.25:0,color=color.red) // plot(crsiCrossAboveWMA?1.5:0,color=color.blue) // plot(crsiCrossBelowWMA?1.75:0,color=color.maroon) //----------------------------------------------------------------------------- // Crossing of 50 level crsiAbove50 = crsi >= 50 crsiBelow50 = not(crsiAbove50) crsiCrossAbove50 = crsiAbove50[0] and crsiBelow50[1] ? true : false crsiCrossBelow50 = crsiBelow50[0] and crsiAbove50[1] ? true : false //----------------------------------------------------------------------------- // CRSI falling or rising crsiRising = crsi[0] >= crsi[1] crsiFalling = crsi[0] < crsi[1] // plot(crsiRising?3.0:0,color=color.green) // plot(crsiFalling?3.0:0,color=color.red) //----------------------------------------------------------------------------- // Compare cRSI to crsiWMA to determine if equity is bullish (motive) or bearish (corrective) bull = crsiAboveWMA bear = not(bull) bullBearColor = bull ? color.green : color.red bullStart = bull[0] and bear[1] ? true : false bearStart = bear[0] and bull[1] ? true : false alertcondition(bullStart, title='Bull - cRSI above WMA', message='Bull - cRSI above WMA') alertcondition(bearStart, title='Bear - cRSI below WMA', message='Bear - cRSI below WMA') //================================================================================================================================= //================================================================================================================================= // Plot cRSI colored by Bull or Bear //================================================================================================================================= //================================================================================================================================= // Basic RSI hline(plotCRSI?50:na, title="Middle Line", linestyle=hline.style_dashed, linewidth=2) h2 = hline(plotCRSI?70:na, title="Overbought", linestyle=hline.style_dashed, linewidth=2) h1 = hline(plotCRSI?30:na, title="Oversold", linestyle=hline.style_dashed, linewidth=2) fill(h1, h2, color=color.silver, transp=80) // cRSI crsiLB2 = plot(plotCRSI?crsiLowband:na, "cRSI LowBand", bullBearColor) crsiHB2 = plot(plotCRSI?crsiHighband:na, "cRSI HighBand", bullBearColor) fill(crsiLB2, crsiHB2, bullBearColor, transp=75) plot(plotCRSI?crsiWMA:na, "CRSI WMA", color.fuchsia, linewidth=2) plot(plotCRSI?crsi:na, "CRSI", color.black, linewidth=4) //================================================================================================================================= //================================================================================================================================= // Moitve (impulse) and Corrective Waves //================================================================================================================================= //================================================================================================================================= // THIS IS A MAJOR ASSUMPTION TO THIS APPROACH!!! motiveWave = bull correctiveWave = bear // TOP AND BOTTOM ARE DETECTED ONE BAR LATE!!! topBottomLookback = input(title="cRSI Top/Bottom Detector Lookback (3 is more robust but misses smaller)", defval=2, minval=2, maxval=3, step=1, type=input.integer) crsiTop = isTop(crsi, topBottomLookback) crsiBottom = isBottom(crsi,topBottomLookback) // Top above high band crsiTopAboveHighband = crsiTop and crsiAboveHighband[1] waveStrongImpulse = crsiTopAboveHighband // Top that does not break high band but is above WMA crsiTopBelowHighband = (crsiTop and crsiBelowHighband[1]) and (crsi > crsiWMA) waveWeakImpulse = crsiTopBelowHighband //----------------------------------------------------------------------------- // Determine the ABC, ABCDE, ABCDEFG sequence // Note that ABCDEFG is not a true Elliott corrective wave sequence, but for this approach is shows up once in a blue moon possibleWaveA = crsiBottom and crsiBelowLowband[1] possibleWaveB = (crsiTop and crsiBelowWMA[1]) or (crsiTop and crsiBelow50[1]) // Also catch the tops that are above wma but stay under RSI 50 (rare) possibleWaveC = possibleWaveA or (crsiBottom and crsiBelowWMA[1]) // sometimes wave C is above the lower band but below the WMA // Wave AB findWaveAB(possibleWaveA, possibleWaveB, correctiveWave) => isWaveAB = false foundMatch = false // start with Wave B if possibleWaveB // search backwards and look for wave A for i=1 to 50 // Equity must be in correction else invalidated if correctiveWave[i] if possibleWaveA[i] foundMatch := true break //else // keep looping else // motive wave invalidates search foundMatch := false break // Did we match an A and B wave? if foundMatch isWaveAB := true else isWaveAB := false else isWaveAB := false waveAB = findWaveAB(possibleWaveA, possibleWaveB, correctiveWave) // Wave ABC findWaveABC(possibleWaveC, waveAB, correctiveWave) => isWaveABC = false foundMatch = false if possibleWaveC // search backwards and look for wave AB for i=1 to 50 // Equity must be in correction else invalidated if correctiveWave[i] if waveAB[i] foundMatch := true break //else // keep looping else // motive wave invalidates search foundMatch := false break // Did we match a waveAB with C? if foundMatch isWaveABC := true else isWaveABC := false else isWaveABC := false waveABC = findWaveABC(possibleWaveC, waveAB, correctiveWave) // Wave ABCD findWaveABCD(possibleWaveB, waveABC, correctiveWave) => isWaveABCD = false foundMatch = false if possibleWaveB // search backwards and look for wave ABC for i=1 to 50 // Equity must be in correction else invalidated if correctiveWave[i] if waveABC[i] foundMatch := true break //else // keep looping else // motive wave invalidates search foundMatch := false break // Did we match a waveABC with D? if foundMatch isWaveABCD := true else isWaveABCD := false else isWaveABCD := false waveABCD = findWaveABCD(possibleWaveB, waveABC, correctiveWave) // Wave ABCDE findWaveABCDE(possibleWaveC, waveABCD, correctiveWave) => isWaveABCDE = false foundMatch = false if possibleWaveC // search backwards and look for another wave ABC in this correction for i=1 to 50 // Equity must be in correction else invalidated if correctiveWave[i] if waveABCD[i] foundMatch := true break //else // keep looping else // motive wave invalidates search foundMatch := false break // Did we match a waveABC with another waveABC? if foundMatch isWaveABCDE := true else isWaveABCDE := false else isWaveABCDE := false waveABCDE = findWaveABCDE(possibleWaveC, waveABCD, correctiveWave) // Wave ABCDEF findWaveABCDEF(possibleWaveB, waveABCDE, correctiveWave) => isWaveABCDEF = false foundMatch = false if possibleWaveB // search backwards and look for another wave ABC in this correction for i=1 to 50 // Equity must be in correction else invalidated if correctiveWave[i] if waveABCDE[i] foundMatch := true break //else // keep looping else // motive wave invalidates search foundMatch := false break // Did we match a waveABC with another waveABC? if foundMatch isWaveABCDEF := true else isWaveABCDEF := false else isWaveABCDEF := false waveABCDEF = findWaveABCDEF(possibleWaveB, waveABCDE, correctiveWave) // Wave ABCDEFG findWaveABCDEFG(possibleWaveC, waveABCDEF, correctiveWave) => isWaveABCDEFG = false foundMatch = false if possibleWaveC // search backwards and look for another wave ABC in this correction for i=1 to 50 // Equity must be in correction else invalidated if correctiveWave[i] if waveABCDEF[i] foundMatch := true break //else // keep looping else // motive wave invalidates search foundMatch := false break // Did we match a waveABC with another waveABC? if foundMatch isWaveABCDEFG := true else isWaveABCDEFG := false else isWaveABCDEFG := false waveABCDEFG = findWaveABCDEFG(possibleWaveC, waveABCDEF, correctiveWave) // Determine individual corrective waves waveA = possibleWaveA and not(waveABC) and not(waveABCDE) waveB = waveAB and not(waveABCD) waveC = waveABC waveD = waveABCD waveE = waveABCDE waveF = waveABCDEF waveG = waveABCDEFG //----------------------------------------------------------------------------- // Plot key cRSI points // plot(crsiCrossBelowHighband?crsi:na, title='cRSI cross below high band', color=color.red, linewidth=7, style=plot.style_circles) // plot(crsiCrossAboveLowband?crsi:na, title='cRSI cross above low band', color=color.green, linewidth=7, style=plot.style_circles) // plot(crsiCrossBelowWMA?crsi:na, title='cRSI cross below WMA', color=color.red, linewidth=5, style=plot.style_cross) // plot(crsiCrossAboveWMA?crsi:na, title='cRSI cross above WMA', color=color.green, linewidth=5, style=plot.style_cross) // plot(crsiCrossAbove50?crsi:na, title='cRSI cross above 50', color=color.black, linewidth=7, style=plot.style_circles) // plot(crsiCrossBelow50?crsi:na, title='cRSI cross below 50', color=color.black, linewidth=7, style=plot.style_circles) // plot(crsiTop?crsi[1]:na, title='cRSI Top', color=color.blue, linewidth=4, style=plot.style_cross, offset=-1) // plot(crsiBottom?crsi[1]:na, title='cRSI Top', color=color.purple, linewidth=4, style=plot.style_cross, offset=-1) //-------------------- // Impulse waves plotStrong = input(title="Plot Strong Impulse Waves (above upper band)", defval=true) and plotCRSI plotWeak = input(title="Plot Weak Impulse Waves (below upper band)", defval=true) and plotCRSI impWaveSz = size.tiny plotshape(plotStrong and waveStrongImpulse?crsi[1]:na, text="s", title='Strong Impulse', style=shape.labeldown, location=location.absolute, color=color.navy, transp=0, offset=-1, textcolor=color.white, size=impWaveSz) plotshape(plotWeak and waveWeakImpulse?crsi[1]:na, text="w", title='Weak Impulse', style=shape.labeldown, location=location.absolute, color=color.purple, transp=0, offset=-1, textcolor=color.white, size=impWaveSz) //--------------------- // Corrective waves // plot(possibleWaveC?crsi[1]:na, title='Possible Wave C', color=color.green, linewidth=6, style=plot.style_circles, offset=-1) // plot(possibleWaveB?crsi[1]:na, title='Possible Wave B', color=color.blue, linewidth=6, style=plot.style_circles, offset=-1) // plot(possibleWaveA?crsi[1]:na, title='Possible Wave A', color=color.purple, linewidth=6, style=plot.style_circles, offset=-1) // plot(waveAB?crsi[1]:na, title='Wave AB', color=color.black, linewidth=5, style=plot.style_cross, offset=-1) // plot(waveABC?crsi[1]:na, title='Wave ABC', color=color.black, linewidth=7, style=plot.style_cross, offset=-1) // plot(waveABCDE?crsi[1]:na, title='Wave ABCDE', color=color.black, linewidth=9, style=plot.style_cross, offset=-1) // plotshape(waveAB?crsi[1]:na, title='Wave AB', style=shape.triangledown, location=location.absolute, color=color.orange, transp=0, offset=-1, text="AB", textcolor=color.orange, size=size.small) // plotshape(waveABC?crsi[1]:na, title='Wave ABC', style=shape.triangleup, location=location.absolute, color=color.blue, transp=0, offset=-1, text="ABC", textcolor=color.blue, size=size.small) // plotshape(waveABCD?crsi[1]:na, title='Wave ABCD', style=shape.triangledown, location=location.absolute, color=color.red, transp=0, offset=-1, text="ABCD", textcolor=color.red, size=size.small) // plotshape(waveABCDE?crsi[1]:na, title='Wave ABCDE', style=shape.triangleup, location=location.absolute, color=color.green, transp=0, offset=-1, text="ABCDE", textcolor=color.green, size=size.small) plotWaves = input(title="Plot Corrective Waves (ABC,ABCDE)", defval=true) and plotCRSI corWaveSz = size.small plotshape(plotWaves and waveA?crsi[1]:na, text="A", title='Wave A', style=shape.labelup, location=location.absolute, color=color.blue, transp=0, offset=-1, textcolor=color.white, size=corWaveSz) plotshape(plotWaves and waveB?crsi[1]:na, text="B", title='Wave B', style=shape.labeldown, location=location.absolute, color=color.red, transp=0, offset=-1, textcolor=color.white, size=corWaveSz) plotshape(plotWaves and waveC?crsi[1]:na, text="C", title='Wave C', style=shape.labelup, location=location.absolute, color=color.green, transp=0, offset=-1, textcolor=color.white, size=corWaveSz) plotshape(plotWaves and waveD?crsi[1]:na, text="D", title='Wave D', style=shape.labeldown, location=location.absolute, color=color.maroon, transp=0, offset=-1, textcolor=color.white, size=corWaveSz) plotshape(plotWaves and waveE?crsi[1]:na, text="E", title='Wave E', style=shape.labelup, location=location.absolute, color=color.lime, transp=0, offset=-1, textcolor=color.white, size=corWaveSz) plotshape(plotWaves and waveF?crsi[1]:na, text="F", title='Wave F', style=shape.labeldown, location=location.absolute, color=color.fuchsia, transp=0, offset=-1, textcolor=color.white, size=corWaveSz) plotshape(plotWaves and waveG?crsi[1]:na, text="G", title='Wave G', style=shape.labelup, location=location.absolute, color=color.aqua, transp=0, offset=-1, textcolor=color.white, size=corWaveSz) //--------------------- // PRICE CHANGE BETWEEN IMPULSE AND WAVE A //================================================================================================================================= //================================================================================================================================= // Divergence Indicator Using cRSI //================================================================================================================================= //================================================================================================================================= plotBull = input(title="Plot Bullish (cRSI Higher-Low : Price Lower-Low)", defval=true) and plotCRSI plotHiddenBull = input(title="Plot Hidden Bullish (cRSI Lower-Low : Price Higher-Low)", defval=true) and plotCRSI plotBear = input(title="Plot Bearish (cRSI Lower-High : Price Higher-High", defval=true) and plotCRSI plotHiddenBear = input(title="Plot Hidden Bearish (cRSI Higher-High : Price Lower-High)", defval=true) and plotCRSI //------------------------------------------------------------------------------ crsiHighs = waveStrongImpulse or waveWeakImpulse crsiLows = possibleWaveA or possibleWaveC //------------------------------------------------------------------------------ // Regular Bullish --> cRSI makes a Higher-Low, but price makes a Lower-Low // Hidden Bullish --> cRSI makes a Lower-Low, but price makes a Higher-Low bullish(crsiLows, crsi, price) => foundLow = false crsiHigherLow = false priceHigher = false regularBullish = false hiddenBullish = false if crsiLows[0] == true for i=1 to 50 if crsiLows[i] == true foundLow := true // crsi higher or lower? if crsi[0] > crsi[i] crsiHigherLow := true else crsiHigherLow := false // price higher or lower if price[0] > price[i] priceHigher := true else priceHigher := false // found low, stop looking break else continue if foundLow // Regular Bullish --> cRSI makes a Higher-Low, but price makes a Lower-Low if (crsiHigherLow==true) and (priceHigher==false) regularBullish := true hiddenBullish := false // Hidden Bullish --> cRSI makes a Lower-Low, but price makes a Higher-Low else if (crsiHigherLow==false) and (priceHigher==true) regularBullish := false hiddenBullish := true else regularBullish := false hiddenBullish := false else regularBullish := false hiddenBullish := false else // this is not a low regularBullish := false hiddenBullish := false // return tuple [regularBullish,hiddenBullish] [regularBullish,hiddenBullish] = bullish(crsiLows, crsi, close) plotshape(plotBull and regularBullish?crsi[1]-12:na, text="Bull", title='Bull', style=shape.labelup, location=location.absolute, color=color.green, transp=0, offset=-1, textcolor=color.white, size=corWaveSz) plotshape(plotHiddenBull and hiddenBullish?crsi[1]-12:na, text="H Bull", title='Hidden Bull', style=shape.labelup, location=location.absolute, color=color.green, transp=20, offset=-1, textcolor=color.white, size=corWaveSz) //------------------------------------------------------------------------------ // Regular Bearish --> cRSI makes a Lower-High, but price makes a Higher-High // Hidden Bearish --> cRSI makes a Higher-High, but price makes a Lower-High bearish(crsiHighs, crsi, price) => foundHigh = false crsiHigherHigh = false priceHigher = false regularBearish = false hiddenBearish = false if crsiHighs[0] == true for i=1 to 50 if crsiHighs[i] == true foundHigh := true // crsi higher or lower? if crsi[0] > crsi[i] crsiHigherHigh := true else crsiHigherHigh := false // price higher or lower if price[0] > price[i] priceHigher := true else priceHigher := false // found high, stop looking break else continue if foundHigh // Regular Bearish --> cRSI makes a Lower-High, but price makes a Higher-High if (crsiHigherHigh==false) and (priceHigher==true) regularBearish := true hiddenBearish := false // Hidden Bearish --> cRSI makes a Higher-High, but price makes a Lower-High else if (crsiHigherHigh==true) and (priceHigher==false) regularBearish := false hiddenBearish := true else regularBearish := false hiddenBearish := false else regularBearish := false hiddenBearish := false else // this is not a low regularBearish := false hiddenBearish := false // return tuple [regularBearish,hiddenBearish] [regularBearish,hiddenBearish] = bearish(crsiHighs, crsi, close) plotshape(plotBear and regularBearish?crsi[1]+10:na, text="Bear", title='Bear', style=shape.labeldown, location=location.absolute, color=color.red, transp=0, offset=-1, textcolor=color.white, size=corWaveSz) plotshape(plotHiddenBear and hiddenBearish?crsi[1]+10:na, text="H Bear", title='Hidden Bear', style=shape.labeldown, location=location.absolute, color=color.red, transp=20, offset=-1, textcolor=color.white, size=corWaveSz) //================================================================================================================================================================================================================================================================== //================================================================================================================================================================================================================================================================== //================================================================================================================================================================================================================================================================== // Buy/Sell Strategy //================================================================================================================================================================================================================================================================== //================================================================================================================================================================================================================================================================== //================================================================================================================================================================================================================================================================== // Remove duplicate buy/sells if one was already executed recently filterLookback = 5 // normalize a value in a range between min and max normalize(val, valMin, valMax) => valNorm = val valNorm := valNorm < valMin ? valMin : valNorm valNorm := valNorm > valMax ? valMax : valNorm valNorm := (valNorm-valMin) / (valMax-valMin) recentWave(wave, lookback) => ret = false found = false for i=0 to lookback if wave[i] == true found := true break if found ret := true else ret := false //----------------------------------------------------------------------------- // Levels for upper band - High crsiHighband_extremeHighLevel = 90 crsiHighband_highLevel = 70 crsiHighband_highWeight = normalize(crsiHighband, crsiHighband_highLevel, crsiHighband_extremeHighLevel) // Levels for upper band - Low crsiHighband_extremeLowLevel = 45 crsiHighband_lowLevel = 55 crsiHighband_lowWeight = 1.0 - normalize(crsiHighband, crsiHighband_extremeLowLevel, crsiHighband_lowLevel) // plot(crsiHighband_highWeight,color=color.blue) // plot(crsiHighband_lowWeight,color=color.red) //----------------------------------------------------------------------------- // // Levels for lower band - High crsiLowband_extremeHighLevel = 80 crsiLowband_highLevel = 60 crsiLowband_higheight = normalize(crsiLowband, crsiLowband_highLevel, crsiLowband_extremeHighLevel) // Levels for lower band - Low crsiLowband_extremeLowLevel = 20 crsiLowband_lowLevel = 45 crsiLowband_lowWeight = 1.0 - normalize(crsiLowband, crsiLowband_extremeLowLevel, crsiLowband_lowLevel) // plot(crsiLowband_highWeight,color=color.blue) // plot(crsiLowband_lowWeight,color=color.red) //-------------------------------------------------------------------------------------------- // DETERMINE IF NEW TRADES ARE PERMITTED //-------------------------------------------------------------------------------------------- newTrades = false if (useSessions) if ( hour == sess1_startHour and minute >= sess1_startMinute ) newTrades := true else if ( hour > sess1_startHour and hour < sess1_stopHour ) newTrades := true else if ( hour == sess1_stopHour and minute < sess1_stopMinute ) newTrades := true else if ( hour == sess2_startHour and minute >= sess2_startMinute ) newTrades := true else if ( hour > sess2_startHour and hour < sess2_stopHour ) newTrades := true else if ( hour == sess2_stopHour and minute < sess2_stopMinute ) newTrades := true else newTrades := false else newTrades := true //-------------------------------------------------------------------------------------------- // SELL //-------------------------------------------------------------------------------------------- maxSellOrderSize = maxOrderSize crsiHighband_above_crsiHighband_highLevel = crsiHighband > crsiHighband_highLevel ? true : false Sell1 = waveStrongImpulse Sell2 = crsiAboveHighband and crsiFalling ? true : false // Above high band and now falling Sell3 = crsiAboveHighband[1] and crsiFalling ? true : false // 1x previous was above high band and now falling (sometimes it can be off by a bar) Sell4 = crsiAboveHighband[2] and crsiFalling ? true : false // 2x previous was above high band and now falling (sometimes it can be off by a bar) //Sell = Sell1 //and crsiHighband_above_crsiHighband_highLevel // Sell = Sell1 //and crsiHighband_above_crsiHighband_highLevel // Sell = (Sell1 or Sell2) //and crsiHighband_above_crsiHighband_highLevel // Sell = (Sell1 or Sell2 or Sell3) //and crsiHighband_above_crsiHighband_highLevel Sell = (Sell1 or Sell2 or Sell3 or Sell4) and crsiHighband_above_crsiHighband_highLevel Sell := filterSignal(Sell, filterLookback) // Base sell size on how high the Highband is sellSize = crsiHighband_highWeight *maxSellOrderSize // When in doubt, DON'T SELL! Stonks only go up ;) // extreme cRSI sellSize := crsi > crsiHighband_extremeHighLevel ? 1.5*maxSellOrderSize : sellSize // if the sell size is small, just make min sell sellSize := sellSize < maxSellOrderSize/3 ? 0 : sellSize sellSize := round(sellSize) if (Sell and newTrades) strategy.order("Sell", false, sellSize) //-------------------------------------------------------------------------------------------- // BUY - Price can continue to fall even when cRSI is rising!!! //-------------------------------------------------------------------------------------------- maxBuyOrderSize = maxOrderSize // Wait until it crosses back above WMA so it is clear that motive wave is clear. // Buying at the bottom is really hard because RSI can start to rise yet price will continue to fall Buy1 = bullStart // Using waves can help do a better job timing the bottom, but big corrections can go much deeper than just Wave C (Zig Zag) Buy2 = waveA and regularBullish Buy3 = waveC and regularBullish Buy4 = waveE and (topBottomLookback == 3) // usullay max is a wave E with topBottomLookback == 3 Buy5 = waveG and (topBottomLookback == 2) // can see a G wave when topBottomLookback == 2 Buy = Buy1 or Buy2 or Buy3 or Buy4 or Buy5 Buy := filterSignal(Buy, filterLookback) // Base buy size on how low the Lowband is buySize = crsiLowband_lowWeight*maxBuyOrderSize // buySize := buySize < 1 ? 1 : buySize // When in doubt, BUY! Stonks only go up ;) // Look for recent wave endings that can increase our guess of buying at a low recentWaveC = recentWave(waveC, 10) recentWaveE = recentWave(waveE, 10) recentWaveG = recentWave(waveG, 10) // buySize := recentWaveE ? 1.5*maxBuyOrderSize : buySize // buySize := recentWaveG ? 1.5*maxBuyOrderSize : buySize buySize := recentWaveE ? maxBuyOrderSize : buySize buySize := recentWaveG ? maxBuyOrderSize : buySize // if the buy size is small, just make min buy buySize := buySize < maxSellOrderSize/3 ? 0 : buySize buySize := round(buySize) if (Buy and newTrades) strategy.order("Buy", true, buySize) // Close open position at end of Session 1, if enabled if (sess1_closeAll and hour == sess1_stopHour and minute >= sess1_stopMinute ) strategy.close_all() // Close open position at end of Session 2, if enabled if (sess2_closeAll and hour == sess2_stopHour and minute >= sess2_stopMinute ) strategy.close_all()
Alex Days HiLo Rajib
https://www.tradingview.com/script/tke82Sib-Alex-Days-HiLo-Rajib/
14rajib
https://www.tradingview.com/u/14rajib/
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/ // Β© 14rajib //@version=4 strategy(title="Alex Days HiLo Rajib", overlay = true) length = input(20) hh = highest(high, length) ll = lowest(low, length) plot(hh[1], color=color.green, title="HH") plot(ll[1], color=color.red, title="LL") //bgColour = (high > hh) ? color.blue : // (low < ll) ? color.yellow : // na //bgcolor(color=bgColour, transp=90) plotshape(high>hh[1] ? hh + 5:na, color=#FF0000,location=location.absolute, style=shape.arrowdown) plotshape(low< ll[1] ? ll-5: na, color=#00FF00, location=location.absolute, style=shape.arrowup)
EMA & Supertrend
https://www.tradingview.com/script/elShbJCK-EMA-Supertrend/
bhavikmota
https://www.tradingview.com/u/bhavikmota/
157
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/ // Β© bhavikmota //@version=4 strategy("EMA & Supertrend", overlay = true) //length = input(9, minval=1) //ema1 = ema(close, length) //ema2 = ema(ema1, length) //ema3 = ema(ema2, length) //shortest = ema(close, 20) //short = ema(close, 50) //longer = ema(close, 100) //longest = ema(close, 200) //for Ema1 len1 = input(21, minval=1) //src1 = input(close) ema1 = ema(close,len1) plot(ema1, color=color.red, linewidth=1) //for Ema2 len2 = input(55, minval=1) //src2 = input(close) ema2 = ema(close,len2) plot(ema2, color=color.green, linewidth=1) //for Ema3 len3 = input(200, minval=1) //src3 = input(close) ema3 = ema(close,len3) plot(ema3, color=color.blue, linewidth=1) //for Ema4 len4 = input(233, minval=1) //src4 = input(close) ema4 = ema(close,len4) plot(ema4, color=color.black, linewidth=1) 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 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) alertcondition(buySignal, title="SuperTrend Buy", message="SuperTrend Buy!") alertcondition(sellSignal, title="SuperTrend Sell", message="SuperTrend Sell!") changeCond = trend != trend[1] alertcondition(changeCond, title="SuperTrend Direction Change", message="SuperTrend has changed direction!") //Trading logic Enterlong = crossover(ema1,ema2) or (close>ema1 and close>ema2 and ema1>ema2) and close>ema4// positive ema crossover Exitlong = crossunder(close,ema2) // candle closes below supertrend Entershort = crossunder(ema1,ema2) or (close<ema1 and close<ema2 and ema2<ema1) and close<ema4// negative ema crossover Exitshort = crossover(close,ema2) // candle closes above supertrend //Execution Logic - Placing Order start = timestamp(2008,1,1,0,0) if time>= start strategy.entry("long", strategy.long, 100, when=Enterlong) strategy.close("long",when=Exitlong) //strategy.entry("short",strategy.short,100,when=Entershort) //strategy.close("short",when=Exitshort)
Richard's Strategy
https://www.tradingview.com/script/ZD4V9sA1-Richard-s-Strategy/
Deepak8369
https://www.tradingview.com/u/Deepak8369/
38
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/ // Β© melodyera0822 //@version=4 strategy("Richard Strategy", overlay=true) // User input variable_for_stoploss = input(4,title="stop loss var") lenght = input(20,title="lenght") // high_low _20_day_highest = highest(nz(close[1]), lenght) _20_day_lowest = lowest(nz(close[1]), lenght) _10_day_low = lowest(nz(close[1]), lenght/2) _10_day_high = highest(nz(close[1]), lenght/2) //indicators atr20 = atr(20) ema_atr20 = ema(atr20,20) //vars var traded = "false" var buy_sell = "none" var buyExit = false var sellExit = false var stoploss = 0 buyCon = close > _20_day_highest and traded == "false" plotshape(buyCon,style = shape.triangleup,location = location.belowbar, color = color.green ) if (buyCon) strategy.entry("long", strategy.long, when = buyCon) traded := "true" buy_sell := "buy" stoploss := round(close - variable_for_stoploss * ema_atr20) sellCon = close < _20_day_lowest and traded == "false" plotshape(sellCon,style = shape.triangledown, color = color.red ) if (sellCon) strategy.entry("short", strategy.short) traded := "true" buy_sell := "sell" stoploss := round(close - variable_for_stoploss * ema_atr20) if traded == "true" if buy_sell == "buy" and ((close<stoploss)or(close<_10_day_low)) strategy.close("long") buyExit := true traded := "false" if buy_sell == "sell" and ((close>stoploss)or(close>_10_day_high)) strategy.close("short") sellExit := true traded := "false" plotshape(buyExit,style = shape.triangleup,location = location.belowbar, color = color.yellow ) buyExit := false plotshape(sellExit,style = shape.triangledown, color = color.yellow ) sellExit := false
All in One Strategy
https://www.tradingview.com/script/6vHRkdsf-All-in-One-Strategy/
Solutions1978
https://www.tradingview.com/u/Solutions1978/
671
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ //@version=4 // β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•— β–ˆβ–ˆβ•— //β–ˆβ–ˆβ•”β•β•β•β•β•β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β•β•β•β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β•šβ•β•β–ˆβ–ˆβ•”β•β•β•β–ˆβ–ˆβ•”β•β•β•β•β•β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•— β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β•šβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•”β• //β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β• β•šβ–ˆβ–ˆβ–ˆβ–ˆβ•”β• //β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β• β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β•β•β• β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•— β•šβ–ˆβ–ˆβ•”β• //β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β• β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β• β–ˆβ–ˆβ•‘ // β•šβ•β•β•β•β•β•β•šβ•β• β•šβ•β•β•šβ•β•β•β•β•β•β•β•šβ•β• β•šβ•β• β•šβ•β• β•šβ•β•β•β•β•β•β•β•šβ•β•β•β•β•β• β•šβ•β•β•β•β•β• β•šβ•β• //β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•— β–ˆβ–ˆβ•— β–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— //β–ˆβ–ˆβ•”β•β•β•β•β•β–ˆβ–ˆβ•”β•β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β•šβ•β•β–ˆβ–ˆβ•”β•β•β•β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β•β•β•β–ˆβ–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β•šβ•β•β•β•β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•— //β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β–ˆβ–ˆβ•— β–ˆβ–ˆβ•‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β•šβ–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β•β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β• //β•šβ•β•β•β•β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘β•šβ•β•β•β•β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β•šβ•β•β•β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β• β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•— //β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β• β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ•‘ β•šβ–ˆβ–ˆβ–ˆβ–ˆβ•‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β• β–ˆβ–ˆβ•‘ β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β• //β•šβ•β•β•β•β•β•β• β•šβ•β•β•β•β•β• β•šβ•β•β•β•β•β•β• β•šβ•β•β•β•β•β• β•šβ•β• β•šβ•β• β•šβ•β•β•β•β•β• β•šβ•β• β•šβ•β•β•β•β•šβ•β•β•β•β•β•β• β•šβ•β• β•šβ•β•β•β•β• β•šβ•β• β•šβ•β•β•β•β• strategy(shorttitle='Ain1v4',title='All in One Strategy', overlay=true, scale=scale.left, initial_capital = 1000, process_orders_on_close=true, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type=strategy.commission.percent, commission_value=0.18, calc_on_every_tick=true) kcolor = color.new(#0094FF, 60) dcolor = color.new(#FF6A00, 60) // ----------------- Strategy Inputs ------------------------------------------------------------- //Backtest dates with auto finish date of today start = input(defval = timestamp("22 June 2021 00:00 -0500"), title = "Start Time", type = input.time) finish = input(defval = timestamp("31 December 2021 00:00 -0600"), title = "End Time", type = input.time) window() => time >= start and time <= finish ? true : false // create function "within window of time" // Strategy Selection - Long, Short, or Both stratinfo = input(true, "Long/Short for Mixed Market, Long for Bull, Short for Bear") strat = input(title="Trade Types", defval="Long/Short", options=["Long Only", "Long/Short", "Short Only"]) strat_val = strat == "Long Only" ? 1 : strat == "Long/Short" ? 0 : -1 // Risk Management Inputs sl= input(10.0, "Stop Loss %", minval = 0, maxval = 100, step = 0.01) stoploss = sl/100 tp = input(20.0, "Target Profit %", minval = 0, maxval = 100, step = 0.01) TargetProfit = tp/100 ld = input(2, "Stop Trading After This Many Losing Days", type=input.integer, minval=0, maxval=100, step=1) strategy.risk.max_cons_loss_days(count=ld) ml = input(10, "Maximum % of Equity Lost to Halt Trading", type=input.integer, minval=1, maxval=100, step=1) strategy.risk.max_drawdown(value=ml, type=strategy.percent_of_equity) useXRSI = input(false, "Use RSI crossing back, select only one strategy") useCRSI = input(false, "Use Tweaked Connors RSI, select only one") RSIInfo = input(true, "These are the RSI Strategy Inputs, RSI Length applies to MACD, set OB and OS to 45 for using Stoch and EMA strategies.") length = input(14, "RSI Length", minval=1) overbought= input(62, "Overbought") oversold= input(35, "Oversold") cl1 = input(3, "Connor's MA Length 1", minval=1, step=1) cl2 = input(20, "Connor's MA Lenght 2", minval=1, step=1) cl3 = input(50, "Connor's MA Lenght 3", minval=1, step=1) // MACD and EMA Inputs useMACD = input(false, "Use MACD Only, select only one strategy") useEMA = input(false, "Use EMA Only, select only one strategy (EMA uses Stochastic inputs too)") MACDInfo=input(true, "These are the MACD strategy variables") fastLength = input(5, minval=1, title="EMA Fast Length") slowLength = input(10, minval=1, title="EMA Slow Length") ob_min = input(52, "Overbought Lookback Minimum Value", minval=0, maxval=200) ob_lb = input(25, "Overbought Lookback Bars", minval=0, maxval=100) os_min = input(50, "Oversold Lookback Minimum Value", minval=0, maxval=200) os_lb = input(35, "Oversold Lookback Bars", minval=0, maxval=100) source = input(title="Source", type=input.source, defval=close) RSI = rsi(source, length) // Price Movement Inputs PriceInfo = input(true, "Price Change Percentage Cross Check Inputs for all Strategies, added logic to avoid early sell. This is different from setting of max loss in risk management.") lkbk = input(5,"Max Lookback Period") // EMA and SMA Background Inputs useStoch = input(false, "Use Stochastic Strategy, choose only one") StochInfo = input(true, "Stochastic Strategy Inputs") smoothK = input(3, "K", minval=1) periodK = input(14, "K Period", minval=1) periodD = input(3, "D Period", minval=1) k_mode = input("SMA", "K Mode", options=["SMA", "EMA", "WMA"]) high_source = input(high,"High Source") low_source= input(low,"Low Source") // Selections to show or hide the overlays showZones = input(true, title="Show Bullish/Bearish Zones") showStoch = input(true, title="Show Stochastic Overlays") showRSIBS = input(true, title="Show RSI Buy Sell Zones") showMACD = input(true, title="Show MACD") color_bars=input(true, "Color Bars") // ----------------------- Dynamic RSI -------------------------------------- // Define f_print function to show key recommendations for RSI f_print(_text) => // Create label on the first bar. var _label = label(na), label.delete(_label), _label := label.new( time + (time-time[1]), ohlc4, _text, xloc.bar_time, yloc.price, color(na), label.style_none, color.gray, size.large, text.align_left ) // Display highest and lowest RSI values AvgHigh(src,cnt,val) => total = 0.0 count = 0 for i = 0 to cnt if src[i] > val count := count + 1 total := total + src[i] round(total / count) RSI_high = AvgHigh(RSI, ob_lb, ob_min) AvgLow(src,cnt,val) => total = 0.0 count = 0 for i = 5 to cnt by 5 if src[i] < val count := count + 1 total := total + src[i] round(total / count) RSI_low = AvgLow(RSI, os_lb, os_min) f_print("Recommended RSI Settings:" + "\nOverbought = " + tostring(RSI_high) + "\nOversold = " + tostring(RSI_low)) // Plot Oversold and Overbought Lines over = hline(oversold, title="Oversold", color=color.green) under = hline(overbought, title="Overbought", color=color.red) fillcolor = color.new(#9915FF, 90) fill(over, under, fillcolor, title="Band Background") // ------------------ Background Colors based on EMA Indicators ----------------------------------- rsi_ema = ema(RSI, length) emaA = ema(rsi_ema, fastLength) emaFast = 2 * emaA - ema(emaA, fastLength) emaB = ema(rsi_ema, slowLength) emaSlow = 2 * emaB - ema(emaB, slowLength) // New Bullish and Bearish Signal Rule logic check out = ema(RSI, length) // bullish signal rule: bullishRule =emaFast > emaSlow and out >=out[1] // bearish signal rule: bearishRule =emaFast < emaSlow and out <= out[1] EMAShortSell = crossunder(rsi_ema, emaFast) and crossunder(rsi_ema, emaSlow) and bearishRule and window() EMAShortBuy = crossover(rsi_ema, emaFast) and crossover(rsi_ema, emaSlow) and bullishRule and window() EMALongBuy = crossover(rsi_ema, emaSlow) and crossover(rsi_ema, emaFast) and bullishRule and window() EMALongSell = crossunder(emaFast, emaSlow) and bearishRule and window() // current trading State ruleState = 0 ruleState := bullishRule ? 1 : bearishRule ? -1 : nz(ruleState[1]) ruleColor = ruleState==1 ? color.new(color.blue, 90) : ruleState == -1 ? color.new(color.red, 90) : ruleState == 0 ? color.new(color.gray, 90) : na bgcolor(showZones ? ruleColor : na, title="Bullish/Bearish Zones") // ------------------ Price Percentage Change Calculation --------------------------------------- perc_change(lkbk) => overall_change = ((close[0] - open[lkbk]) / open[lkbk]) * 100 highest_high = 0.0 lowest_low = 0.0 for i = lkbk to 0 highest_high := i == lkbk ? high : high[i] > high[(i + 1)] ? high[i] : highest_high[1] lowest_low := i == lkbk ? low : low[i] < low[(i + 1)] ? low[i] : lowest_low[1] start_to_high = ((highest_high - open[lkbk]) / open[lkbk]) * 100 start_to_low = ((lowest_low - open[lkbk]) / open[lkbk]) * 100 previous_to_high = ((highest_high - open[1])/open[1])*100 previous_to_low = ((lowest_low-open[1])/open[1])*100 previous_bar = ((close[1]-open[1])/open[1])*100 [overall_change, start_to_high, start_to_low, previous_to_high, previous_to_low, previous_bar] // Call the function [overall, to_high, to_low, last_high, last_low, last_bar] = perc_change(lkbk) // Plot the function //plot(overall*50, color=color.white, title='Overall Percentage Change', linewidth=3) //plot(to_high*50, color=color.green,title='Percentage Change from Start to High', linewidth=2) //plot(to_low*50, color=color.red, title='Percentage Change from Start to Low', linewidth=2) //plot(last_high*100, color=color.teal, title="Previous to High", linewidth=2) //plot(last_low*100, color=color.maroon, title="Previous to Close", linewidth=2) //plot(last_bar*100, color=color.orange, title="Previous Bar", linewidth=2) //hline(0, title='Center Line', color=color.orange, linewidth=2) true_dip = overall < 0 and to_high > 0 and to_low < 0 and last_high > 0 and last_low < 0 and last_bar < 0 true_peak = overall > 0 and to_high > 0 and to_low > 0 and last_high > 0 and last_low < 0 and last_bar > 0 // ------------------ Stochastic Indicator Overlay ----------------------------------------------- // Calculation // Use highest highs and lowest lows h_high = highest(high_source ,lkbk) l_low = lowest(low_source ,lkbk) stoch = stoch(close, high_source, low_source, periodK) k = k_mode=="EMA" ? ema(stoch, smoothK) : k_mode=="WMA" ? wma(stoch, smoothK) : sma(stoch, smoothK) d = sma(k, periodD) k_c = change(k) d_c = change(d) kd = k - d // Plot signalColor = k>oversold and d<overbought and k>d and k_c>0 and d_c>0 ? kcolor : k<overbought and d>oversold and k<d and k_c<0 and d_c<0 ? dcolor : na kp = plot(showStoch ? k : na, "K", color=kcolor) dp = plot(showStoch ? d : na, "D", color=dcolor) fill(kp, dp, color = signalColor, title="K-D") signalUp = showStoch ? not na(signalColor) and kd>0 : na signalDown = showStoch ? not na(signalColor) and kd<0 : na //plot(signalUp ? kd : na, "Signal Up", color=kcolor, transp=90, style=plot.style_columns) //plot(signalDown ? (kd+100) : na , "Signal Down", color=dcolor, transp=90, style=plot.style_columns, histbase=100) StochBuy = crossover(k, d) and k_c>0 and d_c>0 and k<RSI and d<RSI and window() StochSell = crossunder(k, d) and k_c<0 and d_c<0 and k<RSI and d<RSI and window() // -------------- Add Price Movement to Strategy for better visualization ------------------------- // Calculations h1 = vwma(high, length) l1 = vwma(low, length) hp = h_high[1] lp = l_low[1] // Plot var plot_color=#353535 var sig = 0 if (h1 >hp) sig:=1 plot_color:=color.lime else if (l1 <lp) sig:=-1 plot_color:=color.maroon //plot(1,title = "Price Movement Bars", style=plot.style_columns,color=plot_color) //plot(sig,title="Signal 1 or -1",display=display.none) // --------------------------------------- RSI Plot ---------------------------------------------- // Show RSI and EMA crosses with arrows and RSI Color (tweaked Connors RSI) // Improves strategy setting ease by showing where EMA 5 crosses EMA 10 from above to confirm overbought conditions or trend reversals // This shows where you should enter shorts or exit longs // Tweaked Connors RSI Calculation connor_ob = overbought connor_os = oversold ma1 = sma(close,cl1) ma2 = sma(close, cl2) ma3 = sma(close, cl3) // Buy Sell Zones using tweaked Connors RSI (RSI values of 80 and 20 for Crypto as well as ma3, ma20, and ma50 are the tweaks) RSI_SELL = ma1 > ma2 and open > ma3 and RSI >= connor_ob and true_peak and window() RSI_BUY = ma2 < ma3 and ma3 > close and RSI <= connor_os and true_dip and window() // Color Definition col = useCRSI ? (close > ma2 and close < ma3 and RSI <= connor_os ? color.lime : close < ma2 and close > ma3 and RSI <= connor_ob ? color.red : color.yellow ) : color.yellow // Plot colored RSI Line plot(RSI, title="RSI", linewidth=3, color=col) //------------------- MACD Strategy ------------------------------------------------- [macdLine, signalLine, _] = macd(close, fastLength, slowLength, length) bartrendcolor = macdLine > signalLine and k > 50 and RSI > 50 ? color.teal : macdLine < signalLine and k < 50 and RSI < 50 ? color.maroon : macdLine < signalLine ? color.yellow : color.gray barcolor(color = color_bars ? bartrendcolor : na) MACDBuy = macdLine>signalLine and RSI<RSI_low and overall<0 and window() MACDSell = macdLine<signalLine and RSI>RSI_high and overall>0 and window() //plotshape(showMACD ? MACDBuy: na, title = "MACD Buy", style = shape.arrowup, text = "MACD Buy", color=color.green, textcolor=color.green, size=size.small) //plotshape(showMACD ? MACDSell: na, title = "MACD Sell", style = shape.arrowdown, text = "MACD Sell", color=color.red, textcolor=color.red, size=size.small) MACColor = MACDBuy ? color.new(color.teal, 50) : MACDSell ? color.new(color.maroon, 50) : na bgcolor(showMACD ? MACColor : na, title ="MACD Signals") // -------------------------------- Entry and Exit Logic ------------------------------------ // Entry Logic XRSI_OB = crossunder(RSI, overbought) and overall<0 and window() RSI_OB = RSI>overbought and true_peak and window() XRSI_OS = crossover(RSI, oversold) and overall>0 and window() RSI_OS = RSI<oversold and true_dip and window() // Strategy Entry and Exit with built in Risk Management if(strategy.opentrades==0 and strat_val>-1) OtherLong = rsi_ema > RSI and k < d GoLong = useStoch ? StochBuy : useXRSI ? OtherLong and XRSI_OS : useMACD ? OtherLong and MACDBuy : useCRSI ? OtherLong and RSI_BUY : useEMA ? EMALongBuy : RSI_OS if (GoLong) strategy.entry("LONG", strategy.long) if(strategy.opentrades==0 and strat_val<1) OtherShort = rsi_ema < RSI and d < k GoShort = useStoch ? StochSell : useXRSI ? OtherShort and XRSI_OB : useMACD ? OtherShort and MACDSell : useCRSI ? OtherShort and RSI_SELL : useEMA ? EMAShortSell : OtherShort and RSI_OB if (GoShort) strategy.entry("SHORT", strategy.short) longStopPrice = strategy.position_avg_price * (1 - stoploss) longTakePrice = strategy.position_avg_price * (1 + TargetProfit) shortStopPrice = strategy.position_avg_price * (1 + stoploss) shortTakePrice = strategy.position_avg_price * (1 - TargetProfit) //plot(series=(strategy.position_size > 0) ? longTakePrice : na, color=color.green, style=plot.style_circles, linewidth=3, title="Long Take Profit") //plot(series=(strategy.position_size < 0) ? shortTakePrice : na, color=color.green, style=plot.style_circles, linewidth=3, title="Short Take Profit") //plot(series=(strategy.position_size > 0) ? longStopPrice : na, color=color.red, style=plot.style_cross, linewidth=2, title="Long Stop Loss") //plot(series=(strategy.position_size < 0) ? shortStopPrice : na, color=color.red, style=plot.style_cross, linewidth=2, title="Short Stop Loss") if (strategy.position_size > 0) strategy.exit(id="Exit Long", from_entry = "LONG", stop = longStopPrice, limit = longTakePrice) if (strategy.position_size < 0) strategy.exit(id="Exit Short", from_entry = "SHORT", stop = shortStopPrice, limit = shortTakePrice) StochLong2 = strategy.position_size<0 and strat_val > -1 OtherLong2 = strategy.position_size<0 and strat_val > -1 and rsi_ema > RSI and k < d CloseShort= useStoch ? StochLong2 and StochBuy : useXRSI ? OtherLong2 and XRSI_OS : useMACD ? OtherLong2 and MACDBuy : useCRSI ? OtherLong2 and RSI_BUY : useEMA ? EMAShortBuy : RSI_OS StochShort2 = strategy.position_size>0 and strat_val < 1 OtherShort2 = strategy.position_size>0 and strat_val < 1 and rsi_ema < RSI and d < k CloseLong = useStoch ? StochShort2 and StochSell : useXRSI ? OtherShort2 and XRSI_OB : useMACD ? OtherShort2 and MACDSell : useCRSI ? OtherShort2 and RSI_SELL : useEMA ? EMALongSell : OtherShort2 and RSI_OB if(CloseLong) strategy.close("LONG") if(CloseShort) strategy.close("SHORT")
Morun Astro Trend MAs cross Strategy
https://www.tradingview.com/script/dWi5MI7l-Morun-Astro-Trend-MAs-cross-Strategy/
citlacom
https://www.tradingview.com/u/citlacom/
539
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/ // Β© citlacom // @version=4 // Strategy developed by the Financial Astrology Research Group. strategy("Financial Astrology Research MA Strategy", overlay=true, linktoseries=true, currency="USD", pyramiding=0, initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=25, commission_type=strategy.commission.percent, commission_value=0.1) // Signals indicators. var int masterCycleLength = input(40, minval=30, step=10, title="Master cycle length") var int minCrossConsolidationPeriod = input(0, minval=0, step=5, title="Minimum MA cross consolidation period") var int leadShiftHours = input(0, type=input.integer, minval=0, step=4, title="Hours shift for leading effect") var int futureWeeksNumber = timeframe.isminutes ? 1 : 2 // Risk control settings. float trailingStopPercent = input(10, title="Trailing Stop Distance(%)", type=input.float, minval=0.0, step=1) * 0.01 float trailingStopTriggerPercent = input(1, title="Trailing Stop Trigger Distance(%)", type=input.float, minval=0.0, step=1) * 0.01 float stopLossPercent = input(5, title="Stop Loss (%)", type=input.float, minval=0.0, step=1) * 0.01 bool plotTrailingStop = input(false, title="Plot trailing stop prices.", type=input.bool) string orderType = "market" // Order signals controls. bool enableEntryShortOrder = input(true, title="Enable entry short orders", type=input.bool) bool enableEntryLongOrder = input(true, title="Enable entry long orders", type=input.bool) bool ignoreEarlyReverseSignal = input(false, title="Ignore exit signal when change is lower than stop loss", type=input.bool) string zignalyProviderEnvKey = input("", title="Zignaly provider key environment variable", type=input.string) bool skipProcessingFilters = true bool exitOnReverseSignal = true int fastMAPeriod = masterCycleLength / 2 int slowMAPeriod = masterCycleLength // Position information. float currentPositionSize = strategy.position_size float currentPositionEntryPrice = strategy.position_avg_price string positionSymbol = syminfo.ticker string positionSymbolId = syminfo.tickerid float positionSymbolMinTick = syminfo.mintick string exchangeId = syminfo.prefix string entryName = strategy.position_entry_name bool ignoreNewSignal = currentPositionSize != 0 // Trailing stop trigger checks. float entryPriceLongDiff = 1 - (currentPositionEntryPrice[1] / high) float entryPriceShortDiff = 1 - (low / currentPositionEntryPrice[1]) bool trailingStopLongTrigger = entryPriceLongDiff > trailingStopTriggerPercent bool trailingStopShortTrigger = entryPriceShortDiff > trailingStopTriggerPercent // Trailing stop calculation base price. float baseStopPrice = trailingStopLongTrigger or trailingStopShortTrigger ? close : currentPositionEntryPrice // Due to TradingView limitations to integrate external signals from financial astrology ML models // we needed to hardcode the buy/sell signals here in the code as PineScript array with start Date index at 2021-01-01 // and end index at 2022-12-31, this signal is based on the correlation of planets cycles and price trend for each research // asset historical data detected through machine learning methods, once models are trained can forecast future daily trend. varip int[] ADA = array.from( 1,0,1,1,1,1,1,1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,1,0,0,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,0,1,0,1,0,0,1,1,0,1,0,0,1,0,0,0,1,0,0,1,0,0,0,0,1,0,1,0,0,1,1,0,0,1,1,0,1,0,0,0,0,0,1,1,1,0,0,0,1,1,0,0,1,1,1,0,0,0,1,1,1,1,0,0,1,1,0,1,0,1,0,0,0,0,1,1,1,1,1,0,0,0,1,1,1,1,1,0,1,0,0,0,1,0,1,0,0,0,0,1,0,1,1,1,1,1,0,1,0,1,0,0,0,1,1,0,0,1,1,0,1,1,1,0,1,0,1,0,0,0,0,0,1,0,0,1,1,1,1,1,1,1,0, 1,1,1,1,1,0,1,0,1,1,1,0,0,1,0,0,0,0,1,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,0,1,0,0,1,1,1,0,1,1,0,1,0,0,0,0,0,0,1,1,1,1,0,0,0,1,0,1,0,1,1,0,0,0,1,1,1,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,1,1,1,0,1,1,0,0,0,0,0,0,1,1,1,1,0,1,1,1,0,0,0,0,0,1,1,0,1,0,1,1,0,1,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,1,0,0,1,1,1,0,0,0,0,0,1,0,1,0,0,1,0,1,0,0,0,1, 0,1,0,0,1,0,1,0,1,0,0,1,0,0,1,1,0,0,1,1,1,1,1,1,1,0,1,1,1,0,0,1,1,1,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,0,0,0,0,0,1,1,0,0,0,1,0,1,0,1,0,0,0,0,0,0,1,1,1,1,1,0,1,1,0,1,1,1,1,0,0,0,0,0,0,0,1,1,1,0,1,1,0,0,0,1,0,1,0,1,1,1,0,0,0,0,1,0,0,0,0,0,0,1,1,1,0,0,1,1,0,1,1,0,0,1,0,0,1,0,1,1,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,0,1,0,0,0,1,1,1,0,0,0,0,0,0,0,1,1,0,0,1,0,1,0, 1,1,0,1,1,1,0,0,1,1,1,0,1,0,1,1,0,0,0,0,1,0,1,0,1,1,0,1,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,1,1,1,0,1,1,1,0,0,0,1,1,1,1,1,1,0,0,1,0,0,0,0,0,1,0,1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,0,0,0,0,0,0,0,0,1,0,1,0,0,1,1,0,0,0,0,1,1,1,0,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1,0,0,0,0,1,0,0,1,1,0,0,0,0,0,1,0,0,0,0,0,0,1,1,1,1,1,1,0,1,1,0,0,0,1,0,1,0,1,1,0,1) varip int[] BAT = array.from( 1,1,1,1,0,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,0,1,1,1,1,1,1,0,0,1,0,1,0,1,0,1,1,0,0,1,0,1,1,0,1,0,0,0,1,1,1,1,1,1,1,0,1,1,1,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,1,1,0,1,1,1,1,0,1,1,1,0,0,0,1,1,0,1,1,0,0,0,1,0,0,1,1,0,1,1,1,1,0,0,1,1,1,1,1,1,0,0,0,1,0,0,0,0,0,1,0,1,1,0,1,0,1,1,1,0,0,0,0,1,0,0,1,1,0,0,0,1,0,0,0,0,0,1,1,0,0,1,1,1,0,1,0,0,0, 1,1,0,0,0,0,0,0,0,0,1,0,0,1,0,1,0,1,1,0,0,0,0,1,0,0,1,0,0,0,1,0,0,1,0,1,0,0,1,1,1,0,0,0,1,0,0,1,0,0,0,0,1,1,1,0,1,0,0,1,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0,0,1,0,0,0,1,0,0,0,0,1,1,1,1,0,1,0,1,1,1,1,1,0,1,0,1,1,1,1,0,0,0,1,0,0,1,1,1,1,0,0,0,1,1,1,0,1,1,0,0,1,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,1,0,1,0,1,1,1,0,1,1,1,1,1,0,1,0,1,1,0,0,0,0,0,0,0, 1,0,0,0,1,1,0,1,1,1,0,0,0,0,1,0,1,0,0,0,0,0,0,0,1,1,0,0,1,0,1,1,1,1,1,1,1,0,1,0,1,1,1,1,1,0,1,0,1,1,1,0,1,1,0,1,0,0,0,1,1,1,0,0,0,0,1,1,1,1,1,0,0,1,0,0,1,1,0,1,1,1,1,1,0,0,1,1,0,1,1,1,1,0,0,0,1,1,0,0,1,1,1,1,1,0,0,0,1,0,1,0,1,0,1,1,1,0,1,0,1,1,1,1,0,1,1,1,1,0,0,1,1,0,1,0,1,1,0,1,0,1,1,1,1,1,0,0,0,1,0,1,0,1,0,1,1,0,0,0,0,1,1,1,1,0,1,0,1,0,1,1,1,1,0,1,1,0,1,1,0,1, 0,0,0,1,1,0,0,0,0,1,0,0,0,1,0,1,0,0,0,0,1,0,1,1,1,1,0,0,1,1,0,0,1,0,1,1,1,0,1,0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,0,0,0,0,1,1,1,0,0,0,1,1,0,1,0,1,0,1,1,0,1,1,0,1,1,1,1,1,1,0,1,0,0,0,0,0,1,0,0,0,1,0,1,1,1,1,0,0,0,0,0,1,0,0,1,1,0,0,1,0,0,0,1,0,0,1,1,1,0,1,1,0,0,1,0,0,0,0,1,0,1,0,0,1,0,1,1,0,0,0,1,1,1,1,1,1,0,1,1,0,1,0,0,1,0,0,1,0,0,0,0,0,0,0,0,1,1,0,1,1,1,0,1,1,1,1,1,0) varip int[] BNB = array.from( 1,1,1,0,0,0,0,1,1,0,1,1,1,1,1,1,1,1,0,1,0,0,1,0,0,0,0,1,0,1,0,1,1,1,0,1,1,0,0,1,1,1,1,0,0,0,0,0,1,1,1,0,0,0,0,1,1,0,0,1,1,0,0,0,0,1,1,0,0,1,0,0,1,1,1,1,1,0,0,0,0,1,0,1,0,1,1,1,1,1,1,1,0,1,1,0,0,1,1,0,0,0,1,1,0,1,0,0,1,0,1,0,0,1,0,1,1,1,1,0,1,0,1,1,0,1,0,0,0,1,1,1,1,0,0,1,1,1,1,0,0,0,0,1,0,0,0,0,1,1,1,1,0,0,0,0,1,0,0,1,1,0,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,1,0,0,0,0,0, 0,1,0,0,0,0,0,1,1,1,0,0,1,1,1,0,0,1,0,1,1,1,1,1,0,0,0,0,0,0,1,0,0,0,1,1,0,0,1,1,1,0,1,1,1,0,1,0,0,1,0,1,1,0,1,1,1,1,1,1,0,1,1,1,1,0,0,0,1,1,1,0,1,1,0,1,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,1,1,0,1,0,1,0,1,1,1,0,1,1,1,1,1,1,1,0,1,1,1,1,0,0,1,1,0,1,1,1,0,1,1,1,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,0,1,1,1,1,1,1,0,0,0,0,1,1,0,0,0,1,0,1,1,1,1,0,0,0,0,0,1,0,0,1,0,0,0,0,1,1,1,1, 1,0,0,0,1,0,1,0,0,1,0,0,1,0,1,1,1,0,0,0,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,0,0,1,0,1,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,1,1,0,0,0,0,1,1,1,0,1,1,0,1,0,1,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,1,0,1,0,1,0,0,0,1,1,1,0,0,0,0,1,0,0,1,1,0,1,1,0,1,1,1,1,0,0,1,1,1,1,0,1,1,1,0,0,1,1,1,1,1,0,1,1,0,1,1,0,0,0,1,0,1,1,1,1,1,1,1,1,1,0,1,1,0,1,0,0,1,0,1,1,0,0,0,0,0,0,0, 0,0,1,0,1,1,1,0,0,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,0,1,1,0,1,1,0,1,1,1,1,1,1,0,0,0,1,0,0,0,1,0,0,1,1,0,1,0,0,1,1,1,1,1,0,1,1,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,1,0,0,0,0,0,0,0,1,0,0,1,1,1,1,1,0,0,0,0,1,0,1,0,1,0,0,1,1,1,1,1,1,0,1,0,0,0,0,0,0,0,1,0,0,1,1,0,1,1,1,1,1,0,1,0,0,1,0,1,0,1,0,0,1,1,1,1,0,1,0,1,1,1,1,1,1,0,1,0,1,1,0,1,1,1,1,0,0,0,0,0,0,1,0,1,0,0,0) varip int[] BTC = array.from( 0,0,0,0,0,1,1,1,0,1,0,0,0,0,1,0,0,1,1,1,0,0,1,1,1,1,1,1,1,1,0,1,0,1,0,0,1,1,0,1,1,1,1,0,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,0,1,0,1,0,1,1,0,0,1,0,0,1,1,1,1,1,1,1,1,0,0,0,0,0,1,1,1,0,1,1,1,0,0,0,1,1,0,0,0,1,0,1,0,1,1,1,0,1,0,0,0,1,0,0,0,1,1,1,1,1,1,0,1,0,0,1,1,1,1,1,1,1,1,1,0,1,0,1,0,0,0,0,0,1,1,0,1,1,0,0,1,1,0,1,0,0,0,0,1,1,0,0,1,1,0,0,1,1,0,0,0,0,1,1,0,0,1,0,0,0,0,1,1, 1,1,0,1,1,1,0,1,0,1,1,0,0,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,0,1,1,0,0,1,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,1,0,1,0,1,1,1,1,1,1,0,1,0,0,0,1,1,1,0,0,0,1,0,0,1,0,0,1,1,1,0,0,0,1,1,1,1,0,1,0,1,1,1,1,1,1,0,1,1,1,0,0,0,1,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1,0,1,1,0,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,0,1,1,1,0,0,1,1,0,0,0,0,0,1,1,1,1,1,0,1,1,1,1,0,1,1,1,0,0,1,1,0,0,0,0,1,1,0, 1,0,0,0,1,0,1,1,1,0,1,1,1,1,0,1,0,0,0,1,0,1,1,1,0,0,0,0,0,1,1,1,1,1,0,0,0,1,1,0,0,1,1,1,1,1,0,1,1,0,1,0,1,0,1,1,0,0,1,1,1,1,0,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1,0,0,0,1,1,1,1,0,1,1,1,1,0,0,0,1,0,1,1,1,1,1,0,1,0,0,1,0,0,1,0,0,0,0,1,0,1,1,0,0,1,1,0,1,1,1,1,1,1,1,0,0,1,1,1,0,1,1,0,0,1,0,0,0,0,0,0,1,1,0,1,1,1,1,0,0,1,0,0,0,0,0,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,1,1, 1,0,1,1,1,0,1,0,0,0,0,0,0,1,0,1,0,1,0,0,1,1,0,1,1,1,1,1,1,1,1,0,0,0,1,1,0,0,1,1,1,0,1,1,0,0,1,0,0,0,1,0,1,1,0,1,1,1,0,0,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,1,1,1,1,1,0,0,1,0,1,1,1,1,1,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,0,1,0,1,1,0,1,1,0,0,0,1,1,1,1,0,0,1,1,1,0,1,0,0,0,1,1,1,0,0,0,0,0,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,0,1,1,1,0,0,0,0,1,1,1) varip int[] DASH = array.from( 0,0,0,0,1,0,0,1,0,1,1,0,0,1,0,0,0,1,1,1,1,0,1,1,0,0,0,0,0,0,0,0,1,1,0,1,1,0,1,1,1,1,1,1,0,0,1,0,0,0,0,0,0,0,0,1,1,0,1,0,1,0,0,0,0,1,1,0,0,1,0,0,1,1,1,1,0,0,1,0,1,0,1,1,0,1,0,1,1,0,1,1,0,0,1,1,1,0,1,1,1,0,0,1,1,1,0,0,0,0,1,0,0,0,1,1,1,0,0,0,1,0,1,0,1,0,1,0,1,1,1,0,0,1,1,1,0,1,0,0,0,0,0,0,1,0,0,0,1,1,1,0,1,1,0,0,0,0,0,1,0,0,0,0,1,1,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0, 0,0,0,1,1,1,0,1,0,1,0,0,1,1,1,0,1,1,1,0,1,0,0,1,0,0,1,0,0,0,1,1,1,0,0,0,1,0,1,1,0,0,1,0,1,1,0,1,1,1,0,0,1,1,1,1,0,0,0,1,1,0,1,1,1,1,0,1,0,1,1,1,0,1,1,1,1,1,0,1,0,0,0,0,0,0,0,0,0,1,0,1,1,0,1,0,0,0,0,1,1,1,1,0,0,1,1,1,1,1,1,0,0,1,0,0,0,1,1,0,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,1,0,1,1,0,1,1,1,0,0,0,1,1,1,1,1,1,0,1,0,0,1,0,1,1,0,1,1,1,0,0,0,0,1,1,1,1,1,0,0,1,0,1,0,1, 1,1,0,0,1,1,1,1,0,1,0,0,1,0,0,0,1,0,0,0,1,0,0,1,0,0,0,1,1,1,1,0,1,0,1,1,1,0,1,0,0,0,1,0,0,0,0,0,1,1,0,1,1,1,0,0,0,1,1,0,0,0,0,1,1,0,0,0,1,1,0,0,0,0,1,0,1,1,0,1,0,0,0,0,0,0,0,1,1,0,0,1,0,0,1,1,1,1,0,1,0,1,1,0,0,1,1,1,0,1,0,0,1,1,1,1,0,1,1,1,0,0,1,0,1,0,1,1,0,0,1,1,1,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,1,1,0,0,1,0,0,1,0,1,1,1,1,0,0,1,1,1,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0, 0,1,1,1,0,1,0,1,1,1,1,0,1,0,0,0,1,1,0,1,0,1,0,0,0,0,0,0,0,1,1,0,0,0,0,1,0,0,1,1,0,1,1,0,1,0,0,1,1,1,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,1,0,0,0,1,0,1,0,1,0,0,0,1,1,1,1,1,0,1,0,1,1,1,0,0,0,0,1,1,1,1,1,0,1,1,1,1,0,1,1,1,1,1,1,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,1,1,1,0,1,0,1,1,1,1,1,1,1,0,0,1,0,1,1,1,0,1,0,0,0,1,1,0,1,1,0,1,1,0,1,0,0,0,0,1,1,0,1,0,1,1,0,1,1,1,1,0,0,0) varip int[] EOS = array.from( 1,0,1,1,1,0,1,1,1,1,0,0,0,1,1,1,1,1,0,1,0,0,0,0,0,1,1,0,1,1,1,1,0,0,1,1,1,1,1,1,1,1,1,0,1,0,0,1,1,0,0,0,0,0,0,0,0,1,0,1,1,0,0,1,0,0,1,1,1,1,0,0,1,1,0,1,0,1,0,0,1,0,1,1,0,1,1,1,0,1,0,0,1,1,1,1,0,0,1,1,1,0,1,0,1,1,0,0,0,0,0,1,1,0,0,0,0,1,1,1,0,1,1,0,1,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,0, 1,0,1,0,0,0,1,1,0,0,0,1,0,0,0,0,1,0,1,0,0,0,1,0,0,0,0,1,1,0,1,0,0,1,1,1,0,0,1,0,0,0,0,0,1,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,0,1,1,0,0,1,1,0,0,1,0,1,0,0,0,0,0,0,0,1,0,1,0,1,1,0,1,0,1,1,1,0,1,1,0,0,1,0,1,0,1,0,1,1,1,0,1,0,0,0,0,1,1,0,0,1,1,1,1,1,1,1,0,1,0,0,0,1,0,0,1,0,0,0,0,1,1,0,0,1,0,1,0,1,0,0,0,1,1,1,1,1,1,0,1,0,0,1,0,1,0,1,1,0,0,1,1,1, 0,0,1,1,1,0,0,1,1,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,1,1,1,1,0,0,1,1,1,1,0,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,0,0,1,0,0,0,1,1,1,1,1,1,1,0,0,0,1,0,0,1,1,1,1,1,1,0,0,1,0,0,1,1,1,1,1,1,0,0,0,1,1,1,1,0,1,0,1,1,1,0,0,0,1,0,1,1,1,0,0,0,0,0,0,1,1,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,0,0,1,1,1,1,1,1,1,0,1,0,1,1,1,1,1,1,0,1,1,1,0,0,1,1,0,1,1,1,0, 0,1,0,1,1,1,1,1,0,1,0,1,0,1,0,1,1,0,0,0,1,1,0,0,0,0,0,0,0,1,1,0,1,1,1,0,1,1,1,0,0,0,0,0,0,0,1,1,0,0,0,0,1,0,1,0,1,1,0,0,1,0,1,0,1,0,0,1,1,1,0,0,0,0,1,0,1,0,0,1,0,1,1,1,0,1,1,1,0,0,0,0,0,0,0,0,1,0,0,0,0,1,1,0,0,1,0,1,1,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,1,1,0,0,0,0,0,1,1,1,0,0,1,0,1,1,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1,1,0,1,1,0,0,0,0,0,1,1,1,1,1,1) varip int[] ETC = array.from( 1,0,1,1,1,1,0,1,0,1,0,1,1,0,0,1,0,1,0,1,1,1,1,1,1,1,1,0,0,0,0,0,0,1,0,1,0,0,1,1,1,1,1,0,0,1,0,1,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,1,0,1,1,1,0,1,1,1,1,1,0,0,1,1,0,0,1,0,0,0,1,1,1,1,1,1,0,1,1,0,1,1,1,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,1,0,1,1,1,1,1,1,1,0,1,1,1,1,1,0,0,1,1,1,1,1,0,0,0,0,0,0,1,1,1,0,1,0,0,0,0,1,1,1,0,0,1,0,0,0,0,0,1,1,1,0,1,1,1,0,0,1,1,0,0,0,1,1,1,1,0,0, 1,0,1,0,0,0,0,1,1,1,1,0,0,0,0,0,0,1,0,0,0,1,0,0,0,1,0,1,1,0,1,0,0,0,1,1,1,0,0,1,1,0,0,0,0,0,1,0,0,1,0,1,0,1,0,1,0,0,0,1,1,1,0,1,0,0,1,0,1,0,0,0,1,1,1,1,0,1,0,0,0,1,0,0,0,1,1,0,1,1,1,0,1,0,0,0,0,1,0,1,1,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,1,1,1,0,1,1,1,1,1,0,1,0,1,0,0,0,1,1,1,1,0,0,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,0,1,1,1,0,1,0,0,0,0,1,1,0,0,0,0,0,1,1,1,1,0,0,0,1,1,1,1,1, 1,1,1,1,0,1,0,0,1,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,1,1,1,0,1,1,1,1,1,1,0,0,0,1,1,0,1,0,0,1,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,1,1,0,0,0,1,1,1,0,0,0,0,0,1,0,0,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,1,0,1,0,1,1,0,1,1,0,0,0,1,1,0,1,0,1,1,1,1,1,1,1,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,1,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,1,0,1,1,0,1,0,1,0,0,1,1,1,0,0, 0,0,0,1,0,1,1,1,0,1,0,1,1,0,0,0,1,0,1,0,0,1,0,1,0,1,0,1,1,0,1,0,1,1,1,1,1,0,0,0,1,0,0,0,0,0,1,0,0,0,0,1,0,0,1,0,0,0,0,0,1,0,1,0,0,1,0,1,0,0,0,0,0,0,1,0,1,0,1,1,1,1,1,0,0,0,1,0,1,1,1,0,1,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,1,1,1,1,1,1,1,0,0,1,0,0,0,0,0,0,0,0,1,1,1,0,0,0,1,1,1,0,0,1,1,0,0,0,0,1,1,1,0,1,1,0,1,0,1,1,1,0,1,0,1,1,0,1,0,1,1,0,0,0,0,0,0,1,1,1,1,1,0,1,1,1,0) varip int[] ETH = array.from( 0,1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,0,1,0,0,1,0,0,0,0,1,1,1,1,1,1,0,1,0,0,0,1,1,1,1,1,0,0,0,0,0,1,1,1,0,1,0,1,0,0,1,0,1,0,0,0,1,1,1,1,1,1,0,1,0,0,0,0,0,1,1,1,0,1,0,1,1,0,1,1,1,0,0,1,1,0,0,0,0,0,1,0,1,1,0,1,1,1,1,0,0,1,1,0,1,1,0,0,1,1,0,0,0,0,1,1,1,1,1,1,0,1,0,0,1,0,0,0,0,1,0,1,1,1,0,0,1,1,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,0,1,0,0,1,0,1,1,1,0,0,0,1,1,1, 0,0,1,0,0,0,1,1,0,1,1,0,0,1,1,1,0,1,0,1,0,1,0,0,1,0,0,0,1,0,1,0,0,0,1,1,1,0,0,1,0,1,1,1,1,1,1,0,0,0,0,1,1,1,0,1,0,1,0,0,0,0,0,1,0,0,1,1,0,1,0,0,1,0,0,0,0,1,0,1,0,0,0,1,1,0,0,1,1,0,0,0,0,1,1,1,0,0,1,1,1,1,1,1,1,1,1,0,1,0,0,0,1,0,0,0,0,0,1,0,1,1,0,0,0,0,0,0,1,0,0,0,0,1,1,1,0,0,0,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,1,1,1,0,1,1,1,1,0,1,0,1,1,0,0,1,1,0,1,0,0,1,1,1,1,1,1,1, 1,1,1,0,0,0,1,1,1,0,0,1,0,0,0,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,1,0,1,1,1,1,1,0,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,0,1,0,1,1,1,1,1,1,0,1,0,1,1,1,1,0,1,1,1,0,1,1,1,1,0,1,0,0,0,0,1,1,1,1,0,0,0,1,0,1,0,1,1,1,1,1,1,1,0,0,1,1,0,1,0,1,1,0,1,1,0,1,0,0, 0,1,1,0,0,1,0,1,1,1,0,1,1,1,1,0,0,0,1,0,1,1,0,1,0,0,1,0,1,0,1,1,1,0,1,0,0,1,1,0,0,1,1,0,1,1,1,1,1,1,0,0,1,1,1,0,0,0,0,1,1,0,1,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1,1,0,1,1,1,1,0,1,0,0,0,0,0,1,1,0,1,0,1,1,1,1,1,0,0,0,0,0,0,1,0,1,0,1,0,1,0,0,0,0,1,0,0,1,1,1,1,0,0,0,0,0,0,0,1,0,1,0,1,1,1,0,0,0,0,0,1,1,0,0,1,0,1,0,0,1,1,0,0,0,0,0,0,1,1,0,1,0,1,1,1,1,0,0) varip int[] LINK = array.from( 1,0,1,0,1,1,0,0,0,0,1,0,1,1,1,1,0,0,0,1,0,0,0,1,0,0,1,1,1,0,0,0,0,1,1,1,1,1,1,1,0,0,0,1,0,0,0,0,1,1,0,0,0,0,1,0,1,1,1,0,1,1,0,0,1,1,1,1,1,1,1,1,1,0,0,1,1,1,0,0,0,0,0,0,1,1,0,0,1,0,1,1,1,0,1,1,1,1,1,0,1,1,0,1,1,0,0,0,0,0,1,0,0,0,0,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,0,0,0,0,0,0,1,0,0,1,1,1,0,0,0,1,0,1,0,1,1,1,1,1,1,1,1,1,0,0,1,1,0,0,0,1,0,0,1,0,0,1,1,1,0,1,1,1,1, 0,1,0,1,1,1,1,0,1,0,1,1,0,1,1,0,0,0,0,1,0,1,1,1,1,1,1,1,0,1,1,0,0,0,0,1,1,1,0,1,0,0,1,0,0,0,0,0,1,0,1,1,0,0,1,0,1,0,1,0,0,1,1,0,1,0,0,0,0,0,1,1,1,1,0,1,1,0,0,1,1,1,0,1,1,0,1,0,1,0,1,1,0,0,1,1,1,1,0,1,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,1,0,0,1,1,0,0,0,1,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,1,0,0,1,1,1,0,1,1,0,1,0,1,1,0,1,1,1,0,0,1,1,0,0,1,1,1,1,1,1,1,0,1,0,0,1,0,0,1,0,1,1,1, 0,0,0,1,0,1,0,1,1,1,0,0,1,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,1,0,1,0,0,1,0,1,0,1,1,0,0,1,1,1,1,0,1,0,1,1,1,1,1,0,1,1,1,0,0,0,1,1,1,1,1,0,0,0,1,1,0,0,1,0,0,1,0,0,0,0,0,1,0,1,1,1,1,1,1,1,1,1,0,0,1,0,1,0,1,1,1,1,1,0,0,0,1,0,0,0,1,1,1,1,1,1,1,0,1,0,1,0,1,1,1,1,1,1,0,1,1,0,0,0,0,1,0,0,1,0,1,1,1,1,1,0,0,0,1,0,0,0,1,1,1,0,1,0,0,0,0,1,0,1,1,1,0,1,0,0,0,0,1,1,0,0,1,1,1,1,1, 0,1,0,0,1,0,0,1,1,1,0,1,0,1,0,0,0,1,1,1,0,0,0,1,0,0,1,1,1,1,0,1,1,1,1,1,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,1,1,1,1,1,0,0,1,0,0,1,1,1,0,1,0,0,0,0,0,0,0,1,0,1,0,1,0,1,0,0,0,1,1,1,1,1,1,0,1,0,1,1,0,0,1,1,1,0,1,1,1,1,1,1,0,1,0,0,0,0,0,0,1,1,1,1,1,1,1,0,1,0,0,0,1,0,0,0,1,1,1,1,0,0,1,1,0,1,1,0,1,1,0,0,1,1,1,0,0,1,1,1,1,0,0,0,1,1,1,1,1,0,1,0,1,0,0,0,1,1,0,0,1,1,0,1,1,1,1,0) varip int[] LTC = array.from( 0,1,0,1,1,0,1,1,0,0,0,0,1,1,0,1,0,0,1,1,0,0,1,0,1,0,1,1,0,0,0,1,1,1,0,0,1,1,0,1,1,1,1,1,0,1,1,1,1,1,0,1,1,0,1,1,1,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,1,0,0,1,1,1,0,1,1,1,0,1,1,0,0,1,1,1,1,1,0,1,1,1,1,1,1,1,0,0,1,1,0,1,1,0,0,0,0,0,0,0,1,1,1,0,0,1,0,1,1,1,1,1,1,1,1,1,0,0,1,1,1,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,1,0,1,0,1,0,1,1,0,1,1,1,1,1,1,1,0,0,1,1,1,0,1,1,1,1,1,1,1,0,1,1, 0,1,1,1,1,0,1,1,1,1,1,0,1,0,0,0,0,1,1,0,0,0,1,1,1,0,0,0,0,0,0,0,1,0,1,1,0,0,0,1,1,0,0,0,1,0,0,1,1,1,1,1,0,0,0,1,1,0,0,0,0,1,0,0,0,0,1,0,1,0,0,0,1,0,0,0,0,1,0,1,1,0,0,0,1,1,1,0,0,0,0,1,0,1,0,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,0,1,1,1,1,0,1,0,0,1,1,1,1,1,0,0,1,0,0,1,1,0,1,0,1,1,0,0,0,1,1,1,0,0,0,0,1,1,0,1,1,1,0,1,1,1,1,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,1,1, 1,0,1,0,0,0,1,0,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,1,1,0,1,1,1,0,0,0,0,0,0,1,0,1,0,1,1,0,0,1,0,0,0,0,0,1,0,1,1,1,0,1,0,0,0,1,1,0,0,0,0,1,1,0,0,0,1,1,1,1,1,1,0,0,1,1,0,1,1,0,0,1,0,0,1,0,0,0,0,1,1,1,0,1,0,0,0,0,1,0,0,1,0,0,1,1,1,0,0,1,1,1,1,1,0,0,1,0,0,0,1,1,1,1,1,1,0,0,1,1,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,0,0,1,1,0,1,0,0,1,1,0,1,0,1,0,1,0,0,0,1,0,1,1,1,0,0,0,1, 0,0,1,1,1,1,1,0,0,1,1,0,1,0,1,1,0,0,0,0,1,1,1,0,1,0,0,0,1,1,0,0,0,1,1,0,0,0,0,1,0,1,1,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,1,0,1,0,1,0,0,1,1,0,0,1,1,1,1,1,1,0,0,0,1,1,0,0,0,0,0,0,0,1,1,1,0,0,1,0,0,1,0,1,1,0,1,0,0,1,0,0,0,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,0,1,1,0,0,0,1,1,1,1,1,0,1,1,1,1,1,0,0,1,0,1,1,1,1,1,1,1,1) varip int[] XLM = array.from( 0,0,0,1,0,1,1,0,0,1,0,1,0,1,1,1,1,1,0,1,0,0,1,0,0,0,0,0,1,0,0,1,0,1,1,0,0,0,0,0,1,1,1,1,0,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,1,1,0,1,1,1,0,1,1,1,1,0,1,1,1,0,1,0,1,0,1,1,1,1,0,0,0,0,1,1,0,0,1,1,0,1,1,1,1,0,1,0,0,0,0,1,0,1,1,1,1,0,0,1,1,0,0,0,0,0,0,0,0,1,1,1,0,0,0,1,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0, 0,0,1,1,0,0,0,0,1,0,0,1,1,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,0,1,0,0,0,0,0,1,1,1,0,1,0,0,0,0,0,1,0,0,0,0,1,1,0,0,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,1,1,0,0,1,1,0,0,1,1,1,0,1,0,0,1,0,0,0,0,0,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,1,0,0,1,1,0,1,0,1,0,1,0,0,0,1,0,0,0,0,1,0,0,0,0,1,0,0,1,0,1,1,1,0,1,1,0,1,1, 1,0,0,1,1,1,1,0,1,0,0,1,0,0,1,1,0,1,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,1,0,0,1,0,0,1,0,1,0,1,1,0,1,1,1,0,1,1,0,0,1,0,0,1,0,1,1,1,1,1,1,1,0,1,0,0,0,0,1,1,0,1,1,0,1,1,1,1,0,1,1,0,1,0,1,0,0,0,0,1,1,1,1,0,1,0,1,1,1,0,0,1,1,1,0,0,0,1,1,1,1,1,0,0,1,1,0,1,0,1,0,0,0,0,1,1,1,0,0,0,0,0,1,1,1,0,0,0,0,0,1,1,0,0,0,0,0,1,1,0,0,1,0,0,0,0,1,1,0,1,0,0,1,1,0,0,0,0,0,1,0,1,1,0,0,0,1,0, 0,1,0,0,1,1,1,0,0,0,0,0,1,0,1,1,0,0,0,1,0,1,1,0,0,1,1,0,0,1,1,1,0,1,0,0,1,1,1,1,0,1,0,0,0,1,1,1,1,0,0,0,1,1,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,1,0,0,0,1,1,1,0,1,1,1,0,0,1,1,0,1,1,0,1,0,0,0,1,0,0,0,0,0,0,0,1,1,0,0,0,1,1,0,1,0,0,0,0,1,0,1,0,0,0,1,1,1,0,1,1,0,0,1,1,0,1,1,0,1,1,1,0,1,0,0,0,0,0,1,1,1,0,0,0,0,0,0,1,1,0,0,0,0,1,0,1,0,0,1,1,1,1,0,0,0) varip int[] XRP = array.from( 0,0,0,0,0,0,0,1,0,1,0,1,0,0,0,0,0,1,0,0,1,1,1,0,0,1,0,0,1,0,0,0,0,0,1,1,1,0,1,1,1,1,0,0,0,0,0,0,1,1,1,0,1,1,0,0,1,1,0,1,0,1,1,1,1,0,1,1,0,0,0,0,1,0,0,0,1,0,0,1,1,1,0,0,0,1,0,1,0,0,0,0,1,0,1,1,1,0,0,0,1,0,1,1,0,0,0,0,0,0,1,0,0,0,1,1,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,0,1,1,1,0,0,0,0,0,1,0,0,0,1,0,0,0,1,1,1,1,0,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,0,0,0,1,1, 0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,0,1,1,1,1,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0,0,0,0,0,1,0,1,0,1,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,1,0,1,1,1,1,0,0,1,1,1,1,1,1,1,1,1,0,1,0,1,0,0,0,1,1,0,0,0,1,0,1,1,1,1,1,1,1,1,0,0,1,1,1,1,0,1,0,0,1,1,1,0,1,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,1,1,0,0,0,0,1,0,1,0,0,0,0,1,1,0,0,0,0,0,0,1, 0,0,0,0,0,1,1,0,1,1,0,0,0,0,0,0,0,0,1,1,0,0,0,1,1,1,0,0,0,1,0,0,0,0,0,0,1,0,0,1,0,0,1,1,0,1,0,0,0,0,0,1,1,0,0,0,0,1,0,0,0,1,0,1,1,1,0,1,1,1,1,0,0,0,1,1,0,1,0,0,0,0,0,1,1,0,0,0,1,0,0,1,0,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,0,1,0,0,1,0,0,0,0,0,0,1,1,0,1,1,1,1,0,0,1,0,0,1,0,0,0,0,0,0,1,1,0,1,1,1,1,1,0,1,1,1,1,1,0,1,0,0,1,0,0,0,1,1,0,1,1,1,0,1,1,0,1,1,0,1,1,1,1,0,1,0, 1,0,0,0,0,1,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,1,1,1,1,1,0,0,0,0,0,1,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,1,1,1,0,0,1,0,1,1,1,0,1,0,0,1,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,1,1,0,1,1,1,1,0,0,0,0,0,1,1,1,0,0,0,0,0,1,0,0,1,0,1,0,1,0,1,1,0,1,0,1,0,0,0,0,1,0,0,1,1,0,1,0,0,1,1,1) varip int[] ZEC = array.from( 0,0,0,0,1,0,0,1,1,0,0,1,1,0,0,0,0,1,0,0,0,0,1,1,0,1,0,1,0,0,0,0,0,0,1,1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,1,1,1,1,0,1,1,0,0,0,1,1,0,1,1,1,0,0,1,0,0,1,1,1,1,1,0,0,0,1,1,0,1,1,1,1,1,1,1,0,1,1,0,1,1,1,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,1,0,0,0,1,0,0,0,0,0,0,0,1,1,0,0,0,0,1,0,0,0,1,0,1,0,0,0,1,1,0,1,1,1,1,1,0,1,0,0,0,0,1,0,0,1,0,1,1, 1,0,0,0,0,0,1,1,0,0,0,1,1,1,0,1,0,0,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,1,1,0,1,1,0,1,0,0,1,0,0,0,0,1,1,1,0,0,0,1,1,0,1,0,1,1,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,0,1,1,1,0,0,1,0,1,0,1,1,1,1,0,1,1,0,0,0,0,1,1,0,1,0,1,1,1,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,1,0,0,1,0,0,0,1,1,1,1,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,1,1,1,1, 0,1,0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,1,0,1,0,0,0,0,0,0,0,1,1,1,1,0,1,0,1,1,1,1,1,1,1,1,0,0,1,0,1,0,0,0,1,1,0,1,0,0,1,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,1,1,1,0,1,1,1,0,0,1,1,1,0,0,1,0,0,1,1,0,0,0,0,1,1,1,0,0,1,1,1,0,1,1,1,1,1,1,0,0,0,0,0,0,1,1,1,1,0,1,0,1,0,1,0,0,0,0,0,0,0,1,0,1,1,0,1,0,0,1,0,0,0,1,0,1,0,0,0,0,0,0,0,0,1, 1,1,1,1,1,0,1,1,0,0,0,0,1,1,1,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,1,0,0,0,0,0,1,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,1,1,0,1,0,1,1,1,1,0,0,0,0,1,1,1,1,1,0,0,0,0,1,0,1,0,0,1,0,0,0,0,0,0,1,0,1,0,1,1,1,1,0,0,0,0,1,0,0,1,0,0,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,1,0,1,1,0,1,1,0,0,0,1,0,0,1,0,1,0,0,0,1,1,1,0,1,0,0,0,0,1,1,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0) varip int[] ZRX = array.from( 0,0,0,0,1,0,0,1,0,1,0,1,1,0,0,0,0,1,0,1,0,1,0,0,1,0,1,1,1,1,1,1,1,0,0,0,1,0,0,0,1,1,0,0,0,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,1,0,0,1,1,0,1,0,0,1,1,1,0,0,0,0,1,1,1,1,0,1,1,1,1,1,0,0,1,1,1,0,1,1,1,1,1,1,1,1,0,0,0,1,0,0,0,0,1,1,1,0,1,0,1,1,1,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,1,0,0,1,1,1,1,1,0,0,0,1,0,0,0,1,0,1,0,1,0,0,0,0,0,0,0,0,0,1,0,1,1,1,0,1,1,0, 1,1,1,1,0,0,0,0,0,1,1,0,0,0,0,1,1,0,1,1,1,0,0,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,1,1,0,0,0,1,1,0,0,0,0,1,1,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,1,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,1,1,0,1,0,1,1,0,0,0,0,0,0,1,0,0,1,1,0,0,0,0,0,0,1,0,0,0,1,1,1,0,0,1,1,0,0,0,0,1,0,0,0,1,0,0,0,0,1,0,0,1,0,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,0,1,0,0,0,0,0,0,1,1,0,0,0,1, 0,0,1,0,0,0,1,0,0,1,0,1,1,1,1,0,0,1,1,0,1,1,1,1,1,1,0,0,1,1,0,1,1,1,1,0,1,0,0,0,0,0,0,0,1,0,0,0,0,1,1,1,1,0,0,1,1,0,0,1,0,0,1,1,0,1,1,1,0,0,0,1,1,0,0,0,1,0,1,0,0,0,0,0,1,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,1,1,0,1,0,1,0,1,1,0,0,0,0,0,0,1,1,0,0,1,0,1,1,1,0,1,1,1,1,1,0,0,1,0,1,1,1,1,1,0,0,1,1,1,0,0,0,0,0,0,0,1,1,1,0,0,0,1,0,1,1,0,1,1,0,0,0,0,1,1,1,0,0,0,0,0,0, 0,0,1,1,1,1,1,1,0,1,0,1,0,1,1,0,0,0,0,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,0,0,1,0,0,0,0,0,0,0,0,0,1,1,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0,1,1,1,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1,0,1,1,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,1,1,1,0,0,1,1,0,0,0,0,0,0,0,0,1,0,1,0,0,1,1,1,1,1,0,1,1,0,0,0,1,1,0,1,0,1,1,1,0,0,1,0,0,1,1,0,1,1,1,0,0,1,1,1,0,0,1,1,1,1,1,0,0) var mlSignal = if (syminfo.ticker == "ADAUSDT") ADA else if (syminfo.ticker == "BATUSDT") BAT else if (syminfo.ticker == "BNBUSDT") BNB else if (syminfo.ticker == "BTCUSDT") BTC else if (syminfo.ticker == "DASHUSDT") DASH else if (syminfo.ticker == "EOSUSDT") EOS else if (syminfo.ticker == "ETCUSDT") ETC else if (syminfo.ticker == "ETHUSDT") ETH else if (syminfo.ticker == "LINKUSDT") LINK else if (syminfo.ticker == "LTCUSDT") LTC else if (syminfo.ticker == "XLMUSDT") XLM else if (syminfo.ticker == "XRPUSDT") XRP else if (syminfo.ticker == "ZECUSDT") ZEC else if (syminfo.ticker == "ZRXUSDT") ZRX else array.from(0) scaleBetween(unscaledNum, minAllowed, maxAllowed, min, max) => (maxAllowed - minAllowed) * (unscaledNum - min) / (max - min) + minAllowed calculateDayBarsCount() => // Daily resolution if (timeframe.period == "D") 1 // 4 hours else if (timeframe.period == "240") 6 // 3 hours else if (timeframe.period == "180") 8 // 2 hours else if (timeframe.period == "120") 12 // 1 hour else if (timeframe.period == "60") 24 // 45 minutes else if (timeframe.period == "45") 32 // 30 minutes else if (timeframe.period == "30") 48 // 15 minutes else if (timeframe.period == "15") 96 // 10 minutes else if (timeframe.period == "10") 144 // 5 minutes else if (timeframe.period == "5") 288 // For other resolutions don't plot future predictions. else 0 calculateWeekBarsCount(numWeeks) => dayBarsCount = calculateDayBarsCount() numWeeks * 7 * dayBarsCount calculateCandleTimeDiff(futureWeekOffset) => // 2021-01-01 00:00 ML signal day time serie start. leadShiftSeconds = leadShiftHours * 3600 futureOffsetSeconds = calculateWeekBarsCount(futureWeekOffset) > 0 ? futureWeekOffset * 7 * 86400 : 0 referenceUnixTime = 1609459200 - futureOffsetSeconds - leadShiftSeconds candleUnixTime = (time / 1000) + 1 timeDiff = candleUnixTime - referenceUnixTime iff(timeDiff < 0, na, timeDiff) getMLSignalCandleIndex(futureWeekOffset) => timeDiff = calculateCandleTimeDiff(futureWeekOffset) // Day index, days count elapsed from reference date. candleIndex = floor(timeDiff / 86400) iff(candleIndex < 0, na, candleIndex) getMLSignal(futureWeekOffset) => // Map array data items indexes to candles. int candleIndex = getMLSignalCandleIndex(futureWeekOffset) int itemsCount = array.size(mlSignal) // Return na for candles where indicator data is not available. int index = candleIndex > itemsCount ? na : candleIndex signal = if (index >= 0 and itemsCount > 1) array.get(mlSignal, index) else na calculateSmoothSignal(mlSignalSerie) => int smoothPeriod = calculateWeekBarsCount(1) if (smoothPeriod > 0) sma(mlSignalSerie, smoothPeriod) else na getCurrentDayMLSignal(mlSignal, dayOffset) => futureWeekBarsOffset = calculateWeekBarsCount(futureWeeksNumber) dayBarsOffset = calculateDayBarsCount() * dayOffset dayIndex = futureWeekBarsOffset - dayBarsOffset mlSignal[dayIndex] // Compose signal time serie from array data, N weaks lead signals for future projection (plot offset). int mlSignalLeadSerie = getMLSignal(futureWeeksNumber) // Scale smooth signal into price -/+ 20% price range. float mlSignalSerieSmooth = scaleBetween(calculateSmoothSignal(mlSignalLeadSerie), 0.8, 1.2, 0, 1) int todayMLSignal = getCurrentDayMLSignal(mlSignalLeadSerie, 0) int tomorrowMLSignal = getCurrentDayMLSignal(mlSignalLeadSerie, 1) calculateFastMA() => sma(hl2, fastMAPeriod) calculateSlowMA() => src = hl2 smma = 0.0 smma := na(smma[1]) ? sma(src, slowMAPeriod) : (smma[1] * (slowMAPeriod - 1) + src) / slowMAPeriod // vwma(hl2, slowMAPeriod) currentDate() => tostring(year) + '-' + tostring(month) + '-' + tostring(dayofmonth) currentTime() => tostring(hour) + ':' + tostring(minute) + ":" + "00" currentTimezone() => syminfo.timezone composeSignalData(action, side, type) => string skipProcessingFiltersString = skipProcessingFilters ? "true" : "false" string signalData = '{' + '"date":"' + currentDate() + '"' + "," + '"hour":"' + currentTime() + '"' + "," + '"timezone":"' + currentTimezone() + '"' + "," + '"orderType":"' + orderType + '"' + "," + '"action":"' + action + '"' + "," + '"side":"' + side + '"' + "," + '"symbolCode":"' + positionSymbol + '"' + "," + '"symbolId":"' + positionSymbolId + '"' + "," + '"symbolMinTick":' + tostring(positionSymbolMinTick) + "," + '"exchangeId":"' + exchangeId + '"' + "," + '"signalPrice":' + tostring(open) + "," + '"indicatorType":"' + type + '"' + "," + '"indicatorPeriod":' + tostring(masterCycleLength) + "," + '"trailingStopTriggerPercent":' + tostring(trailingStopTriggerPercent * 100) + "," + '"trailingStopPercent":' + tostring(trailingStopPercent * 100) + "," + '"trailingStopLongPercent":' + tostring(trailingStopPercent * 100) + "," + '"stopLossPercent":' + tostring(stopLossPercent * 100) + "," + '"skipProcessingFilters":' + skipProcessingFiltersString + "," + '"providerEnvKey":"' + zignalyProviderEnvKey + '"' + '}' entryLongPosition(type) => string alertMessageEntry = composeSignalData("entry", "long", type) strategy.entry("long_entry", strategy.long, comment=type + "EntryLong", alert_message=alertMessageEntry) entryShortPosition(type) => string alertMessageEntry = composeSignalData("entry", "short", type) strategy.entry("short_entry", strategy.short, comment=type + "EntryShort", alert_message=alertMessageEntry) closeLongPosition(type) => string alertMessage = composeSignalData("exit", "long", type) bool executeExit = ignoreEarlyReverseSignal ? (entryPriceShortDiff >= stopLossPercent or entryPriceLongDiff >= trailingStopTriggerPercent) : true if (executeExit) strategy.close("long_entry", comment= type + "ExitLong", alert_message=alertMessage) closeShortPosition(type) => string alertMessage = composeSignalData("exit", "short", type) bool executeExit = ignoreEarlyReverseSignal ? (entryPriceLongDiff >= stopLossPercent or entryPriceShortDiff >= trailingStopTriggerPercent) : true if (executeExit) strategy.close("short_entry", comment=type + "ExitShort", alert_message=alertMessage) // Calculate long trailing stop. calculateTrailingStopLong() => longStopPrice = 0.0 stopFactor = trailingStopLongTrigger ? trailingStopPercent : stopLossPercent longStopPrice := if (currentPositionSize > 0) stopValue = baseStopPrice * (1 - stopFactor) max(stopValue, longStopPrice[1]) else 0 longStopPrice // Calculate short trailing stop. calculateTrailingStopShort() => shortStopPrice = 0.0 stopFactor = trailingStopShortTrigger ? trailingStopPercent : stopLossPercent shortStopPrice := if (currentPositionSize < 0) stopValue = baseStopPrice * (1 + stopFactor) min(stopValue, shortStopPrice[1]) else 9999999 shortStopPrice checkMACrossUpper(fastMAValues, slowMAValues) => bool maCross = crossover(fastMAValues, slowMAValues) int underCrossConsolidationPeriod = barssince(crossunder(fastMAValues, slowMAValues)) bool minCrossConsolidationPass = underCrossConsolidationPeriod >= minCrossConsolidationPeriod bool mlTrendLong = todayMLSignal == 1 and tomorrowMLSignal >= 1 if (exitOnReverseSignal and maCross) closeShortPosition("MA") if (enableEntryLongOrder and maCross and minCrossConsolidationPass and mlTrendLong) if (not ignoreNewSignal) entryLongPosition("MA") checkMACrossLower(fastMAValues, slowMAValues) => bool maCross = crossunder(fastMAValues, slowMAValues) int overCrossConsolidationPeriod = barssince(crossover(fastMAValues, slowMAValues)) bool minCrossConsolidationPass = overCrossConsolidationPeriod >= minCrossConsolidationPeriod bool mlTrendShort = todayMLSignal == 0 and tomorrowMLSignal == 0 if (exitOnReverseSignal and maCross) closeLongPosition("MA") if (enableEntryShortOrder and maCross and minCrossConsolidationPass and mlTrendShort) if (not ignoreNewSignal) entryShortPosition("MA") // Strategy MAs line plots. fastMAValues = calculateFastMA() slowMAValues = calculateSlowMA() plot(fastMAValues, color=color.lime, style=plot.style_line, linewidth=3) plot(slowMAValues, color=color.orange, style=plot.style_line, linewidth=2) checkMACrossUpper(fastMAValues, slowMAValues) checkMACrossLower(fastMAValues, slowMAValues) // Plot trailing stop price marks. longStopPrice = calculateTrailingStopLong() plot(series=(currentPositionSize > 0 and plotTrailingStop) ? longStopPrice: na, color=color.fuchsia, style=plot.style_cross, linewidth=2, title="Long Trail Stop") shortStopPrice = calculateTrailingStopShort() plot(series=(currentPositionSize < 0 and plotTrailingStop) ? shortStopPrice : na, color=color.fuchsia, style=plot.style_cross, linewidth=2, title="Short Trail Stop") // ISSUE NOTE: When strategy.exit is invoked through a function the alert_message // results in empty data. Keep the call at main script level. if (currentPositionSize > 0) string alertMessage = composeSignalData("exit", "long", "SL") strategy.exit("long_exit", "long_entry", comment="TSLExitLong", alert_message=alertMessage, stop=longStopPrice) // Submit exit orders for short position trailing stop. if (currentPositionSize < 0) string alertMessage = composeSignalData("exit", "short", "SL") strategy.exit("short_exit", "short_entry", comment="TSLExitShort", alert_message=alertMessage, stop=shortStopPrice) // Thanks to "Sol" trader that contributed the idea of rescaling ML daily trend signal to price. realOHLC = avg(open, high, low, close) priceSignalSmoothPeriod = calculateDayBarsCount() * 2 smoothRealPrice = priceSignalSmoothPeriod > 0 ? sma(realOHLC, priceSignalSmoothPeriod) : na priceSignal = smoothRealPrice * mlSignalSerieSmooth int plotOffset = calculateWeekBarsCount(futureWeeksNumber) plot(priceSignal, color=color.aqua, style=plot.style_line, linewidth=2, offset=plotOffset) //plot(todayMLSignal, color=color.silver, style=plot.style_cross, linewidth=1) // Mark future predictions boundary. bgcolor(barstate.islast ? color.new(color.silver, 60) : na)
Hammers & Stars Strategy
https://www.tradingview.com/script/t776tkZv-Hammers-Stars-Strategy/
ZenAndTheArtOfTrading
https://www.tradingview.com/u/ZenAndTheArtOfTrading/
3,558
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/ // Β© ZenAndTheArtOfTrading / PineScriptMastery // Last Updated: 5th October, 2021 // @version=4 strategy("Hammers & Stars Strategy [v1.1]", shorttitle="HSS[v1.1]", overlay=true) // Strategy Settings var g_strategy = "Strategy Settings" atrMinFilterSize = input(title=">= ATR Filter", type=input.float, defval=0.0, minval=0.0, group=g_strategy, tooltip="Minimum size of entry candle compared to ATR") atrMaxFilterSize = input(title="<= ATR Filter", type=input.float, defval=3.0, minval=0.0, group=g_strategy, tooltip="Maximum size of entry candle compared to ATR") stopMultiplier = input(title="Stop Loss ATR", type=input.float, defval=1.0, group=g_strategy, tooltip="Stop loss multiplier (x ATR)") rr = input(title="R:R", type=input.float, defval=1.0, group=g_strategy, tooltip="Risk:Reward profile") fibLevel = input(title="Fib Level", type=input.float, defval=0.333, group=g_strategy, tooltip="Used to calculate upper/lower third of candle. (For example, setting it to 0.5 will mean hammers must close >= 50% mark of the total candle size)") // Filter Settings var g_filter = "Filter Settings" emaFilter = input(title="EMA Filter", type=input.integer, defval=0, group=g_filter, tooltip="EMA length to filter trades - set to zero to disable") i_startTime = input(title="Start Date Filter", defval=timestamp("01 Jan 2000 13:30 +0000"), type=input.time, group=g_filter, tooltip="Date & time to begin trading from") i_endTime = input(title="End Date Filter", defval=timestamp("1 Jan 2099 19:30 +0000"), type=input.time, group=g_filter, tooltip="Date & time to stop trading") // Backtester Settings var g_tester = "Backtester Settings" startBalance = input(title="Starting Balance", type=input.float, defval=10000.0, group=g_tester, tooltip="Your starting balance for the custom inbuilt tester system") riskPerTrade = input(title="Risk Per Trade", type=input.float, defval=1.0, group=g_tester, tooltip="Your desired % risk per trade (as a whole number)") drawTester = input(title="Draw Backtester", type=input.bool, defval=true, group=g_tester, tooltip="Turn on/off inbuilt backtester display") // AutoView Settings var g_av = "AutoView Settings [OANDA]" av_use = input(title="Use AutoView?", type=input.bool, defval=false, group=g_av, tooltip="If turned on then the alerts this script generates will use AutoView syntax for auto-trading (WARNING: USE AT OWN RISK! RESEARCH THE DANGERS)") av_oandaDemo = input(title="Use Oanda Demo?", type=input.bool, defval=false, group=g_av, tooltip="If turned on then oandapractice broker prefix will be used for AutoView alerts (demo account). If turned off then live account will be used") av_limitOrder = input(title="Use Limit Order?", type=input.bool, defval=true, group=g_av, tooltip="If turned on then AutoView will use limit orders. If turned off then market orders will be used") av_gtdOrder = input(title="Days To Leave Limit Order", type=input.integer, minval=0, defval=2, group=g_av, tooltip="This is your GTD setting (good til day)") av_accountBalance = input(title="Account Balance", type=input.float, defval=1000.0, step=100, group=g_av, tooltip="Your account balance (used for calculating position size)") av_accountCurrency = input(title="Account Currency", type=input.string, defval="USD", options=["AUD", "CAD", "CHF", "EUR", "GBP", "JPY", "NZD", "USD"], group=g_av, tooltip="Your account balance currency (used for calculating position size)") av_riskPerTrade = input(title="Risk Per Trade %", type=input.float, defval=2.0, step=0.5, group=g_av, tooltip="Your risk per trade as a % of your account balance") // PineConnector Settings var g_pc = "PineConnector Settings" pc_use = input(title="Use PineConnector?", type=input.bool, defval=false, group=g_pc, tooltip="Use PineConnector Alerts? (WARNING: USE AT OWN RISK! RESEARCH THE DANGERS)") pc_id = input(title="License ID", type=input.string, defval="ID", group=g_pc, tooltip="This is your PineConnector license ID") pc_spread = input(title="Spread", type=input.float, defval=0.5, group=g_pc, tooltip="Enter your average spread for this pair (used for offsetting entry limit order from closing price)") pc_risk = input(title="Risk Per Trade", type=input.float, defval=1, step=0.5, group=g_pc, tooltip="This is how much to risk per trade (% of balance or lots - based on PC settings)") pc_prefix = input(title="MetaTrader Prefix", type=input.string, defval="", group=g_pc, tooltip="This is your broker's MetaTrader symbol prefix (leave blank if there is none)") pc_suffix = input(title="MetaTrader Suffix", type=input.string, defval="", group=g_pc, tooltip="This is your broker's MetaTrader symbol suffix (leave blank if there is none)") pc_limit = input(title="Use Limit Order?", type=input.bool, defval=true, group=g_pc, tooltip="If true a limit order will be used, if false a market order will be used") // Generate PineConnector alert string & prepare OANDA broker string var broker = av_oandaDemo ? "oandapractice" : "oanda" var symbol = pc_prefix + syminfo.ticker + pc_suffix var limit = pc_limit ? "limit" : "" var spread = syminfo.mintick * 10 * pc_spread pc_entry_alert(direction, sl, tp) => limit_price = direction == "buy" ? close - spread : close + spread price = pc_limit ? "price=" + tostring(limit_price) + "," : "" pc_id + "," + direction + limit + "," + symbol + "," + price + "sl=" + tostring(sl) + ",tp=" + tostring(tp) + ",risk=" + tostring(pc_risk) // See if this bar's time happened within date filter dateFilter = time >= i_startTime and time <= i_endTime // Get indicator values atr = atr(14) ema = ema(close, emaFilter == 0 ? 1 : emaFilter) // Custom function to convert pips into whole numbers toWhole(number) => return = atr < 1.0 ? (number / syminfo.mintick) / (10 / syminfo.pointvalue) : number return := atr >= 1.0 and atr < 100.0 and syminfo.currency == "JPY" ? return * 100 : return // Custom function to convert whole numbers back into pips toPips(number) => return = atr >= 1.0 ? number : (number * syminfo.mintick) * (10 / syminfo.pointvalue) return := atr >= 1.0 and atr < 100.0 and syminfo.currency == "JPY" ? return / 100 : return // Custom function to truncate (cut) excess decimal places truncate(_number, _decimalPlaces) => _factor = pow(10, _decimalPlaces) int(_number * _factor) / _factor // Check EMA Filter emaFilterLong = emaFilter == 0 or close > ema emaFilterShort = emaFilter == 0 or close < ema // Check ATR filter atrMinFilter = abs(high - low) >= (atrMinFilterSize * atr) or atrMinFilterSize == 0.0 atrMaxFilter = abs(high - low) <= (atrMaxFilterSize * atr) or atrMaxFilterSize == 0.0 atrFilter = atrMinFilter and atrMaxFilter // Calculate 33.3% 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 setup validHammer = lowestBody >= bullFib and atrFilter and close != open and not na(atr) and emaFilterLong validStar = highestBody <= bearFib and atrFilter and close != open and not na(atr) and emaFilterShort // Check if we have confirmation for our setup validLong = validHammer and strategy.position_size == 0 and dateFilter and barstate.isconfirmed validShort = validStar and strategy.position_size == 0 and dateFilter and barstate.isconfirmed //------------- DETERMINE POSITION SIZE -------------// // Get account inputs var tradePositionSize = 0.0 var pair = syminfo.basecurrency + "/" + syminfo.currency // Check if our account currency is the same as the base or quote currency (for risk $ conversion purposes) accountSameAsCounterCurrency = av_accountCurrency == syminfo.currency accountSameAsBaseCurrency = av_accountCurrency == syminfo.basecurrency // Check if our account currency is neither the base or quote currency (for risk $ conversion purposes) accountNeitherCurrency = not accountSameAsCounterCurrency and not accountSameAsBaseCurrency // Get currency conversion rates if applicable conversionCurrencyPair = accountSameAsCounterCurrency ? syminfo.tickerid : accountNeitherCurrency ? av_accountCurrency + syminfo.currency : av_accountCurrency + syminfo.currency conversionCurrencyRate = security(symbol=syminfo.type == "forex" ? conversionCurrencyPair : "AUDUSD", resolution="D", expression=close) // Calculate position size getPositionSize(stopLossSizePoints) => riskAmount = (av_accountBalance * (av_riskPerTrade / 100)) * (accountSameAsBaseCurrency or accountNeitherCurrency ? conversionCurrencyRate : 1.0) riskPerPoint = (stopLossSizePoints * syminfo.pointvalue) positionSize = (riskAmount / riskPerPoint) / syminfo.mintick round(positionSize) // Set up our GTD (good-til-day) order info gtdTime = time + (av_gtdOrder * 1440 * 60 * 1000) // 86,400,000ms per day gtdYear = year(gtdTime) gtdMonth = month(gtdTime) gtdDay = dayofmonth(gtdTime) gtdString = " dt=" + tostring(gtdYear) + "-" + tostring(gtdMonth) + "-" + tostring(gtdDay) //------------- END POSITION SIZE CODE -------------// // Calculate our stop distance & size for the current bar stopSize = atr * stopMultiplier longStopPrice = low < low[1] ? low - stopSize : low[1] - stopSize longStopDistance = close - longStopPrice longTargetPrice = close + (longStopDistance * rr) shortStopPrice = high > high[1] ? high + stopSize : high[1] + stopSize shortStopDistance = shortStopPrice - close shortTargetPrice = close - (shortStopDistance * rr) // Save trade stop & target & position size if a valid setup is detected var t_entry = 0.0 var t_stop = 0.0 var t_target = 0.0 var t_direction = 0 // Detect valid long setups & trigger alert if validLong t_entry := close t_stop := longStopPrice t_target := longTargetPrice t_direction := 1 tradePositionSize := getPositionSize(toWhole(longStopDistance) * 10) strategy.entry(id="Long", long=strategy.long, when=validLong, comment="(SL=" + tostring(truncate(toWhole(longStopDistance),2)) + " pips)") // Fire alerts if not av_use and not pc_use alert(message="Bullish Hammer Detected!", freq=alert.freq_once_per_bar_close) // Trigger PineConnector long alert if pc_use alertString = pc_entry_alert("buy", t_stop, t_target) alert(alertString, alert.freq_once_per_bar_close) // Trigger AutoView long alert if av_use alert(message="e=" + broker + " b=long q=" + tostring(tradePositionSize) + " s=" + pair + " t=" + (av_limitOrder ? "limit fp=" + tostring(close) : "market") + " fsl=" + tostring(t_stop) + " ftp=" + tostring(t_target) + (av_gtdOrder != 0 and av_limitOrder ? gtdString : ""), freq=alert.freq_once_per_bar_close) // Detect valid short setups & trigger alert if validShort t_entry := close t_stop := shortStopPrice t_target := shortTargetPrice t_direction := -1 tradePositionSize := getPositionSize(toWhole(shortStopDistance) * 10) strategy.entry(id="Short", long=strategy.short, when=validShort, comment="(SL=" + tostring(truncate(toWhole(shortStopDistance),2)) + " pips)") // Fire alerts if not av_use and not pc_use alert(message="Bearish Hammer Detected!", freq=alert.freq_once_per_bar_close) // Trigger PineConnector short alert if pc_use alertString = pc_entry_alert("sell", t_stop, t_target) alert(alertString, alert.freq_once_per_bar_close) // Trigger AutoView short alert if av_use alert(message="e=" + broker + " b=short q=" + tostring(tradePositionSize) + " s=" + pair + " t=" + (av_limitOrder ? "limit fp=" + tostring(close) : "market") + " fsl=" + tostring(t_stop) + " ftp=" + tostring(t_target) + (av_gtdOrder != 0 and av_limitOrder ? gtdString : ""), freq=alert.freq_once_per_bar_close) // Check if price has hit long stop loss or target if t_direction == 1 and (low <= t_stop or high >= t_target) t_direction := 0 // Cancel limit order if it hasn't been filled yet if pc_limit and pc_use alert(pc_id + ",cancellong," + symbol) // Check if price has hit short stop loss or target if t_direction == -1 and (high >= t_stop or low <= t_target) t_direction := 0 // Cancel limit order if it hasn't been filled yet if pc_limit and pc_use alert(pc_id + ",cancelshort," + symbol) // Exit trades whenever our stop or target is hit strategy.exit(id="Long Exit", from_entry="Long", limit=t_target, stop=t_stop, when=strategy.position_size > 0) strategy.exit(id="Short Exit", from_entry="Short", limit=t_target, stop=t_stop, when=strategy.position_size < 0) // Draw trade data plot(strategy.position_size != 0 or validLong or validShort ? t_stop : na, title="Trade Stop Price", color=color.red, style=plot.style_linebr) plot(strategy.position_size != 0 or validLong or validShort ? t_target : na, title="Trade Target Price", color=color.green, style=plot.style_linebr) plot(strategy.position_size != 0 or validLong or validShort ? tradePositionSize : na, color=color.purple, display=display.none, title="AutoView Position Size") // Draw EMA if it's enabled plot(emaFilter == 0 ? na : ema, color=emaFilterLong ? color.green : color.red, linewidth=2, title="EMA") // Draw price action setup arrows plotshape(validLong ? 1 : na, style=shape.triangleup, location=location.belowbar, color=color.green, title="Bullish Setup") plotshape(validShort ? 1 : na, style=shape.triangledown, location=location.abovebar, color=color.red, title="Bearish Setup") // --- BEGIN TESTER CODE --- // // Declare performance tracking variables var balance = startBalance var drawdown = 0.0 var maxDrawdown = 0.0 var maxBalance = 0.0 var totalPips = 0.0 var totalWins = 0 var totalLoss = 0 // Detect winning trades if strategy.wintrades != strategy.wintrades[1] balance := balance + ((riskPerTrade / 100) * balance) * rr totalPips := totalPips + abs(t_entry - t_target) totalWins := totalWins + 1 if balance > maxBalance maxBalance := balance // Detect losing trades if strategy.losstrades != strategy.losstrades[1] balance := balance - ((riskPerTrade / 100) * balance) totalPips := totalPips - abs(t_entry - t_stop) totalLoss := totalLoss + 1 // Update drawdown drawdown := (balance / maxBalance) - 1 if drawdown < maxDrawdown maxDrawdown := drawdown // Prepare stats table var table testTable = table.new(position.top_right, 5, 2, border_width=1) f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) => _cellText = _title + "\n" + _value table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor) // Draw stats table var bgcolor = color.new(color.black,0) if drawTester if barstate.islastconfirmedhistory // Update table dollarReturn = balance - startBalance f_fillCell(testTable, 0, 0, "Total Trades:", tostring(strategy.closedtrades), bgcolor, color.white) f_fillCell(testTable, 0, 1, "Win Rate:", tostring(truncate((strategy.wintrades/strategy.closedtrades)*100,2)) + "%", bgcolor, color.white) f_fillCell(testTable, 1, 0, "Starting:", "$" + tostring(startBalance), bgcolor, color.white) f_fillCell(testTable, 1, 1, "Ending:", "$" + tostring(truncate(balance,2)), bgcolor, color.white) f_fillCell(testTable, 2, 0, "Return:", "$" + tostring(truncate(dollarReturn,2)), dollarReturn > 0 ? color.green : color.red, color.white) f_fillCell(testTable, 2, 1, "Pips:", (totalPips > 0 ? "+" : "") + tostring(truncate(toWhole(totalPips),2)), bgcolor, color.white) f_fillCell(testTable, 3, 0, "Return:", (dollarReturn > 0 ? "+" : "") + tostring(truncate((dollarReturn / startBalance)*100,2)) + "%", dollarReturn > 0 ? color.green : color.red, color.white) f_fillCell(testTable, 3, 1, "Max DD:", tostring(truncate(maxDrawdown*100,2)) + "%", color.red, color.white) // --- END TESTER CODE --- //
VixFixLinReg-Strategy
https://www.tradingview.com/script/VRbtGCcs-VixFixLinReg-Strategy/
Trendoscope
https://www.tradingview.com/u/Trendoscope/
269
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/ // Β© HeWhoMustNotBeNamed //@version=4 strategy("VixFixLinReg-Strategy", shorttitle="VixFixLinReg - Strategy", overlay=false, initial_capital = 100000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, pyramiding = 1, commission_value = 0.01) pd = input(22, title="LookBack Period Standard Deviation High") bbl = input(20, title="Bolinger Band Length") mult = input(2.0 , minval=1, maxval=5, title="Bollinger Band Standard Devaition Up") lb = input(50 , title="Look Back Period Percentile High") ph = input(.85, title="Highest Percentile - 0.90=90%, 0.95=95%, 0.99=99%") pl = input(1.01, title="Lowest Percentile - 1.10=90%, 1.05=95%, 1.01=99%") hp = input(false, title="Show High Range - Based on Percentile and LookBack Period?") sd = input(false, title="Show Standard Deviation Line?") i_startTime = input(defval = timestamp("01 Jan 2010 00:00 +0000"), title = "Start Time", type = input.time) i_endTime = input(defval = timestamp("01 Jan 2099 00:00 +0000"), title = "End Time", type = input.time) inDateRange = time >= i_startTime and time <= i_endTime considerVIXFixClose = input(false) lengthKC=input(20, title="KC Length") multKC = input(1.5, title="KC MultFactor") atrLen = input(22) atrMult = input(5) initialStopBar = input(5) waitForCloseBeforeStop = input(true) f_getStop(atrLen, atrMult)=> stop = strategy.position_size > 0 ? close - (atrMult * atr(atrLen)) : lowest(initialStopBar) stop := strategy.position_size > 0 ? max(stop,nz(stop[1], stop)) : lowest(initialStopBar) stop wvf = ((highest(close, pd)-low)/(highest(close, pd)))*100 sDev = mult * stdev(wvf, bbl) midLine = sma(wvf, bbl) lowerBand = midLine - sDev upperBand = midLine + sDev rangeHigh = (highest(wvf, lb)) * ph rangeLow = (lowest(wvf, lb)) * pl col = wvf >= upperBand or wvf >= rangeHigh ? color.lime : color.gray val = linreg(wvf, pd, 0) absVal = abs(val) linRegColor = val>val[1]? (val > 0 ? color.green : color.orange): (val > 0 ? color.lime : color.red) plot(hp and rangeHigh ? rangeHigh : na, title="Range High Percentile", style=plot.style_line, linewidth=4, color=color.orange) plot(hp and rangeLow ? rangeLow : na, title="Range High Percentile", style=plot.style_line, linewidth=4, color=color.orange) plot(wvf, title="Williams Vix Fix", style=plot.style_histogram, linewidth = 4, color=col) plot(sd and upperBand ? upperBand : na, title="Upper Band", style=plot.style_line, linewidth = 3, color=color.aqua) plot(-absVal, title="Linear Regression", style=plot.style_histogram, linewidth=4, color=linRegColor) vixFixState = (col == color.lime) ? 1: 0 vixFixState := strategy.position_size == 0? max(vixFixState, nz(vixFixState[1],0)) : vixFixState longCondition = (vixFixState == 1 and linRegColor == color.lime) and inDateRange exitLongCondition = (linRegColor == color.orange or linRegColor == color.red) and considerVIXFixClose stop = f_getStop(atrLen, atrMult) label_x = time+(60*60*24*1000*20) myLabel = label.new(x=label_x, y=0, text="Stop : "+tostring(stop), xloc=xloc.bar_time, style=label.style_none, textcolor=color.black, size=size.normal) label.delete(myLabel[1]) strategy.entry("Long", strategy.long, when=longCondition, oca_name="oca_buy", oca_type=strategy.oca.cancel) strategy.close("Long", when=exitLongCondition or (close < stop and waitForCloseBeforeStop and linRegColor == color.green)) strategy.exit("ExitLong", "Long", stop = stop, when=not waitForCloseBeforeStop and linRegColor == color.green)
BTC Rapid fire strategy 1M Scalping
https://www.tradingview.com/script/c620W1po-BTC-Rapid-fire-strategy-1M-Scalping/
atakhadivi
https://www.tradingview.com/u/atakhadivi/
70
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© atakhadivi //@version=4 strategy("rapid fire", overlay=true) longCondition = open > sar(0.02,0.02,0.2) and open[1] < sar(0.02,0.02,0.2)[1] and open > sma(close,50) takeprofit = strategy.position_avg_price * (1 + 0.005) stopLoss = strategy.position_avg_price * (1 - 0.015) if (longCondition) strategy.entry("longEntry", strategy.long, limit = takeprofit, stop = stopLoss) shortCondition = open < sar(0.02,0.02,0.2) and open[1] > sar(0.02,0.02,0.2)[1] and open < sma(close,50) take_profit = strategy.position_avg_price * (1 - 0.005) stop_Loss = strategy.position_avg_price * (1 + 0.015) if (shortCondition) strategy.entry("shortEntry", strategy.short, limit = take_profit, stop = stop_Loss)
Donchian Channel Strategy
https://www.tradingview.com/script/7lDOCF4F-Donchian-Channel-Strategy/
pratyush_trades
https://www.tradingview.com/u/pratyush_trades/
449
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/ // Β© pratyush_trades //@version=4 strategy("Donchian Channel Strategy", overlay=true) length = input(20) longRule = input("Higher High", "Long Entry", options=["Higher High", "Basis"]) shortRule = input("Lower Low", "Short Entry", options=["Lower Low", "Basis"]) hh = highest(high, length) ll = lowest(low, length) up = plot(hh, 'Upper Band', color = color.green) dw = plot(ll, 'Lower Band', color = color.red) mid = (hh + ll) / 2 midPlot = plot(mid, 'Basis', color = color.orange) fill(up, midPlot, color=color.green, transp = 95) fill(dw, midPlot, color=color.red, transp = 95) if (close>ema(close,200)) if (not na(close[length])) strategy.entry("Long", strategy.long, stop=longRule=='Basis' ? mid : hh) if (close<ema(close,200)) if (not na(close[length])) strategy.entry("Short", strategy.short, stop=shortRule=='Basis' ? mid : ll) if (strategy.position_size>0) strategy.exit(id="Longs Exit",stop=ll) if (strategy.position_size<0) strategy.exit(id="Shorts Exit",stop=hh)
Jigga - Heatmap Comparision
https://www.tradingview.com/script/N9IEVihp-Jigga-Heatmap-Comparision/
jigneshjc
https://www.tradingview.com/u/jigneshjc/
36
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/ // Β© jigneshjc //@version=5 strategy('Jigga - Heatmap Comparision', overlay=false) checkRSI = input(true, title='------------------------ RSI ------------------------') length_RSI = input.int(14, title='Signal', inline='RSI') upperValueRSI = input.int(55, title='Upper', inline='RSI') lowerValueRSI = input.int(45, title='Lower', inline='RSI') checkMA = input(false, title='------------------------ EMA CrossOver ------------------------') fastMA = input.int(20, title='Fast', inline='EMA Crossover') slowMA = input.int(50, title='Slow', inline='EMA Crossover') includeIndex = input(false, title='------------------------ INDEX ------------------------') symbol1 = input.symbol(title='1', defval='NSE:CNXMETAL', inline='Symbol') symbol2 = input.symbol(title='2', defval='NSE:CNXFMCG', inline='Symbol') symbol3 = input.symbol(title='3', defval='NSE:CNXIT', inline='Symbol') symbol4 = input.symbol(title='4', defval='NSE:CNXPHARMA', inline='Symbol') symbol5 = input.symbol(title='5', defval='NSE:CNXAUTO', inline='Symbol') doBackTesting = input(false, title='------------------------ Do BackTesting ------------------------') refSector = input.int(title='Buy sell based on sector #', defval=1, options=[1, 2, 3, 4, 5]) updown(price) => closePrice = price vrsi = ta.rsi(closePrice, length_RSI) up = false down = false if checkRSI and checkMA up := vrsi > upperValueRSI and ta.ema(closePrice, fastMA) > ta.ema(closePrice, slowMA) ? true : vrsi < lowerValueRSI and ta.ema(closePrice, fastMA) < ta.ema(closePrice, slowMA) ? false : up[1] up else if checkRSI up := vrsi > upperValueRSI ? true : vrsi < lowerValueRSI ? false : up[1] up else if checkMA up := ta.ema(closePrice, fastMA) > ta.ema(closePrice, slowMA) ? true : false up up s1Close = request.security(symbol1, timeframe.period, close) s2Close = request.security(symbol2, timeframe.period, close) s3Close = request.security(symbol3, timeframe.period, close) s4Close = request.security(symbol4, timeframe.period, close) s5Close = request.security(symbol5, timeframe.period, close) s1RSIup = updown(s1Close) s2RSIup = updown(s2Close) s3RSIup = updown(s3Close) s4RSIup = updown(s4Close) s5RSIup = updown(s5Close) refSectorup = refSector == 1 ? s1RSIup : refSector == 2 ? s2RSIup : refSector == 3 ? s2RSIup : refSector == 4 ? s4RSIup : s5RSIup h0 = hline(1, color=color.new(color.black, 10), linewidth=2, linestyle=hline.style_solid) h1 = hline(2, color=color.new(color.black, 10), linewidth=2, linestyle=hline.style_solid) h2 = hline(3, color=color.new(color.black, 10), linewidth=2, linestyle=hline.style_solid) h3 = hline(4, color=color.new(color.black, 10), linewidth=2, linestyle=hline.style_solid) h4 = hline(5, color=color.new(color.black, 10), linewidth=2, linestyle=hline.style_solid) h5 = hline(6, color=color.new(color.black, 10), linewidth=2, linestyle=hline.style_solid) lapos_x = timenow + math.round(ta.change(time) * 20) lapos_y = ta.highest(5) // + (0.15 * highest(20)) get_bars(Trend) => since_st_buy = ta.barssince(Trend == true) since_st_sell = ta.barssince(Trend == false) [since_st_buy, since_st_sell] [since_st_1_buy, since_st_1_sell] = get_bars(s5RSIup) [since_st_2_buy, since_st_2_sell] = get_bars(s4RSIup) [since_st_3_buy, since_st_3_sell] = get_bars(s3RSIup) [since_st_4_buy, since_st_4_sell] = get_bars(s2RSIup) [since_st_5_buy, since_st_5_sell] = get_bars(s1RSIup) heatmap_color(cond1, cond2, colorValue) => cond1 ? colorValue : cond2 ? color.new(color.silver, 20) : na f_draw_label(x, y, _text, _textcolor, _size) => var label Label = na label.delete(Label) Label := label.new(x, y, _text, color=color.new(color.white, 20), textcolor=_textcolor, style=label.style_none, yloc=yloc.price, xloc=xloc.bar_time, size=_size) Label f_draw_label(lapos_x, 1, symbol5, color.black, size.large) f_draw_label(lapos_x, 2, symbol4, color.black, size.large) f_draw_label(lapos_x, 3, symbol3, color.black, size.large) f_draw_label(lapos_x, 4, symbol2, color.black, size.large) f_draw_label(lapos_x, 5, symbol1, color.black, size.large) fill(h0, h1, color=heatmap_color(since_st_1_sell > since_st_1_buy, since_st_1_sell < since_st_1_buy, color.new(color.fuchsia, 20)), title='Sector5', transp=90) fill(h1, h2, color=heatmap_color(since_st_2_sell > since_st_2_buy, since_st_2_sell < since_st_2_buy, color.new(color.yellow, 20)), title='Sector4', transp=90) fill(h2, h3, color=heatmap_color(since_st_3_sell > since_st_3_buy, since_st_3_sell < since_st_3_buy, color.new(color.lime, 20)), title='Sector3', transp=90) fill(h3, h4, color=heatmap_color(since_st_4_sell > since_st_4_buy, since_st_4_sell < since_st_4_buy, color.new(color.orange, 20)), title='Sector2', transp=90) fill(h4, h5, color=heatmap_color(since_st_5_sell > since_st_5_buy, since_st_5_sell < since_st_5_buy, color.new(color.blue, 20)), title='Sector1', transp=90) if strategy.position_size == 0 and refSectorup and doBackTesting strategy.entry(id='In', direction=strategy.long) if not refSectorup and doBackTesting strategy.close('In')
Momentum Strategy
https://www.tradingview.com/script/LGAJeltq-Momentum-Strategy/
PrattyCharts
https://www.tradingview.com/u/PrattyCharts/
467
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/ // Β© PrattyCharts //@version=4 strategy("Momentum Strategy", overlay=true, process_orders_on_close =true) isCrypto = false if(syminfo.prefix == "COINBASE" or syminfo.prefix == "BINANCE" or syminfo.prefix == "FTX" or syminfo.prefix == "BITSTAMP") isCrypto := true benchmark = syminfo.root == "SPX" or syminfo.root == "BTCUSD" // momentum settings highPeriod = input(63, type = input.integer, title = "New Highs Period") relativeHighPeriod = input(40, type = input.integer, title = "New Relative Highs Period") trendMovingAverage = input(50, type = input.integer, title = "Uptrend Period") trailingMovingAverage = input(20, type = input.integer, title = "First Moving Average Stop") bullmarket = rising(ema(close, 200),1) and rising(ema(close, 200),1) strategy.risk.allow_entry_in(strategy.direction.long) longMA = ema(close, trendMovingAverage) shortMA = ema(close, trailingMovingAverage) plot(shortMA, transp = 70) plot(longMA, transp = 70) // check for new relative high comparativeTickerStock = input("SPX", type = input.symbol, title = "Stock Benchmark") comparativeTickerCrypto = input("BTCUSD", type = input.symbol, title = "Crypto Benchmark") baseSymbol = security(syminfo.tickerid, timeframe.period, close) benchmarkStock = security(comparativeTickerStock, timeframe.period, close) benchmarkCrypto = security(comparativeTickerCrypto, timeframe.period, close) rs = baseSymbol / benchmarkStock // check if bitcoin should be used for relative strength if(isCrypto) rs := baseSymbol / benchmarkCrypto newRelativeHigh = rs > highest(rs[1], relativeHighPeriod) relativeUptrend = rising(ema(rs,trendMovingAverage),1) // triggers isNewHigh = close > highest(close[1], highPeriod) hasRelativeStrength = newRelativeHigh and relativeUptrend upperClosingRange = close-open > 0.85 * (open-high) // closing near upper 85% of candle range hasBullishRSI = rsi(close, 14) > 60 inUptrend = rising(longMA,1) buyTrigger = isNewHigh and upperClosingRange and inUptrend and hasBullishRSI if(not benchmark) // do not do relative analysis for benchmarks buyTrigger := buyTrigger and hasRelativeStrength // determine which exit to use exitTrigger = close < shortMA var trending = false // check if the stock is trending nicely if(close > strategy.position_avg_price * 1.20) trending := true // if the stock is trending well use a longer moving average if(trending) exitTrigger := close < longMA // check if the stock is breaking down on a relative basis rsEMA = ema(rs, trendMovingAverage) if(rs < rsEMA ) exitTrigger :=true // strategy if (buyTrigger) strategy.entry("buy ", strategy.long, comment = "Buy") if(exitTrigger) strategy.entry("sell ", strategy.short, comment = "Exit") trending := false
Fibonacci candle with Fibonacci ema strategy
https://www.tradingview.com/script/zQD1Qknz-Fibonacci-candle-with-Fibonacci-ema-strategy/
SoftKill21
https://www.tradingview.com/u/SoftKill21/
221
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/ // Β© SoftKill21 //@version=4 strategy("Fibonacci candle", overlay=true,initial_capital = 1000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent , commission_value=0.1 ) //plot of our fibonacci candle // Fibonacci // Fn = Fn-1 + Fn-2 // F10 = 55 // 0 1 2 3 5 8 13 21 34 55 avg_close = (close[0] + close[1] + close[2] + close[3] +close[5] + close[8] + close[13]+ close[21] + close[34] + close[55]) / 10 avg_high = (high[0] + high[1] + high[2] + high[3] +high[5] + high[8] + high[13]+ high[21] + high[34] + high[55]) / 10 avg_low = (low[0] + low[1] + low[2] + low[3] +low[5] + low[8] + low[13]+ low[21] + low[34] + low[55]) / 10 avg_open = (open[0] + open[1] + open[2] + open[3] +open[5] + open[8] + open[13]+ open[21] + open[34] + open[55]) / 10 length_ema_vol=input(12) volume_avg =(volume[0] + volume[1] + volume[2] + volume[3] +volume[5] + volume[8] + volume[13]+ volume[21] + volume[34] + volume[55]) / 10 ema_volume_avg = ema(volume_avg,length_ema_vol) // plot(volume_avg,color=color.white) // plot(ema_volume_avg) longvol = crossover(volume_avg,ema_volume_avg) shortvol = crossunder(volume_avg, ema_volume_avg) src = avg_close//input(avg_close, title="Source") out55 = ema(src, 55) out1 = ema(src, 1) out2 = ema(src, 2) out3 = ema(src, 3) out5 = ema(src, 5) out8 = ema(src, 8) out13 = ema(src, 13) out21 = ema(src, 21) out34 = ema(src, 34) avg_ema = (out55 + out1 + out2 + out3+ out5 + out8 + out13 + out21 + out34)/9 //plot(avg_ema) //plotcandle(avg_open, avg_high, avg_low, avg_close, title='Title', color = avg_open < avg_close ? color.green : color.red, wickcolor=color.white) //stochastic periodK = input(9, title="K", minval=1) periodD = input(3, title="D", minval=1) smoothK = input(3, title="Smooth", minval=1) k = sma(stoch(close, high, low, periodK), smoothK) d = sma(k, periodD) avg_stoch = (k+d)/2 //plot(avg_stoch) stoch_middle=input(40) //plot(50) // long = avg_open < avg_close and avg_close > avg_close[1] and avg_high > avg_high[1] and avg_close[1] > avg_close[2] and avg_high[1] > avg_high[2] and longvol and avg_stoch>stoch_middle short = avg_open > avg_close and avg_close < avg_close[1] and avg_low < avg_low[1] and avg_close[1] < avg_close[2] and avg_low[1] < avg_low[2] and shortvol and avg_stoch<stoch_middle strategy.entry("long",1,when=long and avg_close > avg_ema) strategy.close('long',when=short and avg_close < avg_ema)
MACD, RSI, & RVOL Strategy
https://www.tradingview.com/script/7GmXKfig-MACD-RSI-RVOL-Strategy/
BobBarker42069
https://www.tradingview.com/u/BobBarker42069/
806
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/ // Β© BobBarker42069 //@version=4 strategy("MACD, RSI, & RVOL Strategy", overlay=true, max_bars_back=5000, default_qty_type= strategy.cash, calc_on_order_fills=false, calc_on_every_tick=false, pyramiding=0, default_qty_value=100000, initial_capital=100000) strategy.risk.allow_entry_in(strategy.direction.long) length = input( 14 ) overSold = input( 30 ) overBought = input( 70 ) price = close vrsi = rsi(price, length) co = crossover(vrsi, overSold) cu = crossunder(vrsi, overBought) fastLength = input(12) slowlength = input(26) MACDLength = input(9) MACD = ema(close, fastLength) - ema(close, slowlength) aMACD = ema(MACD, MACDLength) delta = MACD - aMACD RVOLlen = input(14, minval=1, title="RVOL Length") av = sma(volume, RVOLlen) RVOL = volume / av if (not na(vrsi)) if ((co and crossover(delta, 0)) or (co and crossover(RVOL, 2)) or (crossover(delta, 0) and crossover(RVOL, 2))) strategy.entry("MACD & RSI BUY Long", strategy.long, comment="BUY LONG") if ((cu and crossunder(delta, 0)) or (cu and crossunder(RVOL, 5)) or (crossunder(delta, 0) and crossunder(RVOL, 5))) strategy.entry("MACD & RSI SELL Short", strategy.short, comment="SELL LONG") //plot(strategy.equity, title="equity", color=color.red, linewidth=2, style=plot.style_areabr)
(IK) Base Break Buy
https://www.tradingview.com/script/JkzbgenP-IK-Base-Break-Buy/
tapRoot_coding
https://www.tradingview.com/u/tapRoot_coding/
453
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© userIan //@version=4 strategy("(IK) Base Break Buy", overlay=true, pyramiding=6, precision=2, default_qty_type=strategy.cash, initial_capital=100.0, currency="USD", commission_type=strategy.commission.percent, commission_value=0.1) // == INPUT == i_baseMax = input(group="Base Calculations", title="Max Bases", type=input.integer, defval=3, minval=1, maxval=10) // max amount of bases on the chart at any specific time i_dev = input(group="Base Calculations", title="Base Area Deviation", type=input.float, defval=0.005, minval=0.0, maxval=1.0) // if enough recent bars had bottoms within this deviation of the current bar's bottom, a base is created i_baseDev = input(group="Base Calculations", title="Unique Base Deviation", type=input.float, defval=0.05, minval=0.0, maxval=1.0) // bases cannot be created if they fall within this deviation of an extant base i_baseSource = input(group="Base Calculations", title="Base Source", options=["Close or Open", "Low"], defval="Close or Open") // should base calcuations be based off of candlestick closes and opens (whichever is lower), or candlestick lows i_lookback = input(group="Base Calculations", title="Lookback", type=input.integer, defval=100) // how many bars back do we check to confirm current bases i_confLevel = input(group="Base Calculations", title="Confidence Level", type=input.float, defval=0.01, minval=0.0, maxval=1.0) // what percentage of historical bars bottoming within deviation are needed to confirm a base i_breakThresh = input(group="Base Break Detection", title="Break Threshold", type=input.float, defval=0.02, minval=0.0, maxval=1.0) // how far (by percentage) does price have to fall below a base to constitute a 'break' i_breakWindow = input(group="Base Break Detection", title="Break Window", type=input.integer, defval=5) // how many bars should we allow for price to fall below the break threshold before it's no longer a tradable break i_initialOrder = input(group="Order Settings", title="Initial Order Capital", type=input.float, defval=0.2, minval=0.0, maxval=1.0) // what percentage of capital to use in initial trade entry i_safetyCount = input(group="Order Settings", title="Safety Order Max Count", type=input.integer, defval=3, minval=0, maxval=5) // maximum amount of safety orders per trade. remaining capital after initial entry will be divided evenly among these i_safetyThresh = input(group="Order Settings", title="Safter Order Threshold", type=input.float, defval=0.03, minval=0.0, maxval=1.0) // what percentage does price need to fall to activate a safety order i_stopLoss = input(group="Order Settings", title="Stop Loss", type=input.float, defval=0.2, minval=0.0, maxval=1.0) // what percentage does price need to fall to activate a stop loss i_stopLossType = input(group="Order Settings", title="Stop Loss Type", options=['From Initial Entry', 'From Price Average'], defval='From Price Average') // calculate static stop loss based on price at first entry, or dynamic stop loass based on position average price // == FUNCTIONS == // is _val1 within the deviation (_dev) of _val2? f_isCloseTo(_val1, _val2, _dev) => (_val1 <= _val2*(1+_dev)) and (_val1 >= _val2*(1-_dev)) // is this confirmed base (_val) distant enough (outside of deviation _dev) from another confirmed base (in _arr)? f_newBase(_val, _arr, _dev) => result = true if array.size(_arr) > 0 for i = 0 to array.size(_arr)-1 if (_val <= array.get(_arr, i)*(1+_dev)) and (_val >= array.get(_arr, i)*(1-_dev)) result := false result // == VARIABLES == var bases = array.new_float() // reference to every current base var closestBase = float(na) // the closest base to currenct price (only below price) var brokenBase = float(na) // the base that has been recently broken var baseBreakIndex = int(na) // when the most recent base was broken var takeProfit = float(na) // dynamic take profit percentage base on severity of base break var safetyOrderQty = ((strategy.initial_capital*(1-i_initialOrder))/i_safetyCount)/100 // percentage of capital to use for each safety order var safetyCount = 0 // keep track of how many safety orders we've made // == LOGIC == // detect bases and add unique bases to base array currentBot = i_baseSource == "Low" ? low : min(close,open) count = 0 for i = 1 to i_lookback bot = i_baseSource == "Low" ? low[i] : min(close[i],open[i]) if f_isCloseTo(currentBot, bot, i_dev) count := count +1 if count >= (i_lookback * i_confLevel) and f_newBase(currentBot, bases, i_baseDev) array.unshift(bases, currentBot) // prune base array if array.size(bases) > i_baseMax array.pop(bases) // detect base break if crossunder(close, closestBase) and strategy.position_size == 0 baseBreakIndex := bar_index brokenBase := closestBase // reset baseBreak if window has expired; this is no longer a tradable break if (bar_index - baseBreakIndex > i_breakWindow) and strategy.position_size == 0 brokenBase := na // update closest base if array.size(bases) > 0 array.sort(bases, order.descending) for i = 0 to array.size(bases)-1 if array.get(bases, i) < close closestBase := array.get(bases,i) break // reset safety count if a trade has just been exited if strategy.position_size == 0 safetyCount := 0 // == ENTRY AND EXIT == // enter trade if break is confirmed and set the takeProfit percentage if close < (brokenBase * (1-i_breakThresh)) and strategy.position_size == 0 and barstate.isconfirmed strategy.entry(id="Long", long=strategy.long, qty=(strategy.initial_capital * i_initialOrder)/close, comment='buy') takeProfit := 1-(close/brokenBase) // safety order if close < (strategy.position_avg_price * (1-i_safetyThresh)) and safetyCount < i_safetyCount safetyCount := safetyCount + 1 strategy.entry(id="Long", long=strategy.long, qty=(strategy.initial_capital * safetyOrderQty)/close, comment='safety') // exit trade strategy.exit(id="Long", stop=i_stopLossType == "From Price Average" ? strategy.position_avg_price * (1-i_stopLoss) : brokenBase * (1-i_stopLoss), comment='sell-stop') if (close > strategy.position_avg_price * (1+takeProfit)) and barstate.isconfirmed strategy.close("Long", comment='sell-profit') brokenBase := na // == PLOT == plotTimer = bar_index % 2 == 0 // this creates a dashed line plot(array.size(bases) > 0 and plotTimer ? array.get(bases,0) : na, color=color.white, style=plot.style_linebr) plot(array.size(bases) > 1 and plotTimer ? array.get(bases,1) : na, color=color.white, style=plot.style_linebr) plot(array.size(bases) > 2 and plotTimer ? array.get(bases,2) : na, color=color.white, style=plot.style_linebr) plot(array.size(bases) > 3 and plotTimer ? array.get(bases,3) : na, color=color.white, style=plot.style_linebr) plot(array.size(bases) > 4 and plotTimer ? array.get(bases,4) : na, color=color.white, style=plot.style_linebr) plot(array.size(bases) > 5 and plotTimer ? array.get(bases,5) : na, color=color.white, style=plot.style_linebr) plot(array.size(bases) > 6 and plotTimer ? array.get(bases,6) : na, color=color.white, style=plot.style_linebr) plot(array.size(bases) > 7 and plotTimer ? array.get(bases,7) : na, color=color.white, style=plot.style_linebr) plot(array.size(bases) > 8 and plotTimer ? array.get(bases,8) : na, color=color.white, style=plot.style_linebr) plot(array.size(bases) > 9 and plotTimer ? array.get(bases,9) : na, color=color.white, style=plot.style_linebr) plot(closestBase == closestBase[1] and strategy.position_size == 0 ? closestBase : na, color=color.yellow, style=plot.style_linebr) // yellow line for closest base (if not in trade) plot(brokenBase, color=color.purple, style=plot.style_linebr) // purple line for the broken base that triggered the trade plot(strategy.position_avg_price * (1+takeProfit), color=color.silver, style=plot.style_linebr) // silver line for target profit plot(i_stopLossType == "From Price Average" ? strategy.position_avg_price * (1-i_stopLoss) : brokenBase * (1-i_stopLoss), color=color.red, style=plot.style_linebr) // red line for stop loss
[KL] Bollinger Bands Consolidation Strategy
https://www.tradingview.com/script/UIdThJsJ-KL-Bollinger-Bands-Consolidation-Strategy/
DojiEmoji
https://www.tradingview.com/u/DojiEmoji/
169
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© DojiEmoji // //@version=4 strategy("[KL] BB Consolidation Strategy",overlay=true,pyramiding=1) // Timeframe { backtest_timeframe_start = input(defval = timestamp("01 Apr 2016 13:30 +0000"), title = "Backtest Start Time", type = input.time) USE_ENDTIME = input(false,title="Define backtest end-time (If false, will test up to most recent candle)") backtest_timeframe_end = input(defval = timestamp("19 Apr 2021 19:30 +0000"), title = "Backtest End Time (if checked above)", type = input.time) within_timeframe = time >= backtest_timeframe_start and (time <= backtest_timeframe_end or not USE_ENDTIME) // } // Bollinger bands (sdv=2, len=20) { BOLL_length = 20, BOLL_src = close, SMA20 = sma(BOLL_src, BOLL_length), BOLL_sDEV_x2 = 2 * stdev(BOLL_src, BOLL_length) BOLL_upper = SMA20 + BOLL_sDEV_x2, BOLL_lower = SMA20 - BOLL_sDEV_x2 plot(SMA20, "Basis", color=#872323, offset = 0) BOLL_p1 = plot(BOLL_upper, "BOLL Upper", color=color.navy, offset = 0, transp=50) BOLL_p2 = plot(BOLL_lower, "BOLL Lower", color=color.navy, offset = 0, transp=50) fill(BOLL_p1, BOLL_p2, title = "Background", color=#198787, transp=85) // } // Volatility Indicators { ATR_x2 = atr(BOLL_length) * 2 // multiplier aligns with BOLL avg_atr = sma(ATR_x2, input(1,title="No. of candles to lookback when determining ATR is decreasing")) plot(SMA20+ATR_x2, "SMA20 + ATR_x2", color=color.gray, offset = 0, transp=50) plot(SMA20-ATR_x2, "SMA20 - ATR_x2", color=color.gray, offset = 0, transp=50) plotchar(ATR_x2, "ATR_x2", "", location = location.bottom) //} // Trailing stop loss { var entry_price = float(0), var stop_loss_price = float(0), trail_profit_line_color = color.green var trailing_SL_buffer = float(0) var risk_value = trailing_SL_buffer //declared separately; trailing_SL_buffer may be tightened subsequently UPDATE_ATR_LEN = input(true, title="Update the size of stoploss after entry") if UPDATE_ATR_LEN and strategy.position_size > 0 and close < open trailing_SL_buffer := ATR_x2 TSL_source = input(title="Source of TSL", defval="low", options=["close","low","middle of both"]) get_TSL_src() => result = float(-1) case = TSL_source if case == "close" result := close else if case == "low" result := low else if case == "middle of both" result := avg(low, close) if strategy.position_size == 0 or not within_timeframe trail_profit_line_color := color.black // make TSL line less visible stop_loss_price := get_TSL_src() - ATR_x2 // " else if strategy.position_size > 0 stop_loss_price := max(stop_loss_price, get_TSL_src() - trailing_SL_buffer) if strategy.position_size > 0 and stop_loss_price > stop_loss_price[1] alert("Stop loss limit raised", alert.freq_once_per_bar) // } end of Trailing stop loss //Buy setup - Long positions { is_squeezing = ATR_x2 > BOLL_sDEV_x2 if is_squeezing and within_timeframe and not is_squeezing[1] alert("BOLL bands are squeezing", alert.freq_once_per_bar) else if not is_squeezing and within_timeframe and is_squeezing[1] alert("BOLL bands stopped squeezing", alert.freq_once_per_bar) ema_trend = ema(close, 20) VERBOSE = input(true, title="Show text descriptions of buy/sell orders") concat(a, b) => concat = " " if VERBOSE concat := a if a != "" concat := concat + ", " concat := concat + b concat // } end of Buy setup - Long positions // Sell setup - Long position { REWARD_RATIO_EXIT = input(3, title="Reward ratio for exit (if selected above)") IGNORE_EXIT_CONSOL = input(true,title="Ignore sell signals during consolidation (unless hitting stop loss)") bearish_candle1 = (close - open)/(high - low) < -0.5 and high > max(close[1],open[1]) and abs(open-close) > BOLL_sDEV_x2/2 gapped_down = high < low[1] and close < open is_bearish = bearish_candle1 or gapped_down reward_met = close >= (entry_price + (REWARD_RATIO_EXIT * risk_value)) rsi10 = rsi(close, 10), rsi14 = rsi(close, 14) overbought = rsi14 > 70 and rsi10 > rsi14 EXIT_OVERBOUGHT = input(false,title="Exit position when overbought") TIGHTEN_TSL_BEARISH = input(true,title="Tighten TSL instead of exiting when candle is bearish") // } end of Sell setup - Long position // MAIN: if within_timeframe entry_msg = "" exit_msg = "" // ENTRY confirm_entry = false conf_count = 0 if avg_atr <= avg_atr[1] // "decreased volatility" conf_count := conf_count + 1 if open < close // "Green candlestick" conf_count := conf_count + 1 entry_msg := concat(entry_msg, "green") else if abs(close-open)/abs(high-low) < 0.1 //"Doji" conf_count := conf_count + 1 entry_msg := concat(entry_msg, "doji") if ema_trend > ema_trend[1] //"Upward EMA20" conf_count := conf_count + 1 entry_msg := concat(entry_msg, "+ve ema20") confirm_entry := conf_count >= 2 if is_squeezing and confirm_entry and strategy.position_size == 0 strategy.entry("Long",strategy.long, comment=entry_msg) entry_price := close trailing_SL_buffer := ATR_x2 risk_value := trailing_SL_buffer // may be adjusted during holding-period stop_loss_price := get_TSL_src() - trailing_SL_buffer // EXIT if strategy.position_size > 0 SL_hit = low < stop_loss_price bExit = false if close > entry_price and SL_hit exit_msg := concat(exit_msg, "profit [TSL]") bExit := true else if close <= entry_price and SL_hit exit_msg := concat(exit_msg, "stop loss") bExit := true else if (not IGNORE_EXIT_CONSOL or not is_squeezing) and is_bearish and not TIGHTEN_TSL_BEARISH exit_msg := concat(exit_msg, "bearish") bExit := true if reward_met exit_msg := concat(exit_msg, "reward met") bExit := true else if overbought exit_msg := concat(exit_msg, "overbought") bExit := EXIT_OVERBOUGHT if TIGHTEN_TSL_BEARISH and is_bearish stop_loss_price := max(low-(low-stop_loss_price)*0.9,stop_loss_price) else if overbought and not EXIT_OVERBOUGHT stop_loss_price := max(low-(low-stop_loss_price)*0.7,stop_loss_price) strategy.close("Long", when=bExit, comment=exit_msg) // plot TSL line plot(stop_loss_price, color=trail_profit_line_color) // CLEAN UP: if strategy.position_size == 0 and not is_squeezing entry_price := 0 trailing_SL_buffer := float(0) stop_loss_price := float(0) risk_value := 0
72s Strat: Backtesting Adaptive HMA+ pt.1
https://www.tradingview.com/script/FrjeeWdl-72s-Strat-Backtesting-Adaptive-HMA-pt-1/
io72signals
https://www.tradingview.com/u/io72signals/
3,388
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/ // 2020 Β© io72signals / Antorio Bergasdito //@version=4 strategy("72s Strategy: Adaptive Hull Moving Average+ pt.1", shorttitle="72s Strat: Adaptive HMA+ pt.1", overlay=true, pyramiding=1, initial_capital=1000, commission_type=strategy.commission.cash_per_order, commission_value=.5, slippage=3, max_bars_back=1000) atrBase = atr(21) src = close adaptPct = 0.03141 //{ INPUTS orderSize = input(0.1, title="Order Size (in Lot)", step=.1, group="ORDERS") minProfit = input(1, step=.1, title="Base Minimum Profit before exit (ATR)", group="ORDERS") * atrBase takeProfit = input(3, step=.1, title="Default Target Profit (ATR)", group="ORDERS") * atrBase useSL = input(true, title="Use StopLoss", group="ORDERS") SLInput = input("Half Distance Zone", title="Base StopLoss Point", options=["One Distance Zone", "Half Distance Zone", "Last High/Low", "ATR Only"], group="ORDERS") maxSL = input(4.5, step=.1, title="Maximum StopLoss (ATR)", group="ORDERS") * atrBase doubleUp = input(false, "Activate 2nd order with xHMA+ exits", group="ORDERS") //If enable, set pyramiding to at least: 2 minLength = input(172, title="Minimum:", group="Adaptive HMA+ Period", inline="HMA+") maxLength = input(233, title="Maximum:", group="Adaptive HMA+ Period", inline="HMA+") flat = input(17, title="Flat Market when xHMA's slope below", group="Market Movement") atrFast = input(14, "Charged if ATR", group="Market Movement", inline="volality", minval=2, maxval=34) atrSlow = input(46, ">= ATR", group="Market Movement", inline="volality", minval=21, maxval=120) showZone = input(false, title="Show Adaptive HMA+ Distance Zone", group="DISTANCE ZONE") mult = input(2.7, title="Distance (Envelope) Multiplier", step=.1, group="DISTANCE ZONE") minorMin = input(89, title="Minimum:", group="Minor Adaptive HMA+ Period", inline="mHMA+") minorMax = input(121, title="Maximum:", group="Minor Adaptive HMA+ Period", inline="mHMA+") showMA = input(true, title="Show MA?", group="OTHER") useBg = input(true, title="Background color to differentiate movement", group="OTHER") rsi = rsi(input(close,"RSI Source", inline="RSI", group="OTHER"), input(14, "RSI Length", inline="RSI", group="OTHER")) //}...inputs //{ ADAPTIVE HMA+ //Condition to adapt to: charged = atr(atrFast) > atr(atrSlow) //<--Volatility Meter. Change it to whatever match your strat/pair/tf. //Dynamics var float dynamicLength = avg(minLength,maxLength) var float minorLength = avg(minorMin,minorMax) dynamicLength := iff(charged, max(minLength, dynamicLength * (1 - adaptPct)), min(maxLength, dynamicLength * (1 + adaptPct))) minorLength := iff(charged, max(minorMin, minorLength * (1 - adaptPct)), min(minorMax, minorLength * (1 + adaptPct))) //Slope calculation to determine whether market is in trend, or in consolidation or choppy, or might about to change current trend pi = atan(1) * 4 highestHigh = highest(34), lowestLow = lowest(34) slope_range = 25 / (highestHigh - lowestLow) * lowestLow calcslope(_ma)=> dt = (_ma[2] - _ma) / src * slope_range c = sqrt(1 + dt * dt) xAngle = round(180 * acos(1 / c) / pi) maAngle = iff(dt > 0, -xAngle, xAngle) maAngle //MA coloring+ to mark market dynamics dynColor(_ma,_col1a,_col1b,_col2a,_col2b,_col0) => slope = calcslope(_ma) slope >= flat ? charged? _col1a : _col1b : slope < flat and slope > -flat ? _col0 : slope <= -flat ? charged? _col2a : _col2b : _col0 //Adaptive HMA xhma(_src,_length) => _return = wma(2 * wma(_src, _length / 2) - wma(_src, _length), floor(sqrt(_length))) dynamicHMA = xhma(src,int(dynamicLength)) //<--Batman - Our main xHMA+ minorHMA = xhma(src,int(minorLength)) //<--Robin - Faster minor xHMA+ (Optional). Can be use to assist for // faster entry, slower exit point, or pullbacks info too. _slope = calcslope(dynamicHMA) plotchar(_slope, "slope is:", "", location.top) //<--Output current slope to Data Window, for our reference when optimizing Strategy //Envelope the main DynamicHMA with ATR band, just one way to approximate current price distance to MA. Other usages/methods may vary. upperTL = dynamicHMA + mult * atr(40) , lowerTL = dynamicHMA - mult * atr(40) //<--Half distance zone topTL = dynamicHMA + (mult*2) * atr(40) , botTL = dynamicHMA - (mult*2) * atr(40) //<--One distance zone stopupperTL = dynamicHMA + (mult/2) * atr(40), stoplowerTL = dynamicHMA - (mult/2) * atr(40) //<--Half of the half. If need ie. tighter SL or trailing //Plotting Distance Zone plot(showZone?upperTL:na, color=color.green, transp=72) plot(showZone?lowerTL:na, color=color.red, transp=72) plot(showZone?topTL:na, color=color.gray, transp=72) plot(showZone?botTL:na, color=color.gray, transp=72) sutl = plot(showZone?stopupperTL:na, color=color.white, transp=100) sltl = plot(showZone?stoplowerTL:na, color=color.white, transp=100) colZone = showZone? color.purple:color.new(color.white,100) fill(sutl, sltl, color=colZone, transp=90) plot(showMA?dynamicHMA:na, "Adaptive HMA+", dynColor(dynamicHMA, #6fbf73, #c0f5ae, #eb4d5c, #f2b1d4, color.yellow), 3) plot(showMA?minorHMA:na, "minor HMA+", dynColor(minorHMA, #6fbf73, #c0f5ae, #eb4d5c, #f2b1d4, color.yellow), 1) //Backgroud color to differentiate market condition notgreat = _slope < flat and _slope > -flat bgcolor(useBg? charged? na : #afb4b9 : na) //EMA 200. (Not being use in here. But since they've been a BFF since long, thought I'm just gonna put it here..) emma200 = ema(close,200) //, plot(emma200) //}...adaptive HMA+ //{ SIGNALS //Base; When HMA+ turn to a darker color and market is out from low volatility upSig = _slope >= flat and charged dnSig = _slope <= -flat and charged //Default buy/sell, when market switchs to the above base condition, and typical price is still in tolerated distance, and RSI is on the right side. buy = upSig and not upSig[1] and close>dynamicHMA and low<=upperTL and (rsi>51 and rsi<=70) sell = dnSig and not dnSig[1] and close<dynamicHMA and high>=lowerTL and (rsi<49 and rsi>=30) //Alternative buy/sell, when price is a bit far from MA, and RSI is still on the same side but already on oversold/overbought (relatively). overBuy = upSig and not upSig[1] and rsi>70 and close>dynamicHMA and hl2>upperTL and minorHMA>dynamicHMA overSell= dnSig and not dnSig[1] and rsi<30 and close<dynamicHMA and hl2<lowerTL and minorHMA<dynamicHMA //Alternative additional buy/sell with different exits at Robin's. secondBuy = (buy or overBuy) and rsi[1]<rsi secondSell = (sell or overSell) and rsi[1]>rsi //Plot 'em up atrPos = 0.2 * atr(5) plotshape(buy? dynamicHMA-atrPos:na,color=color.green, location=location.absolute, style=shape.labelup, text="buy", textcolor=color.white, size = size.small) plotshape(sell? dynamicHMA+atrPos:na, color=color.red, location=location.absolute, style=shape.labeldown, text="sell", textcolor=color.white, size = size.small) plotshape(overBuy? dynamicHMA-atrPos:na,color=color.green, location=location.absolute, style=shape.labelup, text="overBuy", textcolor=color.white, size = size.small) plotshape(overSell?dynamicHMA+atrPos:na, color=color.red, location=location.absolute, style=shape.labeldown, text="overSell", textcolor=color.white, size = size.small) plotshape(doubleUp and secondBuy? dynamicHMA-atrPos*8:na,color=color.green, location=location.absolute, style=shape.labelup, text="+buy", textcolor=color.white, size = size.small) plotshape(doubleUp and secondSell?dynamicHMA+atrPos*8:na, color=color.red, location=location.absolute, style=shape.labeldown, text="+sell", textcolor=color.white, size = size.small) //Alert if buy alert("Buy signal at "+tostring(close), alert.freq_once_per_bar_close) if sell alert("Sell signal at "+tostring(close), alert.freq_once_per_bar_close) if overBuy alert("OverBuy signal at "+tostring(close), alert.freq_once_per_bar_close) if overSell alert("OverSell signal at "+tostring(close), alert.freq_once_per_bar_close) if doubleUp and secondBuy alert("2nd Buy signal at "+tostring(close), alert.freq_once_per_bar_close) if doubleUp and secondSell alert("2nd Sell signal at "+tostring(close), alert.freq_once_per_bar_close) //}...signals //{ ORDERS //(I use Lot just because it's how I usually trade, matches my flow when thinking/planning. Change the "qty" in "strategy.entry()" below to use other UOM.) //Forex pairs are 100,000 units per 1 lot. Units per 1 lot vary on non-forex pairs, please check with your broker and change accordingly if necessary. //(ie: In MT4 and MT5 right click a symbol and then click Specification. The Contract Size field tells how many units are in one lot.) standard1LotUnits = syminfo.type == "forex" ? 100000 : syminfo.ticker == "XAUUSD" ? 100 : syminfo.ticker == "XAGUSD" ? 5000 : syminfo.type == "crypto" ? 1 : 1000 lotSize = standard1LotUnits * orderSize pip() => syminfo.mintick * (syminfo.type == "forex" ? 10 : 1) //{ StopLoss SLHighMax = high + maxSL, SLLowMax = low - maxSL //<--Maximum StopLoss. If a chosen SL-point from input above happen // to be outside this max point, then this one will be use as SL. lastHigh = highest(high, 48) + (5 * pip()) //<--Last High/Low. If use as SL-point, adjust the lookback length lastLow = lowest(low, 48) - (5 * pip()) // according to where your comfort lies (and position-size). //Delivering SL from inputs SLBuy = SLInput == "One Distance Zone"? botTL : SLInput == "Half Distance Zone"? lowerTL : SLInput == "Last High/Low"? lastLow : SLInput == "ATR Only"? SLLowMax : SLLowMax SLSell= SLInput == "One Distance Zone"? topTL : SLInput == "Half Distance Zone"? upperTL : SLInput == "Last High/Low"? lastHigh: SLInput == "ATR Only"? SLHighMax: SLHighMax //}---stopLoss // float entryPrice = na, float normOrder = 0, float riskOrder = 0 float buyTP = na, float sellTP = na, float buySL = na, float sellSL = na entryPrice := nz(entryPrice[1]), normOrder := nz(normOrder[1]), riskOrder := nz(riskOrder[1]) buyTP:=nz(buyTP[1]), sellTP:=nz(sellTP[1]), buySL:=nz(buySL[1]), sellSL :=nz(sellSL[1]) //This part will also make your TP/SL change dynamically if there's a new signal while you have an open position. //If you want to fire this TP/SL only in a new position, then add "strategy.position_size == 0" if (buy or sell or overBuy or overSell) //and strategy.position_size == 0 entryPrice := close if buy or sell and strategy.position_size == 0 normOrder := 1 if overBuy or overSell and strategy.position_size == 0 riskOrder := 1 buyTP := high + takeProfit sellTP := low - takeProfit if buy or overBuy buySL := SLLowMax<SLBuy? SLBuy:SLLowMax if sell or overSell sellSL:= SLHighMax>SLSell? SLSell:SLHighMax //Trailing Minimum-Profit. --Just a simple helper to prevent premature exit rule. Or at least to have a //change to get break-even (after commission) if market turns its back on us, before heading to stoploss area. minBuyProfit = strategy.position_avg_price + minProfit minSellProfit = strategy.position_avg_price - minProfit //{ Exit Points //TP/SL Exits stopLossBuy = useSL? low <=buySL : na stopLossSell = useSL? high>=sellSL: na takeProfitBuy = high>= buyTP takeProfitSell = low <= sellTP //Simplified RSI Exits RSIexitBuy = crossunder(rsi,70) or rsi<50 RSIexitSell = crossover(rsi,30) or rsi>50 //Exit Conditions exitBuy = ( close >= minBuyProfit and (RSIexitBuy or crossunder(close,dynamicHMA)) ) or stopLossBuy or takeProfitBuy exitSell = ( close <= minSellProfit and (RSIexitSell or crossover(close,dynamicHMA) ) ) or stopLossSell or takeProfitSell exitoverBuy = ( close >= minBuyProfit and (crossunder(rsi,45) or (open<stopupperTL and hl2<stopupperTL)) ) or (open<dynamicHMA and rsi<60) or stopLossBuy or takeProfitBuy exitoverSell = ( close <= minSellProfit and (crossover(rsi,55) or (open>stoplowerTL and hl2>stoplowerTL)) ) or (open>dynamicHMA and rsi>40) or stopLossSell or takeProfitSell //Alternative 2nd Exits at Robin's (or SL) exitSecondBuy = (close >= minBuyProfit and crossunder(close, minorHMA)) or stopLossBuy exitSecondSell = (close <= minSellProfit and crossover(close, minorHMA)) or stopLossSell //Plotting and Alert for Exits inBuyExit = strategy.position_size > 0 and ((normOrder == 1 and exitBuy) or (riskOrder == 1 and exitoverBuy)) inSellExit = strategy.position_size < 0 and ((normOrder == 1 and exitSell) or (riskOrder == 1 and exitoverSell)) in2ndBuyExit = strategy.position_size > 0 and (doubleUp and exitSecondBuy) in2ndSellExit= strategy.position_size < 0 and (doubleUp and exitSecondSell) if inBuyExit or inSellExit if normOrder == 1 and exitBuy normOrder := 0, alert("Close Buy Position/s at "+tostring(close), alert.freq_once_per_bar_close) if normOrder == 1 and exitSell normOrder := 0, alert("Close Sell Position/s at "+tostring(close), alert.freq_once_per_bar_close) if riskOrder == 1 and exitoverBuy riskOrder := 0, alert("Close overBuy Position/s at "+tostring(close), alert.freq_once_per_bar_close) if riskOrder == 1 and exitoverSell riskOrder := 0, alert("Close overSell Position/s at "+tostring(close), alert.freq_once_per_bar_close) if in2ndBuyExit alert("Close 2nd Buy Position/s at "+tostring(close), alert.freq_once_per_bar_close) if in2ndSellExit alert("Close 2nd Sell Position/s at "+tostring(close), alert.freq_once_per_bar_close) plotchar(inBuyExit, color=color.green, location=location.abovebar, char="ⓧ", size=size.tiny) plotchar(inSellExit, color=color.red, location=location.belowbar, char="ⓧ", size=size.tiny) plotchar(in2ndBuyExit, color=color.teal, location=location.abovebar, char="ⓧ", size=size.tiny) plotchar(in2ndSellExit, color=color.maroon, location=location.belowbar, char="ⓧ", size=size.tiny) //}---exit points //{ Actions //ENTRIES strategy.entry("buy", strategy.long, qty=lotSize, when=buy ) strategy.entry("sell", strategy.short, qty=lotSize, when=sell) strategy.entry("overBuy", strategy.long, qty=lotSize, when=overBuy ) strategy.entry("overSell", strategy.short, qty=lotSize, when=overSell) if doubleUp strategy.entry("2ndBuy", strategy.long, qty=lotSize, when=secondBuy ) strategy.entry("2ndSell", strategy.short, qty=lotSize, when=secondSell) //EXITS //We use just "strategy.close" because we already set limit conditions above for SL and TP, fires at candle close. If you want to //separate exit data or exit at the exact SL/TP you can add such as: strategy.exit("exitbuy", from_entry="buy", stop=buySL, limit=buyTP) //accordingly. And delete stopLossBuy, stopLossSell, takeProfitBuy, takeProfitSell definitions from above. strategy.close("buy", when=exitBuy , comment="close buy") strategy.close("sell", when=exitSell, comment="close sell") strategy.close("overBuy", when=exitoverBuy , comment="close overBuy") strategy.close("overSell", when=exitoverSell, comment="close overSell") if doubleUp strategy.close("2ndBuy", when=exitSecondBuy , comment="close 2nd Buy") strategy.close("2ndSell", when=exitSecondSell, comment="close 2nd Sell") //}---actions orderCol = strategy.position_size>0? color.green : strategy.position_size<0? color.red : na // plot(strategy.position_size>0? minBuyProfit : strategy.position_size<0? minSellProfit : na, color=orderCol, style=plot.style_linebr, linewidth=1, title="Minimum Profit") plot(strategy.position_size != 0? entryPrice:na, style=plot.style_cross, transp=50) plot(useSL and strategy.position_size>0? buySL : useSL and strategy.position_size<0? sellSL : na, color=color.red, style=plot.style_cross, linewidth=1, title="Stop Loss", transp=50) plot(strategy.position_size>0? buyTP : strategy.position_size<0? sellTP : na, color=color.green, style=plot.style_cross, linewidth=1, title="Take Profit", transp=50) //}...orders //{------------------------------------------------------------------------ //Below is just fancy stuff approximating gain in pips. You probably don't need this. //(Also I'm not too sure this is the right way calculating pip gain in pine. If somebody knows how, kindly correct me please) mUnit = lotSize*pip() ppip = round((strategy.grossprofit-strategy.grossprofit[1]) / syminfo.pointvalue/mUnit,1) lpip = round((strategy.grossloss-strategy.grossloss[1]) / syminfo.pointvalue/mUnit,1) pipGain = round((strategy.grossprofit/syminfo.pointvalue)/mUnit) pipLoss = round((strategy.grossloss/syminfo.pointvalue)/mUnit) avg_ppip = round((pipGain/strategy.wintrades),1) pctProfit = round(strategy.wintrades/strategy.closedtrades * 100, 2) maxDD = ceil(strategy.max_drawdown/ syminfo.pointvalue/mUnit) //check if our margin can handle DD's pips*orderSize var txt2 = "" txt = "Total trades: "+ tostring(strategy.closedtrades)+"\n("+tostring(pctProfit)+"%) Win: "+tostring(strategy.wintrades)+" / Loss: "+tostring(strategy.losstrades)+ "\nAverage win pips per trade: "+ tostring(avg_ppip) + " pips\n\nApproximate (*give n take)\nTotal Pip Gain: "+ tostring(pipGain) +" pips"+ "\nTotal Pip Loss: "+tostring(pipLoss)+ " pips"+"\n\nMax Drawdown so far: "+tostring(maxDD)+" pips" if strategy.wintrades>strategy.wintrades[1] txt2 := "\n\nLast closed trade: Bagged "+tostring(ppip)+" pips πŸ‘»" if strategy.losstrades>strategy.losstrades[1] txt2 := "\n\nLast closed trade: Blew "+tostring(lpip)+" pips πŸ˜ͺ" txt += txt2 label pvtLabel = label.new(time, lowestLow, text=txt, color=color.new(color.white,100), xloc=xloc.bar_time, style=label.style_label_left, textcolor=color.gray, textalign=text.align_left) label.set_x(pvtLabel, label.get_x(pvtLabel) + ((time-time[1]) * 21)) label.delete(pvtLabel[1]) //}
T3 crossover strategy
https://www.tradingview.com/script/0DeI9Z4m-T3-crossover-strategy/
DynamicSignalLab
https://www.tradingview.com/u/DynamicSignalLab/
30
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/ // Β© DynamicSignalLab //@version=4 strategy(title="T3 crossover strategy", shorttitle="T3 strategy", overlay=true) length = input(title="Length", type=input.integer, defval=5) factor = input(title="Factor", type=input.float, minval=0, maxval=1, defval=0.7) highlightMovements = input(title="Highlight Movements ?", type=input.bool, defval=true) src = input(title="Source", type=input.source, defval=close) gd(src, length) => ema(src, length) * (1 + factor) - ema(ema(src, length), length) * factor t3 = gd(gd(gd(src, length), length), length) t3Color = highlightMovements ? (t3 > t3[1] ? color.green : color.red) : #6d1e7f plot(t3, title="T3", linewidth=2, color=t3Color, transp=0) longCondition = crossover(t3, t3[2]) if (longCondition) strategy.entry("long", strategy.long) shortCondition = crossunder(t3, t3[2]) if (shortCondition) strategy.entry("short", strategy.short)
4X EMA and volume strategy
https://www.tradingview.com/script/j6jo4PEh-4X-EMA-and-volume-strategy/
SoftKill21
https://www.tradingview.com/u/SoftKill21/
133
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/ // Β© SoftKill21 //@version=4 strategy("4x ema + volume", overlay=true,initial_capital = 1000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent , commission_value=0.1 ) //ema x 4 ema1l=input(13) ema2l=input(21) ema3l=input(50) ema4l=input(180) ema1=ema(close,ema1l) ema2=ema(close,ema2l) ema3=ema(close,ema3l) ema4=ema(close,ema4l) long1 = close > ema1 and ema1 > ema2 and ema2> ema3 and ema3 > ema4 long2 = crossover(ema1,ema2) and crossover(ema1,ema3) short1 = close < ema1 and ema1 < ema2 and ema2< ema3 and ema3 < ema4 short2= crossunder(ema1,ema2) and crossunder(ema1,ema3) //eom length = input(14, minval=1) div = input(10000, title="Divisor", minval=1) eom = sma(div * change(hl2) * (high - low) / volume, length) option1=input(true) option2=input(false) if(option1) strategy.entry("long",1,when=long1 and eom>0) strategy.close("long",when=short1 and eom<0) if(option2) strategy.entry("long",1,when=long2 and eom>0) strategy.close("long",when=short2 and eom<0)
ATR with EOM and VORTEX
https://www.tradingview.com/script/9OKaWbM4-ATR-with-EOM-and-VORTEX/
SoftKill21
https://www.tradingview.com/u/SoftKill21/
166
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/ // Β© SoftKill21 //@version=4 strategy("atr+eom+vortex strat", overlay=true,initial_capital = 1000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent , commission_value=0.01 ) //atr and ema atr_lenght=input(10) atrvalue = atr(atr_lenght) //plot(atrvalue) ema_atr_length=input(5) ema_atr = ema(atrvalue,ema_atr_length) //plot(ema_atr,color=color.white) //EOM and ema lengthEOM = input(10, minval=1) div = 10//input(10000, title="Divisor", minval=1) eom = sma(div * change(hl2) * (high - low) / volume, lengthEOM) // + - 0 long/short //VORTEX period_ = input(10, title="Length", minval=2) VMP = sum( abs( high - low[1]), period_ ) VMM = sum( abs( low - high[1]), period_ ) STR = sum( atr(1), period_ ) VIP = VMP / STR VIM = VMM / STR avg_vortex=(VIP+VIM)/2 //plot(avg_vortex) long= atrvalue > ema_atr and eom > 0 and avg_vortex>1 short=atrvalue < ema_atr and eom < 0 and avg_vortex<1 strategy.entry("long",1,when=long) //strategy.entry("short",0,when=short) strategy.close("long",when=short)
ATR trailing Stop Loss tight to slack [Takazudo]
https://www.tradingview.com/script/uPqTfcHs-ATR-trailing-Stop-Loss-tight-to-slack-Takazudo/
Takazudo
https://www.tradingview.com/u/Takazudo/
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/ //@version=5 //@author=Takazudo strategy("ATR trailing SL tight to slack [Takazudo]", overlay=true, default_qty_type=strategy.fixed, initial_capital=0, currency=currency.USD) posSize = strategy.position_size hasNoPos = posSize == 0 hasLongPos = posSize > 0 hasShortPos = posSize < 0 //============================================================================ // consts, inputs //============================================================================ // colors var COLOR_SL_LINE = color.new(#e0f64d, 20) var COLOR_SL_LINE_THIN = color.new(#e0f64d, 90) var COLOR_ENTRY_BAND = color.new(#43A6F5, 30) var COLOR_TRANSPARENT = color.new(#000000, 100) // Entry strategy _g1 = 'Entry strategy' var config_entryBandBars = input.int(defval = 100, title = "Entry band bar count", minval=1, group=_g1) _g2 = 'ATR SL' var config_slAtr_length = input.int(24, title = "Trailing stop ATR Length", group=_g2) var config_slAtr_multi1 = input.float(1.5, title = "Trailing stop ATR Multiple on tight", step=0.1, group=_g2) var config_slAtr_multi2 = input.float(4, title = "Trailing stop ATR Multiple on slack", step=0.1, group=_g2) _g3 = 'Backtesting range' var config_fromYear = input.int(defval = 2016, title = "From Year", minval = 1970, group=_g3) var config_fromMonth = input.int(defval = 1, title = "From Month", minval = 1, maxval = 12, group=_g3) var config_fromDay = input.int(defval = 1, title = "From Day", minval = 1, maxval = 31, group=_g3) var config_toYear = input.int(defval = 2021, title = "To Year", minval = 1970, group=_g3) var config_toMonth = input.int(defval = 4, title = "To Month", minval = 1, maxval = 12, group=_g3) var config_toDay = input.int(defval = 5, title = "To Day", minval = 1, maxval = 31, group=_g3) //============================================================================ // Range Edge calculation //============================================================================ f_calcEntryBand_high() => _highest = math.max(open[3], close[3]) for i = 4 to (config_entryBandBars - 1) _highest := math.max(_highest, open[i], close[i]) _highest f_calcEntryBand_low() => _lowest = math.min(open[3], close[3]) for i = 4 to (config_entryBandBars - 1) _lowest := math.min(_lowest, open[i], close[i]) _lowest entryBand_high = f_calcEntryBand_high() entryBand_low = f_calcEntryBand_low() entryBand_height = entryBand_high - entryBand_low plot(entryBand_high, color=COLOR_ENTRY_BAND, linewidth=1) plot(entryBand_low, color=COLOR_ENTRY_BAND, linewidth=1) rangeBreakDetected_long = entryBand_high < close rangeBreakDetected_short = entryBand_low > close shouldMakeEntryLong = (strategy.position_size == 0) and rangeBreakDetected_long shouldMakeEntryShort = (strategy.position_size == 0) and rangeBreakDetected_short //============================================================================ // ATR based stuff //============================================================================ sl_atrHeight_tight = ta.atr(config_slAtr_length) * config_slAtr_multi1 sl_atrHeight_slack = ta.atr(config_slAtr_length) * config_slAtr_multi2 sl_tight_bull = math.min(open, close) - sl_atrHeight_tight sl_tight_bear = math.max(open, close) + sl_atrHeight_tight sl_slack_bull = math.min(open, close) - sl_atrHeight_slack sl_slack_bear = math.max(open, close) + sl_atrHeight_slack plot(sl_tight_bull, color=COLOR_SL_LINE_THIN, linewidth=1) plot(sl_tight_bear, color=COLOR_SL_LINE_THIN, linewidth=1) plot(sl_slack_bull, color=COLOR_SL_LINE_THIN, linewidth=1) plot(sl_slack_bear, color=COLOR_SL_LINE_THIN, linewidth=1) //============================================================================ // Sl //============================================================================ var trailingSl_long = hl2 var trailingSl_short = hl2 trailingSl_long := if hasLongPos math.max(trailingSl_long, sl_slack_bull) else sl_tight_bull trailingSl_short := if hasShortPos math.min(trailingSl_short, sl_slack_bear) else sl_tight_bear color_sl_long = hasLongPos ? COLOR_SL_LINE : COLOR_TRANSPARENT color_sl_short = hasShortPos ? COLOR_SL_LINE : COLOR_TRANSPARENT plot(trailingSl_long, color=color_sl_long, linewidth=2) plot(trailingSl_short, color=color_sl_short, linewidth=2) //============================================================================ // make entries //============================================================================ // Calculate start/end date and time condition startDate = timestamp(config_fromYear, config_fromMonth, config_fromDay, 00, 00) finishDate = timestamp(config_toYear, config_toMonth, config_toDay, 00, 00) if (time >= startDate and time <= finishDate) if shouldMakeEntryLong strategy.entry(id="Long", direction=strategy.long, stop=close, qty=1000) if shouldMakeEntryShort strategy.entry(id="Short", direction=strategy.short, stop=close, qty=1000) strategy.exit('Long-SL/TP', 'Long', stop=trailingSl_long) strategy.exit('Short-SL/TP', 'Short', stop=trailingSl_short)
RSI+PA+DCA Strategy
https://www.tradingview.com/script/tPeoGM3W-RSI-PA-DCA-Strategy/
A3Sh
https://www.tradingview.com/u/A3Sh/
271
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ //@version=4 // Β© A3Sh // RSI Strategy that buys the dips, works with Price Averaging and has a Dollar Cost Average option. // When the price drops below specified percentages of the price (6 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. // The idea is to lower the average position price to a point that when the market rises, the current price crosses over the average position price. // When the current price crosses the average position size and reaches the specified take profit, all entries are closed at once. // In case the market drops significantly, there is an option to activate DCA to lower the average price further. // RSI code 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 // 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/ // Buy every week code based on the following question in Stack Overflow // https://stackoverflow.com/questions/59870411/in-pine-script-how-can-you-do-something-once-per-day-or-keep-track-if-somethin strategy(title = "RSI+PA+DCA", 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(15, title = "Portfolio %", type = input.float, step = 0.1, minval = 0.1, maxval = 100) q = (strategy.equity / 100 * port) / open // Long position entry layers. Percentage from the entry price of the the first long PositionInputs = input("++++", title = "+++++ Long Positions VA Layers +++++") ps2 = input(2, title = "2nd Long Entry %", step = 0.1) ps3 = input(3, title = "3rd Long Entry %", step = 0.1) ps4 = input(5, title = "4th Long Entry %", step = 0.1) ps5 = input(10, title = "5th Long Entry %", step = 0.1) ps6 = input(16, title = "6th Long Entry %", step = 0.1) // Calculate Moving Averages maInput = input("++++", title = "+++++ Moving Average Filter +++++") plotMA = input(title = "Plot Moving Average", defval = false) movingaverage_signal = sma(close, input(100)) plot (plotMA ? movingaverage_signal : na, color = color.green) // RSI inputs and calculations rsiInput = input( "++++", title = "+++++ RSI Inputs +++++" ) length = input( 14 ) overSold = input( 30, title = "oversold, entry trigger long position" ) overBought = input( 70, title = "overbought, has no specific function") price = close vrsi = rsi(price, length) // Long trigger (co) co = crossover(vrsi, overSold) and close < movingaverage_signal // Take profit takeprofit = input("++++", title = "+++++ Take Profit +++++") ProfitTarget_Percent = input(5, title = "Take Profit % (Per Position)") ProfitTarget_Percent_All = input(7, title = "Take Profit % (Exit All, above % of price average, white line)") // Store values to create and plot the different PA layers long1 = valuewhen(co, close, 0) long2 = valuewhen(co, close - (close / 100 * ps2), 0) long3 = valuewhen(co, close - (close / 100 * ps3), 0) long4 = valuewhen(co, close - (close / 100 * ps4), 0) long5 = valuewhen(co, close - (close / 100 * ps5), 0) long6 = valuewhen(co, close - (close / 100 * ps6), 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] 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 position average price plot (strategy.position_avg_price, title = "Average price", style = plot.style_linebr, color = color.white, linewidth = 2) // Take profit and exit all on take profit above position average price + plot a red take profit line tpv = strategy.position_avg_price + (strategy.position_avg_price / 100 * ProfitTarget_Percent_All) plot (tpv, title = "Take Profit All", style = plot.style_linebr, color = color.red, linewidth = 1) tpl1 = close < tpv ? eps1 + close * (ProfitTarget_Percent / 100) : tpv tpl2 = close < tpv ? eps2 + close * (ProfitTarget_Percent / 100) : tpv tpl3 = close < tpv ? eps3 + close * (ProfitTarget_Percent / 100) : tpv tpl4 = close < tpv ? eps4 + close * (ProfitTarget_Percent / 100) : tpv tpl5 = close < tpv ? eps5 + close * (ProfitTarget_Percent / 100) : tpv tpl6 = close < tpv ? eps6 + close * (ProfitTarget_Percent / 100) : tpv // Open DCA order once at the start of the week dcaWeek = input("++++", title = "+++++ Open DCA order once every week +++++") newWeek = change(time("W")) dcatime = input(title = "Buy a fixed amount every Monday", defval = false) fixedAmount = input(40, title = "Fixed amount currency for DCA orders", step = 0.1) dcaq = fixedAmount / open plotchar (dcatime ? newWeek : na, "buy at Week start", "β–Ό", location.top, size = size.tiny, color = color.white) bgcolor (dcatime and newWeek ? color.white : na, transp = 50) // Submit Entry Orders if (co and strategy.opentrades == 0) eps1 := long1 eps2 := long2 eps3 := long3 eps4 := long4 eps5 := long5 eps6 := long6 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) // Submit Weekly DCA order, only when price is below position average price and when a position is open if (dcatime and newWeek and strategy.position_size > 0 and close < strategy.position_avg_price) strategy.entry("DCA", strategy.long, dcaq) // 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 DCA", from_entry = "DCA", limit = tpv) // 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()
Scalping Dips On Trend (by Coinrule)
https://www.tradingview.com/script/iHHO0PJA-Scalping-Dips-On-Trend-by-Coinrule/
Coinrule
https://www.tradingview.com/u/Coinrule/
585
strategy
3
MPL-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=3 strategy(shorttitle='Scalping Dips On Trend',title='Scalping Dips On Trend (by Coinrule)', overlay=true, initial_capital = 1000, default_qty_type = strategy.percent_of_equity, default_qty_value = 30, commission_type=strategy.commission.percent, commission_value=0.1) //Backtest dates fromMonth = input(defval = 1, title = "From Month") fromDay = input(defval = 10, title = "From Day") fromYear = input(defval = 2020, title = "From Year") thruMonth = input(defval = 1, title = "Thru Month") thruDay = input(defval = 1, title = "Thru Day") thruYear = input(defval = 2112, title = "Thru Year") showDate = input(defval = true, title = "Show Date Range") start = timestamp(fromYear, fromMonth, fromDay, 00, 00) // backtest start window finish = timestamp(thruYear, thruMonth, thruDay, 23, 59) // backtest finish window window() => time >= start and time <= finish ? true : false // create function "within window of time" inp_lkb = input(1, title='Lookback Period') perc_change(lkb) => overall_change = ((close[0] - close[lkb]) / close[lkb]) * 100 // Call the function overall = perc_change(inp_lkb) //MA inputs and calculations MA=input(50, title='Moving Average') MAsignal = sma(close, MA) //Entry dip= -(input(2)) strategy.entry(id="long", long = true, when = overall< dip and MAsignal > close and window()) //Exit Stop_loss= ((input (10))/100) Take_profit= ((input (3))/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())
Bollinger Bands strategy with RSI and MACD v1.0
https://www.tradingview.com/script/CEzU8qc0/
juliangonzaconde
https://www.tradingview.com/u/juliangonzaconde/
438
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/ // Β© juliangonzaconde //@version=4 strategy(title="BB-strategy", calc_on_every_tick=true,max_labels_count=500, max_bars_back = 1000, overlay=true, pyramiding=5, default_qty_value=3,initial_capital=100000, currency=currency.EUR) bbSource = input(title="BB source", type=input.source, defval=close) smaLength = input(title="Bollinger Bands SMA length", type=input.integer, defval=20) stdLength = input(title="Bollinger Bands StdDev length", type=input.integer, defval=2) longTrailPerc = input(title="Trail Long Loss (%) (min: 0.0)", type=input.float, minval=0.0, step=0.1, defval=4.0) * 0.01 shortTrailPerc = input(title="Trail Short Loss (%) (min: 0.0)", type=input.float, minval=0.0, step=0.1, defval=4.0) * 0.01 maxOrders= input(title="Maximum orders (min: 1, max: 3)", type=input.integer,minval=1, maxval=3, defval=2) posSize= input(title="Position size (min: 1, max: 100)", type=input.integer, minval=1, maxval=100, defval=2) rsiChosen= input(title="Use RSI", type=input.bool, defval=false) rsiSource = input(title="RSI source", type=input.source, defval=close) rsiPeriod= input(title="RSI period", type=input.integer, minval=1, maxval=1000, defval=14) rsiBuy = input(title="RSI value for buy", type=input.integer, minval=1, maxval=99, defval=30) rsiSell = input(title="RSI value for sell", type=input.integer, minval=1, maxval=99, defval=70) macdChosen= input(title="Use MACD", type=input.bool, defval=false) macdVariation= input(title="Use MACD variation (Use MACD must be selected)", type=input.bool, defval=false) macdSource = input(title="MACD source", type=input.source, defval=close) fastLen= input(title="MACD fast length", type=input.integer, minval=1, maxval=1000, defval=12) slowLen= input(title="MACD slow length", type=input.integer, minval=1, maxval=1000, defval=26) signLen= input(title="MACD signal length", type=input.integer, minval=1, maxval=1000, defval=9) longMaxTpChosen= input(title="Use maximum TP long", type=input.bool, defval=true) longMaxTp= input(title="Maximum take profit long (%) (min: 0.5, max: 30.0)", type=input.float, minval=0.5, step=0.1, defval=3.0 ,maxval=30.0) * 0.01 shortMaxTpChosen= input(title="Use maximum TP short", type=input.bool, defval=true) shortMaxTp= input(title="Maximum take profit short (%) (min: 0.5, max: 30.0)", type=input.float, minval=0.5, step=0.1, defval=3.0 ,maxval=30.0) * 0.01 rsiValue= rsi(rsiSource, rsiPeriod) [macdLine, signalLine, histLine] = macd(macdSource, fastLen, slowLen, signLen) plot(macdLine, color=color.red) plot(signalLine, color=color.green) plot(histLine, color=color.yellow, style=plot.style_histogram) [middle, upper, lower] = bb(bbSource, smaLength, stdLength) var idsLong = array.new_string(maxOrders,na) var idsShort = array.new_string(maxOrders,na) var stopLong = array.new_float(maxOrders, 0.0) var stopShort = array.new_float(maxOrders,999999.0) var longPartialClose = array.new_bool(maxOrders,false) var shortPartialClose = array.new_bool(maxOrders,false) var opTp = array.new_float(maxOrders, 0.0) var opTpShort = array.new_float(maxOrders, 0.0) canBuyMacd = true if macdVariation canBuyMacd := histLine[2]<histLine[1] and histLine[1] < histLine if not macdChosen canBuyMacd := true else canBuyMacd := histLine[2]<0 and histLine[1] >= 0 and histLine >= 0 if not macdChosen canBuyMacd := true canSellMacd = true if macdVariation canSellMacd := histLine[2]> histLine[1] and histLine[1]> histLine if not macdChosen canSellMacd := true else canSellMacd := histLine[2]>0 and histLine[1] <= 0 and histLine <= 0 if not macdChosen canSellMacd := true canBuyRsi = true if rsiChosen if rsiValue > rsiBuy canBuyRsi := false canSellRsi = true if rsiChosen if rsiValue < rsiSell canSellRsi := false canBuy = false int index = na for i = 0 to (maxOrders - 1) val=array.get(idsLong,i) if val==na canBuy := true index := i canSell = false int indexSell= na for i = 0 to (maxOrders - 1) val=array.get(idsShort,i) if val==na canSell := true indexSell := i bool isLong = close[2] < lower[2] and close[1] > close[2] and close > close[1] and canBuy and close[3] > close[2] and close < middle and (canBuyRsi and canBuyMacd) bool isShort = close[2] > upper[2] and close[1] < close[2] and close < close[1] and canSell and close[3] < close[2] and close > middle and (canSellRsi and canSellMacd) longStopPrice = 0.0 shortStopPrice = 0.0 tp=0.0 id = "" if (isLong) id := tostring(time) strategy.entry(id=id, long=true, qty=posSize) array.set(idsLong, index, id) stopValue = close * (1 - longTrailPerc) longStopPrice := stopValue array.set(stopLong, index, longStopPrice) tp := close * (1 + longMaxTp) array.set(opTp,index,tp) for i = 0 to (maxOrders - 1) stopValue = close * (1 - longTrailPerc) longStopPrice := max(stopValue, array.get(stopLong,i)) array.set(stopLong,i,longStopPrice) if ((longMaxTpChosen and array.get(opTp,i)<= close) or close >= upper or close <= array.get(stopLong,i)) and array.get(idsLong,i) != na id := array.get(idsLong,i) strategy.close(id=id, qty=posSize) array.set(idsLong,i,na) array.set(stopLong,i,0.0) array.set(longPartialClose,i,false) if close > middle and array.get(idsLong,i) != na and not array.get(longPartialClose,i) id := array.get(idsLong,i) x=array.get(idsLong,i) strategy.close(id=id, qty=posSize/2) array.set(longPartialClose,i,true) if (isShort) id := tostring(time) strategy.entry(id=id, long=false, qty=posSize) array.set(idsShort, indexSell, id) stopValue = close * (1 + shortTrailPerc) shortStopPrice := stopValue array.set(stopShort, indexSell, shortStopPrice) tp := close * (1 - shortMaxTp) array.set(opTpShort,indexSell,tp) for i = 0 to (maxOrders - 1) stopValue = close * (1 + shortTrailPerc) shortStopPrice := min(stopValue, array.get(stopShort,i)) array.set(stopShort,i,shortStopPrice) if ((shortMaxTpChosen and array.get(opTpShort,i) >= close) or close <= lower or close >= array.get(stopShort,i)) and array.get(idsShort,i) != na id := array.get(idsShort,i) strategy.close(id=id, qty=posSize) array.set(idsShort,i,na) array.set(stopShort,i,999999.0) array.set(shortPartialClose,i,false) if close < middle and not array.get(shortPartialClose,i) and array.get(idsShort,i) != na id := array.get(idsShort,i) strategy.close(id=id, qty=posSize/2) array.set(shortPartialClose,i,true) plot(middle, color=color.yellow) plot(upper, color=color.yellow) plot(lower, color=color.yellow)
(IK) Stoch-60-15
https://www.tradingview.com/script/CJ7Q8NyT-IK-Stoch-60-15/
tapRoot_coding
https://www.tradingview.com/u/tapRoot_coding/
296
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/ // Β© userIan //@version=4 strategy(title="(IK) 60-15", precision=2, default_qty_type=strategy.cash, default_qty_value=100.0, initial_capital=100.0, currency="USD", commission_type=strategy.commission.percent, commission_value=0.1) // get input i_length = input(group="Stochastic", title="Stochastic Length", minval=1, defval=18) i_k = input(group="Stochastic", title="Stochastic %K", minval=1, defval=2) i_d = input(group="Stochastic", title="Stochastic %D", minval=1, defval=10) i_trailingStop = input(group="Trade Settings", title="Trailing Stop?", type=input.bool, defval=true) // should stop loss be dynamic, based on most recent high, or static, based on entry price? i_stopPercent = input(group="Trade Settings", title="Stop Percent", type=input.float, defval=0.05, maxval=1.0, minval=0.001) // how much (percentage) can price fall before exiting the trade i_takeProfit = input(group="Trade Settings", title="Take Profit", type=input.float, defval=0.05, maxval=1.0, minval=0.001) // how much (percentage) can price rise before exiting the trade i_sellThreshold = input(group="Trade Settings", title="Sell Threshold", type=input.float, defval=75.0, maxval=100, minval=0.0) // when stochastic %D crosses under this value, exit the trade i_buyThreshold = input(group="Trade Settings", title="Buy Threshold", type=input.float, defval=40.0, maxval=100, minval=0.0) // stochastic %D must be below this value to enter a trade // declare order variables var recentHigh = 0.0 // the highest high while in a trade var stop = 0.0 // the price that will trigger as stop loss var entryPrice = 0.0 // the price when the trade was entered // build stochastic sto = stoch(close, high, low, i_length) K = sma(sto, i_k) D = sma(K, i_d) // get stochastic trend stoch_upTrend = D > D[1] // get stochastic trend for 60 minute stoch_60 = security(syminfo.tickerid, "60", D) stoch_60_upTrend = (stoch_60[4] >= stoch_60[8]) // entry if (D < i_buyThreshold) and stoch_upTrend and stoch_60_upTrend and barstate.isconfirmed recentHigh := close entryPrice := close stop := (close * (1-i_stopPercent)) strategy.entry(id="60-15-Long", long=strategy.long, comment='buy') // update recent high, trailing stop if close > recentHigh recentHigh := close stop := i_trailingStop ? (recentHigh * (1-i_stopPercent)) : stop // exit strategy.exit(id="60-15-Long", stop=stop, comment='sell-stop') if close > (entryPrice * (1+i_takeProfit)) and barstate.isconfirmed strategy.close(id="60-15-Long", comment='sell-profit') if crossunder(D, i_sellThreshold) and barstate.isconfirmed strategy.close(id="60-15-Long", comment='sell-trend') // plot plot(K, title="%K", color=color.blue, linewidth=1) plot(D, title="%D", color=color.orange, linewidth=1) plot(stoch_60, title="Hourly Stochastic (D)", color= stoch_60_upTrend ? color.green : color.red, style=plot.style_stepline) upperBand = hline(i_sellThreshold, title="Upper Limit", linestyle=hline.style_dashed) middleBand = hline(50, title="Midline", linestyle=hline.style_dotted) lowerBand = hline(i_buyThreshold, title="Lower Limit", linestyle=hline.style_dashed) fill(lowerBand, upperBand, color=color.purple, transp=75)
ELIA MULTI INDICATORS STRATEGY
https://www.tradingview.com/script/wsOhcM8r/
ally17
https://www.tradingview.com/u/ally17/
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/ // Β© ally17 //@version=4 strategy("ELIA MULTI STRATEGY",overlay=false,initial_capital=1000, default_qty_type=strategy.percent_of_equity, commission_type=strategy.commission.percent, commission_value=0.00, default_qty_value=25) //INPUT start = timestamp(input(2021, "start year"), 1, 1, 00, 00) end = timestamp(input(9999, "end year"), 1, 1, 00, 00) triggerin=input(6, title="Trigger In Value", minval=1, maxval=15) triggerout=input(3, title="Trigger Out Value", minval=1, maxval=15) emalen=input(80, title="Ema Len") macdfast=input(12, title="Macd Fast Len") macdslow=input(26, title="Macd Fast Len") macdsig=input(12, title="Macd Signal Len") occlen=input(15, title="Occ Len") rsilen=input(2, title="Rsi Len") stochklen=input(11, title="Stk K Len") stochdlen=input(3, title="Stk D Len") stochlen=input(3, title="Stk Smooth Len") bblength = input(10, minval=1, title="BB Len") mult = input(2.0, minval=0.001, maxval=50, title="BB Std Dev") momlen=input(10, title="Mom Len") //CALCOLI var trigger = 0.0 var emavar = 0.0 var macdvar = 0.0 var occvar = 0.0 var rsivar = 0.0 var stochvar = 0.0 var bbvar = 0.0 var donvar =0.0 ema = ema(close,emalen) [macdLine, signalLine, histLine] = macd(close, 12, 26, 9) // MACD occ = ema(close,occlen) - ema(open,occlen) rsi = rsi(close, rsilen) // RSI stoch = sma(stoch(close, high, low, stochklen), stochlen) // Stoch basis = sma(close, bblength) dev = mult * stdev(close, bblength) upper = basis + dev lower = basis - dev moment = mom(close, momlen) // Momentum Obv = obv // OBV //PLOT //STRATEGIA emavar := (close>ema)? 3 : -3 macdvar := (macdLine>signalLine)? 3 : -3 occvar := (occ>0)? 3 : -3 rsivar := (rsi<20)? 2 : (rsi>50 and rsi<80)? 1 : (rsi>80)? -2 : (rsi<50 and rsi>20)? -1 : 0 stochvar := (stoch<20)? 2 : (stoch>80)? -2 : 0 bbvar := (close<lower)? 2 : (close>upper)? -2 : 0 trigger := emavar+macdvar+occvar+rsivar+stochvar+bbvar longcondition = trigger >= triggerin closelong = trigger < triggerout shortcondition = trigger <= -triggerin closeshort = trigger > -triggerout trendcolor = longcondition ? color.green : shortcondition? color.red : (trigger>triggerout and trigger<triggerin)? #A2E1BF : (trigger<-triggerout and trigger>-triggerin)? #E19997 : na //bgcolor(trendcolor, transp=80) plot(trigger, color=color.white) hline(triggerin, title="long", color=color.green, linestyle=hline.style_dashed) hline(0-triggerin, title="short", color=color.red, linestyle=hline.style_dashed) hline(triggerout, title="close long",color=color.blue, linestyle=hline.style_dashed) hline(0-triggerout, title="closeshort",color=color.blue, linestyle=hline.style_dashed) if time > start and time < end if longcondition strategy.entry("LONG", long=strategy.long) if closelong strategy.close("LONG", comment="CLOSE LONG") if time > start and time < end if shortcondition strategy.entry("SHORT", long=strategy.short) if closeshort strategy.close("SHORT", comment="CLOSE SHORT") //plotshape(longcondition, color=color.green, text="L", size=size.small, style=shape.triangledown) //plotshape(shortcondition, color=color.red, "S"(trigger), size=size.small, style=shape.triangledown) //plotshape(closelong, color=color.purple, text="LC", size=size.small, style=shape.triangledown) //plotshape(closeshort, color=color.purple, text="SC", size=size.small, style=shape.triangledown)
Buying Dip Strategy With Take Profit And Stop Loss [racer8]
https://www.tradingview.com/script/AHxkEMXm-Buying-Dip-Strategy-With-Take-Profit-And-Stop-Loss-racer8/
racer8
https://www.tradingview.com/u/racer8/
919
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/ // Β© racer8 //@version=4 strategy("BuyTheDip", overlay=true) atn = input(10, "ATR Length") atr = sma(tr,atn)[1] bought = strategy.position_size[0] > strategy.position_size[1] tpm = input(2.0,"ATR Take Profit",minval=0) TakePrice = strategy.position_avg_price + tpm*atr // determines Take Profit's price FixedTakePrice = valuewhen(bought,TakePrice,0) // stores original TakePrice plot(FixedTakePrice,"ATR Take Profit",color=color.blue,linewidth=1,style=plot.style_cross) slm = input(2.0,"ATR Stop Loss",minval=0) StopPrice = strategy.position_avg_price - slm*atr // determines stop loss's price FixedStopPrice = valuewhen(bought,StopPrice,0) // stores original StopPrice plot(FixedStopPrice,"ATR Stop Loss",color=color.yellow,linewidth=1,style=plot.style_cross) n = input(7,"Dip Length") Dip = lowest(low,n) if close<Dip[1] strategy.entry("Buy",strategy.long) if strategy.position_size > 0 strategy.exit(id="Stop", stop=FixedStopPrice, limit=FixedTakePrice) // commands stop loss order to exit! plot(Dip,"Dip Line",color=color.aqua,linewidth=2) // β™‘β™‘β™‘
Korea premium(KIMP)
https://www.tradingview.com/script/cfZgHp0l-Korea-premium-KIMP/
roses27
https://www.tradingview.com/u/roses27/
73
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/ // Β© roses27 //@version=4 // Ver. 1.4 strategy(title = "Korea premium(KIMP)", overlay=true, calc_on_every_tick=false, process_orders_on_close=true, initial_capital=100000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, pyramiding = 0, commission_type=strategy.commission.percent, commission_value=0.25) tradeType = input("LONG", title="What trades should be taken : ", options=["LONG", "SHORT", "BOTH"]) use_ema = input(defval = false, title = "use EMA?") basisLen0 = input(defval = 10, title = "MA Period", minval = 1) alma_offset = input(defval = 0.5, title = "Offset for ALMA", minval = 0.0, step = 0.02) alma_sigma = input(defval = 20.0, title = "Sigma for ALMA", minval = 0.0, step = 1.0) high_low_Len= input(defval = 254, title = "High Low Period", minval = 1) i_startTime = input(defval = timestamp(" 1 Mar 2021 00:00 +0000"), title ="Start Time", type = input.time) i_endTime = input(defval = timestamp(" 1 Dec 2022 00:00 +0000"), title ="End Time", type = input.time) use_index_btc= input(defval = false, title = "Use INDEX:BTCUSD KIMP?", group = "Select data to use for calculation") use_absolute= input(defval = false, title = "Use Absolute Percentage?", group = "Absolute Percentage") bias_low_A = input(defval = 13.2, title = "Absolute bias_low %", group = "Absolute Percentage", step=0.1) bias_high_A = input(defval = 16.7, title = "Absolute bias_high %", group = "Absolute Percentage", minval=0, step=0.1) bias_low = input(defval = 30.0 , title = "Relative bias_low %", group = "Relative Percentage", minval=0, step=1.0)/100.0 bias_high = input(defval = 95.0 , title = "Relative bias_high %", group = "Relative Percentage", step=1.0)/100.0 bb = input(defval = false, title = "use BB?") length0 = input(defval = 70, title = "BB Length") stddev0 = input(defval = 0.3, title = "BB Stddev", step = 0.01) length_ema = input(defval = 34, title = "ema Length") st0 = input(defval = 'KRW', title = "Current Currency", group = "Select Currency to use for calculation") st1 = input(defval = 'USDT', title = "Currency to compare", group = "Select Currency to use for calculation") st2 = input(defval = 'USD', title = "Currency to compare", group = "Select Currency to use for calculation") Dealer_0 = input(defval = 'BITHUMB', title = "Current Dealer", group = "Select Currency to use for calculation") Dealer_1 = input(defval = 'BINANCE', title = "Dealer to compare", group = "Select Currency to use for calculation") // id01 = input(defval = syminfo.ticker, title='Symbol 01',type=input.symbol) // id01 = input(defval = 'XRP', title='Symbol 01',type=input.symbol) f_grad_transp(_c_col, _transp) => _c_red = color.r(_c_col) _c_green = color.g(_c_col) _c_blue = color.b(_c_col) color.rgb(_c_red, _c_green, _c_blue, _transp) var string id00 = str.replace_all(syminfo.ticker,st1,'') var string id0 = str.replace_all(id00,st2,'') var string id = str.replace_all(id0, st0,'') var string id0_0 = Dealer_0 + ':' + id + st0 var string id0_1 = Dealer_1 + ':' + id + st1 showPlot = input(defval = true, title = "Show Plot", type = input.bool) inDateRange = time >= i_startTime and time <= i_endTime coin_0 = security(id0_0, "", close) coin_0_high = security(id0_0, "", high) coin_0_low = security(id0_0, "", low) coin_1 = security(id0_1, "", close) coin_1_high = security(id0_1, "", high) coin_1_low = security(id0_1, "", low) btc_krw = security('BITHUMB:BTCKRW',"", close) btc_krw_high = security('BITHUMB:BTCKRW',"", high) btc_krw_low = security('BITHUMB:BTCKRW',"", low) // btc_usd = security('BINANCE:BTCUSDT',"", close) // btc_usd_high = security('BINANCE:BTCUSDT',"", high) // btc_usd_low = security('BINANCE:BTCUSDT',"", low) btc_usd = security('INDEX:BTCUSD',"", close) btc_usd_high = security('INDEX:BTCUSD',"", high) btc_usd_low = security('INDEX:BTCUSD',"", low) usd_krw = security('USDKRW',"",close) kimp_ = 0.0 kimp_high = 0.0 kimp_low = 0.0 if use_index_btc kimp_ := 100.0 * (btc_krw - btc_usd * usd_krw) / (btc_usd * usd_krw) kimp_high := 100.0 * (btc_krw_high - btc_usd_high * usd_krw) / (btc_usd_high * usd_krw) kimp_low := 100.0 * (btc_krw_low - btc_usd_low * usd_krw) / (btc_usd_low * usd_krw) else if syminfo.ticker == id + st0 //krw // kimp_ := 100.0 * (coin_1 - close * usd_krw) / (close * usd_krw) kimp_ := 100.0 * (close - coin_1 * usd_krw) / close kimp_high := 100.0 * (high - coin_1 * usd_krw) / high kimp_low := 100.0 * (low - coin_1 * usd_krw) / low else //usd kimp_ := 100.0 * (coin_0 / usd_krw - close) / close kimp_high := 100.0 * (coin_0_high / usd_krw - high) / high kimp_low := 100.0 * (coin_0_low / usd_krw - low) / low var int basisLen = int(3 * basisLen0/tonumber(timeframe.period)) > 3 ? int(3 * basisLen0/tonumber(timeframe.period)) : 3 kimp_alma = alma(kimp_, basisLen, alma_offset, alma_sigma) kimp_alma_h = alma(kimp_high, basisLen, alma_offset, alma_sigma) kimp_alma_l = alma(kimp_low, basisLen, alma_offset, alma_sigma) // kimp_alma_high = highest(kimp_alma, high_low_Len) // kimp_alma_low = lowest( kimp_alma, high_low_Len) kimp_alma_high = highest(kimp_alma_h, high_low_Len) kimp_alma_low = lowest( kimp_alma_l, high_low_Len) kimp_ema = ema(kimp_, basisLen0) kimp_ema_h = ema(kimp_high, basisLen0) kimp_ema_l = ema(kimp_low, basisLen0) kimp_ema_high = highest(kimp_ema_h, high_low_Len) kimp_ema_low = lowest( kimp_ema_l, high_low_Len) kimp_plot_ = 0.0 if syminfo.ticker == id + st1 or syminfo.ticker == id + st2 kimp_plot_ := coin_0 / usd_krw if syminfo.ticker == id + st0 kimp_plot_ := coin_1 * usd_krw // if use_index_btc and id == 'BTC' // kimp_plot_ := btc_usd * usd_krw if use_index_btc and id == 'BTC' and syminfo.ticker == id + st0 kimp_plot_ := btc_usd * usd_krw if use_index_btc and id == 'BTC' and (syminfo.ticker == id + st1 or syminfo.ticker == id + st2) kimp_plot_ := btc_krw / usd_krw [middle, upper, lower] = bb(kimp_, length0, stddev0) close_ema = ema(kimp_, length_ema) value = 0.0 bottom_value= 0.0 top_value = 0.0 if use_absolute value := kimp_ bottom_value:= bias_low_A top_value := bias_high_A else if bb value := close_ema bottom_value:= lower top_value := upper else if use_ema value := kimp_ bottom_value:= (kimp_ema_high - kimp_ema_low) * bias_low + kimp_ema_low top_value := (kimp_ema_high - kimp_ema_low) * bias_high + kimp_ema_low else value := kimp_ bottom_value:= (kimp_alma_high - kimp_alma_low) * bias_low + kimp_alma_low top_value := (kimp_alma_high - kimp_alma_low) * bias_high + kimp_alma_low PAL = (value < bottom_value) PAS = (value > top_value ) c_grad = color.from_gradient(value, bottom_value, top_value, color.lime, color.red) chgPAL = PAL and not PAL[1] chgPAS = PAS and not PAS[1] band0 = plot(series = showPlot and inDateRange ? kimp_plot_ : na, color = syminfo.ticker == id0 ? color.blue : color.red, linewidth = 2) band1 = plot(inDateRange ? close: na) fill(band0, band1, color=f_grad_transp(c_grad, 80), title="Background") if (inDateRange and tradeType!="NONE") strategy.entry("long", strategy.long, when=chgPAL ==true and tradeType!="SHORT" and inDateRange, comment = "EL") strategy.entry("short", strategy.short, when=chgPAS ==true and tradeType!="LONG" and inDateRange, comment = "ES") strategy.close("long", when=chgPAS ==true and tradeType=="LONG" and inDateRange, comment = "EL close") strategy.close("short", when=chgPAL ==true and tradeType=="SHORT" and inDateRange, comment = "ES close") // === /STRATEGY === // eof
Fixed price Stop Loss [Takazudo]
https://www.tradingview.com/script/Df9916Ar-Fixed-price-Stop-Loss-Takazudo/
Takazudo
https://www.tradingview.com/u/Takazudo/
60
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=Takazudo strategy("Fixed price SL", overlay=true, default_qty_type=strategy.fixed, initial_capital=0, currency=currency.USD) var COLOR_TRANSPARENT = color.new(#000000, 100) var COLOR_ENTRY_BAND = color.new(#43A6F5, 30) var COLOR_RANGE_BREAK_BULL = color.new(#315F2E, 80) var COLOR_RANGE_BREAK_BEAR = color.new(#802A1C, 80) //============================================================================ // config //============================================================================ // Money management _g1 = 'Money management' var config_riskPrice = input.int(100, minval=1, title="Risk price for each entry", group=_g1) var config_depositCurrency = input.string(title="Deposit currency", defval="USD", options=["USD"], group=_g1) // Entry strategy _g2 = 'Entry strategy' var config_entryBandBars = input.int(defval = 100, title = "Entry band bar count", minval=1, group=_g2) // Backtesting range _g3 = 'Backtesting range' fromYear = input.int(defval = 2016, title = "From Year", minval = 1970, group=_g3) fromMonth = input.int(defval = 1, title = "From Month", minval = 1, maxval = 12, group=_g3) fromDay = input.int(defval = 1, title = "From Day", minval = 1, maxval = 31, group=_g3) toYear = input.int(defval = 2020, title = "To Year", minval = 1970, group=_g3) toMonth = input.int(defval = 12, title = "To Month", minval = 1, maxval = 12, group=_g3) toDay = input.int(defval = 31, title = "To Day", minval = 1, maxval = 31, group=_g3) //============================================================================ // exchange calculations //============================================================================ // mico pip size calculation // ex1: AUDCAD -> 0.0001 // ex2: USDJPY -> 0.01 f_calcMicroPipSize() => _base = syminfo.basecurrency _quote = syminfo.currency _result = 0.0001 if _quote == 'JPY' _result := _result * 100 if _base == 'BTC' _result := _result * 100 _result // convert price to pips f_convertPriceToPips(_price) => _microPipSize = f_calcMicroPipSize() _price / _microPipSize // calculate exchange rate between deposit and quote currency f_calcDepositExchangeSymbolId() => _result = '' _deposit = config_depositCurrency _quote = syminfo.currency if (_deposit == 'USD') and (_quote == 'USD') _result := na if (_deposit == 'USD') and (_quote == 'AUD') _result := 'OANDA:AUDUSD' if (_deposit == 'EUR') and (_quote == 'USD') _result := 'OANDA:EURUSD' if (_deposit == 'USD') and (_quote == 'GBP') _result := 'OANDA:GBPUSD' if (_deposit == 'USD') and (_quote == 'NZD') _result := 'OANDA:NZDUSD' if (_deposit == 'USD') and (_quote == 'CAD') _result := 'OANDA:USDCAD' if (_deposit == 'USD') and (_quote == 'CHF') _result := 'OANDA:USDCHF' if (_deposit == 'USD') and (_quote == 'JPY') _result := 'OANDA:USDJPY' _result // Let's say we need CAD to USD exchange // However there's only "OANDA:USDCAD" symbol. // Then we need to invert the exhchange rate. // this function tells us whether we should invert the rate or not f_calcShouldInvert() => _result = false _deposit = config_depositCurrency _quote = syminfo.currency if (_deposit == 'USD') and (_quote == 'CAD') _result := true if (_deposit == 'USD') and (_quote == 'CHF') _result := true if (_deposit == 'USD') and (_quote == 'JPY') _result := true _result // calculate how much quantity should I buy or sell f_calcQuantitiesForEntry(_depositExchangeRate, _slPips) => _microPipSize = f_calcMicroPipSize() _priceForEachPipAsDeposit = _microPipSize * _depositExchangeRate _losePriceOnSl = _priceForEachPipAsDeposit * _slPips math.floor(config_riskPrice / _losePriceOnSl) //============================================================================ // Quantity calculation //============================================================================ depositExchangeSymbolId = f_calcDepositExchangeSymbolId() // calculate deposit exchange rate rate = request.security(depositExchangeSymbolId, timeframe.period, hl2) shouldInvert = f_calcShouldInvert() depositExchangeRate = if config_depositCurrency == syminfo.currency // if USDUSD, no exchange of course 1 else // else, USDCAD to CADUSD invert if we need shouldInvert ? (1 / rate) : rate //============================================================================ // Range Edge calculation //============================================================================ f_calcEntryBand_high() => _highest = math.max(open[3], close[3]) for i = 4 to (config_entryBandBars - 1) _highest := math.max(_highest, open[i], close[i]) _highest f_calcEntryBand_low() => _lowest = math.min(open[3], close[3]) for i = 4 to (config_entryBandBars - 1) _lowest := math.min(_lowest, open[i], close[i]) _lowest entryBand_high = f_calcEntryBand_high() entryBand_low = f_calcEntryBand_low() entryBand_height = entryBand_high - entryBand_low plot(entryBand_high, color=COLOR_ENTRY_BAND, linewidth=1) plot(entryBand_low, color=COLOR_ENTRY_BAND, linewidth=1) rangeBreakDetected_long = entryBand_high < close rangeBreakDetected_short = entryBand_low > close shouldMakeEntryLong = (strategy.position_size == 0) and rangeBreakDetected_long shouldMakeEntryShort = (strategy.position_size == 0) and rangeBreakDetected_short //============================================================================ // SL & Quantity //============================================================================ var sl_long = hl2 var sl_short = hl2 entryQty = 0 slPips = 0.0 // just show info bubble f_showEntryInfo(_isLong) => _str = 'SL pips: ' + str.tostring(slPips) + '\n' + 'Qty: ' + str.tostring(entryQty) _bandHeight = entryBand_high - entryBand_low _y = _isLong ? (entryBand_low + _bandHeight * 1/4) : (entryBand_high - _bandHeight * 1/4) _style = _isLong ? label.style_label_up : label.style_label_down label.new(bar_index, _y, _str, size=size.large, style=_style) if shouldMakeEntryLong sl_long := (entryBand_high + entryBand_low) / 2 slPips := f_convertPriceToPips(close - sl_long) entryQty := f_calcQuantitiesForEntry(depositExchangeRate, slPips) if shouldMakeEntryShort sl_short := (entryBand_high + entryBand_low) / 2 slPips := f_convertPriceToPips(sl_short - close) entryQty := f_calcQuantitiesForEntry(depositExchangeRate, slPips) // trailing SL if strategy.position_size > 0 sl_long := math.max(sl_long, entryBand_low) if strategy.position_size < 0 sl_short := math.min(sl_short, entryBand_high) //============================================================================ // backtest duration //============================================================================ // Calculate start/end date and time condition startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00) finishDate = timestamp(toYear, toMonth, toDay, 00, 00) //============================================================================ // make entries //============================================================================ if (time >= startDate and time <= finishDate) if shouldMakeEntryLong strategy.entry(id="Long", direction=strategy.long, stop=close, qty=entryQty) f_showEntryInfo(true) if shouldMakeEntryShort strategy.entry(id="Short", direction=strategy.short, stop=close, qty=entryQty) f_showEntryInfo(false) strategy.exit('Long-SL/TP', 'Long', stop=sl_long) strategy.exit('Short-SL/TP', 'Short', stop=sl_short) //============================================================================ // plot misc //============================================================================ sl = strategy.position_size > 0 ? sl_long : strategy.position_size < 0 ? sl_short : na plot(sl, color=color.red, style=plot.style_cross, linewidth=2, title="SL") value_bgcolor = rangeBreakDetected_long ? COLOR_RANGE_BREAK_BULL : rangeBreakDetected_short ? COLOR_RANGE_BREAK_BEAR : COLOR_TRANSPARENT bgcolor(value_bgcolor)
MACD oscillator with EMA strategy 4H
https://www.tradingview.com/script/VCWVU9ge-MACD-oscillator-with-EMA-strategy-4H/
SoftKill21
https://www.tradingview.com/u/SoftKill21/
518
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/ // Β© SoftKill21 //@version=4 strategy("MACD+EMA 4H STRATEGY", overlay=true) //heiking ashi calculation UseHAcandles = input(false, title="Use Heikin Ashi Candles in Algo Calculations") //// // === /INPUTS === // === BASE FUNCTIONS === haClose = UseHAcandles ? security(heikinashi(syminfo.tickerid), timeframe.period, close) : close haOpen = UseHAcandles ? security(heikinashi(syminfo.tickerid), timeframe.period, open) : open haHigh = UseHAcandles ? security(heikinashi(syminfo.tickerid), timeframe.period, high) : high haLow = UseHAcandles ? security(heikinashi(syminfo.tickerid), timeframe.period, low) : low //timecondition 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 = 2020, title = "From Year", minval = 1970) //monday and session // To Date Inputs toDay = input(defval = 31, title = "To Day", minval = 1, maxval = 31) toMonth = input(defval = 12, title = "To Month", minval = 1, maxval = 12) toYear = input(defval = 2021, title = "To Year", minval = 1970) startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00) finishDate = timestamp(toYear, toMonth, toDay, 00, 00) time_cond = time >= startDate and time <= finishDate //ema data -- moving average len = input(9, minval=1, title="Length") src = input(hl2, title="Source") out = ema(src, len) //plot(out, title="EMA", color=color.blue) //histogram fast_length = input(title="Fast Length", type=input.integer, defval=12) slow_length = input(title="Slow Length", type=input.integer, defval=26) 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 //main variables to apply conditions are going to be out(moving avg) and hist(macd) long = haClose > out and haClose > haClose[1] and out > out[1] and hist> 0 and hist[1] < 0 and time_cond short = haClose < out and haClose < haClose[1] and out < out[1] and hist < 0 and hist[1] > 0 and time_cond //limit to 1 entry var longOpeneda = false var shortOpeneda = false var int timeOfBuya = na longCondition= long and not longOpeneda if longCondition longOpeneda := true timeOfBuya := time longExitSignala = short exitLongCondition = longOpeneda[1] and longExitSignala if exitLongCondition longOpeneda := false timeOfBuya := na plotshape(longCondition, style=shape.labelup, location=location.belowbar, color=color.green, size=size.tiny, title="BUY", text="BUY", textcolor=color.white) plotshape(exitLongCondition, style=shape.labeldown, location=location.abovebar, color=color.red, size=size.tiny, title="SELL", text="SELL", textcolor=color.white) //automatization longEntry= input(true) shortEntry=input(false) if(longEntry) strategy.entry("long",strategy.long,when=longCondition) strategy.close("long",when=exitLongCondition) if(shortEntry) strategy.entry("short",strategy.short,when=exitLongCondition) strategy.close("short",when=longCondition)
Buy every Month
https://www.tradingview.com/script/lPghpGeV-Buy-every-Month/
Embit0one
https://www.tradingview.com/u/Embit0one/
48
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/ // Β© Embit0one //@version=4 strategy("Buy every Month",pyramiding=10000, overlay=true,initial_capital=0,default_qty_type=strategy.cash,default_qty_value=500,currency = currency.EUR,commission_type=strategy.commission.cash_per_order,commission_value=0) //INPUTS################################################################################################################## iniordersize = input(title="Ordersize / Sparrate", type=input.integer,defval=500) // Input for Date Range startDate = input(title="Start Date", type=input.integer, defval=1, minval=1, maxval=31) startMonth = input(title="Start Month", type=input.integer, defval=1, minval=1, maxval=12) startYear = input(title="Start Year", type=input.integer, defval=2020, minval=1800, maxval=2100) endDate = input(title="End Date", type=input.integer, defval=7, minval=1, maxval=31) endMonth = input(title="End Month", type=input.integer, defval=04, minval=1, maxval=12) endYear = input(title="End Year", type=input.integer, defval=2021, minval=1800, maxval=2100) endDate1=endDate-1 //Check if in Date Range inDateRange = (time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0)) and (time < timestamp(syminfo.timezone, endYear, endMonth, endDate1, 0, 0)) //Ordersize calculation####################################################### var ordersize = 0 ordersize:=floor(iniordersize/close) var float insgesamtinvestiert = 0 //Open Position at beginning##################################### var firsttrade=true longCondition = inDateRange longnow=false if(firsttrade and inDateRange) strategy.entry("My Long Entry Id", strategy.long,ordersize) longnow:=true insgesamtinvestiert:= insgesamtinvestiert + (ordersize*close) firsttrade:=false if(longCondition and strategy.position_size > 0) longnow:=true //Start of new Month, open a possition if(longCondition and strategy.position_size > 0 and month>valuewhen(longnow, month ,1) or longCondition and strategy.position_size > 0 and year>valuewhen(longnow, year ,1) and inDateRange) strategy.entry("My Long Entry Id", strategy.long,ordersize) insgesamtinvestiert:= insgesamtinvestiert + (ordersize*close) //Close all positions when End Date if(time > timestamp(syminfo.timezone, endYear, endMonth, endDate1, 0, 0)) strategy.close_all() //print sum of investeted capital######################################################################################################################### f_print(_text) => // Create label on the first bar. var _label = label.new(bar_index, na, _text, xloc.bar_index, yloc.price, color(na), label.style_none, color.gray, size.large, text.align_left) // On next bars, update the label's x and y position, and the text it displays. label.set_xy(_label, bar_index, highest(10)[1]) label.set_text(_label, _text) f_print(" Invested: " + tostring(floor(insgesamtinvestiert)))
Full CRYPTO pack macd, rsi, obv, ema strategy
https://www.tradingview.com/script/DbRYTl6G-Full-CRYPTO-pack-macd-rsi-obv-ema-strategy/
SoftKill21
https://www.tradingview.com/u/SoftKill21/
3,144
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/ // Β© SoftKill21 //@version=4 strategy("Full strategy ", overlay=true, initial_capital = 1000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent , commission_value=0.1 ) //heiking ashi calculation UseHAcandles = input(false, title="Use Heikin Ashi Candles in Algo Calculations") //// // === /INPUTS === // === BASE FUNCTIONS === haClose = UseHAcandles ? security(heikinashi(syminfo.tickerid), timeframe.period, close) : close haOpen = UseHAcandles ? security(heikinashi(syminfo.tickerid), timeframe.period, open) : open haHigh = UseHAcandles ? security(heikinashi(syminfo.tickerid), timeframe.period, high) : high haLow = UseHAcandles ? security(heikinashi(syminfo.tickerid), timeframe.period, low) : low //timecondition 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 = 2020, title = "From Year", minval = 1970) //monday and session // To Date Inputs toDay = input(defval = 31, title = "To Day", minval = 1, maxval = 31) toMonth = input(defval = 12, title = "To Month", minval = 1, maxval = 12) toYear = input(defval = 2021, title = "To Year", minval = 1970) startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00) finishDate = timestamp(toYear, toMonth, toDay, 00, 00) time_cond = time >= startDate and time <= finishDate //ema data -- moving average len = input(9, minval=1, title="Length") src = input(hl2, title="Source") out = ema(src, len) //plot(out, title="EMA", color=color.blue) //histogram fast_length = input(title="Fast Length", type=input.integer, defval=12) slow_length = input(title="Slow Length", type=input.integer, defval=26) 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 //rsi length = input( 14 ) overSold = input( 35 ) overBought = input( 100 ) price = close vrsi = rsi(price, length) co = crossover(vrsi, overSold) cu = crossunder(vrsi, overBought) //volume r = cum(sign(change(src)) * volume) outvolume= sma(obv,10) //main variables to apply conditions are going to be out(moving avg) and hist(macd) long = haClose > out and haClose > haClose[1] and out > out[1] and hist> 0 and hist[1] < 0 and time_cond and vrsi<overBought and obv> outvolume short = haClose < out and haClose < haClose[1] and out < out[1] and hist < 0 and hist[1] > 0 and time_cond and vrsi>overSold and obv< outvolume //limit to 1 entry var longOpeneda = false var shortOpeneda = false var int timeOfBuya = na longCondition= long and not longOpeneda if longCondition longOpeneda := true timeOfBuya := time longExitSignala = short exitLongCondition = longOpeneda[1] and longExitSignala if exitLongCondition longOpeneda := false timeOfBuya := na plotshape(longCondition, style=shape.labelup, location=location.belowbar, color=color.green, size=size.tiny, title="BUY", text="BUY", textcolor=color.white) plotshape(exitLongCondition, style=shape.labeldown, location=location.abovebar, color=color.red, size=size.tiny, title="SELL", text="SELL", textcolor=color.white) //automatization longEntry= input(true) shortEntry=input(false) g(v, p) => round(v * (pow(10, p))) / pow(10, p) risk = input(100) leverage = input(1) c = g((strategy.equity * leverage / open) * (risk / 100), 4) if(longEntry) strategy.entry("long",strategy.long,c,when=longCondition) strategy.close("long",when=exitLongCondition) if(shortEntry) strategy.entry("short",strategy.short,c,when=exitLongCondition) strategy.close("short",when=longCondition)
MACD BTC Long/Short Strategy v1.0
https://www.tradingview.com/script/Z4bCLIrN-MACD-BTC-Long-Short-Strategy-v1-0/
Puckapao
https://www.tradingview.com/u/Puckapao/
99
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© Puckapao //@version=4 strategy(title="MACD", shorttitle="MACD", overlay=true, initial_capital=10000.00, currency="USD", default_qty_type=strategy.cash, default_qty_value=10000.00) // Getting inputs reenter_delay = input(title="Re-enter Delay", type=input.integer, defval=2) sculp_delay = input(title="Sculp Delay", type=input.integer, defval=8) close_delay = input(title="Close Delay", type=input.integer, defval=1) ema_period = input(title="EMA Period", type=input.integer, defval=21) 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=true) // Date Settings startDate = input(title="Start Date", type=input.integer, defval=19, minval=1, maxval=31) startMonth = input(title="Start Month", type=input.integer, defval=09, minval=1, maxval=12) startYear = input(title="Start Year", type=input.integer, defval=2017, minval=1800, maxval=2100) endDate = input(title="End Date", type=input.integer, defval=31, minval=1, maxval=31) endMonth = input(title="End Month", type=input.integer, defval=3, minval=1, maxval=12) endYear = input(title="End Year", type=input.integer, defval=2021, minval=1800, maxval=2100) inDateRange = (time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0)) and (time < timestamp(syminfo.timezone, endYear, endMonth, endDate, 0, 0)) reenter_cnt = 0 reenter_cnt := nz(reenter_cnt[1]) sculp_cnt = 0 sculp_cnt := nz(sculp_cnt[1]) close_cnt = 0 close_cnt := nz(close_cnt[1]) on_long = false on_long := nz(on_long[1]) on_short = false on_short := nz(on_short[1]) sculp = false reenter = false slowdown = false overwater = false underwater = false ema = ema(close, ema_period) // Plot colors col_grow_above = #26A69A col_grow_below = #FFCDD2 col_fall_above = #B2DFDB col_fall_below = #EF5350 col_macd = #0094ff col_signal = #ff6a00 // Calculating fast_ma = sma_source ? sma(src, fast_length) : ema(src, fast_length) slow_ma = sma_source ? sma(src, slow_length) : ema(src, slow_length) macd = fast_ma - slow_ma signal = sma_signal ? sma(macd, signal_length) : ema(macd, signal_length) hist = macd - signal // plot(hist, title="Histogram", style=plot.style_columns, color=(hist>=0 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below) ), transp=0 ) // plot(macd, title="MACD", color=col_macd, transp=0) // plot(signal, title="Signal", color=col_signal, transp=0) cross_up = crossover(macd, signal) cross_down = crossunder(macd, signal) if (inDateRange) over_macd = macd > 0 and signal > 0 ? true : false under_macd = macd < 0 and signal < 0 ? true : false overwater := crossover(close, ema) underwater := crossunder(close, ema) slowdown := hist >= 0 ? (hist[1] > hist ? true : false) : (hist[1] < hist ? true : false) reenter := hist >= 0 ? (hist[1] < hist ? true : false) : (hist[1] > hist ? true : false) sculp := (hist >= 0 ? (hist[1] > hist ? true : false) : (hist[1] < hist ? true : false)) if(reenter == true) if(reenter_cnt < reenter_delay) reenter_cnt := reenter_cnt + 1 else if(reenter_cnt > 0) reenter_cnt := reenter_cnt - 1 if(sculp == true) if(sculp_cnt < sculp_delay) sculp_cnt := sculp_cnt + 1 else if(sculp_cnt > 0) sculp_cnt := sculp_cnt - 1 if(slowdown == true) if(close_cnt < close_delay) close_cnt := close_cnt + 1 else close_cnt := close_cnt - 1 // Entry if (cross_up == true) strategy.entry("long", strategy.long, comment = "long", alert_message = "long") if (cross_down == true) strategy.entry("short", strategy.short, comment = "short", alert_message = "short") // Sculp bottom / top if (sculp == true and sculp_cnt >= sculp_delay) if (hist >= 0) strategy.entry("sculp-short", strategy.short, comment = "sculp-short", alert_message = "sculp-short") else strategy.entry("sculp-long", strategy.long, comment = "sculp-long", alert_message = "sculp-long") sculp_cnt := 0 sculp := false // Re-Entry if (reenter == true and reenter_cnt >= reenter_delay) if (hist >= 0) strategy.entry("re-long", strategy.long, comment = "re-long", alert_message = "re-long") else strategy.entry("re-short", strategy.short, comment = "re-short", alert_message = "re-short") reenter_cnt := 0 reenter := false // Over EMA if (overwater == true) strategy.entry("ema-long", strategy.long, comment = "ema-long", alert_message = "ema-long") // Close if (slowdown == true and close_cnt >= close_delay) strategy.close("long", when = slowdown, comment = "close long", alert_message = "close long") strategy.close("short", when = slowdown, comment = "close short", alert_message = "close short") strategy.close("re-long", when = slowdown, comment = "close re-long", alert_message = "close re-long") strategy.close("re-short", when = slowdown, comment = "close re-short", alert_message = "close re-short") if (hist >= 0) strategy.close("sculp-long", when = slowdown, comment = "close sculp-long", alert_message = "close sculp-long") else strategy.close("sculp-short", when = slowdown, comment = "close sculp-short", alert_message = "close sculp-short") if (slowdown) if (hist >= 0) on_long := false else on_short := false strategy.close("ema-long", when = underwater, comment = "close ema-long", alert_message = "close ema-long") plotchar(slowdown, "close?", "") plotchar(close_cnt, "close delay", "") plotchar(reenter, "reenter?", "") plotchar(reenter_cnt, "reenter delay", "") plotchar(sculp, "sculp?", "") plotchar(sculp_cnt, "sculp delay", "") plotchar(overwater, "over ema", "") plotchar(underwater, "under ema", "")
dEMA w/ VWAP filter
https://www.tradingview.com/script/d5I7yUXY-dEMA-w-VWAP-filter/
shiner_trading
https://www.tradingview.com/u/shiner_trading/
82
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/ // Β© shiner_trading //@version=4 strategy("dEMA w/ VWAP filter", overlay=true, default_qty_type=strategy.cash, initial_capital=500) len = input(34, "EMA Length") ma = ema(close, len) longCondition = change(ma) > 0 and ma < vwap if (longCondition) strategy.entry("Buy", true, 1) shortCondition = (change(ma) < 0 and close > vwap) or (crossunder(ma, vwap) and change(ma) > 0) if (shortCondition) strategy.close("Buy") plot (vwap, color=color.fuchsia) plot (ma)
2Tier Ichimoku Pyramiding [Takazudo]
https://www.tradingview.com/script/xTO21owU-2Tier-Ichimoku-Pyramiding-Takazudo/
Takazudo
https://www.tradingview.com/u/Takazudo/
213
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/ // https://www.tradingview.com/script/UhhFWEus-MTF-Ichimoku-Takazudo/ //@version=4 //@author=Takazudo strategy("2Tier Ichimoku Pyramiding [Takazudo]", pyramiding=2, overlay=true, default_qty_type=strategy.fixed, initial_capital=0, currency=currency.USD) //============================================================================ // consts, inputs //============================================================================ // colors var COLOR_KIJUN = color.new(#fcb103, 20) var COLOR_TENKAN = color.new(#f57f17, 20) var COLOR_CHIKOU = color.new(#ffffff, 50) var COLOR_KUMO_BASEHTF_BULL = color.new(#315F2E, 60) var COLOR_KUMO_BASEHTF_BEAR = color.new(#802A1C, 60) var COLOR_KUMO_HIGHESTTF_BULL = color.new(#1D4F8A, 60) var COLOR_KUMO_HIGHESTTF_BEAR = color.new(#6B2B55, 60) var COLOR_SENKOUA_BASEHTF = color.new(#315F2E, 30) var COLOR_SENKOUB_BASEHTF = color.new(#802A1C, 30) var COLOR_SENKOUA_HIGHESTTF = color.new(#1D4F8A, 30) var COLOR_SENKOUB_HIGHESTTF = color.new(#6B2B55, 30) var COLOR_CROSS_POINT_BULL = color.new(#315F2E, 20) var COLOR_CROSS_POINT_BEAR = color.new(#802A1C, 20) var COLOR_CHIKOU_CROSS_POINT_BULL = color.new(#315F2E, 20) var COLOR_CHIKOU_CROSS_POINT_BEAR = color.new(#802A1C, 20) var COLOR_CHIKOU_KUMO_BREAKOUT_BULL = color.new(#315F2E, 0) var COLOR_CHIKOU_KUMO_BREAKOUT_BEAR = color.new(#802A1C, 0) var COLOR_CHIKOU_HINT_BULL = color.new(#315F2E, 0) var COLOR_CHIKOU_HINT_BEAR = color.new(#802A1C, 0) var COLOR_SENKOU_CROSS_HINT_BULL = color.new(#315F2E, 0) var COLOR_SENKOU_CROSS_HINT_BEAR = color.new(#802A1C, 0) var COLOR_TENKAN_CROSS_BG = color.new(#f2931d, 90) var COLOR_CHIKOU_BREAKOUT_BG = color.new(#656565, 90) var COLOR_SENKOU_CROSS_BG = color.new(#7a73d8, 90) var COLOR_GAP_KUMO = color.new(#FCC02C, 97) var COLOR_RANGE_EDGE = color.new(#43A6F5, 30) var COLOR_RESISTANCE_PRICE_LINE = color.new(#e0f64d, 20) var COLOR_TRANSPARENT = color.new(#000000, 100) // HTF var _1 = input(true, "═════════ HTF ══════════") var config_baseHtf = input("D", "Base Higher Timeframe", type = input.resolution) var config_useHighestTf = input(true, "use Highest Timeframe (Kumo only)") var config_highestTf= input("W", "Highest Timeframe", type = input.resolution) var _2 = input(true, "═════════ Ichimoku ══════════") var config_tenkanSen = input(9, minval=1, title="Tenkan-Sen Bars") var config_kijunSen = input(26, minval=1, title="Kijun-Sen Bars") var config_senkouSpanB = input(52, minval=1, title="Senkou-Span B Bars") var config_chikouSpan = input(26, minval=1, title="Chikou-Span Offset") var config_senkouSpan = input(26, minval=1, title="Senkou-Span Offset") var _3 = input(true, "═════════ Smooth Line ══════════") var config_useSmooth = input(true, "enable smooth line") var config_smoothFactor = input(2, minval=2, title="smooth factor") var _4 = input(true, "═════════ MTF stuff ══════════") var config_autoSwitchToHtf = input(true, "avoid to refer lower resolution indicator") var config_avoidTooHighResolution = input(true, "avoid to refer too high resolution indicator") var config_useGapKumo = input(true, "use Gap Kumo") var _5 = input(true, "═════════ etc ══════════") var config_bullDetectBars = input(defval = 3, title = "bull detection min bar count", minval = 1) var config_rangeDetectBars = input(defval = 200, title = "range detection bar count", minval = 1) var config_recentBars = input(defval = 50, title = "recent bar count for SL", minval = 1) var config_atrLength = input(4, title = "Trailing stop ATR Length") var config_atrSlMult = input(1, title = "Trailing stop ATR Multiple factor", type=input.float) var config_atrEntryPaddingMult = input(0.5, title = "Entry padding ATR Multiple factor", type=input.float) var config_atrEntryPaddingLength = input(10, title = "Entry padding ATR Length") var config_extraEntryStopDetectBars = input(defval = 10, title = "Pyramiding entry recent detect bar count", minval = 1) var _6 = input(true, "═════════ Backtesting range ══════════") // From Date Inputs fromYear = input(defval = 2019, title = "From Year", minval = 1970) fromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12) fromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31) // To Date Inputs toYear = input(defval = 2021, title = "To Year", minval = 1970) toMonth = input(defval = 3, title = "To Month", minval = 1, maxval = 12) toDay = input(defval = 10, title = "To Day", minval = 1, maxval = 31) //============================================================================ // MTF Selection Framework // http://www.pinecoders.com/faq_and_code/#other-intervals-mtf //============================================================================ // β€”β€”β€”β€”β€” Converts current "timeframe.multiplier" plus the TF into minutes of type float. f_resInMinutes() => _resInMinutes = timeframe.multiplier * ( timeframe.isseconds ? 1. / 60. : timeframe.isminutes ? 1. : timeframe.isdaily ? 1440. : timeframe.isweekly ? 10080. : timeframe.ismonthly ? 43800. : na) // β€”β€”β€”β€”β€” Returns resolution of _resolution period in minutes. f_tfResInMinutes(_res) => // _res: resolution of any TF (in "timeframe.period" string format). security(syminfo.tickerid, _res, f_resInMinutes()) // β€”β€”β€”β€”β€” Given current resolution, returns next step of HTF. f_resNextStep(_res) => // _res: current TF in fractional minutes. _res <= 1 ? "15" : _res <= 5 ? "60" : _res <= 30 ? "240" : _res <= 60 ? "1D" : _res <= 360 ? "3D" : _res <= 1440 ? "1W" : _res <= 10080 ? "1M" : "12M" // β€”β€”β€”β€”β€” Returns a multiple of current resolution as a string in "timeframe.period" format usable with "security()". f_multipleOfRes(_res, _mult) => // _res: current resolution in minutes, in the fractional format supplied by f_resInMinutes() companion function. // _mult: Multiple of current TF to be calculated. // Convert current float TF in minutes to target string TF in "timeframe.period" format. _targetResInMin = _res * max(_mult, 1) // Find best string to express the resolution. _targetResInMin <= 0.083 ? "5S" : _targetResInMin <= 0.251 ? "15S" : _targetResInMin <= 0.501 ? "30S" : _targetResInMin <= 1440 ? tostring(round(_targetResInMin)) : _targetResInMin <= 43800 ? tostring(round(min(_targetResInMin / 1440, 365))) + "D" : tostring(round(min(_targetResInMin / 43800, 12))) + "M" // β€”β€”β€”β€”β€” Converts a resolution expressed in float minutes into a string usable by "security()". // See our FAQ & Code for an example of using this function: http://www.pinecoders.com/faq_and_code/#how-can-i-convert-a-resolution-in-float-minutes-into-a-string-usable-with-security f_resFromMinutes(_minutes) => _minutes <= 0.0167 ? "1S" : _minutes <= 0.0834 ? "5S" : _minutes <= 0.2500 ? "15S" : _minutes <= 0.5000 ? "30S" : _minutes <= 1440 ? tostring(round(_minutes)) : _minutes <= 43800 ? tostring(round(min(_minutes / 1440, 365))) + "D" : tostring(round(min(_minutes / 43800, 12))) + "M" // Returns the theoretical numbers of current chart bars in the given target HTF resolution (note that this number maybe very different from actual number on certain symbols). f_theoreticalDilationOf(_res) => // _res: resolution of any TF (in "timeframe.period" string format). f_tfResInMinutes(_res) / f_resInMinutes() // Returns the average number of current chart bars in the given target HTF resolution (this reflects the dataset's history). f_avgDilationOf(_res) => // _res: resolution of any TF (in "timeframe.period" string format). b = barssince(change(time(_res))) cumTotal = cum(b == 0 ? b[1] + 1 : 0) cumCount = cum(b == 0 ? 1 : 0) cumTotal / cumCount // β€”β€”β€”β€”β€” Print a label at end of chart. f_htfLabel(_txt, _y, _color, _offsetLabels) => _t = int(time + (f_resInMinutes() * _offsetLabels * 60000)) // Create the label on the dataset's first bar. var _lbl = label.new(_t, _y, _txt, xloc.bar_time, yloc.price, #00000000, label.style_none, color.gray, size.large) if barstate.islast // Rather than delete and recreate the label on every realtime bar update, // simply update the label's information; it's more efficient. label.set_xy(_lbl, _t, _y) label.set_text(_lbl, _txt) label.set_textcolor(_lbl, _color) // } //============================================================================ // utils, setup //============================================================================ // initialize var tenkanLine_baseHtf = 0.0 var kijunLine_baseHtf = 0.0 var senkouALine_baseHtf = 0.0 var senkouBLine_baseHtf = 0.0 var tenkanLine_highestTf = 0.0 var kijunLine_highestTf = 0.0 var senkouALine_highestTf = 0.0 var senkouBLine_highestTf = 0.0 var gapKumo_high = 0.0 var gapKumo_low = 0.0 f_isUsingHtf() => _current = f_resInMinutes() _target = f_tfResInMinutes(config_baseHtf) _current < _target f_isOverHtf() => _current = f_resInMinutes() _target = f_tfResInMinutes(config_baseHtf) _current > _target f_isOverHighestTf() => _current = f_resInMinutes() _target = f_tfResInMinutes(config_highestTf) _current >= _target f_shouldAvoidHighestTf(barsMultipiller) => // it the resolution was too high, requested candle sticks // hit the limit of trading view. // this function detects the limit config_avoidTooHighResolution and barsMultipiller > 150 var useSmooth = f_isUsingHtf() and config_useSmooth f_smooth(_series) => _f = config_smoothFactor // Tricky part. the lines that refers higher Timeframe got zig-zag // because the granularity of the value per bar is the same // inside the higher timeframe's one bar length. // This smooth factor blends the value with previous values using ema. _smoothed = ema(ema(ema(_series, _f), _f), _f) useSmooth ? _smoothed : _series lostPositionsInPrevBar = strategy.position_size == 0 and (strategy.position_size[0] != strategy.position_size[1]) // remember entry price var previousEntryPrice = hl2 //============================================================================ // entry quantity caliculation // wider SL = less quantities //============================================================================ f_calcQtyForInitialEntry(_percentage) => if _percentage < 1 10000 else if _percentage < 2 8000 else if _percentage < 3 6000 else 4000 f_calcQtyForExtraEntry(_percentage) => if _percentage < 1 5000 else if _percentage < 2 4000 else if _percentage < 3 3000 else 2000 //============================================================================ // candle actions //============================================================================ f_isUpDoji() => fullPriceHeight = high-low bodyPriceHeight = abs(close-open) (bodyPriceHeight < fullPriceHeight * 1/7) and (max(open, close) > (low + (high-low) * 2/3)) f_isDownDoji() => fullPriceHeight = high-low bodyPriceHeight = abs(close-open) (bodyPriceHeight < fullPriceHeight * 1/7) and (min(open, close) < (high - (high-low) * 2/3)) f_isLastCandleUp() => result = false (close > open) or f_isUpDoji() f_isLastCandleDown() => result = false (close < open) or f_isDownDoji() //============================================================================ // Ichimoku calcs //============================================================================ f_donchian(len) => avg(lowest(len), highest(len)) f_tenkan() => f_donchian(config_tenkanSen) f_kijun() => f_donchian(config_kijunSen) f_senkouA(_tenkan, _kijun) => avg(_tenkan, _kijun) f_senkouB() => f_donchian(config_senkouSpanB) barsMultipiller_baseHtf = f_isOverHtf() ? 1 : f_theoreticalDilationOf(config_baseHtf) barsMultipiller_highestTf = f_isOverHighestTf() ? 1 : f_theoreticalDilationOf(config_highestTf) shouldAvoidHighestTf = f_shouldAvoidHighestTf(barsMultipiller_highestTf) f_calcUseHighestTf() => _result = true if shouldAvoidHighestTf _result := false else if config_useHighestTf if f_isOverHighestTf() _result := false else _result := true _result var useHighestTf = f_calcUseHighestTf() senkouOffset = config_senkouSpan - 1 chikouOffset = -config_chikouSpan + 1 senkouOffset_baseHtf = round((config_senkouSpan - 1) * barsMultipiller_baseHtf) chikouOffset_baseHtf = round((config_chikouSpan - 1) * barsMultipiller_baseHtf) senkouOffsetForPlot_baseHtf = round(senkouOffset * barsMultipiller_baseHtf) chikouOffsetForPlot_baseHtf = round(-chikouOffset_baseHtf) senkouOffset_highestTf = useHighestTf ? round((config_senkouSpan - 1) * barsMultipiller_highestTf) : 0 chikouOffset_highestTf = useHighestTf ? round((config_chikouSpan - 1) * barsMultipiller_highestTf) : 0 senkouOffsetForPlot_highestTf = useHighestTf ? round(senkouOffset * barsMultipiller_highestTf) : 0 chikouOffsetForPlot_highestTf = useHighestTf ? round(-chikouOffset_highestTf) : 0 senkouSpanIndexDiff = senkouOffsetForPlot_highestTf - senkouOffsetForPlot_baseHtf // not sure why but it says negative index was detected if senkouSpanIndexDiff < 0 senkouSpanIndexDiff := 0 if not useHighestTf or not config_useGapKumo senkouSpanIndexDiff := 0 f_calcIchimoku_baseHtf() => _useCurrentRes = config_autoSwitchToHtf and f_isOverHtf() _tenkan = f_tenkan() _kijun = f_kijun() _senkouA = f_senkouA(_tenkan[0], _kijun[0]) _senkouB = f_senkouB() _htfTenkan = _useCurrentRes ? _tenkan : security(syminfo.tickerid, config_baseHtf, _tenkan) _htfKijun = _useCurrentRes ? _kijun : security(syminfo.tickerid, config_baseHtf, _kijun) _htfSenkouA = _useCurrentRes ? _senkouA : security(syminfo.tickerid, config_baseHtf, _senkouA) _htfSenkouB = _useCurrentRes ? _senkouB : security(syminfo.tickerid, config_baseHtf, _senkouB) [_htfTenkan, _htfKijun, _htfSenkouA, _htfSenkouB] f_calcIchimoku_highestTf() => _tenkan = f_tenkan() _kijun = f_kijun() _senkouA = f_senkouA(_tenkan[0], _kijun[0]) _senkouB = f_senkouB() _highestTfTenkan = useHighestTf ? security(syminfo.tickerid, config_highestTf, _tenkan) : _tenkan _highestTfKijun = useHighestTf ? security(syminfo.tickerid, config_highestTf, _kijun) : _kijun _highestTfSenkouA = useHighestTf ? security(syminfo.tickerid, config_highestTf, _senkouA) : _senkouA _highestTfSenkouB = useHighestTf ? security(syminfo.tickerid, config_highestTf, _senkouB) : _senkouB [_highestTfTenkan, _highestTfKijun, _highestTfSenkouA, _highestTfSenkouB] //-------------------------------------- // HTF Ichimoku values [_htfTenkan, _htfKijun, _htfSenkouA, _htfSenkouB] = f_calcIchimoku_baseHtf() tenkanLine_baseHtf := _htfTenkan kijunLine_baseHtf := _htfKijun senkouALine_baseHtf := _htfSenkouA senkouBLine_baseHtf := _htfSenkouB //-------------------------------------- // Highest TF Ichimoku values [_highestTfTenkan, _highestTfKijun, _highestTfSenkouA, _highestTfSenkouB] = f_calcIchimoku_highestTf() tenkanLine_highestTf := _highestTfTenkan kijunLine_highestTf := _highestTfKijun senkouALine_highestTf := _highestTfSenkouA senkouBLine_highestTf := _highestTfSenkouB f_calcIchimokuSignals_baseHtf() => var _chikouAboveCandle = false var _chikouBelowCandle = false var _chikouAboveKumo = false var _chikouBelowKumo = false _kumoColor_bull = senkouALine_baseHtf > senkouBLine_baseHtf _senkouCross_bull = crossover(senkouALine_baseHtf, senkouBLine_baseHtf) _senkouCross_bear = crossover(senkouBLine_baseHtf, senkouALine_baseHtf) _senkouSpanHigh = max(senkouALine_baseHtf[senkouOffset_baseHtf], senkouBLine_baseHtf[senkouOffset_baseHtf]) _senkouSpanLow = min(senkouALine_baseHtf[senkouOffset_baseHtf], senkouBLine_baseHtf[senkouOffset_baseHtf]) _chikouKumoHigh = max(senkouALine_baseHtf[senkouOffset_baseHtf+chikouOffset_baseHtf], senkouBLine_baseHtf[senkouOffset_baseHtf+chikouOffset_baseHtf]) _chikouKumoLow = min(senkouALine_baseHtf[senkouOffset_baseHtf+chikouOffset_baseHtf], senkouBLine_baseHtf[senkouOffset_baseHtf+chikouOffset_baseHtf]) _tenkanCross_bull = crossover(tenkanLine_baseHtf, kijunLine_baseHtf) _tenkanCross_bear = crossover(kijunLine_baseHtf, tenkanLine_baseHtf) _tenkanAboveKijun = tenkanLine_baseHtf > kijunLine_baseHtf _tenkanBelowKijun = tenkanLine_baseHtf < kijunLine_baseHtf _chikouAboveCandle := close > close[chikouOffset_baseHtf] _chikouBelowCandle := close < close[chikouOffset_baseHtf] _chikouCross_bull = _chikouAboveCandle and not _chikouAboveCandle[1] _chikouCross_bear = _chikouBelowCandle and not _chikouBelowCandle[1] _chikouAboveKumo := close > _chikouKumoHigh _chikouBelowKumo := close < _chikouKumoLow _currentInKumo = (_senkouSpanLow <= close) and (close <= _senkouSpanHigh) _currentTouchingKumo = not _currentInKumo and (((low <= _senkouSpanHigh) and (low >= _senkouSpanLow)) or ((high >= _senkouSpanLow) and (high <= _senkouSpanHigh))) _currentAboveKumo = close > _senkouSpanHigh _currentBelowKumo = close < _senkouSpanLow _chikouInKumo = (_chikouKumoLow <= close) and (close <= _chikouKumoHigh) _chikouTouchingKumo = not _chikouInKumo and (((low <= _chikouKumoHigh) and (low >= _chikouKumoLow)) or ((high >= _chikouKumoLow) and (high <= _chikouKumoHigh))) _chikouKumoBreakout_bull = _chikouAboveKumo and not _chikouAboveKumo[1] _chikouKumoBreakout_bear = _chikouBelowKumo and not _chikouBelowKumo[1] [_currentInKumo, _currentTouchingKumo, _kumoColor_bull, _senkouCross_bull, _senkouCross_bear, _senkouSpanHigh, _senkouSpanLow, _chikouKumoHigh, _chikouKumoLow, _chikouAboveCandle, _chikouBelowCandle, _tenkanCross_bull, _tenkanCross_bear, _tenkanAboveKijun, _tenkanBelowKijun, _chikouCross_bull, _chikouCross_bear, _chikouAboveKumo, _chikouBelowKumo, _chikouKumoBreakout_bull, _chikouKumoBreakout_bear, _currentAboveKumo, _currentBelowKumo, _chikouInKumo, _chikouTouchingKumo] f_calcIchimokuSignals_highestTf() => var _chikouAboveCandle = false var _chikouBelowCandle = false var _chikouAboveKumo = false var _chikouBelowKumo = false _kumoColor_bull = senkouALine_highestTf > senkouBLine_highestTf _senkouCross_bull = crossover(senkouALine_highestTf, senkouBLine_highestTf) _senkouCross_bear = crossover(senkouBLine_highestTf, senkouALine_highestTf) _senkouSpanCurrentHigh = max(senkouALine_highestTf[senkouOffset_highestTf], senkouBLine_highestTf[senkouOffset_highestTf]) _senkouSpanCurrentLow = min(senkouALine_highestTf[senkouOffset_highestTf], senkouBLine_highestTf[senkouOffset_highestTf]) _chikouKumoHigh = max(senkouALine_highestTf[senkouOffset_highestTf+chikouOffset_highestTf], senkouBLine_highestTf[senkouOffset_highestTf+chikouOffset_highestTf]) _chikouKumoLow = min(senkouALine_highestTf[senkouOffset_highestTf+chikouOffset_highestTf], senkouBLine_highestTf[senkouOffset_highestTf+chikouOffset_highestTf]) _tenkanCross_bull = crossover(tenkanLine_highestTf, kijunLine_highestTf) _tenkanCross_bear = crossover(kijunLine_highestTf, tenkanLine_highestTf) _chikouAboveCandle := close > close[chikouOffset_highestTf] _chikouBelowCandle := close < close[chikouOffset_highestTf] _chikouCross_bull = _chikouAboveCandle and not _chikouAboveCandle[1] _chikouCross_bear = _chikouBelowCandle and not _chikouBelowCandle[1] _chikouAboveKumo := close > _chikouKumoHigh _chikouBelowKumo := close < _chikouKumoLow _chikouKumoBreakout_bull = _chikouAboveKumo and not _chikouAboveKumo[1] _chikouKumoBreakout_bear = _chikouBelowKumo and not _chikouBelowKumo[1] _currentAboveKumo = close > _senkouSpanCurrentHigh _currentBelowKumo = close < _senkouSpanCurrentLow [_kumoColor_bull, _senkouCross_bull, _senkouCross_bear, _senkouSpanCurrentHigh, _senkouSpanCurrentLow, _chikouKumoHigh, _chikouKumoLow, _chikouAboveCandle, _chikouBelowCandle, _tenkanCross_bull, _tenkanCross_bear, _chikouCross_bull, _chikouCross_bear, _chikouAboveKumo, _chikouBelowKumo, _chikouKumoBreakout_bull, _chikouKumoBreakout_bear, _currentAboveKumo, _currentBelowKumo] f_calcGapKumo(_tf1_senkouA, _tf1_senkouB, _tf2_senkouA, _tf2_senkouB) => _max = max(_tf1_senkouA, _tf1_senkouB, _tf2_senkouA, _tf2_senkouB) _tf1IsHigher = (_tf1_senkouA == _max) or (_tf1_senkouB == _max) _kumoA_max = _tf1IsHigher ? max(_tf1_senkouA, _tf1_senkouB) : max(_tf2_senkouA, _tf2_senkouB) _kumoA_min = _tf1IsHigher ? min(_tf1_senkouA, _tf1_senkouB) : min(_tf2_senkouA, _tf2_senkouB) _kumoB_max = _tf1IsHigher ? max(_tf2_senkouA, _tf2_senkouB) : max(_tf1_senkouA, _tf1_senkouB) _kumoB_min = _tf1IsHigher ? min(_tf2_senkouA, _tf2_senkouB) : min(_tf1_senkouA, _tf1_senkouB) _kumoCrossed = false _gapKumo_high = max(_kumoA_max, _kumoB_max) _gapKumo_low = _gapKumo_high if _kumoA_max > _kumoB_max if _kumoA_min < _kumoB_max _kumoCrossed := true else _gapKumo_high := _kumoA_min _gapKumo_low := _kumoB_max else if _kumoB_min < _kumoA_max _kumoCrossed := true else _gapKumo_high := _kumoB_min _gapKumo_low := _kumoA_max [_kumoCrossed, _gapKumo_high, _gapKumo_low] //============================================================================ // calc Ichimoku values for plot //============================================================================ //-------------------------------------- // HTF Ichimoku signals [currentInKumo_baseHtf, _, kumoColor_bull_baseHtf, _, _, senkouSpanHigh_baseHtf, senkouSpanLow_baseHtf, _, _, chikouAboveCandle_baseHtf, chikouBelowCandle_baseHtf, _, _, tenkanAboveKijun_baseHtf, tenkanBelowKijun_baseHtf, _, _, chikouAboveKumo_baseHtf, chikouBelowKumo_baseHtf, _, _, currentAboveKumo_baseHtf, currentBelowKumo_baseHtf, _, _] = f_calcIchimokuSignals_baseHtf() //-------------------------------------- // Highest TF Ichimoku signals [kumoColor_bull_highestTf, senkouCross_bull_highestTf, senkouCross_bear_highestTf, senkouSpanHigh_highestTf, senkouSpanLow_highestTf, _, _, _, _, tenkanCross_bull_highestTf, tenkanCross_bear_highestTf, chikouCross_bull_highestTf, chikouCross_bear_highestTf, _, _, chikouKumoBreakout_bull_highestTf, chikouKumoBreakout_bear_highestTf, currentAboveKumo_highestTf, currentBelowKumo_highestTf] = f_calcIchimokuSignals_highestTf() //-------------------------------------- // smooth lines smooth_tenkanLine_baseHtf = f_smooth(tenkanLine_baseHtf) smooth_kijunLine_baseHtf = f_smooth(kijunLine_baseHtf) smooth_senkouALine_baseHtf = f_smooth(senkouALine_baseHtf) smooth_senkouBLine_baseHtf = f_smooth(senkouBLine_baseHtf) //smooth_tenkanLine_highestTf = f_smooth(tenkanLine_highestTf) //smooth_kijunLine_highestTf = f_smooth(kijunLine_highestTf) smooth_senkouALine_highestTf = f_smooth(senkouALine_highestTf) smooth_senkouBLine_highestTf = f_smooth(senkouBLine_highestTf) //-------------------------------------- // gap kumo //max_bars_back(senkouALine_highestTf, 600) //max_bars_back(senkouBLine_highestTf, 600) [_, _gapKumo_high, _gapKumo_low] = f_calcGapKumo( senkouALine_baseHtf, senkouBLine_baseHtf, senkouALine_highestTf[senkouSpanIndexDiff], senkouBLine_highestTf[senkouSpanIndexDiff]) gapKumo_high := _gapKumo_high gapKumo_low := _gapKumo_low smooth_gapKumo_high = f_smooth(gapKumo_high) smooth_gapKumo_low = f_smooth(gapKumo_low) //============================================================================ // plot stuffs //============================================================================ // gap kumo val_gapKumo_high = useHighestTf and config_useGapKumo ? smooth_gapKumo_high : na val_gapKumo_low = useHighestTf and config_useGapKumo ? smooth_gapKumo_low : na plot_gapKumo_high = plot(val_gapKumo_high, offset=senkouOffsetForPlot_baseHtf, color=COLOR_TRANSPARENT, transp=0, linewidth=1, title="Gap Kumo High") plot_gapKumo_low = plot(val_gapKumo_low, offset=senkouOffsetForPlot_baseHtf, color=COLOR_TRANSPARENT, transp=0, linewidth=1, title="Gap Kumo LOW") fill(plot_gapKumo_high, plot_gapKumo_low, color=COLOR_GAP_KUMO, transp=0, title="Gap Kumo") // kumo HighestTF plotVal_senkouA_highestTf = useHighestTf ? smooth_senkouALine_highestTf : na plotVal_senkouB_highestTf = useHighestTf ? smooth_senkouBLine_highestTf : na color_kumo_highestTf = kumoColor_bull_highestTf ? COLOR_KUMO_HIGHESTTF_BULL : COLOR_KUMO_HIGHESTTF_BEAR plot_senkouA_highestTf = plot(plotVal_senkouA_highestTf, offset=senkouOffsetForPlot_highestTf, color=COLOR_SENKOUA_HIGHESTTF, transp=0, linewidth=1, title="Highest TFSenkou-Span A") plot_senkouB_highestTf = plot(plotVal_senkouB_highestTf, offset=senkouOffsetForPlot_highestTf, color=COLOR_SENKOUB_HIGHESTTF, transp=0, linewidth=1, title="Highest TFSenkou-Span B") fill(plot_senkouA_highestTf, plot_senkouB_highestTf, color=color_kumo_highestTf, transp=0, title="Highest TF Kumo") // kumo HTF color_kumo_baseHtf = kumoColor_bull_baseHtf ? COLOR_KUMO_BASEHTF_BULL : COLOR_KUMO_BASEHTF_BEAR plot_senkouA_baseHtf = plot(smooth_senkouALine_baseHtf, offset=senkouOffsetForPlot_baseHtf, color=COLOR_SENKOUA_BASEHTF, transp=0, linewidth=1, title="Base HTF: Senkou-Span A") plot_senkouB_baseHtf = plot(smooth_senkouBLine_baseHtf, offset=senkouOffsetForPlot_baseHtf, color=COLOR_SENKOUB_BASEHTF, transp=0, linewidth=1, title="Base HTF: Senkou-Span B") fill(plot_senkouA_baseHtf, plot_senkouB_baseHtf, color=color_kumo_baseHtf, transp=0, title="Base HTF Kumo") // chikou plot(close, offset=chikouOffsetForPlot_baseHtf, color=COLOR_CHIKOU, linewidth=1, transp=0, title="Chikou-Span") // tenkan & kijun plot(smooth_tenkanLine_baseHtf, color=COLOR_TENKAN, linewidth=1, transp=0, title="Tenkan-Sen") plot(smooth_kijunLine_baseHtf, color=COLOR_KIJUN, linewidth=3, transp=0, title="Kijun-Sen") //============================================================================ // backtest duration //============================================================================ // Calculate start/end date and time condition startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00) finishDate = timestamp(toYear, toMonth, toDay, 00, 00) //============================================================================ // bullish / bearish detection //============================================================================ var bullish = false var bearish = false // detect bullish or bearish by many incidents bullish := kumoColor_bull_baseHtf and chikouAboveCandle_baseHtf and tenkanAboveKijun_baseHtf and chikouAboveKumo_baseHtf and currentAboveKumo_baseHtf and currentAboveKumo_highestTf bearish := not kumoColor_bull_baseHtf and chikouBelowCandle_baseHtf and tenkanBelowKijun_baseHtf and chikouBelowKumo_baseHtf and currentBelowKumo_baseHtf and currentBelowKumo_highestTf // calc continuous bullish or bearish f_isContinuousBull() => inTrend = 0 for i = 0 to (config_bullDetectBars-1) if bullish[i] inTrend := inTrend + 1 inTrend == config_bullDetectBars f_isContinuousBear() => inTrend = 0 for i = 0 to (config_bullDetectBars-1) if bearish[i] inTrend := inTrend + 1 inTrend == config_bullDetectBars continuousBull = f_isContinuousBull() continuousBear = f_isContinuousBear() //============================================================================ // MACD //============================================================================ f_isMacdUpTrend() => [_macdLine, _signalLine, _] = macd(close, 12, 26, 9) _upTrend = _macdLine > _signalLine // calc macd for entry macdUpTrend = f_isMacdUpTrend() macdDownTrend = not macdUpTrend //============================================================================ // recent high / low //============================================================================ f_calcRecentHigh() => startIndex = 1 highest = max(open[startIndex], close[startIndex]) for i = startIndex to (config_recentBars - 1) current = max(open[i], close[i]) if highest < current highest := current highest f_calcRecentLow() => startIndex = 1 lowest = min(open[startIndex], close[startIndex]) for i = startIndex to (config_recentBars - 1) current = min(open[i], close[i]) if lowest > current lowest := current lowest recentHigh = f_calcRecentHigh() recentLow = f_calcRecentLow() //============================================================================ // ATR based stuff //============================================================================ entryPadding = config_atrEntryPaddingMult * atr(config_atrEntryPaddingLength) sl_val = config_atrSlMult * atr(config_atrLength) atrSl_long = low - sl_val atrSl_short = high + sl_val //============================================================================ // Kumo based SL //============================================================================ kumoBasedSlLong = (senkouSpanHigh_baseHtf + atrSl_long) / 2 kumoBasedSlShort = (senkouSpanLow_baseHtf + atrSl_short) / 2 //============================================================================ // Mixed SL //============================================================================ var initialEntryTpPrice_long = hl2 var initialEntryTpPrice_short = hl2 var mixedTrailingSl_long = hl2 var mixedTrailingSl_short = hl2 mixedSlLong = min(atrSl_long, kumoBasedSlLong, recentLow) mixedSlShort = max(atrSl_short, kumoBasedSlShort, recentHigh) //plot(mixedSlLong, color=color.green, linewidth=2) //plot(mixedSlShort, color=color.red, linewidth=2) //============================================================================ // Range Edge caliculation //============================================================================ // calc range edge f_calcRangeEdge_high() => //highest = high[3] highest = max(open[3], close[3]) for i = 4 to (config_rangeDetectBars - 1) //current = high[i] current = max(open[i], close[i]) if highest < current highest := current highest f_calcRangeEdge_low() => //lowest = low[3] lowest = min(open[3], close[3]) for i = 4 to (config_rangeDetectBars - 1) //current = low[i] current = min(open[i], close[i]) if lowest > current lowest := current lowest entryLimitHigh = f_calcRangeEdge_high() entryLimitLow = f_calcRangeEdge_low() plot(entryLimitHigh, color=COLOR_RANGE_EDGE, linewidth=1) plot(entryLimitLow, color=COLOR_RANGE_EDGE, linewidth=1) //============================================================================ // entry timing judge //============================================================================ f_trendStatsChanged() => var trendStats = 0 var kumoBull = false var kumoBear = false var kumoRanged = false kumoBull := currentAboveKumo_baseHtf and currentAboveKumo_highestTf kumoBear := currentBelowKumo_baseHtf and currentBelowKumo_highestTf kumoRanged := not kumoBull and not kumoBear if kumoRanged trendStats := 0 // respect recent bullish or bearish if kumoBull[1] or kumoBull[2] or kumoBull[3] or kumoBear[1] or kumoBear[2] or kumoBear[3] trendStats := trendStats[1] if kumoBull trendStats := 1 if kumoBear trendStats := -1 trendStats[1] != trendStats[0] trendStatsChanged = f_trendStatsChanged() var isFirstEntry = true var resistancePrice = hl2 var rangeBreakSignalDetected = false var rangeBreakMacdReversalDetected = false var rangeBreakConfirmed = false //-------------------------------------- // reset flags // if trend stats changed, reset flags if trendStatsChanged isFirstEntry := true rangeBreakSignalDetected := false rangeBreakMacdReversalDetected := false rangeBreakConfirmed := false else // if has no positions if strategy.position_size == 0 isFirstEntry := isFirstEntry[1] // if lost positions in prev bar if lostPositionsInPrevBar rangeBreakSignalDetected := false rangeBreakConfirmed := false else rangeBreakSignalDetected := rangeBreakSignalDetected[1] rangeBreakConfirmed := rangeBreakConfirmed[1] // if has any position else isFirstEntry := false // no more first entry resistancePrice := hl2 // no resistance price //-------------------------------------- // 1st entry confirmation var firstReverseAfterTrendChange = false var trendConfirmed = false // this operation is for the 1st entry if isFirstEntry if bullish // wait for the short reversal for confirmation if not firstReverseAfterTrendChange and not rangeBreakMacdReversalDetected if macdDownTrend rangeBreakMacdReversalDetected := true if rangeBreakMacdReversalDetected if macdUpTrend trendConfirmed := true if bearish if not firstReverseAfterTrendChange and not rangeBreakMacdReversalDetected if macdUpTrend rangeBreakMacdReversalDetected := true if rangeBreakMacdReversalDetected if macdDownTrend trendConfirmed := true else trendConfirmed := false firstReverseAfterTrendChange := false if (bullish[0] != bullish[1]) or (bearish[0] != bearish[1]) trendConfirmed := false // plot trend confirmation if (trendConfirmed[0] == true) and (trendConfirmed[1] == false) if bullish label.new(bar_index, low, 'Trend Confirmed', style=label.style_triangleup, size=size.tiny, color=#ffffff, textcolor=#ffffff) else label.new(bar_index, high, 'Trend Confirmed', style=label.style_triangledown, size=size.tiny, color=#ffffff, textcolor=#ffffff) //-------------------------------------- // later entry confirmation if strategy.position_size == 0 // this operation is for later entry if isFirstEntry resistancePrice := hl2 else // if range break was detected, set flag if not rangeBreakSignalDetected and continuousBull and entryLimitHigh < close rangeBreakSignalDetected := true if not rangeBreakSignalDetected and continuousBear and close < entryLimitLow rangeBreakSignalDetected := true // after range break, wait for short MACD reversal. // after this confirmation, make stop entry if rangeBreakSignalDetected if senkouSpanHigh_baseHtf < close resistancePrice := entryLimitHigh if macdDownTrend rangeBreakConfirmed := true if senkouSpanLow_baseHtf > close resistancePrice := entryLimitLow if macdUpTrend rangeBreakConfirmed := true // plot rangebreak detection if (rangeBreakSignalDetected[0] == true) and (rangeBreakSignalDetected[1] == false) if bullish label.new(bar_index, low, 'Rangebreak detected', style=label.style_triangleup, size=size.tiny, color=#ffffff, textcolor=#ffffff) else label.new(bar_index, high, 'Rangebreak detected', style=label.style_triangledown, size=size.tiny, color=#ffffff, textcolor=#ffffff) // plot resistance price line resitancePriceColor = rangeBreakConfirmed and strategy.position_size == 0 ? COLOR_RESISTANCE_PRICE_LINE : COLOR_TRANSPARENT plot(resistancePrice, linewidth=4, color=resitancePriceColor) //============================================================================ // Pyramiding entry judge //============================================================================ f_calcExtraEntryStopForShort() => startIndex = 2 highest = max(open[startIndex], close[startIndex]) for i = startIndex to (config_extraEntryStopDetectBars - 1) current = max(open[i], close[i]) if highest < current highest := current highest f_calcExtraEntryStopForLong() => startIndex = 2 lowest = min(open[startIndex], close[startIndex]) for i = startIndex to (config_extraEntryStopDetectBars - 1) current = min(open[i], close[i]) if lowest > current lowest := current lowest extraEntryStopLong = f_calcExtraEntryStopForLong() + entryPadding extraEntryStopShort = f_calcExtraEntryStopForShort() - entryPadding extraEntryStop = bullish ? extraEntryStopLong : bearish ? extraEntryStopShort : hl2 extraEntryStopColor = (bullish or bearish) ? color.green : COLOR_TRANSPARENT // plot as line plot(extraEntryStop, color=extraEntryStopColor, linewidth=2) //============================================================================ // entry, TP, SL //============================================================================ shouldMakeEntryLong = continuousBull and ((isFirstEntry and trendConfirmed) or (rangeBreakConfirmed and close > resistancePrice)) shouldMakeEntryShort = continuousBear and ((isFirstEntry and trendConfirmed) or (rangeBreakConfirmed and close < resistancePrice)) // TP caliculation if strategy.position_size == 0 initialEntryTpPrice_long := entryLimitHigh + (hl2 - extraEntryStopLong) initialEntryTpPrice_short := entryLimitLow - (extraEntryStopShort - hl2) // SL caliculation mixedTrailingSl_long := if ((strategy.position_size == 0) and shouldMakeEntryLong) or ((strategy.position_size > 0) and (mixedTrailingSl_long < mixedSlLong)) mixedSlLong else if (strategy.position_size == 0) or (strategy.position_size < 0) hl2 else mixedTrailingSl_long[1] mixedTrailingSl_short := if ((strategy.position_size == 0) and shouldMakeEntryShort) or ((strategy.position_size < 0) and (mixedTrailingSl_short > mixedSlShort)) mixedSlShort else if (strategy.position_size == 0) or (strategy.position_size > 0) hl2 else mixedTrailingSl_short[1] // final entry price initialEntryStopPrice_long = entryLimitHigh + entryPadding initialEntryStopPrice_short = entryLimitLow - entryPadding extraEntryLimitPrice_long = extraEntryStopLong extraEntryLimitPrice_short = extraEntryStopShort extraEntryTpPrice_long = entryLimitHigh + entryPadding extraEntryTpPrice_short = entryLimitLow - entryPadding //============================================================================ // Quantitiy caliculation //============================================================================ var initialQty = 0 slPercentage = bullish ? abs(mixedTrailingSl_long-hl2)/hl2*100 : abs(mixedTrailingSl_short-hl2)/hl2*100 qtyForInitialEntry = f_calcQtyForInitialEntry(slPercentage) qtyForExtraEntry = f_calcQtyForExtraEntry(slPercentage) //============================================================================ // Pyramiding judge //============================================================================ var anyTpTriggered = false var hasAnyPositions = false if strategy.position_size != 0 and strategy.position_size[1] == 0 hasAnyPositions := true if strategy.position_size == 0 and strategy.position_size[1] != 0 hasAnyPositions := false anyTpTriggered := false if hasAnyPositions and not anyTpTriggered and (abs(strategy.position_size) < initialQty) anyTpTriggered := true pyramidingReady = (anyTpTriggered and bullish and (extraEntryStopLong > previousEntryPrice) and f_isLastCandleUp()) or (anyTpTriggered and bearish and (extraEntryStopShort < previousEntryPrice) and f_isLastCandleDown()) //============================================================================ // make entries //============================================================================ if (time >= startDate and time <= finishDate) if strategy.position_size == 0 if shouldMakeEntryLong initialQty := qtyForInitialEntry strategy.entry(id="Long", long=true, stop=initialEntryStopPrice_long, qty=initialQty) previousEntryPrice := entryLimitHigh if shouldMakeEntryShort initialQty := qtyForInitialEntry strategy.entry(id="Short", long=false, stop=initialEntryStopPrice_short, qty=initialQty) previousEntryPrice := entryLimitLow // Long pyramiding if (strategy.position_size > 0) and pyramidingReady previousEntryPrice := extraEntryStopLong strategy.entry(id="LongExtra", long=true, limit=extraEntryLimitPrice_long, qty=qtyForExtraEntry) else strategy.cancel(id="LongExtra") // Short pyramiding if (strategy.position_size < 0) and pyramidingReady previousEntryPrice := extraEntryStopShort strategy.entry(id="ShortExtra", long=false, limit=extraEntryLimitPrice_short, qty=qtyForExtraEntry) else strategy.cancel(id="ShortExtra") // cancel stop entries if not continuousBull strategy.cancel(id="Long") strategy.cancel(id="LongExtra") if not continuousBear strategy.cancel(id="Short") strategy.cancel(id="ShortExtra") // TP, SL strategy.exit('Long-TP', 'Long', stop=mixedTrailingSl_long, limit=initialEntryTpPrice_long, qty=(initialQty/2)) strategy.exit('Long-SL', 'Long', stop=mixedTrailingSl_long) strategy.exit('LongExtra-SL/TP', 'LongExtra', stop=mixedTrailingSl_long, limit=extraEntryTpPrice_long) strategy.exit('Short-TP', 'Short', stop=mixedTrailingSl_short, limit=initialEntryTpPrice_short, qty=(initialQty/2)) strategy.exit('Short-SL', 'Short', stop=mixedTrailingSl_short) strategy.exit('ShortExtra-SL/TP', 'ShortExtra', stop=mixedTrailingSl_short, limit=extraEntryTpPrice_short) //============================================================================ // plot SL, TP //============================================================================ sl = if strategy.position_size > 0 mixedTrailingSl_long else if strategy.position_size < 0 mixedTrailingSl_short else na tp = if hasAnyPositions and not anyTpTriggered strategy.position_size > 0 ? initialEntryTpPrice_long : initialEntryTpPrice_short else na plot(sl, color=color.red, style=plot.style_cross, linewidth=2, title="SL") plot(tp, color=color.blue, style=plot.style_cross, linewidth=2, title="T") //============================================================================ // debug //============================================================================ // continuous bull / bear check value_bgcolor = continuousBull ? color.green : continuousBear ? color.red: color.new(#000000, 100) // MACD up or down check //value_bgcolor = macdUpTrend ? color.green : color.red // both kumo bull //value_bgcolor = (kumoColor_bull_baseHtf and kumoColor_bull_highestTf) ? color.green: // (not kumoColor_bull_baseHtf and not kumoColor_bull_highestTf) ? color.red: color.new(#000000, 100) // doji //dojiUp = bullish and f_isUpDoji() //dojiDown = bearish and f_isDownDoji() //value_bgcolor = dojiUp ? color.green : // dojiDown ? color.red : // COLOR_TRANSPARENT //value_bgcolor = f_isLastCandleUp() ? color.green : COLOR_TRANSPARENT //value_bgcolor = pyramidingReady ? color.green : COLOR_TRANSPARENT bgcolor(value_bgcolor, transp=95)
Crypto rsi cci mf stoch rsi oscillators all in one strategy
https://www.tradingview.com/script/2juMhHY0-Crypto-rsi-cci-mf-stoch-rsi-oscillators-all-in-one-strategy/
SoftKill21
https://www.tradingview.com/u/SoftKill21/
281
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/ // Β© SoftKill21 //@version=4 strategy(title="something", initial_capital = 1000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=0.03, pyramiding=1 ) length = input(title="Length", type=input.integer, defval=100, minval=1, maxval=2000) src = hlc3 upper = sum(volume * (change(src) <= 0 ? 0 : src), length) lower = sum(volume * (change(src) >= 0 ? 0 : src), length) _rsi(upper, lower) => if lower == 0 100 if upper == 0 0 100.0 - (100.0 / (1.0 + upper / lower)) mf = _rsi(upper, lower) up = rma(max(change(src), 0), length) down = rma(-min(change(src), 0), length) rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down)) plot(rsi, "RSI", color=#8E1599) plot(mf, "MF", color=#459915) hline(50, title="zap", color=#c0c0c0) ma = sma(src, length) cci = (src - ma) / (0.015 * dev(src, length)) //plot(cci, "CCI", color=#996A15) smoothK = input(1, "K", minval=1) smoothD = input(1, "D", minval=1) rsi1 = rsi(src, length) k = sma(stoch(rsi1, rsi1, rsi1, length), smoothK) d = sma(k, smoothD) plot(k, "K", color=#0094FF) plot(d, "D", color=#FF6A00) avg = (rsi + mf + cci + k + d)/5 long = rsi > 50 and mf > 50 and cci >50 and (k > 50 or d>50) short= rsi<49 and mf<49 and cci<0 and (k<50 or d<50) // long= avg > 100 // short=avg<0 plot(avg) strategy.entry('long',1,when=long) strategy.close("long",when=short) //strategy.entry('short',0,when=short) //strategy.close("short",when=exitshort)
Delta-RSI Strategy (with filters)
https://www.tradingview.com/script/0OdCms2T-Delta-RSI-Strategy-with-filters/
tbiktag
https://www.tradingview.com/u/tbiktag/
2,403
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/ // Β© tbiktag // // Delta-RSI Oscillator Strategy With Filters // // This is a version of the Delta-RSI Oscillator Strategy compatible with // the Strategy Tester. // // This version also allows filtering the trade signals generated by Delts-RSI // by means of volatility (defined by ATR), relative volume and RSI(14). // // Delta-RSI (Β© tbiktag) is a smoothed time derivative of the RSI designed // as a momentum indicator. For the original publication, see link below: // https://www.tradingview.com/script/OXQVFTQD-Delta-RSI-Oscillator/ // // D-RSI model parameters: // RSI Length: The timeframe of the RSI that serves as an input to D-RSI. // Frame Length: The length of the lookback frame used for local regression. // Polynomial Order: The order of the local polynomial function used to interpolate // the RSI. // Trade signals are generated based on three optional conditions: // - Zero-crossing: bullish when D-RSI crosses zero from negative to positive // values (bearish otherwise) // - Signal Line Crossing: bullish when D-RSI crosses from below to above the signal // line (bearish otherwise) // - Direction Change: bullish when D-RSI was negative and starts ascending // (bearish otherwise) // //@version=4 strategy(title="Delta-RSI Strategy with Filters", shorttitle = "D-RSI with filters", overlay = true) // ---Subroutines--- matrix_get(_A,_i,_j,_nrows) => // Get the value of the element of an implied 2d matrix //input: // _A :: array: pseudo 2d matrix _A = [[column_0],[column_1],...,[column_(n-1)]] // _i :: integer: row number // _j :: integer: column number // _nrows :: integer: number of rows in the implied 2d matrix array.get(_A,_i+_nrows*_j) matrix_set(_A,_value,_i,_j,_nrows) => // Set a value to the element of an implied 2d matrix //input: // _A :: array, changed on output: pseudo 2d matrix _A = [[column_0],[column_1],...,[column_(n-1)]] // _value :: float: the new value to be set // _i :: integer: row number // _j :: integer: column number // _nrows :: integer: number of rows in the implied 2d matrix array.set(_A,_i+_nrows*_j,_value) transpose(_A,_nrows,_ncolumns) => // Transpose an implied 2d matrix // input: // _A :: array: pseudo 2d matrix _A = [[column_0],[column_1],...,[column_(n-1)]] // _nrows :: integer: number of rows in _A // _ncolumns :: integer: number of columns in _A // output: // _AT :: array: pseudo 2d matrix with implied dimensions: _ncolums x _nrows var _AT = array.new_float(_nrows*_ncolumns,0) for i = 0 to _nrows-1 for j = 0 to _ncolumns-1 matrix_set(_AT, matrix_get(_A,i,j,_nrows),j,i,_ncolumns) _AT multiply(_A,_B,_nrowsA,_ncolumnsA,_ncolumnsB) => // Calculate scalar product of two matrices // input: // _A :: array: pseudo 2d matrix // _B :: array: pseudo 2d matrix // _nrowsA :: integer: number of rows in _A // _ncolumnsA :: integer: number of columns in _A // _ncolumnsB :: integer: number of columns in _B // output: // _C:: array: pseudo 2d matrix with implied dimensions _nrowsA x _ncolumnsB var _C = array.new_float(_nrowsA*_ncolumnsB,0) int _nrowsB = _ncolumnsA float elementC= 0.0 for i = 0 to _nrowsA-1 for j = 0 to _ncolumnsB-1 elementC := 0 for k = 0 to _ncolumnsA-1 elementC := elementC + matrix_get(_A,i,k,_nrowsA)*matrix_get(_B,k,j,_nrowsB) matrix_set(_C,elementC,i,j,_nrowsA) _C vnorm(_X,_n) => //Square norm of vector _X with size _n float _norm = 0.0 for i = 0 to _n-1 _norm := _norm + pow(array.get(_X,i),2) sqrt(_norm) qr_diag(_A,_nrows,_ncolumns) => //QR Decomposition with Modified Gram-Schmidt Algorithm (Column-Oriented) // input: // _A :: array: pseudo 2d matrix _A = [[column_0],[column_1],...,[column_(n-1)]] // _nrows :: integer: number of rows in _A // _ncolumns :: integer: number of columns in _A // output: // _Q: unitary matrix, implied dimenstions _nrows x _ncolumns // _R: upper triangular matrix, implied dimansions _ncolumns x _ncolumns var _Q = array.new_float(_nrows*_ncolumns,0) var _R = array.new_float(_ncolumns*_ncolumns,0) var _a = array.new_float(_nrows,0) var _q = array.new_float(_nrows,0) float _r = 0.0 float _aux = 0.0 //get first column of _A and its norm: for i = 0 to _nrows-1 array.set(_a,i,matrix_get(_A,i,0,_nrows)) _r := vnorm(_a,_nrows) //assign first diagonal element of R and first column of Q matrix_set(_R,_r,0,0,_ncolumns) for i = 0 to _nrows-1 matrix_set(_Q,array.get(_a,i)/_r,i,0,_nrows) if _ncolumns != 1 //repeat for the rest of the columns for k = 1 to _ncolumns-1 for i = 0 to _nrows-1 array.set(_a,i,matrix_get(_A,i,k,_nrows)) for j = 0 to k-1 //get R_jk as scalar product of Q_j column and A_k column: _r := 0 for i = 0 to _nrows-1 _r := _r + matrix_get(_Q,i,j,_nrows)*array.get(_a,i) matrix_set(_R,_r,j,k,_ncolumns) //update vector _a for i = 0 to _nrows-1 _aux := array.get(_a,i) - _r*matrix_get(_Q,i,j,_nrows) array.set(_a,i,_aux) //get diagonal R_kk and Q_k column _r := vnorm(_a,_nrows) matrix_set(_R,_r,k,k,_ncolumns) for i = 0 to _nrows-1 matrix_set(_Q,array.get(_a,i)/_r,i,k,_nrows) [_Q,_R] pinv(_A,_nrows,_ncolumns) => //Pseudoinverse of matrix _A calculated using QR decomposition // Input: // _A:: array: implied as a (_nrows x _ncolumns) matrix //. _A = [[column_0],[column_1],...,[column_(_ncolumns-1)]] // Output: // _Ainv:: array implied as a (_ncolumns x _nrows) matrix // _A = [[row_0],[row_1],...,[row_(_nrows-1)]] // ---- // First find the QR factorization of A: A = QR, // where R is upper triangular matrix. // Then _Ainv = R^-1*Q^T. // ---- [_Q,_R] = qr_diag(_A,_nrows,_ncolumns) _QT = transpose(_Q,_nrows,_ncolumns) // Calculate Rinv: var _Rinv = array.new_float(_ncolumns*_ncolumns,0) float _r = 0.0 matrix_set(_Rinv,1/matrix_get(_R,0,0,_ncolumns),0,0,_ncolumns) if _ncolumns != 1 for j = 1 to _ncolumns-1 for i = 0 to j-1 _r := 0.0 for k = i to j-1 _r := _r + matrix_get(_Rinv,i,k,_ncolumns)*matrix_get(_R,k,j,_ncolumns) matrix_set(_Rinv,_r,i,j,_ncolumns) for k = 0 to j-1 matrix_set(_Rinv,-matrix_get(_Rinv,k,j,_ncolumns)/matrix_get(_R,j,j,_ncolumns),k,j,_ncolumns) matrix_set(_Rinv,1/matrix_get(_R,j,j,_ncolumns),j,j,_ncolumns) // _Ainv = multiply(_Rinv,_QT,_ncolumns,_ncolumns,_nrows) _Ainv norm_rmse(_x, _xhat) => // Root Mean Square Error normalized to the sample mean // _x. :: array float, original data // _xhat :: array float, model estimate // output // _nrmse:: float float _nrmse = 0.0 if array.size(_x) != array.size(_xhat) _nrmse := na else int _N = array.size(_x) float _mse = 0.0 for i = 0 to _N-1 _mse := _mse + pow(array.get(_x,i) - array.get(_xhat,i),2)/_N _xmean = array.sum(_x)/_N _nrmse := sqrt(_mse) /_xmean _nrmse diff(_src,_window,_degree) => // Polynomial differentiator // input: // _src:: input series // _window:: integer: wigth of the moving lookback window // _degree:: integer: degree of fitting polynomial // output: // _diff :: series: time derivative // _nrmse:: float: normalized root mean square error // // Vandermonde matrix with implied dimensions (window x degree+1) // Linear form: J = [ [z]^0, [z]^1, ... [z]^degree], // with z = [ (1-window)/2 to (window-1)/2 ] var _J = array.new_float(_window*(_degree+1),0) for i = 0 to _window-1 for j = 0 to _degree matrix_set(_J,pow(i,j),i,j,_window) // Vector of raw datapoints: var _Y_raw = array.new_float(_window,na) for j = 0 to _window-1 array.set(_Y_raw,j,_src[_window-1-j]) // Calculate polynomial coefficients which minimize the loss function _C = pinv(_J,_window,_degree+1) _a_coef = multiply(_C,_Y_raw,_degree+1,_window,1) // For first derivative, approximate the last point (i.e. z=window-1) by float _diff = 0.0 for i = 1 to _degree _diff := _diff + i*array.get(_a_coef,i)*pow(_window-1,i-1) // Calculates data estimate (needed for rmse) _Y_hat = multiply(_J,_a_coef,_window,_degree+1,1) float _nrmse = norm_rmse(_Y_raw,_Y_hat) [_diff,_nrmse] /// --- main --- degree = input(title="Polynomial Order", group = "Model Parameters:", inline = "linepar1", type = input.integer, defval=3, minval = 1) rsi_l = input(title = "RSI Length", group = "Model Parameters:", inline = "linepar1", type = input.integer, defval = 21, minval = 1, tooltip="The period length of RSI that is used as input.") window = input(title="Length ( > Order)", group = "Model Parameters:", inline = "linepar2", type = input.integer, defval=50, minval = 2) signalLength = input(title="Signal Length", group = "Model Parameters:", inline = "linepar2", type=input.integer, defval=9, tooltip="The signal line is a EMA of the D-RSI time series.") islong = input(title = "Long", group = "Allowed Entries:", inline = "lineent",type = input.bool, defval = true) isshort = input(title = "Short", group = "Allowed Entries:", inline = "lineent", type = input.bool, defval= true) buycond = input(title="Buy", group = "Entry and Exit Conditions:", inline = "linecond",type = input.string, defval="Signal Line Crossing", options=["Zero-Crossing", "Signal Line Crossing","Direction Change"]) sellcond = input(title="Sell", group = "Entry and Exit Conditions:", inline = "linecond",type = input.string, defval="Signal Line Crossing", options=["Zero-Crossing", "Signal Line Crossing","Direction Change"]) endcond = input(title="Exit", group = "Entry and Exit Conditions:", inline = "linecond",type = input.string, defval="Signal Line Crossing", options=["Zero-Crossing", "Signal Line Crossing","Direction Change"]) filterlong =input(title = "Long Entries", inline = 'linefilt', group = 'Apply Filters to', type = input.bool, defval = true) filtershort =input(title = "Short Enties", inline = 'linefilt', group = 'Apply Filters to', type = input.bool, defval = true) filterend =input(title = "Exits", inline = 'linefilt', group = 'Apply Filters to', type = input.bool, defval = true) usevol =input(title = "", inline = 'linefiltvol', group = 'Relative Volume Filter:', type = input.bool, defval = false) rvol = input(title = "Volume >", inline = 'linefiltvol', group = 'Relative Volume Filter:', type = input.integer, defval = 1) len_vol = input(title = "Avg. Volume Over Period", inline = 'linefiltvol', group = 'Relative Volume Filter:', type = input.integer, defval = 30, minval = 1, tooltip="The current volume must be greater than N times the M-period average volume.") useatr =input(title = "", inline = 'linefiltatr', group = 'Volatility Filter:', type = input.bool, defval = false) len_atr1 = input(title = "ATR", inline = 'linefiltatr', group = 'Volatility Filter:', type = input.integer, defval = 5, minval = 1) len_atr2 = input(title = "> ATR", inline = 'linefiltatr', group = 'Volatility Filter:', type = input.integer, defval = 30, minval = 1, tooltip="The N-period ATR must be greater than the M-period ATR.") usersi =input(title = "", inline = 'linersi', group = 'Overbought/Oversold Filter:', type = input.bool, defval = false) rsitrhs1 = input(title = "", inline = 'linersi', group = 'Overbought/Oversold Filter:', type = input.integer, defval = 0, minval=0, maxval=100) rsitrhs2 = input(title = "< RSI (14) <", inline = 'linersi', group = 'Overbought/Oversold Filter:', type = input.integer, defval = 100, minval=0, maxval=100, tooltip="RSI(14) must be in the range between N and M.") issl = input(title = "SL", inline = 'linesl1', group = 'Stop Loss / Take Profit:', type = input.bool, defval = false) slpercent = input(title = ", %", inline = 'linesl1', group = 'Stop Loss / Take Profit:', type = input.float, defval = 10, minval=0.0) istrailing = input(title = "Trailing", inline = 'linesl1', group = 'Stop Loss / Take Profit:', type = input.bool, defval = false) istp = input(title = "TP", inline = 'linetp1', group = 'Stop Loss / Take Profit:', type = input.bool, defval = false) tppercent = input(title = ", %", inline = 'linetp1', group = 'Stop Loss / Take Profit:', type = input.float, defval = 20) fixedstart =input(title="", group = "Fixed Backtest Period Start/End Dates:", inline = "linebac1", type = input.bool, defval = true) backtest_start=input(title = "", type = input.time, inline = "linebac1", group = "Fixed Backtest Period Start/End Dates:", defval = timestamp("01 Jan 2017 13:30 +0000"), tooltip="If deactivated, backtest staring from the first available price bar.") fixedend = input(title="", group = "Fixed Backtest Period Start/End Dates:", inline = "linebac2", type = input.bool, defval = false) backtest_end =input(title = "", type = input.time, inline = "linebac2", group = "Fixed Backtest Period Start/End Dates:", defval = timestamp("30 Dec 2080 23:30 +0000"), tooltip="If deactivated, backtesting ends at the last available price bar.") if window < degree window := degree+1 src = rsi(close,rsi_l) [drsi,nrmse] = diff(src,window,degree) signalline = ema(drsi, signalLength) // Conditions for D-RSI dirchangeup = (drsi>drsi[1]) and (drsi[1]<drsi[2]) and drsi[1]<0.0 dirchangedw = (drsi<drsi[1]) and (drsi[1]>drsi[2]) and drsi[1]>0.0 crossup = crossover(drsi,0.0) crossdw = crossunder(drsi,0.0) crosssignalup = crossover(drsi,signalline) crosssignaldw = crossunder(drsi,signalline) // D-RSI signals drsilong = (buycond=="Direction Change"?dirchangeup:(buycond=="Zero-Crossing"?crossup:crosssignalup)) drsishort= (sellcond=="Direction Change"?dirchangedw:(sellcond=="Zero-Crossing"?crossdw:crosssignaldw)) drisendlong = (endcond=="Direction Change"?dirchangedw:(endcond=="Zero-Crossing"?crossdw:crosssignaldw)) drisendshort= (endcond=="Direction Change"?dirchangeup:(endcond=="Zero-Crossing"?crossup:crosssignalup)) // Filters rsifilter = usersi?(rsi(close,14) > rsitrhs1 and rsi(close,14) < rsitrhs2):true volatilityfilter = useatr?(atr(len_atr1) > atr(len_atr2)):true volumefilter = usevol?(volume > rvol*sma(volume,len_vol)):true totalfilter = volatilityfilter and volumefilter and rsifilter //Filtered signals golong = drsilong and islong and (filterlong?totalfilter:true) goshort = drsishort and isshort and (filtershort?totalfilter:true) endlong = drisendlong and (filterend?totalfilter:true) endshort = drisendlong and (filterend?totalfilter:true) // Backtest period //backtest_start = timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0) //backtest_end = timestamp(syminfo.timezone, endYear, endMonth, endDate, 0, 0) isinrange = (fixedstart?time>=backtest_start:true) and (fixedend?time<=backtest_end:true) // Entry price / Take profit / Stop Loss startprice = valuewhen(condition=golong or goshort, source=close, occurrence=0) pm = golong?1:goshort?-1:1/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 := max(close*(1 - slpercent*0.01),stoploss[1]) else if istrailing and strategy.position_size<0 stoploss := min(close*(1 + slpercent*0.01),stoploss[1]) tpline = plot(takeprofit,color=color.blue,transp=100, title="TP") slline = plot(stoploss, color=color.red, transp=100, title="SL") p1 = plot(close,transp=100,color=color.white, title="Dummy Close") fill(p1, tpline, color=color.green, transp=istp?70:100, title="TP") fill(p1, slline, color=color.red, transp=issl?70:100, title="SL") // Backtest: Basic Entry and Exit Conditions if golong and isinrange and islong strategy.entry("long", true ) alert("D-RSI Long " + syminfo.tickerid, alert.freq_once_per_bar_close) if goshort and isinrange and isshort strategy.entry("short", false) alert("D-RSI Short " + syminfo.tickerid, alert.freq_once_per_bar_close) if endlong strategy.close("long", alert_message="Close Long") alert("D-RSI Exit Long " + syminfo.tickerid, alert.freq_once_per_bar_close) if endshort strategy.close("short", alert_message="Close Short") alert("D-RSI Exit Short " + syminfo.tickerid, alert.freq_once_per_bar_close) // Exit via SL or TP strategy.exit(id="sl/tp long", from_entry="long", stop=issl?stoploss:na, limit=istp?takeprofit:na, alert_message="Close Long") strategy.exit(id="sl/tp short",from_entry="short",stop=issl?stoploss:na, limit=istp?takeprofit:na, alert_message="Stop Loss Short") // Close if outside the range if (not isinrange) strategy.close_all()
[KL] BOLL + MACD Strategy v2 (published)
https://www.tradingview.com/script/EyElTlCG-KL-BOLL-MACD-Strategy-v2-published/
DojiEmoji
https://www.tradingview.com/u/DojiEmoji/
291
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© DojiEmoji // https://www.tradingview.com/script/EyElTlCG-KL-BOLL-MACD-Strategy-v2-published/ //@version=4 strategy("[KL] BOLL + MACD Strategy",overlay=true,pyramiding=1) // BOLL bands { BOLL_length = 20 BOLL_src = close BOLL_mult = 2.0 BOLL_center = sma(BOLL_src, BOLL_length) BOLL_dev = BOLL_mult * stdev(BOLL_src, BOLL_length) BOLL_upper = BOLL_center + BOLL_dev BOLL_lower = BOLL_center - BOLL_dev BOLL_offset = 0 plot(BOLL_center, "Basis", color=#872323, offset = BOLL_offset) BOLL_p1 = plot(BOLL_upper, "Upper", color=color.navy, offset = BOLL_offset, transp=50) BOLL_p2 = plot(BOLL_lower, "Lower", color=color.navy, offset = BOLL_offset, transp=50) fill(BOLL_p1, BOLL_p2, title = "Background", color=#198787, transp=85) // } // MACD signals { MACD_fastLen = 12 MACD_slowLen = 26 MACD_Len = 9 MACD = ema(close, MACD_fastLen) - ema(close, MACD_slowLen) aMACD = ema(MACD, MACD_Len) MACD_delta = MACD - aMACD // } backtest_timeframe_start = input(defval = timestamp("01 Nov 2010 13:30 +0000"), title = "Backtest Start Time", type = input.time) USE_ENDTIME = input(false,title="Define backtest end-time (If false, will test up to most recent candle)") backtest_timeframe_end = input(defval = timestamp("19 Mar 2021 19:30 +0000"), title = "Backtest End Time (if checked above)", type = input.time) EXIT1 = input(false, title="Take profit when Risk:Reward met") REWARD_RATIO = input(3,title="Risk:[Reward] for exit") EXIT2 = input(false, title="Take profit when candle is bearish") // Trailing stop loss { var entry_price = float(0) ATR_multi_len = 26 ATR_multi = input(2, "ATR multiplier for stop loss") ATR_buffer = atr(ATR_multi_len) * ATR_multi plotchar(ATR_buffer, "ATR Buffer", "", location = location.top) risk_reward_buffer = (atr(ATR_multi_len) * ATR_multi) * REWARD_RATIO reward_met_long = low > entry_price + risk_reward_buffer take_profit_short = low < entry_price - risk_reward_buffer var trailing_SL_buffer = float(0) var stop_loss_price = float(0) stop_loss_price := max(stop_loss_price, close - trailing_SL_buffer) // plot TSL line trail_profit_line_color = color.green if strategy.position_size == 0 // make TSL line less visible trail_profit_line_color := color.black stop_loss_price := close - trailing_SL_buffer plot(stop_loss_price,color=trail_profit_line_color) // } var bTouched = false if low < BOLL_center - atr(BOLL_length) alert("Price approached lower band", alert.freq_once_per_bar) bTouched := true else if low > BOLL_center bTouched := false // MAIN if time >= backtest_timeframe_start and (time <= backtest_timeframe_end or not USE_ENDTIME) expected_MACD_crossing = MACD > MACD[1] and MACD < aMACD and abs(MACD - aMACD) < abs(MACD[1] - aMACD[1]) buy_condition = bTouched and expected_MACD_crossing //ENTRY { if buy_condition if strategy.position_size == 0 entry_price := close trailing_SL_buffer := ATR_buffer stop_loss_price := close - ATR_buffer msg = "buy" if strategy.position_size > 0 msg := "+" strategy.entry("Long",strategy.long, comment=msg) // } //EXIT: // Case A: if strategy.position_size > 0 and close <= stop_loss_price if close > entry_price strategy.close("Long", comment="take profit [trailing]") stop_loss_price := 0 else if close <= entry_price strategy.close("Long", comment="stop loss") stop_loss_price := 0 // Case B: if EXIT1 or EXIT2 and strategy.position_size > 0 engulfing_bearish = open - close > abs(open[1]-close[1]) and high > high[1] and (open - close)/(high - low) > 0.4 gapped_down = high < low[1] and close < open is_bearish_candle = engulfing_bearish or gapped_down msg = "exit" strategy.close("Long", when=(EXIT1 and reward_met_long), comment="risk:reward met") strategy.close("Long", when=(EXIT2 and engulfing_bearish), comment="bearish") // CLEAN UP if strategy.position_size == 0 stop_loss_price := 0
Risk Reduction Ultimate Template
https://www.tradingview.com/script/YiHwSD3P-Risk-Reduction-Ultimate-Template/
burgercrisis
https://www.tradingview.com/u/burgercrisis/
217
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/ // Β© burgercrisis //@version=4 strategy(title="Risk Reduction Ultimate Template", overlay=false, pyramiding=10, calc_on_every_tick=true, default_qty_type=strategy.percent_of_equity, default_qty_value=10, initial_capital=1000, slippage=10, commission_value=0.1) //This is just to make this template work and publishable. src = input(close, title="Source") //SMII longlen = input(20, minval=1, title="Long Length") shortlen = input(5, minval=1, title="Short Length") siglen = input(5, minval=1, title="Signal Line Length") erg = tsi(src, shortlen, longlen) sig = ema(erg, siglen) plot(erg, color=#0094FF, title="SMI") plot(sig, color=#FF6A00, title="Signal") //%Blength = input(20, minval=1) length = input(20, minval=1) mult = input(2.0, minval=0.001, maxval=50, step=0.1, title="StdDev") basis = sma(src, length) dev = mult * stdev(src, length) upper = basis + dev lower = basis - dev bbr = (src - lower)/(upper - lower) plot(bbr, "Bollinger Bands %B", color=color.teal) buy=input(0.0,step=0.1) sellonce=input(1.0,step=0.1) sellall=input(1.1,step=0.1) band1 = hline(sellonce, "Overbought", color=#606060, linestyle=hline.style_dashed) band0 = hline(buy, "Oversold", color=#606060, linestyle=hline.style_dashed) fill(band1, band0, color=color.teal, title="Background") //Always include a backtesting period selector. Always always always always or I hate you. //* Backtesting Period Selector | Component *// //* https://www.tradingview.com/script/eCC1cvxQ-Backtesting-Period-Selector-Component *// //* https://www.tradingview.com/u/pbergden/ *// //* Modifications made *// testStartYear = input(2020, "Backtest Start Year") testStartMonth = input(1, "Backtest Start Month") testStartDay = input(1, "Backtest Start Day") testPeriodStart = timestamp(testStartYear,testStartMonth,testStartDay,0,0) testStopYear = input(999999, "Backtest Stop Year") testStopMonth = input(9, "Backtest Stop Month") testStopDay = input(26, "Backtest Stop Day") testPeriodStop = timestamp(testStopYear,testStopMonth,testStopDay,0,0) testPeriod() => time >= testPeriodStart and time <= testPeriodStop ? true : false /////// //////// END - Backtesting Period Selector | Component /////////////// //Whats the point of this? //This is a strategy template for risk reduction. I've found that the main problem with strategies on Tradingview is they do not account for risk and reward management! The ones that do, do so very poorly and rudimentarily! //Utter lack of stop losses, rudimentary and unconditional stop losses with no care for changes in momentum that may indicate the stop loss shouldn't be taken, take profits occurring in the middle of huge rush just because a price was hit //and momentum based signals with no care for whether the sale is profitable or not, or if price had barely even changed! //I thought maybe TA-based bots just aren't possible to actually be any good for a moment. But rather then give up, I decided to try to gear up. And I believe I found a key that can make almost any strategy work. A path to actually beating buy and hold. // //How do I use this? //It's actually really simple. It might have a lot of tiny pieces but that is to maximize the users choices in maximizing risk adjusted return and its really simple once you make sense of it. //You have a single buy signal, three stop losses, two take profits and two (roughly) standard sells. //I tend to use a trigger and multiple filter conditions for both my buys and sales. This strategy doesn't need it for the buys but that is how you make the sale system work so for clarity there are two conditions for buys – longtrigger and longcondition1. //The trigger, you want to be something that occurs at a single point in time, such as a crossover of some kind. The filter you want to be more loose and regional, such as an overbought or oversold condition. //The sells conditions are similar. You have a shorttrigger and two shortconditions sets for filtering. The first shortcondition is to sell a single set (depending on your position sizing settings in properties tab). //The second shortcondition is to sell everything at more extreme settings. This is because nobody can perfectly time every top, even with a script, so you want to take profits along the way without completely exiting //and allowing yourself to re-enter when its right and only fully exit at extreme cases. If you want to use just one set of conditions, move to the last line and replace shortcondition2 with shortcondition1. //Then you can decide if selling all is truly better then pyramiding things out... Test both % and flat and you will see. // //Everything should be pretty clearly labeled. // // longtrigger=crossover(erg,sig) ////Put your trigger for buys here longcondition1=bbr<buy ////Put your buy filter signals here shorttrigger=crossunder(erg,sig) ////Put your sell trigger here shortcondition1=bbr>sellonce ////This is your filters for partial exits shortcondition2=bbr>sellall ////This is your filter for full sales. //This gets multiplied to your sale thresholds to make sure they account for commission properly. commission=input(0.1) comms=(100+commission)/100 //Three stop losses //StopLosses stopLossFear=input(100.0, step=0.2, title="Hard Stop Loss") //Hard stop loss triggers immediately when a drop from your assumed average position price occurs equal to set percentage sl1=(100-stopLossFear)/100*comms stopLossSafe=input(100.0, step=0.2, title="Soft Stop Loss") //Soft stop loss triggers when your shorttrigger occurs after a drop from position price equal to set percentage sl2=(100-stopLossSafe)/100*comms stopLossSafest=input(100.0, step=0.2, title="Safe Stop Loss") //Safe stop loss triggers when both shorttrigger and shortcondition1 occur after a drop from position price equal to set percentage sl3=(100-stopLossSafest)/100*comms //TakeProfits TakeProfit1=input(100.0, step=0.2, title="Hard Take Profit") //Hard Take Profit occurs after a rise from position price equal to set percentage tp1=(100+TakeProfit1)/100*comms TakeProfit2=input(100.0, step=0.2, title="Soft Take Profit") //Soft Take Profit occurs when your shorttrigger occurs after a rise from position price equal to set percentage tp2=(100+TakeProfit2)/100*comms TakeProfit3=input(0.0, step=0.2, title="Minimum Sale Profit") //This is the standard single sell signal, it occurs when shorttrigger and shortcondition1 occur after a rise from position price equal to set percentage to filter bad signals tp3=(100+TakeProfit3)/100*comms TakeProfit4=input(0.0, step=0.2, title="Sell All Profit") //This sells all positions when shorttrigger and shortcondition1 occur after a rise from position price equal to set percentage tp4=(100+TakeProfit4)/100*comms if testPeriod() //Backtesting period selector component if longcondition1 and longtrigger strategy.entry(id="EL", comment="Buy", long=true) //Buy signal if shortcondition1 and shorttrigger and ((strategy.position_avg_price*tp3 < high) or (strategy.position_avg_price*tp3 < close)) //Sell One signal strategy.entry("Sell One Order", strategy.short) if shortcondition2 and shorttrigger and ((strategy.position_avg_price*tp4 < high) or (strategy.position_avg_price*tp4 < close)) //Sell All signal strategy.close(id="EL", comment="Sell All") if ((strategy.position_avg_price*tp1 < high) or (strategy.position_avg_price*tp1 < close)) //Hard Take Profit signal strategy.close(id="EL", comment="Hard Take Profit") if ((strategy.position_avg_price*tp2 < high) or (strategy.position_avg_price*tp2 < close)) and shorttrigger //Soft Take Profit signal strategy.close(id="EL", comment="Soft Take Profit") if (strategy.position_avg_price*sl1 > close) //Hard Stop Loss Signal strategy.close(id="EL", comment="Hard Stop Loss") if (strategy.position_avg_price*sl2 > close) and shorttrigger //Soft Stop Loss signal strategy.close(id="EL", comment="Soft Stop Loss") if (strategy.position_avg_price*sl3 > close) and shortcondition1 and shorttrigger //Safe Stop Loss from Sell One conditions strategy.close(id="EL", comment="Safe Stop Loss 1") if (strategy.position_avg_price*sl3 > close) and shortcondition2 and shorttrigger //Safe Stop Loss from Sell All condition strategy.close(id="EL", comment="Safe Stop Loss 2")
[KL] RSI 14 + 10 Strategy
https://www.tradingview.com/script/8TqESNDK-KL-RSI-14-10-Strategy/
DojiEmoji
https://www.tradingview.com/u/DojiEmoji/
184
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© DojiEmoji //@version=4 strategy("[KL] RSI 14 + 10 Strategy v2.1",overlay=true,pyramiding=1) // changes in Version 2.1: // 1) Fixed a bug (related to TSL) backtest_timeframe_start = input(defval = timestamp("01 Apr 2016 13:30 +0000"), title = "Backtest Start Time", type = input.time) USE_ENDTIME = input(false,title="Define the ending period for backtests (If false, will test up to most recent candle)") backtest_timeframe_end = input(defval = timestamp("19 Mar 2021 19:30 +0000"), title = "Backtest End Time", type = input.time) TARGET_PROFIT_MODE = input(false,title="Exit when Risk:Reward met") REWARD_RATIO = input(3,title="Risk:[Reward] (i.e. 3) for exit") // Trailing stop loss { TSL_ON = input(true,title="Use trailing stop loss") var entry_price = float(0) ATR_multi_len = 26 ATR_multi = input(2, "ATR multiplier for stop loss") ATR_buffer = atr(ATR_multi_len) * ATR_multi //plotchar(ATR_buffer, "ATR Buffer", "", location = location.top) risk_reward_buffer = (atr(ATR_multi_len) * ATR_multi) * REWARD_RATIO take_profit_long = low > entry_price + risk_reward_buffer take_profit_short = low < entry_price - risk_reward_buffer var trailing_SL_buffer = float(0) var stop_loss_price = float(0) stop_loss_price := max(stop_loss_price, close - trailing_SL_buffer) // plot TSL line trail_profit_line_color = color.green if strategy.position_size == 0 or not TSL_ON trail_profit_line_color := color.black stop_loss_price := close - trailing_SL_buffer plot(stop_loss_price,color=trail_profit_line_color) // } // RSI { RSI_LOW = input(40,title="RSI entry") RSI_HIGH = input(70,title="RSI exit") rsi14 = rsi(close, 14) rsi10 = rsi(close, 10) // } if time >= backtest_timeframe_start and (time <= backtest_timeframe_end or not USE_ENDTIME) buy_condition = rsi14 <= RSI_LOW and rsi10 < rsi14 exit_condition = rsi14 >= RSI_HIGH and rsi10 > rsi14 //ENTRY: if buy_condition if strategy.position_size == 0 entry_price := close trailing_SL_buffer := ATR_buffer stop_loss_price := close - ATR_buffer msg = "entry" if strategy.position_size > 0 msg := "pyramiding" strategy.entry("Long",strategy.long, comment=msg) //EXIT: // Case (A) hits trailing stop if TSL_ON and strategy.position_size > 0 and close <= stop_loss_price if close > entry_price strategy.close("Long", comment="take profit [trailing]") else if close <= entry_price strategy.close("Long", comment="stop loss") // Case (B) take targeted profit relative to risk if strategy.position_size > 0 and TARGET_PROFIT_MODE if take_profit_long strategy.close("Long", comment="take profits [risk:reward]") // Case (C) if strategy.position_size > 0 and exit_condition if take_profit_long strategy.close("Long", comment="exit[rsi]") // Also included an additional script (Study script) - "RSI[14 + 10] Double Indicators" // The following script is a modification of the original RSI indicator built into TradingView // The reason that it is not included in the Strategy script is because the plotting scales are different. // // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // // Β© DojiEmoji // //@version=4 // study(title="RSI[14 + 10] Double Indicators", shorttitle="RSI", format=format.price, precision=2, resolution="") // len1 = input(14, minval=1, title="RSI A Length") // src1 = input(close, "RSI A Source", type = input.source) // rsi1 = rsi(src1,len1) // plot(rsi1, "RSI", color=#ffffff) // len2 = input(10, minval=1, title="RSI B Length") // src2 = input(close, "RSI B Source", type = input.source) // rsi2 = rsi(src2,len2) // plot(rsi2, "RSI", color=#fb8c00) // band1 = hline(70, "Upper Band", color=#C0C0C0) // band0 = hline(30, "Lower Band", color=#C0C0C0) // fill(band1, band0, color=#9915FF, transp=90, title="Background")
HiLo Extension
https://www.tradingview.com/script/rsbViwZX-HiLo-Extension/
Saravanan_Ragavan
https://www.tradingview.com/u/Saravanan_Ragavan/
223
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/ // Β© Saravanan_Ragavan // This Strategy is finding high or low breaks of the day and enter into the trader based on RSI value and time value //@version=4 strategy(title="HiLoExtn", shorttitle="HiLoExtn", overlay=true) T1 = time(timeframe.period, "0915-0916") Y = bar_index Z1 = valuewhen(T1, bar_index, 0) L = Y-Z1 + 1 tim = time(timeframe.period, "1015-1510") exitt= time(timeframe.period, "1511-1530") //VWMA 20 plot(vwma(close,20), color=color.blue) length = L lower = lowest(length) upper = highest(length) u = plot(upper, "Upper", color=color.green) l = plot(lower, "Lower", color=color.red) //**** RSI len = 14 src = close up = rma(max(change(src), 0), len) down = rma(-min(change(src), 0), len) rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down)) // Buy above Buy Line if ( (upper==high) and rsi>50 and tim and close>open ) strategy.entry("Buy", strategy.long, comment="Buy") // Exit Long Below Vwap strategy.close("Buy", when = close < vwma(close,20) or exitt) // Sell above Buy Line if ((lower==low) and rsi<50 and tim and close<open) strategy.entry("Sell", strategy.short, comment="Sell") // Exit Short above Vwap strategy.close("Sell", when = close > vwma(close,20) or exitt)
Momentum Strategy (BTC/USDT; 1h) - MACD (with source code)
https://www.tradingview.com/script/b7zn25L6-Momentum-Strategy-BTC-USDT-1h-MACD-with-source-code/
Drun30
https://www.tradingview.com/u/Drun30/
643
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/ // Β© Drun30 //@version=4 strategy("MACD+RSI", initial_capital=100, overlay=false,default_qty_type=strategy.percent_of_equity,default_qty_value=100,commission_type="percent",commission_value=0.075) //@version=4 // Getting inputs fast_length = input(title="Fast Length", type=input.integer, defval=12,group="MACD") slow_length = input(title="Slow Length", type=input.integer, defval=26,group="MACD") src = input(title="Source", type=input.source, defval=close,group="MACD") signal_length = input(title="Signal Smoothing", type=input.integer, minval = 1, maxval = 50, defval = 9,group="MACD") sma_source1 = input(title="Simple MA FAST (Oscillator)", defval="EMA", options=["HMA","DHMA","THMA","FHMA","WMA","DWMA","TWMA","FWMA","SMA","DSMA","TSMA","FSMA","EMA","DEMA","TEMA","FEMA","RMA","DRMA","TRMA","FRMA"],group="MACD") sma_source2 = input(title="Simple MA SLOW (Oscillator)", defval="EMA", options=["HMA","DHMA","THMA","FHMA","WMA","DWMA","TWMA","FWMA","SMA","DSMA","TSMA","FSMA","EMA","DEMA","TEMA","FEMA","RMA","DRMA","TRMA","FRMA"],group="MACD") sma_signal = input(title="Simple MA(Signal Line)",defval="EMA", options=["HMA","DHMA","THMA","FHMA","WMA","DWMA","TWMA","FWMA","SMA","DSMA","TSMA","FSMA","EMA","DEMA","TEMA","FEMA","RMA","DRMA","TRMA","FRMA"],group="MACD") // Calculating ma(source,length,type)=> type=="FEMA"?4*ema(source,length)-ema(ema(ema(ema(source,length),length),length),length):type=="FSMA"?4*sma(source,length)-sma(sma(sma(sma(source,length),length),length),length):type=="FWMA"?4*wma(source,length)-wma(wma(wma(wma(source,length),length),length),length):type=="FRMA"?4*rma(source,length)-rma(rma(rma(rma(source,length),length),length),length):type=="TEMA"?3*ema(source,length)-ema(ema(ema(source,length),length),length):type=="TSMA"?3*sma(source,length)-sma(sma(sma(source,length),length),length):type=="TWMA"?3*wma(source,length)-wma(wma(wma(source,length),length),length):type=="TRMA"?3*rma(source,length)-rma(rma(rma(source,length),length),length):type=="EMA"?ema(source,length):type=="SMA"?sma(source,length):type=="WMA"?wma(source,length):type=="RMA"?rma(source,length):type=="DEMA"?2*ema(source,length)-ema(ema(source,length),length):type=="DSMA"?2*sma(source,length)-sma(sma(source,length),length):type=="DWMA"?2*wma(source,length)-wma(wma(source,length),length):type=="DRMA"?2*rma(source,length)-rma(rma(source,length),length):type=="HMA"?hma(source,length):type=="DHMA"?2*hma(source,length)-hma(hma(source,length),length):type=="THMA"?3*hma(source,length)-hma(hma(hma(source,length),length),length):type=="FHMA"?4*hma(source,length)-hma(hma(hma(hma(source,length),length),length),length):ema(source,length) fast_ma = ma(src,fast_length,sma_source1) slow_ma = ma(src,slow_length,sma_source2) macd = fast_ma - slow_ma //Differenza tra la media mobile veloce e quella lenta signal = ma(macd,signal_length,sma_signal) //usa o la SMA oppure la EMA sulla differenza tra la media mobile veloce e lenta hist = macd - signal //Differenza tra la differenza precedente e la media mobile della differenza // Plot colors col_grow_above = #26A69A col_grow_below = #FFCDD2 col_fall_above = #B2DFDB col_fall_below = #EF5350 col_macd = #0094ff col_signal = #ff6a00 use_stress=input(false,title="Use stress on recent bars",group="Stress") recent_stress=input(0.01,title="Stress on recent bars",group="Stress",step=0.01,minval=0.01,maxval=0.99) level=input(1,title="Level of stress",group="Stress") if use_stress macd:=macd*(1/(1-recent_stress)) if not na(macd[1]) macd:=pow((macd*(recent_stress)),level)+(1-recent_stress*macd[1]) use_ma= input(true,title="Use moving average (MACD)?",group="Moving Average") if use_ma macd:=ma(macd,input(36,title="Length",group="Moving Average"),input(title="Type MA",defval="THMA", options=["HMA","DHMA","THMA","FHMA","WMA","DWMA","TWMA","FWMA","SMA","DSMA","TSMA","FSMA","EMA","DEMA","TEMA","FEMA","RMA","DRMA","TRMA","FRMA"],group="Moving Average")) use_linreg= input(true,title="Use linear regression (MACD)?",group="Linear Regression") if use_linreg macd:=linreg(macd,input(10,title="Length",group="Linear Regression"),input(1,title="Offset",group="Linear Regression")) //macd == linea blu (differenza tra media mobile veloce e media mobile lenta) //signal == linea arancione (media mobile dell'macd) //hist == istogramma (differenza tra macd e media mobile) on_cross = input(false,title="Use cross macd and signal",group="Condition entry/exit") on_minmax = input(true,title="Use min/max macd",group="Condition entry/exit") aperturaLong = change(macd)>0//crossover(macd,signal) aperturashort=not (change(macd)>0)//crossunder(macd,signal) if on_cross on_minmax:=false aperturaLong := crossover(macd,signal) aperturashort := crossunder(macd,signal) if on_minmax on_cross:=false aperturaLong := change(macd)>0//crossover(macd,signal) aperturashort:=change(macd)<0//crossunder(macd,signal) //plot(hist, title="Histogram", style=plot.style_columns, color=(hist>=0 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below) ), transp=0 ) plot(macd, title="MACD", color=change(macd)>0 and on_minmax?color.white:change(macd)<0 and on_minmax?color.purple:color.blue, transp=0) plot(on_cross?signal:na, title="Signal", color=col_signal, transp=0) rsiFilter = input(false,title="Use RSI filter?",group="RSI") rsiTP = input(true,title="Use RSI Take Profit?",group="RSI") len=input(14,title="RSI period",group="RSI") srcr=input(close,title="RSI source",group="RSI") rsi=rsi(srcr,len) ovb=input(90,title="Overbought height",group="RSI") ovs=input(44,title="Oversold height",group="RSI") okLong=rsi<ovb and change(macd)>0 and change(macd)[1]<=0 okShort=rsi>ovs and change(macd)<0 and change(macd)[1]>=0 if not rsiFilter okLong:=true okShort:=true usiLong=input(true,title="Use long?") usiShort=input(true,title="Use short?") chiusuraShort=rsi<ovs or (aperturaLong) chiusuraLong=rsi>ovb or (aperturashort) if rsiTP aperturaLong := change(macd)>0 and change(macd)[1]<=0 and rsi<ovb//crossover(macd,signal) aperturashort:=change(macd)<0 and change(macd)[1]>=0 and rsi>ovs//crossunder(macd,signal) if not rsiTP chiusuraShort:=okLong and aperturaLong chiusuraLong:=okShort and aperturashort if chiusuraShort strategy.close("SHORTISSIMO") if usiLong and strategy.position_size<=0 and okLong and aperturaLong strategy.entry("LONGHISSIMO",true) if chiusuraLong strategy.close("LONGHISSIMO") if usiShort and strategy.position_size>=0 and okShort and aperturashort strategy.entry("SHORTISSIMO",false)
Three moving average strategies
https://www.tradingview.com/script/sPAROdDQ/
dadashkadir
https://www.tradingview.com/u/dadashkadir/
487
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/ // © dadashkadir //@version=4 strategy("Üç Hareketli Ortalama Str.", overlay=true, initial_capital=10000, commission_value=0.047, default_qty_type=strategy.percent_of_equity, default_qty_value=100, pyramiding=0, calc_on_order_fills=true) kisa = input(title = "Kısa Vade - Gün", defval = 7, minval = 1) orta = input(title = "Orta Vade - Gün", defval = 25, minval = 1) uzun = input(title = "Uzun Vade - Gün", defval = 99, minval = 1) sma7 = sma(close, kisa) sma25 = sma(close, orta) sma99 = sma(close, uzun) alTrend = plot (sma7, color=#2323F1, linewidth=2, title="Har.Ort. Kısa Vade", transp=0) satTrend = plot (sma25, color=#FF0C00, linewidth=3, title="Har.Ort. Orta Vade", transp=0) ort99 = plot (sma99, color=#DFB001, linewidth=3, title="Har.Ort. Uzun Vade", transp=0) zamanaralik = input (2020, title="Backtest Başlangıç Tarihi") al = crossover (sma7, sma25) and zamanaralik <= year sat = crossover (sma25, sma7) and zamanaralik <= year hizlial = crossover (sma7, sma99) and zamanaralik <= year hizlisat = crossover (sma99, sma7) and zamanaralik <= year alkosul = sma7 >= sma25 satkosul = sma25 >= sma7 hizlialkosul = sma7 >= sma99 hizlisatkosul = sma99 >= sma7 plotshape(al, title = "Buy", text = 'Al', style = shape.labelup, location = location.belowbar, color= color.green, textcolor = color.white, transp = 0, size = size.tiny) plotshape(sat, title = "Sell", text = 'Sat', style = shape.labeldown, location = location.abovebar, color= color.red, textcolor = color.white, transp = 0, size = size.tiny) plotshape(hizlial, title = "Hızlı Al", text = 'Hızlı Al', style = shape.labelup, location = location.belowbar, color= color.blue, textcolor = color.white, transp = 0, size = size.tiny) plotshape(hizlisat, title = "Hızlı Sat", text = 'Hızlı Sat', style = shape.labeldown, location = location.abovebar, color= #6106D6 , textcolor = color.white, transp = 0, size = size.tiny) fill (alTrend, satTrend, color = sma7 >= sma25? #4DFF00 : #FF0C00, transp=80, title="Al-Sat Aralığı") //fill (ort99, satTrend, color = sma7 >= sma25? #6106D6 : color.blue, transp=80, title="Hızlı Al-Sat Aralığı") if (al) strategy.entry("LONG", strategy.long) if (sat) strategy.entry("SHORT", strategy.short) //if (hizlial) // strategy.entry("My Short Entry Id", strategy.long) //if (hizlisat) // strategy.entry("My Short Entry Id", strategy.short)
Multi Moving Average Crossing (by Coinrule)
https://www.tradingview.com/script/DDnx7g70-Multi-Moving-Average-Crossing-by-Coinrule/
Coinrule
https://www.tradingview.com/u/Coinrule/
410
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='Multi Moving Average Crossing',title='Multi Moving Average Crossing (by Coinrule)', overlay=true, initial_capital=1000, default_qty_type = strategy.percent_of_equity, default_qty_value = 30, 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" //MA inputs and calculations inlong=input(100, title='MAlong') inmid=input(50, title='MAmid') inshort=input(9, title='MAfast') MAlong = sma(close, inlong) MAshort= sma(close, inshort) MAmid= sma(close, inmid) //Entry bullish = crossover(MAmid, MAlong) strategy.entry(id="long", long = true, when = bullish and window()) //Exit bearish = crossunder(MAshort, MAmid) strategy.close("long", when = bearish and window()) plot(MAshort, color=color.orange, linewidth=2) plot(MAmid, color=color.red, linewidth=2) plot(MAlong, color=color.blue, linewidth=2)
TEMA Cross Backtest
https://www.tradingview.com/script/QCoYSFGj-TEMA-Cross-Backtest/
Seltzer_
https://www.tradingview.com/u/Seltzer_/
151
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/ // Β© Seltzer_ //@version=4 strategy(title="TEMA Cross Backtest", shorttitle="TEMA_X_BT", overlay=true, commission_type=strategy.commission.percent, commission_value=0, initial_capital = 1000, default_qty_type=strategy.percent_of_equity, default_qty_value=100) // Backtest inputs FromMonth = input(defval=1, title="From Month", minval=1, maxval=12) FromDay = input(defval=1, title="From Day", minval=1, maxval=31) FromYear = input(defval=2020, title="From Year", minval=2010) 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=2017) // Define backtest timewindow start = timestamp(FromYear, FromMonth, FromDay, 00, 00) // backtest start window finish = timestamp(ToYear, ToMonth, ToDay, 23, 59) // backtest finish window window() => // create function "within window of time" time >= start and time <= finish ? true : false //TEMA Section xLength = input(20, minval=1, title="Fast Length") xPrice = close xEMA1 = ema(xPrice, xLength) xEMA2 = ema(xEMA1, xLength) xEMA3 = ema(xEMA2, xLength) xnRes = (3 * xEMA1) - (3 * xEMA2) + xEMA3 xnResP = plot(xnRes, color=color.green, linewidth=2, title="TEMA1") yLength = input(60, minval=1, title="Slow Length") yPrice = close yEMA1 = ema(yPrice, yLength) yEMA2 = ema(yEMA1, yLength) yEMA3 = ema(yEMA2, yLength) ynRes = (3 * yEMA1) - (3 * yEMA2) + yEMA3 ynResP = plot(ynRes, color=color.red, linewidth=2, title="TEMA2") fill(xnResP, ynResP, color=xnRes > ynRes ? color.green : color.red, transp=75, editable=true) // Buy and Sell Triggers LongEntryAlert = xnRes > ynRes LongCloseAlert = xnRes < ynRes ShortEntryAlert = xnRes < ynRes ShortCloseAlert = xnRes > ynRes // Entry & Exit signals strategy.entry("Long", strategy.long, when = xnRes > ynRes and window()) strategy.close("Long", when = xnRes < ynRes) //strategy.entry("Short", strategy.short, when = xnRes < ynRes and window()) //strategy.close("Short", when = xnRes > ynRes)
Open Close Cross Strategy plus Explorer
https://www.tradingview.com/script/XPMLrxgf/
roses27
https://www.tradingview.com/u/roses27/
531
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ //@version=4 //author roses27 // V 1.464 // There is a code that can control sensitivity. // There is a code for prevent 'repaint' // There is a code for data sorting and display. // thanks to @JustUncleL @JayRogers about 'BASE FUNCTIONS' strategy(title = "Open Close Cross Strategy plus Explorer", shorttitle = "OCC plus Explorer",overlay=true, calc_on_every_tick=false, initial_capital=100000, default_qty_type= strategy.cash, default_qty_value=100000, process_orders_on_close = true, pyramiding = 0, commission_type=strategy.commission.percent, commission_value=0.25) // === INPUTS === tradeType = input("LONG", title = "What trades should be taken : ", options=["LONG", "SHORT", "BOTH", "NONE"]) resMultiplier = input(defval = 5, title = "Multiplier for Alternate Resolution('1' is original)", minval = 1, tooltip = "The current resolution is multiplied by this number and calculated at Alternate Resolution.") basisType = input(defval = "TEMA",title = "MA Type: ", options=["SMA", "EMA", "DEMA", "TEMA", "WMA", "VWMA", "SMMA", "HullMA", "LSMA", "ALMA", "SSMA", "TMA"], tooltip = "Moving Average Type") basisLen = input(defval = 50, title = "MA Period", minval = 1) alma_offset = input(defval = 0.85, title = "Offset for ALMA", minval = 0.0, step = 0.01) alma_sigma = input(defval = 6.0, title = "Sigma for ALMA", minval = 0.0, step = 0.1) lsma_offset = input(defval = 5, title = "Offset for LSMA", minval = 0, step = 1) useStartPeriodTime = input(true, "Start", input.bool, group = "Date Range", inline = "Start Period") startPeriodTime = input(timestamp(" 4 Mar 2021"), "", input.time, group = "Date Range", inline = "Start Period") useEndPeriodTime = input(false,"End ", input.bool, group = "Date Range", inline = "End Period") endPeriodTime = input(timestamp("19 Apr 2021"), "", input.time, group = "Date Range", inline = "End Period") enableHighlight = input(false, "Highlight", input.bool, group = "Date Range", inline = "Highlight") highlightType = input( "Anchors","", input.string, options = ["Anchors", "Background"], group = "Date Range",inline = "Highlight") highlightColor = input(color.red, "", input.color, group = "Date Range", inline = "Highlight") scolor = input(defval = true, title = "Show coloured Bars to indicate Trend?", group = "Date Range") //=== Code to adjust sensitivity 'Multiplier*atr'=== Periods = input(defval = 30, title = "ATR Length", group = "Sensitivity", minval = 1) Multiplier = input(defval = 0.3, title = "ATR Multiplier", group = "Sensitivity", minval = 0.0, step = 0.01, tooltip = "The larger the value, enter late and exit late.") Non_Repainting = input(defval = 2, title = "Forces to Non-Repainting", options=[0,1,2], group = "Sensitivity", tooltip = "0: The results are delayed as much as '0'. 1: The results are delayed as much as the current resolution. 2: The results are delayed as much as the Alternate Resolution. The larger the probability of 'repainting' decreases.") //===/Code to adjust sensitivity 'Multiplier*atr' === // === /INPUTS === start = useStartPeriodTime ? startPeriodTime >= time : false end = useEndPeriodTime ? endPeriodTime <= time : false calcPeriod = not start and not end var line startAnchor = line.new(na, na, na, na, xloc.bar_time, extend.both, highlightColor, width = 2) var line endAnchor = line.new(na, na, na, na, xloc.bar_time, extend.both, highlightColor, width = 2) useBgcolor = false // {β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” PineCoders MTF Selection Framework functions // β€”β€”β€”β€”β€” Converts current "timeframe.multiplier" plus the TF into minutes of type float. f_resInMinutes() => _resInMinutes = timeframe.multiplier * ( timeframe.isseconds ? 1. / 60. : timeframe.isminutes ? 1. : timeframe.isdaily ? 1440. : timeframe.isweekly ? 10080. : timeframe.ismonthly ? 43800. : na) // β€”β€”β€”β€”β€” Returns resolution of _resolution period in minutes. f_tfResInMinutes(_resolution) => // _resolution: resolution of any TF (in "timeframe.period" string format). security(syminfo.tickerid, _resolution, f_resInMinutes()) // β€”β€”β€”β€”β€” Given current resolution, returns next step of HTF. f_resNextStep(_res) => // _res: current TF in fractional minutes. _res <= 1 ? "60" : _res <= 60 ? "1D" : _res <= 360 ? "3D" : _res <= 1440 ? "1W" : _res <= 10080 ? "1M" : "12M" // β€”β€”β€”β€”β€” Returns a multiple of current resolution as a string in "timeframe.period" format usable with "security()". f_multipleOfRes(_res, _mult) => // _res: current resolution in minutes, in the fractional format supplied by f_resInMinutes() companion function. // _mult: Multiple of current TF to be calculated. // Convert current float TF in minutes to target string TF in "timeframe.period" format. _targetResInMin = _res * max(_mult, 1) // Find best string to express the resolution. _targetResInMin <= 0.083 ? "5S" : _targetResInMin <= 0.251 ? "15S" : _targetResInMin <= 0.501 ? "30S" : _targetResInMin <= 1440 ? tostring(round(_targetResInMin)) : _targetResInMin <= 43800 ? tostring(round(min(_targetResInMin / 1440, 365))) + "D" : tostring(round(min(_targetResInMin / 43800, 12))) + "M" // β€”β€”β€”β€”β€” HTF calcs // }β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” PineCoders MTF Selection Framework functions // { === BASE FUNCTIONS === variant(_type, _src, _len, _alma_offset, _alma_sigma, _lsma_offset) => v1 = sma(_src, _len) // Simple v2 = ema(_src, _len) // Exponential v3 = 2 * v2 - ema(v2, _len) // Double Exponential v4 = 3 * (v2 - ema(v2, _len)) + ema(ema(v2, _len), _len) // Triple Exponential v5 = wma(_src, _len) // Weighted v6 = vwma(_src, _len) // Volume Weighted v7 = 0.0 v7 := na(v7[1]) ? sma(_src, _len) : (v7[1] * (_len - 1) + _src) / _len // Smoothed v8 = wma(2 * wma(_src, _len / 2) - wma(_src, _len), round(sqrt(_len))) // Hull v9 = linreg(_src, _len, _lsma_offset) // Least Squares v10 = alma(_src, _len, _alma_offset, _alma_sigma) // Arnaud Legoux v11 = sma(v1,_len) // Triangular (extreme smooth) // SuperSmoother filter // Β© 2013 John F. Ehlers a1 = exp(-1.414*3.14159 / _len) b1 = 2*a1*cos(1.414*3.14159 / _len) c2 = b1 c3 = (-a1)*a1 c1 = 1 - c2 - c3 v12 = 0.0 v12 := c1*(_src + nz(_src[1])) / 2 + c2*nz(v12[1]) + c3*nz(v12[2]) _type=="EMA" ? v2 :_type=="DEMA" ? v3 : _type=="TEMA" ? v4 : _type=="WMA" ? v5 : _type=="VWMA" ? v6 : _type=="SMMA" ? v7 : _type=="HullMA" ? v8 : _type=="LSMA" ? v9 : _type=="ALMA" ? v10 : _type=="TMA" ? v11: _type=="SSMA" ? v12 : v1 // }=== /BASE FUNCTIONS === // {==== Code for prevent 'repaint' === // security wrapper for repeat calls f_security( _id, _res, _exp, _non_rep) => security(_id, _res, _exp[_non_rep == 2 ? 1 : 0], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)[_non_rep == 1 ? 1 : 0] // }====/Code for prevent 'repaint' === // Get current resolution in float minutes. var vResInMinutes = f_resInMinutes() stratRes = f_multipleOfRes(vResInMinutes, resMultiplier) atr = atr(Periods) // === SERIES SETUP === closeSeries = variant(basisType, close, basisLen, alma_offset, alma_sigma, lsma_offset) openSeries = variant(basisType, open, basisLen, alma_offset, alma_sigma, lsma_offset) // === /SERIES === // Get Alternate resolution Series if selected. closeSeriesAlt = f_security(syminfo.tickerid, stratRes, closeSeries, Non_Repainting) openSeriesAlt = f_security(syminfo.tickerid, stratRes, openSeries, Non_Repainting) // {=== PLOTTING === trendColour = (closeSeriesAlt > openSeriesAlt + Multiplier*atr) ? color.green : (closeSeriesAlt < openSeriesAlt - Multiplier*atr) ? color.red : color.yellow bcolour = (closeSeriesAlt > openSeriesAlt) ? color.green : color.red barcolor(scolor and calcPeriod ? bcolour : na, title = "Bar Colours") closeP = plot(series= scolor and calcPeriod ? closeSeriesAlt : na, title = "Close Series", color = trendColour, linewidth = 2, style = plot.style_line, transp = 20) openP = plot(series= scolor and calcPeriod ? openSeriesAlt : na, title = "Open Series", color = trendColour, linewidth = 2, style = plot.style_line, transp = 20) fill(closeP,openP,color=trendColour,transp=80) if enableHighlight if highlightType == "Anchors" if useStartPeriodTime line.set_xy1(startAnchor, startPeriodTime, low) line.set_xy2(startAnchor, startPeriodTime, high) if useEndPeriodTime line.set_xy1(endAnchor, calcPeriod ? time : line.get_x1(endAnchor), low) line.set_xy2(endAnchor, calcPeriod ? time : line.get_x1(endAnchor), high) if highlightType == "Background" useBgcolor := true bgcolor(useBgcolor and calcPeriod ? highlightColor : na, editable = false) // plot "calcPeriod of time" // }=== /PLOTTING === // // {=== STRATEGY conditions long = crossover( closeSeriesAlt, openSeriesAlt + Multiplier*atr) //Code to adjust sensitivity 'Multiplier*atr' short = crossunder(closeSeriesAlt, openSeriesAlt - Multiplier*atr) //Code to adjust sensitivity 'Multiplier*atr' // === /STRATEGY conditions. // === STRATEGY === // stop loss // stopLoss = input(defval = 0, title = "Stop Loss Points (zero for disable)", group = "Stop Condition", minval = 0) // targetProfit= input(defval = 0, title = "Target Profit Points (zero for disable)", group = "Stop Condition", minval = 0) // STEP 1: // Configure trail stop level with input options (optional) // longTrailPerc = input(title="Trail Long Loss (%)(zero for disable)", type=input.float, minval=0.0, step=0.1, defval=5.0, group = "Stop Condition", tooltip = "from highest point") * 0.01 // shortTrailPerc= input(title="Trail Short Loss(%)(zero for disable)", type=input.float, minval=0.0, step=0.1, defval=5.0, group = "Stop Condition", tooltip = "from lowest point" ) * 0.01 longTrailPerc = input(title="Trail Long Loss (%)(zero for disable)", type=input.float, minval=0.0, step=0.1, defval=0.0, group = "Stop Condition", tooltip = "From the previous 'close' value") * 0.01 shortTrailPerc= input(title="Trail Short Loss(%)(zero for disable)", type=input.float, minval=0.0, step=0.1, defval=0.0, group = "Stop Condition", tooltip = "From the previous 'close' value") * 0.01 // STEP 2: // Determine trail stop loss prices longStopPrice = 0.0, shortStopPrice = 0.0 longStopPrice := if (strategy.position_size > 0) stopValue = close * (1 - longTrailPerc) // stopValue = high * (1 - longTrailPerc) max(stopValue, longStopPrice[1]) else 0 shortStopPrice := if (strategy.position_size < 0) stopValue = close * (1 + shortTrailPerc) // stopValue = low * (1 + shortTrailPerc) min(stopValue, shortStopPrice[1]) else 9999999999 // Plot stop loss values for confirmation plot(series=(strategy.position_size > 0) and calcPeriod and longTrailPerc != 0.0 ? longStopPrice : na, color=color.fuchsia, style=plot.style_linebr, linewidth=2, title="Long Trail Stop" , transp = 0) plot(series=(strategy.position_size < 0) and calcPeriod and shortTrailPerc != 0.0 ? shortStopPrice : na, color=color.purple, style=plot.style_linebr, linewidth=2, title="Short Trail Stop", transp = 0) //exit parameters // TP = targetProfit > 0 ? targetProfit : na // SL = stopLoss > 0 ? stopLoss : na if (calcPeriod and tradeType!="NONE") strategy.entry("long", strategy.long, when=long ==true and tradeType!="SHORT", comment = "EL" , alert_message = "Long") strategy.entry("short", strategy.short, when=short==true and tradeType!="LONG" , comment = "ES" , alert_message = "Short") strategy.close("long", when=short==true and tradeType=="LONG" , comment = "EL close" , alert_message = "Long close") strategy.close("short", when=long ==true and tradeType=="SHORT", comment = "ES close" , alert_message = "Short close") // strategy.exit( "XL", from_entry = "long", profit = TP, loss = SL, comment = "XL long" , alert_message = "exit long") // strategy.exit( "XS", from_entry = "short", profit = TP, loss = SL, comment = "XL short" , alert_message = "exit short") strategy.exit(id="long", when = strategy.position_size > 0 and longTrailPerc != 0.0, stop=longStopPrice, comment = "Long TRL STP", alert_message = "Long TRL STP") strategy.exit(id="short", when = strategy.position_size < 0 and shortTrailPerc != 0.0, stop=shortStopPrice, comment = "Short TRL STP", alert_message = "Short TRL STP") // }=== /STRATEGY === // eof // { To view trends start //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// // // // If you don't want a [screen label], comment or delete the line below all. // // // ////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // { input for Label start showLabel = input(defval = true, title = "Show Screener Label with Text Color", group = "Label", inline = "Show Label") textColor = input(color.blue, "", input.color, group = "Label", inline = "Show Label") rmCurrency = input(defval = true, title = "Remove Currency Display", group = "Label", inline = "Remove Currency") Currency = input(defval = "USDT,USD,KRW", title ="" , type = input.string, confirm =false,group = "Label",inline = "Remove Currency") sort_by = input(defval ="Change Rate",title = "Label Sort by: ", options=["Profit", "Change Rate", "None"], group = "Label") posX_scr = input(defval = 100, title = "Label Position x-axis(#bars)", group = "Label", tooltip = "The label moves to the right by the number of bars..") posY_scr = input(defval = 100.0, title = "Label Position y-axis(ohlc4[100] * %/100)", step = 0.1, group = "Label", tooltip = "The label moves up and down depending on the input value. 100% is original point. ex) 99.5, ex) 105 ") // } input for Label end // { Function for handling strings start // β€”β€”β€”β€”β€” Function returning a string representation of a numeric `_val` using a special `_fmt` string allowing all strings to be of the same width, to help align columns of values. f_tostringPad(_val, _fmt) => // float _val: string to separate. // string _fmt: formatting string similar to those used in the `tostring()` format string, with "?" used to indicate padding, // e.g., "??0.00" to ensure that numbers always contain three characters left of the decimal point. // WARNING: A minus sign MUST begin the format ("-??0.00") if negative values are to be handled, otherwise negative values will have no minus sign. // Character used to pad numbers: Unicode figure space (U+2007). var string FIGURE_SPACE = " " // Character used to pad minus signs: Unicode punctuation space (U+2008). var string PUNCTUATION_SPACE = "β€ˆ" // Preliminary conversion of the value to a string. string _formattedVal = tostring(_val, _fmt) // Remove minus sign from format string. _formattedVal := str.replace_all(_formattedVal, "-", "") // Split value and format string into characters. string[] _chars = str.split(_formattedVal, "") string[] _charsFmt = str.split(_fmt, "") // Detect if we need to handle negative values, and if so, remove the minus sign from format. bool _handleNegs = array.get(_charsFmt, 0) == "-" if _handleNegs array.shift(_charsFmt) // Detect if value or format string are without a decimal point and if so, add a temporary one for our logic, which we'll remove later. int _pointPos = array.indexof(_chars, ".") int _pointPosFmt = array.indexof(_charsFmt, ".") bool _noPoint = _pointPos == -1 bool _noPointFmt = _pointPosFmt == -1 if _noPoint array.push(_chars, ".") _pointPos := array.indexof(_chars, ".") if _noPointFmt array.push(_charsFmt, ".") _pointPosFmt := array.indexof(_charsFmt, ".") // Remove extra instances of "?" in front of value. _extraChars = _pointPos - _pointPosFmt if _extraChars > 0 for _i = 0 to _extraChars - 1 array.shift(_chars) // Add minus sign or space if needed. if _handleNegs // Format accounts for negative values; insert minus sign or space. array.unshift(_chars, (_val < 0 ? "-" : PUNCTUATION_SPACE)) // Remove temporary decimal point if needed. if _noPointFmt or _noPoint array.pop(_chars) // Rejoin our array and replace the "?" chars left in our result with figure space padding. string _return = array.join(_chars, "") _return := str.replace_all(_return, "?", FIGURE_SPACE) f_rmDnC(_str, _space, _rmCurrency ,_Currency) => // string _str: string to separate. // int _space : space for id // bool _rmCurrency : if true remove currency display // string _Currency : Separated by ',' list of Currency var string FIGURE_SPACE = " " var string _str0 = _str if _rmCurrency _Currencys0 = str.split(str.replace_all(_Currency, " ", ""), ",") for i = 0 to array.size(_Currencys0) - 1 _str0 := str.replace_all(_str0, array.get(_Currencys0, i), '') string[] _chars = str.split(_str0, "") int _len = array.size(_chars) int _ofPos = array.indexof(_chars, ":") string[] _substr = array.new_string(0) if _ofPos >= 0 and _ofPos < _len - 1 _substr := array.slice(_chars, _ofPos + 1, _len) // remove Dealer code int _len2 = array.size(_substr) if _len2 < _space for _i = _len2 + 1 to _space array.push(_substr, FIGURE_SPACE) // array.unshift(_substr, FIGURE_SPACE) else if _len < _space _len := _str == '' ? 0 : _len // size of 'string[] _chars = str.split('', "")' is 1 not 0 for _i = _len + 1 to _space array.push(_chars, FIGURE_SPACE) // array.unshift(_chars, FIGURE_SPACE) string _return = _ofPos >= 0 and _ofPos < _len - 1 ? array.join(_substr, "") : array.join(_chars, "") // } Function for handling strings end OCCmax(_id, _multiplier, _non_rep) => var Trend = 0 var Position = 0 var profit = 0.0 var changeRate = 0.0 var tm = 0 var to_num = 0 if _id == '' Trend := 0, Position := 0, profit := -99999999.9, changeRate := -99999999.9, tm := 0 if _id != '' Trend := closeSeries[1] > (openSeries[1] + _multiplier * atr) ? 1 : closeSeries[1] < (openSeries[1] - _multiplier * atr) ? -1 : 0 Position := Trend != 0 ? Trend : Position[1] to_num := barssince(Position[1] != Position[0]) + 1 profit := 100.0 * (close[0] - close[to_num]) / close[to_num] tm := to_num * resMultiplier changeRate := 100.0 * profit / (tm * vResInMinutes) [Trend, Position, profit, changeRate, tm] ////////////////////////////////////////////////////////////////////////////////////////////// // If you want to reduce the input space, adjust the 'array_size'. // // And comment the id number as many as you want from the line below. // // 'array_size' is 1 larger than the 'ID number'. array_size cannot be greater than 38. // ////////////////////////////////////////////////////////////////////////////////////////////// array_size = 38 spaceSize = rmCurrency ? 4 : 6 // for tickerid display // { Label list start var id_ = array.new_string(array_size), var t_ = array.new_int(array_size), var p_ = array.new_int(array_size) var pr_ = array.new_float(array_size), var cr_ = array.new_float(array_size), var tm_ = array.new_int(array_size) id00 = syminfo.tickerid , [t00, p00, pr00, cr00, tm00] = security(id00, stratRes, OCCmax(id00, Multiplier, Non_Repainting)), array.set(id_, 0, f_rmDnC(id00, spaceSize, rmCurrency , Currency)), array.set(t_, 0, t00), array.set(p_, 0, p00), array.set(pr_, 0, pr00), array.set(cr_, 0, cr00), array.set(tm_, 0, tm00) id01 = input('', title='Symbol 01',type=input.symbol, group = "Inputs to view trends"), [t01, p01, pr01, cr01, tm01] = security(id01, stratRes, OCCmax(id01, Multiplier, Non_Repainting)), array.set(id_, 1, f_rmDnC(id01, spaceSize, rmCurrency , Currency)), array.set(t_, 1, t01), array.set(p_, 1, p01), array.set(pr_, 1, pr01), array.set(cr_, 1, cr01), array.set(tm_, 1, tm01) id02 = input('', title='Symbol 02',type=input.symbol, group = "Inputs to view trends"), [t02, p02, pr02, cr02, tm02] = security(id02, stratRes, OCCmax(id02, Multiplier, Non_Repainting)), array.set(id_, 2, f_rmDnC(id02, spaceSize, rmCurrency , Currency)), array.set(t_, 2, t02), array.set(p_, 2, p02), array.set(pr_, 2, pr02), array.set(cr_, 2, cr02), array.set(tm_, 2, tm02) id03 = input('', title='Symbol 03',type=input.symbol, group = "Inputs to view trends"), [t03, p03, pr03, cr03, tm03] = security(id03, stratRes, OCCmax(id03, Multiplier, Non_Repainting)), array.set(id_, 3, f_rmDnC(id03, spaceSize, rmCurrency , Currency)), array.set(t_, 3, t03), array.set(p_, 3, p03), array.set(pr_, 3, pr03), array.set(cr_, 3, cr03), array.set(tm_, 3, tm03) id04 = input('', title='Symbol 04',type=input.symbol, group = "Inputs to view trends"), [t04, p04, pr04, cr04, tm04] = security(id04, stratRes, OCCmax(id04, Multiplier, Non_Repainting)), array.set(id_, 4, f_rmDnC(id04, spaceSize, rmCurrency , Currency)), array.set(t_, 4, t04), array.set(p_, 4, p04), array.set(pr_, 4, pr04), array.set(cr_, 4, cr04), array.set(tm_, 4, tm04) id05 = input('', title='Symbol 05',type=input.symbol, group = "Inputs to view trends"), [t05, p05, pr05, cr05, tm05] = security(id05, stratRes, OCCmax(id05, Multiplier, Non_Repainting)), array.set(id_, 5, f_rmDnC(id05, spaceSize, rmCurrency , Currency)), array.set(t_, 5, t05), array.set(p_, 5, p05), array.set(pr_, 5, pr05), array.set(cr_, 5, cr05), array.set(tm_, 5, tm05) id06 = input('', title='Symbol 06',type=input.symbol, group = "Inputs to view trends"), [t06, p06, pr06, cr06, tm06] = security(id06, stratRes, OCCmax(id06, Multiplier, Non_Repainting)), array.set(id_, 6, f_rmDnC(id06, spaceSize, rmCurrency , Currency)), array.set(t_, 6, t06), array.set(p_, 6, p06), array.set(pr_, 6, pr06), array.set(cr_, 6, cr06), array.set(tm_, 6, tm06) id07 = input('', title='Symbol 07',type=input.symbol, group = "Inputs to view trends"), [t07, p07, pr07, cr07, tm07] = security(id07, stratRes, OCCmax(id07, Multiplier, Non_Repainting)), array.set(id_, 7, f_rmDnC(id07, spaceSize, rmCurrency , Currency)), array.set(t_, 7, t07), array.set(p_, 7, p07), array.set(pr_, 7, pr07), array.set(cr_, 7, cr07), array.set(tm_, 7, tm07) id08 = input('', title='Symbol 08',type=input.symbol, group = "Inputs to view trends"), [t08, p08, pr08, cr08, tm08] = security(id08, stratRes, OCCmax(id08, Multiplier, Non_Repainting)), array.set(id_, 8, f_rmDnC(id08, spaceSize, rmCurrency , Currency)), array.set(t_, 8, t08), array.set(p_, 8, p08), array.set(pr_, 8, pr08), array.set(cr_, 8, cr08), array.set(tm_, 8, tm08) id09 = input('', title='Symbol 09',type=input.symbol, group = "Inputs to view trends"), [t09, p09, pr09, cr09, tm09] = security(id09, stratRes, OCCmax(id09, Multiplier, Non_Repainting)), array.set(id_, 9, f_rmDnC(id09, spaceSize, rmCurrency , Currency)), array.set(t_, 9, t09), array.set(p_, 9, p09), array.set(pr_, 9, pr09), array.set(cr_, 9, cr09), array.set(tm_, 9, tm09) id10 = input('', title='Symbol 10',type=input.symbol, group = "Inputs to view trends"), [t10, p10, pr10, cr10, tm10] = security(id10, stratRes, OCCmax(id10, Multiplier, Non_Repainting)), array.set(id_, 10, f_rmDnC(id10, spaceSize, rmCurrency , Currency)), array.set(t_, 10, t10), array.set(p_, 10, p10), array.set(pr_, 10, pr10), array.set(cr_, 10, cr10), array.set(tm_, 10, tm10) id11 = input('', title='Symbol 11',type=input.symbol, group = "Inputs to view trends"), [t11, p11, pr11, cr11, tm11] = security(id11, stratRes, OCCmax(id11, Multiplier, Non_Repainting)), array.set(id_, 11, f_rmDnC(id11, spaceSize, rmCurrency , Currency)), array.set(t_, 11, t11), array.set(p_, 11, p11), array.set(pr_, 11, pr11), array.set(cr_, 11, cr11), array.set(tm_, 11, tm11) id12 = input('', title='Symbol 12',type=input.symbol, group = "Inputs to view trends"), [t12, p12, pr12, cr12, tm12] = security(id12, stratRes, OCCmax(id12, Multiplier, Non_Repainting)), array.set(id_, 12, f_rmDnC(id12, spaceSize, rmCurrency , Currency)), array.set(t_, 12, t12), array.set(p_, 12, p12), array.set(pr_, 12, pr12), array.set(cr_, 12, cr12), array.set(tm_, 12, tm12) id13 = input('', title='Symbol 13',type=input.symbol, group = "Inputs to view trends"), [t13, p13, pr13, cr13, tm13] = security(id13, stratRes, OCCmax(id13, Multiplier, Non_Repainting)), array.set(id_, 13, f_rmDnC(id13, spaceSize, rmCurrency , Currency)), array.set(t_, 13, t13), array.set(p_, 13, p13), array.set(pr_, 13, pr13), array.set(cr_, 13, cr13), array.set(tm_, 13, tm13) id14 = input('', title='Symbol 14',type=input.symbol, group = "Inputs to view trends"), [t14, p14, pr14, cr14, tm14] = security(id14, stratRes, OCCmax(id14, Multiplier, Non_Repainting)), array.set(id_, 14, f_rmDnC(id14, spaceSize, rmCurrency , Currency)), array.set(t_, 14, t14), array.set(p_, 14, p14), array.set(pr_, 14, pr14), array.set(cr_, 14, cr14), array.set(tm_, 14, tm14) id15 = input('', title='Symbol 15',type=input.symbol, group = "Inputs to view trends"), [t15, p15, pr15, cr15, tm15] = security(id15, stratRes, OCCmax(id15, Multiplier, Non_Repainting)), array.set(id_, 15, f_rmDnC(id15, spaceSize, rmCurrency , Currency)), array.set(t_, 15, t15), array.set(p_, 15, p15), array.set(pr_, 15, pr15), array.set(cr_, 15, cr15), array.set(tm_, 15, tm15) id16 = input('', title='Symbol 16',type=input.symbol, group = "Inputs to view trends"), [t16, p16, pr16, cr16, tm16] = security(id16, stratRes, OCCmax(id16, Multiplier, Non_Repainting)), array.set(id_, 16, f_rmDnC(id16, spaceSize, rmCurrency , Currency)), array.set(t_, 16, t16), array.set(p_, 16, p16), array.set(pr_, 16, pr16), array.set(cr_, 16, cr16), array.set(tm_, 16, tm16) id17 = input('', title='Symbol 17',type=input.symbol, group = "Inputs to view trends"), [t17, p17, pr17, cr17, tm17] = security(id17, stratRes, OCCmax(id17, Multiplier, Non_Repainting)), array.set(id_, 17, f_rmDnC(id17, spaceSize, rmCurrency , Currency)), array.set(t_, 17, t17), array.set(p_, 17, p17), array.set(pr_, 17, pr17), array.set(cr_, 17, cr17), array.set(tm_, 17, tm17) id18 = input('', title='Symbol 18',type=input.symbol, group = "Inputs to view trends"), [t18, p18, pr18, cr18, tm18] = security(id18, stratRes, OCCmax(id18, Multiplier, Non_Repainting)), array.set(id_, 18, f_rmDnC(id18, spaceSize, rmCurrency , Currency)), array.set(t_, 18, t18), array.set(p_, 18, p18), array.set(pr_, 18, pr18), array.set(cr_, 18, cr18), array.set(tm_, 18, tm18) id19 = input('', title='Symbol 19',type=input.symbol, group = "Inputs to view trends"), [t19, p19, pr19, cr19, tm19] = security(id19, stratRes, OCCmax(id19, Multiplier, Non_Repainting)), array.set(id_, 19, f_rmDnC(id19, spaceSize, rmCurrency , Currency)), array.set(t_, 19, t19), array.set(p_, 19, p19), array.set(pr_, 19, pr19), array.set(cr_, 19, cr19), array.set(tm_, 19, tm19) id20 = input('', title='Symbol 20',type=input.symbol, group = "Inputs to view trends"), [t20, p20, pr20, cr20, tm20] = security(id20, stratRes, OCCmax(id20, Multiplier, Non_Repainting)), array.set(id_, 20, f_rmDnC(id20, spaceSize, rmCurrency , Currency)), array.set(t_, 20, t20), array.set(p_, 20, p20), array.set(pr_, 20, pr20), array.set(cr_, 20, cr20), array.set(tm_, 20, tm20) id21 = input('', title='Symbol 21',type=input.symbol, group = "Inputs to view trends"), [t21, p21, pr21, cr21, tm21] = security(id21, stratRes, OCCmax(id21, Multiplier, Non_Repainting)), array.set(id_, 21, f_rmDnC(id21, spaceSize, rmCurrency , Currency)), array.set(t_, 21, t21), array.set(p_, 21, p21), array.set(pr_, 21, pr21), array.set(cr_, 21, cr21), array.set(tm_, 21, tm21) id22 = input('', title='Symbol 22',type=input.symbol, group = "Inputs to view trends"), [t22, p22, pr22, cr22, tm22] = security(id22, stratRes, OCCmax(id22, Multiplier, Non_Repainting)), array.set(id_, 22, f_rmDnC(id22, spaceSize, rmCurrency , Currency)), array.set(t_, 22, t22), array.set(p_, 22, p22), array.set(pr_, 22, pr22), array.set(cr_, 22, cr22), array.set(tm_, 22, tm22) id23 = input('', title='Symbol 23',type=input.symbol, group = "Inputs to view trends"), [t23, p23, pr23, cr23, tm23] = security(id23, stratRes, OCCmax(id23, Multiplier, Non_Repainting)), array.set(id_, 23, f_rmDnC(id23, spaceSize, rmCurrency , Currency)), array.set(t_, 23, t23), array.set(p_, 23, p23), array.set(pr_, 23, pr23), array.set(cr_, 23, cr23), array.set(tm_, 23, tm23) id24 = input('', title='Symbol 24',type=input.symbol, group = "Inputs to view trends"), [t24, p24, pr24, cr24, tm24] = security(id24, stratRes, OCCmax(id24, Multiplier, Non_Repainting)), array.set(id_, 24, f_rmDnC(id24, spaceSize, rmCurrency , Currency)), array.set(t_, 24, t24), array.set(p_, 24, p24), array.set(pr_, 24, pr24), array.set(cr_, 24, cr24), array.set(tm_, 24, tm24) id25 = input('', title='Symbol 25',type=input.symbol, group = "Inputs to view trends"), [t25, p25, pr25, cr25, tm25] = security(id25, stratRes, OCCmax(id25, Multiplier, Non_Repainting)), array.set(id_, 25, f_rmDnC(id25, spaceSize, rmCurrency , Currency)), array.set(t_, 25, t25), array.set(p_, 25, p25), array.set(pr_, 25, pr25), array.set(cr_, 25, cr25), array.set(tm_, 25, tm25) id26 = input('', title='Symbol 26',type=input.symbol, group = "Inputs to view trends"), [t26, p26, pr26, cr26, tm26] = security(id26, stratRes, OCCmax(id26, Multiplier, Non_Repainting)), array.set(id_, 26, f_rmDnC(id26, spaceSize, rmCurrency , Currency)), array.set(t_, 26, t26), array.set(p_, 26, p26), array.set(pr_, 26, pr26), array.set(cr_, 26, cr26), array.set(tm_, 26, tm26) id27 = input('', title='Symbol 27',type=input.symbol, group = "Inputs to view trends"), [t27, p27, pr27, cr27, tm27] = security(id27, stratRes, OCCmax(id27, Multiplier, Non_Repainting)), array.set(id_, 27, f_rmDnC(id27, spaceSize, rmCurrency , Currency)), array.set(t_, 27, t27), array.set(p_, 27, p27), array.set(pr_, 27, pr27), array.set(cr_, 27, cr27), array.set(tm_, 27, tm27) id28 = input('', title='Symbol 28',type=input.symbol, group = "Inputs to view trends"), [t28, p28, pr28, cr28, tm28] = security(id28, stratRes, OCCmax(id28, Multiplier, Non_Repainting)), array.set(id_, 28, f_rmDnC(id28, spaceSize, rmCurrency , Currency)), array.set(t_, 28, t28), array.set(p_, 28, p28), array.set(pr_, 28, pr28), array.set(cr_, 28, cr28), array.set(tm_, 28, tm28) id29 = input('', title='Symbol 29',type=input.symbol, group = "Inputs to view trends"), [t29, p29, pr29, cr29, tm29] = security(id29, stratRes, OCCmax(id29, Multiplier, Non_Repainting)), array.set(id_, 29, f_rmDnC(id29, spaceSize, rmCurrency , Currency)), array.set(t_, 29, t29), array.set(p_, 29, p29), array.set(pr_, 29, pr29), array.set(cr_, 29, cr29), array.set(tm_, 29, tm29) id30 = input('', title='Symbol 30',type=input.symbol, group = "Inputs to view trends"), [t30, p30, pr30, cr30, tm30] = security(id30, stratRes, OCCmax(id30, Multiplier, Non_Repainting)), array.set(id_, 30, f_rmDnC(id30, spaceSize, rmCurrency , Currency)), array.set(t_, 30, t30), array.set(p_, 30, p30), array.set(pr_, 30, pr30), array.set(cr_, 30, cr30), array.set(tm_, 30, tm30) id31 = input('', title='Symbol 31',type=input.symbol, group = "Inputs to view trends"), [t31, p31, pr31, cr31, tm31] = security(id31, stratRes, OCCmax(id31, Multiplier, Non_Repainting)), array.set(id_, 31, f_rmDnC(id31, spaceSize, rmCurrency , Currency)), array.set(t_, 31, t31), array.set(p_, 31, p31), array.set(pr_, 31, pr31), array.set(cr_, 31, cr31), array.set(tm_, 31, tm31) id32 = input('', title='Symbol 32',type=input.symbol, group = "Inputs to view trends"), [t32, p32, pr32, cr32, tm32] = security(id32, stratRes, OCCmax(id32, Multiplier, Non_Repainting)), array.set(id_, 32, f_rmDnC(id32, spaceSize, rmCurrency , Currency)), array.set(t_, 32, t32), array.set(p_, 32, p32), array.set(pr_, 32, pr32), array.set(cr_, 32, cr32), array.set(tm_, 32, tm32) id33 = input('', title='Symbol 33',type=input.symbol, group = "Inputs to view trends"), [t33, p33, pr33, cr33, tm33] = security(id33, stratRes, OCCmax(id33, Multiplier, Non_Repainting)), array.set(id_, 33, f_rmDnC(id33, spaceSize, rmCurrency , Currency)), array.set(t_, 33, t33), array.set(p_, 33, p33), array.set(pr_, 33, pr33), array.set(cr_, 33, cr33), array.set(tm_, 33, tm33) id34 = input('', title='Symbol 34',type=input.symbol, group = "Inputs to view trends"), [t34, p34, pr34, cr34, tm34] = security(id34, stratRes, OCCmax(id34, Multiplier, Non_Repainting)), array.set(id_, 34, f_rmDnC(id34, spaceSize, rmCurrency , Currency)), array.set(t_, 34, t34), array.set(p_, 34, p34), array.set(pr_, 34, pr34), array.set(cr_, 34, cr34), array.set(tm_, 34, tm34) id35 = input('', title='Symbol 35',type=input.symbol, group = "Inputs to view trends"), [t35, p35, pr35, cr35, tm35] = security(id35, stratRes, OCCmax(id35, Multiplier, Non_Repainting)), array.set(id_, 35, f_rmDnC(id35, spaceSize, rmCurrency , Currency)), array.set(t_, 35, t35), array.set(p_, 35, p35), array.set(pr_, 35, pr35), array.set(cr_, 35, cr35), array.set(tm_, 35, tm35) id36 = input('', title='Symbol 36',type=input.symbol, group = "Inputs to view trends"), [t36, p36, pr36, cr36, tm36] = security(id36, stratRes, OCCmax(id36, Multiplier, Non_Repainting)), array.set(id_, 36, f_rmDnC(id36, spaceSize, rmCurrency , Currency)), array.set(t_, 36, t36), array.set(p_, 36, p36), array.set(pr_, 36, pr36), array.set(cr_, 36, cr36), array.set(tm_, 36, tm36) id37 = input('', title='Symbol 37',type=input.symbol, group = "Inputs to view trends"), [t37, p37, pr37, cr37, tm37] = security(id37, stratRes, OCCmax(id37, Multiplier, Non_Repainting)), array.set(id_, 37, f_rmDnC(id37, spaceSize, rmCurrency , Currency)), array.set(t_, 37, t37), array.set(p_, 37, p37), array.set(pr_, 37, pr37), array.set(cr_, 37, cr37), array.set(tm_, 37, tm37) // { Label list end // { for Label display start var string scr_label = '' var string pot_label = '' var string up_label = '' var string dn_label = '' pot_label := rmCurrency ? '[ Potential Reversal:        ]\n' : '[ Potential Reversal:            ]\n' up_label := rmCurrency ? '[ Uptrend:Profit,ChgRate,#Bars\n' : '[ Uptrend: Profit%, ChgRate,#Bars\n' dn_label := rmCurrency ? '[ Downtrend:              ]\n' : '[ Downtrend:                  ]\n' scr_label := rmCurrency ? '[ Confirmed Reversal:       ]\n' : '[ Confirmed Reversal:           ]\n' up_label := sort_by == "Profit" ? (rmCurrency ? up_label + '|         -------           |\n' : up_label + '|          -----------           |\n') : up_label up_label := sort_by == "Change Rate" ? (rmCurrency ? up_label + '|               --------    |\n' : up_label + '|                 ---------     |\n' ) : up_label up_label := sort_by == "None" ? (rmCurrency ? up_label + '|                         |\n' : up_label + '|                           |\n' ) : up_label // { sorting start var not_blank = array.indexof(id_, rmCurrency ? "    " : "      ") != -1 ? array.indexof(id_, rmCurrency ? "    " : "      ") : array_size arrayForSort = sort_by == "Profit" ? array.copy(pr_) : array.copy(cr_) array.sort(arrayForSort, order.descending) stock_info = '' sorted_index = 0 for i = 0 to not_blank if i == 0 sorted_index := 0 // for id00 = syminfo.tickerid else sorted_index := sort_by == "None" ? i - 1 : sort_by == "Profit" ? array.indexof(pr_, array.get(arrayForSort, i - 1)[0]) : array.indexof(cr_, array.get(arrayForSort, i - 1)[0]) sorted_index := sorted_index != -1 ? sorted_index : 0 stock_info := array.get(id_, sorted_index)[0] + ' ' + f_tostringPad(array.get(pr_, sorted_index)[0], "-??0.00") + ' ' + f_tostringPad(array.get(cr_, sorted_index)[0], "-?0.00") + ' ' + f_tostringPad(array.get(tm_, sorted_index)[0], "???0") + '\n' scr_label := array.get(p_, sorted_index)[0] != array.get(p_, sorted_index)[1] and array.get(t_, sorted_index)[0] != 0 ? scr_label + stock_info : scr_label pot_label := array.get(t_, sorted_index)[0] == 0 ? pot_label + stock_info : pot_label up_label := array.get(t_, sorted_index)[0] == 1 ? up_label + stock_info : up_label dn_label := array.get(t_, sorted_index)[0] == -1 ? dn_label + stock_info : dn_label // } sorting end f_printscr (_txtscr ) => var _lblscr = label(na), label.delete(_lblscr ), _lblscr := label.new( time + (time-time[1])*posX_scr, ohlc4[100] * posY_scr/100.0, _txtscr, xloc.bar_time, yloc.price, showLabel ? #00000000 : na, textcolor = showLabel ? textColor : na, size = size.normal, style = label.style_label_center, textalign = text.align_right ) f_printscr ( scr_label + '\n' + pot_label +'\n' + up_label + '\n' + dn_label) // } for Label display end // }To view trends end
TTM-SQUEEZE STRATEGY
https://www.tradingview.com/script/FbGPdTnr-TTM-SQUEEZE-STRATEGY/
Hodl4dearlife
https://www.tradingview.com/u/Hodl4dearlife/
197
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/ // Β© Hodl4dearlife // create base on http://www.dailyfx.com/forex_forum/coding-strategy-advisors-indicators-functions/237563-ttm-squeeze-indicator.html //@version=4 strategy(title="TTM-SQUEEZE STRATEGY", overlay=false, default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=100, commission_value = 0.1)////////////////////// USER INPUTS ///////////////////////// // Only enter long positions // strategy.risk.allow_entry_in(strategy.direction.long) // Backtest Start Date // startDate = input(title="Start Date", type=input.integer, defval=1, minval=1, maxval=31) startMonth = input(title="Start Month", type=input.integer, defval=1, minval=1, maxval=12) startYear = input(title="Start Year", type=input.integer, defval=2020, minval=1800, maxval=2100) afterStartDate = (time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0)) ////////////////////// USER INPUTS ///////////////////////// useTrend = input(true, title="Use Trend as Indicator", type=input.bool) trendMA = input(100, title="Trend Indicating MA Length") useTrueRange = input(true, title="Use TrueRange (KC)", type=input.bool) activeTrader = input(false, title="Engage Active Trade Mode", type=input.bool) hybridTrader = input(false, title="Engage Hybrid Trade Mode", type=input.bool) safety = input(true, title="Engage Safety Mode", type=input.bool) showMACD = input(true, title="Plot MACD?", type=input.bool) length = input(20, title="BB Length") mult = input(2,title="BB MultFactor") lengthKC=input(20, title="KC Length") multKC = input(1.5, title="KC MultFactor") lbp = input(title="Slope Lookback Periods", type=input.integer, defval= 3, minval = 1) ////////////////////// TTM SQUEEZE VARIABLES ///////////////////////// // Calculate BB // source = close basis = sma(source, length) [middleBB, upperBB, lowerBB] = bb(source, length, mult) // Calculate KC // f_kc(src, length, multKC, useTrueRange) => float base = sma(src, length) float range = (useTrueRange) ? tr : (high - low) float rangeSma = sma(range, length) [base, base + rangeSma * multKC, base - rangeSma * multKC] [middleKC, upperKC, lowerKC] = f_kc(source, length, multKC, useTrueRange) sqzOn = (lowerBB > lowerKC) and (upperBB < upperKC) sqzOff = not sqzOn noSqz = (sqzOn == false) and (sqzOff == false) val = linreg(source - avg(avg(highest(high, lengthKC), lowest(low, lengthKC)),sma(close,lengthKC)), lengthKC,0) ////////////////////// OTHER VARIABLES ///////////////////////// slopeMOM = 10 * ((val - val[lbp])/lbp) maFast = hma(close, 7) maMedium = sma(close, 7) maSlow = wma(close, trendMA) slopeMA = (maSlow - maSlow[lbp])/lbp slopeTrend = slopeMA > 0 lb = 3 mom_PH = pivothigh(val,lb,lb) and val > 0 mom_PL = pivotlow(val,lb,lb) and val < 0 slope_PH = pivothigh(slopeMOM,lb,lb) and val > 0 slope_PL = pivotlow(slopeMOM,lb,lb) and val < 0 up = close > open dwn = close < open [macdLine, signalLine, _] = macd(close, 12, 26, 9) macdArea = macdLine - signalLine macdBear = crossunder(macdLine, signalLine) ////////////////////// TRIGGER CONDITIONS ///////////////////////// ///buy = sqzOff and sqzOn[1] and up buy = sqzOn and slopeTrend //sell = sqzOff and sqzOn[1] and dwn sell = macdBear buy_A = sqzOn[1] and maFast > maMedium sell_A = maFast < maMedium crossUp = showMACD and crossover(macdLine, signalLine) crossDwn = showMACD and crossunder(macdLine, signalLine) ////////////////////// PLOT VARIABLES ///////////////////////// plotMACD = if showMACD color.teal else na plotSignal = if showMACD color.red else na bcolor = iff( val > 0, iff( val > nz(val[1]), color.olive, color.gray), iff( val < nz(val[1]), color.maroon, color.gray)) scolor = sqzOn ? color.red : color.green plot(val, color=bcolor, style=plot.style_histogram, linewidth=4, transp = 50) plot(0, color=scolor, style=plot.style_circles, linewidth=3) plot(macdLine, color=plotMACD, style=plot.style_line, linewidth=2) plot(signalLine, color=plotSignal, style=plot.style_line, linewidth=2) bgcolor(color=(buy[1] and not buy[2]) ? color.green : na, transp = 80) bgcolor(color=(sell[1] and not sell[2]) ? color.red : na, transp = 80) ////////////////////// PLACE ORDERS ///////////////////////// if(not activeTrader and not hybridTrader and not useTrend and buy and afterStartDate) strategy.entry("Buy - Long Term", long=true) if(not activeTrader and not hybridTrader and not useTrend and sell and afterStartDate) strategy.close("Buy - Long Term") if(not activeTrader and not hybridTrader and useTrend and slopeMA > 0 and buy and afterStartDate) strategy.entry("Buy - Long Term", long=true) if(not activeTrader and not hybridTrader and useTrend and sell and afterStartDate) strategy.close("Buy - Long Term") /// Active Trader Mode /// if(not useTrend and not hybridTrader and activeTrader and buy_A and afterStartDate) strategy.entry("Buy - Active Trading", long=true) if(not useTrend and not hybridTrader and activeTrader and sell_A and afterStartDate) strategy.close("Buy - Active Trading") if(not hybridTrader and useTrend and slopeMA > 0 and activeTrader and buy_A and afterStartDate) strategy.entry("Buy - Active Trading", long=true) if(not hybridTrader and useTrend and activeTrader and sell_A and afterStartDate) strategy.close("Buy - Active Trading") /// HYBRID MODE /// if(hybridTrader and not useTrend and buy and afterStartDate) strategy.entry("Buy - Long Term", long=true) if(not useTrend and hybridTrader and sell and afterStartDate) strategy.close("Buy - Long Term") if(useTrend and hybridTrader and slopeMA > 0 and buy and afterStartDate) strategy.entry("Buy - Long Term", long=true) if(useTrend and hybridTrader and sell and afterStartDate) strategy.close("Buy - Long Term") if(not useTrend and hybridTrader and buy_A and afterStartDate) strategy.entry("Buy - Active Trading", long=true) if(not useTrend and hybridTrader and sell_A and afterStartDate) strategy.close("Buy - Active Trading") if(useTrend and hybridTrader and slopeMA > 0 and activeTrader and buy_A and afterStartDate) strategy.entry("Buy - Active Trading", long=true) if(useTrend and hybridTrader and sell_A and afterStartDate) strategy.close("Buy - Active Trading") if(safety and sqzOff) strategy.exit("Sell Safety", "Buy - Long Term", stop = lowerBB)
RSI Mean Reversion Bot Strategy
https://www.tradingview.com/script/PhfmO5kT-RSI-Mean-Reversion-Bot-Strategy/
Solutions1978
https://www.tradingview.com/u/Solutions1978/
407
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ //@version=4 // β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•— β–ˆβ–ˆβ•— //β–ˆβ–ˆβ•”β•β•β•β•β•β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β•β•β•β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β•šβ•β•β–ˆβ–ˆβ•”β•β•β•β–ˆβ–ˆβ•”β•β•β•β•β•β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•— β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β•šβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•”β• //β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β• β•šβ–ˆβ–ˆβ–ˆβ–ˆβ•”β• //β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β• β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β•β•β• β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•— β•šβ–ˆβ–ˆβ•”β• //β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β• β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β• β–ˆβ–ˆβ•‘ // β•šβ•β•β•β•β•β•β•šβ•β• β•šβ•β•β•šβ•β•β•β•β•β•β•β•šβ•β• β•šβ•β• β•šβ•β• β•šβ•β•β•β•β•β•β•β•šβ•β•β•β•β•β• β•šβ•β•β•β•β•β• β•šβ•β• //β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•— β–ˆβ–ˆβ•— β–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— //β–ˆβ–ˆβ•”β•β•β•β•β•β–ˆβ–ˆβ•”β•β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β•šβ•β•β–ˆβ–ˆβ•”β•β•β•β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β•β•β•β–ˆβ–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β•šβ•β•β•β•β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•— //β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β–ˆβ–ˆβ•— β–ˆβ–ˆβ•‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β•šβ–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β•β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β• //β•šβ•β•β•β•β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘β•šβ•β•β•β•β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β•šβ•β•β•β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β• β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•— //β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β• β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ•‘ β•šβ–ˆβ–ˆβ–ˆβ–ˆβ•‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β• β–ˆβ–ˆβ•‘ β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β• //β•šβ•β•β•β•β•β•β• β•šβ•β•β•β•β•β• β•šβ•β•β•β•β•β•β• β•šβ•β•β•β•β•β• β•šβ•β• β•šβ•β• β•šβ•β•β•β•β•β• β•šβ•β• β•šβ•β•β•β•β•šβ•β•β•β•β•β•β• β•šβ•β• β•šβ•β•β•β•β• β•šβ•β• β•šβ•β•β•β•β• strategy(shorttitle='RSI Bot Strategy v3',title='Holy Grail RSI Strategy', overlay=true, scale=scale.left, initial_capital = 1000, process_orders_on_close=true, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type=strategy.commission.percent, commission_value=0.18, calc_on_every_tick=true) kcolor = color.new(#0094FF, 60) dcolor = color.new(#FF6A00, 60) // ----------------- Strategy Inputs ------------------------------------------------------------- //Backtest dates with auto finish date of today start = input(defval = timestamp("01 April 2021 00:00 -0500"), title = "Start Time", type = input.time) finish = input(defval = timestamp("31 December 2021 00:00 -0600"), title = "End Time", type = input.time) window() => time >= start and time <= finish ? true : false // create function "within window of time" // Strategy Selection - Long, Short, or Both stratinfo = input(true, "Long/Short for Mixed Market, Long for Bull, Short for Bear") strat = input(title="Trade Types", defval="Long/Short", options=["Long Only", "Long/Short", "Short Only"]) strat_val = strat == "Long Only" ? 1 : strat == "Long/Short" ? 0 : -1 // Risk Management Inputs sl = input(10.0, "Stop Loss %", minval = 0, maxval = 100, step = 0.01) tp = input(20.0, "Target Profit %", minval = 0, maxval = 100, step = 0.01) stoploss = sl/100 TargetProfit = tp/100 // RSI Inputs RSIinfo = input(true, "RSI Strategy Inputs") length = input(14, minval=1) source = input(title="Source", type=input.source, defval=close) overbought = input(60, "Overbought") oversold = input(30, "Oversold") // Stochastic Inputs Stochinfo = input(true, "Stochastic Overlay Inputs") smoothK = input(3, "K", minval=1) smoothD = input(3, "D", minval=1) k_mode = input("SMA", "K Mode", options=["SMA", "EMA", "WMA"]) //EMA Inputs EMAInfo = input(true, "EMA Fast and Slow Length Inputs") fastLength = input(5, minval=1, title="EMA Fast Length") slowLength = input(10, minval=1, title="EMA Slow Length") VWAPSource = input(title="VWAP Source", type=input.source, defval=close) // Selections to show or hide the overlays showZones = input(true, title="Show Bullish/Bearish Zones") showStoch = input(true, title="Show Stochastic Overlays") // ------------------ Background Colors based on EMA Indicators ----------------------------------- haClose(gap) => (open[gap] + high[gap] + low[gap] + close[gap]) / 4 rsi_ema = rsi(haClose(0), length) v2 = ema(rsi_ema, length) v3 = 2 * v2 - ema(v2, length) emaA = ema(rsi_ema, fastLength) emaFast = 2 * emaA - ema(emaA, fastLength) emaB = ema(rsi_ema, slowLength) emaSlow = 2 * emaB - ema(emaB, slowLength) vwapVal = vwap(VWAPSource) // bullish signal rule: bullishRule =emaFast > emaSlow and close>open and close>vwapVal // bearish signal rule: bearishRule =emaFast < emaSlow and close<open and close<vwapVal // current trading State ruleState = 0 ruleState := bullishRule ? 1 : bearishRule ? -1 : nz(ruleState[1]) ruleColor = ruleState==1 ? color.new(color.blue, 90) : ruleState == -1 ? color.new(color.red, 90) : ruleState == 0 ? color.new(color.gray, 90) : na bgcolor(showZones ? ruleColor : na, title="Bullish/Bearish Zones") // ------------------ Stochastic Indicator Overlay ----------------------------------------------- // Calculation rsi1 = rsi(source, length) stoch = stoch(rsi1, rsi1, rsi1, length) k = k_mode=="EMA" ? ema(stoch, smoothK) : k_mode=="WMA" ? wma(stoch, smoothK) : sma(stoch, smoothK) d = sma(k, smoothD) k_c = change(k) d_c = change(d) kd = k - d // Plot signalColor = k>oversold and d<overbought and k>d and k_c>0 and d_c>0 ? kcolor : k<overbought and d>oversold and k<d and k_c<0 and d_c<0 ? dcolor : na kp = plot(showStoch ? k : na, "K", color=kcolor) dp = plot(showStoch ? d : na, "D", color=dcolor) fill(kp, dp, color = signalColor, title="K-D") signalUp = showStoch ? not na(signalColor) and kd>0 : na signalDown = showStoch ? not na(signalColor) and kd<0 : na plot(signalUp ? kd : na, "Signal Up", color=kcolor, style=plot.style_columns) plot(signalDown ? (kd+100) : na , "Signal Down", color=dcolor, style=plot.style_columns, histbase=100) // Add RSI Candle Plot to Strategy for better visualization //overlay RSI h0 = hline(oversold, title="Oversold", color=color.green) h1 = hline(overbought, title="Overbought", color=color.red) RSIFill = color.new(#9915FF, 95) fill(h0, h1, RSIFill, title="Band Background") plot(rsi1, title="RSI", color=color.yellow, linewidth=3) // End Plot Code // -------------------------------- Entry and Exit Logic ------------------------------------ // Entry Logic GoLong = strat_val>-1 and crossover(rsi1, oversold) and strategy.position_size==0 and window() GoShort = strat_val<1 and crossunder(rsi1, overbought) and strategy.position_size==0 and window() // Strategy Entry and Exit with built in Risk Management if (GoLong) strategy.entry("LONG", strategy.long) if (GoShort) strategy.entry("SHORT", strategy.short) CloseLong = strat_val > -1 and strategy.position_size > 0 and crossover(rsi1, overbought) and window() CloseShort = strat_val < 1 and strategy.position_size < 0 and crossunder(rsi1, oversold) and window() if(CloseLong) strategy.close("LONG") if(CloseShort) strategy.close("SHORT") // Determine where you've entered and in what direction longStopPrice = strategy.position_avg_price * (1 - stoploss) longTakePrice = strategy.position_avg_price * (1 + TargetProfit) shortStopPrice = strategy.position_avg_price * (1 + stoploss) shortTakePrice = strategy.position_avg_price * (1 - TargetProfit) if (strategy.position_size > 0) strategy.exit(id="Exit Long", from_entry = "LONG", stop = longStopPrice, limit = longTakePrice) if (strategy.position_size < 0) strategy.exit(id="Exit Short", from_entry = "SHORT", stop = shortStopPrice, limit = shortTakePrice) //PLOT FIXED SLTP LINE plot(strategy.position_size > 0 ? longStopPrice : na, style=plot.style_linebr, color=color.red, linewidth=1, title="Long Fixed SL") plot(strategy.position_size < 0 ? shortStopPrice : na, style=plot.style_linebr, color=color.red, linewidth=1, title="Short Fixed SL") plot(strategy.position_size > 0 ? longTakePrice : na, style=plot.style_linebr, color=color.green, linewidth=1, title="Long Take Profit") plot(strategy.position_size < 0 ? shortTakePrice : na, style=plot.style_linebr, color=color.green, linewidth=1, title="Short Take Profit")
ETF trader
https://www.tradingview.com/script/bz1II9Sg-ETF-trader/
FX_minds
https://www.tradingview.com/u/FX_minds/
39
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/ // Β© FX_minds //@version=4 strategy("ETF trader", overlay=true, pyramiding=100, default_qty_type=strategy.percent_of_equity, default_qty_value=100) //------------------------------ get user input lookback = input(title="HH LL lookback", type=input.integer, defval=20) ATR_periode = input(title="ATR period", type=input.integer, defval=14) ATR_SL_multiplier = input(title="ATR SL multiplier", type=input.float, defval=2) ATR_TP_multiplier = input(title="ATR TP multiplier", type=input.float, defval=1) trailing_SL_ATR_multiplier = input(title="ATR trailing SL multiplier", type=input.float, defval=3.5) lookback_trailing_SL = input(title="trailing SL lookback", type=input.integer, defval=4) max_sequel_trades = input(title="max sequel trades", type=input.float, defval=1) trade_long = input(title= "trade long ?", type=input.bool, defval=true) trade_short = input(title= "trade short ?", type=input.bool, defval=false) //------------------------------ determine entry conditions long_condition = barstate.isconfirmed and crossover(high, highest(high, lookback)[1]) short_condition = barstate.isconfirmed and crossunder(low, lowest(low, lookback)[1]) //------------------------------ count open long trades count_open_longs = 0 count_open_longs := nz(count_open_longs[1]) if (long_condition) count_open_longs := count_open_longs +1 //label.new(bar_index, low, tostring(count_open_longs, "#"), xloc.bar_index, yloc.belowbar, color.green, label.style_none, color.green, size.large) if (short_condition) count_open_longs := 0 //------------------------------ count open short trades count_open_shorts = 0 count_open_shorts := nz(count_open_shorts[1]) if (short_condition) count_open_shorts := count_open_shorts +1 //label.new(bar_index, low, tostring(count_open_shorts, "#"), xloc.bar_index, yloc.belowbar, color.red, label.style_none, color.red, size.large) if (long_condition) count_open_shorts := 0 //------------------------------ calculate entryprice entryprice_long = long_condition ? close : na entryprice_short = short_condition ? close : na //------------------------------ calculate SL & TP SL_distance = atr(ATR_periode) * ATR_SL_multiplier TP_distance = atr(ATR_periode) * ATR_TP_multiplier trailing_SL_distance = atr(ATR_periode) * trailing_SL_ATR_multiplier SL_long = entryprice_long - SL_distance SL_short = entryprice_short + SL_distance trailing_SL_short = lowest(close, lookback_trailing_SL) + trailing_SL_distance trailing_SL_long = highest(close, lookback_trailing_SL) - trailing_SL_distance trailing_SL_short_signal = crossover(high, trailing_SL_short[1]) trailing_SL_long_signal = crossunder(low, trailing_SL_long[1]) //------------------------------ plot entry price & SL plot(entryprice_long, style=plot.style_linebr, color=color.white) plot(SL_long, style=plot.style_linebr, color=color.red) plot(SL_short, style=plot.style_linebr, color=color.green) plot(trailing_SL_short, style=plot.style_linebr, color=color.red) plot(trailing_SL_long, style=plot.style_linebr, color=color.green) //------------------------------ submit entry orders if (long_condition) and (count_open_longs <= max_sequel_trades) and (trade_long == true) strategy.entry("Long" + tostring(count_open_longs, "#"), strategy.long) strategy.exit("SL Long"+ tostring(count_open_longs, "#"), from_entry="Long" + tostring(count_open_longs, "#"), stop=SL_long) if (short_condition) and (count_open_shorts <= max_sequel_trades) and (trade_short == true) strategy.entry("Short" + tostring(count_open_shorts, "#"), strategy.short) strategy.exit("SL Short" + tostring(count_open_shorts, "#"), from_entry="Short" + tostring(count_open_shorts, "#"), stop=SL_short) //------------------------------ submit exit conditions if (trailing_SL_long_signal) strategy.close("Long" + tostring(count_open_longs, "#")) strategy.close("Long" + tostring(count_open_longs-1, "#")) strategy.close("Long" + tostring(count_open_longs-2, "#")) strategy.close("Long" + tostring(count_open_longs-4, "#")) strategy.close("Long" + tostring(count_open_longs-5, "#")) strategy.close("Long" + tostring(count_open_longs-6, "#")) strategy.close("Long" + tostring(count_open_longs-7, "#")) strategy.close("Long" + tostring(count_open_longs-8, "#")) strategy.close("Long" + tostring(count_open_longs-9, "#")) if (trailing_SL_short_signal) strategy.close("Short" + tostring(count_open_shorts, "#")) strategy.close("Short" + tostring(count_open_shorts-1, "#")) strategy.close("Short" + tostring(count_open_shorts-2, "#")) strategy.close("Short" + tostring(count_open_shorts-3, "#")) strategy.close("Short" + tostring(count_open_shorts-4, "#")) strategy.close("Short" + tostring(count_open_shorts-5, "#")) strategy.close("Short" + tostring(count_open_shorts-6, "#")) strategy.close("Short" + tostring(count_open_shorts-7, "#")) strategy.close("Short" + tostring(count_open_shorts-8, "#")) strategy.close("Short" + tostring(count_open_shorts-9, "#"))
Buy and Hold entry finder Strategy
https://www.tradingview.com/script/dxmtiTqW-Buy-and-Hold-entry-finder-Strategy/
Embit0one
https://www.tradingview.com/u/Embit0one/
240
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/ // Β© runescapeyttanic //@version=4 strategy("Buy and Hold entry finder Strategy",pyramiding=10000, overlay=true,initial_capital=0,default_qty_type=strategy.cash,default_qty_value=1000,currency = currency.EUR,commission_type=strategy.commission.cash_per_order,commission_value=0) //INPUTS################################################################################################################## maxEmaDistance = input(title="Maximum EMA Distance", type=input.float, step=0.01, defval=50000) emalength = input(title="EMA Length", type=input.integer,defval=200) // Make input options that configure backtest date range startDate = input(title="Start Date", type=input.integer, defval=1, minval=1, maxval=31) startMonth = input(title="Start Month", type=input.integer, defval=1, minval=1, maxval=12) startYear = input(title="Start Year", type=input.integer, defval=2020, minval=1800, maxval=2100) endDate = input(title="End Date", type=input.integer, defval=12, minval=1, maxval=31) endMonth = input(title="End Month", type=input.integer, defval=02, minval=1, maxval=12) endYear = input(title="End Year", type=input.integer, defval=2021, minval=1800, maxval=2100) endDate1=endDate-1 //starttag //startmonat //MACD######################################################################################################################## fast_length=12 slow_length=26 src=close col_macd=#0094ff fast_ma = ema(src, fast_length) slow_ma = ema(src, slow_length) macd = fast_ma - slow_ma //EMA Distance CALC######################################################################################################## ma1 =ema(close,emalength) distFromMean = close - ma1 inDateRange = (time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0)) and (time < timestamp(syminfo.timezone, endYear, endMonth, endDate1, 0, 0)) longCondition = (distFromMean<=maxEmaDistance and distFromMean>=distFromMean[1] and macd<=0 and inDateRange) longnow=false if(longCondition and strategy.position_size == 0) strategy.entry("My Long Entry Id", strategy.long) longnow:=true if(longCondition and strategy.position_size > 0) longnow:=true if(longCondition and strategy.position_size > 0 and month>valuewhen(longnow, month ,1) or longCondition and strategy.position_size > 0 and year>valuewhen(longnow, year ,1) and inDateRange) strategy.entry("My Long Entry Id", strategy.long) plotchar(minute, "Minuten", "", location = location.top) plotchar(hour, "Stunden", "", location = location.top) plotchar(dayofmonth, "Tage", "", location = location.top) plotchar(month, "Monat", "", location = location.top) plotchar(year, "Jahr", "", location = location.top) plotchar(strategy.position_size, "Positionen", "", location = location.top) plotchar(longCondition, "Long Condition", "", location = location.top) if(time > timestamp(syminfo.timezone, endYear, endMonth, endDate1, 0, 0)) strategy.close_all() //######################################################################################################################### plotArrow = if (distFromMean<=maxEmaDistance and distFromMean>=distFromMean[1] and macd<=0) 1 else 0 plotarrow(series=plotArrow)
Equal-Length EMA/SMA Crossover Momentum Strategy
https://www.tradingview.com/script/fmMKWEs0-Equal-Length-EMA-SMA-Crossover-Momentum-Strategy/
Cryptoluc1d
https://www.tradingview.com/u/Cryptoluc1d/
117
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/ // Β© Cryptoluc1d //@version=4 strategy("Equal-Length EMA/SMA Crossover Strategy", initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=25, commission_type=strategy.commission.percent, commission_value=0.2, overlay=true) // Create inputs mom_length = input(title="Momentum Length (EMA=SMA)", defval=50) bias_length_fast = input(title="Golden Cross Length (Fast)", defval=50) bias_length_slow = input(title="Golden Cross Length (Slow)", defval=100) // Define MAs ema = ema(close, mom_length) // EMA/SMA crossover of the same period for detecting trend acceleration/deceleration sma = sma(close, mom_length) bias_fast = sma(close, bias_length_fast) // golden/death cross for overall trend bias bias_slow = sma(close, bias_length_slow) // Define signal conditions buy_trend = crossover(ema, sma) and bias_fast >= bias_slow // buy when EMA cross above SMA. if this happens during a bullish golden cross, buying is in confluence with the overall trend (bias). buy_risky = crossover(ema, sma) and bias_fast < bias_slow // buy when EMA cross above SMA. if this happens during a bearish death cross, buying is early, more risky, and not in confluence with the overall trend (bias). buy_late = crossover(sma, bias_slow) and ema > sma // the SMA crossing the Slow_SMA gives further confirmation of bullish trend, but signal comes later. sell = crossunder(ema, sma) // sell when EMA cross under SMA. // Enable option to hide signals, then plot signals show_signal = input(title="Show Signals", defval=true) plotshape(show_signal ? buy_trend : na, title='Trend Buy', style=shape.triangleup, location=location.belowbar, color=color.green, text='TREND BUY') plotshape(show_signal ? buy_risky : na, title='Risky Buy', style=shape.triangleup, location=location.belowbar, color=color.olive, text='RISKY BUY') plotshape(show_signal ? buy_late : na, title='Late Buy', style=shape.triangleup, location=location.belowbar, color=color.lime, text='LATE BUY') plotshape(show_signal ? sell : na, title='Sell', style=shape.triangledown, location=location.abovebar, color=color.red, text='SELL') // Define entry and exit conditions longCondition = ema > sma and bias_fast >= bias_slow // LONG when EMA above SMA, and overall trend bias is bullish if (longCondition) strategy.entry("BUY TREND", strategy.long) exitLong = crossunder(ema, sma) // close LONG when EMA cross under SMA strategy.close("BUY TREND", when=exitLong) // // short conditions. turned off because up only. // shortCondition = ema < sma and bias_fast <= bias_slow // SHORT when EMA under SMA, and overall trend bias is bearish // if (shortCondition) // strategy.entry("SELL TREND", strategy.short) // exitShort = crossover(ema, sma) // close SHORT when EMA cross over SMA // strategy.close("SELL TREND", when=exitShort) // Enable option to show MAs, then plot MAs show_ma = input(title="Show MAs", defval=false) plot(show_ma ? ema : na, title="Momentum EMA", color=color.green, linewidth=1) plot(show_ma ? sma : na, title="Momentum SMA", color=color.yellow, linewidth=1) plot(show_ma ? bias_fast : na, title="Golden Cross SMA (Fast)", color=color.orange, linewidth=2) plot(show_ma ? bias_slow : na, title="Golden Cross SMA (Slow)", color=color.red, linewidth=2)
Please help to make Larry Williams' volatility breakthrough.
https://www.tradingview.com/script/Du8sJ2tf/
kgp1202
https://www.tradingview.com/u/kgp1202/
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/ // β“’ kgp1202 //@version=4 strategy("larry wiliams", overlay=true) R = 0.5 range = high[1] - low[1] buy_price = open + R * range plot(buy_price) if bar_index > 6000 strategy.entry("BUY", strategy.long, stop=buy_price, when=strategy.position_size == 0) strategy.close("BUY")
Example of Simple RSI Buy/Sell at a level and hold for 10 days
https://www.tradingview.com/script/WbZjbqlo-Example-of-Simple-RSI-Buy-Sell-at-a-level-and-hold-for-10-days/
sevendays
https://www.tradingview.com/u/sevendays/
61
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/ // Β© Bitduke //@version=4 strategy("Simple RSI Buy/Sell at a level", shorttitle="Simple RSI Strategy", overlay=true,calc_on_every_tick=false,pyramiding=1, default_qty_type=strategy.cash,default_qty_value=1000, currency=currency.USD, initial_capital=1000,commission_type=strategy.commission.percent, commission_value=0.075) overbought = input(40, title="overbought value") oversold = input(30, title="oversold value") // Component Test Periods Code Begin testStartYear = input(2018, "Backtest Start Year") testStartMonth = input(1, "Backtest Start Month") testStartDay = input(1, "Backtest Start Day") testPeriodStart = timestamp(testStartYear,testStartMonth,testStartDay,0,0) testStopYear = input(2021, "Backtest Stop Year") testStopMonth = input(16, "Backtest Stop Month") testStopDay = input(2, "Backtest Stop Day") testPeriodStop = timestamp(testStopYear,testStopMonth,testStopDay,0,0) // A switch to control background coloring of the test period testPeriodBackground = input(title="Color Background?", type=input.bool, defval=true) testPeriodBackgroundColor = testPeriodBackground and (time >= testPeriodStart) and (time <= testPeriodStop) ? #00FF00 : na bgcolor(testPeriodBackgroundColor, transp=97) testPeriod() => time >= testPeriodStart and time <= testPeriodStop ? true : false // Component Test Periods Code End ////////////////////////////////////////////////////////////////////// myrsi = rsi(close, 10) > overbought myrsi2 = rsi(close, 10) < oversold barcolor(myrsi ? color.black : na) barcolor(myrsi2 ? color.blue : na) myEntry = myrsi2 and hour(time) <= 9 strategy.entry("Buy Signal", strategy.long, when = myEntry and testPeriod()) // Close 10 bar periods after the condition that triggered the entry //if (myEntry[10]) //strategy.close("Buy Signal") strategy.close("Buy Signal", when = barssince(myEntry) >= 10 or myrsi and testPeriod()) //strategy.entry("Sell Signal",strategy.short, when = myrsi2)
EMA Cross Strategy
https://www.tradingview.com/script/fAxX6kbm-EMA-Cross-Strategy/
kirilov
https://www.tradingview.com/u/kirilov/
1,404
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/ // This strategy has been created for illustration purposes only and should not be relied upon as a basis for buying, selling, or holding any asset or security. // Β© kirilov //@version=4 strategy( "EMA Cross Strategy", overlay=true, calc_on_every_tick=true, currency=currency.USD ) // INPUT: // Options to enter fast and slow Exponential Moving Average (EMA) values emaFast = input(title="Fast EMA", type=input.integer, defval=10, minval=1, maxval=9999) emaSlow = input(title="Slow EMA", type=input.integer, defval=20, minval=1, maxval=9999) // Option to select trade directions tradeDirection = input(title="Trade Direction", options=["Long", "Short", "Both"], defval="Both") // Options that configure the backtest date range startDate = input(title="Start Date", type=input.time, defval=timestamp("01 Jan 1970 00:00")) endDate = input(title="End Date", type=input.time, defval=timestamp("31 Dec 2170 23:59")) // CALCULATIONS: // Use the built-in function to calculate two EMA lines fastEMA = ema(close, emaFast) slowEMA = ema(close, emaSlow) // PLOT: // Draw the EMA lines on the chart plot(series=fastEMA, color=color.orange, linewidth=2) plot(series=slowEMA, color=color.blue, linewidth=2) // CONDITIONS: // Check if the close time of the current bar falls inside the date range inDateRange = (time >= startDate) and (time < endDate) // Translate input into trading conditions longOK = (tradeDirection == "Long") or (tradeDirection == "Both") shortOK = (tradeDirection == "Short") or (tradeDirection == "Both") // Decide if we should go long or short using the built-in functions longCondition = crossover(fastEMA, slowEMA) shortCondition = crossunder(fastEMA, slowEMA) // ORDERS: // Submit entry (or reverse) orders if (longCondition and inDateRange) strategy.entry(id="long", long=true, when = longOK) if (shortCondition and inDateRange) strategy.entry(id="short", long=false, when = shortOK) // Submit exit orders in the cases where we trade only long or only short if (strategy.position_size > 0 and shortCondition) strategy.exit(id="exit long", stop=close) if (strategy.position_size < 0 and longCondition) strategy.exit(id="exit short", stop=close)
Ichimoku Strategy [CDI]
https://www.tradingview.com/script/FbFNuM6u/
JMLSlop
https://www.tradingview.com/u/JMLSlop/
231
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/ // Β© JMLSlop //@version=4 strategy("Ichimoku Strategy [CDI]", shorttitle="Ichimoku Strategy", overlay=true, pyramiding=3, calc_on_order_fills=false ) conversionPeriods = input(9, minval=1, title="Conversion Line Periods") basePeriods = input(26, minval=1, title="Base Line Periods") laggingSpan2Periods = input(52, minval=1, title="Lagging Span 2 Periods") displacement = input(26, minval=1, title="Displacement") limmit = input(6, minval=1, title="Profit %") * 0.01 stop = input(3, minval=1, title="Loss %") * 0.01 PreBars = input(6, minval=2, title="Crossing Candles:") donchian(len) => avg(lowest(len), highest(len)) conversionLine = donchian(conversionPeriods) baseLine = donchian(basePeriods) leadLine1 = offset(avg(conversionLine, baseLine),displacement - 1) leadLine2 = offset(donchian(laggingSpan2Periods),displacement - 1) leadLine1ax = avg(conversionLine, baseLine) leadLine2ax = donchian(laggingSpan2Periods) plot(conversionLine, color=#0496ff, title="Conversion Line", display=display.none) plot(baseLine, color=#991515, title="Base Line", display=display.none) plot(close, offset = -displacement + 1, color=#459915, title="Lagging Span", display=display.none) p1 = plot(leadLine1ax, offset = displacement - 1, color=color.green, title="Lead 1",display=display.none) p2 = plot(leadLine2ax, offset = displacement - 1, color=color.red, title="Lead 2",display=display.none) fill(p1, p2, color = leadLine1ax > leadLine2ax ? color.green : color.red) // Orders config higherLine = leadLine1 > leadLine2 ? leadLine1 : leadLine2 downLine = leadLine1 < leadLine2 ? leadLine1 : leadLine2 crossConfim = false var float auxlead = na for i = 1 to PreBars auxlead := leadLine1[i] < leadLine2 [i] ? leadLine1[i] : leadLine2[i] crossConfim:= crossConfim or (auxlead >= open[i]) or auxlead >= close[i] conditionEntry = (open > higherLine or close > higherLine) and crossConfim and (open[1] < higherLine[1] and close[1] < higherLine[1]) barColour = if (conditionEntry) alert("Price (" + tostring(close) + ") crossed over Ichimoku Strategy.", alert.freq_all) color.yellow else na barcolor(color=barColour) bgcolor(color=barColour) takeProfitPrice = 0.0 longStopPrice = 0.0 takeProfitPrice := conditionEntry and strategy.position_size == 0 ? close + (close * limmit) : takeProfitPrice[1] longStopPrice := conditionEntry ? close - (close * stop) : longStopPrice[1] if (conditionEntry) strategy.entry("Entry", strategy.long) strategy.exit("Exit", limit=takeProfitPrice, stop=longStopPrice) //alertcondition(condition=conditionEntry,title="Crossover Ichimoku",message="Price (" + tostring(close) + ") crossed over Ichimoku Strategy.")
Moving Regression Band Breakout strategy
https://www.tradingview.com/script/Tls8Y2hc-Moving-Regression-Band-Breakout-strategy/
tbiktag
https://www.tradingview.com/u/tbiktag/
2,094
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/ // Β© tbiktag // // Moving Regression Band Breakout strategy // // The strategy based on the Moving Regression Prediction Bands indicator: // // https://www.tradingview.com/script/zOaMXJ65-Moving-Regression-Prediction-Bands/ // // Entry condition: // Long: the price crosses the Upper Band from below. // Short: the price crosses the Lower Band from above. // Exit condition Long: // the price crosses the Lower Band (the Lower Band - ATR, or Central Line) // Exit condition Short: // the price crosses the Upper Band (the Upper Band + ATR, or Central Line) // // //@version=4 strategy("Moving Regression Band Breakout strategy", shorttitle = "MRBand Strat", overlay=true) matrix_get(_A,_i,_j,_nrows) => // Get the value of the element of an implied 2d matrix //input: // _A :: array: pseudo 2d matrix _A = [[column_0],[column_1],...,[column_(n-1)]] // _i :: integer: row number // _j :: integer: column number // _nrows :: integer: number of rows in the implied 2d matrix array.get(_A,_i+_nrows*_j) matrix_set(_A,_value,_i,_j,_nrows) => // Set a value to the element of an implied 2d matrix //input: // _A :: array, changed on output: pseudo 2d matrix _A = [[column_0],[column_1],...,[column_(n-1)]] // _value :: float: the new value to be set // _i :: integer: row number // _j :: integer: column number // _nrows :: integer: number of rows in the implied 2d matrix array.set(_A,_i+_nrows*_j,_value) transpose(_A,_nrows,_ncolumns) => // Transpose an implied 2d matrix // input: // _A :: array: pseudo 2d matrix _A = [[column_0],[column_1],...,[column_(n-1)]] // _nrows :: integer: number of rows in _A // _ncolumns :: integer: number of columns in _A // output: // _AT :: array: pseudo 2d matrix with implied dimensions: _ncolums x _nrows var _AT = array.new_float(_nrows*_ncolumns,0) for i = 0 to _nrows-1 for j = 0 to _ncolumns-1 matrix_set(_AT, matrix_get(_A,i,j,_nrows),j,i,_ncolumns) _AT multiply(_A,_B,_nrowsA,_ncolumnsA,_ncolumnsB) => // Calculate scalar product of two matrices // input: // _A :: array: pseudo 2d matrix // _B :: array: pseudo 2d matrix // _nrowsA :: integer: number of rows in _A // _ncolumnsA :: integer: number of columns in _A // _ncolumnsB :: integer: number of columns in _B // output: // _C:: array: pseudo 2d matrix with implied dimensions _nrowsA x _ncolumnsB var _C = array.new_float(_nrowsA*_ncolumnsB,0) int _nrowsB = _ncolumnsA float elementC= 0.0 for i = 0 to _nrowsA-1 for j = 0 to _ncolumnsB-1 elementC := 0 for k = 0 to _ncolumnsA-1 elementC := elementC + matrix_get(_A,i,k,_nrowsA)*matrix_get(_B,k,j,_nrowsB) matrix_set(_C,elementC,i,j,_nrowsA) _C vnorm(_X,_n) => //Square norm of vector _X with size _n float _norm = 0.0 for i = 0 to _n-1 _norm := _norm + pow(array.get(_X,i),2) sqrt(_norm) qr_diag(_A,_nrows,_ncolumns) => //QR Decomposition with Modified Gram-Schmidt Algorithm (Column-Oriented) // input: // _A :: array: pseudo 2d matrix _A = [[column_0],[column_1],...,[column_(n-1)]] // _nrows :: integer: number of rows in _A // _ncolumns :: integer: number of columns in _A // output: // _Q: unitary matrix, implied dimenstions _nrows x _ncolumns // _R: upper triangular matrix, implied dimansions _ncolumns x _ncolumns var _Q = array.new_float(_nrows*_ncolumns,0) var _R = array.new_float(_ncolumns*_ncolumns,0) var _a = array.new_float(_nrows,0) var _q = array.new_float(_nrows,0) float _r = 0.0 float _aux = 0.0 //get first column of _A and its norm: for i = 0 to _nrows-1 array.set(_a,i,matrix_get(_A,i,0,_nrows)) _r := vnorm(_a,_nrows) //assign first diagonal element of R and first column of Q matrix_set(_R,_r,0,0,_ncolumns) for i = 0 to _nrows-1 matrix_set(_Q,array.get(_a,i)/_r,i,0,_nrows) if _ncolumns != 1 //repeat for the rest of the columns for k = 1 to _ncolumns-1 for i = 0 to _nrows-1 array.set(_a,i,matrix_get(_A,i,k,_nrows)) for j = 0 to k-1 //get R_jk as scalar product of Q_j column and A_k column: _r := 0 for i = 0 to _nrows-1 _r := _r + matrix_get(_Q,i,j,_nrows)*array.get(_a,i) matrix_set(_R,_r,j,k,_ncolumns) //update vector _a for i = 0 to _nrows-1 _aux := array.get(_a,i) - _r*matrix_get(_Q,i,j,_nrows) array.set(_a,i,_aux) //get diagonal R_kk and Q_k column _r := vnorm(_a,_nrows) matrix_set(_R,_r,k,k,_ncolumns) for i = 0 to _nrows-1 matrix_set(_Q,array.get(_a,i)/_r,i,k,_nrows) [_Q,_R] pinv(_A,_nrows,_ncolumns) => //Pseudoinverse of matrix _A calculated using QR decomposition // Input: // _A:: array: implied as a (_nrows x _ncolumns) matrix _A = [[column_0],[column_1],...,[column_(_ncolumns-1)]] // Output: // _Ainv:: array implied as a (_ncolumns x _nrows) matrix _A = [[row_0],[row_1],...,[row_(_nrows-1)]] // ---- // First find the QR factorization of A: A = QR, // where R is upper triangular matrix. // Then _Ainv = R^-1*Q^T. // ---- [_Q,_R] = qr_diag(_A,_nrows,_ncolumns) _QT = transpose(_Q,_nrows,_ncolumns) // Calculate Rinv: var _Rinv = array.new_float(_ncolumns*_ncolumns,0) float _r = 0.0 matrix_set(_Rinv,1/matrix_get(_R,0,0,_ncolumns),0,0,_ncolumns) if _ncolumns != 1 for j = 1 to _ncolumns-1 for i = 0 to j-1 _r := 0.0 for k = i to j-1 _r := _r + matrix_get(_Rinv,i,k,_ncolumns)*matrix_get(_R,k,j,_ncolumns) matrix_set(_Rinv,_r,i,j,_ncolumns) for k = 0 to j-1 matrix_set(_Rinv,-matrix_get(_Rinv,k,j,_ncolumns)/matrix_get(_R,j,j,_ncolumns),k,j,_ncolumns) matrix_set(_Rinv,1/matrix_get(_R,j,j,_ncolumns),j,j,_ncolumns) // _Ainv = multiply(_Rinv,_QT,_ncolumns,_ncolumns,_nrows) _Ainv mae(_x, _xhat) => // Mean Average Error // _x. :: array float, original data // _xhat :: array float, model estimate // output // _nrmse:: float float _mae = 0.0 if array.size(_x) != array.size(_xhat) _mae := na else _N = array.size(_x) for i = 0 to _N-1 _mae := _mae + abs(array.get(_x,i) - array.get(_xhat,i))/_N _mae mr(_src,_window,_degree) => // Vandermonde matrix with implied dimensions (window x degree+1) // Linear form: J = [ [z]^0, [z]^1, ... [z]^degree], with z = [ (1-window)/2 to (window-1)/2 ] var _J = array.new_float(_window*(_degree+1),0) for i = 0 to _window-1 for j = 0 to _degree matrix_set(_J,pow(i,j),i,j,_window) // Vector of raw datapoints: var _Y_raw = array.new_float(_window,na) for j = 0 to _window-1 array.set(_Y_raw,j,_src[_window-1-j]) // Calculate polynomial coefficients which minimize the loss function _C = pinv(_J,_window,_degree+1) _a_coef = multiply(_C,_Y_raw,_degree+1,_window,1) // For smoothing, approximate the last point (i.e. z=window-1) by a0 float _Y = 0.0 for i = 0 to _degree _Y := _Y + array.get(_a_coef,i)*pow(_window-1,i) // Trend Direction Forecast float _Y_f = 0.0 for i = 0 to _degree _Y_f := _Y_f + array.get(_a_coef,i)*pow(_window,i) // Calculates data estimate (needed for rmse) _Y_hat = multiply(_J,_a_coef,_window,_degree+1,1) float _err = mae(_Y_raw,_Y_hat) [_Y,_Y_f,_err] /// --- main --- src = input(title="Source", defval=close, group = "Model Parameters:") degree = input(title="Local Polynomial Degree", type = input.integer, defval=2, minval = 0, group = "Model Parameters:") window = input(title="Length (must be larger than degree)", type = input.integer, defval=80, minval = 2, group = "Model Parameters:") mult = input(title="Multiplier", type=input.float,defval=2.0,minval=0.0, group = "Model Parameters:", tooltip = "Defines the Band Width.") doLong = input(title="Allow Long Entries", type=input.bool,defval=true, inline = "linealwd", group = "Allowed Entries:") doShort = input(title="Allow Short Entries", type=input.bool,defval=false, inline = "linealwd", group = "Allowed Entries:") stoplong = input(title="Exit Long At", defval="Lower Band - ATR", options = ["Lower Band","Lower Band - ATR","Central Line"], inline = "lineexit", group = "Exit Conditions:") stopshort = input(title="Exit Short At", defval="Central Line", options = ["Upper Band","Upper Band + ATR","Central Line"], inline = "lineexit", group = "Exit Conditions:") fixedstart =input(title="", group = "Fixed Backtest Period Start/End Dates:", inline = "linebac1", type = input.bool, defval = true) backtest_start=input(title = "", type = input.time, inline = "linebac1", group = "Fixed Backtest Period Start/End Dates:", defval = timestamp("01 Jan 2017 13:30 +0000"), tooltip="If deactivated, backtest staring from the first available price bar.") fixedend = input(title="", group = "Fixed Backtest Period Start/End Dates:", inline = "linebac2", type = input.bool, defval = false) backtest_end =input(title = "", type = input.time, inline = "linebac2", group = "Fixed Backtest Period Start/End Dates:", defval = timestamp("30 Dec 2080 23:30 +0000"), tooltip="If deactivated, backtesting ends at the last available price bar.") istoploss = input(title="Show Stop-Loss Line", type=input.bool,defval=true, group="Additional Options") slopefilter = input(title="Enter Only When MR Slope is Positive/Negative", type=input.bool,defval=false, group="Additional Options") issignal = input(title="Show Breakout Signals Labels", type=input.bool,defval=false, group="Additional Options") clinetype = input(title="Show Central Line As", defval="Previous-Period MR Prediction", options = ["Ribbon","MR","Previous-Period MR Prediction"], group="Additional Options") [MR,MR_f,div] = mr(src,window,degree) div := div*mult // plot bands highband = MR_f[1]+div[1] lowband = MR_f[1]-div[1] centralline = MR_f[1] hbplt = plot(highband,title='Upper Band',color=#3C94B8,linewidth=2, transp = 40) lbplt = plot(lowband,title='Lower Band',color=#B83C94,linewidth=2, transp = 40) fill(hbplt,lbplt,color=#3C94B8) // plot central line var plt_color = #3C94B8 if MR_f[1] < MR and clinetype=="Ribbon" plt_color := #94B83C else if MR_f[1] > MR and clinetype=="Ribbon" plt_color := #B83C71 mrplt = plot(MR,title='MR',color=plt_color,linewidth=1, transp = clinetype=="Previous-Period MR Prediction"?100:20) mrfplt = plot(centralline,title='MR Prediction',color=plt_color,linewidth=1, transp = clinetype=="MR"?100:20) fill(mrplt,mrfplt,color=plt_color,transp = clinetype!="Ribbon"?100:20) // breakout signals ATR = atr(14) Breakout = crossover(src,highband) Breakdown = crossunder(src,lowband) ATRBreakout = crossover(src,highband + ATR) ATRBreakdown = crossunder(src,lowband - ATR) MRSlopesUp = MR>MR[1] MRSlopesDw = MR<MR[1] plotshape(Breakout and issignal ? high : na, location=location.abovebar, style=shape.triangleup, color=#88d4ca, size=size.tiny, title='Breakout') plotshape(Breakdown and issignal? low : na, location=location.belowbar, style=shape.triangledown, color=#f67e7d, size=size.tiny,title='Breakdown') goLong = Breakout and (slopefilter?MRSlopesUp:true) goShort = Breakdown and (slopefilter?MRSlopesDw:true) // trailing stop / stop loss trailinglong = stoplong=="Central Line"?centralline:(stoplong=="Lower Band"?lowband:lowband-ATR) trailingshort= stopshort=="Central Line"?centralline:(stopshort=="Upper Band"?highband:highband+ATR) // if signal has been triggered at previous bar, set position open price and initial SL var float opprice = 0.0 var float stoploss = 0.0 if (strategy.position_entry_name[1]=="short" or strategy.position_size[1]==0) and goLong[1] opprice := open stoploss := trailinglong else if (strategy.position_entry_name[1]=="long" or strategy.position_size[1]==0) and goShort[1] opprice := open stoploss := trailingshort // move SL to position opening price if lowband crosses the initial SL if (strategy.position_entry_name=="long" and crossover(trailinglong, opprice)) or (strategy.position_entry_name=="short" and crossunder(trailingshort, opprice)) stoploss := opprice stoplosscolor = strategy.position_entry_name=="long"?#B83C94:(strategy.position_entry_name=="short"?#3C94B8:color.silver) plot(istoploss?stoploss:na,title='sl',color=stoplosscolor,linewidth=1,transp=50) endLong = crossunder(src,trailinglong) endShort = crossover(src,trailingshort) // backtest isinrange = (fixedstart?time>=backtest_start:true) and (fixedend?time<=backtest_end:true) if goLong and isinrange and doLong strategy.entry("long", true) alert(syminfo.tickerid+" Long Signal Triggered",alert.freq_once_per_bar_close) if goShort and isinrange and doShort strategy.entry("short", false) alert(syminfo.tickerid+" Short Signal Triggered",alert.freq_once_per_bar_close) if endLong or crossunder(src,stoploss) strategy.close("long") alert(syminfo.tickerid+" Exit Signal Triggered for Long Position",alert.freq_once_per_bar_close) if endShort or crossover(src,stoploss) strategy.close("short") alert(syminfo.tickerid+" Exit Signal Triggered for Short Position",alert.freq_once_per_bar_close) if (not isinrange) strategy.close_all()
RSI Classic Strategy (by Coinrule)
https://www.tradingview.com/script/JMm04UG5-RSI-Classic-Strategy-by-Coinrule/
Coinrule
https://www.tradingview.com/u/Coinrule/
453
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© relevantLeader16058 //@version=4 strategy(shorttitle='RSI Classic Strategy',title='RSI Classic Strategy (by Coinrule)', overlay=true, initial_capital = 1000, process_orders_on_close=true, default_qty_type = strategy.percent_of_equity, default_qty_value = 30, commission_type=strategy.commission.percent, commission_value=0.1) //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" // RSI inputs and calculations lengthRSI = 14 RSI = rsi(close, lengthRSI) oversold= input(30) overbought= input(60) //Entry strategy.entry(id="long", long = true, when = RSI< oversold and window()) //Exit //RSI strategy.close("long", when = RSI > overbought and window())
Jim's MACD
https://www.tradingview.com/script/AO8H2UZ3-Jim-s-MACD/
yimbobz
https://www.tradingview.com/u/yimbobz/
269
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© melihtuna //@version=4 strategy("Jim's MACD v8", overlay=true) Tendies = input(true, title="Check here for tendies") //Momentum Logic mlength = input(12) price = close momentum(seria, mlength) => mom = seria - seria[mlength] mom mom0 = momentum(price, mlength) mom1 = momentum( mom0, 1) //MACD Setup signalLength=input(9) [macdLine, signalLine, histLine] = macd(close, 12, 26, signalLength) //Hullema hlength = input(9, minval=1) src = input(close, title="Source") hullma = wma(2*wma(src, hlength/2)-wma(src, hlength), floor(sqrt(hlength))) //Time entryt = time(timeframe.period, "0955-1430,1755-2030") //Ensures no new trades in last 30 minutes exitt = time(timeframe.period, "0955-1500,1755-2100") //Trading times : 11AM-4PM , 7PM-10PM EST b = (na(entryt) ? 0 : 1) c = (na(exitt) ? 0 : 1) //Bar coloring barcolor((strategy.position_size>0)?color.green:(strategy.position_size<0)?color.red:color.white) //Entry if( mom0 > 0 and mom1 > 0 and histLine > 0 and signalLine < 0 and close > hullma ) strategy.entry( "BUY", strategy.long, when = b == 1 ) if( mom0 < 0 and mom1 < 0 and histLine < -0.1 and signalLine > 0 and close < hullma ) strategy.entry( "SELL", strategy.short, when = b == 1 ) //Exit strategy.close("BUY", when = histLine < 0 or c == 0) strategy.close("SELL", when = histLine > 0 or c == 0)
B-Xtrender [Backtest Edition] @QuantTherapy
https://www.tradingview.com/script/uCWPAPT2-B-Xtrender-Backtest-Edition-QuantTherapy/
QuantTherapy
https://www.tradingview.com/u/QuantTherapy/
555
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/ // Β© QuantTherapy //@version=4 strategy("B-Xtrender [Backtest Edition] @QuantTherapy") // === DATE & TIME SELECTION === i_fromMonth = input(defval = 1, title = "[Backtest] From Month", type = input.integer, minval = 1, maxval = 12) i_fromDay = input(defval = 1, title = "[Backtest] From Day", type = input.integer, minval = 1, maxval = 31) i_fromYear = input(defval = 2010, title = "[Backtest] From Year", type = input.integer, minval = 1970) i_thruMonth = input(defval = 1, title = "[Backtest] Thru Month", type = input.integer, minval = 1, maxval = 12) i_thruDay = input(defval = 1, title = "[Backtest] Thru Day", type = input.integer, minval = 1, maxval = 31) i_thruYear = input(defval = 2345, title = "[Backtest] Thru Year", type = input.integer, minval = 1970) // === DATE & TIME RANGE FUNCTIONS === f_isDate() => // create function "within window of dates" start = timestamp(i_fromYear, i_fromMonth, i_fromDay, 00, 00) // date start finish = timestamp(i_thruYear, i_thruMonth, i_thruDay, 23, 59) // date finish isDate = time >= start and time <= finish // current date is "within window of dates" // === TRADE DIRECTION === i_tradeDirection = input(title="[Backtest] Trade Direction", defval=strategy.direction.all, options=[strategy.direction.all, strategy.direction.long, strategy.direction.short]) strategy.risk.allow_entry_in(i_tradeDirection) // === LONG/ SHORT EXTRENDER SELECTION === i_short_l1 = input(5 , title="[Short] L1") i_short_l2 = input(20, title="[Short] L2") i_short_l3 = input(15, title="[Short] L3") i_long_l1 = input(20, title="[Long] L1") i_long_l2 = input(15, title="[Long] L2") // === TSL SELECTION === i_ma_use = input(true , title="[MA Filter] Yes/No" ) i_ma_len = input(200 , title="[MA Filter] length" ) i_ma_type = input("EMA", title="[MA Filter] type", options = ["SMA", "EMA"]) shortTermXtrender = rsi( ema(close, i_short_l1) - ema(close, i_short_l2), i_short_l3 ) - 50 longTermXtrender = rsi( ema(close, i_long_l1), i_long_l2 ) - 50 shortXtrenderCol = shortTermXtrender > 0 ? shortTermXtrender > shortTermXtrender[1] ? color.lime : #228B22 : shortTermXtrender > shortTermXtrender[1] ? color.red : #8B0000 plot(shortTermXtrender, color=shortXtrenderCol, style=plot.style_columns, linewidth=1, title="B-Xtrender Osc. - Histogram", transp = 40) longXtrenderCol = longTermXtrender> 0 ? longTermXtrender > longTermXtrender[1] ? color.lime : #228B22 : longTermXtrender > longTermXtrender[1] ? color.red : #8B0000 macollongXtrenderCol = longTermXtrender > longTermXtrender[1] ? color.lime : color.red plot(longTermXtrender , color=longXtrenderCol, style=plot.style_columns, linewidth=2, title="B-Xtrender Trend - Histogram", transp = 90) plot(longTermXtrender , color=#000000 , style=plot.style_line, linewidth=5, title="B-Xtrender Trend - Line", transp = 100) plot(longTermXtrender , color=macollongXtrenderCol, style=plot.style_line, linewidth=3, title="B-Xtrender Trend - Line", transp = 100) // === INIT MA FILTER ma = i_ma_type == "EMA" ? ema(close, i_ma_len) : sma(close, i_ma_len) maFilterLong = true maFilterShort = true if i_ma_use maFilterLong := close > ma ? true : false maFilterShort := close < ma ? true : false long = shortTermXtrender > 0 and longTermXtrender > 0 and maFilterLong closeLong = shortTermXtrender < 0 or longTermXtrender < 0 short = shortTermXtrender < 0 and longTermXtrender < 0 and maFilterShort closeShort = shortTermXtrender > 0 or longTermXtrender > 0 plotshape(long[1]==true and long[2]==false ? 0 : na , location=location.absolute, style=shape.labelup , color=color.lime, size=size.small, transp=10) plotshape(short[1]==true and short[2]==false ? 0 : na, location=location.absolute, style=shape.labeldown, color=color.red , size=size.small, transp=10) plotshape(closeLong[1]==true and closeLong[2]==false or closeShort[1]==true and closeShort[2]==false ? 0 : na, location=location.absolute, style=shape.circle, color=color.orange , size=size.small) i_perc = input(defval = 20.0, title = "[TSL-%] Percent" , minval = 0.1 ) i_src = close // constant for calculation sl_val = i_src * i_perc / 100 toLong = long and f_isDate() toShort = short and f_isDate() // === WHEN POSITION IS OPEN AN DATE IS OUT OF BOUND CLOSE ALL TRADES if not f_isDate() and strategy.position_size != 0 strategy.close_all() strategy.entry("Long", strategy.long, when = toLong ) strategy.close("Long", when = closeLong) strategy.entry("Short", strategy.short, when = toShort) strategy.close("Short", when = closeShort) // Calculate SL longStopPrice = 0.0, shortStopPrice = 0.0 longStopPrice := if (strategy.position_size > 0) stopValue = close - sl_val max(stopValue, longStopPrice[1]) else 0 shortStopPrice := if (strategy.position_size < 0) stopValue = close + sl_val min(stopValue, shortStopPrice[1]) else syminfo.mintick*1000000 // For TSL Visualisation on Chart // plot(series=(strategy.position_size > 0) ? longStopPrice : na, // color=color.fuchsia, style = plot.style_circles, // linewidth=1, title="Long Trail Stop") // plot(series=(strategy.position_size < 0) ? shortStopPrice : na, // color=color.fuchsia, style = plot.style_circles, // linewidth=1, title="Short Trail Stop") if (strategy.position_size > 0) strategy.exit(id="TSL Long", stop=longStopPrice) if (strategy.position_size < 0) strategy.exit(id="TSL Short", stop=shortStopPrice)
Bottom catch strategy
https://www.tradingview.com/script/Ifss1FF4/
footlz
https://www.tradingview.com/u/footlz/
125
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/ // Β© footlz //@version=4 strategy("Bottom catch strategy", overlay=true) v_len = input(20, title="Volume SMA Length") mult = input(2) rsi_len = input(20, title="RSI Length") oversold = input(30, title="Oversold") close_time = input(10, title="Close After") v = volume basis = sma(v, v_len) dev = mult * stdev(v, v_len) upper_volume = basis + dev rsi = rsi(close, rsi_len) long = v > upper_volume and rsi < oversold strategy.entry("Long", true, when=long) passed_time = 0.0 if strategy.position_size != 0 passed_time := 1 else passed_time := 0 if strategy.position_size != 0 and strategy.position_size[1] != 0 passed_time := passed_time[1] + 1 if passed_time >= close_time strategy.close_all() // If want to enable plot, change overlay=false. v_color = close >= close[1] ? color.new(#3eb370, 0) : color.new(#e9546b, 0) // plot(v, title="volume", color=v_color, style=plot.style_columns) // plot(upper_volume, title="Threshold", color=color.aqua)
MACD 50x Leveraged Strategy Real Equity Simulation
https://www.tradingview.com/script/r69MUDSl-MACD-50x-Leveraged-Strategy-Real-Equity-Simulation/
Noldo
https://www.tradingview.com/u/Noldo/
360
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© Noldo //@version=4 strategy(title="MACD STRATEGY REAL EQUITY WITH 50X LEVERAGE",shorttitle = "MACD 50X REAL EQUITY", overlay=true, initial_capital=100, linktoseries = false, default_qty_type=strategy.cash, default_qty_value=1, commission_type=strategy.commission.percent, commission_value=0.0, calc_on_order_fills = false, calc_on_every_tick = true, max_bars_back = 5000, pyramiding = 0, precision = 0) // Variables src = close fromyear = input(2016, defval = 2009, minval = 2000, maxval = 2100, title = "From Year") toyear = input(2100, defval = 2100, minval = 1900, maxval = 2100, title = "To Year") frommonth = input(04, defval = 04, minval = 01, maxval = 12, title = "From Month") tomonth = input(12, defval = 12, minval = 01, maxval = 12, title = "To Month") fromday = input(01, defval = 01, minval = 01, maxval = 31, title = "From day") today = input(31, defval = 31, minval = 01, maxval = 31, title = "To day") term = (time > timestamp(fromyear, frommonth, fromday, 00, 00) and time < timestamp(toyear, tomonth, today, 23, 59)) // LEVERAGE ==> 50X leverage = 50 // POSITION SIZE ==> %1 (0.01) possize = 1 // MACD fastLength = input(12) slowlength = input(26) MACDLength = input(9) MACD = ema(close, fastLength) - ema(close, slowlength) aMACD = ema(MACD, MACDLength) delta = MACD - aMACD // DEFINITION : TREND float trend = na trend:= delta > 0 ? 1 : -1 // SL values stop_long = valuewhen(strategy.position_size > 0 and strategy.position_size[1] <= 0 and trend == 1 ,strategy.position_avg_price * 0.98,0) stop_short= valuewhen(strategy.position_size < 0 and strategy.position_size[1] >= 0 and trend == -1 ,strategy.position_avg_price * 1.02,0) // REAL LEVERAGE SIMULATION --- _lmov = strategy.position_size > 0 and strategy.position_size[1] == 0 _elmov = strategy.position_size[1] > 0 and strategy.position_size == 0 _smov = strategy.position_size < 0 and strategy.position_size[1] == 0 _esmov= strategy.position_size[1] < 0 and strategy.position_size == 0 _dlmov = strategy.position_size[1] < 0 and strategy.position_size > 0 _dsmov = strategy.position_size[1] > 0 and strategy.position_size < 0 onlylong = barssince(_lmov) < barssince(_dlmov) and _lmov onlyshort = barssince(_smov) < barssince (_dsmov) and _smov onlylongexit = barssince(_elmov) < barssince(_dsmov) and _elmov onlyshortexit = barssince(_esmov) < barssince(_dlmov) and _esmov directlong = barssince(_dlmov) < barssince(_lmov) and _dlmov directshort = barssince(_dsmov) < barssince(_smov) and _dsmov // float capital = 0.00 chg = change(strategy.position_size) ch = strategy.position_size _l = valuewhen(strategy.position_size > 0 and strategy.position_size[1] == 0,strategy.position_avg_price,0) // Long after Short or Long Exit _le = valuewhen(strategy.position_size[1] > 0 and strategy.position_size == 0 ,open,0) _s = valuewhen(strategy.position_size < 0 and strategy.position_size[1] == 0,strategy.position_avg_price,0) // Short after Long or Long Exit _se = valuewhen(strategy.position_size[1] < 0 and strategy.position_size == 0 ,open,0) _dds = valuewhen(strategy.position_size < 0 and strategy.position_size[1] >= 0,strategy.position_avg_price,0) // Close Short and Long == DirectLong _ddl = valuewhen(strategy.position_size > 0 and strategy.position_size[1] <= 0,strategy.position_avg_price,0) // Close Long and Short == DirectShort piplong = ((_le - _l) / _l) * 100 pipshort= ((_se - _s) / _s) * 100 pipdl = ((_ddl - _dds) / _dds) * 100 // Direct Long pipds = ((_dds - _ddl) / _ddl) * 100 // Direct Short // CONSTRUCTION enterLong = ((trend == 1 and term and trend[1] != 1) or (trend == 1 and term and trend[1] != 1 and low[1] <= stop_long) or (trend == 1 and term and trend[1] == 1 and low[1] <= stop_long)) // 2 sLong = low <= stop_long and trend == 1 and strategy.position_size > 0 and term // 1 enterShort = ((trend == -1 and term and trend[1] != -1) or (trend == -1 and term and trend[1] != -1 and high[1] >= stop_short) or (trend == -1 and term and trend[1] == -1 and high[1] >= stop_short)) // -2 sShort = high >= stop_short and trend == -1 and strategy.position_size < 0 and term // -1 float mode = na mode := change(strategy.wintrades) > 0 ? 1 : change(strategy.losstrades) > 0 ? -1 : nz(mode[1], 1) pipsize = (abs(chg) - abs(ch)) capital := onlylong ? nz(capital[1], 0) - chg : onlylongexit ? capital[1] : onlyshort ? nz(capital[1], 0) + chg : onlyshortexit ? capital[1] : directlong and mode == 1 ? (capital[1]) - ch + ((-pipsize * leverage * pipdl)/100) : directlong and mode != 1 ? capital[1] - ch : directshort and mode == 1 ? (capital[1]) + ch + ((pipsize * leverage * pipds)/100) : directshort and mode != 1 ? capital[1] + ch : capital[1] // NET CAPITAL capita = 100 + capital float netcapital = na netcapital := netcapital[1] <= 0 ? 0 : capita // STRATEGY strategy.entry("Long",strategy.long, comment="LONG" ,when = enterLong , qty = possize) strategy.entry("Short",strategy.short, comment="SHORT" ,when = enterShort , qty = possize) if(sLong) strategy.close("Long",strategy.long , comment = "SL LONG") if(sShort ) strategy.close("Short" , comment = "SL SHORT") if time > timestamp(toyear, tomonth, today, 23, 59) strategy.close_all() plot(netcapital)
MA Divergences Strategy
https://www.tradingview.com/script/O3odi9VJ-MA-Divergences-Strategy/
burgercrisis
https://www.tradingview.com/u/burgercrisis/
178
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© tista //https://www.tradingview.com/u/tista/#published-scripts //@version=4 strategy(title="MA Divergences", format=format.price) //* Backtesting Period Selector | Component *// //* https://www.tradingview.com/script/eCC1cvxQ-Backtesting-Period-Selector-Component *// //* https://www.tradingview.com/u/pbergden/ *// //* Modifications made *// testStartYear = input(2021, "Backtest Start Year") testStartMonth = input(1, "Backtest Start Month") testStartDay = input(1, "Backtest Start Day") testPeriodStart = timestamp(testStartYear,testStartMonth,testStartDay,0,0) testStopYear = input(999999, "Backtest Stop Year") testStopMonth = input(9, "Backtest Stop Month") testStopDay = input(26, "Backtest Stop Day") testPeriodStop = timestamp(testStopYear,testStopMonth,testStopDay,0,0) testPeriod() => time >= testPeriodStart and time <= testPeriodStop ? true : false /////////////// END - Backtesting Period Selector | Component /////////////// len = input(title="MA Period", minval=1, defval=14) src = input(title="MA Source", defval=close) lbR = input(title="Pivot Lookback Right", defval=5) lbL = input(title="Pivot Lookback Left", defval=5) rangeUpper = input(title="Max of Lookback Range", defval=600) rangeLower = input(title="Min of Lookback Range", defval=2) plotBull = input(title="Plot Bullish", defval=true) plotHiddenBull = input(title="Plot Hidden Bullish", defval=true) plotBear = input(title="Plot Bearish", defval=true) plotHiddenBear = input(title="Plot Hidden Bearish", defval=true) bearColor = color.red bullColor = color.green hiddenBullColor = color.green hiddenBearColor = color.red textColor = color.white noneColor = color.new(color.white, 100) osc = wma(src, len) plot(osc, title="MA", linewidth=2, color=color.yellow) plFound = na(pivotlow(osc, lbL, lbR)) ? false : true phFound = na(pivothigh(osc, lbL, lbR)) ? false : true _inRange(cond) => bars = barssince(cond == true) rangeLower <= bars and bars <= rangeUpper alertcondition(osc[1] > 100.0 and osc[2] < 100.0, title="MA value crosses over 100.0", message="Check charts for a MA cross over 100.0") alertcondition(osc[1] < 100.0 and osc[2] > 100.0, title="MA value crosses under 100.0", message="Check charts for a MA cross under 100.0") alertcondition(osc[1] > -100. and osc[2] < -100.0, title="MA value crosses over -100.0", message="Check charts for a MA cross over -100.0") alertcondition(osc[1] < -100.0 and osc[2] > -100.0, title="MA value crosses under -100.0", message="Check charts for a MA cross under -100.0") //------------------------------------------------------------------------------ // Regular Bullish // Osc: Higher Low oscHL = osc[lbR] > valuewhen(plFound, osc[lbR], 1) and _inRange(plFound[1]) // Price: Lower Low priceLL = low[lbR] < valuewhen(plFound, low[lbR], 1) bullCond = plotBull and priceLL and oscHL and plFound plot( plFound ? osc[lbR] : na, offset=-lbR, title="Regular Bullish", linewidth=2, color=(bullCond ? bullColor : noneColor), transp=0 ) plotshape( bullCond ? osc[lbR] : na, offset=-lbR, title="Regular Bullish Label", text=" Bull ", style=shape.labelup, location=location.absolute, color=bullColor, textcolor=textColor, transp=0 ) alertcondition(bullCond, title="Regular bullish divergence in MA found", message="Check charts for a regular bullish divergence found with MA") //------------------------------------------------------------------------------ // Hidden Bullish // Osc: Lower Low oscLL = osc[lbR] < valuewhen(plFound, osc[lbR], 1) and _inRange(plFound[1]) // Price: Higher Low priceHL = low[lbR] > valuewhen(plFound, low[lbR], 1) hiddenBullCond = plotHiddenBull and priceHL and oscLL and plFound plot( plFound ? osc[lbR] : na, offset=-lbR, title="Hidden Bullish", linewidth=2, color=(hiddenBullCond ? hiddenBullColor : noneColor), transp=0 ) plotshape( hiddenBullCond ? osc[lbR] : na, offset=-lbR, title="Hidden Bullish Label", text=" H Bull ", style=shape.labelup, location=location.absolute, color=bullColor, textcolor=textColor, transp=0 ) alertcondition(hiddenBullCond, title="Hidden bullish divergence in MA found", message="Check charts for a hidden bullish divergence found with MA") //------------------------------------------------------------------------------ // Regular Bearish // Osc: Lower High oscLH = osc[lbR] < valuewhen(phFound, osc[lbR], 1) and _inRange(phFound[1]) // Price: Higher High priceHH = high[lbR] > valuewhen(phFound, high[lbR], 1) bearCond = plotBear and priceHH and oscLH and phFound plot( phFound ? osc[lbR] : na, offset=-lbR, title="Regular Bearish", linewidth=2, color=(bearCond ? bearColor : noneColor), transp=0 ) plotshape( bearCond ? osc[lbR] : na, offset=-lbR, title="Regular Bearish Label", text=" Bear ", style=shape.labeldown, location=location.absolute, color=bearColor, textcolor=textColor, transp=0 ) alertcondition(bearCond, title="Regular bearish divergence in MA found", message="Check charts for a regular bearish divergence found with MA") //------------------------------------------------------------------------------ // Hidden Bearish // Osc: Higher High oscHH = osc[lbR] > valuewhen(phFound, osc[lbR], 1) and _inRange(phFound[1]) // Price: Lower High priceLH = high[lbR] < valuewhen(phFound, high[lbR], 1) hiddenBearCond = plotHiddenBear and priceLH and oscHH and phFound plot( phFound ? osc[lbR] : na, offset=-lbR, title="Hidden Bearish", linewidth=2, color=(hiddenBearCond ? hiddenBearColor : noneColor), transp=0 ) plotshape( hiddenBearCond ? osc[lbR] : na, offset=-lbR, title="Hidden Bearish Label", text=" H Bear ", style=shape.labeldown, location=location.absolute, color=bearColor, textcolor=textColor, transp=0 ) // Alerts //alertcondition(bearCond or hiddenBearCond, title='Bear div', message='Bear div') //alertcondition(bullCond or hiddenBullCond, title='Bull div', message='Bull div') //alertcondition(bearCond or bullCond, title='Bull or beal div', message='Bull or bear div') //alertcondition(hiddenBearCond or hiddenBullCond, title='Bull or beal div', message='Hidden Bull or bear div') //alertcondition(hiddenBearCond or hiddenBullCond or bearCond or bullCond, title='Bull or beal div', message='Any Bull or bear div') if testPeriod() if bullCond or hiddenBullCond strategy.entry("Buy", strategy.long) if bearCond or hiddenBearCond strategy.entry("Sell", strategy.short)
Grid Tool
https://www.tradingview.com/script/5YXV2p1J-Grid-Tool/
ramsay09
https://www.tradingview.com/u/ramsay09/
219
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© ramsay09 //@version=5 strategy(title='Grid Tool', shorttitle='Grid', overlay=true, initial_capital=10000, pyramiding=3000, calc_on_every_tick=false, default_qty_type=strategy.fixed, default_qty_value=0.01, currency=currency.USD, commission_type=strategy.commission.percent, commission_value=0.075, margin_long=0, margin_short=0, max_lines_count=500) general_info = input.bool(title='General Description', defval=false, tooltip="This script can make you free from entry decisions. You just have to manage your exits or additionally manage your exits. Exiting a trend is more important than enter a trade. Use a small time frame for the grid signals to get the distance between the trades as accurate as possible for the selected grid gap distance since TV back tests are carried out with closed bars. Before set up the grid-tool: pre-analyse the market to make sure it is in a trend or will be soon. Select the grid gap and grid position size that you are comfortable with. Define the start date for the grid (start of a new trend), select a signal and use optionally filters, stop loss and take profit. Monitor the trend and your exit levels. The default values are suitable for Bitcoin on ByBit (one tick = 0.5).") //-------------------------------------------------------------------------------------- inputs ----------------------------------------------------------------------------------------------- entry_type = input.string('Long', title='Trade Direction', options=['Long', 'Short', 'Both'], tooltip='Long = long entries only, Short = short entries only, both = long and short entries.') repaint = input.string('Allowed', title='Repainting', options=['Not allowed', 'Allowed'], tooltip='If repainting \'Not allowed\' is selected, then signals from higher time frames have a lag of an additional bar from the higher time frame but you trade what you have backtested. If repainting \'Allowed\' is selected, singals can occure multiple times as long as the higher time frame bar is not closed but the first signal of these possible multiple signals is much earlier. Signals on current time frame (\'Current\' time frame filter is selected) do not repaint by default.') panel = input.bool(true, title='Plot Info Panel', tooltip='Info panel for current unrealized profit or loss for the open position.') plot_avg_price = input.bool(true, title='Plot Position Avarage Price Line.', tooltip='This plots the position avarage price line. Green = position is in profit, red = position is in loss.') en_scalp_mode = input.bool(false, title='Scalping Mode', tooltip='Works only with TP/SL and their enabled counter (output filters are optional). Choose an entry signal and define the scalping signal using entry filters. Makes strategy entry signal idle between exit event and new scalping signal.') en_trig_lvl = input.bool(false, title='Enable Strategy Switch/Trigger Level', group='Strategy trigger and border levels:', tooltip='This enables the strategy price level that must be crossed. Otherwise the strategy entry signals will be ignored. The stop loss and take profit is not affected.') trig_lvl = input.float(0, title='Strategy Switch/Trigger Level', minval=0, step=200, group='Strategy trigger and border levels:', tooltip='Define the price level which must be crossed (up or down) to make the strategy entry signals work.') en_border_up = input.bool(false, title='Enable Upper Border Level', group='Strategy trigger and border levels:', tooltip='In case the market has crossed this level, the strategy entry signals will be turned off (long and short). The stop loss and take profit is not affected. Works when "Strategy Switch/Trigger Level" is not activated or an activated trigger level was crossed.') bup_lvl = input.float(0, title='Strategy Upper Border Level', minval=0, step=200, group='Strategy trigger and border levels:', tooltip='Define strategy upper border level.') en_border_dn = input.bool(false, title='Enable Lower Border Level', group='Strategy trigger and border levels:', tooltip='In case the market has crossed this level, the strategy entry signals will be turned off (long and short). The stop loss and take profit is not affected. Works when "Strategy Switch/Trigger Level" is not activated or an activated trigger level was crossed.') bdn_lvl = input.float(0, title='Strategy Lower Border Level', minval=0, step=200, group='Strategy trigger and border levels:', tooltip='Define strategy lower border level.') border_con = input.string('Close All', title='Strategy Behaviour When A Border Level Is Crossed', options=['Turn Off Entries', 'Idle', 'Close All'], group='Strategy trigger and border levels:', tooltip='Select the strategy behaviour when a border level is crossed. "Turn Off Entries" = The strategy entry signals will be turned off (long and short). The stop loss and take profit is not affected. "Idle" = The strategy remains idle. Affects entries, stop loss, take profit and exit filters. Position remains open. "Close All" = The entire position will be closed and strategy remains idle.') extend_lines = input.string('Right', title='Extend Lines', options=['Right', 'Both'], group='Strategy trigger and border levels:', tooltip='Select the trigger and border line extention') en_close_stop = input.bool(false, title='Enable "Close & Stop" Level', group='Strategy trigger and border levels:', tooltip='In case the market has crossed this level, the entire position will be closed and the strategy remains idle. This Feature works on current bar and is independent of time and date.') cl_st_lvl = input.float(0, title='"Close & Stop" Level', minval=0, step=100, group='Strategy trigger and border levels:', tooltip='Define "Close & Stop" level.') //---------------------------- Backtest periode inputs ----------------------------------- inst_grid = input.bool(false, title='Instant Grid', group='Define the period of the grid/trend:', tooltip='This enables the grid with current time and date. Do not change input settings while running an instant grid otherwise the grid will restart at current bar.') period_start = input.time(title='', inline='start_timestamp', defval=timestamp('01 SEP 2022 00:00 +0000'), group='Define the period of the grid/trend:', tooltip='Trend/grid start date and time. In case of live trading you have to set the period to the current date and time otherwise history trades will influence the position management.') period_stop = input.time(title='', inline='end_timestamp', defval=timestamp('31 Dec 2122 00:00 +0000'), group='Define the period of the grid/trend:', tooltip='Trend/grid end date and time.') //backtesting lot size lot_size_b = input.float(0.01, title='Lot Size - Backtesting', minval= 0, step= 0.01, tooltip='Affects backtesting only.', group='Backtesting and live-trading lot size:') //Alertatron lot size on Bybit lot_size_lv = input.int(50, title='Lot Size - Live Trading', minval= 0, step= 50, tooltip='Alertatron Bitcoin lot size string for Bybit exchange. Affects live trading only.', group='Backtesting and live-trading lot size:') //------------------------ entry signal inputs -------------------------- x_opt_1 = input.string('Grid - reentry', title='--- 1st ENTRY SIGNAL ---', options=['---', 'Grid - reentry', 'Grid - counter trend', 'Fractals', 'Reverse fractal', 'Pin bar', 'BB reverse'], tooltip='The grid entry signals are time independent. The Fractals signal is a breakout signal. The reverse fractal and the Pin bar signal are bottom fishing signal.', group='Entry signals:') x_opt_2 = input.string('---', title='--- 2nd ENTRY SIGNAL ---', options=['---', 'Grid - reentry', 'Grid - counter trend', 'Fractals', 'Reverse fractal', 'Pin bar', 'BB reverse'], tooltip='The grid entry signals are time independent. The Fractals signal is a breakout signal. The reverse fractal and the pin bar signal are bottom fishing signals.', group='Entry signals:') //grid parameter grid_gap = input.float(500, title='Grid Gap - Base Currency', minval=0, step=50, tooltip='The minimum trigger-gap between two trades in case of a selected grid signal.', group='Grid parameter:') //---------------------------- 1st position factor inputs ------------------------------ en_1st_pos_f = input.bool(false, title='Enable First Position', group='First position size:', tooltip='This enables the first position that will be opened when entry condition is met. In case all positions are closed, a new "first position" will be opened. Works when no exit filters are selected.') inst_pos = input.bool(false, title='Instantly On Current Bar Close', group='First position size:', tooltip='This opens the first position immediately when the grid is placed and the current bar is closed.') pos_start_1st = input.float(0.05, title='Position Start-Size - Backtesting', minval=0.000001, step=0.01, group='First position size:', tooltip='This replaces the default strategy position size ("Lot Size - Backtesting") and is the starting position size. Backtesting only.') pos_start_1st_lv = input.float(250, title='Position Start-Size - Live Trading', minval=0.000001, step=50, group='First position size:', tooltip='This replaces the default strategy live trading position size ("Lot Size - Live Trading") and is the starting position size. Live trading only.') //-------------------------------- auto-increase of position inputs ----------------------------------- en_pos_mart = input.bool(false, title='Enable Position Auto-Increase', group='Automatic position size increase for each trade (Martingale):', tooltip='This enables the automatic increase in position size for each trade. With "Position Factor = 1" you get the martingale sequence. This \'automatic increase\' works until a position has been closed. After a closing event, this function remains inactive. Works not with "Trade Direction" = "Both".') pos_factor = input.float(0.5, title='Position Factor', minval=0.000001, step=0.1, group='Automatic position size increase for each trade (Martingale):', tooltip='This factor controls the position size. The next position size is: strategy_position_size + strategy_position_size * position_factor. Keep in mind that a take profit event reduces the current position size.') pos_count_in = input.int(4, title='Position Count', minval=1, step=1, group='Automatic position size increase for each trade (Martingale):', tooltip='This value determines how often the position is increased.') pos_start_mart = input.float(0.01, title='Position Start-Size - Backtesting', minval=0.000001, step=0.001, group='Automatic position size increase for each trade (Martingale):', tooltip='This replaces the default strategy position size ("Lot Size - Backtesting") and is the starting position size for "Auto-Increase". Backtesting only.') pos_start_mart_lv = input.float(100, title='Position Start-Size - Live Trading', minval=0.000001, step=50, group='Automatic position size increase for each trade (Martingale):', tooltip='This replaces the default live trading strategy position size ("Lot Size - Live Trading") and is the starting position size for "Auto-Increase". Live trading only.') //------------------------------ take average profit inputs -------------------------------- av_tp_en = input.bool(title='Enable Take Profit - Average-Position-Price Profit', defval=true, group='Take profit based on average-position-price:', tooltip='Profit taking condition: current price >= average price of positions + "Take Average-Price Of Positions Profit..." AND current price >= average-price of positions + "Take Profit Step...". Enable when scalping mode is used.') av_tp_qty = input.float(10, title='Take Average-Position-Price Profit - Quantity Of Position (Percent)', minval=0, step=5, maxval=100, group='Take profit based on average-position-price:', tooltip='Reduction of current position in percent. Affects backtesting and live trading.') av_tp = input.float(500, title='Take Average-Position-Price Profit - Base Currency', minval=0, step=50, group='Take profit based on average-position-price:', tooltip='The profit in points of base currency, calculated from the average price of all open trades.') avtp_step = input.float(500, title='Take Profit Step - Base Currency', minval=0, step=50, group='Take profit based on average-position-price:', tooltip='The minimum distance between two profit-taking events in case of "Take Average-Entry Profit - Quantity Of Position (Percent)" < 100.') en_tp_counter = input.bool(title='Enable Take Profit Count', defval=false, group='Take profit based on average-position-price:', tooltip='Enables "Take Profit Count". If disabled the stepwise take profit is endless. Enable when scalping mode is used.') tp_count = input.int(3, title='Take Profit Count', minval=1, step=1, group='Take profit based on average-position-price:', tooltip='Defines how many times a take profit event will happen before the entire position will be closed. Once the counter limit has been reached the counter gets reseted.') //---------------------------------- break even stop loss ----------------------------------- break_even = input.bool(title='Close On Break Even And Remain Idle', defval=false, group='Break even stop loss:', tooltip='Sets the stop loss to break even after the first take profit event. Strategy remains idle after a break even close event. Works on live trading too but the triggering lot size is the backtest lot size.') rep_even = input.bool(title='Close Partly On Break Even', defval=false, group='Break even stop loss:', tooltip='Sets a partly stop loss on break even. Strategy will not be further affected after a partly break even close event. Works on live trading too but the triggering lot size is the backtest lot size.') rep_ev_qty = input.int(50, title='Percent Close On Break Even', minval= 0, maxval= 100, step= 5, group='Break even stop loss:', tooltip= 'Percent of position that will be closed after a break even event.') be_min_lot = input.float(0.1, title='Min Lot Size (Backtesting lot size)', minval= 0, step= 0.01, group='Break even stop loss:', tooltip= 'Min lot size to trigger break even partly close. Current lot size > "Min Lot Size"') //---------------------------- stop loss of average position inputs ------------------------------ av_sl_en = input.bool(title='Enable Stop Loss - Average-Position-Price Loss', defval=true, group='Stop loss based on average-position price or recent top/bottom:', tooltip='Stop loss condition: current price <= average-position price of positions - "Stop Average-Entry Loss..." AND current price <= Average-Position Price Of Positions - "Stop Loss Step...". Enable when scalping mode is used.') tb_tog = input.bool(title='Toggle: Average-Position-Price Loss (Default) / Top/Bottom Based Loss', defval=true, group='Stop loss based on average-position price or recent top/bottom:', tooltip='Stop loss condition top/bottom mode: current price <> last local top/bottom AND step condition. Stop loss condition average-position-price loss mode: price <> average entry position price AND step condition. Default = selected.') av_sl_qty = input.float(30, title='Stop Average-Position-Price Loss - Quantity Of Position (Percent)', minval=0, step=5, maxval=100, group='Stop loss based on average-position price or recent top/bottom:', tooltip='Reduction of current position in percent. Affects backtesting and live trading.') av_sl = input.float(500, title='Stop Average-Position-Price Loss - Base Currency', minval=0, step=50, group='Stop loss based on average-position price or recent top/bottom:', tooltip='The loss in points of base currency, calculated from the average-position-price of all open trades.') avsl_step = input.float(500, title='Stop Loss Step - Base Currency', minval=0, step=50, group='Stop loss based on average-position price or recent top/bottom:', tooltip='The minimum distance between two stop-loss events in case of "Stop Average-Position-Price Loss - Quantity Of Position (Percent)" < 100.') sl_sen = input.int(20, title='Top/Bottom Sensitivity', minval=1, step=1, group='Stop loss based on average-position price or recent top/bottom:', tooltip='Number of past candles within the top and bottom are detected. For "Top/Bottom Based Loss" only.') en_sl_counter = input.bool(title='Enable Stop Loss Count', defval=false, group='Stop loss based on average-position price or recent top/bottom:', tooltip='Enables "Stop Loss Count". If disabled the stepwise stop loss is endless. Enable when scalping mode is used.') sl_count = input.int(3, title='Stop Loss Count', minval=1, step=1, group='Stop loss based on average-position price or recent top/bottom:', tooltip='Defines how many times a take profit event will happen before the entire position will be closed. Once the counter limit has been reached the counter gets reseted.') //---------------------------- entry filters and time frame inputs ------------------------------ htf_entr_opt_1 = input.string('Current', title='Time Frame - Entry Filter 1', options=['Current', '5m', '10m', '15m', '30m', '1H', '2H', '3H', '4H', '6H', '8H', '12H', 'D', '3D', 'W', 'M'], tooltip='The time frame for the 1st ENTRY SIGNAL filter. Choose always a higher time frame than the current. Lower time frames than the current may result in false values.', group='Entry filters:') htf_entr_opt_2 = input.string('Current', title='Time Frame - Entry Filter 2', options=['Current', '5m', '10m', '15m', '30m', '1H', '2H', '3H', '4H', '6H', '8H', '12H', 'D', '3D', 'W', 'M'], tooltip='The time frame for the 2nd ENTRY SIGNAL filter. Choose always a higher time frame than the current. Lower time frames than the current may result in false values.', group='Entry filters:') entry_f_1 = input.string('---', title='Entry Filter 1', options=['---', 'Fractals trend lines filter (no tf filter)', 'Bar breakout 1 filter', 'Bar breakout 2 filter', 'SMA filter', 'MACD filter', 'MACD(fast) slope filter', 'RSI50 filter', 'Fractals filter', 'Segments filter (no tf filter)', 'Fractals 1-2-3 filter', 'Reverse fractal filter', 'EMA21/SMA20 filter', 'BB reverse filter (no tf filter)', 'ALMA slope filter', 'SuperTrend filter', 'EMA1 x EMA2 filter', 'ADX DMI filter', 'ADX slope filter', 'HMA slope filter', '2HMA cross filter', 'TRIX slope filter', 'Parabolic SAR filter', 'Price X Kumo filter', 'Price X Kijun filter', 'Kumo flip filter', 'Price filtered Kumo flip filter (no tf filter)', 'Chikou X price filter', 'Chikou X Kumo filter', 'Price X Tenkan filter', 'Tenkan X Kumo filter', 'Tenkan X Kijun filter'], tooltip='Various filter signals for the 1nd ENTRY SIGNAL.', group='Entry filters:') entry_f_2 = input.string('---', title='Entry Filter 2', options=['---', 'Fractals trend lines filter (no tf filter)', 'Bar breakout 1 filter', 'Bar breakout 2 filter', 'SMA filter', 'MACD filter', 'MACD(fast) slope filter', 'RSI50 filter', 'Fractals filter', 'Segments filter (no tf filter)', 'Fractals 1-2-3 filter', 'Reverse fractal filter', 'EMA21/SMA20 filter', 'BB reverse filter (no tf filter)', 'ALMA slope filter', 'SuperTrend filter', 'EMA1 x EMA2 filter', 'ADX DMI filter', 'ADX slope filter', 'HMA slope filter', '2HMA cross filter', 'TRIX slope filter', 'Parabolic SAR filter', 'Price X Kumo filter', 'Price X Kijun filter', 'Kumo flip filter', 'Price filtered Kumo flip filter (no tf filter)', 'Chikou X price filter', 'Chikou X Kumo filter', 'Price X Tenkan filter', 'Tenkan X Kumo filter', 'Tenkan X Kijun filter'], tooltip='Various filter signals for the 2nd ENTRY SIGNAL.', group='Entry filters:') //-------------------------- exit filters and time frame inputs ---------------------------- tog_exit = input.bool(title='Toggle Exit Mode 1/2', defval=true, tooltip='Mode 1: All open positions will be closed. Entry signals are not affected. Mode 2: All open positions will be closed. New entry signals are inactive while exit signal is valid. Mode 1 = default = selected.', group='Exit filters:') qyt_exit = input.int(100, title='Exit Quantity', minval= 0, maxval= 100, step= 5, tooltip= 'Percent of position that will be closed. Affects backtesting and live trading.', group='Exit filters:') htf_exit_opt_1 = input.string('Current', title='Time Frame - Exit Filter 1', options=['Current', '5m', '10m', '15m', '30m', '1H', '2H', '3H', '4H', '6H', '8H', '12H', 'D', '3D', 'W', 'M'], tooltip='The time frame for Exit filter 1. Choose always a higher time frame than the current. Lower time frames than the current may result in false values.', group='Exit filters:') htf_exit_opt_2 = input.string('Current', title='Time Frame - Exit Filter 2', options=['Current', '5m', '10m', '15m', '30m', '1H', '2H', '3H', '4H', '6H', '8H', '12H', 'D', '3D', 'W', 'M'], tooltip='The time frame for Exit filter 2. Choose always a higher time frame than the current. Lower time frames than the current may result in false values.', group='Exit filters:') exit_f_1 = input.string('---', title='Exit filter 1', options=['---', 'Fractals trend lines filter (no tf-filter)', 'ALMA slope exit', 'Reverse fractal exit', 'SMA exit', 'MACD exit', 'MACD(fast) slope exit', 'HMA slope exit', '2HMA cross exit', 'EMA1 x EMA2 exit', 'ADX slope exit', 'ADX Threshold exit', 'DMI exit', 'TRIX slope exit', 'BB reverse exit', 'RSI50 exit', 'Fractals exit', 'SuperTrend exit', 'Parabolic SAR exit', 'Cloud exit', 'Kijun exit'], tooltip='Various exit signals for the 1nd ENTRY SIGNAL and the 2nd ENTRY SIGNAL. The exit signals are OR connected.', group='Exit filters:') exit_f_2 = input.string('---', title='Exit filter 2', options=['---', 'Fractals trend lines filter (no tf-filter)', 'ALMA slope exit', 'Reverse fractal exit', 'SMA exit', 'MACD exit', 'MACD(fast) slope exit', 'HMA slope exit', '2HMA cross exit', 'EMA1 x EMA2 exit', 'ADX slope exit', 'ADX Threshold exit', 'DMI exit', 'TRIX slope exit', 'BB reverse exit', 'RSI50 exit', 'Fractals exit', 'SuperTrend exit', 'Parabolic SAR exit', 'Cloud exit', 'Kijun exit'], tooltip='Various exit signals for both the 1nd ENTRY SIGNAL and the 2nd ENTRY SIGNAL. The exit signals are OR connected.', group='Exit filters:') //------------------------- Signal parameter inputs ---------------------------- p_bar_sens_1 = input.float(0.6, title='Pin Bar Sensitivity 1', step=0.02, tooltip='Condition: candle wick > candle body * "Pin bar sensitivity". The smaller the factor, the more wicks are detected as part of a pin bar.', group='Pin bar and segment parameters:') p_bar_sens_2 = input.int(1, title='Pin Bar Sensitivity 2', step=1, minval=0, tooltip='Condition: high/low >< last two high/low.', group='Pin bar and segment parameters:') sb = input.int(title='Segment Max Bars', defval=10, minval=0, step=1, tooltip='The Maximum bars between two segment highs or lows.', group='Pin bar and segment parameters:') //--------------------- filters inputs -------------------- fr_period = input.int(2, title='Fractals Period', minval=1, group='Entry and filter signal parameters:') rsi_period = input.int(14, title='RSI Period', minval=1, group='Entry and filter signal parameters:') ma_period = input.int(50, title='MA Period', minval=1, group='Entry and filter signal parameters:') mult = input.float(3, title='SuperTrend Multiplier', minval=1, step=0.1, group='Entry and filter signal parameters:') len = input.int(6, title='SuperTrend Length', minval=1, group='Entry and filter signal parameters:') start = 0.02 //input(0.02, title= "PSAR Start (Filter/Entry)", minval= 0) inc = 0.02 //input(0.02, title= "PSAR Increment (Filter/Entry)", minval= 0) max = 0.2 //input(.2, title= "PSAR Maximum (Filter/Entry)", minval= 0) windowsize_f = input.int(title="ALMA Window Size", defval=9, minval=1, step=1, group='Entry and filter signal parameters:', tooltip='') offset_f = input.float(title="ALMA Offset", defval=0.85, minval=0, step=0.05, group='Entry and filter signal parameters:', tooltip='') sigma_f = input.float(title="ALMA Sigma", defval=6, minval=1, step=1, group='Entry and filter signal parameters:', tooltip='') di_length_s = input.int(10, title='DMI ADX Length', minval=1, group='Entry and filter signal parameters:') adx_smooth_s = input.int(10, title='DMI ADX Smooth', minval=1, group='Entry and filter signal parameters:') adx_thres_s = input.int(25, title='DMI ADX Threshold', minval=1, group='Entry and filter signal parameters:') slope_len = input.int(1, minval=1, title='MACD MacdlLine Slope Lenth', tooltip='MACD\'s fast line', group='Entry and filter signal parameters:') hma_len_f = input.int(100, minval=1, step=5, title='HMA Length', group='Entry and filter signal parameters:') hma2_len_f = input.int(25, title = "2HMA Period", minval=1, step=1, group='Entry and filter signal parameters:') ema1_len_f = input.int(10, minval=1, step=2, title='EMA1 Length', group='Entry and filter signal parameters:') ema2_len_f = input.int(20, minval=1, step=2, title='EMA2 Length', group='Entry and filter signal parameters:') trix_len_f = input.int(10, title="TRIX Length", minval=1, group='Entry and filter signal parameters:') bb_length_s = input.int(20, minval=1, title='BB Length (signal)', group='Entry and filter signal parameters:', tooltip='') bb_std_fac_s = input.float(2, minval=0.1, step=0.2, title='BB StdDev Factor (signal)', group='Entry and filter signal parameters:', tooltip='') bb_length_f = input.int(20, minval=1, step=10, title='BB Length (filter)', group='Entry and filter signal parameters:', tooltip='Formula to adapt BB length of a lower TF to a higher TF: (higher TF in minutes) / (lower TF) * (BB Length of higher TF)') bb_std_fac_f = input.float(2, minval=0.1, step=0.2, title='BB StdDev Factor (filter)', group='Entry and filter signal parameters:', tooltip='') //--------------------- exits inputs -------------------- fr_period_x = input.int(2, title='Exit Fractals - Period', minval=1, group='Exit signal parameters:') fr_past_x = input.int(0, title='Exit Fractals - Past Fractal', minval=0, group='Exit signal parameters:') rsi_period_x = input.int(14, title='Exit RSI Period', minval=1, group='Exit signal parameters:') ma_period_x = input.int(50, title='Exit MA Period', minval=1, group='Exit signal parameters:') mult_x = input.float(2, title='Exit SuperTrend Multiplier', minval=1, group='Exit signal parameters:') len_x = input.int(5, title='Exit SuperTrend Length', minval=1, group='Exit signal parameters:') di_length_x = input.int(10, title='Exit DMI ADX Length', minval=1, group='Exit signal parameters:') adx_smooth_x = input.int(10, title='Exit DMI ADX Smooth', minval=1, group='Exit signal parameters:') adx_thres_x = input.int(25, title='Exit DMI ADX Threshold', minval=1, group='Exit signal parameters:') slope_len_x = input.int(1, minval=1, title='Exit MACD MacdlLine Slope Lenth', tooltip='MACD\'s fast line', group='Exit signal parameters:') hma_len_x = input.int(100, minval=1, step=5, title='EXIT HMA Length', group='Exit signal parameters:') hma2_len_x = input.int(25, title = "Exit 2HMA Period", minval=1, step=1, group='Exit signal parameters:') ema1_len_x = input.int(10, minval=1, step=2, title='Exit EMA1 Length', group='Exit signal parameters:') ema2_len_x = input.int(20, minval=1, step=2, title='Exit EMA2 Length', group='Exit signal parameters:') windowsize_x = input.int(9, title="Exit ALMA Window Size", minval=1, step=1, group='Exit signal parameters:', tooltip='') offset_x = input.float(0.85, title="Exit ALMA Offset", minval=0, step=0.05, group='Exit signal parameters:', tooltip='') sigma_x = input.float(6, title="Exit ALMA Sigma", minval=1, step=1, group='Exit signal parameters:', tooltip='') trix_len_x = input.int(10, title="Exit TRIX Length", minval=1, group='Exit signal parameters:', tooltip='') bb_length_x = input.int(20, minval=1, title='Exit BB Length', group='Exit signal parameters:', tooltip='') bb_std_fac_x = input.float(2, minval=0.1, step=0.2, title='Exit BB StdDev Factor', group='Exit signal parameters:', tooltip='') //--------------- Current unrealized profit or loss for the open position ------------------- if panel var info_panel = table.new(position = position.bottom_left, columns = 1, rows = 2, bgcolor=color.new(color.blue, 92), frame_width=1, border_width=1) text0 = "Position Size: " + str.tostring(strategy.position_size, "#.0000") text1 = "Unrealized Profit/Loss: " + str.tostring(strategy.openprofit, "#.00") table.cell(table_id=info_panel, column=0, row=0, text=text0, text_halign=text.align_left, text_size= size.small, text_color=color.new(color.silver, 0)) table.cell(table_id=info_panel, column=0, row=1, text=text1, text_halign=text.align_left, text_size= size.small, text_color=color.new(color.silver, 0)) //------------------------- entry direction -------------------------- long = entry_type != 'Short' // long or both short = entry_type != 'Long' // short or both both = entry_type == 'Both' // both //----------------------- Backtest periode -------------------------------- backtest_period() => time >= period_start and time <= period_stop ? true : false //-------------------------------- plots ---------------------------- //plot trigger level trig_line = en_trig_lvl ? line.new(x1=period_start, x2=time, xloc = xloc.bar_time, y1=trig_lvl, y2=trig_lvl, extend=extend_lines == 'Right' ? extend.right : extend.both, color=color.new(color.yellow, 40), style=line.style_solid, width=2) : na //plot upper border level bup_line = en_border_up ? line.new(x1=period_start, x2=time, xloc = xloc.bar_time, y1=bup_lvl, y2=bup_lvl, extend=extend_lines == 'Right' ? extend.right : extend.both, color=color.new(color.red, 40), style=line.style_solid, width=3) : na //plot lower border level bdn_line = en_border_dn ? line.new(x1=period_start, x2=time, xloc = xloc.bar_time, y1=bdn_lvl, y2=bdn_lvl, extend=extend_lines == 'Right' ? extend.right : extend.both, color=color.new(color.green, 40), style=line.style_solid, width=3) : na //plot "close & stop" level clst_line = en_close_stop ? line.new(x1=bar_index[1], x2=bar_index, y1=cl_st_lvl, y2=cl_st_lvl, extend=extend.right, color=color.new(color.white, 10), style=line.style_solid, width=1) : na line.delete(trig_line[1]) line.delete(bup_line[1]) line.delete(bdn_line[1]) line.delete(clst_line[1]) //average price plot plot(plot_avg_price ? strategy.position_avg_price : na, linewidth=1, color=close > strategy.position_avg_price and long or close < strategy.position_avg_price and short ? color.new(color.green, 30) : color.new(color.red, 30), title='position_avg_price') //-------------------- Ichimoku -------------------- TKlength = 9 //input(9, "Tenkan-sen length", minval= 1) KJlength = 26 //input(26, "Kijun-sen length", minval= 1) CSHSlength = 26 //input(26, "Chikouspan length/horizontal shift", minval= 1) SBlength = 52 //input(52, "SenkouspanB length", minval= 1) // calculation TK = math.avg(ta.lowest(TKlength), ta.highest(TKlength)) KJ = math.avg(ta.lowest(KJlength), ta.highest(KJlength)) CS = close SB = math.avg(ta.lowest(SBlength), ta.highest(SBlength)) SA = math.avg(TK, KJ) kumo_high = math.max(SA[CSHSlength - 1], SB[CSHSlength - 1]) kumo_low = math.min(SA[CSHSlength - 1], SB[CSHSlength - 1]) //----------------------------------------------------------------------- Filters and entry signals ------------------------------------------------------------------------ //---------------------- Ichimoku filters ------------------------ // cross conditions for "Strong" filtered signals var bool sasb_x = true if ta.crossover(SA, SB) and low > kumo_high sasb_x := true sasb_x if ta.crossunder(SA, SB) and high < kumo_low sasb_x := false sasb_x var bool tkkj_x = true if ta.crossover(TK, KJ) and TK > kumo_high and KJ > kumo_high tkkj_x := true tkkj_x if ta.crossunder(TK, KJ) and TK < kumo_low and KJ < kumo_low tkkj_x := false tkkj_x // Ichimoku filters kijun_buy_f = close > KJ kumo_buy_f = close > kumo_high kumo_flip_buy_f = SA > SB price_filtered_kumo_flip_buy_f = sasb_x and low > kumo_high chikou_X_price_buy_f = CS > high[26 - 1] chikou_X_kumo_buy_f = CS > kumo_high[26 - 1] price_X_tenkan_buy_f = close > TK tenkan_X_kumo_buy_f = TK > kumo_high tenkan_X_kijun_buy_f = TK > KJ kumo_filtered_tenkan_X_kijun_buy_f = tkkj_x and TK > kumo_high and KJ > kumo_high and TK > KJ kijun_sell_f = close < KJ kumo_sell_f = close < kumo_low kumo_flip_sell_f = SA < SB price_filtered_kumo_flip_sell_f = not sasb_x and high < kumo_low chikou_X_price_sell_f = CS < low[26 - 1] chikou_X_kumo_sell_f = CS < kumo_low[26 - 1] price_X_tenkan_sell_f = close < TK tenkan_X_kumo_sell_f = TK < kumo_low tenkan_X_kijun_sell_f = TK < KJ kumo_filtered_tenkan_X_kijun_sell_f = not tkkj_x and TK < kumo_low and KJ < kumo_low and TK < KJ // Ichimoku exits kijun_buy_x = tog_exit ? ta.crossover(high, KJ) : high > KJ kijun_sell_x = tog_exit ? ta.crossunder(low, KJ) : low < KJ kumo_buy_x = tog_exit ? ta.crossover(high, kumo_high) : high > kumo_high kumo_sell_x = tog_exit ? ta.crossunder(low, kumo_low) : low < kumo_low //--------------------- Bollinger Bands ------------------------ f_stdev(_bb_len) => ta.stdev(close, _bb_len) f_sma(_sma_len) => ta.sma(close, _sma_len) dev_s = bb_std_fac_s * f_stdev(bb_length_s) dev_f = bb_std_fac_f * f_stdev(bb_length_f) dev_x = bb_std_fac_x * f_stdev(bb_length_x) //signal upper_bb_s = f_sma(bb_length_s) + dev_s lower_bb_s = f_sma(bb_length_s) - dev_s bb_long_s = low < lower_bb_s // ta.crossunder(low, lower_bb_s) bb_short_s = high > upper_bb_s // ta.crossover(high, upper_bb_s) //filter upper_bb_f = f_sma(bb_length_f) + dev_f lower_bb_f = f_sma(bb_length_f) - dev_f var bool bb_dnx_buy = false var bool bb_upx_sell = false if low < lower_bb_f and backtest_period() bb_dnx_buy := true bb_upx_sell := false if high > upper_bb_f and backtest_period() bb_upx_sell := true bb_dnx_buy := false bb_long_f = bb_dnx_buy // [pine] [/pine] bb_short_f = bb_upx_sell //exit upper_bb_x = f_sma(bb_length_x) + dev_x lower_bb_x = f_sma(bb_length_x) - dev_x bb_long_x = tog_exit ? ta.crossunder(low, lower_bb_x) : low < lower_bb_x bb_short_x = tog_exit ? ta.crossover(high, upper_bb_x) : high > upper_bb_x //-------------------------- trix -------------------------- trix_f = 10000 * ta.change(ta.ema(ta.ema(ta.ema(math.log(close), trix_len_f), trix_len_f), trix_len_f)) trix_x = 10000 * ta.change(ta.ema(ta.ema(ta.ema(math.log(close), trix_len_x), trix_len_x), trix_len_x)) trix_slo_up_f = ta.rising(trix_f, 1) trix_slo_up_x = tog_exit ? ta.rising(trix_x, 1) and not ta.rising(trix_x, 1)[1] : ta.rising(trix_x, 1) trix_slo_dn_x = tog_exit ? ta.falling(trix_x, 1) and not ta.falling(trix_x, 1)[1] : ta.falling(trix_x, 1) //------------------------- hma ---------------------------- hma_f = ta.hma(close, hma_len_f) // entry filter //[repaint == 'Allowed' ? 0 : 1] hma_x = ta.hma(close, hma_len_x) // exit hma_up_f = ta.rising(hma_f, 1) hma_dn_f = ta.falling(hma_f, 1) // entry filter hma_up_x = tog_exit ? ta.rising(hma_x, 1) and not ta.rising(hma_x, 1)[1] : ta.rising(hma_x, 1) // exit hma_dn_x = tog_exit ? ta.falling(hma_x, 1) and not ta.falling(hma_x, 1)[1] : ta.falling(hma_x, 1) //------------------- 2hma cross ----------------------- f_hma3(_src, _len) => ta.wma(ta.wma(close, (_len/2)/3)*3 - ta.wma(close, (_len/2)/2) - ta.wma(close, (_len/2)), (_len/2)) //entry filter hma_n_f = ta.hma(hl2, hma2_len_f) //[repaint == 'Allowed' ? 0 : 1] hma_m_f = f_hma3(hl2, hma2_len_f) //[repaint == 'Allowed' ? 0 : 1] hma_c_up_f = hma_m_f > hma_n_f hma_c_dn_f = hma_m_f < hma_n_f //exit hma_n_x = ta.hma(hl2, hma2_len_x) //[repaint == 'Allowed' ? 0 : 1] hma_m_x = f_hma3(hl2, hma2_len_x) //[repaint == 'Allowed' ? 0 : 1] hma_c_up_x = tog_exit ? ta.crossover(hma_m_x, hma_n_x) : hma_m_x > hma_n_x hma_c_dn_x = tog_exit ? ta.crossunder(hma_m_x, hma_n_x) : hma_m_x < hma_n_x //---------------- williams fractals trend lines ----------------- up_w_fr = ta.pivothigh(2, 2) dn_w_fr = ta.pivotlow(2, 2) y1_frup_1 = ta.valuewhen(up_w_fr, high[2], 1) y0_frup_0 = ta.valuewhen(up_w_fr, high[2], 0) y1_frdn_1 = ta.valuewhen(dn_w_fr, low[2], 1) y0_frdn_0 = ta.valuewhen(dn_w_fr, low[2], 0) // bar-id loops to get x1 and x2 for line.new() xup0 = 2 for i = 1 to 25 by 1 if high[i + 2] >= high[i + 3] and high[i + 2] > high[i + 4] and high[i + 2] > high[i + 1] and high[i + 2] >= high[i + 0] break xup0 := xup0 + 1 xup0 xup1 = xup0 for i = xup1 to 40 by 1 if high[i + 2] >= high[i + 3] and high[i + 2] > high[i + 4] and high[i + 2] > high[i + 1] and high[i + 2] >= high[i + 0] break xup1 := xup1 + 1 xup1 xdn0 = 2 for i = 1 to 25 by 1 if low[i + 2] <= low[i + 3] and low[i + 2] < low[i + 4] and low[i + 2] < low[i + 1] and low[i + 2] <= low[i + 0] break xdn0 := xdn0 + 1 xdn0 xdn1 = xdn0 for i = xdn1 to 40 by 1 if low[i + 2] <= low[i + 3] and low[i + 2] < low[i + 4] and low[i + 2] < low[i + 1] and low[i + 2] <= low[i + 0] break xdn1 := xdn1 + 1 xdn1 // y-linebreak values for upper_line and lower_line y_up_lvl = (y0_frup_0 - y1_frup_1) / (xup1 + 2 - xup0) * xup0 + y0_frup_0 // y = slope * x0 + y0 y_dn_lvl = (y0_frdn_0 - y1_frdn_1) / (xdn1 + 2 - xdn0) * xdn0 + y0_frdn_0 // exit / filter //frup_buy = ta.crossover(high, y0_frup_0) //frdn_sell = ta.crossunder(low, y0_frdn_0) buy_up_line = tog_exit ? ta.crossover(high, y_up_lvl) : high > y_up_lvl// or frup_buy sell_dn_line = tog_exit ? ta.crossunder(low, y_dn_lvl) : low < y_dn_lvl// or frdn_sell //------------------------ grid -------------------------- re_grid = 0. re_grid := nz(high > re_grid[1] + grid_gap or low < re_grid[1] - grid_gap ? close : re_grid[1]) grid_ct_buy = re_grid < re_grid[1] grid_ct_sell = re_grid > re_grid[1] grid_re_buy = re_grid > re_grid[1] grid_re_sell = re_grid < re_grid[1] //plot(re_grid,"Plot Entry Grid ", color= color.yellow, linewidth= 2) //---------------------- reverse fractal signal and filter -------------------------- up_bar = close[0] > open[0] dn_bar = close[0] < open[0] hl = low[0] > low[1] lh = high[0] < high[1] rev_up_fr_sell = ta.pivothigh(high, 3, 0) and dn_bar and up_bar[1] or ta.pivothigh(high, 4, 1) and dn_bar and up_bar[1] or ta.pivothigh(high, 4, 1) and lh and up_bar and up_bar[1] rev_dn_fr_buy = ta.pivotlow(low, 3, 0) and up_bar and dn_bar[1] or ta.pivotlow(low, 4, 1) and up_bar and dn_bar[1] or ta.pivotlow(low, 4, 1) and hl and dn_bar and dn_bar[1] //-------------------------- pin bar entry signal------------------------------- candle_body = math.abs(open - close) pivot_up = ta.pivothigh(high, p_bar_sens_2, 0) pivot_dn = ta.pivotlow(low, p_bar_sens_2, 0) up_wick = close > open ? high - close : high - open dn_wick = close > open ? open - low : close - low pin_up_def = high - open > p_bar_sens_1 * candle_body and close < open or high - close > p_bar_sens_1 * candle_body and close > open pin_dn_def = open - low > p_bar_sens_1 * candle_body and close > open or close - low > p_bar_sens_1 * candle_body and close < open p_bar_sell = pin_up_def and pivot_up and up_wick > dn_wick p_bar_buy = pin_dn_def and pivot_dn and up_wick < dn_wick //------------------ ema21/sma20 filter ------------------------- ema_f(src, ema_len) => ta.ema(src, ema_len) // ma function definition sma_f(src, sma_len) => ta.sma(src, sma_len) ema_21 = ema_f(close, 21) sma_20 = sma_f(close, 20) ma_cross_buy = high > ema_21 and high > sma_20 and ema_21 > sma_20 ma_cross_sell = low < ema_21 and low < sma_20 and ema_21 < sma_20 //------------------------ ema1 x ema2 --------------------------- ema1_f = ema_f(close, ema1_len_f) ema2_f = ema_f(close, ema2_len_f) ema1_x = ema_f(close, ema1_len_x) ema2_x = ema_f(close, ema2_len_x) ema_1x2_buy_f = ema1_f > ema2_f ema_1x2_buy_x = tog_exit ? ta.crossover(ema1_x, ema2_x) : ema1_x > ema2_x ema_1x2_sell_x = tog_exit ? ta.crossunder(ema1_x, ema2_x) : ema1_x < ema2_x //--------------------- alma ------------------------ //filters alma_f = ta.alma(close, windowsize_f, offset_f, sigma_f) alma_slo_up_f = ta.rising(alma_f, 1) //exits alma_x = ta.alma(close, windowsize_x, offset_x, sigma_x) alma_slo_up_x = tog_exit ? ta.rising(alma_x, 1) and not ta.rising(alma_x, 1)[1] : ta.rising(alma_x, 1) alma_slo_dn_x = tog_exit ? ta.falling(alma_x, 1) and not ta.falling(alma_x, 1)[1] : ta.falling(alma_x, 1) //----------------------- macd filter ----------------------- [macdLine_f, signalLine_f, histLine_f] = ta.macd(close, 12, 26, 9) //filters macd_buy = macdLine_f > signalLine_f macd_sell = macdLine_f < signalLine_f //exit macd_buy_x = tog_exit ? ta.crossover(macdLine_f, signalLine_f) : macdLine_f > signalLine_f macd_sell_x = tog_exit ? ta.crossunder(macdLine_f, signalLine_f) : macdLine_f < signalLine_f //macd fast line slope macd_slope_up = ta.rising(macdLine_f, slope_len) //entry and filter macd_slope_up_x = tog_exit ? ta.rising(macdLine_f, slope_len_x) and not ta.rising(macdLine_f, slope_len_x)[1] : ta.rising(macdLine_f, slope_len_x) //exit macd_slope_dn_x = tog_exit ? ta.falling(macdLine_f, slope_len_x) and not ta.falling(macdLine_f, slope_len_x)[1] : ta.falling(macdLine_f, slope_len_x) //---------------------- rsi filters and entry signal------------------------ //entry rsi_f = ta.rsi(close, rsi_period) rsi_f_buy = rsi_f > 50 rsi_f_sell = rsi_f < 50 //filters rsi_f_buy_f = rsi_f > 50 rsi_f_sell_f = rsi_f < 50 //exit rsi_f_x = ta.rsi(close, rsi_period_x) rsi_f_buy_x = tog_exit ? ta.crossover(rsi_f_x, 50) : rsi_f_x > 50 rsi_f_sell_x = tog_exit ? ta.crossunder(rsi_f_x, 50) : rsi_f_x < 50 //---------------- Bill Williams Fractals (filter and entry signal) ----------------- up_fr = ta.pivothigh(fr_period, fr_period) dn_fr = ta.pivotlow(fr_period, fr_period) fractal_up_v = ta.valuewhen(up_fr, high[fr_period], 0) fractal_dn_v = ta.valuewhen(dn_fr, low[fr_period], 0) //entry signal fr_upx = ta.crossover(high, fractal_up_v) fr_dnx = ta.crossunder(low, fractal_dn_v) //filters fr_upx_f = high > fractal_up_v fr_dnx_f = low < fractal_dn_v //exit up_fr_x = ta.pivothigh(fr_period_x, fr_period_x) dn_fr_x = ta.pivotlow(fr_period_x, fr_period_x) fractal_up_v_x = ta.valuewhen(up_fr_x, high[fr_period_x], fr_past_x) fractal_dn_v_x = ta.valuewhen(dn_fr_x, low[fr_period_x], fr_past_x) fr_upx_x = tog_exit ? ta.crossover(high, fractal_up_v_x) : high > fractal_up_v_x fr_dnx_x = tog_exit ? ta.crossunder(low, fractal_dn_v_x) : low < fractal_dn_v_x //----------- higher low and higher high - lower high and lower low - entry -------------- fractal_dn_v_1 = ta.valuewhen(dn_fr, low[fr_period], 1) fractal_up_v_1 = ta.valuewhen(up_fr, high[fr_period], 1) hl_hh_buy = fractal_dn_v > fractal_dn_v_1 and high > fractal_up_v // 123 signal and filter lh_ll_sell = fractal_up_v < fractal_up_v_1 and low < fractal_dn_v //-------------------- SuperTrend filter and entry signal --------------------- //entry [SuperTrend, Dir] = ta.supertrend(mult, len) sup_buy = high > SuperTrend sup_sell = low < SuperTrend //filters sup_buy_f = high > SuperTrend sup_sell_f = low < SuperTrend //exit [SuperTrend_x, Dir_x] = ta.supertrend(mult_x, len_x) sup_buy_x = tog_exit ? ta.crossover(high, SuperTrend_x) : high > SuperTrend_x sup_sell_x = tog_exit ? ta.crossunder(low, SuperTrend_x) : low < SuperTrend_x //----------------- Parabolic SAR Signal (pb/ps) and filter ------------------- psar_buy = tog_exit ? ta.crossover(high, ta.sar(start, inc, max)) : high > ta.sar(start, inc, max)[0] psar_sell = tog_exit ? ta.crossunder(low, ta.sar(start, inc, max)) : low < ta.sar(start, inc, max)[0] //-------------------------- ADX entry and filter --------------------------- //adx signal 1/2 and filter [diplus_s, diminus_s, adx_s] = ta.dmi(di_length_s, adx_smooth_s) adx_above_thres = adx_s > adx_thres_s long_1 = diplus_s > diminus_s and adx_s < diplus_s and adx_s > diminus_s // ADX DMI entry and filter classic short_1 = diplus_s < diminus_s and adx_s > diplus_s and adx_s < diminus_s long_2 = diplus_s > diminus_s and adx_above_thres short_2 = diplus_s < diminus_s and adx_above_thres //filter adx_up_f = ta.rising(adx_s, 1) // ADX filter rising/falling //exit [diplus_x, diminus_x, adx_x] = ta.dmi(di_length_x, adx_smooth_x) adx_thres_f_x = tog_exit ? ta.crossunder(adx_x, adx_thres_x) : adx_x < adx_thres_x // ADX exit classic dmi_long_x = tog_exit ? ta.crossover(diplus_x, diminus_x) : diplus_x > diminus_x // dmi exit dmi_short_x = tog_exit ? ta.crossunder(diplus_x, diminus_x) : diplus_x < diminus_x adx_dn_x = tog_exit ? ta.falling(adx_x, 1) and not ta.falling(adx_x, 1)[1] : ta.falling(adx_x, 1) // ADX exit falling //-------------------------- SMA50 filter and entry--------------------------- //entry sma_buy = close[2] > ema_f(close, ma_period) sma_sell = close[2] < ema_f(close, ma_period) //filters sma_buy_f = close[2] > sma_f(close, ma_period) sma_sell_f = close[2] < sma_f(close, ma_period) //exit sma_buy_x = tog_exit ? ta.crossover(close[1], sma_f(close, ma_period_x)) : close[1] > sma_f(close, ma_period_x) sma_sell_x = tog_exit ? ta.crossunder(close[1], sma_f(close, ma_period_x)) : close[1] < sma_f(close, ma_period_x) //--------------------------- Segments signal ---------------------------- count1_l = 0 count2_l = 0 segment_1_stat_l = false segment_2_stat_l = false segment_3_stat_l = false higher_low = low > low[1] var line segment_low_1_l = na var line segment_low_2_l = na var line segment_low_3_l = na // long segments for i = 0 to sb by 1 count1_l := count1_l + 1 if low[1] > low[i + 2] and higher_low segment_1_stat_l := true break for i = count1_l to sb + count1_l by 1 count2_l := count2_l + 1 if low[1 + count1_l] > low[i + 2] and segment_1_stat_l segment_2_stat_l := true break for i = count2_l to sb + count2_l by 1 if low[1 + count1_l + count2_l] > low[i + 2 + count1_l] and segment_2_stat_l segment_3_stat_l := true break // short segments count1_s = 0 count2_s = 0 segment_1_stat_s = false segment_2_stat_s = false segment_3_stat_s = false lower_high = high < high[1] var line segment_high_1 = na var line segment_high_2 = na var line segment_high_3 = na for i = 0 to sb by 1 count1_s := count1_s + 1 if high[1] < high[i + 2] and lower_high segment_1_stat_s := true break for i = count1_s to sb + count1_s by 1 count2_s := count2_s + 1 if high[1 + count1_s] < high[i + 2] and segment_1_stat_s segment_2_stat_s := true break for i = count2_s to sb + count2_s by 1 if high[1 + count1_s + count2_s] < high[i + 2 + count1_s] and segment_2_stat_s segment_3_stat_s := true break // segments signals seg_stat_l = segment_1_stat_l and segment_2_stat_l and segment_3_stat_l seg_stat_s = segment_1_stat_s and segment_2_stat_s and segment_3_stat_s //entry segments_buy = high > high[1] and seg_stat_l[1] segments_sell = low < low[1] and seg_stat_s[1] //filters segments_buy_f = high > high[1] and seg_stat_l[1] segments_sell_f = low < low[1] and seg_stat_s[1] //-------------------------------------------------------------------------- Entry Signal Options ---------------------------------------------------------------------- // buy signal options 1 opt_sig_buy_1 = x_opt_1 == '---' ? false : x_opt_1 == 'BB reverse' ? bb_long_s : x_opt_1 == 'Grid - counter trend' ? grid_ct_buy : x_opt_1 == 'Grid - reentry' ? grid_re_buy : x_opt_1 == 'Pin bar' ? p_bar_buy : x_opt_1 == 'Fractals' ? fr_upx : x_opt_1 == 'Reverse fractal' ? rev_dn_fr_buy : false // sell signal options 1 opt_sig_sell_1 = x_opt_1 == '---' ? false : x_opt_1 == 'BB reverse' ? bb_short_s : x_opt_1 == 'Grid - counter trend' ? grid_ct_sell : x_opt_1 == 'Grid - reentry' ? grid_re_sell : x_opt_1 == 'Pin bar' ? p_bar_sell : x_opt_1 == 'Fractals' ? fr_dnx : x_opt_1 == 'Reverse fractal' ? rev_up_fr_sell : false // buy signal options 2 opt_sig_buy_2 = x_opt_2 == '---' ? false : x_opt_2 == 'BB reverse' ? bb_long_s : x_opt_2 == 'Grid - counter trend' ? grid_ct_buy : x_opt_2 == 'Grid - reentry' ? grid_re_buy : x_opt_2 == 'Pin bar' ? p_bar_buy : x_opt_2 == 'Fractals' ? fr_upx : x_opt_2 == 'Reverse fractal' ? rev_dn_fr_buy : false // sell signal options 2 opt_sig_sell_2 = x_opt_2 == '---' ? false : x_opt_2 == 'BB reverse' ? bb_short_s : x_opt_2 == 'Grid - counter trend' ? grid_ct_sell : x_opt_2 == 'Grid - reentry' ? grid_re_sell : x_opt_2 == 'Pin bar' ? p_bar_sell : x_opt_2 == 'Fractals' ? fr_dnx : x_opt_2 == 'Reverse fractal' ? rev_up_fr_sell : false //------------------------------------------------------------------------------ entry filters ----------------------------------------------------------------------------- f_secureSecurity(_symbol, _res, _src) => request.security(_symbol, _res, _src[repaint == 'Allowed' ? 0 : 1]) // no repainting - taken from PineCoders entry_filter_sig_buy_1 = entry_f_1 == '---' ? true : entry_f_1 == 'TRIX slope filter' ? trix_slo_up_f : entry_f_1 == 'EMA1 x EMA2 filter' ? ema_1x2_buy_f : entry_f_1 == '2HMA cross filter' ? hma_c_up_f : entry_f_1 == 'HMA slope filter' ? hma_up_f : entry_f_1 == 'MACD(fast) slope filter' ? macd_slope_up : entry_f_1 == 'MACD filter' ? macd_buy : entry_f_1 == 'RSI50 filter' ? rsi_f_buy_f : entry_f_1 == 'Fractals filter' ? fr_upx_f : entry_f_1 == 'SuperTrend filter' ? sup_buy_f : entry_f_1 == 'Parabolic SAR filter' ? psar_buy : entry_f_1 == 'SMA filter' ? sma_buy_f : entry_f_1 == 'ADX slope filter' ? adx_up_f : entry_f_1 == 'ADX DMI filter' ? adx_above_thres : entry_f_1 == 'Fractals 1-2-3 filter' ? hl_hh_buy : entry_f_1 == 'Reverse fractal filter' ? rev_dn_fr_buy : entry_f_1 == 'EMA21/SMA20 filter' ? ma_cross_buy : entry_f_1 == 'ALMA slope filter' ? alma_slo_up_f : entry_f_1 == 'Price X Kumo filter' ? kumo_buy_f : entry_f_1 == 'Price X Kijun filter' ? kijun_buy_f : entry_f_1 == 'Kumo flip filter' ? kumo_flip_buy_f : entry_f_1 == 'Chikou X price filter' ? chikou_X_price_buy_f : entry_f_1 == 'Chikou X Kumo filter' ? chikou_X_kumo_buy_f : entry_f_1 == 'Price X Tenkan filter' ? price_X_tenkan_buy_f : entry_f_1 == 'Tenkan X Kumo filter' ? tenkan_X_kumo_buy_f : entry_f_1 == 'Tenkan X Kijun filter' ? tenkan_X_kijun_buy_f : true entry_filter_sig_sell_1 = entry_f_1 == '---' ? true : entry_f_1 == 'TRIX slope filter' ? not trix_slo_up_f : entry_f_1 == 'EMA1 x EMA2 filter' ? not ema_1x2_buy_f : entry_f_1 == '2HMA cross filter' ? hma_c_dn_f : entry_f_1 == 'HMA slope filter' ? hma_dn_f : entry_f_1 == 'MACD(fast) slope filter' ? not macd_slope_up : entry_f_1 == 'MACD filter' ? macd_sell : entry_f_1 == 'RSI50 filter' ? rsi_f_sell_f : entry_f_1 == 'Fractals filter' ? fr_dnx_f : entry_f_1 == 'SuperTrend filter' ? sup_sell_f : entry_f_1 == 'Parabolic SAR filter' ? psar_sell : entry_f_1 == 'SMA filter' ? sma_sell_f : entry_f_1 == 'ADX slope filter' ? not adx_up_f : entry_f_1 == 'ADX DMI filter' ? adx_above_thres : entry_f_1 == 'Fractals 1-2-3 filter' ? lh_ll_sell : entry_f_1 == 'Reverse fractal filter' ? rev_up_fr_sell : entry_f_1 == 'EMA21/SMA20 filter' ? ma_cross_sell : entry_f_1 == 'ALMA slope filter' ? not alma_slo_up_f : entry_f_1 == 'Price X Kumo filter' ? kumo_sell_f : entry_f_1 == 'Price X Kijun filter' ? kijun_sell_f : entry_f_1 == 'Kumo flip filter' ? kumo_flip_sell_f : entry_f_1 == 'Chikou X price filter' ? chikou_X_price_sell_f : entry_f_1 == 'Chikou X Kumo filter' ? chikou_X_kumo_sell_f : entry_f_1 == 'Price X Tenkan filter' ? price_X_tenkan_sell_f : entry_f_1 == 'Tenkan X Kumo filter' ? tenkan_X_kumo_sell_f : entry_f_1 == 'Tenkan X Kijun filter' ? tenkan_X_kijun_sell_f : true entry_filter_sig_buy_2 = entry_f_2 == '---' ? true : entry_f_2 == 'TRIX slope filter' ? trix_slo_up_f : entry_f_2 == 'EMA1 x EMA2 filter' ? ema_1x2_buy_f : entry_f_2 == '2HMA cross filter' ? hma_c_up_f : entry_f_2 == 'HMA slope filter' ? hma_up_f : entry_f_2 == 'MACD(fast) slope filter' ? macd_slope_up : entry_f_2 == 'MACD filter' ? macd_buy : entry_f_2 == 'RSI50 filter' ? rsi_f_buy_f : entry_f_2 == 'Fractals filter' ? fr_upx_f : entry_f_2 == 'SuperTrend filter' ? sup_buy_f : entry_f_2 == 'Parabolic SAR filter' ? psar_buy : entry_f_2 == 'SMA filter' ? sma_buy_f : entry_f_2 == 'ADX slope filter' ? adx_up_f : entry_f_2 == 'ADX DMI filter' ? adx_above_thres : entry_f_2 == 'Fractals 1-2-3 filter' ? hl_hh_buy : entry_f_2 == 'Reverse fractal filter' ? rev_dn_fr_buy : entry_f_2 == 'EMA21/SMA20 filter' ? ma_cross_buy : entry_f_2 == 'ALMA slope filter' ? alma_slo_up_f : entry_f_2 == 'Price X Kumo filter' ? kumo_buy_f : entry_f_2 == 'Price X Kijun filter' ? kijun_buy_f : entry_f_2 == 'Kumo flip filter' ? kumo_flip_buy_f : entry_f_2 == 'Chikou X price filter' ? chikou_X_price_buy_f : entry_f_2 == 'Chikou X Kumo filter' ? chikou_X_kumo_buy_f : entry_f_2 == 'Price X Tenkan filter' ? price_X_tenkan_buy_f : entry_f_2 == 'Tenkan X Kumo filter' ? tenkan_X_kumo_buy_f : entry_f_2 == 'Tenkan X Kijun filter' ? tenkan_X_kijun_buy_f : true entry_filter_sig_sell_2 = entry_f_2 == '---' ? true : entry_f_2 == 'TRIX slope filter' ? not trix_slo_up_f : entry_f_2 == 'EMA1 x EMA2 filter' ? not ema_1x2_buy_f : entry_f_2 == '2HMA cross filter' ? hma_c_dn_f : entry_f_2 == 'HMA slope filter' ? hma_dn_f: entry_f_2 == 'MACD(fast) slope filter' ? not macd_slope_up : entry_f_2 == 'MACD filter' ? macd_sell : entry_f_2 == 'RSI50 filter' ? rsi_f_sell_f : entry_f_2 == 'Fractals filter' ? fr_dnx_f : entry_f_2 == 'SuperTrend filter' ? sup_sell_f : entry_f_2 == 'Parabolic SAR filter' ? psar_sell : entry_f_2 == 'SMA filter' ? sma_sell_f : entry_f_2 == 'ADX slope filter' ? not adx_up_f : entry_f_2 == 'ADX DMI filter' ? adx_above_thres : entry_f_2 == 'Fractals 1-2-3 filter' ? lh_ll_sell : entry_f_2 == 'Reverse fractal filter' ? rev_up_fr_sell : entry_f_2 == 'EMA21/SMA20 filter' ? ma_cross_sell : entry_f_2 == 'ALMA slope filter' ? not alma_slo_up_f : entry_f_2 == 'Price X Kumo filter' ? kumo_sell_f : entry_f_2 == 'Price X Kijun filter' ? kijun_sell_f : entry_f_2 == 'Kumo flip filter' ? kumo_flip_sell_f : entry_f_2 == 'Chikou X price filter' ? chikou_X_price_sell_f : entry_f_2 == 'Chikou X Kumo filter' ? chikou_X_kumo_sell_f : entry_f_2 == 'Price X Tenkan filter' ? price_X_tenkan_sell_f : entry_f_2 == 'Tenkan X Kumo filter' ? tenkan_X_kumo_sell_f : entry_f_2 == 'Tenkan X Kijun filter' ? tenkan_X_kijun_sell_f : true //entry buy filter 1 entry_filter_buy_1 = htf_entr_opt_1 == 'current' ? entry_filter_sig_buy_1[repaint == 'Allowed' ? 0 : 1] : f_secureSecurity(syminfo.tickerid, htf_entr_opt_1 == '5m' ? '5' : htf_entr_opt_1 == '10m' ? '10' : htf_entr_opt_1 == '15m' ? '15' : htf_entr_opt_1 == '30m' ? '30' : htf_entr_opt_1 == '1H' ? '60' : htf_entr_opt_1 == '2H' ? '120' : htf_entr_opt_1 == '3H' ? '180' : htf_entr_opt_1 == '4H' ? '240' : htf_entr_opt_1 == '6H' ? '360' : htf_entr_opt_1 == '8H' ? '480' : htf_entr_opt_1 == '12H' ? '720' : htf_entr_opt_1 == 'D' ? 'D' : htf_entr_opt_1 == '3D' ? '3D' : htf_entr_opt_1 == 'W' ? 'W' : htf_entr_opt_1 == 'M' ? 'M' : na, entry_filter_sig_buy_1) entry_filter_buy_11 = entry_f_1 == 'Fractals trend lines filter (no tf filter)' ? buy_up_line[repaint == 'Allowed' ? 0 : 1] : entry_f_1 == 'Segments filter (no tf filter)' ? segments_buy[repaint == 'Allowed' ? 0 : 1] : entry_f_1 == 'BB reverse filter (no tf filter)' ? bb_long_f[repaint == 'Allowed' ? 0 : 1] : entry_f_1 == 'Price filtered Kumo flip filter (no tf filter)' ? price_filtered_kumo_flip_buy_f[repaint == 'Allowed' ? 0 : 1] : true //entry sell filter 1 entry_filter_sell_1 = htf_entr_opt_1 == 'Current' ? entry_filter_sig_sell_1[repaint == 'Allowed' ? 0 : 1] : f_secureSecurity(syminfo.tickerid, htf_entr_opt_1 == '5m' ? '5' : htf_entr_opt_1 == '10m' ? '10' : htf_entr_opt_1 == '15m' ? '15' : htf_entr_opt_1 == '30m' ? '30' : htf_entr_opt_1 == '1H' ? '60' : htf_entr_opt_1 == '2H' ? '120' : htf_entr_opt_1 == '3H' ? '180' : htf_entr_opt_1 == '4H' ? '240' : htf_entr_opt_1 == '6H' ? '360' : htf_entr_opt_1 == '8H' ? '480' : htf_entr_opt_1 == '12H' ? '720' : htf_entr_opt_1 == 'D' ? 'D' : htf_entr_opt_1 == '3D' ? '3D' : htf_entr_opt_1 == 'W' ? 'W' : htf_entr_opt_1 == 'M' ? 'M' : na, entry_filter_sig_sell_1) entry_filter_sell_11 = entry_f_1 == 'Fractals trend lines filter (no tf filter)' ? sell_dn_line[repaint == 'Allowed' ? 0 : 1] : entry_f_1 == 'Segments filter (no tf filter)' ? segments_sell[repaint == 'Allowed' ? 0 : 1] : entry_f_1 == 'BB reverse filter (no tf filter)' ? bb_short_f[repaint == 'Allowed' ? 0 : 1] : entry_f_1 == 'Price filtered Kumo flip filter (no tf filter)' ? price_filtered_kumo_flip_sell_f[repaint == 'Allowed' ? 0 : 1] : true //entry buy filter 2 entry_filter_buy_2 = htf_entr_opt_2 == 'Current' ? entry_filter_sig_buy_2[repaint == 'Allowed' ? 0 : 1] : f_secureSecurity(syminfo.tickerid, htf_entr_opt_2 == '5m' ? '5' : htf_entr_opt_2 == '10m' ? '10' : htf_entr_opt_2 == '15m' ? '15' : htf_entr_opt_2 == '30m' ? '30' : htf_entr_opt_2 == '1H' ? '60' : htf_entr_opt_2 == '2H' ? '120' : htf_entr_opt_2 == '3H' ? '180' : htf_entr_opt_2 == '4H' ? '240' : htf_entr_opt_2 == '6H' ? '360' : htf_entr_opt_1 == '8H' ? '480' : htf_entr_opt_2 == '12H' ? '720' : htf_entr_opt_2 == 'D' ? 'D' : htf_entr_opt_2 == '3D' ? '3D' : htf_entr_opt_2 == 'W' ? 'W' : htf_entr_opt_2 == 'M' ? 'M' : na, entry_filter_sig_buy_2) entry_filter_buy_22 = entry_f_2 == 'Fractals trend lines filter (no tf filter)' ? buy_up_line[repaint == 'Allowed' ? 0 : 1] : entry_f_2 == 'Segments filter (no tf filter)' ? segments_buy[repaint == 'Allowed' ? 0 : 1] : entry_f_2 == 'BB reverse filter (no tf filter)' ? bb_long_f[repaint == 'Allowed' ? 0 : 1] : entry_f_2 == 'Price filtered Kumo flip filter (no tf filter)' ? price_filtered_kumo_flip_buy_f[repaint == 'Allowed' ? 0 : 1] : true //entry sell filter 2 entry_filter_sell_2 = htf_entr_opt_2 == 'Current' ? entry_filter_sig_sell_2[repaint == 'Allowed' ? 0 : 1] : f_secureSecurity(syminfo.tickerid, htf_entr_opt_2 == '5m' ? '5' : htf_entr_opt_2 == '10m' ? '10' : htf_entr_opt_2 == '15m' ? '15' : htf_entr_opt_2 == '30m' ? '30' : htf_entr_opt_2 == '1H' ? '60' : htf_entr_opt_2 == '2H' ? '120' : htf_entr_opt_2 == '3H' ? '180' : htf_entr_opt_2 == '4H' ? '240' : htf_entr_opt_2 == '6H' ? '360' : htf_entr_opt_1 == '8H' ? '480' : htf_entr_opt_2 == '12H' ? '720' : htf_entr_opt_2 == 'D' ? 'D' : htf_entr_opt_2 == '3D' ? '3D' : htf_entr_opt_2 == 'W' ? 'W' : htf_entr_opt_2 == 'M' ? 'M' : na, entry_filter_sig_sell_2) entry_filter_sell_22 = entry_f_2 == 'Fractals trend lines filter (no tf filter)' ? sell_dn_line[repaint == 'Allowed' ? 0 : 1] : entry_f_2 == 'Segments filter (no tf filter)' ? segments_sell[repaint == 'Allowed' ? 0 : 1] : entry_f_2 == 'BB reverse filter (no tf filter)' ? bb_short_f[repaint == 'Allowed' ? 0 : 1] : entry_f_2 == 'Price filtered Kumo flip filter (no tf filter)' ? price_filtered_kumo_flip_sell_f[repaint == 'Allowed' ? 0 : 1] : true //----------------------------------------------------------------------- exit filters ------------------------------------------------------------------------ exit_sig_buy_1 = exit_f_1 == '---' ? false : exit_f_1 == 'BB reverse exit' ? bb_long_x : exit_f_1 == 'TRIX slope exit' ? trix_slo_up_x : exit_f_1 == 'EMA1 x EMA2 exit' ? ema_1x2_buy_x : exit_f_1 == '2HMA cross exit' ? hma_c_up_x : exit_f_1 == 'HMA slope exit' ? hma_up_x : exit_f_1 == 'ALMA slope exit' ? alma_slo_up_x : exit_f_1 == 'Reverse fractal exit' ? rev_dn_fr_buy : exit_f_1 == 'MACD(fast) slope exit' ? macd_slope_up_x : exit_f_1 == 'MACD exit' ? macd_buy_x : exit_f_1 == 'RSI50 exit' ? rsi_f_buy_x : exit_f_1 == 'Fractals exit' ? fr_upx_x : exit_f_1 == 'SuperTrend exit' ? sup_buy_x : exit_f_1 == 'Parabolic SAR exit' ? psar_buy : exit_f_1 == 'SMA exit' ? sma_buy_x : exit_f_1 == 'DMI exit' ? dmi_long_x : exit_f_1 == 'ADX slope exit' ? adx_dn_x : exit_f_1 == 'ADX Threshold exit' ? adx_thres_f_x : exit_f_1 == 'Cloud exit' ? kumo_buy_x : exit_f_1 == 'Kijun exit' ? kijun_buy_x : false exit_sig_sell_1 = exit_f_1 == '---' ? false : exit_f_1 == 'BB reverse exit' ? bb_short_x : exit_f_1 == 'TRIX slope exit' ? trix_slo_dn_x : exit_f_1 == 'EMA1 x EMA2 exit' ? ema_1x2_sell_x : exit_f_1 == '2HMA cross exit' ? hma_c_dn_x : exit_f_1 == 'HMA slope exit' ? hma_dn_x : exit_f_1 == 'ALMA slope exit' ? alma_slo_dn_x : exit_f_1 == 'Reverse fractal exit' ? rev_up_fr_sell : exit_f_1 == 'MACD(fast) slope exit' ? macd_slope_dn_x : exit_f_1 == 'MACD exit' ? macd_sell_x : exit_f_1 == 'RSI50 exit' ? rsi_f_sell_x : exit_f_1 == 'Fractals exit' ? fr_dnx_x : exit_f_1 == 'SuperTrend exit' ? sup_sell_x : exit_f_1 == 'Parabolic SAR exit' ? psar_sell : exit_f_1 == 'SMA exit' ? sma_sell_x : exit_f_1 == 'DMI exit' ? dmi_short_x : exit_f_1 == 'ADX slope exit' ? adx_dn_x : exit_f_1 == 'ADX Threshold exit' ? adx_thres_f_x : exit_f_1 == 'Cloud exit' ? kumo_sell_x : exit_f_1 == 'Kijun exit' ? kijun_sell_x : false exit_sig_buy_2 = exit_f_2 == '---' ? false : exit_f_2 == 'BB reverse exit' ? bb_long_x : exit_f_2 == 'TRIX slope exit' ? trix_slo_up_x : exit_f_2 == 'EMA1 x EMA2 exit' ? ema_1x2_buy_x : exit_f_2 == '2HMA cross exit' ? hma_c_up_x : exit_f_2 == 'HMA slope exit' ? hma_up_x : exit_f_2 == 'ALMA slope exit' ? alma_slo_up_x : exit_f_2 == 'Reverse fractal exit' ? rev_dn_fr_buy : exit_f_2 == 'MACD(fast) slope exit' ? macd_slope_up_x : exit_f_2 == 'MACD exit' ? macd_buy_x : exit_f_2 == 'RSI50 exit' ? rsi_f_buy_x : exit_f_2 == 'Fractals exit' ? fr_upx_x : exit_f_2 == 'SuperTrend exit' ? sup_buy_x : exit_f_2 == 'Parabolic SAR exit' ? psar_buy : exit_f_2 == 'SMA exit' ? sma_buy_x : exit_f_2 == 'DMI exit' ? dmi_long_x : exit_f_2 == 'ADX slope exit' ? adx_dn_x : exit_f_2 == 'ADX Threshold exit' ? adx_thres_f_x : exit_f_2 == 'Cloud exit' ? kumo_buy_x : exit_f_2 == 'Kijun exit' ? kijun_buy_x : false exit_sig_sell_2 = exit_f_2 == '---' ? false : exit_f_2 == 'BB reverse exit' ? bb_short_s : exit_f_2 == 'TRIX slope exit' ? trix_slo_dn_x : exit_f_2 == 'EMA1 x EMA2 exit' ? ema_1x2_sell_x : exit_f_2 == '2HMA cross exit' ? hma_c_dn_x : exit_f_2 == 'HMA slope exit' ? hma_dn_x : exit_f_2 == 'ALMA slope exit' ? alma_slo_dn_x : exit_f_2 == 'Reverse fractal exit' ? rev_up_fr_sell : exit_f_2 == 'MACD(fast) slope exit' ? macd_slope_dn_x : exit_f_2 == 'MACD exit' ? macd_sell_x : exit_f_2 == 'RSI50 exit' ? rsi_f_sell_x : exit_f_2 == 'Fractals exit' ? fr_dnx_x : exit_f_2 == 'SuperTrend exit' ? sup_sell_x : exit_f_2 == 'Parabolic SAR exit' ? psar_sell : exit_f_2 == 'SMA exit' ? sma_sell_x : exit_f_2 == 'DMI exit' ? dmi_short_x : exit_f_2 == 'ADX slope exit' ? adx_dn_x : exit_f_2 == 'ADX Threshold exit' ? adx_thres_f_x : exit_f_2 == 'Cloud exit' ? kumo_sell_x : exit_f_2 == 'Kijun exit' ? kijun_sell_x : false // higher timeframe filter //short exit buy filter 1 exit_filter_buy_1 = htf_exit_opt_1 == 'Current' ? exit_sig_buy_1[repaint == 'Allowed' ? 0 : 1] : f_secureSecurity(syminfo.tickerid, htf_exit_opt_1 == '5m' ? '5' : htf_exit_opt_1 == '10m' ? '10' : htf_exit_opt_1 == '15m' ? '15' : htf_exit_opt_1 == '30m' ? '30' : htf_exit_opt_1 == '1H' ? '60' : htf_exit_opt_1 == '2H' ? '120' : htf_exit_opt_1 == '3H' ? '180' : htf_exit_opt_1 == '4H' ? '240' : htf_exit_opt_1 == '6H' ? '360' : htf_entr_opt_1 == '8H' ? '480' : htf_exit_opt_1 == '12H' ? '720' : htf_exit_opt_1 == 'D' ? 'D' : htf_exit_opt_1 == '3D' ? '3D' : htf_exit_opt_1 == 'W' ? 'W' : htf_exit_opt_1 == 'M' ? 'M' : na, exit_sig_buy_1) exit_filter_buy_11 = exit_f_1 == 'Fractals trend lines filter (no tf-filter)' ? buy_up_line[repaint == 'Allowed' ? 0 : 1] : false //long exit sell filter 1 exit_filter_sell_1 = htf_exit_opt_1 == 'Current' ? exit_sig_sell_1[repaint == 'Allowed' ? 0 : 1] : f_secureSecurity(syminfo.tickerid, htf_exit_opt_1 == '5m' ? '5' : htf_exit_opt_1 == '10m' ? '10' : htf_exit_opt_1 == '15m' ? '15' : htf_exit_opt_1 == '30m' ? '30' : htf_exit_opt_1 == '1H' ? '60' : htf_exit_opt_1 == '2H' ? '120' : htf_exit_opt_1 == '3H' ? '180' : htf_exit_opt_1 == '4H' ? '240' : htf_exit_opt_1 == '6H' ? '360' : htf_entr_opt_1 == '8H' ? '480' : htf_exit_opt_1 == '12H' ? '720' : htf_exit_opt_1 == 'D' ? 'D' : htf_exit_opt_1 == '3D' ? '3D' : htf_exit_opt_1 == 'W' ? 'W' : htf_exit_opt_1 == 'M' ? 'M' : na, exit_sig_sell_1) exit_filter_sell_11 = exit_f_1 == 'Fractals trend lines filter (no tf-filter)' ? sell_dn_line[repaint == 'Allowed' ? 0 : 1] : false //short exit buy filter 2 exit_filter_buy_2 = htf_exit_opt_2 == 'Current' ? exit_sig_buy_2[repaint == 'Allowed' ? 0 : 1] : f_secureSecurity(syminfo.tickerid, htf_exit_opt_2 == '5m' ? '5' : htf_exit_opt_2 == '10m' ? '10' : htf_exit_opt_2 == '15m' ? '15' : htf_exit_opt_2 == '30m' ? '30' : htf_exit_opt_2 == '1H' ? '60' : htf_exit_opt_2 == '2H' ? '120' : htf_exit_opt_2 == '3H' ? '180' : htf_exit_opt_2 == '4H' ? '240' : htf_exit_opt_2 == '6H' ? '360' : htf_entr_opt_1 == '8H' ? '480' : htf_exit_opt_2 == '12H' ? '720' : htf_exit_opt_2 == 'D' ? 'D' : htf_exit_opt_2 == '3D' ? '3D' : htf_exit_opt_2 == 'W' ? 'W' : htf_exit_opt_2 == 'M' ? 'M' : na, exit_sig_buy_2) exit_filter_buy_22 = exit_f_2 == 'Fractals trend lines filter (no tf-filter)' ? buy_up_line[repaint == 'Allowed' ? 0 : 1] : false //long exit sell filter 2 exit_filter_sell_2 = htf_exit_opt_2 == 'Current' ? exit_sig_sell_2[repaint == 'Allowed' ? 0 : 1] : f_secureSecurity(syminfo.tickerid, htf_exit_opt_2 == '5m' ? '5' : htf_exit_opt_2 == '10m' ? '10' : htf_exit_opt_2 == '15m' ? '15' : htf_exit_opt_2 == '30m' ? '30' : htf_exit_opt_2 == '1H' ? '60' : htf_exit_opt_2 == '2H' ? '120' : htf_exit_opt_2 == '3H' ? '180' : htf_exit_opt_2 == '4H' ? '240' : htf_exit_opt_2 == '6H' ? '360' : htf_entr_opt_1 == '8H' ? '480' : htf_exit_opt_2 == '12H' ? '720' : htf_exit_opt_2 == 'D' ? 'D' : htf_exit_opt_2 == '3D' ? '3D' : htf_exit_opt_2 == 'W' ? 'W' : htf_exit_opt_2 == 'M' ? 'M' : na, exit_sig_sell_2) exit_filter_sell_22 = exit_f_2 == 'Fractals trend lines filter (no tf-filter)' ? sell_dn_line[repaint == 'Allowed' ? 0 : 1] : false //------------------------------------------------------------ trigger and border levels ------------------------------------------------------- //close & stop level var bool cl_st_sw = false if (ta.cross(high, cl_st_lvl) or ta.cross(low, cl_st_lvl)) and barstate.isrealtime cl_st_sw := true strat_cl_st = en_close_stop and cl_st_sw //trigger level var bool trig_sw = false if (ta.cross(high, trig_lvl) or ta.cross(low, trig_lvl)) and backtest_period() trig_sw := true en_strat_st = en_trig_lvl ? trig_sw : true //upper border level var bool upper_sw = true if (ta.cross(high, bup_lvl) or ta.cross(low, bup_lvl)) and en_strat_st and backtest_period() upper_sw := false en_strat_bup = en_border_up ? upper_sw : true //lower border level var bool lower_sw = true if (ta.cross(high, bdn_lvl) or ta.cross(low, bdn_lvl)) and en_strat_st and backtest_period() lower_sw := false en_strat_bdn = en_border_dn ? lower_sw : true border_close = en_strat_st and (not en_strat_bup or not en_strat_bdn) // border level close en_strat = en_strat_st and en_strat_bup and en_strat_bdn // stops entries var bool en_idle = false var bool en_close = false if border_con == 'Idle' en_idle := true if border_con == 'Close All' en_close := true strat_idle = en_idle ? en_strat : true // makes entire strategy idle if borders are crossed //----------------------------------------------------------- entry and exit conditions ----------------------------------------------------------- exit_long = exit_filter_sell_1 or exit_filter_sell_2 or exit_filter_sell_11 or exit_filter_sell_22 exit_short = exit_filter_buy_1 or exit_filter_buy_2 or exit_filter_buy_11 or exit_filter_buy_22 long_filter = entry_filter_buy_1 and entry_filter_buy_2 and entry_filter_buy_11 and entry_filter_buy_22 short_filter = entry_filter_sell_1 and entry_filter_sell_2 and entry_filter_sell_11 and entry_filter_sell_22 es_l_cond = not exit_long and en_strat es_s_cond = not exit_short and en_strat entry_long_1 = opt_sig_buy_1 and long_filter and es_l_cond entry_long_2 = opt_sig_buy_2 and long_filter and es_l_cond entry_short_1 = opt_sig_sell_1 and short_filter and es_s_cond entry_short_2 = opt_sig_sell_2 and short_filter and es_s_cond //-------------------------------------------------------------- take average profit -------------------------------------------------------------- tp_step = 0. tp_step := nz(high > tp_step[1] + avtp_step or low < tp_step[1] - avtp_step ? close : tp_step[1]) tp_step_l = tp_step > tp_step[1] tp_step_s = tp_step < tp_step[1] av_profit_l = close - strategy.position_avg_price > av_tp and tp_step_l and long av_profit_s = strategy.position_avg_price - close > av_tp and tp_step_s and short //--------------------------------------------------------- stop loss of average position -------------------------------------------------------- sl_step = 0. sl_step := nz(high > sl_step[1] + avsl_step or low < sl_step[1] - avsl_step ? close : sl_step[1]) sl_step_l = sl_step < sl_step[1] sl_step_s = sl_step > sl_step[1] top = .0 top := nz(ta.pivothigh(high, sl_sen, 0), top[1]) bottom = .0 bottom := nz(ta.pivotlow(low, sl_sen, 0), bottom[1]) av_loss_l = tb_tog ? strategy.position_avg_price - close > av_sl and sl_step_l and long : top - close > av_sl and sl_step_l and long av_loss_s = tb_tog ? close - strategy.position_avg_price > av_sl and sl_step_s and short : close - bottom > av_sl and sl_step_s and short //---------------------------------------------------------------- tp and sl counter --------------------------------------------------------------- no_open_pos = strategy.position_size == 0 //break even var first_close_be = false first_close_be := strategy.netprofit > 0 // enables break even. Profit of all completed trades. var even_sw = false if ta.cross(close, strategy.position_avg_price)[repaint == 'Allowed' ? 0 : 1] and first_close_be and (inst_grid ? barstate.isrealtime : backtest_period()) even_sw := true break_ev = break_even and even_sw //tp counter var tp_ev_count_l = 0 var tp_ev_count_s = 0 if av_profit_l and long tp_ev_count_l := tp_ev_count_l +1 if av_profit_s and short tp_ev_count_s := tp_ev_count_s +1 count_con_tp_l = tp_ev_count_l >= tp_count or exit_long or no_open_pos // counter exit condition - longs count_con_tp_s = tp_ev_count_s >= tp_count or exit_short or no_open_pos // counter exit condition - shorts if count_con_tp_l // counter reset condioton for filter - longs tp_ev_count_l := 0 if count_con_tp_s // counter reset condioton for filter - shorts. tp_ev_count_s := 0 av_tp_qty_c_l = count_con_tp_l and en_tp_counter ? 100 : av_tp_qty // counter switch for tp - longs av_tp_qty_c_s = count_con_tp_s and en_tp_counter ? 100 : av_tp_qty // counter switch for tp - shorts //sl counter var sl_ev_count_l = 0 var sl_ev_count_s = 0 if av_loss_l and long sl_ev_count_l := sl_ev_count_l +1 if av_loss_s and short sl_ev_count_s := sl_ev_count_s +1 count_con_sl_l = sl_ev_count_l >= sl_count or exit_long or no_open_pos count_con_sl_s = sl_ev_count_s >= sl_count or exit_short or no_open_pos if count_con_sl_l sl_ev_count_l := 0 if count_con_sl_s sl_ev_count_s := 0 av_sl_qty_c_l = count_con_sl_l and en_sl_counter ? 100 : av_sl_qty av_sl_qty_c_s = count_con_sl_s and en_sl_counter ? 100 : av_sl_qty //scalping mode var scalp_sw = false if long and long_filter and not long_filter[1] or short and short_filter and not short_filter[1] or both and (long_filter and not long_filter[1] or short_filter and not short_filter[1]) scalp_sw := true if strategy.opentrades[1] != 0 and strategy.opentrades == 0 scalp_sw := false enabled_sl_tp = av_tp_en and av_sl_en and en_tp_counter and en_sl_counter scalp_l = (entry_long_1 or entry_long_2) and en_scalp_mode and scalp_sw and enabled_sl_tp// and tp_ev_count_l < tp_count scalp_s = (entry_short_1 or entry_short_2) and en_scalp_mode and scalp_sw and enabled_sl_tp// and tp_ev_count_s < tp_count //---------------------------------------------------------- 1st position factor and auto-increase of position calc ----------------------------------------------------------------- var first_close_mr = false first_close_mr := strategy.closedtrades == 0 // makes martingale working until the first close pos_c_cond = pos_count_in > strategy.opentrades // trade counter condition no_exit_filter = exit_f_1 == '---' and exit_f_2 == '---' // makes first position factor only working when no exit filters are active // calc and cond - backtesting pos_qty = en_pos_mart and pos_c_cond and first_close_mr and not both and no_exit_filter ? no_open_pos ? pos_start_mart : math.abs(strategy.position_size) * pos_factor : en_1st_pos_f ? no_open_pos ? pos_start_1st : lot_size_b : lot_size_b // martingale calc and sw - condition for martingale and 1st position - backtesting // calc and cond - live trading var float mart_lot_size = pos_start_mart_lv mart_lot_size := mart_lot_size * pos_factor + mart_lot_size[1] pos_qty_lv = en_pos_mart and pos_c_cond and first_close_mr and not both and no_exit_filter ? no_open_pos ? pos_start_mart_lv : mart_lot_size : en_1st_pos_f ? no_open_pos ? pos_start_1st_lv : lot_size_lv : lot_size_lv // martingale calc and sw - condition for martingale and 1st position - live trading // something like "get position_size" for lot size on bybit is needed for live trading. //------------------------------------- repetitive break even condition ---------------------------------- rep_even_long = rep_even and low[1] > strategy.position_avg_price and low < strategy.position_avg_price and not no_open_pos and math.abs(strategy.position_size) > be_min_lot rep_even_short = rep_even and high[1] < strategy.position_avg_price and high > strategy.position_avg_price and not no_open_pos and math.abs(strategy.position_size) > be_min_lot //rep_even_long_lv = rep_even and low[1] > strategy.position_avg_price and low < strategy.position_avg_price and not no_open_pos and math.abs(strategy.position_size) > be_min_lot //rep_even_short_lv = rep_even and high[1] < strategy.position_avg_price and high > strategy.position_avg_price and not no_open_pos and math.abs(strategy.position_size) > be_min_lot // something like "get position_size" for lot size on bybit is needed for live trading. //---------------------------------------------------------------------- strategy entries and exits --------------------------------------------------------------------- // strategy entries and exits (backtesting) if inst_grid ? barstate.isrealtime and strat_idle and not break_ev[1] and not strat_cl_st[1] : backtest_period() and strat_idle and not break_ev[1] and not strat_cl_st[1] if long if entry_long_1 and not en_scalp_mode strategy.entry('os_b', strategy.long, qty= pos_qty) if entry_long_2 and not en_scalp_mode strategy.entry('os_b', strategy.long, qty= pos_qty) if inst_pos and en_1st_pos_f and no_open_pos and en_strat and not en_scalp_mode strategy.entry('os_b', strategy.long, qty= pos_qty) if scalp_l strategy.entry('os_b', strategy.long, qty= pos_qty) if av_tp_en and av_profit_l and not no_open_pos strategy.close('os_b', qty_percent= av_tp_qty_c_l) if av_sl_en and av_loss_l and not no_open_pos strategy.close('os_b', qty_percent= av_sl_qty_c_l) if exit_long and not exit_long[1] and not no_open_pos strategy.close('os_b', qty_percent= qyt_exit) if border_close and en_close and not no_open_pos strategy.close('os_b', qty_percent= 100) if break_ev and not no_open_pos strategy.close('os_b', qty_percent= 100) if strat_cl_st and not no_open_pos strategy.close('os_b', qty_percent= 100) if rep_even_long strategy.close('os_b', qty_percent= rep_ev_qty) if short if entry_short_1 and not en_scalp_mode strategy.entry('os_s', strategy.short, qty= pos_qty) if entry_short_2 and not en_scalp_mode strategy.entry('os_s', strategy.short, qty= pos_qty) if inst_pos and en_1st_pos_f and no_open_pos and en_strat and not en_scalp_mode strategy.entry('os_s', strategy.short, qty= pos_qty) if scalp_s strategy.entry('os_s', strategy.short, qty= pos_qty) if av_tp_en and av_profit_s and not no_open_pos strategy.close('os_s', qty_percent= av_tp_qty_c_s) if av_sl_en and av_loss_s and not no_open_pos strategy.close('os_s', qty_percent= av_sl_qty_c_s) if exit_short and not exit_short[1] and not no_open_pos strategy.close('os_s', qty_percent= qyt_exit) if border_close and en_close and not no_open_pos strategy.close('os_s', qty_percent= 100) if break_ev and not no_open_pos strategy.close('os_s', qty_percent= 100) if strat_cl_st and not no_open_pos strategy.close('os_s', qty_percent= 100) if rep_even_short strategy.close('os_s', qty_percent= rep_ev_qty) // strategy entries and exits (live trading with alertatron on bybit ) - alert messages - same conditions like strategy....() var float av_tp_qty_c_l_var = 100 - av_tp_qty_c_l // calc because of alertatron syntax string var float av_sl_qty_c_l_var = 100 - av_sl_qty_c_l var float av_tp_qty_c_s_var = 100 - av_tp_qty_c_s var float av_sl_qty_c_s_var = 100 - av_sl_qty_c_s var float qyt_exit_var = 100 - qyt_exit var float rep_ev_qty_var = 100 - rep_ev_qty if inst_grid ? barstate.isrealtime and strat_idle and not break_ev[1] and not strat_cl_st[1] : backtest_period() and strat_idle and not break_ev[1] and not strat_cl_st[1] //entries if long and (entry_long_1 or entry_long_2) alert(message= 'BybitAPI(BTCUSD) { continue(if=positionShort); market(position= 0); } BybitAPI(BTCUSD) { wait(0.5s); market(side=buy, amount=' + str.tostring(pos_qty_lv) + '); } \n #bot', freq= alert.freq_once_per_bar) if long and inst_pos and en_1st_pos_f and no_open_pos and en_strat alert(message= 'BybitAPI(BTCUSD) { continue(if=positionShort); market(position= 0); } BybitAPI(BTCUSD) { wait(0.5s); market(side=buy, amount=' + str.tostring(pos_qty_lv) + '); } \n #bot', freq= alert.freq_once_per_bar) if short and (entry_short_1 or entry_short_2) alert(message= 'BybitAPI(BTCUSD) { continue(if=positionLong); market(position= 0); } BybitAPI(BTCUSD) { wait(0.5s); market(side=sell, amount=' + str.tostring(pos_qty_lv) + '); } \n #bot', freq= alert.freq_once_per_bar) if short and inst_pos and en_1st_pos_f and no_open_pos and en_strat alert(message= 'BybitAPI(BTCUSD) { continue(if=positionLong); market(position= 0); } BybitAPI(BTCUSD) { wait(0.5s); market(side=sell, amount=' + str.tostring(pos_qty_lv) + '); } \n #bot', freq= alert.freq_once_per_bar) //tp and sl if long and av_tp_en and av_profit_l and not no_open_pos alert(message= 'BybitAPI(BTCUSD) { market(position= ' + str.tostring(av_tp_qty_c_l_var) + ' %p); } \n #bot', freq= alert.freq_once_per_bar) if long and av_sl_en and av_loss_l and not no_open_pos alert(message= 'BybitAPI(BTCUSD) { market(position=' + str.tostring(av_sl_qty_c_l_var) + ' %p); } \n #bot', freq= alert.freq_once_per_bar) if short and av_tp_en and av_profit_s and not no_open_pos alert(message= 'BybitAPI(BTCUSD) { market(position= ' + str.tostring(av_tp_qty_c_s_var) + ' %p); } \n #bot', freq= alert.freq_once_per_bar) if short and av_sl_en and av_loss_s and not no_open_pos alert(message= 'BybitAPI(BTCUSD) { market(position=' + str.tostring(av_sl_qty_c_s_var) + ' %p); } \n #bot', freq= alert.freq_once_per_bar) //exit filters if long and not no_open_pos and exit_long and not exit_long[1] or short and exit_short and not exit_short[1] alert(message= 'BybitAPI(BTCUSD) { market(position=' + str.tostring(qyt_exit_var) + ' %p); } \n #bot', freq= alert.freq_once_per_bar) //start strategy, border exits if border_close and en_close and not no_open_pos alert(message= 'BybitAPI(BTCUSD) { market(position= 0); } \n #bot', freq= alert.freq_once_per_bar) //break even if break_ev and not no_open_pos alert(message= 'BybitAPI(BTCUSD) { market(position= 0); } \n #bot', freq= alert.freq_once_per_bar) //close & stop if strat_cl_st and not no_open_pos alert(message= 'BybitAPI(BTCUSD) { market(position= 0); } \n #bot', freq= alert.freq_once_per_bar) //repetitive break even if rep_even_long alert(message= 'BybitAPI(BTCUSD) { market(position=' + str.tostring(rep_ev_qty_var) + ' %p); } \n #bot', freq= alert.freq_once_per_bar) if rep_even_short alert(message= 'BybitAPI(BTCUSD) { market(position=' + str.tostring(rep_ev_qty_var) + ' %p); } \n #bot', freq= alert.freq_once_per_bar)
RSI of MACD Strategy [Long only]
https://www.tradingview.com/script/WfaaCqaN-RSI-of-MACD-Strategy-Long-only/
mohanee
https://www.tradingview.com/u/mohanee/
519
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© mohanee //@version=4 strategy(title="RSI of MACD Strategy[Long only]", shorttitle="RSIofMACD" , overlay=false, pyramiding=1, default_qty_type=strategy.percent_of_equity, default_qty_value=20, initial_capital=10000, currency=currency.USD) //default_qty_value=10, default_qty_type=strategy.fixed, ///////////////////////////////////////////////////////////////////////////////// // MACD Inputs /// fastLen = input(12, title="Fast Length") slowLen = input(21, title="Slow Length") sigLen = input(9, title="Signal Length") rsiLength = input(14, title="RSI of MACD Length") riskCapital = input(title="Risk % of capital", defval=10, minval=1) stopLoss=input(3,title="Stop Loss",minval=1) takeProfit=input(false, title="Take Profit") [macdLine, signalLine, _] = macd(close, fastLen, slowLen, sigLen) rsiOfMACD = rsi(macdLine, rsiLength) emaSlow = ema(close, slowLen) //drawings ///////////////////////////////////////////////////////////////////////////////// obLevelPlot = hline(80, title="Overbought / Profit taking line", color=color.blue , linestyle=hline.style_dashed) osLevelPlot = hline(30, title="Oversold / entry line", color=color.green, linestyle=hline.style_dashed) exitLinePlot = hline(15, title="Exit line", color=color.red, linestyle=hline.style_dashed) plot(rsiOfMACD, title = "rsiOfMACD" , color=color.purple) //drawings ///////////////////////////////////////////////////////////////////////////////// //Strategy Logic ///////////////////////////////////////////////////////////////////////////////// //Entry-- //Echeck how many units can be purchased based on risk manage ment and stop loss qty1 = (strategy.equity * riskCapital / 100 ) / (close*stopLoss/100) //check if cash is sufficient to buy qty1 , if capital not available use the available capital only qty1:= (qty1 * close >= strategy.equity ) ? (strategy.equity / close) : qty1 strategy.entry(id="RSIofMACD", long=true, qty=qty1, when = ( crossover(rsiOfMACD, 30) or crossover(rsiOfMACD, 35) ) and close>=emaSlow ) bgcolor(abs(strategy.position_size)>=1 ? color.blue : na , transp=70) barcolor(abs(strategy.position_size)>=1 and ( crossover(rsiOfMACD, 30) or crossover(rsiOfMACD, 35) ) ? color.purple : abs(strategy.position_size)>=1 ? color.blue : na ) //partial exit strategy.close(id="RSIofMACD", comment="PExit Profit is "+tostring(close - strategy.position_avg_price, "###.##") , qty=strategy.position_size/3, when= takeProfit and abs(strategy.position_size)>=1 and close > strategy.position_avg_price and crossunder(rsiOfMACD,80) ) //Close All strategy.close(id="RSIofMACD", comment="Close All Profit is "+tostring(close - strategy.position_avg_price, "###.##"), when=abs(strategy.position_size)>=1 and crossunder(rsiOfMACD,15) ) //and close > strategy.position_avg_price ) //Strategy Logic /////////////////////////////////////////////////////////////////////////////////
Ultimate Strategy Template
https://www.tradingview.com/script/2lGyzYkC-Ultimate-Strategy-Template/
Daveatt
https://www.tradingview.com/u/Daveatt/
8,862
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/ // Β© Daveatt // @version=4 // https://www.tradingview.com/blog/en/use-an-input-from-another-indicator-with-your-strategy-19584/ SystemName = "BEST Strategy Template" TradeId = "DAVE" // These values are used both in the strategy() header and in the script's relevant inputs as default values so they match. // Unless these values match in the script's Inputs and the TV backtesting Properties, results between them cannot be compared. InitCapital = 1000000 InitPosition = 10.0 InitCommission = 0.075 InitPyramidMax = 3 CalcOnorderFills = true strategy(title=SystemName, shorttitle=SystemName, overlay=true, pyramiding=InitPyramidMax, initial_capital=InitCapital, default_qty_type=strategy.percent_of_equity, default_qty_value=InitPosition, commission_type=strategy.commission.percent, commission_value=InitCommission, calc_on_order_fills=CalcOnorderFills, precision=6, max_lines_count=500, max_labels_count=500) // β€”β€”β€”β€”β€” You capture the Source of your indicator here ext_source_ = input(close, type=input.source, title="Data source") // Custom close signal custom_close = input(false, title="Use Custom Close?") // β€”β€”β€”β€”β€” Bar Coloring clrBars = input(true,title="Colour Candles to Trade Order state") CloseSession = input(false, title="Close positions at market at the end of each session ?") Session = input(title="Trading Session", type=input.session, defval="0000-2345") OpenDirection = input(defval="ALL", title="Open Trading Direction", options=["ALL", "LONG", "SHORT"]) CloseDirection = input(defval="ALL", title="Close Trading Direction", options=["ALL", "LONG", "SHORT"]) closeOnOpposite = input(true, title="Close on Opposite Signal") // β€”β€”β€”β€”β€” Date range filtering DateFilter = input(false, "═════════════ Date Range Filtering") // β€”β€”β€”β€”β€” Syntax coming from https://www.tradingview.com/blog/en/new-parameter-for-date-input-added-to-pine-21812/ i_startTime = input(defval = timestamp("01 Jan 2019 13:30 +0000"), title = "Start Time", type = input.time) i_endTime = input(defval = timestamp("30 Dec 2021 23:30 +0000"), title = "End Time", type = input.time) TradeDateIsAllowed() => DateFilter ? time >= i_startTime and time <= i_endTime : true // β€”β€”β€”β€”β€” Set the max losing streak length with an input setmaxLosingStreak = input(title="═════════════ Set Max number of consecutive loss trades", type=input.bool, defval=false) maxLosingStreak = input(title="Max of consecutive loss trades", type=input.integer, defval=15, minval=1) setmaxWinStreak = input(title="═════════════ Set Max number of consecutive won trades", type=input.bool, defval=false) maxWinStreak = input(title="Max Winning Streak Length", type=input.integer, defval=15, minval=1) // β€”β€”β€”β€”β€” Set the max consecutive days with a loss setmaxLosingDaysStreak = input(title="═════════════ Set MAX consecutive days with a loss in a row", type=input.bool, defval=false) maxLosingDaysStreak = input(title="Max of consecutive days with a loss in a row", type=input.integer, defval=3, minval=1) setMaxDrawdown = input(title="═════════════ Set Max Total DrawDown", type=input.bool, defval=false) // β€”β€”β€”β€”β€” Input for the strategy's maximum drawdown (in % of strategy equity) maxPercDd = input(title="Max Drawdown (%)", type=input.integer, defval=10, minval=1, maxval=100) setMaxIntradayLoss = input(title="═════════════ Set Max Intraday Loss", type=input.bool, defval=false) // β€”β€”β€”β€”β€” Input for the strategy's maximum intraday loss (in % of strategy equity) maxIntradayLoss = input(title="Max Intraday Loss (%)", type=input.integer, defval=3, minval=1, maxval=100) setNumberDailyTrades = input(title="═════════════ Limit the number of trades per day", type=input.bool, defval=false) maxDailyTrades = input(title="Number MAX of daily trades", type=input.integer, defval=10, minval=1, maxval=100) setNumberWeeklyTrades = input(title="═════════════ Limit the number of trades per week", type=input.bool, defval=false) maxWeeklyTrades = input(title="Number MAX of weekly trades", type=input.integer, defval=50, minval=1, maxval=100) // β€”β€”β€”β€”β€” Stop loss management StopType = input(title="═════════════ Stop Type Selection", defval="None", options=["None", "Percent", "Trailing", "ATR"]) // β€”β€”β€”β€”β€” Percent LossPerc = input(title="Stop Loss (%)", type=input.float, minval=0.0, step=0.5, defval=1) * 0.01 TrailPerc = input(title="Trail Stop Loss (%)", type=input.float, minval=0.0, step=0.5, defval=3) * 0.01 // β€”β€”β€”β€”β€” ATR atrStopLength = input(title="═════════════ ATR Stop Length", type=input.integer, defval=14) riskRatioATR = input(defval=1, title="[ATR ONLY] Risk Ratio", type=input.float,step=0.10) // β€”β€”β€”β€”β€” Take Profit TakeProfitType = input(title="════ Take Profit Type Selection", defval="None", options=["None", "Percent", "ATR"]) // β€”β€”β€”β€”β€” Percent ProfitPerc = input(title="Take Profit (%)", type=input.float, minval=0.0, step=0.5, defval=3) * 0.01 // β€”β€”β€”β€”β€” ATR atrTakeProfitLength = input(title="══════ ATR Take Profit Length", type=input.integer, defval=14) rewardRatioATR = input(defval=2, title="[ATR ONLY] Reward Ratio", type=input.float,step=0.10) // global variables from PineCoders // β€”β€”β€”β€”β€” Colors MyGreenRaw = color.new(color.lime,0), MyGreenMedium = color.new(#00b300,0), MyGreenSemiDark = color.new(#009900,0), MyGreenDark = color.new(#006600,0), MyGreenDarkDark = color.new(#003300,0) MyRedRaw = color.new(color.red,0), MyRedMedium = color.new(#cc0000,0), MyRedSemiDark = color.new(#990000,0), MyRedDark = color.new(#330000,0), MyRedDarkDark = color.new(#330000,0) MyFuchsiaRaw = color.new(color.fuchsia,0), MyFuchsiaMedium = color.new(#c000c0,0), MyFuchsiaDark = color.new(#800080,0), MyFuchsiaDarkDark = color.new(#400040,0) MyYellowRaw = color.new(color.yellow,0), MyYellowMedium = color.new(#c0c000,0), MyYellowDark = color.new(#808000,0), MyYellowDarkDark = color.new(#404000,0) MyOrangeRaw = color.new(#ffa500,0), MyOrangeMedium = color.new(#cc8400,0), MyOrangeDark = color.new(#996300,0) MyBlueRaw = color.new(#4985E7,0), MyBlueMedium = color.new(#4985E7,0) MyGreenBackGround = color.new(#00FF00,93), MyRedBackGround = color.new(#FF0000,90) BIG_NUMBER_COUNT = 1000 // variables initialisation ext_source = nz(ext_source_) // 1 is bull signal bull = (ext_source == 1) // -1 is bear signal bear = (ext_source == -1) // 2 exit custom close long exit_bull = custom_close and (ext_source == 2) // -2 exit custom close short exit_bear = custom_close and (ext_source == -2) // Entry Price entry_price = valuewhen(condition=bear or bull, source=close, occurrence=0) // β€”β€”β€”β€”β€” RISK MANAGEMENT condintradayloss = (setMaxIntradayLoss) ? maxIntradayLoss : 100 strategy.risk.max_intraday_loss(value=condintradayloss, type=strategy.percent_of_equity) condmaxdrawdown = (setMaxDrawdown) ? maxPercDd : 100 strategy.risk.max_drawdown(value=condmaxdrawdown, type=strategy.percent_of_equity) // daily trades calculation oktoTradeDaily = true tradesIntradayCount = (setNumberDailyTrades) ? maxDailyTrades : BIG_NUMBER_COUNT strategy.risk.max_intraday_filled_orders(count=tradesIntradayCount) // weekly trades calculation tradesLastWeek = 0 tradesLastWeek := if (dayofweek == dayofweek.monday) and (dayofweek != dayofweek[1]) strategy.closedtrades[1] + strategy.opentrades[1] else tradesLastWeek[1] // Calculate number of trades this week weeklyTrades = (strategy.closedtrades + strategy.opentrades) - tradesLastWeek okToTradeWeekly = (setNumberWeeklyTrades) ? (weeklyTrades < maxWeeklyTrades) : true // consecutive loss days in a row countConsLossDays = (setmaxLosingDaysStreak) ? maxLosingDaysStreak : BIG_NUMBER_COUNT strategy.risk.max_cons_loss_days(countConsLossDays) // Calculate the total losing streaks // Check if there's a new losing trade that increased the streak newLoss = (strategy.losstrades > strategy.losstrades[1]) and (strategy.wintrades == strategy.wintrades[1]) and (strategy.eventrades == strategy.eventrades[1]) // Determine current losing streak length streakLossLen = 0 streakLossLen := if (newLoss) nz(streakLossLen[1]) + 1 else if (strategy.wintrades > strategy.wintrades[1]) or (strategy.eventrades > strategy.eventrades[1]) 0 else nz(streakLossLen[1]) // Check if losing streak is under max allowed okToTradeLossStreak = (setmaxLosingStreak) ? streakLossLen < maxLosingStreak : true // Calculate the total winning streaks // See if there's a new winner that increased the streak newWin = (strategy.wintrades > strategy.wintrades[1]) and (strategy.losstrades == strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1]) // Figure out current winning streak length streakWinLen = 0 streakWinLen := if (newWin) nz(streakWinLen[1]) + 1 else if (strategy.losstrades > strategy.losstrades[1]) or (strategy.eventrades > strategy.eventrades[1]) 0 else nz(streakWinLen[1]) // Check if winning streak is under max allowed okToTradeWinStreak = (setmaxWinStreak) ? streakWinLen < maxWinStreak : true // Stop loss management longPercStopPrice = strategy.position_avg_price * (1 - LossPerc) shortPercStopPrice = strategy.position_avg_price * (1 + LossPerc) // trailing // Determine trail stop loss prices longTrailStopPrice = 0.0, shortTrailStopPrice = 0.0 final_SL_Long = 0.0, final_SL_Short = 0.0 longTrailStopPrice := if (strategy.position_size > 0) stopValue = close * (1 - TrailPerc) max(stopValue, longTrailStopPrice[1]) else 0 shortTrailStopPrice := if (strategy.position_size < 0) stopValue = close * (1 + TrailPerc) min(stopValue, shortTrailStopPrice[1]) else 999999 useSL = StopType != "None" use_SL_Percent = StopType == "Percent" use_SL_Trail = StopType == "Trailing" use_SL_ATR = StopType == "ATR" // Use this function to return the correct pip value for pips on Forex symbols pip() => syminfo.mintick * (syminfo.type == "forex" ? 10 : 1) // ATR // Function atr (average true range) returns the RMA of true range. // True range is max(high - low, abs(high - close[1]), abs(low - close[1])) atr_stop = atr(atrStopLength) atr_tp = atr(atrTakeProfitLength) // ATR used for Risk:Reward RR_STOP_ATR = 0.0, RR_STOP_ATR := nz(RR_STOP_ATR[1]) RR_TP_ATR = 0.0, RR_TP_ATR := nz(RR_TP_ATR[1]) // Capturig the atr value at signal time only if bull or bear RR_STOP_ATR := atr_stop RR_TP_ATR := atr_tp final_SL_Long := if use_SL_Percent longPercStopPrice else if use_SL_Trail longTrailStopPrice else if use_SL_ATR entry_price - (RR_STOP_ATR * riskRatioATR) final_SL_Short := if use_SL_Percent shortPercStopPrice else if use_SL_Trail shortTrailStopPrice else if use_SL_ATR entry_price + (RR_STOP_ATR * riskRatioATR) // Plot stop loss values for confirmation plot(series=(strategy.position_size > 0 and useSL) ? final_SL_Long : na, color=color.red, style=plot.style_cross, linewidth=2, title="Long Stop Loss") plot(series=(strategy.position_size < 0 and useSL) ? final_SL_Short : na, color=color.red, style=plot.style_cross, linewidth=2, title="Short Stop Loss") // Used for debug and check the ATR SL value plot(use_SL_ATR and strategy.position_size != 0 ? RR_STOP_ATR * riskRatioATR : na, color=color.red, transp=100, title="ATR Stop Value") // Take Profit Manangement useTakeProfit = TakeProfitType != "None" use_TP_Percent = TakeProfitType == "Percent" use_TP_ATR = TakeProfitType == "ATR" TPlongPrice = use_TP_Percent ? strategy.position_avg_price * (1 + ProfitPerc) : strategy.position_avg_price + (RR_TP_ATR * rewardRatioATR) TPshortPrice = use_TP_Percent ? strategy.position_avg_price * (1 - ProfitPerc) : strategy.position_avg_price - (RR_TP_ATR * rewardRatioATR) // Plot take profit values for confirmation plot(series=(strategy.position_size > 0 and useTakeProfit) ? TPlongPrice : na, color=color.green, style=plot.style_circles, linewidth=3, title="Long Take Profit") plot(series=(strategy.position_size < 0 and useTakeProfit) ? TPshortPrice : na, color=color.red, style=plot.style_circles, linewidth=3, title="Short Take Profit") // Used for debug and check the ATR TP value plot(use_TP_ATR and strategy.position_size != 0 ? RR_TP_ATR * rewardRatioATR : na, color=color.green, transp=100, title="ATR TP Value") // Session calculations // The BarInSession function returns true when // the current bar is inside the session parameter BarInSession(sess) => time(timeframe.period, sess) != 0 in_session = BarInSession(Session) okToTradeInSession = CloseSession ? in_session : true new_session = in_session and not in_session[1] bgcolor(color=(CloseSession and BarInSession(Session)[1]) ? color.green : na, title="Trading Session", transp=85) // consolidation of the conditions okToTrade = okToTradeWeekly and okToTradeLossStreak and okToTradeWinStreak and TradeDateIsAllowed() and okToTradeInSession// and TradeHourlyIsAllowed() // Orders part longs_opened = strategy.position_size > 0 shorts_opened = strategy.position_size < 0 trades_opened = strategy.position_size != 0 longs_opened_in_session = CloseSession and longs_opened shorts_opened_in_session = CloseSession and shorts_opened // trades_opened_in_session = CloseSession and trades_opened open_all = OpenDirection == "ALL" open_all_longs = OpenDirection != "SHORT" open_all_shorts = OpenDirection != "LONG" // Go long longCondition = bull if (longCondition and okToTrade and okToTradeInSession and open_all_longs) strategy.entry("Long", strategy.long, alert_message="{{ticker}} Long Signal - Entry Price: " + tostring(close) + " Timeframe: {{interval}}") alert(syminfo.tickerid + " Long Signal - Entry Price: " + tostring(close) + " Timeframe: " + timeframe.period, alert.freq_once_per_bar_close) // Go Short shortCondition = bear if (shortCondition and okToTrade and okToTradeInSession and open_all_shorts) strategy.entry("Short", strategy.short, alert_message="{{ticker}} Short Signal - Entry Price: " + tostring(close) + " Timeframe: {{interval}}") alert(syminfo.tickerid + " Short Signal - Entry Price: " + tostring(close) + " Timeframe: " + timeframe.period, alert.freq_once_per_bar_close) // Execute Exits if closeOnOpposite and strategy.position_size > 0 and shortCondition// and open_all_shorts strategy.close(id="Long", alert_message="{{ticker}} Short Signal - Close Long Signal - Timeframe: {{interval}}", comment="Short Signal\nClose Long") if closeOnOpposite and strategy.position_size < 0 and longCondition// and open_all_longs strategy.close(id="Short", alert_message="{{ticker}} Long Signal - Close Short Signal - Timeframe: {{interval}}", comment="Long Signal\nClose Short") // Custom close if (strategy.position_size > 0 and exit_bull) strategy.close(id="Long", alert_message="{{ticker}} Custom Close Long Signal - Timeframe: {{interval}}", comment="Custom Close Signal\nClose Long") alert(syminfo.tickerid + " Custom Close Long Signal - Entry Price: " + tostring(close) + " Timeframe: " + timeframe.period, alert.freq_once_per_bar_close) if (strategy.position_size < 0 and exit_bear) strategy.close(id="Short", alert_message="{{ticker}} Custom Close Short Signal - Timeframe: {{interval}}", comment="Custom Close Signal\nClose Short") alert(syminfo.tickerid + " Custom Close Short Signal - Entry Price: " + tostring(close) + " Timeframe: " + timeframe.period, alert.freq_once_per_bar_close) close_all = CloseDirection == "ALL" close_all_longs = CloseDirection != "SHORT" close_all_shorts = CloseDirection != "LONG" if (strategy.position_size > 0 and close_all_longs) strategy.exit(id="Exit Long", from_entry="Long", stop=(useSL) ? final_SL_Long : na, limit=(useTakeProfit) ? TPlongPrice : na, alert_message="{{ticker}} Close Long Signal - Timeframe: {{interval}}") alert(syminfo.tickerid + " Exit Long Signal - Exit Price: " + tostring(close) + " Timeframe: " + timeframe.period, alert.freq_once_per_bar_close) if (strategy.position_size < 0 and close_all_shorts) strategy.exit(id="Exit Short", from_entry="Short", stop=(useSL) ? final_SL_Short : na, limit=(useTakeProfit) ? TPshortPrice : na, alert_message="{{ticker}} Close Short Signal - Timeframe: {{interval}}") alert(syminfo.tickerid + " Exit Short Signal - Exit Price: " + tostring(close) + "Timeframe: " + timeframe.period, alert.freq_once_per_bar_close) // // Close all Longs only // if not okToTradeInSession and close_all_longs and longs_opened_in_session // strategy.close(id="Long") // // Close all Shorts only // if not okToTradeInSession and close_all_shorts and shorts_opened_in_session // strategy.close(id="Short") // Close all positions at the end of each session regardeless of their profit/loss if not okToTradeInSession and close_all and trades_opened strategy.close_all() // Flatten strategy when max losing streak is reached close_strat = not okToTradeWeekly or not okToTradeLossStreak or not okToTradeWinStreak or not TradeDateIsAllowed() if (close_strat) // close all existing orders strategy.close_all() // Colour code the candles bclr = not clrBars ? na : strategy.position_size == 0 ? color.gray : longs_opened ? color.lime : shorts_opened ? color.red : color.gray barcolor(bclr, title="Trade State Bar Colouring")
JBravo Swing with GoGo Juice
https://www.tradingview.com/script/ROnotdxa-JBravo-Swing-with-GoGo-Juice/
bradvaughn
https://www.tradingview.com/u/bradvaughn/
110
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© bradvaughn //@version=4 strategy("JBravo Swing", overlay = false) var buy_in_progress = false //Moving Averages smaInput1 = input(title="Display SMA 9", type=input.bool, defval=true) smaInput2 = input(title="Display EMA 20", type=input.bool, defval=true) smaInput4 = input(title="Display SMA 180", type=input.bool, defval=true) colored_180 = input(false, title="Color-code 180 trend direction") vwapInput = input(title="Display VWAP", type=input.bool, defval=true) sma9 = sma(close, 9) ema20 = ema(close, 20) sma180 = sma(close, 180) //Plot Moving Averages plot(smaInput1 ? sma9 : na, color= color.red, title="SMA 9") plot(smaInput2 ? ema20 : na, color = color.yellow, title="EMA 20") // Plot VWAP vwap1 = vwap(hlc3) plot(vwapInput ? vwap1 : na, color = color.blue, title="VWAP") vwaplong = vwap1 > ema20 vwapshort = vwap1 < ema20 //Color SMA 180 trend direction if selected sma180_uptrend = sma(close, 180) > sma(close[2], 180) colr = sma180_uptrend == true or colored_180 == false ? color.white : colored_180 == true ? color.gray : na plot(smaInput4 ? sma180 : na, color = colr, title="SMA 180") //Get value of lower end of candle buyLow = iff(lowest(open, 1) < lowest(close, 1), lowest(open, 1), lowest(close, 1)) sellLow = lowest(close, 1) // Find the lower MA for crossover sell condition sellma = iff((sma9<ema20), sma9, ema20) //SMA 9 trend direction sma9_uptrend = sma(close, 9) > sma(close[2], 9) //EMA 20 trend direction ema20_uptrend = ema(close, 20) > sma(close[2], 20) //Buy or sell if conditions are met // Buy when the candle low is above the SMA9 // Sell when the candle low is below the lower of SMA9 and EMA20 Buy = iff(buy_in_progress == false and buyLow > sma9 == true, true, false) Sell = iff(buy_in_progress == true and sellLow < sellma == true, true, false) // Determine stong buy and strong sell conditions. // If moving averages are all up, then this will qualify a buy as a strong buy. // If the moving averages are not up (ie. down) then this will qualify a sell as a strong sell StrongBuy = iff (Buy and sma9_uptrend and sma180_uptrend and ema20_uptrend and (sma9 > ema20) and (ema20 > sma180), true, false) StrongSell = iff (Sell and not sma9_uptrend and not sma180_uptrend and not ema20_uptrend and (sma9 < ema20) and (ema20 < sma180), true, false) //Update Trading status if bought or sold if Buy buy_in_progress := true if Sell buy_in_progress := false // Clear Buy and Sell conditions if StrongBuy or StrongSell conditions exist. // This disables plotting Buy and Sell conditions if StrongBuy Buy := false if StrongSell Sell := false //Display BUY/SELL indicators plotshape(Buy,title="Buy", color=color.green, style=shape.arrowup,location=location.belowbar, text="Buy") plotshape(StrongBuy,title="Strong Buy", color=color.green, style=shape.arrowup,location=location.belowbar, text="Strong Buy") plotshape(Sell,title="Sell", color=color.red, style=shape.arrowdown,text="Sell") plotshape(StrongSell,title="Strong Sell", color=color.red, style=shape.arrowdown,text="Strong Sell") strategy.entry("GoGo Long", strategy.long, 1, when=vwaplong and vwapInput) strategy.entry("GoGo Short", strategy.short, 1, when=vwapshort and vwapInput) strategy.close("GoGo Long", when = vwapshort and vwapInput) strategy.close("GoGo Short", when = vwaplong and vwapInput) alertcondition(Buy, title="Buy Signal", message="Buy") alertcondition(Sell, title="Sell Signal", message="Sell")
Donchian Channels Strategy by KrisWaters
https://www.tradingview.com/script/z7hAbAHD/
kriswaters
https://www.tradingview.com/u/kriswaters/
390
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/ // Β© kriswaters //@version=4 strategy("Donchian Channels Strategy by KrisWaters", overlay=true, initial_capital=1000, currency='USD', default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type= strategy.commission.percent, commission_value=0.075) // Date filter 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 = 2017, title = "From Year", minval = 1900) 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 = 9999, title = "To Year", minval = 2017) 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" // Strategy Settings canEnterLong = input(true, title="Can Enter Long Position") canEnterShort = input(false, title="Can Enter Short Position") showLongChannel = input(true, title="Show Donchian Long Channels") showShortChannel = input(false , title="Show Donchian Short Channels") useAtrAsStopRule = input(false, title="Enable ATR Stop Rule") // DonCcian Channel Lengths longUpperLength = input(20, minval=1) longLowerLength = input(10, minval=1) shortUpperLength = input(10, minval=1) shortLowerLength = input(20, minval=1) // Donchian indicator calculations longUpperValue = highest(high,longUpperLength) longLowerValue = lowest(low,longLowerLength) shortUpperValue = highest(high,shortUpperLength) shortLowerValue = lowest(low,shortLowerLength) // Plot Donchian Channels uLong = plot(showLongChannel ? longUpperValue : na, color=color.green, offset=1) lLong = plot(showLongChannel ? longLowerValue : na, color=color.green, offset=1) uShort = plot(showShortChannel ? shortUpperValue : na, color=color.red, offset=1) lShort = plot(showShortChannel ? shortLowerValue : na, color=color.red, offset=1) // Styling fill(uLong,lLong, color=color.green, transp=95, title="Long Arkaplan") fill(uShort,lShort, color=color.red, transp=95, title="Short Arkaplan") // Stop-loss value calculations atrMultiplier = 2.0 atrValue = atr(20) longStopValue = open - (atrMultiplier*atrValue) shortStopValue = open + (atrMultiplier*atrValue) // Plot stop-loss line plot(useAtrAsStopRule ? longStopValue : na, color=color.red, linewidth=2, offset=1) plot(useAtrAsStopRule ? shortStopValue : na, color=color.red, linewidth=2, offset=1) // Long and Short Position Rules if canEnterLong and na(longUpperValue) != true and na(longLowerValue) != true and window() strategy.entry("Long", true, stop=longUpperValue) strategy.exit("Long Exit", "Long", stop=useAtrAsStopRule ? max(longLowerValue,longStopValue) : longLowerValue) if canEnterShort and na(shortUpperValue) != true and na(shortLowerValue) != true and window() strategy.entry("Short", false, stop=shortLowerValue) strategy.exit("Short Exit", "Short", stop=useAtrAsStopRule ? min(shortUpperValue,shortStopValue) : shortUpperValue)
Simple Heiken Ashi Stop and Reverse Trading on Futures
https://www.tradingview.com/script/n0Ojkl7j-Simple-Heiken-Ashi-Stop-and-Reverse-Trading-on-Futures/
avnsiva
https://www.tradingview.com/u/avnsiva/
32
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ //@version=4 strategy(title = "Modified Smoothed Heiken Ashi", shorttitle="Modified Smoothed Heiken Ashi", overlay=true) t_id = tickerid(syminfo.prefix, syminfo.ticker) heikin_o = security(heikinashi(t_id), timeframe.period, open) heikin_h = security(heikinashi(t_id), timeframe.period, high) heikin_l = security(heikinashi(t_id), timeframe.period, low) heikin_c = security(heikinashi(t_id), timeframe.period, close) startYear = 2019 endYear = 2019 buy_entry = heikin_o[0] == heikin_l[0] sel_entry = heikin_o[0] == heikin_h[0] strategy.entry('buy', long=strategy.long, comment='buy', when=buy_entry and (time > timestamp(startYear, 01, 01, 00, 00) and time < timestamp(endYear, 12, 31, 00, 00))) strategy.entry('sell', long=strategy.short, comment='sell', when=sel_entry and (time > timestamp(startYear, 01, 01, 00, 00) and time < timestamp(endYear, 12, 31, 00, 00)))
TradingView Alerts to MT4 MT5 - Forex, indices, commodities
https://www.tradingview.com/script/BTSkg8IP-TradingView-Alerts-to-MT4-MT5-Forex-indices-commodities/
Peter_O
https://www.tradingview.com/u/Peter_O/
870
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© Peter_O //@version=4 strategy(title="TradingView Alerts to MT4 MT5 - Forex, indices, commodities, stocks, crypto", commission_type=strategy.commission.cash_per_contract, commission_value=0.00003, overlay=false, default_qty_value=20000, initial_capital=1000) // // This script was created for educational purposes only. // It is showing how to use Alerts-Straight-From-Strategies and // dynamic variables in TradingView alerts. // And how to auto-execute them in Forex, indices, commodities markets // // (This method will also work with stocks and crypto - anything your // broker is offering via their MT4/MT5 platform). TakeProfitLevel=input(400) TakePartialProfitLevel=input(150) // **** Entries logic **** { periodK = input(13, title="K", minval=1) periodD = input(3, title="D", minval=1) smoothK = input(4, title="Smooth", minval=1) k = sma(stoch(close, high, low, periodK), smoothK) d = sma(k, periodD) plot(k, title="%K", color=color.blue) plot(d, title="%D", color=color.orange) h0 = hline(80) h1 = hline(20) fill(h0, h1, color=color.purple, transp=75) GoLong=crossover(k,d) and k<80 and year>2009 GoShort=crossunder(k,d) and k>20 and year>2009 AlertTest=open>close or open<close or open==close // } End of entries logic // **** Pivot-points and stop-loss logic **** { piv_high = pivothigh(high,1,1) piv_low = pivotlow(low,1,1) var float stoploss_long=low var float stoploss_short=high pl=valuewhen(piv_low,piv_low,0) ph=valuewhen(piv_high,piv_high,0) if GoLong stoploss_long := low<pl ? low : pl if GoShort stoploss_short := high>ph ? high : ph // } End of Pivot-points and stop-loss logic // **** Trade counter and partial closing mechanism **** { var int trade_id=0 if GoLong or GoShort trade_id:=trade_id+1 TakePartialProfitLong = barssince(GoLong)<barssince(GoShort) and crossover(high,(valuewhen(GoLong,close,0)+TakePartialProfitLevel*syminfo.mintick)) TakePartialProfitShort = barssince(GoLong)>barssince(GoShort) and crossunder(low,(valuewhen(GoShort,close,0)-TakePartialProfitLevel*syminfo.mintick)) // } End of Trade counter and partial closing mechanism strategy.entry("Long", strategy.long, when=GoLong) strategy.exit("XPartLong", from_entry="Long", qty_percent=50, profit=TakePartialProfitLevel) strategy.exit("XLong", from_entry="Long", stop=stoploss_long, profit=TakeProfitLevel) strategy.entry("Short", strategy.short, when=GoShort) strategy.exit("XPartShort", from_entry="Short", qty_percent=50, profit=TakePartialProfitLevel) strategy.exit("XShort", from_entry="Short", stop=stoploss_short, profit=TakeProfitLevel) if GoLong alertsyntax_golong='long slprice=' + tostring(stoploss_long) + ' tradeid=' + tostring(trade_id) + ' tp=' + tostring(TakeProfitLevel) alert(message=alertsyntax_golong, freq=alert.freq_once_per_bar_close) if GoShort alertsyntax_goshort='short slprice=' + tostring(stoploss_short) + ' tradeid=' + tostring(trade_id) + ' tp=' + tostring(TakeProfitLevel) alert(message=alertsyntax_goshort, freq=alert.freq_once_per_bar_close) if TakePartialProfitLong alertsyntax_closepartlong='closepart tradeid=' + tostring(trade_id) + ' part=0.5' alert(message=alertsyntax_closepartlong, freq=alert.freq_once_per_bar_close) if TakePartialProfitShort alertsyntax_closepartshort='closepart tradeid=' + tostring(trade_id) + ' part=0.5' alert(message=alertsyntax_closepartshort, freq=alert.freq_once_per_bar_close)
T3MA_KC_7ye Strategy
https://www.tradingview.com/script/4KHgamqw/
Trader_7ye
https://www.tradingview.com/u/Trader_7ye/
105
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/ // Β© Trader_7ye //@version=4 strategy(title="Trader_7ye_ETH_30M_T3ma Strategy", shorttitle="Trader_7ye_ETH_30M_T3ma Strategy",max_bars_back=500,overlay=true,default_qty_type=strategy.percent_of_equity,default_qty_value=100,initial_capital=5000,currency=currency.USD) t3(src,len)=> xe1 = ema(src, len) xe2 = ema(xe1, len) xe3 = ema(xe2, len) xe4 = ema(xe3, len) xe5 = ema(xe4, len) xe6 = ema(xe5, len) b = 0.7 c1 = -b*b*b c2 = 3*b*b+3*b*b*b c3 = -6*b*b-3*b-3*b*b*b c4 = 1+3*b+b*b*b+3*b*b c1 * xe6 + c2 * xe5 + c3 * xe4 + c4 * xe3 Length = input(title="均线长度", type=input.integer, defval=24, minval=1) xPrice = input(title="均线源", type=input.source, defval=close) T3ma=t3(xPrice,Length) upCol = T3ma > T3ma[1] downCol = T3ma < T3ma[1] range= high - low rangema=t3(range,Length) upper = T3ma + rangema lower = T3ma - rangema myColor = upCol ? color.lime : downCol ? color.red : na plot(T3ma, color=myColor, title="T3均线") c = color.blue u = plot(upper, color=#0094FF, title="KCι€šι“δΈŠζ²Ώ") l = plot(lower, color=#0094FF, title="KCι€šι“δΈ‹ζ²Ώ") fill(u, l, color=#0094FF, transp=95, title="θƒŒζ™―") buySignal = upCol and ohlc4>upper sellSignal= downCol and ohlc4<lower //=======θΎ“ε‡Ί======= //ε€šη©Ίι’œθ‰²εˆ€ζ–­ direction=0 direction:=buySignal?1:sellSignal?-1:direction[1] macolor=direction==1?color.green:color.red //ε€šδΏ‘ε·ε€„η†δΈΊδΈ€δΈͺ俑号 alertlong = direction!=direction[1] and direction== 1 alertshort= direction!=direction[1] and direction==-1 bgcolor(alertshort ? color.red : alertlong?color.lime:na, transp=20) if (alertlong) strategy.entry("倚", strategy.long) if (alertshort) strategy.entry("η©Ί",strategy.short)
[DS]Entry_Exit_TRADE.V01-Strategy
https://www.tradingview.com/script/RO4rB2HF/
DalmarSantos
https://www.tradingview.com/u/DalmarSantos/
1,353
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/ // Β© DalmarSantos //@version=4 //Entry and Exit points to TRADE ==> Pontos de Entrada e Saida de TRADE //Functions in use ==> Funçáes em uso //(1) DEMA - Double Exponential Moving Average 08/17/34/72 ==> MΓ©dia MΓ³vel Exponencial Dupla //(2) ema() - Exponential Moving Averge 72/ochl4 ==> MΓ©dia MΓ³vel Exponencial //(3) plot() //(4) barcolor() //(5) cross() //(6) pivots() //(7) William R% Md //(8) Maximum and Minimum Value //(9) fill() //(10) macd() - Moving Average Convergence Divergence //(11) tsi() - Trading Strenght Indicator==> Índice de ForΓ§a Real (IFR) //(12) Buy and Sell TRADE Points //(13) Strategy Buy and Sell TRADE Points strategy("[DS]Entry_Exit_TRADE.V01-Strategy", overlay=true) //variable ==> variΓ‘veis return = input(title="Return Candels ?", type=input.integer, defval=190) //quantity of candles to analise ==> quantidade de candles para analise // //**************************** //Function==> Função | (1)DEMA //**************************** //Dema 08 e1 = ema(close,8) e2 = ema(e1,8) dema08 = 2 * e1 - e2 // //Dema 17 e1 := ema(close,17) e2 := ema(e1,17) dema17 = 2 * e1 - e2 // //Dema 34 e1 := ema(close,34) e2 := ema(e1,34) dema34 = 2 * e1 - e2 // //Dema 72 e1 := ema(close,72) e2 := ema(e1,72) dema72 = 2 * e1 - e2 // //****************************** //Function==> Função | (2) ema() //****************************** ema72 = ema(close,72) emaOhlc4=ema(ohlc4,8) // //****************************** //Function==> Função | (3)plot() //****************************** // ////Show the avareges ==> Apresenta as mΓ©dias //plot(dema17, title="DEMA 17", color=color.new(color.lime,0), linewidth=1, style=plot.style_line, transp=0, show_last=return) // Doble Exponential Moving Avarage 17 //plot(dema34, title="DEMA 34", color=color.new(color.black,0), linewidth=1, style=plot.style_line, transp=0, show_last=return) // Doble Exponential Moving Avarage 34 plot(dema72, title="DEMA 72", color=color.orange, linewidth=2, style=plot.style_line, transp=0, show_last=return) // Doble Exponential Moving Avarage 72 plot(emaOhlc4, title="EMA ohlc4", color=emaOhlc4>dema72 ? color.new(color.green,0) : color.new(color.red,0), linewidth=2, style=plot.style_line, transp=0, show_last=return) // Doble Exponential Moving Avarage 72 // //*********************************** //Function==> Função | (4) barcolor() //*********************************** //Show color TRADE bar if emaOhlc4>dema72 green (Buy) if not red (Red) ==> Mostra a cor da barra de TRADE se emaOhlc4>dema72 verde (Compra) se nΓ£o vermelha (Venda) barcolor(close>dema34 and close>dema72 or close>close[1] ? color.new(color.green,0) : color.new(color.red,0), show_last=return) // //******************************** //Function==> Função | (5) cross() //******************************** // Show the intersections crossing average on the graph ==> Apresenta no grΓ‘fico o local dos cruzamentos das mΓ©dias //UP ==> para CIMA plot(crossover(emaOhlc4,dema72) ? dema72 : na, title="Cross UP", color=color.green, transp=0, style=plot.style_circles, linewidth=5, show_last=return) //DOWM ==> para BAIXO plot(crossunder(emaOhlc4,dema72) ? dema72 : na, title="Cross DOWN", color=color.red, transp=50, style=plot.style_circles, linewidth=5, show_last=return) // //******************************** //Function==> Função | (6) pivot() //Reference: Pine Script Manual //******************************** _Pivots = input(title = "══════ Pivots ══════", type = input.bool, defval = false) leftBars = input(4) rightBars=input(4) pivotHigh = pivothigh(leftBars, rightBars) //pivot de alta plot(pivotHigh>ema72[rightBars] ? pivotHigh : na, title="Pivot High", style=plot.style_cross, linewidth=3, color= color.purple, transp=50, offset=-rightBars, show_last=return) pivotLow = pivotlow(leftBars, rightBars) //pivot de baixa plot(pivotLow<ema72[rightBars] ? pivotLow : na, title="Pivot Low", style=plot.style_cross, linewidth=3, color= color.blue, transp=50, offset=-rightBars, show_last=return) // //*************************************** //Function==> Função | (7) WILLIAM R% MOD //Reference: Pine Script Manual //*************************************** // Getting inputs _WilliamR = input(title = "══════ William R% Mod ══════", type = input.bool, defval = false) SOB_William = input(title="OverBought Area", type=input.integer, defval=-7) //OverBought area ==> Area de SobreCompra SOS_William = input(title="OverSold Area", type=input.integer, defval=-93) //OverSold area ==> Area de SobreVenda length_William = input(17, minval=1) //interval ==> intervalo highestHigh_William = highest(length_William) //maximum value ==> valor mΓ‘ximo highestLow_William = lowest(length_William) //minumum value ==> valor mΓ­nimo R_William = (highestHigh_William - close) / (highestHigh_William - highestLow_William) * -100 //Show the position ==> mostra a posição //plotshape(R_William > SOS_William ? na : high, text="+R%", title="+r(+)%R Up", location=location.belowbar, color=color.green, transp=30, style=shape.triangleup, size=size.tiny, show_last=return) //plotshape(R_William < SOB_William ? na : low, text="-R%", title="(-)%R DN", location=location.abovebar, color=color.red, transp=30, style=shape.triangledown, size=size.tiny, show_last=return) // // Show label with William %R value ==> Mostra a etiqueta com o valor do William %R // The color label red is when the value arrive on OverBought Area and green on OverSold Area, be careful with these areas ==> O rΓ³tulo de cor vermelha Γ© quando o valor chega na Γ‘rea de SobreCompra e verde na Γ‘rea de SobreVenda, cuidado com estas Γ‘reas // corTest=color.white colorText = color.white estilo = label.style_label_upper_left textW="" if R_William>SOB_William corTest := color.new(color.red,0) //vermelho escuro estilo := label.style_label_lower_left textW:="OB" if R_William>-30 and R_William<=SOB_William corTest := #f5948e //vermelho intermediΓ‘rio estilo := label.style_label_lower_left if R_William>-50 and R_William<=-30 corTest := #f5d5d3 //vermelho claro colorText := color.black if R_William>-70 and R_William<=-50 corTest := #e7f5d3 //verde claro colorText := color.black if R_William>=SOS_William and R_William<=-70 corTest := color.lime //verde intermediario estilo := label.style_label_upper_left colorText := color.black if R_William<SOS_William corTest := color.new(color.green,0) // verde escuro estilo := label.style_label_upper_left textW:="OS" // Make a label at the high of the current bar myLabel = label.new(x=bar_index, y=close, style= estilo, color=corTest, text=tostring(R_William,"#.#")+"% "+textW, textcolor=colorText, size=size.normal) // Get the label text labelText = label.get_text(id=myLabel) // Then set the label's text to a new string that // includes its current text label.set_text(id=myLabel, text=labelText) label.delete(myLabel[1]) // //************************************************** //Function==> Função | (8) MAXIMUM AND MINIMUM VALUE //Reference: Pine Script Manual //************************************************** //Maximum High and Minimum Low close position ==> Posição MΓ‘xima e Minima de fechamento ExtremoHigh=high+(highestHigh_William-high) ExtremoLow=low-(low-highestLow_William) plot(ExtremoHigh, color=color.new(color.red,70), style=plot.style_line, linewidth=1, show_last=return) plot(ExtremoLow, color=color.new(color.green,70), style=plot.style_line, linewidth=1, show_last=return) //Show the Extreme High and Low close position ==> Mostra a extrema posicao alta e baixa do fechamento lH1 = 0.0 lHInt = close lL1 = close lLInt = close Vr_LinhaH=0.0 Vr_LinhaL=0.0 Vr_LinhaC=0.0 if emaOhlc4<dema72 Vr_LinhaH := high+(highestHigh_William-high) lH1 := Vr_LinhaH>dema72 ? Vr_LinhaH : dema72 lHInt:=emaOhlc4<dema72 ? dema72 : emaOhlc4 lLInt := lHInt==emaOhlc4 ? dema72 : emaOhlc4 Vr_LinhaL:= low-(low-highestLow_William) lL1 := Vr_LinhaL>lLInt ? lLInt : Vr_LinhaL if emaOhlc4>dema72 Vr_LinhaH := high+(highestHigh_William-high) lH1 := Vr_LinhaH>dema72 ? Vr_LinhaH : dema72 lHInt:=dema72>emaOhlc4 ? dema72 : emaOhlc4 lLInt := lHInt==dema72 ? emaOhlc4 : dema72 Vr_LinhaL:= low-(low-highestLow_William) lL1 := Vr_LinhaL>lLInt ? lLInt : Vr_LinhaL // //******************************* //Function==> Função | (9) fill() //Reference: Pine Script Manual //******************************* //Show TRADE area in red (Sell) and green (Buy) ==> Mostra a Γ‘rea de trade em vermelho (Venda) e verde (Compra) Line1 = plot(emaOhlc4, title="Dema ohlc4", color=color.new(color.white,100), linewidth=1, transp=0, show_last=return) Line2 = plot(dema72, title="Dema 72", color=color.new(color.white,100), linewidth=1,transp=0, show_last=return) fill(Line1, Line2, color=emaOhlc4>dema72 ? color.new(color.green,90) : color.new(color.red,90), transp=70, show_last=return) //High area ==> Area de alta HighlH1 = plot(lH1, title="HighlH1", color=color.green, linewidth=1, transp=90, show_last=return, style=plot.style_linebr) HighlHInt = plot(lHInt, title="HighlHInt", color=color.green, linewidth=1, transp=100, show_last=return, style=plot.style_linebr) fill(HighlH1, HighlHInt, color=color.new(color.purple,90), transp=0, show_last=return) //Low area ==> Area de baixa LowlL1 = plot(lL1, title="LowlL1", color=color.red, linewidth=1, transp=90, show_last=return, style=plot.style_linebr) LowlLInt = plot(lLInt, title="LowlLInt", color=color.red, linewidth=1, transp=100, show_last=return, style=plot.style_linebr) fill(LowlL1, LowlLInt, color=color.new(color.blue,90), transp=0, show_last=return) // //*************************************************************************** //Function==> Função | (10) macd() - Moving Average Convergence Divergence //Reference: Pine Script Manual - adapted TradingView version - Dalmar Santos //*************************************************************************** // Getting inputs _Macd = input(title = "═════ Macd ══════════", type = input.bool, defval = false) fast_length_Macd = input(title="Fast Length", type=input.integer, defval=12) slow_length_Macd = input(title="Slow Length", type=input.integer, defval=26) src_Macd = input(title="Source", type=input.source, defval=close) signal_length_Macd = input(title="Signal Smoothing", type=input.integer, minval = 1, maxval = 50, defval = 9) // Calculating fast_ma_Macd = ema(src_Macd, fast_length_Macd) slow_ma_Macd = ema(src_Macd, slow_length_Macd) macd_Macd = fast_ma_Macd - slow_ma_Macd signal_Macd = ema(macd_Macd, signal_length_Macd) hist_Macd = macd_Macd - signal_Macd //cross Macd MacdUp = crossover(macd_Macd,signal_Macd) ? 1 : 0 MacdDown = crossunder (macd_Macd,signal_Macd) ? 1 : 0 plotshape(MacdUp, text="+Md", title="(+)MACD UP", location=location.belowbar, color=color.green, transp=30, style=shape.triangleup, size=size.tiny, show_last=return) plotshape(MacdDown, text="-Md", title="(-)MACD DN", location=location.abovebar, color=color.red, transp=30, style=shape.triangledown, size=size.tiny, show_last=return) // //***************************************************************************************** //Function==> Função | (11) tsi() - Trading Strenght Indicator ==> Indice de ForΓ§a do Trading //Reference: Pine Script Manual - adapted TradingView version - Dalmar Santos //***************************************************************************************** _Tsi = input(title = "═════ Tsi ══════════", type = input.bool, defval = false) long_tsi = input(title="Long Length", type=input.integer, defval=72) short_tsi = input(title="Short Length", type=input.integer, defval=17) signal_tsi = input(title="Signal Length", type=input.integer, defval=17) price_tsi = close double_smooth(src_tsi, long_tsi, short_tsi) => fist_smooth_tsi = ema(src_tsi, long_tsi) ema(fist_smooth_tsi, short_tsi) pc_tsi = change(price_tsi) double_smoothed_pc_tsi = double_smooth(pc_tsi, long_tsi, short_tsi) double_smoothed_abs_pc_tsi = double_smooth(abs(pc_tsi), long_tsi, short_tsi) tsi_value_tsi = 100 * (double_smoothed_pc_tsi / double_smoothed_abs_pc_tsi) //TSI signal ==> Signal do TSI TsiUp = crossover(tsi_value_tsi,ema(tsi_value_tsi, signal_tsi)) ? 1 : 0 TsiDown = crossunder(tsi_value_tsi,ema(tsi_value_tsi, signal_tsi)) ? 1 : 0 //Show the Position ==> Mostra a posicao plotshape(TsiUp==1 ? low : na, text="+Tsi", title="(+)TSI Up", location=location.belowbar, color=color.green, transp=30, style=shape.triangleup, size=size.tiny, show_last=return) plotshape(TsiDown==1 ? high : na, text="-Tsi", title="(-)TSI DN", location=location.abovebar, color=color.red, transp=30, style=shape.triangledown, size=size.tiny, show_last=return) // //*************************************************************************** //Function==> Função | (12) Buy and Sell TRADE Points //Reference: Pine Script Manual - adapted TradingView version - Dalmar Santos //*************************************************************************** //Cross Point ==> pontos de cruzamento crossUP=crossover(emaOhlc4,dema34) crossDN=crossunder(emaOhlc4,dema34) //Show de Buy and Sell points ==> mostra pontos de compra e venda tradeColor=crossUP ? color.red : crossDN ? color.green : na //line buy or sell ==> linha de compra ou venda plot(crossUP ? dema34 : crossDN ? dema34: na, color=tradeColor, style=plot.style_line, linewidth=4, editable=false, show_last=return) //Buy point ==> pontos de compra plotshape(crossUP ? dema34 : na, style=shape.labelup, location=location.absolute, text="Buy", transp=0, textcolor = color.white, color=color.green, editable=false, show_last=return) //Sell points ==> pontos de venda plotshape(crossDN ? dema34: na, style=shape.labeldown, location=location.absolute, text="Sell", transp=0, textcolor = color.white, color=color.red, editable=false, show_last=return) // //************************************************************ //Function==> Função | (13) Strategy Buy and Sell TRADE Points //Reference: Pine Script Manual - Dalmar Santos //************************************************************ //Start backtest year, month, day, hour, minute, second ==> Inicio do backtest ano, mΓͺs, dia, hora, minuto, segundo start = timestamp(2021,01,01,1,00,00) //***************** //BUY ==> COMPRA //***************** if time>= start if crossUP strategy.close("Short", comment="Close Sell") strategy.entry("Long", strategy.long, 1, comment="Open Buy") //***************** //SELL ==> Venda //***************** if crossDN strategy.close("Long", comment="Close Buy") strategy.entry("Short", strategy.short, 1, comment="Open Sell")
Combined EMA & MA crossovers [CDI]
https://www.tradingview.com/script/0BxZRxIS/
JMLSlop
https://www.tradingview.com/u/JMLSlop/
91
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/ // Β© JMLSlop //@version=4 src = close strategy("Crossover moving averages", shorttitle="Cross MA-EMA", overlay=true, calc_on_order_fills=false) // first fast EMA len = input(8, "Length", type=input.integer, minval=1) doma1 = input(true, title="EMA") out1 = ema(src, len) //Second fast EMA len2 = input(21, minval=1, title="Length") doma2 = input(true, title="EMA") out2 = ema(src, len2) //First slow MA len3 = input(50, minval=1, title="Length") doma3 = input(true, title="SMA") out3 = sma(src, len3) //Second slow MA len4 = input(200, minval=1, title="Length") doma4 = input(true, title="SMA") out4 = sma(src, len4) // Profit profit = input(8, "Profit/lost %", type=input.float, minval=1) * 0.01 plot(doma1 and out1 ? out1: na, color=color.blue, linewidth=1, title="1st EMA") plot(doma2 and out2 ? out2: na, color=color.red, linewidth=1, title="2nd EMA") plot(doma3 and out3 ? out3: na, color=color.green, linewidth=2, title="1st MA") plot(doma4 and out4 ? out4: na, color=color.orange, linewidth=3, title="2nd MA") // Orders config takeProfitPrice = (strategy.position_size > 0) ? strategy.position_avg_price + open*profit : (strategy.position_size < 0) ? strategy.position_avg_price - (open*profit) : na longStopPrice = strategy.position_avg_price * (1 - profit) shortStopPrice = strategy.position_avg_price * (1 + profit) longCondition2 = (out2>out3 and (crossover(out1, out4) or crossover(out1[1], out4[1]) or crossover(out1[2], out4[2]) or (crossover(out1[3], out4[3]))) or (out2>out3 and (crossover(out1, out3) or crossover(out1[1], out3[1]) or crossover(out1[2], out3[2]) or crossover(out1[3], out3[3])))) if (longCondition2) strategy.entry("Enter L", strategy.long) shortCondition2 = (out2<out3 and (crossunder(out1, out4) or crossunder(out1[1], out4[1]) or crossunder(out1[2], out4[2]) or crossunder(out1[3], out4[3]))) or (out2<out3 and (crossunder(out1, out3) or crossunder(out1[1], out3[1]) or crossunder(out1[2], out3[2]) or crossunder(out1[3], out3[3]))) if (shortCondition2) strategy.entry("Enter S", strategy.short) if (strategy.position_size > 0) strategy.exit("Exit L", limit=takeProfitPrice, stop=longStopPrice) if (strategy.position_size < 0) strategy.exit("Exit S", limit=takeProfitPrice, stop=shortStopPrice)
Buy and hold calculator
https://www.tradingview.com/script/67yjZSq2-Buy-and-hold-calculator/
SoftKill21
https://www.tradingview.com/u/SoftKill21/
123
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/ // Β© SoftKill21 //@version=4 strategy(title="Buy and hold calculator", overlay=true, initial_capital = 1, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent ) fromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31) fromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12) fromYear = input(defval = 2000, title = "From Year", minval = 1970) //monday and session // To Date Inputs toDay = input(defval = 31, title = "To Day", minval = 1, maxval = 31) toMonth = input(defval = 12, title = "To Month", minval = 1, maxval = 12) toYear = input(defval = 2020, title = "To Year", minval = 1970) startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00) finishDate = timestamp(toYear, toMonth, toDay, 00, 00) time_cond = time >= startDate and time <= finishDate strategy.entry("long",1,when=time_cond) strategy.close("long",when= not time_cond)
Volatility Bands Reversal Strategy [Long Only]
https://www.tradingview.com/script/uGEv5oZb-Volatility-Bands-Reversal-Strategy-Long-Only/
ediks123
https://www.tradingview.com/u/ediks123/
102
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/ // Β© ediks123 //strategy logic has been borrowed from ceyhun and tweaked the settings for back testing //@version=4 //SPY 4 hrs settings 8, 13 , 3.33 , 0.9 on 4 hrs chart //QQQ above settings is good , but 13, 13 has less number of bars //QQQ 4 hrs settings 13, 13 , 3.33 , 0.9 on 4 hrs chart strategy(title="Volatility Bands Reversal Strategy", shorttitle="VolatilityBandReversal" , overlay=true, pyramiding=2, default_qty_type=strategy.percent_of_equity, default_qty_value=20, initial_capital=10000, currency=currency.USD) //default_qty_value=10, default_qty_type=strategy.fixed, av = input(8, title="Band Average") vp = input(13, title="Volatility Period") df = input(3.33,title="Deviation Factor",minval=0.1) lba = input(0.9,title="Lower Band Adjustment",minval=0.1) riskCapital = input(title="Risk % of capital", defval=10, minval=1) stopLoss=input(6,title="Stop Loss",minval=1) exitOn=input(title="Exit on", defval="touch_upperband", options=["Sell_Signal", "touch_upperband"]) src = hlc3 typical = src >= src[1] ? src - low[1] : src[1] - low deviation = sum( typical , vp )/ vp * df devHigh = ema(deviation, av) devLow = lba * devHigh medianAvg = ema(src, av) emaMediaAvg=ema(medianAvg, av) upperBandVal= emaMediaAvg + devHigh lowerbandVal= emaMediaAvg - devLow MidLineVal=sma(medianAvg, av) UpperBand = plot ( upperBandVal, color=#EE82EE, linewidth=2, title="UpperBand") LowerBand = plot ( lowerbandVal , color=#EE82EE, linewidth=2, title="LowerBand") MidLine = plot (MidLineVal, color=color.blue, linewidth=2, title="MidLine") buyLine = plot ( (lowerbandVal + MidLineVal )/2 , color=color.blue, title="BuyLine") up=ema(medianAvg, av) + devHigh down=ema(medianAvg, av) - devLow ema50=ema(hlc3,50) plot ( ema50, color=color.orange, linewidth=2, title="ema 50") //outer deviation //deviation1 = sum( typical , vp )/ vp * 4 //devHigh1 = ema(deviation, av) //devLow1 = lba * devHigh //medianAvg1 = ema(src, av) //UpperBand1 = plot (emaMediaAvg + devHigh1, color=color.red, linewidth=3, title="UpperBand1") //LowerBand1 = plot (emaMediaAvg - devLow1, color=color.red, linewidth=3, title="LowerBand1") // ///Entry Rules //1)First candle close below the Lower Band of the volatility Band //2)Second candle close above the lower band //3)Third Candle closes above previous candle Buy = close[2] < down[2] and close[1]>down[1] and close>close[1] //plotshape(Buy,color=color.blue,style=shape.arrowup,location=location.belowbar, text="Buy") //barcolor(close[2] < down[2] and close[1]>down[1] and close>close[1] ? color.blue :na ) //bgcolor(close[2] < down[2] and close[1]>down[1] and close>close[1] ? color.green :na ) ///Exit Rules //1)One can have a static stops initially followed by an trailing stop based on the risk the people are willing to take //2)One can exit with human based decisions or predefined target exits. Choice of deciding the stop loss and profit targets are left to the readers. Sell = close[2] > up[2] and close[1]<up[1] and close<close[1] //plotshape(Sell,color=color.red,style=shape.arrowup,text="Sell") barcolor(close[2] > up[2] and close[1]<up[1] and close<close[1] ? color.yellow :na ) bgcolor(close[2] > up[2] and close[1]<up[1] and close<close[1] ? color.red :na ) //Buyer = crossover(close,Buy) //Seller = crossunder(close,Sell) //alertcondition(Buyer, title="Buy Signal", message="Buy") //alertcondition(Seller, title="Sell Signal", message="Sell") //Entry-- //Echeck how many units can be purchased based on risk manage ment and stop loss qty1 = (strategy.equity * riskCapital / 100 ) / (close*stopLoss/100) //check if cash is sufficient to buy qty1 , if capital not available use the available capital only qty1:= (qty1 * close >= strategy.equity ) ? (strategy.equity / close) : qty1 strategy.entry(id="vbLE", long=true, qty=qty1, when=Buy) bgcolor(strategy.position_size>=1 ? color.blue : na) // stop loss exit stopLossVal = strategy.position_size>=1 ? strategy.position_avg_price * ( 1 - (stopLoss/100) ) : 0.00 //draw initil stop loss plot(strategy.position_size>=1 ? stopLossVal : na, color = color.purple , style=plot.style_linebr, linewidth = 2, title = "stop loss") //, trackprice=true) strategy.close(id="vbLE", comment="SL exit Loss is "+tostring(close - strategy.position_avg_price, "###.##") , when=abs(strategy.position_size)>=1 and close < stopLossVal ) //close on Sell_Signal strategy.close(id="vbLE", comment="Profit is : "+tostring(close - strategy.position_avg_price, "###.##") , when=strategy.position_size>=1 and exitOn=="Sell_Signal" and Sell) //close on touch_upperband strategy.close(id="vbLE", comment="Profit is : "+tostring(close - strategy.position_avg_price, "###.##") , when=strategy.position_size>=1 and exitOn=="touch_upperband" and (crossover(close, up) or crossover(high, up)))
Strategy- Double Decker RSI
https://www.tradingview.com/script/9K6jUWR1-Strategy-Double-Decker-RSI/
Ankit_Quant
https://www.tradingview.com/u/Ankit_Quant/
235
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/ // Β© Ankit_Quant //@version=4 // ******************************************************************************************************** // This was coded live during webinar on Backtesting in Tradingview // That was held on 16-Jan-21 // Aim of this strategy is to code a Double Decker RSI Strategy - Rules of Strategy are given in Description // ********************************************************************************************************* // Identifier of strategy or an indicator (study()) strategy(title="Strategy- Double Decker RSI",shorttitle='Strategy - Double Decker RSI',overlay=true,initial_capital=250000) // ******************** // INPUTS // ******************** // RSI Lookback Periods slowRSI=input(defval=14,title='Slow RSI Period',type=input.integer) fastRSI=input(defval=5,title='Fast RSI Period',type=input.integer) // Time Period Backtesting Input start_year=input(defval=2000,title='Backtest Start Year',type=input.integer) end_year=input(defval=2021,title='Backtest End Year',type=input.integer) //Specific Years to Test Starategy timeFilter=(year>=start_year and year<=end_year) // Trade Conditions and signals long = rsi(close,fastRSI)>70 and rsi(close,slowRSI)>50 short = rsi(close,fastRSI)<40 and rsi(close,slowRSI)<50 long_exit=rsi(close,fastRSI)<55 short_exit=rsi(close,fastRSI)>45 //positionSize - 1 Unit (also default setting) positionSize=1 // Trade Firing - Entries and Exits if(timeFilter) if(long and strategy.position_size<=0) strategy.entry(id='Long',long=strategy.long,qty=positionSize) if(short and strategy.position_size>=0) strategy.entry(id="Short",long=strategy.short,qty=positionSize) if(long_exit and strategy.position_size>0) strategy.close_all(comment='Ex') if(short_exit and strategy.position_size<0) strategy.close_all(comment='Ex') // Plot on Charts the Buy Sell Labels plotshape(strategy.position_size<1 and long,style=shape.labelup,location=location.belowbar,color=color.green,size=size.tiny,text='Long',textcolor=color.white) plotshape(strategy.position_size>-1 and short,style=shape.labeldown,location=location.abovebar,color=color.red,size=size.tiny,text='Short',textcolor=color.white) plotshape(strategy.position_size<0 and short_exit?1:0,style=shape.labelup,location=location.belowbar,color=color.maroon,size=size.tiny,text='ExShort',textcolor=color.white) plotshape(strategy.position_size>0 and long_exit?1:0,style=shape.labeldown,location=location.abovebar,color=color.olive,size=size.tiny,text='ExLong',textcolor=color.white)
Crypto Long only Strategy 3h+ timeframe
https://www.tradingview.com/script/jA129J1f-Crypto-Long-only-Strategy-3h-timeframe/
SoftKill21
https://www.tradingview.com/u/SoftKill21/
112
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/ // Β© SoftKill21 //@version=4 strategy("My Script", initial_capital=1000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent , commission_value=0.1 ) var candela = 0.0 candela := (high+low+open+close)/4 long = candela > candela[1] and candela[1] > candela[2] and candela[2] > candela[3] and candela[3] > candela[4] and candela[4] > candela[5] short = candela< candela[1] and candela[1] < candela[2] and candela[2] < candela[3] and candela[3] < candela[4] //and candela[4] < candela[5] plot(candela, color=long? color.green : short? color.red : color.white ,linewidth=4) strategy.entry("long",1,when=long) //strategy.entry('short',0,when=short) strategy.close("long", when = short) risk= input(25) strategy.risk.max_intraday_loss(risk, strategy.percent_of_equity) //strategy.close("short", when = not long or short)
Momentum Strategy (BTC/USDT; 30m) - STOCH RSI (with source code)
https://www.tradingview.com/script/79Tn4cQY-Momentum-Strategy-BTC-USDT-30m-STOCH-RSI-with-source-code/
Drun30
https://www.tradingview.com/u/Drun30/
576
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/ // Β© Drun30 (Federico Magnani) //@version=4 //STRATEGIA PRINCIPALE /////////////////// CHANGE THESE VARIABLES FOR TV-HUB /////////////////// var pair = "BTCUSDT" //metti il valore associato a "pair" nel JSON generato da TVHUB var orderSizePercent = 70 // β†’ % di capitale investita per ogni trade, la percentuale Γ¨ da riferirsi alla PERCENTUALE DI CRIPTOVALUTA PRESENTE NEL PORTAFOGLIO SPOT (se ho messo la coppia "BTCUSDT", ho 1200 USDT liberi nel portafoglio e lascio "orderSizePercent"=50, mi eseguirΓ  un ordine di acquisto spendendo 600 USDT (=1200*0.5) per comprare BTC (in caso di ordine long)) var stopLossPercent_Long = 10 //Γ¨ lo stop loss (percentuale) per le posizioni Long, metti il valore associato a "stopLossPercent" nel JSON generato da TVHUB per le posizioni long var takeProfitPercent_Long = 8 //Γ¨ il take profit (percentuale) per le posizioni Long, metti il valore associato a "takeProfitPercent" nel JSON generato da TVHUB per le posizioni long var stopLossPercent_Short = 20 //Γ¨ lo stop loss (percentuale) per le posizioni Short, metti il valore associato a "stopLossPercent" nel JSON generato da TVHUB per le posizioni short var takeProfitPercent_Short = 35 //Γ¨ il take profit (percentuale) per le posizioni Short, metti il valore associato a "takeProfitPercent" nel JSON generato da TVHUB per le posizioni short var tokenTVHUB = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" //Γ¨ il token associato al tuo account su TV-HUB, metti il valore associato a "token" nel JSON generato da TVHUB var exchange = "Binance-Futures-Testnet" //metti il valore associato a "exchange" nel JSON generato da TVHUB //Excgange possibili: Bitmex, Bitmex-Testnet, Binance, Binance-Futures, Binance-Futures-Testnet, Bybit, Bybit-Testnet var leverage = 1 //lascia 1 se non stai usando binance futures o bitmex commissionsPercent = 0.1 //commissioni dell'exchange (0.1 = 0.1%, sono le commissioni di Binance) //////////////////////////////////////////////////////////////////////// /////////////////// QUICK CHANGE VARIABLES OF THE STRATEGY /////////////////// wantToUseGambleSizing=true //se "true" aumenterΓ  la size del trade successivo a quello perdente per il valore percentuale associato a "deltasize" (se ho fallito un trade con il 50% della size, se wantToUseGambleSizing=true e deltaSize=25, il trade successivo impiegherΓ  il 75% della valuta in portafoglio) var deltaSize = 25 // β†’ delta% di capitale investito se trade precedente Γ¨ stato in perdita (cumulabile: se parto con il 50% del capitale ed il trade va in perdita, il trade successivo userΓ  il 75% (=50+25), se fallisce anche quello userΓ  il 100%(=50+25+25) (ammesso che sia stato raggiunto il valore "sizeLimite")) var sizeLimite = 100 //il trade non impiegherΓ  mai una percentuale superiore a questa nei trade successivi a quello andato in perdita capitaleIniziale=1000 var sizeordineInit= orderSizePercent var sizeordine = sizeordineInit //Parametri ottimali 30 min usiShort=true usiLong=true ipercomprato=85.29 ipervenduto=30.6 // ////////////////////////////////////////////////////////////////////////////// strategy("Momentum Strategy (V7.B.4)", initial_capital=capitaleIniziale, currency="USD", default_qty_type=strategy.percent_of_equity, commission_type=strategy.commission.percent, commission_value=commissionsPercent, slippage = 5, default_qty_value=sizeordineInit, overlay=false, pyramiding=0) backtest = input(title="------------------------Backtest Period------------------------", defval = false) start = timestamp(input(2020, "start year"), input(1, "start month"), input(1, "start day"), 00, 00) end = timestamp(input(0, "end year"), input(0, "end month"), input(0, "end day"), 00, 00) siamoindata=time > start?true:false if end > 0 siamoindata:=time > start and time <= end?true:false basicParameters = input(title="------------------------Basic Parameters------------------------", defval = false) smoothK = input(3, minval=1) smoothD = input(6, minval=1) lengthRSI = input(12, minval=1) src = input(close, title="RSI Source") rsi1 = rsi(src, lengthRSI) lengthStoch = input(12, minval=1) k = ema(stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK) d = ema(k, smoothD) altezzaipercomprato= input(ipercomprato, title="Overbought Height", minval=1, type=input.float) altezzaipervenduto= input(ipervenduto, title="Oversold Height", minval=1,type=input.float) BarsDelay = input(6,title="Bars delay",minval=0) GambleSizing = input(wantToUseGambleSizing, title = "Gamble Sizing?",type=input.bool) gambleAdd = input(deltaSize,title="Gamble Add (%)",minval=0,type=input.integer) gambleLimit = input(sizeLimite,title="Gamble MAX (%)",minval=0,type=input.integer) if GambleSizing and strategy.closedtrades[0]>strategy.closedtrades[1] if strategy.losstrades[0]>strategy.losstrades[1] and sizeordine<gambleLimit sizeordine:=sizeordine+gambleAdd if strategy.wintrades[0]>strategy.wintrades[1] sizeordine:=sizeordineInit periodomediamobile_fast = input(1, title="Fast EMA length",minval=1) periodomediamobile_slow = input(60, title="Slow EMA length",minval=1) plot(k, color=color.blue) plot(d, color=color.orange) h0 = hline(altezzaipercomprato) h1 = hline(altezzaipervenduto) fill(h0, h1, color=color.purple, transp=80) // n=input(Vicinanzadalcentro,title="Vicinanza dal centro",minval=0) //sarebbe il livello di D in cui si acquista o si vende, maggiore Γ¨ la vicinanza maggiore sarΓ  la frequenza dei trades, SE 0 Γ¨ DISABILITATO // siamoinipervenduto= d<=altezzaipervenduto and d<=d[n] and d>d[1]?true:false //and d<d[3] and d>d[1] // siamoinipercomprato= d>=altezzaipercomprato and d>=d[n] and d<d[1]?true:false //and d>d[3] and d<d[1] goldencross = crossover(k,d) deathcross = crossunder(k,d) // METTI VARIABILE IN CUI AVVIENE CROSSOVER O CROSSUNDER valoreoro = valuewhen(goldencross,d,0) valoremorte = valuewhen(deathcross,d,0) siamoinipervenduto = goldencross and valoreoro<=altezzaipervenduto?true:false//d<=altezzaipervenduto?true:false siamoinipercomprato = deathcross and valoremorte>=altezzaipercomprato?true:false//d>=altezzaipercomprato?true:false long_separator = input(title="------------------------LONG------------------------", defval = usiLong) sl_long_inp = input(stopLossPercent_Long, title="Stop Loss LONG %", type=input.float,step=0.1) tp_long_inp = input(takeProfitPercent_Long, title="Take Profit LONG %",type=input.float,step=0.1) stop_level_long = strategy.position_avg_price * (1 - (sl_long_inp/100)) //strategy.position_avg_price corrisponde al prezzo con cui si Γ¨ aperta la posizione take_level_long = strategy.position_avg_price * (1 + (tp_long_inp/100)) //BINANCE JSON_long = '{"pair":"'+pair+'","isBuy":true,"isSell":false,"isMarket":true,"isLimit":false,"isClose":false,"price":"9497.59","unitsPercent":"'+tostring(sizeordine)+'","unitsType":"percentBalance","stopLoss":"8545.44","stopLossPercent":"-'+tostring(sl_long_inp)+'","stopLossType":"percent","marginType":"ISOLATED","targets":[{"idx":1,"price":"10257.32","amount":"'+tostring(100-commissionsPercent)+'","takeProfitPercent":"'+tostring(tp_long_inp)+'"}],"targetType":"percent","leverage":"'+tostring(leverage)+'","closeCurrentPosition":true,"token":"'+tokenTVHUB+'","exchange":"'+exchange+'"}' JSON_chiusura = '{"pair":"'+pair+'","isBuy":false,"isSell":false,"isMarket":true,"isLimit":false,"isClose":true,"price":"9497.36","units":"0.01","unitsPercent":"'+tostring(sizeordine)+'","unitsType":"percentBalance","stopLoss":"8545.44","stopLossPercent":"-'+tostring(sl_long_inp)+'","stopLossType":"percent","marginType":"ISOLATED","targets":[{"idx":1,"price":"10257.32","amount":"'+tostring(100-commissionsPercent)+'","takeProfitPercent":"'+tostring(tp_long_inp)+'"}],"targetType":"percent","leverage":"'+tostring(leverage)+'","closeCurrentPosition":true,"token":"'+tokenTVHUB+'","exchange":"'+exchange+'"}' webhookLong = JSON_long webhookClose= JSON_chiusura trendFilterL = input(title="TREND FILTER LONG?", defval = true) EMAfast=ema(close,periodomediamobile_fast) EMAslow=ema(close,periodomediamobile_slow) siamoinuptrend_ema=EMAfast>EMAslow?true:false //close>=EMAfast and EMAfast>EMAslow siamoinuptrend = siamoinuptrend_ema // CondizioneAperturaLong = siamoinipervenduto and siamoindata // and siamoinuptrend CondizioneAperturaLong = siamoinipervenduto and siamoindata and long_separator if trendFilterL CondizioneAperturaLong := siamoinipervenduto and siamoindata and long_separator and siamoinuptrend CondizioneChiusuraLong = siamoinipercomprato and siamoindata possiamoAprireLong=0 if trendFilterL and siamoinuptrend possiamoAprireLong:=5 plot(possiamoAprireLong,color=color.green) sonPassateLeBarreG = barssince(CondizioneAperturaLong) == BarsDelay?true:false sonPassateLeBarreD = barssince(CondizioneChiusuraLong) == BarsDelay?true:false haiUnLongAncoraAperto = false haiUnLongAncoraAperto := strategy.position_size>0?true:false // Se l'ultimo valore della serie "CondizioneAperturaLong" Γ¨ TRUE, allora hai un long ancora aperto // Se l'ultimo valore della serie "CondizioneAperturaLong" Γ¨ FALSE, allora: // Se l'ultimo valore della serie "CondizioneChiusuraLong" Γ¨ TRUE, allora NON hai un long ancora aperto // Se l'ultimo valore della serie "CondizioneChiusuraLong" Γ¨ FALSE, allora restituisce l'ultimo valore della serie "haiUnLongAncoraAperto" haiUnLongAncoraAperto_float = if(haiUnLongAncoraAperto==true) 10 else 0 plot(haiUnLongAncoraAperto_float,color=color.red) //FInchΓ© la linea rossa si trova a livello "1" allora c'Γ¨ un ordine long in corso quantita = (sizeordine/100*(capitaleIniziale+strategy.netprofit))/valuewhen(haiUnLongAncoraAperto==false and CondizioneAperturaLong,close,0) plot(sizeordine,color=color.purple, linewidth=3) if strategy.position_size<=0 and CondizioneAperturaLong //and sonPassateLeBarreG and haiUnLongAncoraAperto==false strategy.opentrades==0 strategy.entry("Vamonos",strategy.long, alert_message=webhookLong, comment="OPEN LONG", qty=quantita) if strategy.position_size>0 //and sonPassateLeBarreD // and CondizioneChiusuraLong if siamoinuptrend == true and sonPassateLeBarreD strategy.close("Vamonos", alert_message=webhookClose, comment="CLOSE LONG") else if siamoinuptrend == false and CondizioneChiusuraLong strategy.close("Vamonos", alert_message=webhookClose, comment="CLOSE LONG") if strategy.position_size>0 and siamoindata strategy.exit("Vamonos", stop=stop_level_long, limit=take_level_long, alert_message=webhookClose, comment="CLOSE LONG (LIMIT/STOP)") short_separator = input(title="------------------------SHORT------------------------", defval = usiShort) sl_short_inp = input(stopLossPercent_Short, title="Stop Loss SHORT %",type=input.float,step=0.1) tp_short_inp = input(takeProfitPercent_Short, title="Take Profit SHORT %",type=input.float,step=0.1) stop_level_short = strategy.position_avg_price * (1 + (sl_short_inp/100)) take_level_short= strategy.position_avg_price * (1 - (tp_short_inp/100)) // BINANCE JSON_short = '{"pair":"'+pair+'","isBuy":false,"isSell":true,"isMarket":true,"isLimit":false,"isClose":false,"price":"9147.62","units":"'+tostring(sizeordine)+'","unitsPercent":"'+tostring(sizeordine)+'","unitsType":"percentBalance","stopLoss":"10062.41","stopLossPercent":"-'+tostring(sl_short_inp)+'","stopLossType":"percent","marginType":"ISOLATED","targets":[{"idx":1,"price":"7775.50","amount":"'+tostring(100-commissionsPercent)+'","takeProfitPercent":"'+tostring(tp_short_inp)+'"}],"targetType":"percent","leverage":"'+tostring(leverage)+'","closeCurrentPosition":true,"token":"'+tokenTVHUB+'","exchange":"'+exchange+'"}' webhookShort = JSON_short trendFilterS = input(title="TREND FILTER SHORT?", defval = true) siamoindowntrend_ema=EMAfast<EMAslow?true:false //close<=EMAfast and EMAfast<EMAslow siamoindowntrend=siamoindowntrend_ema CondizioneAperturaShort = short_separator and siamoinipercomprato and siamoindata if trendFilterS CondizioneAperturaShort:=short_separator and siamoinipercomprato and siamoindata and siamoindowntrend CondizioneChiusuraShort = siamoinipervenduto and siamoindata sonPassateLeBarreGs = barssince(CondizioneAperturaShort) == BarsDelay?true:false sonPassateLeBarreDs = barssince(CondizioneChiusuraShort) == BarsDelay?true:false haiUnoShortAncoraAperto = false haiUnoShortAncoraAperto := strategy.position_size<0?true:false haiUnoShortAncoraAperto_float = if(haiUnoShortAncoraAperto==true) 15 else 0 plot(haiUnoShortAncoraAperto_float,color=color.purple) //FInchΓ© la linea viola si trova a livello "2" allora c'Γ¨ un ordine short in corso if CondizioneAperturaShort and strategy.position_size>=0 //and haiUnoShortAncoraAperto==false strategy.entry("Andale",strategy.short,alert_message=webhookShort, comment="OPEN SHORT") if strategy.position_size<0 //and sonPassateLeBarreD // and CondizioneChiusuraLong if siamoindowntrend == true and sonPassateLeBarreDs strategy.close("Andale",alert_message=webhookClose, comment="CLOSE SHORT") else if siamoindowntrend == false and CondizioneChiusuraShort strategy.close("Andale",alert_message=webhookClose, comment="CLOSE SHORT") if strategy.position_size<0 and siamoindata strategy.exit("Andale", stop=stop_level_short, limit=take_level_short, alert_message=webhookClose, comment="CLOSE SHORT (LIMIT/STOP)")
Phoenix085-Strategies==>MTF - Average True Range + MovAvg
https://www.tradingview.com/script/hXk5s0ec-Phoenix085-Strategies-MTF-Average-True-Range-MovAvg/
Phoenix085
https://www.tradingview.com/u/Phoenix085/
120
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/ // Β© Phoenix085 //@version=4 strategy("Phoenix085-Strategy_ATR+MovAvg", shorttitle="Strategy_ATR+MovAvg", overlay=true) // // ######################>>>>>>>>>>>>Inputs<<<<<<<<<<<######################### // // ######################>>>>>>>>>>>>Strategy Inputs<<<<<<<<<<<######################### TakeProfitPercent = input(50, title="Take Profit %", type=input.float, step=.25) StopLossPercent = input(5, title="Stop Loss %", type=input.float, step=.25) ProfitTarget = (close * (TakeProfitPercent / 100)) / syminfo.mintick LossTarget = (close * (StopLossPercent / 100)) / syminfo.mintick len_S = input(title="Shorter MA Length", defval=8, minval=1) len_L = input(title="Longer MA Length", defval=38, minval=1) TF = input(defval="", title="Session TF for calc only", type=input.session,options=[""]) TF_ = "1" if TF == "3" TF_ == "1" else if TF == "5" TF_ == "3" else if TF == "15" TF_ == "5" else if TF == "30" TF_ == "15" else if TF == "1H" TF_ == "30" else if TF == "2H" TF_ == "1H" else if TF == "4H" TF_ == "3H" else if TF == "1D" TF_ == "4H" else if TF == "1W" TF_ == "1H" else if TF == "1M" TF_ == "1W" else if TF =="3H" TF_ == "2H" Src = security(syminfo.tickerid, TF, close[1], barmerge.lookahead_on) Src_ = security(syminfo.tickerid, TF_, close, barmerge.lookahead_off) // ######################>>>>>>>>>>>>ATR Inputs<<<<<<<<<<<######################### length = input(title="ATR Length", defval=4, minval=1) smoothing = input(title="ATR Smoothing", defval="RMA", options=["RMA", "SMA", "EMA", "WMA"]) // //######################>>>>>>>>>>>>Custom Functions Declarations<<<<<<<<<<<######################### // ######################>>>>>>>>>>>>ATR<<<<<<<<<<<######################### ma_function(source, length) => if smoothing == "RMA" rma(Src, length) else if smoothing == "SMA" sma(Src, length) else if smoothing == "EMA" ema(Src, length) else wma(Src, length) ATR=ma_function(tr(true), length) // //######################>>>>>>>>>>>>Conditions<<<<<<<<<<<######################### ATR_Rise = ATR>ATR[1] and ATR[1]<ATR[2] and ATR[2]<ATR[3] longCondition = crossover(sma(Src_, len_S), sma(Src_, len_L)) and sma(Src_, len_L) < sma(Src_, len_S) and (sma(Src_, len_S) < Src_[1]) shortCondition = crossunder(sma(Src_, len_S), sma(Src_, len_L)) and sma(Src_, len_L) > sma(Src_, len_S) plot(sma(Src_, len_S), color=color.lime, transp=90) col = longCondition ? color.lime : shortCondition ? color.red : color.gray plot(sma(Src_, len_L),color=col,linewidth=2) bool IsABuy = longCondition bool IsASell = shortCondition // // ######################>>>>>>>>>>>>Strategy<<<<<<<<<<<######################### testStartYear = input(2015, "Backtest Start Year", minval=1980) testStartMonth = input(1, "Backtest Start Month", minval=1, maxval=12) testStartDay = input(1, "Backtest Start Day", minval=1, maxval=31) testPeriodStart = timestamp(testStartYear, testStartMonth, testStartDay, 0, 0) testStopYear = input(9999, "Backtest Stop Year", minval=1980) testStopMonth = input(12, "Backtest Stop Month", minval=1, maxval=12) testStopDay = input(31, "Backtest Stop Day", minval=1, maxval=31) testPeriodStop = timestamp(testStopYear, testStopMonth, testStopDay, 0, 0) testPeriod() => time >= testPeriodStart and time <= testPeriodStop ? true : false inDateRange = time >= testPeriodStart and time <= testPeriodStop bgcolor(inDateRange ? color.green : na, 90) // //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<// // // ######################>>>>>>LongEntries<<<<<<<######################### if inDateRange and ATR_Rise and IsABuy strategy.entry("longCondition",true,when = longCondition) strategy.close("shortCondition") strategy.exit("Take Profit or Stop Loss", "longCondition",trail_points = close * 0.05 / syminfo.mintick ,trail_offset = close * 0.05 / syminfo.mintick, loss = LossTarget) // strategy.risk.max_drawdown(10, strategy.percent_of_equity) // // ######################>>>>>>ShortEntries<<<<<<<######################### if inDateRange and ATR_Rise and IsASell strategy.entry("shortCondition",false,when = shortCondition) strategy.exit("Take Profit or Stop Loss", "shortCondition",trail_points = close * 0.05 / syminfo.mintick ,trail_offset = close * 0.05 / syminfo.mintick, loss = LossTarget) strategy.close("longCondition")
Ultimate Oscillator [Long] Strategy
https://www.tradingview.com/script/fm62SY8J-Ultimate-Oscillator-Long-Strategy/
mohanee
https://www.tradingview.com/u/mohanee/
189
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© mohanee //@version=4 strategy(title="Ultimate Oscillator [Long] Strategy", shorttitle="UO" , overlay=false, pyramiding=2, default_qty_type=strategy.percent_of_equity, default_qty_value=20, initial_capital=10000, currency=currency.USD) //default_qty_value=10, default_qty_type=strategy.fixed, //Ultimate Oscillator logic copied from TradingView builtin indicator ///////////////////////////////////////////////////////////////////////////////// length1 = input(5, minval=1), length2 = input(10, minval=1), length3 = input(15, minval=1) //rsiUOLength = input(7, title="RSI UO length", minval=1) signalLength = input(9, title="Signal length", minval=1) buyLine = input (45, title="Buy Line (UO crossing up oversold at ) ") //crossover exitLine = input (70, title="Exit Line (UO crsossing down overbought at) ") //crossunder riskCapital = input(title="Risk % of capital", defval=10, minval=1) stopLoss=input(3,title="Stop Loss",minval=1) takeProfit=input(false, title="Take Profit") profitExitLine = input (75, title="Take Profit at RSIofUO crossing below this value ") //crossunder showSignalLine=input(true, "show Signal Line") //showUO=input(false, "show Ultimate Oscialltor") average(bp, tr_, length) => sum(bp, length) / sum(tr_, length) high_ = max(high, close[1]) low_ = min(low, close[1]) bp = close - low_ tr_ = high_ - low_ avg7 = average(bp, tr_, length1) avg14 = average(bp, tr_, length2) avg28 = average(bp, tr_, length3) ultOscVal = 100 * (4*avg7 + 2*avg14 + avg28)/7 //Ultimate Oscillator ///////////////////////////////////////////////////////////////////////////////// //Willimas Alligator copied from TradingView built in Indicator ///////////////////////////////////////////////////////////////////////////////// smma(src, length) => smma = 0.0 smma := na(smma[1]) ? sma(src, length) : (smma[1] * (length - 1) + src) / length smma //moving averages logic copied from Willimas Alligator -- builtin indicator in TradingView sma1=smma(hl2,5) sma2=smma(hl2,20) sma3=smma(hl2,50) //Willimas Alligator ///////////////////////////////////////////////////////////////////////////////// myVwap= vwap(hlc3) //drawings ///////////////////////////////////////////////////////////////////////////////// hline(profitExitLine, title="Middle Line 60 [Profit Exit Here]", color=color.purple , linestyle=hline.style_dashed) obLevelPlot = hline(exitLine, title="Overbought", color=color.red , linestyle=hline.style_dashed) osLevelPlot = hline(buyLine, title="Oversold", color=color.blue, linestyle=hline.style_dashed) //fill(obLevelPlot, osLevelPlot, title="Background", color=color.blue, transp=90) //rsiUO = rsi(ultOscVal,rsiUOLength) rsiUO=ultOscVal //emaUO = ema(rsiUO, 9) //signal line emaUO = ema(ultOscVal , 5) // ema(ultOscVal / rsiUO, 9) //ultPlot=plot(showUO==true? ultOscVal : na, color=color.green, title="Oscillator") plot(rsiUO, title = "rsiUO" , color=color.purple) plot(showSignalLine ? emaUO : na , title = "emaUO [signal line]" , color=color.blue) //emaUO //drawings ///////////////////////////////////////////////////////////////////////////////// //Strategy Logic ///////////////////////////////////////////////////////////////////////////////// longCond= crossover(rsiUO, buyLine) or crossover(rsiUO, 30) //longCond= ( ema10>ema20 and crossover(rsiUO, buyLine) ) or ( ema10 < ema20 and crossover(rsiUO, 75) ) //Entry-- //Echeck how many units can be purchased based on risk manage ment and stop loss qty1 = (strategy.equity * riskCapital / 100 ) / (close*stopLoss/100) //check if cash is sufficient to buy qty1 , if capital not available use the available capital only qty1:= (qty1 * close >= strategy.equity ) ? (strategy.equity / close) : qty1 //strategy.entry(id="LERSIofUO", long=true, qty=qty1, when = close > open and barssince(longCond)<=3 and strategy.position_size<1 ) //and sma1 > sma3) // and close>open and rsiUO >= 25 ) //and strategy.entry(id="LEUO", long=true, qty=qty1, when = close > open and barssince(longCond)<=3 and strategy.position_size<1 and sma2 > sma3) // and close>open and rsiUO >= 25 ) //and //Add //strategy.entry(id="LEUO", comment="Add" , qty=qty1/2 , long=true, when = strategy.position_size>=1 and close < strategy.position_avg_price and crossover(rsiUO, 60) ) //and sma1 > sma3) // and close>open and rsiUO >= 25 ) //and //strategy.entry(id="LEUO", long=true, qty=qty1, when = close > open and barssince(longCond)<=10 and valuewhen(longCond , close , 1) > close and rsiUO>=30) // and close>open and rsiUO >= 25 ) //and //for Later versions //also check for divergence ... later version //also check if close above vwap session //strategy.entry(id="LEUO", long=false, when = sma1< sma2 and crossunder(rsiUO,60) ) //change the bar color to yellow , indicating startegy will trigger BUY barcolor( close > open and barssince(longCond)<=3 and strategy.position_size<1 and sma2 > sma3 ? color.orange : na) //barcolor(abs(strategy.position_size)>=1 ? color.blue : na ) bgcolor(abs(strategy.position_size)>=1 ? color.blue : na , transp=70) //signal for addition to existing position barcolor( strategy.position_size>=1 and close < strategy.position_avg_price and crossover(rsiUO, 60) ? color.yellow : na) //bgcolor( strategy.position_size>=1 and close < strategy.position_avg_price and crossover(rsiUO, 60) ? color.yellow : na, transp=30) //partial exit strategy.close(id="LEUO", comment="PExit", qty=strategy.position_size/3, when= takeProfit and abs(strategy.position_size)>=1 and close > strategy.position_avg_price and crossunder(rsiUO,profitExitLine) ) //close the Long order strategy.close(id="LEUO", comment="Profit is "+tostring(close - strategy.position_avg_price, "###.##"), when=abs(strategy.position_size)>=1 and crossunder(rsiUO,exitLine) ) //and close > strategy.position_avg_price ) //strategy.close(id="LEUO", comment="CloseAll", when=abs(strategy.position_size)>=1 and crossunder(rsiUO2,40) ) //and close > strategy.position_avg_price ) // stop loss exit stopLossVal = strategy.position_size>=1 ? strategy.position_avg_price * ( 1 - (stopLoss/100) ) : 0.00 strategy.close(id="LEUO", comment="SL exit Loss is "+tostring(close - strategy.position_avg_price, "###.##") , when=abs(strategy.position_size)>=1 and close < stopLossVal and rsiUO < exitLine) //reason to rsiUO <30 is if price is going down , indicator should reflect it ... but indicator is above 30 means it showing divergence... so hold on it until it crossdown 30 ...that way even Stop Loss less than predefined ... //Strategy Logic /////////////////////////////////////////////////////////////////////////////////
Trading Inside Gap - 15 min chart
https://www.tradingview.com/script/J8TRZZna-Trading-Inside-Gap-15-min-chart/
achalmeena
https://www.tradingview.com/u/achalmeena/
24
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 // Β© achalmeena // Reference E-Book - Teach Yourself Coding Indicators PineScript // Udemy course on Creating trade strategies backtesting using pinescript // The code is to trade "inside Gap up", inside Gap means open of new candle is above close of previous candle but below high of previous candle. // In this code "Security function" is used to get high low of previous bar // time function is also used to identify first bar of the session. // The code can be refined by using filters to have more better results. //@version=4 strategy("Trading Inside Gap - 15 min chart",overlay=true) maxTrades = 2 strategy.risk.max_intraday_filled_orders(count=maxTrades) t = time("1440", session.regular) // 1440=60*24 is the number of minutes in a whole day. You may use "0930-1600" as second session parameter is_first = na(t[1]) and not na(t) or t[1] < t condition_H()=> (high) condition_L()=>(low) condition_R()=>(close<open) RedCandle = security(syminfo.tickerid,'D',condition_R()) DayHigh = security(syminfo.tickerid,'D',condition_H()) DayLow = security(syminfo.tickerid,'D',condition_L()) GapUp = is_first and open > close[1]*1.005 and open < DayHigh t1 = time("1440", "0930-1600") t11 = na(t1) ? 0 : 1 if GapUp[1] and t11 == 1 //add code to mark all session bars as GapUp GapUp := true plotshape(GapUp,style=shape.triangleup,location=location.abovebar,color=color.green) ///take long when price near low NearLow = close < DayLow * 1.005 strategy.entry("Gap Up Long",long=1,when = GapUp and NearLow and (RedCandle) and hour(time) < 15,stop=high[1]) strategy.close("Gap Up Long", comment="Session Ends",when=hour(time)==14 and minute(time) > 30 )
Bull Call Spread Entry Strategy
https://www.tradingview.com/script/Q8EHOi40-Bull-Call-Spread-Entry-Strategy/
DeuceDavis
https://www.tradingview.com/u/DeuceDavis/
214
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/ // Β© DeuceDavis //@version=4 strategy("Spread Entry Strategy", shorttitle="SE Strategy", max_bars_back=1, overlay=true) //Remove or Add Narrative Label narrationYes = input(title="Provide Narrative (Troubleshooting)", type=input.bool, defval=false) //Overall Market Condition //This used to filter out noise caused by overall dramatic market moves //Any comparison ticker can be used, the default is the QQQ ticker //Defaults are 1% for being to hot and 2.5% for being too cold mktFilter = input(title="Use Market Filter", type=input.bool, defval=true) mkt = input(title="Market Ticker to Use", type=input.symbol, defval="QQQ") mktChange = (security(mkt, "D", close) - security(mkt, "D", close[1])) / security(mkt, "D", close[1]) * 100 mktChangeTooHighLevel = input(title="Market Too Hot Level", type=input.float, defval = 1) mktChangeTooCoolLevel = input(title="Market Too Cool Level", type=input.float, defval = -2.5) mktIsHot = not mktFilter ? false: mktChange >= mktChangeTooHighLevel ? true:false mktIsCold = not mktFilter ? false: mktChange <= mktChangeTooCoolLevel ? true:false //Sets the level for when an overlay will show using the absolute power on the side of the trade setting up strengthFilter = input(title="Overlay Signal Strength Level", type=input.integer, defval=6) //Filters out Bull and Bear overlays when engaged useSqueezeFilter = input(title="Remove Strength Indicator When Squeezed", type=input.bool, defval=false) //Shades the background when the stock is undergoing a squeeze showSqueezes = input(title="Show Squeezes (Will Override Indicator When Concurrent)", type=input.bool, defval=false) showBear = input(title="Show Bear Side", type=input.bool, defval=true) showBull = input(title="Show Bull Side", type=input.bool, defval=true) rsiPeriod = input(title="RSI Period", type=input.integer, defval=14) dmiPeriod = input(title="DMI Period", type=input.integer, defval=14) dmiSmoothing = input(title="DMI Smoothing", type=input.integer, defval=14) bbPeriod = input(title="Bollinger Bands Period", type=input.integer, defval=20) bbMultiplier = input(title="Bollinger Bands Multiplier", type=input.integer, defval=2) kcPeriod = input(title="Keltner Channel Period", type=input.integer, defval=20) kcMultiplier = input(title="Keltner Channel Multiplier", type=input.float, defval=1.5) shortSMAPeriod = input(title="Short SMA Period", type=input.integer, defval=20) mediumSMAPeriod = input(title="Medium SMA Period", type=input.integer, defval=50) longSMAPeriod = input(title="Long SMA Period", type=input.integer, defval=200) smaShort = sma(close, shortSMAPeriod) smaMedium = sma(close, mediumSMAPeriod) smaLong = sma(close, longSMAPeriod) rsiPlot = rsi(close, rsiPeriod) [diPlus, diMinus, adx] = dmi(dmiPeriod, dmiSmoothing) [middleBB, upperBB, lowerBB] = bb(close, 20, 2) [middleKC, upperKC, lowerKC] = kc(close, 20, 1.5, useTrueRange=true) //Bull or Bear side is determined whether the price is above or below the Bollinger Band Basis (BB Middle) bullOrBear = close < middleBB ? "Bull" : "Bear" //Squeeze Condition bbOutsideKC = (((lowerBB < lowerKC) and (upperBB > upperKC))) ? 1 : 0 currentlySqueezed = bbOutsideKC == 0 ? true : false squeezedOut = bbOutsideKC > bbOutsideKC[1] ? 1 : 0 //Penalty for -DI and +DI going in same direction (Currently not used) diDirDivergency = (diPlus > diPlus[1]) and (diMinus < diMinus[1]) ? "UpDn" : (diPlus < diPlus[1]) and (diMinus > diMinus[1]) ? "DnUp" : (diPlus > diPlus[1]) and (diMinus > diMinus[1]) ? "UpUp" : "DnDn" diPenalty = (diDirDivergency == "UpUp") or (diDirDivergency == "DnDn") ? 2 : 0 adxUpDown = adx > adx[1] ? "Up" : "Down" diMinusUpDown = diMinus > diMinus[1] ? "Up" : "Down" diPlusUpDown = diPlus > diPlus[1] ? "Up" : "Down" rsiUpDown = rsiPlot > rsiPlot[1] ? "Up" : "Down" //Conditions for Bull Strength lowerBB_Bounce = lowest(5) <= lowerBB ? 1 : 0 adxUpTrend = adx > adx[1] ? 1 : 0 bullRSIStat = rsiPlot[0] > rsiPlot[1] ? 1 : 0 diMinusStat = diMinus[0] < diMinus[1] ? 1 : 0 lowerBBStat = close < middleBB and close > lowerBB ? 1 : 0 lowerKCStat = close < lowerKC ? 1 : 0 rsiUnder30 = rsiPlot < 30 ? 1: 0 bullCondition = rsiPlot > 70 ? 0 : bullRSIStat + diMinusStat + lowerBBStat + lowerKCStat + bbOutsideKC + lowerBB_Bounce + adxUpTrend + rsiUnder30 //Conditions for Bear Strength upperBB_Bounce = highest(5) >= upperBB ? 1 : 0 adxDownTrend = adx < adx[1] ? 1 : 0 bearRSIStat = rsiPlot[0] < rsiPlot[1] ? 1 : 0 diPlusStat = diPlus[0] > diPlus[1] ? 1 : 0 upperBBStat = close > middleBB and close < upperBB ? 1 : 0 upperKCStat = close > upperKC ? 1 : 0 rsiOver70 = rsiPlot > 70 ? 1: 0 bearCondition = rsiPlot < 30 ? 0 : ( bearRSIStat + diPlusStat + upperBBStat + upperKCStat + bbOutsideKC + upperBB_Bounce + adxDownTrend + rsiOver70 ) * -1 //Overall Trade Condition, used to find the right side //tradeCondition = (bullOrBear == "Bull") ? (bullCondition) : (bearCondition) tradeCondition = (currentlySqueezed and useSqueezeFilter) ? 0 : bullOrBear == "Bull" ? (bullCondition > 1 ? bullCondition : 0) : (bearCondition < -1 ? bearCondition : 0) signalYesNo = "Yes" //Not currently used bullColor = color.blue bearColor = color.purple squeezeColor = color.orange var sessionFills = array.new_color(22) array.set(sessionFills, 0, color.new(bearColor, 0)) array.set(sessionFills, 1, color.new(bearColor, 10)) array.set(sessionFills, 2, color.new(bearColor, 20)) array.set(sessionFills, 3, color.new(bearColor, 30)) array.set(sessionFills, 4, color.new(bearColor, 40)) array.set(sessionFills, 5, color.new(bearColor, 50)) array.set(sessionFills, 6, color.new(bearColor, 60)) array.set(sessionFills, 7, color.new(bearColor, 70)) array.set(sessionFills, 8, color.new(bearColor, 80)) array.set(sessionFills, 9, color.new(bearColor, 90)) array.set(sessionFills, 10, color.new(bullColor, 100)) array.set(sessionFills, 11, color.new(bullColor, 90)) array.set(sessionFills, 12, color.new(bullColor, 80)) array.set(sessionFills, 13, color.new(bullColor, 70)) array.set(sessionFills, 14, color.new(bullColor, 60)) array.set(sessionFills, 15, color.new(bullColor, 50)) array.set(sessionFills, 16, color.new(bullColor, 40)) array.set(sessionFills, 17, color.new(bullColor, 30)) array.set(sessionFills, 18, color.new(bullColor, 20)) array.set(sessionFills, 19, color.new(bullColor, 10)) array.set(sessionFills, 20, color.new(bullColor, 0)) array.set(sessionFills, 21, color.new(squeezeColor, 90)) //Calculate Overlay Color fillNumber = (currentlySqueezed and showSqueezes) ? 21 : (mktIsHot or mktIsCold) ? 10 : signalYesNo == "No" ? 10 : abs(tradeCondition) < strengthFilter ? 10 : (bullOrBear == "Bear") and (not showBear) ? 10 : (bullOrBear == "Bull") and (not showBull) ? 10 : tradeCondition + 10 bgcolor(array.get(sessionFills, fillNumber)) //plot(lowerKC, title='lowerKC', color=#00ffaa, linewidth=2, style=plot.style_line) bullOrBearColor = bullOrBear == "Bull" ? color.green : color.red plotshape(tradeCondition, title="Entry Strength", offset=0, style=shape.flag, location=location.top, color=bullOrBearColor, transp=100) plotshape(bullCondition, title="Bull Strength", offset=0, style=shape.flag, location=location.top, color=bullColor, transp=100) plotshape(bearCondition, title="Bear Strength", offset=0, style=shape.flag, location=location.top, color=bearColor, transp=100) curHour = hour(time) - 5 rippleDoD = smaShort > smaShort[1] ? "UP" : "DOWN" waveDoD = smaMedium > smaMedium[1] ? "UP" : "DOWN" tideDoD = smaLong > smaLong[1] ? "UP" : "DOWN" rippleWaveUpDn = smaShort > smaMedium ? "ABOVE" : "BELOW" waveTideUpDn = smaMedium > smaLong ? "ABOVE" : "BELOW" // STEP 1: // Make input options that configure backtest date range startDate = input(title="Start Date", type=input.integer, defval=1, minval=1, maxval=31) startMonth = input(title="Start Month", type=input.integer, defval=1, minval=1, maxval=12) startYear = input(title="Start Year", type=input.integer, defval=2018, minval=1800, maxval=2100) endDate = input(title="End Date", type=input.integer, defval=1, minval=1, maxval=31) endMonth = input(title="End Month", type=input.integer, defval=12, minval=1, maxval=12) endYear = input(title="End Year", type=input.integer, defval=2021, minval=1800, maxval=2100) // STEP 2: // 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)) entryLimit = close triggerBar = (bullOrBear=="Bull" and bullCondition >= strengthFilter and (not mktIsHot and not mktIsCold)) if triggerBar and inDateRange strategy.entry("BCS", strategy.long, 100, limit=entryLimit, when=strategy.position_size <= 0) // strategy.entry("sell", strategy.short, 10, when=strategy.position_size > 0) //plot(strategy.equity) exitWeekDay = dayofweek == 5 ? 1 : 0 //Exiting on Thursday entryBar = strategy.position_size[0] > strategy.position_size[1] barsPassedBy = barssince(entryBar) triggerBars = barssince(triggerBar) strategy.cancel("BCS", when = (triggerBars>0)) exitStrategy = (barsPassedBy >= 30) and exitWeekDay strategy.close("BCS", when=exitStrategy) //Narrative Build narSqueezed = currentlySqueezed ? "A Squeezed" + "\n" : na narrativeText = narSqueezed + bullOrBear + " Setup Strength " + tostring(abs(tradeCondition)) + "\n\n" + "RSI " + rsiUpDown + " to " + tostring(rsiPlot, "#.##") + "\n\n" + "ADX " + adxUpDown + " to " + tostring(adx, "#.##") + "\n\n" + "+DI " + diPlusUpDown + " to " + tostring(diPlus, "#.##") + "\n" + "-DI " + diMinusUpDown + " to " + tostring(diMinus, "#.##") + "\n" + "\n-------------------\n" + "Box Score" + "\n-------------------\n" + "Bulls " + tostring(bullCondition) + " | " + "Bears " + tostring(abs(bearCondition)) + "\n\n" + tostring(bullRSIStat) + " RSI " + tostring(bearRSIStat) + "\n" + tostring(diMinusStat) + " DI " + tostring(diPlusStat) + "\n" + tostring(lowerBBStat) + " BB " + tostring(upperBBStat) + "\n" + tostring(lowerKCStat) + " KC " + tostring(upperKCStat) + "\n" + tostring(bbOutsideKC) + " SQ " + tostring(bbOutsideKC) + "\n" + tostring(lowerBB_Bounce) + " BB Bounce " + tostring(upperBB_Bounce) + "\n" + tostring(adxUpTrend) + " ADX " + tostring(adxDownTrend) + "\n" + tostring(rsiUnder30) + " RSI 30/70 " + tostring(rsiOver70) + "\n" +"\n-------------------\n" + "Additional Narrative" + "\n-------------------\n" + tostring(shortSMAPeriod, "##") + " SMA is " + rippleWaveUpDn + " " + tostring(mediumSMAPeriod, "##") + " SMA\n" + "and is " + rippleDoD + " compared to prior bar\n\n" + tostring(mediumSMAPeriod, "##") + " SMA is " + waveTideUpDn + " " + tostring(longSMAPeriod, "##") + " SMA\n" + "and is " + waveDoD + " compared to prior bar\n\n" + tostring(longSMAPeriod, "##") + " SMA is " + tideDoD + " compared to prior bar\n" + "entry Conditions\n" + "BullOrBear " + (bullOrBear) + "\n" + "BullCondition " + tostring(bullCondition,"##") + "\n" + "Entry Limit " + tostring(entryLimit,"##.##") + "\n" + "BullCondition " + tostring(bullCondition,"##") + "\n" + "Bars Passed " + tostring(barsPassedBy,"##") + "\n" + "Tigger Bar " + tostring(triggerBars,"##") + "\n" narrativeLabel = narrationYes ? label.new(x=time, y=((low+high)/2), xloc=xloc.bar_time, text=narrativeText, color=bullOrBear=="Bull" ? bullColor : bearColor, textcolor=color.white, style=label.style_label_left) : na label.set_x(id=narrativeLabel, x=label.get_x(narrativeLabel) + 1) label.delete(narrativeLabel[1])