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
[D] Dudu 95 Strategy Template ver.1.1.
https://www.tradingview.com/script/C3D8ElZZ/
DuDu95
https://www.tradingview.com/u/DuDu95/
147
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© fpemehd // Thanks to myncrypto, jason5480, kevinmck100 // @version=5 strategy(title = '[D] Strategy Template v.1.2.', shorttitle = '[D] Template', overlay = true, pyramiding = 0, currency = currency.USD, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_value = 0.1, initial_capital = 100000, max_bars_back = 500, max_lines_count = 150, max_labels_count = 300) // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Time, Direction, Etc - Basic Settings Inputs // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // 1. Time: Based on UTC +09:00 i_start = input.time (defval = timestamp("20 Jan 1990 00:00 +0900"), title = "Start Date", tooltip = "Choose Backtest Start Date", inline = "Start Date", group = "Time" ) i_end = input.time (defval = timestamp("20 Dec 2030 00:00 +0900"), title = "End Date", tooltip = "Choose Backtest End Date", inline = "End Date", group = "Time" ) inTime = time >= i_start and time <= i_end // 2. Inputs for direction: Long? Short? Both? i_longEnabled = input.bool (defval = true , title = "Long?", tooltip = "Enable Long Position Trade?", inline = "Long / Short", group = "Long / Short" ) i_shortEnabled = input.bool (defval = true , title = "Short?", tooltip = "Enable Short Position Trade?", inline = "Long / Short", group = "Long / Short" ) // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Filter - Inputs, Indicaotrs // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // 3. Use Filters? What Filters? //// 3-1. ATR Filter i_ATRFilterOn = input.bool (defval = false , title = "ATR Filter On?", tooltip = "ATR Filter On? Order will not be made unless filter condition is fulfilled", inline = "1", group = "Filters") i_ATRFilterLen = input.int (defval = 14, title = "Length for ATR Filter", minval = 1 , maxval = 100 , step = 1 , tooltip = "", inline = "2", group = "Filters") i_ATRSMALen = input.int (defval = 40, title = "SMA Length for ATR SMA", minval = 1 , maxval = 100000 , step = 1 , tooltip = "ATR should be bigger than this", inline = "2", group = "Filters") bool ATRFilter = ta.atr(i_ATRFilterLen) >= ta.sma(ta.atr(length = i_ATRFilterLen), i_ATRSMALen) ? true : false //// 3-2. EMA Filter i_EMAFilterOn = input.bool (defval = false , title = "EMA Filter On?", tooltip = "EMA Filter On? Order will not be made unless filter condition is fulfilled", inline = "3", group = "Filters") i_EMALen = input.int (defval = 200, title = "EMA Length", minval = 1 , maxval = 100000 , step = 1 , tooltip = "EMA Length", inline = "4", group = "Filters") bool longEMAFilter = close >= ta.ema(source = close, length = i_EMALen) ? true : false bool shortEMAFilter = close <= ta.ema(source = close, length = i_EMALen) ? true : false //// 3-3. ADX Filter ////3-4. DMI Filter (Uses same ADX Length) i_ADXFilterOn = input.bool (defval = false , title = "ADX Filter On?", tooltip = "ADX Filter On? Order will not be made unless filter condition is fulfilled", inline = "5", group = "Filters") i_DMIFilterOn = input.bool (defval = false , title = "DMI Filter On?", tooltip = "DMI (Directional Moving Index) Filter On? Order will not be made unless filter condition is fulfilled", inline = "6", group = "Filters") i_ADXLength = input.int (defval = 20, title = "ADX Length", minval = 1 , maxval = 100000 , step = 1 , tooltip = "ADX Length", inline = "7", group = "Filters") i_ADXThreshold = input.int (defval = 25, title = "ADX Threshold", minval = 1 , maxval = 100000 , step = 1 , tooltip = "ADX should be bigger than threshold", inline = "8", group = "Filters") //// 3-4. SuperTrend Filter i_superTrendFilterOn = input.bool (defval = false , title = "Super Trend Filter On?", tooltip = "Super Trend Filter On? Order will not be made unless filter condition is fulfilled", inline = "9", group = "Filters") i_superTrendATRLen = input.int (defval = 10, title = "ATR Length", minval = 1 , maxval = 100000 , step = 1 , tooltip = "Super Trend ATR Length", inline = "10", group = "Filters") i_superTrendATRFactor = input.float (defval = 3, title = "Factor", minval = 1 , maxval = 100000 , step = 0.1 , tooltip = "Super Trend ATR Factor", inline = "11", group = "Filters") // ADX and DI Thanks to @BeikabuOyaji int len = i_ADXLength float th = i_ADXThreshold TR = math.max(math.max(high - low, math.abs(high - nz(close[1]))), math.abs(low - nz(close[1]))) DMPlus = high - nz(high[1]) > nz(low[1]) - low ? math.max(high - nz(high[1]), 0) : 0 DMMinus = nz(low[1]) - low > high - nz(high[1]) ? math.max(nz(low[1]) - low, 0) : 0 SmoothedTR = 0.0 SmoothedTR := nz(SmoothedTR[1]) - nz(SmoothedTR[1]) / len + TR SmoothedDMPlus = 0.0 SmoothedDMPlus := nz(SmoothedDMPlus[1]) - nz(SmoothedDMPlus[1]) / len + DMPlus SmoothedDMMinus = 0.0 SmoothedDMMinus := nz(SmoothedDMMinus[1]) - nz(SmoothedDMMinus[1]) / len + DMMinus DIPlus = SmoothedDMPlus / SmoothedTR * 100 DIMinus = SmoothedDMMinus / SmoothedTR * 100 DX = math.abs(DIPlus - DIMinus) / (DIPlus + DIMinus) * 100 ADX = ta.sma(source = DX, length = len) // plot(DIPlus, color=color.new(color.green, 0), title='DI+') // plot(DIMinus, color=color.new(color.red, 0), title='DI-') // plot(ADX, color=color.new(color.navy, 0), title='ADX') // hline(th, color=color.white) bool ADXFilter = ADX > th ? true : false bool longDMIFilter = DIPlus >= DIMinus ? true : false bool shortDMIFilter = DIPlus <= DIMinus ? true : false // Calculate Super Trend [supertrend, direction] = ta.supertrend(factor = i_superTrendATRFactor, atrPeriod = i_superTrendATRLen) bodyMiddle = plot((open + close) / 2, display=display.none) upTrend = plot(i_superTrendFilterOn ? direction < 0 ? supertrend : na : na, "Up Trend", color = color.green, style=plot.style_linebr) downTrend = plot(i_superTrendFilterOn ? direction < 0 ? na : supertrend : na, "Down Trend", color = color.red, style=plot.style_linebr) fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps=false) fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps=false) bool longSTFilter = direction <= 0 bool shortSTFilter = direction >= 0 // Filter bool longFilterFilled = (not i_ATRFilterOn or ATRFilter) and (not i_EMAFilterOn or longEMAFilter) and (not i_ADXFilterOn or ADXFilter) and (not i_DMIFilterOn or longDMIFilter) and (not i_superTrendFilterOn or longSTFilter) bool shortFilterFilled = (not i_ATRFilterOn or ATRFilter) and (not i_EMAFilterOn or shortEMAFilter) and (not i_ADXFilterOn or ADXFilter) and (not i_DMIFilterOn or shortDMIFilter) and (not i_superTrendFilterOn or shortSTFilter) // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Strategy Logic (Entry & Exit Condition) - Inputs, Indicators for Strategy // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ //// Indicators // Inputs for Strategy Indicators i_fastMALen = input.int (defval = 21, title = 'Fast SMA Length', minval = 1, inline = 'MA Length', group = 'Strategy') i_slowMALen = input.int (defval = 49, title = 'Slow SMA Length', minval = 1, tooltip = 'How many candles back to calculte the fast/slow SMA.', inline = 'MA Length', group = 'Strategy') // Calculate Indicators float indicator1 = ta.sma(source = close, length = i_fastMALen) float indicator2 = ta.sma(source = close, length = i_slowMALen) // Plot: Indicators var indicator1Color = color.new(color = color.yellow, transp = 0) plot(series = indicator1, title = 'indicator1', color = indicator1Color, linewidth = 1, style = plot.style_line) var indicator2Color = color.new(color = color.orange, transp = 0) plot(series = indicator2, title = 'indicator2', color = indicator2Color, linewidth = 1, style = plot.style_line) ////// Entry, Exit // Long, Short Logic with Indicator bool crossover = ta.crossover (indicator1, indicator2) bool crossunder = ta.crossunder (indicator1, indicator2) // Basic Cond + Long, Short Entry Condition bool longCond = (i_longEnabled and inTime) and (crossover) bool shortCond = (i_shortEnabled and inTime) and (crossunder) // Basic Cond + Long, Short Exit Condition bool closeLong = (i_longEnabled) and (crossunder) bool closeShort = (i_shortEnabled) and (crossover) // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Position Control // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Long, Short Entry Condition + Not entered Position Yet bool openLong = longCond and not (strategy.opentrades.size(strategy.opentrades - 1) > 0) and longFilterFilled bool openShort = shortCond and not (strategy.opentrades.size(strategy.opentrades - 1) < 0) and shortFilterFilled bool enteringTrade = openLong or openShort float entryBarIndex = bar_index // Long, Short Entry Fulfilled or Already Entered bool inLong = openLong or strategy.opentrades.size(strategy.opentrades - 1) > 0 and not closeLong bool inShort = openShort or strategy.opentrades.size(strategy.opentrades - 1) < 0 and not closeShort // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Stop Loss - Inputs, Indicaotrs // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ //// Use SL? TSL? i_useSLTP = input.bool (defval = true, title = "Enable SL & TP?", tooltip = "", inline = "1", group = "Stop Loss") i_tslEnabled = input.bool (defval = false , title = "Enable Trailing SL?", tooltip = "Enable Stop Loss & Take Profit? \n\Enable Trailing SL?", inline = "1", group = "Stop Loss") // i_breakEvenAfterTP = input.bool (defval = false, title = 'Enable Break Even After TP?', tooltip = 'When Take Profit price target is hit, move the Stop Loss to the entry price (or to a more strict price defined by the Stop Loss %/ATR Multiplier).', inline = '2', group = 'Stop Loss / Take Profit') //// Sl Options i_slType = input.string (defval = "ATR", title = "Stop Loss Type", options = ["Percent", "ATR", "Previous LL / HH"], tooltip = "Stop Loss based on %? ATR?", inline = "3", group = "Stop Loss") i_slATRLen = input.int (defval = 14, title = "ATR Length", minval = 1 , maxval = 200 , step = 1, inline = "4", group = "Stop Loss") i_slATRMult = input.float (defval = 3, title = "ATR Multiplier", minval = 1 , maxval = 200 , step = 0.1, tooltip = "", inline = "4", group = "Stop Loss") i_slPercent = input.float (defval = 3, title = "Percent", tooltip = "", inline = "5", group = "Stop Loss") i_slLookBack = input.int (defval = 30, title = "Lowest Price Before Entry", group = "Stop Loss", inline = "6", minval = 30, step = 1, tooltip = "Lookback to find the Lowest Price. \nStopLoss is determined by the Lowest price of the look back period. Take Profit is derived from this also by multiplying the StopLoss value by the Risk:Reward multiplier.") // Functions for Stop Loss float openAtr = ta.valuewhen(condition = enteringTrade, source = ta.atr(i_slATRLen), occurrence = 0) float openLowest = ta.valuewhen(condition = openLong, source = ta.lowest(low, i_slLookBack), occurrence = 0) float openHighest = ta.valuewhen(condition = openShort, source = ta.highest(high, i_slLookBack), occurrence = 0) f_getLongSLPrice(source) => switch i_slType "Percent" => source * (1 - (i_slPercent/100)) "ATR" => source - (i_slATRMult * openAtr) "Previous LL / HH" => openLowest => na f_getShortSLPrice(source) => switch i_slType "Percent" => source * (1 + (i_slPercent/100)) "ATR" => source + (i_slATRMult * openAtr) "Previous LL / HH" => openHighest => na // Calculate Stop Loss var float longSLPrice = na var float shortSLPrice = na bool longTPExecuted = false bool shortTPExecuted = false longSLPrice := if (inLong and i_useSLTP) if (openLong) f_getLongSLPrice (close) else // 1. Trailing Stop Loss if i_tslEnabled stopLossPrice = f_getLongSLPrice (high) math.max(stopLossPrice, nz(longSLPrice[1])) // 2. Normal StopLoss else nz(source = longSLPrice[1], replacement = 0) else na shortSLPrice := if (inShort and i_useSLTP) if (openShort) f_getShortSLPrice (close) else // 1. Trailing Stop Loss if i_tslEnabled stopLossPrice = f_getShortSLPrice (low) math.min(stopLossPrice, nz(shortSLPrice[1])) // 2. Normal StopLoss else nz(source = shortSLPrice[1], replacement = 999999.9) else na // Plot: Stop Loss of Long, Short Entry var longSLPriceColor = color.new(color.maroon, 0) plot(series = longSLPrice, title = 'Long Stop Loss', color = longSLPriceColor, linewidth = 1, style = plot.style_linebr, offset = 1) var shortSLPriceColor = color.new(color.maroon, 0) plot(series = shortSLPrice, title = 'Short Stop Loss', color = shortSLPriceColor, linewidth = 1, style = plot.style_linebr, offset = 1) // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Take Profit - Inputs, Indicaotrs // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ i_useTPExit = input.bool (defval = true, title = "Use Take Profit?", tooltip = "", inline = "1", group = "Take Profit") i_RRratio = input.float (defval = 1.8, title = "R:R Ratio", minval = 0.1 , maxval = 200 , step = 0.1, tooltip = "R:R Ratio > Risk Reward Ratio? It will automatically set Take Profit % based on Stop Loss", inline = "2", group = "Take Profit") i_tpQuantityPerc = input.float (defval = 50, title = 'Take Profit Quantity %', minval = 0.0, maxval = 100, step = 1.0, tooltip = '% of position closed when tp target is met.', inline="34", group = 'Take Profit') var float longTPPrice = na var float shortTPPrice = na f_getLongTPPrice() => close + i_RRratio * math.abs (close - f_getLongSLPrice (close)) f_getShortTPPrice() => close - i_RRratio * math.abs(close - f_getShortSLPrice (close)) longTPPrice := if (inLong and i_useSLTP) if (openLong) f_getLongTPPrice () else nz(source = longTPPrice[1], replacement = f_getLongTPPrice ()) else na shortTPPrice := if (inShort and i_useSLTP) if (openShort) f_getShortTPPrice () else nz(source = shortTPPrice[1], replacement = f_getShortTPPrice ()) else na // Plot: Take Profit of Long, Short Entry var longTPPriceColor = color.new(color.teal, 0) plot(series = longTPPrice, title = 'Long Take Profit', color = longTPPriceColor, linewidth = 1, style = plot.style_linebr, offset = 1) var shortTPPriceColor = color.new(color.teal, 0) plot(series = shortTPPrice, title = 'Short Take Profit', color = shortTPPriceColor, linewidth = 1, style = plot.style_linebr, offset = 1) // Plot: Entry Price var posColor = color.new(color.white, 0) plot(series = strategy.opentrades.entry_price(strategy.opentrades - 1), title = 'Position Entry Price', color = posColor, linewidth = 1, style = plot.style_linebr) // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Quantity - Inputs // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ i_useRiskManangement = input.bool (defval = true, title = "Use Risk Manangement?", tooltip = "", inline = "1", group = "Quantity") i_riskPerTrade = input.float (defval = 3, title = "Risk Per Trade (%)", minval = 0, maxval = 100, step = 0.1, tooltip = "Use Risk Manangement by Quantity Control?", inline = "2", group = "Quantity") // i_leverage = input.float (defval = 2, title = "Leverage", minval = 0, maxval = 100, step = 0.1, tooltip = "Leverage", inline = "3", group = "Quantity") float qtyPercent = na float entryQuantity = na f_calQtyPerc() => if (i_useRiskManangement) riskPerTrade = (i_riskPerTrade) / 100 // 1번 κ±°λž˜μ‹œ 3% 손싀 stopLossPrice = openLong ? f_getLongSLPrice (close) : openShort ? f_getShortSLPrice (close) : na riskExpected = math.abs((close-stopLossPrice)/close) // μ†μ ˆκ°€λž‘ 6% 차이 riskPerTrade / riskExpected // 0 ~ 1 else 1 f_calQty(qtyPerc) => math.min (math.max (0.000001, strategy.equity / close * qtyPerc), 1000000000) // TP Execution longTPExecuted := strategy.opentrades.size(strategy.opentrades - 1) > 0 and (longTPExecuted[1] or strategy.opentrades.size(strategy.opentrades - 1) < strategy.opentrades.size(strategy.opentrades - 1)[1] or strategy.opentrades.size(strategy.opentrades - 1)[1] == 0 and high >= longTPPrice) shortTPExecuted := strategy.opentrades.size(strategy.opentrades - 1) < 0 and (shortTPExecuted[1] or strategy.opentrades.size(strategy.opentrades - 1) > strategy.opentrades.size(strategy.opentrades - 1)[1] or strategy.opentrades.size(strategy.opentrades - 1)[1] == 0 and low <= shortTPPrice) // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Plot Label, Boxes, Results, Etc // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ i_showSimpleLabel = input.bool(false, "Show Simple Label for Entry?", group = "Strategy: Drawings", inline = "1", tooltip ="") i_showLabels = input.bool(true, "Show Trade Exit Labels", group = "Strategy: Drawings", inline = "1", tooltip = "Useful labels to identify Profit/Loss and cumulative portfolio capital after each trade closes.\n\nAlso note that TradingView limits the max number of 'boxes' that can be displayed on a chart (max 500). This means when you lookback far enough on the chart you will not see the TP/SL boxes. However you can check this option to identify where trades exited.") i_showDashboard = input.bool(true, "Show Dashboard", group = "Strategy: Drawings", inline = "2", tooltip = "Show Backtest Results. Backtest Dates, Win/Lose Rates, Etc.") // Plot: Label for Long, Short Entry var openLongColor = color.new(#2962FF, 0) var openShortColor = color.new(#FF1744, 0) var entryTextColor = color.new(color.white, 0) if (openLong and i_showSimpleLabel) label.new (x = bar_index, y = na, text = 'Open', yloc = yloc.belowbar, color = openLongColor, style = label.style_label_up, textcolor = entryTextColor) entryBarIndex := bar_index if (openShort and i_showSimpleLabel) label.new (x = bar_index, y = na, text = 'Close', yloc = yloc.abovebar, color = openShortColor, style = label.style_label_down, textcolor = entryTextColor) entryBarIndex := bar_index float prevEntryPrice = strategy.closedtrades.entry_price (strategy.closedtrades - 1) float pnl = strategy.closedtrades.profit (strategy.closedtrades - 1) float prevExitPrice = strategy.closedtrades.exit_price (strategy.closedtrades - 1) f_enteringTradeLabel(x, y, qty, entryPrice, slPrice, tpPrice, rrRatio, direction) => if i_showLabels labelStr = ("Trade Start" + "\nDirection: " + direction + "\nRisk Per Trade: " + str.tostring (i_useRiskManangement ? i_riskPerTrade : 100, "#.##") + "%" + "\nExpected Risk: " + str.tostring (math.abs((close-slPrice)/close) * 100, "#.##") + "%" + "\nEntry Position Qty: " + str.tostring(math.abs(qty * 100), "#.##") + "%" + "\nEntry Price: " + str.tostring(entryPrice, "#.##")) + "\nStop Loss Price: " + str.tostring(slPrice, "#.##") + "\nTake Profit Price: " + str.tostring(tpPrice, "#.##") + "\nRisk - Reward Ratio: " + str.tostring(rrRatio, "#.##") label.new(x = x, y = y, text = labelStr, color = color.new(color.blue, 60) , textcolor = color.white, style = label.style_label_up) f_exitingTradeLabel(x, y, entryPrice, exitPrice, direction) => if i_showLabels labelStr = ("Trade Result" + "\nDirection: " + direction + "\nEntry Price: " + str.tostring(entryPrice, "#.##") + "\nExit Price: " + str.tostring(exitPrice,"#.##") + "\nGain %: " + str.tostring(direction == 'Long' ? -(entryPrice-exitPrice) / entryPrice * 100 : (entryPrice-exitPrice) / entryPrice * 100 ,"#.##") + "%") label.new(x = x, y = y, text = labelStr, color = pnl > 0 ? color.new(color.green, 60) : color.new(color.red, 60), textcolor = color.white, style = label.style_label_down) f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) => _cellText = _title + " " + _value table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor, text_size=size.auto) // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Orders // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ if (inTime) if (openLong) qtyPercent := f_calQtyPerc() entryQuantity := f_calQty(qtyPercent) strategy.entry(id = "Long", direction = strategy.long, qty = entryQuantity, comment = 'Long(' + syminfo.ticker + '): Started', alert_message = 'Long(' + syminfo.ticker + '): Started') f_enteringTradeLabel(x = bar_index + 1, y = close-3*ta.tr, entryPrice = close, qty = qtyPercent, slPrice = longSLPrice, tpPrice = longTPPrice, rrRatio = i_RRratio, direction = "Long") if (openShort) qtyPercent := f_calQtyPerc() entryQuantity := f_calQty(qtyPercent) strategy.entry(id = "Short", direction = strategy.short, qty = entryQuantity, comment = 'Short(' + syminfo.ticker + '): Started', alert_message = 'Short(' + syminfo.ticker + '): Started') f_enteringTradeLabel(x = bar_index + 1, y = close-3*ta.tr, entryPrice = close, qty = qtyPercent, slPrice = shortSLPrice, tpPrice = shortTPPrice, rrRatio = i_RRratio, direction = "Short") if (closeLong) strategy.close(id = 'Long', comment = 'Close Long', alert_message = 'Long: Closed at market price') strategy.position_size > 0 ? f_exitingTradeLabel(x = bar_index, y = close+3*ta.tr, entryPrice = prevEntryPrice, exitPrice = prevExitPrice, direction = 'Long') : na if (closeShort) strategy.close(id = 'Short', comment = 'Close Short', alert_message = 'Short: Closed at market price') strategy.position_size < 0 ? f_exitingTradeLabel(x = bar_index, y = close+3*ta.tr, entryPrice = prevEntryPrice, exitPrice = prevExitPrice, direction = 'Short') : na if (inLong) strategy.exit(id = 'Long TP / SL', from_entry = 'Long', qty_percent = i_tpQuantityPerc, limit = longTPPrice, stop = longSLPrice, alert_message = 'Long(' + syminfo.ticker + '): Take Profit or Stop Loss executed') strategy.exit(id = 'Long SL', from_entry = 'Long', stop = longSLPrice, alert_message = 'Long(' + syminfo.ticker + '): Stop Loss executed') if (inShort) strategy.exit(id = 'Short TP / SL', from_entry = 'Short', qty_percent = i_tpQuantityPerc, limit = shortTPPrice, stop = shortSLPrice, alert_message = 'Short(' + syminfo.ticker + '): Take Profit or Stop Loss executed') strategy.exit(id = 'Short SL', from_entry = 'Short', stop = shortSLPrice, alert_message = 'Short(' + syminfo.ticker + '): Stop Loss executed') if strategy.position_size[1] > 0 and strategy.position_size == 0 f_exitingTradeLabel(x = bar_index, y = close+3*ta.tr, entryPrice = prevEntryPrice, exitPrice = prevExitPrice, direction = 'Long') if strategy.position_size[1] < 0 and strategy.position_size == 0 f_exitingTradeLabel(x = bar_index, y = close+3*ta.tr, entryPrice = prevEntryPrice, exitPrice = prevExitPrice, direction = 'Short') // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Backtest Result Dashboard // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ if i_showDashboard var bgcolor = color.new(color = color.black, transp = 100) var greenColor = color.new(color = #02732A, transp = 0) var redColor = color.new(color = #D92332, transp = 0) var yellowColor = color.new(color = #F2E313, transp = 0) // Keep track of Wins/Losses streaks newWin = (strategy.wintrades > strategy.wintrades[1]) and (strategy.losstrades == strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1]) newLoss = (strategy.wintrades == strategy.wintrades[1]) and (strategy.losstrades > strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1]) varip int winRow = 0 varip int lossRow = 0 varip int maxWinRow = 0 varip int maxLossRow = 0 if newWin lossRow := 0 winRow := winRow + 1 if winRow > maxWinRow maxWinRow := winRow if newLoss winRow := 0 lossRow := lossRow + 1 if lossRow > maxLossRow maxLossRow := lossRow // Prepare stats table var table dashTable = table.new(position.top_right, 1, 15, border_width=1) if barstate.islastconfirmedhistory dollarReturn = strategy.netprofit f_fillCell(dashTable, 0, 0, "Start:", str.format("{0,date,long}", strategy.closedtrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.closedtrades.entry_time(0)) f_fillCell(dashTable, 0, 1, "End:", str.format("{0,date,long}", strategy.opentrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.opentrades.entry_time(0)) _profit = (strategy.netprofit / strategy.initial_capital) * 100 f_fillCell(dashTable, 0, 2, "Net Profit:", str.tostring(_profit, '##.##') + "%", _profit > 0 ? greenColor : redColor, color.white) _numOfDaysInStrategy = (strategy.opentrades.entry_time(0) - strategy.closedtrades.entry_time(0)) / (1000 * 3600 * 24) f_fillCell(dashTable, 0, 3, "Percent Per Day", str.tostring(_profit / _numOfDaysInStrategy, '#########################.#####')+"%", _profit > 0 ? greenColor : redColor, color.white) _winRate = ( strategy.wintrades / strategy.closedtrades ) * 100 f_fillCell(dashTable, 0, 4, "Percent Profitable:", str.tostring(_winRate, '##.##') + "%", _winRate < 50 ? redColor : _winRate < 75 ? greenColor : yellowColor, color.white) f_fillCell(dashTable, 0, 5, "Profit Factor:", str.tostring(strategy.grossprofit / strategy.grossloss, '##.###'), strategy.grossprofit > strategy.grossloss ? greenColor : redColor, color.white) f_fillCell(dashTable, 0, 6, "Total Trades:", str.tostring(strategy.closedtrades), bgcolor, color.white) f_fillCell(dashTable, 0, 8, "Max Wins In A Row:", str.tostring(maxWinRow, '######') , bgcolor, color.white) f_fillCell(dashTable, 0, 9, "Max Losses In A Row:", str.tostring(maxLossRow, '######') , bgcolor, color.white)
Trend #4 - ATR+EMA channel
https://www.tradingview.com/script/4KrLn3pk/
zxcv55602
https://www.tradingview.com/u/zxcv55602/
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/ // Β© zxcv55602 //@version=4 strategy("Trend #4 - ATR+EMA channel", overlay = true,slippage=2,commission_value=0.05) date1 = input(title="Start Date", type=input.time, defval=timestamp("2020-01-01T00:00:00")) date2 = input(title="Stop Date", type=input.time, defval=timestamp("2030-01-01T00:00:00")) stoploss=input(1000, minval=1, title="stoploss") length = input(10, minval=1, title="Blue EMA length",step=1) multy = input(1.8, step=0.1, title="Blue EMA multy") atrlen = input(15, "ATR Period") mult_atr = input(0.7, "ATR mult", step=0.1) redema=input(20, "Red EMA length", step=1) longsignal=input(true,"long",type=input.bool) shortsignal=input(true,"short",type=input.bool) Breakout=input(false,"Breakout mode",type=input.bool) //------------------ upper_atr = ema(tr(true),atrlen) * mult_atr + close lower_atr = close - ema(tr(true),atrlen) * mult_atr plot(upper_atr, "+ATR", color=color.new(color.white,80),style=plot.style_stepline) plot(lower_atr, "-ATR", color=color.new(color.white,80),style=plot.style_stepline) //------------------ var op_upper_atr=0.0 var op_lower_atr=0.0 var op_close=0.0 //------------------ Keltma =ema(close, length) range = high - low rangema = ema(range, length) upperk =Keltma + rangema * multy lowerk = Keltma - rangema * multy plot(upperk, color=color.blue, title="") plot(lowerk, color=color.blue, title="") //------------------ red_ema=ema(close,redema) plot(red_ema, color=color.red, title="") //------------------ if time >= date1 and time <= date2 and Breakout==false if longsignal and strategy.position_size==0 and close>upperk and close>red_ema op_close:=close op_upper_atr:=upper_atr strategy.entry("L",true,qty=(stoploss/(op_close-red_ema)),stop=red_ema) strategy.exit("L",limit=op_upper_atr,comment="exit_L",stop=red_ema) if shortsignal and strategy.position_size==0 and close<lowerk and close<red_ema op_close:=close op_lower_atr:=lower_atr strategy.entry("S",false,qty=(stoploss/(red_ema-op_close)),stop=red_ema) strategy.exit("S",limit=op_lower_atr,comment="exit_S",stop=red_ema) if strategy.position_size>0 strategy.exit("L",limit=op_upper_atr,comment="exit_L",stop=red_ema) if strategy.position_size<0 strategy.exit("S",limit=op_lower_atr,comment="exit_S",stop=red_ema) //------------------ if time >= date1 and time <= date2 and Breakout if longsignal and strategy.position_size==0 and close[0]>high[1] and close>red_ema and close>upperk op_upper_atr:=upper_atr op_lower_atr:=lower_atr op_close:=close strategy.entry("long",strategy.long,qty=stoploss/(op_close-red_ema),limit=op_upper_atr,stop=red_ema) strategy.exit("long",comment="exit_L1",limit=op_upper_atr,stop=red_ema) if shortsignal and strategy.position_size==0 and close[0]<low[1] and close<red_ema and close<lowerk op_upper_atr:=upper_atr op_lower_atr:=lower_atr op_close:=close strategy.entry("short",strategy.short,qty=stoploss/(red_ema-op_close),limit=op_lower_atr,stop=red_ema) strategy.exit("short",comment="exit_S1",limit=op_lower_atr,stop=red_ema) if strategy.position_size>0 strategy.exit("long",comment="exit_L",limit=op_upper_atr,stop=red_ema) if strategy.position_size<0 strategy.exit("short",comment="exit_S",limit=op_lower_atr,stop=red_ema)
TradeIQ - Crazy Scalping Trading Strategy [Kaspricci]
https://www.tradingview.com/script/R7OSA2ar/
Kaspricci
https://www.tradingview.com/u/Kaspricci/
258
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/ // Β© Kaspricci //@version=5 strategy("TradeIQ - Crazy Scalping Trading Strategy [Kaspricci]", overlay=true, initial_capital = 1000, currency = currency.USD) headlineTMO = "TMO Settings" tmoLength = input.int(7, "TMO Length", minval = 1, group = headlineTMO) tmoSource = input.source(close, "TMO Source", group = headlineTMO) // calculate values osc = ta.mom(ta.sma(ta.sma(tmoSource, tmoLength), tmoLength), tmoLength) // determine color of historgram oscColor = osc > osc[1] and osc > 0 ? #00c42b : osc < osc[1] and osc > 0 ? #4ee567 : osc < osc[1] and osc < 0 ? #ff441f : osc > osc[1] and osc < 0 ? #c03920 : na // plot histogram //plot(osc, "OSC", oscColor, linewidth = 3, style = plot.style_histogram) // conditon to find highs and lows up = ta.highest(tmoSource, tmoLength) dn = ta.lowest(tmoSource, tmoLength) // define conditions to be used for finding divergence phosc = ta.crossunder(ta.change(osc), 0) plosc = ta.crossover (ta.change(osc), 0) // test for divergence bear = osc > 0 and phosc and ta.valuewhen(phosc,osc,0) < ta.valuewhen(phosc,osc,1) and ta.valuewhen(phosc,up,0) > ta.valuewhen(phosc,up,1) ? 1 : 0 bull = osc < 0 and plosc and ta.valuewhen(plosc,osc,0) > ta.valuewhen(plosc,osc,1) and ta.valuewhen(plosc,dn,0) < ta.valuewhen(plosc,dn,1) ? 1 : 0 // ------------------------------------------------------------------------------------------------------------- headlineAMA = "AMA Settings" amaSource = input.source(defval = close, title = "AMA Source", group = headlineAMA) amaLength = input.int(defval = 50, title = "AMA Length", minval = 2, group = headlineAMA) amaMulti = input.float(defval = 2.0, title = "Factor", minval = 1) amaShowCd = input(defval = true , title = "As Smoothed Candles") amaShowEx = input(defval = true, title = "Show Alternating Extremities") amaAlpha = input.float(1.0, "Lag", minval=0, step=.1, tooltip='Control the lag of the moving average (higher = more lag)', group= 'AMA Kernel Parameters') amaBeta = input.float(0.5, "Overshoot", minval=0, step=.1, tooltip='Control the overshoot amplitude of the moving average (higher = overshoots with an higher amplitude)', group='AMA Kernel Parameters') // ------------------------------------------------------------------------------------------------------------- headlineSL = "Stop Loss Settings" slLength = input.int(defval = 10, title = "SL Period", minval = 1, group = headlineSL, tooltip = "Number of bars for swing high / low") // ------------------------------------------------------------------------------------------------------------- var b = array.new_float(0) var float x = na if barstate.isfirst for i = 0 to amaLength - 1 x := i / (amaLength - 1) w = math.sin(2 * 3.14159 * math.pow(x, amaAlpha)) * (1 - math.pow(x, amaBeta)) array.push(b, w) // local function to filter the source filter(series float x) => sum = 0. for i = 0 to amaLength - 1 sum := sum + x[i] * array.get(b,i) sum / array.sum(b) // apply filter function on source series srcFiltered = filter(amaSource) deviation = ta.sma(math.abs(amaSource - srcFiltered), amaLength) * amaMulti upper = srcFiltered + deviation lower = srcFiltered - deviation //---- crossHigh = ta.cross(high, upper) crossLow = ta.cross(low, lower) var os = 0 os := crossHigh ? 1 : crossLow ? 0 : os[1] ext = os * upper + (1 - os) * lower //---- os_css = ta.rsi(srcFiltered, amaLength) / 100 extColor = os == 1 ? #30FF85 : #ff1100 plot(srcFiltered, "MA", amaShowCd ? na : color.black, 2, editable = false) plot(amaShowEx ? ext : na, "Extremities", ta.change(os) ? na : extColor, 2, editable=false) // handle smoothed candles var float h = na var float l = na var float c = na var float body = na if amaShowCd h := filter(high) l := filter(low) c := filter(amaSource) body := math.abs(math.avg(c[1], c[2]) - c) ohlc_os = ta.rsi(c, amaLength) / 100 plotcandle(math.avg(c[1], c[2]), h, l, c, "Smooth Candles", #434651, bordercolor = na, editable = false, display = amaShowCd ? display.all : display.none) // ------------------------------------------------------------------------------------------------------------- plotshape(bull ? ext : na, "Bullish Circle", shape.circle, location.absolute, color = #00c42b, size=size.tiny) plotshape(bear ? ext : na, "Bearish Circle", shape.circle, location.absolute, color = #ff441f, size=size.tiny) plotshape(bull ? ext : na, "Bullish Label", shape.labeldown, location.absolute, color = #00c42b, text="Buy", textcolor=color.white, size=size.tiny) plotshape(bear ? ext : na, "Bearish Label", shape.labelup, location.absolute, color = #ff441f, text="Sell", textcolor=color.white, size=size.tiny) // ------------------------------------------------------------------------------------------------------------- candleSizeIncreasing = body[2] < body[1] and body[1] < body[0] longEntryCond = os == 1 and bull shortEntryCond = os == 0 and bear longEntry = strategy.opentrades == 0 and candleSizeIncreasing and not candleSizeIncreasing[1] and ta.barssince(longEntryCond) < ta.barssince(os == 0) and ta.barssince(longEntryCond) < ta.barssince(bear) shortEntry = strategy.opentrades == 0 and candleSizeIncreasing and not candleSizeIncreasing[1] and ta.barssince(shortEntryCond) < ta.barssince(os == 1) and ta.barssince(shortEntryCond) < ta.barssince(bull) longExit = strategy.opentrades > 0 and strategy.position_size > 0 and (bear or os == 0) shortExit = strategy.opentrades > 0 and strategy.position_size < 0 and (bull or os == 1) recentSwingHigh = ta.highest(high, slLength) // highest high of last candles recentSwingLow = ta.lowest(low, slLength) // lowest low of recent candles bgcolor(longEntry ? color.rgb(76, 175, 79, 90) : na) bgcolor(shortEntry ? color.rgb(255, 82, 82, 90) : na) slLong = (close - recentSwingLow) / syminfo.mintick // stop loss in ticks slShort = (recentSwingHigh - close) / syminfo.mintick // stop loss in ticks newOrderID = str.tostring(strategy.closedtrades + strategy.opentrades + 1) curOrderID = str.tostring(strategy.closedtrades + strategy.opentrades) alertMessageForEntry = "Trade {0} - New {1} Entry at price: {2} with stop loss at: {3}" if (longEntry) alertMessage = str.format(alertMessageForEntry, newOrderID, "Long", close, recentSwingLow) strategy.entry(newOrderID, strategy.long, alert_message = alertMessage) strategy.exit("Stop Loss Long", newOrderID, loss = slLong, alert_message = "Stop Loss for Trade " + newOrderID) if(longExit) strategy.close(curOrderID, alert_message = "Close Trade " + curOrderID) if (shortEntry) alertMessage = str.format(alertMessageForEntry, newOrderID, "Short", close, recentSwingLow) strategy.entry(newOrderID, strategy.short, alert_message = alertMessage) strategy.exit("Stop Loss Short", newOrderID, loss = slShort, alert_message = "Stop Loss for Trade " + newOrderID) if(shortExit) strategy.close(curOrderID, alert_message = "Close Trade " + curOrderID)
[Sniper] SuperTrend + SSL Hybrid + QQE MOD
https://www.tradingview.com/script/6w9Jchj6/
DuDu95
https://www.tradingview.com/u/DuDu95/
584
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© fpemehd // Thanks to myncrypto, jason5480, kevinmck100 // @version=5 strategy(title = '[D] SuperTrend + SSL Hybrid + QQE MOD', shorttitle = '[D] SSQ Strategy', overlay = true, pyramiding = 0, currency = currency.USD, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_value = 0.1, initial_capital = 100000, max_bars_back = 500, max_lines_count = 150, max_labels_count = 300) // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Time, Direction, Etc - Basic Settings Inputs // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // 1. Time: Based on UTC +09:00 i_start = input.time (defval = timestamp("20 Jan 1990 00:00 +0900"), title = "Start Date", tooltip = "Choose Backtest Start Date", inline = "Start Date", group = "Time" ) i_end = input.time (defval = timestamp("20 Dec 2030 00:00 +0900"), title = "End Date", tooltip = "Choose Backtest End Date", inline = "End Date", group = "Time" ) inTime = time >= i_start and time <= i_end // 2. Inputs for direction: Long? Short? Both? i_longEnabled = input.bool (defval = true , title = "Long?", tooltip = "Enable Long Position Trade?", inline = "Long / Short", group = "Long / Short" ) i_shortEnabled = input.bool (defval = true , title = "Short?", tooltip = "Enable Short Position Trade?", inline = "Long / Short", group = "Long / Short" ) // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Filter - Inputs, Indicaotrs // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // 3. Use Filters? What Filters? //// 3-1. ATR Filter i_ATRFilterOn = input.bool (defval = false , title = "ATR Filter On?", tooltip = "ATR Filter On? Order will not be made unless filter condition is fulfilled", inline = "1", group = "Filters") i_ATRFilterLen = input.int (defval = 14, title = "Length for ATR Filter", minval = 1 , maxval = 100 , step = 1 , tooltip = "", inline = "2", group = "Filters") i_ATRSMALen = input.int (defval = 40, title = "SMA Length for ATR SMA", minval = 1 , maxval = 100000 , step = 1 , tooltip = "ATR should be bigger than this", inline = "2", group = "Filters") bool ATRFilter = ta.atr(i_ATRFilterLen) >= ta.sma(ta.atr(length = i_ATRFilterLen), i_ATRSMALen) ? true : false //// 3-2. EMA Filter i_EMAFilterOn = input.bool (defval = false , title = "EMA Filter On?", tooltip = "EMA Filter On? Order will not be made unless filter condition is fulfilled", inline = "3", group = "Filters") i_EMALen = input.int (defval = 200, title = "EMA Length", minval = 1 , maxval = 100000 , step = 1 , tooltip = "EMA Length", inline = "4", group = "Filters") bool longEMAFilter = close >= ta.ema(source = close, length = i_EMALen) ? true : false bool shortEMAFilter = close <= ta.ema(source = close, length = i_EMALen) ? true : false plot(i_EMAFilterOn ? ta.ema(source = close, length = i_EMALen) : na, title = "EMA Filter", color = color.new(color = color.orange , transp = 0), linewidth = 1) //// 3-3. ADX Filter ////3-4. DMI Filter (Uses same ADX Length) i_ADXFilterOn = input.bool (defval = false , title = "ADX Filter On?", tooltip = "ADX Filter On? Order will not be made unless filter condition is fulfilled", inline = "5", group = "Filters") i_DMIFilterOn = input.bool (defval = false , title = "DMI Filter On?", tooltip = "DMI (Directional Moving Index) Filter On? Order will not be made unless filter condition is fulfilled", inline = "6", group = "Filters") i_ADXLength = input.int (defval = 20, title = "ADX Length", minval = 1 , maxval = 100000 , step = 1 , tooltip = "ADX Length", inline = "7", group = "Filters") i_ADXThreshold = input.int (defval = 25, title = "ADX Threshold", minval = 1 , maxval = 100000 , step = 1 , tooltip = "ADX should be bigger than threshold", inline = "8", group = "Filters") //// 3-4. SuperTrend Filter // i_superTrendFilterOn = input.bool (defval = false , title = "Super Trend Filter On?", tooltip = "Super Trend Filter On? Order will not be made unless filter condition is fulfilled", inline = "9", group = "Filters") // i_superTrendATRLen = input.int (defval = 10, title = "ATR Length", minval = 1 , maxval = 100000 , step = 1 , tooltip = "Super Trend ATR Length", inline = "10", group = "Filters") // i_superTrendATRFactor = input.float (defval = 3, title = "Factor", minval = 1 , maxval = 100000 , step = 0.1 , tooltip = "Super Trend ATR Factor", inline = "11", group = "Filters") // ADX and DI Thanks to @BeikabuOyaji int len = i_ADXLength float th = i_ADXThreshold TR = math.max(math.max(high - low, math.abs(high - nz(close[1]))), math.abs(low - nz(close[1]))) DMPlus = high - nz(high[1]) > nz(low[1]) - low ? math.max(high - nz(high[1]), 0) : 0 DMMinus = nz(low[1]) - low > high - nz(high[1]) ? math.max(nz(low[1]) - low, 0) : 0 SmoothedTR = 0.0 SmoothedTR := nz(SmoothedTR[1]) - nz(SmoothedTR[1]) / len + TR SmoothedDMPlus = 0.0 SmoothedDMPlus := nz(SmoothedDMPlus[1]) - nz(SmoothedDMPlus[1]) / len + DMPlus SmoothedDMMinus = 0.0 SmoothedDMMinus := nz(SmoothedDMMinus[1]) - nz(SmoothedDMMinus[1]) / len + DMMinus DIPlus = SmoothedDMPlus / SmoothedTR * 100 DIMinus = SmoothedDMMinus / SmoothedTR * 100 DX = math.abs(DIPlus - DIMinus) / (DIPlus + DIMinus) * 100 ADX = ta.sma(source = DX, length = len) // plot(DIPlus, color=color.new(color.green, 0), title='DI+') // plot(DIMinus, color=color.new(color.red, 0), title='DI-') // plot(ADX, color=color.new(color.navy, 0), title='ADX') // hline(th, color=color.white) bool ADXFilter = ADX > th ? true : false bool longDMIFilter = DIPlus >= DIMinus ? true : false bool shortDMIFilter = DIPlus <= DIMinus ? true : false // Calculate Super Trend for Filter // i_superTrendFilterOn = input.bool (defval = false , title = "Super Trend Filter On?", tooltip = "Super Trend Filter On? Order will not be made unless filter condition is fulfilled", inline = "9", group = "Filters") // i_superTrendATRLen = input.int (defval = 10, title = "ATR Length", minval = 1 , maxval = 100000 , step = 1 , tooltip = "Super Trend ATR Length", inline = "10", group = "Filters") // i_superTrendATRFactor = input.float (defval = 3, title = "Factor", minval = 1 , maxval = 100000 , step = 0.1 , tooltip = "Super Trend ATR Factor", inline = "11", group = "Filters") // [supertrend, direction] = ta.supertrend(factor = i_superTrendATRFactor, atrPeriod = i_superTrendATRLen) // bodyMiddle = plot((open + close) / 2, display=display.none) // upTrend = plot(i_superTrendFilterOn ? direction < 0 ? supertrend : na : na, "Up Trend", color = color.green, style=plot.style_linebr) // downTrend = plot(i_superTrendFilterOn ? direction < 0 ? na : supertrend : na, "Down Trend", color = color.red, style=plot.style_linebr) // fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps=false) // fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps=false) // bool longSTFilter = direction <= 0 // bool shortSTFilter = direction >= 0 // Filter bool longFilterFilled = (not i_ATRFilterOn or ATRFilter) and (not i_EMAFilterOn or longEMAFilter) and (not i_ADXFilterOn or ADXFilter) and (not i_DMIFilterOn or longDMIFilter) // and (not i_superTrendFilterOn or longSTFilter) bool shortFilterFilled = (not i_ATRFilterOn or ATRFilter) and (not i_EMAFilterOn or shortEMAFilter) and (not i_ADXFilterOn or ADXFilter) and (not i_DMIFilterOn or shortDMIFilter) // and (not i_superTrendFilterOn or shortSTFilter) // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Strategy Logic (Entry & Exit Condition) - Inputs, Indicators for Strategy // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ //// Indicators // Inputs for Strategy Indicators //// 1. Super Trend i_superTrendATRLen = input.int (defval = 10, title = "ATR Length", minval = 1 , maxval = 100000 , step = 1 , tooltip = "Super Trend ATR Length", inline = "1", group = "1: SuperTrend") i_superTrendATRFactor = input.float (defval = 3, title = "Factor", minval = 1 , maxval = 100000 , step = 0.1 , tooltip = "Super Trend ATR Factor", inline = "2", group = "1: SuperTrend") [supertrend, direction] = ta.supertrend(factor = i_superTrendATRFactor, atrPeriod = i_superTrendATRLen) //// 2. SSL Hybrid Baseline i_useTrueRange = input.bool (defval = true, title = "use true range for Keltner Channel?", tooltip = "", inline = "1", group = "2: SSL Hybrid") i_maType = input.string (defval ='EMA', title='Baseline Type', options=['SMA', 'EMA', 'DEMA', 'TEMA', 'LSMA', 'WMA', 'VAMA', 'TMA', 'HMA', 'McGinley'], inline="2", group = "2: SSL Hybrid") i_len = input.int (defval =30, title='Baseline Length', inline="2", group = "2: SSL Hybrid") i_multy = input.float (defval = 0.2, title='Base Channel Multiplier', minval = 0, maxval = 100, step=0.05, inline="3", group = "2: SSL Hybrid") i_volatility_lookback = input.int (defval =10, title='Volatility lookback length(for VAMA)', inline='4',group="2: SSL Hybrid") tema(src, len) => ema1 = ta.ema(src, len) ema2 = ta.ema(ema1, len) ema3 = ta.ema(ema2, len) 3 * ema1 - 3 * ema2 + ema3 f_ma(type, src, len) => float result = 0 if type == 'TMA' result := ta.sma(ta.sma(src, math.ceil(len / 2)), math.floor(len / 2) + 1) result if type == 'LSMA' result := ta.linreg(src, len, 0) result if type == 'SMA' // Simple result := ta.sma(src, len) result if type == 'EMA' // Exponential result := ta.ema(src, len) result if type == 'DEMA' // Double Exponential e = ta.ema(src, len) result := 2 * e - ta.ema(e, len) result if type == 'TEMA' // Triple Exponential e = ta.ema(src, len) result := 3 * (e - ta.ema(e, len)) + ta.ema(ta.ema(e, len), len) result if type == 'WMA' // Weighted result := ta.wma(src, len) result if type == 'VAMA' // Volatility Adjusted /// Copyright Β© 2019 to present, Joris Duyck (JD) mid = ta.ema(src, len) dev = src - mid vol_up = ta.highest(dev, i_volatility_lookback) vol_down = ta.lowest(dev, i_volatility_lookback) result := mid + math.avg(vol_up, vol_down) result if type == 'HMA' // Hull result := ta.wma(2 * ta.wma(src, len / 2) - ta.wma(src, len), math.round(math.sqrt(len))) result if type == 'McGinley' mg = 0.0 mg := na(mg[1]) ? ta.ema(src, len) : mg[1] + (src - mg[1]) / (len * math.pow(src / mg[1], 4)) result := mg result result //// 2-1. SSL Hybrid Keltner Baseline Channel BBMC = f_ma (i_maType, close, i_len) // BaseLone Keltma = f_ma (i_maType, close, i_len) range_1 = i_useTrueRange ? ta.tr : high - low rangema = ta.ema(range_1, i_len) upperk = Keltma + rangema * i_multy lowerk = Keltma - rangema * i_multy //// 3. QQE MOD, thanks to Mihkel100 RSI_Period = input.int (defval = 6, title = 'RSI Length', inline = "1", group = "3: QQE MOD") SF = input.int (defval = 5, title = 'RSI Smoothing', inline = "2", group = "3: QQE MOD") QQE = input.float (defval = 3, title = 'Fast QQE Factor', inline = "3", group = "3: QQE MOD") ThreshHold = input.int (defval = 3, title = 'Thresh-hold', inline = "4", group = "3: QQE MOD") src = input (defval = close, title='RSI Source') Wilders_Period = RSI_Period * 2 - 1 Rsi = ta.rsi(src, RSI_Period) RsiMa = ta.ema(Rsi, SF) AtrRsi = math.abs(RsiMa[1] - RsiMa) MaAtrRsi = ta.ema(AtrRsi, Wilders_Period) dar = ta.ema(MaAtrRsi, Wilders_Period) * QQE longband = 0.0 shortband = 0.0 trend = 0 DeltaFastAtrRsi = dar RSIndex = RsiMa newshortband = RSIndex + DeltaFastAtrRsi newlongband = RSIndex - DeltaFastAtrRsi longband := RSIndex[1] > longband[1] and RSIndex > longband[1] ? math.max(longband[1], newlongband) : newlongband shortband := RSIndex[1] < shortband[1] and RSIndex < shortband[1] ? math.min(shortband[1], newshortband) : newshortband cross_1 = ta.cross(longband[1], RSIndex) trend := ta.cross(RSIndex, shortband[1]) ? 1 : cross_1 ? -1 : nz(trend[1], 1) FastAtrRsiTL = trend == 1 ? longband : shortband //////////////////// length = input.int (defval = 50, minval = 1, title = 'Bollinger Length', group = "3: QQE MOD") mult = input.float (defval = 0.35, minval = 0.01, maxval = 5, step = 0.1, title = 'BB Multiplier', group = "3: QQE MOD") basis = ta.sma(FastAtrRsiTL - 50, length) dev = mult * ta.stdev(FastAtrRsiTL - 50, length) upper = basis + dev lower = basis - dev color_bar = RsiMa - 50 > upper ? #00c3ff : RsiMa - 50 < lower ? #ff0062 : color.gray // // Zero cross QQEzlong = 0 QQEzlong := nz(QQEzlong[1]) QQEzshort = 0 QQEzshort := nz(QQEzshort[1]) QQEzlong := RSIndex >= 50 ? QQEzlong + 1 : 0 QQEzshort := RSIndex < 50 ? QQEzshort + 1 : 0 // // Zero = hline(0, color=color.white, linestyle=hline.style_dotted, linewidth=1) //////////////////////////////////////////////////////////////// RSI_Period2 = input.int (defval = 6, title = 'RSI 2 Length', group = "3: QQE MOD") SF2 = input.int (defval = 5, title = 'RSI Smoothing', group = "3: QQE MOD") QQE2 = input.float (defval = 1.61, title = 'Fast QQE2 Factor', group = "3: QQE MOD") ThreshHold2 = input.int (defval = 3, title = 'Thresh-hold', group = "3: QQE MOD") src2 = input (defval = close, title = 'RSI Source', group = "3: QQE MOD") // // Wilders_Period2 = RSI_Period2 * 2 - 1 Rsi2 = ta.rsi(src2, RSI_Period2) RsiMa2 = ta.ema(Rsi2, SF2) AtrRsi2 = math.abs(RsiMa2[1] - RsiMa2) MaAtrRsi2 = ta.ema(AtrRsi2, Wilders_Period2) dar2 = ta.ema(MaAtrRsi2, Wilders_Period2) * QQE2 longband2 = 0.0 shortband2 = 0.0 trend2 = 0 DeltaFastAtrRsi2 = dar2 RSIndex2 = RsiMa2 newshortband2 = RSIndex2 + DeltaFastAtrRsi2 newlongband2 = RSIndex2 - DeltaFastAtrRsi2 longband2 := RSIndex2[1] > longband2[1] and RSIndex2 > longband2[1] ? math.max(longband2[1], newlongband2) : newlongband2 shortband2 := RSIndex2[1] < shortband2[1] and RSIndex2 < shortband2[1] ? math.min(shortband2[1], newshortband2) : newshortband2 cross_2 = ta.cross(longband2[1], RSIndex2) trend2 := ta.cross(RSIndex2, shortband2[1]) ? 1 : cross_2 ? -1 : nz(trend2[1], 1) FastAtrRsi2TL = trend2 == 1 ? longband2 : shortband2 // // Zero cross QQE2zlong = 0 QQE2zlong := nz(QQE2zlong[1]) QQE2zshort = 0 QQE2zshort := nz(QQE2zshort[1]) QQE2zlong := RSIndex2 >= 50 ? QQE2zlong + 1 : 0 QQE2zshort := RSIndex2 < 50 ? QQE2zshort + 1 : 0 // hcolor2 = RsiMa2 - 50 > ThreshHold2 ? color.silver : RsiMa2 - 50 < 0 - ThreshHold2 ? color.silver : na Greenbar1 = RsiMa2 - 50 > ThreshHold2 Greenbar2 = RsiMa - 50 > upper Redbar1 = RsiMa2 - 50 < 0 - ThreshHold2 Redbar2 = RsiMa - 50 < lower // Plot: Indicators //// 1. Super Trend bodyMiddle = plot((open + close) / 2, display=display.none) upTrend = plot(direction < 0 ? supertrend : na, "Up Trend", color = color.green, style=plot.style_linebr) downTrend = plot(direction < 0 ? na : supertrend, "Down Trend", color = color.red, style=plot.style_linebr) fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps=false) fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps=false) //// 2. SSL Hybrid var bullSSLColor = #00c3ff var bearSSLColor = #ff0062 // color_bar = color.new(color = close > upperk ? bullSSLColor : close < lowerk ? bearSSLColor : color.gray, transp = 0) // i_show_color_bar = input.bool(defval = true , title = "Color Bars") // barcolor(i_show_color_bar ? color_bar : na) plot(series = BBMC, title = 'MA Baseline', color = color_bar, linewidth = 1, style = plot.style_line) up_channel = plot(upperk, color=color_bar, title='Baseline Upper Channel') low_channel = plot(lowerk, color=color_bar, title='Basiline Lower Channel') fill(up_channel, low_channel, color.new(color=color_bar, transp=90)) //// 3. QQE MOD: No Plotting because of overlay option // plot(FastAtrRsi2TL - 50, title='QQE Line', color=color.new(color.white, 0), linewidth=2) // plot(RsiMa2 - 50, color=hcolor2, title='Histo2', style=plot.style_columns, transp=50) // plot(Greenbar1 and Greenbar2 == 1 ? RsiMa2 - 50 : na, title='QQE Up', style=plot.style_columns, color=color.new(#00c3ff, 0)) // plot(Redbar1 and Redbar2 == 1 ? RsiMa2 - 50 : na, title='QQE Down', style=plot.style_columns, color=color.new(#ff0062, 0)) ////// Entry, Exit // Long, Short Logic with Indicator bool longSTCond = direction[1] >= 0 and direction <= 0 bool shortSTCond = direction[1] <= 0 and direction >= 0 bool longSSLCond = close > upperk bool shortSSLCond = close < lowerk bool longQQECond = Greenbar1 and Greenbar2 == 1 bool shortQQECond = Redbar1 and Redbar2 == 1 // Basic Cond + Long, Short Entry Condition bool longCond = (i_longEnabled and inTime) and (longSTCond and longSSLCond and longQQECond) bool shortCond = (i_shortEnabled and inTime) and (shortSTCond and shortSSLCond and shortQQECond) // Basic Cond + Long, Short Exit Condition bool closeLong = (i_longEnabled) and (shortSTCond) bool closeShort = (i_shortEnabled) and (longSTCond) // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Position Control // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Long, Short Entry Condition + Not entered Position Yet bool openLong = longCond and not (strategy.opentrades.size(strategy.opentrades - 1) > 0) and longFilterFilled bool openShort = shortCond and not (strategy.opentrades.size(strategy.opentrades - 1) < 0) and shortFilterFilled bool enteringTrade = openLong or openShort float entryBarIndex = bar_index // Long, Short Entry Fulfilled or Already Entered bool inLong = openLong or strategy.opentrades.size(strategy.opentrades - 1) > 0 and not closeLong bool inShort = openShort or strategy.opentrades.size(strategy.opentrades - 1) < 0 and not closeShort // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Stop Loss - Inputs, Indicaotrs // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ //// Use SL? TSL? i_useSLTP = input.bool (defval = true, title = "Enable SL & TP?", tooltip = "", inline = "1", group = "Stop Loss") i_tslEnabled = input.bool (defval = false , title = "Enable Trailing SL?", tooltip = "Enable Stop Loss & Take Profit? \n\Enable Trailing SL?", inline = "1", group = "Stop Loss") // i_breakEvenAfterTP = input.bool (defval = false, title = 'Enable Break Even After TP?', tooltip = 'When Take Profit price target is hit, move the Stop Loss to the entry price (or to a more strict price defined by the Stop Loss %/ATR Multiplier).', inline = '2', group = 'Stop Loss / Take Profit') //// Sl Options i_slType = input.string (defval = "ATR", title = "Stop Loss Type", options = ["Percent", "ATR", "Previous LL / HH"], tooltip = "Stop Loss based on %? ATR?", inline = "3", group = "Stop Loss") i_slATRLen = input.int (defval = 14, title = "ATR Length", minval = 1 , maxval = 200 , step = 1, inline = "4", group = "Stop Loss") i_slATRMult = input.float (defval = 3, title = "ATR Multiplier", minval = 1 , maxval = 200 , step = 0.1, tooltip = "", inline = "4", group = "Stop Loss") i_slPercent = input.float (defval = 3, title = "Percent", tooltip = "", inline = "5", group = "Stop Loss") i_slLookBack = input.int (defval = 30, title = "Lowest Price Before Entry", group = "Stop Loss", inline = "6", minval = 30, step = 1, tooltip = "Lookback to find the Lowest Price. \nStopLoss is determined by the Lowest price of the look back period. Take Profit is derived from this also by multiplying the StopLoss value by the Risk:Reward multiplier.") // Functions for Stop Loss float openAtr = ta.valuewhen(condition = enteringTrade, source = ta.atr(i_slATRLen), occurrence = 0) float openLowest = ta.valuewhen(condition = openLong, source = ta.lowest(low, i_slLookBack), occurrence = 0) float openHighest = ta.valuewhen(condition = openShort, source = ta.highest(high, i_slLookBack), occurrence = 0) f_getLongSLPrice(source) => switch i_slType "Percent" => source * (1 - (i_slPercent/100)) "ATR" => source - (i_slATRMult * openAtr) "Previous LL / HH" => openLowest => na f_getShortSLPrice(source) => switch i_slType "Percent" => source * (1 + (i_slPercent/100)) "ATR" => source + (i_slATRMult * openAtr) "Previous LL / HH" => openHighest => na // Calculate Stop Loss var float longSLPrice = na var float shortSLPrice = na bool longTPExecuted = false bool shortTPExecuted = false longSLPrice := if (inLong and i_useSLTP) if (openLong) f_getLongSLPrice (close) else // 1. Trailing Stop Loss if i_tslEnabled stopLossPrice = f_getLongSLPrice (high) math.max(stopLossPrice, nz(longSLPrice[1])) // 2. Normal StopLoss else nz(source = longSLPrice[1], replacement = 0) else na shortSLPrice := if (inShort and i_useSLTP) if (openShort) f_getShortSLPrice (close) else // 1. Trailing Stop Loss if i_tslEnabled stopLossPrice = f_getShortSLPrice (low) math.min(stopLossPrice, nz(shortSLPrice[1])) // 2. Normal StopLoss else nz(source = shortSLPrice[1], replacement = 999999.9) else na // Plot: Stop Loss of Long, Short Entry var longSLPriceColor = color.new(color.maroon, 0) plot(series = longSLPrice, title = 'Long Stop Loss', color = longSLPriceColor, linewidth = 1, style = plot.style_linebr, offset = 1) var shortSLPriceColor = color.new(color.maroon, 0) plot(series = shortSLPrice, title = 'Short Stop Loss', color = shortSLPriceColor, linewidth = 1, style = plot.style_linebr, offset = 1) // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Take Profit - Inputs, Indicaotrs // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ i_useTPExit = input.bool (defval = true, title = "Use Take Profit?", tooltip = "", inline = "1", group = "Take Profit") i_RRratio = input.float (defval = 1.8, title = "R:R Ratio", minval = 0.1 , maxval = 200 , step = 0.1, tooltip = "R:R Ratio > Risk Reward Ratio? It will automatically set Take Profit % based on Stop Loss", inline = "2", group = "Take Profit") i_tpQuantityPerc = input.float (defval = 50, title = 'Take Profit Quantity %', minval = 0.0, maxval = 100, step = 1.0, tooltip = '% of position closed when tp target is met.', inline="34", group = 'Take Profit') var float longTPPrice = na var float shortTPPrice = na f_getLongTPPrice() => close + i_RRratio * math.abs (close - f_getLongSLPrice (close)) f_getShortTPPrice() => close - i_RRratio * math.abs(close - f_getShortSLPrice (close)) longTPPrice := if (inLong and i_useSLTP) if (openLong) f_getLongTPPrice () else nz(source = longTPPrice[1], replacement = f_getLongTPPrice ()) else na shortTPPrice := if (inShort and i_useSLTP) if (openShort) f_getShortTPPrice () else nz(source = shortTPPrice[1], replacement = f_getShortTPPrice ()) else na // Plot: Take Profit of Long, Short Entry var longTPPriceColor = color.new(color.teal, 0) plot(series = longTPPrice, title = 'Long Take Profit', color = longTPPriceColor, linewidth = 1, style = plot.style_linebr, offset = 1) var shortTPPriceColor = color.new(color.teal, 0) plot(series = shortTPPrice, title = 'Short Take Profit', color = shortTPPriceColor, linewidth = 1, style = plot.style_linebr, offset = 1) // Plot: Entry Price var posColor = color.new(color.white, 0) plot(series = strategy.opentrades.entry_price(strategy.opentrades - 1), title = 'Position Entry Price', color = posColor, linewidth = 1, style = plot.style_linebr) // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Quantity - Inputs // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ i_useRiskManangement = input.bool (defval = true, title = "Use Risk Manangement?", tooltip = "", inline = "1", group = "Quantity") i_riskPerTrade = input.float (defval = 3, title = "Risk Per Trade (%)", minval = 0, maxval = 100, step = 0.1, tooltip = "Use Risk Manangement by Quantity Control?", inline = "2", group = "Quantity") // i_leverage = input.float (defval = 2, title = "Leverage", minval = 0, maxval = 100, step = 0.1, tooltip = "Leverage", inline = "3", group = "Quantity") float qtyPercent = na float entryQuantity = na f_calQtyPerc() => if (i_useRiskManangement) riskPerTrade = (i_riskPerTrade) / 100 // 1번 κ±°λž˜μ‹œ 3% 손싀 stopLossPrice = openLong ? f_getLongSLPrice (close) : openShort ? f_getShortSLPrice (close) : na riskExpected = math.abs((close-stopLossPrice)/close) // μ†μ ˆκ°€λž‘ 6% 차이 riskPerTrade / riskExpected // 0 ~ 1 else 1 f_calQty(qtyPerc) => math.min (math.max (0.000001, strategy.equity / close * qtyPerc), 1000000000) // TP Execution longTPExecuted := strategy.opentrades.size(strategy.opentrades - 1) > 0 and (longTPExecuted[1] or strategy.opentrades.size(strategy.opentrades - 1) < strategy.opentrades.size(strategy.opentrades - 1)[1] or strategy.opentrades.size(strategy.opentrades - 1)[1] == 0 and high >= longTPPrice) shortTPExecuted := strategy.opentrades.size(strategy.opentrades - 1) < 0 and (shortTPExecuted[1] or strategy.opentrades.size(strategy.opentrades - 1) > strategy.opentrades.size(strategy.opentrades - 1)[1] or strategy.opentrades.size(strategy.opentrades - 1)[1] == 0 and low <= shortTPPrice) // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Plot Label, Boxes, Results, Etc // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ i_showSimpleLabel = input.bool(false, "Show Simple Label for Entry?", group = "Strategy: Drawings", inline = "1", tooltip ="") i_showLabels = input.bool(true, "Show Trade Exit Labels", group = "Strategy: Drawings", inline = "1", tooltip = "Useful labels to identify Profit/Loss and cumulative portfolio capital after each trade closes.\n\nAlso note that TradingView limits the max number of 'boxes' that can be displayed on a chart (max 500). This means when you lookback far enough on the chart you will not see the TP/SL boxes. However you can check this option to identify where trades exited.") i_showDashboard = input.bool(true, "Show Dashboard", group = "Strategy: Drawings", inline = "2", tooltip = "Show Backtest Results. Backtest Dates, Win/Lose Rates, Etc.") // Plot: Label for Long, Short Entry var openLongColor = color.new(#2962FF, 0) var openShortColor = color.new(#FF1744, 0) var entryTextColor = color.new(color.white, 0) if (openLong and i_showSimpleLabel) label.new (x = bar_index, y = na, text = 'Open', yloc = yloc.belowbar, color = openLongColor, style = label.style_label_up, textcolor = entryTextColor) entryBarIndex := bar_index if (openShort and i_showSimpleLabel) label.new (x = bar_index, y = na, text = 'Close', yloc = yloc.abovebar, color = openShortColor, style = label.style_label_down, textcolor = entryTextColor) entryBarIndex := bar_index float prevEntryPrice = strategy.closedtrades.entry_price (strategy.closedtrades - 1) float pnl = strategy.closedtrades.profit (strategy.closedtrades - 1) float prevExitPrice = strategy.closedtrades.exit_price (strategy.closedtrades - 1) f_enteringTradeLabel(x, y, qty, entryPrice, slPrice, tpPrice, rrRatio, direction) => if i_showLabels labelStr = ("Trade Start" + "\nDirection: " + direction + "\nRisk Per Trade: " + str.tostring (i_useRiskManangement ? i_riskPerTrade : 100, "#.##") + "%" + "\nExpected Risk: " + str.tostring (math.abs((close-slPrice)/close) * 100, "#.##") + "%" + "\nEntry Position Qty: " + str.tostring(math.abs(qty * 100), "#.##") + "%" + "\nEntry Price: " + str.tostring(entryPrice, "#.##")) + "\nStop Loss Price: " + str.tostring(slPrice, "#.##") + "\nTake Profit Price: " + str.tostring(tpPrice, "#.##") + "\nRisk - Reward Ratio: " + str.tostring(rrRatio, "#.##") label.new(x = x, y = y, text = labelStr, color = color.new(color.blue, 60) , textcolor = color.white, style = label.style_label_up) f_exitingTradeLabel(x, y, entryPrice, exitPrice, direction) => if i_showLabels labelStr = ("Trade Result" + "\nDirection: " + direction + "\nEntry Price: " + str.tostring(entryPrice, "#.##") + "\nExit Price: " + str.tostring(exitPrice,"#.##") + "\nGain %: " + str.tostring(direction == 'Long' ? -(entryPrice-exitPrice) / entryPrice * 100 : (entryPrice-exitPrice) / entryPrice * 100 ,"#.##") + "%") label.new(x = x, y = y, text = labelStr, color = pnl > 0 ? color.new(color.green, 60) : color.new(color.red, 60), textcolor = color.white, style = label.style_label_down) f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) => _cellText = _title + " " + _value table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor, text_size=size.auto) // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Orders // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ if (inTime) if (openLong) qtyPercent := f_calQtyPerc() entryQuantity := f_calQty(qtyPercent) strategy.entry(id = "Long", direction = strategy.long, qty = entryQuantity, comment = 'Long(' + syminfo.ticker + '): Started', alert_message = 'Long(' + syminfo.ticker + '): Started') f_enteringTradeLabel(x = bar_index + 1, y = close-3*ta.tr, entryPrice = close, qty = qtyPercent, slPrice = longSLPrice, tpPrice = longTPPrice, rrRatio = i_RRratio, direction = "Long") if (openShort) qtyPercent := f_calQtyPerc() entryQuantity := f_calQty(qtyPercent) strategy.entry(id = "Short", direction = strategy.short, qty = entryQuantity, comment = 'Short(' + syminfo.ticker + '): Started', alert_message = 'Short(' + syminfo.ticker + '): Started') f_enteringTradeLabel(x = bar_index + 1, y = close-3*ta.tr, entryPrice = close, qty = qtyPercent, slPrice = shortSLPrice, tpPrice = shortTPPrice, rrRatio = i_RRratio, direction = "Short") if (closeLong) strategy.close(id = 'Long', comment = 'Close Long', alert_message = 'Long: Closed at market price') strategy.position_size > 0 ? f_exitingTradeLabel(x = bar_index, y = close+3*ta.tr, entryPrice = prevEntryPrice, exitPrice = prevExitPrice, direction = 'Long') : na if (closeShort) strategy.close(id = 'Short', comment = 'Close Short', alert_message = 'Short: Closed at market price') strategy.position_size < 0 ? f_exitingTradeLabel(x = bar_index, y = close+3*ta.tr, entryPrice = prevEntryPrice, exitPrice = prevExitPrice, direction = 'Short') : na if (inLong) strategy.exit(id = 'Long TP / SL', from_entry = 'Long', qty_percent = i_tpQuantityPerc, limit = longTPPrice, stop = longSLPrice, alert_message = 'Long(' + syminfo.ticker + '): Take Profit or Stop Loss executed') strategy.exit(id = 'Long SL', from_entry = 'Long', stop = longSLPrice, alert_message = 'Long(' + syminfo.ticker + '): Stop Loss executed') if (inShort) strategy.exit(id = 'Short TP / SL', from_entry = 'Short', qty_percent = i_tpQuantityPerc, limit = shortTPPrice, stop = shortSLPrice, alert_message = 'Short(' + syminfo.ticker + '): Take Profit or Stop Loss executed') strategy.exit(id = 'Short SL', from_entry = 'Short', stop = shortSLPrice, alert_message = 'Short(' + syminfo.ticker + '): Stop Loss executed') if strategy.position_size[1] > 0 and strategy.position_size == 0 f_exitingTradeLabel(x = bar_index, y = close+3*ta.tr, entryPrice = prevEntryPrice, exitPrice = prevExitPrice, direction = 'Long') if strategy.position_size[1] < 0 and strategy.position_size == 0 f_exitingTradeLabel(x = bar_index, y = close+3*ta.tr, entryPrice = prevEntryPrice, exitPrice = prevExitPrice, direction = 'Short') // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Backtest Result Dashboard // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ if i_showDashboard var bgcolor = color.new(color = color.black, transp = 100) var greenColor = color.new(color = #02732A, transp = 0) var redColor = color.new(color = #D92332, transp = 0) var yellowColor = color.new(color = #F2E313, transp = 0) // Keep track of Wins/Losses streaks newWin = (strategy.wintrades > strategy.wintrades[1]) and (strategy.losstrades == strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1]) newLoss = (strategy.wintrades == strategy.wintrades[1]) and (strategy.losstrades > strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1]) varip int winRow = 0 varip int lossRow = 0 varip int maxWinRow = 0 varip int maxLossRow = 0 if newWin lossRow := 0 winRow := winRow + 1 if winRow > maxWinRow maxWinRow := winRow if newLoss winRow := 0 lossRow := lossRow + 1 if lossRow > maxLossRow maxLossRow := lossRow // Prepare stats table var table dashTable = table.new(position.top_right, 1, 15, border_width=1) if barstate.islastconfirmedhistory dollarReturn = strategy.netprofit f_fillCell(dashTable, 0, 0, "Start:", str.format("{0,date,long}", strategy.closedtrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.closedtrades.entry_time(0)) f_fillCell(dashTable, 0, 1, "End:", str.format("{0,date,long}", strategy.opentrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.opentrades.entry_time(0)) _profit = (strategy.netprofit / strategy.initial_capital) * 100 f_fillCell(dashTable, 0, 2, "Net Profit:", str.tostring(_profit, '##.##') + "%", _profit > 0 ? greenColor : redColor, color.white) _numOfDaysInStrategy = (strategy.opentrades.entry_time(0) - strategy.closedtrades.entry_time(0)) / (1000 * 3600 * 24) f_fillCell(dashTable, 0, 3, "Percent Per Day", str.tostring(_profit / _numOfDaysInStrategy, '#########################.#####')+"%", _profit > 0 ? greenColor : redColor, color.white) _winRate = ( strategy.wintrades / strategy.closedtrades ) * 100 f_fillCell(dashTable, 0, 4, "Percent Profitable:", str.tostring(_winRate, '##.##') + "%", _winRate < 50 ? redColor : _winRate < 75 ? greenColor : yellowColor, color.white) f_fillCell(dashTable, 0, 5, "Profit Factor:", str.tostring(strategy.grossprofit / strategy.grossloss, '##.###'), strategy.grossprofit > strategy.grossloss ? greenColor : redColor, color.white) f_fillCell(dashTable, 0, 6, "Total Trades:", str.tostring(strategy.closedtrades), bgcolor, color.white) f_fillCell(dashTable, 0, 8, "Max Wins In A Row:", str.tostring(maxWinRow, '######') , bgcolor, color.white) f_fillCell(dashTable, 0, 9, "Max Losses In A Row:", str.tostring(maxLossRow, '######') , bgcolor, color.white)
[DuDu95] SSL 4C MACD Laugerre RSI Strategy
https://www.tradingview.com/script/BckFbevb/
DuDu95
https://www.tradingview.com/u/DuDu95/
113
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© DuDu95 // Thanks to myncrypto, jason5480, kevinmck100 // @version=5 strategy(title = '[DuDu95] SSL 4C MACD Laugerre RSI Strategy', shorttitle = '[D] SMR Strategy', overlay = true, pyramiding = 0, currency = currency.USD, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_value = 0.1, initial_capital = 100000, max_bars_back = 500, max_lines_count = 150, max_labels_count = 300) // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Time, Direction, Etc - Basic Settings Inputs // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // 1. Time: Based on UTC +09:00 i_start = input.time (defval = timestamp("20 Jan 1990 00:00 +0900"), title = "Start Date", tooltip = "Choose Backtest Start Date", inline = "Start Date", group = "Time" ) i_end = input.time (defval = timestamp("20 Dec 2030 00:00 +0900"), title = "End Date", tooltip = "Choose Backtest End Date", inline = "End Date", group = "Time" ) inTime = time >= i_start and time <= i_end // 2. Inputs for direction: Long? Short? Both? i_longEnabled = input.bool (defval = true , title = "Long?", tooltip = "Enable Long Position Trade?", inline = "Long / Short", group = "Long / Short" ) i_shortEnabled = input.bool (defval = true , title = "Short?", tooltip = "Enable Short Position Trade?", inline = "Long / Short", group = "Long / Short" ) // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Filter - Inputs, Indicaotrs // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // 3. Use Filters? What Filters? i_ATRFilterOn = input.bool (defval = false , title = "ATR Filter On?", tooltip = "ATR Filter On? Order will not be made unless filter condition is fulfilled", inline = "1", group = "Filters") i_ATRFilterLen = input.int (defval = 14 , title = "Length for ATR Filter", minval = 1 , maxval = 100 , step = 1 , tooltip = "", inline = "2", group = "Filters") i_ATRSMALen = input.int (defval = 40 , title = "SMA Length for ATR SMA", minval = 1 , maxval = 100000 , step = 1 , tooltip = "ATR should be bigger than this", inline = "2", group = "Filters") bool i_ATRFilter = ta.atr(i_ATRFilterLen) >= ta.sma(ta.atr(length = i_ATRFilterLen), i_ATRSMALen) ? true : false bool filterFulfilled = not i_ATRFilterOn or i_ATRFilter // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Strategy Logic (Entry & Exit Condition) - Inputs, Indicators for Strategy // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Inputs for Strategy Indicators //// 1. SSL Hybrid Baseline i_useTrueRange = input.bool (defval = true, title = "use true range for Keltner Channel?", tooltip = "", inline = "1", group = "1: SSL Hybrid") i_maType = input.string (defval ='EMA', title='Baseline Type', options=['SMA', 'EMA', 'DEMA', 'TEMA', 'LSMA', 'WMA', 'VAMA', 'TMA', 'HMA', 'McGinley'], inline="2", group = "1: SSL Hybrid") i_len = input.int (defval =30, title='Baseline Length', inline="2", group = "1: SSL Hybrid") i_multy = input.float (defval = 0.2, title='Base Channel Multiplier', minval = 0, maxval = 100, step=0.05, inline="3", group = "1: SSL Hybrid") i_volatility_lookback = input.int (defval =10, title='Volatility lookback length(for VAMA)', inline='4',group="1: SSL Hybrid") tema(src, len) => ema1 = ta.ema(src, len) ema2 = ta.ema(ema1, len) ema3 = ta.ema(ema2, len) 3 * ema1 - 3 * ema2 + ema3 f_ma(type, src, len) => float result = 0 if type == 'TMA' result := ta.sma(ta.sma(src, math.ceil(len / 2)), math.floor(len / 2) + 1) result if type == 'LSMA' result := ta.linreg(src, len, 0) result if type == 'SMA' // Simple result := ta.sma(src, len) result if type == 'EMA' // Exponential result := ta.ema(src, len) result if type == 'DEMA' // Double Exponential e = ta.ema(src, len) result := 2 * e - ta.ema(e, len) result if type == 'TEMA' // Triple Exponential e = ta.ema(src, len) result := 3 * (e - ta.ema(e, len)) + ta.ema(ta.ema(e, len), len) result if type == 'WMA' // Weighted result := ta.wma(src, len) result if type == 'VAMA' // Volatility Adjusted /// Copyright Β© 2019 to present, Joris Duyck (JD) mid = ta.ema(src, len) dev = src - mid vol_up = ta.highest(dev, i_volatility_lookback) vol_down = ta.lowest(dev, i_volatility_lookback) result := mid + math.avg(vol_up, vol_down) result if type == 'HMA' // Hull result := ta.wma(2 * ta.wma(src, len / 2) - ta.wma(src, len), math.round(math.sqrt(len))) result if type == 'McGinley' mg = 0.0 mg := na(mg[1]) ? ta.ema(src, len) : mg[1] + (src - mg[1]) / (len * math.pow(src / mg[1], 4)) result := mg result result //// 1-1. SSL Hybrid Keltner Baseline Channel BBMC = f_ma (i_maType, close, i_len) // BaseLone Keltma = f_ma (i_maType, close, i_len) range_1 = i_useTrueRange ? ta.tr : high - low rangema = ta.ema(range_1, i_len) upperk = Keltma + rangema * i_multy lowerk = Keltma - rangema * i_multy //// 2. 4 Color MACD i_fastMA = input.int (defval=12, title='MACD fast MA', minval=7, inline = '1' , group = '2: 4 Color MACD') i_slowMA = input.int (defval=26, title='MACD slow MA', minval=7, inline = '1' , group = '2: 4 Color MACD') i_signalLength = input.int (defval=9, title='MACD signal Length', minval=1, inline = '2' , group = '2: 4 Color MACD') [currMacd, _, _] = ta.macd (source = close[0], fastlen = i_fastMA, slowlen = i_slowMA, siglen = 9) [prevMacd, _, _] = ta.macd (source = close[1], fastlen = i_fastMA, slowlen = i_slowMA, siglen = 9) signalLine = ta.sma (currMacd, i_signalLength) //// 3. Laguerre RSI i_src = input (defval=close, title='Laguerre RSI source', inline = '1' , group = '3: Laguerre RSI') i_alpha = input.float (defval=0.2, title='Alpha', inline = '2', minval = 0, maxval = 1, step = 0.1, group = '3: Laguerre RSI') i_overbought = input.int (defval=80, title='Overbought Level?', minval=50, maxval = 99, inline = '4' , group = '3: Laguerre RSI') i_oversold = input.int (defval=20, title='Overbought Level?', minval=0, maxval = 50, inline = '4' , group = '3: Laguerre RSI') // i_colorchange = input.bool (defval=false, title='Change Color?', inline = '3' , group = '3: Laguerre RSI') float LaRSIResult = 0 gamma = 1 - i_alpha L0 = 0.0 L0 := (1 - gamma) * i_src + gamma * nz(L0[1]) L1 = 0.0 L1 := -gamma * L0 + nz(L0[1]) + gamma * nz(L1[1]) L2 = 0.0 L2 := -gamma * L1 + nz(L1[1]) + gamma * nz(L2[1]) L3 = 0.0 L3 := -gamma * L2 + nz(L2[1]) + gamma * nz(L3[1]) cu = (L0 > L1 ? L0 - L1 : 0) + (L1 > L2 ? L1 - L2 : 0) + (L2 > L3 ? L2 - L3 : 0) cd = (L0 < L1 ? L1 - L0 : 0) + (L1 < L2 ? L2 - L1 : 0) + (L2 < L3 ? L3 - L2 : 0) temp = cu + cd == 0 ? -1 : cu + cd LaRSI = temp == -1 ? 0 : cu / temp LaRSIResult := LaRSI * 100 // Entry Condition for Long and Short //// 1. Condition 1: SSL Hybrid bool bullSSL = close > upperk bool bearSSL = close < lowerk //// 2. Condition 2: 4 Color MACD bool bullSignalMACD = signalLine > 0 bool bearSignalMACD = signalLine < 0 bool bull4cMACD = currMacd > prevMacd and prevMacd > 0 bool bear4cMACD = currMacd < prevMacd and prevMacd < 0 //// 3. Condition 3 bool bullLaRSI = LaRSIResult < i_overbought bool bearLaRSI = LaRSIResult > i_oversold // Plot: Indicators //// 1. SSL Hybrid var bullSSLColor = #00c3ff var bearSSLColor = #ff0062 color_bar = color.new(color = close > upperk ? bullSSLColor : close < lowerk ? bearSSLColor : color.gray, transp = 0) plot(series = BBMC, title = 'MA Baseline', color = color_bar, linewidth = 1, style = plot.style_line) i_show_color_bar = input.bool(defval = true , title = "Color Bars",inline = "2", group = "Strategy: Drawings") barcolor(i_show_color_bar ? color_bar : na) up_channel = plot(upperk, color=color_bar, title='Baseline Upper Channel') low_channel = plot(lowerk, color=color_bar, title='Basiline Lower Channel') fill(up_channel, low_channel, color.new(color=color_bar, transp=90)) //// 2. MACD Line var bull4cMACDColor = color.lime var bear4cMACDColor = color.orange MACDbgColor = color.new (color = bull4cMACD and bullSignalMACD ? bull4cMACDColor : bear4cMACD and bearSignalMACD ? bear4cMACDColor : na, transp = not bull4cMACD and not bear4cMACD ? 100 : 80) bgcolor(color = MACDbgColor, title = "MACD Condition") // plotColor = currMacd > 0 ? currMacd > prevMacd ? color.lime : color.green : currMacd < prevMacd ? color.maroon : color.red // plot(currMacd, style=plot.style_columns, color=color.new(plotColor,20), linewidth=3) // plot(0, title='Zero line', linewidth=1, color=color.new(color.gray, 0)) // plot(signalLine, color=color.new(color.white, 0), title='Signal') //// 3. Laguerre RSI var overboughtColor = color.blue var oversoldColor = color.aqua LaRSIColor = color.new(color = LaRSIResult > i_overbought ? overboughtColor : LaRSIResult < i_oversold ? oversoldColor : na, transp = 90) bgcolor (color = LaRSIColor, title = "LaRSI Condition") // lineColor = i_colorchange ? LaRSI > LaRSI[1] ? color.green : color.red : color.teal // plot(LaRSIResult, title='LaRSI', linewidth=2, color=color.new(color=lineColor,transp=0)) // plot(i_oversold, linewidth=1, color=color.new(color.maroon, 0)) // plot(i_overbought, linewidth=1, color=color.new(color.maroon, 0)) ////// Entry, Exit // Long, Short Logic with Indicator // Basic Cond + Long, Short Entry Condition bool longCond = (i_longEnabled and inTime) and (bullSSL and bullSignalMACD and bull4cMACD and bullLaRSI) bool shortCond = (i_shortEnabled and inTime) and (bearSSL and bearSignalMACD and bear4cMACD and bearLaRSI) // Basic Cond + Long, Short Exit Condition bool closeLong = (i_longEnabled) and (bearSSL or bearSignalMACD) bool closeShort = (i_shortEnabled) and (bullSSL or bullSignalMACD) // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Position Control // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Long, Short Entry Condition + Not entered Position Yet bool openLong = longCond and not (strategy.opentrades.size(strategy.opentrades - 1) > 0) and filterFulfilled bool openShort = shortCond and not (strategy.opentrades.size(strategy.opentrades - 1) < 0) and filterFulfilled bool enteringTrade = openLong or openShort float entryBarIndex = bar_index // Long, Short Entry Fulfilled or Already Entered bool inLong = openLong or strategy.opentrades.size(strategy.opentrades - 1) > 0 and not closeLong bool inShort = openShort or strategy.opentrades.size(strategy.opentrades - 1) < 0 and not closeShort // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Stop Loss - Inputs, Indicaotrs // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ //// Use SL? TSL? i_useSLTP = input.bool (defval = true, title = "Enable SL & TP?", tooltip = "", inline = "1", group = "Stop Loss") i_tslEnabled = input.bool (defval = false , title = "Enable Trailing SL?", tooltip = "Enable Stop Loss & Take Profit? \n\Enable Trailing SL?", inline = "1", group = "Stop Loss") // i_breakEvenAfterTP = input.bool (defval = false, title = 'Enable Break Even After TP?', tooltip = 'When Take Profit price target is hit, move the Stop Loss to the entry price (or to a more strict price defined by the Stop Loss %/ATR Multiplier).', inline = '2', group = 'Stop Loss / Take Profit') //// Sl Options i_slType = input.string (defval = "ATR", title = "Stop Loss Type", options = ["Percent", "ATR", "Previous LL / HH"], tooltip = "Stop Loss based on %? ATR?", inline = "3", group = "Stop Loss") i_slATRLen = input.int (defval = 14, title = "ATR Length", minval = 1 , maxval = 200 , step = 1, inline = "4", group = "Stop Loss") i_slATRMult = input.float (defval = 3, title = "ATR Multiplier", minval = 1 , maxval = 200 , step = 0.1, tooltip = "", inline = "4", group = "Stop Loss") i_slPercent = input.float (defval = 3, title = "Percent", tooltip = "", inline = "5", group = "Stop Loss") i_slLookBack = input.int (defval = 30, title = "Lowest / Highest Price Before Entry", group = "Stop Loss", inline = "6", minval = 1, maxval=200, step = 1, tooltip = "Lookback to find the Lowest Price. \nStopLoss is determined by the Lowest price of the look back period. Take Profit is derived from this also by multiplying the StopLoss value by the Risk:Reward multiplier.") // Functions for Stop Loss float openAtr = ta.valuewhen(condition = enteringTrade, source = ta.atr(i_slATRLen), occurrence = 0) float openLowest = ta.valuewhen(condition = openLong, source = ta.lowest(low, i_slLookBack), occurrence = 0) float openHighest = ta.valuewhen(condition = openShort, source = ta.highest(high, i_slLookBack), occurrence = 0) f_getLongSLPrice(source) => switch i_slType "Percent" => source * (1 - (i_slPercent/100)) "ATR" => source - (i_slATRMult * openAtr) "Previous LL / HH" => openLowest => na f_getShortSLPrice(source) => switch i_slType "Percent" => source * (1 + (i_slPercent/100)) "ATR" => source + (i_slATRMult * openAtr) "Previous LL / HH" => openHighest => na // Calculate Stop Loss var float longSLPrice = na var float shortSLPrice = na bool longTPExecuted = false bool shortTPExecuted = false longSLPrice := if (inLong and i_useSLTP) if (openLong) f_getLongSLPrice (close) else // 1. Trailing Stop Loss if i_tslEnabled stopLossPrice = f_getLongSLPrice (high) math.max(stopLossPrice, nz(longSLPrice[1])) // 2. Normal StopLoss else nz(source = longSLPrice[1], replacement = 0) else na shortSLPrice := if (inShort and i_useSLTP) if (openShort) f_getShortSLPrice (close) else // 1. Trailing Stop Loss if i_tslEnabled stopLossPrice = f_getShortSLPrice (low) math.min(stopLossPrice, nz(shortSLPrice[1])) // 2. Normal StopLoss else nz(source = shortSLPrice[1], replacement = 999999.9) else na // Plot: Stop Loss of Long, Short Entry var longSLPriceColor = color.new(color.maroon, 0) plot(series = longSLPrice, title = 'Long Stop Loss', color = longSLPriceColor, linewidth = 1, style = plot.style_linebr, offset = 1) var shortSLPriceColor = color.new(color.maroon, 0) plot(series = shortSLPrice, title = 'Short Stop Loss', color = shortSLPriceColor, linewidth = 1, style = plot.style_linebr, offset = 1) // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Take Profit - Inputs, Indicaotrs // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ i_useTPExit = input.bool (defval = true, title = "Use Take Profit?", tooltip = "", inline = "1", group = "Take Profit") i_RRratio = input.float (defval = 1.8, title = "R:R Ratio", minval = 0.1 , maxval = 200 , step = 0.1, tooltip = "R:R Ratio > Risk Reward Ratio? It will automatically set Take Profit % based on Stop Loss", inline = "2", group = "Take Profit") i_tpQuantityPerc = input.float (defval = 50, title = 'Take Profit Quantity %', minval = 0.0, maxval = 100, step = 1.0, tooltip = '% of position closed when tp target is met.', inline="34", group = 'Take Profit') var float longTPPrice = na var float shortTPPrice = na f_getLongTPPrice() => close + i_RRratio * math.abs (close - f_getLongSLPrice (close)) f_getShortTPPrice() => close - i_RRratio * math.abs(close - f_getShortSLPrice (close)) longTPPrice := if (inLong and i_useSLTP) if (openLong) f_getLongTPPrice () else nz(source = longTPPrice[1], replacement = f_getLongTPPrice ()) else na shortTPPrice := if (inShort and i_useSLTP) if (openShort) f_getShortTPPrice () else nz(source = shortTPPrice[1], replacement = f_getShortTPPrice ()) else na // Plot: Take Profit of Long, Short Entry var longTPPriceColor = color.new(color.teal, 0) plot(series = longTPPrice, title = 'Long Take Profit', color = longTPPriceColor, linewidth = 1, style = plot.style_linebr, offset = 1) var shortTPPriceColor = color.new(color.teal, 0) plot(series = shortTPPrice, title = 'Short Take Profit', color = shortTPPriceColor, linewidth = 1, style = plot.style_linebr, offset = 1) // Plot: Entry Price var posColor = color.new(color.white, 0) plot(series = strategy.opentrades.entry_price(strategy.opentrades - 1), title = 'Position Entry Price', color = posColor, linewidth = 1, style = plot.style_linebr) // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Quantity - Inputs // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ i_useRiskManangement = input.bool (defval = true, title = "Use Risk Manangement?", tooltip = "", inline = "1", group = "Quantity") i_riskPerTrade = input.float (defval = 3, title = "Risk Per Trade (%)", minval = 0, maxval = 100, step = 0.1, tooltip = "Use Risk Manangement by Quantity Control?", inline = "2", group = "Quantity") // i_leverage = input.float (defval = 2, title = "Leverage", minval = 0, maxval = 100, step = 0.1, tooltip = "Leverage", inline = "3", group = "Quantity") float qtyPercent = na float entryQuantity = na f_calQtyPerc() => if (i_useRiskManangement) riskPerTrade = (i_riskPerTrade) / 100 // 1번 κ±°λž˜μ‹œ 3% 손싀 stopLossPrice = openLong ? f_getLongSLPrice (close) : openShort ? f_getShortSLPrice (close) : na riskExpected = math.abs((close-stopLossPrice)/close) // μ†μ ˆκ°€λž‘ 6% 차이 riskPerTrade / riskExpected // 0 ~ 1 else 1 f_calQty(qtyPerc) => math.min (math.max (0.000001, strategy.equity / close * qtyPerc), 1000000000) // TP Execution longTPExecuted := strategy.opentrades.size(strategy.opentrades - 1) > 0 and (longTPExecuted[1] or strategy.opentrades.size(strategy.opentrades - 1) < strategy.opentrades.size(strategy.opentrades - 1)[1] or strategy.opentrades.size(strategy.opentrades - 1)[1] == 0 and high >= longTPPrice) shortTPExecuted := strategy.opentrades.size(strategy.opentrades - 1) < 0 and (shortTPExecuted[1] or strategy.opentrades.size(strategy.opentrades - 1) > strategy.opentrades.size(strategy.opentrades - 1)[1] or strategy.opentrades.size(strategy.opentrades - 1)[1] == 0 and low <= shortTPPrice) // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Plot Label, Boxes, Results, Etc // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ i_showSimpleLabel = input.bool(false, "Show Simple Label for Entry?", group = "Strategy: Drawings", inline = "1", tooltip ="") i_showLabels = input.bool(true, "Show Trade Exit Labels", group = "Strategy: Drawings", inline = "1", tooltip = "Useful labels to identify Profit/Loss and cumulative portfolio capital after each trade closes.\n\nAlso note that TradingView limits the max number of 'boxes' that can be displayed on a chart (max 500). This means when you lookback far enough on the chart you will not see the TP/SL boxes. However you can check this option to identify where trades exited.") i_showDashboard = input.bool(true, "Show Dashboard", group = "Strategy: Drawings", inline = "2", tooltip = "Show Backtest Results. Backtest Dates, Win/Lose Rates, Etc.") // Plot: Label for Long, Short Entry var openLongColor = color.new(#2962FF, 0) var openShortColor = color.new(#FF1744, 0) var entryTextColor = color.new(color.white, 0) if (openLong and i_showSimpleLabel) label.new (x = bar_index, y = na, text = 'Open', yloc = yloc.belowbar, color = openLongColor, style = label.style_label_up, textcolor = entryTextColor) entryBarIndex := bar_index if (openShort and i_showSimpleLabel) label.new (x = bar_index, y = na, text = 'Close', yloc = yloc.abovebar, color = openShortColor, style = label.style_label_down, textcolor = entryTextColor) entryBarIndex := bar_index float prevEntryPrice = strategy.closedtrades.entry_price (strategy.closedtrades - 1) float pnl = strategy.closedtrades.profit (strategy.closedtrades - 1) float prevExitPrice = strategy.closedtrades.exit_price (strategy.closedtrades - 1) f_enteringTradeLabel(x, y, qty, entryPrice, slPrice, tpPrice, rrRatio, direction) => if i_showLabels labelStr = ("Trade Start" + "\nDirection: " + direction + "\nRisk Per Trade: " + str.tostring (i_useRiskManangement ? i_riskPerTrade : 100, "#.##") + "%" + "\nExpected Risk: " + str.tostring (math.abs((close-slPrice)/close) * 100, "#.##") + "%" + "\nEntry Position Qty: " + str.tostring(math.abs(qty * 100), "#.##") + "%" + "\nEntry Price: " + str.tostring(entryPrice, "#.##")) + "\nStop Loss Price: " + str.tostring(slPrice, "#.##") + "\nTake Profit Price: " + str.tostring(tpPrice, "#.##") + "\nRisk - Reward Ratio: " + str.tostring(rrRatio, "#.##") label.new(x = x, y = y, text = labelStr, color = color.new(color.blue, 60) , textcolor = color.white, style = label.style_label_up) f_exitingTradeLabel(x, y, entryPrice, exitPrice, direction) => if i_showLabels labelStr = ("Trade Result" + "\nDirection: " + direction + "\nEntry Price: " + str.tostring(entryPrice, "#.##") + "\nExit Price: " + str.tostring(exitPrice,"#.##") + "\nGain %: " + str.tostring(direction == 'Long' ? -(entryPrice-exitPrice) / entryPrice * 100 : (entryPrice-exitPrice) / entryPrice * 100 ,"#.##") + "%") label.new(x = x, y = y, text = labelStr, color = pnl > 0 ? color.new(color.green, 60) : color.new(color.red, 60), textcolor = color.white, style = label.style_label_down) f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) => _cellText = _title + " " + _value table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor, text_size=size.auto) // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Orders // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ if (inTime) if (openLong) qtyPercent := f_calQtyPerc() entryQuantity := f_calQty(qtyPercent) strategy.entry(id = "Long", direction = strategy.long, qty = entryQuantity, comment = 'Long(' + syminfo.ticker + '): Started', alert_message = 'Long(' + syminfo.ticker + '): Started') f_enteringTradeLabel(x = bar_index + 1, y = close-3*ta.tr, entryPrice = close, qty = qtyPercent, slPrice = longSLPrice, tpPrice = longTPPrice, rrRatio = i_RRratio, direction = "Long") if (openShort) qtyPercent := f_calQtyPerc() entryQuantity := f_calQty(qtyPercent) strategy.entry(id = "Short", direction = strategy.short, qty = entryQuantity, comment = 'Short(' + syminfo.ticker + '): Started', alert_message = 'Short(' + syminfo.ticker + '): Started') f_enteringTradeLabel(x = bar_index + 1, y = close-3*ta.tr, entryPrice = close, qty = qtyPercent, slPrice = shortSLPrice, tpPrice = shortTPPrice, rrRatio = i_RRratio, direction = "Short") if (closeLong) strategy.close(id = 'Long', comment = 'Close Long', alert_message = 'Long: Closed at market price') strategy.position_size > 0 ? f_exitingTradeLabel(x = bar_index, y = close+3*ta.tr, entryPrice = prevEntryPrice, exitPrice = prevExitPrice, direction = 'Long') : na if (closeShort) strategy.close(id = 'Short', comment = 'Close Short', alert_message = 'Short: Closed at market price') strategy.position_size < 0 ? f_exitingTradeLabel(x = bar_index, y = close+3*ta.tr, entryPrice = prevEntryPrice, exitPrice = prevExitPrice, direction = 'Short') : na if (inLong) strategy.exit(id = 'Long TP / SL', from_entry = 'Long', qty_percent = i_tpQuantityPerc, limit = longTPPrice, stop = longSLPrice, alert_message = 'Long(' + syminfo.ticker + '): Take Profit or Stop Loss executed') strategy.exit(id = 'Long SL', from_entry = 'Long', stop = longSLPrice, alert_message = 'Long(' + syminfo.ticker + '): Stop Loss executed') if (inShort) strategy.exit(id = 'Short TP / SL', from_entry = 'Short', qty_percent = i_tpQuantityPerc, limit = shortTPPrice, stop = shortSLPrice, alert_message = 'Short(' + syminfo.ticker + '): Take Profit or Stop Loss executed') strategy.exit(id = 'Short SL', from_entry = 'Short', stop = shortSLPrice, alert_message = 'Short(' + syminfo.ticker + '): Stop Loss executed') if strategy.position_size[1] > 0 and strategy.position_size == 0 f_exitingTradeLabel(x = bar_index, y = close+3*ta.tr, entryPrice = prevEntryPrice, exitPrice = prevExitPrice, direction = 'Long') if strategy.position_size[1] < 0 and strategy.position_size == 0 f_exitingTradeLabel(x = bar_index, y = close+3*ta.tr, entryPrice = prevEntryPrice, exitPrice = prevExitPrice, direction = 'Short') // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Backtest Result Dashboard // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ if i_showDashboard var bgcolor = color.new(color = color.black, transp = 100) var greenColor = color.new(color = #02732A, transp = 0) var redColor = color.new(color = #D92332, transp = 0) var yellowColor = color.new(color = #F2E313, transp = 0) // Keep track of Wins/Losses streaks newWin = (strategy.wintrades > strategy.wintrades[1]) and (strategy.losstrades == strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1]) newLoss = (strategy.wintrades == strategy.wintrades[1]) and (strategy.losstrades > strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1]) varip int winRow = 0 varip int lossRow = 0 varip int maxWinRow = 0 varip int maxLossRow = 0 if newWin lossRow := 0 winRow := winRow + 1 if winRow > maxWinRow maxWinRow := winRow if newLoss winRow := 0 lossRow := lossRow + 1 if lossRow > maxLossRow maxLossRow := lossRow // Prepare stats table var table dashTable = table.new(position.top_right, 1, 15, border_width=1) if barstate.islastconfirmedhistory dollarReturn = strategy.netprofit f_fillCell(dashTable, 0, 0, "Start:", str.format("{0,date,long}", strategy.closedtrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.closedtrades.entry_time(0)) f_fillCell(dashTable, 0, 1, "End:", str.format("{0,date,long}", strategy.opentrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.opentrades.entry_time(0)) _profit = (strategy.netprofit / strategy.initial_capital) * 100 f_fillCell(dashTable, 0, 2, "Net Profit:", str.tostring(_profit, '##.##') + "%", _profit > 0 ? greenColor : redColor, color.white) _numOfDaysInStrategy = (strategy.opentrades.entry_time(0) - strategy.closedtrades.entry_time(0)) / (1000 * 3600 * 24) f_fillCell(dashTable, 0, 3, "Percent Per Day", str.tostring(_profit / _numOfDaysInStrategy, '#########################.#####')+"%", _profit > 0 ? greenColor : redColor, color.white) _winRate = ( strategy.wintrades / strategy.closedtrades ) * 100 f_fillCell(dashTable, 0, 4, "Percent Profitable:", str.tostring(_winRate, '##.##') + "%", _winRate < 50 ? redColor : _winRate < 75 ? greenColor : yellowColor, color.white) f_fillCell(dashTable, 0, 5, "Profit Factor:", str.tostring(strategy.grossprofit / strategy.grossloss, '##.###'), strategy.grossprofit > strategy.grossloss ? greenColor : redColor, color.white) f_fillCell(dashTable, 0, 6, "Total Trades:", str.tostring(strategy.closedtrades), bgcolor, color.white) f_fillCell(dashTable, 0, 8, "Max Wins In A Row:", str.tostring(maxWinRow, '######') , bgcolor, color.white) f_fillCell(dashTable, 0, 9, "Max Losses In A Row:", str.tostring(maxLossRow, '######') , bgcolor, color.white)
Davin's 10/200MA Pullback on SPY Strategy v2.0
https://www.tradingview.com/script/Gkib6KgL-Davin-s-10-200MA-Pullback-on-SPY-Strategy-v2-0/
Gold_D_Roger
https://www.tradingview.com/u/Gold_D_Roger/
722
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/ // Β© Gold_D_Roger //note: spreading 1 statement over multiple lines needs 1 apce + 1 tab | multi line function is 1 tab //Recommended tickers: SPY (D), QQQ (D) and big indexes, AAPL (4H) //@version=5 strategy("Davin's 10/200MA Pullback on SPY Strategy v2.0", overlay=true, initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=10, // 10% of equity on each trade commission_type=strategy.commission.cash_per_contract, commission_value=0.1) //Insert your broker's rate, IB is 0.005USD or tiered //Best parameters // SPY D // Stop loss 0.15 // commission of 0.005 USD using Interactive brokers // Exit on lower close // Buy more when x% down --> 14% // DO NOT include stop condition using MA crossover // Get User Input i_ma1 = input.int(title="MA Length 1", defval=200, step=10, group="Strategy Parameters", tooltip="Long-term MA 200") i_ma2 = input.int(title="MA Length 2", defval=10, step=10, group="Strategy Parameters", tooltip="Short-term MA 10") i_ma3 = input.int(title="MA Length 3", defval=50, step=1, group="Strategy Parameters", tooltip="MA for crossover signals`") i_stopPercent = input.float(title="Stop Loss Percent", defval=0.15, step=0.01, group="Strategy Parameters", tooltip="Hard stop loss of 10%") i_startTime = input.time(title="Start filter", defval=timestamp("01 Jan 2013 13:30 +0000"), group="Time filter", tooltip="Start date and time to begin") i_endTime = input.time(title="End filter", defval=timestamp("01 Jan 2099 19:30 +0000"), group="Time filter", tooltip="End date and time to stop") i_lowerClose = input.bool(title="Exit on lower close", defval=true, group="Strategy Parameters", tooltip="Wait for lower close after above 10SMA before exiting") // optimise exit strat, boolean type creates tickbox type inputs i_contrarianBuyTheDip = input.bool(title="Buy whenever more than x% drawdown", defval=true, group="Strategy Parameters", tooltip="Buy the dip! Whenever x% or more drawdown on SPY") i_contrarianTrigger = input.int(title="Trigger % drop to buy the dip", defval=14, step=1, group="Strategy Parameters", tooltip="% drop to trigger contrarian Buy the Dip!") //14% to be best for SPY 1D //20% best for AMZN 1D i_stopByCrossover_MA2_3 = input.bool(title="Include stop condition using MA crossover", defval=false, group="Strategy Parameters", tooltip="Sell when crossover of MA2/1 happens") // Get indicator values ma1 = ta.sma(close,i_ma1) //param 1 ma2 = ta.sma(close,i_ma2) //param 2 ma3 = ta.sma(close,i_ma3) //param 3 ma_9 = ta.ema(close,9) //param 2 ma_20 = ta.ema(close,20) //param 3 // Check filter(s) f_dateFilter = time >+ i_startTime and time <= i_endTime //make sure date entries are within acceptable range // Highest price of the prev 52 days: https://www.tradingcode.net/tradingview/largest-maximum-value/#:~:text=()%20versus%20ta.-,highest(),max()%20and%20ta. highest52 = ta.highest(high,52) overall_change = ((highest52 - close[0]) / highest52) * 100 // Check buy/sell conditions var float buyPrice = 0 //intialise buyPrice, this will change when we enter a trade ; float = decimal number data type 0.0 buyCondition = (close > ma1 and close < ma2 and strategy.position_size == 0 and f_dateFilter) or (strategy.position_size == 0 and i_contrarianBuyTheDip==true and overall_change > i_contrarianTrigger and f_dateFilter) // higher than 200sma, lower than short term ma (pullback) + avoid pyramiding positions sellCondition = close > ma2 and strategy.position_size > 0 and (not i_lowerClose or close < low[1]) //check if we already in trade + close above 10MA; // third condition: EITHER i_lowerClose not turned on OR closing price has to be < previous candle's LOW [1] stopDistance = strategy.position_size > 0 ? ((buyPrice - close)/close) : na // check if in trade > calc % drop dist from entry, if not na stopPrice = strategy.position_size > 0 ? (buyPrice - (buyPrice * i_stopPercent)) : na // calc SL price if in trade, if not, na stopCondition = (strategy.position_size > 0 and stopDistance > i_stopPercent) or (strategy.position_size > 0 and (i_stopByCrossover_MA2_3==true and ma3 < ma1)) // Enter positions if buyCondition strategy.entry(id="Long", direction=strategy.long) //long only if buyCondition[1] // if buyCondition is true prev candle buyPrice := open // entry price = current bar opening price // Exit position if sellCondition or stopCondition strategy.close(id="Long", comment = "Exit" + (stopCondition ? "Stop loss=true" : "")) // if condition? "Value for true" : "value for false" buyPrice := na //reset buyPrice // Plot plot(buyPrice, color=color.lime, style=plot.style_linebr) plot(stopPrice, color=color.red, style=plot.style_linebr, offset = -1) plot(ma1, color=color.blue) //defval=200 plot(ma2, color=color.white) //defval=10 plot(ma3, color=color.yellow) // defval=50
[fpemehd] SSL Baseline Strategy
https://www.tradingview.com/script/r4SVQcwp/
DuDu95
https://www.tradingview.com/u/DuDu95/
73
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Thanks to @kevinmck100 for opensource strategy template and @Mihkel00 for SSL Hybrid // @fpemehd // @version=5 strategy(title = '[fpemehd] SSL Baseline Strategy', shorttitle = '[f] SSL', overlay = true, pyramiding = 0, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, commission_value = 0.1, initial_capital = 100000, max_lines_count = 150, max_labels_count = 300) // # ========================================================================= # // # Inputs // # ========================================================================= # // 1. Time i_start = input.time (defval = timestamp("20 Jan 1990 00:00 +0900"), title = "Start Date", tooltip = "Choose Backtest Start Date", inline = "Start Date", group = "Time" ) i_end = input.time (defval = timestamp("20 Dec 2030 00:00 +0900"), title = "End Date", tooltip = "Choose Backtest End Date", inline = "End Date", group = "Time" ) inDateRange = time >= i_start and time <= i_end // 2. Inputs for direction: Long? Short? Both? // i_longEnabled = input.bool(defval = true , title = "Long?", tooltip = "Enable Long Position Trade?", inline = "1", group = "Long / Short" ) // i_shortEnabled = input.bool(defval = true , title = "Short?", tooltip = "Enable Short Position Trade?", inline = "1", group = "Long / Short" ) // 3. Shared inputs for Long and Short //// 3-1. Inputs for Stop Loss Type: ATR or Percent? i_slType = input.string (defval = "ATR", title = "SL Type ", group = "Strategy: Stop Loss Conditions", options = ["Percent", "ATR", "Previous LL / HH"], tooltip = "Stop Loss based on %? ATR?", inline = "1") i_slPercent = input.float (defval = 3, title = "SL % ", group = "Strategy: Stop Loss Conditions", inline = "2") i_slAtrLength = input.int (14, "SL ATR Length ", group = "Strategy: Stop Loss Conditions", inline = "3", minval = 0, maxval = 10000) i_slAtrMultiplier = input.float (4, "SL ATR Multiplier", group = "Strategy: Stop Loss Conditions", inline = "3", minval = 0, step = 0.1, tooltip = "Length of ATR used to calculate Stop Loss. \nSize of StopLoss is determined by multiplication of ATR value. Take Profit is derived from this also by multiplying the StopLoss value by the Risk:Reward multiplier.") i_slLookBack = input.int(30, "Lowest Price Before Entry", group = "Strategy: Stop Loss Conditions", inline = "4", minval = 30, step = 1, tooltip = "Lookback to find the Lowest Price. \nStopLoss is determined by the Lowest price of the look back period. Take Profit is derived from this also by multiplying the StopLoss value by the Risk:Reward multiplier.") //// 3-2. Inputs for Quantity & Risk Manangement: Take Profit i_riskReward = input.float(2, "Risk : Reward Ratio ", group = "Strategy: Risk Management", inline = "1", minval = 0, step = 0.1, tooltip = "Previous high or low (long/short dependant) is used to determine TP level. 'Risk : Reward' ratio is then used to calculate SL based of previous high/low level.\n\nIn short, the higher the R:R ratio, the smaller the SL since TP target is fixed by previous high/low price data.") i_accountRiskPercent = input.float(1, "Portfolio Risk %", group = "Strategy: Risk Management", inline = "1", minval = 0, step = 0.1, tooltip = "Percentage of portfolio you lose if trade hits SL.\n\nYou then stand to gain\n Portfolio Risk % * Risk : Reward\nif trade hits TP.") // 4. Inputs for Drawings i_showTpSlBoxes = input.bool(true, "Show TP / SL Boxes", group = "Strategy: Drawings", inline = "1", tooltip = "Show or hide TP and SL position boxes.\n\nNote: TradingView limits the maximum number of boxes that can be displayed to 500 so they may not appear for all price data under test.") i_showLabels = input.bool(true, "Show Trade Exit Labels", group = "Strategy: Drawings", inline = "1", tooltip = "Useful labels to identify Profit/Loss and cumulative portfolio capital after each trade closes.\n\nAlso note that TradingView limits the max number of 'boxes' that can be displayed on a chart (max 500). This means when you lookback far enough on the chart you will not see the TP/SL boxes. However you can check this option to identify where trades exited.") i_showDashboard = input.bool(true, "Show Dashboard", group = "Strategy: Drawings", inline = "1", tooltip = "Show Backtest Results") i_show_color_bar = input.bool(true , "Color Bars", group = "Strategy: Drawings", inline = "1") // 5. Inputs for Indicators //// 5-1. Inputs for Indicator - 1: SSL Hybrid i_useTrueRange = input.bool(defval = true , title = "use true range for Keltner Channel?", tooltip = "", inline = " ", group = "1: SSL Hybrid") i_maType = input.string(defval='EMA', title='Baseline Type', options=['SMA', 'EMA', 'DEMA', 'TEMA', 'LSMA', 'WMA', 'MF', 'VAMA', 'TMA', 'HMA', 'JMA', 'Kijun v2', 'EDSMA', 'McGinley'],group = "1: SSL Hybrid") i_len = input.int(defval=30,title='Baseline Length', group = "1: SSL Hybrid") i_multy = input.float(0.2, step=0.05, title='Base Channel Multiplier', group = "1: SSL Hybrid") // Input for Baseline i_kidiv = input.int(defval=1, maxval=4, minval=0, title='Kijun MOD Divider',inline="Kijun v2", group="1: SSL Hybrid") i_jurik_phase = input.int(defval=3, title='Baseline Type = JMA -> Jurik Phase', inline='JMA',group="1: SSL Hybrid") i_jurik_power = input.int(defval=1, title='Baseline Type = JMA -> Jurik Power', inline='JMA',group="1: SSL Hybrid") i_volatility_lookback = input.int(defval=10, title='Baseline Type = VAMA -> Volatility lookback length', inline='VAMA',group="1: SSL Hybrid") // MF i_beta = input.float(0.8, minval=0, maxval=1, step=0.1, title='Baseline Type = MF (Modular Filter, General Filter) ->Beta', inline='MF',group="1: SSL Hybrid") i_feedback = input.bool(defval=false, title='Baseline Type = MF (Modular Filter) -> Use Feedback?', inline='MF',group="1: SSL Hybrid") i_z = input.float(0.5, title='Baseline Type = MF (Modular Filter) -> Feedback Weighting', step=0.1, minval=0, maxval=1, inline='MF',group="1: SSL Hybrid") // EDSMA i_ssfLength = input.int(title='EDSMA - Super Smoother Filter Length', minval=1, defval=20, inline='EDSMA',group="1: SSL Hybrid") i_ssfPoles = input.int(title='EDSMA - Super Smoother Filter Poles', defval=2, options=[2, 3], inline='EDSMA',group="1: SSL Hybrid") // # ========================================================================= # // # Functions for Stop Loss & Take Profit & Plots // # ========================================================================= # percentAsPoints(pcnt) => math.round(pcnt / 100 * close / syminfo.mintick) calcStopLossPrice(pointsOffset, isLong) => priceOffset = pointsOffset * syminfo.mintick if isLong close - priceOffset else close + priceOffset calcProfitTrgtPrice(pointsOffset, isLong) => calcStopLossPrice(-pointsOffset, isLong) printLabel(barIndex, msg) => label.new(barIndex, close, msg) printTpSlHitBox(left, right, slHit, tpHit, entryPrice, slPrice, tpPrice) => if i_showTpSlBoxes box.new (left = left, top = entryPrice, right = right, bottom = slPrice, bgcolor = slHit ? color.new(color.red, 60) : color.new(color.gray, 90), border_width = 0) box.new (left = left, top = entryPrice, right = right, bottom = tpPrice, bgcolor = tpHit ? color.new(color.green, 60) : color.new(color.gray, 90), border_width = 0) line.new(x1 = left, y1 = entryPrice, x2 = right, y2 = entryPrice, color = color.new(color.yellow, 20)) line.new(x1 = left, y1 = slPrice, x2 = right, y2 = slPrice, color = color.new(color.red, 20)) line.new(x1 = left, y1 = tpPrice, x2 = right, y2 = tpPrice, color = color.new(color.green, 20)) printTpSlNotHitBox(left, right, entryPrice, slPrice, tpPrice) => if i_showTpSlBoxes box.new (left = left, top = entryPrice, right = right, bottom = slPrice, bgcolor = color.new(color.gray, 90), border_width = 0) box.new (left = left, top = entryPrice, right = right, bottom = tpPrice, bgcolor = color.new(color.gray, 90), border_width = 0) line.new(x1 = left, y1 = entryPrice, x2 = right, y2 = entryPrice, color = color.new(color.yellow, 20)) line.new(x1 = left, y1 = slPrice, x2 = right, y2 = slPrice, color = color.new(color.red, 20)) line.new(x1 = left, y1 = tpPrice, x2 = right, y2 = tpPrice, color = color.new(color.green, 20)) printTradeExitLabel(x, y, posSize, entryPrice, pnl) => if i_showLabels labelStr = "Position Size: " + str.tostring(math.abs(posSize), "#.##") + "\nPNL: " + str.tostring(pnl, "#.##") + "\nCapital: " + str.tostring(strategy.equity, "#.##") + "\nEntry Price: " + str.tostring(entryPrice, "#.##") + "\nExit Price: " + str.tostring(close,"#.##") label.new(x = x, y = y, text = labelStr, color = pnl > 0 ? color.new(color.green, 60) : color.new(color.red, 60), textcolor = color.white, style = label.style_label_down) f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) => _cellText = _title + " " + _value table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor, text_size=size.auto) // # ========================================================================= # // # Entry, Close Logic // # ========================================================================= # // 1. Calculate Indicators //// 1-1. Calculate Indicators for SSL Hybrid Baseline ////// TEMA tema(src, len) => ema1 = ta.ema(src, len) ema2 = ta.ema(ema1, len) ema3 = ta.ema(ema2, len) 3 * ema1 - 3 * ema2 + ema3 ////// EDSMA get2PoleSSF(src, length) => PI = 2 * math.asin(1) arg = math.sqrt(2) * PI / length a1 = math.exp(-arg) b1 = 2 * a1 * math.cos(arg) c2 = b1 c3 = -math.pow(a1, 2) c1 = 1 - c2 - c3 ssf = 0.0 ssf := c1 * src + c2 * nz(ssf[1]) + c3 * nz(ssf[2]) ssf get3PoleSSF(src, length) => PI = 2 * math.asin(1) arg = PI / length a1 = math.exp(-arg) b1 = 2 * a1 * math.cos(1.738 * arg) c1 = math.pow(a1, 2) coef2 = b1 + c1 coef3 = -(c1 + b1 * c1) coef4 = math.pow(c1, 2) coef1 = 1 - coef2 - coef3 - coef4 ssf = 0.0 ssf := coef1 * src + coef2 * nz(ssf[1]) + coef3 * nz(ssf[2]) + coef4 * nz(ssf[3]) ssf ma(type, src, len) => float result = 0 if type == 'TMA' result := ta.sma(ta.sma(src, math.ceil(len / 2)), math.floor(len / 2) + 1) result if type == 'MF' ts = 0. b = 0. c = 0. os = 0. //---- alpha = 2 / (len + 1) a = i_feedback ? i_z * src + (1 - i_z) * nz(ts[1], src) : src //---- b := a > alpha * a + (1 - alpha) * nz(b[1], a) ? a : alpha * a + (1 - alpha) * nz(b[1], a) c := a < alpha * a + (1 - alpha) * nz(c[1], a) ? a : alpha * a + (1 - alpha) * nz(c[1], a) os := a == b ? 1 : a == c ? 0 : os[1] //---- upper = i_beta * b + (1 - i_beta) * c lower = i_beta * c + (1 - i_beta) * b ts := os * upper + (1 - os) * lower result := ts result if type == 'LSMA' result := ta.linreg(src, len, 0) result if type == 'SMA' // Simple result := ta.sma(src, len) result if type == 'EMA' // Exponential result := ta.ema(src, len) result if type == 'DEMA' // Double Exponential e = ta.ema(src, len) result := 2 * e - ta.ema(e, len) result if type == 'TEMA' // Triple Exponential e = ta.ema(src, len) result := 3 * (e - ta.ema(e, len)) + ta.ema(ta.ema(e, len), len) result if type == 'WMA' // Weighted result := ta.wma(src, len) result if type == 'VAMA' // Volatility Adjusted /// Copyright Β© 2019 to present, Joris Duyck (JD) mid = ta.ema(src, len) dev = src - mid vol_up = ta.highest(dev, i_volatility_lookback) vol_down = ta.lowest(dev, i_volatility_lookback) result := mid + math.avg(vol_up, vol_down) result if type == 'HMA' // Hull result := ta.wma(2 * ta.wma(src, len / 2) - ta.wma(src, len), math.round(math.sqrt(len))) result if type == 'JMA' // Jurik /// Copyright Β© 2018 Alex Orekhov (everget) /// Copyright Β© 2017 Jurik Research and Consulting. phaseRatio = i_jurik_phase < -100 ? 0.5 : i_jurik_phase > 100 ? 2.5 : i_jurik_phase / 100 + 1.5 beta = 0.45 * (len - 1) / (0.45 * (len - 1) + 2) alpha = math.pow(beta, i_jurik_power) jma = 0.0 e0 = 0.0 e0 := (1 - alpha) * src + alpha * nz(e0[1]) e1 = 0.0 e1 := (src - e0) * (1 - beta) + beta * nz(e1[1]) e2 = 0.0 e2 := (e0 + phaseRatio * e1 - nz(jma[1])) * math.pow(1 - alpha, 2) + math.pow(alpha, 2) * nz(e2[1]) jma := e2 + nz(jma[1]) result := jma result if type == 'Kijun v2' kijun = math.avg(ta.lowest(len), ta.highest(len)) //, (open + close)/2) conversionLine = math.avg(ta.lowest(len / i_kidiv), ta.highest(len / i_kidiv)) delta = (kijun + conversionLine) / 2 result := delta result if type == 'McGinley' mg = 0.0 mg := na(mg[1]) ? ta.ema(src, len) : mg[1] + (src - mg[1]) / (len * math.pow(src / mg[1], 4)) result := mg result if type == 'EDSMA' zeros = src - nz(src[2]) avgZeros = (zeros + zeros[1]) / 2 // Ehlers Super Smoother Filter ssf = i_ssfPoles == 2 ? get2PoleSSF(avgZeros, i_ssfLength) : get3PoleSSF(avgZeros, i_ssfLength) // Rescale filter in terms of Standard Deviations stdev = ta.stdev(ssf, len) scaledFilter = stdev != 0 ? ssf / stdev : 0 alpha = 5 * math.abs(scaledFilter) / len edsma = 0.0 edsma := alpha * src + (1 - alpha) * nz(edsma[1]) result := edsma result result ////// Keltner Baseline Channel (Baseline) BBMC = ma(i_maType, close, i_len) Keltma = ma(i_maType, close, i_len) range_1 = i_useTrueRange ? ta.tr : high - low rangema = ta.ema(range_1, i_len) upperk = Keltma + rangema * i_multy lowerk = Keltma - rangema * i_multy // 2. Entry Condition for Long and Short // Condition 1 bullSSL = close > upperk bearSSL = close < lowerk // Enter Position based on Condition 1 goLong = inDateRange and bullSSL goShort = inDateRange and bearSSL // # ========================================================================= # // # Position Control Logic (Entry & Exit) // # ========================================================================= # // 1. Trade entry and exit variables var tradeEntryBar = bar_index var profitPoints = 0. var lossPoints = 0. var slPrice = 0. var tpPrice = 0. var inLong = false var inShort = false // 2. Entry decisions openLong = (goLong and not inLong) // Long entry condition & not in long position openShort = (goShort and not inShort) // Short entry condition & not in short position flippingSides = (goLong and inShort) or (goShort and inLong) // (Long entry condition & in short position) and the opposite enteringTrade = openLong or openShort // Entering Long or Short Condition inTrade = inLong or inShort // 3. Stop Loss & Take Profit Percent lowestLow = ta.lowest(source = low, length = i_slLookBack) highestHigh = ta.highest(source = high, length = i_slLookBack) llhhSLPercent = openLong ? math.abs((close - lowestLow) / close) * 100 : openShort ? math.abs((highestHigh - close) / close) * 100 : na atr = ta.atr(i_slAtrLength) slAmount = atr * i_slAtrMultiplier slPercent = i_slType == 'ATR' ? math.abs((1 - (close - slAmount) / close) * 100) : i_slType == 'Percent' ? i_slPercent : llhhSLPercent tpPercent = slPercent * i_riskReward // 4. Risk calculations & Quantity Management riskAmt = strategy.equity * i_accountRiskPercent / 100 entryQty = math.abs(riskAmt / slPercent * 100) / close // 5. Open Position if openLong if strategy.position_size < 0 printTpSlNotHitBox(tradeEntryBar + 1, bar_index + 1, strategy.position_avg_price, slPrice, tpPrice) printTradeExitLabel(bar_index + 1, math.max(tpPrice, slPrice), strategy.position_size, strategy.position_avg_price, strategy.openprofit) strategy.entry("Long", strategy.long, qty = entryQty, alert_message = "Long Entry") enteringTrade := true inLong := true inShort := false if openShort if strategy.position_size > 0 printTpSlNotHitBox(tradeEntryBar + 1, bar_index + 1, strategy.position_avg_price, slPrice, tpPrice) printTradeExitLabel(bar_index + 1, math.max(tpPrice, slPrice), strategy.position_size, strategy.position_avg_price, strategy.openprofit) strategy.entry("Short", strategy.short, qty = entryQty, alert_message = "Short Entry") enteringTrade := true inShort := true inLong := false if enteringTrade profitPoints := percentAsPoints(tpPercent) lossPoints := percentAsPoints(slPercent) slPrice := calcStopLossPrice(lossPoints, openLong) tpPrice := calcProfitTrgtPrice(profitPoints, openLong) tradeEntryBar := bar_index // Can add more take profit Actions strategy.exit("TP/SL", profit = profitPoints, loss = lossPoints, comment_profit = "TP Hit", comment_loss = "SL Hit", alert_profit = "TP Hit Alert", alert_loss = "SL Hit Alert") // # ========================================================================= # // # Plots (Bar Color, Plot, Label, Boxes) // # ========================================================================= # // 1. SSL Hybrid Baseline longColor = #00c3ff shortColor = #ff0062 color_bar = close > upperk ? longColor : close < lowerk ? shortColor : color.gray p1 = plot(BBMC, color=color.new(color=color_bar, transp=0), linewidth=4, title='MA Baseline') // 2. Bar color Based On SSL Hybrid Baseline barcolor(i_show_color_bar ? color_bar : na) up_channel = plot(upperk, color=color_bar, title='Baseline Upper Channel') low_channel = plot(lowerk, color=color_bar, title='Basiline Lower Channel') fill(up_channel, low_channel, color.new(color=color_bar, transp=90)) // 3. Stoploss Boxes slHit = (inShort and high >= slPrice) or (inLong and low <= slPrice) tpHit = (inLong and high >= tpPrice) or (inShort and low <= tpPrice) exitTriggered = slHit or tpHit entryPrice = strategy.closedtrades.entry_price (strategy.closedtrades - 1) pnl = strategy.closedtrades.profit (strategy.closedtrades - 1) posSize = strategy.closedtrades.size (strategy.closedtrades - 1) if (inTrade and exitTriggered) inShort := false inLong := false printTpSlHitBox(tradeEntryBar + 1, bar_index, slHit, tpHit, entryPrice, slPrice, tpPrice) printTradeExitLabel(bar_index, math.max(tpPrice, slPrice), posSize, entryPrice, pnl) if barstate.islastconfirmedhistory and strategy.position_size != 0 printTpSlNotHitBox(tradeEntryBar + 1, bar_index + 1, strategy.position_avg_price, slPrice, tpPrice) // 4. Data Windows plotchar(slPrice, "Stop Loss Price", "") plotchar(tpPrice, "Take Profit Price", "") // 5. Showing Labels plotDebugLabels = false if plotDebugLabels if bar_index == tradeEntryBar printLabel(bar_index, "Position size: " + str.tostring(entryQty * close, "#.##")) // 6. Showing Dashboard if i_showDashboard var bgcolor = color.new(color.black,0) // Keep track of Wins/Losses streaks newWin = (strategy.wintrades > strategy.wintrades[1]) and (strategy.losstrades == strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1]) newLoss = (strategy.wintrades == strategy.wintrades[1]) and (strategy.losstrades > strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1]) varip int winRow = 0 varip int lossRow = 0 varip int maxWinRow = 0 varip int maxLossRow = 0 if newWin lossRow := 0 winRow := winRow + 1 if winRow > maxWinRow maxWinRow := winRow if newLoss winRow := 0 lossRow := lossRow + 1 if lossRow > maxLossRow maxLossRow := lossRow // Prepare stats table var table dashTable = table.new(position.bottom_right, 1, 15, border_width=1) if barstate.islastconfirmedhistory // Update table dollarReturn = strategy.netprofit f_fillCell(dashTable, 0, 0, "Start:", str.format("{0,date,long}", strategy.closedtrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.closedtrades.entry_time(0)) f_fillCell(dashTable, 0, 1, "End:", str.format("{0,date,long}", strategy.opentrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.opentrades.entry_time(0)) _profit = (strategy.netprofit / strategy.initial_capital) * 100 f_fillCell(dashTable, 0, 2, "Net Profit:", str.tostring(_profit, '##.##') + "%", _profit > 0 ? color.green : color.red, color.white) _numOfDaysInStrategy = (strategy.opentrades.entry_time(0) - strategy.closedtrades.entry_time(0)) / (1000 * 3600 * 24) f_fillCell(dashTable, 0, 3, "Percent Per Day", str.tostring(_profit / _numOfDaysInStrategy, '#########################.#####')+"%", _profit > 0 ? color.green : color.red, color.white) _winRate = ( strategy.wintrades / strategy.closedtrades ) * 100 f_fillCell(dashTable, 0, 4, "Percent Profitable:", str.tostring(_winRate, '##.##') + "%", _winRate < 50 ? color.red : _winRate < 75 ? #999900 : color.green, color.white) f_fillCell(dashTable, 0, 5, "Profit Factor:", str.tostring(strategy.grossprofit / strategy.grossloss, '##.###'), strategy.grossprofit > strategy.grossloss ? color.green : color.red, color.white) f_fillCell(dashTable, 0, 6, "Total Trades:", str.tostring(strategy.closedtrades), bgcolor, color.white) f_fillCell(dashTable, 0, 8, "Max Wins In A Row:", str.tostring(maxWinRow, '######') , bgcolor, color.white) f_fillCell(dashTable, 0, 9, "Max Losses In A Row:", str.tostring(maxLossRow, '######') , bgcolor, color.white)
Strategy Myth-Busting #10 - InsideBar+EMA - [MYN]
https://www.tradingview.com/script/SvcAJM3O-Strategy-Myth-Busting-10-InsideBar-EMA-MYN/
myncrypto
https://www.tradingview.com/u/myncrypto/
423
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© myn //@version=5 strategy('Strategy Myth-Busting #10 - InsideBar+EMA - [MYN]', max_bars_back=5000, overlay=true, pyramiding=0, initial_capital=20000, currency='USD', default_qty_type=strategy.percent_of_equity, default_qty_value=100.0, commission_value=0.075, use_bar_magnifier = false) ///////////////////////////////////// //* Put your strategy logic below *// ///////////////////////////////////// //short if: inside bar and bearish & below 50 ema & price falls below low of inside bar. Opposite for long. on 4H TF // Inside Bar //β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ f_priorBarsSatisfied(_objectToEval, _numOfBarsToLookBack) => returnVal = false for i = 0 to _numOfBarsToLookBack if (_objectToEval[i] == true) returnVal = true i_numLookbackBars = input(2,title="Lookback for Inside Bar") // This source code is subject to the terms of the GNU License 2.0 at https://www.gnu.org/licenses/old-licenses/gpl-2.0.en.html // Β© cma //@version=5 //indicator('Inside Bar Ind/Alert', overlay=true) bullishBar = 1 bearishBar = -1 isInside() => previousBar = 1 bodyStatus = close >= open ? 1 : -1 isInsidePattern = high < high[previousBar] and low > low[previousBar] isInsidePattern ? bodyStatus : 0 barcolor(isInside() == bullishBar ? color.green : na) barcolor(isInside() == bearishBar ? color.red : na) // When is bullish bar paint green plotshape(isInside() == bullishBar, style=shape.triangleup, location=location.abovebar, color=color.new(color.green, 0)) // When is bearish bar paint red plotshape(isInside() == bearishBar, style=shape.triangledown, location=location.belowbar, color=color.new(color.red, 0)) isInsideBarMade = isInside() == bullishBar or isInside() == bearishBar alertcondition(isInsideBarMade, title='Inside Bar', message='Inside Bar came up!') i_srcInsideBarLong = input.source(close, title = "_____ falls above HIGH of inside bar (Long condition)") i_srcInsideBarShort = input.source(close, title = "_____ falls below LOW of inside bar (Short condition)") //if: inside bar and falls below low of inside bar. I think. insideBarLongEntry = f_priorBarsSatisfied(isInside() == bullishBar,i_numLookbackBars) and i_srcInsideBarLong > high[i_numLookbackBars] //isInside() == bullishBar insideBarShortEntry = f_priorBarsSatisfied(isInside() == bearishBar,i_numLookbackBars) and i_srcInsideBarShort < low[i_numLookbackBars] //isInside() == bearishBar // EMA //β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ i_src = input.source(close, title = "EMA Source") i_emaLength = input(50,title="EMA Length") ema = ta.ema(i_src, i_emaLength) emaPlot = plot(series=ema,color=color.blue, linewidth=2) emaLongEntry = i_src > ema emaShortEntry = i_src < ema ////////////////////////////////////// //* Put your strategy rules below *// ///////////////////////////////////// longCondition = insideBarLongEntry and emaLongEntry shortCondition = insideBarShortEntry and emaShortEntry //define as 0 if do not want to use closeLongCondition = 0 closeShortCondition = 0 // ADX //β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ adxEnabled = input.bool(defval = false , title = "Average Directional Index (ADX)", tooltip = "", group ="ADX" ) adxlen = input(14, title="ADX Smoothing", group="ADX") adxdilen = input(14, title="DI Length", group="ADX") adxabove = input(25, title="ADX Threshold", group="ADX") adxdirmov(len) => adxup = ta.change(high) adxdown = -ta.change(low) adxplusDM = na(adxup) ? na : (adxup > adxdown and adxup > 0 ? adxup : 0) adxminusDM = na(adxdown) ? na : (adxdown > adxup and adxdown > 0 ? adxdown : 0) adxtruerange = ta.rma(ta.tr, len) adxplus = fixnan(100 * ta.rma(adxplusDM, len) / adxtruerange) adxminus = fixnan(100 * ta.rma(adxminusDM, len) / adxtruerange) [adxplus, adxminus] adx(adxdilen, adxlen) => [adxplus, adxminus] = adxdirmov(adxdilen) adxsum = adxplus + adxminus adx = 100 * ta.rma(math.abs(adxplus - adxminus) / (adxsum == 0 ? 1 : adxsum), adxlen) adxsig = adxEnabled ? adx(adxdilen, adxlen) : na isADXEnabledAndAboveThreshold = adxEnabled ? (adxsig > adxabove) : true //Backtesting Time Period (Input.time not working as expected as of 03/30/2021. Giving odd start/end dates //β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ useStartPeriodTime = input.bool(true, 'Start', group='Date Range', inline='Start Period') startPeriodTime = input.time(timestamp('1 Jan 2019'), '', group='Date Range', inline='Start Period') useEndPeriodTime = input.bool(true, 'End', group='Date Range', inline='End Period') endPeriodTime = input.time(timestamp('31 Dec 2030'), '', group='Date Range', inline='End Period') start = useStartPeriodTime ? startPeriodTime >= time : false end = useEndPeriodTime ? endPeriodTime <= time : false calcPeriod = not start and not end // Trade Direction // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ tradeDirection = input.string('Long and Short', title='Trade Direction', options=['Long and Short', 'Long Only', 'Short Only'], group='Trade Direction') // Percent as Points // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ per(pcnt) => strategy.position_size != 0 ? math.round(pcnt / 100 * strategy.position_avg_price / syminfo.mintick) : float(na) // Take profit 1 // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ tp1 = input.float(title='Take Profit 1 - Target %', defval=10.5, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 1') q1 = input.int(title='% Of Position', defval=25, minval=0, group='Take Profit', inline='Take Profit 1') // Take profit 2 // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ tp2 = input.float(title='Take Profit 2 - Target %', defval=11, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 2') q2 = input.int(title='% Of Position', defval=25, minval=0, group='Take Profit', inline='Take Profit 2') // Take profit 3 // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ tp3 = input.float(title='Take Profit 3 - Target %', defval=11.5, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 3') q3 = input.int(title='% Of Position', defval=25, minval=0, group='Take Profit', inline='Take Profit 3') // Take profit 4 // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ tp4 = input.float(title='Take Profit 4 - Target %', defval=12, minval=0.0, step=0.5, group='Take Profit') /// Stop Loss // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ stoplossPercent = input.float(title='Stop Loss (%)', defval=4, minval=0.01, group='Stop Loss') * 0.01 slLongClose = close < strategy.position_avg_price * (1 - stoplossPercent) slShortClose = close > strategy.position_avg_price * (1 + stoplossPercent) /// Leverage // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ leverage = input.float(1, 'Leverage', step=.5, group='Leverage') contracts = math.min(math.max(.000001, strategy.equity / close * leverage), 1000000000) /// Trade State Management // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ isInLongPosition = strategy.position_size > 0 isInShortPosition = strategy.position_size < 0 /// ProfitView Alert Syntax String Generation // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ alertSyntaxPrefix = input.string(defval='CRYPTANEX_99FTX_Strategy-Name-Here', title='Alert Syntax Prefix', group='ProfitView Alert Syntax') alertSyntaxBase = alertSyntaxPrefix + '\n#' + str.tostring(open) + ',' + str.tostring(high) + ',' + str.tostring(low) + ',' + str.tostring(close) + ',' + str.tostring(volume) + ',' /// Trade Execution // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ longConditionCalc = (longCondition and isADXEnabledAndAboveThreshold) shortConditionCalc = (shortCondition and isADXEnabledAndAboveThreshold) if calcPeriod if longConditionCalc and tradeDirection != 'Short Only' and isInLongPosition == false strategy.entry('Long', strategy.long, qty=contracts) alert(message=alertSyntaxBase + 'side:long', freq=alert.freq_once_per_bar_close) if shortConditionCalc and tradeDirection != 'Long Only' and isInShortPosition == false strategy.entry('Short', strategy.short, qty=contracts) alert(message=alertSyntaxBase + 'side:short', freq=alert.freq_once_per_bar_close) //Inspired from Multiple %% profit exits example by adolgo https://www.tradingview.com/script/kHhCik9f-Multiple-profit-exits-example/ strategy.exit('TP1', qty_percent=q1, profit=per(tp1)) strategy.exit('TP2', qty_percent=q2, profit=per(tp2)) strategy.exit('TP3', qty_percent=q3, profit=per(tp3)) strategy.exit('TP4', profit=per(tp4)) strategy.close('Long', qty_percent=100, comment='SL Long', when=slLongClose) strategy.close('Short', qty_percent=100, comment='SL Short', when=slShortClose) strategy.close_all(when=closeLongCondition or closeShortCondition, comment='Close Postion') /// Dashboard // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Inspired by https://www.tradingview.com/script/uWqKX6A2/ - Thanks VertMT showDashboard = input.bool(group="Dashboard", title="Show Dashboard", defval=true) f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) => _cellText = _title + "\n" + _value table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor, text_size=size.auto) // Draw dashboard table if showDashboard var bgcolor = color.new(color.black,0) // Keep track of Wins/Losses streaks newWin = (strategy.wintrades > strategy.wintrades[1]) and (strategy.losstrades == strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1]) newLoss = (strategy.wintrades == strategy.wintrades[1]) and (strategy.losstrades > strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1]) varip int winRow = 0 varip int lossRow = 0 varip int maxWinRow = 0 varip int maxLossRow = 0 if newWin lossRow := 0 winRow := winRow + 1 if winRow > maxWinRow maxWinRow := winRow if newLoss winRow := 0 lossRow := lossRow + 1 if lossRow > maxLossRow maxLossRow := lossRow // Prepare stats table var table dashTable = table.new(position.bottom_right, 1, 15, border_width=1) if barstate.islastconfirmedhistory // Update table dollarReturn = strategy.netprofit f_fillCell(dashTable, 0, 0, "Start:", str.format("{0,date,long}", strategy.closedtrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.closedtrades.entry_time(0)) f_fillCell(dashTable, 0, 1, "End:", str.format("{0,date,long}", strategy.opentrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.opentrades.entry_time(0)) _profit = (strategy.netprofit / strategy.initial_capital) * 100 f_fillCell(dashTable, 0, 2, "Net Profit:", str.tostring(_profit, '##.##') + "%", _profit > 0 ? color.green : color.red, color.white) _numOfDaysInStrategy = (strategy.opentrades.entry_time(0) - strategy.closedtrades.entry_time(0)) / (1000 * 3600 * 24) f_fillCell(dashTable, 0, 3, "Percent Per Day", str.tostring(_profit / _numOfDaysInStrategy, '#########################.#####')+"%", _profit > 0 ? color.green : color.red, color.white) _winRate = ( strategy.wintrades / strategy.closedtrades ) * 100 f_fillCell(dashTable, 0, 4, "Percent Profitable:", str.tostring(_winRate, '##.##') + "%", _winRate < 50 ? color.red : _winRate < 75 ? #999900 : color.green, color.white) f_fillCell(dashTable, 0, 5, "Profit Factor:", str.tostring(strategy.grossprofit / strategy.grossloss, '##.###'), strategy.grossprofit > strategy.grossloss ? color.green : color.red, color.white) f_fillCell(dashTable, 0, 6, "Total Trades:", str.tostring(strategy.closedtrades), bgcolor, color.white) f_fillCell(dashTable, 0, 8, "Max Wins In A Row:", str.tostring(maxWinRow, '######') , bgcolor, color.white) f_fillCell(dashTable, 0, 9, "Max Losses In A Row:", str.tostring(maxLossRow, '######') , bgcolor, color.white)
Crypto BTC Correlation Scalper Gaps Strategy
https://www.tradingview.com/script/2vgZW5T0-Crypto-BTC-Correlation-Scalper-Gaps-Strategy/
exlux99
https://www.tradingview.com/u/exlux99/
240
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© exlux99 //@version=5 strategy("Crypto BTC Correlation Scalper Gaps Strategy", overlay = true) inverse=input.bool(false, title="Inverse Mode / Long = Short or Long = Long") ex_symbol = input.symbol("CME:BTC1!") ex_high = request.security(ex_symbol, timeframe.period,high) ex_low = request.security(ex_symbol, timeframe.period,low) ex_open = request.security(ex_symbol, timeframe.period,open) ex_close = request.security(ex_symbol, timeframe.period,close) apply_correlation = input.bool(true, title="Correlation Candles") def_high = 0.0 def_low =0.0 def_open =0.0 def_close =0.0 def_high := apply_correlation? ex_high : high def_low := apply_correlation? ex_low : low def_open := apply_correlation? ex_open : open def_close := apply_correlation? ex_close : close daily_sma = request.security(ex_symbol, "D", ta.sma(request.security(ex_symbol, "D", close), input(1))) //plot(daily_sma) legnth_tp_sl = input(50, title="Length for Checking Highest High/Lowest Low Points") minimalDeviationInput = nz(input.float(30.0, "Minimal Deviation (%)", minval=1, maxval=100) / 100 * ta.sma(def_high-def_low, 14)) // Detect gaps. isGapDown = def_high < def_low[1] and def_low[1] - def_high >= minimalDeviationInput isGapUp = def_low > def_high[1] and def_low - def_high[1] >= minimalDeviationInput isGap = isGapDown or isGapUp isGapClosed = false lowest_low=ta.lowest(def_low, legnth_tp_sl) highest_high=ta.highest(def_high, legnth_tp_sl) long = isGapUp and def_close > daily_sma short = isGapDown and def_close < daily_sma var longOpened = false var int timeOfBuyLong = na var float lowest_low_var_tp = na var float lowest_low_var_sl = na var bool longEntry = na longEntry := long and not longOpened if longEntry longOpened := true timeOfBuyLong := time lowest_low_var_tp := def_close * (1 + ((def_close / lowest_low) -1)) lowest_low_var_sl := lowest_low longExitSignal = short or def_high > lowest_low_var_tp //or def_low < lowest_low_var_sl longExit = longOpened[1] and longExitSignal if longExit longOpened := false timeOfBuyLong := na lowest_low_var_tp:=na lowest_low_var_sl :=na //------------------------------------------------------------------------------- var shortOpened = false var int timeOfBuyShort = na var float highest_high_var_tp = na var float highest_high_var_sl = na var bool shortEntry = na shortEntry := short and not shortOpened if shortEntry shortOpened := true timeOfBuyShort := time timeOfBuyShort highest_high_var_tp := def_close * (1 - ((highest_high / def_close) - 1 )) highest_high_var_sl := highest_high shortExitSignal = long or def_low < highest_high_var_tp //or def_high > highest_high_var_sl shortExit = shortOpened[1] and shortExitSignal if shortExit shortOpened := false timeOfBuyShort := na highest_high_var_tp := na highest_high_var_sl := na if(inverse) strategy.entry("long",strategy.short,when=longEntry) strategy.close("long",when=longExit) strategy.entry("short",strategy.long,when=shortEntry) strategy.close("short",when=shortExit) if(not inverse) strategy.entry("long",strategy.long,when=longEntry) strategy.close("long",when=longExit) strategy.entry("short",strategy.short,when=shortEntry) strategy.close("short",when=shortExit)
hΓ  tα»· phΓΊ 999
https://www.tradingview.com/script/rkPNeSLb/
hatnxkld
https://www.tradingview.com/u/hatnxkld/
11
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/ // © hatnxkld //@version=4 strategy("Chiến lược 3EMA giao cắt", overlay=true) ngan=input(title="Ema ngắn", defval = 12) plot(ngan, title="EMA ngắn", color=color.yellow) tb=input(title="Ema trung bình", defval = 48) plot(tb, title="EMA trung bình", color=color.blue) dai=input(title="Ema dai", defval = 288) plot(dai, title="EMA dai", color=color.red)
EMA Slope AyE
https://www.tradingview.com/script/hHVN14jd/
fajardoarelys
https://www.tradingview.com/u/fajardoarelys/
44
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© fajardoarelys //@version=4 strategy("EMA Slope AyE", shorttitle = "SLOPE", overlay=false) EMAPeriod = input(20, title = "EMA Period", type = input.integer) SlopePeriod = input(1, title = "Slope Period", type = input.integer) EMA = ema(close, EMAPeriod) Slope = (EMA - EMA[SlopePeriod]) / SlopePeriod plot(Slope, color = color.yellow, linewidth = 2) zero = hline(0, "zero", color=#787B86)
EMA Slope AyE
https://www.tradingview.com/script/R6Oma910/
fajardoarelys
https://www.tradingview.com/u/fajardoarelys/
10
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/ // Β© fajardoarelys //@version=4 strategy("EMA Slope AyE", shorttitle="SLOPE", overlay=false) EMAPeriod = input(50, title = "EMA Period", type = input.integer) SlopePeriod = input(3, title = "Slope Period", type = input.integer) EMA = ema(close, EMAPeriod) Slope = (EMA - EMA[SlopePeriod]) / SlopePeriod plot(Slope, color = color.yellow, linewidth = 2) zero = hline(0, "zero", color=#787B86)
EMA Cross Strategy
https://www.tradingview.com/script/Fr07EAEb-EMA-Cross-Strategy/
wirunekaewjai
https://www.tradingview.com/u/wirunekaewjai/
37
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© wirunekaewjai //@version=5 strategy("EMA Cross Strategy", overlay=true, default_qty_type=strategy.percent_of_equity, initial_capital=1000, commission_value=0.05) fastLength = input.int(12, "EMA Fast") slowLength = input.int(26, "EMA Slow") priceGap = input.float(100, "Gap (%)", minval=0.01, maxval=100, tooltip="Gap Between Price and Slow EMA") slValue = input.float(5, "SL (%)", minval=0) tpMode = input.string('%','TP Mode', options=['%','Ratio']) tpLongValue = input.float(200, "TP Long", minval=0) tpShortValue = input.float(50, "TP Short", minval=0) //// yearStart = input.int(1980, "Year Start", minval=1700, maxval=3000) //// fast = ta.ema(close, fastLength) slow = ta.ema(close, slowLength) eCrossOver = ta.crossover(fast, slow) eCrossUnder = ta.crossunder(fast, slow) eHigher = fast > slow eLower = fast < slow enableLong = input.bool(true, "Long") enableShort = input.bool(true, "Short") currentYear = year(time) pGap = priceGap / 100 avgPrice = strategy.position_avg_price sl = slValue / 100 slLong = avgPrice * (1 - sl) slShort = avgPrice * (1 + sl) tpL = tpLongValue / 100 tpS = tpShortValue / 100 tpLong = tpMode == '%' ? avgPrice * (1 + tpL) : avgPrice * (1 + (sl * tpLongValue)) tpShort = tpMode == '%' ? avgPrice * (1 - tpS) : avgPrice * (1 - (sl * tpShortValue)) if currentYear >= yearStart if enableLong and eCrossOver gap = (close / slow) - 1 if close > slow and gap < pGap strategy.entry("Long", strategy.long) if enableShort and eCrossUnder gap = 1 - (close / slow) if close < slow and gap < pGap strategy.entry("Short", strategy.short) if strategy.position_size > 0 if slValue > 0 and tpLongValue > 0 strategy.exit("Stop Long", "Long", stop=slLong, limit=tpLong, comment_profit="TP", comment_loss="SL") else if slValue > 0 strategy.exit("SL Long", "Long", stop=slLong, comment_loss="SL") else if tpLongValue > 0 strategy.exit("TP Long", "Long", limit=tpLong, comment_profit="TP") if eCrossUnder strategy.close("Long") if strategy.position_size < 0 if slValue > 0 and tpShortValue > 0 strategy.exit("Stop Short", "Short", stop=slShort, limit=tpShort, comment_profit="TP", comment_loss="SL") else if slValue > 0 strategy.exit("SL Short", "Short", stop=slShort, comment_loss="SL") else if tpShortValue > 0 strategy.exit("TP Short", "Short", limit=tpShort, comment_profit="TP") if eCrossOver strategy.close("Short") ///////////////// plot(fast, color=color.white) plot(slow, color=color.yellow) plot(series=(strategy.position_size > 0 and slValue > 0) ? slLong : na, color=color.red, style=plot.style_linebr, title="SL Long") plot(series=(strategy.position_size < 0 and slValue > 0) ? slShort : na, color=color.red, style=plot.style_linebr, title="SL Short") plot(series=(strategy.position_size > 0 and tpLongValue > 0) ? tpLong : na, color=color.teal, style=plot.style_linebr, title="TP Long") plot(series=(strategy.position_size < 0 and tpShortValue > 0) ? tpShort : na, color=color.teal, style=plot.style_linebr, title="TP Short")
Volatility Stop with Vwap Strategy
https://www.tradingview.com/script/1HLAXDrD-Volatility-Stop-with-Vwap-Strategy/
exlux99
https://www.tradingview.com/u/exlux99/
256
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/ // Β© TradingView // @ exlux99 //@version=5 // Volatility Stop MTF // v3, 2022.05.29 // This code was written using the recommendations from the Pine Scriptβ„’ User Manual's styleInput Guide: // https://www.tradingview.com/pine-script-docs/en/v5/writing/Style_guide.html strategy("Volatility Stop with Vwap Strategy", "VStop Vwap", true) import PineCoders/Time/1 as pcTimeLib string GRP1 = "═════════ Stop Calculations ═════════" float srcInput = input.source(close, "Source", group = GRP1) int lenInput = input.int(20, "Length", group = GRP1, minval = 2) float atrInput = input.float(2.0, "ATR Factor", group = GRP1, minval = 0.25, step = 0.25) vwap_weekly = request.security(syminfo.tickerid, 'W', ta.vwap) // β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” Functions { // @function Calculates a value from the ATR, which is offset from price action to use as a stop loss or trend detection. // @param source (series int/float) The source to calculate the stop value from. // @param atrLength (simple int) The length over which to calcualte the RMA of the true range. (number of bars back). // @param atrInput (series int/float) A multiplier to allow adjustment of the stop as a function of the ATR value. Example: 1 is 100% of the calculated ATR value. // @param offset (series int) The first half of the offset calculations required to achieve repainting/non-repainting data when used in `request.security()`. // @returns ([float, bool]) A tuple of the volatility stop value and the trend direction as a bool. vStop(series float source, simple int atrLength, series float atrInput, series int offset = 0) => float src = nz(source, close) var bool trendUp = true var float max = src var float min = src var float stop = 0.0 float atrM = nz(ta.atr(atrLength) * atrInput, ta.tr) max := math.max(max, src) min := math.min(min, src) stop := nz(trendUp ? math.max(stop, max - atrM) : math.min(stop, min + atrM), src) trendUp := src - stop >= 0.0 if trendUp != nz(trendUp[1], true) max := src min := src stop := trendUp ? max - atrM : min + atrM [stop[offset], trendUp[offset]] // β€”β€”β€”β€”β€” Stop calcs [stopChartTf, trendUpChartTf] = vStop(srcInput, lenInput, atrInput, 0) float stop = stopChartTf bool trendUp = trendUpChartTf var bool inLimbo = false // Get conditions for colors, plotting, and alerts. bool trendReversal = trendUp != trendUp[1] bool trendChangeToUp = trendUp and not trendUp[1] bool trendChangeToDn = not trendUp and trendUp[1] inLimbo := inLimbo and trendUp == trendUp[1] plot(stop) long = trendUp and close > stop and close > vwap_weekly short = not trendUp and close < stop and close < vwap_weekly distance_long = close + (close - stop ) distance_short = close - (stop - close) var longOpened = false var int timeOfBuyLong = na var float tpLong_long = na var float slLong_long = na var bool longEntry = na longEntry := long and not longOpened and not long[1] if longEntry longOpened := true tpLong_long := distance_long slLong_long := distance_short tpLong_trigger = longOpened[1] and (ta.crossover(close, tpLong_long) or ta.crossover(high, tpLong_long)) //or high > lowest_low_var_tp slLong_Trigger = longOpened[1] and (ta.crossunder(close, slLong_long) or ta.crossover(low, slLong_long)) //or low < lowest_low_var_sl longExitSignal = tpLong_trigger or slLong_Trigger or short longExit = longOpened[1] and longExitSignal if longExit longOpened := false timeOfBuyLong := na tpLong_long := na slLong_long := na /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// var shortOpened = false var int timeOfBuyShort = na var float tp_short = na var float sl_short = na var bool shortEntry = na shortEntry := short and not shortOpened and not short[1] if shortEntry shortOpened := true timeOfBuyShort := time tp_short := distance_short sl_short := distance_long tpShort_trigger = shortOpened[1] and (ta.crossunder(close, tp_short) or ta.crossunder(low, tp_short)) //or low < highest_high_var_tp slShort_Trigger = shortOpened[1] and (ta.crossover(close, sl_short) or ta.crossover(high, sl_short)) //or high > highest_high_var_sl shortExitSignal = long or tpShort_trigger or slShort_Trigger shortExit = shortOpened[1] and shortExitSignal if shortExit shortOpened := false timeOfBuyShort := na timeOfBuyShort tp_short := na sl_short := na strategy.entry("long",strategy.long,when=longEntry) strategy.close("long",when=longExit) strategy.entry("short",strategy.short,when=shortEntry) strategy.close('short',when=shortExit)
EMA12/26 buy spot only
https://www.tradingview.com/script/fOkd27us-EMA12-26-buy-spot-only/
sasinp
https://www.tradingview.com/u/sasinp/
24
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© sasinp //@version=5 strategy("EMA12/26 buy spot only", overlay=true) longCondition = ta.crossover(ta.ema(close, 12), ta.ema(close, 26)) if (longCondition) strategy.entry("buy", strategy.long) if ta.crossunder(ta.ema(close, 12), ta.ema(close, 26)) strategy.close("buy")
Trend #2 - BB+EMA
https://www.tradingview.com/script/juVQWbsI/
zxcv55602
https://www.tradingview.com/u/zxcv55602/
97
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/ // Β© zxcv55602 //@version=4 strategy(shorttitle="Trend #2 - BB+EMA v4", title="Bollinger Bands", overlay=true) date1 = input(title="Start Date", type=input.time, defval=timestamp("2000-01-01T00:00:00")) date2 = input(title="Stop Date", type=input.time, defval=timestamp("2030-01-01T00:00:00")) length = input(100, minval=1,step=10) mult = input(1.5,title="StdDev",step=0.1) //------------------ basis = ema(close, length) dev = mult * stdev(close, length) upper = basis + dev lower = basis - dev //------------------ stopcon=input(title="stopcon/lot", type=input.bool, defval=true) lot1=input(title="lot",defval=1) stoploss=input(title="stoploss",defval=1000) emacon=input(title="EMA", type=input.bool, defval=true) ema_value=input(title="EMA value",defval=100, minval=2,step=1) sarcon=input(title="SAR boost", type=input.bool, defval=true) start = input(0.1, minval=0, maxval=10, title="Start",step=0.1) increment = input(0.3, minval=0, maxval=10, title="Step Setting" ,step=0.1) maximum = input(1, minval=1, maxval=10, title="Maximum Step",step=0.1) plot(basis, "Basis", color=sarcon?na:color.new(#FF6D00,50)) p1 = plot(upper, "Upper", color=color.new(color.blue,30)) p2 = plot(lower, "Lower", color=color.new(color.blue,30)) ema1=ema(close,ema_value) sarUp = sar(start*0.01, increment*0.01, maximum*0.1) sarDown = sar(start*0.01, increment*0.01, maximum*0.1) var ema2=0.0 if strategy.position_size>0 ema2:=ema1>sarUp?ema1:(close<sarUp?na:sarUp) else ema2:=ema1>sarDown?(close>sarDown?na:sarDown):ema1 plot(sarcon ? ema2 : na, title="EMA", color=color.red,style=plot.style_stepline) plot(emacon?ema1:na, title="EMA", color=sarcon?na:color.blue) if time >= date1 and time <= date2 if ema1<upper and close>upper strategy.cancel("short") lot_L=stoploss/(close-basis) strategy.entry("long",strategy.long,qty=stopcon?lot_L:lot1,stop=emacon?sarcon?max(basis,ema1,sarUp):max(basis,ema1):basis) if ema1>lower and close<lower strategy.cancel("long") lot_S=stoploss/(basis-close) strategy.entry("short",strategy.short,qty=stopcon?lot_S:lot1,stop=emacon?sarcon?min(basis,ema1,sarDown):min(basis,ema1):basis) if strategy.position_size>0 strategy.exit("long",from_entry="long",stop=emacon?sarcon?max(basis,ema1,sarUp):max(basis,ema1):basis,comment="close_L") if strategy.position_size<0 strategy.exit("short",from_entry="short",stop=emacon?sarcon?min(basis,ema1,sarDown):min(basis,ema1):basis,comment="close_S")
Tick Strategy
https://www.tradingview.com/script/J2VH9JLH-Tick-Strategy/
Sharad_Gaikwad
https://www.tradingview.com/u/Sharad_Gaikwad/
103
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© Sharad_Gaikwad //@version=5 strategy("Tick Strategy", overlay = true, calc_on_every_tick = true) g1 = '============= Strategy based on tick data =============' _x = input.bool(title = '<Long on WIP Green candle and Short on WIP Red candle>', defval = 0, group = g1) entry_on_ticks = input.int(title = 'No of successive ticks to enter the trade', defval = 10, group = g1) ticks_from_beginnig = input.bool(title = 'Count successive ticks for trade only from start of candle', defval = false, group = g1) exit_on_ticks = input.int(title = 'Exit if succussive ticks in opposite direction', defval = 10, group = g1) exit_on_same_candle = input.bool(title = 'Apply exit criteria on entry candle', defval = true, group = g1) box_color = input.color(title = 'Data box color', defval = color.new(color.black, 75), inline = 'b1', group = g1) text_color = input.color(title = 'Data box text color', defval = color.new(color.yellow, 0), inline = 'b1', group = g1) //=================================== tab = table.new(position=position.top_right, columns=7, rows=200,frame_color = color.yellow, frame_width = 1) msg(int row, int col, string msg_str, clr=color.blue) => table.cell(table_id=tab, column=col, row=row, text=msg_str, text_color=clr) t(val) => str.tostring(val) //================================= var tf_msec = timeframe.in_seconds(timeframe.period) * 1000 var data_box = box.new(na, na, na, na) varip tick_no = int(0) varip prev_tick_price = float(na) varip prev_tick_volume = float(na) varip no_of_up_ticks = int(na) varip no_of_down_ticks = int(na) varip succ_up_ticks = int(na) varip succ_down_ticks = int(na) varip up_tick = bool(na) varip down_tick = bool(na) varip up_tick_cnt = int(na) varip down_tick_cnt = int(na) varip up_tick_volume = float(na) varip down_tick_volume = float(na) var trade_candle_no= int(0) var candle_cnt = int(na) candle_cnt := timeframe.change('D') ? 0 : candle_cnt if(barstate.isnew) tick_no := 0 no_of_up_ticks := 0, no_of_down_ticks := 0 succ_up_ticks := 0, succ_down_ticks := 0 up_tick_cnt := 0, down_tick_cnt := 0 up_tick_volume := 0, down_tick_volume := 0 prev_tick_volume := 0 tick_no := tick_no + 1 candle_cnt := candle_cnt + 1 up_tick := close > prev_tick_price down_tick := close < prev_tick_price up_tick_volume := up_tick ? up_tick_volume + (volume - prev_tick_volume) : up_tick_volume down_tick_volume := down_tick ? down_tick_volume + (volume - prev_tick_volume) : down_tick_volume up_tick_volume_percent = math.round(up_tick_volume / (up_tick_volume + down_tick_volume) * 100, 2) succ_up_ticks := up_tick ? succ_up_ticks + 1 : 0 succ_down_ticks := down_tick ? succ_down_ticks + 1 : 0 up_tick_cnt := up_tick ? up_tick_cnt + 1 : up_tick_cnt down_tick_cnt := down_tick ? down_tick_cnt + 1 : down_tick_cnt candle_progress = 100 - math.round(((time_close - timenow) / tf_msec) * 100, 0) candle_color = close > open ? 'Green' : close < open ? 'Red' : 'None' box_text = ' Candle no ==> ' + t(candle_cnt) + '\n' + ' Candle now ==> ' + t(candle_color) + '\n' + ' Tick count ==> ' + t(tick_no) + '\n' + ' Up tick count ==> ' + t(up_tick_cnt) + '\n' + ' Down tick count ==> ' + t(down_tick_cnt) + '\n' + ' Successive up ticks ==> ' + t(succ_up_ticks) + '\n' + 'Successive down ticks ==> ' + t(succ_down_ticks)+'\n' + ' Up tick volume ==> ' + t(math.round(up_tick_volume,2))+'\n' + ' Down tick volume ==> ' + t(math.round(down_tick_volume,2))+'\n' + ' Up tick volume % ==> ' + t(up_tick_volume_percent)+ ' %'+'\n' + ' Total volume ==> ' + t(math.round(up_tick_volume + down_tick_volume, 0))+'\n' + ' Candle completion ==> ' + t(candle_progress) +' %' data_box := box.new(left = bar_index + 2, top = high+syminfo.mintick*100, right = bar_index + 20, bottom = low-syminfo.mintick*100, text = box_text, text_size = size.normal, text_color = text_color, bgcolor = box_color, border_color = box_color, text_halign = text.align_left) if(not na(data_box[1])) box.delete(data_box[1]) //===== Sscenario 1 if(close > open and strategy.position_size == 0 and ((ticks_from_beginnig and tick_no == entry_on_ticks and succ_up_ticks == entry_on_ticks) or (not ticks_from_beginnig and succ_up_ticks == entry_on_ticks))) trade_candle_no := candle_cnt strategy.entry(id = 'Long', direction = strategy.long, comment = 'LE@tick: '+ t(tick_no) +' Candle: '+t(candle_cnt)) if(close < open and strategy.position_size == 0 and ((ticks_from_beginnig and tick_no == entry_on_ticks and succ_down_ticks == entry_on_ticks) or (not ticks_from_beginnig and succ_down_ticks == entry_on_ticks))) trade_candle_no := candle_cnt strategy.entry(id = 'Short', direction = strategy.short, comment = 'SE@tick: '+ t(tick_no) +' Candle: '+t(candle_cnt)) if((exit_on_same_candle and succ_down_ticks == exit_on_ticks) or (not exit_on_same_candle and candle_cnt > trade_candle_no and succ_down_ticks == exit_on_ticks)) strategy.close(id = 'Long', comment = 'LX@tick: '+ t(tick_no) + ' Candle: '+t(candle_cnt)) if((exit_on_same_candle and succ_up_ticks == exit_on_ticks) or (not exit_on_same_candle and candle_cnt > trade_candle_no and succ_up_ticks == exit_on_ticks)) strategy.close(id = 'Short', comment = 'SX@tick: '+ t(tick_no) + ' Candle: '+t(candle_cnt)) prev_tick_price := close prev_tick_volume := volume
Strategy Myth-Busting #6 - PSAR+MA+SQZMOM+HVI - [MYN]
https://www.tradingview.com/script/wkb7JqzN-Strategy-Myth-Busting-6-PSAR-MA-SQZMOM-HVI-MYN/
myncrypto
https://www.tradingview.com/u/myncrypto/
583
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© myn //@version=5 strategy('Strategy Myth-Busting #6 - PSAR+MA+SQZMOM+HVI - [MYN]', max_bars_back=5000, overlay=true, pyramiding=0, initial_capital=20000, currency='USD', default_qty_type=strategy.percent_of_equity, default_qty_value=100.0, commission_value=0.075, use_bar_magnifier = false) ///////////////////////////////////// //* Put your strategy logic below *// ///////////////////////////////////// // dOg28adjYWY //Trading Strategies Used // Parabolic Sar // 10 in 1 MA's // Squeeze Momentum // HawkEYE Volume Indicator // Long Condition // Parabolic Sar shift below price at last dot above and then previous bar needs to breach above that. // Price action has to be below both MA's and 50MA needs to be above 200MA // Squeeze Momentum needsd to be in green or close to going green // HawkEYE Volume Indicator needs to be show a green bar on the histagram // Short Condition // Parabolic Sar shift above price at last dot below and then previous bar needs to breach below that. // Price action needs to be above both MA's and 50MA needs to be below 200MA // Squeeze Momentum needsd to be in red or close to going red // HawkEYE Volume Indicator needs to be show a red bar on the histagram // Parabolic SAR //β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Functions // Dynamic Max based on trendcode int trendCodeAdaptive = switch timeframe.multiplier 1 => 1 3 => 1 5 => 1 10 => 2 15 => 3 30 => 5 45 => 5 60 => 7 120 => 9 180 => 9 240 => 13 300 => 14 360 => 15 => int(4) bool overrideAdaptiveSar = input(false, title="Override Adaptive PSAR", group="Adaptive Parabolic Sar") TrendCodeOverRide = input(5, title='Trend Code (If Overriding Adaptive PSAR)') startPSAR = 0.02 increment = 0.02 maximum = overrideAdaptiveSar ? TrendCodeOverRide * 0.005 : trendCodeAdaptive * 0.005 psar = ta.sar(startPSAR, increment, maximum) dir = psar < close ? 1 : -1 psarColor = dir == 1 ? #00c3ff : #ff0062 psarPlot = plot(psar, title='PSAR', style=plot.style_circles, linewidth=3, color=psarColor, transp=0) var color longColor = color.green var color shortColor = color.red PSARLongEntry = dir == 1 and dir[1] == -1 PSARShortEntry = dir == -1 and dir[1] == 1 // Squeeze Momentum //β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ //@version=5 // @author LazyBear // List of all my indicators: https://www.tradingview.com/v/4IneGo8h/ // //indicator(shorttitle='SQZMOM_LB', title='Squeeze Momentum Indicator [LazyBear]', overlay=false) lengthBB = input(20, title='BB Length', group="Squeeze Momentum") mult = input(2.0, title='BB MultFactor') lengthKC = input(20, title='KC Length') multKC = input(1.5, title='KC MultFactor') useTrueRange = input(true, title='Use TrueRange (KC)') // Calculate BB source = close basis = ta.sma(source, lengthBB) dev = multKC * ta.stdev(source, lengthBB) upperBB = basis + dev lowerBB = basis - dev // Calculate KC ma = ta.sma(source, lengthKC) range_1 = useTrueRange ? ta.tr : high - low rangema = ta.sma(range_1, lengthKC) upperKC = ma + rangema * multKC lowerKC = ma - rangema * multKC sqzOn = lowerBB > lowerKC and upperBB < upperKC sqzOff = lowerBB < lowerKC and upperBB > upperKC noSqz = sqzOn == false and sqzOff == false val = ta.linreg(source - math.avg(math.avg(ta.highest(high, lengthKC), ta.lowest(low, lengthKC)), ta.sma(close, lengthKC)), lengthKC, 0) iff_1 = val > nz(val[1]) ? color.lime : color.green iff_2 = val < nz(val[1]) ? color.red : color.maroon bcolor = val > 0 ? iff_1 : iff_2 scolor = noSqz ? color.blue : sqzOn ? color.black : color.gray //plot(val, color=bcolor, style=plot.style_histogram, linewidth=4) //plot(0, color=scolor, style=plot.style_cross, linewidth=2) SQZMOMLongEntry = val > 0 SQZMOMShortEntry = val < 0 // 10 in 1 Different Moving Averages //β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Β© hiimannshu //@version=5 // This indicator is just a simple indicator which plot any kind of multiple (atmost 10) moving everage (sma/ema/wma/rma/hma/vwma) on chart. // Enjoy the new update //indicator(title='10 in 1 Different Moving Averages ( SMA/EMA/WMA/RMA/HMA/VWMA )', shorttitle=' 10 in 1 MAs', overlay=true) bool plot_ma_1 = input.bool(true, '', inline='MA 1',group= "Multi Timeframe Moving Averages") string ma_1_type = input.string(defval='EMA', title='MA 1', options=['RMA', 'SMA', 'EMA', 'WMA','HMA','VWMA'], inline='MA 1',group= "Multi Timeframe Moving Averages") int ma_1_val = input.int(200, '', minval=1, inline='MA 1',group= "Multi Timeframe Moving Averages") ma1_tf = input.timeframe(title='', defval='', inline='MA 1',group= "Multi Timeframe Moving Averages") color ma_1_colour = input.color(color.green, '', inline='MA 1',group= "Multi Timeframe Moving Averages") bool plot_ma_2 = input.bool(true, '', inline='MA 2',group= "Multi Timeframe Moving Averages") string ma_2_type = input.string(defval='SMA', title='MA 2 ', options=['RMA', 'SMA', 'EMA', 'WMA','HMA','VWMA'], inline='MA 2',group= "Multi Timeframe Moving Averages") int ma_2_val = input.int(50, '', minval=1, inline='MA 2',group= "Multi Timeframe Moving Averages") ma2_tf = input.timeframe(title='', defval='', inline='MA 2',group= "Multi Timeframe Moving Averages") color ma_2_colour = input.color(color.yellow, '', inline='MA 2',group= "Multi Timeframe Moving Averages") bool plot_ma_3 = input.bool(false, '', inline='MA 3',group= "Multi Timeframe Moving Averages") string ma_3_type = input.string(defval='SMA', title='MA 3 ', options=['RMA', 'SMA', 'EMA', 'WMA','HMA','VWMA'], inline='MA 3',group= "Multi Timeframe Moving Averages") int ma_3_val = input.int(1, '', minval=1, inline='MA 3',group= "Multi Timeframe Moving Averages") ma3_tf = input.timeframe(title='', defval='', inline='MA 3',group= "Multi Timeframe Moving Averages") color ma_3_colour = input.color(color.black, '', inline='MA 3',group= "Multi Timeframe Moving Averages") bool plot_ma_4 = input.bool(false, '', inline='MA 4',group= "Multi Timeframe Moving Averages") string ma_4_type = input.string(defval='SMA', title='MA 4 ', options=['RMA', 'SMA', 'EMA', 'WMA','HMA','VWMA'], inline='MA 4',group= "Multi Timeframe Moving Averages") int ma_4_val = input.int(1, '', minval=1, inline='MA 4',group= "Multi Timeframe Moving Averages") ma4_tf = input.timeframe(title='', defval='', inline='MA 4',group= "Multi Timeframe Moving Averages") color ma_4_colour = input.color(color.black, '', inline='MA 4',group= "Multi Timeframe Moving Averages") bool plot_ma_5 = input.bool(false, '', inline='MA 5',group= "Multi Timeframe Moving Averages") string ma_5_type = input.string(defval='SMA', title='MA 5 ', options=['RMA', 'SMA', 'EMA', 'WMA','HMA','VWMA'], inline='MA 5',group= "Multi Timeframe Moving Averages") int ma_5_val = input.int(1, '', minval=1, inline='MA 5',group= "Multi Timeframe Moving Averages") ma5_tf = input.timeframe(title='', defval='', inline='MA 5',group= "Multi Timeframe Moving Averages") color ma_5_colour = input.color(color.black, '', inline='MA 5',group= "Multi Timeframe Moving Averages") bool plot_ma_6 = input.bool(false, '', inline='MA 6',group= "Normal Moving Averages") string ma_6_type = input.string(defval='SMA', title='MA 6 ', options=['RMA', 'SMA', 'EMA', 'WMA','HMA','VWMA'], inline='MA 6',group= "Normal Moving Averages") int ma_6_val = input.int(1, '', minval=1, inline='MA 6',group= "Normal Moving Averages") ma_6_src = input.source(defval=close, title='', inline='MA 6',group= "Normal Moving Averages") color ma_6_colour = input.color(color.black, '', inline='MA 6',group= "Normal Moving Averages") bool plot_ma_7 = input.bool(false, '', inline='MA 7',group= "Normal Moving Averages") string ma_7_type = input.string(defval='SMA', title='MA 7 ', options=['RMA', 'SMA', 'EMA', 'WMA','HMA','VWMA'], inline='MA 7',group= "Normal Moving Averages") int ma_7_val = input.int(1, '', minval=1, inline='MA 7',group= "Normal Moving Averages") ma_7_src = input.source(defval=close, title='', inline='MA 7',group= "Normal Moving Averages") color ma_7_colour = input.color(color.black, '', inline='MA 7',group= "Normal Moving Averages") bool plot_ma_8 = input.bool(false, '', inline='MA 8',group= "Normal Moving Averages") string ma_8_type = input.string(defval='SMA', title='MA 8', options=['RMA', 'SMA', 'EMA', 'WMA','HMA','VWMA'], inline='MA 8',group= "Normal Moving Averages") int ma_8_val = input.int(1, '', minval=1, inline='MA 8',group= "Normal Moving Averages") ma_8_src = input.source(defval=close, title='', inline='MA 8',group= "Normal Moving Averages") color ma_8_colour = input.color(color.black, '', inline='MA 8',group= "Normal Moving Averages") bool plot_ma_9 = input.bool(false, '', inline='MA 9',group= "Normal Moving Averages") string ma_9_type = input.string(defval='SMA', title='MA 9 ', options=['RMA', 'SMA', 'EMA', 'WMA','HMA','VWMA'], inline='MA 9',group= "Normal Moving Averages") int ma_9_val = input.int(1, '', minval=1, inline='MA 9',group= "Normal Moving Averages") ma_9_src = input.source(defval=close, title='', inline='MA 9',group= "Normal Moving Averages") color ma_9_colour = input.color(color.black, '', inline='MA 9',group= "Normal Moving Averages") bool plot_ma_10 = input.bool(false, '', inline='MA 10',group= "Normal Moving Averages") string ma_10_type = input.string(defval='SMA', title='MA 10', options=['RMA', 'SMA', 'EMA', 'WMA','HMA','VWMA'], inline='MA 10',group= "Normal Moving Averages") int ma_10_val = input.int(1, '', minval=1, inline='MA 10',group= "Normal Moving Averages") ma_10_src = input.source(defval=close, title='', inline='MA 10',group= "Normal Moving Averages") color ma_10_colour = input.color(color.black, '', inline='MA 10',group= "Normal Moving Averages") ma_function(source, length, type) => if type == 'RMA' ta.rma(source, length) else if type == 'SMA' ta.sma(source, length) else if type == 'EMA' ta.ema(source, length) else if type == 'WMA' ta.wma(source, length) else if type == 'HMA' if(length<2) ta.hma(source,2) else ta.hma(source, length) else ta.vwma(source, length) ma_1 = plot_ma_1 ? request.security(syminfo.tickerid, ma1_tf, ma_function(close, ma_1_val, ma_1_type)):0 ma_2 = plot_ma_2 ?request.security(syminfo.tickerid, ma2_tf, ma_function(close, ma_2_val, ma_2_type)):0 ma_3 = plot_ma_3 ?request.security(syminfo.tickerid, ma3_tf, ma_function(close, ma_3_val, ma_3_type)):0 ma_4 = plot_ma_4 ? request.security(syminfo.tickerid, ma4_tf, ma_function(close, ma_4_val, ma_4_type)):0 ma_5 = plot_ma_5 ?request.security(syminfo.tickerid, ma5_tf, ma_function(close, ma_5_val, ma_5_type)):0 ma_6 = plot_ma_6 ?ma_function(ma_6_src, ma_6_val, ma_6_type):0 ma_7 = plot_ma_7 ?ma_function(ma_7_src, ma_7_val, ma_7_type):0 ma_8 = plot_ma_8 ?ma_function(ma_8_src, ma_8_val, ma_8_type):0 ma_9 = plot_ma_9 ?ma_function(ma_9_src, ma_9_val, ma_9_type):0 ma_10 = plot_ma_10 ?ma_function(ma_10_src, ma_10_val, ma_10_type):0 plot(plot_ma_1 ? ma_1 : na, 'MA 1', ma_1_colour) plot(plot_ma_2 ? ma_2 : na, 'MA 2', ma_2_colour) plot(plot_ma_3 ? ma_3 : na, 'MA 3', ma_3_colour) plot(plot_ma_4 ? ma_4 : na, 'MA 4', ma_4_colour) plot(plot_ma_5 ? ma_5 : na, 'MA 5', ma_5_colour) plot(plot_ma_6 ? ma_6 : na, 'MA 6', ma_6_colour) plot(plot_ma_7 ? ma_7 : na, 'MA 7', ma_7_colour) plot(plot_ma_8 ? ma_8 : na, 'MA 8', ma_8_colour) plot(plot_ma_9 ? ma_9 : na, 'MA 9', ma_9_colour) plot(plot_ma_10 ? ma_10 : na, 'MA 10', ma_10_colour) // Long entry - Price has to be below both MA's and 50MA needs to be above 200MA MALongEntry = (close > ma_1 and close > ma_2) and (ma_2 > ma_1) // Short Entry - Price has to be above both MA's and 50MA needs to be below 200MA MAShortEntry = (close < ma_1 and close < ma_2) and (ma_2 < ma_1) // HawkEYE Volume Indicator //β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ //@version=5 // @author LazyBear // If you use this code, in its original or modified form, do drop me a note. Thx. // //indicator('HawkEye Volume Indicator [LazyBear]', shorttitle='HVI_LB') lengthhvi = input(200, group="HawkEye Volume Indicator") range_1HVI = high - low rangeAvg = ta.sma(range_1HVI, lengthhvi) volumeA = ta.sma(volume, lengthhvi) divisor = input(1) high1 = high[1] low1 = low[1] mid1 = hl2[1] u1 = mid1 + (high1 - low1) / divisor d1 = mid1 - (high1 - low1) / divisor r_enabled1 = range_1HVI > rangeAvg and close < d1 and volume > volumeA r_enabled2 = close < mid1 r_enabled = r_enabled1 or r_enabled2 g_enabled1 = close > mid1 g_enabled2 = range_1HVI > rangeAvg and close > u1 and volume > volumeA g_enabled3 = high > high1 and range_1HVI < rangeAvg / 1.5 and volume < volumeA g_enabled4 = low < low1 and range_1HVI < rangeAvg / 1.5 and volume > volumeA g_enabled = g_enabled1 or g_enabled2 or g_enabled3 or g_enabled4 gr_enabled1 = range_1HVI > rangeAvg and close > d1 and close < u1 and volume > volumeA and volume < volumeA * 1.5 and volume > volume[1] gr_enabled2 = range_1HVI < rangeAvg / 1.5 and volume < volumeA / 1.5 gr_enabled3 = close > d1 and close < u1 gr_enabled = gr_enabled1 or gr_enabled2 or gr_enabled3 v_color = gr_enabled ? color.gray : g_enabled ? color.green : r_enabled ? color.red : color.blue //plot(volume, style=plot.style_histogram, color=v_color, linewidth=5) HVILongEntry = g_enabled HVIShortEntry = r_enabled ////////////////////////////////////// //* Put your strategy rules below *// ///////////////////////////////////// longCondition = PSARLongEntry and MALongEntry and HVILongEntry and SQZMOMLongEntry shortCondition = PSARShortEntry and MAShortEntry and HVIShortEntry and SQZMOMShortEntry //define as 0 if do not want to use closeLongCondition = 0 closeShortCondition = 0 // ADX //β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ adxEnabled = input.bool(defval = false , title = "Average Directional Index (ADX)", tooltip = "", group ="ADX" ) adxlen = input(14, title="ADX Smoothing", group="ADX") adxdilen = input(14, title="DI Length", group="ADX") adxabove = input(25, title="ADX Threshold", group="ADX") adxdirmov(len) => adxup = ta.change(high) adxdown = -ta.change(low) adxplusDM = na(adxup) ? na : (adxup > adxdown and adxup > 0 ? adxup : 0) adxminusDM = na(adxdown) ? na : (adxdown > adxup and adxdown > 0 ? adxdown : 0) adxtruerange = ta.rma(ta.tr, len) adxplus = fixnan(100 * ta.rma(adxplusDM, len) / adxtruerange) adxminus = fixnan(100 * ta.rma(adxminusDM, len) / adxtruerange) [adxplus, adxminus] adx(adxdilen, adxlen) => [adxplus, adxminus] = adxdirmov(adxdilen) adxsum = adxplus + adxminus adx = 100 * ta.rma(math.abs(adxplus - adxminus) / (adxsum == 0 ? 1 : adxsum), adxlen) adxsig = adxEnabled ? adx(adxdilen, adxlen) : na isADXEnabledAndAboveThreshold = adxEnabled ? (adxsig > adxabove) : true //Backtesting Time Period (Input.time not working as expected as of 03/30/2021. Giving odd start/end dates //β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ useStartPeriodTime = input.bool(true, 'Start', group='Date Range', inline='Start Period') startPeriodTime = input.time(timestamp('1 Jan 2019'), '', group='Date Range', inline='Start Period') useEndPeriodTime = input.bool(true, 'End', group='Date Range', inline='End Period') endPeriodTime = input.time(timestamp('31 Dec 2030'), '', group='Date Range', inline='End Period') start = useStartPeriodTime ? startPeriodTime >= time : false end = useEndPeriodTime ? endPeriodTime <= time : false calcPeriod = not start and not end // Trade Direction // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ tradeDirection = input.string('Long and Short', title='Trade Direction', options=['Long and Short', 'Long Only', 'Short Only'], group='Trade Direction') // Percent as Points // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ per(pcnt) => strategy.position_size != 0 ? math.round(pcnt / 100 * strategy.position_avg_price / syminfo.mintick) : float(na) // Take profit 1 // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ tp1 = input.float(title='Take Profit 1 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 1') q1 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 1') // Take profit 2 // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ tp2 = input.float(title='Take Profit 2 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 2') q2 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 2') // Take profit 3 // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ tp3 = input.float(title='Take Profit 3 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 3') q3 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 3') // Take profit 4 // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ tp4 = input.float(title='Take Profit 4 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit') /// Stop Loss // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ stoplossPercent = input.float(title='Stop Loss (%)', defval=999, minval=0.01, group='Stop Loss') * 0.01 slLongClose = close < strategy.position_avg_price * (1 - stoplossPercent) slShortClose = close > strategy.position_avg_price * (1 + stoplossPercent) /// Leverage // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ leverage = input.float(1, 'Leverage', step=.5, group='Leverage') contracts = math.min(math.max(.000001, strategy.equity / close * leverage), 1000000000) /// Trade State Management // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ isInLongPosition = strategy.position_size > 0 isInShortPosition = strategy.position_size < 0 /// ProfitView Alert Syntax String Generation // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ alertSyntaxPrefix = input.string(defval='CRYPTANEX_99FTX_Strategy-Name-Here', title='Alert Syntax Prefix', group='ProfitView Alert Syntax') alertSyntaxBase = alertSyntaxPrefix + '\n#' + str.tostring(open) + ',' + str.tostring(high) + ',' + str.tostring(low) + ',' + str.tostring(close) + ',' + str.tostring(volume) + ',' /// Trade Execution // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ longConditionCalc = (longCondition and isADXEnabledAndAboveThreshold) shortConditionCalc = (shortCondition and isADXEnabledAndAboveThreshold) if calcPeriod if longConditionCalc and tradeDirection != 'Short Only' and isInLongPosition == false strategy.entry('Long', strategy.long, qty=contracts) alert(message=alertSyntaxBase + 'side:long', freq=alert.freq_once_per_bar_close) if shortConditionCalc and tradeDirection != 'Long Only' and isInShortPosition == false strategy.entry('Short', strategy.short, qty=contracts) alert(message=alertSyntaxBase + 'side:short', freq=alert.freq_once_per_bar_close) //Inspired from Multiple %% profit exits example by adolgo https://www.tradingview.com/script/kHhCik9f-Multiple-profit-exits-example/ strategy.exit('TP1', qty_percent=q1, profit=per(tp1)) strategy.exit('TP2', qty_percent=q2, profit=per(tp2)) strategy.exit('TP3', qty_percent=q3, profit=per(tp3)) strategy.exit('TP4', profit=per(tp4)) strategy.close('Long', qty_percent=100, comment='SL Long', when=slLongClose) strategy.close('Short', qty_percent=100, comment='SL Short', when=slShortClose) strategy.close_all(when=closeLongCondition or closeShortCondition, comment='Close Postion') /// Dashboard // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Inspired by https://www.tradingview.com/script/uWqKX6A2/ - Thanks VertMT showDashboard = input.bool(group="Dashboard", title="Show Dashboard", defval=true) f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) => _cellText = _title + "\n" + _value table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor, text_size=size.auto) // Draw dashboard table if showDashboard var bgcolor = color.new(color.black,0) // Keep track of Wins/Losses streaks newWin = (strategy.wintrades > strategy.wintrades[1]) and (strategy.losstrades == strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1]) newLoss = (strategy.wintrades == strategy.wintrades[1]) and (strategy.losstrades > strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1]) varip int winRow = 0 varip int lossRow = 0 varip int maxWinRow = 0 varip int maxLossRow = 0 if newWin lossRow := 0 winRow := winRow + 1 if winRow > maxWinRow maxWinRow := winRow if newLoss winRow := 0 lossRow := lossRow + 1 if lossRow > maxLossRow maxLossRow := lossRow // Prepare stats table var table dashTable = table.new(position.bottom_right, 1, 15, border_width=1) if barstate.islastconfirmedhistory // Update table dollarReturn = strategy.netprofit f_fillCell(dashTable, 0, 0, "Start:", str.format("{0,date,long}", strategy.closedtrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.closedtrades.entry_time(0)) f_fillCell(dashTable, 0, 1, "End:", str.format("{0,date,long}", strategy.opentrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.opentrades.entry_time(0)) _profit = (strategy.netprofit / strategy.initial_capital) * 100 f_fillCell(dashTable, 0, 2, "Net Profit:", str.tostring(_profit, '##.##') + "%", _profit > 0 ? color.green : color.red, color.white) _numOfDaysInStrategy = (strategy.opentrades.entry_time(0) - strategy.closedtrades.entry_time(0)) / (1000 * 3600 * 24) f_fillCell(dashTable, 0, 3, "Percent Per Day", str.tostring(_profit / _numOfDaysInStrategy, '#########################.#####')+"%", _profit > 0 ? color.green : color.red, color.white) _winRate = ( strategy.wintrades / strategy.closedtrades ) * 100 f_fillCell(dashTable, 0, 4, "Percent Profitable:", str.tostring(_winRate, '##.##') + "%", _winRate < 50 ? color.red : _winRate < 75 ? #999900 : color.green, color.white) f_fillCell(dashTable, 0, 5, "Profit Factor:", str.tostring(strategy.grossprofit / strategy.grossloss, '##.###'), strategy.grossprofit > strategy.grossloss ? color.green : color.red, color.white) f_fillCell(dashTable, 0, 6, "Total Trades:", str.tostring(strategy.closedtrades), bgcolor, color.white) f_fillCell(dashTable, 0, 8, "Max Wins In A Row:", str.tostring(maxWinRow, '######') , bgcolor, color.white) f_fillCell(dashTable, 0, 9, "Max Losses In A Row:", str.tostring(maxLossRow, '######') , bgcolor, color.white)
Fake Strategy
https://www.tradingview.com/script/ekQPU4LF-Fake-Strategy/
UnknownUnicorn14312093
https://www.tradingview.com/u/UnknownUnicorn14312093/
84
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© strategydebunker //@version=5 strategy("Fake Strategy", overlay=true, initial_capital=1000, default_qty_value=100, default_qty_type=strategy.percent_of_equity, commission_type=strategy.commission.percent, commission_value=0.1) import PineCoders/Time/3 as t resolution = t.secondsToTfString(timeframe.in_seconds(timeframe.period), 2) [htfClose, htfHigh, htfLow] = request.security(syminfo.tickerid, resolution, [close, high, low], lookahead=barmerge.lookahead_on) if(close!=htfClose and htfHigh > high and bar_index > last_bar_index-5000) strategy.entry('Long', strategy.long) strategy.exit("ExitLong", "Long", limit=htfHigh, stop=htfLow-ta.tr)
MA Simple Strategy with SL & TP & ATR Filters
https://www.tradingview.com/script/BNMeQJfS/
DuDu95
https://www.tradingview.com/u/DuDu95/
134
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© fpemehd // @version=5 // # ========================================================================= # // # | STRATEGY | // # ========================================================================= # strategy(title = 'MA Simple Strategy with SL & TP & ATR Filters', shorttitle = 'MA Strategy', overlay = true, pyramiding = 0, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, commission_value = 0.1, initial_capital = 100000, max_lines_count = 150, max_labels_count = 300) // # ========================================================================= # // # Inputs // # ========================================================================= # // 1. Time i_start = input.time (defval = timestamp("20 Jan 1990 00:00 +0900"), title = "Start Date", tooltip = "Choose Backtest Start Date", inline = "Start Date", group = "Time" ) i_end = input.time (defval = timestamp("20 Dec 2030 00:00 +0900"), title = "End Date", tooltip = "Choose Backtest End Date", inline = "End Date", group = "Time" ) c_timeCond = time >= i_start and time <= i_end // 2. Inputs for direction: Long? Short? Both? i_longEnabled = input.bool(defval = true , title = "Long?", tooltip = "Enable Long Position Trade?", inline = "Long / Short", group = "Long / Short" ) i_shortEnabled = input.bool(defval = true , title = "Short?", tooltip = "Enable Short Position Trade?", inline = "Long / Short", group = "Long / Short" ) // 3. Use Filters? What Filters? i_ATRFilterOn = input.bool(defval = true , title = "ATR Filter On?", tooltip = "ATR Filter On?", inline = "ATR Filter", group = "Filters") i_ATRSMALen = input.int(defval = 40 , title = "SMA Length for ATR SMA", minval = 1 , maxval = 100000 , step = 1 , tooltip = "ATR should be bigger than this", inline = "ATR Filter", group = "Filters") // 3. Shared inputs for Long and Short //// 3-1. Inputs for Stop Loss Type: normal? or trailing? //// If trailing, always trailing or trailing after take profit order executed? i_useSLTP = input.bool(defval = true, title = "Enable SL & TP?", tooltip = "", inline = "Enable SL & TP & SL Type", group = "Shared Inputs") i_tslEnabled = input.bool(defval = false , title = "Enable Trailing SL?", tooltip = "Enable Stop Loss & Take Profit? \n\Enable Trailing SL?", inline = "Enable SL & TP & SL Type", group = "Shared Inputs") // i_tslAfterTP = input.bool(defval = true , title = "Enable Trailing SL after TP?", tooltip = "Enable Trailing SL after TP?", inline = "Trailing SL Execution", group = "Shared Inputs") i_slType = input.string(defval = "ATR", title = "Stop Loss Type", options = ["Percent", "ATR"], tooltip = "Stop Loss based on %? ATR?", inline = "Stop Loss Type", group = "Shared Inputs") i_slATRLen = input.int(defval = 14, title = "ATR Length", minval = 1 , maxval = 200 , step = 1, inline = "Stop Loss ATR", group = "Shared Inputs") i_tpType = input.string(defval = "R:R", title = "Take Profit Type", options = ["Percent", "ATR", "R:R"], tooltip = "Take Profit based on %? ATR? R-R ratio?", inline = "Take Profit Type", group = "Shared Inputs") //// 3-2. Inputs for Quantity i_tpQuantityPerc = input.float(defval = 50, title = 'Take Profit Quantity %', minval = 0.0, maxval = 100, step = 1.0, tooltip = '% of position when tp target is met.', group = 'Shared Inputs') // 4. Inputs for Long Stop Loss & Long Take Profit i_slPercentLong = input.float(defval = 3, title = "SL Percent", tooltip = "", inline = "Percent > Long Stop Loss / Take Profit Percent", group = "Long Stop Loss / Take Profit") i_tpPercentLong = input.float(defval = 3, title = "TP Percent", tooltip = "Long Stop Loss && Take Profit Percent?", inline = "Percent > Long Stop Loss / Take Profit Percent", group = "Long Stop Loss / Take Profit") i_slATRMultLong = input.float(defval = 3, title = "SL ATR Multiplier", minval = 1 , maxval = 200 , step = 0.1, tooltip = "", inline = "Long Stop Loss / Take Profit ATR", group = "Long Stop Loss / Take Profit") i_tpATRMultLong = input.float(defval = 3, title = "TP ATR Multiplier", minval = 1 , maxval = 200 , step = 0.1, tooltip = "ATR > Long Stop Loss && Take Profit ATR Multiplier? \n\Stop Loss = i_slATRMultLong * ATR (i_slATRLen) \n\Take Profit = i_tpATRMultLong * ATR (i_tpATRLen)", inline = "Long Stop Loss / Take Profit ATR", group = "Long Stop Loss / Take Profit") i_tpRRratioLong = input.float(defval = 1.8, title = "R:R Ratio", minval = 0.1 , maxval = 200 , step = 0.1, tooltip = "R:R Ratio > Risk Reward Ratio? It will automatically set Take Profit % based on Stop Loss", inline = "R:R Ratio", group = "Long Stop Loss / Take Profit") // 5. Inputs for Short Stop Loss & Short Take Profit i_slPercentShort = input.float(defval = 3, title = "SL Percent", tooltip = "", inline = "Percent > Short Stop Loss / Take Profit Percent", group = "Short Stop Loss / Take Profit") i_tpPercentShort = input.float(defval = 3, title = "TP Percent", tooltip = "Short Stop Loss && Take Profit Percent?", inline = "Percent > Short Stop Loss / Take Profit Percent", group = "Short Stop Loss / Take Profit") i_slATRMultShort = input.float(defval = 3, title = "SL ATR Multiplier", minval = 1 , maxval = 200 , step = 0.1, tooltip = "", inline = "ATR > Short Stop Loss / Take Profit ATR", group = "Short Stop Loss / Take Profit") i_tpATRMultShort = input.float(defval = 3, title = "TP ATR Multiplier", minval = 1 , maxval = 200 , step = 0.1, tooltip = "ATR > Short Stop Loss && Take Profit ATR Multiplier? \n\Stop Loss = i_slATRMultShort * ATR (i_slATRLen) \n\Take Profit = i_tpATRMultShort * ATR (i_tpATRLen)", inline = "ATR > Short Stop Loss / Take Profit ATR", group = "Short Stop Loss / Take Profit") i_tpRRratioShort = input.float(defval = 1.8, title = "R:R Ratio", minval = 0.1 , maxval = 200 , step = 0.1, tooltip = "R:R Ratio > Risk Reward Ratio? It will automatically set Take Profit % based on Stop Loss", inline = "R:R Ratio", group = "Short Stop Loss / Take Profit") // 6. Inputs for logic i_MAType = input.string(defval = "RMA", title = "MA Type", options = ["SMA", "EMA", "WMA", "HMA", "RMA", "VWMA", "SWMA", "ALMA", "VWAP"], tooltip = "Choose MA Type", inline = "MA Type", group = 'Strategy') i_MA1Len = input.int(defval = 5, title = 'MA 1 Length', minval = 1, inline = 'MA Length', group = 'Strategy') i_MA2Len = input.int(defval = 10, title = 'MA 2 Length', minval = 1, inline = 'MA Length', group = 'Strategy') i_MA3Len = input.int(defval = 15, title = 'MA 3 Length', minval = 1, inline = 'MA Length', group = 'Strategy') i_MA4Len = input.int(defval = 25, title = 'MA 4 Length', minval = 1, inline = 'MA Length', group = 'Strategy') i_ALMAOffset = input.float(defval = 0.7 , title = "ALMA Offset Value", tooltip = "The Value of ALMA offset", inline = "ALMA Input", group = 'Strategy') i_ALMASigma = input.float(defval = 7 , title = "ALMA Sigma Value", tooltip = "The Value of ALMA sigma", inline = "ALMA Input", group = 'Strategy') // # ========================================================================= # // # Entry, Close Logic // # ========================================================================= # bool i_ATRFilter = ta.atr(length = i_slATRLen) >= ta.sma(source = ta.atr(length = i_slATRLen), length = i_ATRSMALen) ? true : false // calculate Technical Indicators for the Logic getMAValue (source, length, almaOffset, almaSigma) => switch i_MAType 'SMA' => ta.sma(source = source, length = length) 'EMA' => ta.ema(source = source, length = length) 'WMA' => ta.wma(source = source, length = length) 'HMA' => ta.hma(source = source, length = length) 'RMA' => ta.rma(source = source, length = length) 'SWMA' => ta.swma(source = source) 'ALMA' => ta.alma(series = source, length = length, offset = almaOffset, sigma = almaSigma) 'VWMA' => ta.vwma(source = source, length = length) 'VWAP' => ta.vwap(source = source) => na float c_MA1 = getMAValue(close, i_MA1Len, i_ALMAOffset, i_ALMASigma) float c_MA2 = getMAValue(close, i_MA2Len, i_ALMAOffset, i_ALMASigma) float c_MA3 = getMAValue(close, i_MA3Len, i_ALMAOffset, i_ALMASigma) float c_MA4 = getMAValue(close, i_MA4Len, i_ALMAOffset, i_ALMASigma) // Logic: μ •λ°°μ—΄ 될 λ–„ λ“€μ–΄κ°€ var ma1Color = color.new(color.red, 0) plot(series = c_MA1, title = 'SMA 1', color = ma1Color, linewidth = 1, style = plot.style_line) var ma2Color = color.new(color.orange, 0) plot(series = c_MA2, title = 'SMA 2', color = ma2Color, linewidth = 1, style = plot.style_line) var ma3Color = color.new(color.yellow, 0) plot(series = c_MA3, title = 'SMA 3', color = ma3Color, linewidth = 1, style = plot.style_line) var ma4Color = color.new(color.green, 0) plot(series = c_MA4, title = 'SMA 4', color = ma4Color, linewidth = 1, style = plot.style_line) bool openLongCond = (c_MA1 >= c_MA2 and c_MA2 >= c_MA3 and c_MA3 >= c_MA4) bool openShortCond = (c_MA1 <= c_MA2 and c_MA2 <= c_MA3 and c_MA3 <= c_MA4) bool openLong = i_longEnabled and openLongCond and (not i_ATRFilterOn or i_ATRFilter) bool openShort = i_shortEnabled and openShortCond and (not i_ATRFilterOn or i_ATRFilter) openLongCondColor = openLongCond ? color.new(color = color.blue, transp = 80) : na bgcolor(color = openLongCondColor) ATRFilterColor = i_ATRFilter ? color.new(color = color.orange, transp = 80) : na bgcolor(color = ATRFilterColor) bool enterLong = openLong and not (strategy.opentrades.size(strategy.opentrades-1) > 0) bool enterShort = openShort and not (strategy.opentrades.size(strategy.opentrades-1) < 0) bool closeLong = i_longEnabled and (c_MA1[1] >= c_MA2[1] and c_MA2[1] >= c_MA3[1] and c_MA3[1] >= c_MA4[1]) and not (c_MA1 >= c_MA2 and c_MA2 >= c_MA3 and c_MA3 >= c_MA4) bool closeShort = i_shortEnabled and (c_MA1[1] <= c_MA2[1] and c_MA2[1] <= c_MA3[1] and c_MA3[1] <= c_MA4[1]) and not (c_MA1 <= c_MA2 and c_MA2 <= c_MA3 and c_MA3 <= c_MA4) // # ========================================================================= # // # Position, Status Conrtol // # ========================================================================= # // longisActive: New Long || Already Long && not closeLong, short is the same bool longIsActive = enterLong or strategy.opentrades.size(strategy.opentrades - 1) > 0 and not closeLong bool shortIsActive = enterShort or strategy.opentrades.size(strategy.opentrades - 1) < 0 and not closeShort // before longTPExecution: no trailing SL && after longTPExecution: trailing SL starts // longTPExecution qunatity should be less than 100% bool longTPExecuted = false bool shortTPExecuted = false // # ========================================================================= # // # Long Stop Loss Logic // # ========================================================================= # float openAtr = ta.valuewhen(enterLong or enterShort, ta.atr(i_slATRLen), 0) f_getLongSL (source) => switch i_slType 'Percent' => source * (1 - (i_slPercentLong/100)) 'ATR' => source - i_slATRMultLong * openAtr => na var float c_longSLPrice = na c_longSLPrice := if (longIsActive) if (enterLong) f_getLongSL(close) else c_stopPrice = f_getLongSL(i_tslEnabled ? high : strategy.opentrades.entry_price(trade_num = strategy.opentrades - 1)) math.max(c_stopPrice, nz(c_longSLPrice[1])) else na // # ========================================================================= # // # Short Stop Loss Logic // # ========================================================================= # f_getShortSL (source) => switch i_slType 'Percent' => source * (1 + (i_slPercentShort)/100) 'ATR' => source + i_slATRMultShort * openAtr => na var float c_shortSLPrice = na c_shortSLPrice := if (shortIsActive) if (enterShort) f_getShortSL (close) else c_stopPrice = f_getShortSL(i_tslEnabled ? low : strategy.opentrades.entry_price(strategy.opentrades - 1)) math.min(c_stopPrice, nz(c_shortSLPrice[1], 999999.9)) else na // # ========================================================================= # // # Long Take Profit Logic // # ========================================================================= # f_getLongTP () => switch i_tpType 'Percent' => close * (1 + (i_tpPercentLong/100)) 'ATR' => close + i_tpATRMultLong * openAtr 'R:R' => close + i_tpRRratioLong * (close - f_getLongSL(close)) => na var float c_longTPPrice = na c_longTPPrice := if (longIsActive and not longTPExecuted) if (enterLong) f_getLongTP() else nz(c_longTPPrice[1], f_getLongTP()) else na longTPExecuted := strategy.opentrades.size(strategy.opentrades - 1) > 0 and (longTPExecuted[1] or strategy.opentrades.size(strategy.opentrades - 1) < strategy.opentrades.size(strategy.opentrades - 1)[1] or strategy.opentrades.size(strategy.opentrades - 1)[1] == 0 and high >= c_longTPPrice) // # ========================================================================= # // # Short Take Profit Logic // # ========================================================================= # f_getShortTP () => switch i_tpType 'Percent' => close * (1 - (i_tpPercentShort/100)) 'ATR' => close - i_tpATRMultShort * openAtr 'R:R' => close - i_tpRRratioShort * (close - f_getLongSL(close)) => na var float c_shortTPPrice = na c_shortTPPrice := if (shortIsActive and not shortTPExecuted) if (enterShort) f_getShortTP() else nz(c_shortTPPrice[1], f_getShortTP()) else na shortTPExecuted := strategy.opentrades.size(strategy.opentrades - 1) < 0 and (shortTPExecuted[1] or strategy.opentrades.size(strategy.opentrades - 1) > strategy.opentrades.size(strategy.opentrades - 1)[1] or strategy.opentrades.size(strategy.opentrades - 1)[1] == 0 and low <= c_shortTPPrice) // # ========================================================================= # // # Make Orders // # ========================================================================= # if (c_timeCond) if (enterLong) strategy.entry(id = "Long Entry", direction = strategy.long , comment = 'Long(' + syminfo.ticker + '): Started', alert_message = 'Long(' + syminfo.ticker + '): Started') if (enterShort) strategy.entry(id = "Short Entry", direction = strategy.short , comment = 'Short(' + syminfo.ticker + '): Started', alert_message = 'Short(' + syminfo.ticker + '): Started') if (closeLong) strategy.close(id = 'Long Entry', comment = 'Close Long', alert_message = 'Long: Closed at market price') if (closeShort) strategy.close(id = 'Short Entry', comment = 'Close Short', alert_message = 'Short: Closed at market price') if (longIsActive and i_useSLTP) strategy.exit(id = 'Long Take Profit / Stop Loss', from_entry = 'Long Entry', qty_percent = i_tpQuantityPerc, limit = c_longTPPrice, stop = c_longSLPrice, alert_message = 'Long(' + syminfo.ticker + '): Take Profit or Stop Loss executed') strategy.exit(id = 'Long Stop Loss', from_entry = 'Long Entry', stop = c_longSLPrice, alert_message = 'Long(' + syminfo.ticker + '): Stop Loss executed') if (shortIsActive and i_useSLTP) strategy.exit(id = 'Short Take Profit / Stop Loss', from_entry = 'Short Entry', qty_percent = i_tpQuantityPerc, limit = c_shortTPPrice, stop = c_shortSLPrice, alert_message = 'Short(' + syminfo.ticker + '): Take Profit or Stop Loss executed') strategy.exit(id = 'Short Stop Loss', from_entry = 'Short Entry', stop = c_shortSLPrice, alert_message = 'Short(' + syminfo.ticker + '): Stop Loss executed') // # ========================================================================= # // # Plot // # ========================================================================= # var posColor = color.new(color.white, 0) plot(series = strategy.opentrades.entry_price(strategy.opentrades - 1), title = 'Position', color = posColor, linewidth = 1, style = plot.style_linebr) var stopLossColor = color.new(color.maroon, 0) plot(series = c_longSLPrice, title = 'Long Stop Loss', color = stopLossColor, linewidth = 1, style = plot.style_linebr, offset = 1) plot(series = c_shortSLPrice, title = 'Short Stop Loss', color = stopLossColor, linewidth = 1, style = plot.style_linebr, offset = 1) longTPExecutedColor = longTPExecuted ? color.new(color = color.green, transp = 80) : na //bgcolor(color = longTPExecutedColor) shortTPExecutedColor = shortTPExecuted ? color.new(color = color.red, transp = 80) : na //bgcolor(color = shortTPExecutedColor) // isPositionOpenedColor = strategy.opentrades.size(strategy.opentrades-1) != 0 ? color.new(color = color.yellow, transp = 90) : na // bgcolor(color = isPositionOpenedColor) var takeProfitColor = color.new(color.teal, 0) plot(series = c_longTPPrice, title = 'Long Take Profit', color = takeProfitColor, linewidth = 1, style = plot.style_linebr, offset = 1) plot(series = c_shortTPPrice, title = 'Short Take Profit', color = takeProfitColor, linewidth = 1, style = plot.style_linebr, offset = 1)
Suchit RSI CCI
https://www.tradingview.com/script/i4msrNrT-Suchit-RSI-CCI/
SuchitRaju
https://www.tradingview.com/u/SuchitRaju/
23
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/ // Β© SuchitRaju //@version=4 strategy("MA RSI CCI") price_up = if(close > open and close > sma(hl2,14)) 1 else 0 price_down = if(open > close and close < sma(hl2,14)) 1 else 0 // cci_indicator = cci(hl2, 14) // plot(cci_indicator, color=color.blue) rsi_slow = sma(rsi(close, 14), 50) // plot(rsi_slow, color=color.red) rsi_fast = rsi(close, 14) // plot(rsi_fast, color=color.green) isCrossover = if(rsi_fast > rsi_slow and cci_indicator > 0) 1 else 0 // plotshape(isCrossover, style = shape.arrowup, color = color.green, size = size.huge) isCrossunder = if(rsi_fast < rsi_slow and cci_indicator < 0) 1 else 0 // plotshape(isCrossunder, style = shape.arrowup, color = color.red, size = size.huge) // start = timestamp("GMT-5", 2016,9,1,0,0) // end = timestamp("GMT-5", 2017,9,1,0,0) // strategy.entry("Long", strategy.long, 1, when = isCrossover and price_up) // strategy.entry("Short", strategy.short, 1, when = isCrossunder and price_down) // strategy.close("Long", when = isCrossunder and price_down) // strategy.close("Short", when = isCrossover and price_up) strategy.entry("Long", strategy.long, 1, when = isCrossover) strategy.entry("Short", strategy.short, 1, when = isCrossunder) strategy.close("Long", when = isCrossunder) strategy.close("Short", when = isCrossover)
Morning Scalp Strategy
https://www.tradingview.com/script/eYsUViQA-Morning-Scalp-Strategy/
Trading_Bites
https://www.tradingview.com/u/Trading_Bites/
206
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/ // Β© Trading_Bites //@version=5 strategy('Morning Scalp', overlay=false, pyramiding=2, initial_capital=3000, default_qty_value=0, commission_value=0.02, max_labels_count=500) // Initial Inputs StartDate = timestamp('15Aug 2022 14:00 +0000') EndDate = timestamp('15Aug 2022 20:00 +0000') testPeriodStart = input.time(StartDate, 'Start of trading') testPeriodEnd = input.time(EndDate, 'End of trading') QuantityOnLong = input.int(title="Quantity", defval=100, minval=1) QuantityOnClose = QuantityOnLong ////////////////////////////////////////////////////////////////////// //-- Time In Range timeinrange(res, sess) => not na(time(res, sess)) //Market Open// marketopen = '0930-1600' MarketOpen = timeinrange(timeframe.period, marketopen) ////////////////////////////////////////////////////////////////////// //Market Hour// morning = '1000-1210' Morning = timeinrange(timeframe.period, morning) ////////////////////////////////////////////////////////////////////////// //STOCK MOMENTUM INDEX// a = input(5, 'Percent K Length') b = input(3, 'Percent D Length') ovrsld = input.float(40, 'Over Bought') ovrbgt = input(-40, 'Over Sold') //lateleave = input(14, "Number of candles", type=input.integer) // Range Calculation ll = ta.lowest(low, a) hh = ta.highest(high, a) diff = hh - ll rdiff = close - (hh + ll) / 2 // Nested Moving Average for smoother curves avgrel = ta.ema(ta.ema(rdiff, b), b) avgdiff = ta.ema(ta.ema(diff, b), b) // SMI calculations SMI = avgdiff != 0 ? avgrel / (avgdiff / 2) * 100 : 0 SMIsignal = ta.ema(SMI, b) CrossoverIndex = ta.crossover(SMI, SMIsignal) CrossunderIndex = ta.crossunder(SMI, SMIsignal) plot1 = plot(SMI, color=color.new(color.aqua, 0), title='Stochastic Momentum Index', linewidth=1, style=plot.style_line) plot2 = plot(SMIsignal, color=color.new(color.red, 0), title='SMI Signal Line', linewidth=1, style=plot.style_line) hline = plot(ovrsld, color=color.new(color.red, 0), title='Over Bought') lline = plot(ovrbgt, color=color.new(color.green, 0), title='Over Sold') plot(CrossoverIndex ? close : na, color=color.new(color.aqua, 0), style=plot.style_cross, linewidth=2, title='RSICrossover') mycol1 = SMIsignal > -ovrbgt ? color.red : na mycol2 = SMIsignal < -ovrsld ? color.green : na fill(plot1, hline, color=color.new(mycol1, 80)) fill(plot2, lline, color=color.new(mycol2, 80)) ////////////////////////////////////////////////////////////////////// // Input EMA9 and EMA21 EMA50Len = input( 50 ) EMA50 = ta.ema(close, EMA50Len) ////////////////////////////////////////////////////////////////////////// // -------- VWAP ----------// vwapLine = ta.vwap(close) //////////////////////////////////////////////////////////////////////// //PROFIT TARGET// longProfitPer = input(10.0, title='Take Profit %') / 100 TargetPrice = strategy.position_avg_price * (1 + longProfitPer) //plot (strategy.position_size > 0 ? TargetPrice : na, style=plot.style_linebr, color=color.green, linewidth=1, title="Price Target") //BUY STRATEGY CONDITION// condentry = ta.crossover(SMI, SMIsignal) and SMI < 0 profittarget = TargetPrice stoploss = close < EMA50 ///////////////////////////STRATEGY BUILD////////////////////////////////////// if MarketOpen if close > EMA50 if (condentry) and time > testPeriodStart and time < testPeriodEnd and Morning strategy.entry('Long', strategy.long, qty = QuantityOnLong) if profittarget and strategy.position_size > 0 strategy.exit(id="Long", limit=TargetPrice) if stoploss strategy.close('Long', qty = QuantityOnClose)
EMA 5,15,35,89,200 BY NUT
https://www.tradingview.com/script/O4vhK1BK/
samatchanut
https://www.tradingview.com/u/samatchanut/
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/ // Β© samatchanut //@version=4 strategy("EMA 5,15,35,89,200 BY NUT",overlay =1) a = input(title="EMA_a length", type=input.integer, defval=5, minval=-3, maxval=200) b = input(title="EMA_b length", type=input.integer, defval=15, minval=-3, maxval=200) c = input(title="EMA_c length", type=input.integer, defval=35, minval=-3, maxval=200) d = input(title="EMA_d length", type=input.integer, defval=89, minval=-3, maxval=200) e = input(title="EMA_e length", type=input.integer, defval=200, minval=-3, maxval=200) maf5=ema(close,a) mas15=ema(close,b) mas35=ema(close,c) maa89=ema(close,d) mab200=ema(close,e) plot(maf5,color=color.white) plot(mas15,color=color.red) plot(mas35,color=color.green) plot(maa89,color=color.blue) plot(mab200,color=color.orange)
Faytterro Estimator Strategy
https://www.tradingview.com/script/qgtXBmhG/
faytterro
https://www.tradingview.com/u/faytterro/
296
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/ // Β© faytterro //@version=5 strategy("Faytterro Estimator Strategy v2", overlay=true, default_qty_type = strategy.percent_of_equity, default_qty_value = 100) src=input(hlc3,title="source") len=input.int(10,title="faytterro estimator lenght", maxval=500) len2=100 len3=input.float(650,title="minumum enrty-close gap (different direction)") len4=input.float(650,title="minumum entry-entry gap (same direction)") cr(x, y) => z = 0.0 weight = 0.0 for i = 0 to y-1 z:=z + x[i]*((y-1)/2+1-math.abs(i-(y-1)/2)) z/(((y+1)/2)*(y+1)/2) cr= cr(src,2*len-1) dizi = array.new_float(500) var line=array.new_line() for i=0 to len*2 array.set(dizi,i,(i*(i-1)*(cr-2*cr[1]+cr[2])/2+i*(cr[1]-cr[2])+cr[2])) buy = array.get(dizi,len+1+5)>array.get(dizi,len+1+4) and array.get(dizi,len+1+5)<cr[len] sell = array.get(dizi,len+1+5)<array.get(dizi,len+1+4) and array.get(dizi,len+1+5)>cr[len] bb=buy? hlc3 : na ss=sell? hlc3 : na sbuy= buy and close<(close[ta.barssince(buy or sell)])[1]-len4 and close<ta.highest(fixnan(ss),len2)-len3*3 ssell= sell and close>(close[ta.barssince(buy or sell)])[1]+len4 and close>ta.lowest(fixnan(bb),len2)+len3*3 buy:= buy and close<(close[ta.barssince(buy or sell)])[1]-len4 and close<ta.highest(fixnan(ss),len2)-len3 //and close>ta.highest(fixnan(ss),len2)-len3*3 sell:= sell and close>(close[ta.barssince(buy or sell)])[1]+len4 and close>ta.lowest(fixnan(bb),len2)+len3 //and close<ta.lowest(fixnan(bb),len2)+len3*3 alertcondition(buy or sell) sl = input.float(5, title = "trailing stop loss", step = 0.1) //if (sbuy) // strategy.entry("strong long", strategy.long,width) // strategy.exit("close long","strong long", stop = close*(100-sb)/100 ) //if (ssell) // strategy.entry("strong sell", strategy.short,width) if (buy) strategy.entry("long", strategy.long) strategy.exit("close long","long", trail_price = close, trail_offset = close*sl) if (sell) strategy.entry("short", strategy.short) strategy.exit("close short","short", trail_price = close, trail_offset = close*sl)
Super Scalp 007
https://www.tradingview.com/script/znwUmFrj-Super-Scalp-007/
MA_Seifi
https://www.tradingview.com/u/MA_Seifi/
313
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/ // Β© MA_Seifi //@version=4 strategy("Super Scalp 007", overlay=false, initial_capital = 200, default_qty_value = 100, default_qty_type = strategy.percent_of_equity) // Indicator len=20 p=close sma=sma(p,len) avg=atr(len) fibratio1=input(defval=1.618,title="Fibonacci Ratio 1") fibratio2=input(defval=2.618,title="Fibonacci Ratio 2") fibratio3=input(defval=4.236,title="Fibonacci Ratio 3") r1=avg*fibratio1 r2=avg*fibratio2 r3=avg*fibratio3 top3=sma+r3 top2=sma+r2 top1=sma+r1 bott1=sma-r1 bott2=sma-r2 bott3=sma-r3 // t3=plot(top3,transp=0,title="Upper 3",color=teal) // t2=plot(top2,transp=20,title="Upper 2",color=teal) // t1=plot(top1,transp=40,title="Upper 1",color=teal) // b1=plot(bott1,transp=40,title="Lower 1",color=teal) // b2=plot(bott2,transp=20,title="Lower 2",color=teal) // b3=plot(bott3,transp=0,title="Lower 3",color=teal) // plot(sma,style=cross,title="SMA",color=teal) // fill(t3,b3,color=navy,transp=85) // Conditions k = 0.005 longCondition = cross(low, bott2) shortCondition = cross(high, top2) stop_l = bott3 * (1 - k * 0.5) stop_s = top3 * (1 + k) limit_l = top2 * (1 - k) limit_s = bott2 plot(limit_l, color=color.green) plot(stop_l, color=color.red) strategy.entry("long", strategy.long, when = longCondition) strategy.exit('long', limit = limit_l, stop=stop_l) // strategy.entry("short", strategy.short, when = shortCondition) // strategy.exit('short', limit = limit_s, stop=stop_s) // shortCondition = ta.crossunder(ta.sma(close, 14), ta.sma(close, 28)) // if (shortCondition) // strategy.entry("My Short Entry Id", strategy.short)
tw.tha_V2 EMA
https://www.tradingview.com/script/WIjvvLuT/
MCDELL
https://www.tradingview.com/u/MCDELL/
5
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/ // Β© MCDELL //@version=5 strategy(" tw.tha_",overlay=1) lot= input.float(0, "Lot", minval=0, maxval=999, step=0.5) a = input.int(8, "EMA 1", minval=1, maxval=9999999, step=1) b = input.int(13, "EMA 2", minval=1, maxval=9999999, step=1) e = input.int(55, "EMA 5", minval=1, maxval=9999999, step=1) f = input.int(89, "EMA 6", minval=1, maxval=9999999, step=1) h = input.int(233, "EMA 8", minval=1, maxval=9999999, step=1) i = input.int(377, "EMA 9", minval=1, maxval=9999999, step=1) k = input.int(987, "EMA 11", minval=1, maxval=9999999, step=1) l = input.int(1597, "EMA 12", minval=1, maxval=9999999, step=1) maa=ta.ema(close,a) mab=ta.ema(close,b) mae=ta.ema(close,e) maf=ta.ema(close,f) mah=ta.ema(close,h) mai=ta.ema(close,i) mak=ta.ema(close,k) mal=ta.ema(close,l) plot(maa,color=color.green) plot(mab,color=color.blue) plot(mae,color=color.yellow) plot(maf,color=color.orange) plot(mah,color=color.red) plot(mai,color=color.purple) plot(mak,color=color.silver) plot(mal,color=color.white)
eswaran ab
https://www.tradingview.com/script/gULPpVBa-eswaran-ab/
ESWARMONK2515
https://www.tradingview.com/u/ESWARMONK2515/
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 //Break out trading system works best in a weekly chart and daily chart of Nifty and BankNifty //@version=4 strategy("Eswar New",shorttitle = "ESW",default_qty_type = strategy.percent_of_equity,default_qty_value = 100, overlay=true) length = input(20, minval=1) exit = input(1, minval=1, maxval=2,title = "Exit Option") // Use Option 1 to exit using lower band; Use Option 2 to exit using basis line lower = lowest(length) upper = highest(length) basis = avg(upper, lower) l = plot(lower, color=color.blue) u = plot(upper, color=color.blue) plot(basis, color=color.orange) fill(u, l, color=color.blue) longCondition = crossover(close,upper[1]) if (longCondition) strategy.entry("Long", strategy.long) if(exit==1) if (crossunder(close,lower[1])) strategy.close("Long") if(exit==2) if (crossunder(close,basis[1])) strategy.close("Long")
tw.tha_V1 EMA
https://www.tradingview.com/script/ANBnINQf/
MCDELL
https://www.tradingview.com/u/MCDELL/
9
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© MCDELL //@version=5 strategy(" tw.tha_",overlay=1) a = input.int(8, "EMA 1", minval=1, maxval=9999999, step=1) b = input.int(13, "EMA 2", minval=1, maxval=9999999, step=1) c = input.int(21, "EMA 3", minval=1, maxval=9999999, step=1) d = input.int(34, "EMA 4", minval=1, maxval=9999999, step=1) e = input.int(55, "EMA 5", minval=1, maxval=9999999, step=1) f = input.int(89, "EMA 6", minval=1, maxval=9999999, step=1) g = input.int(144, "EMA 7", minval=1, maxval=9999999, step=1) h = input.int(233, "EMA 8", minval=1, maxval=9999999, step=1) i = input.int(377, "EMA 9", minval=1, maxval=9999999, step=1) j = input.int(610, "EMA 10", minval=1, maxval=9999999, step=1) k = input.int(987, "EMA 11", minval=1, maxval=9999999, step=1) l = input.int(1597, "EMA 12", minval=1, maxval=9999999, step=1) m = input.int(2584, "EMA 13", minval=1, maxval=9999999, step=1) n = input.int(4181, "EMA 14", minval=1, maxval=9999999, step=1) maa=ta.ema(close,a) mab=ta.ema(close,b) mac=ta.ema(close,d) mad=ta.ema(close,d) mae=ta.ema(close,e) maf=ta.ema(close,f) mag=ta.ema(close,g) mah=ta.ema(close,h) mai=ta.ema(close,i) maj=ta.ema(close,j) mak=ta.ema(close,k) mal=ta.ema(close,l) mam=ta.ema(close,m) man=ta.ema(close,n) plot(maa,color=color.green) plot(mab,color=color.green) plot(mac,color=color.green) plot(mad,color=color.green) plot(mae,color=color.green) plot(maf,color=color.green) plot(mag,color=color.blue) plot(mah,color=color.blue) plot(mai,color=color.blue) plot(maj,color=color.blue) plot(mak,color=color.blue) plot(mal,color=color.yellow) plot(mam,color=color.yellow) plot(man,color=color.yellow)
Ultra Moving Average Rating Trend Strategy
https://www.tradingview.com/script/A2j2KYK4-Ultra-Moving-Average-Rating-Trend-Strategy/
exlux99
https://www.tradingview.com/u/exlux99/
104
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© exlux99 //@version=5 strategy(title='Ultra Moving Average Rating Trend Strategy', overlay=true) //, pyramiding=1,initial_capital = 1000, default_qty_type= strategy.percent_of_equity, default_qty_value = 100, calc_on_order_fills=false, slippage=0,commission_type=strategy.commission.percent,commission_value=0.03) // // //==========DEMA getDEMA(src, len) => dema = 2 * ta.ema(src, len) - ta.ema(ta.ema(src, len), len) dema //==========HMA getHULLMA(src, len) => hullma = ta.wma(2 * ta.wma(src, len / 2) - ta.wma(src, len), math.round(math.sqrt(len))) hullma //==========KAMA getKAMA(src, len, k1, k2) => change = math.abs(ta.change(src, len)) volatility = math.sum(math.abs(ta.change(src)), len) efficiency_ratio = volatility != 0 ? change / volatility : 0 kama = 0.0 fast = 2 / (k1 + 1) slow = 2 / (k2 + 1) smooth_const = math.pow(efficiency_ratio * (fast - slow) + slow, 2) kama := nz(kama[1]) + smooth_const * (src - nz(kama[1])) kama //==========TEMA getTEMA(src, len) => e = ta.ema(src, len) tema = 3 * (e - ta.ema(e, len)) + ta.ema(ta.ema(e, len), len) tema //==========ZLEMA getZLEMA(src, len) => zlemalag_1 = (len - 1) / 2 zlemadata_1 = src + src - src[zlemalag_1] zlema = ta.ema(zlemadata_1, len) zlema //==========FRAMA getFRAMA(src, len) => Price = src N = len if N % 2 != 0 N += 1 N N1 = 0.0 N2 = 0.0 N3 = 0.0 HH = 0.0 LL = 0.0 Dimen = 0.0 alpha = 0.0 Filt = 0.0 N3 := (ta.highest(N) - ta.lowest(N)) / N HH := ta.highest(N / 2 - 1) LL := ta.lowest(N / 2 - 1) N1 := (HH - LL) / (N / 2) HH := high[N / 2] LL := low[N / 2] for i = N / 2 to N - 1 by 1 if high[i] > HH HH := high[i] HH if low[i] < LL LL := low[i] LL N2 := (HH - LL) / (N / 2) if N1 > 0 and N2 > 0 and N3 > 0 Dimen := (math.log(N1 + N2) - math.log(N3)) / math.log(2) Dimen alpha := math.exp(-4.6 * (Dimen - 1)) if alpha < .01 alpha := .01 alpha if alpha > 1 alpha := 1 alpha Filt := alpha * Price + (1 - alpha) * nz(Filt[1], 1) if bar_index < N + 1 Filt := Price Filt Filt //==========VIDYA getVIDYA(src, len) => mom = ta.change(src) upSum = math.sum(math.max(mom, 0), len) downSum = math.sum(-math.min(mom, 0), len) out = (upSum - downSum) / (upSum + downSum) cmo = math.abs(out) alpha = 2 / (len + 1) vidya = 0.0 vidya := src * alpha * cmo + nz(vidya[1]) * (1 - alpha * cmo) vidya //==========JMA getJMA(src, len, power, phase) => phase_ratio = phase < -100 ? 0.5 : phase > 100 ? 2.5 : phase / 100 + 1.5 beta = 0.45 * (len - 1) / (0.45 * (len - 1) + 2) alpha = math.pow(beta, power) MA1 = 0.0 Det0 = 0.0 MA2 = 0.0 Det1 = 0.0 JMA = 0.0 MA1 := (1 - alpha) * src + alpha * nz(MA1[1]) Det0 := (src - MA1) * (1 - beta) + beta * nz(Det0[1]) MA2 := MA1 + phase_ratio * Det0 Det1 := (MA2 - nz(JMA[1])) * math.pow(1 - alpha, 2) + math.pow(alpha, 2) * nz(Det1[1]) JMA := nz(JMA[1]) + Det1 JMA //==========T3 getT3(src, len, vFactor) => ema1 = ta.ema(src, len) ema2 = ta.ema(ema1, len) ema3 = ta.ema(ema2, len) ema4 = ta.ema(ema3, len) ema5 = ta.ema(ema4, len) ema6 = ta.ema(ema5, len) c1 = -1 * math.pow(vFactor, 3) c2 = 3 * math.pow(vFactor, 2) + 3 * math.pow(vFactor, 3) c3 = -6 * math.pow(vFactor, 2) - 3 * vFactor - 3 * math.pow(vFactor, 3) c4 = 1 + 3 * vFactor + math.pow(vFactor, 3) + 3 * math.pow(vFactor, 2) T3 = c1 * ema6 + c2 * ema5 + c3 * ema4 + c4 * ema3 T3 //==========TRIMA getTRIMA(src, len) => N = len + 1 Nm = math.round(N / 2) TRIMA = ta.sma(ta.sma(src, Nm), Nm) TRIMA //-------------- FUNCTIONS dirmov(len) => up = ta.change(high) down = -ta.change(low) plusDM = na(up) ? na : up > down and up > 0 ? up : 0 minusDM = na(down) ? na : down > up and down > 0 ? down : 0 truerange = ta.rma(ta.tr, len) plus = fixnan(100 * ta.rma(plusDM, len) / truerange) minus = fixnan(100 * ta.rma(minusDM, len) / truerange) [plus, minus] adx(dilen, adxlen) => [plus, minus] = dirmov(dilen) sum = plus + minus adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), adxlen) adx src = close res = input.timeframe("", title="Indicator Timeframe") // Ichimoku Cloud donchian(len) => math.avg(ta.lowest(len), ta.highest(len)) ichimoku_cloud() => conversionLine = donchian(9) baseLine = donchian(26) leadLine1 = math.avg(conversionLine, baseLine) leadLine2 = donchian(52) [conversionLine, baseLine, leadLine1, leadLine2] calcRatingMA(ma, src) => na(ma) or na(src) ? na : (ma == src ? 0 : ( ma < src ? 1 : -1 )) calcRating(buy, sell) => buy ? 1 : ( sell ? -1 : 0 ) calcRatingAll() => //============== MA ================= SMA10 = ta.sma(close, 10) SMA20 = ta.sma(close, 20) SMA30 = ta.sma(close, 30) SMA50 = ta.sma(close, 50) SMA100 = ta.sma(close, 100) SMA200 = ta.sma(close, 200) EMA10 = ta.ema(close, 10) EMA20 = ta.ema(close, 20) EMA30 = ta.ema(close, 30) EMA50 = ta.ema(close, 50) EMA100 = ta.ema(close, 100) EMA200 = ta.ema(close, 200) ALMA10 = ta.alma(close, 10, 0.85, 6) ALMA20 = ta.alma(close, 20, 0.85, 6) ALMA50 = ta.alma(close, 50, 0.85, 6) ALMA100 = ta.alma(close, 100, 0.85, 6) ALMA200 = ta.alma(close, 200, 0.85, 6) SMMA10 = ta.rma(close, 10) SMMA20 = ta.rma(close, 20) SMMA50 = ta.rma(close, 50) SMMA100 = ta.rma(close, 100) SMMA200 = ta.rma(close, 200) LSMA10 = ta.linreg(close, 10, 0) LSMA20 = ta.linreg(close, 20, 0) LSMA50 = ta.linreg(close, 50, 0) LSMA100 = ta.linreg(close, 100, 0) LSMA200 = ta.linreg(close, 200, 0) VWMA10 = ta.vwma(close, 10) VWMA20 = ta.vwma(close, 20) VWMA50 = ta.vwma(close, 50) VWMA100 = ta.vwma(close, 100) VWMA200 = ta.vwma(close, 200) DEMA10 = getDEMA(close, 10) DEMA20 = getDEMA(close, 20) DEMA50 = getDEMA(close, 50) DEMA100 =getDEMA(close, 100) DEMA200 = getDEMA(close, 200) HMA10 = ta.hma(close, 10) HMA20 = ta.hma(close, 20) HMA50 = ta.hma(close, 50) HMA100 = ta.hma(close, 100) HMA200 = ta.hma(close, 200) KAMA10 = getKAMA(close, 10, 2, 30) KAMA20 = getKAMA(close, 20, 2, 30) KAMA50 = getKAMA(close, 50, 2, 30) KAMA100 = getKAMA(close, 100, 2, 30) KAMA200 = getKAMA(close, 200 , 2, 30) FRAMA10 = getFRAMA(close, 10) FRAMA20 = getFRAMA(close, 20) FRAMA50 = getFRAMA(close, 50) FRAMA100 =getFRAMA(close, 100) FRAMA200 = getFRAMA(close, 200) VIDMA10 = getVIDYA(close, 10) VIDMA20 = getVIDYA(close, 20) VIDMA50 = getVIDYA(close, 50) VIDMA100 =getVIDYA(close, 100) VIDMA200 = getVIDYA(close, 200) JMA10 = getJMA(close, 10, 2, 50) JMA20 = getJMA(close, 20, 2, 50) JMA50 = getJMA(close, 50, 2, 50) JMA100 =getJMA(close, 100, 2, 50) JMA200 = getJMA(close, 200, 2, 50) TEMA10 = getTEMA(close, 10) TEMA20 = getTEMA(close, 20) TEMA50 = getTEMA(close, 50) TEMA100 =getTEMA(close, 100) TEMA200 = getTEMA(close, 200) ZLEMA10 = getZLEMA(close, 10) ZLEMA20 = getZLEMA(close, 20) ZLEMA50 = getZLEMA(close, 50) ZLEMA100 =getZLEMA(close, 100) ZLEMA200 = getZLEMA(close, 200) TRIMA10 = getTRIMA(close, 10) TRIMA20 = getTRIMA(close, 20) TRIMA50 = getTRIMA(close, 50) TRIMA100 =getTRIMA(close, 100) TRIMA200 = getTRIMA(close, 200) T3MA10 = getT3(close, 10, 0.7) T3MA20 = getT3(close, 20, 0.7) T3MA50 = getT3(close, 50, 0.7) T3MA100 =getT3(close, 100, 0.7) T3MA200 = getT3(close, 200, 0.7) [IC_CLine, IC_BLine, IC_Lead1, IC_Lead2] = ichimoku_cloud() //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// PriceAvg = ta.ema(close, 50) DownTrend = close < PriceAvg UpTrend = close > PriceAvg // calculate trading recommendation based on SMA/EMA float ratingMA = 0 float ratingMAC = 0 float ratingSMA10 = na if not na(SMA10) ratingSMA10 := calcRatingMA(SMA10, close) ratingMA := ratingMA + ratingSMA10 ratingMAC := ratingMAC + 1 float ratingSMA20 = na if not na(SMA20) ratingSMA20 := calcRatingMA(SMA20, close) ratingMA := ratingMA + ratingSMA20 ratingMAC := ratingMAC + 1 float ratingSMA30 = na if not na(SMA30) ratingSMA30 := calcRatingMA(SMA30, close) ratingMA := ratingMA + ratingSMA30 ratingMAC := ratingMAC + 1 float ratingSMA50 = na if not na(SMA50) ratingSMA50 := calcRatingMA(SMA50, close) ratingMA := ratingMA + ratingSMA50 ratingMAC := ratingMAC + 1 float ratingSMA100 = na if not na(SMA100) ratingSMA100 := calcRatingMA(SMA100, close) ratingMA := ratingMA + ratingSMA100 ratingMAC := ratingMAC + 1 float ratingSMA200 = na if not na(SMA200) ratingSMA200 := calcRatingMA(SMA200, close) ratingMA := ratingMA + ratingSMA200 ratingMAC := ratingMAC + 1 float ratingEMA10 = na if not na(EMA10) ratingEMA10 := calcRatingMA(EMA10, close) ratingMA := ratingMA + ratingEMA10 ratingMAC := ratingMAC + 1 float ratingEMA20 = na if not na(EMA20) ratingEMA20 := calcRatingMA(EMA20, close) ratingMA := ratingMA + ratingEMA20 ratingMAC := ratingMAC + 1 float ratingEMA30 = na if not na(EMA30) ratingEMA30 := calcRatingMA(EMA30, close) ratingMA := ratingMA + ratingEMA30 ratingMAC := ratingMAC + 1 float ratingEMA50 = na if not na(EMA50) ratingEMA50 := calcRatingMA(EMA50, close) ratingMA := ratingMA + ratingEMA50 ratingMAC := ratingMAC + 1 float ratingEMA100 = na if not na(EMA100) ratingEMA100 := calcRatingMA(EMA100, close) ratingMA := ratingMA + ratingEMA100 ratingMAC := ratingMAC + 1 float ratingEMA200 = na if not na(EMA200) ratingEMA200 := calcRatingMA(EMA200, close) ratingMA := ratingMA + ratingEMA200 ratingMAC := ratingMAC + 1 /////////////////////////// float ratingALMA10 = na if not na(ALMA10) ratingALMA10 := calcRatingMA(ALMA10, close) ratingMA := ratingMA + ratingALMA10 ratingMAC := ratingMAC + 1 float ratingALMA20 = na if not na(ALMA20) ratingALMA20 := calcRatingMA(ALMA20, close) ratingMA := ratingMA + ratingALMA20 ratingMAC := ratingMAC + 1 float ratingALMA50 = na if not na(ALMA50) ratingALMA50 := calcRatingMA(ALMA50, close) ratingMA := ratingMA + ratingALMA50 ratingMAC := ratingMAC + 1 float ratingALMA100 = na if not na(ALMA100) ratingALMA100 := calcRatingMA(ALMA100, close) ratingMA := ratingMA + ratingALMA100 ratingMAC := ratingMAC + 1 float ratingALMA200 = na if not na(ALMA200) ratingALMA200 := calcRatingMA(ALMA200, close) ratingMA := ratingMA + ratingALMA200 ratingMAC := ratingMAC + 1 ///////////////////////// /////////////////////////// /////////////////////////// float ratingSMMA10 = na if not na(SMMA10) ratingSMMA10 := calcRatingMA(SMMA10, close) ratingMA := ratingMA + ratingSMMA10 ratingMAC := ratingMAC + 1 float ratingSMMA20 = na if not na(SMMA20) ratingSMMA20 := calcRatingMA(SMMA20, close) ratingMA := ratingMA + ratingSMMA20 ratingMAC := ratingMAC + 1 float ratingSMMA50 = na if not na(SMMA50) ratingSMMA50 := calcRatingMA(SMMA50, close) ratingMA := ratingMA + ratingSMMA50 ratingMAC := ratingMAC + 1 float ratingSMMA100 = na if not na(SMMA100) ratingSMMA100 := calcRatingMA(SMMA100, close) ratingMA := ratingMA + ratingSMMA100 ratingMAC := ratingMAC + 1 float ratingSMMA200 = na if not na(SMMA200) ratingSMMA200 := calcRatingMA(SMMA200, close) ratingMA := ratingMA + ratingSMMA200 ratingMAC := ratingMAC + 1 ///////////////////////// /////////////////////////// /////////////////////////// float ratingLSMA10 = na if not na(LSMA10) ratingLSMA10 := calcRatingMA(LSMA10, close) ratingMA := ratingMA + ratingLSMA10 ratingMAC := ratingMAC + 1 float ratingLSMA20 = na if not na(LSMA20) ratingLSMA20 := calcRatingMA(LSMA20, close) ratingMA := ratingMA + ratingLSMA20 ratingMAC := ratingMAC + 1 float ratingLSMA50 = na if not na(LSMA50) ratingLSMA50 := calcRatingMA(LSMA50, close) ratingMA := ratingMA + ratingLSMA50 ratingMAC := ratingMAC + 1 float ratingLSMA100 = na if not na(LSMA100) ratingLSMA100 := calcRatingMA(LSMA100, close) ratingMA := ratingMA + ratingLSMA100 ratingMAC := ratingMAC + 1 float ratingLSMA200 = na if not na(LSMA200) ratingLSMA200 := calcRatingMA(LSMA200, close) ratingMA := ratingMA + ratingLSMA200 ratingMAC := ratingMAC + 1 ///////////////////////// /////////////////////////// /////////////////////////// float ratingVWMA10 = na if not na(VWMA10) ratingVWMA10 := calcRatingMA(VWMA10, close) ratingMA := ratingMA + ratingVWMA10 ratingMAC := ratingMAC + 1 float ratingVWMA20 = na if not na(VWMA20) ratingVWMA20 := calcRatingMA(VWMA20, close) ratingMA := ratingMA + ratingVWMA20 ratingMAC := ratingMAC + 1 float ratingVWMA50 = na if not na(VWMA50) ratingVWMA50 := calcRatingMA(VWMA50, close) ratingMA := ratingMA + ratingVWMA50 ratingMAC := ratingMAC + 1 float ratingVWMA100 = na if not na(VWMA100) ratingVWMA100 := calcRatingMA(VWMA100, close) ratingMA := ratingMA + ratingVWMA100 ratingMAC := ratingMAC + 1 float ratingVWMA200 = na if not na(VWMA200) ratingVWMA200 := calcRatingMA(VWMA200, close) ratingMA := ratingMA + ratingVWMA200 ratingMAC := ratingMAC + 1 ///////////////////////// /////////////////////////// /////////////////////////// float ratingDEMA10 = na if not na(DEMA10) ratingDEMA10 := calcRatingMA(DEMA10, close) ratingMA := ratingMA + ratingDEMA10 ratingMAC := ratingMAC + 1 float ratingDEMA20 = na if not na(DEMA20) ratingDEMA20 := calcRatingMA(DEMA20, close) ratingMA := ratingMA + ratingDEMA20 ratingMAC := ratingMAC + 1 float ratingDEMA50 = na if not na(DEMA50) ratingDEMA50 := calcRatingMA(DEMA50, close) ratingMA := ratingMA + ratingDEMA50 ratingMAC := ratingMAC + 1 float ratingDEMA100 = na if not na(DEMA100) ratingDEMA100 := calcRatingMA(DEMA100, close) ratingMA := ratingMA + ratingDEMA100 ratingMAC := ratingMAC + 1 float ratingDEMA200 = na if not na(DEMA200) ratingDEMA200 := calcRatingMA(DEMA200, close) ratingMA := ratingMA + ratingDEMA200 ratingMAC := ratingMAC + 1 ///////////////////////// /////////////////////////// float ratingHMA10 = na if not na(HMA10) ratingHMA10 := calcRatingMA(HMA10, close) ratingMA := ratingMA + ratingHMA10 ratingMAC := ratingMAC + 1 float ratingHMA20 = na if not na(HMA20) ratingHMA20 := calcRatingMA(HMA20, close) ratingMA := ratingMA + ratingHMA20 ratingMAC := ratingMAC + 1 float ratingHMA50 = na if not na(HMA50) ratingHMA50 := calcRatingMA(HMA50, close) ratingMA := ratingMA + ratingHMA50 ratingMAC := ratingMAC + 1 float ratingHMA100 = na if not na(HMA100) ratingHMA100 := calcRatingMA(HMA100, close) ratingMA := ratingMA + ratingHMA100 ratingMAC := ratingMAC + 1 float ratingHMA200 = na if not na(HMA200) ratingHMA200 := calcRatingMA(HMA200, close) ratingMA := ratingMA + ratingHMA200 ratingMAC := ratingMAC + 1 ///////////////////////// /////////////////////////// /////////////////////////// float ratingKAMA10 = na if not na(KAMA10) ratingKAMA10 := calcRatingMA(KAMA10, close) ratingMA := ratingMA + ratingKAMA10 ratingMAC := ratingMAC + 1 float ratingKAMA20 = na if not na(KAMA20) ratingKAMA20 := calcRatingMA(KAMA20, close) ratingMA := ratingMA + ratingKAMA20 ratingMAC := ratingMAC + 1 float ratingKAMA50 = na if not na(KAMA50) ratingKAMA50 := calcRatingMA(KAMA50, close) ratingMA := ratingMA + ratingKAMA50 ratingMAC := ratingMAC + 1 float ratingKAMA100 = na if not na(KAMA100) ratingKAMA100 := calcRatingMA(KAMA100, close) ratingMA := ratingMA + ratingKAMA100 ratingMAC := ratingMAC + 1 float ratingKAMA200 = na if not na(KAMA200) ratingKAMA200 := calcRatingMA(KAMA200, close) ratingMA := ratingMA + ratingKAMA200 ratingMAC := ratingMAC + 1 ///////////////////////// /////////////////////////// /////////////////////////// float ratingFRAMA10 = na if not na(FRAMA10) ratingFRAMA10 := calcRatingMA(FRAMA10, close) ratingMA := ratingMA + ratingFRAMA10 ratingMAC := ratingMAC + 1 float ratingFRAMA20 = na if not na(FRAMA20) ratingFRAMA20 := calcRatingMA(FRAMA20, close) ratingMA := ratingMA + ratingFRAMA20 ratingMAC := ratingMAC + 1 float ratingFRAMA50 = na if not na(FRAMA50) ratingFRAMA50 := calcRatingMA(FRAMA50, close) ratingMA := ratingMA + ratingFRAMA50 ratingMAC := ratingMAC + 1 float ratingFRAMA100 = na if not na(FRAMA100) ratingFRAMA100 := calcRatingMA(FRAMA100, close) ratingMA := ratingMA + ratingFRAMA100 ratingMAC := ratingMAC + 1 float ratingFRAMA200 = na if not na(FRAMA200) ratingFRAMA200 := calcRatingMA(FRAMA200, close) ratingMA := ratingMA + ratingFRAMA200 ratingMAC := ratingMAC + 1 ///////////////////////// /////////////////////////// /////////////////////////// float ratingVIDMA10 = na if not na(VIDMA10) ratingVIDMA10 := calcRatingMA(VIDMA10, close) ratingMA := ratingMA + ratingVIDMA10 ratingMAC := ratingMAC + 1 float ratingVIDMA20 = na if not na(VIDMA20) ratingVIDMA20 := calcRatingMA(VIDMA20, close) ratingMA := ratingMA + ratingVIDMA20 ratingMAC := ratingMAC + 1 float ratingVIDMA50 = na if not na(VIDMA50) ratingVIDMA50 := calcRatingMA(VIDMA50, close) ratingMA := ratingMA + ratingVIDMA50 ratingMAC := ratingMAC + 1 float ratingVIDMA100 = na if not na(VIDMA100) ratingVIDMA100 := calcRatingMA(VIDMA100, close) ratingMA := ratingMA + ratingVIDMA100 ratingMAC := ratingMAC + 1 float ratingVIDMA200 = na if not na(VIDMA200) ratingVIDMA200 := calcRatingMA(VIDMA200, close) ratingMA := ratingMA + ratingVIDMA200 ratingMAC := ratingMAC + 1 ///////////////////////// /////////////////////////// float ratingJMA10 = na if not na(JMA10) ratingJMA10 := calcRatingMA(JMA10, close) ratingMA := ratingMA + ratingJMA10 ratingMAC := ratingMAC + 1 float ratingJMA20 = na if not na(JMA20) ratingJMA20 := calcRatingMA(JMA20, close) ratingMA := ratingMA + ratingJMA20 ratingMAC := ratingMAC + 1 float ratingJMA50 = na if not na(JMA50) ratingJMA50 := calcRatingMA(JMA50, close) ratingMA := ratingMA + ratingJMA50 ratingMAC := ratingMAC + 1 float ratingJMA100 = na if not na(JMA100) ratingJMA100 := calcRatingMA(JMA100, close) ratingMA := ratingMA + ratingJMA100 ratingMAC := ratingMAC + 1 float ratingJMA200 = na if not na(JMA200) ratingJMA200 := calcRatingMA(JMA200, close) ratingMA := ratingMA + ratingJMA200 ratingMAC := ratingMAC + 1 ///////////////////////// /////////////////////////// /////////////////////////// float ratingTEMA10 = na if not na(TEMA10) ratingTEMA10 := calcRatingMA(TEMA10, close) ratingMA := ratingMA + ratingTEMA10 ratingMAC := ratingMAC + 1 float ratingTEMA20 = na if not na(TEMA20) ratingTEMA20 := calcRatingMA(TEMA20, close) ratingMA := ratingMA + ratingTEMA20 ratingMAC := ratingMAC + 1 float ratingTEMA50 = na if not na(TEMA50) ratingTEMA50 := calcRatingMA(TEMA50, close) ratingMA := ratingMA + ratingTEMA50 ratingMAC := ratingMAC + 1 float ratingTEMA100 = na if not na(TEMA100) ratingTEMA100 := calcRatingMA(TEMA100, close) ratingMA := ratingMA + ratingTEMA100 ratingMAC := ratingMAC + 1 float ratingTEMA200 = na if not na(TEMA200) ratingTEMA200 := calcRatingMA(TEMA200, close) ratingMA := ratingMA + ratingTEMA200 ratingMAC := ratingMAC + 1 ///////////////////////// /////////////////////////// float ratingZLEMA10 = na if not na(ZLEMA10) ratingZLEMA10 := calcRatingMA(ZLEMA10, close) ratingMA := ratingMA + ratingZLEMA10 ratingMAC := ratingMAC + 1 float ratingZLEMA20 = na if not na(ZLEMA20) ratingZLEMA20 := calcRatingMA(ZLEMA20, close) ratingMA := ratingMA + ratingZLEMA20 ratingMAC := ratingMAC + 1 float ratingZLEMA50 = na if not na(ZLEMA50) ratingZLEMA50 := calcRatingMA(ZLEMA50, close) ratingMA := ratingMA + ratingZLEMA50 ratingMAC := ratingMAC + 1 float ratingZLEMA100 = na if not na(ZLEMA100) ratingZLEMA100 := calcRatingMA(ZLEMA100, close) ratingMA := ratingMA + ratingZLEMA100 ratingMAC := ratingMAC + 1 float ratingZLEMA200 = na if not na(ZLEMA200) ratingZLEMA200 := calcRatingMA(ZLEMA200, close) ratingMA := ratingMA + ratingZLEMA200 ratingMAC := ratingMAC + 1 ///////////////////////// /////////////////////////// /////////////////////////// float ratingTRIMA10 = na if not na(TRIMA10) ratingTRIMA10 := calcRatingMA(TRIMA10, close) ratingMA := ratingMA + ratingTRIMA10 ratingMAC := ratingMAC + 1 float ratingTRIMA20 = na if not na(TRIMA20) ratingTRIMA20 := calcRatingMA(TRIMA20, close) ratingMA := ratingMA + ratingTRIMA20 ratingMAC := ratingMAC + 1 float ratingTRIMA50 = na if not na(TRIMA50) ratingTRIMA50 := calcRatingMA(TRIMA50, close) ratingMA := ratingMA + ratingTRIMA50 ratingMAC := ratingMAC + 1 float ratingTRIMA100 = na if not na(TRIMA100) ratingTRIMA100 := calcRatingMA(TRIMA100, close) ratingMA := ratingMA + ratingTRIMA100 ratingMAC := ratingMAC + 1 float ratingTRIMA200 = na if not na(TRIMA200) ratingTRIMA200 := calcRatingMA(TRIMA200, close) ratingMA := ratingMA + ratingTRIMA200 ratingMAC := ratingMAC + 1 ///////////////////////// /////////////////////////// float ratingT3MA10 = na if not na(T3MA10) ratingT3MA10 := calcRatingMA(T3MA10, close) ratingMA := ratingMA + ratingT3MA10 ratingMAC := ratingMAC + 1 float ratingT3MA20 = na if not na(T3MA20) ratingT3MA20 := calcRatingMA(T3MA20, close) ratingMA := ratingMA + ratingT3MA20 ratingMAC := ratingMAC + 1 float ratingT3MA50 = na if not na(T3MA50) ratingT3MA50 := calcRatingMA(T3MA50, close) ratingMA := ratingMA + ratingT3MA50 ratingMAC := ratingMAC + 1 float ratingT3MA100 = na if not na(T3MA100) ratingT3MA100 := calcRatingMA(T3MA100, close) ratingMA := ratingMA + ratingT3MA100 ratingMAC := ratingMAC + 1 float ratingT3MA200 = na if not na(T3MA200) ratingT3MA200 := calcRatingMA(T3MA200, close) ratingMA := ratingMA + ratingT3MA200 ratingMAC := ratingMAC + 1 ////////////////////////////////////////// float ratingIC = na if not (na(IC_Lead1) or na(IC_Lead2) or na(close) or na(close[1]) or na(IC_BLine) or na(IC_CLine)) ratingIC := calcRating( IC_Lead1 > IC_Lead2 and close > IC_Lead1 and close < IC_BLine and close[1] < IC_CLine and close > IC_CLine, IC_Lead2 > IC_Lead1 and close < IC_Lead2 and close > IC_BLine and close[1] > IC_CLine and close < IC_CLine) if not na(ratingIC) ratingMA := ratingMA + ratingIC ratingMAC := ratingMAC + 1 ratingMA := ratingMAC > 0 ? ratingMA / ratingMAC : na float ratingTotal = 0 float ratingTotalC = 0 if not na(ratingMA) ratingTotal := ratingTotal + ratingMA ratingTotalC := ratingTotalC + 1 ratingTotal := ratingTotalC > 0 ? ratingTotal / ratingTotalC : na [ratingTotal, ratingMA] getSignal2(ratingTotal, ratingMA) => float _res = ratingTotal _res := ratingMA [ratingTotal, ratingMA] = request.security(syminfo.tickerid, res, calcRatingAll()) tradeSignal = getSignal2(ratingTotal, ratingMA) rating_entry = input.float(0.95, title='Rating for long', group="Entry Rating %", step=0.05) rating_exit = input.float(0.75, title='Rating for short', group="Entry Rating %", step=0.05) * -1 long = tradeSignal >= rating_entry short = tradeSignal <= rating_exit strategy.entry("long",strategy.long,when=long) strategy.entry('short',strategy.short,when=short)
BTC Profitable Wallets Strategy
https://www.tradingview.com/script/44FEvYZj-BTC-Profitable-Wallets-Strategy/
Powerscooter
https://www.tradingview.com/u/Powerscooter/
158
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/ // Β© Powerscooter // Since IntoTheBlock only provides daily onchain data, this chart might look chunky on lower timeframes, even with smoothing. //@version=5 strategy("BTC % profitable wallets", overlay=false, default_qty_type = strategy.cash, default_qty_value = 100, initial_capital = 100, pyramiding=100) Source = input.string(title="Blockchain", defval="BTC", options=["BTC", "ETH", "DOGE", "ADA", "MATIC", "SHIB", "UNI", "OKB", "LEO", "LINK", "LTC", "FTT", "CRO", "ALGO", "QNT", "BCH", "SAND", "MANA", "FXS", "AAVE", "CHZ", "HT", "LDO", "KCS", "AXS", "MKR", "ZEC", "GRT", "FTM", "SNX", "NEXO", "CRV", "BIT", "DASH", "BAT", "ENS"], group="Inputs") Threshold = input.int(50, "% Threshold", minval = 0, maxval = 100) smoothing = input.string(title="Smoothing", defval="SMA", options=["SMA", "RMA", "EMA", "WMA"], group="Smoothing Settings") ma_function(source, length) => switch smoothing "RMA" => ta.rma(source, length) "SMA" => ta.sma(source, length) "EMA" => ta.ema(source, length) => ta.wma(source, length) SmoothLength = input(1, 'MA Length', group="Smoothing Settings") Ticker = "INTOTHEBLOCK:" + Source + "_INOUTMONEYINPERCENTAGE" Wallets = request.security(Ticker, "D", close) ProfitWallets = plot(100*ma_function(Wallets, SmoothLength), "Profitable wallets", color=color.white, transp = 50) TresholdLine = plot(Threshold, transp=100, editable=false, display=display.none) //We need this invisible line for the fill command, as it doesn't accept variables of type int. fill(ProfitWallets, TresholdLine, Wallets > (Threshold/100) ? color.new(color.green, 90) : color.new(color.red, 90)) if ta.crossover(Wallets, (Threshold/100)) strategy.entry("Long", strategy.long)
Coral Trend Pullback Strategy (TradeIQ)
https://www.tradingview.com/script/kc6Itas8-Coral-Trend-Pullback-Strategy-TradeIQ/
kevinmck100
https://www.tradingview.com/u/kevinmck100/
459
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/ // Β© kevinmck100 // @description // // Strategy is taken from the TradeIQ YouTube video called "I Finally Found 80% Win Rate Trading Strategy For Crypto" // Check out the full video for further details/clarification on strategy entry/exit conditions. // // It incorporates the following features: // // - Risk management: Configurable X% loss per stop loss // Configurable R:R ratio // // - Trade entry: Conditions outlines below // // - Trade exit: Conditions outlined below // // - Backtesting: Configurable backtesting range by date // // - Trade drawings: TP/SL boxes drawn for all trades (can be turned on and off) // Trade exit information labels (can be turned on and off) // NOTE: Trade drawings will only be applicable when using overlay strategies // // - Debugging: Includes section with useful debugging techniques // // Strategy conditions: // // - Trade entry: LONG: C1: Coral Trend is bullish // C2: At least 1 candle where low is above Coral Trend since last cross above Coral Trend // C3: Pullback happens and price closes below Coral Trend // C4: Coral Trend colour remains bullish for duration of pullback // C5: After valid pullback, price then closes above Coral Trend // C6: Optional confirmation indicators (choose either C6.1 or C6.2 or NONE): // C6.1: ADX and DI (Single indicator) // C6.1.1: Green line is above red line // C6.1.2: Blue line > 20 // C6.1.3: Blue trending up over last 1 candle // C6.2: Absolute Strengeh Histogram + HawkEye Volume Indicator (Two indicators combined) // C6.2.1: Absolute Strengeh Histogram colour is blue // C6.2.2: HawkEye Volume Indicator colour is green // SHORT: C1: Coral Trend is bearish // C2: At least 1 candle where high is below Coral Trend since last cross below Coral Trend // C3: Pullback happens and price closes above Coral Trend // C4: Coral Trend colour remains bearish for duration of pullback // C5: After valid pullback, price then closes below Coral Trend // C6: Optional confirmation indicators (choose either C6.1 or C6.2 or NONE): // C6.1: ADX and DI (Single indicator) // C6.1.1: Red line is above green line // C6.1.2: Blue line > 20 // C6.1.3: Blue trending up over last 1 candle // C6.2: Absolute Strengeh Histogram + HawkEye Volume Indicator (Two indicators combined) // C6.2.1: Absolute Strengeh Histogram colour is red // C6.2.2: HawkEye Volume Indicator colour is red // NOTE: All the optional confirmation indicators cannot be overlayed with Coral Trend so feel free to add each separately to the chart for visual purposes // // // - Trade exit: Stop Loss: Calculated by recent swing low over previous X candles (configurable with "Local High/Low Lookback") // Take Profit: Calculated from R:R multiplier * Stop Loss size // // @credits // // Coral Trend Indicator [LazyBear] by @LazyBear // Absolute Strength Histogram | jh by @jiehonglim // Indicator: HawkEye Volume Indicator by @LazyBear // ADX and DI by @BeikabuOyaji //@version=5 INITIAL_CAPITAL = 1000 DEFAULT_COMMISSION = 0.02 MAX_DRAWINGS = 500 IS_OVERLAY = true strategy("Coral Trend Pullback Strategy (TradeIQ)", "Coral Trend Pullback", overlay = IS_OVERLAY, initial_capital = INITIAL_CAPITAL, currency = currency.NONE, max_labels_count = MAX_DRAWINGS, max_boxes_count = MAX_DRAWINGS, max_lines_count = MAX_DRAWINGS, default_qty_type = strategy.cash, commission_type = strategy.commission.percent, commission_value = DEFAULT_COMMISSION) // ============================================================================= // INPUTS // ============================================================================= // --------------- // Risk Management // --------------- riskReward = input.float(1.5, "Risk : Reward        1 :", group = "Strategy: Risk Management", inline = "RM1", minval = 0, step = 0.1, tooltip = "Previous high or low (long/short dependant) is used to determine TP level. 'Risk : Reward' ratio is then used to calculate SL based of previous high/low level.\n\nIn short, the higher the R:R ratio, the smaller the SL since TP target is fixed by previous high/low price data.") accountRiskPercent = input.float(1, "Portfolio Risk %        ", group = "Strategy: Risk Management", inline = "RM2", minval = 0, step = 0.1, tooltip = "Percentage of portfolio you lose if trade hits SL.\n\nYou then stand to gain\n Portfolio Risk % * Risk : Reward\nif trade hits TP.") localHlLookback = input.int (5, "Local High/Low Lookback     ", group = "Strategy: Stop Loss Settings", inline = "SL1", minval = 1, tooltip = "This strategy calculates the Stop Loss value from the recent local high/low. This lookback period determines the number of candles to include for the local high/low.") // ---------- // Date Range // ---------- startYear = input.int (2010, "Start Date  ", group = "Strategy: Date Range", inline = "DR1", minval = 1900, maxval = 2100) startMonth = input.int (1, "", group = "Strategy: Date Range", inline = "DR1", options = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) startDate = input.int (1, "", group = "Strategy: Date Range", inline = "DR1", options = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]) endYear = input.int (2100, "End Date    ", group = "Strategy: Date Range", inline = "DR2", minval = 1900, maxval = 2100) endMonth = input.int (1, "", group = "Strategy: Date Range", inline = "DR2", options = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) endDate = input.int (1, "", group = "Strategy: Date Range", inline = "DR2", options = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]) // ---------------- // Drawing Settings // ---------------- showTpSlBoxes = input.bool(true, "Show TP / SL Boxes", group = "Strategy: Drawings", inline = "D1", tooltip = "Show or hide TP and SL position boxes.\n\nNote: TradingView limits the maximum number of boxes that can be displayed to 500 so they may not appear for all price data under test.") showLabels = input.bool(false, "Show Trade Exit Labels", group = "Strategy: Drawings", inline = "D2", tooltip = "Useful labels to identify Profit/Loss and cumulative portfolio capital after each trade closes.\n\nAlso note that TradingView limits the max number of 'boxes' that can be displayed on a chart (max 500). This means when you lookback far enough on the chart you will not see the TP/SL boxes. However you can check this option to identify where trades exited.") // ------------------ // Indicator Settings // ------------------ // Coral Trend ctSm = input.int (25, "Smoothing Period       ", group = "Leading Indicator: Coral Trand Settings", inline = "CT1") ctCd = input.float(0.4, "Constant D          ", group = "Leading Indicator: Coral Trand Settings", inline = "CT2", step = 0.1) // Confirmation indicator inputs confirmationInd = input.string("ADX and DI", "Entry Confirmation Method    ", group = "Confirmation Indicator: Indicator Selection", inline = "IS1", options=["None", "ADX and DI", "Absolute Strength Histogram + HawkEye Volume"], tooltip = "Select one of the possible confirmation indicator(s) which can be used to confirm entry signals from the main Coral Trend indicator conditions. See strategy conditions to understand the logic behind each confirmation indicator") // ADX and DI adxLen = input.int(14, "ADX Length           ", group = "Confirmation Indicator: ADX and DI Settings", inline = "AD1") midLine = input.int(20, "Mid Line            ", group = "Confirmation Indicator: ADX and DI Settings", inline = "AD2", tooltip = "Mid line on standard ADX and DI indicator. In this strategy the DI must be above this line for entry confirmation.") // Absolute Strength Histogram ashLength = input.int(9, "Period of Evaluation       ", group = "Confirmation Indicator: Absolute Strength Histogram Settings", inline = "ASH1") ashSmooth = input.int(6, "Period of Smoothing      ", group = "Confirmation Indicator: Absolute Strength Histogram Settings", inline = "ASH2") ashSrc = input.source(close, "Source             ", group = "Confirmation Indicator: Absolute Strength Histogram Settings", inline = "ASH3") ashMode = input.string("RSI", "Indicator Method       ", group = "Confirmation Indicator: Absolute Strength Histogram Settings", inline = "ASH4", options=["RSI", "STOCHASTIC", "ADX"]) sahMaType = input.string("SMA", "MA              ", group = "Confirmation Indicator: Absolute Strength Histogram Settings", inline = "ASH5", options=["ALMA", "EMA", "WMA", "SMA", "SMMA", "HMA"]) ashAlmaOffset = input.float(0.85, "* Arnaud Legoux (ALMA) Offset", group = "Confirmation Indicator: Absolute Strength Histogram Settings", inline = "ASH6", minval=0, step=0.01) ashAlmaSigma = input.int(6, "* Arnaud Legoux (ALMA) Sigma", group = "Confirmation Indicator: Absolute Strength Histogram Settings", inline = "ASH7", minval=0) // HawkEye Volume Indicator hevLength = input.int(200, "Length             ", group = "Confirmation Indicator: HawkEye Volume Settings", inline = "HV1") hevDivisor = input.float(1.6, "Divisor             ", group = "Confirmation Indicator: HawkEye Volume Settings", inline = "HV2", step=0.1) // ============================================================================= // INDICATORS // ============================================================================= // ----------- // Coral Trend // ----------- src = close di = (ctSm - 1.0) / 2.0 + 1.0 c1 = 2 / (di + 1.0) c2 = 1 - c1 c3 = 3.0 * (ctCd * ctCd + ctCd * ctCd * ctCd) c4 = -3.0 * (2.0 * ctCd * ctCd + ctCd + ctCd * ctCd * ctCd) c5 = 3.0 * ctCd + 1.0 + ctCd * ctCd * ctCd + 3.0 * ctCd * ctCd var float i1 = na var float i2 = na var float i3 = na var float i4 = na var float i5 = na var float i6 = na i1 := c1 * src + c2 * nz(i1[1]) i2 := c1 * i1 + c2 * nz(i2[1]) i3 := c1 * i2 + c2 * nz(i3[1]) i4 := c1 * i3 + c2 * nz(i4[1]) i5 := c1 * i4 + c2 * nz(i5[1]) i6 := c1 * i5 + c2 * nz(i6[1]) bfr = -ctCd * ctCd * ctCd * i6 + c3 * i5 + c4 * i4 + c5 * i3 bfrC = bfr > nz(bfr[1]) ? color.new(color.green, 50) : bfr < nz(bfr[1]) ? color.new(color.red, 50) : color.new(color.blue, 50) plot(bfr, "Trend", linewidth = 3, style = plot.style_stepline, color = bfrC) // ---------- // ADX and DI // ---------- TrueRange = math.max(math.max(high - low, math.abs(high - nz(close[1]))), math.abs(low - nz(close[1]))) DirectionalMovementPlus = high - nz(high[1]) > nz(low[1]) - low ? math.max(high - nz(high[1]), 0) : 0 DirectionalMovementMinus = nz(low[1]) - low > high - nz(high[1]) ? math.max(nz(low[1]) - low, 0) : 0 SmoothedTrueRange = 0.0 SmoothedTrueRange := nz(SmoothedTrueRange[1]) - nz(SmoothedTrueRange[1]) / adxLen + TrueRange SmoothedDirectionalMovementPlus = 0.0 SmoothedDirectionalMovementPlus := nz(SmoothedDirectionalMovementPlus[1]) - nz(SmoothedDirectionalMovementPlus[1]) / adxLen + DirectionalMovementPlus SmoothedDirectionalMovementMinus = 0.0 SmoothedDirectionalMovementMinus := nz(SmoothedDirectionalMovementMinus[1]) - nz(SmoothedDirectionalMovementMinus[1]) / adxLen + DirectionalMovementMinus DIPlus = SmoothedDirectionalMovementPlus / SmoothedTrueRange * 100 DIMinus = SmoothedDirectionalMovementMinus / SmoothedTrueRange * 100 DX = math.abs(DIPlus - DIMinus) / (DIPlus + DIMinus) * 100 ADX = ta.sma(DX, adxLen) // --------------------------- // Absolute Strength Histogram // --------------------------- ashMa(ashType, ashSrc, ashLen) => float result = 0 if ashType == 'SMA' // Simple result := ta.sma(ashSrc, ashLen) result if ashType == 'EMA' // Exponential result := ta.ema(ashSrc, ashLen) result if ashType == 'WMA' // Weighted result := ta.wma(ashSrc, ashLen) result if ashType == 'SMMA' // Smoothed ashWma = ta.wma(ashSrc, ashLen) ashSma = ta.sma(ashSrc, ashLen) result := na(ashWma[1]) ? ashSma : (ashWma[1] * (ashLen - 1) + ashSrc) / ashLen result if ashType == 'HMA' // Hull result := ta.wma(2 * ta.wma(ashSrc, ashLen / 2) - ta.wma(ashSrc, ashLen), math.round(math.sqrt(ashLen))) result if ashType == 'ALMA' // Arnaud Legoux result := ta.alma(ashSrc, ashLen, ashAlmaOffset, ashAlmaSigma) result result Price = ashSrc Price1 = ashMa('SMA', Price, 1) Price2 = ashMa('SMA', Price[1], 1) //RSI Bulls0 = 0.5 * (math.abs(Price1 - Price2) + Price1 - Price2) Bears0 = 0.5 * (math.abs(Price1 - Price2) - (Price1 - Price2)) //STOCHASTIC Bulls1 = Price1 - ta.lowest(Price1, ashLength) Bears1 = ta.highest(Price1, ashLength) - Price1 //ADX Bulls2 = 0.5 * (math.abs(high - high[1]) + high - high[1]) Bears2 = 0.5 * (math.abs(low[1] - low) + low[1] - low) Bulls = ashMode == 'RSI' ? Bulls0 : ashMode == 'STOCHASTIC' ? Bulls1 : Bulls2 Bears = ashMode == 'RSI' ? Bears0 : ashMode == 'STOCHASTIC' ? Bears1 : Bears2 AvgBulls = ashMa(sahMaType, Bulls, ashLength) AvgBears = ashMa(sahMaType, Bears, ashLength) SmthBulls = ashMa(sahMaType, AvgBulls, ashSmooth) SmthBears = ashMa(sahMaType, AvgBears, ashSmooth) isTrendBullish = SmthBulls > SmthBears ? true : false // ------------------------ // HawkEye Volume Indicator // ------------------------ hevRange1 = high - low hevRangeAvg = ta.sma(hevRange1, hevLength) hevVolumeA = ta.sma(volume, hevLength) hevHigh1 = high[1] hevLow1 = low[1] hevMid1 = hl2[1] hevU1 = hevMid1 + (hevHigh1 - hevLow1) / hevDivisor hevD1 = hevMid1 - (hevHigh1 - hevLow1) / hevDivisor rEnabled1 = hevRange1 > hevRangeAvg and close < hevD1 and volume > hevVolumeA rEnabled2 = close < hevMid1 rEnabled = rEnabled1 or rEnabled2 gEnabled1 = close > hevMid1 gEnabled2 = hevRange1 > hevRangeAvg and close > hevU1 and volume > hevVolumeA gEnabled3 = high > hevHigh1 and hevRange1 < hevRangeAvg / 1.5 and volume < hevVolumeA gEnabled4 = low < hevLow1 and hevRange1 < hevRangeAvg / 1.5 and volume > hevVolumeA gEnabled = gEnabled1 or gEnabled2 or gEnabled3 or gEnabled4 grEnabled1 = hevRange1 > hevRangeAvg and close > hevD1 and close < hevU1 and volume > hevVolumeA and volume < hevVolumeA * 1.5 and volume > volume[1] grEnabled2 = hevRange1 < hevRangeAvg / 1.5 and volume < hevVolumeA / 1.5 grEnabled3 = close > hevD1 and close < hevU1 grEnabled = grEnabled1 or grEnabled2 or grEnabled3 // ============================================================================= // STRATEGY LOGIC // ============================================================================= // --------- // FUNCTIONS // --------- percentAsPoints(pcnt) => math.round(pcnt / 100 * close / syminfo.mintick) calcStopLossPrice(pointsOffset, isLong) => priceOffset = pointsOffset * syminfo.mintick if isLong close - priceOffset else close + priceOffset calcProfitTrgtPrice(pointsOffset, isLong) => calcStopLossPrice(-pointsOffset, isLong) printLabel(barIndex, msg) => label.new(barIndex, close, msg) printTpSlHitBox(left, right, slHit, tpHit, entryPrice, slPrice, tpPrice) => if showTpSlBoxes box.new (left = left, top = entryPrice, right = right, bottom = slPrice, bgcolor = slHit ? color.new(color.red, 60) : color.new(color.gray, 90), border_width = 0) box.new (left = left, top = entryPrice, right = right, bottom = tpPrice, bgcolor = tpHit ? color.new(color.green, 60) : color.new(color.gray, 90), border_width = 0) line.new(x1 = left, y1 = entryPrice, x2 = right, y2 = entryPrice, color = color.new(color.yellow, 20)) line.new(x1 = left, y1 = slPrice, x2 = right, y2 = slPrice, color = color.new(color.red, 20)) line.new(x1 = left, y1 = tpPrice, x2 = right, y2 = tpPrice, color = color.new(color.green, 20)) printTpSlNotHitBox(left, right, entryPrice, slPrice, tpPrice) => if showTpSlBoxes box.new (left = left, top = entryPrice, right = right, bottom = slPrice, bgcolor = color.new(color.gray, 90), border_width = 0) box.new (left = left, top = entryPrice, right = right, bottom = tpPrice, bgcolor = color.new(color.gray, 90), border_width = 0) line.new(x1 = left, y1 = entryPrice, x2 = right, y2 = entryPrice, color = color.new(color.yellow, 20)) line.new(x1 = left, y1 = slPrice, x2 = right, y2 = slPrice, color = color.new(color.red, 20)) line.new(x1 = left, y1 = tpPrice, x2 = right, y2 = tpPrice, color = color.new(color.green, 20)) printTradeExitLabel(x, y, posSize, entryPrice, pnl) => if showLabels labelStr = "Position Size: " + str.tostring(math.abs(posSize), "#.##") + "\nPNL: " + str.tostring(pnl, "#.##") + "\nCapital: " + str.tostring(strategy.equity, "#.##") + "\nEntry Price: " + str.tostring(entryPrice, "#.##") label.new(x = x, y = y, text = labelStr, color = pnl > 0 ? color.new(color.green, 60) : color.new(color.red, 60), textcolor = color.white, style = label.style_label_down) printVerticalLine(col) => line.new(bar_index, close, bar_index, close * 1.01, extend = extend.both, color = col) // ---------- // CONDITIONS // ---------- inDateRange = time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0) and time < timestamp(syminfo.timezone, endYear, endMonth, endDate, 0, 0) // Condition 1: Coral Trend color matches trend direction (long=green, short=red) isCoralBullish = bfr > nz(bfr[1]) isCoralBearish = bfr < nz(bfr[1]) // Condition 2: At least 1 candle completely above/below (long/short) Coral Trend since last cross above/below (long/short) Coral Trend (could potentially try also with only close above) sincePrePullbackBullBreakout= ta.barssince(ta.crossover(close, bfr)) sincePrePullbackBearBreakout= ta.barssince(ta.crossunder(close, bfr)) prePullbackBullBreakout = ta.barssince(low > bfr and high > bfr) < sincePrePullbackBullBreakout[1] prePullbackBearBreakout = ta.barssince(low < bfr and high < bfr) < sincePrePullbackBearBreakout[1] // Condition 3: Pullback closes below/above (long/short) Coral Trend barssinceBullPullbackStart = ta.barssince(ta.crossunder(close, bfr)) barssinceBearPullbackStart = ta.barssince(ta.crossover(close, bfr)) barssincePullbackStart = isCoralBullish ? barssinceBullPullbackStart : isCoralBearish ? barssinceBearPullbackStart : na // Condition 4: Coral Trend colour matched trend direction for duration of pullback sinceBullish = ta.barssince(ta.crossover(bfr, nz(bfr[1]))) sinceBearish = ta.barssince(ta.crossunder(bfr, nz(bfr[1]))) barssinceCoralflip = isCoralBullish ? sinceBullish : isCoralBearish ? sinceBearish : na isPullbackValid = barssincePullbackStart < barssinceCoralflip // Condition 5: After valid pullback, price then closes above/below (long/short) Coral Trend entryBreakout = (isCoralBullish and ta.crossover(close, bfr)) or (isCoralBearish and ta.crossunder(close, bfr)) // Condition 6: Confirmation indicators (6.1 or 6.2, optional depending on settings) confirms trade entry // 6.1: ADX and DI // 6.1.1: Green and red match trend (long=(green > red), short=(red > green)) // 6.1.2: Blue > 20 // 6.1.3: Blue trending up over last 1 candle // 6.2: Absolute Strengeh Histogram + HawkEye Volume Indicator // 6.2.1: Absolute Strengeh Histogram colour matches trend (long=blue, short=red) // 6.2.2: HawkEye Volume Indicator colour matches trend (long=green, short=red) var longTradeConfirmed = false var shortTradeConfirmed = false if confirmationInd == "ADX and DI" isAdxUp = ADX > ADX [1] isAdxValid = ADX > midLine and isAdxUp longTradeConfirmed := DIPlus > DIMinus and isAdxValid shortTradeConfirmed:= DIMinus > DIPlus and isAdxValid else if confirmationInd == "Absolute Strength Histogram + HawkEye Volume" isAshBullish = SmthBulls > SmthBears ? true : false isHevBullish = not grEnabled and gEnabled ? true : false isHevBearish = not grEnabled and rEnabled ? true : false longTradeConfirmed := isAshBullish and isHevBullish shortTradeConfirmed:= not isAshBullish and isHevBearish else if confirmationInd == "None" longTradeConfirmed := true shortTradeConfirmed:= true // Combine all entry conditions goLong = inDateRange and isCoralBullish and prePullbackBullBreakout and isPullbackValid and entryBreakout and longTradeConfirmed goShort = inDateRange and isCoralBearish and prePullbackBearBreakout and isPullbackValid and entryBreakout and shortTradeConfirmed // Trade entry and exit variables var tradeEntryBar = bar_index var profitPoints = 0. var lossPoints = 0. var slPrice = 0. var tpPrice = 0. var inLong = false var inShort = false var entryPrice = 0. // Entry decisions openLong = (goLong and not inLong) openShort = (goShort and not inShort) flippingSides = (goLong and inShort) or (goShort and inLong) enteringTrade = openLong or openShort inTrade = inLong or inShort // Exit calculations entryPrice := close longSlPrice = ta.lowest(localHlLookback) shortSlPrice = ta.highest(localHlLookback) slAmount = isCoralBullish ? entryPrice - longSlPrice : shortSlPrice - entryPrice slPercent = math.abs((1 - (entryPrice - slAmount) / entryPrice) * 100) tpPercent = slPercent * riskReward // Risk calculations riskAmt = strategy.equity * accountRiskPercent / 100 entryQty = math.abs(riskAmt / slPercent * 100) / close if openLong if strategy.position_size < 0 printTpSlNotHitBox(tradeEntryBar + 1, bar_index + 1, strategy.position_avg_price, slPrice, tpPrice) printTradeExitLabel(bar_index + 1, math.max(tpPrice, slPrice), strategy.position_size, strategy.position_avg_price, strategy.openprofit) strategy.entry("Long", strategy.long, qty = entryQty, alert_message = "Long Entry") enteringTrade := true inLong := true inShort := false if openShort if strategy.position_size > 0 printTpSlNotHitBox(tradeEntryBar + 1, bar_index + 1, strategy.position_avg_price, slPrice, tpPrice) printTradeExitLabel(bar_index + 1, math.max(tpPrice, slPrice), strategy.position_size, strategy.position_avg_price, strategy.openprofit) strategy.entry("Short", strategy.short, qty = entryQty, alert_message = "Short Entry") enteringTrade := true inShort := true inLong := false if enteringTrade profitPoints := percentAsPoints(tpPercent) lossPoints := percentAsPoints(slPercent) slPrice := calcStopLossPrice(lossPoints, openLong) tpPrice := calcProfitTrgtPrice(profitPoints, openLong) tradeEntryBar := bar_index strategy.exit("TP/SL", profit = profitPoints, loss = lossPoints, comment_profit = "TP Hit", comment_loss = "SL Hit", alert_profit = "TP Hit Alert", alert_loss = "SL Hit Alert") // ============================================================================= // DRAWINGS // ============================================================================= // ----------- // TP/SL Boxes // ----------- slHit = (inShort and high >= slPrice) or (inLong and low <= slPrice) tpHit = (inLong and high >= tpPrice) or (inShort and low <= tpPrice) exitTriggered = slHit or tpHit ctEntryPrice = strategy.closedtrades.entry_price (strategy.closedtrades - 1) pnl = strategy.closedtrades.profit (strategy.closedtrades - 1) posSize = strategy.closedtrades.size (strategy.closedtrades - 1) // Print boxes for trades closed at profit or loss if (inTrade and exitTriggered) inShort := false inLong := false printTpSlHitBox(tradeEntryBar, bar_index, slHit, tpHit, ctEntryPrice, slPrice, tpPrice) printTradeExitLabel(bar_index, math.max(tpPrice, slPrice), posSize, ctEntryPrice, pnl) // Print TP/SL box for current open trade if barstate.islastconfirmedhistory and strategy.position_size != 0 printTpSlNotHitBox(tradeEntryBar + 1, bar_index + 1, strategy.position_avg_price, slPrice, tpPrice) // // ============================================================================= // // DEBUGGING // // ============================================================================= // Data window plots plotchar(prePullbackBullBreakout, "prePullbackBullBreakout", "") plotchar(prePullbackBearBreakout, "prePullbackBearBreakout", "") plotchar(barssincePullbackStart, "barssincePullbackStart", "") plotchar(isCoralBullish, "isCoralBullish", "") plotchar(isCoralBearish, "isCoralBearish", "") plotchar(barssinceCoralflip, "barssinceCoralflip", "") plotchar(isPullbackValid, "isPullbackValid", "") plotchar(entryBreakout, "entryBreakout", "") plotchar(slHit, "slHit", "") plotchar(tpHit, "tpHit", "") plotchar(slPrice, "slPrice", "") // Label plots // plotDebugLabels = false // if plotDebugLabels // if bar_index == tradeEntryBar // printLabel(bar_index, "Position size: " + str.tostring(entryQty * close, "#.##"))
supertrend advance
https://www.tradingview.com/script/Ld0TePxg-supertrend-advance/
Aakashparikh787
https://www.tradingview.com/u/Aakashparikh787/
277
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/ // AAKASHPARIKH787 //@version=4 //////// strategy("supertrend advance", "supertrend Advance", overlay=true, max_labels_count=51, max_lines_count=50) SYNTAX_Output = input("{{strategy.order.alert_message}}", title= "OutPut_Syntax") syntax_broker = input("Fyers", title= "Broker", options=["Fyers", "Zerodha"]) tooltip_1_algo = "In Algo Syntax Type '{0}' in place of Quantity\n&& remove '{' & '}' the Bracket from the Syntax" group_buy_syntax_2= "🟩🟩🟩🟩 Algo-Syntax-2 🟩🟩🟩🟩" Want_PaperTrading = input(true, title= "Want Custom Syntax", group=group_buy_syntax_2, tooltip=tooltip_1_algo ) ZX_buy_s_entry_msg_i = input("", title= "Buy Entry Syntax", group=group_buy_syntax_2, tooltip=tooltip_1_algo) ZX_sell_s_entry_msg_i = input("", title= "Sell Entry Syntax", group=group_buy_syntax_2, tooltip=tooltip_1_algo) ZX_buy_s_exit_msg = input("", title= "Buy Exit Syntax", group=group_buy_syntax_2, tooltip=tooltip_1_algo) ZX_sell_s_exit_msg = input("", title= "Sell Exit Syntax", group=group_buy_syntax_2, tooltip=tooltip_1_algo) group_algo_syntax = "πŸŸ₯ πŸŸ₯ πŸŸ₯Options Algo-Syntax πŸŸ₯ πŸŸ₯ πŸŸ₯" tt = input("BUY", "CALL & PUT", options=["BUY", "SELL"], group=group_algo_syntax) ts = input("BANKNIFTY21MAY", "CALL Symbol", input.string, group=group_algo_syntax) ts_1 = input("BANKNIFTY21MAY", "PUT Symbol", input.string, group=group_algo_syntax) nearby = input("100", "Both side Nearby", input.string, group=group_algo_syntax) cal = input("+0", "CALL Side Calculation", input.string, group=group_algo_syntax) cal_1 = input("+0", "PUT Side Calculation", input.string, group=group_algo_syntax) product = input("INTRADAY", "Product", options=["INTRADAY","NRML"], group=group_algo_syntax) DL_Time = input(3000, "Delay Time", group=group_algo_syntax) functions_algo_syntax(qty_ALGOX, result)=> qty = tostring(qty_ALGOX) Buy_Call_f = '[{"AS":"' + ts + '","P":"' + product +'","AT":"FYERSV2"},{"TT":"' + "BUY" + '","TS":"' + ts +'{' +tostring(close) +'}CE","Q":"'+ qty +'","OT":"MARKET","P":"'+ product +'","VL":"DAY","NEAR":"'+ nearby +'","CAL":"'+ cal +'","AT":"FYERSV2"' + ',"DL":"'+ tostring(DL_Time) +'"}]' Buy_Call_z = '[{"AS":"' + ts + '","P":"' + product +'","E":"NFO","AT":"ZERODHA"},' + '{"TT":"' + "BUY" + '","E":"NFO","TS":"' + ts +'{' +tostring(close) +'}CE","Q":"'+ qty +'","OT":"MARKET","P":"'+ product +'","VL":"DAY","NEAR":"'+ nearby +'","CAL":"'+ cal +'","AT":"ZERODHA"' + ',"DL":"'+ tostring(DL_Time) +'"}]' Buy_Call = syntax_broker== "Fyers" ? Buy_Call_f : Buy_Call_z Buy_Put_f = '[{"AS":"' + ts_1+'","P":"' + product +'","AT":"FYERSV2"},{"TT":"' + "BUY" + '","TS":"' + ts_1 +'{' +tostring(close) +'}PE","Q":"'+ qty +'","OT":"MARKET","P":"'+ product +'","VL":"DAY","NEAR":"'+ nearby +'","CAL":"'+ cal_1 +'","AT":"FYERSV2"' + ',"DL":"'+ tostring(DL_Time) +'"}]' Buy_Put_z = '[{"AS":"' + ts_1+'","P":"' + product +'","E":"NFO","AT":"ZERODHA"},' + '{"TT":"' + "BUY" + '","E":"NFO","TS":"' + ts_1 +'{' +tostring(close) +'}PE","Q":"'+ qty +'","OT":"MARKET","P":"'+ product +'","VL":"DAY","NEAR":"'+ nearby +'","CAL":"'+ cal_1 +'","AT":"ZERODHA"' + ',"DL":"'+ tostring(DL_Time) +'"}]' Buy_Put = syntax_broker== "Fyers" ? Buy_Put_f : Buy_Put_z Sell_Call_f = '[{"AS":"' + ts + '","P":"' + product +'","AT":"FYERSV2"},{"TT":"' + "SELL" + '","TS":"' + ts +'{' +tostring(close) +'}PE","Q":"'+ qty +'","OT":"MARKET","P":"'+ product +'","VL":"DAY","NEAR":"'+ nearby +'","CAL":"'+ cal +'","AT":"FYERSV2"' + ',"DL":"'+ tostring(DL_Time) +'"}]' Sell_Call_z = '[{"AS":"' + ts + '","P":"' + product +'","E":"NFO","AT":"ZERODHA"},' + '{"TT":"' + "SELL" + '","E":"NFO","TS":"' + ts +'{' +tostring(close) +'}PE","Q":"'+ qty +'","OT":"MARKET","P":"'+ product +'","VL":"DAY","NEAR":"'+ nearby +'","CAL":"'+ cal +'","AT":"ZERODHA"' + ',"DL":"'+ tostring(DL_Time) +'"}]' Sell_Call = syntax_broker== "Fyers" ? Sell_Call_f : Sell_Call_z Sell_Put_f = '[{"AS":"' + ts_1+'","P":"' + product +'","E":"NFO","AT":"ZERODHA"},' + '{"TT":"' + "SELL" + '","E":"NFO","TS":"' + ts_1 +'{' +tostring(close) +'}CE","Q":"'+ qty +'","OT":"MARKET","P":"'+ product +'","VL":"DAY","NEAR":"'+ nearby +'","CAL":"'+ cal_1 +'","AT":"ZERODHA"' + ',"DL":"'+ tostring(DL_Time) +'"}]' Sell_Put_z = '[{"AS":"' + ts_1+'","P":"' + product +'","E":"NFO","AT":"ZERODHA"},' + '{"TT":"' + "SELL" + '","E":"NFO","TS":"' + ts_1 +'{' +tostring(close) +'}CE","Q":"'+ qty +'","OT":"MARKET","P":"'+ product +'","VL":"DAY","NEAR":"'+ nearby +'","CAL":"'+ cal_1 +'","AT":"ZERODHA"' + ',"DL":"'+ tostring(DL_Time) +'"}]' Sell_Put = syntax_broker== "Fyers" ? Sell_Put_f : Sell_Put_z Exit_Call_f = '[{"AS":"' + ts +'","P":"' + product + '","AT":"FYERSV2"}]' Exit_Call_z = '[{"AS":"' + ts + '","P":"' + product +'","E":"NFO","AT":"ZERODHA"}]' Exit_Call = syntax_broker== "Fyers" ? Exit_Call_f : Exit_Call_z Exit_Put_f = '[{"AS":"' + ts_1+'","P":"' + product + '","AT":"FYERSV2"}]' Exit_Put_z = '[{"AS":"' + ts_1+'","P":"' + product +'","E":"NFO","AT":"ZERODHA"}]' Exit_Put = syntax_broker== "Fyers" ? Exit_Put_f : Exit_Put_z Buy_Entry_msg = tt=="BUY" ? Buy_Call : Sell_Call Sell_Entry_msg = tt=="BUY" ? Buy_Put : Sell_Put buy_s_entry_msg_i = str.format(ZX_buy_s_entry_msg_i , qty, tostring(close) ) sell_s_entry_msg_i = str.format(ZX_sell_s_entry_msg_i , qty, tostring(close) ) buy_s_exit_msg = str.format(ZX_buy_s_exit_msg , qty, tostring(close) ) sell_s_exit_msg = str.format(ZX_sell_s_exit_msg , qty, tostring(close) ) Buy_Entry_msg := Want_PaperTrading ? buy_s_entry_msg_i : Buy_Entry_msg Sell_Entry_msg := Want_PaperTrading ? sell_s_entry_msg_i : Sell_Entry_msg Exit_Call := Want_PaperTrading ? buy_s_exit_msg : Exit_Call Exit_Put := Want_PaperTrading ? sell_s_exit_msg : Exit_Put return_ = result==1 ? Buy_Entry_msg : result==2 ? Sell_Entry_msg : result==3 ? Exit_Call : result==4 ? Exit_Put : "Error" return_ group_indicator_1 = "πŸŸ₯ πŸŸ₯ πŸŸ₯ πŸŸ₯ Indicator Settings πŸŸ₯ πŸŸ₯ πŸŸ₯ πŸŸ₯ " Periods_spt = input(title="ATR Period", type=input.integer, defval=10, group=group_indicator_1) src_spt = input(title="Source", defval=hl2, group=group_indicator_1) Multiplier_spt = input(title="ATR Multiplier", type=input.float, step=0.1, defval=3.0, group=group_indicator_1) changeATR_spt = input(title="Change ATR Calculation Method ?", type=input.bool, defval=true, group=group_indicator_1) showsignals_spt = input(title="Show Buy/Sell Signals ?", type=input.bool, defval=true, group=group_indicator_1) highlighting_spt = input(title="Highlighter On/Off ?", type=input.bool, defval=true, group=group_indicator_1) candle_type_ssl = input(defval="HeikenAshi", title="Candle_Type_Filter", options = ["HeikenAshi", "CandleStick", "Same as Chart"], group=group_indicator_1) f_spt()=> atr2_spt = sma(tr, Periods_spt) atr_spt = changeATR_spt ? atr(Periods_spt) : atr2_spt up_spt = src_spt - (Multiplier_spt*atr_spt) up1_spt = nz(up_spt[1],up_spt) up_spt := close[1] > up1_spt ? max(up_spt,up1_spt) : up_spt dn_spt = src_spt+(Multiplier_spt*atr_spt) dn1_spt = nz(dn_spt[1], dn_spt) dn_spt := close[1] < dn1_spt ? min(dn_spt, dn1_spt) : dn_spt trend_spt = 1 trend_spt := nz(trend_spt[1], trend_spt) trend_spt := trend_spt == -1 and close > dn1_spt ? 1 : trend_spt == 1 and close < up1_spt ? -1 : trend_spt [trend_spt, up_spt, dn_spt] [trend_spt_1, up_spt_1, dn_spt_1] = f_spt() [trend_spt_2, up_spt_2, dn_spt_2] = security(heikinashi(tickerid(syminfo.prefix,syminfo.ticker)), timeframe.period, f_spt()) [trend_spt_3, up_spt_3, dn_spt_3] = security(syminfo.tickerid, timeframe.period, f_spt()) trend_spt = candle_type_ssl=="HeikenAshi" ? trend_spt_2 : candle_type_ssl=="CandleStick" ? trend_spt_2 : trend_spt_1 up_spt = candle_type_ssl=="HeikenAshi" ? up_spt_2 : candle_type_ssl=="CandleStick" ? up_spt_2 : up_spt_1 dn_spt = candle_type_ssl=="HeikenAshi" ? dn_spt_2 : candle_type_ssl=="CandleStick" ? dn_spt_2 : dn_spt_1 buySignal_spt = trend_spt == 1 and trend_spt[1] == -1 sellSignal_spt = trend_spt == -1 and trend_spt[1] == 1 plotshape(buySignal_spt ? up_spt : na, title="UpTrend Begins", location=location.absolute, style=shape.circle, size=size.tiny, color=color.green ) plotshape(sellSignal_spt ? dn_spt : na, title="DownTrend Begins", location=location.absolute, style=shape.circle, size=size.tiny, color=color.red ) plotshape(buySignal_spt and showsignals_spt ? up_spt : na, title="Buy", text="Buy", location=location.absolute, style=shape.labelup, size=size.tiny, color=color.green, textcolor=color.white) plotshape(sellSignal_spt and showsignals_spt ? dn_spt : na, title="Sell", text="Sell", location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.red, textcolor=color.white) longFillColor_spt = highlighting_spt ? (trend_spt == 1 ? color.green : color.white) : color.white shortFillColor_spt = highlighting_spt ? (trend_spt == -1 ? color.red : color.white) : color.white mPlot_spt = plot(ohlc4, title="", style=plot.style_circles, linewidth=0) upPlot_spt = plot(trend_spt == 1 ? up_spt : na, title="Up Trend", style=plot.style_linebr, linewidth=2, color=color.green) dnPlot_spt = plot(trend_spt == 1 ? na : dn_spt, title="Down Trend", style=plot.style_linebr, linewidth=2, color=color.red) fill(mPlot_spt, upPlot_spt, title="UpTrend Highligter", color=longFillColor_spt) fill(mPlot_spt, dnPlot_spt, title="DownTrend Highligter", color=shortFillColor_spt) want_intraday = input(defval=false, type=input.bool, title="Want_Intraday", group=" ════╣ Entry Time ↓╠════") start_hours = input(defval=9 , type=input.integer, title="Hours", minval=0, maxval=23, inline="Entry_Time", group=" ════╣ Entry Time ↓╠════") start_minutes = input(defval=0 , type=input.integer, title="Minutes", minval=0, maxval=59, inline="Entry_Time", group=" ════╣ Entry Time ↓╠════") draw_entry_area = input(defval=false, type=input.bool, title="Highlight", inline="Entry_Time", group=" ════╣ Entry Time ↓╠════") time_entry() => want_intraday ? ((hour > start_hours ) ? true : (hour < start_hours ) ? false : (hour == start_hours ) ? minute >= start_minutes : false) : true bgcolor(time_entry() and draw_entry_area ? color.red : na, title="Entry_Time Area") end_hours = input(defval=14, type=input.integer, title="Hours", minval=0, maxval=23, inline="Exit_Time", group=" ════╣ Exit Time ↓╠════") end_minutes = input(defval=55, type=input.integer, title="Minutes", minval=0, maxval=59, inline="Exit_Time", group=" ════╣ Exit Time ↓╠════") draw_exit_area = input(defval=false, type=input.bool, title="Highlight", inline="Exit_Time", group=" ════╣ Exit Time ↓╠════") time_exit() => want_intraday ? ((hour > end_hours ) ? true : (hour < end_hours ) ? false : (hour == end_hours ) ? minute >= end_minutes : false) : false bgcolor(time_exit() and draw_exit_area ? color.red : na, title="Exit_Time Area") group_date = "πŸŸ₯ πŸŸ₯ πŸŸ₯ πŸŸ₯ Date- Filter πŸŸ₯ πŸŸ₯ πŸŸ₯ πŸŸ₯ " fromDay = input(defval = 1, inline="xx_x", title = "From Day", minval = 1, maxval = 31, group=group_date) fromMonth = input(defval = 1, inline="xx_x", title = " Month", minval = 1, maxval = 12, group=group_date) fromYear = input(defval = 2015, inline="xx_x", title = " Year", minval = 1970, group=group_date) toDay = input(defval = 1, inline="xx_y", title = "To Day", minval = 1, maxval = 31, group=group_date) toMonth = input(defval = 1, inline="xx_y", title = " Month", minval = 1, maxval = 12, group=group_date) toYear = input(defval = 2023, inline="xx_y", title = " Year", minval = 1970 , group=group_date) startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00) finishDate = timestamp(toYear, toMonth, toDay, 00, 00) time_cond() => time >= startDate and time <= finishDate group_strategy_qty_1 = "======== Quantity-Settings ↓========" want_qty_feature = input(defval=true, title="Want_Quantity Feature", group=group_strategy_qty_1) want_qty_feature_refresh = input(defval=true, title="Want_Quantity Feature Refresh Daily", group=group_strategy_qty_1) qty_1_x_max = input(defval=100.0, title="Max_Qty", group=group_strategy_qty_1) qty_1_x = input(defval=25.0, title="Entry Quanity", group=group_strategy_qty_1) f_martangle_qty_1()=> var qty_1 = 0.0 var loss_trade = false if dayofmonth!=dayofmonth[1] and want_qty_feature_refresh loss_trade := false qty_1 := qty_1_x if change(strategy.losstrades) and (strategy.losstrades+strategy.wintrades)>1 loss_trade := true if change(strategy.wintrades) and (strategy.losstrades+strategy.wintrades)>1 loss_trade := false if loss_trade and change(strategy.losstrades) and qty_1_x_max > qty_1 qty_1 := qty_1 * 2 if loss_trade==false //and strategy.position_size==0 qty_1 := qty_1_x if want_qty_feature==false qty_1 := qty_1_x qty_1 buy_time = buySignal_spt and strategy.position_size<=0 and time_cond() and time_entry() and time_exit()==false sell_time = sellSignal_spt and strategy.position_size>=0 and time_cond() and time_entry() and time_exit()==false exit_alert_msg_1 = functions_algo_syntax(f_martangle_qty_1(), 3 ) exit_alert_msg_2 = functions_algo_syntax(f_martangle_qty_1(), 4 ) if strategy.position_size > 0 strategy.close( 'Buy', when=time_exit() and want_intraday, alert_message=exit_alert_msg_1, comment="EoD_Exit") if strategy.position_size < 0 strategy.close( 'Sell', when=time_exit() and want_intraday, alert_message=exit_alert_msg_2, comment="EoD_Exit") strategy.close("Buy", when= sell_time, comment="Buy_Exit", alert_message=functions_algo_syntax(f_martangle_qty_1(), 3 )) strategy.close("Sell", when= buy_time, comment="Sell_Exit", alert_message=functions_algo_syntax(f_martangle_qty_1(), 4 )) group_strategy_tp_sl_1 = "======== TP-SL-Main & Reverse ↓========" tp_sl_type = input(defval="Percent",title="TP-SL Type", options=["Points","Percent"], group=group_strategy_tp_sl_1) target_points_1_00 = input(defval=20, title="Target ", type=input.float, minval=0 , group=group_strategy_tp_sl_1) sl_points_1_00 = input(defval=30, title="Stop-Loss ", type=input.float, minval=0 , group=group_strategy_tp_sl_1 ) want_spt_tp = input(defval=true, title="Want Supertrend TP ", type=input.bool, inline="aabjbdkjbsk", group=group_strategy_tp_sl_1 ) spt_tp_factor = input(defval=1, title="X-times ", type=input.float, inline="aabjbdkjbsk", group=group_strategy_tp_sl_1 ) SPT_value = buySignal_spt ? up_spt : sellSignal_spt ? dn_spt : na spt_sl_x = round( ( abs(close - SPT_value) *spt_tp_factor ) /syminfo.mintick ) spt_sl = 0 spt_sl := buy_time or sell_time ? spt_sl_x : spt_sl[1] target_points_1_01 = round( ( close* (target_points_1_00*0.01) )/syminfo.mintick) target_points_1_02 = round(target_points_1_00/syminfo.mintick) target_points_1 = tp_sl_type=="Points" ? target_points_1_02 : target_points_1_01 target_points_1 := want_spt_tp ? min(target_points_1, spt_sl ) : target_points_1 sl_points_1_01 = round( ( close* (sl_points_1_00*0.01) )/syminfo.mintick) sl_points_1_02 = round(sl_points_1_00/syminfo.mintick) sl_points_1 = tp_sl_type=="Points" ? sl_points_1_02 : sl_points_1_01 group_strategy_1 = "🟧 🟧 🟧 Strategy - Settings 🟧 🟧 🟧 " group_strategy_2 = "🟧 🟧 🟧 SL-Trailing- Settings 🟧 🟧 🟧 " want_buy = input(title="Want_Buy_Side", defval=true, type=input.bool, group=group_strategy_1) want_sell = input(title="Want_Sell_Side", defval=true, type=input.bool, group=group_strategy_1) strategy.entry("Buy", true, when= buy_time and want_buy , qty = f_martangle_qty_1() , alert_message=functions_algo_syntax(f_martangle_qty_1(), 1 )) strategy.entry("Sell", false, when= sell_time and want_sell, qty = f_martangle_qty_1() , alert_message=functions_algo_syntax(f_martangle_qty_1(), 2 )) strategy.exit('Buy_Exit' , 'Buy', loss=sl_points_1, profit=target_points_1 , alert_message=functions_algo_syntax(f_martangle_qty_1(), 3 ) ) strategy.exit('Sell_Exit', 'Sell', loss=sl_points_1, profit=target_points_1 , alert_message=functions_algo_syntax(f_martangle_qty_1(), 4 ) )
CROSS_ALGO SYSTEM
https://www.tradingview.com/script/uM3SMvsM-CROSS-ALGO-SYSTEM/
himanshumahalle
https://www.tradingview.com/u/himanshumahalle/
17
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/ // Β© himanshumahalle //@version=4 strategy("CROSS_ALGO SYSTEM") // INPUT CONTROLS lengthSEMA= input(title="LSEMA", type = input.integer, defval=13,minval=1,maxval=100,step=1) lengthLEMA= input(title="LLEMA", type = input.integer, defval=50,minval=1,maxval=100,step=1) //INDICATOR SEMA= ema(close,lengthSEMA) LEMA= ema(close,lengthLEMA) // BUY AND SELL buy = crossover(SEMA,LEMA) sell = crossunder(SEMA,LEMA) //EXITS buyexit = crossunder(SEMA,LEMA) sellexit = crossover(SEMA,LEMA) //EXECUTION strategy.entry("long",strategy.long,when=buy,comment = "Buy") strategy.entry("short",strategy.short,when=sell,comment = "Sell") strategy.close("long",when= buyexit , comment= "Sell") strategy.close("short",when= sellexit , comment= "Buy")
Balance of Power Heikin Ashi Investing Strategy
https://www.tradingview.com/script/pRel4d46-Balance-of-Power-Heikin-Ashi-Investing-Strategy/
exlux99
https://www.tradingview.com/u/exlux99/
79
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© exlux99 //@version=5 strategy(title="Balance of Power Heikin Ashi Swing Strategy") x_close = request.security(ticker.heikinashi("SPY"), "M", close) x_open = request.security(ticker.heikinashi("SPY"), "M", open) x_high =request.security(ticker.heikinashi("SPY"), "M", high) x_low = request.security(ticker.heikinashi("SPY"), "M", low) gog = (x_close - x_open) / (x_high - x_low) out = ta.ema(gog,input.int(252)) plot(out, color = color.white) hline(0) length = input(75) p = input.int(99, 'Percentage', minval=0, maxval=100) p2 = input.int(1, 'Percentage', minval=0, maxval=100) pnr = ta.percentile_nearest_rank(out, length, p) pnr2 = ta.percentile_nearest_rank(out, length, p2) long = pnr > pnr[1] and ( out > 0 or (out >-0.35 and out[1] <-0.35)) short = (out < 0 and ( pnr < pnr[1] and pnr2 < pnr2[1])) or ( out < 0.6 and out[1] > 0.6) strategy.entry("long",strategy.long,when=long) strategy.entry("short",strategy.short,when=short)
Trend Breakout high/low #1
https://www.tradingview.com/script/vwpomlLR/
zxcv55602
https://www.tradingview.com/u/zxcv55602/
94
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© zxcv55602 //@version=4 strategy("Trend #1 - ATR+Breakout high/low", overlay = true,slippage=0,commission_value=0,initial_capital=100000) date1 = input(title="Start Date", type=input.time, defval=timestamp("2020-01-01T00:00:00")) date2 = input(title="Stop Date", type=input.time, defval=timestamp("2030-01-01T00:00:00")) t1= input(title ="Trading period",type=input.session,defval="3D",options=["1M","3W","2W","1W","5D","4D","3D","2D","1D","720","480","360","240","180","120","60","30","15","10","5","3","1"] ) stop_loss=input(1000,"Stop loss", minval=0,step =1) Trange=input(100,"Trading range", step =1) range=input(100,"Stop range", step =1) atrlen = input(1, "ATR Period") mult_atr = input(1, "ATR mult", step=0.1) smalong=input(title="SMA switch", type=input.bool, defval=false) smainput=input(300,"SMA switch", minval=2,step =1) longsignal=input(title="Long", type=input.bool, defval=true) shortsignal=input(title="Short", type=input.bool, defval=true) fixedmode=input(title="Fixed mode", type=input.bool, defval=false) fixed=input(1,"Fixed mode",step =0.1) //----------- var float Y_Low = na var float Y_High = na if change(time(t1),length=1)!= 0 Y_High:=high Y_Low:= low else Y_High:=high>nz(Y_High)?high:Y_High Y_Low:=low<nz(Y_Low)?low:Y_Low con1= change(time(t1),length = 1 ) != 0?1:0 //plot(Y_High[0],"LOW",color.yellow,linewidth = 2) //plot(Y_Low[0],"LOW",color.white,linewidth = 2) //----------- var upper=0.0 var lower=0.0 var con_op=0.0 var central_line=0.0 if con1==1 upper:=Y_High[1]-(((Y_High[1]-Y_Low[1])/100)*(100-Trange)/2) lower:=Y_Low[1]+(((Y_High[1]-Y_Low[1])/100)*(100-Trange)/2) con_op:=0 central_line:=(Y_High[1]+Y_Low[1])/2 //----------- //plotarrow(con1==1?con1:na,colorup=color.white,colordown=color.white) //----------- var sma1=0.0 sma=sma(close[0],smainput) sma1:=security(syminfo.tickerid,t1,sma) if smalong==false sma1:=sma(close[0],smainput) plot(sma1,color=color.new(color.blue,0),linewidth=1) //------------------ upper_atr = ema(tr(true),atrlen) * mult_atr + close lower_atr = close - ema(tr(true),atrlen) * mult_atr plot(upper_atr, color=color.new(color.white,80),style=plot.style_stepline) plot(lower_atr, color=color.new(color.white,80),style=plot.style_stepline) //------------------ plot(upper,"HIGH",color.green,linewidth = 1,style=plot.style_stepline) plot(lower,"LOW",color.red,linewidth = 1,style=plot.style_stepline) plot(upper-(((upper-lower)/100)*range),color=color.new(color.green,50), linewidth=1) plot(lower+(((upper-lower)/100)*range),color=color.new(color.red,50), linewidth=1) //----------- var OP_L_stop=0.0 var OP_S_stop=0.0 //----------- if time >= date1 and time <= date2 and con_op==0 if longsignal if strategy.position_size==0 and upper>sma1 and close>upper OP_L_stop:=upper-(((upper-lower)/100)*range) con_op:=1 strategy.entry("OP_L",strategy.long,when=close>upper,qty=fixedmode==true?fixed:(stop_loss/(close-OP_L_stop)),limit=upper_atr) strategy.exit("OP_L",stop=OP_L_stop,comment="sell_L",limit=upper_atr) if strategy.position_size>0 strategy.exit("OP_L",stop=OP_L_stop,comment="stop_L",limit=upper_atr) if shortsignal if strategy.position_size==0 and lower<sma1 and close<lower OP_S_stop:=lower+(((upper-lower)/100)*range) con_op:=1 strategy.entry("OP_S",strategy.short,when=close<lower,qty=fixedmode==true?fixed:(stop_loss/(OP_S_stop-close)),limit=lower_atr) strategy.exit("OP_S",stop=OP_S_stop,comment="sell_S",limit=lower_atr) if strategy.position_size<0 strategy.exit("OP_S",stop=OP_S_stop,comment="stop_S",limit=lower_atr)
BTC Hashrate ribbons
https://www.tradingview.com/script/w6QJPRr3-BTC-Hashrate-ribbons/
Powerscooter
https://www.tradingview.com/u/Powerscooter/
110
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/ // Β© Powerscooter // Since IntoTheBlock only provides daily hashrate data, this chart might look chunky on lower timeframes, even with smoothing. //@version=5 strategy("BTC Hashrate ribbons", overlay = true, scale=scale.none, default_qty_type = strategy.cash, default_qty_value = 100, initial_capital = 100) enableDirection = input(0, title="Both(0), Long(1), Short(-1)", group="Direction") smoothingS = input.string(title="Smoothing short MA", defval="SMA", options=["SMA", "RMA", "EMA", "WMA"], group="Hashrate Settings") SmoothLengthS = input(30, 'Short MA length', group="Hashrate Settings") smoothingL = input.string(title="Smoothing long MA", defval="SMA", options=["SMA", "RMA", "EMA", "WMA"], group="Hashrate Settings") SmoothLengthL = input(60, 'Long MA length', group="Hashrate Settings") ma_functionS(source, length) => switch smoothingS "RMA" => ta.rma(source, length) "SMA" => ta.sma(source, length) "EMA" => ta.ema(source, length) => ta.wma(source, length) ma_functionL(source, length) => switch smoothingL "RMA" => ta.rma(source, length) "SMA" => ta.sma(source, length) "EMA" => ta.ema(source, length) => ta.wma(source, length) Source = input.string(title="Data Source", defval="Quandl", options=["Quandl", "Glassnode", "IntoTheBlock"], group="Source Settings") SourceE = switch Source "Quandl" => "QUANDL:BCHAIN/HRATE" "Glassnode" => "GLASSNODE:BTC_HASHRATE" "IntoTheBlock" => "INTOTHEBLOCK:BTC_HASHRATE" HashRate = request.security(SourceE, "D", close) SignalLine = ma_functionS(HashRate, SmoothLengthS) LongLine = ma_functionL(HashRate, SmoothLengthL) plot(ma_functionS(HashRate, SmoothLengthS), "Short MA", color=color.yellow) plot(ma_functionL(HashRate, SmoothLengthL), "Long MA", color=color.blue) LongCondition = ta.crossover(SignalLine, LongLine) ShortCondition = ta.crossunder(SignalLine, LongLine) //Long Entry Condition if LongCondition and (enableDirection == 1 or enableDirection == 0) strategy.entry("Long", strategy.long) if LongCondition and (enableDirection == -1) strategy.close("Short") //Short Entry condition if ShortCondition and (enableDirection == -1 or enableDirection == 0) strategy.entry("Short", strategy.short) if ShortCondition and (enableDirection == 1) strategy.close("Long")
Risk Management Strategy Template
https://www.tradingview.com/script/yWj2AnpX-Risk-Management-Strategy-Template/
kevinmck100
https://www.tradingview.com/u/kevinmck100/
490
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/ // Β© kevinmck100 // @description // This strategy is intended to be used as a base template for building new strategies. // // It incorporates the following features: // // - Risk management: Configurable X% loss per stop loss // Configurable R:R ratio // // - Trade entry: Calculated position size based on risk tolerance // // - Trade exit: Stop Loss currently configurable ATR multiplier but can be replaced based on strategy // Take Profit calculated from Stop Loss using R:R ratio // // - Backtesting: Configurable backtesting range by date // // - Trade drawings: TP/SL boxes drawn for all trades. Can be turned on and off // Trade exit information labels. Can be turned on and off // NOTE: Trade drawings will only be applicable when using overlay strategies // // - Debugging: Includes section with useful debugging techniques // // Strategy conditions: // // - Trade entry: LONG: C1: Price is above EMA line // C2: RSI is crossing out of oversold area // SHORT: C1: Price is below EMA line // C2: RSI is crossing out of overbought area // // - Trade exit: Stop Loss: Stop Loss ATR multiplier is hit // Take Profit: R:R multiplier * Stop Loss is hit // // The idea is to use RSI to catch pullbacks within the main trend. Note that // this strategy is intended to be a simple base strategy for building upon. // It was not designed to be traded in its current form. //@version=5 INITIAL_CAPITAL = 1000 DEFAULT_COMMISSION = 0.02 MAX_DRAWINGS = 500 IS_OVERLAY = true strategy("Risk Management Strategy Template", "Strategy Template", overlay = IS_OVERLAY, initial_capital = INITIAL_CAPITAL, currency = currency.NONE, max_labels_count = MAX_DRAWINGS, max_boxes_count = MAX_DRAWINGS, max_lines_count = MAX_DRAWINGS, default_qty_type = strategy.cash, commission_type = strategy.commission.percent, commission_value = DEFAULT_COMMISSION) // ============================================================================= // INPUTS // ============================================================================= // ------------------------ Replacable section - Start ------------------------- // ------------------ // Indicator Settings // ------------------ emaLength = input.int (200, "EMA Length          ", group = "Indicators: Settings", inline = "IS1", minval = 1, tooltip = "EMA line to identify trend direction. Above EMA trend line is bullish. Below EMA trend line is bearish") rsiLength = input.int (10, "RSI Length            ", group = "Indicators: Settings", inline = "IS2", minval = 1) // ---------------------- // Trade Entry Conditions // ---------------------- rsiOverbought = input.int (60, "RSI Overbought        ", group = "Strategy: Conditions", inline = "SC1", minval = 50, maxval = 100, tooltip = "RSI overbought level used to identify pullbacks within the main trend. RSI crossing BELOW this level triggers a SHORT when in a DOWN trend") rsiOversold = input.int (40, "RSI Oversold          ", group = "Strategy: Conditions", inline = "SC2", minval = 0, maxval = 50, tooltip = "RSI overbought level used to identify pullbacks within the main trend. RSI crossing ABOVE this level triggers a LONG when in an UP trend") // --------------------- // Trade Exit Conditions // --------------------- atrLength = input.int (14, "Stop Loss ATR Length      ", group = "Strategy: Exit Conditions", inline = "EC1", minval = 0, tooltip = "Length of ATR used to calculate Stop Loss.") slAtrMultiplier = input.float(4, "Stop Loss ATR Multiplier     ", group = "Strategy: Exit Conditions", inline = "EC2", minval = 0, step = 0.1, tooltip = "Size of StopLoss is determined by multiplication of ATR value. Take Profit is derived from this also by multiplying the StopLoss value by the Risk:Reward multiplier.") // ------------------------- Replacable section - End -------------------------- // --------------- // Risk Management // --------------- riskReward = input.float(2, "Risk : Reward        1 :", group = "Strategy: Risk Management", inline = "RM1", minval = 0, step = 0.1, tooltip = "Previous high or low (long/short dependant) is used to determine TP level. 'Risk : Reward' ratio is then used to calculate SL based of previous high/low level.\n\nIn short, the higher the R:R ratio, the smaller the SL since TP target is fixed by previous high/low price data.") accountRiskPercent = input.float(1, "Portfolio Risk %         ", group = "Strategy: Risk Management", inline = "RM1", minval = 0, step = 0.1, tooltip = "Percentage of portfolio you lose if trade hits SL.\n\nYou then stand to gain\n Portfolio Risk % * Risk : Reward\nif trade hits TP.") // ---------- // Date Range // ---------- startYear = input.int (2022, "Start Date       ", group = 'Strategy: Date Range', inline = 'DR1', minval = 1900, maxval = 2100) startMonth = input.int (1, "", group = 'Strategy: Date Range', inline = 'DR1', options = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) startDate = input.int (1, "", group = 'Strategy: Date Range', inline = 'DR1', options = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]) endYear = input.int (2100, "End Date      ", group = 'Strategy: Date Range', inline = 'DR2', minval = 1900, maxval = 2100) endMonth = input.int (1, "", group = 'Strategy: Date Range', inline = 'DR2', options = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) endDate = input.int (1, "", group = 'Strategy: Date Range', inline = 'DR2', options = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]) // ---------------- // Drawing Settings // ---------------- showTpSlBoxes = input.bool(true, "Show TP / SL Boxes", group = "Strategy: Drawings", inline = "D1", tooltip = "Show or hide TP and SL position boxes.\n\nNote: TradingView limits the maximum number of boxes that can be displayed to 500 so they may not appear for all price data under test.") showLabels = input.bool(false, "Show Trade Exit Labels", group = "Strategy: Drawings", inline = "D2", tooltip = "Useful labels to identify Profit/Loss and cumulative portfolio capital after each trade closes.\n\nAlso note that TradingView limits the max number of 'boxes' that can be displayed on a chart (max 500). This means when you lookback far enough on the chart you will not see the TP/SL boxes. However you can check this option to identify where trades exited.") // ============================================================================= // INDICATORS // ============================================================================= // ------------------------ Replacable section - Start ------------------------- // --- // EMA // --- ema = ta.ema(close, emaLength) plot(ema, "EMA Trend Line", color.white) // --- // RSI // --- rsi = ta.rsi(close, rsiLength) // ------------------------- Replacable section - End -------------------------- // ============================================================================= // STRATEGY LOGIC // ============================================================================= // --------- // FUNCTIONS // --------- percentAsPoints(pcnt) => math.round(pcnt / 100 * close / syminfo.mintick) calcStopLossPrice(pointsOffset, isLong) => priceOffset = pointsOffset * syminfo.mintick if isLong close - priceOffset else close + priceOffset calcProfitTrgtPrice(pointsOffset, isLong) => calcStopLossPrice(-pointsOffset, isLong) printLabel(barIndex, msg) => label.new(barIndex, close, msg) printTpSlHitBox(left, right, slHit, tpHit, entryPrice, slPrice, tpPrice) => if showTpSlBoxes box.new (left = left, top = entryPrice, right = right, bottom = slPrice, bgcolor = slHit ? color.new(color.red, 60) : color.new(color.gray, 90), border_width = 0) box.new (left = left, top = entryPrice, right = right, bottom = tpPrice, bgcolor = tpHit ? color.new(color.green, 60) : color.new(color.gray, 90), border_width = 0) line.new(x1 = left, y1 = entryPrice, x2 = right, y2 = entryPrice, color = color.new(color.yellow, 20)) line.new(x1 = left, y1 = slPrice, x2 = right, y2 = slPrice, color = color.new(color.red, 20)) line.new(x1 = left, y1 = tpPrice, x2 = right, y2 = tpPrice, color = color.new(color.green, 20)) printTpSlNotHitBox(left, right, entryPrice, slPrice, tpPrice) => if showTpSlBoxes box.new (left = left, top = entryPrice, right = right, bottom = slPrice, bgcolor = color.new(color.gray, 90), border_width = 0) box.new (left = left, top = entryPrice, right = right, bottom = tpPrice, bgcolor = color.new(color.gray, 90), border_width = 0) line.new(x1 = left, y1 = entryPrice, x2 = right, y2 = entryPrice, color = color.new(color.yellow, 20)) line.new(x1 = left, y1 = slPrice, x2 = right, y2 = slPrice, color = color.new(color.red, 20)) line.new(x1 = left, y1 = tpPrice, x2 = right, y2 = tpPrice, color = color.new(color.green, 20)) printTradeExitLabel(x, y, posSize, entryPrice, pnl) => if showLabels labelStr = "Position Size: " + str.tostring(math.abs(posSize), "#.##") + "\nPNL: " + str.tostring(pnl, "#.##") + "\nCapital: " + str.tostring(strategy.equity, "#.##") + "\nEntry Price: " + str.tostring(entryPrice, "#.##") label.new(x = x, y = y, text = labelStr, color = pnl > 0 ? color.new(color.green, 60) : color.new(color.red, 60), textcolor = color.white, style = label.style_label_down) // ---------- // CONDITIONS // ---------- inDateRange = time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0) and time < timestamp(syminfo.timezone, endYear, endMonth, endDate, 0, 0) // ------------------------ Replacable section - Start ------------------------- // Condition 1: Price above EMA indicates bullish trend, price below EMA indicates bearish trend bullEma = close > ema bearEma = close < ema // Condition 2: RSI crossing back from overbought/oversold indicates pullback within trend bullRsi = ta.crossover (rsi, rsiOversold) bearRsi = ta.crossunder (rsi, rsiOverbought) // Combine all entry conditions goLong = inDateRange and bullEma and bullRsi goShort = inDateRange and bearEma and bearRsi // ------------------------- Replacable section - End -------------------------- // Trade entry and exit variables var tradeEntryBar = bar_index var profitPoints = 0. var lossPoints = 0. var slPrice = 0. var tpPrice = 0. var inLong = false var inShort = false // Entry decisions openLong = (goLong and not inLong) openShort = (goShort and not inShort) flippingSides = (goLong and inShort) or (goShort and inLong) enteringTrade = openLong or openShort inTrade = inLong or inShort // ------------------------ Replacable section - Start ------------------------- // Exit calculations atr = ta.atr(atrLength) slAmount = atr * slAtrMultiplier slPercent = math.abs((1 - (close - slAmount) / close) * 100) tpPercent = slPercent * riskReward // ------------------------- Replacable section - End -------------------------- // Risk calculations riskAmt = strategy.equity * accountRiskPercent / 100 entryQty = math.abs(riskAmt / slPercent * 100) / close if openLong if strategy.position_size < 0 printTpSlNotHitBox(tradeEntryBar + 1, bar_index + 1, strategy.position_avg_price, slPrice, tpPrice) printTradeExitLabel(bar_index + 1, math.max(tpPrice, slPrice), strategy.position_size, strategy.position_avg_price, strategy.openprofit) strategy.entry("Long", strategy.long, qty = entryQty, alert_message = "Long Entry") enteringTrade := true inLong := true inShort := false if openShort if strategy.position_size > 0 printTpSlNotHitBox(tradeEntryBar + 1, bar_index + 1, strategy.position_avg_price, slPrice, tpPrice) printTradeExitLabel(bar_index + 1, math.max(tpPrice, slPrice), strategy.position_size, strategy.position_avg_price, strategy.openprofit) strategy.entry("Short", strategy.short, qty = entryQty, alert_message = "Short Entry") enteringTrade := true inShort := true inLong := false if enteringTrade profitPoints := percentAsPoints(tpPercent) lossPoints := percentAsPoints(slPercent) slPrice := calcStopLossPrice(lossPoints, openLong) tpPrice := calcProfitTrgtPrice(profitPoints, openLong) tradeEntryBar := bar_index strategy.exit("TP/SL", profit = profitPoints, loss = lossPoints, comment_profit = "TP Hit", comment_loss = "SL Hit", alert_profit = "TP Hit Alert", alert_loss = "SL Hit Alert") // ============================================================================= // DRAWINGS // ============================================================================= // ----------- // TP/SL Boxes // ----------- slHit = (inShort and high >= slPrice) or (inLong and low <= slPrice) tpHit = (inLong and high >= tpPrice) or (inShort and low <= tpPrice) exitTriggered = slHit or tpHit entryPrice = strategy.closedtrades.entry_price (strategy.closedtrades - 1) pnl = strategy.closedtrades.profit (strategy.closedtrades - 1) posSize = strategy.closedtrades.size (strategy.closedtrades - 1) // Print boxes for trades closed at profit or loss if (inTrade and exitTriggered) inShort := false inLong := false printTpSlHitBox(tradeEntryBar + 1, bar_index, slHit, tpHit, entryPrice, slPrice, tpPrice) printTradeExitLabel(bar_index, math.max(tpPrice, slPrice), posSize, entryPrice, pnl) // Print TP/SL box for current open trade if barstate.islastconfirmedhistory and strategy.position_size != 0 printTpSlNotHitBox(tradeEntryBar + 1, bar_index + 1, strategy.position_avg_price, slPrice, tpPrice) // ============================================================================= // DEBUGGING // ============================================================================= // Data window plots plotchar(slPrice, "Stop Loss Price", "") plotchar(tpPrice, "Take Profit Price", "") // Label plots plotDebugLabels = false if plotDebugLabels if bar_index == tradeEntryBar printLabel(bar_index, "Position size: " + str.tostring(entryQty * close, "#.##"))
Accumulation Stage Identifier and Strategy around for Trading
https://www.tradingview.com/script/YcQgB5IA-Accumulation-Stage-Identifier-and-Strategy-around-for-Trading/
stocktechbot
https://www.tradingview.com/u/stocktechbot/
77
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© stocktechbot //@version=5 strategy("Accumulate", overlay = true) lookback = input(defval = 21, title = 'Lookback') offset = input.int(title="Offset", defval=0, minval=-500, maxval=500) //SMA Tredline out = ta.sma(close, 200) outf = ta.sma(close, 50) outn = ta.sma(close, 90) outt = ta.sma(close, 21) //sma plot plot(out, color=color.blue, title="MA200", offset=offset) plot(outf, color=color.maroon, title="MA50", offset=offset) plot(outn, color=color.orange, title="MA90", offset=offset) plot(outt, color=color.olive, title="MA21", offset=offset) //MarketCap Calculation //MarketCap = 0.0 //TSO = request.financial(syminfo.tickerid, "TOTAL_SHARES_OUTSTANDING", "FQ", ignore_invalid_symbol = true) //if str.tostring(TSO) != 'na' // if ta.barssince(TSO != TSO[1] and TSO > TSO[1])==0 // MarketCap := TSO * close // // if barstate.islast and MarketCap == 0 // runtime.error("No MarketCap is provided by the data vendor.") // //momlen = 100 //msrc = MarketCap //mom = msrc - msrc[momlen] //plotmom = if (mom > mom[1]) // true //else // false //OBV with sma on macd obv = ta.cum(math.sign(ta.change(close)) * volume) smoothingLength = 5 smoothingLine = ta.sma(obv,5) [macdLine, signalLine, histLine] = ta.macd(ta.pvt, 12, 26, 9) sellvolhigh = macdLine < signalLine buyvolhigh = macdLine > signalLine //Buy Signal mafentry =ta.sma(close, 50) > ta.sma(close, 90) //matentry = ta.sma(close, 21) > ta.sma(close, 50) matwohun = close > ta.sma(close, 200) higheshigh = ta.rising(high, 2) higheslow = ta.rising(low, 2 ) twohunraise = ta.rising(out, 2) //highvol = ta.crossover(volume, ta.sma(volume, lookback)) highvol = ta.rising(volume,2) fourlow = ta.lowest(close, lookback) fourhig = ta.highest(close, lookback) change = (((fourhig - fourlow) / fourlow) * 100) <= 30 green = close > open allup = false lineabove = ta.cross(close, ta.sma(close, input(defval = 21, title = 'Entry Line'))) if matwohun and mafentry and higheshigh and twohunraise and buyvolhigh //if higheshigh and higheslow and highvol allup := true plotshape(allup, style=shape.arrowup,location=location.belowbar, color=color.green, title = "Buy Signal") barsSinceLastEntry() => strategy.opentrades > 0 ? bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades - 1) : na //Sell Signal mafexit =ta.sma(close, 50) < ta.sma(close, 90) matexit = ta.sma(close, 21) < ta.sma(close, 50) matwohund = close < ta.sma(close, 200) linebreak = ta.sma(close, input(defval = 21, title = 'Exit Line')) > close lowesthigh = ta.falling(high, 3) lowestlow = ta.falling(low, 2 ) twohunfall = ta.falling(out, 3) twentyfall = ta.falling(outt, 2) highvole = ta.crossover(volume, ta.sma(volume, 5)) //fourlow = ta.lowest(close, lookback) //fourhig = ta.highest(close, lookback) changed = (((fourhig - close) / close) * 100) >= 10 red = close < open atr = ta.atr(14) //atrsmalen = int(bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades - 1) ) atrsmalen = barsSinceLastEntry() atrsma = false atrlen = 5 if str.tostring(atrsmalen) != 'NaN' and atrsmalen > 0 atrlen := atrsmalen atrsma := atr > ta.sma(atr,50) alldwn = false if sellvolhigh and lowestlow and (close < close[1] and close < open) //if higheshigh and higheslow and highvol alldwn := true plotshape(alldwn, style=shape.arrowdown,location=location.abovebar, color=color.red, title = "Sell Signal") longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28)) if (allup) strategy.entry("My Long Entry Id", strategy.long) shortCondition = ta.crossunder(ta.sma(close, 14), ta.sma(close, 28)) if (alldwn) strategy.entry("My Short Entry Id", strategy.short)
Pro Trading Art Open Range Breakout Strategy
https://www.tradingview.com/script/wkwvEkmS-Pro-Trading-Art-Open-Range-Breakout-Strategy/
protradingart
https://www.tradingview.com/u/protradingart/
625
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/ // Β© protradingart //@version=5 strategy('Pro Trading Art Open Range Breakout Strategy', 'PTA - Open Range Breakout Strategy', overlay=true) //#region ///////////// User INput Section //////////////////////////// openRange = input.float(0.4, "Open Range %", step=0.1, group="=============== Indicator Settings ===============") ///////////////////////////////////// Start, Stop & Close Time Input Section ///////////////////////////////////////////////// startH = input.int(9, "Start Hour", inline='start', group="========= Start Trade AT =========") startM = input.int(15, "Start Minute", inline='start', group="========= Start Trade AT =========") stopNewTrade = input.int(14, "Stop Hour", inline='start', group="========= Stop New Trade At =========") endH = input.int(15, "End Hour", inline='end', group="========= Close All Trade At =========") endM = input.int(0, "End Minute", inline='end', group="========= Close All Trade At =========") isCloseAll = input.bool(true, "Close All Trade", group="========= Close All Trade At =========") isHighV = input.bool(true, "Show High", inline="range", group="========= Plot Range =========") isLowV = input.bool(true, "Show Low", inline="range", group="========= Plot Range =========") buffer = input.float(0.0, "Buffer", group="========= Strategy Settings =========") tradeGap = input.float(100, "Trade Gap", group="========= Strategy Settings =========") gapBook = input.float(50, "Min Profit Point After Trade Gap", group="========= Strategy Settings =========") //#endregion ///////////////////////////////////// Configure isStart & isEnd ///////////////////////////////////////////////// isStart = hour == startH and minute == startM isEnd = hour == endH and minute == endM var High = 0.0 var Low = 0.0 if isStart Low := low - buffer High := high + buffer plot(isHighV ? High : na, color=color.lime) plot(isLowV ? Low : na, color=color.red) validOpen = math.abs((High - Low)/Low*100) >= openRange //#region ////////////////////// Session /////////////////////////////////// var start = false if isStart start := true if isEnd start := false var longCondition = false var shortCondition = false var isLongTrade = false var isShortTrade = false if strategy.position_size > 0 isLongTrade := true if strategy.position_size < 0 isShortTrade := true if close > High and start longCondition := true if close < Low and start shortCondition := true if isLongTrade longCondition := false if isShortTrade shortCondition := false if isEnd isLongTrade := false isShortTrade := false longCondition := false shortCondition := false //#endregion ////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Message alert inputs alertGroup = "========= Alert Message Settings =========" longMsg = input.string("Long", "Long MSG", group = alertGroup) shortMsg = input.string("Short", "Short SMG", group = alertGroup) longExitMsg = input.string("Long Exit", "Long Exit SMG", group = alertGroup) shortExitMsg = input.string("Short Exit", "Short Exit MSG", group = alertGroup) //#region ////////////////////////////////////////// Execute Trade Section //////////////////////////////////////////////////////// tradeMode = input.string("Percent", "Trade Mode", options=["Point", "Percent"], group="========= Strategy Settings =========") sl = input.float(1, "Stop Loss Point Or Percent", group="========= Strategy Settings =========") target = input.float(2, "Target Point Or Percent", group="========= Strategy Settings =========") entry_price = strategy.opentrades.entry_price(strategy.opentrades - 1) longSL = 0.0 shortSL = 0.0 longTarget = 0.0 shortTarget = 0.0 if tradeMode == "Percent" longSL := entry_price - entry_price * sl/100 shortSL := entry_price + entry_price * sl/100 longTarget := entry_price + entry_price * target/100 shortTarget := entry_price - entry_price * target/100 if tradeMode == "Point" longSL := entry_price - sl shortSL := entry_price + sl longTarget := entry_price + target shortTarget := entry_price - target if strategy.position_size > 0 and close[1] > (entry_price + tradeGap) longSL := entry_price + gapBook if strategy.position_size < 0 and close[1] < (entry_price - tradeGap) shortSL := entry_price - gapBook if longCondition and validOpen strategy.entry("Long", strategy.long, alert_message=longMsg) if shortCondition and validOpen strategy.entry("Short", strategy.short, alert_message=shortMsg) if strategy.position_size > 0 strategy.exit("Long Exit", "Long", stop=longSL, limit= longTarget, comment_loss="Long SL", comment_profit="Long Profit", alert_message=longExitMsg) if strategy.position_size < 0 strategy.exit("Short Exit", "Short", stop=shortSL, limit= shortTarget, comment_loss="Short SL", comment_profit="Short Profit", alert_message=shortExitMsg) if isEnd and isCloseAll strategy.close_all(comment="Closing Bell") //#endregion //#region ////////////////////////////////////////// Alert Section //////////////////////////////////////////////////////// if longCondition and validOpen alert(longMsg, alert.freq_once_per_bar_close) if shortCondition and validOpen alert(shortMsg, alert.freq_once_per_bar_close) //#endregion
SSL + Wave Trend Strategy
https://www.tradingview.com/script/J0urw1QI-SSL-Wave-Trend-Strategy/
kevinmck100
https://www.tradingview.com/u/kevinmck100/
423
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/ // Β© kevinmck100 // @credits // - Wave Trend: Indicator: WaveTrend Oscillator [WT] by @LazyBear // - SSL Channel: SSL channel by @ErwinBeckers // - SSL Hybrid: SSL Hybrid by @Mihkel00 // - Keltner Channels: Keltner Channels Bands by @ceyhun // - Candle Height: Candle Height in Percentage - Columns by @FreeReveller // - NNFX ATR: NNFX ATR by @sueun123 // // Strategy: Based on the YouTube video "This Unique Strategy Made 47% Profit in 2.5 Months [SSL + Wave Trend Strategy Tested 100 Times]" by TradeSmart. // @description // // Strategy incorporates the following features: // // - Risk management: Configurable X% loss per stop loss // Configurable R:R ratio // // - Trade entry: Based on strategy conditions below // // - Trade exit: Based on strategy conditions below // // - Backtesting: Configurable backtesting range by date // // - Chart drawings: Each entry condition indicator can be turned on and off // TP/SL boxes drawn for all trades. Can be turned on and off // Trade exit information labels. Can be turned on and off // NOTE: Trade drawings will only be applicable when using overlay strategies // // - Alerting: Alerts on LONG and SHORT trade entries // // - Debugging: Includes section with useful debugging techniques // // Strategy conditions: // // - Trade entry: LONG: C1: SSL Hybrid baseline is BLUE // C2: SSL Channel crosses up (green on top) // C3: Wave Trend crosses up (represented by pink candle body) // C4: Entry candle height is not greater than configured threshold // C5: Entry candle is inside Keltner Channel (wicks or body depending on configuration) // C6: Take Profit target does not touch EMA (represents resistance) // // SHORT: C1: SSL Hybrid baseline is RED // C2: SSL Channel crosses down (red on top) // C3: Wave Trend crosses down (represented by orange candle body) // C4: Entry candle height is not greater than configured threshold // C5: Entry candle is inside Keltner Channel (wicks or body depending on configuration) // C6: Take Profit target does not touch EMA (represents support) // // - Trade exit: Stop Loss: Size configurable with NNFX ATR multiplier // Take Profit: Calculated from Stop Loss using R:R ratio //@version=5 INITIAL_CAPITAL = 1000 DEFAULT_COMMISSION = 0.02 MAX_DRAWINGS = 500 IS_OVERLAY = true strategy("SSL + Wave Trend Strategy", overlay = IS_OVERLAY, initial_capital = INITIAL_CAPITAL, currency = currency.NONE, max_labels_count = MAX_DRAWINGS, max_boxes_count = MAX_DRAWINGS, max_lines_count = MAX_DRAWINGS, default_qty_type = strategy.cash, commission_type = strategy.commission.percent, commission_value = DEFAULT_COMMISSION) // ============================================================================= // INPUTS // ============================================================================= // ---------------------- // Trade Entry Conditions // ---------------------- useSslHybrid = input.bool (true, "Use SSL Hybrid Condition", group = "Strategy: Entry Conditions", inline = "SC1") useKeltnerCh = input.bool (true, "Use Keltner Channel Condition   ", group = "Strategy: Entry Conditions", inline = "SC2") keltnerChWicks = input.bool (true, "Keltner Channel Include Wicks", group = "Strategy: Entry Conditions", inline = "SC2") useEma = input.bool (true, "Target not touch EMA Condition", group = "Strategy: Entry Conditions", inline = "SC3") useCandleHeight = input.bool (true, "Use Candle Height Condition", group = "Strategy: Entry Conditions", inline = "SC4") candleHeight = input.float (1.0, "Candle Height Threshold     ", group = "Strategy: Entry Conditions", inline = "SC5", minval = 0, step = 0.1, tooltip = "Percentage difference between high and low of a candle. Expressed as a decimal. Lowering this value will filter out trades on volatile candles.") // --------------------- // Trade Exit Conditions // --------------------- slAtrMultiplier = input.float (1.7, "Stop Loss ATR Multiplier     ", group = "Strategy: Exit Conditions", inline = "EC1", minval = 0, step = 0.1, tooltip = "Size of StopLoss is determined by multiplication of ATR value. Take Profit is derived from this also by multiplying the StopLoss value by the Risk:Reward multiplier.") // --------------- // Risk Management // --------------- riskReward = input.float (2.5, "Risk : Reward        1 :", group = "Strategy: Risk Management", inline = "RM1", minval = 0, step = 0.1, tooltip = "Used to determine Take Profit level. Take Profit will be Stop Loss multiplied by this value.") accountRiskPercent = input.float (1, "Portfolio Risk %         ", group = "Strategy: Risk Management", inline = "RM2", minval = 0, step = 0.1, tooltip = "Percentage of portfolio you lose if trade hits SL.\n\nYou then stand to gain\n Portfolio Risk % * Risk : Reward\nif trade hits TP.") // ---------- // Date Range // ---------- startYear = input.int (2022, "Start Date       ", group = "Strategy: Date Range", inline = "DR1", minval = 1900, maxval = 2100) startMonth = input.int (1, "", group = "Strategy: Date Range", inline = "DR1", options = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) startDate = input.int (1, "", group = "Strategy: Date Range", inline = "DR1", options = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]) endYear = input.int (2100, "End Date      ", group = "Strategy: Date Range", inline = "DR2", minval = 1900, maxval = 2100) endMonth = input.int (1, "", group = "Strategy: Date Range", inline = "DR2", options = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) endDate = input.int (1, "", group = "Strategy: Date Range", inline = "DR2", options = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]) // ---------------- // Display Settings // ---------------- showTpSlBoxes = input.bool (true, "Show TP / SL Boxes", group = "Strategy: Drawings", inline = "D1", tooltip = "Show or hide TP and SL position boxes.\n\nNote: TradingView limits the maximum number of boxes that can be displayed to 500 so they may not appear for all price data under test.") showLabels = input.bool (false, "Show Trade Exit Labels", group = "Strategy: Drawings", inline = "D2", tooltip = "Useful labels to identify Profit/Loss and cumulative portfolio capital after each trade closes.\n\nAlso note that TradingView limits the max number of 'boxes' that can be displayed on a chart (max 500). This means when you lookback far enough on the chart you will not see the TP/SL boxes. However you can check this option to identify where trades exited.") // ------------------ // Indicator Settings // ------------------ // Indicator display options showSslHybrid = input.bool (true, "Show SSL Hybrid", group = "Indicators: Drawings", inline = "ID1") showSslChannel = input.bool (true, "Show SSL Channel", group = "Indicators: Drawings", inline = "ID2") showEma = input.bool (true, "Show EMA", group = "Indicators: Drawings", inline = "ID3") showKeltner = input.bool (true, "Show Keltner Channel", group = "Indicators: Drawings", inline = "ID4") showWaveTrend = input.bool (true, "Show Wave Trend Flip Candles", group = "Indicators: Drawings", inline = "ID5") showAtrSl = input.bool (true, "Show ATR Stop Loss Bands", group = "Indicators: Drawings", inline = "ID6") // Wave Trend Settings n1 = input.int (10, "Channel Length         ", group = "Indicators: Wave Trend", inline = "WT1") n2 = input.int (21, "Average Length         ", group = "Indicators: Wave Trend", inline = "WT2") obLevel1 = input.int (60, "Over Bought Level 1       ", group = "Indicators: Wave Trend", inline = "WT3") obLevel2 = input.int (53, "Over Bought Level 2       ", group = "Indicators: Wave Trend", inline = "WT4") osLevel1 = input.int (-60, "Over Sold Level 1         ", group = "Indicators: Wave Trend", inline = "WT5") osLevel2 = input.int (-53, "Over Sold Level 2         ", group = "Indicators: Wave Trend", inline = "WT6") // SSL Channel Settings sslChLen = input.int (10, "Period             ", group = "Indicators: SSL Channel", inline = "SC1") // SSL Hybrid Settings // Show/hide Inputs show_color_bar = input.bool (false, "Show Color Bars", group = "Indicators: SSL Hybrid", inline = "SH2") // Baseline Inputs maType = input.string ("HMA", "Baseline Type                       ", group = "Indicators: SSL Hybrid", inline = "SH3", options=["SMA", "EMA", "DEMA", "TEMA", "LSMA", "WMA", "MF", "VAMA", "TMA", "HMA", "JMA", "Kijun v2", "EDSMA", "McGinley"]) len = input.int (60, "Baseline Length                      ", group = "Indicators: SSL Hybrid", inline = "SH4") src = input.source (close, "Source                          ", group = "Indicators: SSL Hybrid", inline = "SH5") kidiv = input.int (1, "Kijun MOD Divider                     ", group = "Indicators: SSL Hybrid", inline = "SH6", maxval=4) jurik_phase = input.int (3, "* Jurik (JMA) Only - Phase                 ", group = "Indicators: SSL Hybrid", inline = "SH7") jurik_power = input.int (1, "* Jurik (JMA) Only - Power                 ", group = "Indicators: SSL Hybrid", inline = "SH8") volatility_lookback = input.int (10, "* Volatility Adjusted (VAMA) Only - Volatility lookback length", group = "Indicators: SSL Hybrid", inline = "SH9") //Modular Filter Inputs beta = input.float (0.8, "Modular Filter, General Filter Only - Beta               ", group = "Indicators: SSL Hybrid", inline = "SH10", minval=0, maxval=1, step=0.1) feedback = input.bool (false, "Modular Filter Only - Feedback", group = "Indicators: SSL Hybrid", inline = "SH11") z = input.float (0.5, "Modular Filter Only - Feedback Weighting               ", group = "Indicators: SSL Hybrid", inline = "SH12", step=0.1, minval=0, maxval=1) //EDSMA Inputs ssfLength = input.int (20, "EDSMA - Super Smoother Filter Length               ", group = "Indicators: SSL Hybrid", inline = "SH13", minval=1) ssfPoles = input.int (2, "EDSMA - Super Smoother Filter Poles               ", group = "Indicators: SSL Hybrid", inline = "SH14", options=[2, 3]) ///Keltner Baseline Channel Inputs useTrueRange = input.bool (true, "Use True Range?", group = "Indicators: SSL Hybrid", inline = "SH15") multy = input.float (0.2, "Base Channel Multiplier                   ", group = "Indicators: SSL Hybrid", inline = "SH16", step=0.05) // EMA Settings emaLength = input.int (200, "EMA Length          ", group = "Indicators: EMA", inline = "E1", minval = 1) // Keltner Channel Settings kcLength = input.int (20, "Length              ", group = "Indicators: Keltner Channel", inline = "KC1", minval=1) kcMult = input.float (1.5, "Multiplier             ", group = "Indicators: Keltner Channel", inline = "KC2") kcSrc = input.source (close, "Source              ", group = "Indicators: Keltner Channel", inline = "KC3") alen = input.int (10, "ATR Length            ", group = "Indicators: Keltner Channel", inline = "KC4", minval=1) // Candle Height in Percentage Settings chPeriod = input.int (20, "Period             ", group = "Indicators: Candle Height", inline = "CH1") // NNFX ATR Settings nnfxAtrLength = input.int (14, "Length              ", group = "Indicators: NNFX ATR (Stop Loss Settings)", inline = "ATR1", minval = 1) nnfxSmoothing = input.string ("RMA", "Smoothing            ", group = "Indicators: NNFX ATR (Stop Loss Settings)", inline = "ATR3", options = ["RMA", "SMA", "EMA", "WMA"]) // ============================================================================= // INDICATORS // ============================================================================= // ---------- // Wave Trend // ---------- ap = hlc3 esa = ta.ema(ap, n1) d = ta.ema(math.abs(ap - esa), n1) ci = (ap - esa) / (0.015 * d) tci = ta.ema(ci, n2) wt1 = tci wt2 = ta.sma(wt1, 4) // Show Wave Trend crosses on chart as colour changes (pink bullish, orange bearish) wtBreakUp = ta.crossover (wt1, wt2) wtBreakDown = ta.crossunder (wt1, wt2) barColour = showWaveTrend ? wtBreakUp ? color.fuchsia : wtBreakDown ? color.orange : na : na barcolor(color = barColour) // ----------- // SSL Channel // ----------- smaHigh = ta.sma(high, sslChLen) smaLow = ta.sma(low, sslChLen) var int sslChHlv = na sslChHlv := close > smaHigh ? 1 : close < smaLow ? -1 : sslChHlv[1] sslChDown = sslChHlv < 0 ? smaHigh : smaLow sslChUp = sslChHlv < 0 ? smaLow : smaHigh plot(showSslChannel ? sslChDown : na, "SSL Channel Down", linewidth=1, color=color.new(color.red, 30)) plot(showSslChannel ? sslChUp : na, "SSL Channel Up", linewidth=1, color=color.new(color.lime, 30)) // ---------- // SSL Hybrid // ---------- //EDSMA get2PoleSSF(src, length) => PI = 2 * math.asin(1) arg = math.sqrt(2) * PI / length a1 = math.exp(-arg) b1 = 2 * a1 * math.cos(arg) c2 = b1 c3 = -math.pow(a1, 2) c1 = 1 - c2 - c3 ssf = 0.0 ssf:= c1 * src + c2 * nz(ssf[1]) + c3 * nz(ssf[2]) ssf get3PoleSSF(src, length) => PI = 2 * math.asin(1) arg = PI / length a1 = math.exp(-arg) b1 = 2 * a1 * math.cos(1.738 * arg) c1 = math.pow(a1, 2) coef2 = b1 + c1 coef3 = -(c1 + b1 * c1) coef4 = math.pow(c1, 2) coef1 = 1 - coef2 - coef3 - coef4 ssf = 0.0 ssf := coef1 * src + coef2 * nz(ssf[1]) + coef3 * nz(ssf[2]) + coef4 * nz(ssf[3]) ssf ma(type, src, len) => float result = 0 if type == "TMA" result := ta.sma(ta.sma(src, math.ceil(len / 2)), math.floor(len / 2) + 1) result if type == "MF" ts = 0. b = 0. c = 0. os = 0. //---- alpha = 2 / (len + 1) a = feedback ? z * src + (1 - z) * nz(ts[1], src) : src //---- b := a > alpha * a + (1 - alpha) * nz(b[1], a) ? a : alpha * a + (1 - alpha) * nz(b[1], a) c := a < alpha * a + (1 - alpha) * nz(c[1], a) ? a : alpha * a + (1 - alpha) * nz(c[1], a) os := a == b ? 1 : a == c ? 0 : os[1] //---- upper = beta * b + (1 - beta) * c lower = beta * c + (1 - beta) * b ts := os * upper + (1 - os) * lower result := ts result if type == "LSMA" result := ta.linreg(src, len, 0) result if type == "SMA" // Simple result := ta.sma(src, len) result if type == "EMA" // Exponential result := ta.ema(src, len) result if type == "DEMA" // Double Exponential e = ta.ema(src, len) result := 2 * e - ta.ema(e, len) result if type == "TEMA" // Triple Exponential e = ta.ema(src, len) result := 3 * (e - ta.ema(e, len)) + ta.ema(ta.ema(e, len), len) result if type == "WMA" // Weighted result := ta.wma(src, len) result if type == "VAMA" // Volatility Adjusted /// Copyright Β© 2019 to present, Joris Duyck (JD) mid = ta.ema(src, len) dev = src - mid vol_up = ta.highest(dev, volatility_lookback) vol_down= ta.lowest(dev, volatility_lookback) result := mid + math.avg(vol_up, vol_down) result if type == "HMA" // Hull result := ta.wma(2 * ta.wma(src, len / 2) - ta.wma(src, len), math.round(math.sqrt(len))) result if type == "JMA" // Jurik /// Copyright Β© 2018 Alex Orekhov (everget) /// Copyright Β© 2017 Jurik Research and Consulting. phaseRatio = jurik_phase < -100 ? 0.5 : jurik_phase > 100 ? 2.5 : jurik_phase / 100 + 1.5 beta = 0.45 * (len - 1) / (0.45 * (len - 1) + 2) alpha = math.pow(beta, jurik_power) jma = 0.0 e0 = 0.0 e0 := (1 - alpha) * src + alpha * nz(e0[1]) e1 = 0.0 e1 := (src - e0) * (1 - beta) + beta * nz(e1[1]) e2 = 0.0 e2 := (e0 + phaseRatio * e1 - nz(jma[1])) * math.pow(1 - alpha, 2) + math.pow(alpha, 2) * nz(e2[1]) jma := e2 + nz(jma[1]) result := jma result if type == "Kijun v2" kijun = math.avg(ta.lowest(len), ta.highest(len)) //, (open + close)/2) conversionLine = math.avg(ta.lowest(len / kidiv), ta.highest(len / kidiv)) delta = (kijun + conversionLine) / 2 result := delta result if type == "McGinley" mg = 0.0 mg := na(mg[1]) ? ta.ema(src, len) : mg[1] + (src - mg[1]) / (len * math.pow(src / mg[1], 4)) result := mg result if type == "EDSMA" zeros = src - nz(src[2]) avgZeros = (zeros + zeros[1]) / 2 // Ehlers Super Smoother Filter ssf = ssfPoles == 2 ? get2PoleSSF(avgZeros, ssfLength) : get3PoleSSF(avgZeros, ssfLength) // Rescale filter in terms of Standard Deviations stdev = ta.stdev(ssf, len) scaledFilter= stdev != 0 ? ssf / stdev : 0 alpha = 5 * math.abs(scaledFilter) / len edsma = 0.0 edsma := alpha * src + (1 - alpha) * nz(edsma[1]) result := edsma result result ///Keltner Baseline Channel BBMC = ma(maType, close, len) Keltma = ma(maType, src, len) range_1 = useTrueRange ? ta.tr : high - low rangema = ta.ema(range_1, len) upperk = Keltma + rangema * multy lowerk = Keltma - rangema * multy //COLORS color_bar = close > upperk ? #00c3ff : close < lowerk ? #ff0062 : color.gray //PLOTS p1 = plot(showSslHybrid ? BBMC : na, color=color.new(color_bar, 0), linewidth=4, title="MA Baseline") barcolor(show_color_bar ? color_bar : na) // --- // EMA // --- ema = ta.ema(close, emaLength) plot(showEma ? ema : na, "EMA Trend Line", color.white) // ---------------- // Keltner Channels // ---------------- kcMa = ta.ema(kcSrc, kcLength) KTop2 = kcMa + kcMult * ta.atr(alen) KBot2 = kcMa - kcMult * ta.atr(alen) upperPlot = plot(showKeltner ? KTop2 : na, color=color.new(color.blue, 0), title="Upper", style = plot.style_stepline) lowerPlot = plot(showKeltner ? KBot2 : na, color=color.new(color.blue, 0), title="Lower", style = plot.style_stepline) // --------------------------- // Candle Height in Percentage // --------------------------- percentHL = (high - low) / low * 100 percentRed = open > close ? (open - close) / close * 100 : 0 percentGreen= open < close ? (close - open) / open * 100 : 0 // -------- // NNFX ATR // -------- function(source, length) => if nnfxSmoothing == "RMA" ta.rma(source, nnfxAtrLength) else if nnfxSmoothing == "SMA" ta.sma(source, nnfxAtrLength) else if nnfxSmoothing == "EMA" ta.ema(source, nnfxAtrLength) else ta.wma(source, nnfxAtrLength) formula(number, decimals) => factor = math.pow(10, decimals) int(number * factor) / factor nnfxAtr = formula(function(ta.tr(true), nnfxAtrLength), 5) * slAtrMultiplier //Sell longSlAtr = nnfxAtrLength ? close - nnfxAtr : close + nnfxAtr shortSlAtr = nnfxAtrLength ? close + nnfxAtr : close - nnfxAtr plot(showAtrSl ? longSlAtr : na, "Long SL", color = color.new(color.red, 35), linewidth = 1, trackprice = true, editable = true, style = plot.style_stepline) plot(showAtrSl ? shortSlAtr : na, "Short SL", color = color.new(color.red, 35), linewidth = 1, trackprice = true, editable = true, style = plot.style_stepline) // ============================================================================= // FUNCTIONS // ============================================================================= percentAsPoints(pcnt) => math.round(pcnt / 100 * close / syminfo.mintick) calcStopLossPrice(pointsOffset, isLong) => priceOffset = pointsOffset * syminfo.mintick if isLong close - priceOffset else close + priceOffset calcProfitTrgtPrice(pointsOffset, isLong) => calcStopLossPrice(-pointsOffset, isLong) printLabel(barIndex, msg) => label.new(barIndex, close, msg) printTpSlHitBox(left, right, slHit, tpHit, entryPrice, slPrice, tpPrice) => if showTpSlBoxes box.new (left = left, top = entryPrice, right = right, bottom = slPrice, bgcolor = slHit ? color.new(color.red, 60) : color.new(color.gray, 90), border_width = 0) box.new (left = left, top = entryPrice, right = right, bottom = tpPrice, bgcolor = tpHit ? color.new(color.green, 60) : color.new(color.gray, 90), border_width = 0) line.new(x1 = left, y1 = entryPrice, x2 = right, y2 = entryPrice, color = color.new(color.yellow, 20)) line.new(x1 = left, y1 = slPrice, x2 = right, y2 = slPrice, color = color.new(color.red, 20)) line.new(x1 = left, y1 = tpPrice, x2 = right, y2 = tpPrice, color = color.new(color.green, 20)) printTpSlNotHitBox(left, right, entryPrice, slPrice, tpPrice) => if showTpSlBoxes box.new (left = left, top = entryPrice, right = right, bottom = slPrice, bgcolor = color.new(color.gray, 90), border_width = 0) box.new (left = left, top = entryPrice, right = right, bottom = tpPrice, bgcolor = color.new(color.gray, 90), border_width = 0) line.new(x1 = left, y1 = entryPrice, x2 = right, y2 = entryPrice, color = color.new(color.yellow, 20)) line.new(x1 = left, y1 = slPrice, x2 = right, y2 = slPrice, color = color.new(color.red, 20)) line.new(x1 = left, y1 = tpPrice, x2 = right, y2 = tpPrice, color = color.new(color.green, 20)) printTradeExitLabel(x, y, posSize, entryPrice, pnl) => if showLabels labelStr = "Position Size: " + str.tostring(math.abs(posSize), "#.##") + "\nPNL: " + str.tostring(pnl, "#.##") + "\nCapital: " + str.tostring(strategy.equity, "#.##") + "\nEntry Price: " + str.tostring(entryPrice, "#.##") label.new(x = x, y = y, text = labelStr, color = pnl > 0 ? color.new(color.green, 60) : color.new(color.red, 60), textcolor = color.white, style = label.style_label_down) // ============================================================================= // STRATEGY LOGIC // ============================================================================= // See strategy description at top for details on trade entry/exit logis // ---------- // CONDITIONS // ---------- // Trade entry and exit variables var tradeEntryBar = bar_index var profitPoints = 0. var lossPoints = 0. var slPrice = 0. var tpPrice = 0. var inLong = false var inShort = false // Exit calculations slAmount = nnfxAtr slPercent = math.abs((1 - (close - slAmount) / close) * 100) tpPercent = slPercent * riskReward tpPoints = percentAsPoints(tpPercent) tpTarget = calcProfitTrgtPrice(tpPoints, wtBreakUp) inDateRange = time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0) and time < timestamp(syminfo.timezone, endYear, endMonth, endDate, 0, 0) // Condition 1: SSL Hybrid blue for long or red for short bullSslHybrid = useSslHybrid ? close > upperk : true bearSslHybrid = useSslHybrid ? close < lowerk : true // Condition 2: SSL Channel crosses up for long or down for short bullSslChannel = ta.crossover(sslChUp, sslChDown) bearSslChannel = ta.crossover(sslChDown, sslChUp) // Condition 3: Wave Trend crosses up for long or down for short bullWaveTrend = wtBreakUp bearWaveTrend = wtBreakDown // Condition 4: Entry candle heignt <= 0.6 on Candle Height in Percentage candleHeightValid = useCandleHeight ? percentGreen <= candleHeight and percentRed <= candleHeight : true // Condition 5: Entry candle is inside Keltner Channel withinCh = keltnerChWicks ? high < KTop2 and low > KBot2 : open < KTop2 and close < KTop2 and open > KBot2 and close > KBot2 insideKeltnerCh = useKeltnerCh ? withinCh : true // Condition 6: TP target does not touch 200 EMA bullTpValid = useEma ? not (close < ema and tpTarget > ema) : true bearTpValid = useEma ? not (close > ema and tpTarget < ema) : true // Combine all entry conditions goLong = inDateRange and bullSslHybrid and bullSslChannel and bullWaveTrend and candleHeightValid and insideKeltnerCh and bullTpValid goShort = inDateRange and bearSslHybrid and bearSslChannel and bearWaveTrend and candleHeightValid and insideKeltnerCh and bearTpValid // Entry decisions openLong = (goLong and not inLong) openShort = (goShort and not inShort) flippingSides = (goLong and inShort) or (goShort and inLong) enteringTrade = openLong or openShort inTrade = inLong or inShort // Risk calculations riskAmt = strategy.equity * accountRiskPercent / 100 entryQty = math.abs(riskAmt / slPercent * 100) / close if openLong if strategy.position_size < 0 printTpSlNotHitBox(tradeEntryBar + 1, bar_index + 1, strategy.position_avg_price, slPrice, tpPrice) printTradeExitLabel(bar_index + 1, math.max(tpPrice, slPrice), strategy.position_size, strategy.position_avg_price, strategy.openprofit) strategy.entry("Long", strategy.long, qty = entryQty, alert_message = "Long Entry") enteringTrade := true inLong := true inShort := false alert(message="BUY Trade Entry Alert", freq=alert.freq_once_per_bar_close) if openShort if strategy.position_size > 0 printTpSlNotHitBox(tradeEntryBar + 1, bar_index + 1, strategy.position_avg_price, slPrice, tpPrice) printTradeExitLabel(bar_index + 1, math.max(tpPrice, slPrice), strategy.position_size, strategy.position_avg_price, strategy.openprofit) strategy.entry("Short", strategy.short, qty = entryQty, alert_message = "Short Entry") enteringTrade := true inShort := true inLong := false alert(message="SELL Trade Entry Alert", freq=alert.freq_once_per_bar_close) if enteringTrade profitPoints := percentAsPoints(tpPercent) lossPoints := percentAsPoints(slPercent) slPrice := calcStopLossPrice(lossPoints, openLong) tpPrice := calcProfitTrgtPrice(profitPoints, openLong) tradeEntryBar := bar_index strategy.exit("TP/SL", profit = profitPoints, loss = lossPoints, comment_profit = "TP Hit", comment_loss = "SL Hit", alert_profit = "TP Hit Alert", alert_loss = "SL Hit Alert") // ============================================================================= // DRAWINGS // ============================================================================= // ----------- // TP/SL Boxes // ----------- slHit = (inShort and high >= slPrice) or (inLong and low <= slPrice) tpHit = (inLong and high >= tpPrice) or (inShort and low <= tpPrice) exitTriggered = slHit or tpHit entryPrice = strategy.closedtrades.entry_price (strategy.closedtrades - 1) pnl = strategy.closedtrades.profit (strategy.closedtrades - 1) posSize = strategy.closedtrades.size (strategy.closedtrades - 1) // Print boxes for trades closed at profit or loss if (inTrade and exitTriggered) inShort := false inLong := false printTpSlHitBox(tradeEntryBar + 1, bar_index, slHit, tpHit, entryPrice, slPrice, tpPrice) printTradeExitLabel(bar_index, math.max(tpPrice, slPrice), posSize, entryPrice, pnl) // Print TP/SL box for current open trade if barstate.islastconfirmedhistory and strategy.position_size != 0 printTpSlNotHitBox(tradeEntryBar + 1, bar_index + 1, strategy.position_avg_price, slPrice, tpPrice) // ============================================================================= // DEBUGGING // ============================================================================= // Data window plots plotchar(goLong, "Enter Long", "") plotchar(goShort, "Enter Short", "")
Forex Midpoint Stratejisi For Nasdaq
https://www.tradingview.com/script/ZnRFkWvB/
trademasterf
https://www.tradingview.com/u/trademasterf/
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/ // © MGULHANN //@version=5 strategy('Forex Midpoint Stratejisi For Nasdaq ', overlay=true) BPeriod = input(131, 'Başlangıç Period') kaydirma = input(14, 'Kaydırma Seviyesi') yuzdeseviyesi = input.float(0.0006, 'Yüzde Seviyesi', step=0.0001) len = input.int(44, minval=1, title="Length") src = input(close, title="Source") out = ta.sma(src, len) ma(source, length, type) => switch type "SMA" => ta.sma(source, length) "EMA" => ta.ema(source, length) "SMMA (RMA)" => ta.rma(source, length) "WMA" => ta.wma(source, length) "VWMA" => ta.vwma(source, length) typeMA = input.string(title = "Method", defval = "EMA", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="Smoothing") smoothingLength = input.int(title = "Length", defval = 53, minval = 1, maxval = 100, group="Smoothing") smoothingLine = ma(out, smoothingLength, typeMA) //plot(smoothingLine, title="Smoothing Line", color=color.red, linewidth = 2) //zararDurdurmaYuzde = input.float(0.2, title='Zarar Durdurma %', step=0.01) / 100 //karAlmaYuzde = input.float(0.5, title='Kar Alma %', step=0.01) / 100 //MIDPOINT HESAPLA midpoint1 = ta.highest(high, BPeriod) + ta.lowest(low, BPeriod) midpoint2 = midpoint1 / 2 midyuzdeseviyesi = midpoint2 * yuzdeseviyesi midtopdeger = midyuzdeseviyesi + midpoint2 //GİRİŞ KOŞULLARI buycross = ta.crossover(smoothingLine, midtopdeger[kaydirma]) //? aort > ta.sma(close,50) : na sellcross = ta.crossover(midtopdeger[kaydirma], smoothingLine) // ? aort < ta.sma(close,50) : na //LONG GİRİŞ if (buycross) strategy.entry("BUY", strategy.long) //longKarAl = strategy.position_avg_price * (1 + karAlmaYuzde) //longZararDurdur = strategy.position_avg_price * (1 - zararDurdurmaYuzde) //strategy.exit("Long Exit","Long", stop=longZararDurdur) //SHORT GİRİŞ if (sellcross) strategy.entry("SELL", strategy.short) //shortKarAl = strategy.position_avg_price * (1 - karAlmaYuzde) //shortZararDurdur = strategy.position_avg_price * (1 + zararDurdurmaYuzde) //strategy.exit("Short Exit","Short", stop=shortZararDurdur) //plot(midtopdeger, offset=kaydirma, linewidth=2, color=color.blue)
Simple and Profitable Scalping Strategy (ForexSignals TV)
https://www.tradingview.com/script/x4za4NFZ-Simple-and-Profitable-Scalping-Strategy-ForexSignals-TV/
kevinmck100
https://www.tradingview.com/u/kevinmck100/
530
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/ // Β© kevinmck100 // @description // // Strategy called SIMPLE and PROFITABLE Forex Scalping Strategy taken from YouTube channel ForexSignals TV. // See video for a detailed explaination of the whole strategy. // // It works on the basis of waiting for pullbacks into the EMAs while trading in the direction of the higher timeframe trend // // Strategy incorporates the following features: // // - Risk management: Configurable X% loss per stop loss // Configurable R:R ratio // // - Trade entry: Calculated position size based on risk tolerance // Entry price is a stop order set just above the recent swing high/low (long/short) // // - Trade exit: Stop Loss is set just below trigger candle's low/high (long/short) // Take Profit calculated from Stop Loss using R:R ratio // // - Backtesting: Configurable backtesting range by date // // - Trade drawings: TP/SL boxes drawn for all trades. Can be turned on and off // Trade exit information labels. Can be turned on and off // NOTE: Trade drawings will only be applicable when using overlay strategies // // - Debugging: Includes section with useful debugging techniques // // Strategy conditions: // // - Trade entry: LONG: C1: On higher timeframe trend EMAs, Fast EMA must be above Slow EMA // C2: On higher timeframe trend EMAs, price must be above Fast EMA // C3: On current timeframe entry EMAs, Fast EMA must be above Medium EMA and Medium EMA must be above Slow EMA // C4: On current timeframe entry EMAs, all 3 EMA lines must have fanned out in upward direction for previous X candles // C5: On current timeframe entry EMAs, previous candle must have closed above and not touched any EMA lines // C6: On current timeframe entry EMAs, current candle must have pulled back to touch the EMA line(s) // C7: Price must break through the high of the last X candles to trigger entry // // SHORT: C1: On higher timeframe trend EMAs, Fast EMA must be below Slow EMA // C2: On higher timeframe trend EMAs, price must be below Fast EMA // C3: On current timeframe entry EMAs, Fast EMA must be below Medium EMA and Medium EMA must be below Slow EMA // C4: On current timeframe entry EMAs, all 3 EMA lines must have fanned out in downward direction for previous X candles // C5: On current timeframe entry EMAs, previous candle must have closed above and not touched any EMA lines // C6: On current timeframe entry EMAs, current candle must have pulled back to touch the EMA line(s) // C7: Price must break through the low of the last X candles to trigger entry // // - Trade exit: Trade Invalidation: Price closes below/above (long/short) the current timeframe Slow EMA // Stop Loss: Placed just below trigger candle low/high (long/short) // Take Profit: R:R multiplier * Stop Loss is hit // NOTE: The original strategy uses 2 TP levels. I may add this in future but would like to see some better results from a single TP before I go to the effort to add this //@version=5 INITIAL_CAPITAL = 1000 DEFAULT_COMMISSION = 0.02 MAX_DRAWINGS = 500 IS_OVERLAY = true strategy("Simple and Profitable Scalping Strategy (ForexSignals TV)", "Scalping Strategy", overlay = IS_OVERLAY, initial_capital = INITIAL_CAPITAL, currency = currency.NONE, max_labels_count = MAX_DRAWINGS, max_boxes_count = MAX_DRAWINGS, max_lines_count = MAX_DRAWINGS, default_qty_type = strategy.cash, commission_type = strategy.commission.percent, commission_value = DEFAULT_COMMISSION) // ============================================================================= // INPUTS // ============================================================================= trendFilterTf = input.timeframe ("60", "Trend Timeframe        ", group = "Strategy: Higher Timeframe Trend Filter", inline = "TF1", tooltip = "Higher timeframe to use for finding main trand direction") trendFastEmaLen = input.int (8, "Fast EMA Length        ", group = "Strategy: Higher Timeframe Trend Filter", inline = "TF2", minval = 1, tooltip = "Length of Fast EMA of higher timeframe") trendSlowEmaLen = input.int (21, "Slow EMA Length          ", group = "Strategy: Higher Timeframe Trend Filter", inline = "TF3", minval = 1, tooltip = "Length of Slow EMA of higher timeframe") // ---------------------- // Trade Entry Conditions // ---------------------- entryFastEmaLen = input.int (8, "Fast EMA Length          ", group = "Strategy: Trade Entry Conditions", inline = "TE1", minval = 1, tooltip = "Fast EMA used to find entry candles when price pulls back into this line") entryMedEmaLen = input.int (13, "Medium EMA Length      ", group = "Strategy: Trade Entry Conditions", inline = "TE2", minval = 1, tooltip = "Medium EMA used to filter out entries when lines are not fanned out or not trending in the desired direction") entrySlowEmaLen = input.int (21, "Slow EMA Length         ", group = "Strategy: Trade Entry Conditions", inline = "TE3", minval = 1, tooltip = "Slow EMA used to filter out entries when lines are not fanned out or not trending in the desired direction.\n\nAlso used to cancel open orders which close below this EMA before entry has been triggered") fanoutAtrMult = input.float (0.5, "EMA Fanout ATR Multiplier    ", group = "Strategy: Trade Entry Conditions", inline = "TE4", step = 0.1, tooltip = "ATR multiplier to determine how but the fanout gap must be between the Fast EMA and Slow EMA over the specified number of candles") fanoutLookback = input.int (3, "EMA Fanout Lookback      ", group = "Strategy: Trade Entry Conditions", inline = "TE5", minval = 1, tooltip = "Number of candles over which the entry EMA lines must be fanned out by the specified amount") priceBufferAtrMult = input.float (0.5, "Price Buffer ATR Multiplier    ", group = "Strategy: Trade Entry Conditions", inline = "TE6", step = 0.1, tooltip = "ATR multiplier to determine how big of a butter should be set above/below trade entry and stop loss") localHighLookback = input.int (5, "Entry Price High/Low Lookback ", group = "Strategy: Trade Entry Conditions", inline = "TE7", minval = 1, tooltip = "Number of candles to lookback on to find the local high/low which is used to establish the stop order entry price") // --------------- // Risk Management // --------------- riskReward = input.float(2, "Risk : Reward        1 :", group = "Strategy: Risk Management", inline = "RM1", minval = 0, step = 0.1, tooltip = "Previous high or low (long/short dependant) is used to determine TP level. 'Risk : Reward' ratio is then used to calculate SL based of previous high/low level.\n\nIn short, the higher the R:R ratio, the smaller the SL since TP target is fixed by previous high/low price data.") accountRiskPercent = input.float(1, "Portfolio Risk %         ", group = "Strategy: Risk Management", inline = "RM2", minval = 0, step = 0.1, tooltip = "Percentage of portfolio you lose if trade hits SL.\n\nYou then stand to gain\n Portfolio Risk % * Risk : Reward\nif trade hits TP.") // ---------- // Date Range // ---------- startYear = input.int (2022, "Start Date       ", group = 'Strategy: Date Range', inline = 'DR1', minval = 1900, maxval = 2100) startMonth = input.int (1, "", group = 'Strategy: Date Range', inline = 'DR1', options = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) startDate = input.int (1, "", group = 'Strategy: Date Range', inline = 'DR1', options = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]) endYear = input.int (2100, "End Date      ", group = 'Strategy: Date Range', inline = 'DR2', minval = 1900, maxval = 2100) endMonth = input.int (1, "", group = 'Strategy: Date Range', inline = 'DR2', options = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) endDate = input.int (1, "", group = 'Strategy: Date Range', inline = 'DR2', options = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]) // ---------------- // Drawing Settings // ---------------- showTpSlBoxes = input.bool(true, "Show TP / SL Boxes", group = "Strategy: Drawings", inline = "D1", tooltip = "Show or hide TP and SL position boxes.\n\nNote: TradingView limits the maximum number of boxes that can be displayed to 500 so they may not appear for all price data under test.") showLabels = input.bool(false, "Show Trade Exit Labels", group = "Strategy: Drawings", inline = "D2", tooltip = "Useful labels to identify Profit/Loss and cumulative portfolio capital after each trade closes.\n\nAlso note that TradingView limits the max number of 'boxes' that can be displayed on a chart (max 500). This means when you lookback far enough on the chart you will not see the TP/SL boxes. However you can check this option to identify where trades exited.") // ============================================================================= // INDICATORS // ============================================================================= // -------------------------- // Trend Higher Timeframe EMA // -------------------------- var float currTrendFastEma = na var float currTrendSlowEma = na var color emaFillColor = na trendFastEma = ta.ema(close, trendFastEmaLen) trendSlowEma = ta.ema(close, trendSlowEmaLen) fastSec = request.security(syminfo.tickerid, trendFilterTf, trendFastEma, barmerge.gaps_off, barmerge.lookahead_off) slowSec = request.security(syminfo.tickerid, trendFilterTf, trendSlowEma, barmerge.gaps_off, barmerge.lookahead_off) currTrendFastEma := na(fastSec) ? currTrendFastEma[1] : fastSec currTrendSlowEma := na(slowSec) ? currTrendSlowEma[1] : slowSec fastEmaPlot = plot(fastSec, color=color.green) slowEmaPlot = plot(slowSec, color=color.red) emaFillColor := fastSec > slowSec ? color.new(color.green, 80) : fastSec < slowSec ? color.new(color.red, 80) : emaFillColor[1] fill(fastEmaPlot, slowEmaPlot, color = emaFillColor, fillgaps = true) // --------------- // Trade Entry EMA // --------------- entryFastEma = ta.ema(close, entryFastEmaLen) entryMedEma = ta.ema(close, entryMedEmaLen) entrySlowEma = ta.ema(close, entrySlowEmaLen) plot(entryFastEma, color = color.orange) plot(entryMedEma, color = color.yellow) plot(entrySlowEma, color = color.purple) // ============================================================================= // STRATEGY LOGIC // ============================================================================= // --------- // FUNCTIONS // --------- printLabel(barIndex, msg) => label.new(barIndex, close, msg) percentAsPoints(pcnt) => math.round(pcnt / 100 * close / syminfo.mintick) calcStopLossPrice(pointsOffset, entryPrice, isLong) => priceOffset = pointsOffset * syminfo.mintick if isLong entryPrice - priceOffset else entryPrice + priceOffset calcProfitTrgtPrice(pointsOffset, entryPrice, isLong) => calcStopLossPrice(-pointsOffset, entryPrice, isLong) printTpSlHitBox(left, right, slHit, tpHit, entryPrice, slPrice, tpPrice) => if showTpSlBoxes box.new (left = left, top = entryPrice, right = right, bottom = slPrice, bgcolor = slHit ? color.new(color.red, 60) : color.new(color.gray, 90), border_width = 0) box.new (left = left, top = entryPrice, right = right, bottom = tpPrice, bgcolor = tpHit ? color.new(color.green, 60) : color.new(color.gray, 90), border_width = 0) line.new(x1 = left, y1 = entryPrice, x2 = right, y2 = entryPrice, color = color.new(color.yellow, 20)) line.new(x1 = left, y1 = slPrice, x2 = right, y2 = slPrice, color = color.new(color.red, 20)) line.new(x1 = left, y1 = tpPrice, x2 = right, y2 = tpPrice, color = color.new(color.green, 20)) printTpSlNotHitBox(left, right, entryPrice, slPrice, tpPrice) => if showTpSlBoxes box.new (left = left, top = entryPrice, right = right, bottom = slPrice, bgcolor = color.new(color.orange, 90), border_width = 0) box.new (left = left, top = entryPrice, right = right, bottom = tpPrice, bgcolor = color.new(color.orange, 90), border_width = 0) line.new(x1 = left, y1 = entryPrice, x2 = right, y2 = entryPrice, color = color.new(color.yellow, 20)) line.new(x1 = left, y1 = slPrice, x2 = right, y2 = slPrice, color = color.new(color.red, 20)) line.new(x1 = left, y1 = tpPrice, x2 = right, y2 = tpPrice, color = color.new(color.green, 20)) printTradeExitLabel(x, y, posSize, entryPrice, pnl) => if showLabels labelStr = pnl != 0 ? "Position Size: " + str.tostring(math.abs(posSize), "#.##") + "\nPNL: " + str.tostring(pnl, "#.##") + "\nCapital: " + str.tostring(strategy.equity, "#.##") + "\nEntry Price: " + str.tostring(entryPrice, "#.##") : "Trade Cancelled" label.new(x = x, y = y, text = labelStr, color = pnl > 0 ? color.new(color.green, 60) : pnl < 0 ? color.new(color.red, 60) : color.new(color.orange, 60), textcolor = color.white, style = label.style_label_down) printVerticalLine(col) => line.new(bar_index, close, bar_index, close * 1.01, extend = extend.both, color = col) // ---------- // CONDITIONS // ---------- inDateRange = time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0) and time < timestamp(syminfo.timezone, endYear, endMonth, endDate, 0, 0) // Condition 1: Higher timeframe trend EMAs must be in correct order bullTrendDir = currTrendFastEma > currTrendSlowEma bearTrendDir = currTrendFastEma < currTrendSlowEma // Condition 2: Price must be outside the EMA trend band bullTrendPrice = close > currTrendFastEma bearTrendPrice = close < currTrendFastEma // Condition 3: EMA lines must be in correct order bullEmaOrder = entryFastEma > entryMedEma and entryMedEma > entrySlowEma bearEmaOrder = entryFastEma < entryMedEma and entryMedEma < entrySlowEma // Condition 4: EMA lines must fanned out for previous X candles fanOutGap = ta.atr(14) * fanoutAtrMult var bullFanOutGap = false var bearFanOutGap = false bullFanOutGap := false bearFanOutGap := false for lookback = 0 to fanoutLookback - 1 bullFanOutGap := (entryFastEma[lookback] - fanOutGap) > entrySlowEma[lookback] if bullFanOutGap == false break for lookback = 0 to fanoutLookback - 1 bearFanOutGap := (entryFastEma[lookback] + fanOutGap) < entrySlowEma[lookback] if bearFanOutGap == false break // This will ensure a given fannout gap exists between EACH EMA line, rather than just checking between Fast and Slow // Leaving it here in case I decide to go back to it, or make it configurable between the two // for lookback = 0 to 3 - 1 // bullFanOutGap := (entryFastEma[lookback] - fanOutGap) > entryMedEma[lookback] and (entryMedEma[lookback] - fanOutGap) > entrySlowEma[lookback] // if bullFanOutGap == false // break // for lookback = 0 to 3 - 1 // bearFanOutGap := (entryFastEma[lookback] + fanOutGap) < entryMedEma[lookback] and (entryMedEma[lookback] + fanOutGap) < entrySlowEma[lookback] // if bearFanOutGap == false // break // Condition 5: Previous candle must not have touched any entry EMA lines bullBreakout = low[1] > entryFastEma[1] bearBreakout = high[1] < entryFastEma[1] // Condition 6: Current candle must have touched the Fast EMA bullPullback = low < entryFastEma bearPullback = high > entryFastEma // Combine all entry conditions goLong = inDateRange and bullTrendDir and bullTrendPrice and bullEmaOrder and bullFanOutGap and bullBreakout and bullPullback goShort = inDateRange and bearTrendDir and bearTrendPrice and bearEmaOrder and bearFanOutGap and bearBreakout and bearPullback // Trade entry and exit variables var tradeEntryBar = bar_index var profitPoints = 0. var lossPoints = 0. var slPrice = 0. var slAmount = 0. var slPercent = 0. var tpPrice = 0. var tpPercent = 0. var inLong = false var inShort = false var float entryPrice= na var tradeCancelled = false var tradeActive = false // Entry decisions openLong = (goLong and not inLong) openShort = (goShort and not inShort) flippingSides = (goLong and inShort) or (goShort and inLong) enteringTrade = openLong or openShort inTrade = inLong or inShort // Exit calculations // Condition 7: Price which must be broken to enter trade priceBuffer = ta.atr(14) * priceBufferAtrMult localHigh = ta.highest(high, localHighLookback) localLow = ta.lowest(low, localHighLookback) if enteringTrade entryPrice := goLong ? localHigh + priceBuffer : goShort ? localLow - priceBuffer : na slPrice := openLong ? low - priceBuffer : openShort ? high + priceBuffer : na slAmount := math.abs(entryPrice - slPrice) slPercent := math.abs((1 - (entryPrice - slAmount) / entryPrice) * 100) tpPercent := slPercent * riskReward // Risk calculations riskAmt = strategy.equity * accountRiskPercent / 100 entryQty = math.abs(riskAmt / slPercent * 100) / close if openLong if strategy.position_size < 0 printTpSlNotHitBox(tradeEntryBar + 1, bar_index + 1, strategy.position_avg_price, slPrice, tpPrice) printTradeExitLabel(bar_index + 1, math.max(tpPrice, slPrice), strategy.position_size, strategy.position_avg_price, strategy.openprofit) strategy.entry("Long", strategy.long, stop = entryPrice, qty = entryQty, alert_message = "Long Entry") enteringTrade := true inLong := true inShort := false printVerticalLine(color.new(color.green, 60)) if openShort if strategy.position_size > 0 printTpSlNotHitBox(tradeEntryBar + 1, bar_index + 1, strategy.position_avg_price, slPrice, tpPrice) printTradeExitLabel(bar_index + 1, math.max(tpPrice, slPrice), strategy.position_size, strategy.position_avg_price, strategy.openprofit) strategy.entry("Short", strategy.short, stop = entryPrice, qty = entryQty, alert_message = "Short Entry") enteringTrade := true inShort := true inLong := false printVerticalLine(color.new(color.red, 60)) // Check if trade is active or not longActive = strategy.position_size[1] > 0 shortActive = strategy.position_size[1] < 0 activeTrade = longActive or shortActive // If price closes beyond the Slow EMA, then cancel any pending orders if not activeTrade and ((inLong and close < entrySlowEma) or (inShort and close > entrySlowEma)) printVerticalLine(color.new(color.silver, 60)) inLong := false inShort := false strategy.cancel_all() tradeCancelled := true if enteringTrade profitPoints := percentAsPoints(tpPercent) lossPoints := percentAsPoints(slPercent) tpPrice := calcProfitTrgtPrice(profitPoints, entryPrice, openLong) tradeEntryBar := bar_index strategy.exit("TP/SL", profit = profitPoints, loss = lossPoints, comment_profit = "TP Hit", comment_loss = "SL Hit", alert_profit = "TP Hit Alert", alert_loss = "SL Hit Alert") // ============================================================================= // DRAWINGS // ============================================================================= // ----------- // TP/SL Boxes // ----------- exitedOnCurrentBar = strategy.closedtrades.entry_bar_index(strategy.closedtrades - 1) == bar_index slHit = ((shortActive or exitedOnCurrentBar) and high >= slPrice) or ((longActive or exitedOnCurrentBar) and low <= slPrice) tpHit = ((longActive or exitedOnCurrentBar) and high >= tpPrice) or ((shortActive or exitedOnCurrentBar) and low <= tpPrice) exitTriggered = slHit or tpHit pnl = strategy.closedtrades.profit (strategy.closedtrades - 1) posSize = strategy.closedtrades.size (strategy.closedtrades - 1) // Print boxes for trades closed at profit or loss if (inTrade and exitTriggered and not tradeCancelled or exitedOnCurrentBar) inShort := false inLong := false printTpSlHitBox(tradeEntryBar, bar_index, slHit, tpHit, entryPrice, slPrice, tpPrice) printTradeExitLabel(bar_index, math.max(tpPrice, slPrice), posSize, entryPrice, pnl) // Print TP/SL box for current open trade else if barstate.islastconfirmedhistory and strategy.position_size != 0 printTpSlNotHitBox(tradeEntryBar + 1, bar_index + 1, strategy.position_avg_price, slPrice, tpPrice) // Trade cancelled before entry else if tradeCancelled tradeCancelled := false printTpSlNotHitBox(tradeEntryBar, bar_index, entryPrice, slPrice, tpPrice) printTradeExitLabel(bar_index + 1, math.max(tpPrice, slPrice), strategy.position_size, strategy.position_avg_price, strategy.openprofit) // ============================================================================= // DEBUGGING // ============================================================================= // Data window plots // Leaving all debugging plots in for now as they may be useful during future development/improvements for this strategy plotchar(currTrendFastEma, "currTrendFastEma", "") plotchar(currTrendSlowEma, "currTrendSlowEma", "") plotchar(fanOutGap, "fanGap", "") plotchar(bullTrendDir, "bullTrendDir", "") plotchar(bullTrendPrice, "bullTrendPrice", "") plotchar(bullEmaOrder, "bullEmaOrder", "") plotchar(bullFanOutGap, "bullFanOutGap", "") plotchar(bullBreakout, "bullBreakout", "") plotchar(bullPullback, "bullPullback", "") plotchar(goLong, "goLong", "") plotchar(inLong, "inLong", "") plotchar(bearTrendDir, "bearTrendDir", "") plotchar(bearTrendPrice, "bearTrendPrice", "") plotchar(bearEmaOrder, "bearEmaOrder", "") plotchar(bearFanOutGap, "bearFanOutGap", "") plotchar(bearBreakout, "bearBreakout", "") plotchar(bearPullback, "bearPullback", "") plotchar(goShort, "goShort", "") plotchar(inShort, "inShort", "") plotchar(openLong, "openLong", "") plotchar(openShort, "openShort", "") plotchar(enteringTrade, "enteringTrade", "") plotchar(entryPrice, "entryPrice", "") plotchar(slPrice, "slPrice", "") plotchar(tpPrice, "tpPrice", "") plotchar(tpPercent, "tpPercent", "") plotchar(slPercent, "slPercent", "") plotchar(longActive, "longActive", "") plotchar(shortActive, "shortActive", "") plotchar(exitedOnCurrentBar, "exitedOnCurrentBar", "") plotchar(strategy.position_size, "position_size After", "") plotchar(slHit, "slHit", "") plotchar(tpHit, "tpHit", "") // Label plots // plotDebugLabels = false // if plotDebugLabels // if bar_index == tradeEntryBar // printLabel(bar_index, "Position size: " + str.tostring(entryQty * close, "#.##"))
AlphaTrend Strategy with Trailing SL %
https://www.tradingview.com/script/bw7NiZTJ-AlphaTrend-Strategy-with-Trailing-SL/
rohanarora1313
https://www.tradingview.com/u/rohanarora1313/
158
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // author Β© KivancOzbilgic // developer Β© KivancOzbilgic //@version=5 strategy("AlphaTrend Strategy", shorttitle='ATst', overlay=true, format=format.price, precision=2, margin_long=100, margin_short=100) coeff = input.float(1, 'Multiplier', step=0.1) AP = input(14, 'Common Period') ATR = ta.sma(ta.tr, AP) src = input(close) showsignalsk = input(title='Show Signals?', defval=false) novolumedata = input(title='Change calculation (no volume data)?', defval=false) upT = low - ATR * coeff downT = high + ATR * coeff AlphaTrend = 0.0 AlphaTrend := (novolumedata ? ta.rsi(src, AP) >= 50 : ta.mfi(hlc3, AP) >= 50) ? upT < nz(AlphaTrend[1]) ? nz(AlphaTrend[1]) : upT : downT > nz(AlphaTrend[1]) ? nz(AlphaTrend[1]) : downT color1 = AlphaTrend > AlphaTrend[1] ? #00E60F : AlphaTrend < AlphaTrend[1] ? #80000B : AlphaTrend[1] > AlphaTrend[3] ? #00E60F : #80000B k1 = plot(AlphaTrend, color=color.new(#0022FC, 0), linewidth=3) k2 = plot(AlphaTrend[2], color=color.new(#FC0400, 0), linewidth=3) fill(k1, k2, color=color1) buySignalk = ta.crossover(AlphaTrend, AlphaTrend[2]) sellSignalk = ta.crossunder(AlphaTrend, AlphaTrend[2]) K1 = ta.barssince(buySignalk) K2 = ta.barssince(sellSignalk) O1 = ta.barssince(buySignalk[1]) O2 = ta.barssince(sellSignalk[1]) plotshape(buySignalk and showsignalsk and O1 > K2 ? AlphaTrend[2] * 0.9999 : na, title='BUY', text='BUY', location=location.absolute, style=shape.labelup, size=size.tiny, color=color.new(#0022FC, 0), textcolor=color.new(color.white, 0)) plotshape(sellSignalk and showsignalsk and O2 > K1 ? AlphaTrend[2] * 1.0001 : na, title='SELL', text='SELL', location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.new(color.maroon, 0), textcolor=color.new(color.white, 0)) // //ENTER SOME SETUP TRADES FOR TSL EXAMPLE // longCondition = ta.crossover(ta.sma(close, 10), ta.sma(close, 20)) // if longCondition // strategy.entry('My Long Entry Id', strategy.long) // shortCondition = ta.crossunder(ta.sma(close, 10), ta.sma(close, 20)) // if shortCondition // strategy.entry('My Short Entry Id', strategy.short) longCondition = buySignalk if (longCondition) strategy.entry("Long", strategy.long) shortCondition = sellSignalk if (shortCondition) strategy.entry("Short", strategy.short) enableTrailing = input.bool(title='Enable Trailing Stop (%)',defval = true) //TRAILING STOP CODE trailStop = input.float(title='Trailing (%)', minval=0.0, step=0.1, defval=10) * 0.01 longStopPrice = 0.0 shortStopPrice = 0.0 longStopPrice := if strategy.position_size > 0 stopValue = close * (1 - trailStop) math.max(stopValue, longStopPrice[1]) else 0 shortStopPrice := if strategy.position_size < 0 stopValue = close * (1 + trailStop) math.min(stopValue, shortStopPrice[1]) else 999999 //PLOT TSL LINES plot(series=strategy.position_size > 0 ? longStopPrice : na, color=color.new(color.red, 0), style=plot.style_linebr, linewidth=1, title='Long Trail Stop', offset=1, title='Long Trail Stop') plot(series=strategy.position_size < 0 ? shortStopPrice : na, color=color.new(color.red, 0), style=plot.style_linebr, linewidth=1, title='Short Trail Stop', offset=1, title='Short Trail Stop') if enableTrailing //EXIT TRADE @ TSL if strategy.position_size > 0 strategy.exit(id='Close Long', stop=longStopPrice) if strategy.position_size < 0 strategy.exit(id='Close Short', stop=shortStopPrice)
Impulse Strategy Signals V2
https://www.tradingview.com/script/C71eOyjd-Impulse-Strategy-Signals-V2/
danieljordi
https://www.tradingview.com/u/danieljordi/
55
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© Hiubris_Indicators //@version=5 strategy(title = "Impulse Strategy Signals (SMMA Cross)", overlay = true, default_qty_value = 100, initial_capital=100000,default_qty_type=strategy.percent_of_equity, pyramiding=0, process_orders_on_close=true) ma_len1 = input(21, title="SMMA Length 1 ", group='SMMA') ma_len2 = input(50, title="SMMA Length 2 ", group='SMMA') ma_len3 = input(200, title="SMMA Length 3 ", group='SMMA') smma(src, len) => smma = 0.0 smma := na(smma[1]) ? ta.sma(src, len) : (smma[1] * (len - 1) + src) / len smma ma1 = smma(close, ma_len1) ma2 = smma(close, ma_len2) ma3 = smma(close, ma_len3) plot(ma1, title='MA1', color=color.green) plot(ma2, title='MA2', color=color.orange) plot(ma3, title='MA3', color=color.white) rsi_src = input(close, title="RSI Source", group='RSI') rsi_len = input(14, title='RSI Length', group='RSI') rsi = ta.rsi(rsi_src, rsi_len) rsi_long = input.float(50.0, title="LONG: RSI Entry Threshold", group='RSI') rsi_short= input.float(50.0, title="SHORT: RSI Entry Threshold", group='RSI') // Trading Session 1 session1 = input.session("0700-1600", title="Trading Session 1")+":1234567" t1 = time(timeframe.period, session1) trading_session_filter1 = na(t1) ? 0 : 1 // Trading Session 2 session2 = input.session("1200-2100", title="Trading Session 2")+":1234567" t2 = time(timeframe.period, session2) trading_session_filter2 = na(t2) ? 0 : 1 bgcolor(trading_session_filter1? color.new(color.blue, 90):na, title="Trading Session 1") bgcolor(trading_session_filter2? color.new(color.blue, 90):na, title="Trading Session 2") trading_session_cond = (trading_session_filter1 or trading_session_filter2) and not (trading_session_filter1 and trading_session_filter2) long0 = rsi>rsi_long and close>ma1 and close>ma2 and close>ma3 and ((ta.crossover (ma1, ma2) or ta.crossover (close, ma3))) short0= rsi<rsi_short and close<ma1 and close<ma2 and close<ma3 and ((ta.crossunder(ma1, ma2) or ta.crossunder(close, ma3))) long = long0 and not long0 [1] and trading_session_cond short= short0 and not short0[1] and trading_session_cond // Position Management Tools pos = 0.0 pos:= long? 1 : short? -1 : pos[1] longCond = long and (pos[1]!= 1 or na(pos[1])) shortCond = short and (pos[1]!=-1 or na(pos[1])) // EXIT FUNCTIONS // strat_grp = "strategy settings" atrlen = input(14, title="ATR Length", group=strat_grp) atr = ta.atr(atrlen) i_sl_sw = input.string("ATR", title="", inline="i_sl ", options=["%", "ATR"], group=strat_grp) i_tsl_sw = input.string("ATR", title="", inline="i_tsl", options=["ATR", "%"], group=strat_grp) i_sl = input.float(2.0, title="● Stop Loss  ", minval=0, inline="i_sl ", group=strat_grp,step=0.1) i_tsl = input.float(0.0, title="● Trailing SL", minval=0, inline="i_tsl", group=strat_grp,step=0.1) i_tp1_sw = input.string("%", title="", inline="i_tp1 ", options=["%", "ATR", "R:R"], group=strat_grp) i_tp2_sw = input.string("%", title="", inline="i_tp2 ", options=["%", "ATR", "R:R"], group=strat_grp) i_tp3_sw = input.string("%", title="", inline="i_tp3 ", options=["%", "ATR", "R:R"], group=strat_grp) i_tp4_sw = input.string("%", title="", inline="i_tp4 ", options=["%", "ATR", "R:R"], group=strat_grp) i_tp1 = input.float(1.0, title="TP 1", minval=0, step=0.1, inline="i_tp1 ", group=strat_grp) i_tp2 = input.float(2.0, title="TP 2", minval=0, step=0.1, inline="i_tp2 ", group=strat_grp) i_tp3 = input.float(3.0, title="TP 3", minval=0, step=0.1, inline="i_tp3 ", group=strat_grp) i_tp4 = input.float(4.0, title="TP 4", minval=0, step=0.1, inline="i_tp4 ", group=strat_grp) perc_tp1_0 = input(10.0 , title="QTY%", inline="i_tp1 ", group=strat_grp) perc_tp2_0 = input(10.0 , title="QTY%", inline="i_tp2 ", group=strat_grp) perc_tp3_0 = input(30.0 , title="QTY%", inline="i_tp3 ", group=strat_grp) perc_tp4_0 = input(100.0, title="QTY%", inline="i_tp4 ", group=strat_grp) perc_tp1 = perc_tp1_0 perc_tp2 = perc_tp1_0+perc_tp2_0==100? 100 : perc_tp2_0 perc_tp3 = perc_tp1_0+perc_tp2_0+perc_tp3_0==100? 100 : perc_tp3_0 perc_tp4 = perc_tp1_0+perc_tp2_0+perc_tp3_0+perc_tp4_0==100? 100 : perc_tp4_0 sl = i_sl >0? (i_sl_sw =="%"? i_sl /100 : i_sl ) : 99999 tsl = i_tsl>0? (i_tsl_sw=="%"? i_tsl/100 : i_tsl) : 99999 tp1 = i_tp1 >0? (i_tp1_sw =="%"? i_tp1 /100 : i_tp1 ) : 99999 tp2 = i_tp2 >0? (i_tp2_sw =="%"? i_tp2 /100 : i_tp2 ) : 99999 tp3 = i_tp3 >0? (i_tp3_sw =="%"? i_tp3 /100 : i_tp3 ) : 99999 tp4 = i_tp4 >0? (i_tp4_sw =="%"? i_tp4 /100 : i_tp4 ) : 99999 long_entry = ta.valuewhen(longCond , close, 0) short_entry = ta.valuewhen(shortCond, close, 0) // Trailing Stop Loss trail_long = 0.0, trail_short = 0.0 trail_long := longCond? high : high>trail_long[1]? high : pos<1 ? 0 : trail_long[1] trail_short := shortCond? low : low<trail_short[1]? low : pos>-1 ? 99999 : trail_short[1] trail_long_final_atr = trail_long - atr*tsl trail_short_final_atr = trail_short + atr*tsl trail_long_final_perc = trail_long * (1-tsl) trail_short_final_perc = trail_short * (1+tsl) trail_long_final = i_tsl_sw=="ATR"? trail_long_final_atr : trail_long_final_perc trail_short_final = i_tsl_sw=="ATR"? trail_short_final_atr : trail_short_final_perc // Stop Loss Functions sl_long_perc = long_entry * (1 - sl) sl_short_perc = short_entry * (1 + sl) sl_long_atr = ta.valuewhen(longCond , close -atr * sl, 0) sl_short_atr = ta.valuewhen(shortCond, close +atr * sl, 0) sl_long0 = i_sl_sw =="%"? sl_long_perc : i_sl_sw =="ATR"? sl_long_atr : 0 sl_short0 = i_sl_sw =="%"? sl_short_perc : i_sl_sw =="ATR"? sl_short_atr : 99999 sl_long = math.max(sl_long0 , trail_long_final ) sl_short = math.min(sl_short0, trail_short_final) perc_tp_long1 = long_entry * (1 + tp1 ), atr_tp_long1 = ta.valuewhen(longCond , close + atr * tp1 , 0), rr_tp_long1 = ta.valuewhen(longCond , close+math.abs(close-sl_long )* tp1 , 0) perc_tp_long2 = long_entry * (1 + tp2 ), atr_tp_long2 = ta.valuewhen(longCond , close + atr * tp2 , 0), rr_tp_long2 = ta.valuewhen(longCond , close+math.abs(close-sl_long )* tp2 , 0) perc_tp_long3 = long_entry * (1 + tp3 ), atr_tp_long3 = ta.valuewhen(longCond , close + atr * tp3 , 0), rr_tp_long3 = ta.valuewhen(longCond , close+math.abs(close-sl_long )* tp3 , 0) perc_tp_long4 = long_entry * (1 + tp4 ), atr_tp_long4 = ta.valuewhen(longCond , close + atr * tp4 , 0), rr_tp_long4 = ta.valuewhen(longCond , close+math.abs(close-sl_long )* tp4 , 0) perc_tp_short1 = short_entry * (1 - tp1 ), atr_tp_short1 = ta.valuewhen(shortCond , close - atr * tp1 , 0), rr_tp_short1 = ta.valuewhen(shortCond, close-math.abs(close-sl_short)*tp1 , 0) perc_tp_short2 = short_entry * (1 - tp2 ), atr_tp_short2 = ta.valuewhen(shortCond , close - atr * tp2 , 0), rr_tp_short2 = ta.valuewhen(shortCond, close-math.abs(close-sl_short)*tp2 , 0) perc_tp_short3 = short_entry * (1 - tp3 ), atr_tp_short3 = ta.valuewhen(shortCond , close - atr * tp3 , 0), rr_tp_short3 = ta.valuewhen(shortCond, close-math.abs(close-sl_short)*tp3 , 0) perc_tp_short4 = short_entry * (1 - tp4 ), atr_tp_short4 = ta.valuewhen(shortCond , close - atr * tp4 , 0), rr_tp_short4 = ta.valuewhen(shortCond, close-math.abs(close-sl_short)*tp4 , 0) tp_long1 = i_tp1_sw =="%"? perc_tp_long1 : i_tp1_sw =="ATR"? atr_tp_long1 : rr_tp_long1 tp_long2 = i_tp2_sw =="%"? perc_tp_long2 : i_tp2_sw =="ATR"? atr_tp_long2 : rr_tp_long2 tp_long3 = i_tp3_sw =="%"? perc_tp_long3 : i_tp3_sw =="ATR"? atr_tp_long3 : rr_tp_long3 tp_long4 = i_tp4_sw =="%"? perc_tp_long4 : i_tp4_sw =="ATR"? atr_tp_long4 : rr_tp_long4 tp_short1 = i_tp1_sw =="%"? perc_tp_short1 : i_tp1_sw =="ATR"? atr_tp_short1 : rr_tp_short1 tp_short2 = i_tp2_sw =="%"? perc_tp_short2 : i_tp2_sw =="ATR"? atr_tp_short2 : rr_tp_short2 tp_short3 = i_tp3_sw =="%"? perc_tp_short3 : i_tp3_sw =="ATR"? atr_tp_short3 : rr_tp_short3 tp_short4 = i_tp4_sw =="%"? perc_tp_short4 : i_tp4_sw =="ATR"? atr_tp_short4 : rr_tp_short4 // Take Profits % sum_tp4 = perc_tp1 + perc_tp2 + perc_tp3 + perc_tp4 sum_tp3 = perc_tp1 + perc_tp2 + perc_tp3 sum_tp2 = perc_tp1 + perc_tp2 sum_tp1 = perc_tp1 last_tp_long = i_tp4>0 and sum_tp4>=100? tp_long4 : i_tp3>0 and sum_tp3>=100? tp_long3 : i_tp2>0 and sum_tp2>=100? tp_long2 : i_tp1>0 and sum_tp1>=100? tp_long1 : na last_tp_short = i_tp4>0 and sum_tp4>=100? tp_short4 : i_tp3>0 and sum_tp3>=100? tp_short3 : i_tp2>0 and sum_tp2>=100? tp_short2 : i_tp1>0 and sum_tp1>=100? tp_short1 : na // Position Adjustment long_sl = low <sl_long[1] and pos[1]==1 short_sl = high>sl_short[1] and pos[1]==-1 final_long_tp = high>last_tp_long [1] and pos[1]==1 final_short_tp = low <last_tp_short[1] and pos[1]==-1 if ((long_sl or final_long_tp) and not shortCond) or ((short_sl or final_short_tp) and not longCond) pos:=0 // Strategy Backtest Limiting Algorithm i_startTime = input.time(defval = timestamp("01 Sep 2002 13:30 +0000"), title = "Backtesting Start Time") i_endTime = input.time(defval = timestamp("30 Sep 2099 19:30 +0000"), title = "Backtesting End Time" ) timeCond = (time > i_startTime) and (time < i_endTime) equity = strategy.initial_capital + strategy.netprofit if equity>0 and timeCond if longCond strategy.entry("long" , strategy.long ) if shortCond strategy.entry("short", strategy.short) strategy.exit("SL/TP1 ", from_entry = "long" , stop=sl_long , limit=tp_long1 , qty_percent=perc_tp1 , when=perc_tp1 >0) strategy.exit("SL/TP2 ", from_entry = "long" , stop=sl_long , limit=tp_long2 , qty_percent=perc_tp2 , when=perc_tp2 >0) strategy.exit("SL/TP3 ", from_entry = "long" , stop=sl_long , limit=tp_long3 , qty_percent=perc_tp3 , when=perc_tp3 >0) strategy.exit("SL/TP4 ", from_entry = "long" , stop=sl_long , limit=tp_long4 , qty_percent=perc_tp4 , when=perc_tp4 >0) strategy.exit("SL/TP1 ", from_entry = "short" , stop=sl_short, limit=tp_short1 , qty_percent=perc_tp1 , when=perc_tp1 >0) strategy.exit("SL/TP2 ", from_entry = "short" , stop=sl_short, limit=tp_short2 , qty_percent=perc_tp2 , when=perc_tp2 >0) strategy.exit("SL/TP3 ", from_entry = "short" , stop=sl_short, limit=tp_short3 , qty_percent=perc_tp3 , when=perc_tp3 >0) strategy.exit("SL/TP4 ", from_entry = "short" , stop=sl_short, limit=tp_short4 , qty_percent=perc_tp4 , when=perc_tp4 >0) show_sltp = input(true, title="Show SL/TP Lines on Chart") plot(show_sltp and pos== 1? tp_long1 : na, color=color.green, style=plot.style_linebr, title="TP Long 1") plot(show_sltp and pos== 1? tp_long2 : na, color=color.green, style=plot.style_linebr, title="TP Long 2") plot(show_sltp and pos== 1? tp_long3 : na, color=color.green, style=plot.style_linebr, title="TP Long 3") plot(show_sltp and pos== 1? tp_long4 : na, color=color.green, style=plot.style_linebr, title="TP Long 4") plot(show_sltp and pos==-1? tp_short1 : na, color=color.green, style=plot.style_linebr, title="TP Short 1") plot(show_sltp and pos==-1? tp_short2 : na, color=color.green, style=plot.style_linebr, title="TP Short 2") plot(show_sltp and pos==-1? tp_short3 : na, color=color.green, style=plot.style_linebr, title="TP Short 3") plot(show_sltp and pos==-1? tp_short4 : na, color=color.green, style=plot.style_linebr, title="TP Short 4") plot(show_sltp and pos== 1? sl_long : na, color=color.red , style=plot.style_linebr, title="SL Long ") plot(show_sltp and pos==-1? sl_short : na, color=color.red , style=plot.style_linebr, title="SL Short") plotshape(longCond, textcolor=#ffffff, color=color.lime, style=shape.labelup , title="Buy" , text="Buy" , location=location.belowbar, offset=0, size=size.small) plotshape(shortCond, textcolor=#ffffff, color=color.red , style=shape.labeldown, title="Sell", text="Sell", location=location.abovebar, offset=0, size=size.small) longCond_txt = input("", title='Alert Msg: LONG Entry', group='Alert Message', inline='longCond_txt ') shortCond_txt = input("", title='Alert Msg: SHORT Entry', group='Alert Message', inline='shortCond_txt ') long_sltp_txt = input("", title='Alert Msg: LONG SL/TP', group='Alert Message', inline='long_sltp_txt ') short_sltp_txt = input("", title='Alert Msg: SHORT SL/TP', group='Alert Message', inline='short_sltp_txt ') if longCond alert(longCond_txt, alert.freq_once_per_bar_close) if shortCond alert(shortCond_txt, alert.freq_once_per_bar_close) if long_sl or final_long_tp alert(long_sltp_txt, alert.freq_once_per_bar_close) if short_sl or final_short_tp alert(short_sltp_txt, alert.freq_once_per_bar_close)
ninja strategy
https://www.tradingview.com/script/MnxRo3rZ-ninja-strategy/
kuroisirokisi
https://www.tradingview.com/u/kuroisirokisi/
44
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© kuroisirokisi //@version=5 strategy("ninja strategy") if (low[1] > low[2] and low[2] > low[3] and close <= low[1]) strategy.entry("BarUp", strategy.long, 1000000, stop=low[1]+(high[1]-low[1])*2/3) if (high[1] < high[2] and high[2] < high[3] and close >= high[1]) strategy.entry("BarDown", strategy.short, 1000000, stop=high[1]-(high[1]-low[1])*2/3) if (timenow >= time_close) strategy.close("BarUp") strategy.close("BarDown")
PowerX by jwitt98
https://www.tradingview.com/script/eKdY8CoC-PowerX-by-jwitt98/
jwitt98
https://www.tradingview.com/u/jwitt98/
47
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© jwitt98 //The PowerX strategy - based on the rules outlined in the book "The PowerX Strategy: How to Trade Stocks and Options in Only 15 Minutes a Day" by Markus Heitkoetter //@version=5 strategy("PowerX", overlay=true, initial_capital=10000) longEntry = "Enter long" shortEntry = "Enter short" longExit = "Exit long" shortExit = "Exit short" //*********************************Begin inputs********************************* //get time range inputs and set time range bool timeRangeGroup = "Select the trading range" startDate = input.time(timestamp("1 Jan 2021 00:00 +0000"), "Start date", "Select the start date for the trading range", "", timeRangeGroup) endDate = input.time(timestamp("1 Jan 2050 00:00 +0000"), "End date", "Select the end date for the trading range", "", timeRangeGroup) isInTimeRange = time >= startDate and time <= endDate //get long/short inputs positionsAllowedGroup = "Select the direction(s) of trades to allow" isLongsAllowed = input.bool(true, "Allow long positions", "Check the box if you want to allow long positions", "", positionsAllowedGroup) isShortsAllowed = input.bool(true, "Allow short positions", "Check the box if you want to allow short positions", "", positionsAllowedGroup) //get the stop loss and profit target multiples. Per the PowerX rules the ratio shoud be 1:2. 1.5 and 3 are defaults adrMultuplesGroup="Select the multipliers for the stop loss and profit targets" stopLossMultiple = input.float(1.5, "Stop loss multiple", 0.1, 10, 0.1, "The ADR is multiplied by the stop loss multiple to calculate the stop loss", group=adrMultuplesGroup) profitTargetMultiple=input.float(3.0, "Profit target multiple", 0.1, 10, 0.1, "The ADR is multiplied by the profit target multiple to calculate the profit target", group=adrMultuplesGroup) //get the option to use the money management stategy or not. This is a fixed ratio type management system moneyManagementGroup="Money management" isUsingMoneyManagement=input.bool(false, "Use money management", "Check the box if you want to use a fixed ratio type money management system, such as the type described in PowerX", group=moneyManagementGroup) initial_riskPercent=input.float(2.0, "Percent risk per trade", .1, 100, .1, "The percentage of capital you want to risk when starting out. This will increase or decrease base on the money management rules. Only applicable if money managent is used", group=moneyManagementGroup)/100 isRiskDowsideLimited=input.bool(false, "Keep risk at or above the set point", "Check the box if you don't want the risk to fall below the set \"risk per trade\" percentage, for example, when your equity is underwater. Only applicable if money management is used", "", moneyManagementGroup) initial_riskPerTrade=initial_riskPercent * strategy.initial_capital riskFactor = 0.0 currentProfit = 0.0 currentRisk = 0.0 //*********************************End inputs********************************* //*********************************Begin money management********************************* if(isUsingMoneyManagement) currentProfit := strategy.equity - strategy.initial_capital if(currentProfit < 0) currentProfit:=math.abs(currentProfit) riskFactor := 0.5*(math.pow(1+8*currentProfit/(2*initial_riskPerTrade), 0.5)+1) currentRisk := 1/riskFactor * initial_riskPercent * strategy.initial_capital if(isRiskDowsideLimited) currentRisk := initial_riskPerTrade else riskFactor := 0.5*(math.pow(1+8*currentProfit/(2*initial_riskPerTrade), 0.5)+1) currentRisk := riskFactor * initial_riskPercent * strategy.initial_capital plot(strategy.equity, "Strategy equity", display=display.data_window) plot(currentRisk, "Current risk", display=display.data_window) plot(riskFactor, "Risk Factor", display=display.data_window) //*********************************End money management********************************* //*********************************Begin indicators********************************* //4 indicators are used in this strategy, RSI(7), Stochastics(14, 3, 3), MACD(12, 26, 9), and ADR(7) rsiVal = ta.rsi(close, 7)//this checks out plot(rsiVal, "RSI(7)", color.lime, display=display.data_window) stochKVal = ta.sma(ta.sma(ta.stoch(close, high, low, 14),3),3)//this formula checks out plot(stochKVal, "Stoch %K", color.lime, display=display.data_window) [macdLine, signalLine, histLine] = ta.macd(close, 12, 26, 9) plot(histLine, "MACD Hist", color.lime, display=display.data_window) adr = ta.sma(high, 7) - ta.sma(low, 7) plot(adr, "Average daily range", color.orange, display=display.data_window) //*********************************End indicators********************************* //*********************************Define the bar colors********************************* greenBar = rsiVal > 50 and stochKVal > 50 and histLine > 0 redBar = rsiVal < 50 and stochKVal < 50 and histLine < 0 blackBar = not greenBar and not redBar color currentBarColor = switch greenBar => color.green redBar => color.red blackBar => color.gray //because black is too hard to see in dark mmode => color.yellow barcolor(currentBarColor) //*********************************End defining the bar colors********************************* //*********************************Define the entry, stop loss and profit target********************************* longStopLimit = high + .01 longProfitTarget = high + (profitTargetMultiple * adr) longStopLoss = high - (stopLossMultiple * adr) shortStopLimit = low - .01 shortProfitTarget = low - (profitTargetMultiple * adr) shortStopLoss = low + (stopLossMultiple * adr) qtyToTrade= math.floor(currentRisk / (stopLossMultiple * adr))//only if using money management if(qtyToTrade * high > strategy.equity) qtyToTrade := math.floor(strategy.equity / high) //*********************************End defining stop loss and profit targets********************************* //*********************************Execute trades, set rules, stop loss and profit targets********************************* if (greenBar and not greenBar[1] and isInTimeRange and isLongsAllowed) if(isUsingMoneyManagement) strategy.order(longEntry, strategy.long, qtyToTrade, limit=longStopLimit, stop=longStopLimit) //strategy.order(longEntry, strategy.long, qtyToTrade, stop=longStopLimit) else strategy.order(longEntry, strategy.long, limit=longStopLimit,stop=longStopLimit) //strategy.order(longEntry, strategy.long, stop=longStopLimit) strategy.exit("Long limit/stop", from_entry=longEntry, limit=longProfitTarget, stop=longStopLoss) if(blackBar or redBar) strategy.cancel(longEntry) strategy.close(longEntry, longExit) if (redBar and not redBar[1] and isInTimeRange and isShortsAllowed) if(isUsingMoneyManagement) strategy.order(shortEntry, strategy.short, qtyToTrade, limit=shortStopLimit, stop=shortStopLimit) //strategy.order(shortEntry, strategy.short, qtyToTrade, stop=shortStopLimit) else strategy.order(shortEntry, strategy.short, limit=shortStopLimit, stop=shortStopLimit) //strategy.order(shortEntry, strategy.short, stop=shortStopLimit) strategy.exit("Short limit/stop", from_entry=shortEntry, limit=shortProfitTarget, stop=shortStopLoss) if(blackBar or greenBar) strategy.cancel(shortEntry) strategy.close(shortEntry, shortExit) //*********************************End execute trades, set rules, stop loss and profit targets*********************************
BTC Good Signal
https://www.tradingview.com/script/lDHreXR2-BTC-Good-Signal/
Majaztrades
https://www.tradingview.com/u/Majaztrades/
35
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/ // Β© Wunderbit Trading //@version=4 strategy("Automated Bitcoin (BTC) Investment Strategy", overlay=true, initial_capital=5000,pyramiding = 0, currency="USD", default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent,commission_value=0.1) //////////// Functions Atr(p) => atr = 0. Tr = max(high - low, max(abs(high - close[1]), abs(low - close[1]))) atr := nz(atr[1] + (Tr - atr[1])/p,Tr) //TEMA TEMA(series, length) => if (length > 0) ema1 = ema(series, length) ema2 = ema(ema1, length) ema3 = ema(ema2, length) (3 * ema1) - (3 * ema2) + ema3 else na tradeType = input("LONG", title="What trades should be taken : ", options=["LONG", "SHORT", "BOTH", "NONE"]) /////////////////////////////////////////////////// /// INDICATORS source=close /// TREND trend_type1 = input("TEMA", title ="First Trend Line : ", options=["LSMA", "TEMA","EMA","SMA"]) trend_type2 = input("LSMA", title ="First Trend Line : ", options=["LSMA", "TEMA","EMA","SMA"]) trend_type1_length=input(25, "Length of the First Trend Line") trend_type2_length=input(100, "Length of the Second Trend Line") leadLine1 = if trend_type1=="LSMA" linreg(close, trend_type1_length, 0) else if trend_type1=="TEMA" TEMA(close,trend_type1_length) else if trend_type1 =="EMA" ema(close,trend_type1_length) else sma(close,trend_type1_length) leadLine2 = if trend_type2=="LSMA" linreg(close, trend_type2_length, 0) else if trend_type2=="TEMA" TEMA(close,trend_type2_length) else if trend_type2 =="EMA" ema(close,trend_type2_length) else sma(close,trend_type2_length) p3 = plot(leadLine1, color= #53b987, title="EMA", transp = 50, linewidth = 1) p4 = plot(leadLine2, color= #eb4d5c, title="SMA", transp = 50, linewidth = 1) fill(p3, p4, transp = 60, color = leadLine1 > leadLine2 ? #53b987 : #eb4d5c) //Upward Trend UT=crossover(leadLine1,leadLine2) DT=crossunder(leadLine1,leadLine2) // TP/ SL/ FOR LONG // TAKE PROFIT AND STOP LOSS long_tp1_inp = input(15, title='Long Take Profit 1 %', step=0.1)/100 long_tp1_qty = input(20, title="Long Take Profit 1 Qty", step=1) long_tp2_inp = input(30, title='Long Take Profit 2%', step=0.1)/100 long_tp2_qty = input(20, title="Long Take Profit 2 Qty", step=1) long_take_level_1 = strategy.position_avg_price * (1 + long_tp1_inp) long_take_level_2 = strategy.position_avg_price * (1 + long_tp2_inp) long_sl_input = input(5, title='stop loss in %', step=0.1)/100 long_sl_input_level = strategy.position_avg_price * (1 - long_sl_input) // Stop Loss multiplier = input(3.5, "SL Mutiplier", minval=1, step=0.1) ATR_period=input(8,"ATR period", minval=1, step=1) // Strategy //LONG STRATEGY CONDITION SC = input(close, "Source", input.source) SL1 = multiplier * Atr(ATR_period) // Stop Loss Trail1 = 0.0 Trail1 := iff(SC < nz(Trail1[1], 0) and SC[1] < nz(Trail1[1], 0), min(nz(Trail1[1], 0), SC + SL1), iff(SC > nz(Trail1[1], 0), SC - SL1, SC + SL1)) Trail1_high=highest(Trail1,50) // iff(SC > nz(Trail1[1], 0) and SC[1] > nz(Trail1[1], 0), max(nz(Trail1[1], 0), SC - SL1), entry_long=crossover(leadLine1,leadLine2) and Trail1_high < close exit_long = close < Trail1_high or crossover(leadLine2,leadLine1) or close < long_sl_input_level ///// BACKTEST PERIOD /////// testStartYear = input(2016, "Backtest Start Year") testStartMonth = input(1, "Backtest Start Month") testStartDay = input(1, "Backtest Start Day") testPeriodStart = timestamp(testStartYear, testStartMonth, testStartDay, 0, 0) testStopYear = input(9999, "Backtest Stop Year") testStopMonth = input(12, "Backtest Stop Month") testStopDay = input(31, "Backtest Stop Day") testPeriodStop = timestamp(testStopYear, testStopMonth, testStopDay, 0, 0) testPeriod() => time >= testPeriodStart and time <= testPeriodStop ? true : false if testPeriod() if tradeType=="LONG" or tradeType=="BOTH" if strategy.position_size == 0 or strategy.position_size > 0 strategy.entry("long", strategy.long, comment="BUY", when=entry_long) strategy.exit("TP1", "long", qty_percent=long_tp1_qty, limit=long_take_level_1) strategy.exit("TP2", "long", qty_percent=long_tp2_qty, limit=long_take_level_2) strategy.close("long", when=exit_long, comment="SL" ) // LONG POSITION plot(strategy.position_size > 0 ? long_take_level_1 : na, style=plot.style_linebr, color=color.green, linewidth=1, title="1st Long Take Profit") plot(strategy.position_size > 0 ? long_take_level_2 : na, style=plot.style_linebr, color=color.green, linewidth=1, title="2nd Long Take Profit") plot(strategy.position_size > 0 ? Trail1_high : na, style=plot.style_linebr, color=color.red, linewidth=1, title="Long Stop Loss")
SL1 Pips after TP2 (MA)
https://www.tradingview.com/script/r4aGtj4A-SL1-Pips-after-TP2-MA/
gpadihar
https://www.tradingview.com/u/gpadihar/
12
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/ // Β© gpadihar //@version=4 strategy("SL1 Pips after TP2 (MA)", commission_type=strategy.commission.cash_per_order, overlay=true, default_qty_value=10, initial_capital=100000) // Strategy Buy = input(true) Sell = input(true) // Date Range start_year = input(title='Start year' ,defval=2022) start_month = input(title='Start month' ,defval=1) start_day = input(title='Start day' ,defval=1) start_hour = input(title='Start hour' ,defval=0) start_minute = input(title='Start minute' ,defval=0) end_time = input(title='set end time?',defval=false) end_year = input(title='end year' ,defval=2019) end_month = input(title='end month' ,defval=12) end_day = input(title='end day' ,defval=31) end_hour = input(title='end hour' ,defval=23) end_minute = input(title='end minute' ,defval=59) // MA ema_period = input(title='EMA period',defval=15) wma_period = input(title='WMA period',defval=45) ema = ema(close,ema_period) wma = wma(close,wma_period) // Entry Condition buy = crossover(ema,wma) and nz(strategy.position_size) >= 0 and Buy and time > timestamp(start_year, start_month, start_day, start_hour, start_minute) and (end_time?(time < timestamp(end_year, end_month, end_day, end_hour, end_minute)):true) sell = crossunder(ema,wma) and nz(strategy.position_size) >= 0 and Sell and time > timestamp(start_year, start_month, start_day, start_hour, start_minute) and (end_time?(time < timestamp(end_year, end_month, end_day, end_hour, end_minute)):true) // Pips pip = input(20)*10*syminfo.mintick // Trading parameters // var bool LS = na var bool SS = na var float EP = na var float TVL = na var float TVS = na var float TSL = na var float TSS = na var float TP1 = na var float TP2 = na var float SL1 = na var float SL2 = na if buy or sell and strategy.position_size == 0 EP := close SL1 := EP - pip * 1 * (sell?-1:1) SL2 := EP - pip * (sell?-1:1) TP1 := EP + pip * 2 * (sell?-2:1) TP2 := EP + pip * 3 * (sell?-2:1) // current trade direction LS := buy or strategy.position_size > 0 SS := sell or strategy.position_size < 0 // adjust trade parameters and trailing stop calculations TVL := max(TP1,open) - pip[1] TVS := min(TP1,open) + pip[1] TSL := open[1] > TSL[1] ? max(TVL,TSL[1]):TVL TSS := open[1] < TSS[1] ? min(TVS,TSS[1]):TVS if LS and high > TP1 if open <= TP1 SL2:=min(EP,TSL) if SS and low < TP1 if open >= TP1 SL2:=max(EP,TSS) // Closing conditions close_long = LS and open < SL2 close_short = SS and open > SL2 // Buy strategy.entry("buy" , strategy.long, when=buy and not SS) strategy.exit ("exit1", from_entry="buy", stop=SL1, limit=TP1, qty_percent=100) strategy.exit ("exit2", from_entry="buy", stop=SL2, limit=TP2) // Sell strategy.entry("sell" , strategy.short, when=sell and not LS) strategy.exit ("exit3", from_entry="sell", stop=SL1, limit=TP1, qty_percent=100) strategy.exit ("exit4", from_entry="sell", stop=SL2, limit=TP2) // Plots a=plot(strategy.position_size > 0 ? SL1 : na, color=#dc143c, style=plot.style_linebr) b=plot(strategy.position_size < 0 ? SL1 : na, color=#dc143c, style=plot.style_linebr) c=plot(strategy.position_size > 0 ? TP1 : na, color=#00ced1, style=plot.style_linebr) d=plot(strategy.position_size < 0 ? TP1 : na, color=#00ced1, style=plot.style_linebr) e=plot(strategy.position_size > 0 ? TP2 : na, color=#00ced1, style=plot.style_linebr) f=plot(strategy.position_size < 0 ? TP2 : na, color=#00ced1, style=plot.style_linebr) g=plot(strategy.position_size >= 0 ? na : EP, color=#ffffff, style=plot.style_linebr) h=plot(strategy.position_size <= 0 ? na : EP, color=#ffffff, style=plot.style_linebr) plot(ema,title="ema",color=#fff176) plot(wma,title="wma",color=#00ced1)
DCA After Downtrend v2 (by BHD_Trade_Bot)
https://www.tradingview.com/script/XB3FuiXT-DCA-After-Downtrend-v2-by-BHD-Trade-Bot/
BHD_Trade_Bot
https://www.tradingview.com/u/BHD_Trade_Bot/
169
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© BHD_Trade_Bot // @version=5 strategy( shorttitle = 'DCA After Downtrend v2', title = 'DCA After Downtrend v2 (by BHD_Trade_Bot)', overlay = true, calc_on_every_tick = false, calc_on_order_fills = false, use_bar_magnifier = false, pyramiding = 1000, initial_capital = 0, default_qty_type = strategy.cash, default_qty_value = 1000, commission_type = strategy.commission.percent, commission_value = 1.1) // Backtest Time Period start_year = input(title='Start year' ,defval=2017) start_month = input(title='Start month' ,defval=1) start_day = input(title='Start day' ,defval=1) start_time = timestamp(start_year, start_month, start_day, 00, 00) end_year = input(title='end year' ,defval=2050) end_month = input(title='end month' ,defval=1) end_day = input(title='end day' ,defval=1) end_time = timestamp(end_year, end_month, end_day, 23, 59) window() => time >= start_time and time <= end_time ? true : false h1_last_bar = (math.min(end_time, timenow) - time)/1000/60/60 < 2 // EMA ema50 = ta.ema(close, 50) ema200 = ta.ema(close, 200) // EMA_CD emacd = ema50 - ema200 emacd_signal = ta.ema(emacd, 20) hist = emacd - emacd_signal // BHD Unit bhd_unit = ta.rma(high - low, 200) * 2 bhd_upper = ema200 + bhd_unit bhd_upper2 = ema200 + bhd_unit * 2 bhd_upper3 = ema200 + bhd_unit * 3 bhd_upper4 = ema200 + bhd_unit * 4 bhd_upper5 = ema200 + bhd_unit * 5 bhd_lower = ema200 - bhd_unit bhd_lower2 = ema200 - bhd_unit * 2 bhd_lower3 = ema200 - bhd_unit * 3 bhd_lower4 = ema200 - bhd_unit * 4 bhd_lower5 = ema200 - bhd_unit * 5 // Count n candles after x long entries var int nPastCandles = 0 var int entryNumber = 0 if window() nPastCandles := nPastCandles + 1 // ENTRY CONDITIONS // 24 * 30 per month entry_condition1 = nPastCandles > entryNumber * 24 * 30 // End of downtrend entry_condition2 = emacd < 0 and hist < 0 and hist > hist[2] ENTRY_CONDITIONS = entry_condition1 and entry_condition2 if ENTRY_CONDITIONS entryNumber := entryNumber + 1 entryId = 'Long ' + str.tostring(entryNumber) strategy.entry(entryId, strategy.long) // CLOSE CONDITIONS // Last bar CLOSE_CONDITIONS = barstate.islast or h1_last_bar if CLOSE_CONDITIONS strategy.close_all() // Draw colorRange(src) => if src > bhd_upper5 color.rgb(255,0,0) else if src > bhd_upper4 color.rgb(255,150,0) else if src > bhd_upper3 color.rgb(255,200,0) else if src > bhd_upper2 color.rgb(100,255,0) else if src > bhd_upper color.rgb(0,255,100) else if src > ema200 color.rgb(0,255,150) else if src > bhd_lower color.rgb(0,200,255) else if src > bhd_lower2 color.rgb(0,150,255) else if src > bhd_lower3 color.rgb(0,100,255) else if src > bhd_lower4 color.rgb(0,50,255) else color.rgb(0,0,255) bhd_upper_line = plot(bhd_upper, color=color.new(color.teal, 90)) bhd_upper_line2 = plot(bhd_upper2, color=color.new(color.teal, 90)) bhd_upper_line3 = plot(bhd_upper3, color=color.new(color.teal, 90)) bhd_upper_line4 = plot(bhd_upper4, color=color.new(color.teal, 90)) bhd_upper_line5 = plot(bhd_upper5, color=color.new(color.teal, 90)) bhd_lower_line = plot(bhd_lower, color=color.new(color.teal, 90)) bhd_lower_line2 = plot(bhd_lower2, color=color.new(color.teal, 90)) bhd_lower_line3 = plot(bhd_lower3, color=color.new(color.teal, 90)) bhd_lower_line4 = plot(bhd_lower4, color=color.new(color.teal, 90)) bhd_lower_line5 = plot(bhd_lower5, color=color.new(color.teal, 90)) // fill(bhd_upper_line5, bhd_lower_line5, color=color.new(color.teal, 95)) plot(ema50, color=color.orange, linewidth=3) plot(ema200, color=color.teal, linewidth=3) plot(close, color=color.teal, linewidth=1) plot(close, color=colorRange(close), linewidth=3, style=plot.style_circles)
J2S Backtest: Steven Primo`s Big Trend Strategy
https://www.tradingview.com/script/6VISeroA-J2S-Backtest-Steven-Primo-s-Big-Trend-Strategy/
julianossilva
https://www.tradingview.com/u/julianossilva/
209
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© julianossilva //@version=5 strategy(title="J2S Backtest: Steven Primo`s Big Trend Strategy", shorttitle="J2S Backtest: Steven Primo`s Big Trend Strategy", overlay=true, initial_capital=1000, default_qty_value=10, default_qty_type=strategy.percent_of_equity, pyramiding=0) // Variables to control open orders var myLongOrders = array.new_int(0) var myShortOrders = array.new_int(0) // Initial Backtest Date Range useStartDate = timestamp("01 Jan 2020 21:00:00") useEndDate = timestamp("01 Jan 2023 21:00:00") // User Inputs SIGNAL_CONFIG = "BACKTEST: STEVEN PRIMO'S BIG TREND STRATEGY" longEntryInput = input.bool(defval=true, group=SIGNAL_CONFIG, title="Long entry") shortEntryInput = input.bool(defval=true, group=SIGNAL_CONFIG, title="Short entry") METHOD_CONFIG = "BACKTEST: METHOD" maturityIndexInput = input.int(defval=5, group=METHOD_CONFIG, title="Bar indicating trend maturity", tooltip="Entries are made from the bar that indicates the trend maturity.", minval=1) barsLimitForEntryInput = input.int(defval=5, group=METHOD_CONFIG, title="Bar limit for trading entry", tooltip="Given a signal, entry must be reached within how many bars?", minval=1) barLimitForCloseInput = input.int(defval=30, group=METHOD_CONFIG, title="Bar limit for trading close", tooltip="Once a position is opened, close when it reaches the number of bars in trading.", minval=1) profitOverRiskInput = input.float(defval=15, group=METHOD_CONFIG, title="Profit over risk", tooltip="Multiplication factor based on the risk assumed in trading.", minval=1, step=0.5) BB_CONFIG = "BACKTEST: BOLLINGER BANDS" smaLengthInput = input.int(defval=20, group=BB_CONFIG, inline="01", title="Length", minval=1) smaColorInput = input.color(defval=color.orange, group=BB_CONFIG, inline="01", title="") sourceInput = input.source(defval=close, group=BB_CONFIG, inline="02", title="Source") bbFactorInput = input.float(defval=0.382, group=BB_CONFIG, inline="03", title="Factor", minval=0.001, maxval=50, step=0.05) bbColorInput = input.color(defval=color.blue, group=BB_CONFIG, inline="03", title="") offsetInput = input.int(defval=1, group=BB_CONFIG, inline="04", title="Offset") PERIOD_CONFIG = "BACKTEST: TIME PERIOD" useDateFilterInput = input.bool(defval=true, group=PERIOD_CONFIG, title="Filter date range of backtest") backtestStartDateInput = input.time(defval=useStartDate, group=PERIOD_CONFIG, title="Start date") backtestEndDateInput = input.time(defval=useEndDate, group=PERIOD_CONFIG, title="End date") // Colors bbBackgroundColor = color.rgb(33, 150, 243, 90) candleColorDown = color.rgb(239, 83, 80, 80) candleColorUp = color.rgb(38, 166, 154, 70) insideBarColorDown = color.rgb(239, 83, 80, 40) insideBarColorUp = color.rgb(38, 166, 154, 20) downTrendColor = color.rgb(239, 83, 80, 80) sidewaysTrendColor = color.rgb(252, 232, 131, 80) upTrendColor = color.rgb(38, 166, 154, 80) buySignalColor = color.lime sellSignalColor = color.orange // Candles isCandleUp() => close > open isCandleDown() => close <= open barcolor(isCandleUp() ? candleColorUp : isCandleDown() ? candleColorDown : na) // Bollinger Bands and Simple Moving Average sma = ta.sma(sourceInput, smaLengthInput) bbWidth = ta.stdev(sourceInput, smaLengthInput) * bbFactorInput bbHigh = sma + bbWidth bbLow = sma - bbWidth plot(sma, title="SMA", color=smaColorInput, offset=offsetInput) bbUpper = plot(bbHigh, title="BB High", color=bbColorInput, offset=offsetInput) bbLower = plot(bbLow, title="BB Low", color=bbColorInput, offset=offsetInput) fill(bbUpper, bbLower, title="BB Background", color=bbBackgroundColor) // Backtest Time Period inTradeWindow = not useDateFilterInput or (time >= backtestStartDateInput and time < backtestEndDateInput) isInTradeWindow() => inTradeWindow isBacktestDateRangeOver() => not inTradeWindow and inTradeWindow[1] // Rule that indicates maturity of trend to buy isPrimoBuy() => result = true barIndex = 0 while result and barIndex < maturityIndexInput result := close[barIndex] >= bbHigh[barIndex] barIndex += 1 result := result and close[maturityIndexInput] < bbHigh[maturityIndexInput] // Rule that indicates maturity of trend to sell isPrimoSell() => result = true barIndex = 0 while result and barIndex < maturityIndexInput result := close[barIndex] <= bbLow[barIndex] barIndex += 1 result := result and close[maturityIndexInput] > bbLow[maturityIndexInput] // Entry signals longEntryHasBeenMet() => longEntryInput and isInTradeWindow() and isPrimoBuy() shortEntryHasBeenMet() => shortEntryInput and isInTradeWindow() and isPrimoSell() // Scheduling LONG entry if longEntryHasBeenMet() array.push(myLongOrders, bar_index) longEntryID = "Long Entry:\n" + str.tostring(bar_index) longExitID = "Long Exit:\n" + str.tostring(bar_index) longEntryTrigger = high + 1 * syminfo.mintick stopLossInLong = low[maturityIndexInput - 1] - 1 * syminfo.mintick takeProfitInLong = high + (high - low) * profitOverRiskInput strategy.order(longEntryID, strategy.long, stop=longEntryTrigger) strategy.exit(longExitID, longEntryID, stop=stopLossInLong, limit=takeProfitInLong) // In pine script, any order scheduled but not yet filled can be canceled. // Once a order is filled, the trade is only finished with use of close or exit functions. // As scheduled orders are not stored in the strategy.opentrades array, manual control is required. int myLongOrderIndex = 0 while myLongOrderIndex < array.size(myLongOrders) and array.size(myLongOrders) > 0 myLongOrder = array.get(myLongOrders, myLongOrderIndex) if bar_index - myLongOrder == barsLimitForEntryInput longEntryID = "Long Entry:\n" + str.tostring(myLongOrder) strategy.cancel(longEntryID) array.remove(myLongOrders, myLongOrderIndex) continue myLongOrderIndex += 1 // Scheduling SHORT entry if shortEntryHasBeenMet() array.push(myShortOrders, bar_index) shortEntryID = "Short Entry:\n" + str.tostring(bar_index) shortExitID = "Short Exit:\n" + str.tostring(bar_index) shortEntryTrigger = low - 1 * syminfo.mintick stopLossInShort = high[maturityIndexInput - 1] + 1 * syminfo.mintick takeProfitInShort = low - (high - low) * profitOverRiskInput strategy.order(shortEntryID, strategy.short, stop=shortEntryTrigger) strategy.exit(shortExitID, shortEntryID, stop=stopLossInShort, limit=takeProfitInShort) // In pine script, any order scheduled but not yet filled can be canceled. // Once a order is filled, the trade is only finished with use of close or exit functions. // As scheduled orders are not stored in the strategy.opentrades array, manual control is required. int myShortOrderIndex = 0 while myShortOrderIndex < array.size(myShortOrders) and array.size(myShortOrders) > 0 myShortOrder = array.get(myShortOrders, myShortOrderIndex) if bar_index - myShortOrder == barsLimitForEntryInput shortEntryID = "Short Entry:\n" + str.tostring(myShortOrder) strategy.cancel(shortEntryID) array.remove(myShortOrders, myShortOrderIndex) continue myShortOrderIndex += 1 // Trading must be stopped when candlestick limit reached in a trading for tradeNumber = 0 to strategy.opentrades - 1 tradeEntryID = strategy.opentrades.entry_id(tradeNumber) splitPosition = str.pos(tradeEntryID, ":") entryBar = str.tonumber(str.substring(tradeEntryID, splitPosition + 1)) if bar_index - entryBar == barLimitForCloseInput closeID = "Close Position:\n" + str.tostring(entryBar) strategy.close(id=tradeEntryID, comment=closeID, immediately=true) // Close all positions at the end of the backtest period if isBacktestDateRangeOver() strategy.cancel_all() strategy.close_all(comment="Date Range Exit") // Display Signals plotshape(series=longEntryHasBeenMet(), title="Primo Buy", style=shape.triangleup, location=location.abovebar, color=buySignalColor, text="Buy", textcolor=buySignalColor) plotshape(series=shortEntryHasBeenMet(), title="Primo Sell", style=shape.triangledown, location=location.belowbar, color=sellSignalColor, text="Sell", textcolor=sellSignalColor)
DCA 220824
https://www.tradingview.com/script/YiFrIUW5-DCA-220824/
Tano5himo
https://www.tradingview.com/u/Tano5himo/
26
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© tanoshimooo //@version=5 strategy ("DCA", initial_capital=44700, overlay=true) // To start script at a given date tz = 0 //timezone timeadj = time + tz * 60 * 60 * 1000 //adjust the time (unix) t1 = timeadj >= timestamp(2003, 03, 01, 0, 0) ? 1 : 0 //get the starting time // Variables var float lastRef = na if barstate.isfirst lastRef := close var float cash = strategy.initial_capital // available money var float sell_contracts = na var bool first_trade_done = false // Parameters var float sell_min = 200 //200 sell more than sell_min or sell all var float buy_dollars = 200 var int bi = 90 // LONGS // if bar_index < bi strategy.order("Long", strategy.long, int(buy_dollars/close)) cash := cash - int(buy_dollars/close)*close // label.new(bar_index, na, na, xloc.bar_index, yloc.abovebar, color.blue, label.style_triangleup, color.blue, size.tiny) //plot(cash) // SHORTS // if longExit // if (strategy.position_size*sf*close > sell_min) and (strategy.position_size*sf >= 1) // strategy.order ("Long", strategy.short, strategy.position_size*sf) // cash := cash + strategy.position_size*sf*close // else // strategy.order ("Long", strategy.short, strategy.position_size) // cash := cash + strategy.position_size*close // lastRef := close // label.new(bar_index, na, na, xloc.bar_index, yloc.belowbar, color.red, label.style_triangledown, color.red, size.tiny) if bar_index == last_bar_index - 2 // bi strategy.order ("Long", strategy.short, strategy.position_size)
scalping with market facilitation
https://www.tradingview.com/script/1gV1bg3k-scalping-with-market-facilitation/
trent777brown
https://www.tradingview.com/u/trent777brown/
125
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© trent777brown //@version=5 strategy("scalping with market facilitation", overlay=true, margin_long=100, margin_short=100) MFI0 = (high - low) / volume MFI1 = (high[1] - low[1]) / volume[1] MFIplus = MFI0 > MFI1 MFIminus = MFI0 < MFI1 //Current Trend-(Changed mean to trend)-revised trendplus = hl2 > high[1] trendzero = hl2 < high[1] and hl2 > low[1] //addition of script trendminus = hl2 < low[1] //changed high to low //Volume +/- volplus = volume > volume[1] volminus = volume < volume[1] //Period Control by Buyers or Sellers is determined with reference to Price action of the period //divided into 3 sectors, sector 1 is the Top third, Sector 2 is the middle third, //and sector 3 is the Bottom third of the period. Control classifications are: Extremes(11, 33), Neutral(22), //Climbers(31,21,32) Open lower than Close, and Drifters(13,23,12)Close lower than Open //value0 = low //value1 = ((high - low)/3) //value2 = ((high - low)/3)*2 //value3 = high //o1 = (open >= (((high - low)/3) * 2) + low) //c1 = (close >= (((high - low)/3) * 2) + low) //o2 = (open <= o1) //c2 = (close <= c1) //o3 = (open <= ((high - low)/3) + low) //c3 = (close <= ((high - low)/3) + low) //sector2 = if((high - low)/3) + low and sector2 <= (((high - low)/3)*2) + low //sector3 = if((high - low)/3) + low and >= low //Extremes-Full Control of Period by Buyers or Sellers //pg79 notes an 85% chance that the current trend will change in the next 1 to 5 bars b11 = open >= (high - low) / 3 * 2 + low and close >= (high - low) / 3 * 2 + low //Extreme Buyer Control:Chartruse b33 = open <= (high - low) / 3 + low and close <= (high - low) / 3 + low //Extreme Seller Control:Crimson //Neutral pg80 b22 = open >= (high - low) / 3 + low and open <= (high - low) / 3 * 2 and close >= (high - low) / 3 + low and open <= (high - low) / 3 * 2 //Bracketed Price Control //Climber-Open lower than Close pg81 b31 = open <= (high - low) / 3 + low and close >= (high - low) / 3 * 2 + low //Strong Buyer Control:Dark Green b21 = open >= (high - low) / 3 + low and open <= (high - low) / 3 * 2 and close >= (high - low) / 3 * 2 + low //Moderate Buyer Control:Green b32 = open <= (high - low) / 3 + low and close >= (high - low) / 3 + low and open <= (high - low) / 3 * 2 //Weak Buyer Control:Light Green //Drifter-Close lower than Open pg81 b13 = open >= (high - low) / 3 * 2 + low and close <= (high - low) / 3 + low //Strong Seller Control:Dark Red b23 = open >= (high - low) / 3 + low and open <= (high - low) / 3 * 2 and close <= (high - low) / 3 + low //Moderate Seller Control:Red b12 = open >= (high - low) / 3 * 2 + low and close >= (high - low) / 3 + low and open <= (high - low) / 3 * 2 //Weak Seller Control:Light Red/Pink // psar= ta.sar(.09, .2, .2) ema8= ta.ema(hlc3, 8) ema13h= ta.ema(high, 13) ema13l= ta.ema(low, 13) ema13= ta.ema(close, 13) ema55= ta.ema(close, 100) [dip, dim, adx]= ta.dmi(8, 8) adxema=ta.wma(adx, 135 ) [macdl, sigl, histl]= ta.macd(close, 8, 13, 5) obv= ta.obv obvema= ta.ema(obv, 8) obvema55= ta.ema(obv, 55) mfigreen= MFIplus and volplus adx_x_over= ta.crossover(adx, adxema) and adx >= 25 barssincemfi= ta.barssince(mfigreen) ema5= ta.ema(close,5) ema35=ta.ema(open,35) wma377= ta.wma(close,377) wma144= ta.wma(close,144) upt= ema5 > ema35 and ema35 > wma144 //wma377 < wma144 and hl2 > wma144 and hl2 > wma377 dwnt= ema5 < ema35 and ema35 < wma144 //wma144 < wma377 and hl2 < wma144 and wma377 > hl2 longtrig2= adxema > 35 and adx < 35 and barssincemfi <= 10 //and adxema > adxema[1] shorttrig2= adxema > 35 and adx < 35 and barssincemfi <= 10 //and adxema > adxema[1] long= macdl > sigl and obv > obvema55 and ema8 > ema55 and psar < low //and trendminus //and ema13l > ema55//and open > hull200 and close > hull200 short= macdl < sigl and obv < obvema55 and ema8 < ema55 and psar > high //and trendplus //and ema13h < ema55//open < hull200 and close < hull200 //plot(hull200, color=color.red, linewidth=3) plot(ema13h, color=color.gray, linewidth=3) plot(ema13l, color=color.gray, linewidth=3) plot(ema13, color=color.blue, linewidth=3) // plot(ema55, color=color.white, linewidth=3) plot(psar, color=color.white, style=plot.style_circles) plotshape(mfigreen, color=color.yellow, style=shape.flag, location=location.belowbar, size= size.tiny) longCondition = upt if (longCondition) strategy.entry("My Long Entry Id", strategy.long, 100000, when= longtrig2) strategy.exit("exit long", "My Long Entry Id", profit= 100, loss= 75) shortCondition = dwnt if (shortCondition) strategy.entry("My Short Entry Id", strategy.short, 100000, when= shorttrig2) strategy.exit("exit short", "My Short Entry Id", profit= 100, loss= 75)
Trend Identifier Strategy
https://www.tradingview.com/script/JbYbhKJh-Trend-Identifier-Strategy/
spacekadet17
https://www.tradingview.com/u/spacekadet17/
107
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/ // Β© spacekadet17 // //@version=5 strategy(title="Trend Identifier Strategy", shorttitle="Trend Identifier Strategy", format=format.price, precision=4, overlay = false, initial_capital = 1000, pyramiding = 10, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, commission_value = 0.03) //start-end time startyear = input.int(2020,"start year") startmonth = input.int(1,"start month") startday = input.int(1,"start day") endyear = input.int(2025,"end year") endmonth = input.int(1,"end month") endday = input.int(1,"end day") timeEnd = time <= timestamp(syminfo.timezone,endyear,endmonth,endday,0,0) timeStart = time >= timestamp(syminfo.timezone,startyear,startmonth,startday,0,0) choosetime = input(false,"Choose Time Interval") condTime = (choosetime ? (timeStart and timeEnd) : true) // time frame? tfc = 1 if timeframe.isdaily tfc := 24 // indicators: price normalized alma, and its 1st and 2nd derivatives ema = ta.alma(close,140,1.1,6) dema = (ema-ema[1])/ema stodema = ta.ema(ta.ema(ta.stoch(dema,dema,dema,100),3),3) d2ema = ta.ema(dema-dema[1],5) stod2ema = ta.ema(ta.ema(ta.stoch(d2ema,d2ema,d2ema,100),3),3) ind = (close-ta.ema(close,120*24/tfc))/close heat = ta.ema(ta.stoch(ind,ind,ind,120*24/tfc),3) index = ta.ema(heat,7*24/tfc) //plot graph green = color.rgb(20,255,100) yellow = color.yellow red = color.red blue = color.rgb(20,120,255) tcolor = (dema>0) and (d2ema>0)? green : (dema>0) and (d2ema<0) ? yellow : (dema < 0) and (d2ema<0) ? red : (dema < 0) and (d2ema>0) ? blue : color.black demaema = ta.ema(dema,21) plot(demaema, color = tcolor) //strategy buy-sell conditions cond1a = strategy.position_size <= 0 cond1b = strategy.position_size > 0 if (condTime and cond1a and ( ( ((tcolor[1] == red and demaema<0.02) or (tcolor[1] == blue and demaema < 0.02) or (tcolor[1] == yellow and demaema>-0.02) ) and tcolor == green) or (tcolor[1] == red and tcolor == blue and demaema < -0.01) ) and index<85 and ind<0.4) strategy.entry("buy",strategy.long, (strategy.equity-strategy.position_size*close)/1/close) if (condTime and cond1b and ( (((tcolor[1] == yellow and demaema > -0.02) or (tcolor[1] == blue and demaema < 0.02) or (tcolor[1] == green and demaema < 0.02)) and tcolor == red) or (tcolor[1] == green and tcolor == yellow and demaema > 0.015) ) and index>15 and ind>-0.1) strategy.order("sell",strategy.short, strategy.position_size)
[Strategy Alert Webhook Demo] Buy One Sell One
https://www.tradingview.com/script/TCsd7tB4-Strategy-Alert-Webhook-Demo-Buy-One-Sell-One/
Crypto-Arsenal
https://www.tradingview.com/u/Crypto-Arsenal/
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/ // Β© Crypto-Arsenal //@version=5 strategy("Buy One Sell One", overlay = false, default_qty_type=strategy.percent_of_equity, default_qty_value=10) CONNECTOR_NAME = 'YOUR_CONNECTOR_NAME' CONNECTOR_TOKEN = 'YOUR_CONNECTOR_TOKEN' percent = str.tostring(10) cls = str.tostring(close) tp = str.tostring(strategy.position_avg_price * (1 + 0.1)) sl = str.tostring(strategy.position_avg_price * (1 - 0.1)) if(bar_index % 2 == 0) // DEMO FOR SENDING MESSAGE WITH alert_message() // NEED TO ADD {{{strategy.order.alert_message}} to Message field at Create Alert box // Add "limit" to open a LIMIT order instead of default MARKET alert_message = '{"action":"openLong","percent":"' + percent + '","profit":"' + tp + '","loss":"' + sl + '","connectorName":"' + CONNECTOR_NAME + '","connectorToken":"' + CONNECTOR_TOKEN + '","log":"Open Long at price:' + cls + '"}' strategy.entry('Enter Long', strategy.long, alert_message = alert_message) else // DEMO FOR SENDING MESSAGE WITH alert() strategy.entry('Enter Short', strategy.short) // Add "limit" to open a LIMIT order instead of default MARKET alert_message = '{"action":"closeLong","percent":"' + percent + '","profit":"' + sl + '","loss":"' + tp + '","connectorName":"' + CONNECTOR_NAME + '","connectorToken":"' + CONNECTOR_TOKEN + '","log":"Close long at price:' + cls + '"}' alert(alert_message, alert.freq_once_per_bar)
V Bottom & V Top Pattern [Misu]
https://www.tradingview.com/script/6qmzhNzi-V-Bottom-V-Top-Pattern-Misu/
Fontiramisu
https://www.tradingview.com/u/Fontiramisu/
1,449
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Author : @Fontiramisu // @version=5 strategy("V Bottom/Top Pattern [Misu]", shorttitle="V pattern [Misu]", overlay=true, initial_capital=50000, default_qty_type=strategy.percent_of_equity, default_qty_value=100) // import Fontiramisu/fontLib/80 as fontilab import Fontiramisu/fontilab/8 as fontilab // -------- Find dev pivots ---------- [ // -- Var user input -- var devTooltip = "Deviation is a multiplier that affects how much the price should deviate from the previous pivot in order for the bar to become a new pivot." var depthTooltip = "The minimum number of bars that will be taken into account when analyzing pivots." thresholdMultiplier = input.float(title="Deviation", defval=3.1, step=0.1, minval=0, tooltip=devTooltip, group="Pivot") depth = input.int(title="Depth", defval=8, minval=1, tooltip=depthTooltip, group="Pivot") // Prepare pivot variables var line lineLast = na var int iLast = 0 // Index last var int iPrev = 0 // Index previous var float pLast = 0 // Price last var float pLastHigh = 0 // Price last var float pLastLow = 0 // Price last var isHighLast = false // If false then the last pivot was a pivot low isPivotUpdate = false // Get pivot information from dev pivot finding function [dupLineLast, dupIsHighLast, dupIPrev, dupILast, dupPLast, dupPLastHigh, dupPLastLow] = fontilab.getDeviationPivots(thresholdMultiplier, depth, lineLast, isHighLast, iLast, pLast, true, close, high, low) if not na(dupIsHighLast) lineLast := dupLineLast isHighLast := dupIsHighLast iPrev := dupIPrev iLast := dupILast pLast := dupPLast pLastHigh := dupPLastHigh pLastLow := dupPLastLow isPivotUpdate := true // Plot. // Get last Pivots. var highP = 0.0 var lowP = 0.0 var midP = 0.0 highP := isHighLast ? pLast : highP lowP := not isHighLast ? pLast : lowP midP := (highP + lowP)/2 // ] -------- Input Vars --------------- [. breakoutTypeConf = input.string("Mid Pivot", title="Confirmation Type", options=["At First Break", "Mid Pivot", "Opposit Pivot", "No Confirmation"], group="Signal Type Confirmation") lenghtSizeAvgBody = input.int(9, title="Lenght Avg Body", group="Breakouts Settings") firstBreakoutFactor = input.float(0.2, step=0.1, title="First Breakout Factor", tooltip="Factor used to validate the first breakout of the V pattern", group="Breakouts Settings") confBreakoutFactor = input.float(1.2, step=0.1, title="Confirmation Breakout Factor", tooltip="Factor used to validate the confirmation breakout of the V pattern", group="Breakouts Settings") maxNbBarsValidV = input.int(11, title="Max Bars Confirmation", group="Timing Confirmation") // ] -------- Logical Vars ------------- [ var _isVbottomPot = false var _isVtopPot = false _isVbottom = false _isVtop = false lastLow = 0.0 indexLow = 0 lastHigh = 0.0 indexHigh = 0 // Confirm V pattern vars. var lHighVtopPot = 0.0 var lLowVbotPot = 0.0 var nbBarLVtopPot = 0 var nbBarLVbotPot = 0 var breakLevelVbotPot = 0.0 var breakLevelVtopPot = 0.0 // ] -------- Util Functions ----------- [ // Cond Vars. _bodyHi = math.max(close, open) _bodyLo = math.min(close, open) _body = _bodyHi - _bodyLo _bodyAvg = ta.ema(_body, lenghtSizeAvgBody) _longBody = _body > _bodyAvg _upperWick = high - _bodyHi _greenBody = open < close _redBody = open > close // COND: Potential V pattern. _breakAboveLowP = ta.crossover(close, lowP) and _body > _bodyAvg * firstBreakoutFactor _breakUnderHighP = ta.crossunder(close, highP) and _body > _bodyAvg * firstBreakoutFactor // Crossing Vars. breakLevelVbotPot := ta.crossunder(close, lowP) ? lowP : breakLevelVbotPot breakLevelVtopPot := ta.crossover(close, highP) ? highP : breakLevelVtopPot // @function to get last high/low (handle multiple rsiOver in a row) getIndexHighLowFromNbCandles(bool isLong, int nbCandles) => highLow = isLong ? low : high indexHighLows = 0 // indexHighLow = 0 for counter = 1 to nbCandles + 10 if isLong if low[counter] < highLow highLow := low[counter] indexHighLows := counter else if high[counter] > highLow highLow := high[counter] indexHighLows := counter indexHighLows isWickCrossPattern (src, isCrossUp) => isCross = false if isCrossUp isCross := _bodyHi < src and src < high else isCross := low < src and src < _bodyLo isCross getBreakoutTypeConf(type, isVtop) => switch type "No Confirmation" => isVtop ? highP : lowP "Opposit Pivot" => isVtop ? lowP : highP "Mid Pivot" => midP "At First Break" => isVtop ? breakLevelVtopPot : breakLevelVbotPot isPivotChanged (oldMidP) => midP != oldMidP // ] -------- Logical Script ----------- [ // ----- // Calculate. lastLowDup = fontilab.getHighLowFromNbCandles(true, 10) indexLowDup = getIndexHighLowFromNbCandles(true, 10) lastHighDup = fontilab.getHighLowFromNbCandles(false, 10) indexHighDup = getIndexHighLowFromNbCandles(false, 10) if _breakAboveLowP lastLow := lastLowDup indexLow := indexLowDup _isVbottomPot := true lLowVbotPot := lastLow else if _breakUnderHighP lastHigh := lastHighDup indexHigh := indexHighDup _isVtopPot := true lHighVtopPot := lastHigh // Confirm potential V bot pattern. isBreakBarAvg = breakoutTypeConf != "No Confirmation" ? _body > _bodyAvg * confBreakoutFactor : true vBotConfSrc = getBreakoutTypeConf(breakoutTypeConf, false) _isVbottom := _isVbottomPot and ta.crossover(close, vBotConfSrc) and isBreakBarAvg if _isVbottomPot // Cond V pot invalidated or finished. if not _isVbottom and low >= lLowVbotPot and nbBarLVbotPot <= maxNbBarsValidV nbBarLVbotPot := nbBarLVbotPot + 1 else _isVbottomPot := false nbBarLVbotPot := 0 // Confirm potential V top pattern. vTopConfSrc = getBreakoutTypeConf(breakoutTypeConf, true) _isVtop := _isVtopPot and ta.crossunder(close, vTopConfSrc) and isBreakBarAvg if _isVtopPot // Cond V pot invalidated or finished. if not _isVtop and high <= lHighVtopPot and nbBarLVtopPot <= maxNbBarsValidV nbBarLVtopPot := nbBarLVtopPot + 1 else // reinit for next V patter. _isVtopPot := false nbBarLVtopPot := 0 // ----- // BUY / SELL COND. buyCond = _isVbottom sellCond = _isVtop // ] -------- Strategy Part ------------ [ // if buyCond // strategy.entry("L", strategy.long, alert_message="Buy Signal") // if sellCond // strategy.entry("S", strategy.short, alert_message="Sell Signal") // ] -------- Plot Part & Alerts ------- [ midPPlot = plot(midP, title='Mid Pivot', linewidth=1, color=color.yellow, display=display.none) highPlot = plot(highP, title='High Pivot', linewidth=1, color=color.red, display=display.none) lowPlot = plot(lowP, title='Low Pivot', linewidth=1, color=color.green, display=display.none) distLabel = ta.atr(30) * 0.2 if buyCond label.new(x = bar_index, y = low - distLabel, xloc = xloc.bar_index, text = "V", style = label.style_label_up, color = color.green, size = size.small, textcolor = color.white, textalign = text.align_center) else if sellCond label.new(x = bar_index, y = high + distLabel, xloc = xloc.bar_index, text = "V", style = label.style_label_down, color = color.red, size = size.small, textcolor = color.white, textalign = text.align_center) if _breakAboveLowP label.new(x = bar_index - indexLowDup, y = low[indexLowDup] - distLabel, xloc = xloc.bar_index, text = "Vp", style = label.style_label_up, color = color.new(color.green, 70), size = size.small, textcolor = color.white, textalign = text.align_center) else if _breakUnderHighP label.new(x = bar_index - indexHighDup, y = high[indexHighDup] + distLabel, xloc = xloc.bar_index, text = "Vp", style = label.style_label_down, color = color.new(color.red, 70), size = size.small, textcolor = color.white, textalign = text.align_center)
Monthly Returns of a Strategy in a Chart
https://www.tradingview.com/script/JGhLPNVi-Monthly-Returns-of-a-Strategy-in-a-Chart/
QuantNomad
https://www.tradingview.com/u/QuantNomad/
264
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/ // Β© QuantNomad //@version=5 strategy("Monthly Returns in a Chart", overlay = true, default_qty_type = strategy.percent_of_equity, default_qty_value = 25, calc_on_every_tick = true, commission_type = strategy.commission.percent, commission_value = 0.1) // |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++| // | INPUTS | // |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++| leftBars = input.int(2, title = "Left Bars" ) rightBars = input.int(1, title = "Right Bars") prec = input.int(2, title = "Precision" ) // Plot Location inPlotPos = input.string(title="Plot Location", defval= "Bottom Center", options =["Top Right" , "Middle Right" , "Bottom Right" , "Top Center", "Middle Center", "Bottom Center", "Top Left" , "Middle Left" , "Bottom Left" ], group= "Plot Setting") // Bar Size barHigh = input.float(0.3, "Bar Height", minval = 0.2, step= 0.01, group = "Plot Setting") barWdth = input.float(1.15, "Bar Width" , minval = 1, step= 0.01, group = "Plot Setting") // Plot Color pltCol = input.color(#696969, title="Background ", group = "Plot Setting", inline = "1") borCol = input.color(color.silver, title="Border   ", group = "Plot Setting", inline = "2") txtCol = input.color(color.white, title="Text    ", group = "Plot Setting", inline = "3") // Bar Color posCol = input.color(color.green, title=" UP  ", group = "Plot Setting", inline = "1") negCol = input.color(color.red, title=" DOWN", group = "Plot Setting", inline = "2") // |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++| // | CALCULATION | // |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++| // +++++++++++++++++++++++++++++++++++ STRATEGY // Pivot Points swh = ta.pivothigh(leftBars, rightBars) swl = ta.pivotlow(leftBars, rightBars) hprice = 0.0 hprice := not na(swh) ? swh : hprice[1] lprice = 0.0 lprice := not na(swl) ? swl : lprice[1] le = false le := not na(swh) ? true : (le[1] and high > hprice ? false : le[1]) se = false se := not na(swl) ? true : (se[1] and low < lprice ? false : se[1]) if (le) strategy.entry("PivRevLE", strategy.long, comment="PivRevLE", stop=hprice + syminfo.mintick) if (se) strategy.entry("PivRevSE", strategy.short, comment="PivRevSE", stop=lprice - syminfo.mintick) plot(hprice, color = color.green, linewidth = 2) plot(lprice, color = color.red, linewidth = 2) // +++++++++++++++++++++++++++++++++++ OUTPUT ARRAY new_month = month(time) != month(time[1]) bar_pnl = strategy.equity / strategy.equity[1] - 1 cur_month_pnl = 0.0 // Current Monthly P&L cur_month_pnl := new_month ? 0.0 : (1 + cur_month_pnl[1]) * (1 + bar_pnl) - 1 // Arrays to store Yearly and Monthly P&Ls var month_pnl = array.new_float(0) var month_time = array.new_int(0) last_computed = false if (not na(cur_month_pnl[1]) and (new_month or barstate.islast)) if (last_computed[1]) array.pop(month_pnl) array.pop(month_time) array.push(month_pnl , 100 * cur_month_pnl[1]) array.push(month_time, time[1]) last_computed := barstate.islast ? true : nz(last_computed[1]) if array.size(month_pnl) > 71 array.shift(month_pnl) array.shift(month_time) // Find the Maximum Number for Plot Scale scalCoef = 32/math.max(math.abs(array.min(month_pnl)), math.abs(array.max(month_pnl))) // |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++| // | TABLE | // |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++| // Get months Name monNme(m) => mnth = array.from("JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC") array.get(mnth, m-1) // Get Table Position pltPos(p) => switch p "Top Right" => position.top_right "Middle Right" => position.middle_right "Bottom Right" => position.bottom_right "Top Center" => position.top_center "Middle Center" => position.middle_center "Bottom Center" => position.bottom_center "Top Left" => position.top_left "Middle Left" => position.middle_left => position.bottom_left // Find Number of Columns numCol = array.size(month_pnl) * 2 + 2 < 10 ? 10 : array.size(month_pnl) * 2 + 2 // Set Up Plot Table var plt = table.new(position.bottom_left, 1 , 1) plt := table.new(pltPos(inPlotPos), numCol, 69, bgcolor = color.new(pltCol, 50), frame_width = 1, frame_color = borCol, border_width = 0, border_color = color.new(txtCol, 100)) // Plot Cell pltCell (x, y, w, h, col, tt) => table.cell(plt, x, y, width = w, height = h, bgcolor = col) table.cell_set_tooltip(plt, x, y, tt) // Plot Columns pltCol (x, y, k, col, tt) => pltCell(x, y > 0 ? 33 - k : y < 0 ? 35 - k : 33, barWdth, barHigh, color.new(col, 0), tt) pltCell(x, y > 0 ? 35 + k : y < 0 ? 33 + k : 33, barWdth, barHigh, color.new(col, 100), tt) // Label Y-Axis Increments yInc(y, val) => table.cell(plt, 0, y-2, text = str.tostring(val, "#.#"), text_halign = text.align_center, text_valign = text.align_center, text_color = txtCol, text_size = size.small, width = 1.5, height = 0.2) table.merge_cells(plt, 0, y-2, 0, y+2) // Plot Title pltTtl(x, xf, txt, txtCol) => table.cell(plt, x, 0, width = barWdth, height = 2, bgcolor = color.new(color.black, 100), text_halign = text.align_center, text_valign = text.align_top, text = txt, text_color = txtCol, text_size = size.small) table.merge_cells(plt, x, 0, xf, 0) if barstate.islast if array.size(month_pnl) > 0 // Reset Table. for i = 0 to numCol - 1 for j = 0 to 68 pltCell(i, j, 0.001, 0.001, color.new(txtCol, 100), "") w = 0 for i = 1 to array.size(month_pnl) * 2 + 1 if i%2 == 0 barCol = array.get(month_pnl, w) > 0 ? posCol : array.get(month_pnl, w) < 0 ? negCol : borCol //Plot Columns if scalCoef * array.get(month_pnl, w) == 0 pltCol(i, array.get(month_pnl, w), 0, barCol, "") else for k = 0 to math.round(scalCoef * array.get(month_pnl, w)) pltCol(i, array.get(month_pnl, w), k, barCol, str.tostring(math.round(array.get(month_pnl, w), prec)) + "\n" + monNme(month(array.get(month_time, w))) + "-" + str.tostring(year(array.get(month_time, w)))) // X-Axis Increments table.cell(plt, i, 68, width = barWdth, text_color = txtCol, text = monNme(month(array.get(month_time, w))) + "\n" + str.tostring(year(array.get(month_time, w)) - 2000), text_size = size.tiny) table.merge_cells(plt, i, 68, i+1, 68) w := w + 1 else for j = 0 to 68 pltCell(i, j, 0.05, 0.001, color.new(pltCol, 94), "") if i >= 2 and i <= array.size(month_pnl) * 2 pltCell(i, 34, 0.05, 0.005, borCol, "") // Y-Axis Increments table.cell(plt, 0, 1, width = barWdth, height = 1) yInc( 2, math.ceil( 32/scalCoef)) yInc(18, math.round(16/scalCoef)) yInc(34, 0/scalCoef) yInc(49, math.round(-16/scalCoef)) yInc(66, math.floor(-32/scalCoef)) // Title pltTtl( 1, 8, "Monthly P&L", txtCol)
Ichimoku Cloud with ADX (By Coinrule)
https://www.tradingview.com/script/je5bIJeR-Ichimoku-Cloud-with-ADX-By-Coinrule/
Coinrule
https://www.tradingview.com/u/Coinrule/
145
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© Coinrule //@version=5 strategy('Ichimoku Cloud with ADX (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) showDate = input(defval=true, title='Show Date Range') timePeriod = time >= timestamp(syminfo.timezone, 2022, 1, 1, 0, 0) // Stop Loss and Take Profit for Shorting Stop_loss = input(1) / 100 Take_profit = input(5) / 100 longStopPrice = strategy.position_avg_price * (1 - Stop_loss) longTakeProfit = strategy.position_avg_price * (1 + Take_profit) // Inputs ts_bars = input.int(9, minval=1, title='Tenkan-Sen Bars') ks_bars = input.int(26, minval=1, title='Kijun-Sen Bars') ssb_bars = input.int(52, minval=1, title='Senkou-Span B Bars') cs_offset = input.int(26, minval=1, title='Chikou-Span Offset') ss_offset = input.int(26, minval=1, title='Senkou-Span Offset') long_entry = input(true, title='Long Entry') short_entry = input(true, title='Short Entry') middle(len) => math.avg(ta.lowest(len), ta.highest(len)) // Ichimoku Components tenkan = middle(ts_bars) kijun = middle(ks_bars) senkouA = math.avg(tenkan, kijun) senkouB = middle(ssb_bars) // Plot Ichimoku Kinko Hyo plot(tenkan, color=color.new(#0496ff, 0), title='Tenkan-Sen') plot(kijun, color=color.new(#991515, 0), title='Kijun-Sen') plot(close, offset=-cs_offset + 1, color=color.new(#459915, 0), title='Chikou-Span') sa = plot(senkouA, offset=ss_offset - 1, color=color.new(color.green, 0), title='Senkou-Span A') sb = plot(senkouB, offset=ss_offset - 1, color=color.new(color.red, 0), title='Senkou-Span B') fill(sa, sb, color=senkouA > senkouB ? color.green : color.red, title='Cloud color', transp=90) ss_high = math.max(senkouA[ss_offset - 1], senkouB[ss_offset - 1]) ss_low = math.min(senkouA[ss_offset - 1], senkouB[ss_offset - 1]) // ADX [pos_dm, neg_dm, avg_dm] = ta.dmi(14, 14) // Entry/Exit Signals tk_cross_bull = tenkan > kijun tk_cross_bear = tenkan < kijun cs_cross_bull = ta.mom(close, cs_offset - 1) > 0 cs_cross_bear = ta.mom(close, cs_offset - 1) < 0 price_above_kumo = close > ss_high price_below_kumo = close < ss_low bullish = tk_cross_bull and cs_cross_bull and price_above_kumo and avg_dm < 45 and pos_dm > neg_dm bearish = tk_cross_bear and cs_cross_bear and price_below_kumo and avg_dm > 45 and pos_dm < neg_dm strategy.entry('Long', strategy.long, when=bullish and long_entry and timePeriod) strategy.close('Long', when=bearish and not short_entry) strategy.entry('Short', strategy.short, when=bearish and short_entry and timePeriod) strategy.close('Short', when=bullish and not long_entry)
Ichimoku Cloud and Bollinger Bands (by Coinrule)
https://www.tradingview.com/script/gV8mo1Vj-Ichimoku-Cloud-and-Bollinger-Bands-by-Coinrule/
Coinrule
https://www.tradingview.com/u/Coinrule/
145
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© Coinrule //@version=5 strategy("Ichimoku Cloud and Bollinger Bands", overlay=true, initial_capital=1000, process_orders_on_close=true, default_qty_type=strategy.percent_of_equity, default_qty_value=30, commission_type=strategy.commission.percent, commission_value=0.1) showDate = input(defval=true, title='Show Date Range') timePeriod = time >= timestamp(syminfo.timezone, 2022, 1, 1, 0, 0) notInTrade = strategy.position_size <= 0 //Ichimoku Cloud //Inputs ts_bars = input.int(9, minval=1, title="Tenkan-Sen Bars") ks_bars = input.int(26, minval=1, title="Kijun-Sen Bars") ssb_bars = input.int(52, minval=1, title="Senkou-Span B Bars") cs_offset = input.int(26, minval=1, title="Chikou-Span Offset") ss_offset = input.int(26, minval=1, title="Senkou-Span Offset") long_entry = input(true, title="Long Entry") short_entry = input(true, title="Short Entry") middle(len) => math.avg(ta.lowest(len), ta.highest(len)) // Components of Ichimoku Cloud tenkan = middle(ts_bars) kijun = middle(ks_bars) senkouA = math.avg(tenkan, kijun) senkouB = middle(ssb_bars) // Plot Ichimoku Cloud plot(tenkan, color=#0496ff, title="Tenkan-Sen") plot(kijun, color=#991515, title="Kijun-Sen") plot(close, offset=-cs_offset+1, color=#459915, title="Chikou-Span") sa=plot(senkouA, offset=ss_offset-1, color=color.green, title="Senkou-Span A") sb=plot(senkouB, offset=ss_offset-1, color=color.red, title="Senkou-Span B") fill(sa, sb, color = senkouA > senkouB ? color.green : color.red, title="Cloud color") ss_high = math.max(senkouA[ss_offset-1], senkouB[ss_offset-1]) ss_low = math.min(senkouA[ss_offset-1], senkouB[ss_offset-1]) // Entry/Exit Conditions tk_cross_bull = tenkan > kijun tk_cross_bear = tenkan < kijun cs_cross_bull = ta.mom(close, cs_offset-1) > 0 cs_cross_bear = ta.mom(close, cs_offset-1) < 0 price_above_kumo = close > ss_high price_below_kumo = close < ss_low //Bollinger Bands Indicator length = input.int(20, minval=1) src = input(close, title="Source") mult = input.float(2.0, minval=0.001, maxval=50, title="StdDev") basis = ta.sma(src, length) dev = mult * ta.stdev(src, length) upper = basis + dev lower = basis - dev offset = input.int(0, "Offset", minval = -500, maxval = 500) plot(basis, "Basis", color=#FF6D00, offset = offset) p1 = plot(upper, "Upper", color=#2962FF, offset = offset) p2 = plot(lower, "Lower", color=#2962FF, offset = offset) fill(p1, p2, title = "Background", color=color.rgb(33, 150, 243, 95)) bullish = tk_cross_bull and cs_cross_bull and price_above_kumo and ta.crossover(lower, close) bearish = tk_cross_bear and cs_cross_bear and price_below_kumo and ta.crossover(close, lower) strategy.entry('Long', strategy.long, when=bullish and long_entry and timePeriod) strategy.close('Long', when=bearish and not short_entry) strategy.entry('Short', strategy.short, when=bearish and short_entry and timePeriod) strategy.close('Short', when=bullish and not long_entry) //Works well on BTC 30m/1h (11.29%), ETH 2h (29.05%), MATIC 2h/30m (37.12%), AVAX 1h/2h (49.2%), SOL 45m (45.43%)
PlanB Quant Investing 101 v2
https://www.tradingview.com/script/Tz02ikOo-PlanB-Quant-Investing-101-v2/
fillippone
https://www.tradingview.com/u/fillippone/
590
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/ // Β© fillippone //@version=4 strategy("PlanB Quant Investing 101", shorttitle="PlanB RSI Strategy", overlay=true,calc_on_every_tick=false,pyramiding=0, default_qty_type=strategy.cash,default_qty_value=1000, currency=currency.USD, initial_capital=1000,commission_type=strategy.commission.percent, commission_value=0.0) r=rsi(close,14) //SELL CONDITION //RSI was above 90% last six months AND drops below 65% //RSI above 90% last six month selllevel = input(90) maxrsi = highest(rsi(close,14),6)[1] rsisell = maxrsi > selllevel //RSIdrops below 65% drop = input(65) rsidrop= r < drop //sellsignal sellsignal = rsisell and rsidrop //BUY CONDITION //IF (RSI was below 50% last six months AND jumps +2% from the low) THEN buy, ELSE hold. //RSI was below 50% last six months buylevel = input(50) minrsi = lowest(rsi(close,14),6)[1] rsibuy = minrsi < buylevel //IF (RSI jumps +2% from the low) THEN buy, ELSE hold. rsibounce= r > (minrsi + 2) //buysignal=buyrsi AND rsidrop //buysignal buysignal = rsibuy and rsibounce //Strategy strategy.entry("Buy Signal",strategy.long, when = buysignal) strategy.entry("Sell Signal",strategy.short, when = sellsignal)
MAConverging + QQE Threshold
https://www.tradingview.com/script/ZxEf7uJX-MAConverging-QQE-Threshold/
Trade_Domination
https://www.tradingview.com/u/Trade_Domination/
62
strategy
5
CC-BY-NC-SA-4.0
// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/ // Β© Salman4sgd //@version=5 strategy("MAConverging + QQE Threshold Strategy", overlay = true) //------------------------------------------------------------------------------ //Settings //-----------------------------------------------------------------------------{ length = input(100) incr = input(10, "Increment") fast = input(10) src = input(close) //-----------------------------------------------------------------------------} //Calculations //-----------------------------------------------------------------------------{ var ma = 0. var fma = 0. var alpha = 0. var k = 1 / incr upper = ta.highest(length) lower = ta.lowest(length) init_ma = ta.sma(src, length) cross = ta.cross(src,ma) alpha := cross ? 2 / (length + 1) : src > ma and upper > upper[1] ? alpha + k : src < ma and lower < lower[1] ? alpha + k : alpha ma := nz(ma[1] + alpha[1] * (src - ma[1]), init_ma) fma := nz(cross ? math.avg(src, fma[1]) : src > ma ? math.max(src, fma[1]) + (src - fma[1]) / fast : math.min(src, fma[1]) + (src - fma[1]) / fast,src) //-----------------------------------------------------------------------------} //Plots //-----------------------------------------------------------------------------{ css = fma > ma ? color.teal : color.red plot0 = plot(fma, "Fast MA" , color = #ff5d00 , transp = 100) plot1 = plot(ma, "Converging MA" , color = css) fill(plot0, plot1, css , "Fill" , transp = 80) //-----------------------------------------------------------------------------} RSI_Period = input(14, title='RSI Length') SF = input(5, title='RSI Smoothing') QQE = input(4.238, title='Fast QQE Factor') ThreshHold = input(10, title='Thresh-hold') // sQQEx = input(false, title='Show Smooth RSI, QQE Signal crosses') sQQEz = input(false, title='Show Smooth RSI Zero crosses') sQQEc = input(false, title='Show Smooth RSI Thresh Hold Channel Exits') ma_type = input.string(title='MA Type', defval='EMA', options=['ALMA', 'EMA', 'DEMA', 'TEMA', 'WMA', 'VWMA', 'SMA', 'SMMA', 'HMA', 'LSMA', 'PEMA']) lsma_offset = input.int(defval=0, title='* Least Squares (LSMA) Only - Offset Value', minval=0) alma_offset = input.float(defval=0.85, title='* Arnaud Legoux (ALMA) Only - Offset Value', minval=0, step=0.01) alma_sigma = input.int(defval=6, title='* Arnaud Legoux (ALMA) Only - Sigma Value', minval=0) inpDrawBars = input(true, title='color bars?') ma(type, src, len) => float result = 0 if type == 'SMA' // Simple result := ta.sma(src, len) result if type == 'EMA' // Exponential result := ta.ema(src, len) result if type == 'DEMA' // Double Exponential e = ta.ema(src, len) result := 2 * e - ta.ema(e, len) result if type == 'TEMA' // Triple Exponential e = ta.ema(src, len) result := 3 * (e - ta.ema(e, len)) + ta.ema(ta.ema(e, len), len) result if type == 'WMA' // Weighted result := ta.wma(src, len) result if type == 'VWMA' // Volume Weighted result := ta.vwma(src, len) result if type == 'SMMA' // Smoothed w = ta.wma(src, len) result := na(w[1]) ? ta.sma(src, len) : (w[1] * (len - 1) + src) / len result if type == 'HMA' // Hull result := ta.wma(2 * ta.wma(src, len / 2) - ta.wma(src, len), math.round(math.sqrt(len))) result if type == 'LSMA' // Least Squares result := ta.linreg(src, len, lsma_offset) result if type == 'ALMA' // Arnaud Legoux result := ta.alma(src, len, alma_offset, alma_sigma) result if type == 'PEMA' // Copyright (c) 2010-present, Bruno Pio // Copyright (c) 2019-present, Alex Orekhov (everget) // Pentuple Exponential Moving Average script may be freely distributed under the MIT license. ema1 = ta.ema(src, len) ema2 = ta.ema(ema1, len) ema3 = ta.ema(ema2, len) ema4 = ta.ema(ema3, len) ema5 = ta.ema(ema4, len) ema6 = ta.ema(ema5, len) ema7 = ta.ema(ema6, len) ema8 = ta.ema(ema7, len) pema = 8 * ema1 - 28 * ema2 + 56 * ema3 - 70 * ema4 + 56 * ema5 - 28 * ema6 + 8 * ema7 - ema8 result := pema result result src := input(close, title='RSI Source') // // Wilders_Period = RSI_Period * 2 - 1 Rsi = ta.rsi(src, RSI_Period) RsiMa = ma(ma_type, Rsi, SF) AtrRsi = math.abs(RsiMa[1] - RsiMa) MaAtrRsi = ma(ma_type, AtrRsi, Wilders_Period) dar = ma(ma_type, MaAtrRsi, Wilders_Period) * QQE longband = 0.0 shortband = 0.0 trend = 0 DeltaFastAtrRsi = dar RSIndex = RsiMa newshortband = RSIndex + DeltaFastAtrRsi newlongband = RSIndex - DeltaFastAtrRsi longband := RSIndex[1] > longband[1] and RSIndex > longband[1] ? math.max(longband[1], newlongband) : newlongband shortband := RSIndex[1] < shortband[1] and RSIndex < shortband[1] ? math.min(shortband[1], newshortband) : newshortband cross_1 = ta.cross(longband[1], RSIndex) trend := ta.cross(RSIndex, shortband[1]) ? 1 : cross_1 ? -1 : nz(trend[1], 1) FastAtrRsiTL = trend == 1 ? longband : shortband // // Find all the QQE Crosses QQExlong = 0 QQExlong := nz(QQExlong[1]) QQExshort = 0 QQExshort := nz(QQExshort[1]) QQExlong := sQQEx and FastAtrRsiTL < RSIndex ? QQExlong + 1 : 0 QQExshort := sQQEx and FastAtrRsiTL > RSIndex ? QQExshort + 1 : 0 // Zero cross QQEzlong = 0 QQEzlong := nz(QQEzlong[1]) QQEzshort = 0 QQEzshort := nz(QQEzshort[1]) QQEzlong := sQQEz and RSIndex >= 50 ? QQEzlong + 1 : 0 QQEzshort := sQQEz and RSIndex < 50 ? QQEzshort + 1 : 0 // // Thresh Hold channel Crosses give the BUY/SELL alerts. QQEclong = 0 QQEclong := nz(QQEclong[1]) QQEcshort = 0 QQEcshort := nz(QQEcshort[1]) QQEclong := sQQEc and RSIndex > 50 + ThreshHold ? QQEclong + 1 : 0 QQEcshort := sQQEc and RSIndex < 50 - ThreshHold ? QQEcshort + 1 : 0 // // QQE exit from Thresh Hold Channel // plotshape(sQQEc and QQEclong == 1 ? RsiMa - 50 : na, title='QQE XC Over Channel', style=shape.diamond, location=location.absolute, color=color.new(color.olive, 0), size=size.small, offset=0) // plotshape(sQQEc and QQEcshort == 1 ? RsiMa - 50 : na, title='QQE XC Under Channel', style=shape.diamond, location=location.absolute, color=color.new(color.red, 0), size=size.small, offset=0) // // QQE crosses // plotshape(sQQEx and QQExlong == 1 ? FastAtrRsiTL[1] - 50 : na, title='QQE XQ Cross Over', style=shape.circle, location=location.absolute, color=color.new(color.lime, 0), size=size.small, offset=-1) // plotshape(sQQEx and QQExshort == 1 ? FastAtrRsiTL[1] - 50 : na, title='QQE XQ Cross Under', style=shape.circle, location=location.absolute, color=color.new(color.blue, 0), size=size.small, offset=-1) // // Signal crosses zero line // plotshape(sQQEz and QQEzlong == 1 ? RsiMa - 50 : na, title='QQE XZ Zero Cross Over', style=shape.square, location=location.absolute, color=color.new(color.aqua, 0), size=size.small, offset=0) // plotshape(sQQEz and QQEzshort == 1 ? RsiMa - 50 : na, title='QQE XZ Zero Cross Under', style=shape.square, location=location.absolute, color=color.new(color.fuchsia, 0), size=size.small, offset=0) // hcolor = RsiMa - 50 > ThreshHold ? color.green : RsiMa - 50 < 0 - ThreshHold ? color.red : color.orange // plot(FastAtrRsiTL - 50, color=color.new(color.blue, 0), linewidth=2) // p1 = plot(RsiMa - 50, color=color.new(color.orange, 0), linewidth=2) // plot(RsiMa - 50, color=hcolor, style=plot.style_columns, transp=50) // hZero = hline(0, color=color.black, linestyle=hline.style_dashed, linewidth=1) // hUpper = hline(ThreshHold, color=color.green, linestyle=hline.style_dashed, linewidth=2) // hLower = hline(0 - ThreshHold, color=color.red, linestyle=hline.style_dashed, linewidth=2) // fill(hUpper, hLower, color=color.new(color.gray, 80)) //EOF length := input.int(title='ATR Length', defval=14, minval=1) smoothing = input.string(title='ATR Smoothing', defval='RMA', options=['RMA', 'SMA', 'EMA', 'WMA']) m = input(0.3, 'ATR Multiplier') src1 = input(high) src2 = input(low) pline = input(true, 'Show Price Lines') col1 = input(color.blue, 'ATR Text Color') col2 = input.color(color.teal, 'Low Text Color', inline='1') col3 = input.color(color.red, 'High Text Color', inline='2') collong = input.color(color.teal, 'Low Line Color', inline='1') colshort = input.color(color.red, 'High Line Color', inline='2') ma_function(source, length) => if smoothing == 'RMA' ta.rma(source, length) else if smoothing == 'SMA' ta.sma(source, length) else if smoothing == 'EMA' ta.ema(source, length) else ta.wma(source, length) a = ma_function(ta.tr(true), length) * m s_sl = ma_function(ta.tr(true), length) * m + src1 l_sl = src2 - ma_function(ta.tr(true), length) * m p1 = plot(s_sl, title='ATR Short Stop Loss', color=colshort, trackprice=pline ? true : false, transp=20) p2 = plot(l_sl, title='ATR Long Stop Loss', color=collong, trackprice=pline ? true : false, transp=20) bgc = RsiMa - 50 > ThreshHold ? color.green : Rsi - 50 < 0 - ThreshHold ? color.red : color.orange barcolor(inpDrawBars ? bgc : na) prebuy = RsiMa - 50 > ThreshHold buy=prebuy and not(prebuy[1]) and fma > ma var long_tp=0.0 var long_sl=0.0 var short_tp=0.0 var short_sl=0.0 if prebuy strategy.close("Short") if buy and strategy.position_size<=0 strategy.entry("Long", strategy.long) long_sl:=l_sl long_tp:=close+(close-long_sl)*2 //if strategy.position_size>0 strategy.exit("L_SL","Long",stop=long_sl) //strategy.exit("L_SL","Long",stop=long_sl) // if low<long_sl[1] // strategy.close("Long") presell=RsiMa - 50 < 0 - ThreshHold // RsiMa - 50 < 0 - ThreshHold sell= presell and not(presell[1]) and fma < ma //plotshape(presell) if presell strategy.close("Long") if sell and strategy.position_size>=0 strategy.entry("Short", strategy.short) short_sl:=s_sl short_tp:=close-(short_sl-close)*2 //if strategy.position_size<0 strategy.exit("S_SL","Short",stop=short_sl) //strategy.exit("S_SL","Short",stop=short_sl)
MCL-YG Pair Trading Strategy
https://www.tradingview.com/script/AkJn32dK-MCL-YG-Pair-Trading-Strategy/
shark792
https://www.tradingview.com/u/shark792/
16
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© shark792 //@version=5 // 1. Define strategy settings strategy(title="MCL-YG Pair Trading Strategy", overlay=true, pyramiding=0, initial_capital=10000, commission_type=strategy.commission.cash_per_order, commission_value=4, slippage=2) smaLength = input.int(title="SMA Length", defval=20) stdLength = input.int(title="StdDev Length", defval=20) ubOffset = input.float(title="Upper Band Offset", defval=1, step=0.5) lbOffset = input.float(title="Lower Band Offset", defval=1, step=0.5) usePosSize = input.bool(title="Use Position Sizing?", defval=true) riskPerc = input.float(title="Risk %", defval=0.5, step=0.25) // 2. Calculate strategy values smaValue = ta.sma(close, smaLength) stdDev = ta.stdev(close, stdLength) upperBand = smaValue + (stdDev * ubOffset) lowerBand = smaValue - (stdDev * lbOffset) riskEquity = (riskPerc / 100) * strategy.equity atrCurrency = (ta.atr(20) * syminfo.pointvalue) posSize = usePosSize ? math.floor(riskEquity / atrCurrency) : 1 // 3. Output strategy data plot(series=smaValue, title="SMA", color=color.teal) plot(series=upperBand, title="UB", color=color.green, linewidth=2) plot(series=lowerBand, title="LB", color=color.red, linewidth=2) // 4. Determine long trading conditions enterLong = ta.crossover(close, upperBand) exitLong = ta.crossunder(close, smaValue) // 5. Code short trading conditions enterShort = ta.crossunder(close, lowerBand) exitShort = ta.crossover(close, smaValue) // 6. Submit entry orders if enterLong strategy.entry(id="EL", direction=strategy.long, qty=posSize) if enterShort strategy.entry(id="ES", direction=strategy.short, qty=posSize) // 7. Submit exit orders strategy.close(id="EL", when=exitLong) strategy.close(id="ES", when=exitShort)
Ichimoku Cloud with MACD (By Coinrule)
https://www.tradingview.com/script/DtsAIRvK-Ichimoku-Cloud-with-MACD-By-Coinrule/
Coinrule
https://www.tradingview.com/u/Coinrule/
182
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© Coinrule //@version=5 strategy('Ichimoku Cloud with MACD (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) showDate = input(defval=true, title='Show Date Range') timePeriod = time >= timestamp(syminfo.timezone, 2022, 6, 1, 0, 0) // Inputs ts_bars = input.int(9, minval=1, title='Tenkan-Sen Bars') ks_bars = input.int(26, minval=1, title='Kijun-Sen Bars') ssb_bars = input.int(52, minval=1, title='Senkou-Span B Bars') cs_offset = input.int(26, minval=1, title='Chikou-Span Offset') ss_offset = input.int(26, minval=1, title='Senkou-Span Offset') long_entry = input(true, title='Long Entry') short_entry = input(true, title='Short Entry') middle(len) => math.avg(ta.lowest(len), ta.highest(len)) // Ichimoku Components tenkan = middle(ts_bars) kijun = middle(ks_bars) senkouA = math.avg(tenkan, kijun) senkouB = middle(ssb_bars) // Plot Ichimoku Kinko Hyo plot(tenkan, color=color.new(#0496ff, 0), title='Tenkan-Sen') plot(kijun, color=color.new(#991515, 0), title='Kijun-Sen') plot(close, offset=-cs_offset + 1, color=color.new(#459915, 0), title='Chikou-Span') sa = plot(senkouA, offset=ss_offset - 1, color=color.new(color.green, 0), title='Senkou-Span A') sb = plot(senkouB, offset=ss_offset - 1, color=color.new(color.red, 0), title='Senkou-Span B') fill(sa, sb, color=senkouA > senkouB ? color.green : color.red, title='Cloud color', transp=90) ss_high = math.max(senkouA[ss_offset - 1], senkouB[ss_offset - 1]) ss_low = math.min(senkouA[ss_offset - 1], senkouB[ss_offset - 1]) // MACD [macd, macd_signal, macd_histogram] = ta.macd(close, 12, 26, 9) // Entry/Exit Signals tk_cross_bull = tenkan > kijun tk_cross_bear = tenkan < kijun cs_cross_bull = ta.mom(close, cs_offset - 1) > 0 cs_cross_bear = ta.mom(close, cs_offset - 1) < 0 price_above_kumo = close > ss_high price_below_kumo = close < ss_low bullish = tk_cross_bull and cs_cross_bull and price_above_kumo and ta.crossover(macd, macd_signal) bearish = tk_cross_bear and cs_cross_bear and price_below_kumo and ta.crossunder(macd, macd_signal) strategy.entry('Long', strategy.long, when=bullish and long_entry and timePeriod) strategy.close('Long', when=bearish and not short_entry) strategy.entry('Short', strategy.short, when=bearish and short_entry and timePeriod) strategy.close('Short', when=bullish and not long_entry)
Mou Value Areas
https://www.tradingview.com/script/pEsjPihO-Mou-Value-Areas/
moumoose
https://www.tradingview.com/u/moumoose/
34
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© moumoose //@version=4 strategy(title="Mou Value Areas", shorttitle="Mou Value Areas", overlay = true) MA1 = input(21, "Moving Average1 Lenght") MA2 = input(50, "Moving Average2 Lenght") MA3 = input(75, "Moving Average3 Lenght") HL = input(5, "Length", step = 1) MyMA1 = ema(close, MA1) MyMA2 = ema(close, MA2) MyMA3 = ema(close, MA3) plot(MyMA1, title= "EMA1", color=color.blue, linewidth = 2) plot(MyMA2, title="EMA2", color=color.yellow, linewidth = 1) plot(MyMA3, title="EMA3", color=color.red, linewidth = 1) UP = MyMA1[HL] - MyMA2[HL] <= MyMA1 - MyMA2 DOWN = MyMA1[HL] - MyMA2[HL] >= MyMA1 - MyMA2 bgcolor(UP ? color.new(color.red, 85) : na) bgcolor(DOWN ? color.new(color.green, 85) : na) //BULL = close - open > close[1] - open[1] and close > high[1] and DOWN //BEAR = open -close > open[1] - close [1] and close < low[1] and UP //plotshape(BULL, style=shape.arrowup, size = size.large, color = color.green ) //plotshape(BEAR, style=shape.arrowdown, size = size.large, color = color.red)
VIP
https://www.tradingview.com/script/4OYdIrWk-VIP/
imaya_dewmini
https://www.tradingview.com/u/imaya_dewmini/
306
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/ // Β© Darshana_Alwis //@version=5 strategy("VIP", overlay=true, initial_capital=1000,currency=currency.USD,default_qty_type=strategy.percent_of_equity,default_qty_value=100,pyramiding=0) //SSS = Sultan+Saud Strategy //The original idea of the code belonges to saudALThaidy //The strategy code is basically made out of two other indicators, edited and combined by me. // 1- NSDT HAMA Candles => https://www.tradingview.com/script/k7nrF2oI-NSDT-HAMA-Candles/ // 2- SSL Channel => https://www.tradingview.com/script/6y9SkpnV-SSL-Channel/ //MA INFO WickColor = input.color(color.rgb(80, 80, 80, 100), title='Wick Color', tooltip='Suggest Full Transparency.') LengthMA = input.int(100, minval=1, title='MA Line Length', inline='MA Info') TakeProfit = input.float(1, minval=0, title='Take Profit Percentage', step=1) UseStopLose = input.bool(false, title='Use Stop Percentage') StopLose = input.float(1, minval=0, title='StopLose Percentage', step=1) MASource = close ma(source, length, type) => type == "SMA" ? ta.sma(source, length) : type == "EMA" ? ta.ema(source, length) : type == "SMMA (RMA)" ? ta.rma(source, length) : type == "WMA" ? ta.wma(source, length) : type == "VWMA" ? ta.vwma(source, length) : na ma1_color = color.rgb(230, 172, 0) ma1 = ma(high, 200, "SMA") ma2_color = color.red ma2 = ma(low, 200, "SMA") Hlv1 = float(na) Hlv1 := close > ma1 ? 1 : close < ma2 ? -1 : Hlv1[1] sslUp1 = Hlv1 < 0 ? ma2 : ma1 sslDown1 = Hlv1 < 0 ? ma1 : ma2 Color1 = Hlv1 == 1 ? ma1_color : ma2_color fillColor1 = color.new(Color1, 90) highLine1 = plot(sslUp1, title="UP", linewidth=2, color = Color1) lowLine1 = plot(sslDown1, title="DOWN", linewidth=2, color = Color1) OpenLength = 25 HighLength = 20 LowLength = 20 CloseLength = 20 SourceOpen = (open[1] + close[1]) / 2 SourceHigh = math.max(high, close) SourceLow = math.min(low, close) SourceClose = (open + high + low + close) / 4 funcCalcMA1(src1, len1) => ta.ema(src1, len1) funcCalcOpen(SourceOpen, OpenLength) => ta.ema(SourceOpen, OpenLength) funcCalcHigh(SourceHigh, HighLength) => ta.ema(SourceHigh, HighLength) funcCalcLow(SourceLow, LowLength) => ta.ema(SourceLow, LowLength) funcCalcClose(SourceClose, CloseLength) => ta.ema(SourceClose, CloseLength) MA_1 = funcCalcMA1(MASource, LengthMA) CandleOpen = funcCalcOpen(SourceOpen, OpenLength) CandleHigh = funcCalcHigh(SourceHigh, HighLength) CandleLow = funcCalcLow(SourceLow, LowLength) CandleClose = funcCalcClose(SourceClose, CloseLength) //PLOT CANDLES //-------------------------------NSDT HAMA Candels BodyColor = CandleOpen > CandleOpen[1] ? color.rgb(230, 172, 0) : color.red barcolor(BodyColor) plotcandle(CandleOpen, CandleHigh, CandleLow, CandleClose, color=BodyColor, title='HAMA Candles', wickcolor=WickColor, bordercolor=na) plot(MA_1, title='MA Line', color=BodyColor, style=plot.style_line, linewidth=2) //------------------------------SSL Channel plot_buy = false avg = ((high-low)/2)+low LongCondition = (Hlv1 == 1 and Hlv1[1] == -1) and (BodyColor == color.rgb(230, 172, 0)) and (MA_1 < avg) and (CandleHigh < avg) and (strategy.opentrades == 0) if LongCondition strategy.entry("BUY with VIP", strategy.long) plot_buy := true base = strategy.opentrades.entry_price(0) baseProfit = (base+((base/100)*TakeProfit)) baseLose = (base-((base/100)*StopLose)) strategy.exit("SELL with VIP","BUY with VIP",limit = baseProfit) if UseStopLose and (close < MA_1) strategy.exit("SELL with VIP","BUY with VIP",stop = baseLose) if not UseStopLose and (close < MA_1) strategy.exit("SELL with VIP","BUY with VIP", stop = close) plotshape(plot_buy, title="Buy Label", text="Buy", location=location.belowbar, style=shape.labelup, size=size.tiny, color=Color1, textcolor=color.white) fill(highLine1, lowLine1, color = fillColor1)
Triple RSI strategy
https://www.tradingview.com/script/raWdLVOY-Triple-RSI-strategy/
Trade_by_DB
https://www.tradingview.com/u/Trade_by_DB/
323
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© Trade_by_DB //@version=5 strategy("3 RSI", overlay=true, margin_long=100, margin_short=100) // 3 rsi strategy , when all of them are overbought we sell, and vice versa rsi7 = ta.rsi(close,7) rsi14 = ta.rsi(close,14) rsi21 = ta.rsi(close,21) // sell condition sell = ta.crossunder(rsi7,70) and ta.crossunder(rsi14,70) and ta.crossunder(rsi21,70) //buy condition buy = ta.crossover(rsi7,30) and ta.crossover(rsi14,30) and ta.crossover(rsi21,30) if (buy) strategy.entry("BUY", strategy.long) if (sell) strategy.entry("SELL", strategy.short)
Short Term RSI and SMA Percentage Change
https://www.tradingview.com/script/4FTETUfb-Short-Term-RSI-and-SMA-Percentage-Change/
Coinrule
https://www.tradingview.com/u/Coinrule/
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/ // Β© Coinrule //@version=5 strategy("Short Term RSI and SMA Percentage Change", 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.1) showDate = input(defval=true, title='Show Date Range') timePeriod = time >= timestamp(syminfo.timezone, 2022, 5, 1, 0, 0) notInTrade = strategy.position_size <= 0 //==================================Buy Conditions============================================ //RSI length = input(14) rsi = ta.rsi(close, length) buyCondition1 = rsi > 50 //MA SMA9 = ta.sma(close, 9) SMA100 = ta.sma(close, 100) plot(SMA9, color = color.green) plot(SMA100, color = color.blue) buyCondition2 = (SMA9 > SMA100) //Calculating MA Percentage Change buyMA = (close/SMA9) buyCondition3 = buyMA >= 0.06 if (buyCondition1 and buyCondition2 and buyCondition3 and timePeriod) //and buyCondition strategy.entry("Long", strategy.long) //==================================Sell Conditions============================================ // Configure trail stop level with input options longTrailPerc = input.float(title='Trail Long Loss (%)', minval=0.0, step=0.1, defval=5) * 0.01 shortTrailPerc = input.float(title='Trail Short Loss (%)', minval=0.0, step=0.1, defval=5) * 0.01 // Determine trail stop loss prices longStopPrice = 0.0 shortStopPrice = 0.0 longStopPrice := if strategy.position_size > 0 stopValue = close * (1 - longTrailPerc) math.max(stopValue, longStopPrice[1]) else 0 shortStopPrice := if strategy.position_size < 0 stopValue = close * (1 + shortTrailPerc) math.min(stopValue, shortStopPrice[1]) else 999999 strategy.exit('Exit', stop = longStopPrice, limit = shortStopPrice)
3LS | 3 Line Strike Strategy [Kintsugi Trading]
https://www.tradingview.com/script/fJEKAdgD-3LS-3-Line-Strike-Strategy-Kintsugi-Trading/
KintsugiTrading
https://www.tradingview.com/u/KintsugiTrading/
530
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/ // Β© KintsugiTrading //@version=5 strategy(title="3LS | 3 Line Strike Strategy [Kintsugi Trading]", overlay=true, process_orders_on_close=true, calc_on_every_tick=true, initial_capital=10000) //INPUTS showRiskReward = input(true,title="Show Risk/Reward Area",group="Risk Management") takeLong = input(true, title="Enter Long Position",group="Risk Management") takeShort = input(true, title="Enter Short Position",group="Risk Management") stopType = input.string("Fix PIP Size",title="Stop Loss Strategy",options=["ATR Trail","ATR Trail-Stop","Fix PIP Size"], group="Risk Management") atrPeriod = input(14,title="ATR Period",group="Risk Management",tooltip="Uses on ATR Trail-stop") atrMultip = input.float(2.0,step=0.1,title="ATR Multiplier",group="Risk Management",tooltip="Uses on ATR Trail-stop") riskMultip = input.float(1.0,title="Risk/Reward Ratio",minval=0.1,step=0.1,group="Risk Management") stopTickSize = input(3,title="Additional Stop PIP Size",group="Risk Management")*syminfo.mintick*10 isSessionFilterActive = input.bool(false,title="Session Filter Active?",group="Session") i_tz = input.string('GMT', title='Timezone: ', tooltip='e.g. \'America/New_York\', \'Asia/Tokyo\', \'GMT-4\', \'GMT+9\'...', group='Session') sessionOneRange = input.session(title='Trade Session: ', defval='0900-1600', group='Session') maFill = input(true,title="MA Cloud Fill",group="MA") maPeriod1 = input.int(21,title="MA Period Fast",group="MA") maPeriod2 = input.int(55,title="MA Period Slow",group="MA") //VSA{ showVsa = input.bool(true,title="Show VSA Status?",group="VSA") ma0_length = input.int(30, "Moving Average", minval=1, group="VSA") ma1_length = input.float(0.5,step=0.1,title="MA-1 Multiplier",group="VSA") ma2_length = input.float(1.5,step=0.1,title="MA-2 Multiplier",group="VSA") ma3_length = input.float(3.0,step=0.1,title="MA-3 Multiplier",group="VSA") ma0 = ta.sma(volume, ma0_length) ma1 = ma0 * ma1_length ma2 = ma0 * ma2_length ma3 = ma0 * ma3_length histColor = volume < ma1 ? color.navy : volume < ma2 ? color.green : volume < ma3 ? color.yellow : volume > ma3 ? color.red : color.gray volumeEntryCond = volume > ma2 plotshape(showVsa ? -1 : na, color=histColor, style=shape.square, location=location.bottom, size=size.auto, title='VSA Status') plotshape(showVsa ? -1 : na, color=histColor, textcolor=histColor, text='VSA Status', style=shape.square, location=location.bottom, size=size.auto, title='VSA Label', show_last=1, offset=0) //} //3LS{ showBear3LS = input.bool(title='Show Bearish KT Signal', defval=true, group='3 Line Strike') showBull3LS = input.bool(title='Show Bullish KT Signal', defval=true, group='3 Line Strike') getCandleColorIndex(barIndex) => int ret = na if (close[barIndex] > open[barIndex]) ret := 1 else if (close[barIndex] < open[barIndex]) ret := -1 else ret := 0 ret // Check for engulfing candles isEngulfing(checkBearish) => // In an effort to try and make this a bit more consistent, we're going to calculate and compare the candle body sizes // to inform the engulfing or not decision, and only use the open vs close comparisons to identify the candle "color" ret = false sizePrevCandle = close[1] - open[1] // negative numbers = red, positive numbers = green, 0 = doji sizeCurrentCandle = close - open // negative numbers = red, positive numbers = green, 0 = doji isCurrentLagerThanPrevious = (math.abs(sizeCurrentCandle) > math.abs(sizePrevCandle)) ? true : false // We now have the core info to evaluate engulfing candles switch checkBearish true => // Check for bearish engulfing (green candle followed by a larger red candle) isGreenToRed = ((getCandleColorIndex(0) < 0) and (getCandleColorIndex(1) > 0)) ? true : false ret := (isCurrentLagerThanPrevious and isGreenToRed) ? true : false false => // Check for bullish engulfing (red candle followed by a larger green candle) isRedToGreen = ((getCandleColorIndex(0) > 0) and (getCandleColorIndex(1) < 0)) ? true : false ret := (isCurrentLagerThanPrevious and isRedToGreen) ? true : false => ret := false // This should be impossible to trigger... ret // // Helper functions that wraps the isEngulfing above... isBearishEngulfuing() => ret = isEngulfing(true) ret // isBullishEngulfuing() => ret = isEngulfing(false) ret // // Functions to check for 3 consecutive candles of one color, followed by an engulfing candle of the opposite color // // Bearish 3LS = 3 green candles immediately followed by a bearish engulfing candle is3LSBear() => ret = false is3LineSetup = ((getCandleColorIndex(1) > 0) and (getCandleColorIndex(2) > 0) and (getCandleColorIndex(3) > 0)) ? true : false ret := (is3LineSetup and isBearishEngulfuing()) ? true : false ret // // Bullish 3LS = 3 red candles immediately followed by a bullish engulfing candle is3LSBull() => ret = false is3LineSetup = ((getCandleColorIndex(1) < 0) and (getCandleColorIndex(2) < 0) and (getCandleColorIndex(3) < 0)) ? true : false ret := (is3LineSetup and isBullishEngulfuing()) ? true : false ret is3LSBearSig = is3LSBear() is3LSBullSig = is3LSBull() plotshape(showBull3LS ? is3LSBullSig : na, style=shape.triangleup, color=color.rgb(0, 255, 0, 0), location=location.belowbar, size=size.small, text='KT-Bull', title='3 Line Strike Up') plotshape(showBear3LS ? is3LSBearSig : na, style=shape.triangledown, color=color.rgb(255, 0, 0, 0), location=location.abovebar, size=size.small, text='KT-Bear', title='3 Line Strike Down') //} useCustomRisk = input(true,title="Use Custom Risk",group="Risk Calculation") maxPercRisk = input.float(2.0,step=0.1,minval=0.1,title="% Risk Per Trade",group="Risk Calculation",tooltip="This value used only for backtest results not for auto trading.")/100 // AutoView Settings var g_av = "AutoView Settings [OANDA]" av_use = input.bool(title="Use AutoView?", 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.bool(title="Use Oanda Demo?", defval=true, 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.bool(title="Use Limit Order?", 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_accountBalance = input.float(title="Account Balance", defval=1000.0, step=100, group=g_av, tooltip="Your account balance (used for calculating position size)") av_accountCurrency = input.string(title="Account Currency", 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.float(title="Risk Per Trade %", 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.bool(title='Use PineConnector?', defval=true, group=g_pc, tooltip='Use PineConnector Alerts? (WARNING: USE AT OWN RISK! RESEARCH THE DANGERS)') pc_id = input.string(title='License ID', defval='ID', group=g_pc, tooltip='This is your PineConnector license ID') pc_risk = input.float(title='Risk Per Trade', 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.string(title='MetaTrader Prefix', defval='', group=g_pc, tooltip='This is your broker\'s MetaTrader symbol prefix (leave blank if there is none)') pc_suffix = input.string(title='MetaTrader Suffix', defval='', group=g_pc, tooltip='This is your broker\'s MetaTrader symbol suffix (leave blank if there is none)') // Generate PineConnector alert string var symbol = pc_prefix + syminfo.ticker + pc_suffix var broker = av_oandaDemo ? "oandapractice" : "oanda" var pair = syminfo.basecurrency + "/" + syminfo.currency pc_entry_alert(direction, entry, sl, tp) => order_price = entry tp_value = na(tp) == false ? ',tp=' + str.tostring(tp) : "" price = 'price=' + str.tostring(order_price) pc_id + ',' + direction + ',' + symbol + ',' + price + ',sl=' + str.tostring(sl) + tp_value + ',risk=' + str.tostring(pc_risk) pc_exit_alert(direction) => pc_id + ',' + direction + ',' + symbol av_entry_alert(side, qty, entry, sl, tp)=> tp_value = na(tp) == false ? " ftp=" + str.tostring(tp) : "" "e=" + broker + " b="+side+" q=" + str.tostring(qty) + " s=" + pair+ " t=" + (av_limitOrder ? "limit fp=" + str.tostring(entry) : "market")+ " fsl=" + str.tostring(sl)+ tp_value av_exit_alert(side) => "e=" + broker + " s=" + pair +" c=position b="+side //AUTOTRADE //DETERMINE POSITION SIZE atr = ta.atr(14) toWhole(number) => returnVal = atr < 1.0 ? (number / syminfo.mintick) / (10 / syminfo.pointvalue) : number returnVal := atr >= 1.0 and atr < 100.0 and syminfo.currency == "JPY" ? returnVal * 100 : returnVal var tradePositionSize = 0.0 accountSameAsCounterCurrency = av_accountCurrency == syminfo.currency accountSameAsBaseCurrency = av_accountCurrency == syminfo.basecurrency accountNeitherCurrency = not accountSameAsCounterCurrency and not accountSameAsBaseCurrency conversionCurrencyPair = accountSameAsCounterCurrency ? syminfo.tickerid : accountNeitherCurrency ? av_accountCurrency + syminfo.currency : av_accountCurrency + syminfo.currency conversionCurrencyRate = request.security(symbol=syminfo.type == "forex" ? conversionCurrencyPair : "AUDUSD", timeframe="D", expression=close) getPositionSize(stopLossSizePoints) => riskAmount = (av_accountBalance * (av_riskPerTrade / 100)) * (accountSameAsBaseCurrency or accountNeitherCurrency ? conversionCurrencyRate : 1.0) riskPerPoint = (stopLossSizePoints * syminfo.pointvalue) positionSize = (riskAmount / riskPerPoint) / syminfo.mintick math.round(positionSize) //CALCS //ATR atrValue = ta.atr(atrPeriod) //Sessions in_session_one = time(timeframe.period, sessionOneRange,i_tz) sessionOneActive = in_session_one and timeframe.multiplier <= 1440 sessionFilterResult = isSessionFilterActive ? sessionOneActive : true //MA maValue1 = ta.sma(close,maPeriod1) maValue2 = ta.sma(close,maPeriod2) //STRATEGY var float longStop = na,var float longRisk = na,var float longTp = na var float shortStop = na,var float shortRisk = na,var float shortTp = na string entryAlertString = "", string exitAlertString = "" fix_long_exit = "Exit LONG" fix_short_exit = "Exit SHORT" var float positionSize = 1 calcPositionSize(unitRisk)=> if useCustomRisk == false 1 else totalRisk = strategy.equity *maxPercRisk math.round(totalRisk/unitRisk,6) //FUNCTION calcAtrTrailStop(side)=> if side == "long" tempStop = close - (atrValue * atrMultip) (tempStop > longStop and tempStop < close) ? tempStop : longStop else tempStop = close + (atrValue * atrMultip) (tempStop < shortStop and tempStop > close) ? tempStop : shortStop //ATR TRAIL-STOP if (stopType == "ATR Trail-Stop" or stopType == "ATR Trail") and strategy.position_size > 0 longStop := calcAtrTrailStop("long") if av_use exitAlertString := av_exit_alert('long') else if pc_use exitAlertString := pc_exit_alert('closelong') strategy.exit('Long Exit', 'Long', comment="EXIT LONG", stop=longStop, limit=longTp, alert_message=exitAlertString) if (stopType == "ATR Trail-Stop" or stopType == "ATR Trail") and strategy.position_size < 0 shortStop := calcAtrTrailStop("short") if av_use exitAlertString := av_exit_alert('short') else if pc_use exitAlertString := pc_exit_alert('closeshort') strategy.exit('Short Exit', 'Short', comment="EXIT SHORT", stop=shortStop, limit=shortTp, alert_message=exitAlertString) //LONG longCond = is3LSBullSig and volumeEntryCond and maValue1 > maValue2 shortCond = is3LSBearSig and volumeEntryCond and maValue1 < maValue2 if longCond and takeLong and sessionFilterResult and strategy.position_size == 0 and barstate.isconfirmed and strategy.equity > 0 longStop := stopType == "Fix PIP Size" ? low - stopTickSize : close - (atrValue*atrMultip) longRisk := (close - longStop) longTp := stopType != "ATR Trail" ? close + (riskMultip*longRisk) : na longStopDistance = close - longStop positionSize := calcPositionSize(longRisk) if av_use entryAlertString := av_entry_alert("long",tradePositionSize,close,longStop,longTp) exitAlertString := fix_long_exit else if pc_use entryAlertString := pc_entry_alert("buy", close, longStop, longTp) exitAlertString := fix_long_exit strategy.entry("Long",strategy.long,comment="LONG", qty=positionSize, alert_message=entryAlertString) if stopType != "ATR Trail" strategy.exit("Long Exit","Long", comment="EXIT LONG", stop=longStop, limit=longTp, alert_message=exitAlertString) tradePositionSize := getPositionSize(toWhole(longStopDistance) * 10) if av_use setTp = na(longTp) == false ? " ftp=" + str.tostring(longTp) : "" alert(message="e=" + broker + " b=long q=" + str.tostring(tradePositionSize) + " s=" + pair + " t=" + (av_limitOrder ? "stop fp=" + str.tostring(close) : "market") + " fsl=" + str.tostring(longStop) + setTp, freq=alert.freq_once_per_bar) if pc_use alertString = pc_entry_alert('buystop', close, longStop, longTp) alert(alertString, alert.freq_once_per_bar_close) //SHORT if shortCond and takeShort and sessionFilterResult and strategy.position_size == 0 and barstate.isconfirmed and strategy.equity > 0 shortStop := stopType == "Fix PIP Size" ? high + stopTickSize : close + (atrValue*atrMultip) shortRisk := (shortStop - close) shortTp := stopType != "ATR Trail" ? close - (riskMultip*shortRisk) : na shortStopDistance = math.abs(close-shortStop) positionSize := calcPositionSize(shortRisk) if av_use entryAlertString := av_entry_alert("short",tradePositionSize,close,shortStop,shortTp) exitAlertString := fix_short_exit else if pc_use entryAlertString := pc_entry_alert('sell', close, shortStop, shortTp) exitAlertString := fix_short_exit strategy.entry("Short",strategy.short,comment="SHORT", qty=positionSize, alert_message=entryAlertString) if stopType != "ATR Trail" strategy.exit("Short Exit","Short", comment="EXIT SHORT", stop=shortStop, limit=shortTp, alert_message=exitAlertString) tradePositionSize := getPositionSize(toWhole(shortStopDistance) * 10) if av_use setTp = na(shortTp) == false ? " ftp=" + str.tostring(shortTp) : "" alert(message="e=" + broker + " b=short q=" + str.tostring(tradePositionSize) + " s=" + pair + " t=" + (av_limitOrder ? "stop fp=" + str.tostring(close) : "market") + " fsl=" + str.tostring(shortStop) + setTp, freq=alert.freq_once_per_bar) if pc_use alertString = pc_entry_alert('sellstop', close, shortStop, shortTp) alert(alertString, alert.freq_once_per_bar_close) //PLOTS p1=plot(maValue1,title="MA Fast",color=color.green,linewidth=1) p2=plot(maValue2,title="MA Slow",color=color.red,linewidth=1) fill(p1,p2, color=maFill ? maValue1 > maValue2 ? color.new(color.green,90) : color.new(color.red,90) : color.new(color.black,100)) L1 = plot(showRiskReward and strategy.position_size > 0 ? strategy.position_avg_price : na, color=color.green, linewidth=1, style=plot.style_linebr, title="Long Entry Price") L2 = plot(showRiskReward and strategy.position_size > 0 ? longTp : na, color=color.green, linewidth=1, style=plot.style_linebr, title="Long TP Price") L3 = plot(showRiskReward and strategy.position_size > 0 ? longStop : na, color=color.red, linewidth=1, style=plot.style_linebr, title="Long Stop Price") S1 = plot(showRiskReward and strategy.position_size < 0 ? strategy.position_avg_price : na, color=color.teal, linewidth=1, style=plot.style_linebr, title="Short Entry Price") S2 = plot(showRiskReward and strategy.position_size < 0 ? shortTp : na , color=color.teal, linewidth=1, style=plot.style_linebr, title="Short TP Price") S3 = plot(showRiskReward and strategy.position_size < 0 ? shortStop : na, color=color.maroon, linewidth=1, style=plot.style_linebr, title="Short Stop Price") fill(L1,L2,color=color.new(color.green,90)) fill(L1,L3,color=color.new(color.red,90)) fill(S1,S2,color=color.new(color.teal,90)) fill(S1,S3,color=color.new(color.maroon,90)) bgcolor(sessionOneActive and isSessionFilterActive ? color.new(color.orange,90) : na, title="Trade Session") var table nameDisplay = table.new(position.middle_center, 1, 1, bgcolor = color.white, frame_width = 0) if barstate.isconfirmed and math.round(strategy.equity,0) <= 0 table.cell(nameDisplay, 0, 0, "Total Equity dropped below ZERO.\nThese parameters are not useful.",text_color=color.white, bgcolor=color.red)
DMI Strategy
https://www.tradingview.com/script/oHT8ctYn-DMI-Strategy/
email_analysts
https://www.tradingview.com/u/email_analysts/
68
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© email_analysts // This code gives indication on the chart to go long based on DMI and exit based on RSI. //Default value has been taken as 14 for DMI+ and 6 for RSI. //@version=5 strategy(title="DMI Strategy", overlay=false) lensig = input.int(11, title="ADX Smoothing", minval=1, maxval=50) len = input.int(11, minval=1, title="DI Length") up = ta.change(high) down = -ta.change(low) plusDM = na(up) ? na : (up > down and up > 0 ? up : 0) minusDM = na(down) ? na : (down > up and down > 0 ? down : 0) trur = ta.rma(ta.tr, len) plus = fixnan(100 * ta.rma(plusDM, len) / trur) minus = fixnan(100 * ta.rma(minusDM, len) / trur) sum = plus + minus adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), lensig) //plot(adx, color=#F50057, title="ADX") plot(plus, color=color.green, title="+DI") plot(minus, color=color.red, title="-DI") hlineup = hline(40, color=#787B86) hlinelow = hline(10, color=#787B86) buy = plus < 10 and minus > 40 if buy strategy.entry('long', strategy.long) sell = plus > 40 and minus < 10 if sell strategy.entry('short', strategy.short)
[TH] IMF(In Market Forever)
https://www.tradingview.com/script/zFLMuyND/
dokang
https://www.tradingview.com/u/dokang/
408
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© dokang //@version=5 password = input.string("Your Password", title="Password", confirm=true) strategy("[TH] IMF", initial_capital=10000, currency=currency.KRW, default_qty_type=strategy.percent_of_equity, default_qty_value=100, overlay=true, calc_on_every_tick=true) import dokang/TradingHook/2 as TH numsOfTrades = input.int(1, "Nums of trades", minval=0, step=1) entry_price = input.price(0, title="Entry Price", confirm=true) profit_price = input.price(1000000, title="Profit Price", confirm=true) loss_price = input.price(0, title="Loss Price", confirm=true) isShowPrice = input.bool(true, title="Show Price") if profit_price <= entry_price runtime.error("Profit Price must be higher than Entry Price") if loss_price >= entry_price runtime.error("Loss Price must be less than Entry Price") profit_percent = 100*(profit_price/entry_price-1) loss_percent = 100*(loss_price/entry_price-1) var profit_label = label(na) var loss_label = label(na) var entry_label = label(na) if barstate.islastconfirmedhistory var entry_line = line.new(time, entry_price, time+60, entry_price, xloc=xloc.bar_time, extend = extend.both, color = color.orange) var loss_line = line.new(time, loss_price, time+60, loss_price, xloc=xloc.bar_time, extend = extend.both, color = color.red) var profit_line = line.new(time, profit_price, time+60, profit_price, xloc=xloc.bar_time, extend = extend.both, color = color.green) if barstate.isrealtime label.delete(profit_label) label.delete(loss_label) label.delete(entry_label) str_loss_price = isShowPrice ? str.format("({0})",str.tostring(loss_price, format.mintick)) : na str_profit_price = isShowPrice ? str.format("({0})",str.tostring(profit_price, format.mintick)) : na entry_text = str.format("Entry {0, number,#.##} ({1})", profit_percent/math.abs(loss_percent),str.tostring(entry_price,format.mintick)) profit_text = str.format("Profit {0,number,#.##}% {1}", profit_percent, str_profit_price) loss_text = str.format("Loss {0,number,#.##}% {1}", loss_percent, str_loss_price) profit_label := label.new(bar_index, profit_price, text=profit_text, tooltip=str.tostring(profit_price, format.mintick), style=label.style_label_lower_left, color = color.green, textcolor = color.white) loss_label := label.new(bar_index, loss_price, text=loss_text, tooltip = str.tostring(loss_price, format.mintick), style=label.style_label_upper_left, color = color.red, textcolor = color.white) entry_label := label.new(bar_index+5, entry_price,text=entry_text, style=label.style_label_center, color = color.orange, textcolor = color.white) inTrade= strategy.closedtrades < numsOfTrades if barstate.isrealtime if entry_price > close and inTrade strategy.entry("buy", strategy.long, stop = entry_price, alert_message = TH.buy_message(password, order_name="IMF 맀수")) else if entry_price <= close and inTrade strategy.entry("buy", strategy.long, limit = entry_price, alert_message = TH.buy_message(password, order_name="IMF 맀수")) strategy.exit("sell", "buy", limit = profit_price, stop = loss_price, alert_message = TH.sell_message(password, "100%", order_name="IMF 맀도"))
Strategy Myth-Busting #3 - BB_BUY+SuperTrend - [MYN]
https://www.tradingview.com/script/QMpkE1h6-Strategy-Myth-Busting-3-BB-BUY-SuperTrend-MYN/
myncrypto
https://www.tradingview.com/u/myncrypto/
292
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© myn //@version=5 strategy('Strategy Myth-Busting #3 - BB_BUY+SuperTrend - [MYN]', max_bars_back=5000, overlay=true, pyramiding=0, initial_capital=20000, currency='USD', default_qty_type=strategy.percent_of_equity, default_qty_value=100.0, commission_value=0.075, use_bar_magnifier = true) ///Derek-Multiple-Take-Profit-Strategy-Template-v5-2022-04-03.pine // 04-03-2022 Added ADX // 08-17-2022 Added Dashboard ///////////////////////////////////// //* Put your strategy logic below *// ///////////////////////////////////// // Q0txMfU623Y // Trading Rules //long condition when BB_BUY indicates buy signal and SuperTrend is green //short condition when BB_BUY indicates Sell signal and SuperTrend is red //@version=5 // BB_Buy and sell strategy logic //β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ //indicator(shorttitle='BB_Buy and Sell', title='BB_Buy and Sell', overlay=true) // === INPUTS === // Bollinger Bands Inputs bb_use_ema = input(false, title='Use EMA for Bollinger Band') bb_length = input.int(42, minval=1, title='Bollinger Length') bb_source = input(close, title='Bollinger Source') bb_mult = input.float(2.0, title='Base Multiplier', minval=0.5, maxval=10) // EMA inputs fast_ma_len = input.int(10, title='Fast EMA length', minval=2) // Awesome Inputs nLengthSlow = input.int(77, minval=1, title='Awesome Length Slow') nLengthFast = input.int(10, minval=1, title='Awesome Length Fast') // === /INPUTS === // Breakout Indicator Inputs ema_1 = ta.ema(bb_source, bb_length) sma_1 = ta.sma(bb_source, bb_length) bb_basis = bb_use_ema ? ema_1 : sma_1 fast_ma = ta.ema(bb_source, fast_ma_len) // Deviation // * I'm sure there's a way I could write some of this cleaner, but meh. dev = ta.stdev(bb_source, bb_length) bb_dev_inner = bb_mult * dev // Upper bands inner_high = bb_basis + bb_dev_inner // Lower Bands inner_low = bb_basis - bb_dev_inner // Calculate Awesome Oscillator xSMA1_hl2 = ta.sma(hl2, nLengthFast) xSMA2_hl2 = ta.sma(hl2, nLengthSlow) xSMA1_SMA2 = xSMA1_hl2 - xSMA2_hl2 // Calculate direction of AO AO = xSMA1_SMA2 >= 0 ? xSMA1_SMA2 > xSMA1_SMA2[1] ? 1 : 2 : xSMA1_SMA2 > xSMA1_SMA2[1] ? -1 : -2 // Deternine if we are currently LONG isLong = false isLong := nz(isLong[1], false) // Determine if we are currently SHORT isShort = false isShort := nz(isShort[1], false) // Buy only if the buy signal is triggered and we are not already long LONG = not isLong and ta.crossover(fast_ma, bb_basis) and close > bb_basis and math.abs(AO) == 1 c_green = fast_ma > bb_basis // Sell only if the sell signal is triggered and we are not already short SHORT = not isShort and ta.crossunder(fast_ma, bb_basis) and close < bb_basis and math.abs(AO) == 2 c_red = fast_ma < bb_basis if LONG isLong := true isShort := false isShort barcolor(LONG ? color.green : na) if SHORT isLong := false isShort := true isShort barcolor(c_green ? color.green : na) barcolor(c_red ? color.red : na) // Show Break Alerts plotshape(SHORT, title='Sell', style=shape.labeldown, location=location.abovebar, size=size.normal, text='Sell', textcolor=color.new(color.white, 0), color=color.new(color.red, 0)) plotshape(LONG, title='Buy', style=shape.labelup, location=location.belowbar, size=size.normal, text='Buy', textcolor=color.new(color.white, 0), color=color.new(color.green, 0)) // === /PLOTTING === // Send alert to TV alarm sub-system alertcondition(LONG, title='Buy', message='Buy') alertcondition(LONG, title='Buy', message='Buy') alertcondition(LONG, title='Buy', message='Buy') alertcondition(SHORT, title='Sell', message='Sell') // SuperTrend //β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ //@version=5 //indicator("Supertrend", overlay=true, timeframe="", timeframe_gaps=true) atrPeriod = input(10, "ATR Length") factor = input.float(3.0, "Factor", step = 0.01) [supertrend, direction] = ta.supertrend(factor, atrPeriod) bodyMiddle = plot((open + close) / 2, display=display.none) upTrend = plot(direction < 0 ? supertrend : na, "Up Trend", color = color.green, style=plot.style_linebr) downTrend = plot(direction < 0? na : supertrend, "Down Trend", color = color.red, style=plot.style_linebr) fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps=false) fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps=false) ////////////////////////////////////// //* Put your strategy rules below *// ///////////////////////////////////// //long condition when BB_BUY indicates buy signal and SuperTrend is green //short condition when BB_BUY indicates Sell signal and SuperTrend is red longCondition = LONG and direction < 0 shortCondition = SHORT and direction > 0 //define as 0 if do not want to use closeLongCondition = 0 closeShortCondition = 0 // ADX //β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ adxEnabled = input.bool(defval = false , title = "Average Directional Index (ADX)", tooltip = "", group ="ADX" ) adxlen = input(14, title="ADX Smoothing", group="ADX") adxdilen = input(14, title="DI Length", group="ADX") adxabove = input(25, title="ADX Threshold", group="ADX") adxdirmov(len) => adxup = ta.change(high) adxdown = -ta.change(low) adxplusDM = na(adxup) ? na : (adxup > adxdown and adxup > 0 ? adxup : 0) adxminusDM = na(adxdown) ? na : (adxdown > adxup and adxdown > 0 ? adxdown : 0) adxtruerange = ta.rma(ta.tr, len) adxplus = fixnan(100 * ta.rma(adxplusDM, len) / adxtruerange) adxminus = fixnan(100 * ta.rma(adxminusDM, len) / adxtruerange) [adxplus, adxminus] adx(adxdilen, adxlen) => [adxplus, adxminus] = adxdirmov(adxdilen) adxsum = adxplus + adxminus adx = 100 * ta.rma(math.abs(adxplus - adxminus) / (adxsum == 0 ? 1 : adxsum), adxlen) adxsig = adxEnabled ? adx(adxdilen, adxlen) : na isADXEnabledAndAboveThreshold = adxEnabled ? (adxsig > adxabove) : true //Backtesting Time Period (Input.time not working as expected as of 03/30/2021. Giving odd start/end dates //β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ useStartPeriodTime = input.bool(true, 'Start', group='Date Range', inline='Start Period') startPeriodTime = input.time(timestamp('1 Jan 2019'), '', group='Date Range', inline='Start Period') useEndPeriodTime = input.bool(true, 'End', group='Date Range', inline='End Period') endPeriodTime = input.time(timestamp('31 Dec 2030'), '', group='Date Range', inline='End Period') start = useStartPeriodTime ? startPeriodTime >= time : false end = useEndPeriodTime ? endPeriodTime <= time : false calcPeriod = not start and not end // Trade Direction // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ tradeDirection = input.string('Long and Short', title='Trade Direction', options=['Long and Short', 'Long Only', 'Short Only'], group='Trade Direction') // Percent as Points // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ per(pcnt) => strategy.position_size != 0 ? math.round(pcnt / 100 * strategy.position_avg_price / syminfo.mintick) : float(na) // Take profit 1 // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ tp1 = input.float(title='Take Profit 1 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 1') q1 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 1') // Take profit 2 // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ tp2 = input.float(title='Take Profit 2 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 2') q2 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 2') // Take profit 3 // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ tp3 = input.float(title='Take Profit 3 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 3') q3 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 3') // Take profit 4 // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ tp4 = input.float(title='Take Profit 4 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit') /// Stop Loss // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ stoplossPercent = input.float(title='Stop Loss (%)', defval=999, minval=0.01, group='Stop Loss') * 0.01 slLongClose = close < strategy.position_avg_price * (1 - stoplossPercent) slShortClose = close > strategy.position_avg_price * (1 + stoplossPercent) /// Leverage // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ leverage = input.float(1, 'Leverage', step=.5, group='Leverage') contracts = math.min(math.max(.000001, strategy.equity / close * leverage), 1000000000) /// Trade State Management // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ isInLongPosition = strategy.position_size > 0 isInShortPosition = strategy.position_size < 0 /// ProfitView Alert Syntax String Generation // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ alertSyntaxPrefix = input.string(defval='CRYPTANEX_99FTX_Strategy-Name-Here', title='Alert Syntax Prefix', group='ProfitView Alert Syntax') alertSyntaxBase = alertSyntaxPrefix + '\n#' + str.tostring(open) + ',' + str.tostring(high) + ',' + str.tostring(low) + ',' + str.tostring(close) + ',' + str.tostring(volume) + ',' /// Trade Execution // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ longConditionCalc = (longCondition and isADXEnabledAndAboveThreshold) shortConditionCalc = (shortCondition and isADXEnabledAndAboveThreshold) if calcPeriod if longConditionCalc and tradeDirection != 'Short Only' and isInLongPosition == false strategy.entry('Long', strategy.long, qty=contracts) alert(message=alertSyntaxBase + 'side:long', freq=alert.freq_once_per_bar_close) if shortConditionCalc and tradeDirection != 'Long Only' and isInShortPosition == false strategy.entry('Short', strategy.short, qty=contracts) alert(message=alertSyntaxBase + 'side:short', freq=alert.freq_once_per_bar_close) //Inspired from Multiple %% profit exits example by adolgo https://www.tradingview.com/script/kHhCik9f-Multiple-profit-exits-example/ strategy.exit('TP1', qty_percent=q1, profit=per(tp1)) strategy.exit('TP2', qty_percent=q2, profit=per(tp2)) strategy.exit('TP3', qty_percent=q3, profit=per(tp3)) strategy.exit('TP4', profit=per(tp4)) strategy.close('Long', qty_percent=100, comment='SL Long', when=slLongClose) strategy.close('Short', qty_percent=100, comment='SL Short', when=slShortClose) strategy.close_all(when=closeLongCondition or closeShortCondition, comment='Close Postion') /// Dashboard // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Inspired by https://www.tradingview.com/script/uWqKX6A2/ - Thanks VertMT showDashboard = input.bool(group="Dashboard", title="Show Dashboard", defval=true) f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) => _cellText = _title + "\n" + _value table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor, text_size=size.auto) // Draw dashboard table if showDashboard var bgcolor = color.new(color.black,0) // Keep track of Wins/Losses streaks newWin = (strategy.wintrades > strategy.wintrades[1]) and (strategy.losstrades == strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1]) newLoss = (strategy.wintrades == strategy.wintrades[1]) and (strategy.losstrades > strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1]) varip int winRow = 0 varip int lossRow = 0 varip int maxWinRow = 0 varip int maxLossRow = 0 if newWin lossRow := 0 winRow := winRow + 1 if winRow > maxWinRow maxWinRow := winRow if newLoss winRow := 0 lossRow := lossRow + 1 if lossRow > maxLossRow maxLossRow := lossRow // Prepare stats table var table dashTable = table.new(position.bottom_right, 1, 15, border_width=1) if barstate.islastconfirmedhistory // Update table dollarReturn = strategy.netprofit f_fillCell(dashTable, 0, 0, "Start:", str.format("{0,date,long}", strategy.closedtrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.closedtrades.entry_time(0)) f_fillCell(dashTable, 0, 1, "End:", str.format("{0,date,long}", strategy.opentrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.opentrades.entry_time(0)) _profit = (strategy.netprofit / strategy.initial_capital) * 100 f_fillCell(dashTable, 0, 2, "Net Profit:", str.tostring(_profit, '##.##') + "%", _profit > 0 ? color.green : color.red, color.white) _numOfDaysInStrategy = (strategy.opentrades.entry_time(0) - strategy.closedtrades.entry_time(0)) / (1000 * 3600 * 24) f_fillCell(dashTable, 0, 3, "Percent Per Day", str.tostring(_profit / _numOfDaysInStrategy, '#########################.#####')+"%", _profit > 0 ? color.green : color.red, color.white) _winRate = ( strategy.wintrades / strategy.closedtrades ) * 100 f_fillCell(dashTable, 0, 4, "Percent Profitable:", str.tostring(_winRate, '##.##') + "%", _winRate < 50 ? color.red : _winRate < 75 ? #999900 : color.green, color.white) f_fillCell(dashTable, 0, 5, "Profit Factor:", str.tostring(strategy.grossprofit / strategy.grossloss, '##.###'), strategy.grossprofit > strategy.grossloss ? color.green : color.red, color.white) f_fillCell(dashTable, 0, 6, "Total Trades:", str.tostring(strategy.closedtrades), bgcolor, color.white) f_fillCell(dashTable, 0, 8, "Max Wins In A Row:", str.tostring(maxWinRow, '######') , bgcolor, color.white) f_fillCell(dashTable, 0, 9, "Max Losses In A Row:", str.tostring(maxLossRow, '######') , bgcolor, color.white)
Trend Ravi Trial
https://www.tradingview.com/script/dWutsBPd-Trend-Ravi-Trial/
abhimanyoo
https://www.tradingview.com/u/abhimanyoo/
8
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/ // Β© abhimanyoo //@version=4 strategy("test") if bar_index < 100 strategy.entry("buy", strategy.long, 10, when=strategy.position_size <= 0) strategy.entry("sell", strategy.short, 10, when=strategy.position_size > 0) plot(strategy.equity)
DMI Strategy
https://www.tradingview.com/script/X9nwMUYs-DMI-Strategy/
email_analysts
https://www.tradingview.com/u/email_analysts/
107
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/ // Β© email_analysts // This code gives indication on the chart to go long based on DMI and exit based on RSI. //Default value has been taken as 14 for DMI+ and 6 for RSI. //@version=5 strategy(title="DMI Strategy", overlay=false) lensig = input.int(11, title="ADX Smoothing", minval=1, maxval=50) len = input.int(11, minval=1, title="DI Length") up = ta.change(high) down = -ta.change(low) plusDM = na(up) ? na : (up > down and up > 0 ? up : 0) minusDM = na(down) ? na : (down > up and down > 0 ? down : 0) trur = ta.rma(ta.tr, len) plus = fixnan(100 * ta.rma(plusDM, len) / trur) minus = fixnan(100 * ta.rma(minusDM, len) / trur) sum = plus + minus adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), lensig) //plot(adx, color=#F50057, title="ADX") plot(plus, color=color.green, title="+DI") plot(minus, color=color.red, title="-DI") hlineup = hline(40, color=#787B86) hlinelow = hline(10, color=#787B86) // buy = plus < 10 and minus > 40 if buy strategy.entry('long', strategy.long) sell = plus > 40 and minus < 10 if sell strategy.entry('short', strategy.short)
Gap Stats v2
https://www.tradingview.com/script/MvMOPBmc-Gap-Stats-v2/
PropTradingShop
https://www.tradingview.com/u/PropTradingShop/
86
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/ // Β© PropTradingShop //@version=5 strategy("Gap Stats v2", overlay=true, margin_long=100, margin_short=100) minGapPerc = input.float(1.0,"Min Gap %")/100 var gapPercs = array.new<float>() var gapDates = array.new<string>() var gapAmounts = array.new<float>() var gapPercCovered = array.new<float>() theMonth = str.tostring(month) theDay = str.tostring(dayofmonth) theYear = str.tostring(year) theDate = theMonth+'/'+theDay+'/'+theYear isGapUp = open > high[1] + (high[1] * minGapPerc) isGapDown = open < low[1] - (low[1] * minGapPerc) var coveredCount = 0 plotshape(isGapUp, style=shape.arrowup, color=color.green, location=location.bottom) plotshape(isGapDown, style=shape.arrowdown, color=color.red, location=location.top) if isGapUp gapPerc = ((open - high[1])/high[1]) * 100 gapAmount = open-high[1] diff = open-low percCovered = math.abs(diff/gapAmount) > 1 ? 100 : (math.abs(diff/gapAmount)) * 100 array.push(gapDates,theDate) array.push(gapPercs,gapPerc) array.push(gapAmounts,gapAmount) array.push(gapPercCovered,percCovered) if percCovered >= 100 coveredCount := coveredCount+1 if isGapDown gapPerc = ((low[1] - open)/low) * 100 gapAmount = open-low[1] diff = high - open percCovered = math.abs(diff/gapAmount) > 1 ? 100 : (math.abs(diff/gapAmount)) * 100 array.push(gapDates,theDate) array.push(gapPercs,-gapPerc) array.push(gapAmounts,gapAmount) array.push(gapPercCovered,percCovered) if percCovered >= 100 coveredCount := coveredCount+1 gapTable = table.new(position = position.top_right, columns = 4, rows = array.size(gapDates) > 0 ? array.size(gapDates) + 1 : 1, frame_color=#151715, frame_width=1, border_width=1, border_color=color.white) table.cell(gapTable, 0, 0, 'Date', text_halign = text.align_center, bgcolor = color.gray, text_color = color.white, text_size = size.normal) table.cell(gapTable, 1, 0, 'Gap %', text_halign = text.align_center, bgcolor = color.gray, text_color = color.white, text_size = size.normal) table.cell(gapTable, 2, 0, 'Gap $', text_halign = text.align_center, bgcolor = color.gray, text_color = color.white, text_size = size.normal) table.cell(gapTable, 3, 0, 'Gap % Covered', text_halign = text.align_center, bgcolor = color.gray, text_color = color.white, text_size = size.normal) if barstate.islastconfirmedhistory and array.size(gapDates) > 0 array.reverse(gapDates) array.reverse(gapPercs) array.reverse(gapAmounts) array.reverse(gapPercCovered) for i = 0 to array.size(gapDates) - 1 table.cell(gapTable, column = 0, row = i + 1, text = array.get(gapDates,i),text_halign = text.align_left, bgcolor = color.gray, text_color = color.white, text_size = size.small) table.cell(gapTable, column = 1, row = i + 1, text = str.tostring(array.get(gapPercs,i),'.##')+'%', text_halign = text.align_left, bgcolor = array.get(gapPercs,i) > 0 ? color.green : color.red, text_color = color.white, text_size = size.small) table.cell(gapTable, column = 2, row = i + 1, text = '$'+str.tostring(array.get(gapAmounts,i),'.##'), text_halign = text.align_left, bgcolor = array.get(gapAmounts,i) > 0 ? color.green : color.red, text_color = color.white, text_size = size.small) table.cell(gapTable, column = 3, row = i + 1, text = str.tostring(array.get(gapPercCovered,i),'.##')+'%', text_halign = text.align_left, bgcolor = color.gray, text_color = color.white, text_size = size.small)
Strategy - Trend Chaser - PSe
https://www.tradingview.com/script/wDrRjVrD-Strategy-Trend-Chaser-PSe/
ElvinKennedyHernandezLatayan
https://www.tradingview.com/u/ElvinKennedyHernandezLatayan/
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/ // Β© Dillon_Grech / Elvin Latayan //@version=5 strategy('Strategy - Trend Chaser - PSe', overlay=true, currency=currency.USD, pyramiding=1, initial_capital=25000) //============================================================================== //FOREX EXCHANGE - Currency Conversion //============================================================================== //Select quote currency quoteCurrency = syminfo.currency //gets quote currency automatically by looking using syminfo function - thank you Rodenwild //Get currency pair rate quoted against USD (base currency) usdUSDrate = request.security('USDUSD', 'D', close[1]) gbpUSDrate = request.security('GBPUSD', 'D', close[1]) audUSDrate = request.security('AUDUSD', 'D', close[1]) nzdUSDrate = request.security('NZDUSD', 'D', close[1]) cadUSDrate = request.security('CADUSD', 'D', close[1]) chfUSDrate = request.security('CHFUSD', 'D', close[1]) eurUSDrate = request.security('EURUSD', 'D', close[1]) jpyUSDrate = request.security('JPYUSD', 'D', close[1]) phpUSDrate = request.security('PHPUSD', 'D', close[1]) //Fuction to get currency rate into variable cr_function(source) => if quoteCurrency == 'USD' 1 else if quoteCurrency == 'GBP' gbpUSDrate else if quoteCurrency == 'AUD' audUSDrate else if quoteCurrency == 'NZD' nzdUSDrate else if quoteCurrency == 'CAD' cadUSDrate else if quoteCurrency == 'CHF' chfUSDrate else if quoteCurrency == 'EUR' eurUSDrate else if quoteCurrency == 'PHP' phpUSDrate else jpyUSDrate //Put currency rate function into variable cr_multi = cr_function(ta.tr(true)) //============================================================================== //============================================================================== //BACKTEST DATE RANGE - Select Dates //============================================================================== //Input for date window startDay = input.int(defval=1, title='Start Day', minval=1, maxval=31) startMonth = input.int(defval=1, title='Start Month', minval=1, maxval=12) startYear = input.int(defval=2008, title='Start Year', minval=1970) endDay = input.int(defval=1, title='End Day', minval=1, maxval=31) endMonth = input.int(defval=12, title='End Month', minval=1, maxval=12) endYear = input.int(defval=2022, title='End Year', minval=1970) //Submit date window startDate = timestamp(startYear, startMonth, startDay, 00, 00, 00) // backtest start date endDate = timestamp(endYear, endMonth, endDay, 23, 59, 59) // backtest end date dateRange() => // specify where date range is true time >= startDate and time <= endDate ? true : false // Remove EurChf from testing EURCHFCrashDate = syminfo.currency == 'CHF' or syminfo.basecurrency == 'CHF' ? time >= timestamp(2015, 01, 01) and time <= timestamp(2015, 01, 18) ? false : true : true //============================================================================== //============================================================================== //MONEY MANAGEMENT - ATR //============================================================================== //Entrer intial capital and percentage risk inputs percentRisk = input.float(title='Risk Per Trade', defval=0.02, minval=0.001, maxval=1) //Enter ATR inputs atrLength = 14 atrMulti_Loss = input(title='Atr Loss Multiple', defval=1.25) tsMulti = input(title='Trailing Stop Multiple', defval=1.25) //ATR function truncate(number, decimals) => factor = math.pow(10, decimals) int(number * factor) / factor atr = truncate(ta.atr(atrLength), 5) //Fuction for pse lot size pse_lotsize(tickSize) => if tickSize == 0.0001 10000 else if tickSize >= 0.001 and tickSize <= 0.005 1000 else if tickSize >= 0.01 and tickSize <= 0.05 100 else if tickSize >= 0.10 and tickSize <= 0.50 10 else if tickSize >= 1 and tickSize <= 5 1 //Get position size //posSize = round((((strategy.initial_capital/100) * percentRisk) / (atrMulti_Loss * atr))/ syminfo.mintick) riskMoney = strategy.initial_capital / pse_lotsize(syminfo.mintick) * percentRisk posSize = math.round(riskMoney / (atrMulti_Loss * atr * syminfo.pointvalue) / syminfo.mintick) //============================================================================== //============================================================================== //INDICATOR 1 - Trigger //============================================================================== //Indicator Name [macdLine, signalLine, histLine] = ta.macd(close, 12, 26, 9) Ind_1_L = ta.crossover(histLine, 0) and macdLine > 0 Ind_1_S = false //============================================================================== //============================================================================== //INDICATOR 2 //============================================================================== //Indicator Name // // @author LazyBear // List of all my indicators: // https://docs.google.com/document/d/15AGCufJZ8CIUvwFJ9W-IKns88gkWOKBCvByMEvm5MLo/edit?usp=sharing // // Modified for Crypto Market by ShayanKM sensitivity = input(150, title='Sensitivity') fastLength = input(20, title='FastEMA Length') slowLength = input(40, title='SlowEMA Length') channelLength = input(20, title='BB Channel Length') mult = input(2.0, title='BB Stdev Multiplier') DEAD_ZONE = nz(ta.rma(ta.tr(true), 100)) * 3.7 calc_macd(source, fastLength, slowLength) => fastMA = ta.ema(source, fastLength) slowMA = ta.ema(source, slowLength) fastMA - slowMA calc_BBUpper(source, length, mult) => basis = ta.sma(source, length) dev = mult * ta.stdev(source, length) basis + dev calc_BBLower(source, length, mult) => basis = ta.sma(source, length) dev = mult * ta.stdev(source, length) basis - dev t1 = (calc_macd(close, fastLength, slowLength) - calc_macd(close[1], fastLength, slowLength)) * sensitivity e1 = calc_BBUpper(close, channelLength, mult) - calc_BBLower(close, channelLength, mult) trendUp = t1 >= 0 ? t1 : 0 trendDown = t1 < 0 ? -1 * t1 : 0 //Long and Short Orders (Confirmation Conditions) Ind_2_L = trendUp > e1 Ind_2_S = false //============================================================================== //ENTRY CONDITIONS - Submit Orders //============================================================================== //Long and short strategy conditions entry_long = strategy.position_size <= 0 and dateRange() and EURCHFCrashDate and Ind_1_L and Ind_2_L entry_short = strategy.position_size >= 0 and dateRange() and EURCHFCrashDate and Ind_1_S and Ind_2_S plotshape(entry_long, color=color.new(color.lime, 0), style=shape.arrowup, location=location.belowbar, text='Buy') plotshape(entry_short, color=color.new(color.red, 0), style=shape.arrowdown, location=location.abovebar, text='Sell') //Store ATR and Price upon entry of trade. entry_atr = float(0.0) //set float entry_price = float(0.0) //set float entry_atr := strategy.position_size == 0 or entry_long or entry_short ? atr : entry_atr[1] entry_price := strategy.position_size == 0 or entry_long or entry_short ? close : entry_price[1] //Submit long and short orders based on entry conditions if entry_long strategy.entry(id='Long Entry 1', direction=strategy.long, qty=posSize) if entry_short strategy.entry(id='Short Entry 1', direction=strategy.short, qty=posSize) //============================================================================== //============================================================================== //TAKE PROFIT & STOP LOSS VALUES //============================================================================== //Calculate stop loss and take profit distance (in price) nLoss = entry_atr * atrMulti_Loss nProfit = entry_atr ts_loss = entry_atr * tsMulti //Find long take profit and stop loss levels long_profit_level = float(0.0) //set float long_stop_level = float(0.0) //set float long_profit_level := entry_price + nLoss long_stop_level := entry_price - nLoss if math.max(close, close[1]) > long_profit_level long_stop_level := entry_price long_stop_level if long_stop_level < math.max(close - (ts_loss + ts_loss), nz(long_stop_level[1], 0)) long_stop_level := math.max(close - (ts_loss + ts_loss), nz(long_stop_level[1], 0), strategy.position_avg_price) long_stop_level //Find short take profit and stop loss levels short_profit_level = float(0.0) //set float short_stop_level = float(0.0) //set float short_profit_level := entry_price - nProfit short_stop_level := entry_price + nLoss //Plot stop loss and profit level on graph; hide levels when no trade plot(strategy.position_size <= 0 or entry_long or entry_short ? na : long_stop_level, color=color.new(color.red, 0), style=plot.style_linebr, linewidth=2) plot(strategy.position_size <= 0 or entry_long or entry_short ? na : long_profit_level, color=color.new(color.green, 0), style=plot.style_linebr, linewidth=2) plot(strategy.position_size >= 0 or entry_long or entry_short ? na : short_stop_level, color=color.new(color.red, 0), style=plot.style_linebr, linewidth=2) plot(strategy.position_size >= 0 or entry_long or entry_short ? na : short_profit_level, color=color.new(color.green, 0), style=plot.style_linebr, linewidth=2) //============================================================================== //============================================================================== //EXIT CONDITIONS - Submit Orders //============================================================================== //Submit exit orders on static profit and loss strategy.exit('TP/SL 1', 'Long Entry 1', stop=long_stop_level) strategy.exit('TP/SL 1', 'Short Entry 1', stop=short_stop_level) //Submit exit orders on exit indicator - Exit 1 strategy.close(id='Long Entry 1', comment='Exit 1 L1', when=Ind_1_S) strategy.close(id='Short Entry 1', comment='Exit 1 S1', when=Ind_1_L) //============================================================================== if entry_long label.new(bar_index, na, "β€’ENTRYβ€’\nPosition Size = " + str.tostring(posSize) + "\n Potential Stop Loss = " + str.tostring(close - nLoss) + "\n Actual Stop Loss = " + str.tostring(long_stop_level), yloc = yloc.abovebar, style = label.style_none, textcolor = color.black, size = size.normal)
Trade Hour
https://www.tradingview.com/script/4KxpN6N6-Trade-Hour/
mablue
https://www.tradingview.com/u/mablue/
196
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/ // Β© mablue (Masoud Azizi) // based on idea of circular mean with atan2 //@version=5 strategy("Trade Hour V4",overlay=false) src = input.source(close) timezone = input.string("UTC+0000",options=["UTC+0000","GMT+0000","America/New_York","America/Los_Angeles","America/Chicago","America/Phoenix","America/Toronto","America/Vancouver","America/Argentina" ,"America/El_Salvador","America/Sao_Paulo","America/Bogota","Europe/Moscow","Europe/Athens","Europe/Berlin","Europe/London","Europe/Madrid","Europe/Paris","Europe/Warsaw","Australia/Sydney","Australia/Brisbane","Australia/Adelaide","Australia/ACT","Asia/Almaty","Asia/Ashkhabad","Asia/Tokyo","Asia/Taipei","Asia/Singapore","Asia/Shanghai","Asia/Seoul","Asia/Tehran","Asia/Dubai","Asia/Kolkata","Asia/Hong_Kong","Asia/Bangkok","Pacific/Auckland","Pacific/Chatham","Pacific/Fakaofo","Pacific/Honolulu"] ) length = input.int(24,"Timeperiod") arctan2(x,y)=> if x>0 and y>0 result = math.atan(x/y) else if y<0 result = math.atan(x/y) + math.pi else if x<0 and y>0 result = math.atan(x/y) + 2*math.pi best_hour(indicator)=> hours = (2*math.pi)*(hour(time,timezone)/24) hours_y = math.sin(hours) hours_x = math.cos(hours) hours_x_avg = ta.cum(hours_x*indicator)/ta.cum(indicator) hours_y_avg = ta.cum(hours_y*indicator)/ta.cum(indicator) hours_avg = (arctan2(hours_y_avg,hours_x_avg)*24/(2*math.pi))%24 buy_indicator = math.avg(ta.rsi(src,length),ta.mfi(src,length)) sell_indicator = math.avg(ta.rsi(1/src,length),ta.mfi(1/src,length)) // buy_indicator = ta.roc(src,length) // sell_indicator = ta.roc(1/src,length) // buy_indicator = ta.roc(src,length) // sell_indicator = ta.roc(1/src,length) buy_hour = best_hour(buy_indicator) sell_hour = best_hour(sell_indicator) plot(buy_hour,"Buy hour",color.green) plot(sell_hour,"Sell hour",color.red) bool isLongBestHour = math.round(buy_hour) == hour(time,timezone) bool isShortBestHour = math.round(sell_hour) == hour(time,timezone) bgcolor(isLongBestHour ? color.new(color.green,80) : na) bgcolor(isShortBestHour ? color.new(color.red,80) : na) strategy.order("buy", strategy.long, when =isLongBestHour) strategy.order("sell", strategy.short, when = isShortBestHour)
LONG SAZB $
https://www.tradingview.com/script/b3bLqTrf-LONG-SAZB/
stevenz17
https://www.tradingview.com/u/stevenz17/
6
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/ // Β© Steven A. Zmuda Burke / stevenz17 // From Date Inputs fromDay = input(defval = 01, title = "From Day", minval = 1, maxval = 31) fromMonth = input(defval = 04, title = "From Month", minval = 1, maxval = 12) fromYear = input(defval = 2022, title = "From Year", minval = 1970) // To Date Inputs toDay = input(defval = 01, title = "To Day", minval = 1, maxval = 31) toMonth = input(defval = 05, title = "To Month", minval = 1, maxval = 12) toYear = input(defval = 2022, title = "To Year", minval = 1970) // Calculate start/end date and time condition startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00) finishDate = timestamp(toYear, toMonth, toDay, 00, 00) time_cond = time >= startDate and time <= finishDate // Input strategy("LONG", overlay=true, initial_capital=1000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, slippage=1, commission_type=strategy.commission.percent, commission_value=0.015) SOURCE = input(title = "═════════════════════ SOURCE ═════════════════════", defval = false, type = input.bool) sourcehl2 = input(title="Source hl2 or (open+close)/2 ?",type=input.bool,defval=true) source = sourcehl2 ? hl2 : ((open+close)/2) //MTF EMA MTFEMA = input(title = "════════════════════ MTF EMA ════════════════════", defval = false, type = input.bool) res1=input(title="MTF EMA 1", type=input.resolution, defval="60") len1 = input(title = "EMA Period 1", type=input.integer, defval=70, minval=1) ema1 = ema(source, len1) emaStep1 = security (syminfo.tickerid, res1, ema1, barmerge.gaps_off, barmerge.lookahead_off) mtf1 = emaStep1 res2=input(title="MTF EMA 2", type=input.resolution, defval="15") len2 = input(title = "EMA Period 2", type=input.integer, defval=68, minval=1) ema2 = ema(source, len2) emaStep2 = security (syminfo.tickerid, res2, ema2, barmerge.gaps_off, barmerge.lookahead_off) mtf2 = emaStep2 t1 = plot(mtf1, linewidth=4, color= color.aqua, title="EMA") t2 = plot(mtf2, linewidth=4, color= color.navy, title="EMA") fill(t1, t2, transp = 70, color = mtf1 > mtf2 ? color.red : color.green) ///MACD MACD= input(title = "═════════════════════ MACD ══════════════════════", defval = false, type = input.bool) MACDsource=close fastLength = input(13, minval=1, title="MACD fast moving average") slowLength=input(18,minval=1, title="MACD slow moving average") signalLength=input(24,minval=1, title="MACD signal line moving average") MacdEmaLength =input(9, title="MACD EMA period", minval=1) useEma = input(true, title="Use EMA (otherwise SMA)") useOldAlgo = input(false, title="Use normal MACD") Lmacsig=input(title="LONG MACD and signal crossover limit",type=input.integer,defval=180) // Fast line ma1= useEma ? ema(MACDsource, fastLength) : sma(MACDsource, fastLength) ma2 = useEma ? ema(ma1,fastLength) : sma(ma1,fastLength) fastMA = ((2 * ma1) - ma2) // Slow line mas1= useEma ? ema(MACDsource , slowLength) : sma(MACDsource , slowLength) mas2 = useEma ? ema(mas1 , slowLength): sma(mas1 , slowLength) slowMA = ((2 * mas1) - mas2) // MACD line macd = fastMA - slowMA // Signal line emasig1 = ema(macd, signalLength) emasig2 = ema(emasig1, signalLength) signal = useOldAlgo ? sma(macd, signalLength) : (2 * emasig1) - emasig2 hist = macd - signal histline = hist > 0 ? color.green : color.red //MACD ribbon macdribbon=input(title="Show MACD ribbon?",type=input.bool,defval=false) macdx=input(title="MACD ribbon multiplier", type=input.integer, defval=3, minval=1) leadLine1 = macdribbon ? macd*macdx + source : na leadLine2 = macdribbon ? signal*macdx + source : na leadLine3 = hist + source //MACD plot p3 = plot(leadLine1, color= color.green, title="MACD", transp = 100, linewidth = 8) p4 = plot(leadLine2, color= color.red, title="Signal", transp = 100, linewidth = 8) fill(p3, p4, transp = 20, color = leadLine1 > leadLine2 ? #53b987 : #eb4d5c) plot((leadLine3), color = histline, title="Histogram", linewidth = 3) l="TEst" upHist = (hist > 0) ? hist : 0 downHist = (hist <= 0) ? hist : 0 p1 = plot(upHist, color=color.green, transp=40, style=plot.style_columns, title='Positive delta') p2 = plot(downHist, color=color.green, transp=40, style=plot.style_columns, title='Negative delta') zeroLine = plot(macd, color=color.black, transp=0, linewidth=2, title='MACD line') signalLine = plot(signal, color=color.gray, transp=0, linewidth=2, title='Signal') ribbonDiff = color.green fill(zeroLine, signalLine, color=ribbonDiff) circleYPosition = signal plot(ema(macd,MacdEmaLength) , color=color.red, transp=0, linewidth=2, title='EMA on MACD line') ribbonDiff2 = hist > 0 ? color.green : color.red plot(crossunder(signal,macd) ? circleYPosition : na,style=plot.style_circles, linewidth=4, color=ribbonDiff, title='Dots') //STOCHASTIC stochchch= input(title = "═══════════════════ STOCHASTIC ════════════════════", defval = false, type = input.bool) StochOn = input(title="Stochastic On?",type=input.bool,defval=true) periodK = input(10, title="K", minval=1) periodD = input(1, title="D", minval=1) smoothK = input(3, title="Smooth", minval=1) stochlimit = input(30, title="Stoch value crossover", minval=1) k = sma(stoch(close, high, low, periodK), smoothK) d = sma(k, periodD) stochSignal = StochOn ? (d < stochlimit ? true : false) : true pp= input(1, title="avg price length", minval=1) p = ema (source, pp) K = k + p plot(k, title="%K", color=#0094FF) plot(d, title="%D", color=#FF6A00) h0 = hline(72, "Upper Band", color=#606060) h1 = hline(20, "Lower Band", color=#606060) fill(h0, h1, color=#9915FF, transp=80, title="Background") //Long LS= "════════════════════════════════ LONG CONDITIONS ═══════════════════════════" uptrend = close > mtf1 and mtf1 < mtf2 downtrend = close < mtf1 and mtf1 > mtf2 crossMACD = crossunder(macd,signal) LongBuy = uptrend and stochSignal? crossMACD and signal < Lmacsig and macd < Lmacsig : na LONG = strategy.position_size > 0 SHORT = strategy.position_size < 0 FLAT = strategy.position_size == 0 plotshape(LongBuy, style=shape.xcross, text="LONG", color=color.green) //ATR & TP/SL ATRTPSLX= input(title = "═════════════════ LONG SL ═════════════════", defval = false, type = input.bool) maxIdLossPcnt = input(5, "Max Intraday Loss(%)", type=input.float, minval=0.0, step=0.1) strategy.risk.max_intraday_loss(maxIdLossPcnt, strategy.percent_of_equity) SSL2=input(title="Long Stop Loss when MTF EMA cross?",type=input.bool,defval=false) SSLOP = LONG and crossunder(source, mtf1) SlossPercOn = input(title="Long Stop Loss (%) on?",type=input.bool,defval=false) SlossPerc = input(title="Long Stop Loss (%)", type=input.float, minval=0.0, step=0.1, defval=4.7) * 0.01 SSpricePerc = LONG and SlossPercOn? strategy.position_avg_price * (-1 - SlossPerc) : na plot(series = SSpricePerc, linewidth=2, color= color.maroon,style=plot.style_linebr, title="Long Stop Loss %") SSLX = LONG and crossunder(source, SSpricePerc) SSLatr= input(title="Long Stop Loss ATR?",type=input.bool,defval=true) useStructure=input(title="Look back for High/Lows?",type=input.bool,defval=true) Slookback=input(title="How far to look back for High/Lows:",type=input.integer,defval=18,minval=1) SatrLenghth=input(title="Long ATR Lenghth",type=input.integer,defval=9,minval=1) SatrStopMultiplier=input(title="Long ATR Stop x ?", type=input.float,defval=4.3, minval=0.1,step=0.1) Satr = atr(SatrLenghth) LongStop = SSLatr ? ((useStructure ? lowest(low, Slookback) : source) - Satr * SatrStopMultiplier) : na SStop = crossunder(source,LongStop) plot(Satr, color=color.blue, title="ATR", transp=100) plot(series = uptrend ? LongStop : na, color=color.red, style=plot.style_linebr, title="Long Trailing Stop", transp=0) ATRTPSLXX= input(title = "═════════════════ LONG TP ═════════════════", defval = false, type = input.bool) TpPercOn = input(title="Long Take Profit (%) on?",type=input.bool,defval=true) TpPerc = input(title="Long Take Profit (%)", type=input.float, minval=0.0, step=0.1, defval=5.3) * 0.01 TppricePerc = LONG and TpPercOn? strategy.position_avg_price * (-1 + TpPerc) : na plot(series = TppricePerc, linewidth=2, color= color.lime,style=plot.style_linebr, title="Long Take Profit %") TPLX = LONG and crossunder(source, TppricePerc) TP1=input(title="1 Long Take Profit On?",type=input.bool,defval=true) useStructure1=input(title="Look back for High/Lows?",type=input.bool,defval=true) STplookback=input(title="How far to look back for High/Lows for 1 TP",type=input.integer,defval=12,minval=1) STpatrLenghth=input(title="Long ATR Lenghth 1 TP",type=input.integer,defval=24,minval=1) SatrProfitMultiplier = input(title="First Long ATR Take Profit x ?", type=input.float,defval=5.5, minval=0.1,step=0.1) STpatr = atr(STpatrLenghth) LongTakeProfit = (useStructure1 ? highest(high, STplookback) : source) + STpatr * SatrProfitMultiplier LongTP = TP1 ? crossover(source, LongTakeProfit): false plot(series = uptrend ? LongTakeProfit: na , color=color.green, style=plot.style_linebr, title="Long Trailing Take Profit", transp=0) // Bar color barcolor(cross(macd, signal) ? (macd - signal > 0 ? (uptrend and macd < 0 and signal < 0 ? color.yellow : na) : (downtrend and macd > 0 and signal > 0 ? color.blue : na)) : na) // Strategy ATR GOLONG = LongBuy and SSLatr and FLAT if GOLONG and TP1 strategy.entry(id="Entry LONG 1TP", long=true,comment="Entry Long") strategy.exit("Long Profit or Loss 1TP","Entry LONG 1TP", limit=LongTakeProfit, stop=LongStop) if SSLX strategy.close(id="Entry LONG 1TP", comment="% Long SL EXIT") if TPLX strategy.close(id="Entry LONG 1TP", comment="% Long TP EXIT") if SSLOP and SSL2 strategy.close(id="Entry LONG 1TP", comment="MTF EMA cross EXIT") if (not time_cond) strategy.close_all() strategy.cancel_all() //plot(strategy.equity, title="equity", color=red, linewidth=2, style=areabr) //@version=4
Swing Trend Strategy
https://www.tradingview.com/script/Z51SyFk2-Swing-Trend-Strategy/
Inkedlau
https://www.tradingview.com/u/Inkedlau/
211
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/ // Β© Inkedlau //@version=5 strategy('Swing Trend Strategy', overlay=true, pyramiding=1, default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=1000, commission_value=0.1) use_short = input.bool(false, 'Open Short Positions?') exit_type = input.bool(true, 'Exit trade on Moving Average Cross?') src = input.source(close, 'Source') len = input.int(200, 'Trend Length') ma_type = input.string('ema', 'Moving Average Type', options=['sma', 'ema', 'rma', 'wma', 'vwma'], tooltip='Select the type of Moving Average to use to calculate the Trend') atr_multiplier = input.float(1., 'ATR Threshold', step=0.5, tooltip='Filter the ranging market using the Average True Range') // ----------------------- DESCRIPTION ----------------------- // THIS SCRIPT IS A TREND FOLLOWING SYSTEM THAT USES A COMBINATION OF MOVING AVERAGE AND AVERAGE TRUE RANGE // TO SPOT THE TRENDS AND ENTER THE MARKET ACCODINGLY. // THE MARKET IS CONSIDERED IN AN UPTREND WHEN THE PRICE CLOSES ABOVE THE MOVING AVERAGE + THE AVERAGE TRUE RANGE OF THE LAST 10 PERIODS // THE MARKET IS CONSIDERED IN AN DOWNTREND WHEN THE PRICE CLOSES BLOW THE MOVING AVERAGE - THE AVERAGE TRUE RANGE OF THE LAST 10 PERIODS // BY DEFAULT, THE STRATEGY WILL ENTER LONG WHEN AN UPTREND IS SPOTTED, THEN CLOSES WHEN THE PRICE CLOSES BELOW THE MOVING AVERAGE // THE STRATEGY WILL ENTER SHORT WHEN A DOWNTREND IS SPOTTED, THEN CLOSES WHEN THE PRICE CLOSES ABOVE THE MOVING AVERAGE // ------------------ INDICATORS CALCULATION------------------ my_ma()=> ma = close if ma_type == 'sma' ma := ta.sma(src, len) if ma_type == 'ema' ma := ta.ema(src, len) if ma_type == 'rma' ma := ta.rma(src, len) if ma_type == 'wma' ma := ta.wma(src, len) if ma_type == 'vwma' ma := ta.vwma(src, len) ma trend = my_ma() atr = ta.atr(10) uptrend = trend + atr * atr_multiplier downtrend = trend - atr * atr_multiplier // ---------------- ENTRY AND EXIT CONDITIONS ---------------- open_long = strategy.position_size == 0 and src > uptrend close_long = exit_type ? strategy.position_size > 0 and src < trend : strategy.position_size > 0 and src < downtrend open_short = use_short and strategy.position_size == 0 and src < downtrend close_short = exit_type ? strategy.position_size < 0 and src > trend : strategy.position_size < 0 and src > uptrend strategy.entry('long', strategy.long, when=open_long) strategy.close('long', when=close_long) strategy.entry('short', strategy.short, when=open_short) strategy.close('short', when=close_short) // ------------------ PLOTTING AND COLORING ------------------ tcolor = src > uptrend ? color.green : src < downtrend ? color.red : na ptrend = plot(trend, color=color.blue, linewidth=1) puptrend = plot(uptrend, color=color.green, linewidth=1) pdowntrend = plot(downtrend, color=color.red, linewidth=1) pclose = plot(close, color=na) fill(puptrend, pclose, color=close > uptrend ? color.green : na, transp = 90) fill(pdowntrend, pclose, color=close < downtrend ? color.red : na, transp = 90)
Ichimoku Cloud with RSI (By Coinrule)
https://www.tradingview.com/script/2OfRyQSy-Ichimoku-Cloud-with-RSI-By-Coinrule/
Coinrule
https://www.tradingview.com/u/Coinrule/
401
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© Coinrule //@version=5 strategy("Ichimoku Cloud with RSI (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) showDate = input(defval=true, title='Show Date Range') timePeriod = time >= timestamp(syminfo.timezone, 2022, 6, 1, 0, 0) // RSI inputs and calculations lengthRSI = 14 RSI = ta.rsi(close, lengthRSI) //Inputs ts_bars = input.int(9, minval=1, title="Tenkan-Sen Bars") ks_bars = input.int(26, minval=1, title="Kijun-Sen Bars") ssb_bars = input.int(52, minval=1, title="Senkou-Span B Bars") cs_offset = input.int(26, minval=1, title="Chikou-Span Offset") ss_offset = input.int(26, minval=1, title="Senkou-Span Offset") long_entry = input(true, title="Long Entry") short_entry = input(true, title="Short Entry") middle(len) => math.avg(ta.lowest(len), ta.highest(len)) // Components of Ichimoku Cloud tenkan = middle(ts_bars) kijun = middle(ks_bars) senkouA = math.avg(tenkan, kijun) senkouB = middle(ssb_bars) // Plot Ichimoku Cloud plot(tenkan, color=#0496ff, title="Tenkan-Sen") plot(kijun, color=#991515, title="Kijun-Sen") plot(close, offset=-cs_offset+1, color=#459915, title="Chikou-Span") sa=plot(senkouA, offset=ss_offset-1, color=color.green, title="Senkou-Span A") sb=plot(senkouB, offset=ss_offset-1, color=color.red, title="Senkou-Span B") fill(sa, sb, color = senkouA > senkouB ? color.green : color.red, title="Cloud color") ss_high = math.max(senkouA[ss_offset-1], senkouB[ss_offset-1]) ss_low = math.min(senkouA[ss_offset-1], senkouB[ss_offset-1]) // Entry/Exit Conditions tk_cross_bull = tenkan > kijun tk_cross_bear = tenkan < kijun cs_cross_bull = ta.mom(close, cs_offset-1) > 0 cs_cross_bear = ta.mom(close, cs_offset-1) < 0 price_above_kumo = close > ss_high price_below_kumo = close < ss_low bullish = tk_cross_bull and cs_cross_bull and price_above_kumo bearish = tk_cross_bear and cs_cross_bear and price_below_kumo strategy.entry("Long", strategy.long, when=bullish and long_entry and RSI < 50 and timePeriod) strategy.close("Long", when=bearish and not short_entry) strategy.entry("Short", strategy.short, when=bearish and short_entry and RSI > 50 and timePeriod) strategy.close("Short", when=bullish and not long_entry)
AlphaTrend Strategy
https://www.tradingview.com/script/3wdQu7P3-AlphaTrend-Strategy/
KivancOzbilgic
https://www.tradingview.com/u/KivancOzbilgic/
4,652
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // author Β© KivancOzbilgic // developer Β© KivancOzbilgic //@version=5 strategy("AlphaTrend Strategy", shorttitle='ATSt', overlay=true, format=format.price, precision=2, margin_long=100, margin_short=100) coeff = input.float(1, 'Multiplier', step=0.1) AP = input(14, 'Common Period') ATR = ta.sma(ta.tr, AP) src = input(close) showsignalsk = input(title='Show Signals?', defval=false) novolumedata = input(title='Change calculation (no volume data)?', defval=false) upT = low - ATR * coeff downT = high + ATR * coeff AlphaTrend = 0.0 AlphaTrend := (novolumedata ? ta.rsi(src, AP) >= 50 : ta.mfi(hlc3, AP) >= 50) ? upT < nz(AlphaTrend[1]) ? nz(AlphaTrend[1]) : upT : downT > nz(AlphaTrend[1]) ? nz(AlphaTrend[1]) : downT color1 = AlphaTrend > AlphaTrend[2] ? #00E60F : AlphaTrend < AlphaTrend[2] ? #80000B : AlphaTrend[1] > AlphaTrend[3] ? #00E60F : #80000B k1 = plot(AlphaTrend, color=color.new(#0022FC, 0), linewidth=3) k2 = plot(AlphaTrend[2], color=color.new(#FC0400, 0), linewidth=3) fill(k1, k2, color=color1) buySignalk = ta.crossover(AlphaTrend, AlphaTrend[2]) sellSignalk = ta.crossunder(AlphaTrend, AlphaTrend[2]) K1 = ta.barssince(buySignalk) K2 = ta.barssince(sellSignalk) O1 = ta.barssince(buySignalk[1]) O2 = ta.barssince(sellSignalk[1]) plotshape(buySignalk and showsignalsk and O1 > K2 ? AlphaTrend[2] * 0.9999 : na, title='BUY', text='BUY', location=location.absolute, style=shape.labelup, size=size.tiny, color=color.new(#0022FC, 0), textcolor=color.new(color.white, 0)) plotshape(sellSignalk and showsignalsk and O2 > K1 ? AlphaTrend[2] * 1.0001 : na, title='SELL', text='SELL', location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.new(color.maroon, 0), textcolor=color.new(color.white, 0)) longCondition = buySignalk if (longCondition) strategy.entry("Long", strategy.long) shortCondition = sellSignalk if (shortCondition) strategy.entry("Short", strategy.short)
Bitcoin Scalping Strategy (Sampled with: PMARP+MADRID MA RIBBON)
https://www.tradingview.com/script/T4rBZCvC-Bitcoin-Scalping-Strategy-Sampled-with-PMARP-MADRID-MA-RIBBON/
CheatCode1
https://www.tradingview.com/u/CheatCode1/
1,220
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© CheatCode1 //@version=5 strategy("PMAR and Madrid MA Strategy Excecuted by @CheatCode1", overlay=false, margin_long=0, margin_short=0, default_qty_type = strategy.cash, initial_capital = 1000, pyramiding = 0, default_qty_value = 1000, max_bars_back = 100) // // THIS IS PMARP, AN INDiCATOR CREATED BY @THE_CARETAKER, I DO NOT TAKE CREDIT FOR ANY SCRIPT WRITTEN UNTIL THE START OF THE NEXT INDICATOR. PLEASE REFER TO @The_Caretaker FOR QUESTIONS REGARDING THE PMAR/PMARP INDICATOR. THANK YOU! // // THIS IS PMARP, AN INDiCATOR CREATED BY @THE_CARETAKER, I DO NOT TAKE CREDIT FOR ANY SCRiPT WRITTEN UNTIL THE START OF THE NEXT INDICATOR. PLEASE REFER TO @The_Caretaker FOR QUESTIONS REGARDING THE PMAR/PMARP INDICATOR. THANK YOU! // // THIS IS PMARP, AN INDiCATOR CREATED BY @THE_CARETAKER, I DO NOT TAKE CREDIT FOR ANY SCRIPT WRITTEN UNTIL THE START OF THE NEXT INDICATOR. PLEASE REFER TO @The_Caretaker FOR QUESTIONS REGARDING THE PMAR/PMARP INDICATOR. THANK YOU! // @version=5 // // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // @author = The_Caretaker // Β© The_Caretaker // // Much respect to Eric Crown for this idea. // // Feel free to reuse or develop this script further, please drop me a note below if you find it useful. // /////////////////////////////////////////////////////////////////////////////// // Input default variable declarations var string s_pmarp = 'Price Moving Average Ratio Percentile' var string s_pmar = 'Price Moving Average Ratio' var string s_BGR = 'Blue Green Red' var string s_BR = 'Blue Red' var float pmarHigh = 0.0 /////////////////////////////////////////////////////////////////////////////// // Inputs i_src_price = input.source ( close, 'Price source', inline='1', group='Main Properties') i_p_type_line = input.string ( s_pmarp, 'Indicator....', options=[ s_pmar, s_pmarp ], inline='2', group='Main Properties') i_ma_len = input.int ( 20, 'PMAR length', minval=1, inline='3', group='Main Properties') i_ma_typ = input.string ( 'VWMA', 'MA type...', options=[ 'SMA', 'EMA', 'HMA', 'RMA', 'VWMA' ], inline='3', group='Main Properties') i_c_typ_line = input.string ( 'Spectrum', 'Color type', options=[ 'Spectrum', 'Solid' ], inline='1', group='Line plot settings') i_c_typ_spctrm_line = input.string ( s_BGR, 'Spectrum', options=[ s_BR, s_BGR ], inline='1', group='Line plot settings') i_c_solid_line = input.color ( #FFFF00, 'Solid color', inline='1', group='Line plot settings') i_p_width_line = input.int ( 1, 'Line width', minval=1, maxval=4, inline='2', group='Line plot settings') i_pmarp_lookback = input.int ( 350, 'Lookback', minval=1, maxval=1900, inline='2', group='Line plot settings') i_show_signal_ma = input.bool ( true, 'Signal MA', inline='0', group='Signal MA Settings') i_signal_ma_Len = input.int ( 20, 'MA length', minval=1, inline='1', group='Signal MA Settings') i_signal_ma_typ = input.string ( 'SMA', 'MA type', options=[ 'SMA', 'EMA', 'HMA', 'RMA', 'VWMA' ], inline='1', group='Signal MA Settings') i_c_typ_sig = input.string ( 'Solid', 'Color type', options=[ 'Spectrum', 'Solid' ], inline='2', group='Signal MA Settings') i_c_typ_spctrm_sig = input.string ( s_BGR, 'Spectrum', options=[ s_BR, s_BGR ], inline='2', group='Signal MA Settings') i_c_solid_sig = input.color ( color.white, 'Solid color', inline='2', group='Signal MA Settings') i_p_width_sig = input.int ( 1, 'Line width', minval=1, maxval=4, inline='3', group='Signal MA Settings') i_hi_alert_pmarp = input.float ( 99, 'Hi PMARP alert level', minval=0.1, maxval=100, step=0.01, inline='6', group='Visual Alert Level Settings') i_lo_alert_pmarp = input.float ( 1, 'Lo PMARP alert level', minval=0.1, maxval=100, step=0.01, inline='6', group='Visual Alert Level Settings') i_hi_alert_pmar = input.float ( 2.7, 'Hi PMAR alert level.', minval=0.1, maxval=100, step=0.01, inline='7', group='Visual Alert Level Settings') i_lo_alert_pmar = input.float ( 0.7, 'Lo PMAR alert level.', minval=0.1, maxval=100, step=0.01, inline='7', group='Visual Alert Level Settings') i_hi_alert_line_on = input.bool ( true, 'Hi alert line.', inline='8', group='Visual Alert Level Settings') i_lo_alert_line_on = input.bool ( true, 'Lo alert line.', inline='8', group='Visual Alert Level Settings') i_bg_hi_signal_on = input.bool ( true, 'Hi signal bars', inline='9', group='Visual Alert Level Settings') i_bg_lo_signal_on = input.bool ( true, 'Lo signal bars', inline='9', group='Visual Alert Level Settings') /////////////////////////////////////////////////////////////////////////////// // variable declarations var c_prcntSpctrm1 = array.new_color ( na ) if barstate.isfirst array.push ( c_prcntSpctrm1, #0000FF ), array.push ( c_prcntSpctrm1, #000AFF ), array.push ( c_prcntSpctrm1, #0014FF ), array.push ( c_prcntSpctrm1, #001FFF ), array.push ( c_prcntSpctrm1, #0029FF ), array.push ( c_prcntSpctrm1, #0033FF ), array.push ( c_prcntSpctrm1, #003DFF ), array.push ( c_prcntSpctrm1, #0047FF ), array.push ( c_prcntSpctrm1, #0052FF ), array.push ( c_prcntSpctrm1, #005CFF ), array.push ( c_prcntSpctrm1, #0066FF ), array.push ( c_prcntSpctrm1, #0070FF ), array.push ( c_prcntSpctrm1, #007AFF ), array.push ( c_prcntSpctrm1, #0085FF ), array.push ( c_prcntSpctrm1, #008FFF ), array.push ( c_prcntSpctrm1, #0099FF ), array.push ( c_prcntSpctrm1, #00A3FF ), array.push ( c_prcntSpctrm1, #00ADFF ), array.push ( c_prcntSpctrm1, #00B8FF ), array.push ( c_prcntSpctrm1, #00C2FF ), array.push ( c_prcntSpctrm1, #00CCFF ), array.push ( c_prcntSpctrm1, #00D6FF ), array.push ( c_prcntSpctrm1, #00E0FF ), array.push ( c_prcntSpctrm1, #00EBFF ), array.push ( c_prcntSpctrm1, #00F5FF ), array.push ( c_prcntSpctrm1, #00FFFF ), array.push ( c_prcntSpctrm1, #00FFF5 ), array.push ( c_prcntSpctrm1, #00FFEB ), array.push ( c_prcntSpctrm1, #00FFE0 ), array.push ( c_prcntSpctrm1, #00FFD6 ), array.push ( c_prcntSpctrm1, #00FFCC ), array.push ( c_prcntSpctrm1, #00FFC2 ), array.push ( c_prcntSpctrm1, #00FFB8 ), array.push ( c_prcntSpctrm1, #00FFAD ), array.push ( c_prcntSpctrm1, #00FFA3 ), array.push ( c_prcntSpctrm1, #00FF99 ), array.push ( c_prcntSpctrm1, #00FF8F ), array.push ( c_prcntSpctrm1, #00FF85 ), array.push ( c_prcntSpctrm1, #00FF7A ), array.push ( c_prcntSpctrm1, #00FF70 ), array.push ( c_prcntSpctrm1, #00FF66 ), array.push ( c_prcntSpctrm1, #00FF5C ), array.push ( c_prcntSpctrm1, #00FF52 ), array.push ( c_prcntSpctrm1, #00FF47 ), array.push ( c_prcntSpctrm1, #00FF3D ), array.push ( c_prcntSpctrm1, #00FF33 ), array.push ( c_prcntSpctrm1, #00FF29 ), array.push ( c_prcntSpctrm1, #00FF1F ), array.push ( c_prcntSpctrm1, #00FF14 ), array.push ( c_prcntSpctrm1, #00FF0A ), array.push ( c_prcntSpctrm1, #00FF00 ), array.push ( c_prcntSpctrm1, #0AFF00 ), array.push ( c_prcntSpctrm1, #14FF00 ), array.push ( c_prcntSpctrm1, #1FFF00 ), array.push ( c_prcntSpctrm1, #29FF00 ), array.push ( c_prcntSpctrm1, #33FF00 ), array.push ( c_prcntSpctrm1, #3DFF00 ), array.push ( c_prcntSpctrm1, #47FF00 ), array.push ( c_prcntSpctrm1, #52FF00 ), array.push ( c_prcntSpctrm1, #5CFF00 ), array.push ( c_prcntSpctrm1, #66FF00 ), array.push ( c_prcntSpctrm1, #70FF00 ), array.push ( c_prcntSpctrm1, #7AFF00 ), array.push ( c_prcntSpctrm1, #85FF00 ), array.push ( c_prcntSpctrm1, #8FFF00 ), array.push ( c_prcntSpctrm1, #99FF00 ), array.push ( c_prcntSpctrm1, #A3FF00 ), array.push ( c_prcntSpctrm1, #ADFF00 ), array.push ( c_prcntSpctrm1, #B8FF00 ), array.push ( c_prcntSpctrm1, #C2FF00 ), array.push ( c_prcntSpctrm1, #CCFF00 ), array.push ( c_prcntSpctrm1, #D6FF00 ), array.push ( c_prcntSpctrm1, #E0FF00 ), array.push ( c_prcntSpctrm1, #EBFF00 ), array.push ( c_prcntSpctrm1, #F5FF00 ), array.push ( c_prcntSpctrm1, #FFFF00 ), array.push ( c_prcntSpctrm1, #FFF500 ), array.push ( c_prcntSpctrm1, #FFEB00 ), array.push ( c_prcntSpctrm1, #FFE000 ), array.push ( c_prcntSpctrm1, #FFD600 ), array.push ( c_prcntSpctrm1, #FFCC00 ), array.push ( c_prcntSpctrm1, #FFC200 ), array.push ( c_prcntSpctrm1, #FFB800 ), array.push ( c_prcntSpctrm1, #FFAD00 ), array.push ( c_prcntSpctrm1, #FFA300 ), array.push ( c_prcntSpctrm1, #FF9900 ), array.push ( c_prcntSpctrm1, #FF8F00 ), array.push ( c_prcntSpctrm1, #FF8500 ), array.push ( c_prcntSpctrm1, #FF7A00 ), array.push ( c_prcntSpctrm1, #FF7000 ), array.push ( c_prcntSpctrm1, #FF6600 ), array.push ( c_prcntSpctrm1, #FF5C00 ), array.push ( c_prcntSpctrm1, #FF5200 ), array.push ( c_prcntSpctrm1, #FF4700 ), array.push ( c_prcntSpctrm1, #FF3D00 ), array.push ( c_prcntSpctrm1, #FF3300 ), array.push ( c_prcntSpctrm1, #FF2900 ), array.push ( c_prcntSpctrm1, #FF1F00 ), array.push ( c_prcntSpctrm1, #FF1400 ), array.push ( c_prcntSpctrm1, #FF0000 ), array.push ( c_prcntSpctrm1, #FF0000 ) var c_prcntSpctrm2 = array.new_color ( na ) if barstate.isfirst array.push ( c_prcntSpctrm2, #0000FF ), array.push ( c_prcntSpctrm2, #0200FC ), array.push ( c_prcntSpctrm2, #0500F9 ), array.push ( c_prcntSpctrm2, #0700F7 ), array.push ( c_prcntSpctrm2, #0A00F4 ), array.push ( c_prcntSpctrm2, #0C00F2 ), array.push ( c_prcntSpctrm2, #0F00EF ), array.push ( c_prcntSpctrm2, #1100ED ), array.push ( c_prcntSpctrm2, #1400EA ), array.push ( c_prcntSpctrm2, #1600E8 ), array.push ( c_prcntSpctrm2, #1900E5 ), array.push ( c_prcntSpctrm2, #1C00E2 ), array.push ( c_prcntSpctrm2, #1E00E0 ), array.push ( c_prcntSpctrm2, #2100DD ), array.push ( c_prcntSpctrm2, #2300DB ), array.push ( c_prcntSpctrm2, #2600D8 ), array.push ( c_prcntSpctrm2, #2800D6 ), array.push ( c_prcntSpctrm2, #2B00D3 ), array.push ( c_prcntSpctrm2, #2D00D1 ), array.push ( c_prcntSpctrm2, #3000CE ), array.push ( c_prcntSpctrm2, #3300CC ), array.push ( c_prcntSpctrm2, #3500C9 ), array.push ( c_prcntSpctrm2, #3800C6 ), array.push ( c_prcntSpctrm2, #3A00C4 ), array.push ( c_prcntSpctrm2, #3D00C1 ), array.push ( c_prcntSpctrm2, #3F00BF ), array.push ( c_prcntSpctrm2, #4200BC ), array.push ( c_prcntSpctrm2, #4400BA ), array.push ( c_prcntSpctrm2, #4700B7 ), array.push ( c_prcntSpctrm2, #4900B5 ), array.push ( c_prcntSpctrm2, #4C00B2 ), array.push ( c_prcntSpctrm2, #4F00AF ), array.push ( c_prcntSpctrm2, #5100AD ), array.push ( c_prcntSpctrm2, #5400AA ), array.push ( c_prcntSpctrm2, #5600A8 ), array.push ( c_prcntSpctrm2, #5900A5 ), array.push ( c_prcntSpctrm2, #5B00A3 ), array.push ( c_prcntSpctrm2, #5E00A0 ), array.push ( c_prcntSpctrm2, #60009E ), array.push ( c_prcntSpctrm2, #63009B ), array.push ( c_prcntSpctrm2, #660099 ), array.push ( c_prcntSpctrm2, #680096 ), array.push ( c_prcntSpctrm2, #6B0093 ), array.push ( c_prcntSpctrm2, #6D0091 ), array.push ( c_prcntSpctrm2, #70008E ), array.push ( c_prcntSpctrm2, #72008C ), array.push ( c_prcntSpctrm2, #750089 ), array.push ( c_prcntSpctrm2, #770087 ), array.push ( c_prcntSpctrm2, #7A0084 ), array.push ( c_prcntSpctrm2, #7C0082 ), array.push ( c_prcntSpctrm2, #7F007F ), array.push ( c_prcntSpctrm2, #82007C ), array.push ( c_prcntSpctrm2, #84007A ), array.push ( c_prcntSpctrm2, #870077 ), array.push ( c_prcntSpctrm2, #890075 ), array.push ( c_prcntSpctrm2, #8C0072 ), array.push ( c_prcntSpctrm2, #8E0070 ), array.push ( c_prcntSpctrm2, #91006D ), array.push ( c_prcntSpctrm2, #93006B ), array.push ( c_prcntSpctrm2, #960068 ), array.push ( c_prcntSpctrm2, #990066 ), array.push ( c_prcntSpctrm2, #9B0063 ), array.push ( c_prcntSpctrm2, #9E0060 ), array.push ( c_prcntSpctrm2, #A0005E ), array.push ( c_prcntSpctrm2, #A3005B ), array.push ( c_prcntSpctrm2, #A50059 ), array.push ( c_prcntSpctrm2, #A80056 ), array.push ( c_prcntSpctrm2, #AA0054 ), array.push ( c_prcntSpctrm2, #AD0051 ), array.push ( c_prcntSpctrm2, #AF004F ), array.push ( c_prcntSpctrm2, #B2004C ), array.push ( c_prcntSpctrm2, #B50049 ), array.push ( c_prcntSpctrm2, #B70047 ), array.push ( c_prcntSpctrm2, #BA0044 ), array.push ( c_prcntSpctrm2, #BC0042 ), array.push ( c_prcntSpctrm2, #BF003F ), array.push ( c_prcntSpctrm2, #C1003D ), array.push ( c_prcntSpctrm2, #C4003A ), array.push ( c_prcntSpctrm2, #C60038 ), array.push ( c_prcntSpctrm2, #C90035 ), array.push ( c_prcntSpctrm2, #CC0033 ), array.push ( c_prcntSpctrm2, #CE0030 ), array.push ( c_prcntSpctrm2, #D1002D ), array.push ( c_prcntSpctrm2, #D3002B ), array.push ( c_prcntSpctrm2, #D60028 ), array.push ( c_prcntSpctrm2, #D80026 ), array.push ( c_prcntSpctrm2, #DB0023 ), array.push ( c_prcntSpctrm2, #DD0021 ), array.push ( c_prcntSpctrm2, #E0001E ), array.push ( c_prcntSpctrm2, #E2001C ), array.push ( c_prcntSpctrm2, #E50019 ), array.push ( c_prcntSpctrm2, #E80016 ), array.push ( c_prcntSpctrm2, #EA0014 ), array.push ( c_prcntSpctrm2, #ED0011 ), array.push ( c_prcntSpctrm2, #EF000F ), array.push ( c_prcntSpctrm2, #F2000C ), array.push ( c_prcntSpctrm2, #F4000A ), array.push ( c_prcntSpctrm2, #F70007 ), array.push ( c_prcntSpctrm2, #F90005 ), array.push ( c_prcntSpctrm2, #FC0002 ), array.push ( c_prcntSpctrm2, #FF0000 ) /////////////////////////////////////////////////////////////////////////////// // Function Declarations f_prior_sum ( _P, _X ) => math.sum ( _P[1], _X - 1 ) f_ma_val ( _P, _typ, _len ) => _typ == 'SMA' ? ta.sma ( _P, _len ) : _typ == 'EMA' ? ta.ema ( _P, _len ) : _typ == 'RMA' ? ta.rma ( _P, _len ) : _typ == 'HMA' ? ta.hma ( _P, _len ) : ta.vwma ( _P, _len ) f_pmarp ( _price, _pmarLen, _pmarpLen, _type ) => _pmar = math.abs ( _price / f_ma_val ( _price, _type, _pmarLen )) _pmarpSum = 0 _len = bar_index < _pmarpLen ? bar_index : _pmarpLen for i = 1 to _len by 1 _pmarpSum += ( _pmar[i] > _pmar ? 0 : 1 ) _pmarpSum _return = bar_index >= _pmarLen ? _pmarpSum / _len * 100 : na f_clrSlct ( _percent, _select, _type, _solid, _array1, _array2 ) => _select == 'Solid' ? _solid : array.get ( _type == 'Blue Green Red' ? _array1 : _array2, math.round ( _percent )) /////////////////////////////////////////////////////////////////////////////// // calculations pmarpOn = i_p_type_line == 'Price Moving Average Ratio Percentile' ma = f_ma_val ( i_src_price, i_ma_typ, i_ma_len ) pmar = i_src_price / ma pmarp = f_pmarp ( i_src_price, i_ma_len, i_pmarp_lookback, i_ma_typ ) pmarHigh := pmar > pmarHigh ? pmar : pmarHigh c_pmar = ( pmar / pmarHigh )*100 plotline = pmarpOn ? pmarp : pmar c_plotline = f_clrSlct ( pmarpOn ? plotline : c_pmar, i_c_typ_line, i_c_typ_spctrm_line, i_c_solid_line, c_prcntSpctrm1, c_prcntSpctrm2 ) signal_ma = f_ma_val ( plotline, i_signal_ma_typ, i_signal_ma_Len ) c_plotsig = f_clrSlct ( signal_ma, i_c_typ_sig, i_c_typ_spctrm_sig, i_c_solid_sig, c_prcntSpctrm1, c_prcntSpctrm2 ) hi_alert = pmarpOn ? i_hi_alert_pmarp : i_hi_alert_pmar lo_alert = pmarpOn ? i_lo_alert_pmarp : i_lo_alert_pmar hi_alertc = pmarpOn ? i_hi_alert_pmarp : i_hi_alert_pmar > pmarHigh ? 100 : ( i_hi_alert_pmar / pmarHigh ) * 100 c_hi_alert = f_clrSlct ( hi_alertc, i_c_typ_line, i_c_typ_spctrm_sig, i_c_solid_sig, c_prcntSpctrm1, c_prcntSpctrm2 ) c_lo_alert = f_clrSlct ( lo_alert, i_c_typ_line, i_c_typ_spctrm_sig, i_c_solid_sig, c_prcntSpctrm1, c_prcntSpctrm2 ) c_bg = color.new ( f_clrSlct ( pmarp, i_c_typ_line, i_c_typ_spctrm_line, i_c_solid_line, c_prcntSpctrm1, c_prcntSpctrm2 ), 50 ) p_hi_alert = plotline > hi_alert p_lo_alert = plotline < lo_alert /////////////////////////////////////////////////////////////////////////////// // Line Plot p_scaleHi = plot ( pmarpOn ? 100 : na, 'Scale high', #ff0000, style = plot.style_line ) p_midLine = plot ( pmarpOn ? 50 : na, 'Midline', #555555, style = plot.style_line ) p_scaleLo = plot ( pmarpOn ? 0 : na, 'Scale low', #0000ff, style = plot.style_line ) plot ( plotline, 'Plot line', c_plotline, i_p_width_line, editable=false ) plot ( pmarpOn ? na : pmarHigh, 'Historical PMAR high', f_clrSlct ( 100, i_c_typ_line, i_c_typ_spctrm_line, i_c_solid_line, c_prcntSpctrm1, c_prcntSpctrm2 ), i_p_width_line, editable=false ) plot ( i_show_signal_ma ? signal_ma : na, 'Signal line', c_plotsig, i_p_width_sig, editable=false ) plot ( i_hi_alert_line_on and pmarpOn ? i_hi_alert_pmarp : i_hi_alert_pmar, 'High alert level', c_hi_alert, style = plot.style_line ) plot ( i_lo_alert_line_on and pmarpOn ? i_lo_alert_pmarp : i_lo_alert_pmar, 'Low alert level', c_lo_alert, style = plot.style_line ) bgcolor ( p_hi_alert and i_hi_alert_line_on and i_bg_hi_signal_on ? c_bg : na ) bgcolor ( p_lo_alert and i_lo_alert_line_on and i_bg_lo_signal_on ? c_bg : na ) /////////////////////////////////////////////////////////////////////////////// // End // THIS IS PMARP, AN INDiCATOR CREATED BY @THE_CARETAKER, I DO NOT TAKE CREDIT FOR ANY CODE WRITTEN ABOVE HERE. PLEASE REFER TO @The_Caretaker FOR QUESTIONS REGARDING THE PMAR/PMARP INDICATOR. THANK YOU! // THIS IS PMARP, AN INDiCATOR CREATED BY @THE_CARETAKER, I DO NOT TAKE CREDIT FOR ANY CODE WRITTEN ABOVE HERE. PLEASE REFER TO @The_Caretaker FOR QUESTIONS REGARDING THE PMAR/PMARP INDICATOR. THANK YOU! // // // // THIS IS MADRID MOVING AVERAGE RIBBON, AN INDICATOR CREATED BY @Madrid. I DO NOT TAKE ANY CREDIT FOR THE SCRIPT BELOW UNTIL THE END OF THE INDICATOR IS STATED. FOR ANY QUESTIONS PLEASE REFER TO @Madrid REGARDING THE MADRID MOVING AVERAGE RIBBON INDICATOR, THANK YOU! // // THIS IS MADRID MOVING AVERAGE RIBBON, AN INDICATOR CREATED BY @Madrid. I DO NOT TAKE ANY CREDIT FOR THE SCRIPT BELOW UNTIL THE END OF THE INDICATOR IS STATED. FOR ANY QUESTIONS PLEASE REFER TO @Madrid REGARDING THE MADRID MOVING AVERAGE RIBBON INDICATOR, THANK YOU! // // THIS IS MADRID MOVING AVERAGE RIBBON, AN INDICATOR CREATED BY @Madrid. I DO NOT TAKE ANY CREDIT FOR THE SCRIPT BELOW UNTIL THE END OF THE INDICATOR IS STATED. FOR ANY QUESTIONS PLEASE REFER TO @Madrid REGARDING THE MADRID MOVING AVERAGE RIBBON INDICATOR, THANK YOU! // ╔══════════════════════════════════════════════════════════════════════════════╗ // β•‘ β•‘ // β•‘ Β© Madrid : 141017TH2251 β•‘ // β•‘ // β•‘ Rev. 210306SA1836 : Upgrade to Pinescript 4 β•‘ // β•‘ β•‘ // β•‘ Madrid Moving Average Ribbon β•‘ // β•‘ β•‘ // β•‘ This plots a moving average ribbon, either exponential or standard. β•‘ // β•‘ This study is best viewed with a dark background. It provides an easy β•‘ // β•‘ and fast way to determine the trend direction and possible reversals. β•‘ // β•‘ β•‘ // β•‘ Lime : Uptrend. Long trading β•‘ // β•‘ Green : Reentry (buy the dip) or downtrend reversal warning β•‘ // β•‘ Red : Downtrend. Short trading β•‘ // β•‘ Maroon : Short Reentry (sell the peak) or uptrend reversal warning β•‘ // β•‘ β•‘ // β•‘ To best determine if this is a reentry point or a trend reversal β•‘ // β•‘ the MMARB (Madrid Moving Average Ribbon Bar) study is used. β•‘ // β•‘ This is the bar located at the bottom. This bar signals when a β•‘ // β•‘ current trend reentry is found (partially filled with opposite dark color) β•‘ // β•‘ or when a trend reversal is ahead (filled with the opposite color. β•‘ // β•‘ β•‘ // β•‘ This source code is subject to the terms of the Mozilla Public License 2.0 β•‘ // β•‘ at https://mozilla.org/MPL/2.0/ β•‘ // β•‘ β•‘ // β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β• // ╔══════════════════════════════════════╗ // β•‘ β•‘ // β•‘ CONSTANTS β•‘ // β•‘ β•‘ // β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β• PHI = (1 + math.sqrt(5)) / 2 PI = 104348 / 33215 BULL = 1 BEAR = -1 NONE = 0 // ╔══════════════════════════════════════╗ // β•‘ β•‘ // β•‘ Colors β•‘ // β•‘ β•‘ // β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β• // v3 Style Gradient GRN01 = #7CFC00 GRN02 = #32CD32 GRN03 = #228B22 GRN04 = #006400 GRN05 = #008000 GRN06 = #093507 RED01 = #FF4500 RED02 = #FF0000 RED03 = #B22222 RED04 = #8B0000 RED05 = #800000 RED06 = #330d06 // ──────────[ v3 Style Colors ] AQUA = #00FFFF BLACK = #000000 BLUE = #0000FF FUCHSIA = #FF00FF GRAY = #808080 GREEN = #008000 LIME = #00FF00 MAROON = #800000 NAVY = #000080 OLIVE = #808000 ORANGE = #FF7F00 PURPLE = #800080 RUBI = #FF0000 SILVER = #C0C0C0 TEAL = #008080 YELLOW = #FFFF00 WHITE = #FFFFFF // ╔══════════════════════════════════════╗ // β•‘ β•‘ // β•‘ functions () β•‘ // β•‘ β•‘ // β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β• // ──────────[ Moving Average Color ] // maColor(_ma, _maRef) => diffMA = ta.change(_ma) macol = diffMA >= 0 and _ma > _maRef ? LIME : diffMA < 0 and _ma > _maRef ? MAROON : diffMA <= 0 and _ma < _maRef ? RUBI : diffMA >= 0 and _ma < _maRef ? GREEN : GRAY macol // ╔══════════════════════════════════════════════════════════════════════════════╗ // β•‘ β•‘ // β•‘ main ( ) β•‘ // β•‘ β•‘ // β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β• // ────────────────────[ Input Parameters ] i_exp = input(true, title='Expnential MA') // ────────────────────[ Processing ] src = close ma05 = i_exp ? ta.ema(src, 05) : ta.sma(src, 05) ma10 = i_exp ? ta.ema(src, 10) : ta.sma(src, 10) ma15 = i_exp ? ta.ema(src, 15) : ta.sma(src, 15) ma20 = i_exp ? ta.ema(src, 20) : ta.sma(src, 20) ma25 = i_exp ? ta.ema(src, 25) : ta.sma(src, 25) ma30 = i_exp ? ta.ema(src, 30) : ta.sma(src, 30) ma35 = i_exp ? ta.ema(src, 35) : ta.sma(src, 35) ma40 = i_exp ? ta.ema(src, 40) : ta.sma(src, 40) ma45 = i_exp ? ta.ema(src, 45) : ta.sma(src, 45) ma50 = i_exp ? ta.ema(src, 50) : ta.sma(src, 50) ma55 = i_exp ? ta.ema(src, 55) : ta.sma(src, 55) ma60 = i_exp ? ta.ema(src, 60) : ta.sma(src, 60) ma65 = i_exp ? ta.ema(src, 65) : ta.sma(src, 65) ma70 = i_exp ? ta.ema(src, 70) : ta.sma(src, 70) ma75 = i_exp ? ta.ema(src, 75) : ta.sma(src, 75) ma80 = i_exp ? ta.ema(src, 80) : ta.sma(src, 80) ma85 = i_exp ? ta.ema(src, 85) : ta.sma(src, 85) ma90 = i_exp ? ta.ema(src, 90) : ta.sma(src, 90) ma100 = i_exp ? ta.ema(src, 100) : ta.sma(src, 100) // ╔══════════════════════════════════════════════════════════════════════════════╗ // β•‘ β•‘ // β•‘ That's all Folks ! β•‘ // β•‘ β•‘ // β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β• // THIS IS MADRID MOVING AVERAGE RIBBON, AN INDICATOR CREATED BY @Madrid. I DO NOT TAKE ANY CREDIT FOR THE SCRIPT ABOVE. FOR ANY QUESTIONS PLEASE REFER TO @Madrid REGARDING THE MADRID MOVING AVERAGE RIBBON INDICATOR, THANK YOU! // // THIS IS MADRID MOVING AVERAGE RIBBON, AN INDICATOR CREATED BY @Madrid. I DO NOT TAKE ANY CREDIT FOR THE SCRIPT ABOVE. FOR ANY QUESTIONS PLEASE REFER TO @Madrid REGARDING THE MADRID MOVING AVERAGE RIBBON INDICATOR, THANK YOU! // // THIS IS MADRID MOVING AVERAGE RIBBON, AN INDICATOR CREATED BY @Madrid. I DO NOT TAKE ANY CREDIT FOR THE SCRIPT ABOVE. FOR ANY QUESTIONS PLEASE REFER TO @Madrid REGARDING THE MADRID MOVING AVERAGE RIBBON INDICATOR, THANK YOU! //THE SCRIPT BELOW WAS COMPLETED BY @CHEATCODE1 (Myself) LET ME KNOW IF YOU GUYS WANT MORE COLLAB STRATEGIES AND SUBSCRIBE!! THANKS :) // //THE SCRIPT BELOW WAS COMPLETED BY @CHEATCODE1 (Myself) LET ME KNOW IF YOU GUYS WANT MORE COLLAB STRATEGIES AND SUBSCRIBE!! THANKS :) // //THE SCRIPT BELOW WAS COMPLETED BY @CHEATCODE1 (Myself) LET ME KNOW IF YOU GUYS WANT MORE COLLAB STRATEGIES AND SUBSCRIBE!! THANKS :) //Lime color conditions when true greenMA_1 = ma05 > ma100 greenMA_2 = ma10 > ma100 greenMA_3 = ma15 > ma100 greenMA_4 = ma20 > ma100 greenMA_5 = ma25 > ma100 greenMA_6 = ma30 > ma100 greenMA_7 = ma35 > ma100 greenMA_8 = ma40 > ma100 greenMA_9 = ma45 > ma100 greenMA_10 = ma50 > ma100 greenMA_11 = ma55 > ma100 greenMA_12 = ma60 > ma100 greenMA_13 = ma65 > ma100 greenMA_14 = ma70 > ma100 greenMA_15 = ma75 > ma100 greenMA_16 = ma80 > ma100 greenMA_17 = ma85 > ma100 greenMA_18 = ma90 > ma100 //Red color redMA_1 = ma05 < ma100 redMA_2 = ma10 < ma100 redMA_3 = ma15 < ma100 redMA_4 = ma20 < ma100 redMA_5 = ma25 < ma100 redMA_6 = ma30 < ma100 redMA_7 = ma35 < ma100 redMA_8 = ma40 < ma100 redMA_9 = ma45 < ma100 redMA_10 = ma50 < ma100 redMA_11 = ma55 < ma100 redMA_12 = ma60 < ma100 redMA_13 = ma65 < ma100 redMA_14 = ma70 < ma100 redMA_15 = ma75 < ma100 redMA_16 = ma80 < ma100 redMA_17 = ma85 < ma100 redMA_18 = ma90 < ma100 // Difference of color Diffma1 = ta.change(ma05) Diffma2 = ta.change(ma10) Diffma3 = ta.change(ma15) Diffma4 = ta.change(ma20) Diffma5 = ta.change(ma25) Diffma6 = ta.change(ma30) Diffma7 = ta.change(ma35) Diffma8 = ta.change(ma40) Diffma9 = ta.change(ma45) Diffma10 = ta.change(ma50) Diffma11 = ta.change(ma55) Diffma12 = ta.change(ma60) Diffma13 = ta.change(ma65) Diffma14 = ta.change(ma70) Diffma15 = ta.change(ma75) Diffma16 = ta.change(ma80) Diffma17 = ta.change(ma85) Diffma18 = ta.change(ma90) //Positive difference values Diffma1P = ta.change(ma05) >= 0 Diffma2P = ta.change(ma10) >= 0 Diffma3P = ta.change(ma15) >= 0 Diffma4P = ta.change(ma20) >= 0 Diffma5P = ta.change(ma25) >= 0 Diffma6P = ta.change(ma30) >= 0 Diffma7P = ta.change(ma35) >= 0 Diffma8P = ta.change(ma40) >= 0 Diffma9P = ta.change(ma45) >= 0 Diffma10P = ta.change(ma50) >= 0 Diffma11P = ta.change(ma55) >= 0 Diffma12P = ta.change(ma60) >= 0 Diffma13P = ta.change(ma65) >= 0 Diffma14P = ta.change(ma70) >= 0 Diffma15P = ta.change(ma75) >= 0 Diffma16P = ta.change(ma80) >= 0 Diffma17P = ta.change(ma85) >= 0 Diffma18P = ta.change(ma90) >= 0 //Negative difference values Diffma1N = ta.change(ma05) < 0 Diffma2N = ta.change(ma10) < 0 Diffma3N = ta.change(ma15) < 0 Diffma4N = ta.change(ma20) < 0 Diffma5N = ta.change(ma25) < 0 Diffma6N = ta.change(ma30) < 0 Diffma7N = ta.change(ma35) < 0 Diffma8N = ta.change(ma40) < 0 Diffma9N = ta.change(ma45) < 0 Diffma10N = ta.change(ma50) < 0 Diffma11N = ta.change(ma55) < 0 Diffma12N = ta.change(ma60) < 0 Diffma13N = ta.change(ma65) < 0 Diffma14N = ta.change(ma70) < 0 Diffma15N = ta.change(ma75) < 0 Diffma16N = ta.change(ma80) < 0 Diffma17N = ta.change(ma85) < 0 Diffma18N = ta.change(ma90) < 0 // Reverse enginnered color boolean's Lime1 = Diffma1P and greenMA_1 Red1 = Diffma1N and redMA_1 Maroon1 = Diffma1N and greenMA_1 Green1 = Diffma1P and redMA_1 Lime2 = Diffma2P and greenMA_2 Red2 = Diffma2N and redMA_2 Maroon2 = Diffma2N and greenMA_2 Green2 = Diffma2P and redMA_2 Lime3 = Diffma3P and greenMA_3 Red3 = Diffma3N and redMA_3 Maroon3 = Diffma3N and greenMA_3 Green3 = Diffma3P and redMA_3 Lime4 = Diffma4P and greenMA_4 Red4 = Diffma4N and redMA_4 Maroon4 = Diffma4N and greenMA_4 Green4 = Diffma4P and redMA_4 Lime5 = Diffma5P and greenMA_5 Red5 = Diffma5N and redMA_5 Maroon5 = Diffma5N and greenMA_5 Green5 = Diffma5P and redMA_5 Lime6 = Diffma6P and greenMA_6 Red6 = Diffma6N and redMA_6 Maroon6 = Diffma6N and greenMA_6 Green6 = Diffma6P and redMA_6 Lime7 = Diffma7P and greenMA_7 Red7 = Diffma7N and redMA_7 Maroon7 = Diffma7N and greenMA_7 Green7 = Diffma7P and redMA_7 Lime8 = Diffma8P and greenMA_8 Red8 = Diffma8N and redMA_8 Maroon8 = Diffma8N and greenMA_8 Green8 = Diffma8P and redMA_8 Lime9 = Diffma9P and greenMA_9 Red9 = Diffma9N and redMA_9 Maroon9 = Diffma9N and greenMA_9 Green9 = Diffma9P and redMA_9 Lime10 = Diffma10P and greenMA_10 Red10 = Diffma10N and redMA_10 Maroon10 = Diffma10N and greenMA_10 Green10 = Diffma10P and redMA_10 Lime11 = Diffma11P and greenMA_11 Red11 = Diffma11N and redMA_11 Maroon11 = Diffma11N and greenMA_11 Green11 = Diffma11P and redMA_11 Lime12 = Diffma12P and greenMA_12 Red12 = Diffma12N and redMA_12 Maroon12 = Diffma12N and greenMA_12 Green12 = Diffma12P and redMA_12 Lime13 = Diffma13P and greenMA_13 Red13 = Diffma13N and redMA_13 Maroon13 = Diffma13N and greenMA_13 Green13 = Diffma13P and redMA_13 Lime14 = Diffma14P and greenMA_14 Red14 = Diffma14N and redMA_14 Maroon14 = Diffma14N and greenMA_14 Green14 = Diffma14P and redMA_14 Lime15 = Diffma15P and greenMA_15 Red15 = Diffma15N and redMA_15 Maroon15 = Diffma15N and greenMA_15 Green15 = Diffma15P and redMA_15 Lime16 = Diffma16P and greenMA_16 Red16 = Diffma16N and redMA_16 Maroon16 = Diffma16N and greenMA_16 Green16 = Diffma16P and redMA_16 Lime17 = Diffma17P and greenMA_17 Red17 = Diffma17N and redMA_17 Maroon17 = Diffma17N and greenMA_17 Green17 = Diffma17P and redMA_17 Lime18 = Diffma18P and greenMA_18 Red18 = Diffma18N and redMA_18 Maroon18 = Diffma18N and greenMA_18 Green18 = Diffma18P and redMA_18 //combination of Lime/Red conditions when true lime_Long = Lime1 and Lime2 and Lime3 and Lime4 and Lime5 and Lime6 and Lime7 and Lime8 and Lime9 and Lime10 and Lime11 and Lime12 and Lime13 and Lime14 and Lime15 and Lime16 and Lime17 and Lime18 red_Short = Red1 and Red2 and Red3 and Red4 and Red5 and Red6 and Red7 and Red8 and Red9 and Red10 and Red12 and Red12 and Red13 and Red14 and Red15 and Red16 and Red17 and Red18 maroon_Short = Maroon1 and Maroon2 and Maroon3 and Maroon4 and Maroon5 and Maroon6 and Maroon7 and Maroon8 and Maroon9 and Maroon10 and Maroon11 and Maroon12 and Maroon13 and Maroon14 and Maroon15 and Maroon16 and Maroon17 and Maroon18 green_Long = Green1 and Green2 and Green3 and Green4 and Green5 and Green6 and Green7 and Green8 and Green9 and Green10 and Green11 and Green12 and Green13 and Green14 and Green15 and Green16 and Green17 and Green18 //rsistoch values / r= ta.rsi(close, 14) s = ta.stoch(close, 14,1,3) rP = r <= 55 rM = r >= 75 noREL = strategy.opentrades == 0 and strategy.position_size > 0 noRES = strategy.opentrades == 0 and strategy.position_size < 0 noENGL = close[1] > open[1] //Entry executions if (lime_Long) and not (noREL) and not (noENGL) and not (rP) strategy.entry("Long", strategy.long) if (red_Short) and not (noRES) strategy.entry("Short", strategy.short) //Stop Loss/ Take Profit Variables entry_index() => strategy.opentrades > 0 ? (bar_index - strategy.opentrades.entry_bar_index(strategy.closedtrades + 1)) : na StopLoss() => if entry_index() != 0 and strategy.position_size > 0 low[1] else if entry_index() != 0 and strategy.position_size < 0 high[1] else na //Exit excecutions if strategy.position_size > 0 and pmarp >= 99 and red_Short == true strategy.close("Long") if strategy.position_size < 0 and pmarp <= 01 strategy.close("Short") // if strategy.position_size > 0 // strategy.exit("Stop Loss", stop = StopLoss()) // if strategy.position_size < 0 // strategy.exit("Stop Loss", stop = StopLoss()) // Fixed percentiles for profit taking takeP = input.float(1, title='Take Profit', group = 'Take Profit and Stop Loss') / 100 stopL = input.float(27.75, title = 'Stop Loss', group = 'Take Profit and Stop Loss')/100 // Pre Directionality Stop_L = strategy.position_avg_price * (1 - stopL) Stop_S = strategy.position_avg_price * (1 + stopL) Take_S= strategy.position_avg_price * (1 - takeP) Take_L = strategy.position_avg_price * (1 + takeP) //Post Excecution if strategy.position_size > 0 strategy.exit("Close Long", limit=Take_L, stop = Stop_L) if strategy.position_size < 0 strategy.exit("Close Short", limit=Take_S, stop = Stop_S) //Custom HLine Request H1 = input.int( 75, 'Top Line', 51, 100, group = 'Top and Bottom Lines', inline = '1' ) H2 = input.int( 20, 'Bottom Line', 0, 49, group = 'Top and Bottom Lines', inline = '1' ) H3A = input.int(05, ' Transparancy of FIll', 1, 99, group = 'Top and Bottom Lines', inline = '1') H3B = 100 - H3A H1P = hline(H1, 'Top Line', #5BE14D, hline.style_dotted, 2, true ) H2P = hline(H2, 'Bottom Line', #E14D60, hline.style_dotted, 2, true ) fill(H1P, H2P, color.new(#E1CB5F,H3B), 'Line fills', editable = true )
The Impeccable by zyberal
https://www.tradingview.com/script/WNmcF8Kr-The-Impeccable-by-zyberal/
zyberal
https://www.tradingview.com/u/zyberal/
79
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/ // Β© Revazi //@version=5 strategy("The Impeccable by zyberal", overlay = true) // Inputs { // Strategy variables IchimokuTenkanPeriod = input(9) IchimokuKijunPeriod = input(190) IchimokuSenkouPeriod = input(52) MACDMainFast = input(3) MACDMainSlow = input(10) MACDMainSmooth = input(9) ExitAfterBars = input(2) ProfitTarget = input(135) StopLoss = input(70) // Trading Options DontTradeOnWeekends = input(true) ExitAtEndOfDay = input(true) DayExitTimeHour = input(23) DayExitTimeMinute = input(04) ExitOnFriday = input(true) FridayExitTimeHour = input(20) FridayExitTimeMinute = input(40) // } // TRADING OPTIONS LOGIC { OpenOrdersAllowed = true // Dont trade on weekends { if DontTradeOnWeekends if dayofweek == dayofweek.saturday or dayofweek == dayofweek.sunday OpenOrdersAllowed := false // } // Exit on close (end of day) { if ExitAtEndOfDay if timeframe.isintraday and time >= timestamp(year(timenow), month(timenow), dayofmonth(timenow), DayExitTimeHour, DayExitTimeMinute) OpenOrdersAllowed := false // } // Exit on Friday { if ExitOnFriday if timeframe.isintraday and time >= timestamp(year(timenow), month(timenow), dayofmonth(timenow), FridayExitTimeHour, FridayExitTimeMinute) OpenOrdersAllowed := false // } // Rule: Trading signals { openW3 = request.security(syminfo.tickerid, "W", open)[3] middleDonchian(Length) => math.avg(ta.highest(Length), ta.lowest(Length)) Tenkan = middleDonchian(IchimokuTenkanPeriod)[2] [macdLine, signalLine, _] = ta.macd(close, MACDMainFast, MACDMainSlow, MACDMainSmooth) LongEntrySignal = openW3 > Tenkan and ta.crossunder(macdLine, signalLine)[3] //macdLine[3] < signalLine[3] ShortEntrySignal = openW3 < Tenkan and ta.crossover(macdLine, signalLine)[3] //macdLine[3] > signalLine[3] // } // Calculate conditions { IsFlat() => strategy.position_size == 0 IsLong() => strategy.position_size > 0 IsShort() => strategy.position_size < 0 longCondition = OpenOrdersAllowed and not IsLong() and LongEntrySignal shortCondition = OpenOrdersAllowed and not IsShort() and ShortEntrySignal // } // Open positions based on conditions { strategy.order(id = "buy", direction = strategy.long, qty = 1, when = longCondition) strategy.order(id = "sell", direction = strategy.short, qty = 1, when = shortCondition) // }
Take Profit On Trend v2 (by BHD_Trade_Bot)
https://www.tradingview.com/script/3vXbvuTO-Take-Profit-On-Trend-v2-by-BHD-Trade-Bot/
BHD_Trade_Bot
https://www.tradingview.com/u/BHD_Trade_Bot/
211
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© BHD_Trade_Bot // @version=5 strategy( shorttitle = 'Take Profit On Trend', title = 'Take Profit On Trend (by BHD_Trade_Bot)', overlay = true, calc_on_every_tick = true, calc_on_order_fills = true, use_bar_magnifier = true, initial_capital = 1000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, commission_value = 0.1) // Backtest Time Period start_year = input(title='Start year' ,defval=2021) start_month = input(title='Start month' ,defval=1) start_day = input(title='Start day' ,defval=1) start_time = timestamp(start_year, start_month, start_day, 00, 00) end_year = input(title='end year' ,defval=2050) end_month = input(title='end month' ,defval=1) end_day = input(title='end day' ,defval=1) end_time = timestamp(end_year, end_month, end_day, 23, 59) is_back_test_time() => time >= start_time and time <= end_time ? true : false // EMA ema50 = ta.ema(close, 50) ema200 = ta.ema(close, 200) // RSI rsi200 = ta.rsi(close, 200) // EMA_CD emacd = ema50 - ema200 emacd_signal = ta.ema(emacd, 50) hist = emacd - emacd_signal // BHD Unit bhd_unit = ta.rma(high - low, 200) * 2 bhd_upper = ema200 + bhd_unit bhd_lower = ema200 - bhd_unit // All n candles is going down all_body_decrease(n) => isValid = true for i = 0 to (n - 1) if (close[i] > close[i + 1]) isValid := false break isValid // ENTRY CONDITIONS // Long-term uptrend entry_condition1 = rsi200 > 51 and hist > 0 // Short-term downtrend entry_condition2 = all_body_decrease(2) ENTRY_CONDITIONS = entry_condition1 and entry_condition2 if ENTRY_CONDITIONS and is_back_test_time() strategy.entry('entry', strategy.long) // CLOSE CONDITIONS // Price increase 2 BHD unit take_profit = close > strategy.position_avg_price + bhd_unit * 2 // Price decrease 3 BHD unit stop_loss = close < strategy.position_avg_price - bhd_unit * 3 CLOSE_CONDITIONS = take_profit or stop_loss if CLOSE_CONDITIONS strategy.close('entry') // Draw plot(ema50, color=color.orange, linewidth=2) plot(ema200, color=color.purple, linewidth=2) bhd_upper_line = plot(bhd_upper, color=color.teal) bhd_lower_line = plot(bhd_lower, color=color.teal) fill(bhd_upper_line, bhd_lower_line, color=color.new(color.teal, 90))
MAPM-V1
https://www.tradingview.com/script/O8w1QoIp-mapm-v1/
TradingSoft_tech
https://www.tradingview.com/u/TradingSoft_tech/
134
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/ // Β© TradingSoft_tech //@version=5 strategy("MAPM-V1", overlay=true, default_qty_value=10, max_bars_back=5000,default_qty_type = strategy.percent_of_equity, commission_value=0.1, initial_capital = 100, pyramiding=6, currency=currency.USD) ///////// Options SignalFast = input.int(300, step=10) SignalSlow = input.int(600, step=10) StepAddPurchases = input.float(2.5, step=0.1) VolumePurchases = input.int(6,step=1) Buy = input(true) Sell = input(true) longProfitPerc = input.float(title="Long Take Profit (%)", minval=0.0, step=0.1, defval=1) * 0.01 shortProfitPerc = input.float(title="Short Take Profit (%)", minval=0.0, step=0.1, defval=1) * 0.01 Martingale = input.float(1.6, minval = 1, step = 0.1) VolumeDepo = input.int(100, step=1) PercentOfDepo = input.float(10, step=1) Close = (close) EnterVolume = VolumeDepo*PercentOfDepo*0.01/Close ///////// Calculation indicator fastAverage = ta.ema(close, 8) slowAverage = ta.ema(close, 49) macd = fastAverage - slowAverage macdSignalF = ta.ema(macd,SignalFast) macdSignalS = ta.ema(macd,SignalSlow) // Test Start startYear = input(2005, "Test Start Year") startMonth = input(1, "Test Start Month") startDay = input(1, "Test Start Day") startTest = timestamp(startYear,startMonth,startDay,0,0) //Test End endYear = input(2050, "Test End Year") endMonth = input(12, "Test End Month") endDay = input(30, "Test End Day") endTest = timestamp(endYear,endMonth,endDay,23,59) timeRange = time > startTest and time < endTest ? true : false ///////// Plot Data //plot(macd, style = plot.style_histogram) //plot(macdSignalF*10000, style = plot.style_line, color=color.red) //plot(macdSignalS*10000, style = plot.style_line, color=color.blue) //plot(fastAverage, style = plot.style_line, color=color.red) //plot(slowAverage, style = plot.style_line, color=color.blue) ///////// Calculation of the updated value var x = 0.0 if strategy.opentrades>strategy.opentrades[1] x := x + 1 else if strategy.opentrades==0 x := 0 y = x+1 ///////// Calculation of reference price data entryPrice = strategy.opentrades==0? 0 : strategy.opentrades.entry_price(0) limitLong = strategy.position_avg_price * (1 + longProfitPerc) limitShort = strategy.position_avg_price * (1 - shortProfitPerc) SteplimitLong = entryPrice[0]*(1-StepAddPurchases*y/100) SteplimitShort = entryPrice[0]*(1+StepAddPurchases*y/100) ///////// Conditions for a long bool EntryLong = ta.crossover(macdSignalF, macdSignalS) and Buy and strategy.opentrades==0 and strategy.position_size==0 bool PurchasesLong = Buy and strategy.opentrades==x and strategy.position_size>0 and x<=VolumePurchases bool CancelPurchasesLong = strategy.position_size==0 and strategy.opentrades==0 bool TPLong = strategy.position_size>0 and strategy.opentrades!=0 ///////// Entry Long + add.purchases + cancel purchases + Take profit Long switch EntryLong => strategy.entry("Entry Long", strategy.long, qty = EnterVolume) PurchasesLong => strategy.entry("PurchasesLong", strategy.long, qty = EnterVolume*math.pow(Martingale,y), limit = SteplimitLong) CancelPurchasesLong => strategy.cancel("PurchasesLong") switch TPLong => strategy.exit("TPLong", qty_percent = 100, limit = limitLong) ///////// Conditions for a Short bool EntryShort = ta.crossunder(macdSignalF, macdSignalS) and Sell and strategy.opentrades==0 and strategy.position_size==0 bool PurchasesShort = Sell and strategy.opentrades==x and strategy.position_size<0 and x<=VolumePurchases bool CancelPurchasesShort = strategy.position_size==0 and strategy.opentrades==0 bool TPShort = strategy.position_size<0 and strategy.opentrades!=0 ///////// Entry Short + add.purchases + cancel purchases + Take profit Short switch EntryShort => strategy.entry("Entry Short", strategy.short, qty = EnterVolume) PurchasesShort => strategy.entry("PurchasesShort", strategy.short, qty = EnterVolume*math.pow(Martingale,y), limit = SteplimitShort) CancelPurchasesShort => strategy.cancel("PurchasesShort") switch TPShort => strategy.exit("TPShort", qty_percent = 100, limit = limitShort) /////////Calculation of conditions and reference data for level drawing InTradeLong = strategy.position_size<0 InTradeShort = strategy.position_size>0 PickInLong = strategy.opentrades.entry_price(0)*(1-StepAddPurchases*y/100) PickInShort = strategy.opentrades.entry_price(0)*(1+StepAddPurchases*y/100) /////////Displaying the level of Take Profit plot(InTradeLong ? na : limitLong, color=color.new(#00d146, 0), style=plot.style_linebr, linewidth=1) plot(InTradeShort ? na : limitShort, color=color.new(#00d146, 0), style=plot.style_linebr, linewidth=1) /////////Displaying the level of add.purchases plot(InTradeLong ? na : PickInLong, color=color.white, style=plot.style_linebr, linewidth=1) plot(InTradeShort ? na : PickInShort, color=color.white, style=plot.style_linebr, linewidth=1)
Smoothed Heikin Ashi Trend on Chart - TraderHalai BACKTEST
https://www.tradingview.com/script/Is0LQdiz-Smoothed-Heikin-Ashi-Trend-on-Chart-TraderHalai-BACKTEST/
TraderHalai
https://www.tradingview.com/u/TraderHalai/
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/ // Β© TraderHalai // This is a backtest of the Smoothed Heikin Ashi Trend indicator, which computes the reverse candle close price required to flip a heikin ashi trend from red to green and vice versa. Original indicator can be found on the scripts section of my profile. // Default testing parameters are 10% of equity position size, with a 1% stop loss on short and long strategy.opentrades.commission // This particular back test uses this indicator as a Trend trading tool with a tight stop loss. The equity curve as tested seems promising but requires further work to refine. Note in an actual trading setup, you may wish to use this with volatilty filters as most of the losses are in sideways, low volatility markets. //@version=5 strategy("Smoothed Heikin Ashi Trend on Chart - TraderHalai BACKTEST", " SHA Trend - BACKTEST", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=10) //Inputs i_useSmooth = input ( true, "Use smoothing Heikin Ashi") i_smoothingMethod = input.string("SMA", "Method", options=["SMA", "EMA", "HMA", "VWMA", "RMA"]) i_smoothingPeriod = input ( 10, "Smoothing period") i_infoBox = input ( true, "Show Info Box" ) i_decimalP = input ( 2, "Prices Decimal Places") i_boxOffSet = input ( 5, "Info Box Offset" ) i_repaint = input (false, "Repaint - Keep on for live / Off for backtest") i_longLossPerc = input.float(title="Long Stop Loss (%)",minval=0.0, step=0.1, defval=1) * 0.01 i_shortLossPerc = input.float(title="Short Stop Loss (%)", minval=0.0, step=0.1, defval=1) * 0.01 timeperiod = timeframe.period //Security functions to avoid repaint, as per PineCoders f_secureSecurity(_symbol, _res, _src) => request.security(_symbol, _res, _src[1], lookahead = barmerge.lookahead_on) f_security(_symbol, _res, _src, _repaint) => request.security(_symbol, _res, _src[_repaint ? 0 : barstate.isrealtime ? 1 : 0])[_repaint ? 0 : barstate.isrealtime ? 0 : 1] f_secSecurity2(_symbol, _res, _src) => request.security(_symbol, _res, _src[1]) candleClose = f_security(syminfo.tickerid, timeperiod, close, i_repaint) candleOpen = f_security(syminfo.tickerid, timeperiod, open, i_repaint) candleLow = f_security(syminfo.tickerid, timeperiod, low, i_repaint) candleHigh = f_security(syminfo.tickerid, timeperiod, high, i_repaint) haTicker = ticker.heikinashi(syminfo.tickerid) haClose = f_security(haTicker, timeperiod, close, i_repaint) haOpen = f_security(haTicker, timeperiod, open, i_repaint) haLow = f_security(haTicker, timeperiod, low, i_repaint) haHigh= f_security(haTicker, timeperiod, high, i_repaint) reverseClose = (2 * (haOpen[1] + haClose[1])) - candleHigh - candleLow - candleOpen if(reverseClose < candleLow) reverseClose := (candleLow + reverseClose) / 2 if(reverseClose > candleHigh) reverseClose := (candleHigh + reverseClose) / 2 //Smoothing smaSmoothed = ta.sma(reverseClose, i_smoothingPeriod) emaSmoothed = ta.ema(reverseClose, i_smoothingPeriod) hmaSmoothed = ta.hma(reverseClose, i_smoothingPeriod) vwmaSmoothed = ta.vwma(reverseClose, i_smoothingPeriod) rmaSmoothed = ta.rma(reverseClose, i_smoothingPeriod) shouldApplySmoothing = i_useSmooth and i_smoothingPeriod > 1 smoothedReverseClose = reverseClose if(shouldApplySmoothing) if(i_smoothingMethod == "SMA") smoothedReverseClose := smaSmoothed else if(i_smoothingMethod == "EMA") smoothedReverseClose := emaSmoothed else if(i_smoothingMethod == "HMA") smoothedReverseClose := hmaSmoothed else if(i_smoothingMethod == "VWMA") smoothedReverseClose := vwmaSmoothed else if(i_smoothingMethod == "RMA") smoothedReverseClose := rmaSmoothed else smoothedReverseClose := reverseClose // Default to non-smoothed for invalid smoothing type haBull = candleClose >= smoothedReverseClose haCol = haBull ? color.green : color.red //Overall trading strategy if(ta.crossover(candleClose, smoothedReverseClose)) strategy.entry("LONG", strategy.long) else strategy.cancel("LONG") if(ta.crossunder(candleClose, smoothedReverseClose)) strategy.entry("SHORT", strategy.short) else strategy.cancel("SHORT") longStopPrice = strategy.position_avg_price * (1 - i_longLossPerc) shortStopPrice = strategy.position_avg_price * (1 + i_shortLossPerc) 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") plot(smoothedReverseClose, color=haCol) if (strategy.position_size > 0) strategy.exit(id="XL STP", stop=longStopPrice) if (strategy.position_size < 0) strategy.exit(id="XS STP", stop=shortStopPrice) ///////////////////////////// --- BEGIN TESTER CODE --- //////////////////////// // COPY below into your strategy to enable display //////////////////////////////////////////////////////////////////////////////// // Declare performance tracking variables drawTester = input.bool(true, "Draw Tester") var balance = strategy.initial_capital var drawdown = 0.0 var maxDrawdown = 0.0 var maxBalance = 0.0 var totalWins = 0 var totalLoss = 0 // 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) // Custom function to truncate (cut) excess decimal places truncate(_number, _decimalPlaces) => _factor = math.pow(10, _decimalPlaces) int(_number * _factor) / _factor // Draw stats table var bgcolor = color.new(color.black,0) if drawTester if barstate.islastconfirmedhistory // Update table dollarReturn = strategy.netprofit f_fillCell(testTable, 0, 0, "Total Trades:", str.tostring(strategy.closedtrades), bgcolor, color.white) f_fillCell(testTable, 0, 1, "Win Rate:", str.tostring(truncate((strategy.wintrades/strategy.closedtrades)*100,2)) + "%", bgcolor, color.white) f_fillCell(testTable, 1, 0, "Starting:", "$" + str.tostring(strategy.initial_capital), bgcolor, color.white) f_fillCell(testTable, 1, 1, "Ending:", "$" + str.tostring(truncate(strategy.initial_capital + strategy.netprofit,2)), bgcolor, color.white) f_fillCell(testTable, 2, 0, "Avg Win:", "$"+ str.tostring(truncate(strategy.grossprofit / strategy.wintrades, 2)), bgcolor, color.white) f_fillCell(testTable, 2, 1, "Avg Loss:", "$"+ str.tostring(truncate(strategy.grossloss / strategy.losstrades, 2)), bgcolor, color.white) f_fillCell(testTable, 3, 0, "Profit Factor:", str.tostring(truncate(strategy.grossprofit / strategy.grossloss,2)), strategy.grossprofit > strategy.grossloss ? color.green : color.red, color.white) f_fillCell(testTable, 3, 1, "Max Runup:", str.tostring(truncate(strategy.max_runup, 2 )), bgcolor, color.white) f_fillCell(testTable, 4, 0, "Return:", (dollarReturn > 0 ? "+" : "") + str.tostring(truncate((dollarReturn / strategy.initial_capital)*100,2)) + "%", dollarReturn > 0 ? color.green : color.red, color.white) f_fillCell(testTable, 4, 1, "Max DD:", str.tostring(truncate((strategy.max_drawdown / strategy.equity) * 100 ,2)) + "%", color.red, color.white) // --- END TESTER CODE --- ///////////////
When was the last time we were in stagflation?
https://www.tradingview.com/script/67USaZMK-When-was-the-last-time-we-were-in-stagflation/
brett0923
https://www.tradingview.com/u/brett0923/
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/ // Β© brett0923 //@version=4 // #First I name the strategy strategy("Stagflation backtesting ") // # Collect and store the data for each economic indicator use inflation_rate = security('USIRYY',"M", close) interest_rate = security('US10Y', 'M', close ) GDP_growth_rate = security('USGDPQQ', 'M', close ) //Command the strategy to enter a long position in the dollar when our indicators show or already showing signs of Stagflation strategy.entry("enter long",true , 1000.0, when = inflation_rate > 8.0 and interest_rate >= 3.0 and GDP_growth_rate <= 1)
Strategy BackTest Display Statistics - TraderHalai
https://www.tradingview.com/script/mGF7bMPS-Strategy-BackTest-Display-Statistics-TraderHalai/
TraderHalai
https://www.tradingview.com/u/TraderHalai/
220
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© TraderHalai // This script was born out of my quest to be able to display strategy back test statistics on charts to allow for easier backtesting on devices that do not natively support backtest engine (such as mobile phones, when I am backtesting from away from my computer). There are already a few good ones on TradingView, but most / many are too complicated for my needs. // //Found an excellent display backtest engine by 'The Art of Trading'. This script is a snippet of his hard work, with some very minor tweaks and changes. Much respect to the original author. // //Full credit to the original author of this script. It can be found here: https://www.tradingview.com/script/t776tkZv-Hammers-Stars-Strategy/?offer_id=10&aff_id=15271 // // This script can be copied and airlifted onto existing strategy scripts of your own, and integrates out of the box without implementation of additional functions. I've also added Max Runup, Average Win and Average Loss per trade to the orignal script. // //Will look to add in more performance metrics in future, as I further develop this script. // //Feel free to use this display panel in your scripts and strategies. //Thanks and enjoy! :) //@version=5 strategy("Strategy BackTest Display Statistics - TraderHalai", overlay=true, default_qty_value= 5, default_qty_type = strategy.percent_of_equity, initial_capital=10000, commission_type=strategy.commission.percent, commission_value=0.1) //DEMO basic strategy - Use your own strategy here - Jaws Mean Reversion from my profile used here source = input(title = "Source", defval = close) smallMAPeriod = input(title = "Small Moving Average", defval = 2) bigMAPeriod = input(title = "Big Moving Average", defval = 8) percentBelowToBuy = input(title = "Percent below to buy %", defval = 1) smallMA = ta.sma(source, smallMAPeriod) bigMA = ta.sma(source, bigMAPeriod) buyMA = ((100 - percentBelowToBuy) / 100) * ta.sma(source, bigMAPeriod)[0] buy = ta.crossunder(smallMA, buyMA) if(buy) strategy.entry("BUY", strategy.long) if(strategy.openprofit >= strategy.position_avg_price * 0.01) // 1% profit target strategy.close("BUY") if(ta.barssince(buy) >= 7) //Timed Exit, if you fail to make 1 percent in 7 candles. strategy.close("BUY") ///////////////////////////// --- BEGIN TESTER CODE --- //////////////////////// // COPY below into your strategy to enable display //////////////////////////////////////////////////////////////////////////////// // Declare performance tracking variables drawTester = input.bool(true, "Draw Tester") var balance = strategy.initial_capital var drawdown = 0.0 var maxDrawdown = 0.0 var maxBalance = 0.0 var totalWins = 0 var totalLoss = 0 // 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) // Custom function to truncate (cut) excess decimal places truncate(_number, _decimalPlaces) => _factor = math.pow(10, _decimalPlaces) int(_number * _factor) / _factor // Draw stats table var bgcolor = color.new(color.black,0) if drawTester if barstate.islastconfirmedhistory // Update table dollarReturn = strategy.netprofit f_fillCell(testTable, 0, 0, "Total Trades:", str.tostring(strategy.closedtrades), bgcolor, color.white) f_fillCell(testTable, 0, 1, "Win Rate:", str.tostring(truncate((strategy.wintrades/strategy.closedtrades)*100,2)) + "%", bgcolor, color.white) f_fillCell(testTable, 1, 0, "Starting:", "$" + str.tostring(strategy.initial_capital), bgcolor, color.white) f_fillCell(testTable, 1, 1, "Ending:", "$" + str.tostring(truncate(strategy.initial_capital + strategy.netprofit,2)), bgcolor, color.white) f_fillCell(testTable, 2, 0, "Avg Win:", "$"+ str.tostring(truncate(strategy.grossprofit / strategy.wintrades, 2)), bgcolor, color.white) f_fillCell(testTable, 2, 1, "Avg Loss:", "$"+ str.tostring(truncate(strategy.grossloss / strategy.losstrades, 2)), bgcolor, color.white) f_fillCell(testTable, 3, 0, "Profit Factor:", str.tostring(truncate(strategy.grossprofit / strategy.grossloss,2)), strategy.grossprofit > strategy.grossloss ? color.green : color.red, color.white) f_fillCell(testTable, 3, 1, "Max Runup:", str.tostring(truncate(strategy.max_runup, 2 )), bgcolor, color.white) f_fillCell(testTable, 4, 0, "Return:", (dollarReturn > 0 ? "+" : "") + str.tostring(truncate((dollarReturn / strategy.initial_capital)*100,2)) + "%", dollarReturn > 0 ? color.green : color.red, color.white) f_fillCell(testTable, 4, 1, "Max DD:", str.tostring(truncate((strategy.max_drawdown / strategy.equity) * 100 ,2)) + "%", color.red, color.white) // --- END TESTER CODE --- ///////////////
Strategy Backtesting Template [MYN]
https://www.tradingview.com/script/zi6NdAO0-Strategy-Backtesting-Template-MYN/
myncrypto
https://www.tradingview.com/u/myncrypto/
359
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© myn //@version=5 strategy('Strategy Backtesting Template [MYN]', max_bars_back=5000, overlay=true, pyramiding=0, initial_capital=20000, currency='NONE', default_qty_type=strategy.percent_of_equity, default_qty_value=100.0, commission_value=0.075, use_bar_magnifier = false) ///////////////////////////////////// //* Put your strategy logic below *// ///////////////////////////////////// // Below is a very simple example to demonstrate the trading template rsiEntry = ta.rsi(close, 10) rsiExit = ta.rsi(close,100) longConditionEntry = ta.crossover(rsiEntry, 80) shortConditionEntry = ta.crossunder(rsiEntry, 20) longConditionExit = ta.crossunder(rsiExit,40) shortConditionExit = ta.crossover(rsiExit, 60) ////////////////////////////////////// //* Put your strategy rules below *// ///////////////////////////////////// longCondition = longConditionEntry // default: false shortCondition = shortConditionEntry // default: false //define as 0 if do not want to have a conditional close closeLongCondition = longConditionExit // default: 0 closeShortCondition = shortConditionExit // default: 0 // EMA Filter //β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ i_emaFilterEnabled = input.bool(defval = false , title = "Enable EMA Filter", tooltip = "Enable if you would like to conditionally have entries incorporate EMA as a filter where source is above/below the EMA line", group ="EMA Filter" ) i_emaLength = input.int(200, title="EMA Length", minval=1, group ="EMA Filter") i_emaSource = input.source(close,"EMA Source" , group ="EMA Filter") emaValue = i_emaFilterEnabled ? ta.ema(i_emaSource, i_emaLength) : na bool isEMAFilterEnabledAndCloseAboveMA = i_emaFilterEnabled ? i_emaSource > emaValue : true bool isEMAFilterEnabledAndCloseBelowMA = i_emaFilterEnabled ? i_emaSource < emaValue : true // ADX Filter //β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ i_adxFilterEnabled = input.bool(defval = false , title = "Enable ADX Filter", tooltip = "Enable if you would like to conditionally have entries incorporate ADX as a filter", group ="ADX Filter" ) i_adxVariant = input.string('ORIGINAL', title='ADX Variant', options=['ORIGINAL', 'MASANAKAMURA'], group ="ADX Filter" ) i_adxSmoothing = input.int(14, title="ADX Smoothing", group="ADX Filter") i_adxDILength = input.int(14, title="DI Length", group="ADX Filter") i_adxLowerThreshold = input.float(25, title="ADX Threshold", step=.5, group="ADX Filter") calcADX_Masanakamura(int _len) => _smoothedTrueRange = 0.0 _smoothedDirectionalMovementPlus = 0.0 _smoothed_directionalMovementMinus = 0.0 _trueRange = math.max(math.max(high - low, math.abs(high - nz(close[1]))), math.abs(low - nz(close[1]))) _directionalMovementPlus = high - nz(high[1]) > nz(low[1]) - low ? math.max(high - nz(high[1]), 0) : 0 _directionalMovementMinus = nz(low[1]) - low > high - nz(high[1]) ? math.max(nz(low[1]) - low, 0) : 0 _smoothedTrueRange := nz(_smoothedTrueRange[1]) - nz(_smoothedTrueRange[1]) / _len + _trueRange _smoothedDirectionalMovementPlus := nz(_smoothedDirectionalMovementPlus[1]) - nz(_smoothedDirectionalMovementPlus[1]) / _len + _directionalMovementPlus _smoothed_directionalMovementMinus := nz(_smoothed_directionalMovementMinus[1]) - nz(_smoothed_directionalMovementMinus[1]) / _len + _directionalMovementMinus DIP = _smoothedDirectionalMovementPlus / _smoothedTrueRange * 100 DIM = _smoothed_directionalMovementMinus / _smoothedTrueRange * 100 _DX = math.abs(DIP - DIM) / (DIP + DIM) * 100 adx = ta.sma(_DX, _len) [DIP, DIM, adx] [DIPlusO, DIMinusO, ADXO] = ta.dmi(i_adxDILength, i_adxSmoothing) [DIPlusM, DIMinusM, ADXM] = calcADX_Masanakamura(i_adxDILength) adx = i_adxFilterEnabled and i_adxVariant == "ORIGINAL" ? ADXO : ADXM bool isADXFilterEnabledAndAboveThreshold = i_adxFilterEnabled ? adx > i_adxLowerThreshold : true ///Start / End Time Periods //β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ i_startPeriodEnabled = input.bool(true, 'Start', group='Date Range', inline='Start Period') i_startPeriodTime = input.time(timestamp('1 Jan 2019'), '', group='Date Range', inline='Start Period') i_endPeriodEnabled = input.bool(true, 'End', group='Date Range', inline='End Period') i_endPeriodTime = input.time(timestamp('31 Dec 2030'), '', group='Date Range', inline='End Period') isStartPeriodEnabledAndInRange = i_startPeriodEnabled ? i_startPeriodTime <= time : true isEndPeriodEnabledAndInRange = i_endPeriodEnabled ? i_endPeriodTime >= time : true // Time-Of-Day Window // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Inspired from https://www.tradingview.com/script/3BmID7aW-Highlight-Trading-Window-Simple-Hours-Time-of-Day-Filter/ i_timeFilterEnabled = input.bool(defval = false , title = "Enable Time-Of-Day Window", tooltip = "Limit the time of day for trade execution", group ="Time Window" ) i_timeZone = input.string(title="Select Local Time Zone", defval="GMT-5", options=["GMT-8","GMT-7", "GMT-6", "GMT-5", "GMT-4", "GMT-3", "GMT-2", "GMT-1", "GMT", "GMT+1", "GMT+2", "GMT+3","GMT+4","GMT+5","GMT+6","GMT+7","GMT+8","GMT+9","GMT+10","GMT+11","GMT+12","GMT+13"], group="Time Window") i_betweenTime = input.session('0700-0900', title = "Time Filter", group="Time Window") // '0000-0000' is anytime to enter isWithinWindowOfTime(_position) => currentTimeIsWithinWindowOfTime = not na(time(timeframe.period, _position + ':1234567', i_timeZone)) bool isTimeFilterEnabledAndInRange = i_timeFilterEnabled ? isWithinWindowOfTime(i_betweenTime) : true isStartEndPeriodsAndTimeInRange = isStartPeriodEnabledAndInRange and isEndPeriodEnabledAndInRange and isTimeFilterEnabledAndInRange // Trade Direction // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ i_tradeDirection = input.string('Long and Short', title='Trade Direction', options=['Long and Short', 'Long Only', 'Short Only'], group='Trade Direction') // Percent as Points // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ per(pcnt) => strategy.position_size != 0 ? math.round(pcnt / 100 * strategy.position_avg_price / syminfo.mintick) : float(na) // Take profit 1 // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ i_takeProfitTargetPercent1 = input.float(title='Take Profit 1 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 1') i_takeProfitQuantityPercent1 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 1') // Take profit 2 // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ i_takeProfitTargetPercent2 = input.float(title='Take Profit 2 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 2') i_takeProfitQuantityPercent2 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 2') // Take profit 3 // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ i_takeProfitTargetPercent3 = input.float(title='Take Profit 3 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 3') i_takeProfitQuantityPercent3 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 3') // Take profit 4 // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ i_takeProfitTargetPercent4 = input.float(title='Take Profit 4 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit') /// Stop Loss // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ i_stopLossPercent = input.float(title='Stop Loss (%)', defval=999, minval=0.01, step=0.5, group='Stop Loss') * 0.01 slLongClose = close < strategy.position_avg_price * (1 - i_stopLossPercent) slShortClose = close > strategy.position_avg_price * (1 + i_stopLossPercent) /// Leverage // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ i_leverage = input.float(1, 'Leverage', step=.5, group='Leverage') i_percentOfEquityToTrade = input.float(100, "% of Equity to Stake Per Trade", minval=0.01, maxval=100, step=5, group='Leverage') * .01 contracts = (i_percentOfEquityToTrade * strategy.equity / close * i_leverage) /// Trade State Management // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ isInLongPosition = strategy.position_size > 0 isInShortPosition = strategy.position_size < 0 /// ProfitView Alert Syntax String Generation // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ i_alertSyntaxPrefix = input.string(defval='CRYPTANEX_99FTX_Strategy-Name-Here', title='Alert Syntax Prefix', group='ProfitView Alert Syntax') alertSyntaxBase = i_alertSyntaxPrefix + '\n#' + str.tostring(open) + ',' + str.tostring(high) + ',' + str.tostring(low) + ',' + str.tostring(close) + ',' + str.tostring(volume) + ',' /// Trade Execution // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ longConditionCalc = (longCondition and isADXFilterEnabledAndAboveThreshold and isEMAFilterEnabledAndCloseAboveMA) shortConditionCalc = (shortCondition and isADXFilterEnabledAndAboveThreshold and isEMAFilterEnabledAndCloseBelowMA) if isStartEndPeriodsAndTimeInRange if longConditionCalc and i_tradeDirection != 'Short Only' and isInLongPosition == false strategy.entry('Long', strategy.long, qty=contracts) alert(message=alertSyntaxBase + 'side:long', freq=alert.freq_once_per_bar_close) if shortConditionCalc and i_tradeDirection != 'Long Only' and isInShortPosition == false strategy.entry('Short', strategy.short, qty=contracts) alert(message=alertSyntaxBase + 'side:short', freq=alert.freq_once_per_bar_close) //Inspired from Multiple %% profit exits example by adolgo https://www.tradingview.com/script/kHhCik9f-Multiple-profit-exits-example/ strategy.exit('TP1', qty_percent=i_takeProfitQuantityPercent1, profit=per(i_takeProfitTargetPercent1)) strategy.exit('TP2', qty_percent=i_takeProfitQuantityPercent2, profit=per(i_takeProfitTargetPercent2)) strategy.exit('TP3', qty_percent=i_takeProfitQuantityPercent3, profit=per(i_takeProfitTargetPercent3)) strategy.exit('i_takeProfitTargetPercent4', profit=per(i_takeProfitTargetPercent4)) // Stop Loss strategy.close('Long', qty_percent=100, comment='SL Long', when=slLongClose) strategy.close('Short', qty_percent=100, comment='SL Short', when=slShortClose) // Conditional Closes strategy.close('Long', qty_percent=100, comment='Close Long', when=closeLongCondition) strategy.close('Short', qty_percent=100, comment='Close Short', when=closeShortCondition) // Global Dashboard Variables // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Dashboard Table Text Size i_tableTextSize = input.string(title="Dashboard Size", defval="Small", options=["Auto", "Huge", "Large", "Normal", "Small", "Tiny"], group="Dashboards") table_text_size(s) => switch s "Auto" => size.auto "Huge" => size.huge "Large" => size.large "Normal" => size.normal "Small" => size.small => size.tiny tableTextSize = table_text_size(i_tableTextSize) /// Performance Summary Dashboard // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ // Inspired by https://www.tradingview.com/script/uWqKX6A2/ - Thanks VertMT i_showDashboard = input.bool(title="Performance Summary", defval=true, group="Dashboards", inline="Show Dashboards") f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) => _cellText = _title + "\n" + _value table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor, text_size=tableTextSize) // Draw dashboard table if i_showDashboard var bgcolor = color.new(color.black,0) // Keep track of Wins/Losses streaks newWin = (strategy.wintrades > strategy.wintrades[1]) and (strategy.losstrades == strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1]) newLoss = (strategy.wintrades == strategy.wintrades[1]) and (strategy.losstrades > strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1]) varip int winRow = 0 varip int lossRow = 0 varip int maxWinRow = 0 varip int maxLossRow = 0 if newWin lossRow := 0 winRow := winRow + 1 if winRow > maxWinRow maxWinRow := winRow if newLoss winRow := 0 lossRow := lossRow + 1 if lossRow > maxLossRow maxLossRow := lossRow // Prepare stats table var table dashTable = table.new(position.top_right, 1, 15, border_width=1) if barstate.islastconfirmedhistory // Update table dollarReturn = strategy.netprofit f_fillCell(dashTable, 0, 0, "Start:", str.format("{0,date,long}", strategy.closedtrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.closedtrades.entry_time(0)) f_fillCell(dashTable, 0, 1, "End:", str.format("{0,date,long}", strategy.opentrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.opentrades.entry_time(0)) _profit = (strategy.netprofit / strategy.initial_capital) * 100 f_fillCell(dashTable, 0, 2, "Net Profit:", str.tostring(_profit, '##.##') + "%", _profit > 0 ? color.teal : color.maroon, color.white) _numOfDaysInStrategy = (strategy.opentrades.entry_time(0) - strategy.closedtrades.entry_time(0)) / (1000 * 3600 * 24) f_fillCell(dashTable, 0, 3, "Percent Per Day", str.tostring(_profit / _numOfDaysInStrategy, '#########################.#####')+"%", _profit > 0 ? color.teal : color.maroon, color.white) _winRate = ( strategy.wintrades / strategy.closedtrades ) * 100 f_fillCell(dashTable, 0, 4, "Percent Profitable:", str.tostring(_winRate, '##.##') + "%", _winRate < 50 ? color.maroon : _winRate < 75 ? #999900 : color.teal, color.white) f_fillCell(dashTable, 0, 5, "Profit Factor:", str.tostring(strategy.grossprofit / strategy.grossloss, '##.###'), strategy.grossprofit > strategy.grossloss ? color.teal : color.maroon, color.white) f_fillCell(dashTable, 0, 6, "Total Trades:", str.tostring(strategy.closedtrades), bgcolor, color.white) f_fillCell(dashTable, 0, 8, "Max Wins In A Row:", str.tostring(maxWinRow, '######') , bgcolor, color.white) f_fillCell(dashTable, 0, 9, "Max Losses In A Row:", str.tostring(maxLossRow, '######') , bgcolor, color.white) // Monthly Table Performance Dashboard By @QuantNomad // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ i_showMonthlyPerformance = input.bool(true, 'Monthly Performance', group='Dashboards', inline="Show Dashboards") i_monthlyReturnPercision = 2 if i_showMonthlyPerformance new_month = month(time) != month(time[1]) new_year = year(time) != year(time[1]) eq = strategy.equity bar_pnl = eq / eq[1] - 1 cur_month_pnl = 0.0 cur_year_pnl = 0.0 // Current Monthly P&L cur_month_pnl := new_month ? 0.0 : (1 + cur_month_pnl[1]) * (1 + bar_pnl) - 1 // Current Yearly P&L cur_year_pnl := new_year ? 0.0 : (1 + cur_year_pnl[1]) * (1 + bar_pnl) - 1 // Arrays to store Yearly and Monthly P&Ls var month_pnl = array.new_float(0) var month_time = array.new_int(0) var year_pnl = array.new_float(0) var year_time = array.new_int(0) last_computed = false if (not na(cur_month_pnl[1]) and (new_month or barstate.islastconfirmedhistory)) if (last_computed[1]) array.pop(month_pnl) array.pop(month_time) array.push(month_pnl , cur_month_pnl[1]) array.push(month_time, time[1]) if (not na(cur_year_pnl[1]) and (new_year or barstate.islastconfirmedhistory)) if (last_computed[1]) array.pop(year_pnl) array.pop(year_time) array.push(year_pnl , cur_year_pnl[1]) array.push(year_time, time[1]) last_computed := barstate.islastconfirmedhistory ? true : nz(last_computed[1]) // Monthly P&L Table var monthly_table = table(na) if (barstate.islastconfirmedhistory) monthly_table := table.new(position.bottom_right, columns = 14, rows = array.size(year_pnl) + 1, border_width = 1) table.cell(monthly_table, 0, 0, "", bgcolor = #cccccc, text_size=tableTextSize) table.cell(monthly_table, 1, 0, "Jan", bgcolor = #cccccc, text_size=tableTextSize) table.cell(monthly_table, 2, 0, "Feb", bgcolor = #cccccc, text_size=tableTextSize) table.cell(monthly_table, 3, 0, "Mar", bgcolor = #cccccc, text_size=tableTextSize) table.cell(monthly_table, 4, 0, "Apr", bgcolor = #cccccc, text_size=tableTextSize) table.cell(monthly_table, 5, 0, "May", bgcolor = #cccccc, text_size=tableTextSize) table.cell(monthly_table, 6, 0, "Jun", bgcolor = #cccccc, text_size=tableTextSize) table.cell(monthly_table, 7, 0, "Jul", bgcolor = #cccccc, text_size=tableTextSize) table.cell(monthly_table, 8, 0, "Aug", bgcolor = #cccccc, text_size=tableTextSize) table.cell(monthly_table, 9, 0, "Sep", bgcolor = #cccccc, text_size=tableTextSize) table.cell(monthly_table, 10, 0, "Oct", bgcolor = #cccccc, text_size=tableTextSize) table.cell(monthly_table, 11, 0, "Nov", bgcolor = #cccccc, text_size=tableTextSize) table.cell(monthly_table, 12, 0, "Dec", bgcolor = #cccccc, text_size=tableTextSize) table.cell(monthly_table, 13, 0, "Year", bgcolor = #999999, text_size=tableTextSize) for yi = 0 to array.size(year_pnl) - 1 table.cell(monthly_table, 0, yi + 1, str.tostring(year(array.get(year_time, yi))), bgcolor = #cccccc, text_size=tableTextSize) y_color = array.get(year_pnl, yi) > 0 ? color.new(color.teal, transp = 40) : color.new(color.gray, transp = 40) table.cell(monthly_table, 13, yi + 1, str.tostring(math.round(array.get(year_pnl, yi) * 100, i_monthlyReturnPercision)), bgcolor = y_color, text_color=color.new(color.white, 0),text_size=tableTextSize) for mi = 0 to array.size(month_time) - 1 m_row = year(array.get(month_time, mi)) - year(array.get(year_time, 0)) + 1 m_col = month(array.get(month_time, mi)) m_color = array.get(month_pnl, mi) > 0 ? color.new(color.teal, transp = 40) : color.new(color.maroon, transp = 40) table.cell(monthly_table, m_col, m_row, str.tostring(math.round(array.get(month_pnl, mi) * 100, i_monthlyReturnPercision)), bgcolor = m_color, text_color=color.new(color.white, 0), text_size=tableTextSize)
Buy/Sell Signal Template/Boilerplate Strategy [JacobMagleby]
https://www.tradingview.com/script/7S5yD8R7-Buy-Sell-Signal-Template-Boilerplate-Strategy-JacobMagleby/
JacobMagleby
https://www.tradingview.com/u/JacobMagleby/
74
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/ // Β© ExoMaven //@version=5 strategy(title = "Buy/Sell Signal Template/Boilerplate Strategy[ExoMaven]", shorttitle = "Buy/Sell Signal Template Strategy[V1]", overlay = true) source = input.source(title = "Source", defval = ohlc4, group = "Source Settings") buy_type = input.string(title = "Buy Type", defval = "Greater Than", options = ["Greater Than", "Less Than"], group = "Signal Settings") buy_value = input.float(title = "Buy Value", defval = 50, group = "Signal Settings") sell_type = input.string(title = "Sell Type", defval = "Less Than", options = ["Less Than", "Greater Than"], group = "Signal Settings") sell_value = input.float(title = "Sell Value", defval = 50, group = "Signal Settings") buy_above_or_below = buy_type == "Greater Than" ? source > buy_value and source[1] < buy_value : source < buy_value and source[1] > buy_value sell_above_or_below = sell_type == "Less Than" ? source < sell_value and source[1] > sell_value : source > sell_value and source[1] < sell_value buy = buy_above_or_below and barstate.isconfirmed sell = sell_above_or_below and barstate.isconfirmed if buy strategy.close_all() strategy.entry(id = "Buy", direction = strategy.long) if sell strategy.close_all() strategy.entry(id = "Sell", direction = strategy.short)
Bitpanda Coinrule Template
https://www.tradingview.com/script/tXq7xJ09-Bitpanda-Coinrule-Template/
joshuajcoop01
https://www.tradingview.com/u/joshuajcoop01/
22
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© joshuajcoop01 //@version=5 strategy("Bitpanda Coinrule Template", overlay=true, initial_capital=1000, process_orders_on_close=true, default_qty_type=strategy.percent_of_equity, default_qty_value=30, commission_type=strategy.commission.percent, commission_value=0.1) showDate = input(defval=true, title='Show Date Range') timePeriod = time >= timestamp(syminfo.timezone, 2020, 1, 1, 0, 0) notInTrade = strategy.position_size <= 0 // RSI length = input(14) vrsi = ta.rsi(close, length) // Moving Averages for Buy Condition buyFastEMA = ta.ema(close, 9) buySlowEMA = ta.ema(close, 50) buyCondition1 = ta.crossover(buyFastEMA, buySlowEMA) increase = 5 if ((vrsi > vrsi[1]+increase) and buyCondition1 and vrsi < 70 and timePeriod) strategy.entry("Long", strategy.long) // Moving Averages for Sell Condition sellFastEMA = ta.ema(close, 9) sellSlowEMA = ta.ema(close, 50) plot(request.security(syminfo.tickerid, "60", sellFastEMA), color = color.blue) plot(request.security(syminfo.tickerid, "60", sellSlowEMA), color = color.green) condition = ta.crossover(sellSlowEMA, sellFastEMA) //sellCondition1 = request.security(syminfo.tickerid, "60", condition) strategy.close('Long', when = condition and timePeriod)
Bollinger Bands and RSI Short Selling (by Coinrule)
https://www.tradingview.com/script/G2OpsGq0-Bollinger-Bands-and-RSI-Short-Selling-by-Coinrule/
Coinrule
https://www.tradingview.com/u/Coinrule/
81
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© Coinrule // Works best on 30m, 45m timeframe //@version=5 strategy("Bollinger Bands and RSI Short Selling", overlay=true, initial_capital = 1000, default_qty_value = 30, default_qty_type = strategy.percent_of_equity, commission_type=strategy.commission.percent, commission_value=0.1) //Backtest period timePeriod = time >= timestamp(syminfo.timezone, 2021, 12, 1, 0, 0) notInTrade = strategy.position_size <= 0 //Bollinger Bands Indicator length = input.int(20, minval=1) src = input(close, title="Source") mult = input.float(2.0, minval=0.001, maxval=50, title="StdDev") basis = ta.sma(src, length) dev = mult * ta.stdev(src, length) upper = basis + dev lower = basis - dev offset = input.int(0, "Offset", minval = -500, maxval = 500) plot(basis, "Basis", color=#FF6D00, offset = offset) p1 = plot(upper, "Upper", color=#2962FF, offset = offset) p2 = plot(lower, "Lower", color=#2962FF, offset = offset) fill(p1, p2, title = "Background", color=color.rgb(33, 150, 243, 95)) // RSI inputs and calculations lengthRSI = 14 RSI = ta.rsi(close, lengthRSI) oversold= input(30) //Stop Loss and Take Profit for Shorting Stop_loss= ((input (1))/100) Take_profit= ((input (7)/100)) shortStopPrice = strategy.position_avg_price * (1 + Stop_loss) shortTakeProfit = strategy.position_avg_price * (1 - Take_profit) //Entry and Exit strategy.entry(id="short", direction=strategy.short, when=ta.crossover(close, upper) and RSI < 70 and timePeriod and notInTrade) if (ta.crossover(upper, close) and RSI > 70 and timePeriod) strategy.exit(id='close', stop = shortTakeProfit, limit = shortStopPrice)
Strategy Myth-Busting #1 - UT Bot+STC+Hull [MYN]
https://www.tradingview.com/script/s1ufMqI5-Strategy-Myth-Busting-1-UT-Bot-STC-Hull-MYN/
myncrypto
https://www.tradingview.com/u/myncrypto/
482
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© myn //@version=5 strategy('Strategy Myth-Busting #1 - UT Bot+STC+Hull+ [MYN]', max_bars_back=5000, overlay=true, pyramiding=0, initial_capital=500, currency='USD', default_qty_type=strategy.percent_of_equity, default_qty_value=1.0, commission_value=0.075) ///////////////////////////////////// //* Put your strategy logic below *// ///////////////////////////////////// //2oVDibie_bk /// UT Bot Alerts by QuantNomad - https://www.tradingview.com/script/n8ss8BID-UT-Bot-Alerts/ // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ //study(title="UT Bot Alerts", overlay = true) // Inputs a = input(2, title='Key Vaule. \'This changes the sensitivity\'') c = input(6, title='ATR Period') h = input(false, title='Signals from Heikin Ashi Candles') xATR = ta.atr(c) nLoss = a * xATR src = h ? request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close, lookahead=barmerge.lookahead_off) : close xATRTrailingStop = 0.0 iff_1 = src > nz(xATRTrailingStop[1], 0) ? src - nLoss : src + nLoss iff_2 = src < nz(xATRTrailingStop[1], 0) and src[1] < nz(xATRTrailingStop[1], 0) ? math.min(nz(xATRTrailingStop[1]), src + nLoss) : iff_1 xATRTrailingStop := src > nz(xATRTrailingStop[1], 0) and src[1] > nz(xATRTrailingStop[1], 0) ? math.max(nz(xATRTrailingStop[1]), src - nLoss) : iff_2 pos = 0 iff_3 = src[1] > nz(xATRTrailingStop[1], 0) and src < nz(xATRTrailingStop[1], 0) ? -1 : nz(pos[1], 0) pos := src[1] < nz(xATRTrailingStop[1], 0) and src > nz(xATRTrailingStop[1], 0) ? 1 : iff_3 xcolor = pos == -1 ? color.red : pos == 1 ? color.green : color.blue ema = ta.ema(src, 1) above = ta.crossover(ema, xATRTrailingStop) below = ta.crossover(xATRTrailingStop, ema) buy = src > xATRTrailingStop and above sell = src < xATRTrailingStop and below barbuy = src > xATRTrailingStop barsell = src < xATRTrailingStop //plotshape(buy, title = "Buy", text = 'Buy', style = shape.labelup, location = location.belowbar, color= color.green, textcolor = color.white, transp = 0, size = size.tiny) //plotshape(sell, title = "Sell", text = 'Sell', style = shape.labeldown, location = location.abovebar, color= color.red, textcolor = color.white, transp = 0, size = size.tiny) barcolor(barbuy ? color.green : na) barcolor(barsell ? color.red : na) alertcondition(buy, 'UT Long', 'UT Long') alertcondition(sell, 'UT Short', 'UT Short') /////////////////////////////////////////////// //======[ Position Check (long/short) ]======// /////////////////////////////////////////////// last_longCondition = float(na) last_shortCondition = float(na) last_longCondition := buy ? time : nz(last_longCondition[1]) last_shortCondition := sell ? time : nz(last_shortCondition[1]) in_longCondition = last_longCondition > last_shortCondition in_shortCondition = last_shortCondition > last_longCondition UTBotBuyZone = in_longCondition UTBotSellZone = in_shortCondition /// STC Indicator - A Better MACD [SHK] By shayankm - https://www.tradingview.com/script/WhRRThMI-STC-Indicator-A-Better-MACD-SHK/ // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ //[SHK] STC colored indicator //https://www.tradingview.com/u/shayankm/ //indicator(title='[SHK] Schaff Trend Cycle (STC)', shorttitle='STC', overlay=false) STCDivider = input(false, 'β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘') EEEEEE = input(80, 'Length') BBBB = input(27, 'FastLength') BBBBB = input(50, 'SlowLength') AAAA(BBB, BBBB, BBBBB) => fastMA = ta.ema(BBB, BBBB) slowMA = ta.ema(BBB, BBBBB) AAAA = fastMA - slowMA AAAA AAAAA(EEEEEE, BBBB, BBBBB) => AAA = input(0.5) var CCCCC = 0.0 var DDD = 0.0 var DDDDDD = 0.0 var EEEEE = 0.0 BBBBBB = AAAA(close, BBBB, BBBBB) CCC = ta.lowest(BBBBBB, EEEEEE) CCCC = ta.highest(BBBBBB, EEEEEE) - CCC CCCCC := CCCC > 0 ? (BBBBBB - CCC) / CCCC * 100 : nz(CCCCC[1]) DDD := na(DDD[1]) ? CCCCC : DDD[1] + AAA * (CCCCC - DDD[1]) DDDD = ta.lowest(DDD, EEEEEE) DDDDD = ta.highest(DDD, EEEEEE) - DDDD DDDDDD := DDDDD > 0 ? (DDD - DDDD) / DDDDD * 100 : nz(DDDDDD[1]) EEEEE := na(EEEEE[1]) ? DDDDDD : EEEEE[1] + AAA * (DDDDDD - EEEEE[1]) EEEEE mAAAAA = AAAAA(EEEEEE, BBBB, BBBBB) mColor = mAAAAA > mAAAAA[1] ? color.new(color.green, 20) : color.new(color.red, 20) if mAAAAA[3] <= mAAAAA[2] and mAAAAA[2] > mAAAAA[1] and mAAAAA > 75 alert('Red', alert.freq_once_per_bar) if mAAAAA[3] >= mAAAAA[2] and mAAAAA[2] < mAAAAA[1] and mAAAAA < 25 alert('Green', alert.freq_once_per_bar) //plot(mAAAAA, color=mColor, title='STC', linewidth=2) //ul = plot(25, color=color.new(color.white, 0 )) //ll = plot(75, color=color.new(color.purple, 0)) //fill(ul, ll, color=color.new(color.gray, 96)) STCGreenAndBelow25AndRising = mAAAAA > mAAAAA[1] and mAAAAA < 25 STCRedAndAndAbove75AndFalling = mAAAAA < mAAAAA[1] and mAAAAA > 75 /// Hull Suite by InSilico // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ //Basic Hull Ma Pack tinkered by InSilico - https://www.tradingview.com/script/hg92pFwS-Hull-Suite/ //study("Hull Suite by InSilico", overlay=true) HullDivider = input(false, 'β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘') //INPUT srcHull = input(close, title='Source') modeSwitch = input.string('Hma', title='Hull Variation', options=['Hma', 'Thma', 'Ehma']) length = input(55, title='Length(180-200 for floating S/R , 55 for swing entry)') lengthMult = input(1.0, title='Length multiplier (Used to view higher timeframes with straight band)') useHtf = input(false, title='Show Hull MA from X timeframe? (good for scalping)') htf = input.timeframe('240', title='Higher timeframe') switchColor = input(true, 'Color Hull according to trend?') candleCol = input(false, title='Color candles based on Hull\'s Trend?') visualSwitch = input(true, title='Show as a Band?') thicknesSwitch = input(1, title='Line Thickness') transpSwitch = input.int(40, title='Band Transparency', step=5) //FUNCTIONS //HMA HMA(_src, _length) => ta.wma(2 * ta.wma(_src, _length / 2) - ta.wma(_src, _length), math.round(math.sqrt(_length))) //EHMA EHMA(_src, _length) => ta.ema(2 * ta.ema(_src, _length / 2) - ta.ema(_src, _length), math.round(math.sqrt(_length))) //THMA THMA(_src, _length) => ta.wma(ta.wma(_src, _length / 3) * 3 - ta.wma(_src, _length / 2) - ta.wma(_src, _length), _length) //SWITCH Mode(modeSwitch, src, len) => modeSwitch == 'Hma' ? HMA(src, len) : modeSwitch == 'Ehma' ? EHMA(src, len) : modeSwitch == 'Thma' ? THMA(src, len / 2) : na //OUT _hull = Mode(modeSwitch, srcHull, int(length * lengthMult)) HULL = useHtf ? request.security(syminfo.ticker, htf, _hull) : _hull MHULL = HULL[0] SHULL = HULL[2] //COLOR hullColor = switchColor ? HULL > HULL[2] ? #00ff00 : #ff0000 : #ff9800 //PLOT ///< Frame Fi1 = plot(MHULL, title='MHULL', color=hullColor, linewidth=thicknesSwitch, transp=50) Fi2 = plot(visualSwitch ? SHULL : na, title='SHULL', color=hullColor, linewidth=thicknesSwitch, transp=50) alertcondition(ta.crossover(MHULL, SHULL), title='Hull trending up.', message='Hull trending up.') alertcondition(ta.crossover(SHULL, MHULL), title='Hull trending down.', message='Hull trending down.') ///< Ending Filler fill(Fi1, Fi2, title='Band Filler', color=hullColor, transp=transpSwitch) ///BARCOLOR barcolor(color=candleCol ? switchColor ? hullColor : na : na) HullGreen = hullColor == #00ff00 HullRed = hullColor == #ff0000 ////////////////////////////////////// //* Put your strategy rules below *// ///////////////////////////////////// longCondition = STCGreenAndBelow25AndRising and HullGreen and UTBotBuyZone shortCondition = STCRedAndAndAbove75AndFalling and HullRed and UTBotSellZone //define as 0 if do not want to use closeLongCondition = 0 closeShortCondition = 0 //β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ useStartPeriodTime = input.bool(true, 'Start', group='Date Range', inline='Start Period') startPeriodTime = input.time(timestamp('1 Jan 2019'), '', group='Date Range', inline='Start Period') useEndPeriodTime = input.bool(true, 'End', group='Date Range', inline='End Period') endPeriodTime = input.time(timestamp('31 Dec 2030'), '', group='Date Range', inline='End Period') start = useStartPeriodTime ? startPeriodTime >= time : false end = useEndPeriodTime ? endPeriodTime <= time : false calcPeriod = not start and not end // Trade Direction // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ tradeDirection = input.string('Long and Short', title='Trade Direction', options=['Long and Short', 'Long Only', 'Short Only'], group='Trade Direction') // Percent as Points // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ per(pcnt) => strategy.position_size != 0 ? math.round(pcnt / 100 * strategy.position_avg_price / syminfo.mintick) : float(na) // Take profit 1 // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ tp1 = input.float(title='Take Profit 1 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 1') q1 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 1') // Take profit 2 // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ tp2 = input.float(title='Take Profit 2 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 2') q2 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 2') // Take profit 3 // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ tp3 = input.float(title='Take Profit 3 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 3') q3 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 3') // Take profit 4 // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ tp4 = input.float(title='Take Profit 4 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit') /// Stop Loss // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ stoplossPercent = input.float(title='Stop Loss (%)', defval=15, minval=0.01, group='Stop Loss') * 0.01 slLongClose = close < strategy.position_avg_price * (1 - stoplossPercent) slShortClose = close > strategy.position_avg_price * (1 + stoplossPercent) /// Leverage // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ leverage = input.float(1, 'Leverage', step=.5, group='Leverage') contracts = math.min(math.max(.000001, strategy.equity / close * leverage), 1000000000) /// Trade State Management // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ isInLongPosition = strategy.position_size > 0 isInShortPosition = strategy.position_size < 0 /// ProfitView Alert Syntax String Generation // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ alertSyntaxPrefix = input.string(defval='PV-AccountNameHere_Strategy-Name-Here', title='Alert Syntax Prefix', group='ProfitView Alert Syntax') alertSyntaxBase = alertSyntaxPrefix + '\n#' + str.tostring(open) + ',' + str.tostring(high) + ',' + str.tostring(low) + ',' + str.tostring(close) + ',' + str.tostring(volume) + ',' /// Trade Execution // β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘ if calcPeriod if longCondition and tradeDirection != 'Short Only' and isInLongPosition == false strategy.entry('Long', strategy.long, qty=contracts) alert(message=alertSyntaxBase + 'side:long', freq=alert.freq_once_per_bar_close) if shortCondition and tradeDirection != 'Long Only' and isInShortPosition == false strategy.entry('Short', strategy.short, qty=contracts) alert(message=alertSyntaxBase + 'side:short', freq=alert.freq_once_per_bar_close) //Inspired by Multiple %% profit exits example By adolgo https://www.tradingview.com/script/kHhCik9f-Multiple-profit-exits-example/ strategy.exit('TP1', qty_percent=q1, profit=per(tp1)) strategy.exit('TP2', qty_percent=q2, profit=per(tp2)) strategy.exit('TP3', qty_percent=q3, profit=per(tp3)) strategy.exit('TP4', profit=per(tp4)) strategy.close('Long', qty_percent=100, comment='SL Long', when=slLongClose) strategy.close('Short', qty_percent=100, comment='SL Short', when=slShortClose) strategy.close_all(when=closeLongCondition or closeShortCondition, comment='Close Postion')
tvbot Trend Following with Mean Reversion algo
https://www.tradingview.com/script/NJnvcXRE-tvbot-Trend-Following-with-Mean-Reversion-algo/
tvbot-
https://www.tradingview.com/u/tvbot-/
32
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/ // Β© tvbot //@version=5 strategy("tvbot Trend Following Algo", overlay=true, precision=2, commission_value=0.075, commission_type=strategy.commission.percent, initial_capital=10000, currency=currency.USD, default_qty_type=strategy.percent_of_equity, default_qty_value=10, slippage=1, pyramiding=0) ////////////////////////////////////////////// USER INPUT /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Code below this line is the start of the Automated Trading Platform(ATP) code. It sets the parameters to send the webhook message to the Automated Trading Platform(ATP) to execute the trade/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// enableLong = input.bool(true, "Enable Long", group = "Enable / Disable") enableShort = input.bool(true, "Enable Short", group = "Enable / Disable") //////////////////// SERVER DATA INPUT exchange = input.string(title="Exchange", defval="Coinex", options=["Coinex"], group = "SERVER SIDE") ordertype = input.string(title="Ordertype", defval="Market", options=["Market", "Limit"], group = "SERVER SIDE") cash = input.float(title="Cash per Trade", defval=10, minval=-100, group = "SERVER SIDE") leverage = input.int(title="Leverage", defval=0, minval=0, group = "SERVER SIDE") i_time = input.time(defval = timestamp("01 Jan 2021 13:30 +0000"), title = "Start Time", group = "SERVER SIDE") afterStartDate = (time >= i_time) passphrase = input.string(title="Passphrase", defval='', group = "SERVER SIDE") key = input.string(title="key", defval='', group = "SERVER SIDE") secret = input.string(title="Secret", defval='', group = "SERVER SIDE") ////////////////// FILTER SERVER DATA message = '' var pair = "" var ordervolume = 0.0 if leverage == 0 pair := syminfo.basecurrency + "/" + syminfo.currency else if exchange == "Coinex" and leverage > 0 pair := syminfo.basecurrency + "/" + syminfo.currency + ":" + syminfo.currency if cash > 0 ordervolume := math.round(cash / close, 5) else if cash < 0 ordervolume := cash /////////////////////////////////////////////// ALERT MESSAGE LEmessage = exchange + " long/buy " + pair + " " + ordertype + " " + str.tostring(ordervolume) + " " + str.tostring(close) + " " + str.tostring(leverage) + " " + passphrase + " " + key + " " + secret LCmessage = exchange + " long/sell " + pair + " " + ordertype + " " + str.tostring(ordervolume) + " " + str.tostring(close) + " " + str.tostring(leverage) + " " + passphrase + " " + key + " " + secret SEmessage = exchange + " short/buy " + pair + " " + ordertype + " " + str.tostring(ordervolume) + " " + str.tostring(close) + " " + str.tostring(leverage) + " " + passphrase + " " + key + " " + secret SCmessage = exchange + " short/sell " + pair + " " + ordertype + " " + str.tostring(ordervolume) + " " + str.tostring(close) + " " + str.tostring(leverage) + " " + passphrase + " " + key + " " + secret ///////////////////////////////////////////////////////////////// //The code for the Automated Trading Platform(ATP) ends here///// ///////////////////////////////////////////////////////////////// // Inputs averageData = input.source(close, title="Source", group = "TrendLine") length = input.int(94, minval=1, title="Entry", group = "TrendLine") length3 = input.int(420, minval=1, title="ma", group = "TrendLine") ma = ta.ema(averageData, length3) //ema is used as the trendline hull = ta.vwma(averageData, length) //Base entry parameters use the vwma //section of code below turns the trendline into a range instead of a static line.//////////////////////////////////// Perc = input.float(title="SMA Touch Difference (%)", minval=0.0, step=0.1, defval=0.2, group = "SMA Touch") / 100///// ///// longExitPrice = ma * (1 + Perc) ///// shortExitPrice = ma * (1 - Perc) ///// ///// plot(longExitPrice, color = color.red, display = display.none) ///// plot(shortExitPrice, color = color.red, display = display.none) ///// ///// //section of code above turns the trendline into a range instead of a static line.//////////////////////////////////// //Code below this line is what sets the base entry condition. When a candle closes above or below the vwma, the algorithm records the close price of that candle. //then it waits for the vwma to meet that closed price. When vwma and the closed beaching candle meet then the condition is satisfied. //if the candle breaks back below or above the line it resets the condition. var isbuy = true var isfirstBuyCdnMeet = false var lastbuyClosePrice = 0.0 var isfirstSellCdnMeet = false var lastsellClosePrice = 0.0 buyhullcross = ta.crossover(close , hull) sellhullcross = ta.crossunder(close , hull) buycdn = isfirstBuyCdnMeet and ta.crossover(hull,lastbuyClosePrice) and isbuy sellcdn = isfirstSellCdnMeet and ta.crossunder(hull,lastsellClosePrice) and not isbuy if buyhullcross and barstate.isconfirmed isfirstBuyCdnMeet := true lastbuyClosePrice := close isfirstSellCdnMeet := false if sellhullcross and barstate.isconfirmed isfirstSellCdnMeet := true lastsellClosePrice := close isfirstBuyCdnMeet := false if sellcdn isfirstSellCdnMeet := false isbuy := true if buycdn isfirstBuyCdnMeet := false isbuy := false /////end of base entry condition///////////////////////////// //this section of code checks to see if the trend line has been tested. If the trend line has been tested then the condition also checks to see if your already in a position or not //a base entry signal from the code above is triggered will reset the trend line test condition. var is_sma_touch = false is_new_pos = ((strategy.position_size[1] == 0) and (strategy.position_size != 0)) or ((strategy.position_size[1] * strategy.position_size) == -1) // New position: Either we were not in a position before, or direction changed (short -> long or long -> short) sma_touch = (high > longExitPrice) and (low < longExitPrice) or (high > shortExitPrice) and (low < shortExitPrice) or (close < longExitPrice) and (close > shortExitPrice) or (high > ma ) and (low < ma) // SMA should be between high and low for a touch is_sma_touch := is_new_pos ? false : sma_touch ? true : is_sma_touch // Reset flag when it is a new position. Then check if there is a touch, keep its old value otherwise is_sma_touch := (isbuy and sellcdn) ? false : (not isbuy and buycdn) ? false : is_sma_touch // Reset when an opposite signal takes place //////////end of trend line test condition/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// REVERSION INDICATOR//////////////////// length2 = input.int(277, minval=1, title="Entry", group = "Reversion") length33 = input.int(1100, minval=1, title="ma", group = "Reversion") hull1 = ta.wma(2*ta.wma(averageData, length2/2)-ta.wma(averageData, length2), math.floor(math.sqrt(length2))) ma1 = ta.ema(averageData, length33) ///Code below is the entry condition for the mean reversion trade, its similar to the trend following entry condition but it uses the HMA instead of the VWMA var isbuy1 = true var isfirstBuyCdnMeet1 = false var lastbuyClosePrice1 = 0.0 var isfirstSellCdnMeet1 = false var lastsellClosePrice1 = 0.0 buyhullcross1 = ta.crossover(close , hull1) sellhullcross1 = ta.crossunder(close , hull1) buycdn1 = isfirstBuyCdnMeet1 and ta.crossover(hull1,lastbuyClosePrice1) and isbuy1 sellcdn1 = isfirstSellCdnMeet1 and ta.crossunder(hull1,lastsellClosePrice1) and not isbuy1 if buyhullcross1 and barstate.isconfirmed isfirstBuyCdnMeet1 := true lastbuyClosePrice1 := close isfirstSellCdnMeet1 := false if sellhullcross1 and barstate.isconfirmed isfirstSellCdnMeet1 := true lastsellClosePrice1 := close isfirstBuyCdnMeet1 := false if sellcdn1 isfirstSellCdnMeet1 := false isbuy1 := true if buycdn1 isfirstBuyCdnMeet1 := false isbuy1 := false //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //this code is how far the price needs to move away from the trend line/mean before a mean reversion entry is considered. triggerup = 1.01 * ma1 triggerdown = 0.99 * ma1 ////////////////////////////////////////// ENTRY AND EXIT code//////////////////////////////////////////////////////////////////////////// //"alert_message = LCmessage" is the code to tell the algo to send a LONG CLOSE message to the Automated Trading Platform(ATP)/// //"alert_message = SCmessage" is the code to tell the algo to send a SHORT CLOSE message to the Automated Trading Platform(ATP)// //"alert_message = LEmessage" is the code to tell the algo to send a LONG ENTRY message to the Automated Trading Platform(ATP)/// //"alert_message = SEmessage" is the code to tell the algo to send a SHORT ENTRY message to the Automated Trading Platform(ATP)// //"enableLong and afterStartDate" is required for your long entry parameters // //"enableShort and afterStartDate" is required for your short entry parameters // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //takeprofit conditions//////////////////// strategy.close('Buy Trend', when = sellcdn or sellcdn1 and averageData > triggerup, alert_message = LCmessage) // this is the take profit condition, when the base entry is triggered it will take profit or an entry condtion from the mean reversion system strategy.close('Sell Trend', when = buycdn or buycdn1 and averageData < triggerdown, alert_message = SCmessage) // this is the take profit condition, when the base entry is triggered it will take profit or an entry condtion from the mean reversion system strategy.close('Buy Reversion', when = sellcdn1 or sellcdn and (averageData < ma) and is_sma_touch[1], alert_message = LCmessage) // this is the take profit condition, when the base entry is triggered it will take profit or an entry condition from the trend following system strategy.close('Sell Reversion', when = buycdn1 or buycdn and (averageData > ma) and is_sma_touch[1], alert_message = SCmessage) // this is the take profit condition, when the base entry is triggered it will take profit or an entry condtion from the trend following system ///////////////////////////////// //trend following entry conditions/// if buycdn and (averageData > ma) and is_sma_touch[1] and enableLong and afterStartDate //this is the entry condition, base entry condition, price > trendline and trendline test, long enabled and after date set need to be true before a position is taken strategy.entry('Buy Trend', direction=strategy.long, alert_message = LEmessage) if sellcdn and (averageData < ma) and is_sma_touch[1] and enableShort and afterStartDate //this is the entry condition, base entry condition, price < trendline, trendline test, short enabled and after specified date need to be true before a short positon is taken strategy.entry('Sell Trend', direction=strategy.short, alert_message = SEmessage) ///////////////////// REVERSION entry if buycdn1 and averageData < triggerdown and enableLong and afterStartDate strategy.entry('Buy Reversion', direction=strategy.long, alert_message = LEmessage) if sellcdn1 and averageData > triggerup and enableShort and afterStartDate strategy.entry('Sell Reversion', direction=strategy.short, alert_message = SEmessage) ////////////////////////////////////////// PLOT DATA ON THE CHART plot(ma, color=color.blue, title = "trend mean") plot(hull, color=color.white, title="trend following") plot(hull1, color=color.black, title ="Reversion") //plotshape(buycdn, title='Buy Label for Trend Indicator', text='Buy', location=location.belowbar, style=shape.labelup, size=size.small, color=color.new(#0000FF, 0), textcolor=color.new(#FFFFFF, 0)) //plotshape(sellcdn, title='Sell Label for Trend Indicator', text='Sell', location=location.abovebar, style=shape.labeldown, size=size.small, color=color.new(#FF0000, 0), textcolor=color.new(#FFFFFF, 0)) //plotshape(buycdn1, title='Buy Label for Reversion Indicator', text='Buy', location=location.belowbar, style=shape.labelup, size=size.small, color=color.new(#0000FF, 0), textcolor=color.new(#FFFFFF, 0)) //plotshape(sellcdn1, title='Sell Label for Reversion Indicator', text='Sell', location=location.abovebar, style=shape.labeldown, size=size.small, color=color.new(#FF0000, 0), textcolor=color.new(#FFFFFF, 0))
Arnaud Legoux Moving Average Cross (ALMA)
https://www.tradingview.com/script/PgVGNY0m-Arnaud-Legoux-Moving-Average-Cross-ALMA/
Sarahann999
https://www.tradingview.com/u/Sarahann999/
195
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© Sarahann999 // Calculations for TP/SL based off: https://kodify.net/tradingview/orders/percentage-profit/ //@version=5 strategy("ALMA Cross", overlay=true) //User Inputs src= (close) long_entry = input(true, title='Long Entry') short_entry = input(true, title='Short Entry') //Fast Settings ALMA1 = input(60, "ALMA Lenghth 1", group= "ALMA Fast Length Settings") alma_offset = input.float(defval=0.85, title='Arnaud Legoux (ALMA) - Offset Value', minval=0, step=0.01) alma_sigma = input.int(defval=6, title='Arnaud Legoux (ALMA) - Sigma Value', minval=0) Alma1 = ta.alma(src, ALMA1, alma_offset, alma_sigma) //Slow Settings ALMA2 = input(120, "ALMA Length 2", group = "ALMA Slow Length Settings") alma_offset2 = input.float(defval=0.85, title='Arnaud Legoux (ALMA) - Offset Value', minval=0, step=0.01) alma_sigma2 = input.int(defval=6, title='Arnaud Legoux (ALMA) - Sigma Value', minval=0) Alma2 = ta.alma(src, ALMA2, alma_offset2, alma_sigma2) //Volume var cumVol = 0. cumVol += nz(volume) if barstate.islast and cumVol == 0 runtime.error("No volume is provided by the data vendor.") shortlen = input.int(5, minval=1, title = "Short Length", group= "Volume Settings") longlen = input.int(10, minval=1, title = "Long Length") short = ta.ema(volume, shortlen) long = ta.ema(volume, longlen) osc = 100 * (short - long) / long //Define Cross Conditions buy = ta.crossover(Alma1, Alma2) sell = ta.crossunder(Alma1, Alma2) //Calculate Take Profit Percentage longProfitPerc = input.float(title="Long Take Profit", group='Take Profit Percentage', minval=0.0, step=0.1, defval=2) / 100 shortProfitPerc = input.float(title="Short Take Profit", minval=0.0, step=0.1, defval=2) / 100 // Figure out take profit price 1 longExitPrice = strategy.position_avg_price * (1 + longProfitPerc) shortExitPrice = strategy.position_avg_price * (1 - shortProfitPerc) // Make inputs that set the stop % 1 longStopPerc = input.float(title="Long Stop Loss", group='Stop Percentage', minval=0.0, step=0.1, defval=2.5) / 100 shortStopPerc = input.float(title="Short Stop Loss", minval=0.0, step=0.1, defval=2.5) / 100 // Figure Out Stop Price longStopPrice = strategy.position_avg_price * (1 - longStopPerc) shortStopPrice = strategy.position_avg_price * (1 + shortStopPerc) //Define Conditions buySignal = buy and osc > 0 and strategy.position_size == 0 //sellSignal sellSignal = sell and osc > 0 and strategy.position_size == 0 // Submit entry orders if buySignal and long_entry strategy.entry(id="Long", direction=strategy.long, alert_message="Enter Long") alert(message="BUY Trade Entry Alert", freq=alert.freq_once_per_bar) if sellSignal and short_entry strategy.entry(id="Short", direction=strategy.short, alert_message="Enter Short") alert(message="SELL Trade Entry Alert", freq=alert.freq_once_per_bar) // Submit exit orders based on take profit price if (strategy.position_size > 0) strategy.exit(id="Long TP/SL", limit=longExitPrice, stop=longStopPrice, alert_message="Long Exit 1 at {{close}}") if (strategy.position_size < 0) strategy.exit(id="Short TP/SL", limit=shortExitPrice, stop=shortStopPrice, alert_message="Short Exit 1 at {{close}}") //Draw plot(Alma1,"Alma Fast", color=color.purple, style=plot.style_circles) plot(Alma2,"Alma Slow", color=#acb5c2, style=plot.style_circles)
sachin5986
https://www.tradingview.com/script/VmeLNdxg-sachin5986/
mohitesachin78
https://www.tradingview.com/u/mohitesachin78/
8
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/ // Β© mohitesachin78 //@version=4 strategy("sachin5986") ema3 = ema(close,3) ema21 = ema(close,21) long = ema3>ema21 short = ema3<ema21 start = timestamp(2022,19,7,0) end = timestamp(2022,12,12,0) strategy.entry("buy",strategy.long,when = long) strategy.close("buy",when = short) plot(close)
2x take profit, move stop loss to entry
https://www.tradingview.com/script/0Blrq2NA-2x-take-profit-move-stop-loss-to-entry/
fpsd4ve
https://www.tradingview.com/u/fpsd4ve/
379
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/ // Β© fpsd4ve //@version=5 // Add Bollinger Bands indicator (close, 20, 2) manually to visualise trading conditions strategy("2xTP, SL to entry", overlay=false, pyramiding=0, calc_on_every_tick=false, default_qty_type=strategy.percent_of_equity, default_qty_value=25, initial_capital=1000, commission_type=strategy.commission.percent, commission_value=0.01 ) // PARAMETERS // Assumes quote currency is FIAT as with BTC/USDT pair tp1=input.float(200, title="Take Profit 1") tp2=input.float(500, title="Take Profit 2") sl=input.float(200, title="Stop Loss") stOBOS = input.bool(true, title="Use Stochastic overbought/oversold threshold") // Colors colorRed = #FF2052 colorGreen = #66FF00 // FUNCTIONS // Stochastic f_stochastic() => stoch = ta.stoch(close, high, low, 14) stoch_K = ta.sma(stoch, 3) stoch_D = ta.sma(stoch_K, 3) stRD = ta.crossunder(stoch_K, stoch_D) stGD = ta.crossover(stoch_K, stoch_D) [stoch_K, stoch_D, stRD, stGD] // VARIABLES [bbMiddle, bbUpper, bbLower] = ta.bb(close, 20, 2) [stoch_K, stoch_D, stRD, stGD] = f_stochastic() // ORDERS // Active Orders // Check if strategy has open positions inLong = strategy.position_size > 0 inShort = strategy.position_size < 0 // Check if strategy reduced position size in last bar longClose = strategy.position_size < strategy.position_size[1] shortClose = strategy.position_size > strategy.position_size[1] // Entry Conditions // Enter long when during last candle these conditions are true: // Candle high is greater than upper Bollinger Band // Stochastic K line crosses under D line and is oversold longCondition = stOBOS ? low[1] < bbLower[1] and stGD[1] and stoch_K[1] < 25 : low[1] < bbLower[1] and stGD[1] // Enter short when during last candle these conditions are true: // Candle low is lower than lower Bollinger Band // Stochastic K line crosses over D line and is overbought shortCondition = stOBOS ? high[1] > bbUpper[1] and stRD[1] and stoch_K[1] > 75 : high[1] > bbUpper[1] and stRD[1] // Exit Conditions // Calculate Take Profit longTP1 = strategy.position_avg_price + tp1 longTP2 = strategy.position_avg_price + tp2 shortTP1 = strategy.position_avg_price - tp1 shortTP2 = strategy.position_avg_price - tp2 // Calculate Stop Loss // Initialise variables var float longSL = 0.0 var float shortSL = 0.0 // When not in position, set stop loss using close price which is the price used during backtesting // When in a position, check to see if the position was reduced on the last bar // If it was, set stop loss to position entry price. Otherwise, maintain last stop loss value longSL := if inLong and ta.barssince(longClose) < ta.barssince(longCondition) strategy.position_avg_price else if inLong longSL[1] else close - sl shortSL := if inShort and ta.barssince(shortClose) < ta.barssince(shortCondition) strategy.position_avg_price else if inShort shortSL[1] else close + sl // Manage positions strategy.entry("Long", strategy.long, when=longCondition) strategy.exit("TP1/SL", from_entry="Long", qty_percent=50, limit=longTP1, stop=longSL) strategy.exit("TP2/SL", from_entry="Long", limit=longTP2, stop=longSL) strategy.entry("Short", strategy.short, when=shortCondition) strategy.exit("TP1/SL", from_entry="Short", qty_percent=50, limit=shortTP1, stop=shortSL) strategy.exit("TP2/SL", from_entry="Short", limit=shortTP2, stop=shortSL) // DRAW // Stochastic Chart plot(stoch_K, color=color.blue) plot(stoch_D, color=color.orange) // Circles plot(stOBOS ? stRD and stoch_K >= 75 ? stoch_D : na : stRD ? stoch_D : na, color=colorRed, style=plot.style_circles, linewidth=3) plot(stOBOS ? stGD and stoch_K <= 25 ? stoch_D : na : stGD ? stoch_K : na, color=colorGreen, style=plot.style_circles, linewidth=3) // Levels hline(75, linestyle=hline.style_dotted) hline(25, linestyle=hline.style_dotted)
Daily_Mid Term_Consulting BOLT
https://www.tradingview.com/script/okRDWPql-Daily-Mid-Term-Consulting-BOLT/
murdocksilva
https://www.tradingview.com/u/murdocksilva/
18
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/ // Β© murdocksilva //@version=5 strategy("Daily_Mid Term_Consulting BOLT") //calculo longuitud longuitud = input(58, title= "longitud_sma") px = ta.sma(close, 1) px2 = ta.sma(low, 1) Length1 = input.int(18) Length2 = input.int(18) Length3 = input.int(26) Length4 = input.int(36) Length5 = input.int(78) Length6 = input.int(1) Length7 = input.int(1500) Length8 = input.int(58) Length9 = input.int(3000) Length10 = input.int(2) Length11 = input.int(14) ma1 = ta.sma(low, Length1) ma2 = ta.sma(high, Length2) ma3 = ta.sma(close, Length3) ma4 = ta.sma(close, Length4) ma5 = ta.sma(close, Length5) ma6 = ta.sma(close, Length6) ma7 = ta.sma(close, Length7) ma8 = ta.sma(close, Length8) ma9 = ta.sma(close, Length9) ma10 = ta.sma(close, Length10) ma11 = ta.sma(close, Length11) // calculo EFI efi = (close[1]-close) * volume / 1000 efi_indicador = (efi[1] + efi) / 2 //Variable RSI - calculo desv estandar b = (px-ma10)*(px-ma10) b2 = (px[1]-ma10[1])*(px[1]-ma10[1]) c = b + b2 c2 = c / 2 desv = math.sqrt(c2)/10 //calculo MACD macd = ma4 - ma5 //calculo RSI rsi = ta.rsi(close, 9) // calculo Divergencia ma = ta.sma(close, longuitud) dist = close - ma porcentaje = dist * 100 / close ma_dista = ta.sma(porcentaje, 333) //condiciΓ³n de entrada y salida long long = ma1[1] < ma1 and ma2[1] < ma2 and macd > 0 and px > ma3 and efi_indicador < 9 and px > ma7 and macd[1] < macd clong = efi_indicador > 22000 and px < ma8 strategy.entry("BUY", strategy.long, when = long) strategy.close("BUY", when = clong) //condiciΓ³n de entrada y salida short short = ma1[1] > ma1 and ma2[1] > ma2 and macd < 0 and px < ma3 and efi_indicador > 9 and macd[1] > macd cshort = efi_indicador < 14000 and px > ma8 and ma11 > desv strategy.entry("SELL", strategy.short, when = short) strategy.close("SELL", when = cshort) //SL Y TP //strategy.exit("long exit", "Daily_Mid Term_Consulting BOLT", profit = close * 40 / syminfo.mintick, loss = close * 0.02 / syminfo.mintick) //strategy.exit("shot exit", "Daily_Mid Term_Consulting BOLT", profit = close * 40 / syminfo.mintick, loss = close * 0.02 / syminfo.mintick) // GRAFICA smas plot(ma1, color=color.new(color.orange, 0)) plot(ma2, color=color.new(color.orange, 0)) plot(ma3, color=color.new(color.orange, 0)) plot(ma4, color=color.new(color.orange, 0)) plot(ma5, color=color.new(color.orange, 0)) plot(ma6, color=color.new(color.green, 0)) plot(ma7, color=color.new(color.orange, 0)) plot(ma8, color=color.new(color.orange, 0)) plot(ma9, color=color.new(color.orange, 0)) //GRAFICA MACD plot(macd, color=color.new(color.red, 0), style = plot.style_columns) //GRAFICA DIVERGENCIA plot(porcentaje, style = plot.style_columns) //GRAFICA MA DIVERGENCIA plot(ma_dista, color=color.new(color.white, 0)) //GRAFICA MA DIVERGENCIA plot(desv, color=color.new(color.blue, 0)) //GRAFICA EFI plot(efi_indicador, color=color.new(color.yellow, 0)) // GRAFICA RSI l1 = hline(70, color=color.new(color.green, 0)) l2 = hline(30, color=color.new(color.green, 0)) plot(rsi, color=color.new(color.white, 0)) //prueba 1 stop loss and take profit //sl = 0.05 //tp = 0.1 //calculo de precio para sl y tp //longstop=strategy.position_avg_price*(1-sl) //longprofit=strategy.position_avg_price*(1+tp) //shortstop=strategy.position_avg_price*(1+sl) //shortprofit=strategy.position_avg_price*(1-tp) //if (long) // strategy.exit("BUY", strategy.long) //sl and tp long|short //if strategy.entry("BUY", strategy.long) //if strategy.position_avg_price > 0 //strategy.exit("BUY", limit = longprofit, stop = longstop) //if strategy.position_avg_price < 0 //strategy.exit("SELL", limit = shortprofit, stop=shortstop)
Strategy Oil Z Score
https://www.tradingview.com/script/3K79zam6-Strategy-Oil-Z-Score/
jroche1973
https://www.tradingview.com/u/jroche1973/
49
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© jroche1973 //@version=4 strategy("Strategy Oil Z Score", precision=6, overlay=false, pyramiding=100, calc_on_order_fills=true) 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) Length = input(252) //252 o_StdDevs = input(defval = 2.0, title="Oil Z Std Dev") use_what = input(title="Use underlying", defval="Oil", options=["Oil", "Move", "Vix"]) _bb_mult = input(title="BB mult", type=input.float, defval=2) _bb_range = input(title="BB mean range", type=input.integer, defval=20) //src = input(close) MOVE = security("TVC:MOVE", timeframe.period, close) VIX = security("VIX", timeframe.period, close) OILVIX = security("CBOE:OVX", timeframe.period, close) USO = security("TVC:USOIL", timeframe.period, close) show_ema = input(type=input.bool, title="Apply EMA", defval=true) l_ema = input( title="EMA Length", defval=100) startDateTime = input(type=input.time, defval=timestamp("15 July 2019 09:30"), title="Start Date", group="Strategy Date Range", tooltip="Specifies the start date and time from which " + "the strategy simulates buy and sell trades.") [_bb_mid, _bb_hig, _bb_low] = bb(close, _bb_range, _bb_mult) _bb_percent = (close - _bb_low) / (_bb_hig - _bb_low) s_ema = ema(close, l_ema) iOILVIX = 1/OILVIX divO = USO/iOILVIX //Proxy of M of Move ie alt VVIX if use_what == "Move" divO := MOVE/iOILVIX else if use_what == "Vix" divO := VIX/iOILVIX else divO := USO/iOILVIX m_basis = sma(divO, Length) m_zscore = (divO - m_basis) / stdev(divO, Length) show_m = true hline(o_StdDevs, color=color.white, linestyle=hline.style_dotted) hline(-1 * o_StdDevs, color=color.white, linestyle=hline.style_dotted) color m_color = m_zscore < 0 ? color.new(color.white, 70): color.new(color.blue, 70) //we want white if not active color mb_color = m_zscore < 0 and _bb_percent > 0.5 ? color.new(color.white, 70): color.new(color.blue, 70) //we want white if not active use_b = _bb_percent < 0.5 ? true: false bgcolor(show_m and use_b ? color.new(m_color,70) : color.new(color.white, 70)) // we want whatever color our status stipulates if 'on' or white if 'off' //Strategy Testing long_move = m_zscore < 0 and _bb_percent > 0.5 short_move = m_zscore > 0 and _bb_percent < 0.5 if show_ema if time >= startDateTime and time <= timenow if m_zscore > 0 and _bb_percent < 0.5 and close < s_ema //short strategy.entry("sell", strategy.short, 100, when=strategy.position_size > 0) strategy.close("close long", when=long_move) else strategy.entry("buy", strategy.long, 100, when=strategy.position_size <= 0) strategy.close("close short", when=short_move) else if time >= startDateTime and time <= timenow if m_zscore > 0 and _bb_percent < 0.5//short strategy.entry("sell", strategy.short, 100, when=strategy.position_size > 0) strategy.close("close long", when=long_move) else strategy.entry("buy", strategy.long, 100, when=strategy.position_size <= 0) strategy.close("close short", when=short_move)
UP TREND AND DOWN TREND
https://www.tradingview.com/script/xJjEWHh1-UP-TREND-AND-DOWN-TREND/
natrajgcl
https://www.tradingview.com/u/natrajgcl/
45
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/ // Β© natrajgcl //@version=5 strategy("UP TREND AND DOWN TREND", overlay=true, margin_long=100, margin_short=100) longCondition = ta.crossover(ta.sma(close, 20), ta.sma(close, 200)) if (longCondition) strategy.entry("UP TREND", strategy.long) shortCondition = ta.crossunder(ta.sma(close, 20), ta.sma(close, 200)) if (shortCondition) strategy.entry("DOWN TREND", strategy.short)
Buy Monday, Exit Wednesday
https://www.tradingview.com/script/PpDSzaSs-Buy-Monday-Exit-Wednesday/
mihirkawatra
https://www.tradingview.com/u/mihirkawatra/
33
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© processingclouds // @description Strategy to go long at end of Monday and exit by Tuesday close, or at stop loss or take profit percentages //@version=5 strategy("Buy Monday, Exit Wednesday", "Mon-Wed Swings",overlay=true) // ----- Inputs: stoploss %, takeProfit % stopLossPercentage = input.float(defval=4.0, title='StopLoss %', minval=0.1, step=0.2) / 100 takeProfit = input.float(defval=3.0, title='Take Profit %', minval=0.3, step=0.2) / 100 // ----- Exit and Entry Conditions - Check current day and session time isLong = dayofweek == dayofweek.monday and not na(time(timeframe.period, "1400-1601")) isExit = dayofweek == dayofweek.wednesday and not na(time(timeframe.period, "1400-1601")) // ----- Calculate Stoploss and Take Profit values SL = strategy.position_avg_price * (1 - stopLossPercentage) TP = strategy.position_avg_price * (1 + takeProfit) // ----- Strategy Enter, and exit when conditions are met strategy.entry("Enter Long", strategy.long, when=isLong) if strategy.position_size > 0 strategy.close("Enter Long", isExit) strategy.exit(id="Exit", stop=SL, limit=TP) // ----- Plot Stoploss and TakeProfit lines plot(strategy.position_size > 0 ? SL : na, style=plot.style_linebr, color=color.red, linewidth=2, title="StopLoss") plot(strategy.position_size > 0 ? TP : na, style=plot.style_linebr, color=color.green, linewidth=2, title="TakeProfit")
3ngine Global Boilerplate
https://www.tradingview.com/script/WalPPb0R-3ngine-Global-Boilerplate/
jordanfray
https://www.tradingview.com/u/jordanfray/
118
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© jordanfray //@version=5 strategy(title="Boilerplate", overlay=true, max_bars_back=5000, commission_type=strategy.commission.percent, close_entries_rule="ANY", commission_value=0.035, backtest_fill_limits_assumption=0, calc_on_order_fills=true, process_orders_on_close=true) import jordanfray/threengine_global_automation_library/10 as bot // This is a required library // A B O U T T H E B O I L E R P L A T E // This strategy is desisnged to bring consistency to your strategies. It includes a macro EMA filter for filtering out countertrend trades, // an ADX filter to help filter out chop, a session filter to filter out trades outside of desired timeframe, alert messages setup for automation, // laddering in/out of trades (up to 6 rungs), trailing take profit, and beautiful visuals for each entry. There are comments throughout the // strategy that provide further instructions on how to use the boilerplate strategy. This strategy uses more_margin_trade_automation_library // throughout and must be included at the top of the strategy using import [path to latest version] as bot. This allows you to use dot notation // to access functions in the library - EX: bot.orderCurrentlyExists(). // H O W T O U S E T H I S S T R A T E G Y // 1 Add your inputs // 2 Add your calculations // 3 Add your entry criteria // 3.1 Add your criteria to strategySpecificLongConditions (this gets combined with boilerplate conditions in longConditionsMet) // 3.2 Add your criteria to strategySpecificShortConditions (this gets combined with boilerplate conditions in shortConditionsMet) // 3.4 Set your desired entry price (calculated on every bar unless stored as a static variable) to longEntryPrice and shortEntryPrice. // Default is the bar "close". This will be the FIRST ladder if using laddering capabilities. If you pick 1 for "Ladder In Rungs" // this will be the only entry. // 4 Plot anything you want to overlay on the chart in addition to the boilerplate plots and labels. Included in boilerplate: // Average entry price (blue), stop loss (red), trailing stop (red/green), profit target (green). // Indenting Classs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - indent = "    " // Colors - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - oceanBlue = color.new(#0C6090,0) skyBlue = color.new(#00A5FF,0) green = color.new(#2DBD85,0) nevisShallows = color.new(#00FFD4,0) red = color.new(#E02A4A,0) lightBlue = color.new(#00A5FF,80) lightGreen = color.new(#2DBD85,80) lightRed = color.new(#E02A4A,80) lightYellow = color.new(#FFF900,80) white = color.new(#ffffff,0) black = color.new(#191B20,0) gray = color.new(#AAAAAA,0) lightGray = color.new(#AAAAAA,90) transparent = color.new(#000000,100) // Input Groups - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - groupOneTitle = "Strategy Settings " groupTwoTitle = "Filters" groupThreeTitle = "Entry Settings" groupFourTitle = "Exit Settings" // Tooltips - This is where all of the tooltips are defined to keep the code clean below - - - - - - - - - - - - - - - - - - - - - - - - - - - - startTip = "Select where you want to start laddering in from." stopLossTip = "Select where you want your stop loss to be." ladderInToolTip = "Enable this to use the laddering settings below." cancelEntryToolTip = "When the position reaches a certain percent profit, you can cancel any unfiller orders." ladderInStepsTip = "When the criteria for entering a strategy is met, the order can placed using a single order or split across multiple ladder orders. Select 1 to place a single order." ladderInStepSpacingTip = "The percent distance between the orders. Ex: If the strategy produces an entry signal to buy at $20,000 and the strategy is configured to ladder into the position across 4 steps, setting the Ladder In Step Spacing to 1% would split the entry into 4 orders at $20,000, $19,800, $19,600, and $19,400." ladderOutStepsTip = "When the criteria for exiting a strategy is met, the order can placed using a single order or split across multiple ladder orders. Select 1 to place a single order." ladderOutStepSpacingTip = "The percent distance between the orders. Ex: If the strategy produces an exit signal to sell at $21,000 and the strategy is configured to ladder out of the position across 2 steps, setting the Ladder Out Step Spacing to 1% would split the entry into 2 orders at $21,000, $21,210." // Strategy Specific Inputs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - start = input.price(defval=0, title="Starting ladering in at ", confirm=true, group=groupOneTitle, tooltip=startTip) stop = input.price(defval=0, title="set stop loss at", confirm=true, group=groupOneTitle, tooltip=stopLossTip) // This strategy uses a price based stop loss. You can use a percent based stop loss as part of the boilerplate settings below. cancelUnfilledOrdersAfter = input.float(defval=10, title="Cancel Unfiller Orders After", confirm=false, group=groupOneTitle, tooltip=cancelEntryToolTip)/100 // This strategy uses a price based stop loss. You can use a percent based stop loss as part of the boilerplate settings below. // Boilerplate Inputs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - showStrategyStatusBox = input.bool(defval=true, title="Show Strategy Status Box", group=groupOneTitle) enableMacroEmaFilter = input.bool(defval=false, title="Use EMA Filter", group=groupTwoTitle) macroEmaTimeframe = input.timeframe(defval="240", title=indent+"Timeframe", group=groupTwoTitle) macroEmaLength = input.int(defval=100, minval=1, step=10, title=indent+"Length", group=groupTwoTitle) macroEmaType = input.string(defval="EMA", options = ["EMA", "SMA", "RMA", "WMA"], title=indent+"Type", group=groupTwoTitle) macroEmaSource = input.source(defval=close, title=indent+"Source", group=groupTwoTitle) enableAdxFilter = input.bool(defval=false, title="Use ADX Filter", group=groupTwoTitle) diLength = input.int(defval=14, title=indent+"DI Length", group=groupTwoTitle) adxSmoothing = input.int(defval=14, title=indent+"ADX Smoothing", group=groupTwoTitle) adxMinumum = input.int(defval=30, title=indent+"ADX Must Be Between"+"      ", inline="adxGroup", group=groupTwoTitle) adxMaximum = input.int(defval=100, title="", inline="adxGroup", group=groupTwoTitle) useTimeFilter = input.bool(defval=false, title="Use Time Session Filter", group=groupTwoTitle) timeSession = input.session(defval="0800-1700", title=indent+"Only Take Trades Between", group=groupTwoTitle) startTime = input.time(defval=timestamp("01 Jan 2022 00:00"), confirm=true, title=indent+"Strategy Start", group=groupTwoTitle) // Remove "confirm=true" from this line if you don't want to pick a time when adding the strategy to the chart ladderInSteps = input.int(defval=2, minval=1, maxval=6, step=1, title="Ladder In Rungs", group=groupThreeTitle, tooltip=ladderInStepsTip) ladderInStepSpacingPercent = input.float(defval=2, title="Ladder In Step Spacing (%)", step=.25, group=groupThreeTitle, tooltip=ladderInStepSpacingTip) ladderOutSteps = input.int(defval=2, minval=1, maxval=6, step=1, title="Ladder Out Rungs", group=groupFourTitle, tooltip=ladderOutStepsTip) ladderOutStepSpacingPercent = input.float(defval=2, title="Ladder Out Step Spacing (%)", step=.25, group=groupFourTitle, tooltip=ladderOutStepSpacingTip)/100 takeProfitVal = input.float(defval=20, title="Take Profit (%)", step=0.25, group=groupFourTitle)/100 stopLossVal = input.float(defval=10, title="Stop Loss (%)", step=0.25, group=groupFourTitle)/100 // This sample strategy does not use a percent based stop loss. Instead it uses a price based stop loss above. startTrailingAfter = input.float(defval=10, title="Start Trailing After (%)", step=0.25, group=groupFourTitle)/100 trailBehind = input.float(defval=10, title="Trail Behind (%)", step=0.25, group=groupFourTitle)/100 // Boilerplate Calculations - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - macroEma = request.security(syminfo.tickerid, macroEmaTimeframe, bot.taGetEma(macroEmaType, macroEmaSource, macroEmaLength)[barstate.isrealtime ? 1 : 0]) closeAboveEmaMacroFilter = enableMacroEmaFilter ? close > macroEma : true closeBelowEmaMacroFilter = enableMacroEmaFilter ? close < macroEma : true adx = bot.taGetAdx(diLength, adxSmoothing) adxInRange = enableAdxFilter ? adx >= adxMinumum and adx <= adxMaximum : true withTime = useTimeFilter ? bot.isBetweenTwoTimes(timeSession,"GMT-6") : true bool beyondStartTime = time > startTime currentlyInLongPosition = strategy.position_size > 0 currentlyInShortPosition = strategy.position_size < 0 currentlyInAPosition = strategy.position_size != 0 StrategyEntryPrice = start // Set this to the price the strategy should start laddering in at [ladderStartPrice,ladderStartedOnBar] = bot.getLockedLadderStart(StrategyEntryPrice) barsSinceEntry = currentlyInAPosition ? bar_index - ladderStartedOnBar + 1 : 1 avgPrice = bot.getAveragePriceOfFilledLadders() // Boilerplate Entry Criteria boilerplateLongConditionsMet = beyondStartTime and closeAboveEmaMacroFilter and adxInRange and withTime and not currentlyInShortPosition boilerplateShortConditionsMet = beyondStartTime and closeAboveEmaMacroFilter and adxInRange and withTime and not currentlyInLongPosition // Strategy Specific Calculations - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - var string side = start > stop ? "buy" : "sell" // Strategy Specific Entry Criteria alreadyClosedTrades = strategy.closedtrades > 0 strategySpecificLongConditions = side == "buy" and not alreadyClosedTrades strategySpecificShortConditions = side == "sell" and not alreadyClosedTrades // Combined Entry Conditions Array Construction longConditionsMet = strategySpecificLongConditions and boilerplateLongConditionsMet shortConditionsMet = strategySpecificShortConditions and boilerplateShortConditionsMet longLadder1Criteria = not bot.orderCurrentlyExists("Long - 1") and strategy.opentrades == 0 and longConditionsMet longLadder2Criteria = not bot.orderCurrentlyExists("Long - 2") and strategy.opentrades == 1 and longConditionsMet longLadder3Criteria = not bot.orderCurrentlyExists("Long - 3") and strategy.opentrades == 2 and longConditionsMet longLadder4Criteria = not bot.orderCurrentlyExists("Long - 4") and strategy.opentrades == 3 and longConditionsMet longLadder5Criteria = not bot.orderCurrentlyExists("Long - 5") and strategy.opentrades == 4 and longConditionsMet longLadder6Criteria = not bot.orderCurrentlyExists("Long - 6") and strategy.opentrades == 5 and longConditionsMet bool[] longLadderInCriterias = array.from(longLadder1Criteria,longLadder2Criteria,longLadder3Criteria, longLadder4Criteria, longLadder5Criteria, longLadder6Criteria) shortLadder1Criteria = not bot.orderCurrentlyExists("Short - 1") and strategy.opentrades == 0 and shortConditionsMet shortLadder2Criteria = not bot.orderCurrentlyExists("Short - 2") and strategy.opentrades == 1 and shortConditionsMet shortLadder3Criteria = not bot.orderCurrentlyExists("Short - 3") and strategy.opentrades == 2 and shortConditionsMet shortLadder4Criteria = not bot.orderCurrentlyExists("Short - 4") and strategy.opentrades == 3 and shortConditionsMet shortLadder5Criteria = not bot.orderCurrentlyExists("Short - 5") and strategy.opentrades == 4 and shortConditionsMet shortLadder6Criteria = not bot.orderCurrentlyExists("Short - 6") and strategy.opentrades == 5 and shortConditionsMet bool[] shortLadderInCriterias = array.from(shortLadder1Criteria,shortLadder2Criteria,shortLadder3Criteria, shortLadder4Criteria, shortLadder5Criteria, shortLadder6Criteria) // Stop Criteria - "When" orders will exit due to hitting stop loss or trailing stop - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - longRunUp = ta.highest(high, bar_index == 0 ? 5000 : barsSinceEntry) longTrailingTrigger = avgPrice + (avgPrice * startTrailingAfter) // longStopLoss = currentlyInLongPosition and longRunUp > longTrailingTrigger ? longRunUp - (longRunUp * trailBehind) : strategy.position_avg_price * (1.0 - stopLossVal) // Use this for a percent based stop loss longStopLoss = currentlyInLongPosition and longRunUp > longTrailingTrigger ? longRunUp - (longRunUp * trailBehind) : stop shortRunDown = ta.lowest(low, bar_index == 0 ? 5000 : barsSinceEntry) shortTrailingTrigger = avgPrice - (avgPrice * startTrailingAfter) // shortStopLoss = currentlyInShortPosition and shortRunDown < shortTrailingTrigger ? shortRunDown + (shortRunDown * trailBehind) : strategy.position_avg_price * (1 + stopLossVal) // Use this for a percent based stop loss shortStopLoss = currentlyInShortPosition and shortRunDown < shortTrailingTrigger ? shortRunDown + (shortRunDown * trailBehind) : stop // Use this for a price based stop loss // Take Profit - The point in which the first ladder entry will take profit based on average entry price - - - - - - - - - - - - - - - - - - - - - - - - - - float longProfitTarget = avgPrice * (1 + takeProfitVal) float shortProfitTarget = avgPrice * (1 - takeProfitVal) takeProfitConditions = strategy.openprofit > 0 // Criteria for Canceling unfilled orders cancelUnfilledLongEntries = false // close > strategy.position_avg_price + (strategy.position_avg_price * cancelUnfilledOrdersAfter) cancelUnfilledShortEntries = false // close < strategy.position_avg_price - (strategy.position_avg_price * cancelUnfilledOrdersAfter) // Orders - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - [longEntryPrices, longEntryContractCounts, longEntryOrderNames] = bot.getLadderInSteps(side="buy", amount="10000", ladderRungs=ladderInSteps, ladderStart=ladderStartPrice, ladderStop=na, stepSpacingPercent=ladderInStepSpacingPercent) [shortEntryPrices, shortEntryContractCounts, shortEntryOrderNames] = bot.getLadderInSteps(side="sell", amount="10000", ladderRungs=ladderInSteps, ladderStart=ladderStartPrice, ladderStop=na, stepSpacingPercent=ladderInStepSpacingPercent) [longExitPrices, longExitQuantities, longExitOrderNames] = bot.getLadderOutSteps("sell", longProfitTarget, ladderOutSteps, ladderOutStepSpacingPercent) [shortExitPrices, shortExitQuantities, shortExitOrderNames] = bot.getLadderOutSteps("buy", shortProfitTarget, ladderOutSteps, ladderOutStepSpacingPercent) // Long Ladders for i = 0 to ladderInSteps - 1 by 1 ladderPrice = array.get(longEntryPrices,i) ladderQty = array.get(longEntryContractCounts,i) ladderID = array.get(longEntryOrderNames,i) ladderInCriteria = array.get(longLadderInCriterias,i) ladderAlertMessage = bot.getStrategyAlertMessage("MM1", bot.getChartSymbol(), bot.getBaseCurrency(), "buy", ladderPrice, ladderPrice, str.tostring(ladderQty), longProfitTarget, longProfitTarget, longStopLoss, longStopLoss, false) if ladderInCriteria strategy.order(id=ladderID, direction=strategy.long, limit=ladderPrice, qty=ladderQty, alert_message=ladderAlertMessage) if cancelUnfilledLongEntries strategy.cancel(id=ladderID) if currentlyInLongPosition for x = 0 to ladderOutSteps - 1 by 1 ladderOutID = ladderID + " | Exit " + str.tostring(x + 1) ladderOutPrice = array.get(longExitPrices,x) ladderOutQty = ladderQty / ladderOutSteps if x == ladderOutSteps - 1 strategy.exit(id=ladderOutID, from_entry=ladderID, qty_percent=100, limit=ladderOutPrice, stop=longStopLoss) else strategy.exit(id=ladderOutID, from_entry=ladderID, qty=ladderOutQty, limit=ladderOutPrice, stop=longStopLoss) // Short Ladders for i = 0 to ladderInSteps - 1 by 1 ladderPrice = array.get(shortEntryPrices,i) ladderQty = array.get(shortEntryContractCounts,i) ladderID = array.get(shortEntryOrderNames,i) ladderInCriteria = array.get(shortLadderInCriterias,i) ladderAlertMessage = bot.getStrategyAlertMessage("MM1", bot.getChartSymbol(), bot.getBaseCurrency(), "sell", ladderPrice, ladderPrice, str.tostring(ladderQty), longProfitTarget, longProfitTarget, longStopLoss, longStopLoss, false) if ladderInCriteria strategy.order(id=ladderID, direction=strategy.short, limit=ladderPrice, qty=ladderQty, alert_message=ladderAlertMessage) if cancelUnfilledShortEntries strategy.cancel(id=ladderID) if currentlyInShortPosition for x = 0 to ladderOutSteps - 1 by 1 ladderOutID = ladderID + " | Exit " + str.tostring(x + 1) ladderOutPrice = array.get(shortExitPrices,x) ladderOutQty = ladderQty / ladderOutSteps if x == ladderOutSteps - 1 strategy.exit(id=ladderOutID, from_entry=ladderID, qty_percent=100, limit=ladderOutPrice, stop=shortStopLoss) else strategy.exit(id=ladderOutID, from_entry=ladderID, qty=ladderOutQty, limit=ladderOutPrice, stop=shortStopLoss) // Strategy Plots, Lines, and Labels startLine = plot(series=start, title="Ladder Start Line", color=currentlyInLongPosition ? transparent : green, linewidth=1, editable=false) stopLinep = plot(series=stop, title="Stop Loss Line", color=currentlyInLongPosition ? transparent : red, linewidth=1, editable=false) var line startTimeLine = na var line stopTimeLine = na line.delete(startTimeLine) line.delete(stopTimeLine) stopTime = strategy.closedtrades.exit_time(0) stopBarIndex = strategy.closedtrades.exit_bar_index(0) startTimeLine := line.new(x1=startTime, y1=0, x2=startTime, y2=10000000, color=gray, width=1, xloc=xloc.bar_time) // Boilerplate Plots, Lines, and Labels adxPlot = plot(adx, title="ADX", editable=false, color=nevisShallows) macroEmaPlot = plot(enableMacroEmaFilter ? macroEma: na, title="EMA Macro Filter", linewidth=2, color=white, editable=false) float ladderIn1Price = currentlyInLongPosition ? array.get(longEntryPrices,0) : array.get(shortEntryPrices,0) float ladderIn2Price = currentlyInLongPosition ? array.get(longEntryPrices,1) : array.get(shortEntryPrices,1) float ladderIn3Price = currentlyInLongPosition ? array.get(longEntryPrices,2) : array.get(shortEntryPrices,2) float ladderIn4Price = currentlyInLongPosition ? array.get(longEntryPrices,3) : array.get(shortEntryPrices,3) float ladderIn5Price = currentlyInLongPosition ? array.get(longEntryPrices,4) : array.get(shortEntryPrices,4) float ladderIn6Price = currentlyInLongPosition ? array.get(longEntryPrices,5) : array.get(shortEntryPrices,5) ladderInLineColor = currentlyInAPosition ? oceanBlue : transparent ladderIn1PriceLine = plot(series=ladderIn1Price, style=plot.style_stepline, color=ladderInLineColor, linewidth=1, editable=false) ladderIn2PriceLine = plot(series=ladderIn2Price, style=plot.style_stepline, color=ladderInLineColor, linewidth=1, editable=false) ladderIn3PriceLine = plot(series=ladderIn3Price, style=plot.style_stepline, color=ladderInLineColor, linewidth=1, editable=false) ladderIn4PriceLine = plot(series=ladderIn4Price, style=plot.style_stepline, color=ladderInLineColor, linewidth=1, editable=false) ladderIn5PriceLine = plot(series=ladderIn5Price, style=plot.style_stepline, color=ladderInLineColor, linewidth=1, editable=false) ladderIn6PriceLine = plot(series=ladderIn6Price, style=plot.style_stepline, color=ladderInLineColor, linewidth=1, editable=false) float ladderOut1Price = currentlyInLongPosition ? array.get(longExitPrices,0) : array.get(shortExitPrices,0) float ladderOut2Price = currentlyInLongPosition ? array.get(longExitPrices,1) : array.get(shortExitPrices,1) float ladderOut3Price = currentlyInLongPosition ? array.get(longExitPrices,2) : array.get(shortExitPrices,2) float ladderOut4Price = currentlyInLongPosition ? array.get(longExitPrices,3) : array.get(shortExitPrices,3) float ladderOut5Price = currentlyInLongPosition ? array.get(longExitPrices,4) : array.get(shortExitPrices,4) float ladderOut6Price = currentlyInLongPosition ? array.get(longExitPrices,5) : array.get(shortExitPrices,5) ladderOutLineColor = currentlyInAPosition ? green : transparent ladderOut1PriceLine = plot(series=ladderOut1Price, style=plot.style_stepline_diamond, color=ladderOutLineColor, linewidth=1, editable=false) ladderOut2PriceLine = plot(series=ladderOut2Price, style=plot.style_stepline_diamond, color=ladderOutLineColor, linewidth=1, editable=false) ladderOut3PriceLine = plot(series=ladderOut3Price, style=plot.style_stepline_diamond, color=ladderOutLineColor, linewidth=1, editable=false) ladderOut4PriceLine = plot(series=ladderOut4Price, style=plot.style_stepline_diamond, color=ladderOutLineColor, linewidth=1, editable=false) ladderOut5PriceLine = plot(series=ladderOut5Price, style=plot.style_stepline_diamond, color=ladderOutLineColor, linewidth=1, editable=false) ladderOut6PriceLine = plot(series=ladderOut6Price, style=plot.style_stepline_diamond, color=ladderOutLineColor, linewidth=1, editable=false) averageEntryLine = plot(series=avgPrice, title="Average Entry Price", style=plot.style_stepline_diamond, linewidth=1, color=currentlyInAPosition ? skyBlue : transparent, editable=false) longTrailingStopLine = plot(longStopLoss, title="Long Trailing Stop", style=plot.style_stepline_diamond, editable=false, linewidth=1, color=currentlyInLongPosition ? longStopLoss > strategy.position_avg_price ? green : red : transparent) shortTrailingStopLine = plot(shortStopLoss, title="Short Trailing Stop", style=plot.style_stepline_diamond, editable=false, linewidth=1, color=currentlyInShortPosition ? shortStopLoss < strategy.position_avg_price ? green : red : transparent) //shortRunDownLine = plot(shortRunDown, style=plot.style_stepline, editable=false, linewidth=2, color=currentlyInShortPosition ? green : transparent) //longRunUpLine = plot(longRunUp, style=plot.style_stepline, editable=false, linewidth=2, color=currentlyInLongPosition ? green : transparent) // Strategy Dashboard Panel - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - long1LadderFilled = bot.orderCurrentlyExists("Long - 1") long2LadderFilled = bot.orderCurrentlyExists("Long - 2") long3LadderFilled = bot.orderCurrentlyExists("Long - 3") long4LadderFilled = bot.orderCurrentlyExists("Long - 4") long5LadderFilled = bot.orderCurrentlyExists("Long - 5") long6LadderFilled = bot.orderCurrentlyExists("Long - 6") short1LadderFilled = bot.orderCurrentlyExists("Short - 1") short2LadderFilled = bot.orderCurrentlyExists("Short - 2") short3LadderFilled = bot.orderCurrentlyExists("Short - 3") short4LadderFilled = bot.orderCurrentlyExists("Short - 4") short5LadderFilled = bot.orderCurrentlyExists("Short - 5") short6LadderFilled = bot.orderCurrentlyExists("Short - 6") longTP1Hit = bot.orderAlreadyClosedSince("Long - 1 | Exit 1", barsSinceEntry) longTP2Hit = bot.orderAlreadyClosedSince("Long - 1 | Exit 2", barsSinceEntry) longTP3Hit = bot.orderAlreadyClosedSince("Long - 1 | Exit 3", barsSinceEntry) longTP4Hit = bot.orderAlreadyClosedSince("Long - 1 | Exit 4", barsSinceEntry) longTP5Hit = bot.orderAlreadyClosedSince("Long - 1 | Exit 5", barsSinceEntry) longTP6Hit = bot.orderAlreadyClosedSince("Long - 1 | Exit 6", barsSinceEntry) shortTP1Hit = bot.orderAlreadyClosedSince("Short - 1 | Exit 1", barsSinceEntry) shortTP2Hit = bot.orderAlreadyClosedSince("Short - 1 | Exit 2", barsSinceEntry) shortTP3Hit = bot.orderAlreadyClosedSince("Short - 1 | Exit 3", barsSinceEntry) shortTP4Hit = bot.orderAlreadyClosedSince("Short - 1 | Exit 4", barsSinceEntry) shortTP5Hit = bot.orderAlreadyClosedSince("Short - 1 | Exit 5", barsSinceEntry) shortTP6Hit = bot.orderAlreadyClosedSince("Short - 1 | Exit 6", barsSinceEntry) if showStrategyStatusBox and longConditionsMet or shortConditionsMet // Global Dashboard Settings var string checkMark = "β€‚βœ“" var string fontSize = size.normal cellBgColor = lightGray var float quantityOfAllFilledOrders = 0 var table panel = table.new(position=position.bottom_right, columns=3, rows=100, bgcolor=cellBgColor, border_color=lightGray, border_width=1) rowCount = 0 table.cell(panel, 0, rowCount, text=" " + "Ladder In", text_color=black, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 1, rowCount, text="Price", text_color=black, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 2, rowCount, text="Contracts" + " ", text_color=black, text_halign=text.align_right, bgcolor=cellBgColor, text_size=fontSize) rowCount += 1 // Long Ladder 1 if currentlyInLongPosition and ladderInSteps >= 1 int ladderArrayPosition = 0 string entryID = long1LadderFilled ? str.tostring(array.get(longEntryOrderNames,ladderArrayPosition)) + checkMark : str.tostring(array.get(longEntryOrderNames,ladderArrayPosition)) string price = str.format("{0,number,currency}", array.get(longEntryPrices,ladderArrayPosition)) string quantity = str.format("{0,number,#.#####}", array.get(longEntryContractCounts,ladderArrayPosition)) color = long1LadderFilled ? green : black table.cell(panel, 0, rowCount, text=" " + entryID, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 1, rowCount, text=price, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 2, rowCount, text=quantity + " ", text_color=color, text_halign=text.align_right, bgcolor=cellBgColor, text_size=fontSize) quantityOfAllFilledOrders += array.get(longEntryContractCounts,ladderArrayPosition) rowCount += 1 // Long Ladder 2 if currentlyInLongPosition and ladderInSteps >= 2 int ladderArrayPosition = 1 string entryID = long2LadderFilled ? str.tostring(array.get(longEntryOrderNames,ladderArrayPosition)) + checkMark : str.tostring(array.get(longEntryOrderNames,ladderArrayPosition)) string price = str.format("{0,number,currency}", array.get(longEntryPrices,ladderArrayPosition)) string quantity = str.format("{0,number,#.#####}", array.get(longEntryContractCounts,ladderArrayPosition)) color = long2LadderFilled ? green : black table.cell(panel, 0, rowCount, text=" " + entryID, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 1, rowCount, text=price, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 2, rowCount, text=quantity + " ", text_color=color, text_halign=text.align_right, bgcolor=cellBgColor, text_size=fontSize) quantityOfAllFilledOrders += array.get(longEntryContractCounts,ladderArrayPosition) rowCount += 1 // Long Ladder 3 if currentlyInLongPosition and ladderInSteps >= 3 int ladderArrayPosition = 2 string entryID = long3LadderFilled ? str.tostring(array.get(longEntryOrderNames,ladderArrayPosition)) + checkMark : str.tostring(array.get(longEntryOrderNames,ladderArrayPosition)) string price = str.format("{0,number,currency}", array.get(longEntryPrices,ladderArrayPosition)) string quantity = str.format("{0,number,#.#####}", array.get(longEntryContractCounts,ladderArrayPosition)) color = long3LadderFilled ? green : black table.cell(panel, 0, rowCount, text=" " + entryID, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 1, rowCount, text=price, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 2, rowCount, text=quantity + " ", text_color=color, text_halign=text.align_right, bgcolor=cellBgColor, text_size=fontSize) quantityOfAllFilledOrders += array.get(longEntryContractCounts,ladderArrayPosition) rowCount += 1 // Long Ladder 4 if currentlyInLongPosition and ladderInSteps >= 4 int ladderArrayPosition = 3 string entryID = long4LadderFilled ? str.tostring(array.get(longEntryOrderNames,ladderArrayPosition)) + checkMark : str.tostring(array.get(longEntryOrderNames,ladderArrayPosition)) string price = str.format("{0,number,currency}", array.get(longEntryPrices,ladderArrayPosition)) string quantity = str.format("{0,number,#.#####}", array.get(longEntryContractCounts,ladderArrayPosition)) color = long4LadderFilled ? green : black table.cell(panel, 0, rowCount, text=" " + entryID, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 1, rowCount, text=price, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 2, rowCount, text=quantity + " ", text_color=color, text_halign=text.align_right, bgcolor=cellBgColor, text_size=fontSize) quantityOfAllFilledOrders += array.get(longEntryContractCounts,ladderArrayPosition) rowCount += 1 // Long Ladder 5 if currentlyInLongPosition and ladderInSteps >= 5 int ladderArrayPosition = 4 string entryID = long5LadderFilled ? str.tostring(array.get(longEntryOrderNames,ladderArrayPosition)) + checkMark : str.tostring(array.get(longEntryOrderNames,ladderArrayPosition)) string price = str.format("{0,number,currency}", array.get(longEntryPrices,ladderArrayPosition)) string quantity = str.format("{0,number,#.#####}", array.get(longEntryContractCounts,ladderArrayPosition)) color = long5LadderFilled ? green : black table.cell(panel, 0, rowCount, text=" " + entryID, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 1, rowCount, text=price, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 2, rowCount, text=quantity + " ", text_color=color, text_halign=text.align_right, bgcolor=cellBgColor, text_size=fontSize) quantityOfAllFilledOrders += array.get(longEntryContractCounts,ladderArrayPosition) rowCount += 1 // Long Ladder 6 if currentlyInLongPosition and ladderInSteps >= 6 int ladderArrayPosition = 5 string entryID = long6LadderFilled ? str.tostring(array.get(longEntryOrderNames,ladderArrayPosition)) + checkMark : str.tostring(array.get(longEntryOrderNames,ladderArrayPosition)) string price = str.format("{0,number,currency}", array.get(longEntryPrices,ladderArrayPosition)) string quantity = str.format("{0,number,#.#####}", array.get(longEntryContractCounts,ladderArrayPosition)) color = long6LadderFilled ? green : black table.cell(panel, 0, rowCount, text=" " + entryID, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 1, rowCount, text=price, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 2, rowCount, text=quantity + " ", text_color=color, text_halign=text.align_right, bgcolor=cellBgColor, text_size=fontSize) quantityOfAllFilledOrders += array.get(longEntryContractCounts,ladderArrayPosition) rowCount += 1 // Short Ladder 1 if currentlyInShortPosition and ladderInSteps >= 1 int ladderArrayPosition = 0 string entryID = short1LadderFilled ? str.tostring(array.get(shortEntryOrderNames,ladderArrayPosition)) + checkMark : str.tostring(array.get(shortEntryOrderNames,ladderArrayPosition)) string price = str.format("{0,number,currency}", array.get(shortEntryPrices,ladderArrayPosition)) string quantity = str.format("{0,number,#.#####}", array.get(shortEntryContractCounts,ladderArrayPosition)) table.cell(panel, 0, rowCount, text=" " + entryID, text_color=short1LadderFilled ? green : black, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 1, rowCount, text=price, text_color=short1LadderFilled ? green : black, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 2, rowCount, text=quantity + " ", text_color=short1LadderFilled ? green : black, text_halign=text.align_right, bgcolor=cellBgColor, text_size=fontSize) quantityOfAllFilledOrders += array.get(longEntryContractCounts,ladderArrayPosition) rowCount += 1 // Short Ladder 2 if currentlyInShortPosition and ladderInSteps >= 2 int ladderArrayPosition = 1 string entryID = short2LadderFilled ? str.tostring(array.get(shortEntryOrderNames,ladderArrayPosition)) + checkMark : str.tostring(array.get(shortEntryOrderNames,ladderArrayPosition)) string price = str.format("{0,number,currency}", array.get(shortEntryPrices,ladderArrayPosition)) string quantity = str.format("{0,number,#.#####}", array.get(shortEntryContractCounts,ladderArrayPosition)) color = short2LadderFilled ? green : black table.cell(panel, 0, rowCount, text=" " + entryID, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 1, rowCount, text=price, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 2, rowCount, text=quantity + " ", text_color=color, text_halign=text.align_right, bgcolor=cellBgColor, text_size=fontSize) quantityOfAllFilledOrders += array.get(longEntryContractCounts,ladderArrayPosition) rowCount += 1 // Short Ladder 3 if currentlyInShortPosition and ladderInSteps >= 3 int ladderArrayPosition = 2 string entryID = short3LadderFilled ? str.tostring(array.get(shortEntryOrderNames,ladderArrayPosition)) + checkMark : str.tostring(array.get(shortEntryOrderNames,ladderArrayPosition)) string price = str.format("{0,number,currency}", array.get(shortEntryPrices,ladderArrayPosition)) string quantity = str.format("{0,number,#.#####}", array.get(shortEntryContractCounts,ladderArrayPosition)) color = short3LadderFilled ? green : black table.cell(panel, 0, rowCount, text=" " + entryID, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 1, rowCount, text=price, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 2, rowCount, text=quantity + " ", text_color=color, text_halign=text.align_right, bgcolor=cellBgColor, text_size=fontSize) quantityOfAllFilledOrders += array.get(longEntryContractCounts,ladderArrayPosition) rowCount += 1 // Short Ladder 4 if currentlyInShortPosition and ladderInSteps >= 4 int ladderArrayPosition = 3 string entryID = short4LadderFilled ? str.tostring(array.get(shortEntryOrderNames,ladderArrayPosition)) + checkMark : str.tostring(array.get(shortEntryOrderNames,ladderArrayPosition)) string price = str.format("{0,number,currency}", array.get(shortEntryPrices,ladderArrayPosition)) string quantity = str.format("{0,number,#.#####}", array.get(shortEntryContractCounts,ladderArrayPosition)) color = short4LadderFilled ? green : black table.cell(panel, 0, rowCount, text=" " + entryID, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 1, rowCount, text=price, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 2, rowCount, text=quantity + " ", text_color=color, text_halign=text.align_right, bgcolor=cellBgColor, text_size=fontSize) quantityOfAllFilledOrders += array.get(longEntryContractCounts,ladderArrayPosition) rowCount += 1 // Short Ladder 5 if currentlyInShortPosition and ladderInSteps >= 5 int ladderArrayPosition = 4 string entryID = short5LadderFilled ? str.tostring(array.get(shortEntryOrderNames,ladderArrayPosition)) + checkMark : str.tostring(array.get(shortEntryOrderNames,ladderArrayPosition)) string price = str.format("{0,number,currency}", array.get(shortEntryPrices,ladderArrayPosition)) string quantity = str.format("{0,number,#.#####}", array.get(shortEntryContractCounts,ladderArrayPosition)) color = short5LadderFilled ? green : black table.cell(panel, 0, rowCount, text=" " + entryID, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 1, rowCount, text=price, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 2, rowCount, text=quantity + " ", text_color=color, text_halign=text.align_right, bgcolor=cellBgColor, text_size=fontSize) quantityOfAllFilledOrders += array.get(longEntryContractCounts,ladderArrayPosition) rowCount += 1 // Short Ladder 6 if currentlyInShortPosition and ladderInSteps >= 6 int ladderArrayPosition = 5 string entryID = short6LadderFilled ? str.tostring(array.get(shortEntryOrderNames,ladderArrayPosition)) + checkMark : str.tostring(array.get(shortEntryOrderNames,ladderArrayPosition)) string price = str.format("{0,number,currency}", array.get(shortEntryPrices,ladderArrayPosition)) string quantity = str.format("{0,number,#.#####}", array.get(shortEntryContractCounts,ladderArrayPosition)) color = short6LadderFilled ? green : black table.cell(panel, 0, rowCount, text=" " + entryID, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 1, rowCount, text=price, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 2, rowCount, text=quantity + " ", text_color=color, text_halign=text.align_right, bgcolor=cellBgColor, text_size=fontSize) quantityOfAllFilledOrders += array.get(longEntryContractCounts,ladderArrayPosition) rowCount += 1 // Average Entry Price if currentlyInAPosition table.cell(panel, 0, rowCount, text=" " + "", text_color=black, text_halign=text.align_left, bgcolor=cellBgColor, text_size=size.tiny) table.cell(panel, 1, rowCount, text="", text_color=black, text_halign=text.align_left, bgcolor=cellBgColor, text_size=size.tiny) table.cell(panel, 2, rowCount, text=" ", text_color=black, text_halign=text.align_right, bgcolor=cellBgColor, text_size=size.tiny) rowCount += 1 string avgPriceString = str.format("{0,number,currency}", strategy.position_avg_price) table.cell(panel, 0, rowCount, text=" " + "Avg Price", text_color=black, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 1, rowCount, text="", text_color=black, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 2, rowCount, text=avgPriceString + " ", text_color=black, text_halign=text.align_right, bgcolor=cellBgColor, text_size=fontSize) rowCount += 1 // Total Contracts // if currentlyInAPosition // string totalContracts = str.format("{0,number,#.#####}", quantityOfAllFilledOrders) // table.cell(panel, 0, rowCount, text=" " + "Total Contracts", text_color=black, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) // table.cell(panel, 1, rowCount, text="", text_color=black, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) // table.cell(panel, 2, rowCount, text=strategy.open + " ", text_color=black, text_halign=text.align_right, bgcolor=cellBgColor, text_size=fontSize) // rowCount += 1 if currentlyInAPosition table.cell(panel, 0, rowCount, text=" " + "", text_color=black, text_halign=text.align_left, bgcolor=cellBgColor, text_size=size.tiny) table.cell(panel, 1, rowCount, text="", text_color=black, text_halign=text.align_left, bgcolor=cellBgColor, text_size=size.tiny) table.cell(panel, 2, rowCount, text=" ", text_color=black, text_halign=text.align_right, bgcolor=cellBgColor, text_size=size.tiny) rowCount += 1 table.cell(panel, 0, rowCount, text=" " + "Ladder Out", text_color=black, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 1, rowCount, text="Price", text_color=black, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 2, rowCount, text="% of Order" + " ", text_color=black, text_halign=text.align_right, bgcolor=cellBgColor, text_size=fontSize) rowCount += 1 // Long Ladder Out 1 if currentlyInLongPosition and ladderOutSteps >= 1 int ladderOutArrayPosition = 0 string exitID = str.tostring(array.get(longExitOrderNames,ladderOutArrayPosition)) string price = str.format("{0,number,currency}", array.get(longExitPrices,ladderOutArrayPosition)) string quantity = str.format("{0,number,percent}", array.get(longExitQuantities,ladderOutArrayPosition)/100) color = longTP1Hit ? green : black table.cell(panel, 0, rowCount, text=longTP1Hit ? " " + exitID + checkMark : " " + exitID, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 1, rowCount, text=price, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 2, rowCount, text=quantity + " ", text_color=color, text_halign=text.align_right, bgcolor=cellBgColor, text_size=fontSize) rowCount += 1 // Long Ladder Out 2 if currentlyInLongPosition and ladderOutSteps >= 2 int ladderOutArrayPosition = 1 string exitID = str.tostring(array.get(longExitOrderNames,ladderOutArrayPosition)) string price = str.format("{0,number,currency}", array.get(longExitPrices,ladderOutArrayPosition)) string quantity = str.format("{0,number,percent}", array.get(longExitQuantities,ladderOutArrayPosition)/100) color = longTP2Hit ? green : black table.cell(panel, 0, rowCount, text=longTP2Hit ? " " + exitID + checkMark : " " + exitID, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 1, rowCount, text=price, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 2, rowCount, text=quantity + " ", text_color=color, text_halign=text.align_right, bgcolor=cellBgColor, text_size=fontSize) rowCount += 1 // Long Ladder Out 3 if currentlyInLongPosition and ladderOutSteps >= 3 int ladderOutArrayPosition = 2 string exitID = str.tostring(array.get(longExitOrderNames,ladderOutArrayPosition)) string price = str.format("{0,number,currency}", array.get(longExitPrices,ladderOutArrayPosition)) string quantity = str.format("{0,number,percent}", array.get(longExitQuantities,ladderOutArrayPosition)/100) color = longTP3Hit ? green : black table.cell(panel, 0, rowCount, text=longTP3Hit ? " " + exitID + checkMark : " " + exitID, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 1, rowCount, text=price, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 2, rowCount, text=quantity + " ", text_color=color, text_halign=text.align_right, bgcolor=cellBgColor, text_size=fontSize) rowCount += 1 // Long Ladder Out 4 if currentlyInLongPosition and ladderOutSteps >= 4 int ladderOutArrayPosition = 3 string exitID = str.tostring(array.get(longExitOrderNames,ladderOutArrayPosition)) string price = str.format("{0,number,currency}", array.get(longExitPrices,ladderOutArrayPosition)) string quantity = str.format("{0,number,percent}", array.get(longExitQuantities,ladderOutArrayPosition)/100) color = longTP4Hit ? green : black table.cell(panel, 0, rowCount, text=longTP4Hit ? " " + exitID + checkMark : " " + exitID, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 1, rowCount, text=price, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 2, rowCount, text=quantity + " ", text_color=color, text_halign=text.align_right, bgcolor=cellBgColor, text_size=fontSize) rowCount += 1 // Long Ladder Out 5 if currentlyInLongPosition and ladderOutSteps >= 5 int ladderOutArrayPosition = 4 string exitID = str.tostring(array.get(longExitOrderNames,ladderOutArrayPosition)) string price = str.format("{0,number,currency}", array.get(longExitPrices,ladderOutArrayPosition)) string quantity = str.format("{0,number,percent}", array.get(longExitQuantities,ladderOutArrayPosition)/100) color = longTP5Hit ? green : black table.cell(panel, 0, rowCount, text=longTP5Hit ? " " + exitID + checkMark : " " + exitID, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 1, rowCount, text=price, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 2, rowCount, text=quantity + " ", text_color=color, text_halign=text.align_right, bgcolor=cellBgColor, text_size=fontSize) rowCount += 1 // Long Ladder Out 6 if currentlyInLongPosition and ladderOutSteps >= 6 int ladderOutArrayPosition = 5 string exitID = str.tostring(array.get(longExitOrderNames,ladderOutArrayPosition)) string price = str.format("{0,number,currency}", array.get(longExitPrices,ladderOutArrayPosition)) string quantity = str.format("{0,number,percent}", array.get(longExitQuantities,ladderOutArrayPosition)/100) color = longTP6Hit ? green : black table.cell(panel, 0, rowCount, text=longTP6Hit ? " " + exitID + checkMark : " " + exitID, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 1, rowCount, text=price, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 2, rowCount, text=quantity + " ", text_color=color, text_halign=text.align_right, bgcolor=cellBgColor, text_size=fontSize) rowCount += 1 // Short Ladder Out 1 if currentlyInShortPosition and ladderOutSteps >= 1 int ladderOutArrayPosition = 0 string exitID = str.tostring(array.get(shortExitOrderNames,ladderOutArrayPosition)) string price = str.format("{0,number,currency}", array.get(shortExitPrices,ladderOutArrayPosition)) string quantity = str.format("{0,number,percent}", array.get(shortExitQuantities,ladderOutArrayPosition)/100) color = shortTP1Hit ? green : black table.cell(panel, 0, rowCount, text=longTP1Hit ? " " + exitID + checkMark : " " + exitID, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 1, rowCount, text=price, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 2, rowCount, text=quantity + " ", text_color=color, text_halign=text.align_right, bgcolor=cellBgColor, text_size=fontSize) rowCount += 1 // Short Ladder Out 2 if currentlyInShortPosition and ladderOutSteps >= 2 int ladderOutArrayPosition = 1 string exitID = str.tostring(array.get(shortExitOrderNames,ladderOutArrayPosition)) string price = str.format("{0,number,currency}", array.get(shortExitPrices,ladderOutArrayPosition)) string quantity = str.format("{0,number,percent}", array.get(shortExitQuantities,ladderOutArrayPosition)/100) color = shortTP2Hit ? green : black table.cell(panel, 0, rowCount, text=longTP2Hit ? " " + exitID + checkMark : " " + exitID, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 1, rowCount, text=price, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 2, rowCount, text=quantity + " ", text_color=color, text_halign=text.align_right, bgcolor=cellBgColor, text_size=fontSize) rowCount += 1 // Short Ladder Out 3 if currentlyInShortPosition and ladderOutSteps >= 3 int ladderOutArrayPosition = 2 string exitID = str.tostring(array.get(shortExitOrderNames,ladderOutArrayPosition)) string price = str.format("{0,number,currency}", array.get(shortExitPrices,ladderOutArrayPosition)) string quantity = str.format("{0,number,percent}", array.get(shortExitQuantities,ladderOutArrayPosition)/100) color = shortTP3Hit ? green : black table.cell(panel, 0, rowCount, text=longTP3Hit ? " " + exitID + checkMark : " " + exitID, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 1, rowCount, text=price, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 2, rowCount, text=quantity + " ", text_color=color, text_halign=text.align_right, bgcolor=cellBgColor, text_size=fontSize) rowCount += 1 // Short Ladder Out 4 if currentlyInShortPosition and ladderOutSteps >= 4 int ladderOutArrayPosition = 3 string exitID = str.tostring(array.get(shortExitOrderNames,ladderOutArrayPosition)) string price = str.format("{0,number,currency}", array.get(shortExitPrices,ladderOutArrayPosition)) string quantity = str.format("{0,number,percent}", array.get(shortExitQuantities,ladderOutArrayPosition)/100) color = shortTP4Hit ? green : black table.cell(panel, 0, rowCount, text=longTP4Hit ? " " + exitID + checkMark : " " + exitID, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 1, rowCount, text=price, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 2, rowCount, text=quantity + " ", text_color=color, text_halign=text.align_right, bgcolor=cellBgColor, text_size=fontSize) rowCount += 1 // Short Ladder Out 5 if currentlyInShortPosition and ladderOutSteps >= 5 int ladderOutArrayPosition = 4 string exitID = str.tostring(array.get(shortExitOrderNames,ladderOutArrayPosition)) string price = str.format("{0,number,currency}", array.get(shortExitPrices,ladderOutArrayPosition)) string quantity = str.format("{0,number,percent}", array.get(shortExitQuantities,ladderOutArrayPosition)/100) color = shortTP5Hit ? green : black table.cell(panel, 0, rowCount, text=longTP5Hit ? " " + exitID + checkMark : " " + exitID, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 1, rowCount, text=price, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 2, rowCount, text=quantity + " ", text_color=color, text_halign=text.align_right, bgcolor=cellBgColor, text_size=fontSize) rowCount += 1 // Short Ladder Out 6 if currentlyInShortPosition and ladderOutSteps >= 6 int ladderOutArrayPosition = 5 string exitID = str.tostring(array.get(shortExitOrderNames,ladderOutArrayPosition)) string price = str.format("{0,number,currency}", array.get(shortExitPrices,ladderOutArrayPosition)) string quantity = str.format("{0,number,percent}", array.get(shortExitQuantities,ladderOutArrayPosition)/100) color = shortTP6Hit ? green : black table.cell(panel, 0, rowCount, text=longTP6Hit ? " " + exitID + checkMark : " " + exitID, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 1, rowCount, text=price, text_color=color, text_halign=text.align_left, bgcolor=cellBgColor, text_size=fontSize) table.cell(panel, 2, rowCount, text=quantity + " ", text_color=color, text_halign=text.align_right, bgcolor=cellBgColor, text_size=fontSize) rowCount += 1