name
stringlengths
1
64
url
stringlengths
44
135
author
stringlengths
3
30
author_url
stringlengths
34
61
likes_count
int64
0
33.2k
kind
stringclasses
3 values
pine_version
int64
1
5
license
stringclasses
3 values
source
stringlengths
177
279k
MACD 5 iN 1 [Pro-Tool]
https://www.tradingview.com/script/TtLghbTF-MACD-5-iN-1-Pro-Tool/
HamidBox
https://www.tradingview.com/u/HamidBox/
1,406
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/ // © HamidBox //@version=4 strategy("MACD [5-in-1] V2", default_qty_type=strategy.cash, default_qty_value=100, initial_capital=100, currency='USD', commission_value=0.1) matype_zone(src, len, type) => type == "EMA" ? ema(src, len) : type == "SMA" ? sma(src, len) : type == "RMA" ? rma(src, len) : type == "WMA" ? wma(src, len) : type == "VWMA" ? vwma(src, len) : na matype_signal(src, len, type) => type == "EMA" ? ema(src, len) : type == "SMA" ? sma(src, len) : type == "RMA" ? rma(src, len) : type == "WMA" ? wma(src, len) : type == "VWMA" ? vwma(src, len) : na // MACD INPUTS //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// macd_FastLength = input(title="MACD Fast", defval=12, minval=1, type=input.integer, inline="fastslow") /// macd_SlowLength = input(title="MACD Slow ", defval=26, minval=1, type=input.integer, inline="fastslow") /// macd_signalLen = input(title="Signal Line", defval=9, minval=1, type=input.integer, inline="signalsrc") /// macd_Source = input(title="Source      ", defval=close, type=input.source, inline="signalsrc") /// MACD_Line = input(title="Oscilattor ", defval="EMA", type=input.string, options=["EMA" , "SMA"], inline="matype") /// SignalLine = input(title="Signal       ", defval="EMA", type=input.string, options=["EMA" , "SMA"], inline="matype") /// /// // MACD SETUP ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// macd_Fast = MACD_Line == "SMA" ? sma(macd_Source , macd_FastLength) : ema(macd_Source , macd_FastLength) /// macd_Slow = MACD_Line == "SMA" ? sma(macd_Source , macd_SlowLength) : ema(macd_Source , macd_SlowLength) /// MACD = macd_Fast - macd_Slow /// Signal = SignalLine == "SMA" ? sma(MACD, macd_signalLen) : ema(MACD, macd_signalLen) /// histogram = MACD - Signal /// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // MACD CONDITIONS SECTION ///////////////////////////////////////////////////// macd_grtr_signal = MACD > Signal // macd_less_signal = MACD < Signal // macd_crsovr_signal = crossover(MACD , Signal) ? MACD : na // FOR MACD CROSS DOT PLOTING // macd_crsndr_signal = crossunder(MACD , Signal) ? MACD : na // FOR MACD CROSS DOT PLOTING // macd_crsovr = crossover(MACD , Signal) // macd_crsndr = crossunder(MACD , Signal) // //////////////////////////////////////////////////////////////////////////////// // Choose your Desire Signal /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// MACD_crs_signal = input(false, "Stgy №1:👉 MACD CrossOver", group="CHOOSE YOUR DESIRE SIGNAL", tooltip="🚦🚦🚦 Condition 🚦🚦🚦\nBUY: MACD CrossOver Signal Line\nSELL: MACD CrossUnder Signal Line\nDefault Signal") ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// MACD_OB = input(false, "Stgy №2:👉 MACD + OverBought ", inline="obs", group="CHOOSE YOUR DESIRE SIGNAL", tooltip="MACD also work as OverBought & OverSold system, same like RSI or other indicators who have OB/OS system, so i added OB-Level in MACD,\nso simple rule is: if MACD Lines is Above OB-Level, we will not take any trade, we only follow MACD signals when MACD-Lines will Below OB-Level") MACD_OB_LVL = input(title="", defval=0.0, type=input.float, inline="obs", group="CHOOSE YOUR DESIRE SIGNAL", tooltip="MACD also work as OverBought & OverSold system, same like RSI or other indicators who have OB/OS system, so i added OB-Level in MACD,\nso simple rule is: if MACD Lines is Above OB-Level, we will not take any trade, we only follow MACD signals when MACD-Lines will Below OB-Level") hline(MACD_OB_LVL, color=color.red, title="MACD OB", linestyle=hline.style_dashed) ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// MACD_close = input(false, "Stgy №3:👉 MACD + Close         ", inline="MAsignal", group="CHOOSE YOUR DESIRE SIGNAL", tooltip="🚦🚦🚦 Condition 🚦🚦🚦\n\nBUY RULES\n1st: MACD CrossOver Signal Line\n2nd: Close (Greater) Than Moving Average\n\nSELL RULES\n1st: MACD CrossUnder Signal Line\n2nd: Close (Less) Than Moving Average\n\nExplanation: When (MACD Cross Signal Line) and also Market current Candle Close or previous 1st-4th any Candle will have close greater than Moving Average (You Choose: EMA or SMA etc...)\n🚦NOTE: in this Condition only Singal Moving Average work => (Slow MA),") MA_signal_len = input(title="", defval=21, type=input.integer, inline="MAsignal", group="CHOOSE YOUR DESIRE SIGNAL") // // MA_signal_type = input(title="", defval="EMA", options=["SMA" , "EMA" , "RMA", "WMA" , "VWMA" , "DEMA", "TEMA"], inline="MAsignal", group="CHOOSE YOUR DESIRE SIGNAL", tooltip="🚦🚦🚦 Condition 🚦🚦🚦\n\nBUY RULES\n1st: MACD CrossOver Signal Line\n2nd: Close (Greater) Than Moving Average\n\nSELL RULES\n1st: MACD CrossUnder Signal Line\n2nd: Close (Less) Than Moving Average\n\nExplanation: When (MACD Cross Signal Line) and also Market current Candle Close will have close greater than Moving Average (You Choose: EMA or SMA etc...)") // // dema = if MA_signal_type == "DEMA" ema = ema(close , MA_signal_len) 2 * ema - ema(ema , MA_signal_len) tema = if MA_signal_type == "TEMA" ema = ema(close , MA_signal_len) 3 * (ema - ema(ema, MA_signal_len)) + ema(ema(ema, MA_signal_len), MA_signal_len) MA_signal = matype_zone(close, MA_signal_len, MA_signal_type) ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// MACD_ZONE = input(false, "Stgy №4:👉 MACD + MA-ZONE    ", inline="MAZONE", group="CHOOSE YOUR DESIRE SIGNAL", tooltip="🚦🚦🚦 Condition 🚦🚦🚦\n\nBUY RULES:\n1st: MACD CrossOver Signal Line\n2nd: Close (Greater) than (MA-ZONE)\n\nSELL RULES:\n1st: MACD CrossUnder Signal Line\n2nd: Close (Less) than (MA-ZONE)") MA_zone_len = input(title="", defval=21, type=input.integer, inline="MAZONE", group="CHOOSE YOUR DESIRE SIGNAL") MA_zone_type = input(title="", defval="EMA", options=["SMA" , "EMA" , "RMA", "WMA" , "VWMA" , "DEMA", "TEMA"], inline="MAZONE", group="CHOOSE YOUR DESIRE SIGNAL", tooltip="🚦🚦🚦 Condition 🚦🚦🚦\n\nBUY RULES:\n1st: MACD CrossOver Signal Line\n2nd: Close (Greater) than (MA-ZONE)\n\nSELL RULES:\n1st: MACD CrossUnder Signal Line\n2nd: Close (Less) than (MA-ZONE)") dema2 = if MA_zone_type == "DEMA" ema = ema(close , MA_zone_len) 2 * ema - ema(ema , MA_zone_len) tema2 = if MA_zone_type == "TEMA" ema = ema(close , MA_zone_len) 3 * (ema - ema(ema, MA_zone_len)) + ema(ema(ema, MA_zone_len), MA_zone_len) MA_zone_srcHi = matype_signal(high, MA_zone_len, MA_zone_type) // // MA_zone_srcLO = matype_signal(low, MA_zone_len, MA_zone_type) ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// MACD_wid_rsiOB = input(false, "Stgy №5:👉 MACD + RSI-OB", group="CHOOSE YOUR DESIRE SIGNAL") rsilen = input(title="Length", defval=14, type=input.integer, inline="rsi", group="CHOOSE YOUR DESIRE SIGNAL") rsi_ent_value = input(title="Entry", defval=50, type=input.integer, minval=1, inline="rsi", group="CHOOSE YOUR DESIRE SIGNAL", tooltip="🚦🚦🚦 Condition 🚦🚦🚦\n\nBUY Rule\nMACD Crossover Signal\nRSI Greater then Entry Level (You Choose)\n\n🚦🚦🚦 Explanation 🚦🚦🚦\nWe have RSI with 2 Levels,\n1st: Entry Level\n2nd: No-Entry Level\n\nEntry level:\nfor never want to BUY trade when RSI is Below our specific Level, like you want open Trade when RSI above 50 level or 30 level etc... \n\nNo-Entry Level:\nthis is same as (Entry Level) Condition, as we know RSI-70 level use for OverBought, and its mean market will go down after RSI-OB level, and thats why we can set overbought level for NO-ENTRY when Market is on OverBought area.") rsi_ob_value = input(title="No-Entry", defval=70, minval=1, type=input.integer, inline="rsi", group="CHOOSE YOUR DESIRE SIGNAL") RSI = rsi(close , rsilen) /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// startTime = input(title="Start Time                           ", type = input.time, defval = timestamp("01 Jan 2021 00:00 +0000"), inline="Backtesting Time Period") endTime = input(title="End Time                          ", type = input.time, defval = timestamp("01 Jan 2022 00:00 +0000")) inDateRange = (time >= startTime) and (time < endTime) bot_id = input(title="BOT ID       ", defval='', inline="bot", group="BOT SECTION") email_token = input(title="  Token", defval='', inline="bot", group="BOT SECTION") enter_msg = '{ "message_type": "bot", "bot_id":'+ bot_id + ', "email_token": "'+ email_token + '", "delay_seconds": 0 }' exit_msg = '{ "message_type": "bot", "bot_id":'+ bot_id + ', "email_token": "'+ email_token + '", "delay_seconds": 0 , "action": "close_at_market_price_all"}' // COPY PASTE THIS MSG TO TRADINGVIEW // {{strategy.order.alert_message}} // Stgy №1:👉 MACD Cross Signal CONDITION ////////////////////////////////////// // ENTRY EXIT SECTION ////////////////////////////////////////////////////////// // (( MACD + CLOSE )) //// if macd_crsovr and MACD_crs_signal and inDateRange //// strategy.entry("BUY1", strategy.long, comment="S#1", alert_message=enter_msg) //// if macd_crsndr and MACD_crs_signal and inDateRange //// strategy.close("BUY1", comment="x", alert_message=exit_msg) //// //////////////////////////////////////////////////////////////////////////////// // // Stgy №1 Ploting // plotshape(MACD_crs_signal ? macd_crsovr : na, title="Stgy Sign", color=color.blue, style=shape.labelup, text="MACD", textcolor=color.white, location=location.bottom) // plotshape(MACD_crs_signal ? macd_crsndr : na, title="Stgy Sign", color=color.maroon, style=shape.labeldown, text="MACD-x", textcolor=color.white, location=location.top) // //////////////////////////////////////////////////////////////////////////////// // Stgy №2:👉 MACD + OverBought CONDITION ////////////////////////////////////// only_Trade_when = MACD < MACD_OB_LVL and Signal < MACD_OB_LVL //// macd_ob_buy = macd_crsovr and only_Trade_when //// macd_ob_sell = macd_crsndr //// //////////////////////////////////////////////////////////////////////////////// // ENTRY EXIT SECTION ////////////////////////////////////////////////////////// // (( MACD + ZONE )) //// if macd_ob_buy and MACD_OB and inDateRange //// strategy.entry("BUY2", strategy.long, comment="S#2", alert_message=enter_msg) //// if macd_ob_sell and MACD_OB and inDateRange //// strategy.close("BUY2", comment="x", alert_message=exit_msg) //// //////////////////////////////////////////////////////////////////////////////// // plotshape(MACD_OB ? macd_ob_buy : na, title="Stgy Sign", color=color.blue, style=shape.labelup, text="M+OB", textcolor=color.white, location=location.bottom) // plotshape(MACD_OB ? macd_ob_sell : na, title="Stgy Sign", color=color.maroon, style=shape.labeldown, text="M+OB-x", textcolor=color.white, location=location.top) // //////////////////////////////////////////////////////////////////////////////// // Stgy №3:👉 MACD + CLOSE CONDITION /////////////////////////////////////////// macd_close_buy = macd_crsovr and ( ( close > MA_signal or (close[1] > MA_signal[1]) or (close[2] > MA_signal[2]) or (close[3] > MA_signal[3]) ) or ( close > dema or (close[1] > dema[1]) or (close[2] > dema[2]) or (close[3] > dema[3]) ) or ( close > tema or (close[1] > tema[1]) or (close[2] > tema[2]) or (close[3] > tema[3]) ) ) macd_close_sell = macd_crsndr and ( ( close > MA_signal or (close[1] < MA_signal[1]) or (close[2] < MA_signal[2]) or (close[3] < MA_signal[3]) ) or ( close < dema or (close[1] < dema[1]) or (close[2] < dema[2]) or (close[3] < dema[3]) ) or ( close < tema or (close[1] < tema[1]) or (close[2] < tema[2]) or (close[3] < tema[3]) ) ) //// //////////////////////////////////////////////////////////////////////////////// // ENTRY EXIT SECTION ////////////////////////////////////////////////////////// // (( MACD + CLOSE )) //// if macd_close_buy and MACD_close and inDateRange //// strategy.entry("BUY3", strategy.long, comment="S#3", alert_message=enter_msg) //// if macd_close_sell and MACD_close and inDateRange //// strategy.close("BUY3", comment="x", alert_message=exit_msg) //// //////////////////////////////////////////////////////////////////////////////// // // Stgy №3 Ploting // plotshape(MACD_close ? macd_close_buy : na, title="Stgy Sign", color=color.blue, style=shape.labelup, text="MACD", textcolor=color.white, location=location.bottom) // plotshape(MACD_close ? macd_close_sell : na, title="Stgy Sign", color=color.maroon, style=shape.labeldown, text="MACD-x", textcolor=color.white, location=location.top) // //////////////////////////////////////////////////////////////////////////////// // Stgy №3:👉 MACD + MA-ZONE MACD + ZONE CONDITION ///////////////////////////// macd_zone_buy = macd_crsovr and ( ( close > MA_zone_srcHi or (close[1] > MA_zone_srcHi[1]) or (close[2] > MA_zone_srcHi[2]) or (close[3] > MA_zone_srcHi[3]) ) or ( close > dema2 or (close[1] > dema2[1]) or (close[2] > dema2[2]) or (close[3] > dema2[3]) ) or ( close > tema2 or (close[1] > tema2[1]) or (close[2] > tema2[2]) or (close[3] > tema2[3]) ) ) //// macd_zone_sell = macd_crsndr and ( ( close < MA_zone_srcHi or (close[1] < MA_zone_srcHi[1]) or (close[2] < MA_zone_srcHi[2]) or (close[3] < MA_zone_srcHi[3]) ) or ( close < dema2 or (close[1] < dema2[1]) or (close[2] < dema2[2]) or (close[3] < dema2[3]) ) or ( close < tema2 or (close[1] < tema2[1]) or (close[2] < tema2[2]) or (close[3] < tema2[3]) ) ) //// //////////////////////////////////////////////////////////////////////////////// // ENTRY EXIT SECTION ////////////////////////////////////////////////////////// // (( MACD + ZONE )) //// if macd_zone_buy and MACD_ZONE and inDateRange //// strategy.entry("BUY4", strategy.long, comment="S#4", alert_message=enter_msg) //// if macd_zone_sell and MACD_ZONE and inDateRange //// strategy.close("BUY4", comment="x", alert_message=exit_msg) //// //////////////////////////////////////////////////////////////////////////////// // Stgy №5:👉 MACD + RSI-OB CONDITION ////////////////////////////////////////// MACD_rsi_EnBuy = RSI > rsi_ent_value and RSI < rsi_ob_value //// MACD_rsi_EnSell = RSI < rsi_ent_value //// MACD_rsi_Ex = crossunder(RSI , rsi_ob_value) or crossunder(RSI[1] , rsi_ob_value[1]) or crossunder(RSI[2] , rsi_ob_value[2]) or crossunder(RSI[3] , rsi_ob_value[3]) or crossunder(RSI[4] , rsi_ob_value[4]) or crossunder(RSI[5] , rsi_ob_value[5]) or crossunder(RSI[6] , rsi_ob_value[6]) //// //// //////////////////////////////////////////////////////////////////////////////// // ENTRY EXIT SECTION ////////////////////////////////////////////////////////// // ((MACD + RSI-OB )) //// if macd_crsovr and MACD_rsi_EnBuy and MACD_wid_rsiOB and inDateRange //// strategy.entry("BUY5", strategy.long, comment="S#5", alert_message=enter_msg) //// if macd_crsndr and MACD_wid_rsiOB and inDateRange //// strategy.close("BUY5", comment="x", alert_message=exit_msg) //// //////////////////////////////////////////////////////////////////////////////// if (not inDateRange) /// strategy.close_all() /// ////////////////////////////////// // MACD COLORS SECTION ///////////////////////////////////////////////////////// // ( Colors of [MACD and Signal-Line] ) MACD_width = input(title="MACD Line               ", defval=2, minval=1, type=input.integer, group="🚦🚦macd Width & Colors setting🚦🚦", inline="macdColor") MACD_color_High = input(#11ff00, title="", type=input.color, group="🚦🚦macd Width & Colors setting🚦🚦", inline="macdColor") MACD_color_Low = input(#e91e63, title="", type=input.color, group="🚦🚦macd Width & Colors setting🚦🚦", inline="macdColor") signal_width = input(title="Signal Line               ", defval=2, minval=1, type=input.integer, group="🚦🚦macd Width & Colors setting🚦🚦", inline="signal") signalLine_col_hi = input(#ffeb3b, title="", type=input.color, inline="signal", group="🚦🚦macd Width & Colors setting🚦🚦") signalLine_col_lo = input(#ffeb3b, title="", type=input.color, inline="signal", group="🚦🚦macd Width & Colors setting🚦🚦") // ((Histogram Color)) ///////////////////////////////////////////////////////// macd_hist_on = input(true, "Histogram        ", inline="hist", group="🚦🚦macd Width & Colors setting🚦🚦") BuyStrongHist = input(#26A69A, title="", type=input.color, inline="hist", group="🚦🚦macd Width & Colors setting🚦🚦") BuyWeakHist = input(#B2DFDB, title="", type=input.color, inline="hist", group="🚦🚦macd Width & Colors setting🚦🚦") SellWeakHist = input(#FFCDD2, title="✨", type=input.color, inline="hist", group="🚦🚦macd Width & Colors setting🚦🚦") SellStrongHist = input(#FF5252, title="", type=input.color, inline="hist", group="🚦🚦macd Width & Colors setting🚦🚦") // ((FOR HISTOGRAM COLOR CONDITION)) hist_col = (histogram >= 0 ? (histogram[1] < histogram ? BuyStrongHist : BuyWeakHist) : histogram[1] < histogram ? SellWeakHist : SellStrongHist) // (( CROSSOVER DOT) /////////////////////////////////////////////////////////// macd_crsovr_dot_on = input(true, "Cross               ", inline="dot", group="🚦🚦macd Width & Colors setting🚦🚦") macd_cross_width = input(defval=5, title="", inline="dot", group="🚦🚦macd Width & Colors setting🚦🚦") dot_crsovr_col = input(#ffffff, title="", type=input.color, inline="dot", group="🚦🚦macd Width & Colors setting🚦🚦") dot_crsndr_col = input(color.new(#e91e63, 0), title="", type=input.color, inline="dot", group="🚦🚦macd Width & Colors setting🚦🚦") // (( MACD ZONE COLOR )) zone_on = input(true, "Zone Color        ", inline="zone", group="🚦🚦macd Width & Colors setting🚦🚦") zone_crsovr_col = input(color.new(color.lime, 70), title="", type=input.color, inline="zone", group="🚦🚦macd Width & Colors setting🚦🚦") zone_crsndr_col = input(color.new(#e91e63, 70), title="", type=input.color, inline="zone", group="🚦🚦macd Width & Colors setting🚦🚦") ///////////////////////////////////////// ((FOR MACD LINE COLOR CONDITION)) MACD_line_col = if macd_grtr_signal // MACD_color_High // else // if macd_less_signal // MACD_color_Low // ///////////////////////////////////////// ((FOR SIGNAL LINE COLOR CONDITION)) signal_line_col = if macd_grtr_signal // signalLine_col_hi // else // if macd_less_signal // signalLine_col_lo // ///////////////////////////////////////// ((FOR MACD CROSS DOTs COLOR CONDITION)) MACD_Dot_col = if macd_crsovr_signal // dot_crsovr_col // else // if macd_crsndr_signal // dot_crsndr_col // ///////////////////////////////////////////////////////////////////////////////////////////////// zone_crsovr_plot = if macd_grtr_signal and zone_on // ((For Zone Color Comdition + On/Off)) /// zone_crsovr_col /////////////////////////////////////////// else // if macd_less_signal and zone_on // zone_crsndr_col // ////////////////////////////////////////////////////// // MACD PLOTING ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// histplot = plot(macd_hist_on ? histogram : na, title="Histogram", color=hist_col, style=plot.style_columns) macdplot = plot(MACD, title="MACD", color=MACD_line_col, linewidth=MACD_width) signalplot = plot(Signal, title="Signal", color=signal_line_col, linewidth=signal_width) fill(macdplot , signalplot, color=zone_crsovr_plot) plot(macd_crsovr_dot_on ? macd_crsovr_signal : na, title="c-over", style=plot.style_circles, color=MACD_Dot_col, linewidth=macd_cross_width) plot(macd_crsovr_dot_on ? macd_crsndr_signal : na, title="c-under", style=plot.style_circles, color=MACD_Dot_col, linewidth=macd_cross_width) /////////////////////////////////////////////////////////////////////////////// donttouchzero = input(title="Want DVG when line below 0 ?        ", defval=true, inline="line", group=" ▁▂▃▄▅▆▇▉ MACD DIVERGENCE ▉▇▆▅▄▃▂▁") lbR = input(title="Pivot Lookback Right", defval=5, group=" ▁▂▃▄▅▆▇▉ MACD DIVERGENCE ▉▇▆▅▄▃▂▁") lbL = input(title="Pivot Lookback Left", defval=5, group=" ▁▂▃▄▅▆▇▉ MACD DIVERGENCE ▉▇▆▅▄▃▂▁") rangeUpper = input(title="Max of Lookback Range", defval=60, group=" ▁▂▃▄▅▆▇▉ MACD DIVERGENCE ▉▇▆▅▄▃▂▁") rangeLower = input(title="Min of Lookback Range", defval=5, group=" ▁▂▃▄▅▆▇▉ MACD DIVERGENCE ▉▇▆▅▄▃▂▁") plotBull = input(title="ON/OFF Bullish DVG", defval=true, group=" ▁▂▃▄▅▆▇▉ MACD DIVERGENCE ▉▇▆▅▄▃▂▁") plotHiddenBull = false plotBear = input(title="ON/OFF Bearish DVG", defval=true, group=" ▁▂▃▄▅▆▇▉ MACD DIVERGENCE ▉▇▆▅▄▃▂▁") plotHiddenBear = false bearColor = color.red bullColor = color.green hiddenBullColor = color.new(color.green, 80) hiddenBearColor = color.new(color.red, 80) textColor = color.white noneColor = color.new(color.white, 100) osc = MACD plFound = na(pivotlow(osc, lbL, lbR)) ? false : true phFound = na(pivothigh(osc, lbL, lbR)) ? false : true _inRange(cond) => bars = barssince(cond == true) rangeLower <= bars and bars <= rangeUpper //------------------------------------------------------------------------------ // Regular Bullish // Osc: Higher Low oscHL = osc[lbR] > valuewhen(plFound, osc[lbR], 1) and _inRange(plFound[1]) and osc[lbR] < 0 // Price: Lower Low priceLL = low[lbR] < valuewhen(plFound, low[lbR], 1) priceHHZero = highest(osc, lbL+lbR+5) LineDisplay = input(false, "Line Display", inline="line", group=" ▁▂▃▄▅▆▇▉ MACD DIVERGENCE ▉▇▆▅▄▃▂▁") plot(LineDisplay ? priceHHZero : na, title="priceHHZero", color=color.lime) blowzero = donttouchzero ? priceHHZero < 0 : true bullCond = plotBull and priceLL and oscHL and plFound and blowzero plot( plFound ? osc[lbR] : na, offset=-lbR, title="Regular Bullish", linewidth=2, color=(bullCond ? bullColor : noneColor), transp=0 ) plotshape( bullCond ? osc[lbR] : na, offset=-lbR, title="Regular Bullish Label", text=" Bull ", style=shape.labelup, location=location.absolute, color=bullColor, textcolor=textColor, transp=0 ) //------------------------------------------------------------------------------ // Hidden Bullish // Osc: Lower Low oscLL = osc[lbR] < valuewhen(plFound, osc[lbR], 1) and _inRange(plFound[1]) // Price: Higher Low priceHL = low[lbR] > valuewhen(plFound, low[lbR], 1) hiddenBullCond = plotHiddenBull and priceHL and oscLL and plFound plot( plFound ? osc[lbR] : na, offset=-lbR, title="Hidden Bullish", linewidth=2, color=(hiddenBullCond ? hiddenBullColor : noneColor), transp=0 ) plotshape( hiddenBullCond ? osc[lbR] : na, offset=-lbR, title="Hidden Bullish Label", text=" H Bull ", style=shape.labelup, location=location.absolute, color=bullColor, textcolor=textColor, transp=0 ) //------------------------------------------------------------------------------ // Regular Bearish // Osc: Lower High oscLH = osc[lbR] < valuewhen(phFound, osc[lbR], 1) and _inRange(phFound[1]) and osc[lbR] > 0 priceLLZero = lowest(osc, lbL+lbR+5) //plot(priceLLZero,title="priceLLZero", color=color.red) bearzero = donttouchzero ? priceLLZero > 0 : true // Price: Higher High priceHH = high[lbR] > valuewhen(phFound, high[lbR], 1) bearCond = plotBear and priceHH and oscLH and phFound and bearzero plot( phFound ? osc[lbR] : na, offset=-lbR, title="Regular Bearish", linewidth=2, color=(bearCond ? bearColor : noneColor), transp=0 ) plotshape( bearCond ? osc[lbR] : na, offset=-lbR, title="Regular Bearish Label", text=" Bear ", style=shape.labeldown, location=location.absolute, color=bearColor, textcolor=textColor, transp=0 ) //------------------------------------------------------------------------------ // Hidden Bearish // Osc: Higher High oscHH = osc[lbR] > valuewhen(phFound, osc[lbR], 1) and _inRange(phFound[1]) // Price: Lower High priceLH = high[lbR] < valuewhen(phFound, high[lbR], 1) hiddenBearCond = plotHiddenBear and priceLH and oscHH and phFound plot( phFound ? osc[lbR] : na, offset=-lbR, title="Hidden Bearish", linewidth=2, color=(hiddenBearCond ? hiddenBearColor : noneColor), transp=0 ) plotshape( hiddenBearCond ? osc[lbR] : na, offset=-lbR, title="Hidden Bearish Label", text=" H Bear ", style=shape.labeldown, location=location.absolute, color=bearColor, textcolor=textColor, transp=0 )
Dual MACD Strategy
https://www.tradingview.com/script/YXLCFbET-Dual-MACD-Strategy/
Trading_Solutions_
https://www.tradingview.com/u/Trading_Solutions_/
138
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/ // © maxits // Long Position: Weekly Macd line crosses above Signal line // [Trading Window Macd Line > Signal Line] (Weekly) // Close Position: Daily Macd Line crosses above Daily Signal line. // Re Entry Condition: Macd line crosses above Signal line only if [Trading Window MacdLine > Sgnal Line] (Weekly) //@version=4 strategy("Dual MACD Strategy", shorttitle="Dual Macd Tester", overlay=false, initial_capital=1000, default_qty_value=20, default_qty_type=strategy.percent_of_equity, commission_value=0.1, pyramiding=0) // Define user inputs i_time = input(defval = timestamp("01 May 2018 13:30 +0000"), title = "Start Time", type = input.time) // Starting time for Backtesting f_time = input(defval = timestamp("9 Sep 2021 13:30 +0000"), title = "Finish Time", type = input.time) // Finishing time for Backtesting sep1 = input(false, title="------ Profit & Loss ------") enable_TP = input(true, title="Enable Just a Profit Level?") enable_SL = input(false, title="Enable Just a S.Loss Level?") enable_TS = input(true, title=" Enable Only Trailing Stop") long_TP_Input = input(30.0, title='Take Profit %', type=input.float, minval=0)/100 long_SL_Input = input(1.0, title='Stop Loss %', type=input.float, minval=0)/100 long_TS_Input = input(5.0, title='Trailing Stop %', type=input.float, minval=0)/100 cl_low_Input = input(low, title="Trailing Stop Source") long_TP = strategy.position_avg_price * (1 + long_TP_Input) long_SL = strategy.position_avg_price * (1 - long_SL_Input) long_TS = cl_low_Input * (1 - long_TS_Input) sep2 = input(false, title="------ Macd Properties ------") d_res = input(title="Short Term TimeFrame", type=input.resolution, defval="D") // Daily Time Frame w_res = input(title="Long Term TimeFrame", type=input.resolution, defval="W") // Weekly Time Frame src = input(close, title="Source") // Indicator Price Source fast_len = input(title="Fast Length", type=input.integer, defval=12) // Fast MA Length slow_len = input(title="Slow Length", type=input.integer, defval=26) // Slow MA Length sign_len = input(title="Sign Length", type=input.integer, defval=9) // Sign MA Length d_w = input(title="Daily or Weekly?", type=input.bool, defval=true) // Plot Daily or Weekly MACD // Color Plot for Macd col_grow_above = #26A69A col_grow_below = #FFCDD2 col_fall_above = #B2DFDB col_fall_below = #EF5350 // BG Color bg_color = color.rgb(127, 232, 34, 75) // Daily Macd [d_macdLine, d_singleLine, d_histLine] = security(syminfo.tickerid, d_res, macd(src, fast_len, slow_len, sign_len)) // Funcion Security para poder usar correcta resolución plot(d_w ? d_macdLine : na, color=color.blue) plot(d_w ? d_singleLine : na, color=color.orange) plot(d_w ? d_histLine : na, style=plot.style_columns, color=(d_histLine>=0 ? (d_histLine[1] < d_histLine ? col_grow_above : col_fall_above) : (d_histLine[1] < d_histLine ? col_grow_below : col_fall_below))) // Weekly Macd [w_macdLine, w_singleLine, w_histLine] = security(syminfo.tickerid, w_res, macd(src, fast_len, slow_len, sign_len)) // Funcion Security para poder usar correcta resolución plot(d_w ? na : w_macdLine, color=color.blue) plot(d_w ? na : w_singleLine, color=color.orange) plot(d_w ? na : w_histLine, style=plot.style_columns, color=(w_histLine>=0 ? (w_histLine[1] < w_histLine ? col_grow_above : col_fall_above) : (w_histLine[1] < w_histLine ? col_grow_below : col_fall_below))) ///////////////////////////////// Entry Conditions inTrade = strategy.position_size != 0 // Posición abierta notInTrade = strategy.position_size == 0 // Posición Cerrada start_time = time >= i_time and time <= f_time // Inicio y Fin de BackTest trading_window = w_macdLine > w_singleLine // Weekly Macd Signal enables a trading window bgcolor(trading_window ? bg_color : na) buy_cond = crossover (w_macdLine, w_singleLine) sell_cond = crossunder(d_macdLine, d_singleLine) re_entry_cond = crossover (d_macdLine, d_singleLine) and trading_window // Entry Exit Conditions trailing_stop = 0.0 // Code for calculating Long Positions Trailing Stop Loss trailing_stop := if (strategy.position_size != 0) stopValue = long_TS max(trailing_stop[1], stopValue) else 0 if (buy_cond and notInTrade and start_time) strategy.entry(id="First Entry", long=strategy.long, comment="First Long") if (sell_cond and inTrade) strategy.close(id="First Entry", comment="Close First Long") if (re_entry_cond and notInTrade and start_time) strategy.entry(id="Further Entry", long=strategy.long, comment="Further Entry") if (sell_cond and inTrade) strategy.close(id="Further Entry", comment="Close First Long") if enable_TP if (enable_TS and not enable_SL) strategy.exit("Long TP & TS FiEn", "First Entry", limit = long_TP, stop = trailing_stop) strategy.exit("Long TP & TS FuEn", "Further Entry", limit = long_TP, stop = trailing_stop) else if (enable_SL and not enable_TS) strategy.exit("Long TP & TS FiEn", "First Entry", limit = long_TP, stop = long_SL) strategy.exit("Long TP & TS FuEn", "Further Entry", limit = long_TP, stop = long_SL) else strategy.exit("Long TP & TS FiEn", "First Entry", limit = long_TP) strategy.exit("Long TP & TS FuEn", "Further Entry", limit = long_TP) else if not enable_TP if (enable_TS and not enable_SL) strategy.exit("Long TP & TS FiEn", "First Entry", stop = trailing_stop) strategy.exit("Long TP & TS FuEn", "Further Entry", stop = trailing_stop) else if (enable_SL and not enable_TS) strategy.exit("Long TP & TS FiEn", "First Entry", stop = long_SL) strategy.exit("Long TP & TS FuEn", "Further Entry", stop = long_SL) plot(enable_TP ? long_TP : na, title="TP Level", color=color.green, style=plot.style_linebr, linewidth=2) plot(enable_SL ? long_SL : na, title="SL Level", color=color.red, style=plot.style_linebr, linewidth=2) plot(enable_TS and trailing_stop ? trailing_stop : na, title="TS Level", color=color.red, style=plot.style_linebr, linewidth=2)
[KL] Mean Reversion (ATR) Strategy
https://www.tradingview.com/script/vUm2xj05-KL-Mean-Reversion-ATR-Strategy/
DojiEmoji
https://www.tradingview.com/u/DojiEmoji/
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/ // © DojiEmoji //@version=5 strategy("Mean Reversion (ATR) Strategy [KL]", overlay=true, pyramiding=1) var string GROUP_TP = "Profit taking" var string GROUP_SL = "Stop loss" var string GROUP_ORDER = "Order size" var string GROUP_SIGNALS = "Signals" var string ENUM_LONG = "Long" backtest_timeframe_start = input.time(defval=timestamp("01 Apr 2000 13:30 +0000"), title="Backtest Start Time") within_timeframe = time >= backtest_timeframe_start // Variables stored upon initial entry, var initial_entry_p = float(0) // initial entry price var risk_amt = float(0) // initial entry price minus initial stop loss price var initial_order_size = 0 // TSL: calculate the stop loss price. { ATR_X2_TSL = ta.atr(input.int(14, title="Length of ATR for trailing stop loss", group=GROUP_SL)) * input.float(2.0, title="ATR Multiplier for trailing stop loss", group=GROUP_SL) TSL_source = low var stop_loss_price = float(0) TSL_line_color = color.green TSL_transp = 100 if strategy.position_size == 0 or not within_timeframe TSL_line_color := color.black stop_loss_price := TSL_source - ATR_X2_TSL else if strategy.position_size > 0 stop_loss_price := math.max(stop_loss_price, TSL_source - ATR_X2_TSL) TSL_transp := 0 plot(stop_loss_price, color=color.new(TSL_line_color, TSL_transp)) // } end of "TSL" block // ATR diversion test _len_volat = input(20, title="Main signal: Length of lookback (ATR mean reversion)", group=GROUP_SIGNALS) _ATR_volat = ta.atr(_len_volat) _avg_atr = ta.sma(_ATR_volat, _len_volat) _std_volat = ta.stdev(_ATR_volat, _len_volat) var _signal_diverted_ATR = false MULTIPLE_ATR_STD = 1 _signal_diverted_ATR := not _signal_diverted_ATR and _ATR_volat > (_avg_atr + _std_volat*MULTIPLE_ATR_STD) or _ATR_volat < (_avg_atr - _std_volat*MULTIPLE_ATR_STD) // lognormal returns for trend prediction _len_drift = input(20, title="Confirmation: Lenth to lookback for trend prediction", group=GROUP_SIGNALS) _prcntge_chng = math.log(close / close[1]) _drift = ta.sma(_prcntge_chng, _len_drift) - math.pow(ta.stdev(_prcntge_chng, _len_drift), 2) * 0.5 _signal_uptrend = _drift > _drift[1] and _drift > _drift[2] or _drift > 0 entry_signal_all = _signal_diverted_ATR and _signal_uptrend //main signal + confirmation // Order size and profit taking pcnt_alloc = input.int(5, title="Allocation (%) of portfolio into this security", tooltip="No rebalancing", minval=0, maxval=100, group=GROUP_ORDER) / 100 // Taking profits at user defined target levels relative to risked amount (i.e 1R, 2R, 3R) var bool tp_mode = input(true, title="Take profit and different levels") var float FIRST_LVL_PROFIT = input.float(1, title="First level profit", tooltip="Relative to risk. Example: entry at $10 and inital stop loss at $9. Taking first level profit at 1R means taking profits at $11", group=GROUP_TP) var float SECOND_LVL_PROFIT = input.float(2, title="Second level profit", tooltip="Relative to risk. Example: entry at $10 and inital stop loss at $9. Taking second level profit at 2R means taking profits at $12", group=GROUP_TP) var float THIRD_LVL_PROFIT = input.float(3, title="Third level profit", tooltip="Relative to risk. Example: entry at $10 and inital stop loss at $9. Taking third level profit at 3R means taking profits at $13", group=GROUP_TP) if tp_mode if close >= initial_entry_p + THIRD_LVL_PROFIT * risk_amt strategy.close(ENUM_LONG, comment="TP", qty=math.floor(initial_order_size / 3)) else if close >= initial_entry_p + SECOND_LVL_PROFIT * risk_amt strategy.close(ENUM_LONG, comment="TP", qty=math.floor(initial_order_size / 3)) else if close >= initial_entry_p + FIRST_LVL_PROFIT * risk_amt strategy.close(ENUM_LONG, comment="TP") // MAIN { // Update the stop limit if strategy holds a position if strategy.position_size > 0 strategy.exit(ENUM_LONG, comment="SL", stop=stop_loss_price) // Entry if within_timeframe and entry_signal_all and strategy.position_size == 0 initial_entry_p := close risk_amt := ATR_X2_TSL initial_order_size := math.floor(pcnt_alloc * strategy.equity / close) strategy.entry(ENUM_LONG, strategy.long, comment=strategy.position_size > 0 ? "adding" : "initial", qty=initial_order_size) // Alerts alert_per_bar(msg) => prefix = "[" + syminfo.root + "] " suffix = "(P=" + str.tostring(close, "#.##") + "; atr=" + str.tostring(_ATR_volat, "#.##") + ")" alert(str.tostring(prefix) + str.tostring(msg) + str.tostring(suffix), alert.freq_once_per_bar) if strategy.position_size > 0 and ta.change(strategy.position_size) if strategy.position_size > strategy.position_size[1] alert_per_bar("BUY") else if strategy.position_size < strategy.position_size[1] alert_per_bar("SELL") // Clean up changed_pos_size = ta.change(strategy.position_size) if changed_pos_size and strategy.position_size == 0 initial_order_size := 0 initial_entry_p := float(0) risk_amt := float(0) stop_loss_price := float(0) else if changed_pos_size _signal_diverted_ATR := false // } end of MAIN block
Improved Bollinger Swing Strategy Stock Nasdaq
https://www.tradingview.com/script/3hf7i2vq-Improved-Bollinger-Swing-Strategy-Stock-Nasdaq/
exlux99
https://www.tradingview.com/u/exlux99/
182
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © exlux99 //@version=4 strategy("BB NDX strategy", overlay = true, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, calc_on_every_tick = true, commission_type = strategy.commission.percent, commission_value = 0.01) source = close length = input(25, minval=1, title="Length BB long") mult = input(2.9, minval=0.001, maxval=50, step=0.1, title="MULT BB long") length2 = input(36, minval=1, title="Length BB short") mult2 = input(3.2, minval=0.001, maxval=50, step=0.1, title="MULT BB short") basis = sma(source, length) dev = mult * stdev(source, length) dev2 = mult2 * stdev(source, length2) upper = basis + dev2 lower = basis - dev buyEntry = crossover(source, lower) sellEntry = crossunder(source, upper) longEntry=input(true) shortEntry=input(true) g(v, p) => round(v * (pow(10, p))) / pow(10, p) risk = input(100) leverage = input(1.0, step = 0.5) c = g((strategy.equity * leverage / open) * (risk / 100), 4) tplong=input(0.065, step=0.005, title="Take profit % for long") sllong=input(0.04, step=0.005, title="Stop loss % for long") tpshort=input(0.025, step=0.005, title="Take profit % for short") slshort=input(0.04, step=0.005, title="Stop loss % for short") if(longEntry) strategy.entry("long",1,c,when=buyEntry) strategy.exit("short_tp/sl", "long", profit=close * tplong / syminfo.mintick, loss=close * sllong / syminfo.mintick, comment='LONG EXIT', alert_message = 'closeshort') strategy.close("long",when=sellEntry) if(shortEntry) strategy.entry("short",0,c,when=sellEntry) strategy.exit("short_tp/sl", "short", profit=close * tpshort / syminfo.mintick, loss=close * slshort / syminfo.mintick, comment='SHORT EXIT', alert_message = 'closeshort') strategy.close("short",when=buyEntry)
Full Swing Gold Vwap Macd SMO Strategy
https://www.tradingview.com/script/Aw6BfMjo-Full-Swing-Gold-Vwap-Macd-SMO-Strategy/
exlux99
https://www.tradingview.com/u/exlux99/
126
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © exlux99 //@version=4 strategy("VWAP Gold strategy", overlay = true, default_qty_type = strategy.percent_of_equity, default_qty_value = 10000, calc_on_every_tick = true, commission_type = strategy.commission.percent, commission_value = 0.005) source = input(low) //vwap monthly timeframeM = time("M") beginningM = na(timeframeM[1]) or timeframeM > timeframeM[1] sumsourceM = source * volume sumVolM = volume sumsourceM := beginningM ? sumsourceM : sumsourceM + sumsourceM[1] sumVolM := beginningM ? sumVolM : sumVolM + sumVolM[1] vwapMonthly= sumsourceM / sumVolM //macd fast_length = input(title="Fast Length", type=input.integer, defval=12) slow_length = input(title="Slow Length", type=input.integer, defval=26) src = input(title="Source", type=input.source, defval=close) signal_length = input(title="Signal Smoothing", type=input.integer, minval = 1, maxval = 50, defval = 9) fast_ma = ema(src, fast_length) slow_ma = ema(src, slow_length) macd = fast_ma - slow_ma signal = ema(macd, signal_length) hist = macd - signal //SMO longlen = input(22, minval=1, title="Long Length SMO") shortlen = input(6, minval=1, title="Short Length SMO") siglen = input(5, minval=1, title="Signal Line Length SMO") erg = tsi(close, shortlen, longlen) sig = ema(erg, siglen) osc = erg - sig shortCondition = close < vwapMonthly and hist < hist[1] and osc < 0 longCondition = close > vwapMonthly and hist> hist[1] and osc > 0 tplong=input(0.085, step=0.005, title="Take profit % for long") sllong=input(0.03, step=0.005, title="Stop loss % for long") tpshort=input(0.05, step=0.005, title="Take profit % for short") slshort=input(0.025, step=0.005, title="Stop loss % for short") strategy.entry("long",1,when=longCondition) strategy.entry("short",0,when=shortCondition) strategy.exit("short_tp/sl", "long", profit=close * tplong / syminfo.mintick, loss=close * sllong / syminfo.mintick, comment='LONG EXIT', alert_message = 'closeshort') strategy.exit("short_tp/sl", "short", profit=close * tpshort / syminfo.mintick, loss=close * slshort / syminfo.mintick, comment='SHORT EXIT', alert_message = 'closeshort')
Bagheri IG Ether
https://www.tradingview.com/script/XHnDW4Aa-Bagheri-IG-Ether/
Bagheri_IG
https://www.tradingview.com/u/Bagheri_IG/
71
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © mbagheri746 //@version=4 strategy("Bagheri IG Ether", overlay=true, margin_long=100, margin_short=100) TP = input(3000, minval = 1 , title ="Take Profit") SL = input(3443, minval = 1 , title ="Stop Loss") //_________________ RoC Definition _________________ rocLength = input(title="ROC Length", type=input.integer, minval=1, defval=185) smoothingLength = input(title="Smoothing Length", type=input.integer, minval=1, defval=49) src = input(title="Source", type=input.source, defval=close) ma = ema(src, smoothingLength) mom = change(ma, rocLength) sroc = nz(ma[rocLength]) == 0 ? 100 : mom == 0 ? 0 : 100 * mom / ma[rocLength] //srocColor = sroc >= 0 ? #0ebb23 : color.red //plot(sroc, title="SROC", linewidth=2, color=srocColor, transp=0) //hline(0, title="Zero Level", linestyle=hline.style_dotted, color=#989898) //_________________ Donchian Channel _________________ length1 = input(43, minval=1, title="Upper Channel") length2 = input(43, minval=1, title="Lower Channel") offset_bar = input(90,minval=0, title ="Offset Bars") upper = highest(length1) lower = lowest(length2) basis = avg(upper, lower) DC_UP_Band = upper[offset_bar] DC_LW_Band = lower[offset_bar] l = plot(DC_LW_Band, style=plot.style_line, linewidth=1, color=color.red) u = plot(DC_UP_Band, style=plot.style_line, linewidth=1, color=color.aqua) fill(l,u,color = color.new(color.aqua,transp = 90)) //_________________ Bears Power _________________ wmaBP_period = input(61,minval=1,title="BearsP WMA Period") line_wma = ema(close, wmaBP_period) BP = low - line_wma //_________________ Balance of Power _________________ ES_BoP=input(15, title="BoP Exponential Smoothing") BOP=(close - open) / (high - low) SBOP = rma(BOP, ES_BoP) //_________________ Alligator _________________ //_________________ CCI _________________ //_________________ Moving Average _________________ sma_period = input(74, minval = 1 , title = "SMA Period") sma_shift = input(37, minval = 1 , title = "SMA Shift") sma_primary = sma(close,sma_period) SMA_sh = sma_primary[sma_shift] plot(SMA_sh, style=plot.style_line, linewidth=2, color=color.yellow) //_________________ Long Entry Conditions _________________// MA_Lcnd = SMA_sh > low and SMA_sh < high ROC_Lcnd = sroc < 0 DC_Lcnd = open < DC_LW_Band BP_Lcnd = BP[1] < BP[0] and BP[1] < BP[2] BOP_Lcnd = SBOP[1] < SBOP[0] //_________________ Short Entry Conditions _________________// MA_Scnd = SMA_sh > low and SMA_sh < high ROC_Scnd = sroc > 0 DC_Scnd = open > DC_UP_Band BP_Scnd = BP[1] > BP[0] and BP[1] > BP[2] BOP_Scnd = SBOP[1] > SBOP[0] //_________________ OPEN POSITION __________________// strategy.entry(id = "BUY", long = true , when = MA_Lcnd and ROC_Lcnd and DC_Lcnd and BP_Lcnd and BOP_Lcnd) strategy.entry(id = "SELL", long = false , when = MA_Scnd and ROC_Scnd and DC_Scnd and BP_Scnd and BOP_Scnd) //_________________ CLOSE POSITION __________________// strategy.exit(id = "CLOSE BUY", from_entry = "BUY", profit = TP , loss = SL) strategy.exit(id = "CLOSE SELL", from_entry = "SELL" , profit = TP , loss = SL) //_________________ TP and SL Plot __________________// currentPL= strategy.openprofit pos_price = strategy.position_avg_price open_pos = strategy.position_size TP_line = (strategy.position_size > 0) ? (pos_price + TP/100) : strategy.position_size < 0 ? (pos_price - TP/100) : 0.0 SL_line = (strategy.position_size > 0) ? (pos_price - SL/100) : strategy.position_size < 0 ? (pos_price + SL/100) : 0.0 // hline(TP_line, title = "Take Profit", color = color.green , linestyle = hline.style_dotted, editable = false) // hline(SL_line, title = "Stop Loss", color = color.red , linestyle = hline.style_dotted, editable = false) Tline = plot(TP_line != 0.0 ? TP_line : na , title="Take Profit", color=color.green, trackprice = true, show_last = 1) Sline = plot(SL_line != 0.0 ? SL_line : na, title="Stop Loss", color=color.red, trackprice = true, show_last = 1) Pline = plot(pos_price != 0.0 ? pos_price : na, title="Stop Loss", color=color.gray, trackprice = true, show_last = 1) fill(Tline , Pline, color = color.new(color.green,transp = 90)) fill(Sline , Pline, color = color.new(color.red,transp = 90)) //_________________ Alert __________________// //alertcondition(condition = , title = "Position Alerts", message = "Bagheri IG Ether\n Symbol: {{ticker}}\n Type: {{strategy.order.id}}") //_________________ Label __________________// inMyPrice = input(title="My Price", type=input.float, defval=0) inLabelStyle = input(title="Label Style", options=["Upper Right", "Lower Right"], defval="Lower Right") posColor = color.new(color.green, 25) negColor = color.new(color.red, 25) dftColor = color.new(color.aqua, 25) posPnL = (strategy.position_size != 0) ? (close * 100 / strategy.position_avg_price - 100) : 0.0 posDir = (strategy.position_size > 0) ? "long" : strategy.position_size < 0 ? "short" : "flat" posCol = (strategy.openprofit > 0) ? posColor : (strategy.openprofit < 0) ? negColor : dftColor myPnL = (inMyPrice != 0) ? (close * 100 / inMyPrice - 100) : 0.0 var label lb = na label.delete(lb) lb := label.new(bar_index, close, color=posCol, style=inLabelStyle=="Lower Right"?label.style_label_upper_left:label.style_label_lower_left, text= "╔═══════╗" +"\n" + "Pos: " +posDir +"\n" + "Pos Price: "+tostring(strategy.position_avg_price) +"\n" + "Pos PnL: " +tostring(posPnL, "0.00") + "%" +"\n" + "Profit: " +tostring(strategy.openprofit, "0.00") + "$" +"\n" + "TP: " +tostring(TP_line, "0.00") +"\n" + "SL: " +tostring(SL_line, "0.00") +"\n" + "╚═══════╝")
Macd Divergence + MTF EMA
https://www.tradingview.com/script/dM6UtZqX-Macd-Divergence-MTF-EMA/
Trading_Solutions_
https://www.tradingview.com/u/Trading_Solutions_/
368
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © maxits //@version=5 // MACD Divergence + Multi Time Frame EMA // This Strategy uses 3 indicators: the Macd and two emas in different time frames // The configuration of the strategy is: // Macd standar configuration (12, 26, 9) in 1H resolution // 10 periods ema, in 1H resolution // 5 periods ema, in 15 minutes resolution // We use the two emas to filter for long and short positions. // If 15 minutes ema is above 1H ema, we look for long positions // If 15 minutes ema is below 1H ema, we look for short positions // We can use an aditional filter using a 100 days ema, so when the 15' and 1H emas are above the daily ema we take long positions // Using this filter improves the strategy // We wait for Macd indicator to form a divergence between histogram and price // If we have a bullish divergence, and 15 minutes ema is above 1H ema, we wait for macd line to cross above signal line and we open a long position // If we have a bearish divergence, and 15 minutes ema is below 1H ema, we wait for macd line to cross below signal line and we open a short position // We close both position after a cross in the oposite direction of macd line and signal line // Also we can configure a Take profit parameter and a trailing stop loss strategy('Macd Divergence + MTF EMA [Trading Solutions]', overlay=true, initial_capital=1000, default_qty_value=20, default_qty_type=strategy.percent_of_equity, commission_value=0.1, pyramiding=0) // User Inputs i_time = input.time(defval=timestamp('01 Apr 2018 13:30 +0000'), title='Start Time') // Starting time for backtest f_time = input.time(defval=timestamp('30 Sep 2021 13:30 +0000'), title='Finish Time') // Finishing time for backtest long_pos = input.bool (title='Show Long Positions', defval=true) // Enable Long Positions short_pos = input.bool (title='Show Short Positions', defval=true) // Enable Short Positions src = input.source(title='Source', defval=close) // Price value to calculate indicators emas_properties = "EMAS Settings" mtf_15 = input.timeframe(title='Fast EMA', defval='15', group = emas_properties) // Resolucion para MTF EMA 15 minutes ma_15_length = input.int(5, title='Fast EMA Period', group = emas_properties) // MTF EMA 15 minutes Length mtf_60 = input.timeframe(title='Slow EMA', defval='60', group = emas_properties) // Resolucion para MTF EMA 60 minutes ma_60_length = input.int(10, title='Slow EMA Period', group = emas_properties) // MTF EMA 60 minutes Length filterSettings = "Filter Settings" e_new_filter = input.bool (title='Enable a Third Ema filter?', defval=true, group = filterSettings) // Enable Filter slowest_ema_len = input.int (title='Filter EMA Period', defval = 100, group = filterSettings) // Filter EMA Length slowest_ema_res = input.timeframe(title='Filter Resolution EMA', defval='D', group = filterSettings) // Filter Resolution macd_properties = 'MACD Properties' macd_res = input.timeframe(title='MACD TimeFrame', defval='', group = macd_properties) // MACD Time Frame fast_len = input.int (title='Fast Length', defval=12, group = macd_properties) // Fast MA Length slow_len = input.int (title='Sign Length', defval=26, group = macd_properties) // Sign MA Length sign_len = input.int (title='Sign Length', defval=9, group = macd_properties) syst_properties = 'Trade Management' // Properties lookback = input.int (title='Lookback period', defval=14, minval=1, group = syst_properties) // Candles to lookback for swing high or low multiplier = input.float(title='Profit Multiplier based on Stop Loss', defval=6.0, minval=0.1, group = syst_properties) // Profit multiplier based on stop loss shortStopPer = input.float(title='Short Stop Loss Percentage', defval=1.0, minval=0.0, group = syst_properties) / 100 // Target Percentage longStopPer = input.float(title='Long Stop Loss Percentage', defval=2.0, minval=0.0, group = syst_properties) / 100 // Sloss Percentage // Indicators [macd, signal, hist] = request.security(syminfo.tickerid, macd_res, ta.macd(src, fast_len, slow_len, sign_len)) ma_15 = request.security(syminfo.tickerid, mtf_15, ta.ema(src, ma_15_length)) ma_60 = request.security(syminfo.tickerid, mtf_60, ta.ema(src, ma_60_length)) ma_slo = request.security(syminfo.tickerid, slowest_ema_res, ta.ema(src, slowest_ema_len)) // Macd Plot col_grow_above = #26A69A col_grow_below = #FFCDD2 col_fall_above = #B2DFDB col_fall_below = #EF5350 plot(macd, color=color.new(color.blue, 0)) plot(signal, color=color.new(color.orange, 0)) plot(hist, style=plot.style_columns, color=hist >= 0 ? hist[1] < hist ? col_grow_above : col_fall_above : hist[1] < hist ? col_grow_below : col_fall_below) // MTF EMA Plot bullish_filter = e_new_filter ? ma_15 > ma_60 and ma_60 > ma_slo : ma_15 > ma_60 bearish_filter = e_new_filter ? ma_15 < ma_60 and ma_60 < ma_slo : ma_15 < ma_60 plot(ma_15, color=color.new(color.blue, 0)) plot(ma_60, color=color.new(color.yellow, 0)) plot(e_new_filter ? ma_slo : na, color=ma_60 > ma_slo ? color.new(color.green, 0) : color.new(color.red, 0)) ////////////////////////////////////////////// Logic For Macd Divergence zero_cross = false zero_cross := ta.crossover(hist, 0) or ta.crossunder(hist, 0) //Cruce del Histograma a la linea 0 // plot(zero_cross ? 1 : na) // MACD DIVERGENCE TOPS (Bearish Divergence) highest_top = 0.0 prior_top = 0.0 highest_top := zero_cross == true ? 0.0 : hist > 0 and hist > highest_top[1] ? hist : highest_top[1] prior_top := ta.crossunder(hist, 0) ? highest_top[1] : prior_top[1] highest_top_close = 0.0 prior_top_close = 0.0 highest_top_close := zero_cross == true ? 0.0 : hist > 0 and hist > highest_top[1] ? close : highest_top_close[1] prior_top_close := ta.crossunder(hist, 0) ? highest_top_close[1] : prior_top_close[1] top = false top := highest_top[1] < prior_top[1] and highest_top_close[1] > prior_top_close[1] and hist < hist[1] and ta.crossunder(hist, 0) // Bearish Divergence: top == true // MACD DIVERGENCE BOTTOMS (Bullish Divergence) lowest_bottom = 0.0 prior_bottom = 0.0 lowest_bottom := zero_cross == true ? 0.0 : hist < 0 and hist < lowest_bottom[1] ? hist : lowest_bottom[1] prior_bottom := ta.crossover(hist, 0) ? lowest_bottom[1] : prior_bottom[1] lowest_bottom_close = 0.0 prior_bottom_close = 0.0 lowest_bottom_close := zero_cross == true ? 0.0 : hist < 0 and hist < lowest_bottom[1] ? close : lowest_bottom_close[1] prior_bottom_close := ta.crossover(hist, 0) ? lowest_bottom_close[1] : prior_bottom_close[1] bottom = false bottom := lowest_bottom[1] > prior_bottom[1] and lowest_bottom_close[1] < prior_bottom_close[1] and hist > hist[1] and ta.crossover(hist, 0) // Bullish Divergence: bottom == true ////////////////////////////////////////////// Logic For RSI Divergence ////////////////////////////////////////////// System Conditions ////////////////////////////////////////////// inTrade = strategy.position_size != 0 // In Trade longTrade = strategy.position_size > 0 // Long position shortTrade = strategy.position_size < 0 // Short position notInTrade = strategy.position_size == 0 // No trade entryPrice = strategy.position_avg_price // Position Entry Price ////////////////////////////////////////////// Long Conditions ////////////////////////////////////////////// sl = ta.lowest(low, lookback) // Swing Low for Long Entry longStopLoss = 0.0 // Trailing Stop Loss calculation longStopLoss := if longTrade astopValue = sl * (1 - longStopPer) math.max(longStopLoss[1], astopValue) else 0 longTakeProf = 0.0 // Profit calculation based on stop loss longTakeProf := if longTrade profitValue = entryPrice + (entryPrice - longStopLoss) * multiplier math.max(longTakeProf[1], profitValue) else 0 // Long Entry Conditions if bottom and notInTrade and bullish_filter and long_pos and barstate.isconfirmed strategy.entry(id='Go Long', direction=strategy.long, comment='Long Position') alert("Long Trade: " + syminfo.ticker, alert.freq_once_per_bar_close) label.new(bar_index, low, text = "Long Trade", textcolor = color.white, color = color.green, style = label.style_label_up) // strategy.close(id="Go Long", when=zero_cross) if longTrade strategy.exit('Exit Long', 'Go Long', limit=longTakeProf, stop=longStopLoss) plot(longTrade and longStopLoss ? longStopLoss : na, title='Long Stop Loss', color=color.new(color.red, 0), style=plot.style_linebr) plot(longTrade and longTakeProf ? longTakeProf : na, title='Long Take Prof', color=color.new(color.green, 0), style=plot.style_linebr) ////////////////////////////////////////////// Short Conditions ////////////////////////////////////////////// sh = ta.highest(high, lookback) // Swing High for Short Entry shortStopLoss = 0.0 shortStopLoss := if shortTrade bstopValue = sh * (1 + shortStopPer) math.min(shortStopLoss[1], bstopValue) else 999999 shortTakeProf = 0.0 shortTakeProf := if shortTrade SprofitValue = entryPrice - (shortStopLoss - entryPrice) * multiplier math.min(SprofitValue, shortTakeProf[1]) else 999999 // Short Entry if top and notInTrade and bearish_filter and short_pos and barstate.isconfirmed strategy.entry(id='Go Short', direction=strategy.short, comment='Short Position') alert("Short Trade: " + syminfo.ticker, alert.freq_once_per_bar_close) label.new(bar_index, high, text = "Short Trade", textcolor = color.white, color = color.red, style = label.style_label_down) // strategy.close(id="Go Short", when=zero_cross) if shortTrade strategy.exit('Exit Short', 'Go Short', limit=shortTakeProf, stop=shortStopLoss) plot(shortTrade and shortStopLoss ? shortStopLoss : na, title='Short Stop Loss', color=color.new(color.red, 0), style=plot.style_linebr) plot(shortTrade and shortTakeProf ? shortTakeProf : na, title='Short Take Prof', color=color.new(color.green, 0), style=plot.style_linebr)
Advanced OutSide with HMA and Klinger Forex Swing strategy
https://www.tradingview.com/script/v5vo0vNc-Advanced-OutSide-with-HMA-and-Klinger-Forex-Swing-strategy/
exlux99
https://www.tradingview.com/u/exlux99/
74
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © exlux99 //@version=4 strategy("Advanced OutSide Forex strategy", overlay = true, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, calc_on_every_tick = true, commission_type = strategy.commission.percent, commission_value = 0.0) sv = change(hlc3) >= 0 ? volume : -volume kvo = ema(sv, 34) - ema(sv, 55) sig = ema(kvo, 13) length = input(title="Length", type=input.integer, defval=27) src = input(close, title="Source") lsma = hma(src, length) if (high > high[1] and low < low[1]) if (close > open and kvo>0 and lsma<close) strategy.entry("long", strategy.long, comment="long") if (high < high[1] and low > low[1]) if (close < open and kvo<0 and lsma>close) strategy.entry("short", strategy.short, comment="short") tplong=input(0.006, step=0.001, title="Take profit % for long") sllong=input(0.012, step=0.001, title="Stop loss % for long") tpshort=input(0.0075, step=0.001, title="Take profit % for short") slshort=input(0.015, step=0.001, title="Stop loss % for short") strategy.exit("short_tp/sl", "long", profit=close * tplong / syminfo.mintick, loss=close * sllong / syminfo.mintick, comment='LONG EXIT', alert_message = 'closeshort') strategy.exit("short_tp/sl", "short", profit=close * tpshort / syminfo.mintick, loss=close * slshort / syminfo.mintick, comment='SHORT EXIT', alert_message = 'closeshort')
VWAP Stoch Long Trailing Stop without wednesday and thursday
https://www.tradingview.com/script/8PNzDgM7-VWAP-Stoch-Long-Trailing-Stop-without-wednesday-and-thursday/
Drflexfunk
https://www.tradingview.com/u/Drflexfunk/
73
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © relevantSnail17572 //@version=4 strategy("VWAP Stoch Long Trailing Stop without wednesday and thursday") vwapClose = vwap(close) stochClose = stoch(close, high, low, 10) vwapLong = close < vwapClose stochLong = stochClose < 5 goodDay = dayofweek==dayofweek.sunday or dayofweek==dayofweek.monday or dayofweek==dayofweek.tuesday or dayofweek==dayofweek.friday or dayofweek==dayofweek.saturday startLong = vwapLong and stochLong and goodDay size = strategy.equity / close longStopPrice = 0.0 longStopPrice := if (strategy.position_size > 0) stopValue = close * (1 - 0.03) max(stopValue, longStopPrice[1]) else 0 strategy.entry("Buy", strategy.long, size, when = startLong and strategy.position_size <= 0) strategy.exit(id="Buy", stop=longStopPrice) plot(strategy.equity/close)
Strategy Template - V2
https://www.tradingview.com/script/nSgePqla-Strategy-Template-V2/
Trendoscope
https://www.tradingview.com/u/Trendoscope/
814
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © HeWhoMustNotBeNamed // __ __ __ __ __ __ __ __ __ __ __ _______ __ __ __ // / | / | / | _ / |/ | / \ / | / | / \ / | / | / \ / \ / | / | // $$ | $$ | ______ $$ | / \ $$ |$$ |____ ______ $$ \ /$$ | __ __ _______ _$$ |_ $$ \ $$ | ______ _$$ |_ $$$$$$$ | ______ $$ \ $$ | ______ _____ ____ ______ ____$$ | // $$ |__$$ | / \ $$ |/$ \$$ |$$ \ / \ $$$ \ /$$$ |/ | / | / |/ $$ | $$$ \$$ | / \ / $$ | $$ |__$$ | / \ $$$ \$$ | / \ / \/ \ / \ / $$ | // $$ $$ |/$$$$$$ |$$ /$$$ $$ |$$$$$$$ |/$$$$$$ |$$$$ /$$$$ |$$ | $$ |/$$$$$$$/ $$$$$$/ $$$$ $$ |/$$$$$$ |$$$$$$/ $$ $$< /$$$$$$ |$$$$ $$ | $$$$$$ |$$$$$$ $$$$ |/$$$$$$ |/$$$$$$$ | // $$$$$$$$ |$$ $$ |$$ $$/$$ $$ |$$ | $$ |$$ | $$ |$$ $$ $$/$$ |$$ | $$ |$$ \ $$ | __ $$ $$ $$ |$$ | $$ | $$ | __ $$$$$$$ |$$ $$ |$$ $$ $$ | / $$ |$$ | $$ | $$ |$$ $$ |$$ | $$ | // $$ | $$ |$$$$$$$$/ $$$$/ $$$$ |$$ | $$ |$$ \__$$ |$$ |$$$/ $$ |$$ \__$$ | $$$$$$ | $$ |/ |$$ |$$$$ |$$ \__$$ | $$ |/ |$$ |__$$ |$$$$$$$$/ $$ |$$$$ |/$$$$$$$ |$$ | $$ | $$ |$$$$$$$$/ $$ \__$$ | // $$ | $$ |$$ |$$$/ $$$ |$$ | $$ |$$ $$/ $$ | $/ $$ |$$ $$/ / $$/ $$ $$/ $$ | $$$ |$$ $$/ $$ $$/ $$ $$/ $$ |$$ | $$$ |$$ $$ |$$ | $$ | $$ |$$ |$$ $$ | // $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$/ $$$$$$/ $$/ $$/ $$$$$$/ $$$$$$$/ $$$$/ $$/ $$/ $$$$$$/ $$$$/ $$$$$$$/ $$$$$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$$$$$$/ $$$$$$$/ // // // //@version=5 //########################################### Strategy definition ######################################################/ strategy('Strategy Template - V2', overlay=true, initial_capital=20000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, pyramiding=1, commission_value=0.11, max_lines_count=500, max_labels_count=500, max_boxes_count=500) //########################################### Entry and exit parameters ######################################################/ i_entryType = input.string('Stop', title='Entry Type', options=['Market', 'Stop', 'Limit', 'Stop-Limit'], group='Entry Parameters') i_dcLength = input.int(40, step=10, title='Donchian Length', group='Entry Parameters') i_htfResolution = input.timeframe('W', title='Higher Timeframe', group='Entry Parameters') i_stopType = input.string('Stop', title='Stop Type', options=['Market', 'Stop'], group='Exit Parameters') i_takeProfit = input.bool(false, title='Take Initial Profit', group='Exit Parameters') i_takeProfitRR = input.float(10, step=0.5, title='Risk/Reward (Take Profit)', group='Exit Parameters') i_takeProfitQty = input.int(30, step=5, minval=5, maxval=100, title='Take Profit Percent', group='Exit Parameters') i_atrMaType = input.string('sma', title='ATR MA Type (Stop-Limit)', options=['sma', 'ema', 'hma', 'rma', 'vwma', 'wma'], group='Exit Parameters') i_atrLength = input.int(22, title='ATR Length (Stop-Limit', step=5, group='Exit Parameters') i_atrMultStop = input.float(0.5, step=0.5, title='ATR Multiplier (Stop-Limit)', group='Exit Parameters') //############################################ Generic Strategy Parameters ###################################################/ i_tradeDirection = input.string(title='Trade Direction', defval=strategy.direction.all, options=[strategy.direction.all, strategy.direction.long, strategy.direction.short], group='Trade Filters') strategy.risk.allow_entry_in(i_tradeDirection) i_startTime = input.time(defval=timestamp('01 Jan 2010 00:00 +0000'), title='Start Time', group='Trade Filters') i_endTime = input.time(defval=timestamp('01 Jan 2099 00:00 +0000'), title='End Time', group='Trade Filters') inDateRange = time >= i_startTime and time <= i_endTime //################################################## Generic Methods #########################################################/ f_secureSecurity(_symbol, _res, _src, _offset) => request.security(_symbol, _res, _src[_offset], lookahead=barmerge.lookahead_on) f_getMovingAverage(source, MAType, MALength) => ma = ta.sma(source, MALength) if MAType == 'ema' ma := ta.ema(source, MALength) ma if MAType == 'hma' ma := ta.hma(source, MALength) ma if MAType == 'rma' ma := ta.rma(source, MALength) ma if MAType == 'vwma' ma := ta.vwma(source, MALength) ma if MAType == 'wma' ma := ta.wma(source, MALength) ma ma f_getCustomAtr(MAType, MALength) => f_getMovingAverage(ta.tr, MAType, MALength) f_get_donchian(dcLength, resolution) => top = resolution == '' ? ta.highest(dcLength) : f_secureSecurity(syminfo.tickerid, resolution, ta.highest(dcLength), 1) bottom = resolution == '' ? ta.lowest(dcLength) : f_secureSecurity(syminfo.tickerid, resolution, ta.lowest(dcLength), 1) mid = (top + bottom) / 2 [mid, top, bottom] //###################################################### Calculation and plot ##########################################################/ [mid, top, bottom] = f_get_donchian(i_dcLength, '') [hmid, htop, hbottom] = f_get_donchian(i_dcLength, i_htfResolution) atrStop = f_getCustomAtr(i_atrMaType, i_atrLength) * i_atrMultStop p_top = plot(top, 'TOP', color=color.new(color.lime, 80)) p_bottom = plot(bottom, 'BOTTOM', color=color.new(color.orange, 80)) p_mid = plot(mid, 'MID', color=color.new(color.blue, 80)) fill(p_top, p_mid, title='Upper', color=color.new(color.lime, 80)) fill(p_bottom, p_mid, title='Lower', color=color.new(color.orange, 80)) p_htop = plot(htop, 'HTOP', color=color.new(color.green, 80)) p_hbottom = plot(hbottom, 'HBOTTOM', color=color.new(color.red, 80)) p_hmid = plot(hmid, 'HMID', color=color.new(color.purple, 80)) fill(p_htop, p_hmid, title='HTF Upper', color=color.new(color.green, 80)) fill(p_hbottom, p_hmid, title='HTF Lower', color=color.new(color.red, 80)) // ########################################### Trade conditions and levels ################################################/ longBias = bottom > hmid and inDateRange shortBias = top < hmid and inDateRange closeBuyCondition = strategy.position_size > 0 closeSellCondition = strategy.position_size < 0 // Market order conditions buyMarketCondition = ta.crossover(high, top[1]) and i_entryType == 'Market' sellMarketCondition = ta.crossunder(low, bottom[1]) and i_entryType == 'Market' closeBuyMarketCondition = ta.crossunder(low, bottom[1]) and i_stopType == 'Market' and not longBias closeSellMarketCondition = ta.crossover(high, top[1]) and i_stopType == 'Market' and not shortBias // Stop order conditions buySellStopCondition = i_entryType == 'Stop' closeBuySellStopCondition = i_stopType == 'Stop' // Limit and stoplimit conditions buyLimitCondition = i_entryType == 'Limit' and high > mid sellLimitCondition = i_entryType == 'Limit' and low < mid buyStopLimitCondition = i_entryType == 'Stop-Limit' and ta.crossover(high, top[1]) sellStopLimitCondition = i_entryType == 'Stop-Limit' and ta.crossunder(low, bottom[1]) // Entry levels for long and short orders via Stop, Limit and Stop-Limit buyLevel = top sellLevel = bottom buyStopLimit = top + atrStop sellStopLimit = bottom - atrStop // Exit levels for long and short - to be used in Stop orders closeBuyStop = bottom closeSellStop = top // Take profit conditions and levels for long and short - to be used in Take Profit exit orders takeProfitBuyCondition = longBias and strategy.position_size > 0 and i_takeProfit takeProfitSellCondition = shortBias and strategy.position_size < 0 and i_takeProfit profitLong = top + i_takeProfitRR * (top - bottom) profitShort = bottom - i_takeProfitRR * (top - bottom) profitLong := strategy.position_size <= 0 ? profitLong : high[1] > profitLong[1] ? profitLong[1] + i_takeProfitRR * (top - bottom) : profitLong[1] profitShort := strategy.position_size >= 0 ? profitShort : low[1] < profitShort[1] ? profitShort[1] - i_takeProfitRR * (top - bottom) : profitShort[1] // ########################################### Trade Statements Using If-Blocks ################################################/ //Entry for Long Orders if longBias //Cancel short pending orders and close existing short trades strategy.cancel('Short') strategy.close('Short') //Long entry based on entry type - market, stop, limit or stop-limit if buyMarketCondition strategy.entry('Long', strategy.long, comment='Long-Market-Order') if buySellStopCondition strategy.entry('Long', strategy.long, stop=buyLevel, oca_name='oca_buy', oca_type=strategy.oca.cancel, comment='Long-Stop-Order') if buyLimitCondition strategy.entry('Long', strategy.long, limit=buyLevel, oca_name='oca_buy', oca_type=strategy.oca.cancel, comment='Long-Limit-Order') if buyStopLimitCondition strategy.entry('Long', strategy.long, limit=buyStopLimit, stop=buyLevel, oca_name='oca_buy', oca_type=strategy.oca.cancel, comment='Long-Stop-Limit-Order') //Entry for Short Orders if shortBias //Cancel long pending orders and close existing long trades strategy.cancel('Long') strategy.close('Long') //Short entry based on entry type - market, stop, limit or stop-limit if sellMarketCondition strategy.entry('Short', strategy.short, comment='Short-Market-Order') if buySellStopCondition strategy.entry('Short', strategy.short, stop=sellLevel, oca_name='oca_sell', oca_type=strategy.oca.cancel, comment='Short-Stop-Order') if sellLimitCondition strategy.entry('Short', strategy.short, limit=sellLevel, oca_name='oca_sell', oca_type=strategy.oca.cancel, comment='Short-Limit-Order') if sellStopLimitCondition strategy.entry('Short', strategy.short, limit=sellStopLimit, stop=sellLevel, oca_name='oca_sell', oca_type=strategy.oca.cancel, comment='Short-Stop-Limit-Order') //Exit Long order market condition if closeBuyCondition and closeBuyMarketCondition strategy.close('Long', comment='Close-Long-Market') //Exit Short order by market condition if closeSellCondition and closeSellMarketCondition strategy.close('Short', comment='Close-Short-Market') //Exit by stoploss - Set stoploss beforehand if closeBuySellStopCondition if closeBuyCondition strategy.exit('StopLong', 'Long', stop=closeBuyStop, comment='Close-Buy-Stop') if closeSellCondition strategy.exit('StopShort', 'Short', stop=closeSellStop, comment='Close-Sell-Stop') // Take Profit for Long Order if takeProfitBuyCondition strategy.exit('ProfitLong', 'Long', limit=profitLong, qty_percent=i_takeProfitQty, comment='Close-Buy-Profit') // Take Profit for Short Order if takeProfitSellCondition strategy.exit('ProfitShort', 'Short', limit=profitShort, qty_percent=i_takeProfitQty, comment='Close-Sell-Profit') // ########################################### Trade Statements Using When - Alternative method ################################################/ // //Cancen pending orders when market changes its bias // strategy.cancel("Long", when=shortBias) // strategy.cancel("Short", when=longBias) // //Close existing trades when market changes its bias // strategy.close("Long", when=shortBias) // strategy.close("Short", when=longBias) // //Market orders when Entry Type = Market // strategy.entry("Long", strategy.long, when=longBias and buyMarketCondition, comment = "Long-Market-Order") // strategy.entry("Short", strategy.short, when=shortBias and sellMarketCondition, comment = "Short-Market-Order") // //Stop orders when Entry Type = Stop (Buy at higher price and sell at lower price) - suitable for trend following methods // strategy.entry("Long", strategy.long, when=longBias and buySellStopCondition, stop=buyLevel, // oca_name="oca_buy", oca_type=strategy.oca.cancel, comment = "Long-Stop-Order") // strategy.entry("Short", strategy.short, when=shortBias and buySellStopCondition, stop=sellLevel, // oca_name="oca_sell", oca_type=strategy.oca.cancel, comment = "Short-Stop-Order") // //Limit orders when Entry Type = Limit // strategy.entry("Long", strategy.long, when=longBias and buyLimitCondition, limit=buyLevel, // oca_name="oca_buy", oca_type=strategy.oca.cancel, comment = "Long-Limit-Order") // strategy.entry("Short", strategy.short, when=shortBias and sellLimitCondition, stop=sellLevel, // oca_name="oca_sell", oca_type=strategy.oca.cancel, comment = "Short-Limit-Order") // //Stop-limit orders when Entry Type = Stop-Limit (Buy at higher price and sell at lower price but with protection) - suitable for trend following methods // strategy.entry("Long", strategy.long, when=longBias and buyStopLimitCondition, limit=buyStopLimit, stop=buyLevel, // oca_name="oca_buy", oca_type=strategy.oca.cancel, comment = "Long-Stop-Limit-Order") // strategy.entry("Short", strategy.short, when=shortBias and sellStopLimitCondition, limit=sellStopLimit, stop=sellLevel, // oca_name="oca_sell", oca_type=strategy.oca.cancel, comment = "Short-Stop-Limit-Order") // // Stoploss - Exit by market // strategy.close("Long", when=closeBuyCondition and closeBuyMarketCondition, comment="Close-Long-Market") // strategy.close("Short", when=closeSellCondition and closeSellMarketCondition, comment="Close-Short-Market") // // Stoploss - Exit by stop // strategy.exit("StopLong", "Long", stop=closeBuyStop, when=closeBuyCondition and closeBuySellStopCondition, comment="Close-Buy-Stop") // strategy.exit("StopShort", "Short", stop=closeSellStop, when=closeSellCondition and closeBuySellStopCondition, comment="Close-Sell-Stop") // // Take Profit // strategy.exit("ProfitLong", "Long", limit=profitLong, when=takeProfitBuyCondition, qty_percent=i_takeProfitQty, comment="Close-Buy-Profit") // strategy.exit("ProfitShort", "Short", limit=profitShort, when=takeProfitSellCondition, qty_percent=i_takeProfitQty, comment="Close-Sell-Profit")
Forex Scalping 1min Bollinger Bands, RSI and ADX Trading System
https://www.tradingview.com/script/sR1hePBi-Forex-Scalping-1min-Bollinger-Bands-RSI-and-ADX-Trading-System/
exlux99
https://www.tradingview.com/u/exlux99/
961
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © exlux99 //@version=4 strategy("Bollinger Bands, RSI and ADX Trading System", overlay=true) timeinrange(res, sess) => time(res, sess) != 0 timer = color.red //bgcolor(timeinrange(timeframe.period, "0300-0600") or timeinrange(timeframe.period, "0900-1300") or timeinrange(timeframe.period, "2030-2300") ? timer : na, transp=70) //RSI length = input( 20 ) overSold = input( 35 ) overBought = input( 65 ) price = close vrsi = rsi(price, length) co = crossover(vrsi, overSold) cu = crossunder(vrsi, overBought) //if (not na(vrsi)) //BB lengthB = input(60, minval=1) src = input(close, title="Source") mult = input(2.0, minval=0.001, maxval=50, title="StdDev") basis = sma(src, lengthB) dev = mult * stdev(src, lengthB) upper = basis + dev lower = basis - dev //adx adxlen = input(14, title="ADX Smoothing") dilen = input(14, title="DI Length") dirmov(len) => up = change(high) down = -change(low) plusDM = na(up) ? na : (up > down and up > 0 ? up : 0) minusDM = na(down) ? na : (down > up and down > 0 ? down : 0) truerange = rma(tr, len) plus = fixnan(100 * rma(plusDM, len) / truerange) minus = fixnan(100 * rma(minusDM, len) / truerange) [plus, minus] adx(dilen, adxlen) => [plus, minus] = dirmov(dilen) sum = plus + minus adx = 100 * rma(abs(plus - minus) / (sum == 0 ? 1 : sum), adxlen) sig = adx(dilen, adxlen) longEntry = close < upper and crossover(vrsi,overSold) and sig < 32 //and (timeinrange(timeframe.period, "0301-0600") or timeinrange(timeframe.period, "0901-1300") or timeinrange(timeframe.period, "2031-2300")) shortEntry = close > upper and crossunder(vrsi,overBought) and sig < 32 //and (timeinrange(timeframe.period, "0301-0600") or timeinrange(timeframe.period, "0901-1300") or timeinrange(timeframe.period, "2031-2300")) tp=input(90, step=10) sl=input(90, step=10) strategy.entry("long",1,when=longEntry) strategy.exit("X_long", "long", profit=tp, loss=sl ) strategy.close("long",when=crossunder(close,basis)) strategy.entry('short',0,when=shortEntry) strategy.exit("x_short", "short",profit=tp, loss=sl) strategy.close("short",when=crossover(close,basis))
Rebalancing
https://www.tradingview.com/script/hKwtzj9w-Rebalancing/
Wilson-IV
https://www.tradingview.com/u/Wilson-IV/
114
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © Wilson-IV //@version=5 strategy("Rebalancing", initial_capital = 1000, currency = currency.USD, format = format.price, default_qty_type = strategy.cash, pyramiding = 20, commission_type = strategy.commission.percent, commission_value = 0.1, precision = 7, max_labels_count = 500, max_bars_back = 5000, process_orders_on_close = true, calc_on_order_fills = false, calc_on_every_tick = false, overlay = true) // ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ // ------------------------------------------------------------------------------ //=============================================================================== // --- Discription --- //=============================================================================== // Strategy name : Rebalancing // Developer : Wilson-IV // Rebalancing Type : Dual coin // Rebalancing Modes : Periodic, Treshold // Rebalancing Composition Types : Equal, Proportion // Rebalancing Exchanges available : Binance, Coinbase, KuCoin, Kraken // Rebalancing Base currencies : BTC, USDT // Rebalancing Mian currencies : ALL // Rebalancing Library available : Yes // Change log: // ----------------------------------------------------------------------------- // Version 1.0 // - Initial release // Version 1.1 // - Pyramiding set to 25 // - Using the correct qty now in List of trades // Version 1.2 // - FTX Exchange added // - Main currencie as variable(no need to select currency from list anymore) //=============================================================================== //=== Import Libraries === //=============================================================================== import Wilson-IV/Library_All_In_One/1 as _lib //=============================================================================== //=== Tooltips, Group- and Inline names === //=============================================================================== // --- Inline --- inline_Date = "Date" // --- Group names --- group_Starting_date = "Starting date" group_Settings = "Settings" group_Investment = "Investment" group_Portfolio = "Portfolio" // --- Tooltips --- tooltip_Frequency = "Every 1 hour, 2 hour, 3 hour, ... , daily, weekly and monthly. Note: Rebalance will take place at midnight 0:00 O`clock if Daily, Weekly or Monthly is selected." tooltip_Exchange_Min_Trade_value = "This is the minimum value the trade must have to be executed by the Exchange. Anything below this value will not be executed." tooltip_Exchange = "Exchange of your choice." tooltip_Proportion = "Equal is 50% main currency vs 50% base currency, while Proportional is X% main currency vs. (100 - X) % base currency." tooltip_Mode = "Periodic: the tradingbot will check for the proportion then rebalance after a fixed interval. \n\nTreshold: rebalancing will take place when the proportion of one or both the currenciess crosses outside the bounds of their desired proportion/allocations." tooltip_Treshold = "The percentage the proportion may deviate from the initial proportion. If one of the currencies reaches outside this boundary, the rebalance will take place.\n\nNote: This only happens when rebalance mode is set to 'Treshold'." tooltip_Initial_Investment = "Initial capital." tooltip_Show_Potential_Rebalance_Momentum = "Show the bars where a potential rebalance momentum may take place." //=============================================================================== //=== Backtest date settings === //=============================================================================== startDate = input.int(title = "Start Date" , defval = 1 , minval = 1 , maxval = 31 , group = group_Starting_date , inline = inline_Date) startMonth = input.int(title = "Start Month" , defval = 10 , minval = 1 , maxval = 12 , group = group_Starting_date , inline = inline_Date) startYear = input.int(title = "Start Year" , defval = 2021 , minval = 1800 , maxval = 2100 , group = group_Starting_date , inline = inline_Date) startHour = input.int(title = "Start Hour" , defval = 0 , minval = 0 , maxval = 23 , group = group_Starting_date , inline = inline_Date) startMinute = input.int(title = "Start Minute" , defval = 0 , minval = 0 , maxval = 59 , group = group_Starting_date , inline = inline_Date) startGMT = input.int(title = "GMT + " , defval = 2 , minval = 0 , maxval = 12 , group = group_Starting_date , inline = inline_Date) //=== Start date for Backtesting [Change the GMT setting for your country. E.g.: Amsterdam is GMT+2] === Start_backtest = time >= timestamp(("GMT+" + str.tostring(startGMT)), startYear, startMonth, startDate, startHour, startMinute) ? true : false //=============================================================================== //=== Variables === //=============================================================================== //=== APR === var dbl_APR = 0. //=== Determine when to rebalance === bln_Potential_Rebalance_Momentum = false bln_Rebalance_Momentum = false //=== Determine when Treshold has been reached === bln_Rebalance_Treshold_Reached = false //=== Buying or selling === blnBuy = false blnSell = false //=============================================================================== //=== Settings === //=============================================================================== //=== Exchange === options_Exchange = input.string(title = "Exchange" , defval = "BINANCE" , tooltip = tooltip_Exchange , group = group_Settings , options = ["BINANCE", "COINBASE", "FTX", "KUCOIN", "KRAKEN"]) //=== Exchange minimum trade value for trading === options_Exchange_Min_Trade_value = input.float (title = "Minimum trade value" , defval = 10 , tooltip = tooltip_Exchange_Min_Trade_value , group = group_Settings , minval = 10 , maxval = 1000 , step = 1) //=== Frequency === options_Rebalancing_Frequency = input.string(title = "Frequency" , defval = "1 Hour" , tooltip = tooltip_Frequency , group = group_Settings , options = ["1 Hour", "2 Hour", "3 Hour", "4 Hour", "6 Hour", "8 Hour", "12 Hour", "Daily", "Weekly", "Monthly"]) //=== Composition === options_Rebalancing_Composition = input.string(title = "Composition" , defval = "Proportion" , tooltip = tooltip_Proportion , group = group_Settings , options = ["Equal", "Proportion"] ) //=== Mode === options_Rebalancing_Mode = input.string(title = "Mode" , defval = "Treshold" , tooltip = tooltip_Mode , group = group_Settings , options = ["Periodic", "Treshold"]) //=== Treshold === dbl_Rebalancing_Treshold = input.float (title = "Treshold" , defval = 0.5 , tooltip = tooltip_Treshold , group = group_Settings , minval = 0.25 , maxval = 10 , step = 0.25) * 0.01 //=== Show Potential Rebalance Momentum? === blnShow_Potential_Rebalance_Momentum = input.bool (title = "Show Potential Rebalance Momentum?" , defval = true , tooltip = tooltip_Show_Potential_Rebalance_Momentum , group = group_Settings) //=== Rebalance will take place at midnight 0:00 O`clock if "Daily", "Weekly" or "Monthly" is selected === bln_Midnight = hour(time) == 0 and minute(time) == 0 ? true : false //=== Timeframe === if Start_backtest if options_Rebalancing_Frequency == "1 Hour" if timeframe.period == "60" bln_Potential_Rebalance_Momentum := true if options_Rebalancing_Frequency == "2 Hour" if timeframe.period == "120" bln_Potential_Rebalance_Momentum := true if options_Rebalancing_Frequency == "3 Hour" if timeframe.period == "180" bln_Potential_Rebalance_Momentum := true if options_Rebalancing_Frequency == "4 Hour" if timeframe.period == "240" bln_Potential_Rebalance_Momentum := true if options_Rebalancing_Frequency == "6 Hour" if timeframe.period == "360" bln_Potential_Rebalance_Momentum := true if options_Rebalancing_Frequency == "8 Hour" if timeframe.period == "480" bln_Potential_Rebalance_Momentum := true if options_Rebalancing_Frequency == "12 Hour" if timeframe.period == "720" bln_Potential_Rebalance_Momentum := true if options_Rebalancing_Frequency == "Daily" and bln_Midnight if timeframe.isdaily bln_Potential_Rebalance_Momentum := true else if options_Rebalancing_Frequency == "Weekly" and bln_Midnight if timeframe.isweekly bln_Potential_Rebalance_Momentum := true else if options_Rebalancing_Frequency == "Monthly" and bln_Midnight if timeframe.ismonthly bln_Potential_Rebalance_Momentum := true //=============================================================================== //=== Investment === //=============================================================================== //=== Initial Investment === var dbl_Initial_Investment = input.float(title = "Initial Investment" , defval = 2000 , minval = 0 , step = 10 , tooltip = tooltip_Initial_Investment , group = group_Investment) //=============================================================================== //=== Portfolio === //=============================================================================== //=== Base currency === options_Base_currency = input.string(title = "Base currency" , defval = "USDT" , options = ["BTC", "USDT"] , group = group_Portfolio) //=== Main currency === str_Basecurrency = syminfo.basecurrency //=== Security of the selected Base currency === str_Security_Base_Currency = options_Base_currency != "USDT" ? options_Exchange + ":" + options_Base_currency + "USDT" : "" //=== Source of the selected Base currency === dbl_Base_Currency_Source = options_Base_currency == "USDT" ? 1 : request.security(str_Security_Base_Currency , timeframe.period, close) //=== Security of the selected Main currency === str_Security_Main_Currency = str_Basecurrency != options_Base_currency ? options_Exchange + ":" + str_Basecurrency + options_Base_currency : "" //=== Source of the selected Main currency === dbl_Main_Currency_Source = str_Basecurrency == options_Base_currency ? 1 : request.security(str_Security_Main_Currency , timeframe.period, close) //=============================================================================== //=== Proportion of the coins === //=============================================================================== //=== Initial Balance which changes during rebalancing === var dbl_Balance = 0. //=== Snapshot of the Balance === var dbl_Balance_Snapshot = 0. //=== Quantity of coins === var dbl_Base_Currency_qty_of_coins = 0. var dbl_Main_Currency_qty_of_coins = 0. //=== Quantity of coins to buy or sell === var dbl_Base_Currency_qty_of_coins_to_buy_or_sell = 0. var dbl_Main_Currency_qty_of_coins_to_buy_or_sell = 0. //=== Value of the coins to buy or sell === var dbl_Base_Currency_value_of_coins_to_buy_or_sell = 0. var dbl_Main_Currency_value_of_coins_to_buy_or_sell = 0. //=== Proportion in (%) === dbl_Proportion_Base_currency = input.float(title = "Proportion(%) Base currency", defval = 10.0, minval = 0, maxval = 100, step = 1, group = "Proportion") * 0.01 dbl_Proportion_Main_currency = input.float(title = "Proportion(%) Main currency", defval = 90.0, minval = 0, maxval = 100, step = 1, group = "Proportion") * 0.01 //=== Current Proportion in (%) === dbl_Proportion_Base_currency_Current = 0. dbl_Proportion_Main_currency_Current = 0. //=============================================================================== //=== Rebalance === //=============================================================================== //=== Rebalance only when 2 different coins are selected and the sum of the proportions is equal to 100% === bln_Rebalance = (str_Basecurrency != options_Base_currency ? true : false) and (dbl_Proportion_Main_currency + dbl_Proportion_Base_currency == 1) if bln_Rebalance //=== Overrides!!! (Override the input values of the proportion if set to Equal) === if options_Rebalancing_Composition == "Equal" dbl_Proportion_Base_currency := 0.5 dbl_Proportion_Main_currency := 0.5 //=== Start Rebalancing procedure === if bln_Potential_Rebalance_Momentum //=== Initial Balance is 0 at the beginning of the strategy === if dbl_Balance == 0 //=== Set Initial Balance equal to the Initial Investment and make a snapshot of it === dbl_Balance := dbl_Initial_Investment dbl_Balance_Snapshot := dbl_Balance //=== First distribution of the coins === dbl_Base_Currency_qty_of_coins := (dbl_Proportion_Base_currency * dbl_Balance) / dbl_Base_Currency_Source dbl_Main_Currency_qty_of_coins := (dbl_Proportion_Main_currency * dbl_Balance) / (dbl_Main_Currency_Source * dbl_Base_Currency_Source) //=== Current Proportion that changes as the price changes during time === dbl_Proportion_Base_currency_Current := (dbl_Base_Currency_qty_of_coins * dbl_Base_Currency_Source) / dbl_Balance dbl_Proportion_Main_currency_Current := (dbl_Main_Currency_qty_of_coins * (dbl_Main_Currency_Source * dbl_Base_Currency_Source)) / dbl_Balance //=== First Rebalance momentum === //=== At this stage the Main coins are being bought for the first time. This moment can be considered as the first rebalancing moment. === bln_Rebalance_Momentum := true else //=== Adjust Balance according the current marketprice of the Main and Base currency === dbl_Balance := (dbl_Base_Currency_qty_of_coins * dbl_Base_Currency_Source) + (dbl_Main_Currency_qty_of_coins * (dbl_Main_Currency_Source * dbl_Base_Currency_Source)) //=== Current Proportion that changes as the price changes during time === dbl_Proportion_Base_currency_Current := (dbl_Base_Currency_qty_of_coins * dbl_Base_Currency_Source) / dbl_Balance dbl_Proportion_Main_currency_Current := (dbl_Main_Currency_qty_of_coins * (dbl_Main_Currency_Source * dbl_Base_Currency_Source)) / dbl_Balance //=== Determine when Treshold has been reached === if options_Rebalancing_Mode == "Treshold" //=== Potentially going SHORT if (dbl_Proportion_Main_currency_Current >= dbl_Proportion_Main_currency + dbl_Rebalancing_Treshold) or (dbl_Proportion_Base_currency_Current <= dbl_Proportion_Base_currency - dbl_Rebalancing_Treshold) bln_Rebalance_Treshold_Reached := true else //=== Potentially going LONG if (dbl_Proportion_Main_currency_Current <= dbl_Proportion_Main_currency - dbl_Rebalancing_Treshold) or (dbl_Proportion_Base_currency_Current >= dbl_Proportion_Base_currency + dbl_Rebalancing_Treshold) bln_Rebalance_Treshold_Reached := true //=== Determine if a rebalance moment should take place === if bln_Rebalance_Treshold_Reached if (math.abs((dbl_Proportion_Main_currency * dbl_Balance) - (dbl_Main_Currency_qty_of_coins * (dbl_Main_Currency_Source * dbl_Base_Currency_Source))) >= options_Exchange_Min_Trade_value) //=== Next Rebalance momentum === bln_Rebalance_Momentum := true //=== Distribution of the coins according to the new adjusted balance === dbl_Base_Currency_qty_of_coins := (dbl_Proportion_Base_currency * dbl_Balance) / dbl_Base_Currency_Source dbl_Main_Currency_qty_of_coins := (dbl_Proportion_Main_currency * dbl_Balance) / (dbl_Main_Currency_Source * dbl_Base_Currency_Source) else if (math.abs((dbl_Proportion_Main_currency * dbl_Balance) - (dbl_Main_Currency_qty_of_coins * (dbl_Main_Currency_Source * dbl_Base_Currency_Source))) >= options_Exchange_Min_Trade_value) and options_Rebalancing_Mode != "Treshold" //=== Next Rebalance momentum === bln_Rebalance_Momentum := true //=== Distribution of the coins according to the new adjusted balance === dbl_Base_Currency_qty_of_coins := (dbl_Proportion_Base_currency * dbl_Balance) / dbl_Base_Currency_Source dbl_Main_Currency_qty_of_coins := (dbl_Proportion_Main_currency * dbl_Balance) / (dbl_Main_Currency_Source * dbl_Base_Currency_Source) //=== Quantity of coins to buy or sell === if dbl_Balance[1] == 0 dbl_Base_Currency_qty_of_coins_to_buy_or_sell := 0 dbl_Main_Currency_qty_of_coins_to_buy_or_sell := 0 dbl_Base_Currency_value_of_coins_to_buy_or_sell := 0 dbl_Main_Currency_value_of_coins_to_buy_or_sell := 0 else dbl_Base_Currency_qty_of_coins_to_buy_or_sell := dbl_Base_Currency_qty_of_coins - dbl_Base_Currency_qty_of_coins[1] dbl_Main_Currency_qty_of_coins_to_buy_or_sell := dbl_Main_Currency_qty_of_coins - dbl_Main_Currency_qty_of_coins[1] dbl_Base_Currency_value_of_coins_to_buy_or_sell := math.abs(dbl_Base_Currency_qty_of_coins_to_buy_or_sell * dbl_Base_Currency_Source) dbl_Main_Currency_value_of_coins_to_buy_or_sell := math.abs(dbl_Main_Currency_qty_of_coins_to_buy_or_sell * (dbl_Main_Currency_Source * dbl_Base_Currency_Source)) //=== Buy or Sell qty of Main currency coins === if bln_Rebalance_Momentum //=== Make a snapshot of the Balance at the moment of the Rebalance momentum dbl_Balance_Snapshot := dbl_Balance //=== Sell Main coins because the price increases if dbl_Main_Currency_qty_of_coins_to_buy_or_sell < 0 blnBuy := false blnSell := true //=== Buy Main coins because the price decreases else if dbl_Main_Currency_qty_of_coins_to_buy_or_sell > 0 blnBuy := true blnSell := false //=== Determine the APR === dbl_APR := dbl_Balance / dbl_Initial_Investment - 1 //=============================================================================== //=== Entries === //=============================================================================== //=== Execute entries === if Start_backtest //=== Show Entries? === if blnBuy strategy.entry("LONG", strategy.long, qty = math.abs(dbl_Main_Currency_qty_of_coins - dbl_Main_Currency_qty_of_coins[1]), limit = close, comment = "Rebalancing") if blnSell strategy.entry("SHORT", strategy.short, qty = math.abs(dbl_Main_Currency_qty_of_coins - dbl_Main_Currency_qty_of_coins[1]), limit = close, comment = "Rebalancing") if bln_Rebalance_Momentum and dbl_Balance[1] == 0 strategy.entry("LONG", strategy.long, qty = math.abs(dbl_Main_Currency_qty_of_coins - dbl_Main_Currency_qty_of_coins[1]), limit = close, comment = "Initial Rebalancing") //=============================================================================== //=== Table === //=============================================================================== intRow = 0 intCol_1_width = 6 intCol_2_width = 6 intCol_3_width = 4 intCol_4_width = 4 var table atrDisplay = table.new(position.middle_right , 4 , 40 , bgcolor = color.gray , frame_width = 1 , frame_color = color.white , border_width = 1 , border_color = color.white) intRow += 1 table.cell(atrDisplay , 0 , intRow , "" , intCol_1_width , 1 , text_color = color.white , bgcolor = color.white) table.cell(atrDisplay , 1 , intRow , "" , intCol_2_width , 1 , text_color = color.white , bgcolor = color.white) intRow += 1 table.cell(atrDisplay , 0 , intRow , "" , intCol_1_width , text_color = color.white , bgcolor = color.blue) table.cell(atrDisplay , 1 , intRow , "Value" , intCol_2_width , text_color = color.white , bgcolor = color.blue) intRow += 1 table.cell(atrDisplay , 0 , intRow , "" , intCol_1_width , 1 , text_color = color.white , bgcolor = color.white) table.cell(atrDisplay , 1 , intRow , "" , intCol_2_width , 1 , text_color = color.white , bgcolor = color.white) intRow += 1 table.cell(atrDisplay , 0 , intRow , "APR" , intCol_1_width , text_color = color.white , bgcolor = color.orange) table.cell(atrDisplay , 1 , intRow , str.tostring(dbl_APR, "0.00%") , intCol_2_width , text_color = color.white , bgcolor = color.green) intRow += 1 table.cell(atrDisplay , 0 , intRow , "" , intCol_1_width , 1 , text_color = color.white , bgcolor = color.white) table.cell(atrDisplay , 1 , intRow , "" , intCol_2_width , 1 , text_color = color.white , bgcolor = color.white) //=============================================================================== //=== Plottings === //=============================================================================== //=== Balance === plot(dbl_Initial_Investment , title = "Initial Investment" , color = color.new(color.yellow, 100)) //=== Balance === plot(dbl_Balance , title = "Balance" , color = color.new(color.green, 100)) //=== APR === plot(100 * dbl_APR , title = "APR" , color = color.new(color.blue, 100)) //=== The moment when potentially the rebalancing will take place === bgcolor(blnShow_Potential_Rebalance_Momentum and bln_Potential_Rebalance_Momentum ? color.new(color.blue, 80) : na , title = "Potential Rebalance momentum") // ------------------------------------------------------------------------------ // ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
Crypto Scalper Divergence Macd Psar Ema 200
https://www.tradingview.com/script/84YDnJ9V-Crypto-Scalper-Divergence-Macd-Psar-Ema-200/
exlux99
https://www.tradingview.com/u/exlux99/
2,350
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © exlux99 //@version=4 strategy(title = "Crypto Scalper", overlay = true, pyramiding=1,initial_capital = 100, 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) len = input(60, minval=1, title="Length EMA") src = input(close, title="Source") out = ema(src, len) // fast_length = input(title="Fast Length MACD", type=input.integer, defval=12) slow_length = input(title="Slow Length MACD", type=input.integer, defval=26) signal_length = input(title="Signal Smoothing", type=input.integer, minval = 1, maxval = 50, defval = 9) sma_source = input(title="Oscillator MA Type MACD", type=input.string, defval="EMA", options=["SMA", "EMA"]) sma_signal = input(title="Signal Line MA Type MACD", type=input.string, defval="EMA", options=["SMA", "EMA"]) // Calculating fast_ma = sma_source == "SMA" ? sma(src, fast_length) : ema(src, fast_length) slow_ma = sma_source == "SMA" ? sma(src, slow_length) : ema(src, slow_length) macd = fast_ma - slow_ma signal = sma_signal == "SMA" ? sma(macd, signal_length) : ema(macd, signal_length) hist = macd - signal start = input(0.02) increment = input(0.02) maximum = input(0.2) var bool uptrend = na var float EP = na var float SAR = na var float AF = start var float nextBarSAR = na if bar_index > 0 firstTrendBar = false SAR := nextBarSAR if bar_index == 1 float prevSAR = na float prevEP = na lowPrev = low[1] highPrev = high[1] closeCur = close closePrev = close[1] if closeCur > closePrev uptrend := true EP := high prevSAR := lowPrev prevEP := high else uptrend := false EP := low prevSAR := highPrev prevEP := low firstTrendBar := true SAR := prevSAR + start * (prevEP - prevSAR) if uptrend if SAR > low firstTrendBar := true uptrend := false SAR := max(EP, high) EP := low AF := start else if SAR < high firstTrendBar := true uptrend := true SAR := min(EP, low) EP := high AF := start if not firstTrendBar if uptrend if high > EP EP := high AF := min(AF + increment, maximum) else if low < EP EP := low AF := min(AF + increment, maximum) if uptrend SAR := min(SAR, low[1]) if bar_index > 1 SAR := min(SAR, low[2]) else SAR := max(SAR, high[1]) if bar_index > 1 SAR := max(SAR, high[2]) nextBarSAR := SAR + AF * (EP - SAR) tplong=input(0.245, step=0.005) sllong=input(1.0, step=0.005) tpshort=input(0.055, step=0.005) slshort=input(0.03, step=0.005) if (uptrend and hist >0 and close < out) strategy.entry("short", strategy.short, stop=nextBarSAR, comment="short") strategy.exit("short_tp/sl", "short", profit=close * tpshort / syminfo.mintick, loss=close * slshort / syminfo.mintick, comment='SHORT EXIT', alert_message = 'closeshort') if (not uptrend and hist <0 and close > out) strategy.entry("long", strategy.long, stop=nextBarSAR, comment="long") strategy.exit("short_tp/sl", "long", profit=close * tplong / syminfo.mintick, loss=close * sllong / syminfo.mintick, comment='LONG EXIT', alert_message = 'closelong')
Correlation Strategy
https://www.tradingview.com/script/gnGcgkLv-Correlation-Strategy/
tweakerID
https://www.tradingview.com/u/tweakerID/
77
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/ // © tweakerID // This is strategy determines a level (expressed in a scale from 1 to 100) of correlation // between security A (user defined) and security B (used on the chart) closing prices. If the correlation // is less than the user defined threshold, a buy signal will be possible. To determine the direction // of the trade we can choose between a Simple Moving Average or a Relative Strength Index indicator, // both with user defined lengths. // WFA Explained // This strategy includes a simple Walk Forward Optimization, which is a technique used to evaluate the robustness // of the strategy. The "in-sample" period is where you should optimize the values of the Strategy Inputs that match the ones in the WFA. // Default value is 1 (or 1/3 of all the candles in the chart). After optimizing the first period, the "All" period can be chosen to evaluate the results of // our "in-sample" optimization in an "out-of-sample" period (="All"-"1"). It is also possible and recommended to optimize // each period (1 and 2) independently and then replace the corresponding values in the WFA section of the inputs panel. // The WFA input is used to make those values effective in their corresponding periods. // More info on WFA: https://en.wikipedia.org/wiki/Walk_forward_optimization //@version=4 strategy("Correlation Strategy", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=10000, commission_value=0.04, calc_on_every_tick=false, slippage=0) direction = input(1, title = "Strategy Direction", type=input.integer, minval=-1, maxval=1) strategy.risk.allow_entry_in(direction == 0 ? strategy.direction.all : (direction < 0 ? strategy.direction.short : strategy.direction.long)) // Bought and Sold Boolean Signal bought = strategy.position_size > strategy.position_size[1] or strategy.position_size < strategy.position_size[1] /////////////////////// STRATEGY INPUTS //////////////////////////////////////// title1=input(true, "-----------------Strategy Inputs-------------------") length=input(11, "Correl Length") symbol=input("BTCUSDTPERP", "Symbol", type=input.symbol) i_smalen=input(14, "SMA Length") i_rsilen=input(14, "RSI Length") OS=input(30) OB=input(70) useRSI=input(false, "Use RSI instead of SMA") i_correl=input(20, "Correlation Threshold", step=10) usesamelen=input(true, "Use Correl Length as SMA/RSI Length") ///////////////////WALK FORWARD ANALYSIS//////////////////////////////////////// title3=input(true, "---------------Walk Forward Analysis----------------") //Total Bars Calc totalbars=input(10000) plot(bar_index, title="Current Bar", transp=100) period1in_start=0 period1in_end=0.5 period1out_start=0.5 period1out_end=0.75 period2in_start=0.25 period2in_end=0.75 period2out_start=0.75 period2out_end=1 pretrade_start=0.5 pretrade_end=1 Period1In=bar_index > (totalbars*period1in_start) and bar_index < (totalbars*period1in_end) Period1Out=bar_index > (totalbars*period1out_start) and bar_index < (totalbars*period1out_end) Period2In=bar_index > (totalbars*period2in_start) and bar_index < (totalbars*period2in_end) Period2Out=bar_index > (totalbars*period2out_start) and bar_index < (totalbars*period2out_end) PreTrade=bar_index > (totalbars*pretrade_start) and bar_index < (totalbars*pretrade_end) PeriodInTest = input(defval="1", type=input.string, title="Select In-Sample", options=['1', '2', 'PreTrade', 'All']) WFAwindowSelector(_strat) => if _strat == '1' Period1In [Period1In] else if _strat == '2' Period2In [Period2In] else if _strat == 'PreTrade' PreTrade [PreTrade] else if _strat == 'All' all=bar_index > 0 and bar_index < (totalbars + 1) [all] else [na] WFA=input(false) if WFA if Period1In or Period1Out p1=input(false, title="1") length:=input(11, "Correl Length") i_correl:=input(20, "Correlation Threshold", step=10) if Period2Out p2=input(false, title="2") length:=input(11, "Correl Length") i_correl:=input(20, "Correlation Threshold", step=10) /////////////////////// BACKTESTER ///////////////////////////////////////////// title2=input(true, "-----------------General Inputs-------------------") // Backtester General Inputs i_SL=input(true, title="Use Stop Loss and Take Profit") TS=input(false, title="Use Trailing Stop") i_SLType=input(defval="ATR Stop", title="Type Of Stop", options=["Strategy Stop", "Swing Lo/Hi", "ATR Stop"]) i_SPL=input(defval=10, title="Swing Point Lookback") i_PercIncrement=input(defval=3, step=.1, title="Swing Point SL Perc Increment")*0.01 i_ATR = input(14, title="ATR Length") i_ATRMult = input(2, step=.1, title="ATR Multiple") i_TPRRR = input(1, step=.1, title="Take Profit Risk Reward Ratio") DPR=input(true, "Allow Stop and Reverse") reverse=input(false, "Reverse Trades") BarsExit=input(false, "Use X Bars Exit") XBars=input(1, minval=1, maxval=50, title="X Bars") // Swing Points Stop and Take Profit SwingStopProfit() => LL=(lowest(i_SPL))*(1-i_PercIncrement) HH=(highest(i_SPL))*(1+i_PercIncrement) LL_price = valuewhen(bought, LL, 0) HH_price = valuewhen(bought, HH, 0) entry_LL_price = strategy.position_size > 0 ? LL_price : na entry_HH_price = strategy.position_size < 0 ? HH_price : na tp=strategy.position_avg_price + (strategy.position_avg_price - entry_LL_price)*i_TPRRR stp=strategy.position_avg_price - (entry_HH_price - strategy.position_avg_price)*i_TPRRR [entry_LL_price, entry_HH_price, tp, stp] // ATR Stop ATRStop() => ATR=atr(i_ATR)*i_ATRMult ATRLong = ohlc4 - ATR ATRShort = ohlc4 + ATR ATRLongStop = valuewhen(bought, ATRLong, 0) ATRShortStop = valuewhen(bought, ATRShort, 0) LongSL_ATR_price = strategy.position_size > 0 ? ATRLongStop : na ShortSL_ATR_price = strategy.position_size < 0 ? ATRShortStop : na ATRtp=strategy.position_avg_price + (strategy.position_avg_price - LongSL_ATR_price)*i_TPRRR ATRstp=strategy.position_avg_price - (ShortSL_ATR_price - strategy.position_avg_price)*i_TPRRR [LongSL_ATR_price, ShortSL_ATR_price, ATRtp, ATRstp] // Strategy Stop StrategyStop() => float LongStop = na float ShortStop = na float StratTP = na float StratSTP = na [LongStop, ShortStop, StratTP, StratSTP] // Random Exit BoughtBarsCount(XBars) => EnoughBars=barssince(bought)==XBars [EnoughBars] //TrailingStop TrailingStop(SL,SSL) => dif=(valuewhen(strategy.position_size>0 and strategy.position_size[1]<=0, high,0)) -strategy.position_avg_price trailOffset = strategy.position_avg_price - SL var tstop = float(na) if strategy.position_size > 0 tstop := high- trailOffset - dif if tstop<tstop[1] tstop:=tstop[1] else tstop := na StrailOffset = SSL - strategy.position_avg_price var Ststop = float(na) Sdif=strategy.position_avg_price-(valuewhen(strategy.position_size<0 and strategy.position_size[1]>=0, low,0)) if strategy.position_size < 0 Ststop := low+ StrailOffset + Sdif if Ststop>Ststop[1] Ststop:=Ststop[1] else Ststop := na [tstop, Ststop] //Stop Loss & Take Profit Switches SLTPLogic(LongStop, ShortStop, StratTP, StratSTP, LongSL_ATR_price, ShortSL_ATR_price, ATRtp, ATRstp, entry_LL_price, entry_HH_price, tp, stp) => SL= i_SLType == "Swing Lo/Hi" ? entry_LL_price : i_SLType == "ATR Stop" ? LongSL_ATR_price : LongStop SSL= i_SLType == "Swing Lo/Hi" ? entry_HH_price : i_SLType == "ATR Stop" ? ShortSL_ATR_price : ShortStop TP= i_SLType == "Swing Lo/Hi" ? tp : i_SLType == "ATR Stop" ? ATRtp : StratTP STP= i_SLType == "Swing Lo/Hi" ? stp : i_SLType == "ATR Stop" ? ATRstp : StratSTP [SL, SSL, TP, STP] /////////////////////// STRATEGY LOGIC ///////////////////////////////////////// security=security(symbol,"", close) correl=correlation(security, close, length)*100 smalen= usesamelen ? length : i_smalen rsi=rsi(close, usesamelen ? length : i_rsilen) plot(correl, transp=100) BUY=correl < i_correl and (useRSI? rsi < OS : close < sma(close, smalen)) SELL=correl < i_correl and (useRSI? rsi > OB : close > sma(close, smalen)) /////////////////////// FUNCTION CALLS ///////////////////////////////////////// // Stops and Profits [entry_LL_price, entry_HH_price, tp, stp] = SwingStopProfit() [LongSL_ATR_price, ShortSL_ATR_price, ATRtp, ATRstp] = ATRStop() [LongStop, ShortStop, StratTP, StratSTP] = StrategyStop() [SL, SSL, TP, STP] = SLTPLogic(LongStop, ShortStop, StratTP, StratSTP, LongSL_ATR_price, ShortSL_ATR_price, ATRtp, ATRstp, entry_LL_price, entry_HH_price, tp, stp) [tstop, Ststop] = TrailingStop(SL,SSL) [window] = WFAwindowSelector(PeriodInTest) [EnoughBars] = BoughtBarsCount(XBars) // Entries if reverse if not DPR and window strategy.entry("long", strategy.long, when=SELL and strategy.position_size == 0) strategy.entry("short", strategy.short, when=BUY and strategy.position_size == 0) else if window strategy.entry("long", strategy.long, when=SELL) strategy.entry("short", strategy.short, when=BUY) else if not DPR and window strategy.entry("long", strategy.long, when=BUY and strategy.position_size == 0) strategy.entry("short", strategy.short, when=SELL and strategy.position_size == 0) else if window strategy.entry("long", strategy.long, when=BUY) strategy.entry("short", strategy.short, when=SELL) // Exits if i_SL and not BarsExit strategy.exit("TP & SL", "long", limit=TP, stop=TS? tstop : SL) strategy.exit("TP & SL", "short", limit=STP, stop=TS? Ststop : SSL) if BarsExit and not i_SL strategy.close_all(when=EnoughBars) /////////////////////// PLOTS ////////////////////////////////////////////////// plot(i_SL and strategy.position_size > 0 and not TS ? SL : i_SL and strategy.position_size > 0 and TS ? tstop : na , title='SL', style=plot.style_cross, color=color.red) plot(i_SL and strategy.position_size < 0 and not TS ? SSL : i_SL and strategy.position_size < 0 and TS ? Ststop : na , title='SSL', style=plot.style_cross, color=color.red) plot(i_SL and strategy.position_size > 0 ? TP : na, title='TP', style=plot.style_cross, color=color.green) plot(i_SL and strategy.position_size < 0 ? STP : na, title='STP', style=plot.style_cross, color=color.green) // Draw price action setup arrows plotshape(BUY ? 1 : na, style=shape.triangleup, location=location.belowbar, color=color.green, title="Bullish Setup", size=size.auto) plotshape(SELL ? 1 : na, style=shape.triangledown, location=location.abovebar, color=color.red, title="Bearish Setup", size=size.auto)
Weis BB Strategy
https://www.tradingview.com/script/KH9pN7dN-Weis-BB-Strategy/
sharatgbhat
https://www.tradingview.com/u/sharatgbhat/
59
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/ // © sharatgbhat //@version=4 strategy("Weis BB Strategy", overlay=false, default_qty_type = strategy.percent_of_equity, default_qty_value = 10,max_lines_count = 500, max_labels_count = 500) maxIdLossPcnt = input(1, "Max Intraday Loss(%)", type=input.float) strategy.risk.max_intraday_loss(maxIdLossPcnt, strategy.percent_of_equity) method = input(defval="ATR", options=["ATR", "Traditional", "Part of Price"], title="Renko Assignment Method") methodvalue = input(defval=14.0, type=input.float, minval=0, title="Value") pricesource = input(defval="Close", options=["Close", "Open / Close", "High / Low"], title="Price Source") useClose = pricesource == "Close" useOpenClose = pricesource == "Open / Close" or useClose useTrueRange = input(defval="Auto", options=["Always", "Auto", "Never"], title="Use True Range instead of Volume") isOscillating = input(defval=false, type=input.bool, title="Oscillating") normalize = input(defval=false, type=input.bool, title="Normalize") vol = useTrueRange == "Always" or useTrueRange == "Auto" and na(volume) ? tr : volume op = useClose ? close : open hi = useOpenClose ? close >= op ? close : op : high lo = useOpenClose ? close <= op ? close : op : low if method == "ATR" methodvalue := atr(round(methodvalue)) if method == "Part of Price" methodvalue := close / methodvalue currclose = float(na) prevclose = nz(currclose[1]) prevhigh = prevclose + methodvalue prevlow = prevclose - methodvalue currclose := hi > prevhigh ? hi : lo < prevlow ? lo : prevclose direction = int(na) direction := currclose > prevclose ? 1 : currclose < prevclose ? -1 : nz(direction[1]) directionHasChanged = change(direction) != 0 directionIsUp = direction > 0 directionIsDown = direction < 0 barcount = 1 barcount := not directionHasChanged and normalize ? barcount[1] + barcount : barcount vol := not directionHasChanged ? vol[1] + vol : vol res = barcount > 1 ? vol / barcount : vol plot(isOscillating and directionIsDown ? -res : res, style=plot.style_columns, color=directionIsUp ? color.green : color.red, transp=75, linewidth=3, title="Wave Volume") length = input(14, minval=1) src = input(close, title="Source") mult = input(2, minval=0.001, maxval=50, title="StdDev") basis = sma(src, length) dev = mult * stdev(src, length) upper = basis + dev lower = basis - dev offset = input(0, "Offset", type = input.integer, 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)) MomentumBull = close>upper MomentumBear = close<lower if (MomentumBull and directionIsUp) strategy.entry("Buy", strategy.long) if (MomentumBear and directionIsDown) strategy.entry("Sell", strategy.short) strategy.exit("exit","Buy",when=directionIsDown,qty_percent=100,profit=20,loss=10) strategy.exit("exit","Sell",when=directionIsUp,qty_percent=100,profit=20,loss=10)
Só Trade Top - Média de 8 - Augusto Backes
https://www.tradingview.com/script/cGX0aCYh/
Valente_F
https://www.tradingview.com/u/Valente_F/
655
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/ // © Valente_F //@version=4 strategy("Só Trade Top - Média de 8 - Augusto Backes", overlay=true, max_bars_back = 5000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, initial_capital = 10000, commission_type = strategy.commission.percent, process_orders_on_close = true) tipo_media = input(title="Tipo de Média", defval="EMA", options=["SMA", "EMA"],inline = "3", group = "SETUP MÉDIA DE 8", tooltip = "Média utilizada para os cálculos do Setup") c_media = input(defval = 8, title = "Comprimento", type = input.integer,inline = "3", group = "SETUP MÉDIA DE 8") cb_raro = input(true, title="Habilitar Sinal Raro", group = "SETUP MÉDIA DE 8", tooltip = "Sinais normais são caracterizados por Engolfos, Martelos e Preço de Fechamento de Reversão com FECHAMENTO acima da Média de 8. Sinais Raros são caracterizados pelas mesmas figuras, mas com FECHAMENTO e ABERTURA acima da média de 8. O mesmo vale para sinais de venda.") media8 = tipo_media == "SMA" ? security(syminfo.tickerid, "1W", sma(close[1], c_media)) : security(syminfo.tickerid, "1W", ema(close[1], c_media)) plot(media8, title = "Média", color = color.green, linewidth = 2) lookback_swing=5 candle_engolfo = (close > open and close[1] < open[1] and close >= open[1] and open <= close[1] ) and close>media8 candle_martelo = 2*abs(close-open) < (min(close, open)-low) and (high - max(close, open)) < abs(close-open) and close>open and close>media8 candle_fr = low < low[1] and low < low[2] and close > close[1] and close > open and close>media8 compra = (candle_engolfo or candle_martelo or candle_fr) vcandle_engolfo = (close < open and close[1] > open[1] and close <= open[1] and open >= close[1]) and close<media8 vcandle_martelo = 2*abs(close-open) < (high-max(close, open)) and (min(close, open)-low) < abs(close-open) and close<open and close<media8 vcandle_fr = high > high[1] and high > high[2] and close < close[1] and close < open and close<media8 venda = (vcandle_engolfo or vcandle_martelo or vcandle_fr) if cb_raro compra := compra and open > media8 venda := venda and open <media8 else compra := compra venda := venda barcolor(compra and strategy.position_size==0?color.green:venda and strategy.position_size>0?color.red : color.new(color.black, 100)) plotshape(compra and candle_engolfo and strategy.position_size==0, title = "Engolfo de Alta", style = shape.labeldown, color = color.green, text = "Engolfo de Alta", textcolor = color.white) plotshape(compra and candle_martelo and strategy.position_size==0, title = "Martelo de Alta", style = shape.labeldown, color = color.green, text = "Martelo de Alta", textcolor = color.white) plotshape(compra and candle_fr and strategy.position_size==0, title = "PFR de Alta", style = shape.labeldown, color = color.green, text = "PFR de Alta", textcolor = color.white) plotshape(venda and vcandle_engolfo and strategy.position_size>0, title = "Engolfo de Baixa", style = shape.labelup, location = location.belowbar, color = color.red, text = "Engolfo de Baixa", textcolor = color.white) plotshape(venda and vcandle_martelo and strategy.position_size>0, title = "Martelo de Baixa", style = shape.labelup, location = location.belowbar, color = color.red, text = "Martelo de Baixa", textcolor = color.white) plotshape(venda and vcandle_fr and strategy.position_size>0, title = "PFR de Baixa", style = shape.labelup, location = location.belowbar, color = color.red, text = "PFR de Baixa", textcolor = color.white) strategy.entry("Compra", true, when = compra) strategy.close("Compra", when = venda)
DMI + HMA - No Risk Management
https://www.tradingview.com/script/L306HHgg-DMI-HMA-No-Risk-Management/
Tuned_Official
https://www.tradingview.com/u/Tuned_Official/
235
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © Tuned_Official //@version=4 strategy(title="DMI + HMA - No Risk Management", overlay = false, pyramiding=1, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=0.025) //Inputs hullLen1 = input(title="Hull 1 length", type=input.integer, defval=29) hullLen2 = input(title="Hull 2 length", type=input.integer, defval=2) len = input(title="Length for DI", type=input.integer, defval=76) //Calculations TrueRange = max(max(high-low, abs(high-nz(close[1]))), abs(low-nz(close[1]))) DirectionalMovementPlus = high-nz(high[1]) > nz(low[1])-low ? max(high-nz(high[1]), 0): 0 DirectionalMovementMinus = nz(low[1])-low > high-nz(high[1]) ? max(nz(low[1])-low, 0): 0 SmoothedTrueRange = 0.0 SmoothedTrueRange := nz(SmoothedTrueRange[1]) - (nz(SmoothedTrueRange[1])/len) + TrueRange SmoothedDirectionalMovementPlus = 0.0 SmoothedDirectionalMovementPlus := nz(SmoothedDirectionalMovementPlus[1]) - (nz(SmoothedDirectionalMovementPlus[1])/len) + DirectionalMovementPlus SmoothedDirectionalMovementMinus = 0.0 SmoothedDirectionalMovementMinus := nz(SmoothedDirectionalMovementMinus[1]) - (nz(SmoothedDirectionalMovementMinus[1])/len) + DirectionalMovementMinus //Indicators fasthull = hma(close, hullLen1) slowhull = hma(close, hullLen2) DIPlus = SmoothedDirectionalMovementPlus / SmoothedTrueRange * 100 DIMinus = SmoothedDirectionalMovementMinus / SmoothedTrueRange * 100 DX = abs(DIPlus-DIMinus) / (DIPlus+DIMinus)*100 ADX = sma(DX, len) //Plots plot(DIPlus, color=color.green, title="DI+") plot(DIMinus, color=color.red, title="DI-") plot(ADX, color=color.black, title="ADX") //conditions go_long = crossover(DIPlus, DIMinus) and fasthull > slowhull //crossover(fasthull, slowhull) and DIPlus > DIMinus go_short = crossover(DIMinus, DIPlus) and fasthull < slowhull //crossunder(fasthull, slowhull) and DIMinus > DIPlus //Entry if strategy.position_size < 0 or strategy.position_size == 0 strategy.order("long", strategy.long, when=go_long) if strategy.position_size > 0 or strategy.position_size == 0 strategy.order("Short", strategy.short, when=go_short)
Weis Chop Strategy
https://www.tradingview.com/script/MRmQZwyK-Weis-Chop-Strategy/
sharatgbhat
https://www.tradingview.com/u/sharatgbhat/
78
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/ // © sharatgbhat //@version=4 strategy("Weis Chop Strategy", overlay=false, default_qty_type = strategy.percent_of_equity, default_qty_value = 10,max_lines_count = 500, max_labels_count = 500) maxIdLossPcnt = input(1, "Max Intraday Loss(%)", type=input.float) strategy.risk.max_intraday_loss(maxIdLossPcnt, strategy.percent_of_equity) method = input(defval="ATR", options=["ATR", "Traditional", "Part of Price"], title="Renko Assignment Method") methodvalue = input(defval=14.0, type=input.float, minval=0, title="Value") pricesource = input(defval="Close", options=["Close", "Open / Close", "High / Low"], title="Price Source") useClose = pricesource == "Close" useOpenClose = pricesource == "Open / Close" or useClose useTrueRange = input(defval="Auto", options=["Always", "Auto", "Never"], title="Use True Range instead of Volume") isOscillating = input(defval=false, type=input.bool, title="Oscillating") normalize = input(defval=false, type=input.bool, title="Normalize") vol = useTrueRange == "Always" or useTrueRange == "Auto" and na(volume) ? tr : volume op = useClose ? close : open hi = useOpenClose ? close >= op ? close : op : high lo = useOpenClose ? close <= op ? close : op : low if method == "ATR" methodvalue := atr(round(methodvalue)) if method == "Part of Price" methodvalue := close / methodvalue currclose = float(na) prevclose = nz(currclose[1]) prevhigh = prevclose + methodvalue prevlow = prevclose - methodvalue currclose := hi > prevhigh ? hi : lo < prevlow ? lo : prevclose direction = int(na) direction := currclose > prevclose ? 1 : currclose < prevclose ? -1 : nz(direction[1]) directionHasChanged = change(direction) != 0 directionIsUp = direction > 0 directionIsDown = direction < 0 barcount = 1 barcount := not directionHasChanged and normalize ? barcount[1] + barcount : barcount vol := not directionHasChanged ? vol[1] + vol : vol res = barcount > 1 ? vol / barcount : vol plot(isOscillating and directionIsDown ? -res : res, style=plot.style_columns, color=directionIsUp ? color.green : color.red, transp=75, linewidth=3, title="Wave Volume") length = input(14, minval=1) ci = 100 * log10(sum(atr(1), length) / (highest(length) - lowest(length))) / log10(length) offset = input(0, "Offset", type = input.integer, minval = -500, maxval = 500) plot(ci, "CHOP", color=#2962FF, offset = offset) band1 = hline(61.8, "Upper Band", color=#787B86, linestyle=hline.style_dashed) band0 = hline(38.2, "Lower Band", color=#787B86, linestyle=hline.style_dashed) fill(band1, band0, color = color.rgb(33, 150, 243, 90), title = "Background") MomentumBull = close>ema(close,8) MomentumBear = close<ema(close,8) Tradecon = crossunder(ci,61.8) if (MomentumBull and directionIsUp and Tradecon) strategy.entry("Buy", strategy.long) if (MomentumBear and directionIsDown and Tradecon ) strategy.entry("Sell", strategy.short) strategy.exit("exit","Buy",when=directionIsDown,qty_percent=100,profit=20,loss=10) strategy.exit("exit","Sell",when=directionIsUp,qty_percent=100,profit=20,loss=10)
[KL] Relative Volume + ATR Strategy
https://www.tradingview.com/script/e1iapmtK-KL-Relative-Volume-ATR-Strategy/
DojiEmoji
https://www.tradingview.com/u/DojiEmoji/
258
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © DojiEmoji (kevinhhl) //@version=4 strategy("[KL] Relative Volume + ATR Strategy",overlay=true,pyramiding=1) ENUM_LONG = "Long" // Timeframe { backtest_timeframe_start = input(defval = timestamp("01 Apr 2016 13:30 +0000"), title = "Backtest Start Time", type = input.time) USE_ENDTIME = input(false,title="Define backtest end-time (If false, will test up to most recent candle)") backtest_timeframe_end = input(defval = timestamp("01 May 2021 19:30 +0000"), title = "Backtest End Time (if checked above)", type = input.time) within_timeframe = time >= backtest_timeframe_start and (time <= backtest_timeframe_end or not USE_ENDTIME) // } len_volat = input(14,title="Length of ATR to determine volatility") ATR_volat = atr(len_volat) avg_ATR_volat = sma(ATR_volat, len_volat) std_ATR_volat = stdev(ATR_volat, len_volat) // } // Trailing stop loss { ATR_X2_TSL = atr(input(14,title="Length of ATR for trailing stop loss")) * input(2.0,title="ATR Multiplier for trailing stop loss",type=input.float) TSL_source = low var stop_loss_price = float(0) TSL_line_color = color.green, TSL_transp = 100 if strategy.position_size == 0 or not within_timeframe TSL_line_color := color.black stop_loss_price := TSL_source - ATR_X2_TSL else if strategy.position_size > 0 stop_loss_price := max(stop_loss_price, TSL_source - ATR_X2_TSL) TSL_transp := 0 plot(stop_loss_price, color=color.new(TSL_line_color, TSL_transp)) // } // Signals for entry { _avg_vol = sma(volume,input(20, title="SMA(volume) length (for relative comparison)")) _relative_vol = _avg_vol * input(1.5,title="Multiple of avg vol to consider relative volume as being high",type=input.float) entry_signal1 = volume > _relative_vol entry_signal2 = ATR_volat < avg_ATR_volat + std_ATR_volat and ATR_volat > avg_ATR_volat - std_ATR_volat USE_DRIFT = input(true,title="Use drift to determine uptrend") len_drift = input(50,title="Length of Drift") percentage_chng = log(close/close[1]) drift = sma(percentage_chng, len_drift) - pow(stdev(percentage_chng, len_drift),2)*0.5 entry_signal3 = drift > drift[1] or not USE_DRIFT // } alert_per_bar(msg)=> prefix = "[" + syminfo.root + "] " suffix = "(P=" + tostring(close) + "; atr=" + tostring(ATR_volat) + ")" alert(tostring(prefix) + tostring(msg) + tostring(suffix), alert.freq_once_per_bar) // MAIN: if within_timeframe if strategy.position_size > 0 and strategy.position_size[1] > 0 and (stop_loss_price/stop_loss_price[1]-1) > 0.005 alert_per_bar("TSL raised to " + tostring(stop_loss_price)) exit_msg = close <= strategy.position_avg_price ? "stop loss" : "take profit" // EXIT: if strategy.position_size > 0 and TSL_source <= stop_loss_price strategy.close(ENUM_LONG, comment=exit_msg) // ENTRY: else if (strategy.position_size == 0 or (strategy.position_size > 0 and close > stop_loss_price)) and entry_signal1 and entry_signal2 and entry_signal3 entry_msg = strategy.position_size > 0 ? "adding" : "initial" strategy.entry(ENUM_LONG, strategy.long, comment=entry_msg) // CLEAN UP: if strategy.position_size == 0 stop_loss_price := float(0)
Swing VWAP Weekly Stock and Crypto Strategy
https://www.tradingview.com/script/SFutz9UN-Swing-VWAP-Weekly-Stock-and-Crypto-Strategy/
exlux99
https://www.tradingview.com/u/exlux99/
167
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © exlux99 //@version=4 strategy(title = "Swing VWAP Weekly Strategy", overlay = true, pyramiding=1,initial_capital = 100, 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) vwapweekly= security(syminfo.tickerid, "W", vwap) long=( close > vwapweekly) short=( close < vwapweekly) strategy.entry("long", strategy.long,when=long, comment = "long") strategy.close("long",when=close < vwapweekly or vwapweekly[1] > vwapweekly) strategy.entry("short", strategy.short,when=short, comment = "short") strategy.close("short",when=close > vwapweekly or vwapweekly > vwapweekly[1])
Full Crypto Swing Strategy ALMA Cross with MACD
https://www.tradingview.com/script/P45pt9mA-Full-Crypto-Swing-Strategy-ALMA-Cross-with-MACD/
exlux99
https://www.tradingview.com/u/exlux99/
196
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © exlux99 //@version=4 strategy(title = "Full Crypto Swing Strategy ALMA Cross", overlay = true, pyramiding=1,initial_capital = 1, 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) //time condition fromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31) fromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12) fromYear = input(defval = 2010, title = "From Year", minval = 1970) //monday and session // To Date Inputs toDay = input(defval = 31, title = "To Day", minval = 1, maxval = 31) toMonth = input(defval = 12, title = "To Month", minval = 1, maxval = 12) toYear = input(defval = 2021, title = "To Year", minval = 1970) startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00) finishDate = timestamp(toYear, toMonth, toDay, 00, 00) time_cond = time >= startDate and time <= finishDate UseHAcandles = input(false, title="Use Heikin Ashi Candles in Algo Calculations") haClose = UseHAcandles ? security(heikinashi(syminfo.tickerid), timeframe.period, close) : close haOpen = UseHAcandles ? security(heikinashi(syminfo.tickerid), timeframe.period, open) : open haHigh = UseHAcandles ? security(heikinashi(syminfo.tickerid), timeframe.period, high) : high haLow = UseHAcandles ? security(heikinashi(syminfo.tickerid), timeframe.period, low) : low //alma fast and slow src = haClose windowsize = input(title="Length Size Fast", type=input.integer, defval=20) windowsize2 = input(title="Length Size Slow", type=input.integer, defval=40) offset = input(title="Offset", type=input.float, defval=0.9, step=0.05) sigma = input(title="Sigma", type=input.float, defval=5) outfast=alma(src, windowsize, offset, sigma) outslow=alma(src, windowsize2, offset, sigma) //macd fast_length = input(title="Fast Length", type=input.integer, defval=6) slow_length = input(title="Slow Length", type=input.integer, defval=25) signal_length = input(title="Signal Smoothing", type=input.integer, minval = 1, maxval = 50, defval = 9) // Calculating fast_ma = ema(src, fast_length) slow_ma = ema(src, slow_length) macd = fast_ma - slow_ma signal = ema(macd, signal_length) hist = macd - signal long=crossover(outfast,outslow) and hist > hist[1] and time_cond short=crossunder(outfast,outslow) and hist < hist[1] and time_cond takeProfit_long=input(2.0, step=0.005) stopLoss_long=input(0.2, step=0.005) takeProfit_short=input(0.05, step=0.005) stopLoss_short=input(1.0, step=0.005) strategy.entry("long",1,when=long) strategy.entry("short",0,when=short) strategy.exit("short_tp/sl", "long", profit=close * takeProfit_long / syminfo.mintick, loss=close * stopLoss_long / syminfo.mintick, comment='LONG EXIT', alert_message = 'closeshort') strategy.exit("short_tp/sl", "short", profit=close * takeProfit_short / syminfo.mintick, loss=close * stopLoss_short / syminfo.mintick, comment='SHORT EXIT', alert_message = 'closeshort')
Crypto swing correlation RSI and SMA
https://www.tradingview.com/script/ZfjHw7u2-Crypto-swing-correlation-RSI-and-SMA/
exlux99
https://www.tradingview.com/u/exlux99/
210
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © exlux99 //@version=4 strategy(title = "Crypto swing correlation", overlay = true, pyramiding=1,initial_capital = 1, 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) //time fromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31) fromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12) fromYear = input(defval = 2010, title = "From Year", minval = 1970) //monday and session // To Date Inputs toDay = input(defval = 31, title = "To Day", minval = 1, maxval = 31) toMonth = input(defval = 12, title = "To Month", minval = 1, maxval = 12) toYear = input(defval = 2021, title = "To Year", minval = 1970) startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00) finishDate = timestamp(toYear, toMonth, toDay, 00, 00) time_cond = time >= startDate and time <= finishDate useCorrelation = input(true, title="Use Correlation candles?") symbol = input("CRYPTOCAP:TOTAL", type=input.symbol) haClose = useCorrelation ? security(symbol, timeframe.period, close) : close haOpen = useCorrelation ? security(symbol, timeframe.period, open) : open haHigh = useCorrelation ? security(symbol, timeframe.period, high) : high haLow = useCorrelation ? security(symbol, timeframe.period, low) : low length = input( 50 ) overSold = input( 51 ) overBought = input( 49 ) s = input(title="Source", defval="haClose", options=["haClose", "haOpen", "haHigh", "haLow"]) price = s == "haClose" ? haClose: s == "haOpen" ? haOpen : s == "haHigh" ? haHigh : s == "haLow" ? haLow : na len = input(8, "Length Moving average", minval=1) src = price ma = sma(src, len) vrsi = rsi(price, length) long = crossover(vrsi, overSold) and time_cond and price > ma short = crossunder(vrsi, overBought) and time_cond and price < ma takeProfit_long=input(1.0, step=0.005) stopLoss_long=input(0.1, step=0.005) takeProfit_short=input(0.05, step=0.005) stopLoss_short=input(0.03, step=0.005) strategy.entry("long",1,when=long) strategy.entry("short",0,when=short) strategy.exit("short_tp/sl", "long", profit=close * takeProfit_long / syminfo.mintick, loss=close * stopLoss_long / syminfo.mintick, comment='LONG EXIT', alert_message = 'closeshort') strategy.exit("short_tp/sl", "short", profit=close * takeProfit_short / syminfo.mintick, loss=close * stopLoss_short / syminfo.mintick, comment='SHORT EXIT', alert_message = 'closeshort')
Aggresive Scalper/Swing Crypto Strategy
https://www.tradingview.com/script/2Rx9y2VQ-Aggresive-Scalper-Swing-Crypto-Strategy/
exlux99
https://www.tradingview.com/u/exlux99/
512
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © exlux99 //@version=4 strategy(title="Crypto Price Scalper", shorttitle="Scalper Crypto", overlay=true) inputcc = input(60, title="Number of candles") low9=lowest(low,inputcc) high9=highest(high,inputcc) plotlow = ((close - low9) / low9) * 100 plothigh = ((close - high9) / high9) * 100 plotg = (plotlow +plothigh)/2 center=0.0 period_ = input(14, title="Length VORTEX", minval=2) VMP = sum( abs( high - low[1]), period_ ) VMM = sum( abs( low - high[1]), period_ ) STR = sum( atr(1), period_ ) VIP = VMP / STR VIM = VMM / STR long= crossover(plotg,center) and close > high[2] and crossover(VIP,VIM) short= crossunder(plotg,center) and crossunder(VIP,VIM) tplong=input(0.1, title="TP Long", step=0.01) sllong=input(0.1, title="SL Long", step=0.01) strategy.entry("long",1,when=long) strategy.exit("closelong", "long" , profit = close * tplong / syminfo.mintick, loss = close * sllong / syminfo.mintick, alert_message = "closelong") strategy.close("long",when=short)
High/Low Channel Multi averages Crypto Swing strategy
https://www.tradingview.com/script/UXKktYt6-High-Low-Channel-Multi-averages-Crypto-Swing-strategy/
exlux99
https://www.tradingview.com/u/exlux99/
613
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © exlux99 //@version=4 strategy(title="High/Low channel swing", shorttitle="Multi MA swing", overlay=true) fromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31) fromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12) fromYear = input(defval = 2000, title = "From Year", minval = 1970) //monday and session // To Date Inputs toDay = input(defval = 31, title = "To Day", minval = 1, maxval = 31) toMonth = input(defval = 12, title = "To Month", minval = 1, maxval = 12) toYear = input(defval = 2021, title = "To Year", minval = 1970) startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00) finishDate = timestamp(toYear, toMonth, toDay, 00, 00) time_cond = time >= startDate and time <= finishDate ////// length_ma= input(defval=12, title="Length Moving averages", minval=1) ////////////////////////////////SETUP/////////////////////////////////////////// sma_high = sma(high, length_ma) ema_high = ema(high, length_ma) wma_high = wma(high, length_ma) alma_high = alma(high,length_ma, 0.85, 6) smma_high = rma(high,length_ma) lsma_high = linreg(high, length_ma, 0) vwma_high = vwma(high,length_ma) avg_high = (sma_high+ema_high+wma_high+alma_high+smma_high+lsma_high+vwma_high)/7 /////////////////////////////////////////// sma_low = sma(low, length_ma) ema_low = ema(low, length_ma) wma_low = wma(low, length_ma) alma_low = alma(low,length_ma, 0.85, 6) smma_low = rma(low,length_ma) lsma_low = linreg(low, length_ma, 0) vwma_low = vwma(low,length_ma) avg_low = (sma_low+ema_low+wma_low+alma_low+smma_low+lsma_low+vwma_low)/7 ////////////////////////////PLOTTING//////////////////////////////////////////// plot(avg_high , title="avg", color=color.green, linewidth = 4) plot(avg_low , title="avg", color=color.red, linewidth = 4) long= close > avg_high short = close < avg_low tplong=input(0.06, title="TP Long", step=0.01) sllong=input(0.05, title="SL Long", step=0.01) tpshort=input(0.045, title="TP Short", step=0.01) slshort=input(0.05, title="SL Short", step=0.01) if(time_cond) strategy.entry("long",1,when=long) strategy.exit("closelong", "long" , profit = close * tplong / syminfo.mintick, loss = close * sllong / syminfo.mintick, alert_message = "closelong") strategy.close("long", when=crossunder(low,avg_low)) strategy.entry("short",0,when=short) strategy.exit("closeshort", "short" , profit = close * tpshort / syminfo.mintick, loss = close * slshort / syminfo.mintick, alert_message = "closeshort") strategy.close("short",when=crossover(high,avg_high))
Swing/Scalper HULL + T3 avg Crypto Strategy
https://www.tradingview.com/script/YgRqvCGx-Swing-Scalper-HULL-T3-avg-Crypto-Strategy/
exlux99
https://www.tradingview.com/u/exlux99/
814
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © exlux99 //@version=4 strategy(title="Swing HULL + T3 avg", shorttitle="Swing HULL T3 AVG", overlay=true) fromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31) fromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12) fromYear = input(defval = 2000, title = "From Year", minval = 1970) //monday and session // To Date Inputs toDay = input(defval = 31, title = "To Day", minval = 1, maxval = 31) toMonth = input(defval = 12, title = "To Month", minval = 1, maxval = 12) toYear = input(defval = 2021, title = "To Year", minval = 1970) startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00) finishDate = timestamp(toYear, toMonth, toDay, 00, 00) time_cond = time >= startDate and time <= finishDate ////////////////////////////GENERAL INPUTS////////////////////////////////////// length_Ma= input(defval=50, title="Length MAs", minval=1) //==========HMA getHULLMA(src, len) => hullma = wma(2*wma(src, len/2)-wma(src, len), round(sqrt(len))) hullma //==========T3 getT3(src, len, vFactor) => ema1 = ema(src, len) ema2 = ema(ema1,len) ema3 = ema(ema2,len) ema4 = ema(ema3,len) ema5 = ema(ema4,len) ema6 = ema(ema5,len) c1 = -1 * pow(vFactor,3) c2 = 3*pow(vFactor,2) + 3*pow(vFactor,3) c3 = -6*pow(vFactor,2) - 3*vFactor - 3*pow(vFactor,3) c4 = 1 + 3*vFactor + pow(vFactor,3) + 3*pow(vFactor,2) T3 = c1*ema6 + c2*ema5 + c3*ema4 + c4*ema3 T3 hullma = getHULLMA(close,length_Ma) t3 = getT3(close,length_Ma,0.7) avg = (hullma+t3) /2 ////////////////////////////PLOTTING//////////////////////////////////////////// colorado = avg > avg[1]? color.green : color.red plot(avg , title="avg", color=colorado, linewidth = 4) long=avg>avg[1] short=avg<avg[1] tplong=input(0.08, title="TP Long", step=0.01) sllong=input(1.0, title="SL Long", step=0.01) tpshort=input(0.03, title="TP Short", step=0.01) slshort=input(0.06, title="SL Short", step=0.01) if(time_cond) strategy.entry("long",1,when=long) strategy.exit("closelong", "long" , profit = close * tplong / syminfo.mintick, loss = close * sllong / syminfo.mintick, alert_message = "closelong") strategy.entry("short",0,when=short) strategy.exit("closeshort", "short" , profit = close * tpshort / syminfo.mintick, loss = close * slshort / syminfo.mintick, alert_message = "closeshort")
Chanu Delta Strategy
https://www.tradingview.com/script/xcOoG6TP/
chanu_lev10k
https://www.tradingview.com/u/chanu_lev10k/
187
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © chanu_lev10k //@version=4 strategy(title="Chanu Delta SL/TP Strategy", overlay=false) // Inputs delta_bull = input(defval=14.9, minval=0.1, type=input.float, step=0.1, title="Delta Bull") delta_bear = input(defval=-17.2, maxval=-0.1, type=input.float, step=0.1, title="Delta Bear") src = input(title="Source", type=input.source, defval=hlc3) res = input(title="Resolution", type=input.resolution, defval="") issl = input(title = "SL", inline = 'linesl1', group = 'Stop Loss / Take Profit:', type = input.bool, defval = false) slpercent = input(title = ", %", inline = 'linesl1', group = 'Stop Loss / Take Profit:', type = input.float, defval = 19, minval=0.0, step=0.1) istp = input(title = "TP", inline = 'linetp1', group = 'Stop Loss / Take Profit:', type = input.bool, defval = false) tppercent = input(title = ", %", inline = 'linetp1', group = 'Stop Loss / Take Profit:', type = input.float, defval = 15.6, minval=0.0, step=0.1) // Delta Definition btcusd = security("BYBIT:BTCUSD", res, src) btcusdt = security("BYBIT:BTCUSDT", res, src) delta = btcusd - btcusdt // Long Short Exit conditions longCondition = crossover(delta, delta_bull) if (longCondition) strategy.entry("Long", strategy.long) shortCondition = crossunder(delta, delta_bear) if (shortCondition) strategy.entry("Short", strategy.short) // Entry price / Take profit / Stop Loss entryprice = strategy.position_avg_price pm = longCondition?1:shortCondition?-1:1/sign(strategy.position_size) takeprofit = entryprice * (1+pm*tppercent*0.01) stoploss = entryprice * (1-pm*slpercent*0.01) strategy.exit(id="Exit Long", from_entry="Long", stop=issl?stoploss:na, limit=istp?takeprofit:na, alert_message="Close Long") strategy.exit(id="Exit Short",from_entry="Short",stop=issl?stoploss:na, limit=istp?takeprofit:na, alert_message="Close Short") // Plots plot(delta, style=plot.style_columns, color=delta > 0 ? color.rgb(38, 166, 154) : color.rgb(239, 83, 80)) bgcolor(color=delta >= delta_bull ? color.new(color.lime, transp=75) : delta <= delta_bear ? color.new(color.red, transp=75) : na) bgcolor(color=(delta > delta_bear) and (delta < delta_bull) ? color.new(color.silver, transp=75) : na) hline(0, linestyle=hline.style_dotted, title="zero line") hline(delta_bull, linestyle=hline.style_dotted, color=color.lime, title="Delta Bull") hline(delta_bear, linestyle=hline.style_dotted, color=color.red, title="Delta Bear")
Time of Day and Day of Week Buying and Selling Strategy
https://www.tradingview.com/script/5s03AEYw-Time-of-Day-and-Day-of-Week-Buying-and-Selling-Strategy/
tormunddookie
https://www.tradingview.com/u/tormunddookie/
75
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ //@version=4 strategy("Timeframe Time of Day and Day of Week Buying and Selling Strategy", overlay=true) frommonth = input(defval = 1, minval = 01, maxval = 12, title = "From Month") fromday = input(defval = 1, minval = 01, maxval = 31, title = "From day") fromyear = input(defval = 2021, minval = 1900, maxval = 2100, title = "From Year") tomonth = input(defval = 12, minval = 01, maxval = 12, title = "To Month") today = input(defval = 31, minval = 01, maxval = 31, title = "To day") toyear = input(defval = 2100, minval = 1900, maxval = 2100, title = "To Year") sun = input(defval=true, title='Sunday', type = input.bool) mon = input(defval=true, title='Monday', type = input.bool) tue = input(defval=true, title='Tueday', type = input.bool) wed = input(defval=true, title='Wednesday', type = input.bool) thu = input(defval=true, title='Thurday', type = input.bool) fri = input(defval=true, title='Friday', type = input.bool) sat = input(defval=true, title='Saturday', type = input.bool) sunFilter = sun and ((dayofweek==7 and hour==23 and minute>30) or (dayofweek==1 and (hour <23 or (hour == 23 and minute<=30)))) monFilter = mon and ((dayofweek==1 and hour==23 and minute>30) or (dayofweek==2 and (hour <23 or (hour == 23 and minute<=30)))) tueFilter = tue and ((dayofweek==2 and hour==23 and minute>30) or (dayofweek==3 and (hour <23 or (hour == 23 and minute<=30)))) wedFilter = wed and ((dayofweek==3 and hour==23 and minute>30) or (dayofweek==4 and (hour <23 or (hour == 23 and minute<=30)))) thuFilter = thu and ((dayofweek==4 and hour==23 and minute>30) or (dayofweek==5 and (hour <23 or (hour == 23 and minute<=30)))) friFilter = fri and ((dayofweek==5 and hour==23 and minute>30) or (dayofweek==6 and (hour <23 or (hour == 23 and minute<=30)))) satFilter = sat and ((dayofweek==6 and hour==23 and minute>30) or (dayofweek==7 and (hour <23 or (hour == 23 and minute<=30)))) dayOfWeekFilter = sunFilter or monFilter or tueFilter or wedFilter or thuFilter or friFilter or satFilter timeframes = array.new_string(48, '') timeframes_options = array.new_string(49, 'None') array.set(timeframes,0,'2330-0000') array.set(timeframes_options,0, input(defval='None', options=['Long','Short','None'], title='0000-0030')) array.set(timeframes,1,'0000-0030') array.set(timeframes_options,1, input(defval='None', options=['Long','Short','None'], title='0030-0100')) array.set(timeframes,2,'0030-0100') array.set(timeframes_options,2, input(defval='None', options=['Long','Short','None'], title='0100-0130')) array.set(timeframes,3,'0100-0130') array.set(timeframes_options,3, input(defval='None', options=['Long','Short','None'], title='0130-0200')) array.set(timeframes,4,'0130-0200') array.set(timeframes_options,4, input(defval='None', options=['Long','Short','None'], title='0200-0230')) array.set(timeframes,5,'0200-0230') array.set(timeframes_options,5, input(defval='None', options=['Long','Short','None'], title='0230-0300')) array.set(timeframes,6,'0230-0300') array.set(timeframes_options,6, input(defval='None', options=['Long','Short','None'], title='0300-0330')) array.set(timeframes,7,'0300-0330') array.set(timeframes_options,7, input(defval='None', options=['Long','Short','None'], title='0330-0400')) array.set(timeframes,8,'0330-0400') array.set(timeframes_options,8, input(defval='None', options=['Long','Short','None'], title='0400-0430')) array.set(timeframes,9,'0400-0430') array.set(timeframes_options,9, input(defval='None', options=['Long','Short','None'], title='0430-0500')) array.set(timeframes,10,'0430-0500') array.set(timeframes_options,10, input(defval='None', options=['Long','Short','None'], title='0500-0530')) array.set(timeframes,11,'0500-0530') array.set(timeframes_options,11, input(defval='None', options=['Long','Short','None'], title='0530-0600')) array.set(timeframes,12,'0530-0600') array.set(timeframes_options,12, input(defval='None', options=['Long','Short','None'], title='0600-0630')) array.set(timeframes,13,'0600-0630') array.set(timeframes_options,13, input(defval='None', options=['Long','Short','None'], title='0630-0700')) array.set(timeframes,14,'0630-0700') array.set(timeframes_options,14, input(defval='None', options=['Long','Short','None'], title='0700-0730')) array.set(timeframes,15,'0700-0730') array.set(timeframes_options,15, input(defval='None', options=['Long','Short','None'], title='0730-0800')) array.set(timeframes,16,'0730-0800') array.set(timeframes_options,16, input(defval='None', options=['Long','Short','None'], title='0800-0830')) array.set(timeframes,17,'0800-0830') array.set(timeframes_options,17, input(defval='None', options=['Long','Short','None'], title='0830-0900')) array.set(timeframes,18,'0830-0900') array.set(timeframes_options,18, input(defval='None', options=['Long','Short','None'], title='0900-0930')) array.set(timeframes,19,'0900-0930') array.set(timeframes_options,19, input(defval='None', options=['Long','Short','None'], title='0930-1000')) array.set(timeframes,20,'0930-1000') array.set(timeframes_options,20, input(defval='None', options=['Long','Short','None'], title='1000-1030')) array.set(timeframes,21,'1000-1030') array.set(timeframes_options,21, input(defval='None', options=['Long','Short','None'], title='1030-1100')) array.set(timeframes,22,'1030-1100') array.set(timeframes_options,22, input(defval='None', options=['Long','Short','None'], title='1100-1130')) array.set(timeframes,23,'1100-1130') array.set(timeframes_options,23, input(defval='None', options=['Long','Short','None'], title='1130-1200')) array.set(timeframes,24,'1130-1200') array.set(timeframes_options,24, input(defval='None', options=['Long','Short','None'], title='1200-1230')) array.set(timeframes,25,'1200-1230') array.set(timeframes_options,25, input(defval='None', options=['Long','Short','None'], title='1230-1300')) array.set(timeframes,26,'1230-1300') array.set(timeframes_options,26, input(defval='None', options=['Long','Short','None'], title='1300-1330')) array.set(timeframes,27,'1300-1330') array.set(timeframes_options,27, input(defval='None', options=['Long','Short','None'], title='1330-1400')) array.set(timeframes,28,'1330-1400') array.set(timeframes_options,28, input(defval='None', options=['Long','Short','None'], title='1400-1430')) array.set(timeframes,29,'1400-1430') array.set(timeframes_options,29, input(defval='None', options=['Long','Short','None'], title='1430-1500')) array.set(timeframes,30,'1430-1500') array.set(timeframes_options,30, input(defval='None', options=['Long','Short','None'], title='1500-1530')) array.set(timeframes,31,'1500-1530') array.set(timeframes_options,31, input(defval='None', options=['Long','Short','None'], title='1530-1600')) array.set(timeframes,32,'1530-1600') array.set(timeframes_options,32, input(defval='None', options=['Long','Short','None'], title='1600-1630')) array.set(timeframes,33,'1600-1630') array.set(timeframes_options,33, input(defval='None', options=['Long','Short','None'], title='1630-1700')) array.set(timeframes,34,'1630-1700') array.set(timeframes_options,34, input(defval='None', options=['Long','Short','None'], title='1700-1730')) array.set(timeframes,35,'1700-1730') array.set(timeframes_options,35, input(defval='None', options=['Long','Short','None'], title='1730-1800')) array.set(timeframes,36,'1730-1800') array.set(timeframes_options,36, input(defval='None', options=['Long','Short','None'], title='1800-1830')) array.set(timeframes,37,'1800-1830') array.set(timeframes_options,37, input(defval='None', options=['Long','Short','None'], title='1830-1900')) array.set(timeframes,38,'1830-1900') array.set(timeframes_options,38, input(defval='None', options=['Long','Short','None'], title='1900-0930')) array.set(timeframes,39,'1900-0930') array.set(timeframes_options,39, input(defval='None', options=['Long','Short','None'], title='1930-2000')) array.set(timeframes,40,'1930-2000') array.set(timeframes_options,40, input(defval='None', options=['Long','Short','None'], title='2000-2030')) array.set(timeframes,41,'2000-2030') array.set(timeframes_options,41, input(defval='None', options=['Long','Short','None'], title='2030-2100')) array.set(timeframes,42,'2030-2100') array.set(timeframes_options,42, input(defval='None', options=['Long','Short','None'], title='2100-2130')) array.set(timeframes,43,'2100-2130') array.set(timeframes_options,43, input(defval='None', options=['Long','Short','None'], title='2130-2200')) array.set(timeframes,44,'2130-2200') array.set(timeframes_options,44, input(defval='None', options=['Long','Short','None'], title='2200-2230')) array.set(timeframes,45,'2200-2230') array.set(timeframes_options,45, input(defval='None', options=['Long','Short','None'], title='2230-2300')) array.set(timeframes,46,'2230-2300') array.set(timeframes_options,46, input(defval='None', options=['Long','Short','None'], title='2300-2330')) array.set(timeframes,47,'2300-2330') array.set(timeframes_options,47, input(defval='None', options=['Long','Short','None'], title='2330-0000')) string_hour = hour<10?'0'+tostring(hour):tostring(hour) string_minute = minute<10?'0'+tostring(minute):tostring(minute) current_time = string_hour+string_minute f_strLeft(_str, _n) => string[] _chars = str.split(_str, "") int _len = array.size(_chars) int _end = min(_len, max(0, _n)) string[] _substr = array.new_string(0) if _end <= _len _substr := array.slice(_chars, 0, _end) string _return = array.join(_substr, "") f_strRight(_str, _n) => string[] _chars = str.split(_str, "") int _len = array.size(_chars) int _beg = max(0, _len - _n) string[] _substr = array.new_string(0) if _beg < _len _substr := array.slice(_chars, _beg, _len) string _return = array.join(_substr, "") for i = 0 to array.size(timeframes) - 1 start_time = f_strLeft(array.get(timeframes, i), 4) end_time = f_strRight(array.get(timeframes, i), 4) if current_time == end_time and array.get(timeframes_options, i)!='None' and array.get(timeframes_options, i) != array.get(timeframes_options, i==47?0:i+1) and timestamp(toyear, tomonth, today, 00, 00) strategy.close_all() if current_time == start_time and dayOfWeekFilter and array.get(timeframes_options, i)!='None' and array.get(timeframes_options, i) != array.get(timeframes_options, i==0?47:i-1) if array.get(timeframes_options, i) == 'Long' strategy.entry("Long", strategy.long, when=(time > timestamp(fromyear, frommonth, fromday, 00, 00) and time < timestamp(toyear, tomonth, today, 00, 00))) else if array.get(timeframes_options, i) == 'Short' strategy.entry("Short", strategy.short, when=(time > timestamp(fromyear, frommonth, fromday, 00, 00) and time < timestamp(toyear, tomonth, today, 00, 00)))
[VJ]War Machine PAT Intra
https://www.tradingview.com/script/7kEvY5st-VJ-War-Machine-PAT-Intra/
vikris
https://www.tradingview.com/u/vikris/
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/ // © vikris //@version=4 strategy("[VJ]War Machine PAT Intra", overlay=true, calc_on_every_tick = false) // ********** Strategy inputs - Start ********** // Used for intraday handling // Session value should be from market start to the time you want to square-off // your intraday strategy // Important: The end time should be at least 2 minutes before the intraday // square-off time set by your broker var i_marketSession = input(title="Market session", type=input.session, defval="0915-1455", confirm=true) // Make inputs that set the take profit % (optional) longProfitPerc = input(title="Long Take Profit (%)", type=input.float, minval=0.0, step=0.1, defval=5.0) * 0.01 shortProfitPerc = input(title="Short Take Profit (%)", type=input.float, minval=0.0, step=0.1, defval=5.0) * 0.01 // Set stop loss level with input options (optional) longLossPerc = input(title="Long Stop Loss (%)", type=input.float, minval=0.0, step=0.1, defval=5.0) * 0.01 shortLossPerc = input(title="Short Stop Loss (%)", type=input.float, minval=0.0, step=0.1, defval=5.0) * 0.01 trendFactor = input(title="Trend Factor(Lower means trending)", type=input.integer, minval=1, step=1, defval=50) oversold = input(title="Oversold", type=input.integer, minval=1, step=1, defval=25) overbought = input(title="Overbought", type=input.integer, minval=1, step=1, defval=75) // ********** Strategy inputs - End ********** // ********** Supporting functions - Start ********** // A function to check whether the bar or period is in intraday session barInSession(sess) => time(timeframe.period, sess) != 0 // Figure out take profit price longExitPrice = strategy.position_avg_price * (1 + longProfitPerc) shortExitPrice = strategy.position_avg_price * (1 - shortProfitPerc) // Determine stop loss price longStopPrice = strategy.position_avg_price * (1 - longLossPerc) shortStopPrice = strategy.position_avg_price * (1 + shortLossPerc) // ********** Supporting functions - End ********** // ********** Strategy - Start ********** // See if intraday session is active bool intradaySession = barInSession(i_marketSession) // Trade only if intraday session is active //=================Strategy logic goes in here=========================== //Vol Confirmation vol = volume > volume[1] //Engulfing candle confirm bullishEC = close > open[1] and close[1] < open[1] bearishEC = close < open[1] and close[1] > open[1] //Candles colors greenCandle = (close > open) redCandle = (close < open) length = input(title="Length", type=input.integer, defval=14, minval=1, maxval=2000) src = hlc3 upper = sum(volume * (change(src) <= 0 ? 0 : src), length) lower = sum(volume * (change(src) >= 0 ? 0 : src), length) _rsi(upper, lower) => 100.0 - (100.0 / (1.0 + upper / lower)) mf = _rsi(upper, lower) ci = 100 * log10(sum(atr(1), length) / (highest(length) - lowest(length))) / log10(length) //tradeSignal = ((rsiOS or rsiOS[1]) and bullishEC) or ((rsiOB or rsiOB[1]) and bearishEC) //Final Long/Short Condition longCondition = redCandle and mf < oversold and ci <trendFactor and vol shortCondition = greenCandle and mf >overbought and ci <trendFactor and vol //Long Strategy - buy condition and exits with Take profit and SL if (longCondition and intradaySession) stop_level = longStopPrice profit_level = longExitPrice strategy.entry("My Long Entry Id", strategy.long) strategy.exit("TP/SL", "My Long Entry Id", stop=stop_level, limit=profit_level) //Short Strategy - sell condition and exits with Take profit and SL if (shortCondition and intradaySession) stop_level = shortStopPrice profit_level = shortExitPrice strategy.entry("My Short Entry Id", strategy.short) strategy.exit("TP/SL", "My Short Entry Id", stop=stop_level, limit=profit_level) // Square-off position (when session is over and position is open) squareOff = (not intradaySession) and (strategy.position_size != 0) strategy.close_all(when = squareOff, comment = "Square-off") // ********** Strategy - End **********
[VJ]Thor for MFI
https://www.tradingview.com/script/CmaRExxB-VJ-Thor-for-MFI/
vikris
https://www.tradingview.com/u/vikris/
50
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © vikris //@version=4 strategy("[VJ]Thor for MFI", overlay=true, calc_on_every_tick = false,pyramiding=0) // ********** Strategy inputs - Start ********** // Used for intraday handling // Session value should be from market start to the time you want to square-off // your intraday strategy // Important: The end time should be at least 2 minutes before the intraday // square-off time set by your broker var i_marketSession = input(title="Market session", type=input.session, defval="0915-1455", confirm=true) // Make inputs that set the take profit % (optional) longProfitPerc = input(title="Long Take Profit (%)", type=input.float, minval=0.0, step=0.1, defval=1) * 0.01 shortProfitPerc = input(title="Short Take Profit (%)", type=input.float, minval=0.0, step=0.1, defval=1) * 0.01 // Set stop loss level with input options (optional) longLossPerc = input(title="Long Stop Loss (%)", type=input.float, minval=0.0, step=0.1, defval=0.5) * 0.01 shortLossPerc = input(title="Short Stop Loss (%)", type=input.float, minval=0.0, step=0.1, defval=0.5) * 0.01 i_MFI = input(3, title="MFI Length") OB=input(100, title="Overbought Level") OS=input(0, title="Oversold Level") barsizeThreshold=input(.5, step=.05, minval=.1, maxval=1, title="Bar Body Size, 1=No Wicks") i_MAFilter = input(true, title="Use MA Trend Filter") i_MALen = input(80, title="MA Length") // ********** Strategy inputs - End ********** // ********** Supporting functions - Start ********** // A function to check whether the bar or period is in intraday session barInSession(sess) => time(timeframe.period, sess) != 0 // Figure out take profit price longExitPrice = strategy.position_avg_price * (1 + longProfitPerc) shortExitPrice = strategy.position_avg_price * (1 - shortProfitPerc) // Determine stop loss price longStopPrice = strategy.position_avg_price * (1 - longLossPerc) shortStopPrice = strategy.position_avg_price * (1 + shortLossPerc) // ********** Supporting functions - End ********** // ********** Strategy - Start ********** // See if intraday session is active bool intradaySession = barInSession(i_marketSession) // Trade only if intraday session is active //=================Strategy logic goes in here=========================== MFI=mfi(close,i_MFI) barsize=high-low barbodysize=close>open?(open-close)*-1:(open-close) shortwicksbar=barbodysize>barsize*barsizeThreshold SMA=sma(close, i_MALen) MAFilter=close > SMA BUY = MFI[1] == OB and close > open and shortwicksbar and (i_MAFilter ? MAFilter : true) SELL = MFI[1] == OS and close < open and shortwicksbar and (i_MAFilter ? not MAFilter : true) //Final Long/Short Condition longCondition = BUY shortCondition = SELL //Long Strategy - buy condition and exits with Take profit and SL if (longCondition and intradaySession) stop_level = longStopPrice profit_level = longExitPrice strategy.entry("Buy", strategy.long) strategy.exit("TP/SL", "Buy", stop=stop_level, limit=profit_level) //Short Strategy - sell condition and exits with Take profit and SL if (shortCondition and intradaySession) stop_level = shortStopPrice profit_level = shortExitPrice strategy.entry("Sell", strategy.short) strategy.exit("TP/SL", "Sell", stop=stop_level, limit=profit_level) // Square-off position (when session is over and position is open) squareOff = (not intradaySession) and (strategy.position_size != 0) strategy.close_all(when = squareOff, comment = "Square-off") // ********** Strategy - End **********
QuickSilver Intraday using RSI
https://www.tradingview.com/script/jkbeaOb2-QuickSilver-Intraday-using-RSI/
vikris
https://www.tradingview.com/u/vikris/
56
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © vikris //thanks for template from Pritesh //@version=4 strategy("QS - Intraday", overlay=true, calc_on_every_tick = false,pyramiding=0) // ********** Strategy inputs - Start ********** // Used for intraday handling // Session value should be from market start to the time you want to square-off // your intraday strategy // Important: The end time should be at least 2 minutes before the intraday // square-off time set by your broker var i_marketSession = input(title="Market session", type=input.session, defval="0915-1455", confirm=true) rsiPreiod = input(14, title="RSI Period", type=input.integer) rsiBuy = input(50, title="Buy when RSI is above", type=input.integer) rsiSell = input(50, title="Sell when RSI is Bellow", type=input.integer) isReversal = input(true, title="Exit on VWap Reversal ?", type=input.bool) // ********** Strategy inputs - End ********** // ********** Supporting functions - Start ********** // A function to check whether the bar or period is in intraday session barInSession(sess) => time(timeframe.period, sess) != 0 // ********** Supporting functions - End ********** // ********** Strategy - Start ********** o=(open[1]+close[1])/2 h=max(high,close,o) l=min(low,close,o) c=(open+high+low+close)/4 //additional conditions to improve the % profitablilty greenCandle = (close > open) redCandle = (close < open) vol = volume > volume[1] // See if intraday session is active bool intradaySession = barInSession(i_marketSession) // Trade only if intraday session is active //long and short conditions longCondition = vwap > vwap[1] and rsi(close,rsiPreiod)>rsiBuy and intradaySession if (longCondition) strategy.entry("Buy", strategy.long) shortCondition = vwap < vwap[1] and rsi(close,rsiPreiod)<rsiSell and intradaySession if (shortCondition) strategy.entry("Sell", strategy.short) if(isReversal) strategy.close("Buy", when = vwap < vwap[1] ,comment = "ExitBuy") strategy.close("Sell", when =vwap > vwap[1], comment = "ExitSell") // Square-off position (when session is over and position is open) squareOff = (not intradaySession) and (strategy.position_size != 0) strategy.close_all(when = squareOff, comment = "Square-off") // ********** Strategy - End **********
[VJ] Mega Supertrend for Intraday
https://www.tradingview.com/script/9eagcvfe-VJ-Mega-Supertrend-for-Intraday/
vikris
https://www.tradingview.com/u/vikris/
119
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © vikris //@version=4 strategy("[VJ]Mega ST - Intra Strat", overlay=true, calc_on_every_tick = false) // ********** Strategy inputs - Start ********** // Used for intraday handling // Session value should be from market start to the time you want to square-off // your intraday strategy // Important: The end time should be at least 2 minutes before the intraday // square-off time set by your broker var i_marketSession = input(title="Market session", type=input.session, defval="0915-1455", confirm=true) // Make inputs that set the take profit % (optional) longProfitPerc = input(title="Long Take Profit (%)", type=input.float, minval=0.0, step=0.1, defval=1) * 0.01 shortProfitPerc = input(title="Short Take Profit (%)", type=input.float, minval=0.0, step=0.1, defval=1) * 0.01 // Set stop loss level with input options (optional) longLossPerc = input(title="Long Stop Loss (%)", type=input.float, minval=0.0, step=0.1, defval=0.5) * 0.01 shortLossPerc = input(title="Short Stop Loss (%)", type=input.float, minval=0.0, step=0.1, defval=0.5) * 0.01 var float i_multiplier = input(title = "ST Multiplier", type = input.float, defval = 3, step = 0.1, confirm=true) var int i_atrPeriod = input(title = "ST ATR Period", type = input.integer, defval = 7, confirm=true) // rsiSource = input(title="RSI Source", type=input.source, defval=close) // rsiLength = input(title="RSI Length", type=input.integer, defval=14) // rsiOverbought = input(title="RSI Overbought Level", type=input.integer, defval=70) // rsiOversold = input(title="RSI Oversold Level", type=input.integer, defval=30) // // Get RSI value // rsiValue = rsi(rsiSource, rsiLength) // //rsi sell // rsisell = rsiValue >= rsiOverbought // //rsi buy // rsibuy = rsiValue <= rsiOversold //Get Stochastic values fast = 20, slow = 50, ultraSlow = 200 fastMA = sma(close, fast) slowMA = sma(close, slow) ultraSlowMA = sma(close, ultraSlow) ema150 = 200 ema150MA = ema(close, ema150) // smooth = input(3, minval=1), K = input(14, minval=1), D=input(3,minval=1) // hh=highest(high,K) // ll=lowest(low,K) // k = sma((close-ll)/(hh-ll)*100, smooth) // d = sma(k, 3) // stochiasticHigh = 80 // stochiasticLow = 20 // ********** Strategy inputs - End ********** // ********** Supporting functions - Start ********** // A function to check whether the bar or period is in intraday session barInSession(sess) => time(timeframe.period, sess) != 0 // ********** Supporting functions - End ********** // ********** Strategy - Start ********** // See if intraday session is active bool intradaySession = barInSession(i_marketSession) // Trade only if intraday session is active [superTrend, dir] = supertrend(i_multiplier, i_atrPeriod) colResistance = dir == 1 and dir == dir[1] ? color.new(color.red, 0) : color.new(color.red, 100) colSupport = dir == -1 and dir == dir[1] ? color.new(color.green, 0) : color.new(color.green, 100) // plot(superTrend, color = colResistance, linewidth=2) // plot(superTrend, color = colSupport, linewidth=2) // Super Trend Long/short condition stlong = close > superTrend stshort = close < superTrend //Vol Confirmation vol = volume > volume[1] //Engulfing candle confirm bullishEC = close > open[1] and close[1] < open[1] bearishEC = close < open[1] and close[1] > open[1] //Candles colors greenCandle = (close > open) redCandle = (close < open) // //Stochastic computation // selldata = close < ema150MA and k>stochiasticHigh and d>stochiasticHigh and close>open // // plotshape(selldata, style=shape.triangledown, location=location.belowbar, color=color.red) // buydata2 = close > ema150MA and k<stochiasticLow and d<stochiasticLow and close<open // // plotshape(buydata2, style=shape.triangleup, location=location.abovebar, color=color.green) // Figure out take profit price longExitPrice = strategy.position_avg_price * (1 + longProfitPerc) shortExitPrice = strategy.position_avg_price * (1 - shortProfitPerc) // Determine stop loss price longStopPrice = strategy.position_avg_price * (1 - longLossPerc) shortStopPrice = strategy.position_avg_price * (1 + shortLossPerc) //Final Long/Short Condition longCondition = stlong and redCandle and vol and vwap > vwap[1] shortCondition =stshort and greenCandle and vol and vwap < vwap[1] //Long Strategy - buy condition and exits with Take profit and SL if (longCondition and intradaySession) stop_level = longStopPrice profit_level = longExitPrice strategy.entry("My Long Entry Id", strategy.long) strategy.exit("TP/SL", "My Long Entry Id", stop=stop_level, limit=profit_level) //Short Strategy - sell condition and exits with Take profit and SL if (shortCondition and intradaySession) stop_level = shortStopPrice profit_level = shortExitPrice strategy.entry("My Short Entry Id", strategy.short) strategy.exit("TP/SL", "My Short Entry Id", stop=stop_level, limit=profit_level) // Square-off position (when session is over and position is open) squareOff = (not intradaySession) and (strategy.position_size != 0) strategy.close_all(when = squareOff, comment = "Square-off") // ********** Strategy - End **********
1St Bar GAP+BkOut Screener v2 by RM
https://www.tradingview.com/script/o5teHOB7-1St-Bar-GAP-BkOut-Screener-v2-by-RM/
raul3429
https://www.tradingview.com/u/raul3429/
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/ // © raul3429 // 1St Bar GAP/BkOut/Screener v2 by RM Sun21Aug // This is type of custom screener has a list of predefined stock - In the US MArket- that can be modified to suit. // Generally in TV a maximum of 40 stocks can be used at a time. THis script uses 20 entries for stock called s01, s02 ... to s20. // In some cases there may be other TV automatic calls that may produce an excessive number of calls. // // This code runs on each bar and checks if the stocks has an initial Gap, then checks for next bars to be inside the boundaries of the first candle // you can customize this screener according to your requirement. // There are a number of very clever people I have taken bits of code and ideas, thanks to you all :) //Outline: // gap up/ gap down on 1 min first candle -> good // 2nd candle inside 1st candle -> good // 3rd to nth candle to break out from first candle range -> good /alert/ Plot flag // //M code to load watchlist from txt format // //s01 = input( "ADS " , type=input.string) //let // // replace [my directory] and [my Watchlist.txt] for the correspondign values in your computer // Source = Csv.Document(File.Contents("C:\[my directory]\[my Watchlist.txt]"),[Delimiter=",", Columns=108, Encoding=1252, QuoteStyle=QuoteStyle.None]), // #"Transposed Table" = Table.Transpose(Source), // #"Sorted Rows" = Table.Sort(#"Transposed Table",{{"Column1", Order.Ascending}}), // #"Added Index" = Table.AddIndexColumn(#"Sorted Rows", "Index", 1, 1, Int64.Type), // #"Changed Type1" = Table.TransformColumnTypes(#"Added Index",{{"Index", type text}}), // #"Inserted Merged Column1" = Table.AddColumn(#"Changed Type1", "Merged", each Text.Combine({"0", [Index]}), type text), // #"Inserted First Characters" = Table.AddColumn(#"Inserted Merged Column1", "Two Characters", each Text.End([Merged], 2), type text), // #"Removed Columns" = Table.RemoveColumns(#"Inserted First Characters",{"Index", "Merged"}), // #"Inserted Merged Column" = Table.AddColumn(#"Removed Columns", "Merged", each Text.Combine({"s", [Two Characters], " = input( '", [Column1], "' , type=input.string)"}), type text) //in // #"Inserted Merged Column" // //--> once input string is created Copy&Paste in this code after // Symbols _ Use Power Query in Excel // //@version=4 strategy("1St Bar GAP+BkOut Screener v2 by RM", shorttitle = '1Bar Gap+BkOut v2 by RM ', overlay = true) res = input("", title="input timeframe for the screener" , type = input.resolution) high_show = input(defval = true , title = "Show 1st Bar High" , type = input.bool) low_show = input(defval = true , title = "Show 1st Bar Low" , type = input.bool) barNumber = input(defval = false , title = "Show Bar Numbers", type = input.bool) input_font = input("Normal", "Font size", options = ["Large" ,"Normal", "Small"]) font = input_font == "Small" ? size.small : input_font == "Large" ? size.large : size.normal input_pos = input("top_right", "Table Position", options = ["top_right", "middle_right", "bottom_right", "bottom_center", "bottom_left", "middle_left"]) pos = input_pos == "top_right" ? position.top_right: input_pos == "middle_right" ? position.middle_right : input_pos == "middle_left" ? position.middle_left : input_pos == "bottom_right" ? position.bottom_right : input_pos == "bottom_center" ? position.bottom_center : position.bottom_left //calc_on_every_tick = true We are waiting to close the bar // --------- Colors c_black = #000000 // Black c_maroon = #800000 // Maroon c_green = #008000 // Green c_green90 = #00800090 //Green 90% c_green100 = #008000FF //Green 100% c_olive = #808000 // Olive c_navy = #000080 // Navy c_purple = #800080 // Purple c_teal = #008080 // Teal c_silver = #c0c0c0 // Silver c_grey = #808080 // Grey c_red = #8B0000 //Red c_red100 = #8B0000FF//Red 100% c_red90 = #8B0000FF//Red 90% c_redLight = #b71c1c //Red Light c_lime = #00ff00 // Lime c_yellow = #ffff00 // Yellow c_yellowTr = #FFFF0090 //YellowTransp c_blue = #0000ff // Blue c_fuchsia = #ff00ff // Fuchsia c_aqua = #00ffff // Aqua c_white = #ffffff // White c_darkcyan = #00af87 // DarkCyan c_orange = #f57f17 //Orange // Symbols _ Use Power Query in Excel s01 = input( "AAPL" , type=input.string) s02 = input( "BIDU" , type=input.string) s03 = input( "AMD " , type=input.string) s04 = input( "TAN " , type=input.string) s05 = input( "BABA" , type=input.string) s06 = input( "BILL" , type=input.string) s07 = input( "MSFT" , type=input.string) s08 = input( "PFE" , type=input.string) s09 = input( "BHVN" , type=input.string) s10 = input( "T " , type=input.string) s11 = input( "NVAX" , type=input.string) s12 = input( "NVDA" , type=input.string) s13 = input( "FB " , type=input.string) s14 = input( "PTON" , type=input.string) s15 = input( "RIOT" , type=input.string) s16 = input( "QCOM" , type=input.string) s17 = input( "ROKU" , type=input.string) s18 = input( "FUBO" , type=input.string) s19 = input( "WISH" , type=input.string) s20 = input( "WKHS" , type=input.string) // FUNCTIONS // is_newday(sess) => d = time("W", sess) change(d) != 0 ? true : na is_newbar(res) => t = time(res) change(t) != 0 ? true : na adopt(r, s) => security(syminfo.tickerid, r, s) f_get_h(back, res) => O = security(symbol = syminfo.tickerid, resolution = res, expression = high[back], gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on) f_get_l(back, res) => O = security(symbol = syminfo.tickerid, resolution = res, expression = low[back], gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on) // 1st Bar Limits Function gapScreenerFunc() => high_rangeL = valuewhen(is_newbar('D'),high,0) low_rangeL = valuewhen(is_newbar('D'),low,0) upGap = low > high[1] downGap = high < low[1] gap = upGap or downGap breakUp = close > high_rangeL breakDN = close < low_rangeL insideBand = high < high_rangeL and low > low_rangeL [insideBand, gap, upGap, downGap, breakUp, breakDN] outcomeIs(upGap, downGap, insideBand) => result = upGap ? "upGap" : downGap ? "downGap" : insideBand ? "insideB" : na [result] // first bar bar_date_ts = timestamp(year(time),month(time),dayofmonth(time),0,0,0) is_new_date = change(bar_date_ts) high_1st = valuewhen(is_newbar('D'),high,0) low_1st = valuewhen(is_newbar('D'),low,0) RoundCounter = 0 up1 = plot(high_show ? adopt(res, high_1st): na, color = c_teal, linewidth=1) down1 = plot(low_show ? adopt(res, low_1st): na, color = c_teal, linewidth=1) trans1 = high_show or low_show ? 95 : 100 fill(up1, down1, color.new (c_white, transp=trans1)) // bar counter is_new_day() => d=dayofweek na(d[1]) or d != d[1] vLine(BarIndex, Color, LineStyle) => Line = line.new(x1= BarIndex, y1= low - tr * 5, x2= BarIndex, y2= high + tr * 5, xloc= xloc.bar_index, color=Color, style= LineStyle) if (is_new_date) fisrtDayline = vLine(bar_index,color.new(c_white,95) , line.style_dashed) // Running gapScreenerFunc for all sybmols get InsideBands, Gaps and BreakOuts [insB01, Gap01, upG_01, dnG_01, c_Up01, c_Dn01] = security(s01, res,gapScreenerFunc()) [insB02, Gap02, upG_02, dnG_02, c_Up02, c_Dn02] = security(s02, res,gapScreenerFunc()) [insB03, Gap03, upG_03, dnG_03, c_Up03, c_Dn03] = security(s03, res,gapScreenerFunc()) [insB04, Gap04, upG_04, dnG_04, c_Up04, c_Dn04] = security(s04, res,gapScreenerFunc()) [insB05, Gap05, upG_05, dnG_05, c_Up05, c_Dn05] = security(s05, res,gapScreenerFunc()) [insB06, Gap06, upG_06, dnG_06, c_Up06, c_Dn06] = security(s06, res,gapScreenerFunc()) [insB07, Gap07, upG_07, dnG_07, c_Up07, c_Dn07] = security(s07, res,gapScreenerFunc()) [insB08, Gap08, upG_08, dnG_08, c_Up08, c_Dn08] = security(s08, res,gapScreenerFunc()) [insB09, Gap09, upG_09, dnG_09, c_Up09, c_Dn09] = security(s09, res,gapScreenerFunc()) [insB10, Gap10, upG_10, dnG_10, c_Up10, c_Dn10] = security(s10, res,gapScreenerFunc()) [insB11, Gap11, upG_11, dnG_11, c_Up11, c_Dn11] = security(s11, res,gapScreenerFunc()) [insB12, Gap12, upG_12, dnG_12, c_Up12, c_Dn12] = security(s12, res,gapScreenerFunc()) [insB13, Gap13, upG_13, dnG_13, c_Up13, c_Dn13] = security(s13, res,gapScreenerFunc()) [insB14, Gap14, upG_14, dnG_14, c_Up14, c_Dn14] = security(s14, res,gapScreenerFunc()) [insB15, Gap15, upG_15, dnG_15, c_Up15, c_Dn15] = security(s15, res,gapScreenerFunc()) [insB16, Gap16, upG_16, dnG_16, c_Up16, c_Dn16] = security(s16, res,gapScreenerFunc()) [insB17, Gap17, upG_17, dnG_17, c_Up17, c_Dn17] = security(s17, res,gapScreenerFunc()) [insB18, Gap18, upG_18, dnG_18, c_Up18, c_Dn18] = security(s18, res,gapScreenerFunc()) [insB19, Gap19, upG_19, dnG_19, c_Up19, c_Dn19] = security(s19, res,gapScreenerFunc()) [insB20, Gap20, upG_20, dnG_20, c_Up20, c_Dn20] = security(s20, res,gapScreenerFunc()) var UpTabl = table.new(position = pos, columns = 1, rows = 4, bgcolor = c_black, border_width = 2, frame_color= c_yellowTr, frame_width = 2) table.cell_set_text_size(UpTabl, column = 0, row = 0, text_size= font) // Running gapScreenerFunc for first Candle: check for gaps only if (is_new_date) // Screener label // ↑ → ↓ var s_1 = "" RoundCounter := 1 s_1 := ' Opening(' + tostring(timeframe.period) + ') Gap: \n' s_1 := upG_01 ? s_1 +s01 +' =Gap UP ↑ \n' : dnG_01 ? s_1 +s01 +' =Gap Down ↓ \n': s_1 s_1 := upG_02 ? s_1 +s02 +' =Gap UP ↑ \n' : dnG_02 ? s_1 +s02 +' =Gap Down ↓ \n': s_1 s_1 := upG_03 ? s_1 +s03 +' =Gap UP ↑ \n' : dnG_03 ? s_1 +s03 +' =Gap Down ↓ \n': s_1 s_1 := upG_04 ? s_1 +s04 +' =Gap UP ↑ \n' : dnG_04 ? s_1 +s04 +' =Gap Down ↓ \n': s_1 s_1 := upG_05 ? s_1 +s05 +' =Gap UP ↑ \n' : dnG_05 ? s_1 +s05 +' =Gap Down ↓ \n': s_1 s_1 := upG_06 ? s_1 +s06 +' =Gap UP ↑ \n' : dnG_06 ? s_1 +s06 +' =Gap Down ↓ \n': s_1 s_1 := upG_07 ? s_1 +s07 +' =Gap UP ↑ \n' : dnG_07 ? s_1 +s07 +' =Gap Down ↓ \n': s_1 s_1 := upG_08 ? s_1 +s08 +' =Gap UP ↑ \n' : dnG_08 ? s_1 +s08 +' =Gap Down ↓ \n': s_1 s_1 := upG_09 ? s_1 +s09 +' =Gap UP ↑ \n' : dnG_09 ? s_1 +s09 +' =Gap Down ↓ \n': s_1 s_1 := upG_10 ? s_1 +s10 +' =Gap UP ↑ \n' : dnG_10 ? s_1 +s10 +' =Gap Down ↓ \n': s_1 s_1 := upG_11 ? s_1 +s11 +' =Gap UP ↑ \n' : dnG_11 ? s_1 +s11 +' =Gap Down ↓ \n': s_1 s_1 := upG_12 ? s_1 +s12 +' =Gap UP ↑ \n' : dnG_12 ? s_1 +s12 +' =Gap Down ↓ \n': s_1 s_1 := upG_13 ? s_1 +s13 +' =Gap UP ↑ \n' : dnG_13 ? s_1 +s13 +' =Gap Down ↓ \n': s_1 s_1 := upG_14 ? s_1 +s14 +' =Gap UP ↑ \n' : dnG_14 ? s_1 +s14 +' =Gap Down ↓ \n': s_1 s_1 := upG_15 ? s_1 +s15 +' =Gap UP ↑ \n' : dnG_15 ? s_1 +s15 +' =Gap Down ↓ \n': s_1 s_1 := upG_16 ? s_1 +s16 +' =Gap UP ↑ \n' : dnG_16 ? s_1 +s16 +' =Gap Down ↓ \n': s_1 s_1 := upG_17 ? s_1 +s17 +' =Gap UP ↑ \n' : dnG_17 ? s_1 +s17 +' =Gap Down ↓ \n': s_1 s_1 := upG_18 ? s_1 +s18 +' =Gap UP ↑ \n' : dnG_18 ? s_1 +s18 +' =Gap Down ↓ \n': s_1 s_1 := upG_19 ? s_1 +s19 +' =Gap UP ↑ \n' : dnG_19 ? s_1 +s19 +' =Gap Down ↓ \n': s_1 s_1 := upG_20 ? s_1 +s20 +' =Gap UP ↑ \n' : dnG_20 ? s_1 +s20 +' =Gap Down ↓ \n': s_1 table.cell(table_id = UpTabl, column = 0, row = 0, text_color = c_white, text = s_1) table.cell_set_text_size(UpTabl, column = 0, row = 0, text_size = font) plotchar(barNumber and (barssince(is_new_day())+1)==1,char=' ',text="1",color=color.white,location=location.belowbar,editable=false) // Second Candle: check for gaps in first candle and Inside Bands if (barssince(is_new_day())+1)==2 var s_2 = "" RoundCounter := RoundCounter + 1 s_2 := 'Second Candle: \n' s_2 := Gap01[1] and insB01 ? s_2 +s01 +' =InsB \n' : s_2 s_2 := Gap02[1] and insB02 ? s_2 +s02 +' =InsB \n' : s_2 s_2 := Gap03[1] and insB03 ? s_2 +s03 +' =InsB \n' : s_2 s_2 := Gap04[1] and insB04 ? s_2 +s04 +' =InsB \n' : s_2 s_2 := Gap05[1] and insB05 ? s_2 +s05 +' =InsB \n' : s_2 s_2 := Gap06[1] and insB06 ? s_2 +s06 +' =InsB \n' : s_2 s_2 := Gap07[1] and insB07 ? s_2 +s07 +' =InsB \n' : s_2 s_2 := Gap08[1] and insB08 ? s_2 +s08 +' =InsB \n' : s_2 s_2 := Gap09[1] and insB09 ? s_2 +s09 +' =InsB \n' : s_2 s_2 := Gap10[1] and insB10 ? s_2 +s10 +' =InsB \n' : s_2 s_2 := Gap11[1] and insB11 ? s_2 +s11 +' =InsB \n' : s_2 s_2 := Gap12[1] and insB12 ? s_2 +s12 +' =InsB \n' : s_2 s_2 := Gap13[1] and insB13 ? s_2 +s13 +' =InsB \n' : s_2 s_2 := Gap14[1] and insB14 ? s_2 +s14 +' =InsB \n' : s_2 s_2 := Gap15[1] and insB15 ? s_2 +s15 +' =InsB \n' : s_2 s_2 := Gap16[1] and insB16 ? s_2 +s16 +' =InsB \n' : s_2 s_2 := Gap17[1] and insB17 ? s_2 +s17 +' =InsB \n' : s_2 s_2 := Gap18[1] and insB18 ? s_2 +s18 +' =InsB \n' : s_2 s_2 := Gap19[1] and insB19 ? s_2 +s19 +' =InsB \n' : s_2 s_2 := Gap20[1] and insB20 ? s_2 +s20 +' =InsB \n' : s_2 table.cell(table_id = UpTabl, column = 0, row = 1, text_color = c_white, text = s_2) table.cell_set_text_size(UpTabl, column = 0, row = 1, text_size= font) plotchar(barNumber and (barssince(is_new_day())+1)==2,char=' ',text="2",color=color.white,location=location.belowbar,editable=false) // Third Candle: check for gaps in first candle and Inside Bands in previous, then for inside or break outs if (barssince(is_new_day())+1)==3 var s_3 = "" RoundCounter := RoundCounter + 1 s_3 := 'Third Candle: \n' s_3 := Gap01[2] and insB01[1] and insB01 ? s_3 +s01 +' =InsB \n' : Gap01[2] and insB01[1] and c_Up01 ? s_3 +s01 +' =BrkUp \n' : Gap01[2] and insB01[1] and c_Dn01 ? s_3 +s01 +' =BrkDn \n': s_3 s_3 := Gap02[2] and insB02[1] and insB02 ? s_3 +s02 +' =InsB \n' : Gap02[2] and insB02[1] and c_Up02 ? s_3 +s02 +' =BrkUp \n' : Gap02[2] and insB02[1] and c_Dn02 ? s_3 +s02 +' =BrkDn \n': s_3 s_3 := Gap03[2] and insB03[1] and insB03 ? s_3 +s03 +' =InsB \n' : Gap03[2] and insB03[1] and c_Up03 ? s_3 +s03 +' =BrkUp \n' : Gap03[2] and insB03[1] and c_Dn03 ? s_3 +s03 +' =BrkDn \n': s_3 s_3 := Gap04[2] and insB04[1] and insB04 ? s_3 +s04 +' =InsB \n' : Gap04[2] and insB04[1] and c_Up04 ? s_3 +s04 +' =BrkUp \n' : Gap04[2] and insB04[1] and c_Dn04 ? s_3 +s04 +' =BrkDn \n': s_3 s_3 := Gap05[2] and insB05[1] and insB05 ? s_3 +s05 +' =InsB \n' : Gap05[2] and insB05[1] and c_Up05 ? s_3 +s05 +' =BrkUp \n' : Gap05[2] and insB05[1] and c_Dn05 ? s_3 +s05 +' =BrkDn \n': s_3 s_3 := Gap06[2] and insB06[1] and insB06 ? s_3 +s06 +' =InsB \n' : Gap06[2] and insB06[1] and c_Up06 ? s_3 +s06 +' =BrkUp \n' : Gap06[2] and insB06[1] and c_Dn06 ? s_3 +s06 +' =BrkDn \n': s_3 s_3 := Gap07[2] and insB07[1] and insB07 ? s_3 +s07 +' =InsB \n' : Gap07[2] and insB07[1] and c_Up07 ? s_3 +s07 +' =BrkUp \n' : Gap07[2] and insB07[1] and c_Dn07 ? s_3 +s07 +' =BrkDn \n': s_3 s_3 := Gap08[2] and insB08[1] and insB08 ? s_3 +s08 +' =InsB \n' : Gap08[2] and insB08[1] and c_Up08 ? s_3 +s08 +' =BrkUp \n' : Gap08[2] and insB08[1] and c_Dn08 ? s_3 +s08 +' =BrkDn \n': s_3 s_3 := Gap09[2] and insB09[1] and insB09 ? s_3 +s09 +' =InsB \n' : Gap09[2] and insB09[1] and c_Up09 ? s_3 +s09 +' =BrkUp \n' : Gap09[2] and insB09[1] and c_Dn09 ? s_3 +s09 +' =BrkDn \n': s_3 s_3 := Gap10[2] and insB10[1] and insB10 ? s_3 +s10 +' =InsB \n' : Gap10[2] and insB10[1] and c_Up10 ? s_3 +s10 +' =BrkUp \n' : Gap10[2] and insB10[1] and c_Dn10 ? s_3 +s10 +' =BrkDn \n': s_3 s_3 := Gap11[2] and insB11[1] and insB11 ? s_3 +s11 +' =InsB \n' : Gap11[2] and insB11[1] and c_Up11 ? s_3 +s11 +' =BrkUp \n' : Gap11[2] and insB11[1] and c_Dn11 ? s_3 +s11 +' =BrkDn \n': s_3 s_3 := Gap12[2] and insB12[1] and insB12 ? s_3 +s12 +' =InsB \n' : Gap12[2] and insB12[1] and c_Up12 ? s_3 +s12 +' =BrkUp \n' : Gap12[2] and insB12[1] and c_Dn12 ? s_3 +s12 +' =BrkDn \n': s_3 s_3 := Gap13[2] and insB13[1] and insB13 ? s_3 +s13 +' =InsB \n' : Gap13[2] and insB13[1] and c_Up13 ? s_3 +s13 +' =BrkUp \n' : Gap13[2] and insB13[1] and c_Dn13 ? s_3 +s13 +' =BrkDn \n': s_3 s_3 := Gap14[2] and insB14[1] and insB14 ? s_3 +s14 +' =InsB \n' : Gap14[2] and insB14[1] and c_Up14 ? s_3 +s14 +' =BrkUp \n' : Gap14[2] and insB14[1] and c_Dn14 ? s_3 +s14 +' =BrkDn \n': s_3 s_3 := Gap15[2] and insB15[1] and insB15 ? s_3 +s15 +' =InsB \n' : Gap15[2] and insB15[1] and c_Up15 ? s_3 +s15 +' =BrkUp \n' : Gap15[2] and insB15[1] and c_Dn15 ? s_3 +s15 +' =BrkDn \n': s_3 s_3 := Gap16[2] and insB16[1] and insB16 ? s_3 +s16 +' =InsB \n' : Gap16[2] and insB16[1] and c_Up16 ? s_3 +s16 +' =BrkUp \n' : Gap16[2] and insB16[1] and c_Dn16 ? s_3 +s16 +' =BrkDn \n': s_3 s_3 := Gap17[2] and insB17[1] and insB17 ? s_3 +s17 +' =InsB \n' : Gap17[2] and insB17[1] and c_Up17 ? s_3 +s17 +' =BrkUp \n' : Gap17[2] and insB17[1] and c_Dn17 ? s_3 +s17 +' =BrkDn \n': s_3 s_3 := Gap18[2] and insB18[1] and insB18 ? s_3 +s18 +' =InsB \n' : Gap18[2] and insB18[1] and c_Up18 ? s_3 +s18 +' =BrkUp \n' : Gap18[2] and insB18[1] and c_Dn18 ? s_3 +s18 +' =BrkDn \n': s_3 s_3 := Gap19[2] and insB19[1] and insB19 ? s_3 +s19 +' =InsB \n' : Gap19[2] and insB19[1] and c_Up19 ? s_3 +s19 +' =BrkUp \n' : Gap19[2] and insB19[1] and c_Dn19 ? s_3 +s19 +' =BrkDn \n': s_3 s_3 := Gap20[2] and insB20[1] and insB20 ? s_3 +s20 +' =InsB \n' : Gap20[2] and insB20[1] and c_Up20 ? s_3 +s20 +' =BrkUp \n' : Gap20[2] and insB20[1] and c_Dn20 ? s_3 +s20 +' =BrkDn \n': s_3 table.cell(table_id = UpTabl, column = 0, row = 2, text_color = c_white, text = s_3) table.cell_set_text_size(UpTabl, column = 0, row = 2, text_size= font) plotchar(barNumber and (barssince(is_new_day())+1)==3,char=' ',text="3",color=color.white,location=location.belowbar,editable=false) if (barssince(is_new_day())+1)==4 var s_4 = "" RoundCounter := RoundCounter + 1 s_4 := 'Fourth Candle: \n' s_4 := Gap01[3] and insB01[2] and insB01[1] and insB01 ? s_4 +s01 +' =InsB \n' : Gap01[3] and insB01[2] and insB01[1] and c_Up01 ? s_4 +s01 +' =BrkUp \n' : Gap01[3] and insB01[2] and insB01[1] and c_Dn01 ? s_4 +s01 +' =BrkDn \n': s_4 s_4 := Gap02[3] and insB02[2] and insB02[1] and insB02 ? s_4 +s02 +' =InsB \n' : Gap02[3] and insB02[2] and insB02[1] and c_Up02 ? s_4 +s02 +' =BrkUp \n' : Gap02[3] and insB02[2] and insB02[1] and c_Dn02 ? s_4 +s02 +' =BrkDn \n': s_4 s_4 := Gap03[3] and insB03[2] and insB03[1] and insB03 ? s_4 +s03 +' =InsB \n' : Gap03[3] and insB03[2] and insB03[1] and c_Up03 ? s_4 +s03 +' =BrkUp \n' : Gap03[3] and insB03[2] and insB03[1] and c_Up03 ? s_4 +s03 +' =BrkUp \n': s_4 s_4 := Gap04[3] and insB04[2] and insB04[1] and insB04 ? s_4 +s04 +' =InsB \n' : Gap04[3] and insB04[2] and insB04[1] and c_Up04 ? s_4 +s04 +' =BrkUp \n' : Gap04[3] and insB04[2] and insB04[1] and c_Up04 ? s_4 +s04 +' =BrkUp \n': s_4 s_4 := Gap05[3] and insB05[2] and insB05[1] and insB05 ? s_4 +s05 +' =InsB \n' : Gap05[3] and insB05[2] and insB05[1] and c_Up05 ? s_4 +s05 +' =BrkUp \n' : Gap05[3] and insB05[2] and insB05[1] and c_Up05 ? s_4 +s05 +' =BrkUp \n': s_4 s_4 := Gap06[3] and insB06[2] and insB06[1] and insB06 ? s_4 +s06 +' =InsB \n' : Gap06[3] and insB06[2] and insB06[1] and c_Up06 ? s_4 +s06 +' =BrkUp \n' : Gap06[3] and insB06[2] and insB06[1] and c_Up06 ? s_4 +s06 +' =BrkUp \n': s_4 s_4 := Gap07[3] and insB07[2] and insB07[1] and insB07 ? s_4 +s07 +' =InsB \n' : Gap07[3] and insB07[2] and insB07[1] and c_Up07 ? s_4 +s07 +' =BrkUp \n' : Gap07[3] and insB07[2] and insB07[1] and c_Up07 ? s_4 +s07 +' =BrkUp \n': s_4 s_4 := Gap08[3] and insB08[2] and insB08[1] and insB08 ? s_4 +s08 +' =InsB \n' : Gap08[3] and insB08[2] and insB08[1] and c_Up08 ? s_4 +s08 +' =BrkUp \n' : Gap08[3] and insB08[2] and insB08[1] and c_Up08 ? s_4 +s08 +' =BrkUp \n': s_4 s_4 := Gap09[3] and insB09[2] and insB09[1] and insB09 ? s_4 +s09 +' =InsB \n' : Gap09[3] and insB09[2] and insB09[1] and c_Up09 ? s_4 +s09 +' =BrkUp \n' : Gap09[3] and insB09[2] and insB09[1] and c_Up09 ? s_4 +s09 +' =BrkUp \n': s_4 s_4 := Gap10[3] and insB10[2] and insB10[1] and insB10 ? s_4 +s10 +' =InsB \n' : Gap10[3] and insB10[2] and insB10[1] and c_Up10 ? s_4 +s10 +' =BrkUp \n' : Gap10[3] and insB10[2] and insB10[1] and c_Up10 ? s_4 +s10 +' =BrkUp \n': s_4 s_4 := Gap11[3] and insB11[2] and insB11[1] and insB11 ? s_4 +s11 +' =InsB \n' : Gap11[3] and insB11[2] and insB11[1] and c_Up11 ? s_4 +s11 +' =BrkUp \n' : Gap11[3] and insB11[2] and insB11[1] and c_Up11 ? s_4 +s11 +' =BrkUp \n': s_4 s_4 := Gap12[3] and insB12[2] and insB12[1] and insB12 ? s_4 +s12 +' =InsB \n' : Gap12[3] and insB12[2] and insB12[1] and c_Up12 ? s_4 +s12 +' =BrkUp \n' : Gap12[3] and insB12[2] and insB12[1] and c_Up12 ? s_4 +s12 +' =BrkUp \n': s_4 s_4 := Gap13[3] and insB13[2] and insB13[1] and insB13 ? s_4 +s13 +' =InsB \n' : Gap13[3] and insB13[2] and insB13[1] and c_Up13 ? s_4 +s13 +' =BrkUp \n' : Gap13[3] and insB13[2] and insB13[1] and c_Up13 ? s_4 +s13 +' =BrkUp \n': s_4 s_4 := Gap14[3] and insB14[2] and insB14[1] and insB14 ? s_4 +s14 +' =InsB \n' : Gap14[3] and insB14[2] and insB14[1] and c_Up14 ? s_4 +s14 +' =BrkUp \n' : Gap14[3] and insB14[2] and insB14[1] and c_Up14 ? s_4 +s14 +' =BrkUp \n': s_4 s_4 := Gap15[3] and insB15[2] and insB15[1] and insB15 ? s_4 +s15 +' =InsB \n' : Gap15[3] and insB15[2] and insB15[1] and c_Up15 ? s_4 +s15 +' =BrkUp \n' : Gap15[3] and insB15[2] and insB15[1] and c_Up15 ? s_4 +s15 +' =BrkUp \n': s_4 s_4 := Gap16[3] and insB16[2] and insB16[1] and insB16 ? s_4 +s16 +' =InsB \n' : Gap16[3] and insB16[2] and insB16[1] and c_Up16 ? s_4 +s16 +' =BrkUp \n' : Gap16[3] and insB16[2] and insB16[1] and c_Up16 ? s_4 +s16 +' =BrkUp \n': s_4 s_4 := Gap17[3] and insB17[2] and insB17[1] and insB17 ? s_4 +s17 +' =InsB \n' : Gap17[3] and insB17[2] and insB17[1] and c_Up17 ? s_4 +s17 +' =BrkUp \n' : Gap17[3] and insB17[2] and insB17[1] and c_Up17 ? s_4 +s17 +' =BrkUp \n': s_4 s_4 := Gap18[3] and insB18[2] and insB18[1] and insB18 ? s_4 +s18 +' =InsB \n' : Gap18[3] and insB18[2] and insB18[1] and c_Up18 ? s_4 +s18 +' =BrkUp \n' : Gap18[3] and insB18[2] and insB18[1] and c_Up18 ? s_4 +s18 +' =BrkUp \n': s_4 s_4 := Gap19[3] and insB19[2] and insB19[1] and insB19 ? s_4 +s19 +' =InsB \n' : Gap19[3] and insB19[2] and insB19[1] and c_Up19 ? s_4 +s19 +' =BrkUp \n' : Gap19[3] and insB19[2] and insB19[1] and c_Up19 ? s_4 +s19 +' =BrkUp \n': s_4 s_4 := Gap20[3] and insB20[2] and insB20[1] and insB20 ? s_4 +s20 +' =InsB \n' : Gap20[3] and insB20[2] and insB20[1] and c_Up20 ? s_4 +s20 +' =BrkUp \n' : Gap20[3] and insB20[2] and insB20[1] and c_Up20 ? s_4 +s20 +' =BrkUp \n': s_4 table.cell(table_id = UpTabl, column = 0, row = 3, text_color = c_white, text = s_4) table.cell_set_text_size(UpTabl, column = 0, row = 3, text_size= font) plotchar(barNumber and (barssince(is_new_day())+1)==4,char=' ',text="4",color=color.white,location=location.belowbar,editable=false) //plotchar(barNumber and (barssince(is_new_day())+1)==5,char=' ',text="5",color=color.white,location=location.belowbar,editable=false) //plotchar(barNumber and (barssince(is_new_day())+1)==6,char=' ',text="6",color=color.white,location=location.belowbar,editable=false) //plotchar(barNumber and (barssince(is_new_day())+1)==7,char=' ',text="7",color=color.white,location=location.belowbar,editable=false) //plotchar(barNumber and (barssince(is_new_day())+1)==8,char=' ',text="8",color=color.white,location=location.belowbar,editable=false)
Extremely high win rate FOREX swing strategy
https://www.tradingview.com/script/8hZoUlTI-Extremely-high-win-rate-FOREX-swing-strategy/
exlux99
https://www.tradingview.com/u/exlux99/
507
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © exlux99 //@version=4 strategy("Very high win rate strategy", overlay=true) // fast_length =12 slow_length= 26 src = close signal_length = 9 sma_source = false sma_signal = false // Calculating fast_ma = sma_source ? sma(src, fast_length) : ema(src, fast_length) slow_ma = sma_source ? sma(src, slow_length) : ema(src, slow_length) macd = fast_ma - slow_ma signal = sma_signal ? sma(macd, signal_length) : ema(macd, signal_length) hist = macd - signal //ma len=10 srca = input(close, title="Source") out = hma(srca, len) fromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31) fromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12) fromYear = input(defval = 2000, title = "From Year", minval = 1970) //monday and session // To Date Inputs toDay = input(defval = 31, title = "To Day", minval = 1, maxval = 31) toMonth = input(defval = 12, title = "To Month", minval = 1, maxval = 12) toYear = input(defval = 2021, title = "To Year", minval = 1970) startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00) finishDate = timestamp(toYear, toMonth, toDay, 00, 00) time_cond = time >= startDate and time <= finishDate timeinrange(res, sess) => time(res, sess) != 0 // = input('0900-0915', type=input.session, title="My Defined Hours") myspecifictradingtimes = '0900-0915' exittime = '2100-2115' optionmacd=true entrytime = time(timeframe.period, myspecifictradingtimes) != 0 exit = time(timeframe.period, exittime) != 0 if(time_cond and optionmacd ) if(close > open and close[1] > open[1] and close[2] > open[2] and entrytime and crossover(hist,0)) strategy.entry("long",1) if(close< open and close[1] < open[1] and close[2] < open[2] and entrytime and crossunder(hist,0)) strategy.entry("short",0) tp = input(0.0003, title="tp") //tp = 0.0003 sl = input(1.0 , title="sl") //sl = 1.0 strategy.exit("closelong", "long" , profit = close * tp / syminfo.mintick, loss = close * sl / syminfo.mintick, alert_message = "closelong") strategy.exit("closeshort", "short" , profit = close * tp / syminfo.mintick, loss = close * sl / syminfo.mintick, alert_message = "closeshort")
MACandles-LinearRegression-Strategy
https://www.tradingview.com/script/7ZmLpnJY-MACandles-LinearRegression-Strategy/
Trendoscope
https://www.tradingview.com/u/Trendoscope/
618
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © HeWhoMustNotBeNamed //@version=5 strategy('MACandles-LinearRegression-Strategy', shorttitle='MALinReg - Strategy', overlay=false, initial_capital=100000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, pyramiding=1, commission_value=0.01) resolution = '' MAType = input.string(title='Moving Average Type (MA Candles)', defval='hma', options=['ema', 'sma', 'hma', 'rma', 'vwma', 'wma']) LoopbackBars = input.int(60, title='Length (MA Candles)', step=10) MMAType = input.string(title='Moving Average Type (Momentum)', defval='ema', options=['ema', 'sma', 'hma', 'rma', 'vwma', 'wma']) MLength = input.int(20, title='MA Length (Momentum)', step=10) lb = input.int(40, title='Look Back Period Percentile High/Low', step=10, minval=10, maxval=100) ph = input(.85, title='Highest Percentile - 0.90=90%, 0.95=95%, 0.99=99%') pl = input(1.01, title='Lowest Percentile - 1.10=90%, 1.05=95%, 1.01=99%') mult = input.float(3.0, minval=1, maxval=5, title='Bollinger Band Standard Devaition Up') aggressiveLong = input(true) longTrades = input(true) useVixFix = input(false) i_startTime = input.time(defval=timestamp('01 Jan 2010 00:00 +0000'), title='Start Time') i_endTime = input.time(defval=timestamp('01 Jan 2099 00:00 +0000'), title='End Time') inDateRange = time >= i_startTime and time <= i_endTime f_getMovingAverage(source, MAType, length) => ma = ta.sma(source, length) if MAType == 'ema' ma := ta.ema(source, length) ma if MAType == 'hma' ma := ta.hma(source, length) ma if MAType == 'rma' ma := ta.rma(source, length) ma if MAType == 'vwma' ma := ta.vwma(source, length) ma if MAType == 'wma' ma := ta.wma(source, length) ma ma f_getMACandles(resolution, MAType, LoopbackBars) => oOpen = f_getMovingAverage(open, MAType, LoopbackBars) oClose = f_getMovingAverage(close, MAType, LoopbackBars) oHigh = f_getMovingAverage(high, MAType, LoopbackBars) oLow = f_getMovingAverage(low, MAType, LoopbackBars) [oOpen, oClose, oHigh, oLow] f_getVixFixLinReg(oClose, oLow, MLength) => wvf = (ta.highest(oClose, MLength) - oLow) / ta.highest(oClose, MLength) * 100 sDev = mult * ta.stdev(wvf, MLength) midLine = ta.sma(wvf, MLength) lowerBand = midLine - sDev upperBand = midLine + sDev rangeHigh = ta.highest(wvf, lb) * ph rangeLow = ta.lowest(wvf, lb) * pl col = wvf >= upperBand or wvf >= rangeHigh ? color.lime : color.gray val = ta.linreg(wvf, MLength, 0) absVal = math.abs(val) linRegColor = val > val[1] ? val > 0 ? color.green : color.orange : val > 0 ? color.lime : color.red vixFixState = col == color.lime ? 1 : 0 vixFixState := strategy.position_size == 0 ? math.max(vixFixState, nz(vixFixState[1], 0)) : vixFixState [val, absVal, wvf, col, linRegColor, vixFixState] f_getMACandlesLinReg(oClose, MMAType, MLength, mult, lb, ph, pl) => ma = f_getMovingAverage(oClose, MMAType, MLength) maDiff = oClose - ma val = ta.linreg(maDiff, MLength, 0) absVal = math.abs(val) iff_1 = val > nz(val[1]) ? color.green : color.lime iff_2 = val < nz(val[1]) ? color.red : color.orange linRegColor = val > 0 ? iff_1 : iff_2 sDev = mult * ta.stdev(maDiff, MLength) midLine = ta.sma(maDiff, MLength) lowerBand = midLine - sDev upperBand = midLine + sDev rangeHigh = ta.highest(maDiff, lb) * ph rangeLow = ta.lowest(maDiff, lb) * pl col = maDiff >= upperBand or maDiff >= rangeHigh ? color.lime : maDiff <= lowerBand or maDiff <= rangeLow ? color.orange : color.silver absMaDiff = math.abs(maDiff) [val, absVal, maDiff, absMaDiff, col, linRegColor] f_getSupertrend(resolution, oOpen, oClose, oHigh, oLow, AtrMAType, AtrLength, AtrMult, wicks) => truerange = math.max(oHigh, oClose[1]) - math.min(oLow, oClose[1]) averagetruerange = f_getMovingAverage(truerange, AtrMAType, AtrLength) atr = averagetruerange * AtrMult longWicks = wicks shortWicks = wicks longStop = oClose - atr longStopPrev = nz(longStop[1], longStop) longStop := (longWicks ? oLow[1] : oClose[1]) > longStopPrev ? math.max(longStop, longStopPrev) : longStop shortStop = oClose + atr shortStopPrev = nz(shortStop[1], shortStop) shortStop := (shortWicks ? oHigh[1] : oClose[1]) < shortStopPrev ? math.min(shortStop, shortStopPrev) : shortStop dir = 1 dir := nz(dir[1], dir) dir := dir == -1 and (longWicks ? oHigh : oClose) > shortStopPrev ? 1 : dir == 1 and (shortWicks[1] ? oLow : oClose) < longStopPrev ? -1 : dir [dir, longStop, shortStop] f_getMACandlesAndSupertrend(MAType, LoopbackBars, AtrMult, wicks) => oOpen = f_getMovingAverage(open, MAType, LoopbackBars) oClose = f_getMovingAverage(close, MAType, LoopbackBars) oHigh = f_getMovingAverage(high, MAType, LoopbackBars) oLow = f_getMovingAverage(low, MAType, LoopbackBars) [dir, longStop, shortStop] = f_getSupertrend(resolution, oOpen, oClose, oHigh, oLow, MAType, LoopbackBars, AtrMult, wicks) dir [oOpen, oClose, oHigh, oLow] = f_getMACandles(resolution, MAType, LoopbackBars) dir = f_getMACandlesAndSupertrend('sma', 200, 1, false) colorByPreviousClose = false candleColor = colorByPreviousClose ? oClose[1] < oClose ? color.green : oClose[1] > oClose ? color.red : color.silver : oOpen < oClose ? color.green : oOpen > oClose ? color.red : color.silver [vval, vabsVal, wvf, vcol, vlinRegColor, vixFixState] = f_getVixFixLinReg(oClose, oLow, MLength) [val, absVal, maDiff, absMaDiff, col, linRegColor] = f_getMACandlesLinReg(oClose, MMAType, MLength, mult, lb, ph, pl) plot(useVixFix ? na : absMaDiff, title='Momentum', style=plot.style_histogram, linewidth=4, color=col) plot(useVixFix ? wvf : na, title='VIX Fix', style=plot.style_histogram, linewidth=4, color=vcol) plot(useVixFix ? na : -absVal, title='Linear Regression (Momentum)', style=plot.style_histogram, linewidth=4, color=linRegColor) plot(useVixFix ? -vabsVal : na, title='Linear Regression (VIX Fix)', style=plot.style_histogram, linewidth=4, color=vlinRegColor) exitColor = longTrades ? color.orange : color.silver exitPreviousColor = longTrades ? color.silver : color.lime longCondition = (useVixFix ? vixFixState == 1 and vlinRegColor == color.lime : linRegColor == color.orange and linRegColor[1] == color.red or linRegColor == color.green and linRegColor[1] != color.green and aggressiveLong) and inDateRange and dir > 0 exitLongCondition = col == exitColor and col[1] == exitColor and col[2] == exitPreviousColor and (linRegColor != color.green or not aggressiveLong) strategy.entry('Long', strategy.long, when=longCondition, oca_name='oca_buy', oca_type=strategy.oca.cancel) strategy.close('Long', when=exitLongCondition)
Aroon Strategy long only
https://www.tradingview.com/script/aRzb8R9t-Aroon-Strategy-long-only/
exlux99
https://www.tradingview.com/u/exlux99/
78
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © exlux99 //@version=4 strategy(title = "Aroon Strategy long only", overlay = true, pyramiding=1,initial_capital = 100, 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.1) //Time fromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31) fromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12) fromYear = input(defval = 2010, title = "From Year", minval = 1970) //monday and session // To Date Inputs toDay = input(defval = 31, title = "To Day", minval = 1, maxval = 31) toMonth = input(defval = 12, title = "To Month", minval = 1, maxval = 12) toYear = input(defval = 2021, title = "To Year", minval = 1970) startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00) finishDate = timestamp(toYear, toMonth, toDay, 00, 00) time_cond = time >= startDate and time <= finishDate //INPUTS length = input(15, minval=1, title="Aroon Legnth") upper = 100 * (highestbars(high, length+1) + length)/length lower = 100 * (lowestbars(low, length+1) + length)/length lengthx = input(title="Length LSMA", type=input.integer, defval=20) offset = 0//input(title="Offset", type=input.integer, defval=0) src = input(close, title="Source") lsma = linreg(src, lengthx, offset) long = crossover(upper,lower) and close > lsma longexit = crossunder(upper,lower) and close < lsma if(time_cond) strategy.entry("long",1,when=long) strategy.close("long",when=longexit)
Strategy Template
https://www.tradingview.com/script/yLiA2NgJ-Strategy-Template/
Trendoscope
https://www.tradingview.com/u/Trendoscope/
235
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © HeWhoMustNotBeNamed //@version=4 strategy("Strategy Template", overlay=true, initial_capital = 20000, default_qty_type = strategy.percent_of_equity, default_qty_value = 90, commission_type = strategy.commission.percent, pyramiding = 1, commission_value = 0.01, margin_long=90, margin_short=90, max_lines_count=500, max_labels_count=500, max_boxes_count=500) HigherTimeframe = input("W", type=input.resolution) HTFMAType = input(title="HTF Moving Average Type", defval="hma", options=["ema", "sma", "hma", "rma", "vwma", "wma"]) HTFMaLength= input(20, step=10) HTFUseHighLowRange = input(true) atrLength = input(16, step=5) atrMult = input(3, step=0.5) tradeDirection = input(title="Trade Direction", defval=strategy.direction.all, options=[strategy.direction.all, strategy.direction.long, strategy.direction.short], group="Trade Filters") strategy.risk.allow_entry_in(tradeDirection) i_startTime = input(defval = timestamp("01 Jan 2010 00:00 +0000"), title = "Start Time", type = input.time, group="Trade Filters") i_endTime = input(defval = timestamp("01 Jan 2099 00:00 +0000"), title = "End Time", type = input.time, group="Trade Filters") inDateRange = time >= i_startTime and time <= i_endTime waitForCloseBeforeExit = input(false) f_secureSecurity(_symbol, _res, _src, _offset) => security(_symbol, _res, _src[_offset], lookahead = barmerge.lookahead_on) f_getMovingAverage(source, MAType, length)=> ma = sma(source, length) if(MAType == "ema") ma := ema(source,length) if(MAType == "hma") ma := hma(source,length) if(MAType == "rma") ma := rma(source,length) if(MAType == "vwma") ma := vwma(source,length) if(MAType == "wma") ma := wma(source,length) ma maHTF = f_secureSecurity(syminfo.tickerid, HigherTimeframe, f_getMovingAverage(close, HTFMAType, HTFMaLength), 1) maHTFHigh = f_secureSecurity(syminfo.tickerid, HigherTimeframe, f_getMovingAverage(high, HTFMAType, HTFMaLength), 1) maHTFLow = f_secureSecurity(syminfo.tickerid, HigherTimeframe, f_getMovingAverage(low, HTFMAType, HTFMaLength), 1) [supertrend, dir] = supertrend(atrMult, atrLength) mh = plot(maHTFHigh, "MTF MA High", color=color.new(color.green, 90)) ml = plot(maHTFLow, "MTF MA Low", color=color.new(color.red, 90)) fill(mh, ml, title="No Trade Zone", color=color.new(color.yellow, 50)) plot(strategy.position_size != 0 ? supertrend : na, title="Trailing Stop", color=dir < 0? color.green : color.red, style=plot.style_stepline) buyCondition = crossover(0, dir) and (close > (HTFUseHighLowRange? maHTFHigh : maHTF)) and inDateRange closeBuyCondition = crossunder(0, dir) sellCondition = crossunder(0, dir) and (close < (HTFUseHighLowRange? maHTFLow : maHTF)) and inDateRange closeSellCondition = crossover(0, dir) strategy.entry("Long", strategy.long, when=buyCondition, oca_name="oca_buy", oca_type=strategy.oca.cancel) strategy.close("Long", when=closeBuyCondition and waitForCloseBeforeExit) strategy.exit("ExitLong", "Long", stop=supertrend, when=not waitForCloseBeforeExit) strategy.entry("Short", strategy.short, when=sellCondition, oca_name="oca_sell", oca_type=strategy.oca.cancel) strategy.close("Short", when=closeSellCondition and waitForCloseBeforeExit) strategy.exit("ExitShort", "Short", stop=supertrend, when=not waitForCloseBeforeExit)
Stock trending strategy
https://www.tradingview.com/script/2R1jEdek-Stock-trending-strategy/
exlux99
https://www.tradingview.com/u/exlux99/
147
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © exlux99 //@version=4 strategy("stock trending strategy",overlay=true) len = input(9, minval=1, title="Length") src = input(close, title="Source") out = ema(src, len) fast_length = input(title="Fast Length", type=input.integer, defval=12) slow_length = input(title="Slow Length", type=input.integer, defval=26) signal_length = input(title="Signal Smoothing", type=input.integer, minval = 1, maxval = 50, defval = 9) sma_source = input(title="Simple MA(Oscillator)", type=input.bool, defval=false) sma_signal = input(title="Simple MA(Signal Line)", type=input.bool, defval=false) // Calculating fast_ma = sma_source ? sma(src, fast_length) : ema(src, fast_length) slow_ma = sma_source ? sma(src, slow_length) : ema(src, slow_length) macd = fast_ma - slow_ma signal = sma_signal ? sma(macd, signal_length) : ema(macd, signal_length) hist = macd - signal long = close > vwap and close > out and crossover(hist[1],0) and hist > hist[1] short = close < vwap and close < out and crossunder(hist[1],0) and hist < hist[1] strategy.entry("long",1,when= long) //strategy.entry("short",0,when=short) strategy.close("long", when = crossunder(hist,0)) //strategy.close("short", when = crossover(hist,0))
Ichimoku with MACD/ CMF/ TSI
https://www.tradingview.com/script/uxauGSXV-Ichimoku-with-MACD-CMF-TSI/
exlux99
https://www.tradingview.com/u/exlux99/
217
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © exlux99 //@version=4 strategy("Ichimoku with MACD/ CMF/ TSI", overlay=true, margin_long=0, margin_short=0) //Inputs ts_bars = input(10, minval=1, title="Tenkan-Sen Bars") ks_bars = input(30, minval=1, title="Kijun-Sen Bars") ssb_bars = input(52, minval=1, title="Senkou-Span B Bars") cs_offset = input(26, minval=1, title="Chikou-Span Offset") ss_offset = input(26, minval=1, title="Senkou-Span Offset") long_entry = input(true, title="Long Entry") short_entry = input(true, title="Short Entry") middle(len) => avg(lowest(len), highest(len)) // Ichimoku Components tenkan = middle(ts_bars) kijun = middle(ks_bars) senkouA = avg(tenkan, kijun) senkouB = middle(ssb_bars) ss_high = max(senkouA[ss_offset-1], senkouB[ss_offset-1]) ss_low = min(senkouA[ss_offset-1], senkouB[ss_offset-1]) // Entry/Exit Signals fast_length = input(title="Fast Length", type=input.integer, defval=17) slow_length = input(title="Slow Length", type=input.integer, defval=28) src = input(title="Source", type=input.source, defval=close) signal_length = input(title="Signal Smoothing", type=input.integer, minval = 1, maxval = 50, defval = 5) sma_source = input(title="Simple MA(Oscillator)", type=input.bool, defval=true) sma_signal = input(title="Simple MA(Signal Line)", type=input.bool, defval=true) // Calculating fast_ma = sma_source ? sma(src, fast_length) : ema(src, fast_length) slow_ma = sma_source ? sma(src, slow_length) : ema(src, slow_length) macd = fast_ma - slow_ma signal = sma_signal ? sma(macd, signal_length) : ema(macd, signal_length) hist = macd - signal tk_cross_bull = tenkan > kijun tk_cross_bear = tenkan < kijun cs_cross_bull = mom(close, cs_offset-1) > 0 cs_cross_bear = mom(close, cs_offset-1) < 0 price_above_kumo = close > ss_high price_below_kumo = close < ss_low //CMF lengthA = input(8, minval=1, title="CMF Length") ad = close==high and close==low or high==low ? 0 : ((2*close-low-high)/(high-low))*volume mf = sum(ad, lengthA) / sum(volume, lengthA) //TSI long = input(title="Long Length", type=input.integer, defval=8) short = input(title="Short Length", type=input.integer, defval=8) price = close double_smooth(src, long, short) => fist_smooth = ema(src, long) ema(fist_smooth, short) pc = change(price) double_smoothed_pc = double_smooth(pc, long, short) double_smoothed_abs_pc = double_smooth(abs(pc), long, short) tsi_value = 100 * (double_smoothed_pc / double_smoothed_abs_pc) bullish = tk_cross_bull and cs_cross_bull and price_above_kumo and hist > 0 and mf > 0.1 and tsi_value > 0 bearish = tk_cross_bear and cs_cross_bear and price_below_kumo and hist < 0 and mf < -0.1 and tsi_value < 0 strategy.entry("Long", strategy.long, when=bullish and long_entry) strategy.entry("Short", strategy.short, when=bearish and short_entry) strategy.close("Long", when=bearish and not short_entry) strategy.close("Short", when=bullish and not long_entry)
Vwap mtf Swing Stock Strategy
https://www.tradingview.com/script/1Jt9c9Lk-Vwap-mtf-Swing-Stock-Strategy/
exlux99
https://www.tradingview.com/u/exlux99/
145
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © exlux99 //@version=4 strategy(title="VWAP MTF STOCK STRATEGY", overlay=true, initial_capital = 1000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=0, pyramiding=1 ) // high^2 / 2 - low^2 -2 h=pow(high,2) / 2 l=pow(low,2) / 2 o=pow(open,2) /2 c=pow(close,2) /2 x=(h+l+o+c) / 4 y= sqrt(x) source = y useTrueRange = false length = input(27, minval=1) mult = input(0, step=0.1) ma = sma(source, length) range = useTrueRange ? tr : high - low rangema = sma(range, length) upper = ma + rangema * mult lower = ma - rangema * mult crossUpper = crossover(source, upper) crossLower = crossunder(source, lower) bprice = 0.0 bprice := crossUpper ? high+syminfo.mintick : nz(bprice[1]) sprice = 0.0 sprice := crossLower ? low -syminfo.mintick : nz(sprice[1]) crossBcond = false crossBcond := crossUpper ? true : na(crossBcond[1]) ? false : crossBcond[1] crossScond = false crossScond := crossLower ? true : na(crossScond[1]) ? false : crossScond[1] cancelBcond = crossBcond and (source < ma or high >= bprice ) cancelScond = crossScond and (source > ma or low <= sprice ) longOnly = true fromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31) fromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12) fromYear = input(defval = 2000, title = "From Year", minval = 1970) //monday and session // To Date Inputs toDay = input(defval = 31, title = "To Day", minval = 1, maxval = 31) toMonth = input(defval = 12, title = "To Month", minval = 1, maxval = 12) toYear = input(defval = 2021, title = "To Year", minval = 1970) startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00) finishDate = timestamp(toYear, toMonth, toDay, 00, 00) time_cond = time >= startDate and time <= finishDate srcX = input(ohlc4) t = time("W") start = na(t[1]) or t > t[1] sumSrc = srcX * volume sumVol = volume sumSrc := start ? sumSrc : sumSrc + sumSrc[1] sumVol := start ? sumVol : sumVol + sumVol[1] vwapW= sumSrc / sumVol //crossUpper = crossover(source, upper) //crossLower = crossunder(source, lower) shortCondition = close < vwap and time_cond and (close < vwapW) longCondition = close > vwap and time_cond and (close > vwapW) if(longOnly and time_cond) if (crossLower and close < vwapW ) strategy.close("long") if (crossUpper and close>vwapW) strategy.entry("long", strategy.long, stop=bprice)
Timeframe Time of Day Buying and Selling Strategy
https://www.tradingview.com/script/QKYQ6Tof-Timeframe-Time-of-Day-Buying-and-Selling-Strategy/
tormunddookie
https://www.tradingview.com/u/tormunddookie/
146
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ //@version=4 strategy("Timeframe Time of Day Buying and Selling Strategy", overlay=true, currency=currency.USD, default_qty_value=1.0,initial_capital=30000.00,default_qty_type=strategy.percent_of_equity) frommonth = input(defval = 6, minval = 01, maxval = 12, title = "From Month") fromday = input(defval = 14, minval = 01, maxval = 31, title = "From day") fromyear = input(defval = 2021, minval = 1900, maxval = 2100, title = "From Year") tomonth = input(defval = 12, minval = 01, maxval = 12, title = "To Month") today = input(defval = 31, minval = 01, maxval = 31, title = "To day") toyear = input(defval = 2100, minval = 1900, maxval = 2100, title = "To Year") timeframes = array.new_string(48, '') timeframes_options = array.new_string(49, 'None') array.set(timeframes,0,'2330-0000') array.set(timeframes_options,0, input(defval='None', options=['Long','Short','None'], title='0000-0030')) array.set(timeframes,1,'0000-0030') array.set(timeframes_options,1, input(defval='Long', options=['Long','Short','None'], title='0030-0100')) array.set(timeframes,2,'0030-0100') array.set(timeframes_options,2, input(defval='Long', options=['Long','Short','None'], title='0100-0130')) array.set(timeframes,3,'0100-0130') array.set(timeframes_options,3, input(defval='Long', options=['Long','Short','None'], title='0130-0200')) array.set(timeframes,4,'0130-0200') array.set(timeframes_options,4, input(defval='Long', options=['Long','Short','None'], title='0200-0230')) array.set(timeframes,5,'0200-0230') array.set(timeframes_options,5, input(defval='None', options=['Long','Short','None'], title='0230-0300')) array.set(timeframes,6,'0230-0300') array.set(timeframes_options,6, input(defval='None', options=['Long','Short','None'], title='0300-0330')) array.set(timeframes,7,'0300-0330') array.set(timeframes_options,7, input(defval='None', options=['Long','Short','None'], title='0330-0400')) array.set(timeframes,8,'0330-0400') array.set(timeframes_options,8, input(defval='None', options=['Long','Short','None'], title='0400-0430')) array.set(timeframes,9,'0400-0430') array.set(timeframes_options,9, input(defval='None', options=['Long','Short','None'], title='0430-0500')) array.set(timeframes,10,'0430-0500') array.set(timeframes_options,10, input(defval='None', options=['Long','Short','None'], title='0500-0530')) array.set(timeframes,11,'0500-0530') array.set(timeframes_options,11, input(defval='None', options=['Long','Short','None'], title='0530-0600')) array.set(timeframes,12,'0530-0600') array.set(timeframes_options,12, input(defval='None', options=['Long','Short','None'], title='0600-0630')) array.set(timeframes,13,'0600-0630') array.set(timeframes_options,13, input(defval='None', options=['Long','Short','None'], title='0630-0700')) array.set(timeframes,14,'0630-0700') array.set(timeframes_options,14, input(defval='None', options=['Long','Short','None'], title='0700-0730')) array.set(timeframes,15,'0700-0730') array.set(timeframes_options,15, input(defval='None', options=['Long','Short','None'], title='0730-0800')) array.set(timeframes,16,'0730-0800') array.set(timeframes_options,16, input(defval='None', options=['Long','Short','None'], title='0800-0830')) array.set(timeframes,17,'0800-0830') array.set(timeframes_options,17, input(defval='None', options=['Long','Short','None'], title='0830-0900')) array.set(timeframes,18,'0830-0900') array.set(timeframes_options,18, input(defval='None', options=['Long','Short','None'], title='0900-0930')) array.set(timeframes,19,'0900-0930') array.set(timeframes_options,19, input(defval='None', options=['Long','Short','None'], title='0930-1000')) array.set(timeframes,20,'0930-1000') array.set(timeframes_options,20, input(defval='None', options=['Long','Short','None'], title='1000-1030')) array.set(timeframes,21,'1000-1030') array.set(timeframes_options,21, input(defval='None', options=['Long','Short','None'], title='1030-1100')) array.set(timeframes,22,'1030-1100') array.set(timeframes_options,22, input(defval='None', options=['Long','Short','None'], title='1100-1130')) array.set(timeframes,23,'1100-1130') array.set(timeframes_options,23, input(defval='None', options=['Long','Short','None'], title='1130-1200')) array.set(timeframes,24,'1130-1200') array.set(timeframes_options,24, input(defval='None', options=['Long','Short','None'], title='1200-1230')) array.set(timeframes,25,'1200-1230') array.set(timeframes_options,25, input(defval='None', options=['Long','Short','None'], title='1230-1300')) array.set(timeframes,26,'1230-1300') array.set(timeframes_options,26, input(defval='None', options=['Long','Short','None'], title='1300-1330')) array.set(timeframes,27,'1300-1330') array.set(timeframes_options,27, input(defval='None', options=['Long','Short','None'], title='1330-1400')) array.set(timeframes,28,'1330-1400') array.set(timeframes_options,28, input(defval='None', options=['Long','Short','None'], title='1400-1430')) array.set(timeframes,29,'1400-1430') array.set(timeframes_options,29, input(defval='None', options=['Long','Short','None'], title='1430-1500')) array.set(timeframes,30,'1430-1500') array.set(timeframes_options,30, input(defval='None', options=['Long','Short','None'], title='1500-1530')) array.set(timeframes,31,'1500-1530') array.set(timeframes_options,31, input(defval='None', options=['Long','Short','None'], title='1530-1600')) array.set(timeframes,32,'1530-1600') array.set(timeframes_options,32, input(defval='None', options=['Long','Short','None'], title='1600-1630')) array.set(timeframes,33,'1600-1630') array.set(timeframes_options,33, input(defval='None', options=['Long','Short','None'], title='1630-1700')) array.set(timeframes,34,'1630-1700') array.set(timeframes_options,34, input(defval='None', options=['Long','Short','None'], title='1700-1730')) array.set(timeframes,35,'1700-1730') array.set(timeframes_options,35, input(defval='None', options=['Long','Short','None'], title='1730-1800')) array.set(timeframes,36,'1730-1800') array.set(timeframes_options,36, input(defval='None', options=['Long','Short','None'], title='1800-1830')) array.set(timeframes,37,'1800-1830') array.set(timeframes_options,37, input(defval='None', options=['Long','Short','None'], title='1830-1900')) array.set(timeframes,38,'1830-1900') array.set(timeframes_options,38, input(defval='None', options=['Long','Short','None'], title='1900-0930')) array.set(timeframes,39,'1900-0930') array.set(timeframes_options,39, input(defval='None', options=['Long','Short','None'], title='1930-2000')) array.set(timeframes,40,'1930-2000') array.set(timeframes_options,40, input(defval='None', options=['Long','Short','None'], title='2000-2030')) array.set(timeframes,41,'2000-2030') array.set(timeframes_options,41, input(defval='None', options=['Long','Short','None'], title='2030-2100')) array.set(timeframes,42,'2030-2100') array.set(timeframes_options,42, input(defval='None', options=['Long','Short','None'], title='2100-2130')) array.set(timeframes,43,'2100-2130') array.set(timeframes_options,43, input(defval='None', options=['Long','Short','None'], title='2130-2200')) array.set(timeframes,44,'2130-2200') array.set(timeframes_options,44, input(defval='None', options=['Long','Short','None'], title='2200-2230')) array.set(timeframes,45,'2200-2230') array.set(timeframes_options,45, input(defval='None', options=['Long','Short','None'], title='2230-2300')) array.set(timeframes,46,'2230-2300') array.set(timeframes_options,46, input(defval='None', options=['Long','Short','None'], title='2300-2330')) array.set(timeframes,47,'2300-2330') array.set(timeframes_options,47, input(defval='None', options=['Long','Short','None'], title='2330-0000')) string_hour = hour<10?'0'+tostring(hour):tostring(hour) string_minute = minute<10?'0'+tostring(minute):tostring(minute) current_time = string_hour+string_minute f_strLeft(_str, _n) => string[] _chars = str.split(_str, "") int _len = array.size(_chars) int _end = min(_len, max(0, _n)) string[] _substr = array.new_string(0) if _end <= _len _substr := array.slice(_chars, 0, _end) string _return = array.join(_substr, "") f_strRight(_str, _n) => string[] _chars = str.split(_str, "") int _len = array.size(_chars) int _beg = max(0, _len - _n) string[] _substr = array.new_string(0) if _beg < _len _substr := array.slice(_chars, _beg, _len) string _return = array.join(_substr, "") for i = 0 to array.size(timeframes) - 1 start_time = f_strLeft(array.get(timeframes, i), 4) end_time = f_strRight(array.get(timeframes, i), 4) if current_time == end_time and array.get(timeframes_options, i)!='None' and array.get(timeframes_options, i) != array.get(timeframes_options, i==47?0:i+1) and timestamp(toyear, tomonth, today, 00, 00) strategy.close_all() if current_time == start_time and array.get(timeframes_options, i)!='None' and array.get(timeframes_options, i) != array.get(timeframes_options, i==0?47:i-1) if array.get(timeframes_options, i) == 'Long' strategy.entry("Long", strategy.long, when=(time > timestamp(fromyear, frommonth, fromday, 00, 00) and time < timestamp(toyear, tomonth, today, 00, 00))) else if array.get(timeframes_options, i) == 'Short' strategy.entry("Short", strategy.short, when=(time > timestamp(fromyear, frommonth, fromday, 00, 00) and time < timestamp(toyear, tomonth, today, 00, 00)))
Day of Week Custom Buy/Sell Strategy
https://www.tradingview.com/script/G2PgBrdL-Day-of-Week-Custom-Buy-Sell-Strategy/
tormunddookie
https://www.tradingview.com/u/tormunddookie/
103
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ //@version=4 strategy("Day of Week Custom Buy/Sell Strategy", overlay=true, currency=currency.USD, default_qty_value=1.0,initial_capital=30000.00,default_qty_type=strategy.percent_of_equity) frommonth = input(defval = 6, minval = 01, maxval = 12, title = "From Month") fromday = input(defval = 14, minval = 01, maxval = 31, title = "From day") fromyear = input(defval = 2021, minval = 1900, maxval = 2100, title = "From Year") tomonth = input(defval = 12, minval = 01, maxval = 12, title = "To Month") today = input(defval = 31, minval = 01, maxval = 31, title = "To day") toyear = input(defval = 2100, minval = 1900, maxval = 2100, title = "To Year") timeframes = array.new_int(7, 1) timeframes_options = array.new_string(7, 'None') array.set(timeframes,0,7) array.set(timeframes_options,0, input(defval='None', options=['Long','Short','None'], title='sunday')) array.set(timeframes,1,1) array.set(timeframes_options,1, input(defval='Long', options=['Long','Short','None'], title='monday')) array.set(timeframes,2,2) array.set(timeframes_options,2, input(defval='Long', options=['Long','Short','None'], title='tuesday')) array.set(timeframes,3,3) array.set(timeframes_options,3, input(defval='Long', options=['Long','Short','None'], title='wednesday')) array.set(timeframes,4,4) array.set(timeframes_options,4, input(defval='None', options=['Long','Short','None'], title='thursday')) array.set(timeframes,5,5) array.set(timeframes_options,5, input(defval='None', options=['Long','Short','None'], title='friday')) array.set(timeframes,6,6) array.set(timeframes_options,6, input(defval='None', options=['Long','Short','None'], title='saturday')) for i = 0 to array.size(timeframes) - 1 if dayofweek == array.get(timeframes, i) and array.get(timeframes_options, i) != array.get(timeframes_options, i==0?6:i-1) strategy.close_all() if dayofweek == array.get(timeframes, i) and array.get(timeframes_options, i)!='None' and array.get(timeframes_options, i) != array.get(timeframes_options, i==0?6:i-1) if array.get(timeframes_options, i) == 'Long' strategy.entry("Long", strategy.long, when=(time > timestamp(fromyear, frommonth, fromday, 00, 00) and time < timestamp(toyear, tomonth, today, 00, 00))) else if array.get(timeframes_options, i) == 'Short' strategy.entry("Short", strategy.short, when=(time > timestamp(fromyear, frommonth, fromday, 00, 00) and time < timestamp(toyear, tomonth, today, 00, 00)))
Delayed RSI Strategy
https://www.tradingview.com/script/eagysf5P-Delayed-RSI-Strategy/
tweakerID
https://www.tradingview.com/u/tweakerID/
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/ // © tweakerID and © BacktestRookies // This strategy uses a 21 period RSI with an overbought (RSI indicator // is greater than) level of 60 (user defined) to determines long entries and an oversold // (RSI indicator is less than) level of 40 (user defined) for shorts. It introduces a bar delay that starts // counting when the RSI < Oversold or RSI > Overbought conditions are true, delaying the entry with // the amount of bars determined by the user. The trading logic can be reversed, which seems to work better. //@version=4 strategy("Delayed RSI Strategy", overlay=false, default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=10000, commission_value=0.04, calc_on_every_tick=false, slippage=0) direction = input(0, title = "Strategy Direction", type=input.integer, minval=-1, maxval=1) strategy.risk.allow_entry_in(direction == 0 ? strategy.direction.all : (direction < 0 ? strategy.direction.short : strategy.direction.long)) // Bought and Sold Boolean Signal bought = strategy.position_size > strategy.position_size[1] or strategy.position_size < strategy.position_size[1] /////////////////////// STRATEGY INPUTS //////////////////////////////////////// title1=input(true, "-----------------Strategy Inputs-------------------") rsiLen=input(21, title="RSI Length") i_OB = input(60, title="Overbought") i_OS = input(40, title="Oversold") i_delay = input(15, title="Entry Delay (# of Bars)") i_Close= input(false, title="Use Strategy Close") /////////////////////// BACKTESTER ///////////////////////////////////////////// title2=input(true, "-----------------General Inputs-------------------") // Backtester General Inputs i_SL=input(true, title="Use Stop Loss and Take Profit") TS=input(false, title="Use Trailing Stop") i_SLType=input(defval="ATR Stop", title="Type Of Stop", options=["Strategy Stop", "Swing Lo/Hi", "ATR Stop"]) i_SPL=input(defval=10, title="Swing Point Lookback") i_PercIncrement=input(defval=3, step=.1, title="Swing Point SL Perc Increment")*0.01 i_ATR = input(14, title="ATR Length") i_ATRMult = input(3, step=.1, title="ATR Multiple") i_TPRRR = input(2, step=.1, title="Take Profit Risk Reward Ratio") DPR=input(false, "Allow Direct Position Reverse") reverse=input(true, "Reverse Trades") // Swing Points Stop and Take Profit SwingStopProfit() => LL=(lowest(i_SPL))*(1-i_PercIncrement) HH=(highest(i_SPL))*(1+i_PercIncrement) LL_price = valuewhen(bought, LL, 0) HH_price = valuewhen(bought, HH, 0) entry_LL_price = strategy.position_size > 0 ? LL_price : na entry_HH_price = strategy.position_size < 0 ? HH_price : na tp=strategy.position_avg_price + (strategy.position_avg_price - entry_LL_price)*i_TPRRR stp=strategy.position_avg_price - (entry_HH_price - strategy.position_avg_price)*i_TPRRR [entry_LL_price, entry_HH_price, tp, stp] // ATR Stop ATRStop() => ATR=atr(i_ATR)*i_ATRMult ATRLong = ohlc4 - ATR ATRShort = ohlc4 + ATR ATRLongStop = valuewhen(bought, ATRLong, 0) ATRShortStop = valuewhen(bought, ATRShort, 0) LongSL_ATR_price = strategy.position_size > 0 ? ATRLongStop : na ShortSL_ATR_price = strategy.position_size < 0 ? ATRShortStop : na ATRtp=strategy.position_avg_price + (strategy.position_avg_price - LongSL_ATR_price)*i_TPRRR ATRstp=strategy.position_avg_price - (ShortSL_ATR_price - strategy.position_avg_price)*i_TPRRR [LongSL_ATR_price, ShortSL_ATR_price, ATRtp, ATRstp] // Strategy Stop StrategyStop(bought) => float LongStop = na float ShortStop = na float StratTP = na float StratSTP = na [LongStop, ShortStop, StratTP, StratSTP] //TrailingStop TrailingStop(SL,SSL) => dif=(valuewhen(strategy.position_size>0 and strategy.position_size[1]<=0, high,0)) -strategy.position_avg_price trailOffset = strategy.position_avg_price - SL var tstop = float(na) if strategy.position_size > 0 tstop := high- trailOffset - dif if tstop<tstop[1] tstop:=tstop[1] else tstop := na StrailOffset = SSL - strategy.position_avg_price var Ststop = float(na) Sdif=strategy.position_avg_price-(valuewhen(strategy.position_size<0 and strategy.position_size[1]>=0, low,0)) if strategy.position_size < 0 Ststop := low+ StrailOffset + Sdif if Ststop>Ststop[1] Ststop:=Ststop[1] else Ststop := na [tstop, Ststop] //Stop Loss & Take Profit Switches SLTPLogic(LongStop, ShortStop, StratTP, StratSTP, LongSL_ATR_price, ShortSL_ATR_price, ATRtp, ATRstp, entry_LL_price, entry_HH_price, tp, stp) => SL= i_SLType == "Swing Lo/Hi" ? entry_LL_price : i_SLType == "ATR Stop" ? LongSL_ATR_price : LongStop SSL= i_SLType == "Swing Lo/Hi" ? entry_HH_price : i_SLType == "ATR Stop" ? ShortSL_ATR_price : ShortStop TP= i_SLType == "Swing Lo/Hi" ? tp : i_SLType == "ATR Stop" ? ATRtp : StratTP STP= i_SLType == "Swing Lo/Hi" ? stp : i_SLType == "ATR Stop" ? ATRstp : StratSTP [SL, SSL, TP, STP] /////////////////////// STRATEGY LOGIC ///////////////////////////////////////// rsi = rsi(close, rsiLen) isOB= rsi > i_OB isOS= rsi < i_OS BarsSinceOB = barssince(not isOB) BarsSinceOS = barssince(not isOS) BUY = BarsSinceOS == i_delay SELL = BarsSinceOB == i_delay /////////////////////// FUNCTION CALLS ///////////////////////////////////////// // Stops and Profits [entry_LL_price, entry_HH_price, tp, stp] = SwingStopProfit() [LongSL_ATR_price, ShortSL_ATR_price, ATRtp, ATRstp] = ATRStop() [LongStop, ShortStop, StratTP, StratSTP] = StrategyStop(bought) [SL, SSL, TP, STP] = SLTPLogic(LongStop, ShortStop, StratTP, StratSTP, LongSL_ATR_price, ShortSL_ATR_price, ATRtp, ATRstp, entry_LL_price, entry_HH_price, tp, stp) [tstop, Ststop] = TrailingStop(SL,SSL) // Entries if reverse if not DPR strategy.entry("long", strategy.long, when=SELL and strategy.position_size == 0) strategy.entry("short", strategy.short, when=BUY and strategy.position_size == 0) else strategy.entry("long", strategy.long, when=SELL) strategy.entry("short", strategy.short, when=BUY) else if not DPR strategy.entry("long", strategy.long, when=BUY and strategy.position_size == 0) strategy.entry("short", strategy.short, when=SELL and strategy.position_size == 0) else strategy.entry("long", strategy.long, when=BUY) strategy.entry("short", strategy.short, when=SELL) // Exits if i_SL strategy.exit("TP & SL", "long", limit=TP, stop=TS? tstop : SL) strategy.exit("TP & SL", "short", limit=STP, stop=TS? Ststop : SSL) if i_Close strategy.close_all(when=cross(rsi, 50)) /////////////////////// PLOTS ////////////////////////////////////////////////// //Plots rsiplot = plot(rsi, "RSI", color=#7E57C2) band1 = hline(i_OB, "Upper Band", color=#787B86) bandm = hline(50, "Middle Band", color=color.new(#787B86, 50)) band0 = hline(i_OS, "Lower Band", color=#787B86) fill(band1, band0, color=color.rgb(126, 87, 194, 90), title="Background") plot(rsi, "RSI", color=#7E57C2) OSOBCount = plot(isOB ? BarsSinceOB : isOS ? BarsSinceOS : na, transp=100) OSOBColor = color.from_gradient(isOB ? BarsSinceOB : BarsSinceOS, 0, 20, color.black, isOB ? color.red : isOS ? color.green : na) OBP = plot(rsi > i_OB ? rsi : na, color=color.white, display=display.none) fill(plot(i_OB, display=display.none), OBP, color=OSOBColor, transp=0, fillgaps=false) OSP = plot(rsi < i_OS ? rsi : na, color=color.white, display=display.none) fill(plot(i_OS, display=display.none), OSP, color=OSOBColor, transp=0, fillgaps=false) plotshape(BUY ? 1 : na, style=shape.arrowdown, location=location.bottom, color=color.green, title="Bullish Setup", size=size.normal) plotshape(SELL ? 1 : na, style=shape.arrowup, location=location.top, color=color.red, title="Bearish Setup", size=size.normal)
[Advanced] Hilega-Milega Indicator
https://www.tradingview.com/script/rQZMXkcZ-Advanced-Hilega-Milega-Indicator/
HamidBox
https://www.tradingview.com/u/HamidBox/
573
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/ // © HamidBox //@version=4 strategy("H-M By HamidBox-YT", default_qty_type=strategy.cash, default_qty_value= 100, initial_capital=100, currency='USD', commission_type=strategy.commission.percent, commission_value=0.1) ma(source, length, type) => type == "SMA" ? sma(source , length) : type == "EMA" ? ema(source , length) : type == "WMA" ? wma(source , length) : type == "VWMA" ? vwma(source , length) : na WMA(source, length, type) => type == "SMA" ? sma(source , length) : type == "EMA" ? ema(source , length) : type == "WMA" ? wma(source , length) : type == "VWMA" ? vwma(source , length) : na WithMA(source, length, type) => type == "SMA" ? sma(source , length) : type == "EMA" ? ema(source , length) : type == "WMA" ? wma(source , length) : type == "VWMA" ? vwma(source , length) : na rsi_inline = input(true , title="RSI Value)", inline="rsi") rsiLength = input(title="Length:", type=input.integer, defval=9, minval=1, inline="rsi") rsiLineM = input(title="Level:", type=input.integer, defval=50, minval=1, inline="rsi") rsi_OSOBinline = input(true , title="RSI)", inline="rsiosob") rsiLineU = input(title="O-BOUGHT", type=input.integer, defval=70, minval=1, inline="rsiosob") rsiLineD = input(title="O-SOLD", type=input.integer, defval=30, minval=1, inline="rsiosob") ma_inline = input(true , title="Price-MA)", inline="ma") ma_type = input(title="Type", defval="EMA", options=["EMA","SMA","WMA","VWMA"], inline="ma") emaLength = input(title="Length", type=input.integer, defval=3, inline="ma") wma_inline = input(true , title="Trending-MA)", inline="wma") ma_type2 = input(title="", defval="WMA", options=["EMA","SMA","WMA","VWMA"], inline="wma") wmaLength = input(title="Length", type=input.integer, defval=21, inline="wma") //////////////////////////////////////////////////////////////////////////////// startTime = input(title="Start Time", type = input.time, defval = timestamp("01 Jan 2021 00:00 +0000"), group="Backtest Time Period") endTime = input(title="End Time", type = input.time, defval = timestamp("01 Jan 2200 00:00 +0000"), group="Backtest Time Period") inDateRange = (time >= startTime) and (time < endTime) //////////////////////////////////////////////////////////////////////////////// rsi = rsi(close , rsiLength) r = plot(rsi_inline ? rsi : na, color=color.yellow, linewidth=2) EMA = ma(rsi, emaLength, ma_type) e = plot(ma_inline ? EMA : na, color=color.lime) myWMA = ma(rsi, wmaLength, ma_type2) w = plot(wma_inline ? myWMA : na, color=color.white, linewidth=2) up = hline(rsiLineU, title='UP Level', linewidth=1, color=color.red, linestyle=hline.style_dotted) mid = hline(rsiLineM, title='Mid Level', linewidth=2, color=color.white, linestyle=hline.style_dotted) dn = hline(rsiLineD, title='DN Level', linewidth=1, color=color.green, linestyle=hline.style_dotted) col_e_w = EMA > myWMA ? color.new(color.green , 85) : color.new(color.red , 85) col_r_w = rsi > myWMA ? color.new(color.green , 85) : color.new(color.red , 85) fill(e , w, color=col_e_w) fill(r , w, color=col_r_w) //////////////////////////////////////////////////////////////////////////////// //Signals = input(true,group="👇 🚦 --- Backtesting Signals Type --- 🚦 ") /////////////////////////////////////////////////////////////////////////////// RSI_Cross = input(false, "RSI x Trending-MA", inline="wma_cross",group="👇 🚦 --- Backtesting Signals Type --- 🚦 ") // INPUT rsiBuySignal = crossover(rsi , myWMA) plotshape(RSI_Cross ? rsiBuySignal : na, title="RSI Crossover", style=shape.labelup, location=location.bottom, color=color.green) rsiSellSignal = crossunder(rsi , myWMA) plotshape(RSI_Cross ? rsiSellSignal : na, title="RSI Crossunder", style=shape.labeldown, location=location.top, color=color.red) if rsiBuySignal and RSI_Cross and inDateRange strategy.entry("RSIxWMA", strategy.long) if rsiSellSignal and RSI_Cross and inDateRange strategy.close("RSIxWMA", comment="x") if (not inDateRange) strategy.close_all() //////////////////////////////////////////////////////////////////////////////// MA_Cross = input(false, "MA x Trendin-MA",group="👇 🚦 --- Backtesting Signals Type --- 🚦 ") // INPUT maBuySignal = crossover(EMA, myWMA) plotshape(MA_Cross ? maBuySignal : na, title="MA Cross", style=shape.circle, location=location.bottom, color=color.lime) maSellSignal = crossunder(EMA , myWMA) plotshape(MA_Cross ? maSellSignal : na, title="RSI Crossunder", style=shape.circle, location=location.top, color=color.maroon) if maBuySignal and MA_Cross and inDateRange strategy.entry("MAxWMA", strategy.long) if maSellSignal and MA_Cross and inDateRange strategy.close("MAxWMA", comment="x") if (not inDateRange) strategy.close_all() //////////////////////////////////////////////////////////////////////////////// Mix = input(false, "RSI + EMA x Trending-MA",group="👇 🚦 --- Backtesting Signals Type --- 🚦 ") // INPUT rsi_ma_buy = crossover(rsi , myWMA) and crossover(EMA, myWMA) rsi_ma_sell = crossunder(rsi , myWMA) and crossunder(EMA, myWMA) plotshape(Mix ? rsi_ma_buy : na, title="RSI Crossunder", style=shape.circle, location=location.bottom, color=color.lime, size=size.tiny) plotshape(Mix ? rsi_ma_sell : na, title="RSI Crossunder", style=shape.circle, location=location.top, color=color.yellow, size=size.tiny) if rsi_ma_buy and Mix and inDateRange strategy.entry("RSI+EMA x WMA", strategy.long) if rsi_ma_sell and Mix and inDateRange strategy.close("RSI+EMA x WMA", comment="x") if (not inDateRange) strategy.close_all() //////////////////////////////////////////////////////////////////////////////// wma_cross = input(false, "Trending-MA x 50",group="👇 🚦 --- Backtesting Signals Type --- 🚦 ") // INPUT wma_buy = crossover(myWMA , rsiLineM) plotshape(wma_cross ? wma_buy : na, title="WMA Cross", style=shape.diamond, location=location.bottom, color=color.aqua) wma_sell = crossunder(myWMA , rsiLineM) plotshape(wma_cross ? wma_sell : na, title="WMA Cross", style=shape.diamond, location=location.top, color=color.aqua) if wma_buy and wma_cross and inDateRange strategy.entry("WMA x 50", strategy.long) if wma_sell and wma_cross and inDateRange strategy.close("WMA x 50", comment="x") if (not inDateRange) strategy.close_all() //////////////////////////////////////////////////////////////////////////////// rsi_50 = input(false, "RSI x 50",group="👇 🚦 --- Backtesting Signals Type --- 🚦 ") // INPUT rsi_50_buy = crossover(rsi , rsiLineM) plotshape(rsi_50 ? rsi_50_buy : na, title="WMA Cross", style=shape.cross, location=location.bottom, color=color.purple) rsi_50_sell = crossunder(rsi , rsiLineM) plotshape(rsi_50 ? rsi_50_sell : na, title="WMA Cross", style=shape.cross, location=location.top, color=color.purple) if rsi_50_buy and rsi_50 and inDateRange strategy.entry("RSI Cross 50", strategy.long) if rsi_50_sell and rsi_50 and inDateRange strategy.close("RSI Cross 50", comment="x") if (not inDateRange) strategy.close_all() //////////////////////////////////////////////////////////////////////////////// RSI_OS_OB = input(false, "RSI OS/OB x Trending-MA",group="👇 🚦 --- Backtesting Signals Type --- 🚦 ") // INPUT rsi_OB_buy = (rsi < rsiLineD or rsi[1] < rsiLineD[1] or rsi[2] < rsiLineD[2] or rsi[3] < rsiLineD[3] or rsi[4] < rsiLineD[4] or rsi[5] < rsiLineD[5]) and rsiBuySignal plotshape(RSI_OS_OB ? rsi_OB_buy : na, title="RSI OB + Cross", style=shape.circle, location=location.bottom, color=color.lime, size=size.tiny) rsi_OS_sell = (rsi > rsiLineU or rsi[1] > rsiLineU[1] or rsi[2] > rsiLineU[2] or rsi[3] > rsiLineU[3] or rsi[4] > rsiLineU[4] or rsi[5] > rsiLineU[5]) and maSellSignal plotshape(RSI_OS_OB ? rsi_OS_sell : na, title="RSI OS + Cross", style=shape.circle, location=location.top, color=color.red, size=size.tiny) if rsi_OB_buy and RSI_OS_OB and inDateRange strategy.entry("RSI-OBOS x WMA", strategy.long) if rsi_OS_sell and RSI_OS_OB and inDateRange strategy.close("RSI-OBOS x WMA", comment="x") if (not inDateRange) strategy.close_all() //////////////////////////////////////////////////////////////////////////////// rsi_OB_OS = input(false, "RSI Over Sold/Bought",group="👇 🚦 --- Backtesting Signals Type --- 🚦 ") // INPUT rsiBuy = crossover(rsi , rsiLineD) rsiSell = crossunder(rsi, rsiLineU) rsiExit = crossunder(rsi, rsiLineD) plotshape(rsi_OB_OS ? rsiBuy : na, title="RSI OB", style=shape.cross, location=location.bottom, color=color.purple) plotshape(rsi_OB_OS ? crossunder(rsi, rsiLineU) : na, title="RSI OS", style=shape.cross, location=location.top, color=color.purple) plotshape(rsi_OB_OS ? rsiExit : na, title="RSI OS", style=shape.cross, location=location.bottom, color=color.red) if rsiBuy and rsi_OB_OS and inDateRange strategy.entry("RSI OB", strategy.long) if (rsiSell or rsiExit) and rsi_OB_OS and inDateRange strategy.close("RSI OB", comment="x") if (not inDateRange) strategy.close_all() //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// With_MA_Vis = input(true , title="With MA Signal)", inline="WITH MA", group="With MA") withMA_type = input(title="", defval="SMA", options=["EMA","SMA","WMA","VWMA"], inline="WITH MA", group="With MA") with_MALen = input(title="", defval=9, type=input.integer, inline="WITH MA", group="With MA") // TAKE-PROFIT / STOP-LOSS Stop_Take_Vis = input(true, "TP-SL") LongSLValue = input(title="SL %", type=input.float, defval=3, minval=0.5) * 0.01 LongTPValue = input(title="TP %", type=input.float, defval=15, minval=0.5) * 0.01 LongSLDetermine = strategy.position_avg_price * (1 - LongSLValue) LongTPDetermine = strategy.position_avg_price * (1 + LongTPValue) ////////////////////////// with_ma = WithMA(close, with_MALen, withMA_type) Close_buy_MA = crossover(close , with_ma) Close_sell_MA = crossunder(close , with_ma) // PLOT OPTION WithMaSignal = input(false, "MA + RSI x Trending-MA",group="With MA") // INPUT // CONDITION IN VARIABLE withMA_RSI_BUY = (Close_buy_MA and rsiBuySignal) and WithMaSignal and inDateRange withMA_RSI_SELL = (Close_sell_MA and rsiSellSignal) and WithMaSignal and inDateRange // PLOT ING plotshape(WithMaSignal ? withMA_RSI_BUY : na, title="With MA", style=shape.diamond, location=location.bottom, color=color.aqua) plotshape(WithMaSignal ? withMA_RSI_SELL : na, title="With MA", style=shape.diamond, location=location.top, color=color.aqua) if withMA_RSI_BUY strategy.entry("MA + RSIxWMA", strategy.long) if withMA_RSI_SELL strategy.close("MA + RSIxWMA", comment="x") if (not inDateRange) strategy.close_all() // FOR SL - TP if (strategy.position_size > 0) and Stop_Take_Vis strategy.exit("BUY", stop=LongSLDetermine, limit=LongTPDetermine)
Forex Daytrade T3 MA session
https://www.tradingview.com/script/lasK1jNw-Forex-Daytrade-T3-MA-session/
exlux99
https://www.tradingview.com/u/exlux99/
101
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © exlux99 //@version=4 strategy("FOREX Daytrade T3 MA session",overlay=true) fromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31) fromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12) fromYear = input(defval = 2000, title = "From Year", minval = 1970) //monday and session // To Date Inputs toDay = input(defval = 31, title = "To Day", minval = 1, maxval = 31) toMonth = input(defval = 12, title = "To Month", minval = 1, maxval = 12) toYear = input(defval = 2021, title = "To Year", minval = 1970) startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00) finishDate = timestamp(toYear, toMonth, toDay, 00, 00) time_cond = time >= startDate and time <= finishDate timeinrange(res, sess) => time(res, sess) != 0 Length = input(9, minval=1) xPrice = close xe1 = ema(xPrice, Length) xe2 = ema(xe1, Length) xe3 = ema(xe2, Length) xe4 = ema(xe3, Length) xe5 = ema(xe4, Length) xe6 = ema(xe5, Length) b = 0.7 c1 = -b*b*b c2 = 3*b*b+3*b*b*b c3 = -6*b*b-3*b-3*b*b*b c4 = 1+3*b+b*b*b+3*b*b nT3Average = c1 * xe6 + c2 * xe5 + c3 * xe4 + c4 * xe3 plot(nT3Average, color=color.blue, title="T3") myspecifictradingtimes = input('1000-1900', type=input.session, title="My Defined Hours") //myspecifictradingtimes2 = input('1000-1900', type=input.session, title="My Defined Hours") exittime = input('2100-2115', type=input.session, title="exit time") optionmacd=true entrytime = time(timeframe.period, myspecifictradingtimes) != 0 exiton = time(timeframe.period, exittime) != 0 //entrytime2 = time(timeframe.period, myspecifictradingtimes2) != 0 // long =time_cond and (entrytime or entrytime2) and close > high[1] and close > nT3Average // short =time_cond and (entrytime or entrytime2) and close < low[1] and close < nT3Average long =time_cond and (entrytime ) and close > high[1] and close > nT3Average short =time_cond and (entrytime) and close < low[1] and close < nT3Average tp = input(0.01) sl = input(0.01) modified=input(true) inverse=input(true) exit = input(false) if(modified) if(not exiton) if(inverse) strategy.entry("long",1,when=short) strategy.entry("short",0,when=long) /// strategy.exit("xlong","long",profit=200, loss=200) // strategy.exit("xshort","short",profit=200, loss=200) if(inverse==false) strategy.entry("long",1,when=long) strategy.entry("short",0,when=short) if(exit) // strategy.close("long", when = crossover(close,nT3Average)) // strategy.close("short", when = crossunder(close,nT3Average)) strategy.exit("closelong", "long" , profit = close * tp / syminfo.mintick, loss = close * sl / syminfo.mintick, alert_message = "closelong") strategy.exit("closeshort", "short" , profit = close * tp / syminfo.mintick, loss = close * sl / syminfo.mintick, alert_message = "closeshort") if(modified==false) if(inverse) strategy.entry("long",1,when=short) strategy.entry("short",0,when=long) /// strategy.exit("xlong","long",profit=200, loss=200) // strategy.exit("xshort","short",profit=200, loss=200) if(inverse==false) strategy.entry("long",1,when=long) strategy.entry("short",0,when=short) // if(exit) // // strategy.close("long", when = crossover(close,nT3Average)) // // strategy.close("short", when = crossunder(close,nT3Average)) strategy.exit("closelong", "long" , loss = close * sl / syminfo.mintick, alert_message = "closelong") strategy.exit("closeshort", "short" , loss = close * sl / syminfo.mintick, alert_message = "closeshort") //strategy.close_all(when =exiton ) //gbpnzd 10-20 //gbpcad 10-19 //gbpaud 07-19 //euruad 10-19 / 16-20 //eurnzd 08-21 / 10-20 //eurchf 08-20 //gbpchf 06-18 // 18-19settings entry gbp aud, gbpcad gbpnzd ??? 1 entry only big spread //test
BTC Candle Correlation Strategy
https://www.tradingview.com/script/Bp053p4R-BTC-Candle-Correlation-Strategy/
exlux99
https://www.tradingview.com/u/exlux99/
566
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © exlux99 //@version=4 strategy(title="BTC Candle Correlation Strategy", overlay=true, initial_capital = 1000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=0.1, pyramiding=1 ) //sources for average src_c = close src1_c = security("BITFINEX:BTCUSD", timeframe.period, src_c), src2_c = security("POLONIEX:BTCUSDT", timeframe.period, src_c), src3_c = security("BITSTAMP:BTCUSD", timeframe.period, src_c), src4_c = security("COINBASE:BTCUSD", timeframe.period, src_c), src5_c = security("BITMEX:XBTUSD", timeframe.period, src_c), src6_c = security("KRAKEN:XBTUSD", timeframe.period, src_c), src7_c = security("BINANCE:BTCUSDT", timeframe.period, src_c) src_h = high src1_h = security("BITFINEX:BTCUSD", timeframe.period, src_h), src2_h = security("POLONIEX:BTCUSDT", timeframe.period, src_h), src3_h = security("BITSTAMP:BTCUSD", timeframe.period, src_h), src4_h = security("COINBASE:BTCUSD", timeframe.period, src_h), src5_h = security("BITMEX:XBTUSD", timeframe.period, src_h), src6_h = security("KRAKEN:XBTUSD", timeframe.period, src_h), src7_h = security("BINANCE:BTCUSDT", timeframe.period, src_h) src_l = low src1_l = security("BITFINEX:BTCUSD", timeframe.period, src_l), src2_l = security("POLONIEX:BTCUSDT", timeframe.period, src_l), src3_l = security("BITSTAMP:BTCUSD", timeframe.period, src_l), src4_l = security("COINBASE:BTCUSD", timeframe.period, src_l), src5_l = security("BITMEX:XBTUSD", timeframe.period, src_l), src6_l = security("KRAKEN:XBTUSD", timeframe.period, src_l), src7_l = security("BINANCE:BTCUSDT", timeframe.period, src_l) src_o = open src1_o = security("BITFINEX:BTCUSD", timeframe.period, src_o), src2_o = security("POLONIEX:BTCUSDT", timeframe.period, src_o), src3_o = security("BITSTAMP:BTCUSD", timeframe.period, src_o), src4_o = security("COINBASE:BTCUSD", timeframe.period, src_o), src5_o = security("BITMEX:XBTUSD", timeframe.period, src_o), src6_o = security("KRAKEN:XBTUSD", timeframe.period, src_o), src7_o = security("BINANCE:BTCUSDT", timeframe.period, src_o) //declaring variables candle_open = avg(src1_o, src2_o, src3_o, src4_o, src5_o, src6_o, src7_o) candle_high = avg(src1_h, src2_h, src3_h, src4_h, src5_h, src6_h, src7_h) candle_low = avg(src1_l, src2_l, src3_l, src4_l, src5_l, src6_l, src7_l) candle_close = avg(src1_c, src2_c, src3_c, src4_c, src5_c, src6_c, src7_c) //plots //plotcandle(candle_open, candle_high, candle_low, candle_close, title = "Average BTC candles", color = open < close ? color.green : color.red, wickcolor = color.white) ////////////////////////////////////////////////////////// // high^2 / 2 - low^2 -2 h=pow(candle_high,2) / 2 l=pow(candle_low,2) / 2 o=pow(candle_open,2) /2 c=pow(candle_close,2) /2 x=(h+l+o+c) / 4 y= sqrt(x) source = y useTrueRange = false length = input(9, minval=1) mult = input(0.9, step=0.1) ma = sma(source, length) range = useTrueRange ? tr : candle_high - candle_low rangema = sma(range, length) upper = ma + rangema * mult lower = ma - rangema * mult crossUpper = crossover(source, upper) crossLower = crossunder(source, lower) bprice = 0.0 bprice := crossUpper ? candle_high: nz(bprice[1]) sprice = 0.0 sprice := crossLower ? candle_low : nz(sprice[1]) crossBcond = false crossBcond := crossUpper ? true : na(crossBcond[1]) ? false : crossBcond[1] crossScond = false crossScond := crossLower ? true : na(crossScond[1]) ? false : crossScond[1] cancelBcond = crossBcond and (source < ma or candle_high >= bprice ) cancelScond = crossScond and (source > ma or candle_low <= sprice ) longOnly = input(true) fromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31) fromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12) fromYear = input(defval = 2000, title = "From Year", minval = 1970) //monday and session // To Date Inputs toDay = input(defval = 31, title = "To Day", minval = 1, maxval = 31) toMonth = input(defval = 12, title = "To Month", minval = 1, maxval = 12) toYear = input(defval = 2021, title = "To Year", minval = 1970) startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00) finishDate = timestamp(toYear, toMonth, toDay, 00, 00) time_cond = time >= startDate and time <= finishDate if(longOnly==false and time_cond) if (crossLower) strategy.cancel("long") if (crossUpper) strategy.entry("long", strategy.long) if (cancelScond) strategy.cancel("short") if (crossLower) strategy.entry("short", strategy.short) if(longOnly and time_cond) if (crossLower) strategy.close("long") if (crossUpper and candle_close > candle_open) strategy.entry("long", strategy.long)
Money Flow Index 5 min Strategy
https://www.tradingview.com/script/WCGsbjg1-Money-Flow-Index-5-min-Strategy/
tweakerID
https://www.tradingview.com/u/tweakerID/
226
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/ // From "Crypto Day Trading Strategy" PDF file. // * I'm using a SMA filter to avoid buying when the price is declining. Time frame was better at 15 min according to my test. // 1 - Apply the 3 period Money Flow Index indicator to the 5 minute chart, using 0 and 100 as our oversold and overbought boundaries // 2 - Wait for the MFI to reach overbought levels, that indicates the presence of "big sharks" in the market. Price needs to hold up // the first two MFI overbought occurrences of the day to be considered as a bullish entry signal.* // 3 - We buy when the MFI = 100 and the next candle is a bullish candle with short wicks. // 4 - We place our Stop Loss below the low of the trading day and we Take Profit during the first 60 minutes after taking the trade. // The logic above can be used in a mirrored fashion to take short entries, this is a custom parameter that can be modified from // the strategy Inputs panel. // © tweakerID //@version=4 strategy("Money Flow Index 5 min Strategy", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=10000, commission_value=0.04, calc_on_every_tick=false, slippage=0) direction = input(0, title = "Strategy Direction", type=input.integer, minval=-1, maxval=1) strategy.risk.allow_entry_in(direction == 0 ? strategy.direction.all : (direction < 0 ? strategy.direction.short : strategy.direction.long)) /////////////////////// STRATEGY INPUTS //////////////////////////////////////// title1=input(true, "-----------------Strategy Inputs-------------------") i_MFI = input(3, title="MFI Length") OB=input(100, title="Overbought Level") OS=input(0, title="Oversold Level") barsizeThreshold=input(.5, step=.05, minval=.1, maxval=1, title="Bar Body Size, 1=No Wicks") i_MAFilter = input(true, title="Use MA Trend Filter") i_MALen = input(80, title="MA Length") i_timedexit=input(false, title="Use 60 minutes exit rule") short=input(true, title="Use Mirrored logic for Shorts") /////////////////////// BACKTESTER ///////////////////////////////////////////// title2=input(true, "-----------------General Inputs-------------------") // Backtester General Inputs i_SL=input(true, title="Use Stop Loss and Take Profit") i_SLType=input(defval="Strategy Stop", title="Type Of Stop", options=["Strategy Stop", "Swing Lo/Hi", "ATR Stop"]) i_SPL=input(defval=10, title="Swing Point Lookback") i_PercIncrement=input(defval=3, step=.1, title="Swing Point SL Perc Increment")*0.01 i_ATR = input(14, title="ATR Length") i_ATRMult = input(5, step=.1, title="ATR Multiple") i_TPRRR = input(2.2, step=.1, title="Take Profit Risk Reward Ratio") TS=input(false, title="Trailing Stop") // Bought and Sold Boolean Signal bought = strategy.position_size > strategy.position_size[1] or strategy.position_size < strategy.position_size[1] // Price Action Stop and Take Profit LL=(lowest(i_SPL))*(1-i_PercIncrement) HH=(highest(i_SPL))*(1+i_PercIncrement) LL_price = valuewhen(bought, LL, 0) HH_price = valuewhen(bought, HH, 0) entry_LL_price = strategy.position_size > 0 ? LL_price : na entry_HH_price = strategy.position_size < 0 ? HH_price : na tp=strategy.position_avg_price + (strategy.position_avg_price - entry_LL_price)*i_TPRRR stp=strategy.position_avg_price - (entry_HH_price - strategy.position_avg_price)*i_TPRRR // ATR Stop ATR=atr(i_ATR)*i_ATRMult ATRLong = ohlc4 - ATR ATRShort = ohlc4 + ATR ATRLongStop = valuewhen(bought, ATRLong, 0) ATRShortStop = valuewhen(bought, ATRShort, 0) LongSL_ATR_price = strategy.position_size > 0 ? ATRLongStop : na ShortSL_ATR_price = strategy.position_size < 0 ? ATRShortStop : na ATRtp=strategy.position_avg_price + (strategy.position_avg_price - LongSL_ATR_price)*i_TPRRR ATRstp=strategy.position_avg_price - (ShortSL_ATR_price - strategy.position_avg_price)*i_TPRRR // Strategy Stop DayStart = time == timestamp("UTC", year, month, dayofmonth, 0, 0, 0) plot(DayStart ? 1e9 : na, style=plot.style_columns, color=color.silver, transp=80, title="Trade Day Start") float LongStop = valuewhen(DayStart,low,0)*(1-i_PercIncrement) float ShortStop = valuewhen(DayStart,high,0)*(1+i_PercIncrement) float StratTP = strategy.position_avg_price + (strategy.position_avg_price - LongStop)*i_TPRRR float StratSTP = strategy.position_avg_price - (ShortStop - strategy.position_avg_price)*i_TPRRR /////////////////////// STRATEGY LOGIC ///////////////////////////////////////// MFI=mfi(close,i_MFI) barsize=high-low barbodysize=close>open?(open-close)*-1:(open-close) shortwicksbar=barbodysize>barsize*barsizeThreshold SMA=sma(close, i_MALen) MAFilter=close > SMA timesinceentry=(time - valuewhen(bought, time, 0)) / 60000 timedexit=timesinceentry == 60 BUY = MFI[1] == OB and close > open and shortwicksbar and (i_MAFilter ? MAFilter : true) bool SELL = na if short SELL := MFI[1] == OS and close < open and shortwicksbar and (i_MAFilter ? not MAFilter : true) //Debugging Plots plot(timesinceentry, transp=100, title="Time Since Entry") //Trading Inputs DPR=input(true, "Allow Direct Position Reverse") reverse=input(false, "Reverse Trades") // Entries if reverse if not DPR strategy.entry("long", strategy.long, when=SELL and strategy.position_size == 0) strategy.entry("short", strategy.short, when=BUY and strategy.position_size == 0) else strategy.entry("long", strategy.long, when=SELL) strategy.entry("short", strategy.short, when=BUY) else if not DPR strategy.entry("long", strategy.long, when=BUY and strategy.position_size == 0) strategy.entry("short", strategy.short, when=SELL and strategy.position_size == 0) else strategy.entry("long", strategy.long, when=BUY) strategy.entry("short", strategy.short, when=SELL) if i_timedexit strategy.close_all(when=timedexit) SL= i_SLType == "Swing Lo/Hi" ? entry_LL_price : i_SLType == "ATR Stop" ? LongSL_ATR_price : LongStop SSL= i_SLType == "Swing Lo/Hi" ? entry_HH_price : i_SLType == "ATR Stop" ? ShortSL_ATR_price : ShortStop TP= i_SLType == "Swing Lo/Hi" ? tp : i_SLType == "ATR Stop" ? ATRtp : StratTP STP= i_SLType == "Swing Lo/Hi" ? stp : i_SLType == "ATR Stop" ? ATRstp : StratSTP //TrailingStop dif=(valuewhen(strategy.position_size>0 and strategy.position_size[1]<=0, high,0)) -strategy.position_avg_price trailOffset = strategy.position_avg_price - SL var tstop = float(na) if strategy.position_size > 0 tstop := high- trailOffset - dif if tstop<tstop[1] tstop:=tstop[1] else tstop := na StrailOffset = SSL - strategy.position_avg_price var Ststop = float(na) Sdif=strategy.position_avg_price-(valuewhen(strategy.position_size<0 and strategy.position_size[1]>=0, low,0)) if strategy.position_size < 0 Ststop := low+ StrailOffset + Sdif if Ststop>Ststop[1] Ststop:=Ststop[1] else Ststop := na strategy.exit("TP & SL", "long", limit=TP, stop=TS? tstop : SL, when=i_SL) strategy.exit("TP & SL", "short", limit=STP, stop=TS? Ststop : SSL, when=i_SL) /////////////////////// PLOTS ////////////////////////////////////////////////// plot(i_SL and strategy.position_size > 0 and not TS ? SL : i_SL and strategy.position_size > 0 and TS ? tstop : na , title='SL', style=plot.style_cross, color=color.red) plot(i_SL and strategy.position_size < 0 and not TS ? SSL : i_SL and strategy.position_size < 0 and TS ? Ststop : na , title='SSL', style=plot.style_cross, color=color.red) plot(i_SL and strategy.position_size > 0 ? TP : na, title='TP', style=plot.style_cross, color=color.green) plot(i_SL and strategy.position_size < 0 ? STP : na, title='STP', style=plot.style_cross, color=color.green) // Draw price action setup arrows plotshape(BUY ? 1 : na, style=shape.triangleup, location=location.belowbar, color=color.green, title="Bullish Setup", size=size.auto) plotshape(SELL ? 1 : na, style=shape.triangledown, location=location.abovebar, color=color.red, title="Bearish Setup", size=size.auto)
Modulo Logic + EMA Strat
https://www.tradingview.com/script/gfeRs6P4-Modulo-Logic-EMA-Strat/
tweakerID
https://www.tradingview.com/u/tweakerID/
64
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © tweakerID // To understand this strategy first we need to look into the Modulo (%) operator. The modulo returns the remainder numerator // of a division's quotient (the result). If we do 5 / 3, we get 1 and 2/3 as a result, where the remainder is 2 (two thirds, in this case). This can be // used for many things, for example to determine when a number divides evenly into another number. If we divide 3/3, our result is 1, // with no remainder numerator, hence our modulo result is 0. In this strategy, we compare a given number (divisor, user defined) with the // the closing price of every candle (dividend, modifiable from the inputs panel) to determine if the result between their division is an even number. // If the answer is true, we have an entry signal. If this signal occurs below the EMA (length is defined by the user) we go short and // viceversa for longs. This logic can be reversed. In this case, the modulo works as a random-like filter for a moving average strategy // that usually struggles when the market is ranging. //@version=4 //@version=4 strategy("Modulo Logic + EMA Strat", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=10000, commission_value=0.04, calc_on_every_tick=false, slippage=0) direction = input(0, title = "Strategy Direction", type=input.integer, minval=-1, maxval=1) strategy.risk.allow_entry_in(direction == 0 ? strategy.direction.all : (direction < 0 ? strategy.direction.short : strategy.direction.long)) /////////////////////// STRATEGY INPUTS //////////////////////////////////////// title1=input(true, "-----------------Strategy Inputs-------------------") a=input(close, title="Dividend") b=input(4, title="Divisor") usemod=input(true, title="Use Modulo Logic") MALen=input(70, title="EMA Length") /////////////////////// BACKTESTER ///////////////////////////////////////////// title2=input(true, "-----------------General Inputs-------------------") // Backtester General Inputs i_SL=input(true, title="Use Stop Loss and Take Profit") i_SLType=input(defval="ATR Stop", title="Type Of Stop", options=["Strategy Stop", "Swing Lo/Hi", "ATR Stop"]) i_SPL=input(defval=10, title="Swing Point Lookback") i_PercIncrement=input(defval=3, step=.1, title="Swing Point SL Perc Increment")*0.01 i_ATR = input(14, title="ATR Length") i_ATRMult = input(4, step=.1, title="ATR Multiple") i_TPRRR = input(1, step=.1, title="Take Profit Risk Reward Ratio") TS=input(false, title="Trailing Stop") // Bought and Sold Boolean Signal bought = strategy.position_size > strategy.position_size[1] or strategy.position_size < strategy.position_size[1] // Price Action Stop and Take Profit LL=(lowest(i_SPL))*(1-i_PercIncrement) HH=(highest(i_SPL))*(1+i_PercIncrement) LL_price = valuewhen(bought, LL, 0) HH_price = valuewhen(bought, HH, 0) entry_LL_price = strategy.position_size > 0 ? LL_price : na entry_HH_price = strategy.position_size < 0 ? HH_price : na tp=strategy.position_avg_price + (strategy.position_avg_price - entry_LL_price)*i_TPRRR stp=strategy.position_avg_price - (entry_HH_price - strategy.position_avg_price)*i_TPRRR // ATR Stop ATR=atr(i_ATR)*i_ATRMult ATRLong = ohlc4 - ATR ATRShort = ohlc4 + ATR ATRLongStop = valuewhen(bought, ATRLong, 0) ATRShortStop = valuewhen(bought, ATRShort, 0) LongSL_ATR_price = strategy.position_size > 0 ? ATRLongStop : na ShortSL_ATR_price = strategy.position_size < 0 ? ATRShortStop : na ATRtp=strategy.position_avg_price + (strategy.position_avg_price - LongSL_ATR_price)*i_TPRRR ATRstp=strategy.position_avg_price - (ShortSL_ATR_price - strategy.position_avg_price)*i_TPRRR // Strategy Stop float LongStop = na float ShortStop = na float StratTP = na float StratSTP = na /////////////////////// STRATEGY LOGIC ///////////////////////////////////////// modulo=a%b evennumber=modulo==0 MA=ema(close, MALen) plot(MA) BUY=usemod ? evennumber and close > MA : close > MA SELL=usemod ? evennumber and close < MA : close < MA //Trading Inputs DPR=input(true, "Allow Direct Position Reverse") reverse=input(false, "Reverse Trades") // Entries if reverse if not DPR strategy.entry("long", strategy.long, when=SELL and strategy.position_size == 0) strategy.entry("short", strategy.short, when=BUY and strategy.position_size == 0) else strategy.entry("long", strategy.long, when=SELL) strategy.entry("short", strategy.short, when=BUY) else if not DPR strategy.entry("long", strategy.long, when=BUY and strategy.position_size == 0) strategy.entry("short", strategy.short, when=SELL and strategy.position_size == 0) else strategy.entry("long", strategy.long, when=BUY) strategy.entry("short", strategy.short, when=SELL) SL= i_SLType == "Swing Lo/Hi" ? entry_LL_price : i_SLType == "ATR Stop" ? LongSL_ATR_price : LongStop SSL= i_SLType == "Swing Lo/Hi" ? entry_HH_price : i_SLType == "ATR Stop" ? ShortSL_ATR_price : ShortStop TP= i_SLType == "Swing Lo/Hi" ? tp : i_SLType == "ATR Stop" ? ATRtp : StratTP STP= i_SLType == "Swing Lo/Hi" ? stp : i_SLType == "ATR Stop" ? ATRstp : StratSTP //TrailingStop dif=(valuewhen(strategy.position_size>0 and strategy.position_size[1]<=0, high,0)) -strategy.position_avg_price trailOffset = strategy.position_avg_price - SL var tstop = float(na) if strategy.position_size > 0 tstop := high- trailOffset - dif if tstop<tstop[1] tstop:=tstop[1] else tstop := na StrailOffset = SSL - strategy.position_avg_price var Ststop = float(na) Sdif=strategy.position_avg_price-(valuewhen(strategy.position_size<0 and strategy.position_size[1]>=0, low,0)) if strategy.position_size < 0 Ststop := low+ StrailOffset + Sdif if Ststop>Ststop[1] Ststop:=Ststop[1] else Ststop := na strategy.exit("TP & SL", "long", limit=TP, stop=TS? tstop : SL, when=i_SL) strategy.exit("TP & SL", "short", limit=STP, stop=TS? Ststop : SSL, when=i_SL) /////////////////////// PLOTS ////////////////////////////////////////////////// plot(i_SL and strategy.position_size > 0 and not TS ? SL : i_SL and strategy.position_size > 0 and TS ? tstop : na , title='SL', style=plot.style_cross, color=color.red) plot(i_SL and strategy.position_size < 0 and not TS ? SSL : i_SL and strategy.position_size < 0 and TS ? Ststop : na , title='SSL', style=plot.style_cross, color=color.red) plot(i_SL and strategy.position_size > 0 ? TP : na, title='TP', style=plot.style_cross, color=color.green) plot(i_SL and strategy.position_size < 0 ? STP : na, title='STP', style=plot.style_cross, color=color.green) // Draw price action setup arrows plotshape(BUY ? 1 : na, style=shape.triangleup, location=location.belowbar, color=color.green, title="Bullish Setup", size=size.auto) plotshape(SELL ? 1 : na, style=shape.triangledown, location=location.abovebar, color=color.red, title="Bearish Setup", size=size.auto)
Multi-X by HamidBox
https://www.tradingview.com/script/LZ1KzR4f-Multi-X-by-HamidBox/
HamidBox
https://www.tradingview.com/u/HamidBox/
1,027
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/ // © HAMIDBOX //@version=4 strategy("Multi-X for BOT", overlay=true, default_qty_type=strategy.cash, default_qty_value=100, initial_capital=100, currency='USD', commission_value=0.1) maType(source , length, type) => type == "SMA" ? sma(source , length) : type == "EMA" ? ema(source , length) : type == "RMA" ? rma(source, length) : type == "WMA" ? wma(source, length) : type == "VWMA" ? vwma(source, length) : na //////////////////////////////////////////////////////////////////////////////// colorup = #11ff00 colordn = #e91e63 /////////////////////////// MOVING AVERAGE №1 INPUTS /////////////////////////// ma1_show = input(title="MA №1", defval=true, type=input.bool, inline="ma1") ma1type = input(title="", defval="EMA", options=["SMA","EMA","RMA","WMA","VWMA"], inline="ma1") ma1src = input(title="", defval=close, type=input.source, inline="ma1") ma1Len = input(title="", defval=9, type=input.integer, inline="ma1") ma1col = input(colorup, "MA №1 Line ", type=input.color, inline="maz1") ma1_zon = input(color.new(color.lime, 70), "   Zone    ", type=input.color, inline="maz1") ma1_width = input(title="   Width   ", defval=2, type=input.integer, inline="maz1") ma1 = maType(ma1src, ma1Len, ma1type) ma1p = plot(ma1_show ? ma1 : na, linewidth=ma1_width, color=color.new(ma1col , 0)) /////////////////////////// MOVING AVERAGE №2 INPUTS /////////////////////////// ma2_show = input(title="MA №2", defval=true, type=input.bool, inline="ma2") ma2type = input(title="", defval="SMA", options=["SMA","EMA","RMA","WMA","VWMA"], inline="ma2") ma2src = input(title="", defval=close, type=input.source, inline="ma2") ma2Len = input(title="", defval=21, type=input.integer, inline="ma2") ma2col = input(colordn, "MA №2 Line ", type=input.color, inline="maz2") ma2_zon = input(color.new(#e91e63, 70), "   Zone    ", type=input.color, inline="maz2") ma2_width = input(title="   Width   ", defval=2, type=input.integer, inline="maz2") ma2 = maType(ma2src, ma2Len, ma2type) ma2p = plot(ma2_show ? ma2 : na, linewidth=ma2_width, color=color.new(ma2col , 0)) /////////////////////////// MOVING AVERAGE №3 INPUTS /////////////////////////// read = input(title="For Safe Side = Read This >>>", defval=true, group="Moving average zone section", tooltip="If you want to play on the safe side, Check ON Moving Average № 3, MA №3 shows the major trend, its work as a Trend-Zone,\nRule: Do not open trades if the market is below MA № 3, WHY? because Trend is Bearish and it will make more Down, NOTE:: It is possible after adding MA № 3, it will give you a small profit. But the great advantage of that, it will reduce your loss and it will also increase your Profit Factor.\nAnd if you not have any issue with Risk then you can Leave Moving Average No 3") ma3_show = input(title="MA №3", defval=false, type=input.bool, inline="ma3" , group="Moving average zone section") ma3type = input(title="", defval="SMA", options=["SMA","EMA","RMA","WMA","VWMA"], inline="ma3" , group="Moving average zone section") // ma3srcH = input(title="", defval=high, type=input.source, inline="ma3") // ma3srcL = input(title="", defval=low, type=input.source, inline="ma3") ma3Len = input(title="", defval=50, type=input.integer, inline="ma3" , group="Moving average zone section") ma3col = input(colordn, "", type=input.color, inline="ma3" , group="Moving average zone section") zone_col_on = input(title="", defval=false, inline="ma3" , group="Moving average zone section") ma3col_up = input(color.new(color.lime, 70), "", type=input.color, inline="ma3" , group="Moving average zone section") ma3col_dn = input(color.new(#e91e63, 70), "", type=input.color, inline="ma3" , group="Moving average zone section") ma3H = maType(high, ma3Len, ma3type) ma3L = maType(low, ma3Len, ma3type) ma3p = plot(ma3_show ? ma3H : na, linewidth=1, color=color.new(ma3col , 50)) ma3p2 = plot(ma3_show ? ma3L : na, linewidth=1, color=color.new(ma3col , 50)) Bigcross_zone_color = if zone_col_on and close > ma3H ma3col_up else if zone_col_on and close < ma3L ma3col_dn fill(ma3p , ma3p2, color=Bigcross_zone_color, title="Cross Background Color") BigCrossSignal = close > ma3H ZoneCrossover = crossover(close , ma3H) ZoneCrossunder = crossunder(close , ma3L) //////////////////////////// PLOTING AND COOLORING ///////////////////////////// Cross = input(true, "Cross Sign ON/OFF   | ", inline="col", group="Moving average zone section") maCrossOver = crossover(ma1 , ma2) maCrossUnder = crossunder(ma1 , ma2) col_buy = input(title="UP", type=input.color, defval=color.white, inline="col", group="Moving average zone section") col_sell = input(title="DN", type=input.color, defval=#e91e63, inline="col", group="Moving average zone section") cross_zone_color = ma1 > ma2 ? ma1_zon : ma2_zon plotshape(Cross ? maCrossOver : na, title="CrossUP Sign", style=shape.triangleup, location=location.belowbar, color=col_buy, size=size.tiny) plotshape(Cross ? maCrossUnder : na, title="CrossDN Sign", style=shape.xcross, location=location.abovebar, color=col_sell, size=size.tiny) fill(ma1p , ma2p, color=cross_zone_color, title="Cross Background Color") ////////////////////////////////////////////////////////////////// backtest_on = input(false, "BackTesting ON/OFF", group="Backtesting Section 🕖🕔🕟🕤") ///////////////////////////// BACK TESTING INPUTS ////////////////////////////// startTime = input(title="Start Time", type=input.time, defval= timestamp("01 Jan 2021"), group="Backtesting Section 🕖🕔🕟🕤") endTime = input(title="End Time", type=input.time, defval= timestamp("01 Jan 2100"), group="Backtesting Section 🕖🕔🕟🕤") inDateRange = (time >= startTime) and (time < endTime) ///////////////////////////////// (CONDITIONS) ///////////////////////////////// bot_id = input(title="BOT ID       ", defval='', inline="bot", group="BOT SECTION") email_token = input(title="  Token", defval='', inline="bot", group="BOT SECTION") enter_msg = '{ "message_type": "bot", "bot_id":'+ bot_id + ', "email_token": "'+ email_token + '", "delay_seconds": 0 }' exit_msg = '{ "message_type": "bot", "bot_id":'+ bot_id + ', "email_token": "'+ email_token + '", "delay_seconds": 0 , "action": "close_at_market_price_all"}' // COPY PASTE THIS MSG TO TRADINGVIEW // {{strategy.order.alert_message}} ///////////////////////////////// (CONDITIONS) ///////////////////////////////// if maCrossOver and inDateRange and backtest_on and ma1_show and ma2_show strategy.entry("BUY", strategy.long, alert_message=enter_msg) if maCrossUnder and inDateRange and backtest_on and ma1_show and ma2_show strategy.close("BUY", comment="Exit", alert_message=exit_msg) if ZoneCrossover and backtest_on and inDateRange and ma3_show and not ma1_show and not ma2_show strategy.entry("BUYzone", strategy.long, alert_message=enter_msg) if ZoneCrossunder and backtest_on and inDateRange and ma3_show strategy.close("BUYzone", comment="Exit", alert_message=exit_msg) if (not inDateRange) strategy.close_all()
Simple Buy/Sell Strategy
https://www.tradingview.com/script/M6r8Ziud-Simple-Buy-Sell-Strategy/
BlockchainSpecialists
https://www.tradingview.com/u/BlockchainSpecialists/
119
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/ // © BlockchainSpecialists //@version=4 //Original Indicator by @Shizaru - simply made into a strategy! strategy("Simple Buy/Sell Strategy", overlay=false) psar = sar(0.02,0.02,0.2) c1a = close > psar c1v = close < psar malen = input(200, title="MA Length") mm200 = sma(close, malen) c2a = close > mm200 c2v = close < mm200 fast = input(12, title="Fast EMA Length") slow = input(26, title="Slow EMA Length") [macd,signal,hist] = macd(close, fast,slow, 9) c3a = macd >= 0 c3v = macd <= 0 rsilen = input(7, title="RSI Length") th = input(50, title="RSI Threshold") rsi14 = rsi(close, rsilen) c4a = rsi14 >= th c4v = rsi14 <= th buy = c1a and c2a and c3a and c4a ? 1 : 0 sell = c1v and c2v and c3v and c4v ? -1 : 0 longtrades = input(true, title="Long Trades") shorttrades = input(true, title="Short Trades") quickexit = input(false, title="Quick Exits") strategy.entry("Buy", strategy.long, when=buy==1 and longtrades==true) strategy.close("Buy", when=quickexit==true ? buy==0 : sell==-1) strategy.entry("Sell", strategy.short, when=sell==-1 and shorttrades==true) strategy.close("Sell", when=quickexit==true ? sell==0 : buy==1) plot(buy, style=plot.style_histogram, color=color.green, linewidth=3, title="Buy Signals") plot(sell, style=plot.style_histogram, color=color.red, linewidth=3, title="Sell Signals")
Trendlines Strategy
https://www.tradingview.com/script/Wwn7sqmI-Trendlines-Strategy/
tweakerID
https://www.tradingview.com/u/tweakerID/
358
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/ // © tweakerID and © BacktestRookies // Using the clever calculations and code by BacktestRookies, here is a strategy that buys // when the price breaks above a trendline and sells (or shorts) when it crosses below. // This logic can be reversed, which seems to work better with recent market conditions. // "A general explanation of the indicator would be a good place to start. In it, we plot two // trend lines at any given time. A resistance trend line and a support trend line. The resistance // trend is shown with red circles and is created by joining swing highs together. The second is a // support trend which is created by joining swing lows. // Since we need swings to make the trend, the trend line code contains code for the swing detection. // You can play around with the swing detection to alter how frequently new trend lines are detected. // Relying on swings also means that there will be some delay in trend detection depending on how you // configure the swing detection. The higher you set rightbars, the more lag you will have before a trend // is detected. However, at the same time the quality of the pivots found will increase. So it is a // trade-off you need to come to terms with and decide what the best settings are for you." //@version=4 strategy("Trendlines Strategy", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=10000, commission_value=0.04, calc_on_every_tick=false, slippage=0) direction = input(0, title = "Strategy Direction", type=input.integer, minval=-1, maxval=1) strategy.risk.allow_entry_in(direction == 0 ? strategy.direction.all : (direction < 0 ? strategy.direction.short : strategy.direction.long)) // Bought and Sold Boolean Signal bought = strategy.position_size > strategy.position_size[1] or strategy.position_size < strategy.position_size[1] /////////////////////// STRATEGY INPUTS //////////////////////////////////////// title1=input(true, "-----------------Strategy Inputs-------------------") leftbars = input(100, minval=1, title='Pivot Detection: Left Bars') rightbars = input(15, minval=1, title='Pivot Detection: Right Bars') plotpivots = input(true, title='Plot Pivots') /////////////////////// BACKTESTER ///////////////////////////////////////////// title2=input(true, "-----------------General Inputs-------------------") // Backtester General Inputs i_SL=input(true, title="Use Stop Loss and Take Profit") TS=input(false, title="Use Trailing Stop") i_SLType=input(defval="ATR Stop", title="Type Of Stop", options=["Strategy Stop", "Swing Lo/Hi", "ATR Stop"]) i_SPL=input(defval=10, title="Swing Point Lookback") i_PercIncrement=input(defval=3, step=.1, title="Swing Point SL Perc Increment")*0.01 i_ATR = input(14, title="ATR Length") i_ATRMult = input(4, step=.1, title="ATR Multiple") i_TPRRR = input(2, step=.1, title="Take Profit Risk Reward Ratio") DPR=input(true, "Allow Direct Position Reverse") reverse=input(true, "Reverse Trades") // Swing Points Stop and Take Profit SwingStopProfit() => LL=(lowest(i_SPL))*(1-i_PercIncrement) HH=(highest(i_SPL))*(1+i_PercIncrement) LL_price = valuewhen(bought, LL, 0) HH_price = valuewhen(bought, HH, 0) entry_LL_price = strategy.position_size > 0 ? LL_price : na entry_HH_price = strategy.position_size < 0 ? HH_price : na tp=strategy.position_avg_price + (strategy.position_avg_price - entry_LL_price)*i_TPRRR stp=strategy.position_avg_price - (entry_HH_price - strategy.position_avg_price)*i_TPRRR [entry_LL_price, entry_HH_price, tp, stp] // ATR Stop ATRStop() => ATR=atr(i_ATR)*i_ATRMult ATRLong = ohlc4 - ATR ATRShort = ohlc4 + ATR ATRLongStop = valuewhen(bought, ATRLong, 0) ATRShortStop = valuewhen(bought, ATRShort, 0) LongSL_ATR_price = strategy.position_size > 0 ? ATRLongStop : na ShortSL_ATR_price = strategy.position_size < 0 ? ATRShortStop : na ATRtp=strategy.position_avg_price + (strategy.position_avg_price - LongSL_ATR_price)*i_TPRRR ATRstp=strategy.position_avg_price - (ShortSL_ATR_price - strategy.position_avg_price)*i_TPRRR [LongSL_ATR_price, ShortSL_ATR_price, ATRtp, ATRstp] // Strategy Stop StrategyStop(bought) => float LongStop = na float ShortStop = na float StratTP = na float StratSTP = na [LongStop, ShortStop, StratTP, StratSTP] //TrailingStop TrailingStop(SL,SSL) => dif=(valuewhen(strategy.position_size>0 and strategy.position_size[1]<=0, high,0)) -strategy.position_avg_price trailOffset = strategy.position_avg_price - SL var tstop = float(na) if strategy.position_size > 0 tstop := high- trailOffset - dif if tstop<tstop[1] tstop:=tstop[1] else tstop := na StrailOffset = SSL - strategy.position_avg_price var Ststop = float(na) Sdif=strategy.position_avg_price-(valuewhen(strategy.position_size<0 and strategy.position_size[1]>=0, low,0)) if strategy.position_size < 0 Ststop := low+ StrailOffset + Sdif if Ststop>Ststop[1] Ststop:=Ststop[1] else Ststop := na [tstop, Ststop] //Stop Loss & Take Profit Switches SLTPLogic(LongStop, ShortStop, StratTP, StratSTP, LongSL_ATR_price, ShortSL_ATR_price, ATRtp, ATRstp, entry_LL_price, entry_HH_price, tp, stp) => SL= i_SLType == "Swing Lo/Hi" ? entry_LL_price : i_SLType == "ATR Stop" ? LongSL_ATR_price : LongStop SSL= i_SLType == "Swing Lo/Hi" ? entry_HH_price : i_SLType == "ATR Stop" ? ShortSL_ATR_price : ShortStop TP= i_SLType == "Swing Lo/Hi" ? tp : i_SLType == "ATR Stop" ? ATRtp : StratTP STP= i_SLType == "Swing Lo/Hi" ? stp : i_SLType == "ATR Stop" ? ATRstp : StratSTP [SL, SSL, TP, STP] /////////////////////// STRATEGY LOGIC ///////////////////////////////////////// // Pivots ph = pivothigh(high, leftbars, rightbars) pl = pivotlow(low, leftbars, rightbars) phv1 = valuewhen(ph, high[rightbars], 0) phb1 = valuewhen(ph, bar_index[rightbars], 0) phv2 = valuewhen(ph, high[rightbars], 1) phb2 = valuewhen(ph, bar_index[rightbars], 1) plv1 = valuewhen(pl, low[rightbars], 0) plb1 = valuewhen(pl, bar_index[rightbars], 0) plv2 = valuewhen(pl, low[rightbars], 1) plb2 = valuewhen(pl, bar_index[rightbars], 1) plotshape(ph, style=shape.circle, location=location.abovebar, color=color.orange, title='Pivot High', offset=-rightbars) plotshape(pl, style=shape.circle, location=location.belowbar, color=color.blue, title='Pivot Low', offset=-rightbars) plot(ph ? high[rightbars] : na, color=color.orange, offset=-rightbars) plot(pl ? low[rightbars] : na, color=color.purple, offset=-rightbars) // TRENDLINE CODE // -------------- get_slope(x1,x2,y1,y2)=> m = (y2-y1)/(x2-x1) get_y_intercept(m, x1, y1)=> b=y1-m*x1 get_y(m, b, ts)=> Y = m * ts + b int res_x1 = na float res_y1 = na int res_x2 = na float res_y2 = na int sup_x1 = na float sup_y1 = na int sup_x2 = na float sup_y2 = na // Resistance res_x1 := ph ? phb1 : res_x1[1] res_y1 := ph ? phv1 : res_y1[1] res_x2 := ph ? phb2 : res_x2[1] res_y2 := ph ? phv2 : res_y2[1] res_m = get_slope(res_x1,res_x2,res_y1,res_y2) res_b = get_y_intercept(res_m, res_x1, res_y1) res_y = get_y(res_m, res_b, bar_index) // Support sup_x1 := pl ? plb1 : sup_x1[1] sup_y1 := pl ? plv1 : sup_y1[1] sup_x2 := pl ? plb2 : sup_x2[1] sup_y2 := pl ? plv2 : sup_y2[1] sup_m = get_slope(sup_x1,sup_x2,sup_y1,sup_y2) sup_b = get_y_intercept(sup_m, sup_x1, sup_y1) sup_y = get_y(sup_m, sup_b, bar_index) // plot(line.get_y2(line1)) plot(res_y, color=color.red, title='Resistance Trendline', linewidth=2, style=plot.style_circles) plot(sup_y, color=color.lime, title='Support Trendline', linewidth=2, style=plot.style_circles) if ph line.new(phb1,phv1, bar_index, res_y, style=line.style_dashed, color=color.blue) if pl line.new(plb1,plv1, bar_index, sup_y, style=line.style_dashed, color=color.blue) // Breaks long_break = crossover(close, res_y) short_break = crossunder(close, sup_y) plotshape(long_break, style=shape.triangleup, color=color.green, size=size.tiny, location=location.belowbar, title='Long Break') plotshape(short_break, style=shape.triangledown, color=color.red, size=size.tiny, location=location.abovebar, title='Short Break') BUY=long_break SELL=short_break /////////////////////// FUNCTION CALLS ///////////////////////////////////////// // Stops and Profits [entry_LL_price, entry_HH_price, tp, stp] = SwingStopProfit() [LongSL_ATR_price, ShortSL_ATR_price, ATRtp, ATRstp] = ATRStop() [LongStop, ShortStop, StratTP, StratSTP] = StrategyStop(bought) [SL, SSL, TP, STP] = SLTPLogic(LongStop, ShortStop, StratTP, StratSTP, LongSL_ATR_price, ShortSL_ATR_price, ATRtp, ATRstp, entry_LL_price, entry_HH_price, tp, stp) [tstop, Ststop] = TrailingStop(SL,SSL) // Entries if reverse if not DPR strategy.entry("long", strategy.long, when=SELL and strategy.position_size == 0) strategy.entry("short", strategy.short, when=BUY and strategy.position_size == 0) else strategy.entry("long", strategy.long, when=SELL) strategy.entry("short", strategy.short, when=BUY) else if not DPR strategy.entry("long", strategy.long, when=BUY and strategy.position_size == 0) strategy.entry("short", strategy.short, when=SELL and strategy.position_size == 0) else strategy.entry("long", strategy.long, when=BUY) strategy.entry("short", strategy.short, when=SELL) // Exits if i_SL strategy.exit("TP & SL", "long", limit=TP, stop=TS? tstop : SL) strategy.exit("TP & SL", "short", limit=STP, stop=TS? Ststop : SSL) /////////////////////// PLOTS ////////////////////////////////////////////////// plot(i_SL and strategy.position_size > 0 and not TS ? SL : i_SL and strategy.position_size > 0 and TS ? tstop : na , title='SL', style=plot.style_cross, color=color.red) plot(i_SL and strategy.position_size < 0 and not TS ? SSL : i_SL and strategy.position_size < 0 and TS ? Ststop : na , title='SSL', style=plot.style_cross, color=color.red) plot(i_SL and strategy.position_size > 0 ? TP : na, title='TP', style=plot.style_cross, color=color.green) plot(i_SL and strategy.position_size < 0 ? STP : na, title='STP', style=plot.style_cross, color=color.green) // Draw price action setup arrows plotshape(BUY ? 1 : na, style=shape.triangleup, location=location.belowbar, color=color.green, title="Bullish Setup", size=size.auto) plotshape(SELL ? 1 : na, style=shape.triangledown, location=location.abovebar, color=color.red, title="Bearish Setup", size=size.auto)
Inside Bar Strategy w/ SL
https://www.tradingview.com/script/JeW4LqUA-Inside-Bar-Strategy-w-SL/
tweakerID
https://www.tradingview.com/u/tweakerID/
525
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/ // From "Day Trading Cryptocurrency // Strategies, Tactics, Mindset, and Tools Required To Build Your // New Income Stream" // by Phil C. Senior // "Inside bars are a two -bar pattern. They can indicate either a continuation of the // existing move or a reversal. A continuation occurs when there is no significant // support or resistance level in sight, while a reversal occurs close to a strong sup- // port or resistance level... // ...A lot of traders are aware of inside bars but few manage to make money with // them. Why is this so? It goes back to interpreting price action. A lot of traders look // to trade in geometric ways. What I mean is that they search for fancy shapes on a // chart and think that this is what represents true price action. // This is not the case. A shape is just a shape. The formation by itself means // nothing unless underlying order flow backs it up. This is why it’s extremely impor- // tant that you look for inside bars when a trend is already in place. The best place to // look for them is in the beginning of trends." // © tweakerID //@version=4 strategy("Inside Bar Strategy w/ SL", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=10000, commission_value=0.04, calc_on_every_tick=false, slippage=0) direction = input(0, title = "Strategy Direction", type=input.integer, minval=-1, maxval=1) strategy.risk.allow_entry_in(direction == 0 ? strategy.direction.all : (direction < 0 ? strategy.direction.short : strategy.direction.long)) /////////////////////// STRATEGY INPUTS //////////////////////////////////////// title1=input(true, "-----------------Strategy Inputs-------------------") i_NBars = input(defval=1, type=input.integer, title="# Of Inside Bars in pattern", options=[1, 2, 3, 4]) i_BarsDirection = input(false, title="Only trade using complete bullish or bearish patterns") i_MAFilter = input(true, title="Use MA Trend Filter") i_MALen = input(65, title="MA Length") /////////////////////// BACKTESTER ///////////////////////////////////////////// title2=input(true, "-----------------General Inputs-------------------") // Backtester General Inputs i_SL=input(true, title="Use Stop Loss and Take Profit") i_SLType=input(defval="ATR Stop", title="Type Of Stop", options=["Strategy Stop", "Swing Lo/Hi", "ATR Stop"]) i_SPL=input(defval=10, title="Swing Point Lookback") i_PercIncrement=input(defval=1, step=.1, title="Swing Point SL Perc Increment")*0.01 i_ATR = input(14, title="ATR Length") i_ATRMult = input(5, step=.1, title="ATR Multiple") i_TPRRR = input(2, step=.1, title="Take Profit Risk Reward Ratio") TS=input(false, title="Trailing Stop") // Bought and Sold Boolean Signal bought = strategy.position_size > strategy.position_size[1] or strategy.position_size < strategy.position_size[1] // Price Action Stop and Take Profit LL=(lowest(i_SPL))*(1-i_PercIncrement) HH=(highest(i_SPL))*(1+i_PercIncrement) LL_price = valuewhen(bought, LL, 0) HH_price = valuewhen(bought, HH, 0) entry_LL_price = strategy.position_size > 0 ? LL_price : na entry_HH_price = strategy.position_size < 0 ? HH_price : na tp=strategy.position_avg_price + (strategy.position_avg_price - entry_LL_price)*i_TPRRR stp=strategy.position_avg_price - (entry_HH_price - strategy.position_avg_price)*i_TPRRR // ATR Stop ATR=atr(i_ATR)*i_ATRMult ATRLong = ohlc4 - ATR ATRShort = ohlc4 + ATR ATRLongStop = valuewhen(bought, ATRLong, 0) ATRShortStop = valuewhen(bought, ATRShort, 0) LongSL_ATR_price = strategy.position_size > 0 ? ATRLongStop : na ShortSL_ATR_price = strategy.position_size < 0 ? ATRShortStop : na ATRtp=strategy.position_avg_price + (strategy.position_avg_price - LongSL_ATR_price)*i_TPRRR ATRstp=strategy.position_avg_price - (ShortSL_ATR_price - strategy.position_avg_price)*i_TPRRR // Strategy Stop float LongStop = valuewhen(bought,low[1],0)*(1-i_PercIncrement) float ShortStop = valuewhen(bought,high[1],0)*(1+i_PercIncrement) float StratTP = na float StratSTP = na /////////////////////// STRATEGY LOGIC ///////////////////////////////////////// MAFilter=close > sma(close, i_MALen) plot(i_MAFilter ? sma(close, i_MALen) : na) bullBar=close > open bearBar=close < open contbullBar=barssince(not bullBar) >= (i_NBars+1) contbearBar=barssince(not bearBar) >= (i_NBars+1) InsideBar(NBars) => Inside1Bar=high < high[1] and low > low[1] Inside2Bar=high < high[2] and low > low[2] and Inside1Bar Inside3Bar=high < high[3] and low > low[3] and Inside1Bar and Inside2Bar Inside4Bar=high < high[4] and low > low[4] and Inside1Bar and Inside2Bar and Inside3Bar if NBars == 1 inside1Bar=Inside1Bar [inside1Bar] else if NBars == 2 inside2Bar=Inside2Bar [inside2Bar] else if NBars == 3 inside3Bar=Inside3Bar [inside3Bar] else if NBars == 4 inside4Bar=Inside4Bar [inside4Bar] else [na] [insideBar] = InsideBar(i_NBars) bullInsideBar=bar_index > 40 and insideBar and bullBar and (i_BarsDirection ? contbullBar : true) and (i_MAFilter ? MAFilter : true) bearInsideBar=bar_index > 40 and insideBar and bearBar and (i_BarsDirection ? contbearBar : true) and (i_MAFilter ? not MAFilter : true) BUY = bullInsideBar SELL = bearInsideBar //Debugging Plots plot(contbullBar ? 1:0, transp=100, title="contbullBar") plot(contbearBar ? 1:0, transp=100, title="contbearBar") //Trading Inputs DPR=input(true, "Allow Direct Position Reverse") reverse=input(false, "Reverse Trades") // Entries if reverse if not DPR strategy.entry("long", strategy.long, when=SELL and strategy.position_size == 0) strategy.entry("short", strategy.short, when=BUY and strategy.position_size == 0) else strategy.entry("long", strategy.long, when=SELL) strategy.entry("short", strategy.short, when=BUY) else if not DPR strategy.entry("long", strategy.long, when=BUY and strategy.position_size == 0) strategy.entry("short", strategy.short, when=SELL and strategy.position_size == 0) else strategy.entry("long", strategy.long, when=BUY) strategy.entry("short", strategy.short, when=SELL) SL= i_SLType == "Swing Lo/Hi" ? entry_LL_price : i_SLType == "ATR Stop" ? LongSL_ATR_price : LongStop SSL= i_SLType == "Swing Lo/Hi" ? entry_HH_price : i_SLType == "ATR Stop" ? ShortSL_ATR_price : ShortStop TP= i_SLType == "Swing Lo/Hi" ? tp : i_SLType == "ATR Stop" ? ATRtp : StratTP STP= i_SLType == "Swing Lo/Hi" ? stp : i_SLType == "ATR Stop" ? ATRstp : StratSTP //TrailingStop dif=(valuewhen(strategy.position_size>0 and strategy.position_size[1]<=0, high,0)) -strategy.position_avg_price trailOffset = strategy.position_avg_price - SL var tstop = float(na) if strategy.position_size > 0 tstop := high- trailOffset - dif if tstop<tstop[1] tstop:=tstop[1] else tstop := na StrailOffset = SSL - strategy.position_avg_price var Ststop = float(na) Sdif=strategy.position_avg_price-(valuewhen(strategy.position_size<0 and strategy.position_size[1]>=0, low,0)) if strategy.position_size < 0 Ststop := low+ StrailOffset + Sdif if Ststop>Ststop[1] Ststop:=Ststop[1] else Ststop := na strategy.exit("TP & SL", "long", limit=TP, stop=TS? tstop : SL, when=i_SL) strategy.exit("TP & SL", "short", limit=STP, stop=TS? Ststop : SSL, when=i_SL) /////////////////////// PLOTS ////////////////////////////////////////////////// plot(i_SL and strategy.position_size > 0 and not TS ? SL : i_SL and strategy.position_size > 0 and TS ? tstop : na , title='SL', style=plot.style_cross, color=color.red) plot(i_SL and strategy.position_size < 0 and not TS ? SSL : i_SL and strategy.position_size < 0 and TS ? Ststop : na , title='SSL', style=plot.style_cross, color=color.red) plot(i_SL and strategy.position_size > 0 ? TP : na, title='TP', style=plot.style_cross, color=color.green) plot(i_SL and strategy.position_size < 0 ? STP : na, title='STP', style=plot.style_cross, color=color.green) // Draw price action setup arrows plotshape(BUY ? 1 : na, style=shape.triangleup, location=location.belowbar, color=color.green, title="Bullish Setup", size=size.auto) plotshape(SELL ? 1 : na, style=shape.triangledown, location=location.abovebar, color=color.red, title="Bearish Setup", size=size.auto)
CCI Scalping Strategy
https://www.tradingview.com/script/D96GTo7i-CCI-Scalping-Strategy/
tweakerID
https://www.tradingview.com/u/tweakerID/
154
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/ // © tweakerID // ---From the "Bitcoin Trading Strategies" book, by David Hanson--- // After testing, works better with an ATR stop instead of the Strategy Stop. This paramater // can be changed from the strategy Inputs panel. // "CCI Scalping Strategy // Recommended Timeframe: 5 minutes // Indicators: 20 Period CCI, 20 WMA // Long when: Price closes above 20 WMA and CCI is below -100, enter when CCI crosses above -100. // Stop: Above 20 WMA" //@version=4 strategy("CCI Scalping Strat", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=10000, commission_value=0.04, calc_on_every_tick=false, slippage=0) direction = input(0, title = "Strategy Direction", type=input.integer, minval=-1, maxval=1) strategy.risk.allow_entry_in(direction == 0 ? strategy.direction.all : (direction < 0 ? strategy.direction.short : strategy.direction.long)) /////////////////////// STRATEGY INPUTS //////////////////////////////////////// title1=input(true, "-----------------Strategy Inputs-------------------") i_Stop = input(0, step=.05, title="Strategy Stop Mult")*.01 i_CCI=input(16, title="CCI Length") i_WMA=input(5, title="WMA Length") /////////////////////// BACKTESTER ///////////////////////////////////////////// title2=input(true, "-----------------General Inputs-------------------") // Backtester General Inputs i_SL=input(true, title="Use Stop Loss and Take Profit") i_SLType=input(defval="ATR Stop", title="Type Of Stop", options=["Strategy Stop", "Swing Lo/Hi", "ATR Stop"]) i_SPL=input(defval=10, title="Swing Point Lookback") i_PercIncrement=input(defval=2, step=.1, title="Swing Point SL Perc Increment")*0.01 i_ATR = input(14, title="ATR Length") i_ATRMult = input(10, step=.1, title="ATR Multiple") i_TPRRR = input(1.5, step=.1, title="Take Profit Risk Reward Ratio") // Bought and Sold Boolean Signal bought = strategy.position_size > strategy.position_size[1] or strategy.position_size < strategy.position_size[1] // Price Action Stop and Take Profit LL=(lowest(i_SPL))*(1-i_PercIncrement) HH=(highest(i_SPL))*(1+i_PercIncrement) LL_price = valuewhen(bought, LL, 0) HH_price = valuewhen(bought, HH, 0) entry_LL_price = strategy.position_size > 0 ? LL_price : na entry_HH_price = strategy.position_size < 0 ? HH_price : na tp=strategy.position_avg_price + (strategy.position_avg_price - entry_LL_price)*i_TPRRR stp=strategy.position_avg_price - (entry_HH_price - strategy.position_avg_price)*i_TPRRR // ATR Stop ATR=atr(i_ATR)*i_ATRMult ATRLong = ohlc4 - ATR ATRShort = ohlc4 + ATR ATRLongStop = valuewhen(bought, ATRLong, 0) ATRShortStop = valuewhen(bought, ATRShort, 0) LongSL_ATR_price = strategy.position_size > 0 ? ATRLongStop : na ShortSL_ATR_price = strategy.position_size < 0 ? ATRShortStop : na ATRtp=strategy.position_avg_price + (strategy.position_avg_price - LongSL_ATR_price)*i_TPRRR ATRstp=strategy.position_avg_price - (ShortSL_ATR_price - strategy.position_avg_price)*i_TPRRR /////////////////////// STRATEGY LOGIC ///////////////////////////////////////// //CCI CCI=cci(close, i_CCI) //WMA WMA=wma(close, i_WMA) //Stops LongStop=valuewhen(bought, WMA, 0)*(1-i_Stop) ShortStop=valuewhen(bought, WMA, 0)*(1+i_Stop) StratTP=strategy.position_avg_price + (strategy.position_avg_price - LongStop)*i_TPRRR StratSTP=strategy.position_avg_price - (ShortStop - strategy.position_avg_price)*i_TPRRR BUY = (close > WMA) and crossover(CCI , -100) SELL = (close < WMA) and crossunder(CCI , 100) //Trading Inputs DPR=input(true, "Allow Direct Position Reverse") reverse=input(false, "Reverse Trades") // Entries if reverse if not DPR strategy.entry("long", strategy.long, when=SELL and strategy.position_size == 0) strategy.entry("short", strategy.short, when=BUY and strategy.position_size == 0) else strategy.entry("long", strategy.long, when=SELL) strategy.entry("short", strategy.short, when=BUY) else if not DPR strategy.entry("long", strategy.long, when=BUY and strategy.position_size == 0) strategy.entry("short", strategy.short, when=SELL and strategy.position_size == 0) else strategy.entry("long", strategy.long, when=BUY) strategy.entry("short", strategy.short, when=SELL) SL= i_SLType == "Swing Lo/Hi" ? entry_LL_price : i_SLType == "ATR Stop" ? LongSL_ATR_price : LongStop SSL= i_SLType == "Swing Lo/Hi" ? entry_HH_price : i_SLType == "ATR Stop" ? ShortSL_ATR_price : ShortStop TP= i_SLType == "Swing Lo/Hi" ? tp : i_SLType == "ATR Stop" ? ATRtp : StratTP STP= i_SLType == "Swing Lo/Hi" ? stp : i_SLType == "ATR Stop" ? ATRstp : StratSTP strategy.exit("TP & SL", "long", limit=TP, stop=SL, when=i_SL) strategy.exit("TP & SL", "short", limit=STP, stop=SSL, when=i_SL) /////////////////////// PLOTS ////////////////////////////////////////////////// plot(WMA) plot(i_SL and strategy.position_size > 0 ? SL : na , title='SL', style=plot.style_cross, color=color.red) plot(i_SL and strategy.position_size < 0 ? SSL : na , title='SSL', style=plot.style_cross, color=color.red) plot(i_SL and strategy.position_size > 0 ? TP : na, title='TP', style=plot.style_cross, color=color.green) plot(i_SL and strategy.position_size < 0 ? STP : na, title='STP', style=plot.style_cross, color=color.green) // Draw price action setup arrows plotshape(BUY ? 1 : na, style=shape.triangleup, location=location.belowbar, color=color.green, title="Bullish Setup", size=size.auto) plotshape(SELL ? 1 : na, style=shape.triangledown, location=location.abovebar, color=color.red, title="Bearish Setup", size=size.auto)
EMA crossover (daily TF)
https://www.tradingview.com/script/syhCY9Ai-EMA-crossover-daily-TF/
iitiantradingsage
https://www.tradingview.com/u/iitiantradingsage/
162
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ //This strategy is useful for positional trading //@version=5 //This strategy can be used for daily entry for positional trading strategy('EMA crossover (daily timeframe)', shorttitle='EMA crossver (daily timeframe)', overlay=true, default_qty_value=50, default_qty_type=strategy.percent_of_equity, initial_capital=1000000) emalen1 = input.int(title='Smaller EMA length', defval=50, minval=30, maxval=50, step=5) emalen2 = input.int(title='Longer EMA length', defval=100, minval=70, maxval=200, step=10) ema1 = ta.ema(close, emalen1) emasmooth1 = ta.ema(ema1, emalen1) ema2 = ta.ema(close, emalen2) emasmooth2 = ta.ema(ema2, emalen2) volMA = ta.sma(volume, 20) rsi = ta.rsi(close, 14) atr = ta.atr(14) bodyper = close > open ? (close - open) / (high - low) : (open - close) / (high - low) closebull = close > emasmooth1 and close > emasmooth2 and close > open and bodyper > 0.6 closebear = close < emasmooth1 and close < emasmooth2 and close < open and bodyper > 0.6 volcheck = volume > volMA dailytimeframe = timeframe.isdaily BuyCond = dailytimeframe and closebull and volcheck and rsi > 50 and emasmooth1 > emasmooth2 and volume > volume[1] and close > open SellCond = dailytimeframe and closebear and volcheck and rsi < 50 and emasmooth1 > emasmooth2 and volume > volume[1] and close < open //Buy and Sell Signals Buysignal = BuyCond and strategy.position_size == 0 and barstate.isconfirmed Sellsignal = SellCond and strategy.position_size == 0 and barstate.isconfirmed //settingup stoploss sllong = math.max(math.min(low, low[1]), emasmooth2) slshort = math.min(math.max(low, low[1]), emasmooth2) //Save SLs and Target prices var StopPrice = 0.0 var TargetPrice = 0.0 var EntryPrice = 0.0 //Detect Valid long setup and trigger alerts if Buysignal StopPrice := sllong EntryPrice := ohlc4 TargetPrice := EntryPrice + 10 * (ohlc4 - StopPrice) TargetPrice if Sellsignal StopPrice := slshort EntryPrice := ohlc4 TargetPrice := EntryPrice - 10 * (StopPrice - ohlc4) TargetPrice //Trailing Stoplosses if strategy.position_size > 0 and volume > volMA and close > open and close > 1.10 * EntryPrice StopPrice := StopPrice * 1.05 EntryPrice := 1.05 * EntryPrice EntryPrice if strategy.position_size < 0 and volume > volMA and close < open and close < 0.90 * EntryPrice StopPrice := 0.95 * StopPrice EntryPrice := 0.95 * EntryPrice EntryPrice //enter trades whenever there is signal strategy.entry(id='Buy', direction=strategy.long, when=Buysignal, alert_message='Buy signal given') strategy.entry(id='Sell', direction=strategy.short, when=Sellsignal, alert_message='Sell signal given') //Exit entries if close < StopPrice strategy.exit(id='Exit', from_entry='Buy', limit=TargetPrice, stop=StopPrice, when=strategy.position_size > 0, alert_message='Long closed') if close > StopPrice strategy.exit(id='Exit', from_entry='Sell', limit=TargetPrice, stop=StopPrice, when=strategy.position_size < 0, alert_message='Short closed') //Draw trade data stoplong = plot(strategy.position_size > 0 or Buysignal ? StopPrice : na, title='TSL long', color=color.new(color.black, 0), style=plot.style_linebr, linewidth=1) stopshort = plot(strategy.position_size < 0 or Sellsignal ? StopPrice : na, title='TSL short', color=color.new(color.black, 0), style=plot.style_linebr, linewidth=1) //plot(strategy.position_size!=0?EntryPrice:na, title="EntryPrice", color=color.black, style=plot.style_linebr, linewidth=1) candlenearest = plot(strategy.position_size < 0 ? high : strategy.position_size > 0 ? low : na, title='Candle nearest point', color=color.new(color.green, 80), style=plot.style_linebr, linewidth=1) fill(stoplong, candlenearest, color=color.new(color.green, 80)) fill(stopshort, candlenearest, color=color.new(color.red, 80)) //Draw Price action arrow plotshape(Buysignal ? 1 : na, style=shape.labelup, location=location.belowbar, color=color.new(color.green, 0), title='Long setup', size=size.small) plotshape(Sellsignal ? 1 : na, style=shape.labeldown, location=location.abovebar, color=color.new(color.red, 0), title='Long setup', size=size.small) //Plot emasmooth and vwap plot(emasmooth1, title='Smaller EMA', color=color.new(color.green, 0), linewidth=2) plot(emasmooth2, title='Longer EMA', color=color.new(color.red, 0), linewidth=2)
ZEGUELA DEMABOT
https://www.tradingview.com/script/VwK7imel-ZEGUELA-DEMABOT/
zeguela
https://www.tradingview.com/u/zeguela/
145
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // This code is based on the study you can find here: https://kodify.net/tradingview/indicators/dema/ // ©zeguela //@version=4 strategy(title="ZEGUELA DEMABOT", commission_value=0.070, commission_type=strategy.commission.percent, initial_capital=100, default_qty_value=90, default_qty_type=strategy.percent_of_equity, overlay=true, process_orders_on_close=true) // Step 1. Script settings // Input options srcData = input(title="Source Data", type=input.source, defval=close) // Length settings len1 = input(title="Length DEMA #1", type=input.integer, defval=8, minval=1) len2 = input(title="Length DEMA #2", type=input.integer, defval=21, minval=0) len3 = input(title="Length DEMA #3", type=input.integer, defval=0, minval=0) // Step 2. Calculate indicator values // Function that calculates the DEMA DEMA(series, length) => if (length > 0) emaValue = ema(series, length) 2 * emaValue - ema(emaValue, length) else na // Calculate the DEMA values demaVal1 = DEMA(srcData, len1) demaVal2 = DEMA(srcData, len2) demaVal3 = DEMA(srcData, len3) // Step 3. Determine indicator signals // See if there's a DEMA crossover demaCrossover = if (len2 > 0) and (len3 > 0) crossover(demaVal1, demaVal2) and (demaVal3 > demaVal3[1]) else if (len2 > 0) and (len3 == 0) crossover(demaVal1, demaVal2) else if (len3 > 0) and (len2 == 0) crossover(demaVal1, demaVal3) else crossover(close, demaVal1) // Check if there's a DEMA crossunder demaCrossunder = if (len2 > 0) and (len3 > 0) crossunder(demaVal1, demaVal2) and (demaVal3 < demaVal3[1]) else if (len2 > 0) and (len3 == 0) crossunder(demaVal1, demaVal2) else if (len3 > 0) and (len2 == 0) crossunder(demaVal1, demaVal3) else crossunder(close, demaVal1) // Step 4. Output indicator data // Plot DEMAs on the chart plot(series=demaVal1, color=color.green, linewidth=2, title="DEMA #1") plot(series=demaVal2, color=color.red, linewidth=2, title="DEMA #2") plot(series=demaVal3, color=color.fuchsia, linewidth=2, title="DEMA #3") // Step 5. Trailing Stop, Stop Loss and Take Profit calculation //TRAILING STOP CODE a = input(title="Usar Trailing Stop?", type=input.bool, defval=false) stopPerlong = input(10.0, title='Stop Loss Long %', type=input.float, group="Stop Loss & Take Profit Settings") / 100 stopPershort = input(5.0, title='Stop Loss Short %', type=input.float, group="Stop Loss & Take Profit Settings") / 100 take1Perlong = input(40.0, title='Take Profit Long % 1', type=input.float, group="Stop Loss & Take Profit Settings") / 100 take1Pershort = input(10.0, title='Take Profit Short % 1', type=input.float, group="Stop Loss & Take Profit Settings") / 100 // Determine stop loss price longStopPrice = strategy.position_avg_price * (1 - stopPerlong) shortStopPrice = strategy.position_avg_price * (1 + stopPershort) longTake1Price = strategy.position_avg_price * (1 + take1Perlong) shortTake1Price = strategy.position_avg_price * (1 - take1Pershort) // Determine trail stop loss prices longStopPriceTrail = 0.0 longStopPriceTrail := if (strategy.position_size > 0) stopValue = close * (1 - stopPerlong) max(stopValue, longStopPriceTrail[1]) else 0 // Determine trailing short price shortStopPriceTrail = 0.0 shortStopPriceTrail := if (strategy.position_size < 0) stopValue = close * (1 + stopPershort) min(stopValue, shortStopPriceTrail[1]) else 999999 //Calculate wich stop to use longStop = a ? longStopPriceTrail : longStopPrice shortStop = a ? shortStopPriceTrail : shortStopPrice //Calculate SL and TP value to throw through alert longStopEntrada = close * (1 - stopPerlong) shortStopEntrada = close * (1 + stopPershort) longTPEntrada = close * (1 + take1Perlong) shortTPEntrada = close * (1 - take1Pershort) //Save the SL and TP price for furter results calculation price_entryL = 0.0 price_entryL := na(price_entryL) ? na : price_entryL[1] price_entryS = 0.0 price_entryS := na(price_entryS) ? na : price_entryS[1] stopL = 0.0 stopL := na(stopL) ? na : stopL[1] stopS = 0.0 stopS := na(stopS) ? na : stopS[1] takeL = 0.0 takeL := na(takeL) ? na : takeL[1] takeS = 0.0 takeS := na(takeS) ? na : takeS[1] if (demaCrossover) price_entryL := close stopL := close * (1 - stopPerlong) takeL := close * (1 + take1Perlong) if (demaCrossunder) price_entryS := close stopS := close * (1 + stopPershort) takeS := close * (1 - take1Pershort) //Calculate P&L results resultadoL = ((close - price_entryL)/price_entryL) * 100 resultadoLexit = "(SL = 1% e TP = 0,5%)" resultadoS = ((price_entryS - close)/price_entryS) * 100 resultadoSexit = "(SL = 1% e TP = 0,5)%" // Step 6. Strategy setup // Make input options that configure backtest date range _startDate = input(title="Start Date", type=input.integer, defval=1, minval=1, maxval=31, group="BackTest Period") _startMonth = input(title="Start Month", type=input.integer, defval=4, minval=1, maxval=12, group="BackTest Period") _startYear = input(title="Start Year", type=input.integer, defval=2021, minval=1800, maxval=2100, group="BackTest Period") _endDate = input(title="End Date", type=input.integer, defval=31, minval=1, maxval=31, group="BackTest Period") _endMonth = input(title="End Month", type=input.integer, defval=12, minval=1, maxval=12, group="BackTest Period") _endYear = input(title="End Year", type=input.integer, defval=2031, minval=1800, maxval=2100, group="BackTest Period") // Look if the close time of the current bar // falls inside the date range _inDateRange = (time >= timestamp(syminfo.timezone, _startYear, _startMonth, _startDate, 0, 0)) and (time < timestamp(syminfo.timezone, _endYear, _endMonth, _endDate, 0, 0)) //Alert configuration _alertMessageOpenLong="OpenLong" _alertMessageCloseLong="CloseLong" _alertmessageExitLong="ExitLong" _alertmessageTPLong="TakeProfitLong" _alertMessageOpenShort="OpenShort" _alertMessageCloseShort="CloseShort" _alertMessageTPShort="TakeProfitShort" _alertMessageExitShort="ExitShort" // Step 7. Strategy Execution if (_inDateRange) //ENTER SOME SETUP TRADES FOR TSL EXAMPLE if (demaCrossover) strategy.entry("LONG", strategy.long, comment = "OPEN LONG", alert_message=_alertMessageOpenLong) strategy.exit(id="Close Long TP1", stop=stopL, limit=takeL, comment="CLOSE LONG", alert_message=_alertmessageExitLong) if (demaCrossunder) strategy.entry("SHORT", strategy.short, comment = "OPEN SHORT", alert_message=_alertMessageOpenShort) strategy.exit(id="Close Short TP1", stop=stopS, limit=takeS, comment="CLOSE SHORT", alert_message=_alertMessageExitShort) //EXIT TRADE @ TSL if strategy.position_size > 0 strategy.exit("TP/SL", "LONG", stop=longStop, limit=longTake1Price, comment="EXIT LONG", alert_message=_alertmessageExitLong) if strategy.position_size < 0 strategy.exit("TP/SL", "SHORT", stop=shortStop, limit=shortTake1Price, comment ="EXIT SHORT", alert_message=_alertMessageExitShort) // Step 8. Chart look and feel //Look & Feel - Plot stop loss and take profit areas p1=plot(strategy.position_avg_price, color=color.blue, style=plot.style_linebr, linewidth=1, title="Entry Price") p2=plot(series=strategy.position_size > 0 ? longStop : na, color=color.red, style=plot.style_linebr, linewidth=1, title="Long Stop") p3=plot(series=strategy.position_size > 0 ? longTake1Price : na, color=color.green, style=plot.style_linebr, linewidth=1, title="Long TP") p4=plot(series=strategy.position_size < 0 ? shortStop : na, color=color.red, style=plot.style_linebr, linewidth=1, title="Short Stop") p5=plot(series=strategy.position_size < 0 ? shortTake1Price : na, color=color.green, style=plot.style_linebr, linewidth=1, title="Short TP") fill(p1, p2, color=color.red) fill(p1, p3, color=color.green) fill(p1, p4, color=color.red) fill(p1, p5, color=color.green) // Insert label with value stopLossOnLong = "Stop Loss = " + tostring(longStop) stopLossOnShort = "Stop Loss = " + tostring(shortStop) takeprofitOnLong = "Take Profit = " + tostring(longTake1Price) takeprofitOnShort = "Take Profit = " + tostring(shortTake1Price) precoentrada = "Entry Price = " + tostring(strategy.position_avg_price) var label FinalLabelpriceL = na var label FinalLabelpriceS = na var label slFinalLabelL = na var label slFinalLabelS = na var label slFinalLabelTPL = na var label slFinalLabelTPS = na //Draw entry and stop loss lines and labels if strategy.position_size > 0 //write the price above the end of the stoploss line slFinalLabelL := label.new(bar_index, longStop, stopLossOnLong, style=label.style_none, size=size.normal, textcolor=color.red) slFinalLabelTPL := label.new(bar_index, longTake1Price, takeprofitOnLong, style=label.style_none, size=size.normal, textcolor=color.green) FinalLabelpriceL := label.new(bar_index, strategy.position_avg_price, precoentrada, style=label.style_none, size=size.normal, textcolor=color.blue) // Delete previous label when there is a consecutive new high, as there's no line plot in that case. if strategy.position_size > 0[1] label.delete(slFinalLabelL[1]) label.delete(slFinalLabelTPL[1]) label.delete(FinalLabelpriceL[1]) if strategy.position_size < 0 //write the price above the end of the stoploss line slFinalLabelS := label.new(bar_index, shortStop, stopLossOnShort, style=label.style_none, size=size.normal, textcolor=color.red) slFinalLabelTPS := label.new(bar_index, shortTake1Price, takeprofitOnShort, style=label.style_none, size=size.normal, textcolor=color.green) FinalLabelpriceS := label.new(bar_index, strategy.position_avg_price, precoentrada, style=label.style_none, size=size.normal, textcolor=color.blue) // Delete previous label when there is a consecutive new high, as there's no line plot in that case. if strategy.position_size < 0[1] label.delete(slFinalLabelS[1]) label.delete(slFinalLabelTPS[1]) label.delete(FinalLabelpriceS[1]) // Exit open market position when date range ends if (not _inDateRange) strategy.close_all() //Plot the box with position and P&L posColor = color.new(color.green, 75) negColor = color.new(color.red, 75) dftColor = color.new(color.blue, 75) posProfit= (strategy.position_size > 0) ? (close * 100 / strategy.position_avg_price - 100) : strategy.position_size < 0 ? (strategy.position_avg_price * 100 / close - 100) : 0.0 posDir = (strategy.position_size > 0) ? "long" : strategy.position_size < 0 ? "short" : "flat" posCol = (posProfit > 0) ? posColor : (posProfit < 0) ? negColor : dftColor var label lb = na label.delete(lb) lb := label.new(bar_index, max(high, highest(4)[1]), textcolor=color.white, color=posCol, text="Pos: "+ posDir + "\nPnL: "+tostring(posProfit, "#.##")+"%" + "\nAvg Price: "+tostring(strategy.position_avg_price, "#.####") + "\nClose: "+tostring(close, "#.####"))
FTB Strategy (Automated)
https://www.tradingview.com/script/gcu6zUkw-FTB-Strategy-Automated/
ZenAndTheArtOfTrading
https://www.tradingview.com/u/ZenAndTheArtOfTrading/
1,268
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © ZenAndTheArtOfTrading // Last Updated: 10th March 2022 // @version=5 strategy("FTB Strategy", shorttitle="FTB", overlay=true, calc_on_order_fills=true, initial_capital=10000) // Risk Settings var g_risk = "Risk Settings" pips = input.float(title="Stop Pips", defval=2.0, group=g_risk, tooltip="How many pips above high to put stop loss") rr = input.float(title="Risk:Reward", defval=1.0, group=g_risk, tooltip="This determines the risk:reward profile of the setup") // Filters var g_filter = "Filter Settings" timezone = input.session(title="Timezone", defval="0200-0700", group=g_filter, tooltip="Which timezone to search for FTB signals in") useRsiFilter = input.bool(title="RSI OB/OS?", defval=true, group=g_filter, tooltip="If true then the RSI must be considered overbought before a signal is valid") useCloseFilter = input.bool(title="Previous Bar Must Be Bullish?", defval=false, group=g_filter, tooltip="If true then the previous bar must have closed bullish") useHighFilter = input.bool(title="High Filter", defval=false, group=g_filter, tooltip="If true then the signal bar must be the highest bar over X bars") highLookback = input.int(title="High Lookback", defval=10, group=g_filter, tooltip="This is for setting the High Filter lookback distance") fib = input.float(title="Candle Close %", defval=0.5, group=g_filter, tooltip="For identifying shooting star candles (0.5 = must close <= 50% mark of candle size)") rsiLen = input.int(title="RSI Length", defval=3, group=g_filter, tooltip="RSI length") rsiOB = input.float(title="RSI OB", defval=70.0, group=g_filter, tooltip="RSI overbought threshold") var g_days = "Day Filter" d_monday = input.bool(title="Monday", defval=true, group=g_days, tooltip="Take trades on this day?", inline="days") d_tuesday = input.bool(title="Tuesday", defval=true, group=g_days, tooltip="Take trades on this day?", inline="days") d_wednesday = input.bool(title="Wednesday", defval=true, group=g_days, tooltip="Take trades on this day?", inline="days") d_thursday = input.bool(title="Thursday", defval=true, group=g_days, tooltip="Take trades on this day?", inline="days") d_friday = input.bool(title="Friday", defval=true, group=g_days, tooltip="Take trades on this day?", inline="days") var g_tester = "Backtester Settings" startBalance = input.float(title="Starting Balance", defval=10000.0, group=g_tester, tooltip="Your starting balance for the inbuilt tester system") riskPerTrade = input.float(title="Risk Per Trade", defval=1.0, group=g_tester, tooltip="Your desired % risk per trade (as a whole number)") drawTester = input.bool(title="Draw Backtester", defval=true, group=g_tester, tooltip="Turn on/off inbuilt backtester display") // PineConnector Settings var g_pc = "PineConnector Settings" 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)") pc_prefix = input.string(title="MetaTrader Prefix", defval="", group=g_pc, tooltip="This is your broker's MetaTrader symbol prefix") pc_suffix = input.string(title="MetaTrader Suffix", defval="", group=g_pc, tooltip="This is your broker's MetaTrader symbol suffix") pc_spread = input.float(title="Spread", defval=0.5, group=g_pc, tooltip="Enter your average spread for this pair (used for offsetting limit order)") pc_limit = input.bool(title="Use Limit Order?", defval=true, group=g_pc, tooltip="If true a limit order will be used, if false a market order will be used") // Generate PineConnector alert string var symbol = pc_prefix + syminfo.ticker + pc_suffix var limit = pc_limit ? "limit" : "" pc_entry_alert(direction, sl, tp) => price = pc_limit ? "price=" + str.tostring(pc_spread) + "," : "" pc_id + "," + direction + limit + "," + symbol + "," + price + "sl=" + str.tostring(sl) + ",tp=" + str.tostring(tp) + ",risk=" + str.tostring(pc_risk) // Get RSI filter rsiValue = ta.rsi(close, rsiLen) rsiFilter = not useRsiFilter or rsiValue >= rsiOB // Check high & close filter highFilter = not useHighFilter or high == ta.highest(high, highLookback) closeFilter = not useCloseFilter or close[1] > open[1] // InSession() determines if a price bar falls inside the specified session (and day) days = d_monday ? "2" : "" days := days + (d_tuesday ? "3" : "") days := days + (d_wednesday ? "4" : "") days := days + (d_thursday ? "5" : "") days := days + (d_friday ? "6" : "") inSession(sess) => na(time(timeframe.period, sess + ":" + days)) == false // Calculate 50% mark of candle size bearFib = (high - low) * fib + low // Check filters filters = inSession(timezone) and closeFilter and high > high[1] and rsiFilter and highFilter and open != close // Detect valid shooting star pinbar pattern var takenTradeAlready = false star = filters and close < bearFib and open < bearFib and not takenTradeAlready and strategy.position_size == 0 // Calculate stops & targets shortStopPrice = high + (syminfo.mintick * pips * 10) shortStopDistance = shortStopPrice - close shortTargetPrice = close - (shortStopDistance * rr) // Save stops & targets for the current trade var t_stop = 0.0 var t_target = 0.0 var t_entry = 0.0 // If we detect a valid shooting star, save our stops & targets, enter short and generate alert if star and barstate.isconfirmed t_stop := shortStopPrice t_target := shortTargetPrice t_entry := close takenTradeAlready := true positionSize = math.floor((strategy.equity * (riskPerTrade/100)) / (t_stop - close)) strategy.entry(id="Short", direction=strategy.short, qty=positionSize, when=strategy.position_size == 0) alertString = pc_entry_alert("sell", t_stop, t_target) alert(alertString, alert.freq_once_per_bar_close) // If price has exceeded target then cancel limit order if it's still active if pc_limit and low <= t_target and strategy.position_size == 0 and takenTradeAlready alert(pc_id + ",cancelshort," + symbol, alert.freq_once_per_bar_close) // If we have exited the FTB session then reset our takenTradeAlready flag for the next session if not inSession(timezone) and inSession(timezone)[1] takenTradeAlready := false // Draw stops & targets plot(star or strategy.position_size != 0 ? t_stop : na, color=color.red, style=plot.style_linebr, title="SL") plot(star or strategy.position_size != 0 ? t_target : na, color=color.green, style=plot.style_linebr, title="TP") // Draw short signals plotshape(star ? 1 : na, style=shape.triangledown, color=color.red) // Change background color to highlight detection zone bgcolor(color=inSession(timezone) ? color.new(color.red,80) : na, title="Session") // Exit trade whenever our stop or target is hit strategy.exit(id="Short Exit", from_entry="Short", limit=t_target, stop=t_stop, when=strategy.position_size != 0) // ============================================================================= // START BACKTEST CODE // ============================================================================= // Import Zen library import ZenAndTheArtOfTrading/ZenLibrary/5 as zen // Declare balance tracking variables (for backtester simulation) var balance = startBalance var drawdown = 0.0 var maxDrawdown = 0.0 var maxBalance = 0.0 var totalPips = 0.0 // Increase profit for wins wonTrade = strategy.wintrades != strategy.wintrades[1] if wonTrade balance += riskPerTrade / 100 * balance * rr totalPips += zen.toWhole(math.abs(t_entry - t_target)) if balance > maxBalance maxBalance := balance // Decrease profit for losses lostTrade = strategy.losstrades != strategy.losstrades[1] if lostTrade balance -= riskPerTrade / 100 * balance totalPips -= zen.toWhole(math.abs(t_stop - t_entry)) // Update drawdown drawdown := balance / maxBalance - 1 if drawdown < maxDrawdown maxDrawdown := drawdown // Declare error tracking variables (for identifying how many "questionable" trades were detected) var questionableTrades = 0 flagQuestionableTrade = false // If price has hit both TP & SL on the same bar, flag it for further investigation if ((wonTrade or lostTrade) and high >= t_stop and low <= t_target) questionableTrades += 1 flagQuestionableTrade := true // Highlight questionable trades bgcolor(flagQuestionableTrade ? color.new(color.purple,50) : na) // Prepare stats table var table testTable = table.new(position.top_right, 5, 2, border_width=1) f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) => _cellText = _title + "\n" + _value table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor) // Draw stats table var bgcolor = color.black if barstate.islastconfirmedhistory if drawTester dollarReturn = balance - startBalance f_fillCell(testTable, 0, 0, "Total Trades:", str.tostring(strategy.closedtrades) + " [*" + str.tostring(questionableTrades) + "]", bgcolor, color.white) f_fillCell(testTable, 0, 1, "Win Rate:", str.tostring(zen.truncate(strategy.wintrades / strategy.closedtrades * 100)) + "%", bgcolor, color.white) f_fillCell(testTable, 1, 0, "Starting:", "$" + str.tostring(startBalance), bgcolor, color.white) f_fillCell(testTable, 1, 1, "Ending:", "$" + str.tostring(zen.truncate(balance)), bgcolor, color.white) f_fillCell(testTable, 2, 0, "Return:", "$" + str.tostring(zen.truncate(dollarReturn)), bgcolor, dollarReturn > 0 ? color.green : color.red) f_fillCell(testTable, 2, 1, "Pips:", (totalPips > 0 ? "+" : "") + str.tostring(zen.truncate(totalPips)), bgcolor, color.white) f_fillCell(testTable, 3, 0, "Return:", (dollarReturn > 0 ? "+" : "") + str.tostring(zen.truncate(dollarReturn / startBalance * 100)) + "%", dollarReturn > 0 ? color.green : color.red, color.white) f_fillCell(testTable, 3, 1, "Max DD:", str.tostring(zen.truncate(maxDrawdown * 100)) + "%", color.red, color.white) // ============================================================================= // END BACKTEST CODE // =============================================================================
Double Bollinger Strategy
https://www.tradingview.com/script/Gs8sbyyZ-Double-Bollinger-Strategy/
tweakerID
https://www.tradingview.com/u/tweakerID/
187
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/ // From "Bitcoin Trading Strategies: Algorithmic Trading Strategies For Bitcoin And Cryptocurrency That Work" by David Hanson. // "Double Bolinger Band Scalping System // Recommended Timeframe: 1 minute or 5 minute // Required Indicators: // - RSI with a length of 14 (default settings) // - Bolinger band #1 settings: Length = 50, stDev = 1 Hide the basis/middle line (basis line not needed for this strategy) // Note: This is the slower bolinger band in the directions // - Bolinger band #2 settings: Length 20, stDev = 1 Hide the basis/middle line (basis line not needed for this strategy) // Note: This is the faster bolinger band in the directions // Enter Long/Buy Trade When: // - RSI is above the level 50 // - A candle closes above the top of the faster bolinger band // Enter a long when a candle then closes above the top of the slower bolinger band, and price is above the top of both bands // Place a stop loss under the low of the entry candle Example of a long trade using this strategy // Exit Long Trade When: A candle closes below the top band of the fast bolinger band // Enter Short/Sell Trade When: // - RSI is below the level 50 // - A candle closes below the bottom of the faster bolinger band // Enter a short when a candle then closes below the bottom of the slower bolinger band, and price is below both bands // Place a stop loss above the high of the entry candle Example of a short trade using this strategy // Exit Short Trade When: Price closes inside the bottom of the faster bolinger band" // © tweakerID //@version=4 strategy("Double Bollinger Strategy", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=10000, commission_value=0.04, calc_on_every_tick=false, slippage=0) direction = input(0, title = "Strategy Direction", type=input.integer, minval=-1, maxval=1) strategy.risk.allow_entry_in(direction == 0 ? strategy.direction.all : (direction < 0 ? strategy.direction.short : strategy.direction.long)) /////////////////////// STRATEGY INPUTS //////////////////////////////////////// title1=input(true, "-----------------Strategy Inputs-------------------") i_RSI=input(14, title="RSI Length") lengthS = input(45, minval=1, title="Slow BB Band Length") lengthF = input(31, minval=1, title="Fast BB Band Length") /////////////////////// BACKTESTER ///////////////////////////////////////////// title2=input(true, "-----------------General Inputs-------------------") // Backtester General Inputs i_SL=input(true, title="Use Stop Loss and Take Profit") i_SLType=input(defval="Strategy Stop", title="Type Of Stop", options=["Strategy Stop", "Swing Lo/Hi", "ATR Stop"]) i_SPL=input(defval=10, title="Swing Point Lookback") i_PercIncrement=input(defval=1, step=.1, title="Swing Point SL Perc Increment")*0.01 i_ATR = input(14, title="ATR Length") i_ATRMult = input(5, step=.1, title="ATR Multiple") i_TPRRR = input(2, step=.1, title="Take Profit Risk Reward Ratio") TS=input(false, title="Trailing Stop") // Bought and Sold Boolean Signal bought = strategy.position_size > strategy.position_size[1] or strategy.position_size < strategy.position_size[1] // Price Action Stop and Take Profit LL=(lowest(i_SPL))*(1-i_PercIncrement) HH=(highest(i_SPL))*(1+i_PercIncrement) LL_price = valuewhen(bought, LL, 0) HH_price = valuewhen(bought, HH, 0) entry_LL_price = strategy.position_size > 0 ? LL_price : na entry_HH_price = strategy.position_size < 0 ? HH_price : na tp=strategy.position_avg_price + (strategy.position_avg_price - entry_LL_price)*i_TPRRR stp=strategy.position_avg_price - (entry_HH_price - strategy.position_avg_price)*i_TPRRR // ATR Stop ATR=atr(i_ATR)*i_ATRMult ATRLong = ohlc4 - ATR ATRShort = ohlc4 + ATR ATRLongStop = valuewhen(bought, ATRLong, 0) ATRShortStop = valuewhen(bought, ATRShort, 0) LongSL_ATR_price = strategy.position_size > 0 ? ATRLongStop : na ShortSL_ATR_price = strategy.position_size < 0 ? ATRShortStop : na ATRtp=strategy.position_avg_price + (strategy.position_avg_price - LongSL_ATR_price)*i_TPRRR ATRstp=strategy.position_avg_price - (ShortSL_ATR_price - strategy.position_avg_price)*i_TPRRR // Strategy Stop float LongStop = valuewhen(bought,low[1],0)*(1-i_PercIncrement) float ShortStop = valuewhen(bought,high[1],0)*(1+i_PercIncrement) float StratTP = na float StratSTP = na /////////////////////// STRATEGY LOGIC ///////////////////////////////////////// //RSI RSI=rsi(close, i_RSI) //BOLL1 [middleS, upperS, lowerS] = bb(close, lengthS, 1) p1 = plot(upperS, "Slow BB Upper Band", color=color.teal) p2 = plot(lowerS, "Slow BB Lower Band", color=color.teal) fill(p1, p2, title = "Slow BB Background", color=color.blue, transp=95) //BOLL2 [middleF, upperF, lowerF] = bb(close, lengthF, 1) p1F = plot(upperF, "Fast BB Upper Band", color=color.gray) p2F = plot(lowerF, "Fast BB Lower Band", color=color.gray) fill(p1F, p2F, title = "Fast BB Background", color=color.white, transp=95) BUY = bar_index > 40 and (RSI > 50) and (close > upperF) and crossover(close, upperS) SELL = bar_index > 40 and (RSI < 50) and (close < lowerF) and crossunder(close, lowerS) longexit=close < upperF shortexit=close > lowerF //Trading Inputs i_strategyClose=input(true, title="Use Strategy Close Logic") DPR=input(true, "Allow Direct Position Reverse") reverse=input(false, "Reverse Trades") // Entries if reverse if not DPR strategy.entry("long", strategy.long, when=SELL and strategy.position_size == 0) strategy.entry("short", strategy.short, when=BUY and strategy.position_size == 0) else strategy.entry("long", strategy.long, when=SELL) strategy.entry("short", strategy.short, when=BUY) else if not DPR strategy.entry("long", strategy.long, when=BUY and strategy.position_size == 0) strategy.entry("short", strategy.short, when=SELL and strategy.position_size == 0) else strategy.entry("long", strategy.long, when=BUY) strategy.entry("short", strategy.short, when=SELL) if i_strategyClose strategy.close("long", when=longexit) strategy.close("short", when=shortexit) SL= i_SLType == "Swing Lo/Hi" ? entry_LL_price : i_SLType == "ATR Stop" ? LongSL_ATR_price : LongStop SSL= i_SLType == "Swing Lo/Hi" ? entry_HH_price : i_SLType == "ATR Stop" ? ShortSL_ATR_price : ShortStop TP= i_SLType == "Swing Lo/Hi" ? tp : i_SLType == "ATR Stop" ? ATRtp : StratTP STP= i_SLType == "Swing Lo/Hi" ? stp : i_SLType == "ATR Stop" ? ATRstp : StratSTP //TrailingStop dif=(valuewhen(strategy.position_size>0 and strategy.position_size[1]<=0, high,0)) -strategy.position_avg_price trailOffset = strategy.position_avg_price - SL var tstop = float(na) if strategy.position_size > 0 tstop := high- trailOffset - dif if tstop<tstop[1] tstop:=tstop[1] else tstop := na StrailOffset = SSL - strategy.position_avg_price var Ststop = float(na) Sdif=strategy.position_avg_price-(valuewhen(strategy.position_size<0 and strategy.position_size[1]>=0, low,0)) if strategy.position_size < 0 Ststop := low+ StrailOffset + Sdif if Ststop>Ststop[1] Ststop:=Ststop[1] else Ststop := na strategy.exit("TP & SL", "long", limit=TP, stop=TS? tstop : SL, when=i_SL) strategy.exit("TP & SL", "short", limit=STP, stop=TS? Ststop : SSL, when=i_SL) /////////////////////// PLOTS ////////////////////////////////////////////////// plot(i_SL and strategy.position_size > 0 and not TS ? SL : i_SL and strategy.position_size > 0 and TS ? tstop : na , title='SL', style=plot.style_cross, color=color.red) plot(i_SL and strategy.position_size < 0 and not TS ? SSL : i_SL and strategy.position_size < 0 and TS ? Ststop : na , title='SSL', style=plot.style_cross, color=color.red) plot(i_SL and strategy.position_size > 0 ? TP : na, title='TP', style=plot.style_cross, color=color.green) plot(i_SL and strategy.position_size < 0 ? STP : na, title='STP', style=plot.style_cross, color=color.green) // Draw price action setup arrows plotshape(BUY ? 1 : na, style=shape.triangleup, location=location.belowbar, color=color.green, title="Bullish Setup", size=size.auto) plotshape(SELL ? 1 : na, style=shape.triangledown, location=location.abovebar, color=color.red, title="Bearish Setup", size=size.auto)
Kifier's MFI/STOCH Hidden Divergence/Trend Beater
https://www.tradingview.com/script/FCVH11LD-Kifier-s-MFI-STOCH-Hidden-Divergence-Trend-Beater/
kifier
https://www.tradingview.com/u/kifier/
144
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © kifier //@version=4 strategy("Kifier's MFI/STOCH Hidden Divergence/Trend Beater", shorttitle = "Kifier's MFI/STOCH", overlay=false, margin_long=100, margin_short=100, default_qty_type = strategy.percent_of_equity, default_qty_value = 95, max_boxes_count = 500) //Values enb_date = input(false ,"Enable Date Range?", type = input.bool, inline = "1") enb_current = input(true ,"Today as End Date" , type = input.bool, inline = "1") i_start_date = input(timestamp("01 Jan 2021 00:00 +0300") ,"Start Date" , type=input.time) i_end_date = input(timestamp("16 July 2021 00:00 +0300") ,"End Date" , type=input.time) time_check = iff(enb_date ? (time >= i_start_date) and (enb_current ? true : time <= i_end_date) : true, true, false) i_vwma_length = input(50, "VWMA Length" ,type = input.integer, group = "Indicator Settings", inline = "2") i_sma_length = input(50, "SMA Length" ,type = input.integer, group = "Indicator Settings", inline = "2") i_stoch_length = input(28, "Stoch Length" ,type = input.integer, group = "Indicator Settings", inline = "3") i_mfi_length = input(7 , "MFI Length" ,type = input.integer, group = "Indicator Settings", inline = "3") i_obv_length = input(100, "OBV Length" ,type = input.integer, group = "Indicator Settings") i_atr_len = input(100, "ATR Ranging-trend len" ,type = input.integer, group = "Indicator Settings", tooltip = "This is the length of the ATR Emas that check when the market in a general trend or is just ranging") i_div_price = input(5 ,"Price Divergant Pivots" ,type = input.integer, group = "Divergance Settings") i_inacc = input(0.05 ,"Price Inaccuracy" ,type = input.float , group = "Divergance Settings") i_div_length = input(3 ,"Divergance Valid Period" ,type = input.integer, group = "Divergance Settings") i_mfi_left = input(5 ,"MFI Left/Right Pivots" ,type = input.integer, group = "Divergance Settings", inline = "4") i_mfi_right = input(2 ,"" ,type = input.integer, group = "Divergance Settings", inline = "4") tp_percentage = input(10 , "TP Percentage" ,type = input.float , group = "Exit Settings")/100 _inacc = input(0.03, "Support Inaccuracy" ,type = input.float, step = 0.01, group = "Exit Settings") enb_stoch_mfi = input(true, "Use Stoch/MFI Trend" , type = input.bool, group = "Individual Entries") enb_stoch_mfi_div = input(true, "Use Stoch/MFI Divergance ", type = input.bool, group = "Individual Entries") c_mfi = input(color.yellow ,"MFI/STOCH Colour " , type = input.color, group = "Indicator Colours", inline = "os") c_stoch = input(color.silver ,"" , type = input.color, group = "Indicator Colours", inline = "os") c_buy = input(color.green ,"Buy/Sell Colour " , type = input.color, group = "Indicator Colours", inline = "pos") c_sell = input(color.red ,"" , type = input.color, group = "Indicator Colours", inline = "pos") c_flat = input(color.blue ,"Flat/Trending Colours" , type = input.color, group = "Indicator Colours", inline = "trend") c_longtrend = input(color.green ,"" , type = input.color, group = "Indicator Colours", inline = "trend") //Global Variables var float tpprice = na f_c_gradientAdvDec(_source, _center, _c_bear, _c_bull) => var float _maxAdvDec = 0. var float _qtyAdvDec = 0. bool _xUp = crossover(_source, _center) bool _xDn = crossunder(_source, _center) float _chg = change(_source) bool _up = _chg > 0 bool _dn = _chg < 0 bool _srcBull = _source > _center bool _srcBear = _source < _center _qtyAdvDec := _srcBull ? _xUp ? 1 : _up ? _qtyAdvDec + 1 : _dn ? max(1, _qtyAdvDec - 1) : _qtyAdvDec : _srcBear ? _xDn ? 1 : _dn ? _qtyAdvDec + 1 : _up ? max(1, _qtyAdvDec - 1) : _qtyAdvDec : _qtyAdvDec _maxAdvDec := max(_maxAdvDec, _qtyAdvDec) float _transp = 100 - (_qtyAdvDec * 100 / _maxAdvDec) var color _return = na _return := _srcBull ? color.new(_c_bull, _transp) : _srcBear ? color.new(_c_bear, _transp) : _return //Simple Sup/Res var float _pH = na var float _pL = na _ph = pivothigh(high,20,20) _pl = pivotlow(low,20,20) _high_inacc = _inacc * high _low_inacc = _inacc * low if _ph _pH := high if (high-_high_inacc) > _pH and _ph _pH := high _pH := nz(_pH) if _pl _pL := low if (low+_low_inacc) < _pL[1] _pL := low _pL := nz(_pL) broke_res = iff(crossover(close, _pH), true, false) //Indicator Initialisation s_stoch = stoch(close, high, low, i_stoch_length) s_vwma = vwma(close,i_vwma_length) s_sma = sma(close,i_sma_length) //MONEY FLOW + BBW atr1 =ema((atr(14)/close),i_atr_len/2) atr2 =ema((atr(14)/close), i_atr_len) is_ranging = iff(atr1 < atr2, true, false) s_mfi = mfi(close,i_mfi_length) overTop = iff(s_mfi >= 90, true, false) underBot = iff(s_mfi <= 10, true, false) //Price Divergance ph = pivothigh(high, i_div_price,i_div_price) pl = pivotlow(low,i_div_price,i_div_price) var float pH = 0.0 var float pL = 0.0 high_acc = high * (i_inacc) low_acc = low * i_inacc if (high-high_acc) > pH or (high+high_acc < pH) and ph pH := high pH := nz(pH) if (low+low_acc) < pL or (low-low_acc > pL) and pl pL := low pL := nz(pL) higher_low = false lower_low = false //Filter out innacurate if ph or pl if pL < pL[1] lower_low := true if pL > pL[1] higher_low := true //MFI Divergance mh = pivothigh(s_mfi, i_mfi_left,i_mfi_right) ml = pivotlow(s_mfi, i_mfi_left,i_mfi_right) bl = bar_index var float mH = 0.0 var float mL = 0.0 var int bL = 0 if mh mH := highest(nz(mh),i_mfi_left) mH := nz(mH) if ml bL := bar_index mL := ml mL := nz(mL) higher_low_m = false lower_low_m = false if ml if mL < mL[1] lower_low_m := true if mL > mL[1] higher_low_m := true //Combintion var int price_range = na var int rsi_range = na var int mfi_range = na //Higher low on price, lower low on rsi, then check with stoch mfi_div_bullish = iff(higher_low and higher_low_m, true, false) if mfi_div_bullish price_range := 0 rsi_range := 0 //VWMA/SMA/OBV _src = s_vwma-s_sma sd_src = stdev(_src,14) pooled_src = (_src/sd_src)*2 sd_s_vwma = stdev(s_vwma,14) sd_s_sma = stdev(s_sma,14) longTrend = obv > ema(obv,100) and is_ranging == false crossOver = crossover(s_vwma , s_sma) crossingOver = (s_vwma > s_sma) and (close >= s_vwma) crossUnder = crossunder(s_vwma, s_sma) crossingUnder = (s_vwma < s_sma) and (close <= s_vwma) hist_color = f_c_gradientAdvDec(s_vwma-s_sma, (s_vwma-s_sma)/2, color.new(c_sell,90), color.new(c_buy,80)) //Strategy Entries mfi_stoch_trend = iff(enb_stoch_mfi, iff(s_stoch >= 50 and crossover(s_mfi, 50) and crossingOver and longTrend and is_ranging == false, true, false), false) var buy_counter_rsi = 0 var buy_counter_mfi = 0 mfi_div = iff(enb_stoch_mfi_div, iff(mfi_div_bullish and crossingOver and s_stoch >= 50 and is_ranging, true, false), false) if mfi_div buy_counter_mfi := bar_index + 5 mfi_divergent_buy = iff(bar_index <= buy_counter_mfi and strategy.position_size == 0, true, false) //Strategy Entries order_fired = false var float previousRes = 0.0 tpprice := strategy.position_avg_price * (1+tp_percentage) if time_check if mfi_stoch_trend strategy.entry("Buy", true, comment = "[B] STOCH/MFI") order_fired := true if mfi_divergent_buy strategy.entry("Buy", true, comment = "[B] MFI Hidden Divergance") order_fired := true if order_fired previousRes := _pL if strategy.position_size > 0 strategy.exit("Buy", limit = tpprice, comment = "TP") if close <= previousRes strategy.exit("Buy", stop = previousRes, comment = "SL") //Drawings hline(0, "Base", color.white) hline(100, "Max", color.white) p_stoch = plot(s_stoch, color = c_stoch) p_mfi = plot(s_mfi, color = c_mfi) hline(70, "Top Line") p_mid = plot(50, "Mid Line", color.new(color.white,100)) hline(50, "Mid Line") hline(30, "Bot Line") fill(p_stoch, p_mid, color.new(c_stoch, 60)) plotshape(crossOver ? 5 : crossUnder ? -5 : na, style = shape.square, color = crossOver ? c_buy : crossUnder ? c_sell : na, size = size.tiny, location = location.absolute) plot((_src/sd_src)*2, color = hist_color, style = plot.style_histogram) //Boxes var string same = "" var box _box = na if longTrend and is_ranging == false and same != "longtrend" same := "longtrend" _box := box.new(bar_index, 105, bar_index, 100, bgcolor = c_longtrend,border_color = color.new(color.white, 100)) else if is_ranging and same != "isranging" same := "isranging" _box := box.new(bar_index, 105, bar_index, 100, bgcolor = c_flat,border_color = color.new(color.white, 100)) if not na(_box) box.set_right(_box,bar_index) //Div Lines var line _line = na if mfi_divergent_buy _line = line.new(bL[1] -6, s_mfi[bar_index-bL[1]], bar_index + 6, s_mfi, color = color.green, width = 3)
[astropark] Moon Phases [strategy]
https://www.tradingview.com/script/BAc77VfD-astropark-Moon-Phases-strategy/
astropark
https://www.tradingview.com/u/astropark/
808
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // @version=4 strategy(title="[astropark] Moon Phases [strategy]", overlay=true, pyramiding = 10, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, initial_capital = 100000, currency = currency.USD, commission_value = 0.1) // INPUT --- { newMoonColor = input(color.black, "New Moon Color") fullMoonColor = input(color.white, "Full Moon Color") fillBackground = input(true, "Fill Background?") newMoonBackgroundColor = input(#fffff0aa, "New Moon Background Color") fullMoonBackgroundColor = input(#aaaaaaaa, "Full Moon Background Color") //} --- INPUT // FUNCTION --- { normalize(_v) => x = _v x := x - floor(x) if x < 0 x := x + 1 x calcPhase(_year, _month, _day) => int y = na int m = na float k1 = na float k2 = na float k3 = na float jd = na float ip = na y := _year - floor((12 - _month) / 10) m := _month + 9 if m >= 12 m := m - 12 k1 := floor(365.25 * (y + 4712)) k2 := floor(30.6 * m + 0.5) k3 := floor(floor((y / 100) + 49) * 0.75) - 38 jd := k1 + k2 + _day + 59 if jd > 2299160 jd := jd - k3 ip := normalize((jd - 2451550.1) / 29.530588853) age = ip * 29.53 //} --- FUNCTION // INIT --- { age = calcPhase(year, month, dayofmonth) moon = floor(age)[1] > floor(age) ? 1 : floor(age)[1] < 15 and floor(age) >= 15 ? -1 : na //} --- INIT // PLOT --- { plotshape( moon==1, "Full Moon", shape.circle, location.top, color.new(newMoonColor, 20), size=size.normal ) plotshape( moon==-1, "New Moon", shape.circle, location.bottom, color.new(fullMoonColor, 20), size=size.normal ) var color col = na if moon == 1 and fillBackground col := fullMoonBackgroundColor if moon == -1 and fillBackground col := newMoonBackgroundColor bgcolor(col, title="Moon Phase", transp=10) //} --- PLOT // STRATEGY --- { strategy = input("buy on new moon, sell on full moon", options=["buy on new moon, sell on full moon","sell on new moon, buy on full moon"]) longCond = strategy == "buy on new moon, sell on full moon" ? moon == -1 : moon == 1 shortCond = strategy == "buy on new moon, sell on full moon" ? moon == 1 : moon == -1 weAreInLongTrade = false weAreInShortTrade = false weAreInLongTrade := (longCond or weAreInLongTrade[1]) and shortCond == false weAreInShortTrade := (shortCond or weAreInShortTrade[1]) and longCond == false buySignal = longCond and weAreInLongTrade[1] == false sellSignal = shortCond and weAreInShortTrade[1] == false showBuySellSignals = input(defval=true, title = "Show Buy/Sell Signals") longEnabled = input(true, title="Long enabled") shortEnabled = input(true, title="Short enabled") analysisStartYear = input(2017, "Backtesting From Year", minval=1980) analysisStartMonth = input(1, "And Month", minval=1, maxval=12) analysisStartDay = input(1, "And Day", minval=1, maxval=31) analysisStartHour = input(0, "And Hour", minval=0, maxval=23) analysisStartMinute = input(0, "And Minute", minval=0, maxval=59) analyzeFromTimestamp = timestamp(analysisStartYear, analysisStartMonth, analysisStartDay, analysisStartHour, analysisStartMinute) plotshape(showBuySellSignals and buySignal, title="Buy Label", text="Buy", location=location.belowbar, style=shape.labelup, size=size.tiny, color=color.green, textcolor=color.white, transp=0) plotshape(showBuySellSignals and sellSignal, title="Sell Label", text="Sell", location=location.abovebar, style=shape.labeldown, size=size.tiny, color=color.red, textcolor=color.white, transp=0) strategy.entry("long", strategy.long, when = time > analyzeFromTimestamp and buySignal and longEnabled) strategy.entry("short", strategy.short, when = time > analyzeFromTimestamp and sellSignal and shortEnabled) strategy.close("long", when = sellSignal) strategy.close("short", when = buySignal) //} --- STRATEGY
Trend Bounce [racer8]
https://www.tradingview.com/script/xV3t2X7R-Trend-Bounce-racer8/
racer8
https://www.tradingview.com/u/racer8/
476
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © racer8 //@version=4 // This Algo Strategy Has Only 3 rules and 62% Win Rate (Youtube) strategy("Trend Bounce", overlay=true) nn = input(7,"Channel Length") hi = highest(high,nn) lo = lowest(low,nn) n2 = input(200,"Ma Length") ma = sma(close,n2) if close>ma and close<lo[1] strategy.entry("Buy",strategy.long) if close>hi[1] strategy.close("Buy") if close<ma and close>hi[1] strategy.entry("Sell",strategy.short) if close<lo[1] strategy.close("Sell") plot(hi,"high",color=color.aqua) plot(lo,"low",color=color.aqua) plot(ma,"sma",color=color.yellow) //-----------------------------------------Stop Loss------------------------------------------------------ atr = sma(tr,10)[1] bought = strategy.position_size[0] > strategy.position_size[1] sold = strategy.position_size[0] < strategy.position_size[1] slm = input(2.0,"ATR Stop Loss",minval=0) StopPrice_Long = strategy.position_avg_price - slm*atr // determines stop loss's price StopPrice_Short = strategy.position_avg_price + slm*atr // determines stop loss's price FixedStopPrice_Long = valuewhen(bought,StopPrice_Long,0) // stores original StopPrice FixedStopPrice_Short = valuewhen(sold,StopPrice_Short,0) // stores original StopPrice plot(FixedStopPrice_Long,"ATR Stop Loss Long",color=color.blue,linewidth=1,style=plot.style_cross) plot(FixedStopPrice_Short,"ATR Stop Loss Short",color=color.red,linewidth=1,style=plot.style_cross) if strategy.position_size > 0 strategy.exit(id="Stop", stop=FixedStopPrice_Long) // commands stop loss order to exit! if strategy.position_size < 0 strategy.exit(id="Stop", stop=FixedStopPrice_Short) // commands stop loss order to exit!
255 EMA Strategy
https://www.tradingview.com/script/ThjDXxtX-255-EMA-Strategy/
tweakerID
https://www.tradingview.com/u/tweakerID/
83
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/ // © bufirolas //--- From 15 Trading Examples by Trader Alyx --- // Seems like this strategy works better if we reverse the EMA filter logic. // "Description: This basic scalping strategy allows you to enter the market based upon sentiment // provided by the EMA, set at 255 periods. When price is trading below the 255 EMA, you would // look to enter a LONG BUY positions, and when price is trading above the 255 EMA, you would // look to enter a SELL SHORT position. The MACD lagging indicator will show you clear signals for // when to do this. When the MACD lines cross in a bullish manner and price is below the 255 // EMA, buy. When the MACD lines cross in a bearish manner and price is above the 255 EMA, // sell. // NOTE: Make sure that price is trading away from the 255EMA before entering a LONG or SHORT // position. As you can see in the chart below, the clearest signs for trade entry were presented // when price was trading AWAY from the 255EMA" //@version=4 strategy("255 EMA Strategy", overlay=true, pyramiding=1, default_qty_type=strategy.cash, default_qty_value=30000, commission_value = 0.04, initial_capital=10000) //Inputs i_reverse=input(false, title="Trade Reverse") i_EMAreverse=input(true, title="EMA Reverse Entry") i_EMAlength=input(defval=255, title="EMA Length") i_EMAexpander=input(defval=5, title="EMA Expander") i_MACDmult=input(defval=1, minval=1, title="MACD Mult") //Strategy Variables EMA=ema(close,i_EMAlength) [macdLine, signalLine, histLine]=macd(close, 12*i_MACDmult, 26*i_MACDmult, 9*i_MACDmult) EMAupper=EMA+((atr(100))*i_EMAexpander) EMAlower=EMA-((atr(100))*i_EMAexpander) //SL & TP Inputs i_SL=input(true, title="Use Swing Lo/Hi Stop Loss & Take Profit") i_SwingLookback=input(10, title="Swing Lo/Hi Lookback") i_SLExpander=input(defval=0.6, step=.2, title="SL Expander")*.01 i_TPExpander=input(defval=1.2, step=.2, title="TP Expander")*.01 //SL & TP Variables SwingLow=lowest(i_SwingLookback) SwingHigh=highest(i_SwingLookback) //SL & TP Calculations bought=strategy.position_size != strategy.position_size[1] lSL=valuewhen(bought, SwingLow, 0)*(1-i_SLExpander) sSL=valuewhen(bought, SwingHigh, 0)*(1+i_SLExpander) lTP=strategy.position_avg_price + (strategy.position_avg_price-(valuewhen(bought, SwingLow, 0))*(1-i_TPExpander)) sTP=strategy.position_avg_price - (valuewhen(bought, SwingHigh, 0) - strategy.position_avg_price)*(1+i_TPExpander*100) islong=strategy.position_size > 0 isshort=strategy.position_size < 0 SL= islong ? lSL : isshort ? sSL : na TP= islong ? lTP : isshort ? sTP : na //Calculations EMAbuy=i_EMAreverse ? close > EMAupper : close < EMAlower EMAsell=i_EMAreverse ? close < EMAlower : close > EMAupper MACDbuy=crossover(macdLine, signalLine) MACDsell=crossunder(macdLine, signalLine) //Entries strategy.entry("long", long=not i_reverse?true:false, when=EMAbuy and MACDbuy) strategy.entry("short", long=not i_reverse?false:true, when=EMAsell and MACDsell) //Exits if i_SL strategy.exit("longexit", "long", stop=SL, limit=TP) strategy.exit("shortexit", "short", stop=SL, limit=TP) //Plots plot(EMA, "EMA", color=color.white, linewidth=2) plot(EMAupper, "EMA Upper Band") plot(EMAlower, "EMA Lower Band") plot(i_SL ? SL : na, color=color.red, style=plot.style_cross, title="SL") plot(i_SL ? TP : na, color=color.green, style=plot.style_cross, title="TP")
ADX + RSI Strat
https://www.tradingview.com/script/2z02415r-ADX-RSI-Strat/
tweakerID
https://www.tradingview.com/u/tweakerID/
131
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/ // © tweakerID // This is a strategy that uses the 7 Period RSI to buy when the indicator is shown as oversold (OS) and sells when // the index marks overbought (OB). It also uses the ADX to determine whether the trend is ranging or trending // and filters out the trending trades. Seems to work better for automated trading when the logic is inversed (buying OB // and selling the OS) wihout stop loss. //@version=4 strategy("ADX + RSI Strat", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=100, commission_value=0.04, calc_on_every_tick=false) direction = input(0, title = "Strategy Direction", type=input.integer, minval=-1, maxval=1) strategy.risk.allow_entry_in(direction == 0 ? strategy.direction.all : (direction < 0 ? strategy.direction.short : strategy.direction.long)) //SL & TP Inputs i_SL=input(false, title="Use Swing Lo/Hi Stop Loss & Take Profit") i_SwingLookback=input(20, title="Swing Lo/Hi Lookback") i_SLExpander=input(defval=0, step=.2, title="SL Expander") i_TPExpander=input(defval=0, step=.2, title="TP Expander") i_reverse=input(true, title="Reverse Trades") i_ADXClose=input(true, title="ADX Close") //SL & TP Calculations SwingLow=lowest(i_SwingLookback) SwingHigh=highest(i_SwingLookback) bought=strategy.position_size != strategy.position_size[1] LSL=valuewhen(bought, SwingLow, 0)-((valuewhen(bought, atr(14), 0))*i_SLExpander) SSL=valuewhen(bought, SwingHigh, 0)+((valuewhen(bought, atr(14), 0))*i_SLExpander) lTP=strategy.position_avg_price + (strategy.position_avg_price-(valuewhen(bought, SwingLow, 0))+((valuewhen(bought, atr(14), 0))*i_TPExpander)) sTP=strategy.position_avg_price - (valuewhen(bought, SwingHigh, 0)-strategy.position_avg_price)-((valuewhen(bought, atr(14), 0))*i_TPExpander) islong=strategy.position_size > 0 isshort=strategy.position_size < 0 SL= islong ? LSL : isshort ? SSL : na TP= islong ? lTP : isshort ? sTP : na //RSI Calculations RSI=rsi(close, 7) OS=input(20, step=5) OB=input(80, step=5) //ADX Calculations adxlen = input(14, title="ADX Smoothing") dilen = input(200, title="DI Length") dirmov(len) => up = change(high) down = -change(low) plusDM = na(up) ? na : (up > down and up > 0 ? up : 0) minusDM = na(down) ? na : (down > up and down > 0 ? down : 0) truerange = rma(tr, len) plus = fixnan(100 * rma(plusDM, len) / truerange) minus = fixnan(100 * rma(minusDM, len) / truerange) [plus, minus] adx(dilen, adxlen) => [plus, minus] = dirmov(dilen) sum = plus + minus adx = 100 * rma(abs(plus - minus) / (sum == 0 ? 1 : sum), adxlen) sig = adx(dilen, adxlen) adxlevel=input(20, step=5) //Entry Logic BUY = sig < adxlevel and (RSI < OS) SELL = sig < adxlevel and (RSI > OB) //Entries strategy.entry("long", strategy.long, when=i_reverse?SELL:BUY) strategy.entry("short", strategy.short, when=not i_reverse?SELL:BUY) //Exits if i_SL strategy.exit("longexit", "long", stop=SL, limit=TP) strategy.exit("shortexit", "short", stop=SL, limit=TP) if i_ADXClose strategy.close_all(when=sig > adxlevel) //Plotss plot(i_SL ? SL : na, color=color.red, style=plot.style_cross, title="SL") plot(i_SL ? TP : na, color=color.green, style=plot.style_cross, title="TP") plotshape(BUY ? 1 : na, style=shape.triangleup, location=location.belowbar, color=color.green, title="Bullish Setup") plotshape(SELL ? 1 : na, style=shape.triangledown, location=location.abovebar, color=color.red, title="Bearish Setup")
Bollinger Bands + ADX Strategy
https://www.tradingview.com/script/b4Izc9Je-Bollinger-Bands-ADX-Strategy/
tweakerID
https://www.tradingview.com/u/tweakerID/
150
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/ // © tweakerID // This strategy uses Bollinger Bands to buy when the price // crosses over the lower band and sell when it crosses down // the upper band. It only takes trades when the ADX is // below a certain level, and exits all trades when it's above it. //@version=4 strategy("BB + ADX Strategy", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_value = 0.04, initial_capital=10000) //Inputs i_reverse=input(false, title="Reverse Trades") i_ADXClose=input(true, title="ADX Close") i_SL=input(false, title="Use Swing Lo/Hi Stop Loss & Take Profit") i_SwingLookback=input(20, title="Swing Lo/Hi Lookback") i_SLExpander=input(defval=0, step=.5, title="SL Expander") i_TPExpander=input(defval=0, step=.5, title="TP Expander") //ADX Calculations adxlen = input(14, title="ADX Smoothing") dilen = input(20, title="DI Length") dirmov(len) => up = change(high) down = -change(low) plusDM = na(up) ? na : (up > down and up > 0 ? up : 0) minusDM = na(down) ? na : (down > up and down > 0 ? down : 0) truerange = rma(tr, len) plus = fixnan(100 * rma(plusDM, len) / truerange) minus = fixnan(100 * rma(minusDM, len) / truerange) [plus, minus] adx(dilen, adxlen) => [plus, minus] = dirmov(dilen) sum = plus + minus adx = 100 * rma(abs(plus - minus) / (sum == 0 ? 1 : sum), adxlen) sig = adx(dilen, adxlen) adxlevel=input(20, step=5) //BB Calculations BBCALC=input(false, title="-----------BB Inputs-----------") length = input(20, minval=1) mult = input(2.0, minval=0.001, maxval=50) MAlen=input(defval=9) source = close basis = sma(source, length) dev = mult * stdev(source, length) upper = basis + dev lower = basis - dev //Entry Logic BUY = crossover(source, lower) and sig < adxlevel SELL = crossunder(source, upper) and sig < adxlevel //SL & TP Calculations SwingLow=lowest(i_SwingLookback) SwingHigh=highest(i_SwingLookback) bought=strategy.position_size != strategy.position_size[1] LSL=valuewhen(bought, SwingLow, 0)-((valuewhen(bought, atr(14), 0))*i_SLExpander) SSL=valuewhen(bought, SwingHigh, 0)+((valuewhen(bought, atr(14), 0))*i_SLExpander) lTP=strategy.position_avg_price + (strategy.position_avg_price-(valuewhen(bought, SwingLow, 0))+((valuewhen(bought, atr(14), 0))*i_TPExpander)) sTP=strategy.position_avg_price - (valuewhen(bought, SwingHigh, 0)-strategy.position_avg_price)-((valuewhen(bought, atr(14), 0))*i_TPExpander) islong=strategy.position_size > 0 isshort=strategy.position_size < 0 SL= islong ? LSL : isshort ? SSL : na TP= islong ? lTP : isshort ? sTP : na //Entries strategy.entry("long", long=i_reverse?false:true, when=BUY) strategy.entry("short", long=i_reverse?true:false, when=SELL) //EXITS if i_ADXClose strategy.close_all(when=sig > adxlevel) if i_SL strategy.exit("longexit", "long", stop=SL, limit=TP) strategy.exit("shortexit", "short", stop=SL, limit=TP) //Plots plot(i_SL ? SL : na, color=color.red, style=plot.style_cross, title="SL") plot(i_SL ? TP : na, color=color.green, style=plot.style_cross, title="TP") plot(upper) plot(lower)
Big Bar Strategy
https://www.tradingview.com/script/uuinZwsR-Big-Bar-Strategy/
tweakerID
https://www.tradingview.com/u/tweakerID/
344
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/ // © tweakerID // This strategy detects and uses big bars to enter a position. When the Big Bar // is bearish (red candle) the position will be long and viceversa // for short positions. The stop loss (optional) is placed on the low of the // candle used to trigger the position and user inputs allow you to modify the // size of the SL. Take profit is placed on a reward ratio of 1. User can also modify // the size of the bar body used to determine if we have a real Big Bar and // filter out Doji bars. Big Bars are determined relative to the previous X period size, // which can also be modified, as well as the required size of the Big Bar relative to this period average. //@version=4 strategy("Big Bar Strategy", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=10000, commission_value=0.04, calc_on_every_tick=false, slippage=0) direction = input(0, title = "Strategy Direction", type=input.integer, minval=-1, maxval=1) strategy.risk.allow_entry_in(direction == 0 ? strategy.direction.all : (direction < 0 ? strategy.direction.short : strategy.direction.long)) /////////////////////// STRATEGY INPUTS //////////////////////////////////////// title1=input(true, "-----------------Strategy Inputs-------------------") barsizeThreshold=input(.5, step=.1, minval=.5, maxval=.9, title="Bar Body Size") period=input(10, title="Period for bar size average") mult=input(2, step=.2, title="Big Size Avg Mult to determine Big Bar") i_Confirmation=input(true, title="Enter trade after confirmation bar") /////////////////////// BACKTESTER ///////////////////////////////////////////// title2=input(true, "-----------------General Inputs-------------------") // Backtester General Inputs i_SL=input(true, title="Use Stop Loss and Take Profit") i_SLType=input(defval="ATR Stop", title="Type Of Stop", options=["Strategy Stop", "Swing Lo/Hi", "ATR Stop"]) i_SPL=input(defval=10, title="Swing Point Lookback") i_PercIncrement=input(defval=3, step=.1, title="Swing Point SL Perc Increment")*0.01 i_ATR = input(14, title="ATR Length") i_ATRMult = input(4, step=.1, title="ATR Multiple") i_TPRRR = input(1, step=.1, title="Take Profit Risk Reward Ratio") TS=input(false, title="Trailing Stop") // Bought and Sold Boolean Signal bought = strategy.position_size > strategy.position_size[1] or strategy.position_size < strategy.position_size[1] // Price Action Stop and Take Profit LL=(lowest(i_SPL))*(1-i_PercIncrement) HH=(highest(i_SPL))*(1+i_PercIncrement) LL_price = valuewhen(bought, LL, 0) HH_price = valuewhen(bought, HH, 0) entry_LL_price = strategy.position_size > 0 ? LL_price : na entry_HH_price = strategy.position_size < 0 ? HH_price : na tp=strategy.position_avg_price + (strategy.position_avg_price - entry_LL_price)*i_TPRRR stp=strategy.position_avg_price - (entry_HH_price - strategy.position_avg_price)*i_TPRRR // ATR Stop ATR=atr(i_ATR)*i_ATRMult ATRLong = ohlc4 - ATR ATRShort = ohlc4 + ATR ATRLongStop = valuewhen(bought, ATRLong, 0) ATRShortStop = valuewhen(bought, ATRShort, 0) LongSL_ATR_price = strategy.position_size > 0 ? ATRLongStop : na ShortSL_ATR_price = strategy.position_size < 0 ? ATRShortStop : na ATRtp=strategy.position_avg_price + (strategy.position_avg_price - LongSL_ATR_price)*i_TPRRR ATRstp=strategy.position_avg_price - (ShortSL_ATR_price - strategy.position_avg_price)*i_TPRRR /////////////////////// STRATEGY LOGIC ///////////////////////////////////////// barsize=high-low barbodysize=close>open?(open-close)*-1:(open-close) barsizeavg=sum(barsize, period)/period bigbar=barsize >= barsizeavg*mult and barbodysize>barsize*barsizeThreshold barcolor(bigbar ? color.white : na) // Strategy Stop barsizemult=input(1, step=.1, title="Strategy SL/TP Mult") float LongStop = strategy.position_avg_price - (valuewhen(bought,barsize,0)*barsizemult) float ShortStop = strategy.position_avg_price + (valuewhen(bought,barsize,0)*barsizemult) float StratTP = strategy.position_avg_price + (valuewhen(bought,barsize,0)*barsizemult) float StratSTP = strategy.position_avg_price - (valuewhen(bought,barsize,0)*barsizemult) BUY=i_Confirmation ? close[1] < open[1] and bigbar[1] and close > open : close < open and bigbar SELL=i_Confirmation ? close[1] > open[1] and bigbar[1] and close < open : close > open and bigbar //Trading Inputs DPR=input(true, "Allow Direct Position Reverse") reverse=input(false, "Reverse Trades") // Entries if reverse if not DPR strategy.entry("long", strategy.long, when=SELL and strategy.position_size == 0) strategy.entry("short", strategy.short, when=BUY and strategy.position_size == 0) else strategy.entry("long", strategy.long, when=SELL) strategy.entry("short", strategy.short, when=BUY) else if not DPR strategy.entry("long", strategy.long, when=BUY and strategy.position_size == 0) strategy.entry("short", strategy.short, when=SELL and strategy.position_size == 0) else strategy.entry("long", strategy.long, when=BUY) strategy.entry("short", strategy.short, when=SELL) SL= i_SLType == "Swing Lo/Hi" ? entry_LL_price : i_SLType == "ATR Stop" ? LongSL_ATR_price : LongStop SSL= i_SLType == "Swing Lo/Hi" ? entry_HH_price : i_SLType == "ATR Stop" ? ShortSL_ATR_price : ShortStop TP= i_SLType == "Swing Lo/Hi" ? tp : i_SLType == "ATR Stop" ? ATRtp : StratTP STP= i_SLType == "Swing Lo/Hi" ? stp : i_SLType == "ATR Stop" ? ATRstp : StratSTP //TrailingStop dif=(valuewhen(strategy.position_size>0 and strategy.position_size[1]<=0, high,0)) -strategy.position_avg_price trailOffset = strategy.position_avg_price - SL var tstop = float(na) if strategy.position_size > 0 tstop := high- trailOffset - dif if tstop<tstop[1] tstop:=tstop[1] else tstop := na StrailOffset = SSL - strategy.position_avg_price var Ststop = float(na) Sdif=strategy.position_avg_price-(valuewhen(strategy.position_size<0 and strategy.position_size[1]>=0, low,0)) if strategy.position_size < 0 Ststop := low+ StrailOffset + Sdif if Ststop>Ststop[1] Ststop:=Ststop[1] else Ststop := na strategy.exit("TP & SL", "long", limit=TP, stop=TS? tstop : SL, when=i_SL) strategy.exit("TP & SL", "short", limit=STP, stop=TS? Ststop : SSL, when=i_SL) /////////////////////// PLOTS ////////////////////////////////////////////////// plot(i_SL and strategy.position_size > 0 and not TS ? SL : i_SL and strategy.position_size > 0 and TS ? tstop : na , title='SL', style=plot.style_cross, color=color.red) plot(i_SL and strategy.position_size < 0 and not TS ? SSL : i_SL and strategy.position_size < 0 and TS ? Ststop : na , title='SSL', style=plot.style_cross, color=color.red) plot(i_SL and strategy.position_size > 0 ? TP : na, title='TP', style=plot.style_cross, color=color.green) plot(i_SL and strategy.position_size < 0 ? STP : na, title='STP', style=plot.style_cross, color=color.green) // Draw price action setup arrows plotshape(BUY ? 1 : na, style=shape.triangleup, location=location.belowbar, color=color.green, title="Bullish Setup", size=size.auto) plotshape(SELL ? 1 : na, style=shape.triangledown, location=location.abovebar, color=color.red, title="Bearish Setup", size=size.auto)
2nd Grade Strategy
https://www.tradingview.com/script/JnDTnKH1-2nd-Grade-Strategy/
cyrule
https://www.tradingview.com/u/cyrule/
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/ // © cyrule //@version=4 strategy("2nd Grade Strategy", overlay=false, shorttitle="2GTS", max_lines_count = 500, max_labels_count = 500, calc_on_every_tick = true, calc_on_order_fills = true, pyramiding = 1, default_qty_type = strategy.percent_of_equity, default_qty_value = 10) source = input(close, title = "Source") maType = input(title = "Moving Average Type", defval="SMA", options=["SMA", "EMA", "RMA", "WMA", "VWMA"]) hline( 30, linestyle = hline.style_dotted, color = color.new(color.gray, transp = 50), linewidth = 2, title = "Overbought") hline( 0, linestyle = hline.style_solid , color = color.new(color.black, transp = 50), linewidth = 1, title = "Centerline") hline(-30, linestyle = hline.style_dotted, color = color.new(color.gray, transp = 50), linewidth = 2, title = "Oversold") // ******************* // * Stochastic * // ******************* showSS = input(true , title = "Show Stochastic?" , group = "Stochastic") showSSC = input(true , title = "Show Stochastic Crossovers?", group = "Stochastic") Length = input(10, minval = 1, title = "%K Length" , group = "Stochastic") SmoothK = input(3, minval = 1, title = "%K Smoothing" , group = "Stochastic") SmoothD = input(3, minval = 1, title = "%D Smoothing" , group = "Stochastic") // Calculate Stochastic K = sma(1,1) D = sma(1,1) if (maType == "SMA") K := sma(stoch(source, high, low, Length), SmoothK) D := sma(K, SmoothD) if (maType == "EMA") K := ema(stoch(source, high, low, Length), SmoothK) D := ema(K, SmoothD) if (maType == "RMA") K := rma(stoch(source, high, low, Length), SmoothK) D := rma(K, SmoothD) if (maType == "WMA") K := wma(stoch(source, high, low, Length), SmoothK) D := wma(K, SmoothD) if (maType == "VWMA") K := vwma(stoch(source, high, low, Length), SmoothK) D := vwma(K, SmoothD) StochasticCrossOver = crossover(K, D) StochasticCrossUnder = crossunder(K, D) // Lukis SS plotshape(showSSC and StochasticCrossOver and K <= 20 ? K : na, text = "Golden\nCrossover", color = color.new(color.green, transp = 50), location = location.top, size = size.tiny) plotshape(showSSC and StochasticCrossUnder and K >= 80 ? D : na, text = "Deadly\nCrossover", color = color.new(color.red, transp = 50) , location = location.top, size = size.tiny) plot(series = showSS ? K - 50 : na, color = color.new(#0072E8, transp = 50), linewidth = 2, title = "K") plot(series = showSS ? D - 50 : na, color = color.new(#9F1C24, transp = 50), linewidth = 2, title = "D") // *************************** // * Relative Strength Index * // *************************** showRSI = input(true, title = "Show RSI?", group = "Relative Strength Index") rsiLength = input(title = "RSI Length", type = input.integer, defval = 14, group = "Relative Strength Index") rsiValue = rsi(source, rsiLength) plot(showRSI ? rsiValue - 50 : na, color = color.new(color.fuchsia, transp = 50), linewidth = 2, title = "RSI") // ******** // * MACD * // ******** showMACD = input(true, title = "Show MACD?", group = "MACD") fastMACDLength = input(12, minval = 1, title = "MACD fast moving average", group = "MACD") slowMACDLength = input(26,minval = 1, title = "MACD slow moving average", group = "MACD") signalMACDLength = input(9,minval = 1, title = "MACD signal line moving average", group = "MACD") normalizeMACD = input(3, minval = 0.25, step = 0.25, title = "Normalization factor", group = "MACD") // MACD Calculation fastMA = sma(source, fastMACDLength) slowMA = sma(source, slowMACDLength) filterMA = sma(source, signalMACDLength) if (maType == "SMA") fastMA := sma(source, fastMACDLength) slowMA := sma(source, slowMACDLength) filterMA := sma(source, signalMACDLength) if (maType == "EMA") fastMA := ema(source, fastMACDLength) slowMA := ema(source, slowMACDLength) filterMA := ema(source, signalMACDLength) if (maType == "RMA") fastMA := rma(source, fastMACDLength) slowMA := rma(source, slowMACDLength) filterMA := rma(source, signalMACDLength) if (maType == "WMA") fastMA := wma(source, fastMACDLength) slowMA := wma(source, slowMACDLength) filterMA := wma(source, signalMACDLength) if (maType == "VWMA") fastMA := vwma(source, fastMACDLength) slowMA := vwma(source, slowMACDLength) filterMA := vwma(source, signalMACDLength) macd = fastMA - slowMA macdSignal = sma(macd, signalMACDLength) if (maType == "SMA") macdSignal := sma (macd, signalMACDLength) if (maType == "EMA") macdSignal := ema (macd, signalMACDLength) if (maType == "RMA") macdSignal := rma (macd, signalMACDLength) if (maType == "WMA") macdSignal := wma (macd, signalMACDLength) if (maType == "VWMA") macdSignal := vwma(macd, signalMACDLength) hist = macd - macdSignal maxHist = highest(hist, 252) // Look back 252 bars to be used for normalization factor hist := hist / maxHist * 100 / normalizeMACD histColor = hist < 0 ? hist < hist[1] ? color.new(color.maroon, transp = 80) : color.new(color.red, transp = 80) : hist < hist[1] ? color.new(color.olive, transp = 80) : color.new(color.green, transp = 80) plot(showMACD ? hist : na, style = plot.style_columns, color = histColor) // ************** // * Signal * // ************** showBull = input(false, title = "Show Bullish Signal?", group = "Signal") showBear = input(false, title = "Show Bearish Signal?", group = "Signal") bullishCriteria = 0 if (K > D) and (K > K[1]) and (D > D[1]) bullishCriteria := bullishCriteria + 1 if rsiValue > 50 bullishCriteria := bullishCriteria + 1 if (hist > 0) and (hist > hist[1]) bullishCriteria := bullishCriteria + 1 bearishCriteria = 0 if (K < D) and (K < K[1]) and (D < D[1]) bearishCriteria := bearishCriteria + 1 if rsiValue < 50 bearishCriteria := bearishCriteria + 1 if (hist < 0) and (hist < hist[1]) bearishCriteria := bearishCriteria + 1 signal = color.new(color.white, transp = 0) if bearishCriteria == 2 signal := color.new(color.orange, transp = 50) if bearishCriteria == 3 signal := color.new(color.red, transp = 50) if bullishCriteria == 2 signal := color.new(color.aqua, transp = 50) if bullishCriteria == 3 signal := color.new(color.green, transp = 50) bullishCriteria := showBull ? bullishCriteria : 0 bearishCriteria := showBear ? bearishCriteria : 0 bgcolor(iff(bullishCriteria > 1, signal, na), title = 'Bullish Signal') bgcolor(iff(bearishCriteria > 1, signal, na), title = 'Bearish Signal') // *********** // * Trading * // *********** startDate = input(title="Start Date", type=input.integer, defval=1, minval=1, maxval=31, group = "Trading") startMonth = input(title="Start Month", type=input.integer, defval=1, minval=1, maxval=12, group = "Trading") startYear = input(title="Start Year", type=input.integer, defval=2019, minval=1900, maxval=2100, group = "Trading") endDate = input(title="End Date", type=input.integer, defval=31, minval=1, maxval=31, group = "Trading") endMonth = input(title="End Month", type=input.integer, defval=12, minval=1, maxval=12, group = "Trading") endYear = input(title="End Year", type=input.integer, defval=2019, minval=1800, maxval=2100, group = "Trading") longTPPerc = input(title = "Take Profit Threshold (%)" , minval = 0.0, step = 0.5, defval = 2.5, group = "Trading") / 100 profitRatio = input(title = "Profit-to-Loss ratio (risk tolerance)", minval = 1.0, step = 0.1, defval = 1.4, group = "Trading") longSLPerc = longTPPerc / profitRatio takeProfit = strategy.position_avg_price * (1 + longTPPerc) stopLoss = strategy.position_avg_price * (1 - longSLPerc) inDateRange = (time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0)) and (time < timestamp(syminfo.timezone, endYear, endMonth, endDate, 0, 0)) strategy.entry("Long" , strategy.long , floor(strategy.initial_capital*.1/close), stop = strategy.position_avg_price * 1.25, when = inDateRange and bullishCriteria > 1) strategy.entry("Short", strategy.short, floor(strategy.initial_capital*.1/close), stop = strategy.position_avg_price * 1.25, when = inDateRange and bearishCriteria > 1) strategy.close("Long" , when = (open >= takeProfit) or (open <= stopLoss) or (high >= takeProfit) or (low <= stopLoss)) strategy.close("Short", when = (open >= takeProfit) or (open <= stopLoss) or (high >= takeProfit) or (low <= stopLoss)) if (not inDateRange) strategy.close_all() plotshape(bullishCriteria, location = location.top, color = color.new(color.black, transp = 100)) plotshape(bearishCriteria, location = location.top, color = color.new(color.black, transp = 100))
Stochastic RSI + WMA + SMA strat
https://www.tradingview.com/script/n1M9HghZ-Stochastic-RSI-WMA-SMA-strat/
tweakerID
https://www.tradingview.com/u/tweakerID/
220
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/ // © bufirolas // Works well with a wide stop with 20 bars lookback // for the SL level and a 2:1 reward ratio Take Profit . // These parameters can be modified in the Inputs section of the strategy panel. // "an entry signal it's a cross down or up on // the stochastics. if you're in a downtrend // on the hourly time frame you // must also be in a downtrend on the five // minute so the five period has to be below the 144 // as long as the five period is still trading below // the 144 period on both the hourly and the five minutes // we are looking for these short signals crosses down // in the overbought region of the stochastic. Viceversa for longs" //@version=4 strategy("Stoch + WMA + SMA strat", overlay=true, pyramiding=1, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_value = 0.04, initial_capital=10000) //SL & TP Inputs i_SL=input(true, title="Use Swing Lo/Hi Stop Loss & Take Profit") i_SwingLookback=input(20, title="Swing Lo/Hi Lookback") i_SLExpander=input(defval=10, step=1, title="SL Expander") i_TPExpander=input(defval=30, step=1, title="TP Expander") i_reverse=input(false, title="Reverse Trades") i_TStop =input(false, title="Use Trailing Stop") //Strategy Inputs src4 = input(close, title="RSI Source") stochOS=input(defval=20, step=5, title="Stochastics Oversold Level") stochOB=input(defval=80, step=5, title="Stochastics Overbought Level") //Stoch rsi Calculations smoothK = input(3, minval=1) smoothD = input(3, minval=1) lengthRSI = input(14, minval=1) lengthStoch = input(14, minval=1) rsi1 = rsi(src4, lengthRSI) k = sma(stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK) d = sma(k, smoothD) h0 = hline(80, linestyle=hline.style_dotted) h1 = hline(20, linestyle=hline.style_dotted) //MA wmalen=input(defval=144, title="WMA Length") WMA = security(syminfo.tickerid, "60", wma(close, wmalen)) SMA = security(syminfo.tickerid, "60", sma(close, 5)) minWMA = wma(close, wmalen) minSMA = sma(close, 5) //Entry Logic stobuy = crossover(k, d) and k < stochOS stosell = crossunder(k, d) and k > stochOB mabuy = minSMA > minWMA daymabuy = SMA > WMA //SL & TP Calculations SwingLow=lowest(i_SwingLookback) SwingHigh=highest(i_SwingLookback) bought=strategy.position_size != strategy.position_size[1] LSL=valuewhen(bought, SwingLow, 0)-((valuewhen(bought, atr(14), 0)/5)*i_SLExpander) SSL=valuewhen(bought, SwingHigh, 0)+((valuewhen(bought, atr(14), 0)/5)*i_SLExpander) lTP=(strategy.position_avg_price + (strategy.position_avg_price-(valuewhen(bought, SwingLow, 0)))+((valuewhen(bought, atr(14), 0)/5)*i_TPExpander)) sTP=(strategy.position_avg_price - (valuewhen(bought, SwingHigh, 0) - strategy.position_avg_price))-((valuewhen(bought, atr(14), 0)/5)*i_TPExpander) islong=strategy.position_size > 0 isshort=strategy.position_size < 0 //TrailingStop dif=(valuewhen(strategy.position_size>0 and strategy.position_size[1]<=0, high,0)) -strategy.position_avg_price trailOffset = strategy.position_avg_price - LSL var tstop = float(na) if strategy.position_size > 0 tstop := high- trailOffset - dif if tstop<tstop[1] tstop:=tstop[1] else tstop := na StrailOffset = SSL - strategy.position_avg_price var Ststop = float(na) Sdif=strategy.position_avg_price-(valuewhen(strategy.position_size<0 and strategy.position_size[1]>=0, low,0)) if strategy.position_size < 0 Ststop := low+ StrailOffset + Sdif if Ststop>Ststop[1] Ststop:=Ststop[1] else Ststop := na //Stop Selector SL= islong ? LSL : isshort ? SSL : na if i_TStop SL:= islong ? tstop : isshort ? Ststop : na TP= islong ? lTP : isshort ? sTP : na //Entries if stobuy and mabuy and daymabuy strategy.entry("long", long=not i_reverse?true:false) if stosell and not mabuy and not daymabuy strategy.entry("short", long=not i_reverse?false:true) //Exit if i_SL strategy.exit("longexit", "long", stop=SL, limit=TP) strategy.exit("shortexit", "short", stop=SL, limit=TP) //Plots plot(i_SL ? SL : na, color=color.red, style=plot.style_cross) plot(i_SL ? TP : na, color=color.green, style=plot.style_cross) plot(minWMA) plot(minSMA, color=color.green)
Swing Points Breakouts
https://www.tradingview.com/script/SeK3ch7J-Swing-Points-Breakouts/
tweakerID
https://www.tradingview.com/u/tweakerID/
74
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © tweakerID // Long term strategy for managing a Crypto investment with Swing Trades of more than 1 day. The strategy buys with a // stop order at the Swing High price (green line) and sells with a stop order at the Swing Low price (red line). // The direction of the strategy can be adjusted in the Inputs panel. //@version=4 strategy("Swing Points Breakouts", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=10000, commission_value=0.04) direction = input(0, title = "Strategy Direction", type=input.integer, minval=-1, maxval=1) strategy.risk.allow_entry_in(direction == 0 ? strategy.direction.all : (direction < 0 ? strategy.direction.short : strategy.direction.long)) //Inputss i_SL=input(true, title="Use Swing Lo/Hi Stop Loss & Take Profit") i_SwingLow=input(10, title="Swing Low Lookback") i_SwingHigh=input(10, title="Swing High Lookback") i_reverse=input(false, "Reverse Trades") i_SLExpander=input(defval=0, step=1, title="SL Expander") //Strategy Calculations SwingLow=lowest(i_SwingLow) SwingHigh=highest(i_SwingHigh) //SL & TP Calculations bought=strategy.position_size != strategy.position_size[1] LSL=valuewhen(bought, SwingLow, 0)-((valuewhen(bought, atr(14), 0)/5)*i_SLExpander) SSL=valuewhen(bought, SwingHigh, 0)+((valuewhen(bought, atr(14), 0)/5)*i_SLExpander) islong=strategy.position_size > 0 isshort=strategy.position_size < 0 SL= islong ? LSL : isshort ? SSL : na //Entries and Exits strategy.entry("long", true, stop=i_reverse?na:SwingHigh, limit=i_reverse?SwingLow:na) strategy.entry("short", false, stop=i_reverse?na:SwingLow, limit=i_reverse?SwingHigh:na) if i_SL strategy.exit("longexit", "long", stop=LSL) strategy.exit("shortexit", "short", stop=SSL) //Plots plot(i_SL ? SL : na, color=color.red, style=plot.style_cross, title="SL") plot(SwingLow, color=color.red) plot(SwingHigh, color=color.green)
polynomic_stop
https://www.tradingview.com/script/7HgV7eRl-polynomic-stop/
IntelTrading
https://www.tradingview.com/u/IntelTrading/
64
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © Alferow //@version=4 strategy("polynomic_stop", overlay=true, initial_capital=1000, commission_value=0.1, default_qty_type=strategy.percent_of_equity, default_qty_value=100) D = input(0.1, minval = 0.0001, title = 'decrement') S = input(2, minval = 1.0, title = 'polynomial degree ') MA = input(20, title = 'period SMA') MN = input(20, title = 'period MIN_for') SMA = sma(close, MA) MIN = lowest(low, MN) var stop = 0.0 var num = 0 if strategy.opentrades[1] == 0 and strategy.opentrades != 0 stop := MIN if strategy.opentrades != 0 num := num + 1 if strategy.opentrades == 0 num := 0 stop := MIN hl = stop + D * pow(num, S) plot(hl) plot(SMA, color = color.red) strategy.entry("buy", true, when = close[1] < SMA[1] and close > SMA) strategy.close("buy", when = crossover(hl, close))
SuperTrend - Custom Screener and Dynamic Alerts
https://www.tradingview.com/script/j0IOCx2L-SuperTrend-Custom-Screener-and-Dynamic-Alerts/
sharaaU7
https://www.tradingview.com/u/sharaaU7/
515
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/ // © ralagh //@version=4 strategy("Supertrend", overlay = true, format=format.price, precision=2) alert_strings = array.new_string(2) array.set(alert_strings, 0, "") array.set(alert_strings, 1, "") table_row_count = array.new_int(5) array.set(table_row_count, 0, 1) array.set(table_row_count, 1, 1) array.set(table_row_count, 2, 1) array.set(table_row_count, 3, 1) array.set(table_row_count, 4, 1) var UpTabl = table.new(position = position.top_center, columns = 5, rows = 20, bgcolor = color.rgb(255,255,255), border_width = 2, frame_color= color.black, frame_width = 2) var DnTabl = table.new(position = position.bottom_center, columns = 5, rows = 20, bgcolor = color.rgb(255,255,255), border_width = 2, frame_color= color.black, frame_width = 2) table.cell(table_id = UpTabl, column = 1, row = 0, text = " SuperTrend Buy") table.cell(table_id = DnTabl, column = 1, row = 0, text = " SuperTrend Sell") table.cell(table_id = UpTabl, column = 2, row = 0, text = " ▲▲") table.cell(table_id = DnTabl, column = 2, row = 0, text = " ▼▼") table.cell(table_id = UpTabl, column = 0, row = 1, text = "Ticker") table.cell(table_id = UpTabl, column = 1, row = 1, text = "Close") table.cell(table_id = UpTabl, column = 2, row = 1, text = "DHigh") table.cell(table_id = UpTabl, column = 3, row = 1, text = "DLow") table.cell(table_id = UpTabl, column = 4, row = 1, text = "% Change") table.cell(table_id = DnTabl, column = 0, row = 1, text = "Ticker") table.cell(table_id = DnTabl, column = 1, row = 1, text = "Close") table.cell(table_id = DnTabl, column = 2, row = 1, text = "DHigh") table.cell(table_id = DnTabl, column = 3, row = 1, text = "DLow") table.cell(table_id = DnTabl, column = 4, row = 1, text = "% Change") mult = input(type=input.float, defval=3) period = input(type=input.integer, defval=10) [superTrend, dir] = supertrend(mult, period) colResistance = dir == 1 and dir == dir[1] ? color.new(color.red, 0) : color.new(color.red, 100) colSupport = dir == -1 and dir == dir[1] ? color.new(color.green, 0) : color.new(color.green, 100) plot(superTrend, color = colResistance, linewidth=2) plot(superTrend, color = colSupport, linewidth=2) if (dir == -1 and dir == dir[1]) strategy.entry("Buy", strategy.long, comment="Buy") if (dir == 1 and dir == dir[1]) strategy.entry("Sell", strategy.short, comment="Sell") f_SupCro(_ticker)=> p_chg = (close - close[1])/close[1] * 100 [cl_dp, hi_dp, lo_dp, chg_dp] = security(_ticker, 'D', [close, high, low, p_chg], lookahead = barmerge.lookahead_on) [cl_p, ST_R] = security(_ticker, timeframe.period, [close, superTrend], lookahead = barmerge.lookahead_on) _msg = _ticker + "~Cls-" + tostring(round(cl_p * 100) / 100) + "/" + tostring(round(chg_dp * 100) / 100) + "% ," //cl_p > ST_R (Uptrend) //cl_p < ST_R (Downtrend) if crossover(cl_p, ST_R) _msg := _msg + "PHi~" + tostring(round(hi_dp * 100) / 100) + ", PLo~" + tostring(round(lo_dp * 100) / 100) + "-ST▲" array.set(alert_strings, 0, array.get(alert_strings, 0) + "\n" + _msg) array.set(table_row_count, 0, array.get(table_row_count, 0) + 1) //alert(_msg + "-Sup▲", alert.freq_once_per_bar_close ) // For Individual Stock Alerts if barstate.islast table.cell(table_id = UpTabl, column = 0, row = array.get(table_row_count, 0), text = _ticker) table.cell(table_id = UpTabl, column = 1, row = array.get(table_row_count, 0), text = tostring(round(cl_p * 100) / 100), bgcolor=color.rgb(0, 200, 100)) table.cell(table_id = UpTabl, column = 2, row = array.get(table_row_count, 0), text = tostring(round(hi_dp * 100) / 100), bgcolor=color.rgb(0, 200, 100)) table.cell(table_id = UpTabl, column = 3, row = array.get(table_row_count, 0), text = tostring(round(lo_dp * 100) / 100), bgcolor=color.rgb(0, 200, 100)) table.cell(table_id = UpTabl, column = 4, row = array.get(table_row_count, 0), text = tostring(round(chg_dp * 100) / 100), bgcolor=color.rgb(0, 200, 100)) else if crossunder(cl_p, ST_R) _msg := _msg + "PHi~" + tostring(round(hi_dp * 100) / 100) + ", PLo~" + tostring(round(lo_dp * 100) / 100) + "-ST▼" array.set(table_row_count, 1, array.get(table_row_count, 1) + 1) array.set(alert_strings, 1, array.get(alert_strings, 1) + "\n" + _msg) //alert(_msg + "-Sup▼", alert.freq_once_per_bar_close) // For Individual Stock Alerts if barstate.islast table.cell(table_id = DnTabl, column = 0, row = array.get(table_row_count, 1), text = _ticker) table.cell(table_id = DnTabl, column = 1, row = array.get(table_row_count, 1), text = tostring(round(cl_p * 100) / 100), bgcolor=color.rgb(255, 0, 0)) table.cell(table_id = DnTabl, column = 2, row = array.get(table_row_count, 1), text = tostring(round(hi_dp * 100) / 100), bgcolor=color.rgb(255, 0, 0)) table.cell(table_id = DnTabl, column = 3, row = array.get(table_row_count, 1), text = tostring(round(lo_dp * 100) / 100), bgcolor=color.rgb(255, 0, 0)) table.cell(table_id = DnTabl, column = 4, row = array.get(table_row_count, 1), text = tostring(round(chg_dp * 100) / 100), bgcolor=color.rgb(255, 0, 0)) //plot(close, "Close", color=#8E1599) f_SupCro(syminfo.tickerid) f_SupCro(input('DJI', title=input.symbol)) f_SupCro(input('IXIC', title=input.symbol)) f_SupCro(input('SPX', title=input.symbol)) f_SupCro(input('RUT', title=input.symbol)) f_SupCro(input('AAPL', title=input.symbol)) f_SupCro(input('AMZN', title=input.symbol)) f_SupCro(input('FB', title=input.symbol)) f_SupCro(input('GOOG', title=input.symbol)) f_SupCro(input('NFLX', title=input.symbol)) f_SupCro(input('MSFT', title=input.symbol)) f_SupCro(input('NVDA', title=input.symbol)) f_SupCro(input('FDX', title=input.symbol)) f_SupCro(input('GLD', title=input.symbol)) if array.get(alert_strings, 0) != "" alert(array.get(alert_strings, 0), alert.freq_once_per_bar_close) if array.get(alert_strings, 1) != "" alert(array.get(alert_strings, 1), alert.freq_once_per_bar_close)
Dynamic Price Swing
https://www.tradingview.com/script/5P0IOGdg-Dynamic-Price-Swing/
Solutions1978
https://www.tradingview.com/u/Solutions1978/
250
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ //@version=4 //********************************************************************************************************** // Gradient Color Bars incorporated based on Color Gradient Function script by e2e4mfck //********************************************************************************************************** // ██████╗██████╗ ███████╗ █████╗ ████████╗███████╗██████╗ ██████╗ ██╗ ██╗ //██╔════╝██╔══██╗██╔════╝██╔══██╗╚══██╔══╝██╔════╝██╔══██╗ ██╔══██╗╚██╗ ██╔╝ //██║ ██████╔╝█████╗ ███████║ ██║ █████╗ ██║ ██║ ██████╔╝ ╚████╔╝ //██║ ██╔══██╗██╔══╝ ██╔══██║ ██║ ██╔══╝ ██║ ██║ ██╔══██╗ ╚██╔╝ //╚██████╗██║ ██║███████╗██║ ██║ ██║ ███████╗██████╔╝ ██████╔╝ ██║ // ╚═════╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚══════╝╚═════╝ ╚═════╝ ╚═╝ //███████╗ ██████╗ ██╗ ██╗ ██╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ ██╗ █████╗ ███████╗ █████╗ //██╔════╝██╔═══██╗██║ ██║ ██║╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝███║██╔══██╗╚════██║██╔══██╗ //███████╗██║ ██║██║ ██║ ██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗╚██║╚██████║ ██╔╝╚█████╔╝ //╚════██║██║ ██║██║ ██║ ██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ ██║ ╚═══██║ ██╔╝ ██╔══██╗ //███████║╚██████╔╝███████╗╚██████╔╝ ██║ ██║╚██████╔╝██║ ╚████║███████║ ██║ █████╔╝ ██║ ╚█████╔╝ //╚══════╝ ╚═════╝ ╚══════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚════╝ ╚═╝ ╚════╝ strategy(shorttitle='DPS',title='Dynamic Price Swing', overlay=true, initial_capital = 1000, process_orders_on_close=false, close_entries_rule="ANY", default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type=strategy.commission.percent, commission_value=0.18, calc_on_every_tick=false) // ————— Constants var string SH1 = "Red ⮀ Green" var string SH2 = "Purple ⮀ Blue" var string SH3 = "Yellow ⮀ DarkGreen" var string SH4 = "White ⮀ Black" var string SH5 = "White ⮀ Blue" var string SH6 = "White ⮀ Red" var string SH7 = "Rainbow" bgcolor(color.new(#000000,15), title="Dark Background") white = color.new(color.white, 50) // ----------------- Strategy Inputs ------------------------------------------------------------- //Instructions general = input(false, "Backtest Dates, Strategy Selection, and Risk Management Inputs apply to all strategies") //Backtest dates with auto finish date of today start = input(defval = timestamp("21 June 2021 00:00 -0500"), title = "Start Time", type = input.time, group="Backtest Dates") finish = input(defval = timestamp("31 December 2021 00:00 -0600"), title = "End Time", type = input.time, group="Backtest Dates") window() => time >= start and time <= finish ? true : false // create function "within window of time" // Strategy Selection - Long, Short, or Both general2 = input(false, "Average Price Channel strategy buys and sells when price crosses above or below the previous highest high and lowest low", group="Strategy Descriptions") general3 = input(false, "Moving Average strategy buys and sells when the price crosses above or below the selected price band, which also is shaded based on what you select.", group="Strategy Descriptions") general4 = input(false, "Fibonacci strategy buys and sells when the price crosses above the Fibonacci level selected.", group="Strategy Descriptions") general5 = input(false, "Peaks and Valleys buys and sells based on the combined crossing of the VWMA, ALMA, and Average MACD True Range trend lines.", group="Strategy Descriptions") general5b = input(false, "The settings for each strategy is grouped. Only the inputs indicated for the selected strategy will impact the triggers.", group="Strategy Descriptions") general5c = input(false, "All strategies use the Risk Management and Up/Down Trend Settings.", group="Strategy Descriptions") trigger = input ("Average Price Channel", "Select a Price Swing Trigger", options=["Average Price Channel", "Moving Average", "Fibonacci", "Peaks and Valleys"], group="Strategy Selection") usePrice = trigger=="Average Price Channel" ? true : false useMA = trigger == "Moving Average" ? true : false useFib = trigger == "Fibonacci" ? true : false usePV = trigger == "Peaks and Valleys" ? true : false general6 = input(false, "Use Long/Short only for backtest comparisons. Long is if you are starting with FIAT, Short is if you are starting with crypto.", group="Strategy Selection") strat = input(title="Trade Types", defval="Long/Short", options=["Long Only", "Long/Short", "Short Only"], group="Strategy Selection") strat_val = strat == "Long Only" ? 1 : strat == "Long/Short" ? 0 : -1 // ————— Inputs var bool _1 = input(false, "═══════════⥑ Gradient ⥏═══════════", group="Visualization Selection") var bool colorbars = input(true, "Use Gradient Color Bars?", group="Visualization Selection") var string i_scheme = input(SH1, " 》Color Scheme", options = [SH1, SH2, SH3, SH4, SH5, SH6, SH7], group="Visualization Selection") var bool i_invert = input(false, "Invert Colors", group="Visualization Selection") var bool i_barcolor = input(false, "Colorize Bars", group="Visualization Selection") // } // —————————— Color array { var color[] c_gradients = array.new_color(na) // Risk Management Inputs general7 = input(false, "You can control your gains and losses with these inputs that should be self-explanatory.", group="Risk Management") sl= input(50.0, "Stop Loss %", minval = 0, maxval = 100, step = 0.01, group="Risk Management") stoploss = sl/100 tp = input(50.0, "Target Profit %", minval = 0, maxval = 100, step = 0.01, group="Risk Management") TargetProfit = tp/100 ld = input(10, "Stop Trading After This Many Losing Days", type=input.integer, minval=0, maxval=100, step=1, group="Risk Management") strategy.risk.max_cons_loss_days(count=ld) ml = input(50, "Maximum % of Equity Lost to Halt Trading", type=input.integer, minval=1, maxval=100, step=1, group="Risk Management") strategy.risk.max_drawdown(value=ml, type=strategy.percent_of_equity) // General Settings general8 = input(false, "This section is for adjusting the EMA length and price lookback period for identifying upward/downward zones. You can add the Triple EMA indicator to a new pane to visually tweak these settings.", group="Up/Down Trend Settings") fastLength = input(5, minval=1, title="EMA Fast Length", group="Up/Down Trend Settings") slowLength = input(12, minval=1, title="EMA Slow Length", group="Up/Down Trend Settings") general9 = input(false, "The Average # of bars is what you observe as the number of up and down bars in a cycle", group="Up/Down Trend Settings") general10 = input(false, "For example, if a crypto's chart has 6 up and 4 down for each cycle before it repeats", group="Up/Down Trend Settings") general11 = input(false, "then your Average # of bars is 10 and your Price Lookback Period is 5 (half of the Avg #)", group="Up/Down Trend Settings") AvgLkbk = input(20, minval=1, title="Average # of bars in Up/Down Trend", group="Up/Down Trend Settings") lkbk = input(10,"Price Lookback Period", group="Up/Down Trend Settings") high_source = input(high,"High Source", group="Up/Down Trend Settings") low_source= input(low,"Low Source", group="Up/Down Trend Settings") diff1 = input(2.5, "High Price Knife Percentage (% difference to trigger a quick sell)", group="Price Channel Settings") diff = diff1/100 // Moving Average Inputs general12 = input(false, "For the Moving Average Strategy - define the percentage from the center price line you want trades to occur", group="Moving Average Settings") general13 = input(false, "the default is to use the first band (shaded in green and red) or you can choose to use the second or third price channel bands.", group="Moving Average Settings") InnerValue = input(1.6, title="1st Price Band %", group="Moving Average Settings") OuterValue = input(2.6, title="2nd Price Band %", group="Moving Average Settings") ExtremeValue = input(4.2, title="Extreme Price Band %", group="Moving Average Settings") BandUse = input("First", "Select Price Band to Trigger Trades", options=["First", "Second", "Extremes"], group="Strategy Selection") band = BandUse == "First" ? 1 : BandUse == "Second" ? 2 : BandUse == "Extremes" ? 3 : na // Fib Inputs general14 = input(false, "The standard Fibonacci retracement levels are available in the drop down selection for the Fibonacci strategy.", group="Fibonacci Settings") general15 = input(false, "Level 1 is where the trade will happen if the price crosses and the zone is up (for sell) and down (for buy)", group="Fibonacci Settings") general16 = input(false, "Level 2 is where the trade will always happen when the price crosses regardless of trend indicators.", group="Fibonacci Settings") Fib1 = input(1.618, "Fibonacci Level 1", options=[1.382, 1.618, 1.786, 2.000, 2.272, 2.382, 2.618, 3, 3.382, 3.618], group="Fibonacci Settings") Fib2 = input(2.618, "Fibonacci Level 2", options=[1.382, 1.618, 1.786, 2.000, 2.272, 2.382, 2.618, 3, 3.382, 3.618], group="Fibonacci Settings") // Peaks and Valleys Inputs general17 = input(false, "Peaks and Valleys is a more aggressive form of the moving average strategy. You can change the type of MA to have faster scalps.", group="Peaks and Valleys Options") maInput = input(title="MA Type (EMA is default - the rest experimental)", defval="EMA", options=["EMA", "SMA", "VWMA", "WMA"], group="Peaks and Valleys Options") //Entry area for custom bot messages (i.e. Quadency, 3Commas, etc) general18 = input(false, "Here you can either copy and paste a trigger message for a bot or a custom message for an Email or SMS alert", group="Bot Webhook Messages") general19 = input(false, "replace the alert body message with {{strategy.order.alert_message}} for a single message to map to alll long/short triggers.", group="Bot Webhook Messages") message_long_entry = input("long entry message", group="Bot Webhook Messages") message_long_exit = input("long exit message", group="Bot Webhook Messages") message_short_entry = input("short entry message", group="Bot Webhook Messages") message_short_exit = input("short exit message", group="Bot Webhook Messages") // ================================================================ Where the Magic Happens ======================================================================== // -------------------------------- Price Channel Calculation ---------------------------------- high1 = highest(high_source, AvgLkbk) high2 = highest(high_source, lkbk) lasthigh = max(high1, high2) low1 = lowest(low_source, AvgLkbk) low2 = lowest(low_source, lkbk) lastlow = min(low1, low2) hiHighs = lasthigh[1] loLows = lastlow[1] mids = (hiHighs + loLows)/2 plot(series = usePrice ? mids: na, title="Price Midline", color=white, linewidth=1) plot(series = usePrice ? hiHighs: na, title="Price High Line", color=white, linewidth=1) plot(series = usePrice ? loLows: na, title="Price Low Line", color=white, linewidth=1) // --------------------------------- Moving Averages ------------------------------------------- // Improved Price Channels CMA = mids CenteredMA= plot(series = usePrice ? na : CMA, color=color.blue , linewidth=2) HMA = usePrice ? hiHighs : CMA + (CMA * (InnerValue / 100)) HMA2 = usePrice ? na : useFib ? CMA + (atr(lkbk)*Fib1) : CMA + (CMA * (OuterValue / 100)) HMA3 = usePrice ? na : useFib ? CMA + (atr(lkbk)*Fib2) : CMA + (CMA * (ExtremeValue / 100)) LMA = usePrice ? loLows : CMA - (CMA * (InnerValue / 100)) LMA2 = usePrice ? na : useFib ? CMA - (atr(lkbk)*Fib1) : CMA - (CMA * (OuterValue / 100)) LMA3 = usePrice ? na : useFib ? CMA - (atr(lkbk)*Fib2) : CMA - (CMA * (ExtremeValue / 100)) // For Price Channels ma3 = sma(close, 3), vwma3 = vwma(close, 3) ma5 = sma(close, 5), vwma5 = vwma(close, 5) ma9 = sma(close, 9), vwma9 = vwma(close, 9) ma10 = sma(close,10) ma15 = sma(close,15) // For Fibonacci MA1 = ema(close,5),HA1 = ema(high,5),LA1 = ema(low,5) MA2 = ema(close,8),HA2 = ema(high,8),LA2 = ema(low,8) MA3 = ema(close,13),HA3 = ema(high,13),LA3 = ema(low,13) MA4 = ema(close,21),HA4 = ema(high,21),LA4 = ema(low,21) MA5 = ema(close,34),HA5 = ema(high,34),LA5 = ema(low,34) MA6 = ema(close,55),HA6 = ema(high,55),LA6 = ema(low,55) MA7 = ema(close,89),HA7 = ema(high,89),LA7 = ema(low,89) // For Peaks and Valleys getMA(src, length) => ma = 0.0 if maInput == "EMA" ma := ema(src, length) if maInput == "SMA" ma := sma(src, length) if maInput == "VWMA" ma := vwma(src, length) if maInput == "WMA" ma := wma(src, length) ma FastAvgValue = getMA(close, fastLength) SlowAvgValue = getMA(close, slowLength) fHi = highest(high, fastLength) fLo = lowest(low, fastLength) sHi = highest(high, slowLength) sLo = lowest(low, slowLength) FastStoch = (FastAvgValue - fHi) / (fHi - fLo) SlowStoch = (SlowAvgValue - sLo) / (sHi - sLo) STMACD = (FastStoch - SlowStoch) * 100 STMACDAvg = getMA(STMACD, AvgLkbk) // ====================================== Trend Direction Calculations =========================================== // -------------- Volume Trend------------------ cumUp = 0.0 cntUp = 0 cumDown = 0.0 cntDown = 0 for i=0 to lkbk-1 if close[i] > open[i] cumUp := cumUp + volume[i] cntUp := cntUp + 1 else cumDown := cumDown + volume[i] cntDown := cntDown + 1 averagevolumeup = (cumUp/cntUp) averagevolumedown = -(cumDown/cntDown) volUp = (averagevolumeup) <= volume and close > open volDown = (averagevolumedown) >= -volume and close < open flow = cumUp - cumDown //Call bullshit when trend doesn't agree with the numbers (fake pumps and dumps) BullShit1 = flow > 0 and flow[1] > 0 and volDown BullShit2 = flow < 0 and flow[1] < 0 and volUp BullShit = BullShit1 or BullShit2 upVol = volUp and flow > 0 and not BullShit downVol = volDown and flow < 0 and not BullShit // ----------------- Range Breakout Trend ------------------- src = high_source smoothrng(x, t, m)=> wper = (t*2) - 1 avrng = ema(abs(x - x[1]), t) smoothrng = ema(avrng, wper)*m smoothrng smrng = smoothrng(close, slowLength, lkbk) rngfilt(x, r)=> rngfilt = x rngfilt := x > nz(rngfilt[1]) ? ((x - r) < nz(rngfilt[1]) ? nz(rngfilt[1]) : (x - r)) : ((x + r) > nz(rngfilt[1]) ? nz(rngfilt[1]) : (x + r)) rngfilt filt = rngfilt(src, smrng) upward = 0.0 upward := filt > filt[1] ? nz(upward[1]) + 1 : filt < filt[1] ? 0 : nz(upward[1]) downward = 0.0 downward := filt < filt[1] ? nz(downward[1]) + 1 : filt > filt[1] ? 0 : nz(downward[1]) hband = filt + smrng lband = filt - smrng uptrend1 = (src > filt) and (src > src[1]) and (upward > 0) uptrend2 = (src > filt) and (src < src[1]) and (upward > 0) longCond = uptrend1 or uptrend2 downtrend1 = (src < filt) and (src < src[1]) and (downward > 0) downtrend2 = (src < filt) and (src > src[1]) and (downward > 0) shortCond = downtrend1 or downtrend2 CondIni = 0 CondIni := longCond ? 1 : shortCond ? -1 : CondIni[1] stroking = longCond and CondIni[1] == -1 // Arnaud Legoux Moving Average ( ALMA ) xrf(values, length) => r_val = float(na) if length >= 1 for i = 0 to length by 1 if na(r_val) or not na(values[i]) r_val := values[i] r_val r_val ma20 = sma(close,20) ma50 = sma(close,50) ma200 = sma(close,200) change2 = cmo(close, 2) change9 = cmo(close, 9) trendline = alma((close-sma(close,40))/sma(close,40)*100,21,0.85,6) tradingline = ema(ema(ema((2*close+high+low)/4,4),4),4) fastLine = ( sma((tradingline-xrf(tradingline,1))/xrf(tradingline,1)*100,1))*10 slowLine = alma( sma((tradingline-xrf(tradingline,1))/xrf(tradingline,1)*100,2),3,0.85,6)*10 pd = (high[1] - close[1]) / close[1] // Breakout (upward momentum) and Dumpout (downward momentumm) conditions based on ALMA indicator triggers combined with volume trend as a crosscheck to reduce false alerts // Fakeout based on patterns where the high point of the price is a reverse knife (when high is greater than 2% of the close price) - this typically leads to a small dump of FOOMO sellers breakout = fastLine>slowLine and fastLine<0 and longCond dumpout = fastLine<slowLine and fastLine>0 and shortCond fakeout = pd > diff or high >= HMA3 // ------------------------ Price Channel Plots -------------------------------------------------------- Ctr_Top = (useMA or useFib) ? (band==1 ? mids : band==2 ? HMA : band == 3 ? HMA2: na) : mids Ctr_Bottom = (useMA or useFib) ? (band==1 ? mids : band==2 ? LMA : band == 3 ? LMA2: na) : mids upper_function = (useMA or useFib) ? (band==1 ? HMA : band==2 ? HMA2 : band == 3 ? HMA3: na) : hiHighs lower_function = (useMA or useFib) ? (band==1 ? LMA : band==2 ? LMA2 : band == 3 ? LMA3: na) : loLows Ctr1 = plot(Ctr_Top, color=white) Ctr2 = plot(Ctr_Bottom, color=white) Upper = plot(upper_function, color=white) Lower = plot(lower_function, color=white) upper_color = color.new(color.green, 90) lower_color = color.new(color.red, 90) fill(Ctr1, Upper, upper_color) fill(Ctr2, Lower, lower_color) // ————— Fill the array with colors only on the first iteration of the script if barstate.isfirst if i_scheme == SH1 array.push(c_gradients, #ff0000), array.push(c_gradients, #ff2c00), array.push(c_gradients, #fe4200), array.push(c_gradients, #fc5300), array.push(c_gradients, #f96200), array.push(c_gradients, #f57000), array.push(c_gradients, #f07e00), array.push(c_gradients, #ea8a00), array.push(c_gradients, #e39600), array.push(c_gradients, #dca100), array.push(c_gradients, #d3ac00), array.push(c_gradients, #c9b600), array.push(c_gradients, #bfc000), array.push(c_gradients, #b3ca00), array.push(c_gradients, #a6d400), array.push(c_gradients, #97dd00), array.push(c_gradients, #86e600), array.push(c_gradients, #71ee00), array.push(c_gradients, #54f700), array.push(c_gradients, #1eff00) else if i_scheme == SH2 array.push(c_gradients, #ff00d4), array.push(c_gradients, #f71fda), array.push(c_gradients, #ef2ee0), array.push(c_gradients, #e63ae5), array.push(c_gradients, #de43ea), array.push(c_gradients, #d44bee), array.push(c_gradients, #cb52f2), array.push(c_gradients, #c158f6), array.push(c_gradients, #b75df9), array.push(c_gradients, #ac63fb), array.push(c_gradients, #a267fe), array.push(c_gradients, #966bff), array.push(c_gradients, #8b6fff), array.push(c_gradients, #7e73ff), array.push(c_gradients, #7276ff), array.push(c_gradients, #6479ff), array.push(c_gradients, #557bff), array.push(c_gradients, #437eff), array.push(c_gradients, #2e80ff), array.push(c_gradients, #0082ff) else if i_scheme == SH3 array.push(c_gradients, #fafa6e), array.push(c_gradients, #e0f470), array.push(c_gradients, #c7ed73), array.push(c_gradients, #aee678), array.push(c_gradients, #97dd7d), array.push(c_gradients, #81d581), array.push(c_gradients, #6bcc86), array.push(c_gradients, #56c28a), array.push(c_gradients, #42b98d), array.push(c_gradients, #2eaf8f), array.push(c_gradients, #18a48f), array.push(c_gradients, #009a8f), array.push(c_gradients, #00908d), array.push(c_gradients, #008589), array.push(c_gradients, #007b84), array.push(c_gradients, #0c707d), array.push(c_gradients, #196676), array.push(c_gradients, #215c6d), array.push(c_gradients, #275263), array.push(c_gradients, #2a4858) else if i_scheme == SH4 array.push(c_gradients, #ffffff), array.push(c_gradients, #f0f0f0), array.push(c_gradients, #e1e1e1), array.push(c_gradients, #d2d2d2), array.push(c_gradients, #c3c3c3), array.push(c_gradients, #b5b5b5), array.push(c_gradients, #a7a7a7), array.push(c_gradients, #999999), array.push(c_gradients, #8b8b8b), array.push(c_gradients, #7e7e7e), array.push(c_gradients, #707070), array.push(c_gradients, #636363), array.push(c_gradients, #575757), array.push(c_gradients, #4a4a4a), array.push(c_gradients, #3e3e3e), array.push(c_gradients, #333333), array.push(c_gradients, #272727), array.push(c_gradients, #1d1d1d), array.push(c_gradients, #121212), array.push(c_gradients, #000000) else if i_scheme == SH5 array.push(c_gradients, #ffffff), array.push(c_gradients, #f4f5fa), array.push(c_gradients, #e9ebf5), array.push(c_gradients, #dee1f0), array.push(c_gradients, #d3d7eb), array.push(c_gradients, #c8cde6), array.push(c_gradients, #bdc3e1), array.push(c_gradients, #b2b9dd), array.push(c_gradients, #a7b0d8), array.push(c_gradients, #9ca6d3), array.push(c_gradients, #919dce), array.push(c_gradients, #8594c9), array.push(c_gradients, #7a8bc4), array.push(c_gradients, #6e82bf), array.push(c_gradients, #6279ba), array.push(c_gradients, #5570b5), array.push(c_gradients, #4768b0), array.push(c_gradients, #385fab), array.push(c_gradients, #2557a6), array.push(c_gradients, #004fa1) else if i_scheme == SH6 array.push(c_gradients, #ffffff), array.push(c_gradients, #fff4f1), array.push(c_gradients, #ffe9e3), array.push(c_gradients, #ffded6), array.push(c_gradients, #ffd3c8), array.push(c_gradients, #fec8bb), array.push(c_gradients, #fdbdae), array.push(c_gradients, #fbb2a1), array.push(c_gradients, #f8a794), array.push(c_gradients, #f69c87), array.push(c_gradients, #f3917b), array.push(c_gradients, #f0856f), array.push(c_gradients, #ec7a62), array.push(c_gradients, #e86e56), array.push(c_gradients, #e4634a), array.push(c_gradients, #df563f), array.push(c_gradients, #db4933), array.push(c_gradients, #d63a27), array.push(c_gradients, #d0291b), array.push(c_gradients, #cb0e0e) else if i_scheme == SH7 array.push(c_gradients, #E50000), array.push(c_gradients, #E6023B), array.push(c_gradients, #E70579), array.push(c_gradients, #E908B7), array.push(c_gradients, #E00BEA), array.push(c_gradients, #A70DEB), array.push(c_gradients, #6E10ED), array.push(c_gradients, #3613EE), array.push(c_gradients, #162DEF), array.push(c_gradients, #1969F1), array.push(c_gradients, #1CA4F2), array.push(c_gradients, #1FDFF4), array.push(c_gradients, #22F5D2), array.push(c_gradients, #25F69C), array.push(c_gradients, #28F867), array.push(c_gradients, #2CF933), array.push(c_gradients, #5DFA2F), array.push(c_gradients, #96FC32), array.push(c_gradients, #CDFD35), array.push(c_gradients, #FFF938) // Invert colors in array if i_invert array.reverse(c_gradients) // ————— Rescale function // Credits to LucF, https://www.pinecoders.com/faq_and_code/#how-can-i-rescale-an-indicator-from-one-scale-to-another f_rescale(_src, _min, _max) => // Rescales series with known min/max to the color array size. // Dependency : c_gradients array // _src : series to rescale. // _min, _max : min/max values of series to rescale. var int _size = array.size(c_gradients) - 1 int _colorStep = int(_size * (_src - _min)) / int(max(_max - _min, 10e-10)) _colorStep := _colorStep > _size ? _size : _colorStep < 0 ? 0 : _colorStep int(_colorStep) // ————— Result // Dependency : c_gradients array f_colGrad(_src, _min, _max) => array.get(c_gradients, f_rescale(_src, _min, _max)) // Example: // resultColor = f_colGrad(_src, _min, _max) // } // ————— Rsi as a source rsi = rsi(close, 100) // ————— Bollinger bands on top of Rsi as gradient's min and max [_, rsiUpperBand, rsiLowerBand] = bb(rsi, 200, 1.618) // ————— Colorize the bounded source color c_rsi = f_colGrad(rsi, rsiLowerBand, rsiUpperBand) barcolor(i_barcolor ? crossover(STMACD, STMACDAvg) ? color.red : crossunder(STMACD, STMACDAvg) ? color.yellow : BullShit ? color.white : c_rsi : na) // ============================================================================= Entry and Exit Logic ====================================================================== // Entry Logic //Logic for Channel Buy/Sell CB1 = low < loLows and longCond and window() CB2 = breakout and window() Channel_Buy = CB1 or CB2 CS1 = high >= hiHighs and shortCond and window() CS2 = dumpout and window() CS3 = fakeout and window() Channel_Sell = CS1 or CS2 or CS3 //Logic for Moving Average MS1 = (band == 1 ? high > HMA : band == 2 ? high > HMA2 : band == 3 ? high > HMA3 : na) and shortCond and window() MS2 = (band == 1 ? high > HMA : band == 2 ? high > HMA2 : band == 3 ? high > HMA3 : na) and crossunder(STMACD, STMACDAvg) and window() MA_Sell = MS1 or MS2 MB1 = (band == 1 ? low<LMA : band == 2 ? low < LMA2 : band == 3 ? low < LMA3 : na) and longCond and window() MB2 = (band == 1 ? low<LMA : band == 2 ? low < LMA2 : band == 3 ? low < LMA3 : na) and crossover(STMACD, STMACDAvg) and window() MA_Buy = MB1 or MB2 //Logic for Fib Fib_Sell1 = high[1]>=HMA2 and high>=HMA3 and window() Fib_Sell2 = high[1]>=HMA2 and close<HMA3 and window() Fib_Sell3 = high >= HMA2 and BullShit and window() Fib_Sell4 = high > HMA3 and window() Fib_Sell = Fib_Sell1 or Fib_Sell2 or Fib_Sell3 or Fib_Sell4 Fib_Buy1 = low[3]<=LMA3 and low[2]<=LMA3 and low[1]<=LMA3 and low<=LMA3 and window() Fib_Buy2 = low<=LMA3 and BullShit and window() Fib_Buy3 = low <= LMA2 and crossover(STMACD, STMACDAvg) and window() Fib_Buy = Fib_Buy1 or Fib_Buy2 or Fib_Buy3 //----- Logic for Peaks and Valleys ----------------------------- // LB is Long Buy logic and SB is Short Buy Logic // LS is for Long Sell and is the same for Short Sells LB = low < loLows and crossover(STMACD, STMACDAvg) and window() SB = low < loLows and BullShit and window() PVBuy = LB or SB SS1 = high >= hiHighs and crossunder(STMACD, STMACDAvg) and window() LS1 = BullShit and high >= hiHighs and window() PVSell = LS1 or SS1 // ------------------------ Strategy Trades ------------------------------------------------------------- GoLong = usePrice ? Channel_Buy : useMA ? MA_Buy : useFib ? Fib_Buy : usePV ? PVBuy : false GoShort = usePrice ? Channel_Sell : useMA ? MA_Sell : useFib ? Fib_Sell : usePV ? PVSell : false CloseShort= usePrice ? Channel_Buy : useMA ? MA_Buy : useFib ? Fib_Buy : usePV ? PVBuy : false CloseLong = usePrice ? Channel_Sell : useMA ? MA_Sell : useFib ? Fib_Sell : usePV ? PVSell : false // Strategy Open and Close if (GoLong and strat_val==0 and strategy.position_size==0 and barstate.isconfirmed) strategy.entry(id="MIXED", long=true, oca_type=strategy.oca.cancel, oca_name="Mixed Entry", alert_message = message_long_entry) if (GoLong and strat_val==1 and strategy.position_size==0 and barstate.isconfirmed) strategy.entry("LONG", strategy.long, alert_message = message_long_entry) if (GoShort and strat_val==0 and strategy.position_size==0 and strategy.position_size[1]==0 and barstate.isconfirmed) strategy.entry(id="MIXED", long=false, oca_type=strategy.oca.cancel, oca_name="Mixed Entry", alert_message = message_short_entry) if (GoShort and strat_val==-1 and strategy.position_size==0 and barstate.isconfirmed) strategy.entry("SHORT", strategy.short, alert_message = message_short_entry) if(CloseLong and strategy.position_size > 0 and strat_val==1 and barstate.isconfirmed) strategy.close("LONG", alert_message = message_long_exit) if(CloseLong and strategy.position_size > 0 and strat_val==0 and barstate.isconfirmed) strategy.close("MIXED", alert_message = message_long_exit) if(CloseShort and strategy.position_size < 0 and strat_val==-1 and barstate.isconfirmed) strategy.close("SHORT", alert_message = message_short_exit) if(CloseShort and strategy.position_size < 0 and strat_val==0 and barstate.isconfirmed) strategy.close("MIXED", alert_message = message_short_exit) // -------------------- RISK MANAGEMENT FUNCTIONS ------------------------ //Calculate stop and take profit prices longStopPrice = strategy.position_avg_price * (1 - stoploss) longTakePrice = strategy.position_avg_price * (1 + TargetProfit) shortStopPrice = strategy.position_avg_price * (1 + stoploss) shortTakePrice = strategy.position_avg_price * (1 - TargetProfit) //Set exit strategy parameters if (strategy.position_size > 0 and strat_val==1) strategy.exit(id="Exit Long", from_entry = "LONG", stop = longStopPrice, limit = longTakePrice, alert_message = message_long_exit) if (strategy.position_size > 0 and strat_val==0) strategy.exit(id="Exit Mixed", from_entry = "MIXED", oca_name="Mixed Entry", stop = longStopPrice, limit = longTakePrice, alert_message = message_long_exit) if (strategy.position_size < 0 and strat_val==-1) strategy.exit(id="Exit Short", from_entry = "SHORT", stop = shortStopPrice, limit = shortTakePrice, alert_message = message_short_exit) if (strategy.position_size < 0 and strat_val==0) strategy.exit(id="Exit Mixed", from_entry = "MIXED", oca_name="Mixed Entry", stop = shortStopPrice, limit = shortTakePrice, alert_message = message_short_exit)
EMA Bounce Strategy
https://www.tradingview.com/script/nIGMNPhK-EMA-Bounce-Strategy/
tweakerID
https://www.tradingview.com/u/tweakerID/
207
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/ // © tweakerID // Simple strategy that checks for price bounces over an Exponential Moving Average. If the CLOSE of the candle bounces // back from having it's LOW below the EMA, then it's a Bull Bounce. If the CLOSE of the candle bounces down from having it's // high above the EMA, then it's a Bear Bounce. This logic can be reverted. //@version=4 strategy("EMA Bounce", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=10000, commission_value=0.04, calc_on_every_tick=false, slippage=0) direction = input(0, title = "Strategy Direction", type=input.integer, minval=-1, maxval=1) strategy.risk.allow_entry_in(direction == 0 ? strategy.direction.all : (direction < 0 ? strategy.direction.short : strategy.direction.long)) /////////////////////// STRATEGY INPUTS //////////////////////////////////////// title1=input(true, "-----------------Strategy Inputs-------------------") i_EMA=input(20, title="EMA Length") /////////////////////// BACKTESTER ///////////////////////////////////////////// title2=input(true, "-----------------General Inputs-------------------") // Backtester General Inputs i_SL=input(true, title="Use Swing Stop Loss and Take Profit") i_SPL=input(defval=10, title="Swing Point Loopback") i_PercIncrement=input(defval=.2, step=.1, title="Swing Point SL Perc Increment")*0.01 i_TPRRR = input(1.2, step=.1, title="Take Profit Risk Reward Ratio") // Bought and Sold Boolean Signal bought = strategy.position_size > strategy.position_size[1] or strategy.position_size < strategy.position_size[1] // Price Action Stop and Take Profit LL=(lowest(i_SPL))*(1-i_PercIncrement) HH=(highest(i_SPL))*(1+i_PercIncrement) LL_price = valuewhen(bought, LL, 0) HH_price = valuewhen(bought, HH, 0) entry_LL_price = strategy.position_size > 0 ? LL_price : na entry_HH_price = strategy.position_size < 0 ? HH_price : na tp=strategy.position_avg_price + (strategy.position_avg_price - entry_LL_price)*i_TPRRR stp=strategy.position_avg_price - (entry_HH_price - strategy.position_avg_price)*i_TPRRR /////////////////////// STRATEGY LOGIC ///////////////////////////////////////// EMA=ema(close, i_EMA) LowAboveEMA=low > EMA LowBelowEMA=low < EMA HighAboveEMA=high > EMA HighBelowEMA=high < EMA BullBounce=LowAboveEMA[1] and LowBelowEMA and close > EMA //and close > open BearBounce=HighBelowEMA[1] and HighAboveEMA and close < EMA //and close < open plot(EMA) BUY=BullBounce SELL=BearBounce //Inputs DPR=input(false, "Allow Direct Position Reverse") reverse=input(false, "Reverse Trades") // Entries if reverse if not DPR strategy.entry("long", strategy.long, when=SELL and strategy.position_size == 0) strategy.entry("short", strategy.short, when=BUY and strategy.position_size == 0) else strategy.entry("long", strategy.long, when=SELL) strategy.entry("short", strategy.short, when=BUY) else if not DPR strategy.entry("long", strategy.long, when=BUY and strategy.position_size == 0) strategy.entry("short", strategy.short, when=SELL and strategy.position_size == 0) else strategy.entry("long", strategy.long, when=BUY) strategy.entry("short", strategy.short, when=SELL) SL=entry_LL_price SSL=entry_HH_price TP=tp STP=stp strategy.exit("TP & SL", "long", limit=TP, stop=SL, when=i_SL) strategy.exit("TP & SL", "short", limit=STP, stop=SSL, when=i_SL) /////////////////////// PLOTS ////////////////////////////////////////////////// plot(strategy.position_size > 0 ? SL : na , title='SL', style=plot.style_cross, color=color.red) plot(strategy.position_size < 0 ? SSL : na , title='SSL', style=plot.style_cross, color=color.red) plot(strategy.position_size > 0 ? TP : na, title='TP', style=plot.style_cross, color=color.green) plot(strategy.position_size < 0 ? STP : na, title='STP', style=plot.style_cross, color=color.green) // Draw price action setup arrows plotshape(BUY ? 1 : na, style=shape.triangleup, location=location.belowbar, color=color.green, title="Bullish Setup", transp=80, size=size.auto) plotshape(SELL ? 1 : na, style=shape.triangledown, location=location.abovebar, color=color.red, title="Bearish Setup", transp=80, size=size.auto)
BTC Volatility Band Strategy
https://www.tradingview.com/script/LDCIPS8i-BTC-Volatility-Band-Strategy/
gary_trades
https://www.tradingview.com/u/gary_trades/
233
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/ // © gary_trades //This script is designed to be used on volatile securities/tickers so is best suited for day charts on Crypto (particularly good for BTC). //It takes both long and short trades and the main indicator settings can be changed by the use so they can test for ideal settings for ticker of interest. //@version=4 strategy("BTC Volatility Band Strategy", shorttitle="Vol Band Strategy", overlay=false, margin_long=100, margin_short=100) //VOLATILTY CandleChange = ((close - close[1])/close)*100 //OR CandleChange = ((close[2] - close[1])/close)*100 plot(CandleChange, color=color.red, linewidth = 1) //VOLATILITY BANDS MAlen = input(7, minval=3, maxval=30, title=" MA Length") MAout = sma(CandleChange, MAlen) plot(MAout, color=color.black, display=display.none) InnerBand = input(1.0, minval=0.5, maxval=5, title="Inner Band") OuterBand = input(2.00, minval=0.5, maxval=10, title="Outer Band") devInner = InnerBand * stdev(CandleChange, MAlen) devOuter = OuterBand * stdev(CandleChange, MAlen) upper1 = MAout + devInner lower1 = MAout - devInner b1 = plot(upper1, "Upper Inner", color=color.gray) b2 = plot(lower1, "Lower Inner", color=color.gray) upper2 = MAout + devOuter lower2 = MAout - devOuter b3 = plot(upper2, "Upper Outer", color=color.gray) b4 = plot(lower2, "Lower Outer", color=color.gray) fill(b1, b3, color.rgb(250,145,175,70), title="Background") fill(b2, b4, color.rgb(250,145,175,70), title="Background") band1 = hline(25, "Upper Band", color=color.gray, linestyle=hline.style_dotted, linewidth=2) band0 = hline(-25, "Lower Band", color=color.gray, linestyle=hline.style_dotted, linewidth=2) //LONG FILTER VolFilterL = CandleChange <= lower1 and CandleChange > lower2 SMAFilterL = close[1] > sma(close[1], 50) PriceFilterL = close > lowest(close,7) LongFilter = VolFilterL and SMAFilterL and PriceFilterL bgcolor(LongFilter ? color.new(color.green, 80) : na) //SHORT FILTER VolFilterS = CandleChange >= upper1 and CandleChange < upper2 SMAFilterS = close[1] < sma(close[1], 50) PriceFilterS = close < highest(close,7) ShortFilter = VolFilterS and SMAFilterS and PriceFilterS bgcolor(ShortFilter ? color.new(color.red, 80) : na) //SETTING BACK TEST INPUTS fromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31) fromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12) fromYear = input(defval = 2000, title = "From Year", minval = 1970) toDay = input(defval = 1, title = "To Day", minval = 1, maxval = 31) toMonth = input(defval = 1, title = "To Month", minval = 1, maxval = 12) toYear = input(defval = 2100, title = "To Year", minval = 1970) startDate = timestamp("America/New_York", fromYear, fromMonth, fromDay, 00, 00) finishDate = timestamp("America/New_York", toYear, toMonth, toDay, 00, 00) time_condition = time >= startDate and time <= finishDate //ORDER DETAILS Risk = (high[7] - low[7])/ 7 Profit = Risk*1.15 Loss = Risk*0.65 AlertMSG = "New stategy position" + tostring(strategy.position_size) if (time_condition) strategy.entry("Long", strategy.long, when = LongFilter, alert_message=AlertMSG) if (LongFilter) LongStop = strategy.position_avg_price - Loss LongProfit = strategy.position_avg_price + Profit strategy.exit("TP/SL", "Long", stop=LongStop, limit=LongProfit) if (time_condition) strategy.entry("Short", strategy.short, when = ShortFilter, alert_message=AlertMSG) if (ShortFilter) ShortStop = strategy.position_avg_price + Loss ShortProfit = strategy.position_avg_price - Profit strategy.exit("TP/SL", "Short", stop=ShortStop, limit=ShortProfit)
Simple Moon Phases Strategy
https://www.tradingview.com/script/luiQYWOM-Simple-Moon-Phases-Strategy/
Dustin_D_RLT
https://www.tradingview.com/u/Dustin_D_RLT/
401
strategy
4
MPL-2.0
//This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ //@version=4 //Author: Dustin Drummond https://www.tradingview.com/u/Dustin_D_RLT/ //Simple Moon Phases Strategy //This strategy is very basic and needs some filters to improve results. //It was created to test the Moon Phase theory compared to just a buy and hold strategy and it did not beat the buy and hold. //However, if you flip the entry and exit signals to the opposite signals it performs a lot worse, so there might be some validity to the Moon Phases having an effect on the markets. //I might try to add some filters and increase hold times with trailing stops in a separate version. //This strategy uses hard-coded dates from 1/1/2015 until 12/31/2021 only! //Any dates outside of that range need to be added manually in the code or it will not work. //I may or may not update this so please don't be upset if it stops working after 12/31/2021. //Feel free to use any part of this code and please let me know if you can improve on this strategy. strategy(title="Simple Moon Phases Strategy", shorttitle = "Moon Phases", overlay = true, calc_on_every_tick=true, default_qty_value=100, initial_capital = 100000, default_qty_type=strategy.percent_of_equity, pyramiding = 0, process_orders_on_close=false) //Define Full Moons and New Moons per year (idetifies 1 day prior so order entry can be on open of next day) fullMoon2015 = year == 2015 and ((month == 1 and dayofmonth == 2) or (month == 2 and dayofmonth == 3) or (month == 3 and dayofmonth == 5) or (month == 4 and dayofmonth == 2) or (month == 5 and dayofmonth == 1) or (month == 6 and dayofmonth == 2) or (month == 7 and dayofmonth == 1) or (month == 7 and dayofmonth == 30) or (month == 8 and dayofmonth == 28) or (month == 9 and dayofmonth == 25) or (month == 10 and dayofmonth == 26) or (month == 11 and dayofmonth == 25) or (month == 12 and dayofmonth == 24)) ? 1 : na newMoon2015 = year == 2015 and ((month == 1 and dayofmonth == 16) or (month == 2 and dayofmonth == 18) or (month == 3 and dayofmonth == 19) or (month == 4 and dayofmonth == 17) or (month == 5 and dayofmonth == 15) or (month == 6 and dayofmonth == 16) or (month == 7 and dayofmonth == 15) or (month == 8 and dayofmonth == 14) or (month == 9 and dayofmonth == 11) or (month == 10 and dayofmonth == 12) or (month == 11 and dayofmonth == 11) or (month == 12 and dayofmonth == 10)) ? 1 : na fullMoon2016 = year == 2016 and ((month == 1 and dayofmonth == 22) or (month == 2 and dayofmonth == 22) or (month == 3 and dayofmonth == 22) or (month == 4 and dayofmonth == 21) or (month == 5 and dayofmonth == 20) or (month == 6 and dayofmonth == 17) or (month == 7 and dayofmonth == 19) or (month == 8 and dayofmonth == 17) or (month == 9 and dayofmonth == 16) or (month == 10 and dayofmonth == 14) or (month == 11 and dayofmonth == 11) or (month == 12 and dayofmonth == 13)) ? 1 : na newMoon2016 = year == 2016 and ((month == 1 and dayofmonth == 8) or (month == 2 and dayofmonth == 8) or (month == 3 and dayofmonth == 8) or (month == 4 and dayofmonth == 6) or (month == 5 and dayofmonth == 6) or (month == 6 and dayofmonth == 3) or (month == 7 and dayofmonth == 1) or (month == 8 and dayofmonth == 2) or (month == 8 and dayofmonth == 31) or (month == 9 and dayofmonth == 30) or (month == 10 and dayofmonth == 28) or (month == 11 and dayofmonth == 28) or (month == 12 and dayofmonth == 28)) ? 1 : na fullMoon2017 = year == 2017 and ((month == 1 and dayofmonth == 11) or (month == 2 and dayofmonth == 10) or (month == 3 and dayofmonth == 10) or (month == 4 and dayofmonth == 10) or (month == 5 and dayofmonth == 10) or (month == 6 and dayofmonth == 8) or (month == 7 and dayofmonth == 7) or (month == 8 and dayofmonth == 7) or (month == 9 and dayofmonth == 5) or (month == 10 and dayofmonth == 5) or (month == 11 and dayofmonth == 3) or (month == 12 and dayofmonth == 1) or (month == 12 and dayofmonth == 29)) ? 1 : na newMoon2017 = year == 2017 and ((month == 1 and dayofmonth == 27) or (month == 2 and dayofmonth == 24) or (month == 3 and dayofmonth == 27) or (month == 4 and dayofmonth == 25) or (month == 5 and dayofmonth == 25) or (month == 6 and dayofmonth == 23) or (month == 7 and dayofmonth == 21) or (month == 8 and dayofmonth == 21) or (month == 9 and dayofmonth == 19) or (month == 10 and dayofmonth == 19) or (month == 11 and dayofmonth == 17) or (month == 12 and dayofmonth == 15)) ? 1 : na fullMoon2018 = year == 2018 and ((month == 1 and dayofmonth == 30) or (month == 3 and dayofmonth == 1) or (month == 3 and dayofmonth == 29) or (month == 4 and dayofmonth == 27) or (month == 5 and dayofmonth == 29) or (month == 6 and dayofmonth == 27) or (month == 7 and dayofmonth == 27) or (month == 8 and dayofmonth == 24) or (month == 9 and dayofmonth == 24) or (month == 10 and dayofmonth == 24) or (month == 11 and dayofmonth == 21) or (month == 12 and dayofmonth == 21)) ? 1 : na newMoon2018 = year == 2018 and ((month == 1 and dayofmonth == 16) or (month == 2 and dayofmonth == 15) or (month == 3 and dayofmonth == 16) or (month == 4 and dayofmonth == 13) or (month == 5 and dayofmonth == 14) or (month == 6 and dayofmonth == 13) or (month == 7 and dayofmonth == 12) or (month == 8 and dayofmonth == 10) or (month == 9 and dayofmonth == 7) or (month == 10 and dayofmonth == 8) or (month == 11 and dayofmonth == 7) or (month == 12 and dayofmonth == 6)) ? 1 : na fullMoon2019 = year == 2019 and ((month == 1 and dayofmonth == 18) or (month == 2 and dayofmonth == 19) or (month == 3 and dayofmonth == 20) or (month == 4 and dayofmonth == 18) or (month == 5 and dayofmonth == 17) or (month == 6 and dayofmonth == 14) or (month == 7 and dayofmonth == 16) or (month == 8 and dayofmonth == 14) or (month == 9 and dayofmonth == 13) or (month == 10 and dayofmonth == 11) or (month == 11 and dayofmonth == 11) or (month == 12 and dayofmonth == 11)) ? 1 : na newMoon2019 = year == 2019 and ((month == 1 and dayofmonth == 4) or (month == 2 and dayofmonth == 4) or (month == 3 and dayofmonth == 6) or (month == 4 and dayofmonth == 4) or (month == 5 and dayofmonth == 3) or (month == 5 and dayofmonth == 31) or (month == 7 and dayofmonth == 2) or (month == 7 and dayofmonth == 31) or (month == 8 and dayofmonth == 29) or (month == 9 and dayofmonth == 27) or (month == 10 and dayofmonth == 25) or (month == 11 and dayofmonth == 26) or (month == 12 and dayofmonth == 24)) ? 1 : na fullMoon2020 = year == 2020 and ((month == 1 and dayofmonth == 10) or (month == 2 and dayofmonth == 7) or (month == 3 and dayofmonth == 9) or (month == 4 and dayofmonth == 7) or (month == 5 and dayofmonth == 6) or (month == 6 and dayofmonth == 5) or (month == 7 and dayofmonth == 2) or (month == 8 and dayofmonth == 3) or (month == 9 and dayofmonth == 1) or (month == 10 and dayofmonth == 1) or (month == 10 and dayofmonth == 30) or (month == 11 and dayofmonth == 27) or (month == 12 and dayofmonth == 29)) ? 1 : na newMoon2020 = year == 2020 and ((month == 1 and dayofmonth == 24) or (month == 2 and dayofmonth == 21) or (month == 3 and dayofmonth == 23) or (month == 4 and dayofmonth == 22) or (month == 5 and dayofmonth == 22) or (month == 6 and dayofmonth == 19) or (month == 7 and dayofmonth == 20) or (month == 8 and dayofmonth == 18) or (month == 9 and dayofmonth == 16) or (month == 10 and dayofmonth == 16) or (month == 11 and dayofmonth == 13) or (month == 12 and dayofmonth == 14)) ? 1 : na fullMoon2021 = year == 2021 and ((month == 1 and dayofmonth == 28) or (month == 2 and dayofmonth == 26) or (month == 3 and dayofmonth == 26) or (month == 4 and dayofmonth == 26) or (month == 5 and dayofmonth == 25) or (month == 6 and dayofmonth == 24) or (month == 7 and dayofmonth == 23) or (month == 8 and dayofmonth == 20) or (month == 9 and dayofmonth == 20) or (month == 10 and dayofmonth == 20) or (month == 11 and dayofmonth == 18) or (month == 12 and dayofmonth == 17)) ? 1 : na newMoon2021 = year == 2021 and ((month == 1 and dayofmonth == 12) or (month == 2 and dayofmonth == 11) or (month == 3 and dayofmonth == 12) or (month == 4 and dayofmonth == 9) or (month == 5 and dayofmonth == 11) or (month == 6 and dayofmonth == 9) or (month == 7 and dayofmonth == 9) or (month == 8 and dayofmonth == 6) or (month == 9 and dayofmonth == 6) or (month == 10 and dayofmonth == 5) or (month == 11 and dayofmonth == 4) or (month == 12 and dayofmonth == 3)) ? 1 : na //All Full and New Moons fullMoon = fullMoon2015 or fullMoon2016 or fullMoon2017 or fullMoon2018 or fullMoon2019 or fullMoon2020 or fullMoon2021 newMoon = newMoon2015 or newMoon2016 or newMoon2017 or newMoon2018 or newMoon2019 or newMoon2020 or newMoon2021 //Plot Full and New Moons (offset 1 bar to make up for 1 day prior calculation) plotshape(fullMoon, "Full Moon", shape.circle, location.belowbar, color.new(color.gray, 20), offset=1, size=size.normal) plotshape(newMoon, "New Moon", shape.circle, location.abovebar, color.new(color.white, 20), offset=1, size=size.normal) //Define Entry and Exit Signals entrySignal = (strategy.position_size <= 0 and fullMoon) exitSignal = (strategy.position_size >= 0 and newMoon) //Entry Order strategy.order("Full Moon Entry", long = true, when = (strategy.position_size <= 0 and entrySignal)) //Exit Order strategy.close_all(when = exitSignal, comment = "New Moon Exit") //Background fill backgroundColour = (strategy.position_size > 0) ? color.green : color.red bgcolor(color=backgroundColour, transp=85)
Ichimoku Long and Short Strategy
https://www.tradingview.com/script/7G3ds7ih/
M3RZI
https://www.tradingview.com/u/M3RZI/
206
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/ // © M3RZI //@version=4 strategy("Ichimoku Strategy", overlay = true) //ICHIMOKU------- conversionPeriods = input(9, minval=1, title="Conversion Line Length", group = "Ichimoku Settings") basePeriods = input(26, minval=1, title="Base Line Length", group = "Ichimoku Settings") laggingSpan2Periods = input(52, minval=1, title="Lagging Span 2 Length", group = "Ichimoku Settings") displacement = input(26, minval=1, title="Displacement", group = "Ichimoku Settings") entryStrategy = input(title = "Entry Strategy", defval = "Ichimoku", options = ["Ichimoku"], type = input.string, group = "Entry Strategy") exitStrategy = input(title = "Exit Strategy", defval = "Ichimoku", options = ["Ichimoku","ATR Pullback"], type = input.string, group = "Position Exit Settings") exitATRLength = input(14, title = "ATR Length", minval = 1 ,type = input.integer, group = "Position Exit Settings") exitATRMult = input(2, title = "ATR Multiplier", minval = 0.1 , step = 0.1 ,type = input.float, group = "Position Exit Settings") riskReward = input(2, title = "Risk Reward Ratio", minval = 0.1 , step = 0.1 ,type = input.float, group = "Position Exit Settings") closeLagBelow = input(true, title = "Close long position if lagging span crosses below the price", type = input.bool, group = "Position Exit Settings") closelagAbove = input(true, title = "Close short position if lagging span crosses above the price", type = input.bool, group = "Position Exit Settings") showDash = input(true, title = "Show Dashboard", type = input.bool, group = "Dashboard Options") colorDash = input(color.new(#696969, 80), title = "Background Color", type = input.color, inline = "Dash Colors", group = "Dashboard Options") colorTextDash = input(color.new(#FFFFFF,0), title = "Text Color", type = input.color, inline = "Dash Colors", group = "Dashboard Options") distance = input(30, title = "Bars Distance (to rigth)", minval = 1 ,type = input.integer, group = "Dashboard Options") showSignals = input(true, title = "Show Signals (long/short)", type = input.bool, group = "Extra Options") showTargets = input(true, title = "Show Targets (Profit/Loss)", type = input.bool, group = "Extra Options") donchian(len) => avg(lowest(len), highest(len)) conversionLine = donchian(conversionPeriods) baseLine = donchian(basePeriods) leadLine1 = avg(conversionLine, baseLine) leadLine2 = donchian(laggingSpan2Periods) //--------------------- var long = false var short = false var signalLong = false var signalShort = false //LONG conAbvBase = conversionLine > baseLine cloudGreen = leadLine1 > leadLine2 closeAbvCloud = open > leadLine1[displacement] and open > leadLine2[displacement] lagSpanAbvCloud = close > leadLine1[displacement*2] and close > leadLine2[displacement*2] conditionLong = not long and conAbvBase and cloudGreen and closeAbvCloud and lagSpanAbvCloud //SHORT conBlwBase = conversionLine < baseLine cloudRed = leadLine2 > leadLine1 closeBlwCloud = open < leadLine1[displacement] and open < leadLine2[displacement] lagSpanBlwCloud = close < leadLine1[displacement*2] and close < leadLine2[displacement*2] conditionShort = not short and conBlwBase and cloudRed and closeBlwCloud and lagSpanBlwCloud var drawing = false var waitingLong = false var waitingShort = false var profit = 0.0 var current = 0.0 var loss = 0.0 var pullPrice = 0.0 atrExit = atr(exitATRLength) if conditionLong long := true short := false signalLong := true signalShort := false drawing := true if exitStrategy == "Ichimoku" loss := leadLine2[displacement] < leadLine1[displacement] ? leadLine2[displacement] : leadLine1[displacement] profit := open + ((open - loss) * riskReward) current := open else loss := open - atrExit * exitATRMult current := open profit := open + (open - loss) * riskReward strategy.entry("Long", strategy.long, 10 ,alert_message = "Long Position Open") strategy.exit("Long exit", "Long", limit = profit, stop = loss, alert_message = "Long Position Close") if conditionShort short := true long := false signalShort := true signalLong := false drawing := true if exitStrategy == "Ichimoku" loss := leadLine2[displacement] > leadLine1[displacement] ? leadLine2[displacement] : leadLine1[displacement] profit := open - ((loss - open) * riskReward) current := open else loss := open + atrExit * exitATRMult current := open profit := open - (loss - open) * riskReward strategy.entry("Short", strategy.short, 10 , alert_message = "Short Position Open") strategy.exit("Short exit","Short", limit = profit, stop = loss, alert_message = "Short Position Close") if long if closeLagBelow and open < close[displacement + 1] drawing := false signalLong := false strategy.close("Long", alert_message = "Long Closed by Lagging Span Crossing Below Price") else if high[1] >= profit or low[1] <= loss drawing := false signalLong := false strategy.close("Long", alert_message = "Long Closed") if short if closelagAbove and open > close[displacement + 1] drawing := false signalShort := false strategy.close("Short", alert_message = "Short Closed by Lagging Span Crossing Above Price") else if low[1] <= profit or high[1] >= loss drawing := false signalShort := false strategy.close("Short", alert_message = "Short Closed") decision(condition) => var text = "" if condition text := "🟢" else text := "🔴" position = time+((time-time[1])*distance) PandL = signalLong ? ((open-current)/current)*100 : signalShort ? (((open-current)/current)*100)*-1 : 0.0 if showDash label dashBoard = label.new(position,open, text = "-----------Long conditions-----------" +"\n\n"+decision(signalLong)+" Long position is open" +"\n\n"+decision(conAbvBase)+" Conversion line above base line" +"\n\n"+decision(cloudGreen)+" Cloud is green" +"\n\n"+decision(closeAbvCloud)+" Price closed above cloud" +"\n\n"+decision(lagSpanAbvCloud)+" Lagging span above cloud" +"\n\n-----------Short conditions-----------" +"\n\n"+decision(signalShort)+" Short position is open" +"\n\n"+decision(conBlwBase)+" Conversion line below base line" +"\n\n"+decision(cloudRed)+" Cloud is red" +"\n\n"+decision(closeBlwCloud)+" Price closed below cloud" +"\n\n"+decision(lagSpanBlwCloud)+" Lagging span below cloud" +"\n\n---------------Extra---------------" +"\n\nUnrealized P&L(%): "+tostring(PandL), xloc = xloc.bar_time, textalign = text.align_left, style = label.style_label_left, color = colorDash, textcolor = colorTextDash) label.delete(dashBoard[1]) //DRAWING plotshape(showSignals ? conditionLong : na, title = "Long Signal", location=location.belowbar,style=shape.labelup,color=color.green,textcolor=color.white,size=size.small,text="Long") plotshape(showSignals ? conditionShort : na, title = "Short Signal", location=location.abovebar,style=shape.labeldown,color=color.red,textcolor=color.white,size=size.small,text="Short") profitLine = plot(showTargets ? drawing ? profit : na : na, title = "Take profit", color = color.green, style = plot.style_linebr) currentLine =plot(showTargets ? drawing ? current : na : na, title = "Middle Line", color = color.white, style = plot.style_linebr) lossLine = plot(showTargets ? drawing ? loss : na : na, title = "Stop Loss", color = color.red, style = plot.style_linebr) fill(currentLine,profitLine, title = "Profit Background" ,color = color.new(color.green,75)) fill(currentLine,lossLine, title = "Loss Background" ,color = color.new(color.red,75)) plot(conversionLine, color = #0496ff, title = "Conversion Line") plot(baseLine, color = color.yellow, title = "Base Line") plot(close, offset = -displacement + 1, color = color.purple, title = "Lagging Span") p1 = plot(leadLine1, offset = displacement - 1, color=color.green, title="Lead 1") p2 = plot(leadLine2, offset = displacement - 1, color=color.red, title="Lead 2") fill(p1, p2, title = "Lead 1 and 2 Background" ,color = leadLine1 > leadLine2 ? color.green : color.red) //------NOTE FOR ALERTS //IF YOU WANT TO RECIVE A ALERT JUST FOLLOW THE NEXT STEPS: //1.-GO TO ALERTS AND CLICK IN "CREATE NEW ALERT" //2.-IN CONDITION CHOOSE THE "ICHIMOKU STRATEGY" //3.-GIVE THE ALERT A NAME //4.-IN MESSAGE YOU ARE GOING TO WRITE "{{strategy.order.alert_message}}", WITH THIS WHEN A SHORT OR LONG SIGNAL APPEAR WILL SHOW THE "alert_message" IN THE ALERT. //THE alert_message IS DEFINED IN THE "strategy.entry" and "strategy.exit" //------NOTE IF YOU WANT TO USE A BOT WITH THIS STRATEGY //THIS IS A STRATEGY SO YOU ONLY CAN RECIVE ALERTS FROM THE "strategy.entry" AND "strategy.exit" BUT THIS ARE ONLY IN ONE ALERT //SO IF YOU WANT TO USE A BOTH WITH THE STRATEGY FOLLOW THE NEXT STEPS: //1.-ALREADY HAVE A BOT CREATED //2.-LOCATE YOUR WEBHOOK AND COMMANDS FOR THE BOT //3.-IN THE "alert_message" OF THE "strategy.entry (LINE 95)" YOU WILL PASTE THE COMMAND OF YOUR BOT FOR ENTER A LONG AND IN THE "strategy.exit (LINE 96)" THAT ARE BELOW IN THE "alert_message" PASTE THE COMMAND THAT IS FOR CLOSE THE LONG POSITION //4.-YOU WILL DO THE SAME FOR THE "strategy.entry (LINE 109)" AND THE "strategy.exit (LINE 110)" BUT THIS TIME WITH THE COMMAND OF OPEN A SHORT AND CLOSE A SHORT //5.-AFTER THE PREVIOUS STEPS GO TO ALERTS AND CLICK IN "CREATE NEW ALERT" //6.-IN CONDITION CHOOSE THE "ICHIMOKU STRATEGY" //7.-SELECT "URL from webhook" //8.-GIVE THE ALERT A NAME //9.-IN MESSAGE WRITE "{{strategy.order.alert_message}}" //10.-NOW WITH ALL THIS EACH TIME A SIGNAL APPEAR IN THE STRATEGY THIS WILL SEND THE COMMAND TO YOUR BOT TO OPEN OR CLOSE A LONG OR SHORT ////------ANOTHER IMPORTANT NOTE FOR PEOPLE THAT WANT TO USE A BOT //I NOW THAT I'M SO BAD EXPLAINING THINGS SO WATCH THE FOLLOWING VIDEO THAT EXPLAINS BETTER THAN ME, ITS FROM THE CHANNEL "The Art of Trading" //AND ALSO U CAN CHECK HIS TRADINGVIEW ACCOUNT, HE CREATE AN AMAZING SCRIPT FOR THE COMMUNITY AND CHECK HIS CHANNEL TO LEARN PINE SCRIPT //https://www.youtube.com/watch?v=-d_rFRd3o-0 //https://es.tradingview.com/u/ZenAndTheArtOfTrading/#published-charts
[KL] Relative Volume Strategy
https://www.tradingview.com/script/HNmT0VUi-KL-Relative-Volume-Strategy/
DojiEmoji
https://www.tradingview.com/u/DojiEmoji/
238
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © DojiEmoji (kevinhhl) //@version=4 strategy("[KL] Relative Volume Strategy",overlay=true,pyramiding=1) ENUM_LONG = "Long" // Timeframe { backtest_timeframe_start = input(defval = timestamp("01 Apr 2016 13:30 +0000"), title = "Backtest Start Time", type = input.time) USE_ENDTIME = input(false,title="Define backtest end-time (If false, will test up to most recent candle)") backtest_timeframe_end = input(defval = timestamp("01 May 2021 19:30 +0000"), title = "Backtest End Time (if checked above)", type = input.time) within_timeframe = time >= backtest_timeframe_start and (time <= backtest_timeframe_end or not USE_ENDTIME) // } // Volatility Indicators { BOLL_length = 20, BOLL_src = close, SMA20 = sma(BOLL_src, BOLL_length), BOLL_sDEV_x2 = 2 * stdev(BOLL_src, BOLL_length) BOLL_upper = SMA20 + BOLL_sDEV_x2, BOLL_lower = SMA20 - BOLL_sDEV_x2 plot(SMA20, "Basis", color=#872323, offset = 0) BOLL_p1 = plot(BOLL_upper, "BOLL Upper", color=color.new(color.navy,50), offset = 0) BOLL_p2 = plot(BOLL_lower, "BOLL Lower", color=color.new(color.navy,50), offset = 0) fill(BOLL_p1, BOLL_p2, title = "Background", color=color.new(#198787,90)) ATR_X2_volat = atr(input(10,title="Length of ATR to determine volality"))*2 plot(SMA20+ATR_X2_volat, "SMA20 + ATR_X2_volat", color=color.new(color.gray,75), offset = 0) plot(SMA20-ATR_X2_volat, "SMA20 - ATR_X2_volat", color=color.new(color.gray,75), offset = 0) plotchar(ATR_X2_volat, "ATR_X2_volat", "", location = location.bottom) // } // Trailing stop loss { ATR_X2_TSL = atr(input(10,title="Length of ATR for trailing stop loss")) * input(2.0,title="ATR Multiplier for trailing stop loss",type=input.float) TSL_source = low var stop_loss_price = float(0) TSL_line_color = color.green, TSL_transp = 100 if strategy.position_size == 0 or not within_timeframe TSL_line_color := color.black stop_loss_price := TSL_source - ATR_X2_TSL else if strategy.position_size > 0 stop_loss_price := max(stop_loss_price, TSL_source - ATR_X2_TSL) TSL_transp := 0 plot(stop_loss_price, color=color.new(TSL_line_color, TSL_transp)) // } // Signals for entry { _avg_vol = sma(volume,input(5, title="SMA(volume) length (for relative comparison)")) _relative_vol = _avg_vol * input(1,title="Multiple of avg vol to consider relative volume as being high",type=input.float) __lowerOfOpenClose = min(open,close) _wickRatio_lower = (__lowerOfOpenClose - low) / (high - low) entry_signal1 = volume > _relative_vol entry_signal2 = ATR_X2_volat > BOLL_sDEV_x2 entry_signal3 = _wickRatio_lower > input(0.1,title="Wick ratio (lower:high-low) of entry bar",type=input.float) // } // MAIN: if within_timeframe // ENTRY ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: if entry_signal1 and entry_signal2 and entry_signal3 entry_msg = strategy.position_size > 0 ? "adding" : "initial" strategy.entry(ENUM_LONG, strategy.long, comment=entry_msg) // EXIT :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: exit_msg = close <= strategy.position_avg_price ? "stop loss" : "take profit" if strategy.position_size > 0 exit_condition = TSL_source <= stop_loss_price strategy.close(ENUM_LONG, when=exit_condition, comment=exit_msg) // CLEAN UP: if strategy.position_size == 0 stop_loss_price := float(0)
RSI Cross [xaurr]
https://www.tradingview.com/script/K3W7tQjO-RSI-Cross-xaurr/
livetrend
https://www.tradingview.com/u/livetrend/
252
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/ // © xaurr //@version=4 strategy("RSI Cross [xaurr]", shorttitle="RSIC",overlay=false) src = input(title="Source", type=input.source, defval=close) //RSI Strategy period = input(5,"RSI Period", minval=1) overSold = input(30,"RSI Oversold", minval=1) overBought = input(70, "RSI Overbought", minval=1) fastPeriod = input(20,"Smooth Fast Period") slowPeriod = input(50,"Smooth Slow Period") rsi = rsi(src, period) fast = ema(rsi,fastPeriod) slow = ema(rsi,slowPeriod) long = crossover(fast,slow) short = crossunder(fast,slow) pos = 0 pos:= long ?1:short ?-1 : nz(pos[1]) plot(overSold,"RSI Oversold",color=color.green) plot(overBought, "RSI Overbought",color=color.red) plot(rsi, linewidth = 1, color = color.blue, title="RSI Line") plot(fast, linewidth = 2, color = color.green, title="RSI Fast Line") plot(slow, linewidth = 2, color = color.red, title="RSI Slow Line") bgcolor(pos == 1 ? color.green : pos == -1 ? color.red : na) if pos == 1 strategy.entry("long",strategy.long) if pos == -1 strategy.entry("short",strategy.short)
Moving Stop-Loss mechanism + alerts to MT4/MT5
https://www.tradingview.com/script/GRTIMXzJ-Moving-Stop-Loss-mechanism-alerts-to-MT4-MT5/
Peter_O
https://www.tradingview.com/u/Peter_O/
615
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © Peter_O //@version=5 strategy(title='Moving Stop-Loss mechanism', commission_type=strategy.commission.cash_per_order, commission_value=0.00003, overlay=true, default_qty_value=100000, initial_capital=1000) // This script was created for educational purposes only and it is a spin-off of my previous script: // https://www.tradingview.com/script/9MJO3AgE-TradingView-Alerts-to-MT4-MT5-dynamic-variables-NON-REPAINTING/ // This spin-off adds very often requested Moving Stop-Loss Mechanism - the logic here moves the stop-loss each time // a new pivot is detected. // // Last lines of the script include alert() function calls, with a syntax compatible with TradingConnector // for execution in Forex/indices/commodities/crypto markets via MetaTrader. // Please note that "tradeid=" variable must be passed with each alert, so that MetaTrader knows which // trade to modify. TakeProfitLevel = input(400) // **** Entries logic, based on Stoch **** { periodK = 13 //input(13, title="K", minval=1) periodD = 3 //input(3, title="D", minval=1) smoothK = 4 //input(4, title="Smooth", minval=1) k = ta.sma(ta.stoch(close, high, low, periodK), smoothK) d = ta.sma(k, periodD) GoLong = ta.crossover(k, d) and k < 80 GoShort = ta.crossunder(k, d) and k > 20 // } End of entries logic // **** Pivot-points and stop-loss logic **** { piv_high = ta.pivothigh(high, 1, 1) piv_low = ta.pivotlow(low, 1, 1) var float stoploss_long = low var float stoploss_short = high pl = ta.valuewhen(piv_low, piv_low, 0) ph = ta.valuewhen(piv_high, piv_high, 0) if GoLong stoploss_long := low < pl ? low : pl stoploss_long if GoShort stoploss_short := high > ph ? high : ph stoploss_short plot(stoploss_long, color=color.new(color.red, 0), title='stoploss_long') plot(stoploss_short, color=color.new(color.lime, 0), title='stoploss_short') // Stop-Loss Updating mechanism enable_stoploss_mechanism = input(true, title='Enable Stoploss Modification Mechanism') UpdateLongStopLoss = strategy.position_size > 0 and strategy.position_size[1] > 0 and piv_low and pl != stoploss_long and not GoLong and enable_stoploss_mechanism UpdateShortStopLoss = strategy.position_size < 0 and strategy.position_size[1] < 0 and piv_high and ph != stoploss_short and not GoShort and enable_stoploss_mechanism if UpdateLongStopLoss stoploss_long := pl stoploss_long if UpdateShortStopLoss stoploss_short := ph stoploss_short plotshape(UpdateLongStopLoss ? stoploss_long[1] - 300 * syminfo.mintick : na, location=location.absolute, style=shape.labelup, color=color.new(color.lime, 0), textcolor=color.new(color.white, 0), text='SL\nmove') plotshape(UpdateShortStopLoss ? stoploss_short[1] + 300 * syminfo.mintick : na, location=location.absolute, style=shape.labeldown, color=color.new(color.red, 0), textcolor=color.new(color.black, 0), text='SL\nmove') // } End of Pivot-points and stop-loss logic strategy.entry('Long', strategy.long, when=GoLong) strategy.exit('XLong', from_entry='Long', stop=stoploss_long, profit=TakeProfitLevel) strategy.entry('Short', strategy.short, when=GoShort) strategy.exit('XShort', from_entry='Short', stop=stoploss_short, profit=TakeProfitLevel) if GoLong alertsyntax_golong = 'long slprice=' + str.tostring(stoploss_long) + ' tp=' + str.tostring(TakeProfitLevel) alert(message=alertsyntax_golong, freq=alert.freq_once_per_bar_close) if GoShort alertsyntax_goshort = 'short slprice=' + str.tostring(stoploss_short) + ' tp=' + str.tostring(TakeProfitLevel) alert(message=alertsyntax_goshort, freq=alert.freq_once_per_bar_close) if UpdateLongStopLoss alertsyntax_updatelongstoploss = 'slmod slprice=' + str.tostring(stoploss_long) alert(message=alertsyntax_updatelongstoploss, freq=alert.freq_once_per_bar_close) if UpdateShortStopLoss alertsyntax_updateshortstoploss = 'slmod slprice=' + str.tostring(stoploss_short) alert(message=alertsyntax_updateshortstoploss, freq=alert.freq_once_per_bar_close)
DEMA/EMA & VOLATILITY (VAMS)
https://www.tradingview.com/script/tnaqOPQa-DEMA-EMA-VOLATILITY-VAMS/
Qorbanjf
https://www.tradingview.com/u/Qorbanjf/
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/ // © Qorbanjf //@version=4 strategy("ORIGIN DEMA/EMA & VOL LONG ONLY", shorttitle="ORIGIN DEMA/EMA & VOL LONG", overlay=true, initial_capital=10000, default_qty_value=10000) // DEMA length = input(10, minval=1, title="DEMA LENGTH") src = input(close, title="Source") e1 = ema(src, length) e2 = ema(e1, length) dema1 = 2 * e1 - e2 plot(dema1, "DEMA", color=color.yellow) //EMA len = input(25, minval=1, title="EMA Length") srb = input(close, title="Source") offset = input(title="Offset", type=input.integer, defval=0, minval=-500, maxval=500) ema1 = ema(srb, len) plot(ema1, title="EMA", color=color.blue, offset=offset) // Inputs atrTimeFrame = input("D", title="ATR Timeframe", type=input.resolution) atrLookback = input(defval=14,title="ATR Lookback Period",type=input.integer) useMA = input(title = "Show Moving Average?", type = input.bool, defval = true) maType = input(defval="EMA", options=["EMA", "SMA"], title = "Moving Average Type") maLength = input(defval = 20, title = "Moving Average Period", minval = 1) //longLossPerc = input(title="Long Stop Loss (%)", // type=input.float, minval=0.0, step=0.1, defval=1) * 0.01 longTrailPerc = input(title="Trail stop loss (%)", type=input.float, minval=0.0, step=0.1, defval=50) * 0.01 longProfitPerc = input(title="Long Take Profit (%)", type=input.float, minval=0.0, step=0.1, defval=3000) / 100 // === INPUT BACKTEST RANGE === FromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12) FromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31) FromYear = input(defval = 2017, title = "From Year", minval = 2000) ToMonth = input(defval = 1, title = "To Month", minval = 1, maxval = 12) ToDay = input(defval = 1, title = "To Day", minval = 1, maxval = 31) ToYear = input(defval = 9999, title = "To Year", minval = 2017) // ATR Logic // atrValue = atr(atrLookback) // atrp = (atrValue/close)*100 // plot(atrp, color=color.white, linewidth=2, transp = 30) atrValue = security(syminfo.tickerid, atrTimeFrame, atr(atrLookback)) atrp = (atrValue/close)*100 // Moving Average Logic ma(maType, src, length) => maType == "EMA" ? ema(src, length) : sma(src, length) //Ternary Operator (if maType equals EMA, then do ema calc, else do sma calc) maFilter = security(syminfo.tickerid, atrTimeFrame, ma(maType, atrp, maLength)) // variables for enter position enterLong = crossover(dema1, ema1) and atrp < maFilter // variables for exit position sale = crossunder(dema1, ema1) // stop loss //longStopPrice = strategy.position_avg_price * (1 - longLossPerc) // trail stop // Determine trail stop loss prices longStopTrail = 0.0 longStopTrail := if (strategy.position_size > 0) stopValue = close * (1 - longTrailPerc) max(stopValue, longStopTrail[1]) else 0 //Take profit Percentage longExitPrice = strategy.position_avg_price * (1 + longProfitPerc) //Enter trades when conditions are met strategy.entry(id="long", long=strategy.long, when=enterLong, comment="long") // strategy.close("long", when = sale, comment = "Sell") //place exit orders (only executed after trades are active) strategy.exit(id="sell", limit = longExitPrice, stop = longStopTrail, comment = "SL/TP")
CCI & EMA strategy by Tradeswithashish
https://www.tradingview.com/script/SdhTE8Ao-CCI-EMA-strategy-by-Tradeswithashish/
iitiantradingsage
https://www.tradingview.com/u/iitiantradingsage/
442
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ //This strategy is excellent in timeperiod above 15min. So use it carefully //@version=5 //This strategy can be used for daily entry for positional trading strategy('CCI & EMA strategy by Tradeswithashish', shorttitle='CC-EMA by tradeswithashish', overlay=true, default_qty_type=strategy.percent_of_equity, initial_capital=1000000) emalen = input.int(title='Smooth EMA length', defval=100, minval=50, maxval=200, step=10) Return = input.float(title='Return (%)', defval=5, minval=5, maxval=100, step=5) Risk = input.float(title='Risk (%)', defval=3, minval=1, maxval=10, step=1) ema = ta.ema(close, emalen) emasmooth = ta.ema(ema, emalen) ema2 = ta.ema(close, 50) emasmooth2 = ta.ema(ema2, 50) volMA = ta.sma(volume, 20) volcheck = volume > volMA //fidning CCI-100 and CCI-20 values value ma1 = ta.sma(hlc3, 100) cci100 = (hlc3 - ma1) / (0.015 * ta.dev(hlc3, 100)) ma2 = ta.sma(hlc3, 20) cci20 = (hlc3 - ma2) / (0.015 * ta.dev(hlc3, 20)) //conditions for short and long entries BuyCond = close > emasmooth and close > open and volcheck and cci100 > 0 and cci20 > 100 and close > ta.vwap and barstate.isconfirmed and (close - low) / (high - low) > 0.6 and volume > volume[1] SellCond = close < emasmooth and close < open and volcheck and cci100 < 0 and cci20 < -100 and close < ta.vwap and barstate.isconfirmed and (close - low) / (high - low) < 0.4 and volume > volume[1] //Buy and Sell Signals Buysignal = BuyCond and strategy.position_size == 0 and barstate.isconfirmed Sellsignal = SellCond and strategy.position_size == 0 and barstate.isconfirmed //settingup stoploss sllong = math.max(ema2, emasmooth) slshort = math.min(ema2, emasmooth) //Setting up Targets longtarget = ohlc4 * (1 + Return / 100) shorttarget = ohlc4 * (1 - Return / 100) //Save SLs and Target prices var StopPrice = 0.0 var TargetPrice = 0.0 var EntryPrice = 0.0 //Detect Valid long setup and trigger alerts if Buysignal StopPrice := sllong EntryPrice := ohlc4 TargetPrice := longtarget TargetPrice if Sellsignal StopPrice := slshort TargetPrice := shorttarget EntryPrice := ohlc4 EntryPrice //Trailing Stoplosses if strategy.position_size > 0 StopPrice := math.max(StopPrice, ema2, emasmooth) StopPrice if strategy.position_size < 0 StopPrice := math.min(StopPrice, ema2, emasmooth) StopPrice //enter trades whenever there is signal strategy.entry(id='BUY', direction=strategy.long, when=Buysignal, alert_message='Buy signal given') strategy.entry(id='SELL', direction=strategy.short, when=Sellsignal, alert_message='Sell signal given') //Exit entries if cci100 < 0 or close < emasmooth or close < ema2 strategy.exit(id='Exit', from_entry='BUY', limit=TargetPrice, stop=StopPrice, when=strategy.position_size > 0, alert_message='Long entry closed') if cci100 > 0 or close > emasmooth or close > ema2 strategy.exit(id='Exit', from_entry='SELL', limit=TargetPrice, stop=StopPrice, when=strategy.position_size < 0, alert_message='Short entry closed') //Draw trade data stoplong = plot(strategy.position_size > 0 or Buysignal or Sellsignal ? StopPrice : na, title='Trailing stoploss long', color=color.new(color.red, 80), style=plot.style_linebr, linewidth=1) stopshort = plot(strategy.position_size < 0 or Sellsignal ? StopPrice : na, title='Trailing stoploss short', color=color.new(color.red, 80), style=plot.style_linebr, linewidth=1) candlenearest = plot(strategy.position_size < 0 ? high : strategy.position_size > 0 ? low : na, title='Candle nearest point', color=color.new(color.green, 80), style=plot.style_linebr, linewidth=1) fill(stoplong, candlenearest, color=color.new(color.green, 80)) fill(stopshort, candlenearest, color=color.new(color.red, 80)) //Draw Price action arrow plotshape(Buysignal ? 1 : na, style=shape.triangleup, location=location.belowbar, color=color.new(color.green, 0), title='Bullish setup', size=size.small) plotshape(Sellsignal ? 1 : na, style=shape.triangledown, location=location.abovebar, color=color.new(color.red, 0), title='Bearish setup', size=size.small) //Plot emasmooth and vwap plot(ta.vwap, title='VWAP', color=color.new(color.black, 0), linewidth=2, show_last=75)
Lawyers Trend Pro Strategy
https://www.tradingview.com/script/7umLNb6z/
ErdemDemir
https://www.tradingview.com/u/ErdemDemir/
329
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/ // © ErdemDemir //@version=4 strategy("Lawyers Trend Pro Strategy", shorttitle="Lawyers Trend Pro Strategy", overlay=true) src = close mult = 2.0 basis = sma(src, 20) dev = mult * stdev(src, 20) upper = basis + dev lower = basis - dev offset = 0 lower2 = lowest(20) upper2 = highest(20) basis2 = avg(upper2, lower2) MB= (basis+basis2)/2 col1=close>MB col3=MB>close colorE = col1 ? color.blue : col3 ? color.red : color.yellow p3=plot(MB, color=colorE, linewidth=3) // 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 buySignal = not isLong and crossover(close,MB) // Sell only if the sell signal is triggered and we are not already short sellSignal= not isShort and crossover(MB,close) if (buySignal) isLong := true isShort := false if (sellSignal) isLong := false isShort := true /// LONG strategy.entry("long", true , when = buySignal, comment="Open Long") strategy.close("long", when=sellSignal, comment = "Close Long") /// SHORT strategy.entry("short", false, when = sellSignal, comment="Open Short") strategy.close("short", when=buySignal, comment = "Close Short")
PMA Strategy Idea
https://www.tradingview.com/script/5p6Mli27-PMA-Strategy-Idea/
QuantCT
https://www.tradingview.com/u/QuantCT/
128
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © QuantCT //@version=4 strategy("PMA Strategy Idea", shorttitle="PMA", overlay=true, pyramiding=0, default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=1000, commission_type=strategy.commission.percent, commission_value=0.075) // ____ Inputs ema1_period = input(title="EMA1 Period", defval=10) ema2_period = input(title="EMA2 Period", defval=20) ema3_period = input(title="EMA3 Period", defval=30) long_only = input(title="Long Only", defval=false) slp = input(title="Stop-loss (%)", minval=1.0, maxval=25.0, defval=5.0) use_sl = input(title="Use Stop-Loss", defval=false) // ____ Logic ema1 = ema(hlc3, ema1_period) ema2 = ema(hlc3, ema2_period) ema3 = ema(hlc3, ema3_period) enter_long = (rising(ema1, 1) and rising(ema2, 1) and rising(ema3, 1)) exit_long = not enter_long enter_short = (falling(ema1, 1) and falling(ema2, 1) and falling(ema3, 1)) exit_short = not enter_short strategy.entry("Long", strategy.long, when=enter_long) strategy.close("Long", when=exit_long) if (not long_only) strategy.entry("Short", strategy.short, when=enter_short) strategy.close("Short", when=exit_short) // ____ SL sl_long = strategy.position_avg_price * (1- (slp/100)) sl_short = strategy.position_avg_price * (1 + (slp/100)) if (use_sl) strategy.exit(id="SL", from_entry="Long", stop=sl_long) strategy.exit(id="SL", from_entry="Short", stop=sl_short) // ____ Plots colors = enter_long ? #27D600 : enter_short ? #E30202 : color.orange ema1_plot = plot(ema1, color=colors) ema2_plot = plot(ema2, color=colors) ema3_plot = plot(ema3, color=colors) fill(ema1_plot, ema3_plot, color=colors, transp=50)
Momentum Strategy Idea
https://www.tradingview.com/script/BzVpAYk1-Momentum-Strategy-Idea/
QuantCT
https://www.tradingview.com/u/QuantCT/
151
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © QuantCT //@version=4 strategy("Momentum Strategy Idea", shorttitle="Momentum", overlay=false, pyramiding=0, default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=1000, commission_type=strategy.commission.percent, commission_value=0.075) // ____ Inputs fast_period = input(title="Fast Period", defval=5) slow_period = input(title="Slow Period", defval=10) long_only = input(title="Long Only", defval=false) slp = input(title="Stop-loss (%)", minval=1.0, maxval=25.0, defval=5.0) use_sl = input(title="Use Stop-Loss", defval=false) // ____ Logic mom_fast = mom(close, fast_period) mom_slow = mom(close, slow_period) enter_long = (mom_slow > 0 and mom_fast > 0) exit_long = (mom_slow < 0 or mom_fast < 0) enter_short = (mom_slow < 0 and mom_fast < 0) exit_short = (mom_slow > 0 or mom_fast > 0) strategy.entry("Long", strategy.long, when=enter_long) strategy.close("Long", when=exit_long) if (not long_only) strategy.entry("Short", strategy.short, when=enter_short) strategy.close("Short", when=exit_short) // ____ SL sl_long = strategy.position_avg_price * (1- (slp/100)) sl_short = strategy.position_avg_price * (1 + (slp/100)) if (use_sl) strategy.exit(id="SL", from_entry="Long", stop=sl_long) strategy.exit(id="SL", from_entry="Short", stop=sl_short) // ____ Plots colors = enter_long ? #27D600 : enter_short ? #E30202 : color.orange mom_fast_plot = plot(mom_fast, color=colors) mom_slow_plot = plot(mom_slow, color=colors) fill(mom_fast_plot, mom_slow_plot, color=colors, transp=50)
Chandelier + BB + EMAS
https://www.tradingview.com/script/8F6WNLkO/
juanchez
https://www.tradingview.com/u/juanchez/
60
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © juanchez //@version=4 strategy("CHI", overlay = true, close_entries_rule = "ANY") //Chandelier n = input(title= "highest high o lowest low period", defval= 22) f= input(title= "multiplicador", defval= 4) long = highest(high, n) - atr(n)*f short= lowest(low, n) + atr(n)*f plot(long, color= color.green, linewidth= 2, title= "Long Stop") plot(short, color= color.red, linewidth= 2, title= "Short Stop") //moving averages period= input(title= "moving averages period", defval= 50) period2= input(title= "moving averages period2", defval= 20) type= input(title= "moving averages type", options= ["sma", "ema"], defval= "ema") //moving average function mo(p, t) => if t == "sma" sma(close[barstate.islast ? 1: 0], p) else if t== "ema" ema(close[barstate.islast ? 1: 0], p) show= input(false, title= "Show EMAS") m= mo(period, type) m2= mo(period2, type) trend= m2 > m plot(show? m:na, title= "Slow MA", color = color.maroon, linewidth = 3) plot(show? m2: na, title= "Fast MA",linewidth= 3) //BOLLINGER BANDS ENTRIES bb1_period= input(title= "Bollinger bands 1 period", defval=40, minval=1) bb1_source=input(title="Bollinger band 1 source", defval=close) bb1_multi=input(title="Bollinger Bands 1 factor", defval=2, minval=1, step=0.1) show_bb1= input(title="Show Bollinger bands 1", defval=false) //BOLLINGER BANDS _bb(src, lenght, multi)=> float moving_avg= sma(src[barstate.islast? 1: 0], lenght) float deviation= stdev(src[barstate.islast? 1: 0], lenght) float lowerband = moving_avg - deviation*multi float upperband = moving_avg + deviation*multi [moving_avg, lowerband, upperband] [bb1, lowerband1, upperband1]= _bb(bb1_source, bb1_period, bb1_multi) //FIRST BAND plot(show_bb1? bb1 : na, title="BB1 Moving average", linewidth= 3, color= color.fuchsia) plot(show_bb1? upperband1 : na, title="BB1 Upper Band", linewidth= 3, color= color.green) plot(show_bb1? lowerband1 : na, title="BB1 Lower Band", linewidth= 3, color= color.red) //BB's Width threshold thresh= input(title= "widen %", defval= 9, minval = 0, step = 1, maxval= 100) widht= (upperband1 - lowerband1)/bb1 roc= change(widht)/widht[1]*100 cross=crossover(roc, thresh) // entry //long elong= input(true, title= "enable long") longcondition= m2 > m and cross and elong //short eshort= input(true, title= "enable short") shortcondition= m2 < m and cross and eshort plotshape(longcondition? true: false , location= location.belowbar, style= shape.labelup, size= size.small, color= color.green, text= "Buy", textcolor= color.white) plotshape(shortcondition? true: false , location= location.abovebar, style= shape.labeldown, size= size.small, color= color.red, text= "Sell", textcolor= color.white) out= crossunder(close, long) outt= crossover(close, short) strategy.entry("long", strategy.long, when = longcondition) strategy.close("long", when = out) strategy.entry("short", strategy.short, when = shortcondition) strategy.close("short", when = outt)
Relative Volume & RSI Pop
https://www.tradingview.com/script/4TzCBoTw-Relative-Volume-RSI-Pop/
gary_trades
https://www.tradingview.com/u/gary_trades/
259
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/ // © gary_trades //This script is a basic concept to catch breakout moves utilising a spike in relative volume when the RSI is high (for longs) or when the RSI is low (for shorts). //Drawdown is typically low as it exits out of the trade once the RSI returns back to "normal levels". //@version=4 strategy(title="Relative Volume & RSI Pop", shorttitle="VOL & RSI Pop", overlay=false, precision=2, margin_long=100, margin_short=100) //RSI RSIlength = input(14, title="RSI Period") RSItop = input(70, title="RSI buy", minval= 69, maxval=100) RSIbottom = input(35, title="RSI short", minval= 0, maxval=35) price = close vrsi = rsi(price, RSIlength) RSIco = crossover(vrsi, RSItop) RSIcu = crossunder(vrsi, RSIbottom) plot(vrsi, "RSI", color=color.purple) band1 = hline(70, "Upper Band", color=#C0C0C0) bandm = hline(50, "Middle Band", color=color.new(#C0C0C0, 50)) band0 = hline(30, "Lower Band", color=#C0C0C0) fill(band1, band0, color=color.purple, transp=90, title="Background") //RELATIVE VOLUME RVOLlen = input(14, minval=1, title="RV Period") av = sma(volume, RVOLlen) RVOL = volume / av RVOLthreshold = input(1.5,title="RV Threshold", minval=0.5, maxval=10) //TRADE TRIGGERS LongCondition = RSIco and RVOL > RVOLthreshold CloseLong = vrsi < 69 ShortCondition = RSIcu and RVOL > RVOLthreshold CloseShort = vrsi > 35 if (LongCondition) strategy.entry("Long", strategy.long) strategy.close("Long", when = CloseLong) if (ShortCondition) strategy.entry("Short", strategy.short) strategy.close("Short", when = CloseShort)
Swing High Low Price Channel V.1
https://www.tradingview.com/script/6CioaCN0-Swing-High-Low-Price-Channel-V-1/
ZoomerXeus
https://www.tradingview.com/u/ZoomerXeus/
79
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/ // © ZoomerXeus //@version=4 strategy("Swing High Low Price Channel V.1", overlay=true) //========================= variable =================================// dead_channel_source = input(title="Main swing channel source", defval="H/L", options=["H/L"]) fast_signal_length = input(title="Fast Slow Length", type=input.integer, defval=7, maxval=49, minval=1) slow_signal_length = input(title="Slow Slow Length", type=input.integer, defval=20, maxval=49, minval=1) is_show_only_dead_channel = input(title="Show main channel only", defval=true) main_channel_width = input(title="Main line width", defval=2, minval=1) signal_channel_width = input(title="Signal line width", defval=1, minval=1) //========================= indicator function =================================// dead_cross_high_50 = highest(high, 50) dead_cross_high_200 = highest(high, 200) //======================================== dead_cross_low_50 = lowest(low, 50) dead_cross_low_200 = lowest(low, 200) //======================================== medain_dead_cross_50 = ((dead_cross_high_50-dead_cross_low_50)*0.5)+dead_cross_low_50 medain_dead_cross_200 = ((dead_cross_high_200-dead_cross_low_200)*0.5)+dead_cross_low_200 //======================================== fasthighest = highest(high, fast_signal_length) fastlowest = lowest(low, fast_signal_length) //======================================== slowhighest = highest(high, slow_signal_length) slowlowest = lowest(low, slow_signal_length) //======================================== //========================= plot =================================// plot(dead_channel_source == "H/L" ? dead_cross_high_50 : na,title="50 bar highest", color=color.red, linewidth=main_channel_width) plot(dead_channel_source == "H/L" ? dead_cross_high_200 : na,title="200 bar highest", color=color.aqua, linewidth=main_channel_width) plot(dead_channel_source == "H/L" ? dead_cross_low_50 : na,title="50 bar lowest", color=color.red, linewidth=main_channel_width) plot(dead_channel_source == "H/L" ? dead_cross_low_200 : na,title="200 bar lowest", color=color.aqua, linewidth=main_channel_width) plot(dead_channel_source == "H/L" ? medain_dead_cross_200 : na,title="200 bar middle lowest", color=color.orange, linewidth=main_channel_width) plot(dead_channel_source == "H/L" ? medain_dead_cross_50 : na,title="50 bar middle lowest", color=color.lime, linewidth=main_channel_width) //=========================================== plot(is_show_only_dead_channel == false ? fasthighest : na,title="fast signal highest", color=#ff00f9, linewidth=signal_channel_width) plot(is_show_only_dead_channel == false ? fastlowest : na,title="fast signal lowest", color=#ff00f9, linewidth=signal_channel_width) plot(is_show_only_dead_channel == false ? slowhighest : na,title="slow signal highest", color=color.white, linewidth=signal_channel_width) plot(is_show_only_dead_channel == false ? slowlowest : na,title="slow signal lowest", color=color.white, linewidth=signal_channel_width) //=========================================== plot(crossover(medain_dead_cross_50, medain_dead_cross_200) ? medain_dead_cross_200 : na, title="Dead cross buy plot", style=plot.style_circles, linewidth=6, color=color.lime) plot(crossunder(medain_dead_cross_50, medain_dead_cross_200) ? medain_dead_cross_200 : na, title="Dead cross sell plot", style=plot.style_circles, linewidth=6, color=color.red) plot(is_show_only_dead_channel and (medain_dead_cross_50 < medain_dead_cross_200) and high == slowhighest ? high : na, title="Follow trend short term sell plot zone", style=plot.style_circles, linewidth=3, color=color.orange) plot(is_show_only_dead_channel and (medain_dead_cross_50 > medain_dead_cross_200) and low == slowlowest ? low : na, title="Follow trend short term buy plot zone", style=plot.style_circles, linewidth=3, color=color.green) plot(is_show_only_dead_channel and high == slowhighest and (high == dead_cross_high_200) ? high : na, title="Not follow trend short term sell plot zone", style=plot.style_circles, linewidth=3, color=color.orange) plot(is_show_only_dead_channel and low == slowlowest and (low == dead_cross_low_200) ? low : na, title="Not follow trend short term buy plot zone", style=plot.style_circles, linewidth=3, color=color.green) //===================== open close order condition =========================================================// //strategy.entry("strong buy", true, 1000, when=low == dead_cross_low_200) //strategy.exit("close strong buy 50%", "strong buy", qty_percent=50, when=high==slowhighest) //strategy.entry("strong sell", false, 1000, when=high == dead_cross_high_200) //strategy.exit("close strong sell 50%", "strong sell", qty_percent=50, when=low==slowlowest)
Long/Short Volatility Algo
https://www.tradingview.com/script/HFKxXAON-Long-Short-Volatility-Algo/
sparrow_hawk_737
https://www.tradingview.com/u/sparrow_hawk_737/
95
strategy
3
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © sparrow_hawk_737 //@version=3 strategy("Short Volatility", default_qty_type=strategy.percent_of_equity, default_qty_value=100) exitWhenOscIsZero = input(false, title="Exit when oscillator goes under 0?") enterWhenOscIsZero = input(false, title="Enter when oscillator goes over 0?") isRA=input(true, title="Stockcharts version (Ratio Adjusted)?") rm=input(defval=1000, title="RANA ratio multiplier") showEMAs=input(false, title="Show EMAs?") showOsc=input(true, title="Show Oscillator?") slowLengthSell = input(20, title="Slow Length Sell") fastLengthSell = input(9, title="Fast Length Sell") slowLengthBuy = input(20, title="Slow Length Buy") fastLengthBuy = input(9, title="Fast Length Buy") useCTF=input(false, title="Use Custom Timeframe?"), tf=useCTF?input("D", type=resolution, title="Custom Timeframe"):period // Recommend NOT enabling this gaps=barmerge.gaps_off // Recommend leaving this OFF src=close // Varianta doar cu NYSE sau doar cu NASDAQ da semnale long mai proaste decat // varianta cu toate bursele, dar uneori (f rar) cea cu NYSE le da mai devreme. use_ny=input(100.0,"NYSE %")/100 use_nq=input(0,"NASDAQ %")/100 use_us=input(100.0,"US %")/100 use_dj=input(0,"DJ %")/100 use_ax=input(100.0,"AX %")/100 use_am=input(0,"AM %")/100 ai=0.0, di=0.0 adv=use_ny*nz(security("ADVN.NY", tf, src, gaps))+use_nq*nz(security("ADVN.NQ", tf, src, gaps))+use_us*nz(security("ADVN.US", tf, src, gaps))+use_dj*nz(security("ADVN.DJ", tf, src, gaps))+use_ax*nz(security("ADVN.AX", tf, src, gaps))+use_am*nz(security("ADVN.AM", tf, src, gaps)) dec=use_ny*nz(security("DECL.NY", tf, src, gaps))+use_nq*nz(security("DECL.NQ", tf, src, gaps))+use_us*nz(security("DECL.US", tf, src, gaps))+use_dj*nz(security("DECL.DJ", tf, src, gaps))+use_ax*nz(security("DECL.AX", tf, src, gaps))+use_am*nz(security("DECL.AM", tf, src, gaps)) ai:=ai+adv, di:=di+dec rana=rm * (ai-di)/(ai+di) moonel = input(16, "mo1 length") mtwol = input(36, "mo2 length") e1=isRA?ema(rana, moonel):ema(ai-di, moonel),e2=isRA?ema(rana, mtwol):ema(ai-di, mtwol) mo=e1-e2 hline(0, title="0") plot(showOsc?mo<0?mo:0:na, style=area, color=white, title="-") plot(showOsc?mo>=0?mo:0:na, style=area, color=white, title="+") plot(showOsc?mo:na, style=line, color=black, title="MO", linewidth=2) plot(showEMAs?e1:na, color=blue, linewidth=2, title="19 EMA") plot(showEMAs?e2:na, color=red, linewidth=2, title="39 EMA") short= mo>=100 and mo<mo[1] long= mo<=-100 and mo>mo[1] bgcolor(long ? green : short ? red : white, transp=75) alertcondition(long and not long[1], "McC long ", "McC long ") alertcondition(short and not short[1], "McC short ", "McC short ") exited = false inpos = strategy.position_size > 0 mas1 = ema(mo, fastLengthSell) mas2 = ema(mo, slowLengthSell) mab1 = ema(mo, fastLengthBuy) mab2 = ema(mo, slowLengthBuy) plot(mas1, color=blue, linewidth=2, title="39 EMA") plot(mas2, color=orange, linewidth=2, title="39 EMA") plot(mab1, color=red, linewidth=2, title="39 EMA") plot(mab2, color=black, linewidth=2, title="39 EMA") get_bbr(x, length) => mult = 2 basis = sma(x, length) dev = mult * stdev(x, length) upper = basis + dev lower = basis - dev (x - lower)/(upper - lower) vxx = security("VXX", "D", close) vvix = security("VVIX", "D", close) bbr1 = get_bbr(vvix, input(10, title="vvix bbr length")) bbr2 = get_bbr(vxx, input(20,title="vxx bbr length")) mmthsell = input(true, "Only sell when percent of X stocks is in downtrend") // 25 is the max observed so far mmth = sma(security(input("MMOH", "Percent of stocks above X"), "", close), input(20, "percent of stocks length")) mmthlow =( ( mmth[0] - mmth[1] ) + ( mmth[1] - mmth[2] ) + ( mmth[2] - mmth[3] ) ) / 3 < 0 mmfi = security("MMFI", "D", close) mmfibbr = get_bbr(mmfi, 100) buy2 = mmfibbr >= 0 and ( mmfibbr[1] <= 0.01) skew = security("SKEW", "", close) skewma = sma(skew, input(10, "SKEW MA LENGTH")) skewpos = ( ( (skewma - skewma[1]) + (skewma[1] - skewma[2]) + (skewma[2] - skewma[3]) ) / 3) > 0 skbbr = get_bbr(skew, input(29, "skew bbr length")) skewthresh = input(1.1, "skew bbr thresh") extremenegativeskew = (skbbr > skewthresh) or (skbbr[1] > skewthresh) v1 = security("VX1!", "D", close) v2 = security("VX2!", "D", close) vix = security("VIX", "D", close) roll_yield = (v1 - vix) / vix shape = ( v2 - v1 ) rysell = roll_yield <= 0.01 plot(roll_yield * 100, color=orange, linewidth=2,title="ROLL YIELD") plot(shape * 10, color=yellow, linewidth=2,title="VIX SHAPE") iwm = security("IWM", "", close) iwmma12 = sma(iwm, input(12)) buy3 = iwm > iwmma12 div = close/open plot(div, color=black, linewidth=3, title="jokes") sell = rysell and mmthlow and ( crossunder(mas1, mas2) or mas1 < mas2 ) and ( bbr1 >= 0.90 or bbr2 >= 0.90 and mas1 < mas1[1]) and not extremenegativeskew and not buy3 preznobuy = ((year - 2004) % 4 == 0 and month == 10 ? dayofmonth < 10 and dayofmonth > 31 : true) prezsell = ((year - 2004) % 4 == 0 and month == 10 ? dayofmonth >= 10 and dayofmonth <= 17 : false) if (preznobuy and extremenegativeskew and strategy.position_size >= 0) strategy.entry("extremenegativeskew", strategy.short) if (preznobuy and ( (crossover(mab1, mab2) or mab1 > mab2 )) and strategy.position_size <= 0) strategy.entry("mab cross", strategy.short) if (preznobuy and (buy2 and skewpos) and strategy.position_size >= 0) strategy.entry("mmfi + skew bottom", strategy.short) if (preznobuy and (buy3 and skewpos) and strategy.position_size >= 0) strategy.entry("RUS bottom", strategy.short) if ((prezsell or sell) and strategy.position_size <= 0) strategy.entry("LONG VOL", strategy.long)
Сalculation a position size based on risk
https://www.tradingview.com/script/hoCPm5UY-%D0%A1alculation-a-position-size-based-on-risk/
adolgov
https://www.tradingview.com/u/adolgov/
693
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/ // © adolgov //@description This strategy shows how calculate position size from risk (%% from equity or absolute money value) and stop loss level (%% from entry price) // Important notes: // 1) we suppose that account currency is same as symbol currency // 2) leverage is 1:10 (this can be changed in the Settings dlg) //@version=4 strategy("Сalculation a position size based on risk", overlay=true, margin_long=10, margin_short=10, currency = currency.NONE) percent2points(percent) => strategy.position_size !=0 ? strategy.position_avg_price * percent / 100 / syminfo.mintick : na percent2money(price, percent) => price * percent / 100 * syminfo.pointvalue slPcnt = input(10, title = "Stop Loss %%") riskValue = input(2, title="Risk ", inline="risk", tooltip="Max risk for position") riskType = input("% from equity", title="", options=["% from equity", "$$"], inline="risk") calcPositionSize(entryPrice, slPercent) => risk = if riskType == "% from equity" strategy.equity * riskValue / 100 else riskValue risk / percent2money(entryPrice, slPercent) qty = calcPositionSize(close, slPcnt) // random entry longCondition = bar_index % 333 == 0 if (longCondition) strategy.entry("My Long Entry Id", strategy.long, qty = qty) shortCondition = bar_index % 444 == 0 if (shortCondition) strategy.entry("My Short Entry Id", strategy.short, qty = qty) // exit with stop loss slPts = percent2points(slPcnt) strategy.exit("x", loss = slPts)
Binomial Moving Average Strategy
https://www.tradingview.com/script/ZikqRDDd-Binomial-Moving-Average-Strategy/
HosseinDaftary
https://www.tradingview.com/u/HosseinDaftary/
28
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/ // © HosseinDaftary //@version=4 strategy("Binomial Moving Average","BMA", overlay=true, margin_long=100, margin_short=100 ,max_bars_back=96) //Binomial Moving Average:This type of moving average that is made by myself and i did not see anywhere before uses the half of binomial cofficients for //averaging the prices for example if the period be 5 then we use the 9 degree binomial cofficients(that yields 10 cofficients) and use half of them. //we use 126/256 for last bar,84/256,36/256,9/256 and finally use 1/256 for 5th bar. Seemingly this MA works better than EMA. fa_ma=input(title='Fast MA',defval=10) sl_ma=input(title='Slow MA',defval=30) fac(n)=> fact=1 for i= 1 to n fact:=fact*i fact cof= array.new_float(sl_ma) hn_ma(price,length)=> sum=1.0 sum1=0.0 array.set(cof,length-1,1) for i=2 to length array.set(cof,length-i,fac(2*length-1)/(fac(i-1)*fac(2*length-i))) sum:=sum+array.get(cof,length-i) for i=0 to length-1 array.set(cof,i,array.get(cof,i)/sum) sum1:=sum1+array.get(cof,i)*price[i] sum1 hn1=plot(hn_ma(close,sl_ma) , color=#00ff00) hn2=plot(hn_ma(close,fa_ma) ,color=#ff0000) fill(hn1,hn2,color=hn_ma(close,fa_ma)>hn_ma(close,sl_ma)?color.green:color.red) longCondition = crossover(hn_ma(close, fa_ma), hn_ma(close, sl_ma)) if (longCondition) strategy.entry("Long", strategy.long) shortCondition = crossunder(hn_ma(close, fa_ma), hn_ma(close, sl_ma)) if (shortCondition) strategy.entry("Short", strategy.short)
Maximized Scalping On Trend (by Coinrule)
https://www.tradingview.com/script/XAiEh7nb-Maximized-Scalping-On-Trend-by-Coinrule/
Coinrule
https://www.tradingview.com/u/Coinrule/
1,345
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © Coinrule //@version=4 strategy(shorttitle='Maximized Scalping On Trend',title='Maximized Scalping On Trend (by Coinrule)', overlay=true, initial_capital = 1000, process_orders_on_close=true, default_qty_type = strategy.percent_of_equity, default_qty_value = 30, commission_type=strategy.commission.percent, commission_value=0.1) //Backtest dates fromMonth = input(defval = 1, title = "From Month", type = input.integer, minval = 1, maxval = 12) fromDay = input(defval = 10, title = "From Day", type = input.integer, minval = 1, maxval = 31) fromYear = input(defval = 2019, title = "From Year", type = input.integer, minval = 1970) thruMonth = input(defval = 1, title = "Thru Month", type = input.integer, minval = 1, maxval = 12) thruDay = input(defval = 1, title = "Thru Day", type = input.integer, minval = 1, maxval = 31) thruYear = input(defval = 2112, title = "Thru Year", type = input.integer, minval = 1970) showDate = input(defval = true, title = "Show Date Range", type = input.bool) start = timestamp(fromYear, fromMonth, fromDay, 00, 00) // backtest start window finish = timestamp(thruYear, thruMonth, thruDay, 23, 59) // backtest finish window window() => time >= start and time <= finish ? true : false // create function "within window of time" //MA inputs and calculations movingaverage_fast = sma(close, input(9)) movingaverage_mid= sma(close, input(50)) movingaverage_slow = sma(close, input (100)) //Trend situation Bullish= crossunder(close, movingaverage_fast) Momentum = movingaverage_mid > movingaverage_slow // RSI inputs and calculations lengthRSI = 14 RSI = rsi(close, lengthRSI) //Entry strategy.entry(id="long", long = true, when = Bullish and Momentum and RSI > 50 and window()) //Exit TP = input(70) SL =input(30) longTakeProfit = RSI > TP longStopPrice = RSI < SL strategy.close("long", when = longStopPrice or longTakeProfit and window()) plot(movingaverage_fast, color=color.black, linewidth=2 ) plot(movingaverage_mid, color=color.orange, linewidth=2) plot(movingaverage_slow, color=color.purple, linewidth=2)
Crypto EMA Trend Reversal Strategy
https://www.tradingview.com/script/eBiTvw92-Crypto-EMA-Trend-Reversal-Strategy/
ADHDCRYPT0
https://www.tradingview.com/u/ADHDCRYPT0/
260
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // @author ADHDCRYPT0 //@version=4 strategy(title = "EMA double crossover", shorttitle = "(TEST) double cross over", overlay = true, default_qty_value = 100, initial_capital = 1000,default_qty_type=strategy.percent_of_equity, pyramiding=0, process_orders_on_close=true) // Variables ema_len1 = input(9 , title="Fast EMA") ema_len2 = input(21, title="Slow EMA") ema_len3 = input(5, title="Exit EMA") ema_len4 = input(1, title="FastConf EMA") ema_len5 = input(4, title="SlowConf EMA") fastEMA = ema(open, ema_len1) slowEMA = ema(open, ema_len2) exitEMA = ema(open, ema_len3) conf1EMA = ema(open, ema_len4) conf2EMA = ema(open, ema_len5) plot(fastEMA, title='fastEMA', transp=0, color=color.green) plot(slowEMA, title='slowEMA', transp=0, color=color.red ) plot(exitEMA, title='exitEMA', transp=0, color=color.orange) plot(conf1EMA, title='conf1EMA', transp=0, color=color.blue) plot(conf2EMA, title='conf2EMA', transp=0, color=color.black) vol = volume volma = sma(volume,7) vol_cond = vol>volma atr = atr(5) // Entry Conditions and vol_cond long = crossover(fastEMA, slowEMA) and (conf1EMA > conf2EMA) and (fastEMA < exitEMA) short= crossunder(fastEMA, slowEMA) and (conf1EMA < conf2EMA) and (fastEMA > exitEMA) tradeType = input("BOTH", title="What trades should be taken : ", options=["LONG", "SHORT", "BOTH", "NONE"]) pos = 0.0 if tradeType=="BOTH" pos:= long? 1 : short? -1 : pos[1] if tradeType=="LONG" pos:= long? 1 : pos[1] if tradeType=="SHORT" pos:=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 // sl = input(1, title="Stop Loss (ATR)", minval=0) tp = input(6, title="Take Profit 1 (ATR)", minval=0) // Simple Stop Loss + 2 Take Profits sl_long = valuewhen(longCond , low - atr * sl, 0) sl_short = valuewhen(shortCond, high+ atr * sl, 0) tp_long = valuewhen(longCond , high + atr * tp, 0) tp_short = valuewhen(shortCond, low - atr * tp, 0) long_exit = crossover(fastEMA, exitEMA) and pos[1]==1 short_exit= crossover(exitEMA, fastEMA) and pos[1]==-1 if long_exit or short_exit pos:=0 // Position Adjustment long_sl = low <sl_long [1] and pos[1]==1 short_sl = high>sl_short[1] and pos[1]==-1 if long_sl or short_sl pos:=0 // Strategy Backtest Limiting Algorithm i_startTime = input(defval = timestamp("01 Sep 2002 13:30 +0000"), title = "Backtesting Start Time", type = input.time) i_endTime = input(defval = timestamp("30 Sep 2099 19:30 +0000"), title = "Backtesting End Time", type = input.time) timeCond = (time > i_startTime) and (time < i_endTime) // Make sure we are within the bar range, Set up entries and exit conditions if strategy.equity >0 strategy.entry("long" , strategy.long , when=longCond and timeCond and tradeType!="SHORT" , alert_message="INSERT MESSAGE HERE") strategy.entry("short", strategy.short, when=shortCond and timeCond and tradeType!="LONG" , alert_message="INSERT MESSAGE HERE") strategy.exit("SL/TP1", from_entry = "long" , stop=sl_long , limit=tp_long , alert_message="INSERT MESSAGE HERE") strategy.exit("SL/TP1", from_entry = "short", stop=sl_short, limit=tp_short, alert_message="INSERT MESSAGE HERE") strategy.exit("SL", from_entry = "long" , stop=sl_long, alert_message="INSERT MESSAGE HERE") strategy.exit("SL", from_entry = "short", stop=sl_short, alert_message="INSERT MESSAGE HERE") strategy.close("long", when=long_exit , comment="TP2", alert_message="INSERT MESSAGE HERE") strategy.close("short", when=short_exit, comment="TP2", alert_message="INSERT MESSAGE HERE")
3 x EMA + Stochastic RSI + ATR
https://www.tradingview.com/script/NOFMegun-3-x-EMA-Stochastic-RSI-ATR/
tomimarson
https://www.tradingview.com/u/tomimarson/
191
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/ // © FreddieChopin //@version=4 strategy("3 x EMA + Stochastic RSI + ATR", overlay = true, default_qty_type = strategy.percent_of_equity, default_qty_value = 100) // 3x EMA ema1Length = input(8, "EMA1 Length", minval = 1) ema2Length = input(14, "EMA2 Length", minval = 1) ema3Length = input(50, "EMA3 Length", minval = 1) ema1 = ema(close, ema1Length) ema2 = ema(close, ema2Length) ema3 = ema(close, ema3Length) plot(ema1, color = color.green) plot(ema2, color = color.orange) plot(ema3, color = color.red) // Stochastic RSI smoothK = input(3, "K", minval=1) smoothD = input(3, "D", minval=1) lengthRSI = input(14, "RSI Length", minval=1) lengthStoch = input(14, "Stochastic Length", minval=1) src = input(close, title="RSI Source") rsi1 = rsi(src, lengthRSI) k = sma(stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK) d = sma(k, smoothD) // ATR atrPeriod = input(14, "ATR Period") takeProfitMultiplier= input(2.0, "Take-profit Multiplier") stopLossMultiplier= input(3.0, "Stop-loss Multiplier") atrSeries = atr(atrPeriod)[1] longCondition = ema1 > ema2 and ema2 > ema3 and crossover(k, d) strategy.entry("long", strategy.long, when = longCondition) float stopLoss = na float takeProfit = na if (strategy.position_size > 0) if (na(stopLoss[1])) stopLoss := strategy.position_avg_price - atrSeries * stopLossMultiplier else stopLoss := stopLoss[1] if (na(takeProfit[1])) takeProfit := strategy.position_avg_price + atrSeries * takeProfitMultiplier else takeProfit := takeProfit[1] strategy.exit("take profit / stop loss", limit = takeProfit, stop = stopLoss) plot(stopLoss, color = color.red, linewidth = 2, style = plot.style_linebr) plot(takeProfit, color = color.green, linewidth = 2, style = plot.style_linebr)
Take America Back Version 1.0
https://www.tradingview.com/script/0aZz65d7-Take-America-Back-Version-1-0/
Crystal_Catalyst
https://www.tradingview.com/u/Crystal_Catalyst/
25
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/ // © Crystal_Catalyst //@version=4 // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © Crystal_Catalyst //@version=4 strategy("Take America Back Version 1.0", close_entries_rule="ANY") default_qty_value=input(defval=20, title="Quantity Value") var float saved=input(defval=0, title="Saved") var price = close var float asset = na var float base = na var float ratio = na fees = input(defval=.0025, title="Fees") asset := (strategy.opentrades*default_qty_value+strategy.openprofit)/open base := strategy.initial_capital-strategy.opentrades*default_qty_value+strategy.netprofit ratio := asset*open/(default_qty_value*strategy.opentrades) if ratio>1 ratio := 1 var initial_asset = asset var initial_base = base var previous_asset = asset var previous_base = base if strategy.opentrades != strategy.opentrades[1] price := open[1] if strategy.netprofit>strategy.netprofit[1] saved := saved+(strategy.netprofit-strategy.netprofit[1])*(base-saved)/base buy = "Take America Back" + tostring(strategy.opentrades) sell = "Take America Back" + tostring(strategy.opentrades-1) if open>price and asset*open<default_qty_value price := open if open<price and base<default_qty_value+saved price := open if open>(asset*price+default_qty_value*2*fees)/(asset*ratio) and asset*open>default_qty_value strategy.exit(sell, limit=open, stop=open) if open<price*(1-2*fees/(base/default_qty_value)) and base>default_qty_value+saved strategy.entry(buy, true, limit=open, stop=open, qty=default_qty_value/close, when = close<price*(1-fees)) plot(saved, title="Saved", color=color.black, style=plot.style_line)
Coin Flipper Pro with strategy tester
https://www.tradingview.com/script/5VcoGd6y-Coin-Flipper-Pro-with-strategy-tester/
melodicfish
https://www.tradingview.com/u/melodicfish/
135
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/ // © melodicfish //@version=4 strategy("Coin Flipper Pro",overlay=true,max_bars_back=100) // ======= User Inputs variables========= h1=input(title="------- Trade Activity -------",defval=false) maxBars=input(25.0,title="Max Bars between Coin Filps",step=1.0,minval=4.0) h2=input(title="------- Position Settings -------",defval=false) risk=input(defval=5.0,title="Risk in % ",type=input.float, minval=0.001 ,step=0.1) ratio= input(defval=1.5,title="Risk to Reward Ratio x:1 ",type=input.float, minval=0.001,step=0.1) h3=input(title="------- Plot Options -------",defval=false) showBox=input(defval=true, title="Show Position Boxes") h4=input(title="------- Back Testing -------",defval=false) runTest=input(defval=true, title="Run Strategy Back Test") customTime=input(defval=false, title="Use Custom Date Range for back test") tsYear = input(2021,minval=1000,maxval=9999,title= "Test Start Year") tsMonth = input(1,minval=1,maxval=12,title= "Test Start Month") tsDay = input(1,minval=1,maxval=31,title= "Test Start Day") start = timestamp(tsYear,tsMonth,tsDay,0,0) teYear = input(2021,minval=1000,maxval=9999,title= "Test Stop Year") teMonth = input(5,minval=1,maxval=12,title= "Test Stop Month") teDay = input(1,minval=1,maxval=31,title= "Test Stop Day") end = timestamp(teYear,teMonth,teDay,0,0) // ======= variables ========= var barsBetweenflips=25 var coinFlipResult=0.0 var flip=true var coinLabel=0.0 var stoppedOut= true var takeProfit=true var posLive=false var p1=0.0 var p2=0.0 var p3=0.0 var plotBox=false var posType=0 long=false short=false // ===== Functions ====== getColor() => round(random(1,255)) // ===== Logic ======== if barssince(flip==true)>barsBetweenflips and posLive==false flip:=true coinLabel:=random(1,10) // Candle Colors candleColor= flip==true and flip[1]==false and barstate.isconfirmed==false?color.rgb(getColor(),getColor(),getColor(),0):flip==false and close>=open?color.green:color.red candleColor:= barstate.ishistory==true and close>=open?color.green: barstate.ishistory==true and close<open? color.red:candleColor barcolor(candleColor) if flip[1]==true and posLive==false flip:=false barsBetweenflips:=round(random(3,round(maxBars))) posLive:=true long:= flip[1]==true and coinLabel[1]>=5.0 short:= flip[1]==true and coinLabel[1]<5.0 // Calculate Position Boxes if long==true and posType!=1 riskLDEC=1-(risk/100) p1:= close[1]*(1+((risk/100)*ratio)) // TargetLine p2:=close[1] p3:= close[1]*riskLDEC // StopLine plotBox:=true posType:=1 if short==true and posType!=-1 riskSDEC=1-((risk*ratio)/100) p1:= close[1]*riskSDEC // TargetLine p2:=close[1] p3:= close[1]*(1+(risk/100)) // StopLine plotBox:=true posType:=-1 // Check Trade Status stoppedOut:= posType==1 and long==false and low<= p3? true: posType==-1 and short==false and high>=p3? true: false takeProfit:= posType==1 and long == false and high>= p1? true: posType==-1 and short==false and low<=p1? true: false if stoppedOut==true or takeProfit==true posType:=0 plotBox:=false posLive:=false // ====== Plots ======== plot1=plot(plotBox and showBox? p1:na,style=plot.style_linebr,color=color.white, transp= 100) plot2=plot(plotBox and showBox? p2:na,style=plot.style_linebr,color=color.white, transp= 100) plot3=plot(plotBox and showBox? p3:na,style=plot.style_linebr,color=color.white, transp= 100) fill(plot1,plot2,color= color.green) fill(plot2,plot3,color= color.red) plotshape(flip==true and flip[1]==false and coinLabel>=5.0,style=shape.labelup,location=location.belowbar, color=color.green,size=size.tiny,title="short label",text="Heads",textcolor=color.white) plotshape(flip==true and flip[1]==false and coinLabel<5.0,style=shape.labeldown,location=location.abovebar, color=color.red,size=size.tiny,title="short label",text="Tails",textcolor=color.white) if stoppedOut==true label.new(bar_index-1, p3, style=label.style_xcross, color=color.orange) if takeProfit==true label.new(bar_index-1, p1, style=label.style_flag, color=color.blue) if runTest==true and customTime==false or runTest==true and customTime==true and time >= start and time <= end strategy.entry("Sell", strategy.short,when=short==true) strategy.close("Sell", comment="Close Short", when=stoppedOut==true or takeProfit==true) strategy.entry("Long", strategy.long,when=long==true) strategy.close("Long",comment="Close Long", when= stoppedOut==true or takeProfit==true )
ma 20 high-low
https://www.tradingview.com/script/zio8Ldrd-ma-20-high-low/
AlanAntony
https://www.tradingview.com/u/AlanAntony/
40
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © AlanAntony //@version=4 strategy("ma 20 high-low",overlay=true) //compute the indicators smaH = sma(high, 20) smaL = sma(low, 20) //plot the indicators plot(smaH,title="smaHigh", color=color.green, linewidth=2) plot(smaL,title="smaLow", color=color.red, linewidth=2) //trading logic enterlong = crossover(close,smaH) //positive ema crossover exitlong = crossunder(close,0.99*smaH) //exiting long entershort = crossunder(close,smaL) //negative EMA Crossover exitshort = crossover(close,1.01*smaH) //exiting shorts notintrade = strategy.position_size<=0 bgcolor(notintrade ? color.red:color.green) //execution logic start = timestamp(2015,6,1,0,0) //end = timestamp(2022,6,1,0,0) if time >= start strategy.entry( "long", strategy.long,100, when = enterlong) strategy.entry( "short", strategy.short,100, when = entershort) strategy.close("long", when = exitlong) strategy.close("short", when = exitshort) //if time >= end // strategy.close_all()
MACD Long Strat
https://www.tradingview.com/script/Ouk6qIyJ-MACD-Long-Strat/
TheGrindToday
https://www.tradingview.com/u/TheGrindToday/
69
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/ // © TheGrindToday //@version=4 strategy("MACD Long Strat", overlay=false) //fast = 12, slow = 26 fast = 6, slow = 26 fastMA = ema(close, fast) slowMA = ema(close, slow) macd = fastMA - slowMA signal = sma(macd, 9) histogram = macd-signal macdpos = histogram[0] > 0 macdneg = histogram[0] < 0 histogram_reversing_negative = histogram[1] > histogram[2] LongEntryCondition = histogram > histogram[1] ShortEntryCondition = histogram < histogram[1] exitConditionLong = histogram[0] < histogram[2] if (LongEntryCondition and histogram_reversing_negative) strategy.entry("Long", strategy.long) if (exitConditionLong) strategy.close("Long") plot(histogram)
How to use Leverage and Margin in PineScript
https://www.tradingview.com/script/9Iwinz7I-How-to-use-Leverage-and-Margin-in-PineScript/
Peter_O
https://www.tradingview.com/u/Peter_O/
934
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © Peter_O //@version=4 strategy(title="How to use Leverage and Margin in PineScript", overlay=false, pyramiding=100, default_qty_type = strategy.percent_of_equity, default_qty_value=3000, margin_long=1./30*50, margin_short=1./30*50) periodK = input(13, title="K", minval=1) periodD = input(3, title="D", minval=1) smoothK = input(4, title="Smooth", minval=1) k = sma(stoch(close, high, low, periodK), smoothK) d = sma(k, periodD) plot(k, title="%K", color=color.blue) plot(d, title="%D", color=color.orange) h0 = hline(80) h1 = hline(20) fill(h0, h1, color=color.purple, transp=75) GoLong=crossover(k,d) and k<80 GoShort=crossunder(k,d) and k>20 TP=input(100, title="Take Profit (in ticks)") strategy.entry("Long", strategy.long, when=GoLong) strategy.exit("tp_long", from_entry="Long", profit=TP) strategy.entry("Short", strategy.short, when=GoShort) strategy.exit("tp_short", from_entry="Short", profit=TP)
Supertrend - Intraday
https://www.tradingview.com/script/XssYFmSK-Supertrend-Intraday/
Pritesh-StocksDeveloper
https://www.tradingview.com/u/Pritesh-StocksDeveloper/
250
strategy
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © Pritesh-StocksDeveloper //@version=5 strategy("Supertrend - Intraday", overlay=true, calc_on_every_tick = false) // ********** Strategy inputs - Start ********** // Used for intraday handling // Session value should be from market start to the time you want to square-off // your intraday strategy // Important: The end time should be at least 2 minutes before the intraday // square-off time set by your broker var i_marketSession = input.session(title="Market session", defval="0915-1455", confirm=true) var float i_multiplier = input.float(title = "Multiplier", defval = 4, step = 0.1, confirm=true) var int i_atrPeriod = input.int(title = "ATR Period", defval = 14, confirm=true) // ********** Strategy inputs - End ********** // ********** Supporting functions - Start ********** // A function to check whether the bar or period is in intraday session barInSession(sess) => time(timeframe.period, sess) != 0 // ********** Supporting functions - End ********** // ********** Strategy - Start ********** [superTrend, dir] = ta.supertrend(i_multiplier, i_atrPeriod) colResistance = dir == 1 and dir == dir[1] ? color.new(color.red, 0) : color.new(color.red, 100) colSupport = dir == -1 and dir == dir[1] ? color.new(color.green, 0) : color.new(color.green, 100) plot(superTrend, color = colResistance, linewidth=2) plot(superTrend, color = colSupport, linewidth=2) // Long/short condition longCondition = close > superTrend shortCondition = close < superTrend // See if intraday session is active bool intradaySession = barInSession(i_marketSession) // Trade only if intraday session is active // Long position // When longCondition and intradaySession both are true strategy.entry(id = "Long", direction = strategy.long, when = longCondition and intradaySession) // Short position // When shortCondition and intradaySession both are true strategy.entry(id = "Short", direction = strategy.short, when = shortCondition and intradaySession) // Square-off position (when session is over and position is open) squareOff = (not intradaySession) and (strategy.position_size != 0) strategy.close_all(when = squareOff, comment = "Square-off") // ********** Strategy - End **********
TEMA Cross +HTF Backtest
https://www.tradingview.com/script/MwMvOaZD-TEMA-Cross-HTF-Backtest/
Seltzer_
https://www.tradingview.com/u/Seltzer_/
76
strategy
4
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © Seltzer_ //@version=4 strategy(title="TEMA Cross +HTF Backtest", shorttitle="TEMA_X_+HTF_BT", overlay=true, commission_type=strategy.commission.percent, commission_value=0, initial_capital = 500, default_qty_type=strategy.cash, default_qty_value=500) orderType = input("Longs+Shorts",title="What type of Orders", options=["Longs+Shorts","LongsOnly","ShortsOnly"]) isLong = (orderType != "ShortsOnly") isShort = (orderType != "LongsOnly") // Backtest Section { // Backtest inputs FromMonth = input(defval=1, title="From Month", minval=1, maxval=12) FromDay = input(defval=1, title="From Day", minval=1, maxval=31) FromYear = input(defval=2020, title="From Year", minval=2010) ToMonth = input(defval=1, title="To Month", minval=1, maxval=12) ToDay = input(defval=1, title="To Day", minval=1, maxval=31) ToYear = input(defval=9999, title="To Year", minval=2017) // Define backtest timewindow start = timestamp(FromYear, FromMonth, FromDay, 00, 00) // backtest start window finish = timestamp(ToYear, ToMonth, ToDay, 23, 59) // backtest finish window window() => // create function "within window of time" time >= start and time <= finish ? true : false // } //TEMA Section { //LTF Section xLength = input(20, minval=1, title="Fast Length") xPrice = close xEMA1 = ema(xPrice, xLength) xEMA2 = ema(xEMA1, xLength) xEMA3 = ema(xEMA2, xLength) xnRes = (3 * xEMA1) - (3 * xEMA2) + xEMA3 xnResP = plot(xnRes, color=color.green, linewidth=2, title="TEMA1") yLength = input(60, minval=1, title="Slow Length") yPrice = close yEMA1 = ema(yPrice, yLength) yEMA2 = ema(yEMA1, yLength) yEMA3 = ema(yEMA2, yLength) ynRes = (3 * yEMA1) - (3 * yEMA2) + yEMA3 ynResP = plot(ynRes, color=color.red, linewidth=2, title="TEMA2") fill(xnResP, ynResP, color=xnRes > ynRes ? color.green : color.red, transp=65, editable=true) //HTF Section HTFres = input(defval="D", type=input.resolution, title="HTF Resolution") f_secureSecurity(_symbol, _res, _src) => security(_symbol, _res, _src[1], lookahead = barmerge.lookahead_on) HTFxLength = input(5, minval=1, title="HTF Fast Length") HTFxPrice = close HTFxEMA1 = f_secureSecurity(syminfo.tickerid, HTFres, ema(HTFxPrice, HTFxLength)) HTFxEMA2 = f_secureSecurity(syminfo.tickerid, HTFres, ema(HTFxEMA1, HTFxLength)) HTFxEMA3 = f_secureSecurity(syminfo.tickerid, HTFres, ema(HTFxEMA2, HTFxLength)) HTFxnRes = (3 * HTFxEMA1) - (3 * HTFxEMA2) + HTFxEMA3 HTFxnResP = plot(HTFxnRes, color=color.yellow, linewidth=1,transp=30, title="TEMA1") HTFyLength = input(15, minval=1, title="HTF Slow Length") HTFyPrice = close HTFyEMA1 = f_secureSecurity(syminfo.tickerid, HTFres, ema(HTFyPrice, HTFyLength)) HTFyEMA2 = f_secureSecurity(syminfo.tickerid, HTFres, ema(HTFyEMA1, HTFyLength)) HTFyEMA3 = f_secureSecurity(syminfo.tickerid, HTFres, ema(HTFyEMA2, HTFyLength)) HTFynRes = (3 * HTFyEMA1) - (3 * HTFyEMA2) + HTFyEMA3 HTFynResP = plot(HTFynRes, color=color.purple, linewidth=1, transp=30, title="TEMA2") // HTF Plot fill(HTFxnResP, HTFynResP, color=HTFxnRes > HTFynRes ? color.yellow : color.purple, transp=90, editable=true) bgcolor(HTFxnRes > HTFynRes ? color.yellow : na, transp=90, editable=true) bgcolor(HTFxnRes < HTFynRes ? color.purple : na, transp=90, editable=true) // } // Buy and Sell Triggers LongEntryAlert = xnRes > ynRes and HTFxnRes > HTFynRes and window() LongCloseAlert = xnRes < ynRes and window() ShortEntryAlert = xnRes < ynRes and HTFxnRes < HTFynRes and window() ShortCloseAlert = xnRes > ynRes // Entry & Exit signals if isLong strategy.entry("Long", strategy.long, when = LongEntryAlert) strategy.close("Long", when = LongCloseAlert) if isShort strategy.entry("Short", strategy.short, when = ShortEntryAlert) strategy.close("Short", when = ShortCloseAlert)
Volume Extra (@ulong_Mask)
https://www.tradingview.com/script/ORSD69qJ-Volume-Extra-ulong-Mask/
ulong_Mask
https://www.tradingview.com/u/ulong_Mask/
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/ // © ulong_Mask //@version=4 strategy(title='Volume Extra (@ulong_Mask)', calc_on_every_tick=true) maxvol = input(20000, minval=1, title="MaxVol") lw = input(3, minval=1, title="LineWidth") f_buy() => if(close >= open) color.green f_sell() => if(open > close) color.red f_extra() => if(volume > maxvol) color.yellow plot(volume, title="Buy",style=plot.style_histogram,linewidth=lw,color = f_buy()) plot(volume, title="Sell",style=plot.style_histogram,linewidth=lw,color = f_sell()) plot(volume, title="Volume Extra",style=plot.style_histogram,linewidth=lw,color = f_extra())
Qullamaggie Breakout
https://www.tradingview.com/script/cDCAPrd1-Qullamaggie-Breakout/
millerrh
https://www.tradingview.com/u/millerrh/
528
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/ // © millerrh // The intent of this strategy is to buy breakouts with a tight stop on smaller timeframes in the direction of the longer term trend. // Then use a trailing stop of a close below either the 10 MA or 20 MA (user choice) on that larger timeframe as the position // moves in your favor (i.e. whenever position price rises above the MA). // Option of using daily ATR as a measure of finding contracting ranges and ensuring a decent risk/reward. // (If the difference between the breakout point and your stop level is below a certain % of ATR, it could possibly find those consolidating periods.) //@version=4 strategy("Qullamaggie Breakout", overlay=true, initial_capital=10000, currency='USD', default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=0.1) // === BACKTEST RANGE === Start = input(defval = timestamp("01 Jan 2019 06:00 +0000"), title = "Backtest Start Date", type = input.time) Finish = input(defval = timestamp("01 Jan 2100 00:00 +0000"), title = "Backtest End Date", type = input.time) // Inputs lb = input(defval = 3, title = "Lookback Period for Swing High", minval = 1, tooltip = "Lookback period for defining the breakout level.") lbStop = input(defval = 3, title = "Lookback Bars for Stop Level", minval = 1, tooltip = "Initial stop placement is the lowest low this many bars back. Allows for tighter stop placement than referencing swing lows.") htf = input(defval="D", title="Timeframe of Moving Averages", type=input.resolution, tooltip = "Allows you to set a different time frame for the moving averages. The default behavior is to identify good tightening setups on a larger timeframe (like daily) and enter the trade on a breakout occuring on a smaller timeframe, using the moving averages of the larger timeframe to trail your stop.") maType = input(defval="SMA", options=["EMA", "SMA"], title = "Moving Average Type") ma1Length = input(defval = 10, title = "1st Moving Average Length", minval = 1) ma2Length = input(defval = 20, title = "2nd Moving Average Length", minval = 1) ma3Length = input(defval = 50, title = "3rd Moving Average Length", minval = 1) useMaFilter = input(title = "Use 3rd Moving Average for Filtering?", type = input.bool, defval = true, tooltip = "Signals will be ignored when price is under this slowest moving average. The intent is to keep you out of bear periods and only buying when price is showing strength or trading with the longer term trend.") trailMaInput = input(defval="2nd Moving Average", options=["1st Moving Average", "2nd Moving Average"], title = "Trailing Stop") // MA Calculations ma(maType, src, length) => maType == "EMA" ? ema(src, length) : sma(src, length) //Ternary Operator (if maType equals EMA, then do ema calc, else do sma calc) ma1 = security(syminfo.tickerid, htf, ma(maType, close, ma1Length)) ma2 = security(syminfo.tickerid, htf, ma(maType, close, ma2Length)) ma3 = security(syminfo.tickerid, htf, ma(maType, close, ma3Length)) plot(ma1, color=color.purple, style=plot.style_line, title="MA1", linewidth=2, transp = 60) plot(ma2, color=color.yellow, style=plot.style_line, title="MA2", linewidth=2, transp = 60) plot(ma3, color=color.white, style=plot.style_line, title="MA3", linewidth=2, transp = 60) // === USE ATR FOR FILTERING === // The idea here is that you want to buy in a consolodating range for best risk/reward. So here you can compare the current distance between // support/resistance vs.the ATR and make sure you aren't buying at a point that is too extended from normal. useAtrFilter = input(title = "Use ATR for Filtering?", type = input.bool, defval = false, tooltip = "Signals will be ignored if the distance between support and resistance is larger than a user-defined percentage of Daily ATR. This allows the user to ensure they are not buying something that is too extended and instead focus on names that are consolidating more.") atrPerc = input(defval = 100, title = "% of Daily ATR Value", minval = 1) atrValue = security(syminfo.tickerid, "D", atr(14))*atrPerc*.01 // === PLOT SWING HIGH/LOW AND MOST RECENT LOW TO USE AS STOP LOSS EXIT POINT === // Change these values to adjust the look back and look forward periods for your swing high/low calculations pvtLenL = lb pvtLenR = lb // Get High and Low Pivot Points pvthi_ = pivothigh(high, pvtLenL, pvtLenR) pvtlo_ = pivotlow(low, pvtLenL, pvtLenR) // Force Pivot completion before plotting. Shunt = 1 //Wait for close before printing pivot? 1 for true 0 for flase maxLvlLen = 0 //Maximum Extension Length pvthi = pvthi_[Shunt] pvtlo = pvtlo_[Shunt] // Count How many candles for current Pivot Level, If new reset. counthi = barssince(not na(pvthi)) countlo = barssince(not na(pvtlo)) pvthis = fixnan(pvthi) pvtlos = fixnan(pvtlo) hipc = change(pvthis) != 0 ? na : color.maroon lopc = change(pvtlos) != 0 ? na : color.green // Display Pivot lines plot((maxLvlLen == 0 or counthi < maxLvlLen) ? pvthis : na, color=hipc, transp=0, linewidth=1, offset=-pvtLenR-Shunt, title="Top Levels") // plot((maxLvlLen == 0 or countlo < maxLvlLen) ? pvtlos : na, color=lopc, transp=0, linewidth=1, offset=-pvtLenR-Shunt, title="Bottom Levels") plot((maxLvlLen == 0 or counthi < maxLvlLen) ? pvthis : na, color=hipc, transp=0, linewidth=1, offset=0, title="Top Levels 2") // plot((maxLvlLen == 0 or countlo < maxLvlLen) ? pvtlos : na, color=lopc, transp=0, linewidth=1, offset=0, title="Bottom Levels 2") // BUY CONDITIONS stopLevelCalc = valuewhen(pvtlo_, low[pvtLenR], 0) //Stop Level at Swing Low buyLevel = valuewhen(pvthi_, high[pvtLenR], 0) //Buy level at Swing High plot(buyLevel, style=plot.style_line, color=color.blue, title = "Current Breakout Level", show_last=1, linewidth=1, transp=50, trackprice=true) // Conditions for entry and exit stopLevel = float(na) // Define stop level here as "na" so that I can reference it in the inPosition // variable and the ATR calculation before the stopLevel is actually defined. buyConditions = (useMaFilter ? buyLevel > ma3 : true) and (useAtrFilter ? (buyLevel - stopLevel[1]) < atrValue : true) and time > Start and time < Finish // buySignal = high > buyLevel and buyConditions buySignal = crossover(high, buyLevel) and buyConditions trailMa = trailMaInput == "1st Moving Average" ? ma1 : ma2 sellSignal = crossunder(close, trailMa) // sellSignal = security(syminfo.tickerid, htf, close < trailMa) and security(syminfo.tickerid, htf, close[1] < trailMa) // STOP AND PRICE LEVELS inPosition = bool(na) inPosition := buySignal[1] ? true : sellSignal[1] ? false : low <= stopLevel[1] ? false : inPosition[1] lowDefine = lowest(low, lbStop) stopLevel := inPosition ? stopLevel[1] : lowDefine // plot(stopLevel) buyPrice = buyLevel buyPrice := inPosition ? buyPrice[1] : buyLevel plot(stopLevel, style=plot.style_line, color=color.orange, title = "Current Stop Level", show_last=1, linewidth=1, transp=50, trackprice=true) plot(inPosition ? stopLevel : na, style=plot.style_circles, color=color.orange, title = "Historical Stop Levels", transp=50, trackprice=false) // plot(buyPrice, style=plot.style_line, color=color.blue, linewidth=1, transp=50, trackprice=true) // (STRATEGY ONLY) Comment out for Study strategy.entry("Long", strategy.long, stop = buyLevel, when = buyConditions) strategy.exit("Exit Long", from_entry = "Long", stop=stopLevel[1]) if (low[1] > trailMa) strategy.close("Long", when = sellSignal) // if (low[1] > trailMa) // strategy.exit("Exit Long", from_entry = "Long", stop=trailMa) //to get this to work right, I need to reference highest highs instead of swing highs //because it can have me buy right back in after selling if the stop level is above the last registered swing high point.
[EURUSD60] BB Expansion Strategy
https://www.tradingview.com/script/7yPV3OPU/
kasaism
https://www.tradingview.com/u/kasaism/
50
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/ // © kasaism //@version=4 strategy(title="[EURUSD60] BB Expansion Strategy", shorttitle="[EURUSD60] BBEXP",overlay=true, max_bars_back=5000, max_labels_count=500) // === INPUTS === // ////BB largeBbRes = input(title="Large BB Resolution", type=input.resolution, defval="", group="BB") largeBbLength = input(title="Large BB Length", type=input.integer, defval=40, minval=1, group="BB") smallBbRes = input(title="Small BB Resolution ", type=input.resolution, defval="", group="BB") smallBbLength = input(title="Small BB Length", type=input.integer, defval=20, minval=1, group="BB") multi = input(title="BB StdDev", type=input.float, defval=2.0, maxval=10, minval=0.01, group="BB") validLen = input(title="BB expand valid length", defval=14, group="BB") // 3 each EMA settings. EMA directions are as each time frame directions. resFirstTime = input(title="EMA Trend t/f", type=input.resolution, defval="240", group="SMT") // resSecondTime = input(title="Second t/f", type=input.resolution, defval="30", group="SMT") // resThirdTime = input(title="Third t/f", type=input.resolution, defval="", group="SMT") emaLen = input(14, minval=1, title="Length", group="SMT") smooth = input(3, minval=1, title="Smooth factor", group="SMT") //Lisk Management var riskManagementRule1 = "ATR" var riskManagementRule2 = "Bracket" riskManagementRule = input(riskManagementRule1, "Detect Risk Management Based On", options=[riskManagementRule1, riskManagementRule2, "No detection"], group="Trade") atrMulti = input(3.0, title="ATR Multiple", type=input.float, minval = 1.0, group="ATR") riskRewardRatio = input(1.5, title="Risk Reward Ratio for ATR", type=input.float, minval = 0.01, group="ATR") stopLossPoint = input(100, title="Stop Loss Point for Braket(tick)", type=input.float, minval = 1.0, group="Bracket") takeProfitPoint = input(200, title="Take Profit Point for Braket(tick)", type=input.float, minval = 1.0, group="Bracket") // === /INPUTS/ === // // === CONSTANT === // //For barmerge.lookahead_off index = barstate.isrealtime ? 1 : 0 //For Entry NOENTRY=0 LONG=1 SHORT=2 //SMT color int up=1 int dn=2 int up_HL=3 int dn_HL=4 //label color color_bearish = color.red color_bullish = color.blue C_label_color_bearish = color.red C_label_color_bullish = color.blue // === /CONSTANT/ === // // === FUNCTIONS === // //BB trade direction bbTradeDetection(lrgUpper, lrgLower, smlUpper, smlLower) => if not(na(lrgUpper) or na(lrgLower) or na(smlUpper) or na(smlLower)) if lrgUpper < smlUpper and lrgLower > smlLower true else false else na // === /FUNCTIONS/ === // // === CALCURATES === // ////BB //large BB lrgBbBasis = security(syminfo.tickerid, largeBbRes, sma(close[index], largeBbLength)) lrgBbDev = multi * security(syminfo.tickerid, largeBbRes, stdev(close[index], largeBbLength)) lrgBbUpper = lrgBbBasis + lrgBbDev lrgBbLower = lrgBbBasis - lrgBbDev //small BB smlBbBasis = security(syminfo.tickerid, smallBbRes, sma(close[index], smallBbLength)) smlBbDev = multi * security(syminfo.tickerid, smallBbRes, stdev(close[index], smallBbLength)) smlBbUpper = smlBbBasis + smlBbDev smlBbLower = smlBbBasis - smlBbDev bbTrade = bbTradeDetection(lrgBbUpper, lrgBbLower, smlBbUpper, smlBbLower) //EMA Trend base=security(syminfo.tickerid, resFirstTime, ema(close[index],emaLen)) sig=security(syminfo.tickerid, resFirstTime, ema(base[index],smooth)) emaTrend = not(na(base) or na(sig)) ? base < sig ? dn : up : na ////LISK MANAGEMENT float stopLossLineForLong = na float stopLossLineForShort = na float takeProfitLineForLong = na float takeProfitLineForShort = na atr_ = atr(14) * atrMulti if riskManagementRule == riskManagementRule1 stopLossLineForLong := strategy.position_size > 0 ? stopLossLineForLong[1] ? stopLossLineForLong[1] : round(close[index] - atr_,3) : na stopLossLineForShort := strategy.position_size < 0 ? stopLossLineForShort[1] ? stopLossLineForShort[1] : round(close[index] + atr_,3) : na takeProfitLineForLong := strategy.position_size > 0 ? takeProfitLineForLong[1] ? takeProfitLineForLong[1] : close[index] + atr_*riskRewardRatio : na takeProfitLineForShort := strategy.position_size < 0 ? takeProfitLineForShort[1] ? takeProfitLineForShort[1] :close[index] - atr_*riskRewardRatio : na if riskManagementRule == riskManagementRule2 stopLossLineForLong := strategy.position_size > 0 ? stopLossLineForLong[1] ? stopLossLineForLong[1] : close[index] - stopLossPoint * syminfo.mintick : na stopLossLineForShort := strategy.position_size < 0 ? stopLossLineForShort[1] ? stopLossLineForShort[1] : close[index] + stopLossPoint * syminfo.mintick : na takeProfitLineForLong := strategy.position_size > 0 ? takeProfitLineForLong[1] ? takeProfitLineForLong[1] : close[index] +takeProfitPoint * syminfo.mintick : na takeProfitLineForShort := strategy.position_size < 0 ? takeProfitLineForShort[1] ? takeProfitLineForShort[1] :close[index] - takeProfitPoint * syminfo.mintick : na // === /CALCURATES/ === // // === CONDITIONS === // //BB bool isBbEntry = na for i=0 to validLen isBbEntry := bbTrade==true ? true : bbTrade[i]==true ? true : false //plotshape(isBbEntry, style=shape.circle, location=location.bottom) isBbLong = isBbEntry and open[index] < smlBbBasis[index] and close[index] > smlBbBasis[index] isBbShort = isBbEntry and open[index] > smlBbBasis[index] and close[index] < smlBbBasis[index] //SMT isEmaLong = emaTrend == up isEmaShort = emaTrend == dn //ATR isAtrLongStop = low[index] <= stopLossLineForLong isAtrShortStop = high[index] >= stopLossLineForShort isAtrLongLimit = high[index] >= takeProfitLineForLong isAtrShortLimit = low[index] <= takeProfitLineForShort // === /CONDITIONS/ === // // === TRADE === // //ENTRY if (isBbLong and isEmaLong) strategy.entry("LongEntry", strategy.long, 1000000, comment="LongEntry") if riskManagementRule == riskManagementRule2 strategy.exit("LongEntry", loss=stopLossPoint, profit=takeProfitPoint, comment="bracket") if (isBbShort and isEmaShort) strategy.entry("ShortEntry", strategy.short, 1000000, comment="ShortEntry") if riskManagementRule == riskManagementRule2 strategy.exit("ShortEntry", loss=stopLossPoint, profit=takeProfitPoint, comment="bracket") //EXIT if riskManagementRule == riskManagementRule1 if(isAtrLongStop) strategy.close("LongEntry", when=isAtrLongStop, comment="ATR Stop") if(isAtrShortStop) strategy.close("ShortEntry", when=isAtrShortStop, comment="ATR Stop") if(isAtrLongLimit) strategy.close("LongEntry", when=isAtrLongLimit, comment="ATR Limit") if(isAtrShortLimit) strategy.close("ShortEntry", when=isAtrShortLimit, comment="ATR Limit") // === /TRADE/ === // // === PLOTS === // plot(lrgBbBasis, title="Large BB Basis", linewidth=2, color=color.gray) plot(lrgBbUpper, title="Large BB Upper", linewidth=2, color=color.gray) plot(lrgBbLower, title="Large BB Lower", linewidth=2, color=color.gray) plot(smlBbBasis, title="Small BB Basis", color=color.white) plot(smlBbUpper, title="Small BB Upper", color=color.white) plot(smlBbLower, title="Small BB Lower", color=color.white) plot(base, title="EMA Line", color= emaTrend==dn ? color_bearish : emaTrend==up ? color_bullish : color.gray) plot(stopLossLineForLong ? stopLossLineForLong : na, title="S/L Line For Long", color=color.yellow, style=plot.style_circles) plot(stopLossLineForShort ? stopLossLineForShort : na, title="S/L Line For Short", color=color.yellow, style=plot.style_circles) plot(takeProfitLineForLong ? takeProfitLineForLong : na, title="T/P Line For Long", color=color.purple, style=plot.style_circles) plot(takeProfitLineForShort ? takeProfitLineForShort : na, title="T/P Line For Short", color=color.purple, style=plot.style_circles) // /=== PLOTS ===/ //