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
|
---|---|---|---|---|---|---|---|---|
Combining Trailing Stop and Stop loss (% of instrument price) | https://www.tradingview.com/script/FQCEN1Ka-Combining-Trailing-Stop-and-Stop-loss-of-instrument-price/ | wouterpruym1828 | https://www.tradingview.com/u/wouterpruym1828/ | 98 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © wouterpruym1828
//DISCLAIMER: This is not a trading strategy. Rather, it is a template from which you can take chunks of code and implement them in your own script.
//I do not take any responsibility in case of resulting losses while using parts of this script or the script as a whole. It is up to the user to decide how to use this script,
//thereby assuming full responsibility in the risks taken while trading.
//@version=5
strategy(title=" Combining Trailing Stop, Take Profit and Stop loss (% of instrument price)",
overlay=true, pyramiding=1, shorttitle="TSL&TP&SL%")
//INDICATOR SECTION
// Indicator Input options+
i_FastEMA = input.int(title = "Fast EMA period", minval = 0, defval = 20)
i_SlowEMA = input.int(title = "Slow EMA period", minval = 0, defval = 50)
// Calculate moving averages
fastEMA = ta.ema(close, i_FastEMA)
slowEMA = ta.ema(close, i_SlowEMA)
// Plot moving averages
plot(fastEMA, title="Fast SMA", color=color.blue)
plot(slowEMA, title="Slow SMA", color=color.orange)
//STRATEGY SECTION
// Calculate trading conditions
buy = ta.crossover(fastEMA, slowEMA)
sell = ta.crossunder(fastEMA, slowEMA)
// STEP 1:
// Configure trail stop loss level with input options (optional)
longTrailPerc = input.float(title="Long Trailing Stop (%)", minval=0.0, step=0.1, defval=7) * 0.01
shortTrailPerc = input.float(title="Short Trailing Stop (%)", minval=0.0, step=0.1, defval=7) * 0.01
//Configure stop loss level with input options (optional)
longStopPerc = input.float(title="Long Stop Loss (%)", minval=0.0, step=0.1, defval=2)*0.01
shortStopPerc = input.float(title="Short Stop Loss (%)", minval=0.0, step=0.1, defval=2)*0.01
//Configure take profit price level and take profit ratio with input options (optional)
longTpPerc = input.float(title="Long Take Profit (%)", minval=0.0, step=0.1, defval=2)
shortTpPerc = input.float(title="Short Take Profit (%)", minval=0.0, step=0.1, defval=2)
TP_Ratio = input.float(title="Unwind Postion Size % @ TP", defval=50, step=1, tooltip="Example: 50 closing 50% of the position once TP is reached")/100
//Configure stop loss after take profit with input options (optional)
longStopTpPerc = input.float(title="Long Stop Loss after TP", minval=0.0, step=0.1, defval=1)
shortStopTpPerc = input.float(title="Short Stop Loss after TP", minval=0.0, step=0.1, defval=1)
// STEP 2:
// Determine trail stop loss prices
longTrailPrice = 0.0, shortTrailPrice = 0.0
longTrailPrice := if (strategy.position_size > 0)
stopValue = high * (1 - longTrailPerc)
math.max(stopValue, longTrailPrice[1])
else
0
shortTrailPrice := if (strategy.position_size < 0)
stopValue = low * (1 + shortTrailPerc)
math.min(stopValue, shortTrailPrice[1])
else
999999
//Determine entry price
entryPrice = 0.0
entryPrice := strategy.opentrades.entry_price(strategy.opentrades - 1)
//Determine stop loss after reaching TP
longStopTP = 0.0, shortStopTP = 0.0
longStopTP := entryPrice + (entryPrice * (longStopTpPerc / 100))
shortStopTP := entryPrice - (entryPrice * (shortStopTpPerc / 100))
// Determine take profit prices
percentAsPoints(pcnt) =>
strategy.position_size != 0 ? math.round(pcnt / 100.0 * strategy.position_avg_price / syminfo.mintick) : float(na)
percentAsPrice(pcnt) =>
strategy.position_size != 0 ? ((pcnt / 100.0) + 1.0) * strategy.position_avg_price : float(na)
current_position_size = math.abs(strategy.position_size)
initial_position_size = math.abs(ta.valuewhen(strategy.position_size[1] == 0.0, strategy.position_size, 0))
longTP = strategy.position_avg_price + percentAsPoints(longTpPerc) * syminfo.mintick * strategy.position_size / math.abs(strategy.position_size)
bool stageLongTP = false
if high > longTP
stageLongTP := true
shortTP = strategy.position_avg_price + percentAsPoints(shortTpPerc) * syminfo.mintick * strategy.position_size / math.abs(strategy.position_size)
bool stageShortTP = false
if low < shortTP
stageShortTP := true
// Determine stop loss prices
longLossPrice = entryPrice * (1 - longStopPerc)
shortLossPrice = entryPrice * (1 + shortStopPerc)
// Plot trail stop, stop loss and take profit values for confirmation
plot(entryPrice, color=color.black, style=plot.style_cross, linewidth=2, title="Entry Price")
plot(series=(strategy.position_size > 0) ? longTrailPrice : na,
color=color.fuchsia, style=plot.style_cross,
linewidth=2, title="Long Trail Stop")
plot(series=(strategy.position_size < 0) ? shortTrailPrice : na,
color=color.fuchsia, style=plot.style_cross,
linewidth=2, title="Short Trail Stop")
plot(series=(strategy.position_size > 0) ? longLossPrice : na,
color=color.olive, style=plot.style_cross,
linewidth=2, title="Long Stop Loss")
plot(series=(strategy.position_size < 0) ? shortLossPrice : na,
color=color.olive, style=plot.style_cross,
linewidth=2, title="Short Stop Loss")
plot(series=(strategy.position_size > 0) ? longTP : na,
color=color.green, style=plot.style_cross,
linewidth=2, title="Long TP")
plot(series=(strategy.position_size < 0) ? shortTP : na,
color=color.green, style=plot.style_cross,
linewidth=2, title="Short TP")
plot(series=(strategy.position_size > 0) ? longStopTP : na,
color=color.aqua, style=plot.style_cross,
linewidth=2, title="Long TP Stop Loss")
plot(series=(strategy.position_size < 0) ? shortStopTP : na,
color=color.aqua, style=plot.style_cross,
linewidth=2, title="Short TP Stop Loss")
// Submit entry orders
if (buy)
strategy.entry("Buy", strategy.long)
if (sell)
strategy.entry("Sell", strategy.short)
//Evaluating trailing stop, stop after take profit or stop loss to use,
var longStopPrice = 0.0
if strategy.position_avg_price < longTP
if longTrailPrice < longLossPrice
longStopPrice := longLossPrice
else if longTrailPrice > longLossPrice
longStopPrice := longTrailPrice
if stageLongTP == true
if longTrailPrice < longStopTP
longStopPrice := longStopTP
else if longTrailPrice > longStopTP
longStopPrice := longTrailPrice
var shortStopPrice = 0.0
if strategy.position_avg_price > shortTP
if shortTrailPrice > shortLossPrice
shortStopPrice := shortLossPrice
else if shortTrailPrice < shortLossPrice
shortStopPrice := shortTrailPrice
if stageShortTP == true
if shortTrailPrice > shortStopTP
shortStopPrice := shortStopTP
else if shortTrailPrice < shortStopTP
shortStopPrice := shortTrailPrice
// STEP 3:
// Submit exit orders for take profit (stop loss moves to entry price) and stop price
if (strategy.position_size > 0)
strategy.exit(id="Buy TP", qty = initial_position_size * TP_Ratio, limit = longTP)
strategy.exit(id="Buy Stop", stop=longStopPrice)
if (strategy.position_size < 0)
strategy.exit(id="Sell TP", qty = initial_position_size * TP_Ratio, limit = shortTP)
// shortLossPrice := shortStopTP
strategy.exit(id="Sell Stop", stop=shortStopPrice)
|
STRATEGY R18-F-BTC | https://www.tradingview.com/script/hblG106q-STRATEGY-R18-F-BTC/ | SenatorVonShaft | https://www.tradingview.com/u/SenatorVonShaft/ | 82 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © onurenginogutcu
//@version=4
strategy("STRATEGY R18-F-BTC", overlay=true, margin_long=100, margin_short=100)
///////////default girişler 1 saatlik btc grafiği için geçerli olmak üzere - stop loss'lar %2.5 - long'da %7.6 , short'ta %8.1
sym = input(title="Symbol", type=input.symbol, defval="BINANCE:BTCUSDT") /////////btc'yi indikatör olarak alıyoruz
lsl = input(title="Long Stop Loss (%)",
minval=0.0, step=0.1, defval=2.5) * 0.01
ssl = input(title="Short Stop Loss (%)",
minval=0.0, step=0.1, defval=2.5) * 0.01
longtp = input(title="Long Take Profit (%)",
minval=0.0, step=0.1, defval=7.6) * 0.01
shorttp = input(title="Short Take Profit (%)",
minval=0.0, step=0.1, defval=7.5) * 0.01
capperc = input(title="Capital Percentage to Invest (%)",
minval=0.0, maxval=100, step=0.1, defval=90) * 0.01
choice = input(title="Reverse ?", type=input.bool, defval=false)
symClose = security(sym, "", close)
symHigh = security(sym, "", high)
symLow = security(sym, "", low)
i = ema (symClose , 15) - ema (symClose , 30) ///////// ema close 15 ve 30 inanılmaz iyi sonuç verdi (macd standartı 12 26)
r = ema (i , 9)
sapust = highest (i , 100) * 0.729 //////////0.729 altın oran oldu 09.01.2022
sapalt = lowest (i , 100) * 0.729 //////////0.729 altın oran oldu 09.01.2022
///////////highx = highest (close , 365) * 0.72 fibo belki dahiledilebilir
///////////lowx = lowest (close , 365) * 1.272 fibo belki dahil edilebilir
simRSI = rsi (symClose , 50 ) /////// RSI DAHİL EDİLDİ "50 MUMLUK RSI EN İYİ SONUCU VERİYOR"
//////////////fibonacci seviyesi eklenmesi amacı ile koyuldu fakat en iyi sonuç %50 seviyesinin altı ve üstü (low ve high 38 barlık) en iyi sonuç verdi
fibvar = 38
fibtop = lowest (symLow , fibvar) + ((highest (symHigh , fibvar) - lowest (symLow , fibvar)) * 0.50)
fibbottom = lowest (symLow , fibvar) + ((highest (symHigh , fibvar) - lowest (symLow , fibvar)) * 0.50)
///////////////////////////////////////////////////////////// INDICATOR CONDITIONS
longCondition = crossover(i, r) and i < sapalt and symClose < sma (symClose , 50) and simRSI < sma (simRSI , 50) and symClose < fibbottom
shortCondition = crossunder(i, r) and i > sapust and symClose > sma (symClose , 50) and simRSI > sma (simRSI , 50) and symClose > fibtop
////////////////////////////////////////////////////////////////
///////////////////////////////////////////STRATEGY ENTRIES AND STOP LOSSES /////stratejilerde kalan capital için strategy.equity kullan (bunun üzerinden işlem yap)
if (choice == false and longCondition)
strategy.entry("Long", strategy.long , qty = capperc * strategy.equity / close , when = strategy.position_size == 0)
if (choice == false and shortCondition)
strategy.entry("Short" , strategy.short , qty = capperc * strategy.equity / close , when = strategy.position_size == 0)
if (choice == true and longCondition)
strategy.entry("Short" , strategy.short , qty = capperc * strategy.equity / close , when = strategy.position_size == 0)
if (choice == true and shortCondition)
strategy.entry("Long", strategy.long , qty = capperc * strategy.equity / close , when = strategy.position_size == 0)
if (strategy.position_size > 0)
strategy.exit("Exit Long", "Long", stop=strategy.position_avg_price*(1 - lsl) , limit=strategy.position_avg_price*(1 + longtp))
if (strategy.position_size < 0)
strategy.exit("Exit Short", "Short", stop=strategy.position_avg_price*(1 + ssl) , limit=strategy.position_avg_price*(1 - shorttp))
////////////////////////vertical colouring signals
bgcolor(color=longCondition ? color.new (color.green , 70) : na)
bgcolor(color=shortCondition ? color.new (color.red , 70) : na)
|
Co-relation and St-deviation Strategy - BNB/USDT 15min | https://www.tradingview.com/script/ty2KzvVR-Co-relation-and-St-deviation-Strategy-BNB-USDT-15min/ | pcooma | https://www.tradingview.com/u/pcooma/ | 316 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © pcooma
//version 35
//@version=5
strategy("OPV15 V2 (Duplicate of Used for Signal Generation) - Co-relation and St-deviation Strategy - BNB/USDT 15min", shorttitle="OPV15 V2 Duplicate CS - BNB 15min", overlay=true, calc_on_order_fills=false, close_entries_rule = "FIFO", calc_on_every_tick=false, initial_capital = 1000,pyramiding = 999,precision = 4, process_orders_on_close=true, currency = currency.USD, default_qty_type = strategy.cash, default_qty_value = 33, commission_type = strategy.commission.percent, max_lines_count = 500, commission_value = 0.1)
//Backtest dates
fromDay = input.int(defval = 25, title = "From (DD/MM/YYYY) - ", minval = 1, maxval = 31, group = 'Time Period Values', inline = 'From')
fromMonth = input.int(defval = 02, title = "/", minval = 1, maxval = 12, group = 'Time Period Values', inline = 'From')
fromYear = input.int(defval = 2022, title = "/", minval = 1970, group = 'Time Period Values', inline = 'From')
thruDay = input.int(defval = 1, title = "Thru (DD/MM/YYYY) - ", minval = 1, maxval = 31, group = 'Time Period Values', inline = 'Thru')
thruMonth = input.int(defval = 1, title = "/", minval = 1, maxval = 12, group = 'Time Period Values', inline = 'Thru')
thruYear = input.int(defval = 2112, title = "/", minval = 1970, group = 'Time Period Values', inline = 'Thru')
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"
use_timeframe = input.bool(defval = true, title = "Use data window to limit trade")
var window = true
if use_timeframe == true
window := time >= start and time <= finish ? true : false
else
window := true
//Buy and Sell range
var factor_of_supertrend_to_determine_sell_comand = input.int (defval = 1, title = "Factor of supertrend to determine buy command", group = "Determination of buy or sell command")
var artperiod_of_supertrend_to_determine_sell_comand = input.int (defval = 24, title = "ArtPeriod of supertrend to determine buy command", group = "Determination of buy or sell command")
buy_comand_high_value = input (defval = high, title = "Source of Higher value of Look back period", group = "Determination of buy or sell command")
buy_comand_low_value = input (defval = low, title = "Source of Lower value of Look back period", group = "Determination of buy or sell command")
var buy_or_sell_lookback = input.int (defval = 280, title = "Look back period to determine lower low points", group = "Determination of buy or sell command")
source_of_lower_point = input (defval = open, title = "Source of Lower point to initiate purchase", group = "Determination of buy or sell command")
// Calculation of profit precentage
var profit_precentage = input.float (defval = 7, title = "Profit precentage will be", group = "Profit Calculations", step = 0.01)
var intermidiate_selling = input (defval = false, title = "Enable Swing Trading", group = "Profit Calculations")
var profit_precentage_intermidiate = input.float (defval = 2, title = "Swing Trading profit precentage will be", group = "Profit Calculations", step = 0.01)
//Fund Management
var int_cap = input.float (defval = 1000, title = "Cumilative Investment", group = "Fund Management")
var purchaseing_method = input.string (defval ='Equal amounts', title = "Value of Purchas will be", group = "Fund Management", options=['Equal amounts','Incremental amounts'])
var dev_of_equal_amounts = input.string (defval ='Equal amounts with fixed USDT', title = "Value of Purchas will be", group = "Fund Management", options=['Equal amounts with fixed USDT','Equal amounts with fixed entries'])
var int_val_prc = input.float (defval = 44, title = "Value of first purchase will be", group = "Fund Management", tooltip = "Minimum value of initial purchase will be 15USDT", inline = "Investment")
var int_val_allocation = input.string (defval ='USDT', title = "", group = "Fund Management", options=['% of cumilative investment', 'USDT'], inline = "Investment")
var piramiding = input.int (defval = 35, title = "Numbers of pararal entries", group = "Fund Management")
var r = input.float (defval = 5, title = "r starting value", group = "Input parameters for fund management")
var r_change_input = input.int (defval = 1, title = "Initiative value for r change", group = "Input parameters for fund management")
var r_finetune = input.bool (defval = false, title = "Use r = 0.001 to finetune r value", group = "Input parameters for fund management")
var r_value = input.float (defval = 3.259, title = "Calculated r value", group = "Input parameters for fund management")
//Principle input
look_back_period = input.int (defval = 7, title = "General look back period for calculations", group = "Principle inputs")
source_of_price_average = input (defval = close, title = "Source of Average Price", group = "Principle inputs")
look_back_period_for_price_falling = input.int (defval = 3, title = "Look back period for price falling", group = "Principle inputs")
source_of_ma9 = input (defval = hl2, title = "Source of average price to determine selling and buying", group = "Principle inputs")
look_back_period_of_sma9 = input.int (defval = 3, title = "Look back period of average price to determine buy and sell", group = "Principle inputs")
ma_9_calculation = input.string (defval = 'Exponentially Weighted Moving Average (EMA)', title = "Calculation method of average price", group = "Principle inputs", options=['Lenior regression', 'Simple Moving Average (SMA)','Exponentially Weighted Moving Average (EMA)', 'Hull Moving Average (HMA)', 'Exponentially Weighted Moving average with alpha length (RMA)', 'Weighted Moving Average (WMA)', 'Arnaud Legoux Moving Average (ALMA)', 'Symmetrically weighted moving average with fixed length (SWMA)','Volume-weighted Moving Average (VWMA)'])
volume_profile_calculation = input.string (defval = 'Lenior regression', title = "Calculation method of volume profile", group = "Principle inputs", options=['Lenior regression', 'Simple Moving Average (SMA)','Exponentially Weighted Moving Average (EMA)', 'Hull Moving Average (HMA)', 'Exponentially Weighted Moving average with alpha length (RMA)', 'Weighted Moving Average (WMA)', 'Arnaud Legoux Moving Average (ALMA)', 'Symmetrically weighted moving average with fixed length (SWMA)','Volume-weighted Moving Average (VWMA)'])
//Parabolic SAR (parabolic stop and reverse)
var float sar_start_value = input.float (defval = 0.2, title = "Start value of SAR", group = "Parabolic Stop and Reverse (SAR)", minval = 0, step = 0.01)
var float sar_incrimant_value = input.float (defval = 0.2, title = "Increment value of SAR", group = "Parabolic Stop and Reverse (SAR)", minval = 0, step = 0.01)
var float sar_mac_value = input.float (defval = 0.2, title = "Max value of SAR", group = "Parabolic Stop and Reverse (SAR)", minval = 0, step = 0.01)
//Supertrend
var ST_factor_value = input.int (defval = 1, title = "Factor of Supertrend", group = "Supertrend", minval = 0, step = 1)
var ST_art_period_value = input.int (defval = 10, title = "ArtPeriod of Supertrend", group = "Supertrend", minval = 0, step = 1)
//Relative strength index (RSI)
source_of_rsi = input (defval = close, title = "Source of RSI", group = "Relative strength index (RSI)")
//Money flow index (MFI)
source_of_mfi = input (defval = close, title = "Source of MFI", group = "Money flow index (MFI)")
//Balance of Power
bop_calculation = input.string (defval='Lenior regression', title = "Calculation method of Balance of Power", group = "Balance of Power(BOP)", options=['Lenior regression', 'Simple Moving Average (SMA)','Exponentially Weighted Moving Average (EMA)', 'Hull Moving Average (HMA)', 'Exponentially Weighted Moving average with alpha length (RMA)', 'Weighted Moving Average (WMA)', 'Arnaud Legoux Moving Average (ALMA)', 'Symmetrically weighted moving average with fixed length (SWMA)','Volume-weighted Moving Average (VWMA)'])
//Chande Momentum Oscillator
source_of_mom = input (defval = close, title = "Source of MOM", group = "Chande Momentum Oscillator (MOM)")
//Center of Gravity (COG)
source_of_cog = input (defval = close, title = "Source of COG", group = "The Center of Gravity (COG)")
//Directional Movement Index (DMI)
var dmi_di_length = input.int (defval = 3, title = "DI Length", group = "Directional movement index (DMI)", minval = 0, step = 1)
var dmi_adx_smoothing_length = input.int (defval = 10, title = "ADX Smoothing length", group = "Directional movement index (DMI)", minval = 0, step = 1)
//Stochastic
source_of_stoch = input (defval = close, title = "Source of Stochastic", group = "Stochastic")
stoch_calculation = input.string (defval ='Lenior regression', title = "Calculation method of Stochastic", group = "Stochastic", options=['Lenior regression', 'Simple Moving Average (SMA)','Exponentially Weighted Moving Average (EMA)', 'Hull Moving Average (HMA)', 'Exponentially Weighted Moving average with alpha length (RMA)', 'Weighted Moving Average (WMA)', 'Arnaud Legoux Moving Average (ALMA)', 'Symmetrically weighted moving average with fixed length (SWMA)','Volume-weighted Moving Average (VWMA)'])
//Symmetrically weighted moving average with fixed length
source_of_swma = input (defval = close, title = "Source of SWMA", group = "Symmetrically weighted moving average with fixed length")
swma_calculation = input.string (defval ='Lenior regression', title = "Calculation method of SWMA", group = "Symmetrically weighted moving average with fixed length", options=['Lenior regression', 'Simple Moving Average (SMA)','Exponentially Weighted Moving Average (EMA)', 'Hull Moving Average (HMA)', 'Exponentially Weighted Moving average with alpha length (RMA)', 'Weighted Moving Average (WMA)', 'Arnaud Legoux Moving Average (ALMA)', 'Symmetrically weighted moving average with fixed length (SWMA)','Volume-weighted Moving Average (VWMA)'])
//True strength index (TSI)
source_of_tsi = input (defval = close, title = "Source of TSI", group = "True strength index (TSI)")
var tsi_short_length = input.int (defval = 14, title = "Short Length of TSI", group = "True strength index (TSI)", minval = 0, step = 1)
var tsi_long_length = input.int (defval = 28, title = "Long length of TSI", group = "True strength index (TSI)", minval = 0, step = 1)
//Williams %R
wpr_calculation = input.string (defval ='Exponentially Weighted Moving Average (EMA)', title = "Calculation method of Williams %R", group = "Williams %R", options=['NONE','Lenior regression', 'Simple Moving Average (SMA)','Exponentially Weighted Moving Average (EMA)', 'Hull Moving Average (HMA)', 'Exponentially Weighted Moving average with alpha length (RMA)', 'Weighted Moving Average (WMA)', 'Arnaud Legoux Moving Average (ALMA)', 'Symmetrically weighted moving average with fixed length (SWMA)','Volume-weighted Moving Average (VWMA)'])
//Accumulation/distribution index
accdist_calculation = input.string (defval ='Exponentially Weighted Moving Average (EMA)', title = "Calculation method of Accumulation/distribution Index", group = "Accumulation/distribution Index", options=['NONE','Lenior regression', 'Simple Moving Average (SMA)','Exponentially Weighted Moving Average (EMA)', 'Hull Moving Average (HMA)', 'Exponentially Weighted Moving average with alpha length (RMA)', 'Weighted Moving Average (WMA)', 'Arnaud Legoux Moving Average (ALMA)', 'Symmetrically weighted moving average with fixed length (SWMA)','Volume-weighted Moving Average (VWMA)'])
//Intraday Intensity Index
iii_calculation = input.string (defval ='Exponentially Weighted Moving Average (EMA)', title = "Calculation method of Intraday Intensity Index", group = "Intraday Intensity Index", options=['NONE','Lenior regression', 'Simple Moving Average (SMA)','Exponentially Weighted Moving Average (EMA)', 'Hull Moving Average (HMA)', 'Exponentially Weighted Moving average with alpha length (RMA)', 'Weighted Moving Average (WMA)', 'Arnaud Legoux Moving Average (ALMA)', 'Symmetrically weighted moving average with fixed length (SWMA)','Volume-weighted Moving Average (VWMA)'])
//Negative Volume Index
nvi_calculation = input.string (defval ='Exponentially Weighted Moving Average (EMA)', title = "Calculation method of Negative Volume Index", group = "Negative Volume Index", options=['NONE','Lenior regression', 'Simple Moving Average (SMA)','Exponentially Weighted Moving Average (EMA)', 'Hull Moving Average (HMA)', 'Exponentially Weighted Moving average with alpha length (RMA)', 'Weighted Moving Average (WMA)', 'Arnaud Legoux Moving Average (ALMA)', 'Symmetrically weighted moving average with fixed length (SWMA)','Volume-weighted Moving Average (VWMA)'])
//Positive Volume Index
pvi_calculation = input.string (defval ='Exponentially Weighted Moving Average (EMA)', title = "Calculation method of Positive Volume Index", group = "Positive Volume Index", options=['NONE','Lenior regression', 'Simple Moving Average (SMA)','Exponentially Weighted Moving Average (EMA)', 'Hull Moving Average (HMA)', 'Exponentially Weighted Moving average with alpha length (RMA)', 'Weighted Moving Average (WMA)', 'Arnaud Legoux Moving Average (ALMA)', 'Symmetrically weighted moving average with fixed length (SWMA)','Volume-weighted Moving Average (VWMA)'])
//On Balance Volume
obv_calculation = input.string (defval ='Weighted Moving Average (WMA)', title = "Calculation method of On Balance Volume", group = "On Balance Volume", options=['NONE','Lenior regression', 'Simple Moving Average (SMA)','Exponentially Weighted Moving Average (EMA)', 'Hull Moving Average (HMA)', 'Exponentially Weighted Moving average with alpha length (RMA)', 'Weighted Moving Average (WMA)', 'Arnaud Legoux Moving Average (ALMA)', 'Symmetrically weighted moving average with fixed length (SWMA)','Volume-weighted Moving Average (VWMA)'])
//Price-Volume Trend
pvt_calculation = input.string (defval ='Exponentially Weighted Moving Average (EMA)', title = "Calculation method of Price-Volume Trend", group = "Price-Volume Trend", options=['NONE','Lenior regression', 'Simple Moving Average (SMA)','Exponentially Weighted Moving Average (EMA)', 'Hull Moving Average (HMA)', 'Exponentially Weighted Moving average with alpha length (RMA)', 'Weighted Moving Average (WMA)', 'Arnaud Legoux Moving Average (ALMA)', 'Symmetrically weighted moving average with fixed length (SWMA)','Volume-weighted Moving Average (VWMA)'])
//True range
tr_calculation = input.string (defval ='Exponentially Weighted Moving Average (EMA)', title = "Calculation method of True range", group = "True range", options=['NONE','Lenior regression', 'Simple Moving Average (SMA)','Exponentially Weighted Moving Average (EMA)', 'Hull Moving Average (HMA)', 'Exponentially Weighted Moving average with alpha length (RMA)', 'Weighted Moving Average (WMA)', 'Arnaud Legoux Moving Average (ALMA)', 'Symmetrically weighted moving average with fixed length (SWMA)','Volume-weighted Moving Average (VWMA)'])
//Volume-weighted average price
vwap_calculation = input.string (defval ='Hull Moving Average (HMA)', title = "Calculation method of Volume-weighted average price", group = "Volume-weighted average price", options=['NONE','Lenior regression', 'Simple Moving Average (SMA)','Exponentially Weighted Moving Average (EMA)', 'Hull Moving Average (HMA)', 'Exponentially Weighted Moving average with alpha length (RMA)', 'Weighted Moving Average (WMA)', 'Arnaud Legoux Moving Average (ALMA)', 'Symmetrically weighted moving average with fixed length (SWMA)','Volume-weighted Moving Average (VWMA)'])
//Williams Accumulation/Distribution
wad_calculation = input.string (defval ='Exponentially Weighted Moving Average (EMA)', title = "Calculation method of Williams Accumulation/Distribution", group = "Williams Accumulation/Distribution", options=['NONE','Lenior regression', 'Simple Moving Average (SMA)','Exponentially Weighted Moving Average (EMA)', 'Hull Moving Average (HMA)', 'Exponentially Weighted Moving average with alpha length (RMA)', 'Weighted Moving Average (WMA)', 'Arnaud Legoux Moving Average (ALMA)', 'Symmetrically weighted moving average with fixed length (SWMA)','Volume-weighted Moving Average (VWMA)'])
//Williams Variable Accumulation/Distribution
wvad_calculation = input.string (defval ='Exponentially Weighted Moving Average (EMA)', title = "Calculation method of Williams Variable Accumulation/Distribution", group = "Williams Variable Accumulation/Distribution", options=['NONE','Lenior regression', 'Simple Moving Average (SMA)','Exponentially Weighted Moving Average (EMA)', 'Hull Moving Average (HMA)', 'Exponentially Weighted Moving average with alpha length (RMA)', 'Weighted Moving Average (WMA)', 'Arnaud Legoux Moving Average (ALMA)', 'Symmetrically weighted moving average with fixed length (SWMA)','Volume-weighted Moving Average (VWMA)'])
//Simple Moving Average
source_of_sma = input (defval = close, title = "Source of Simple Moving Average (SMA)", group = "Simple Moving Average (SMA)")
//Exponential Moving Average
source_of_ema = input (defval = close, title = "Source of Exponential Moving Average (EMA)", group = "Exponential Moving Average (EMA)")
//CCI (commodity channel index)
source_of_cci = input (defval = close, title = "Source of Commodity Channel Index (CCI)", group = "Commodity Channel Index (CCI)")
//Chop Zone
source_of_cz = input (defval = close, title = "Source of Chop Zone (CZ)", group = " Chop Zone (CZ)")
source_of_cz_avg = input (defval = hlc3, title = "Source of Average of Chop Zone (CZ)", group = " Chop Zone (CZ)")
cz_calculation = input.string (defval = 'Exponentially Weighted Moving Average (EMA)', title = "Calculation method of Chop Zone", group = " Chop Zone (CZ)", options=['Lenior regression', 'Simple Moving Average (SMA)','Exponentially Weighted Moving Average (EMA)', 'Hull Moving Average (HMA)', 'Exponentially Weighted Moving average with alpha length (RMA)', 'Weighted Moving Average (WMA)', 'Arnaud Legoux Moving Average (ALMA)', 'Symmetrically weighted moving average with fixed length (SWMA)','Volume-weighted Moving Average (VWMA)'])
//Ease of Movement
source_of_eom = input (defval = hl2, title = "Source of Ease of Movement (EOM)", group = "Ease of Movement")
eom_calculation = input.string (defval = 'Simple Moving Average (SMA)', title = "Calculation method of Ease of Movement", group = "Ease of Movement", options=['Lenior regression', 'Simple Moving Average (SMA)','Exponentially Weighted Moving Average (EMA)', 'Hull Moving Average (HMA)', 'Exponentially Weighted Moving average with alpha length (RMA)', 'Weighted Moving Average (WMA)', 'Arnaud Legoux Moving Average (ALMA)', 'Symmetrically weighted moving average with fixed length (SWMA)','Volume-weighted Moving Average (VWMA)'])
//Detrended Price Oscillator
source_of_dpo = input (defval = close, title = "Source of Detrended Price Oscillator (DPO)", group = "Detrended Price Oscillator (DPO)")
isCentered = input (defval = false, title="Alignment to center - Detrended Price Oscillator (DPO)", group = "Detrended Price Oscillator (DPO)")
dpo_calculation = input.string (defval='Simple Moving Average (SMA)', title = "Calculation method of Ease of Movement", group = "Detrended Price Oscillator (DPO)", options=['Lenior regression', 'Simple Moving Average (SMA)','Exponentially Weighted Moving Average (EMA)', 'Hull Moving Average (HMA)', 'Exponentially Weighted Moving average with alpha length (RMA)', 'Weighted Moving Average (WMA)', 'Arnaud Legoux Moving Average (ALMA)', 'Symmetrically weighted moving average with fixed length (SWMA)','Volume-weighted Moving Average (VWMA)'])
//Advance Decline Line
source_of_adl = input (defval = close, title = "Source of Advance Decline Line (ADL)", group = "Advance Decline Line (ADL)")
//Bull Bear Power
source_of_bullp = input (defval = high, title = "Source of Bull Power", group = "Bull Bear Power (BBP)")
source_of_bearp = input (defval = low, title = "Source of Bear Power", group = "Bull Bear Power (BBP)")
source_of_cal_bullp = input (defval = close, title = "Source of Baseline of Bull Power", group = "Bull Bear Power (BBP)")
source_of_cal_bearp = input (defval = close, title = "Source of Baseline of Bear Power", group = "Bull Bear Power (BBP)")
bullp_calculation = input.string (defval ='Simple Moving Average (SMA)', title = "Calculation method of Bull Power", group = "Bull Bear Power (BBP)" , options=['Lenior regression', 'Simple Moving Average (SMA)','Exponentially Weighted Moving Average (EMA)', 'Hull Moving Average (HMA)', 'Exponentially Weighted Moving average with alpha length (RMA)', 'Weighted Moving Average (WMA)', 'Arnaud Legoux Moving Average (ALMA)', 'Symmetrically weighted moving average with fixed length (SWMA)','Volume-weighted Moving Average (VWMA)'])
bearp_calculation = input.string (defval ='Simple Moving Average (SMA)', title = "Calculation method of Bull Power", group = "Bull Bear Power (BBP)", options=['Lenior regression', 'Simple Moving Average (SMA)','Exponentially Weighted Moving Average (EMA)', 'Hull Moving Average (HMA)', 'Exponentially Weighted Moving average with alpha length (RMA)', 'Weighted Moving Average (WMA)', 'Arnaud Legoux Moving Average (ALMA)', 'Symmetrically weighted moving average with fixed length (SWMA)','Volume-weighted Moving Average (VWMA)'])
//high
high_impact_calculation = input.string (defval ='Simple Moving Average (SMA)', title = "Impact calculation method of high", group = "Impact Calculation", options=['Lenior regression', 'Simple Moving Average (SMA)','Exponentially Weighted Moving Average (EMA)', 'Hull Moving Average (HMA)', 'Exponentially Weighted Moving average with alpha length (RMA)', 'Weighted Moving Average (WMA)', 'Arnaud Legoux Moving Average (ALMA)', 'Symmetrically weighted moving average with fixed length (SWMA)','Volume-weighted Moving Average (VWMA)'])
//low
low_impact_calculation = input.string (defval ='Simple Moving Average (SMA)', title = "Impact calculation method of low", group = "Impact Calculation", options=['Lenior regression', 'Simple Moving Average (SMA)','Exponentially Weighted Moving Average (EMA)', 'Hull Moving Average (HMA)', 'Exponentially Weighted Moving average with alpha length (RMA)', 'Weighted Moving Average (WMA)', 'Arnaud Legoux Moving Average (ALMA)', 'Symmetrically weighted moving average with fixed length (SWMA)','Volume-weighted Moving Average (VWMA)'])
//open
open_impact_calculation = input.string (defval ='Simple Moving Average (SMA)', title = "Impact calculation method of open", group = "Impact Calculation", options=['Lenior regression', 'Simple Moving Average (SMA)','Exponentially Weighted Moving Average (EMA)', 'Hull Moving Average (HMA)', 'Exponentially Weighted Moving average with alpha length (RMA)', 'Weighted Moving Average (WMA)', 'Arnaud Legoux Moving Average (ALMA)', 'Symmetrically weighted moving average with fixed length (SWMA)','Volume-weighted Moving Average (VWMA)'])
//close
close_impact_calculation = input.string (defval ='Simple Moving Average (SMA)', title = "Impact calculation method of close", group = "Impact Calculation", options=['Lenior regression', 'Simple Moving Average (SMA)','Exponentially Weighted Moving Average (EMA)', 'Hull Moving Average (HMA)', 'Exponentially Weighted Moving average with alpha length (RMA)', 'Weighted Moving Average (WMA)', 'Arnaud Legoux Moving Average (ALMA)', 'Symmetrically weighted moving average with fixed length (SWMA)','Volume-weighted Moving Average (VWMA)'])
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//General Calculations
var float volume_avg_14 = 0
var float ma_9 = 0
price_avg_14 = ta.linreg((source_of_price_average), look_back_period, 0)
price_rising = ta.rising(price_avg_14,2)
price_falling = ta.falling(price_avg_14,look_back_period_for_price_falling)
//Volume profile
if volume_profile_calculation == 'Lenior regression'
volume_avg_14 := ta.linreg(volume, look_back_period, 0)
else if volume_profile_calculation == 'Simple Moving Average (SMA)'
volume_avg_14 := ta.sma(volume, look_back_period)
else if volume_profile_calculation == 'Exponentially Weighted Moving Average (EMA)'
volume_avg_14 := ta.ema(volume, look_back_period)
else if volume_profile_calculation == 'Hull Moving Average (HMA)'
volume_avg_14 := ta.hma(volume, look_back_period)
else if volume_profile_calculation == 'Exponentially Weighted Moving average with alpha length (RMA)'
volume_avg_14 := ta.rma(volume, look_back_period)
else if volume_profile_calculation == 'Weighted Moving Average (WMA)'
volume_avg_14 := ta.wma(volume, look_back_period)
else if volume_profile_calculation == 'Arnaud Legoux Moving Average (ALMA)'
volume_avg_14 := ta.alma(volume, look_back_period,0,3)
else if volume_profile_calculation == 'Symmetrically weighted moving average with fixed length (SWMA)'
volume_avg_14 := ta.swma(volume)
else if volume_profile_calculation == 'Volume-weighted Moving Average (VWMA)'
volume_avg_14 := ta.vwma(volume, look_back_period)
if ma_9_calculation == 'Lenior regression'
ma_9 := ta.linreg(source_of_ma9, look_back_period, 0)
else if ma_9_calculation == 'Simple Moving Average (SMA)'
ma_9 := ta.sma(source_of_ma9, look_back_period)
else if ma_9_calculation == 'Exponentially Weighted Moving Average (EMA)'
ma_9 := ta.ema(source_of_ma9, look_back_period)
else if ma_9_calculation == 'Hull Moving Average (HMA)'
ma_9 := ta.hma(source_of_ma9, look_back_period)
else if ma_9_calculation == 'Exponentially Weighted Moving average with alpha length (RMA)'
ma_9 := ta.rma(source_of_ma9, look_back_period)
else if ma_9_calculation == 'Weighted Moving Average (WMA)'
ma_9 := ta.wma(source_of_ma9, look_back_period)
else if ma_9_calculation == 'Arnaud Legoux Moving Average (ALMA)'
ma_9 := ta.alma(source_of_ma9, look_back_period,0,3)
else if ma_9_calculation == 'Symmetrically weighted moving average with fixed length (SWMA)'
ma_9 := ta.swma(source_of_ma9)
else if ma_9_calculation == 'Volume-weighted Moving Average (VWMA)'
ma_9 := ta.vwma(source_of_ma9, look_back_period)
st_dev_of_price_avg_14 = ta.stdev(price_avg_14, look_back_period)
st_dev_of_volume_avg_14 = ta.stdev(volume_avg_14, look_back_period)
corelation_btw_price_avg_14_and_volume_avg_14 = ta.correlation(volume_avg_14,price_avg_14,look_back_period)
//Parabolic SAR (parabolic stop and reverse)
indicator_sar_14 = ta.sar(sar_start_value, sar_incrimant_value, sar_mac_value)
[middle_sar_14, upper_sar_14, lower_sar_14] = ta.bb(indicator_sar_14, 5, 4)
bb_gap_of_sar_14 = indicator_sar_14 - middle_sar_14
st_dev_of_bb_gap_of_sar_14 = ta.stdev(bb_gap_of_sar_14, look_back_period)
st_dev_of_indicator_sar_14 = ta.stdev(indicator_sar_14, look_back_period)
corelation_btw_price_avg_14_and_indicator_sar_14 = ta.correlation(indicator_sar_14,price_avg_14,look_back_period)
first_degree_indicator_sar_14 = st_dev_of_indicator_sar_14 * corelation_btw_price_avg_14_and_indicator_sar_14
//Supertrend (ST)
var float st_line = 0
[supertrend, direction] = ta.supertrend(ST_factor_value, ST_art_period_value)
up_direction = direction < 0 ? supertrend : na
down_direction = direction < 0? na : supertrend
if up_direction > 0
st_line := up_direction
else
st_line := down_direction
indicator_st_14 = st_line
[middle_st_14, upper_st_14, lower_st_14] = ta.bb(indicator_st_14, 5, 4)
bb_gap_of_st_14 = indicator_st_14 - middle_st_14
st_dev_of_bb_gap_of_st_14 = ta.stdev(bb_gap_of_st_14, look_back_period)
st_dev_of_indicator_st_14 = ta.stdev(indicator_st_14, look_back_period)
corelation_btw_price_avg_14_and_indicator_st_14 = ta.correlation(indicator_st_14,price_avg_14,look_back_period)
first_degree_indicator_st_14 = st_dev_of_indicator_st_14 * corelation_btw_price_avg_14_and_indicator_st_14
//Relative strength index (RSI)
indicator_rsi_14 = ta.rsi(source_of_rsi,look_back_period)
[middle_rsi_14, upper_rsi_14, lower_rsi_14] = ta.bb(indicator_rsi_14, 5, 4)
bb_gap_of_rsi_14 = indicator_rsi_14 - middle_rsi_14
st_dev_of_bb_gap_of_rsi_14 = ta.stdev(bb_gap_of_rsi_14, look_back_period)
st_dev_of_indicator_rsi_14 = ta.stdev(indicator_rsi_14, look_back_period)
corelation_btw_price_avg_14_and_indicator_rsi_14 = ta.correlation(indicator_rsi_14,price_avg_14,look_back_period)
first_degree_indicator_rsi_14 = st_dev_of_indicator_rsi_14 * corelation_btw_price_avg_14_and_indicator_rsi_14 * st_dev_of_bb_gap_of_rsi_14
//Money flow index (MFI)
indicator_mfi_14 = ta.mfi(source_of_mfi,look_back_period)
[middle_mfi_14, upper_mfi_14, lower_mfi_14] = ta.bb(indicator_mfi_14, 5, 4)
bb_gap_of_mfi_14 = indicator_mfi_14 - middle_mfi_14
st_dev_of_bb_gap_of_mfi_14 = ta.stdev(bb_gap_of_mfi_14, look_back_period)
st_dev_of_indicator_mfi_14 = ta.stdev(indicator_mfi_14, look_back_period)
corelation_btw_price_avg_14_and_indicator_mfi_14 = ta.correlation(indicator_mfi_14,price_avg_14,look_back_period)
first_degree_indicator_mfi_14 = st_dev_of_indicator_mfi_14 * corelation_btw_price_avg_14_and_indicator_mfi_14 * st_dev_of_bb_gap_of_mfi_14
//Balance of Power (BOP)
var float bop_f = 0
bop_nf = ta.linreg((((close - open) / (high - low) * 100)+100)/2, look_back_period, 0)
if bop_calculation == 'Lenior regression'
bop_f := bop_nf
else if bop_calculation == 'Simple Moving Average (SMA)'
bop_f := ta.sma(bop_nf, look_back_period)
else if bop_calculation == 'Exponentially Weighted Moving Average (EMA)'
bop_f := ta.ema(bop_nf, look_back_period)
else if bop_calculation == 'Hull Moving Average (HMA)'
bop_f := ta.hma(bop_nf, look_back_period)
else if bop_calculation == 'Exponentially Weighted Moving average with alpha length (RMA)'
bop_f := ta.rma(bop_nf, look_back_period)
else if bop_calculation == 'Weighted Moving Average (WMA)'
bop_f := ta.wma(bop_nf, look_back_period)
else if bop_calculation == 'Arnaud Legoux Moving Average (ALMA)'
bop_f := ta.alma(bop_nf, look_back_period,0,3)
else if bop_calculation == 'Symmetrically weighted moving average with fixed length (SWMA)'
bop_f := ta.swma(bop_nf)
else if bop_calculation == 'Volume-weighted Moving Average (VWMA)'
bop_f := ta.vwma(bop_nf, look_back_period)
indicator_bop_14 = bop_f
[middle_bop_14, upper_bop_14, lower_bop_14] = ta.bb(indicator_bop_14, 5, 4)
bb_gap_of_bop_14 = indicator_bop_14 - middle_bop_14
st_dev_of_bb_gap_of_bop_14 = ta.stdev(bb_gap_of_bop_14, look_back_period)
st_dev_of_indicator_bop_14 = ta.stdev(indicator_bop_14, look_back_period)
corelation_btw_price_avg_14_and_indicator_bop_14 = ta.correlation(indicator_bop_14,price_avg_14,look_back_period)
first_degree_indicator_bop_14 = st_dev_of_indicator_bop_14 * corelation_btw_price_avg_14_and_indicator_bop_14 * st_dev_of_bb_gap_of_bop_14
//Chande Momentum Oscillator
indicator_mom_14 = ta.cmo(source_of_mom,look_back_period)
[middle_mom_14, upper_mom_14, lower_mom_14] = ta.bb(indicator_mom_14, 5, 4)
bb_gap_of_mom_14 = indicator_mom_14 - middle_mom_14
st_dev_of_bb_gap_of_mom_14 = ta.stdev(bb_gap_of_mom_14, look_back_period)
st_dev_of_indicator_mom_14 = ta.stdev(indicator_mom_14, look_back_period)
corelation_btw_price_avg_14_and_indicator_mom_14 = ta.correlation(indicator_mom_14,price_avg_14,look_back_period)
first_degree_indicator_mom_14 = st_dev_of_indicator_mom_14 * corelation_btw_price_avg_14_and_indicator_mom_14 * st_dev_of_bb_gap_of_mom_14
//Center of Gravity (COG)
indicator_cog_14 = ta.cog(source_of_cog,look_back_period)
[middle_cog_14, upper_cog_14, lower_cog_14] = ta.bb(indicator_cog_14, 5, 4)
bb_gap_of_cog_14 = indicator_cog_14 - middle_cog_14
st_dev_of_bb_gap_of_cog_14 = ta.stdev(bb_gap_of_cog_14, look_back_period)
st_dev_of_indicator_cog_14 = ta.stdev(indicator_cog_14, look_back_period)
corelation_btw_price_avg_14_and_indicator_cog_14 = ta.correlation(indicator_cog_14,price_avg_14,look_back_period)
first_degree_indicator_cog_14 = st_dev_of_indicator_cog_14 * corelation_btw_price_avg_14_and_indicator_cog_14 * st_dev_of_bb_gap_of_cog_14
//Directional Movement Index (DMI)
[diplus, diminus,indicator_dmi_14] = ta.dmi(dmi_di_length, dmi_adx_smoothing_length)
[middle_dmi_14, upper_dmi_14, lower_dmi_14] = ta.bb(indicator_dmi_14, 5, 4)
bb_gap_of_dmi_14 = indicator_dmi_14 - middle_dmi_14
st_dev_of_bb_gap_of_dmi_14 = ta.stdev(bb_gap_of_dmi_14, look_back_period)
st_dev_of_indicator_dmi_14 = ta.stdev(indicator_dmi_14, look_back_period)
corelation_btw_price_avg_14_and_indicator_dmi_14 = ta.correlation(indicator_dmi_14,price_avg_14,look_back_period)
first_degree_indicator_dmi_14 = st_dev_of_indicator_dmi_14 * corelation_btw_price_avg_14_and_indicator_dmi_14 * st_dev_of_bb_gap_of_dmi_14
//Stochastic
stoch_nf = ta.stoch(source_of_stoch, high, low, look_back_period)
var float stoch_f = 0
if stoch_calculation == 'Lenior regression'
stoch_f := ta.linreg(stoch_nf, look_back_period, 0)
else if stoch_calculation == 'Simple Moving Average (SMA)'
stoch_f := ta.sma(stoch_nf, look_back_period)
else if stoch_calculation == 'Exponentially Weighted Moving Average (EMA)'
stoch_f := ta.ema(stoch_nf, look_back_period)
else if stoch_calculation == 'Hull Moving Average (HMA)'
stoch_f := ta.hma(stoch_nf, look_back_period)
else if stoch_calculation == 'Exponentially Weighted Moving average with alpha length (RMA)'
stoch_f := ta.rma(stoch_nf, look_back_period)
else if stoch_calculation == 'Weighted Moving Average (WMA)'
stoch_f := ta.wma(stoch_nf, look_back_period)
else if stoch_calculation == 'Arnaud Legoux Moving Average (ALMA)'
stoch_f := ta.alma(stoch_nf, look_back_period,0,3)
else if stoch_calculation == 'Symmetrically weighted moving average with fixed length (SWMA)'
stoch_f := ta.swma(stoch_nf)
else if stoch_calculation == 'Volume-weighted Moving Average (VWMA)'
stoch_f := ta.vwma(stoch_nf, look_back_period)
indicator_stoch_14 = stoch_f
[middle_stoch_14, upper_stoch_14, lower_stoch_14] = ta.bb(indicator_stoch_14, 5, 4)
bb_gap_of_stoch_14 = indicator_stoch_14 - middle_stoch_14
st_dev_of_bb_gap_of_stoch_14 = ta.stdev(bb_gap_of_stoch_14, look_back_period)
st_dev_of_indicator_stoch_14 = ta.stdev(indicator_stoch_14, look_back_period)
corelation_btw_price_avg_14_and_indicator_stoch_14 = ta.correlation(indicator_stoch_14,price_avg_14,look_back_period)
first_degree_indicator_stoch_14 = st_dev_of_indicator_stoch_14 * corelation_btw_price_avg_14_and_indicator_stoch_14 * st_dev_of_bb_gap_of_stoch_14
//Symmetrically weighted moving average with fixed length
swma_nf = ta.swma(source_of_swma)
var float swma_f = 0
if swma_calculation == 'Lenior regression'
swma_f := ta.linreg(swma_nf, look_back_period, 0)
else if swma_calculation == 'Simple Moving Average (SMA)'
swma_f := ta.sma(swma_nf, look_back_period)
else if swma_calculation == 'Exponentially Weighted Moving Average (EMA)'
swma_f := ta.ema(swma_nf, look_back_period)
else if swma_calculation == 'Hull Moving Average (HMA)'
swma_f := ta.hma(swma_nf, look_back_period)
else if swma_calculation == 'Exponentially Weighted Moving average with alpha length (RMA)'
swma_f := ta.rma(swma_nf, look_back_period)
else if swma_calculation == 'Weighted Moving Average (WMA)'
swma_f := ta.wma(swma_nf, look_back_period)
else if swma_calculation == 'Arnaud Legoux Moving Average (ALMA)'
swma_f := ta.alma(swma_nf, look_back_period,0,3)
else if swma_calculation == 'Symmetrically weighted moving average with fixed length (SWMA)'
swma_f := ta.swma(swma_nf)
else if swma_calculation == 'Volume-weighted Moving Average (VWMA)'
swma_f := ta.vwma(swma_nf, look_back_period)
indicator_swma_14 = swma_f
[middle_swma_14, upper_swma_14, lower_swma_14] = ta.bb(indicator_swma_14, 5, 4)
bb_gap_of_swma_14 = indicator_swma_14 - middle_swma_14
st_dev_of_bb_gap_of_swma_14 = ta.stdev(bb_gap_of_swma_14, look_back_period)
st_dev_of_indicator_swma_14 = ta.stdev(indicator_swma_14, look_back_period)
corelation_btw_price_avg_14_and_indicator_swma_14 = ta.correlation(indicator_swma_14,price_avg_14,look_back_period)
first_degree_indicator_swma_14 = st_dev_of_indicator_swma_14 * corelation_btw_price_avg_14_and_indicator_swma_14 * st_dev_of_bb_gap_of_swma_14
//True strength index (TSI)
indicator_tsi_14 = ta.tsi(source_of_tsi, tsi_short_length, tsi_long_length)
[middle_tsi_14, upper_tsi_14, lower_tsi_14] = ta.bb(indicator_tsi_14, 5, 4)
bb_gap_of_tsi_14 = indicator_tsi_14 - middle_tsi_14
st_dev_of_bb_gap_of_tsi_14 = ta.stdev(bb_gap_of_tsi_14, look_back_period)
st_dev_of_indicator_tsi_14 = ta.stdev(indicator_tsi_14, look_back_period)
corelation_btw_price_avg_14_and_indicator_tsi_14 = ta.correlation(indicator_tsi_14,price_avg_14,look_back_period)
first_degree_indicator_tsi_14 = st_dev_of_indicator_tsi_14 * corelation_btw_price_avg_14_and_indicator_tsi_14 * st_dev_of_bb_gap_of_tsi_14
//Williams %R
var float wpr_f = 0
wpr_nf = ta.wpr(look_back_period)
if wpr_calculation == 'NONE'
wpr_f := wpr_nf
else if wpr_calculation == 'Lenior regression'
wpr_f := ta.linreg(wpr_nf, look_back_period, 0)
else if wpr_calculation == 'Simple Moving Average (SMA)'
wpr_f := ta.sma(wpr_nf, look_back_period)
else if wpr_calculation == 'Exponentially Weighted Moving Average (EMA)'
wpr_f := ta.ema(wpr_nf, look_back_period)
else if wpr_calculation == 'Hull Moving Average (HMA)'
wpr_f := ta.hma(wpr_nf, look_back_period)
else if wpr_calculation == 'Exponentially Weighted Moving average with alpha length (RMA)'
wpr_f := ta.rma(wpr_nf, look_back_period)
else if wpr_calculation == 'Weighted Moving Average (WMA)'
wpr_f := ta.wma(wpr_nf, look_back_period)
else if wpr_calculation == 'Arnaud Legoux Moving Average (ALMA)'
wpr_f := ta.alma(wpr_nf, look_back_period,0,3)
else if wpr_calculation == 'Symmetrically weighted moving average with fixed length (SWMA)'
wpr_f := ta.swma(wpr_nf)
else if wpr_calculation == 'Volume-weighted Moving Average (VWMA)'
wpr_f := ta.vwma(wpr_nf, look_back_period)
indicator_wpr_14 = wpr_f
[middle_wpr_14, upper_wpr_14, lower_wpr_14] = ta.bb(indicator_wpr_14, 5, 4)
bb_gap_of_wpr_14 = indicator_wpr_14 - middle_wpr_14
st_dev_of_bb_gap_of_wpr_14 = ta.stdev(bb_gap_of_wpr_14, look_back_period)
st_dev_of_indicator_wpr_14 = ta.stdev(indicator_wpr_14, look_back_period)
corelation_btw_price_avg_14_and_indicator_wpr_14 = ta.correlation(indicator_wpr_14,price_avg_14,look_back_period)
first_degree_indicator_wpr_14 = st_dev_of_indicator_wpr_14 * corelation_btw_price_avg_14_and_indicator_wpr_14 * st_dev_of_bb_gap_of_wpr_14
//Accumulation/distribution index
var float accdist_f = 0
accdist_nf = ta.accdist
if accdist_calculation == 'NONE'
accdist_f := accdist_nf
else if accdist_calculation == 'Lenior regression'
accdist_f := ta.linreg(accdist_nf, look_back_period, 0)
else if accdist_calculation == 'Simple Moving Average (SMA)'
accdist_f := ta.sma(accdist_nf, look_back_period)
else if accdist_calculation == 'Exponentially Weighted Moving Average (EMA)'
accdist_f := ta.ema(accdist_nf, look_back_period)
else if accdist_calculation == 'Hull Moving Average (HMA)'
accdist_f := ta.hma(accdist_nf, look_back_period)
else if accdist_calculation == 'Exponentially Weighted Moving average with alpha length (RMA)'
accdist_f := ta.rma(accdist_nf, look_back_period)
else if accdist_calculation == 'Weighted Moving Average (WMA)'
accdist_f := ta.wma(accdist_nf, look_back_period)
else if accdist_calculation == 'Arnaud Legoux Moving Average (ALMA)'
accdist_f := ta.alma(accdist_nf, look_back_period,0,3)
else if accdist_calculation == 'Symmetrically weighted moving average with fixed length (SWMA)'
accdist_f := ta.swma(accdist_nf)
else if accdist_calculation == 'Volume-weighted Moving Average (VWMA)'
accdist_f := ta.vwma(accdist_nf, look_back_period)
indicator_accdist_14 = accdist_f
[middle_accdist_14, upper_accdist_14, lower_accdist_14] = ta.bb(indicator_accdist_14, 5, 4)
bb_gap_of_accdist_14 = indicator_accdist_14 - middle_accdist_14
st_dev_of_bb_gap_of_accdist_14 = ta.stdev(bb_gap_of_accdist_14, look_back_period)
st_dev_of_indicator_accdist_14 = ta.stdev(indicator_accdist_14, look_back_period)
corelation_btw_price_avg_14_and_indicator_accdist_14 = ta.correlation(indicator_accdist_14,price_avg_14,look_back_period)
first_degree_indicator_accdist_14 = st_dev_of_indicator_accdist_14 * corelation_btw_price_avg_14_and_indicator_accdist_14 * st_dev_of_bb_gap_of_accdist_14
//Intraday Intensity Index
var float iii_f = 0
iii_nf = ta.iii
if iii_calculation == 'NONE'
iii_f := iii_nf
else if iii_calculation == 'Lenior regression'
iii_f := ta.linreg(iii_nf, look_back_period, 0)
else if iii_calculation == 'Simple Moving Average (SMA)'
iii_f := ta.sma(iii_nf, look_back_period)
else if iii_calculation == 'Exponentially Weighted Moving Average (EMA)'
iii_f := ta.ema(iii_nf, look_back_period)
else if iii_calculation == 'Hull Moving Average (HMA)'
iii_f := ta.hma(iii_nf, look_back_period)
else if iii_calculation == 'Exponentially Weighted Moving average with alpha length (RMA)'
iii_f := ta.rma(iii_nf, look_back_period)
else if iii_calculation == 'Weighted Moving Average (WMA)'
iii_f := ta.wma(iii_nf, look_back_period)
else if iii_calculation == 'Arnaud Legoux Moving Average (ALMA)'
iii_f := ta.alma(iii_nf, look_back_period,0,3)
else if iii_calculation == 'Symmetrically weighted moving average with fixed length (SWMA)'
iii_f := ta.swma(iii_nf)
else if iii_calculation == 'Volume-weighted Moving Average (VWMA)'
iii_f := ta.vwma(iii_nf, look_back_period)
indicator_iii_14 = iii_f
[middle_iii_14, upper_iii_14, lower_iii_14] = ta.bb(indicator_iii_14, 5, 4)
bb_gap_of_iii_14 = indicator_iii_14 - middle_iii_14
st_dev_of_bb_gap_of_iii_14 = ta.stdev(bb_gap_of_iii_14, look_back_period)
st_dev_of_indicator_iii_14 = ta.stdev(indicator_iii_14, look_back_period)
corelation_btw_price_avg_14_and_indicator_iii_14 = ta.correlation(indicator_iii_14,price_avg_14,look_back_period)
first_degree_indicator_iii_14 = st_dev_of_indicator_iii_14 * corelation_btw_price_avg_14_and_indicator_iii_14 * st_dev_of_bb_gap_of_iii_14
//Negative Volume Index
var float nvi_f = 0
nvi_nf = ta.nvi
if nvi_calculation == 'NONE'
nvi_f := nvi_nf
else if nvi_calculation == 'Lenior regression'
nvi_f := ta.linreg(nvi_nf, look_back_period, 0)
else if nvi_calculation == 'Simple Moving Average (SMA)'
nvi_f := ta.sma(nvi_nf, look_back_period)
else if nvi_calculation == 'Exponentially Weighted Moving Average (EMA)'
nvi_f := ta.ema(nvi_nf, look_back_period)
else if nvi_calculation == 'Hull Moving Average (HMA)'
nvi_f := ta.hma(nvi_nf, look_back_period)
else if nvi_calculation == 'Exponentially Weighted Moving average with alpha length (RMA)'
nvi_f := ta.rma(nvi_nf, look_back_period)
else if nvi_calculation == 'Weighted Moving Average (WMA)'
nvi_f := ta.wma(nvi_nf, look_back_period)
else if nvi_calculation == 'Arnaud Legoux Moving Average (ALMA)'
nvi_f := ta.alma(nvi_nf, look_back_period,0,3)
else if nvi_calculation == 'Symmetrically weighted moving average with fixed length (SWMA)'
nvi_f := ta.swma(nvi_nf)
else if nvi_calculation == 'Volume-weighted Moving Average (VWMA)'
nvi_f := ta.vwma(nvi_nf, look_back_period)
indicator_nvi_14 = nvi_f
[middle_nvi_14, upper_nvi_14, lower_nvi_14] = ta.bb(indicator_nvi_14, 5, 4)
bb_gap_of_nvi_14 = indicator_nvi_14 - middle_nvi_14
st_dev_of_bb_gap_of_nvi_14 = ta.stdev(bb_gap_of_nvi_14, look_back_period)
st_dev_of_indicator_nvi_14 = ta.stdev(indicator_nvi_14, look_back_period)
corelation_btw_price_avg_14_and_indicator_nvi_14 = ta.correlation(indicator_nvi_14,price_avg_14,look_back_period)
first_degree_indicator_nvi_14 = st_dev_of_indicator_nvi_14 * corelation_btw_price_avg_14_and_indicator_nvi_14*st_dev_of_bb_gap_of_nvi_14
//Positive Volume Index
var float pvi_f = 0
pvi_nf = ta.pvi
if pvi_calculation == 'NONE'
pvi_f := pvi_nf
else if pvi_calculation == 'Lenior regression'
pvi_f := ta.linreg(pvi_nf, look_back_period, 0)
else if pvi_calculation == 'Simple Moving Average (SMA)'
pvi_f := ta.sma(pvi_nf, look_back_period)
else if pvi_calculation == 'Exponentially Weighted Moving Average (EMA)'
pvi_f := ta.ema(pvi_nf, look_back_period)
else if pvi_calculation == 'Hull Moving Average (HMA)'
pvi_f := ta.hma(pvi_nf, look_back_period)
else if pvi_calculation == 'Exponentially Weighted Moving average with alpha length (RMA)'
pvi_f := ta.rma(pvi_nf, look_back_period)
else if pvi_calculation == 'Weighted Moving Average (WMA)'
pvi_f := ta.wma(pvi_nf, look_back_period)
else if pvi_calculation == 'Arnaud Legoux Moving Average (ALMA)'
pvi_f := ta.alma(pvi_nf, look_back_period,0,3)
else if pvi_calculation == 'Symmetrically weighted moving average with fixed length (SWMA)'
pvi_f := ta.swma(pvi_nf)
else if pvi_calculation == 'Volume-weighted Moving Average (VWMA)'
pvi_f := ta.vwma(pvi_nf, look_back_period)
indicator_pvi_14 = pvi_f
[middle_pvi_14, upper_pvi_14, lower_pvi_14] = ta.bb(indicator_pvi_14, 5, 4)
bb_gap_of_pvi_14 = indicator_pvi_14 - middle_pvi_14
st_dev_of_bb_gap_of_pvi_14 = ta.stdev(bb_gap_of_pvi_14, look_back_period)
st_dev_of_indicator_pvi_14 = ta.stdev(indicator_pvi_14, look_back_period)
corelation_btw_price_avg_14_and_indicator_pvi_14 = ta.correlation(indicator_pvi_14,price_avg_14,look_back_period)
first_degree_indicator_pvi_14 = st_dev_of_indicator_pvi_14 * corelation_btw_price_avg_14_and_indicator_pvi_14*st_dev_of_bb_gap_of_pvi_14
//On Balance Volume
var float obv_f = 0
obv_nf = ta.obv
if obv_calculation == 'NONE'
obv_f := obv_nf
else if obv_calculation == 'Lenior regression'
obv_f := ta.linreg(obv_nf, look_back_period, 0)
else if obv_calculation == 'Simple Moving Average (SMA)'
obv_f := ta.sma(obv_nf, look_back_period)
else if obv_calculation == 'Exponentially Weighted Moving Average (EMA)'
obv_f := ta.ema(obv_nf, look_back_period)
else if obv_calculation == 'Hull Moving Average (HMA)'
obv_f := ta.hma(obv_nf, look_back_period)
else if obv_calculation == 'Exponentially Weighted Moving average with alpha length (RMA)'
obv_f := ta.rma(obv_nf, look_back_period)
else if obv_calculation == 'Weighted Moving Average (WMA)'
obv_f := ta.wma(obv_nf, look_back_period)
else if obv_calculation == 'Arnaud Legoux Moving Average (ALMA)'
obv_f := ta.alma(obv_nf, look_back_period,0,3)
else if obv_calculation == 'Symmetrically weighted moving average with fixed length (SWMA)'
obv_f := ta.swma(obv_nf)
else if obv_calculation == 'Volume-weighted Moving Average (VWMA)'
obv_f := ta.vwma(obv_nf, look_back_period)
indicator_obv_14 = obv_f
[middle_obv_14, upper_obv_14, lower_obv_14] = ta.bb(indicator_obv_14, 5, 4)
bb_gap_of_obv_14 = indicator_obv_14 - middle_obv_14
st_dev_of_bb_gap_of_obv_14 = ta.stdev(bb_gap_of_obv_14, look_back_period)
st_dev_of_indicator_obv_14 = ta.stdev(indicator_obv_14, look_back_period)
corelation_btw_price_avg_14_and_indicator_obv_14 = ta.correlation(indicator_obv_14,price_avg_14,look_back_period)
first_degree_indicator_obv_14 = st_dev_of_indicator_obv_14 * corelation_btw_price_avg_14_and_indicator_obv_14*st_dev_of_bb_gap_of_obv_14
//Price-Volume Trend
var float pvt_f = 0
pvt_nf = ta.pvt
if pvt_calculation == 'NONE'
pvt_f := pvt_nf
else if pvt_calculation == 'Lenior regression'
pvt_f := ta.linreg(pvt_nf, look_back_period, 0)
else if pvt_calculation == 'Simple Moving Average (SMA)'
pvt_f := ta.sma(pvt_nf, look_back_period)
else if pvt_calculation == 'Exponentially Weighted Moving Average (EMA)'
pvt_f := ta.ema(pvt_nf, look_back_period)
else if pvt_calculation == 'Hull Moving Average (HMA)'
pvt_f := ta.hma(pvt_nf, look_back_period)
else if pvt_calculation == 'Exponentially Weighted Moving average with alpha length (RMA)'
pvt_f := ta.rma(pvt_nf, look_back_period)
else if pvt_calculation == 'Weighted Moving Average (WMA)'
pvt_f := ta.wma(pvt_nf, look_back_period)
else if pvt_calculation == 'Arnaud Legoux Moving Average (ALMA)'
pvt_f := ta.alma(pvt_nf, look_back_period,0,3)
else if pvt_calculation == 'Symmetrically weighted moving average with fixed length (SWMA)'
pvt_f := ta.swma(pvt_nf)
else if pvt_calculation == 'Volume-weighted Moving Average (VWMA)'
pvt_f := ta.vwma(pvt_nf, look_back_period)
indicator_pvt_14 = pvt_f
[middle_pvt_14, upper_pvt_14, lower_pvt_14] = ta.bb(indicator_pvt_14, 5, 4)
bb_gap_of_pvt_14 = indicator_pvt_14 - middle_pvt_14
st_dev_of_bb_gap_of_pvt_14 = ta.stdev(bb_gap_of_pvt_14, look_back_period)
st_dev_of_indicator_pvt_14 = ta.stdev(indicator_pvt_14, look_back_period)
corelation_btw_price_avg_14_and_indicator_pvt_14 = ta.correlation(indicator_pvt_14,price_avg_14,look_back_period)
first_degree_indicator_pvt_14 = st_dev_of_indicator_pvt_14 * corelation_btw_price_avg_14_and_indicator_pvt_14*st_dev_of_bb_gap_of_pvt_14
//True range
var float tr_f = 0
tr_nf = ta.tr
if tr_calculation == 'NONE'
tr_f := tr_nf
else if tr_calculation == 'Lenior regression'
tr_f := ta.linreg(tr_nf, look_back_period, 0)
else if tr_calculation == 'Simple Moving Average (SMA)'
tr_f := ta.sma(tr_nf, look_back_period)
else if tr_calculation == 'Exponentially Weighted Moving Average (EMA)'
tr_f := ta.ema(tr_nf, look_back_period)
else if tr_calculation == 'Hull Moving Average (HMA)'
tr_f := ta.hma(tr_nf, look_back_period)
else if tr_calculation == 'Exponentially Weighted Moving average with alpha length (RMA)'
tr_f := ta.rma(tr_nf, look_back_period)
else if tr_calculation == 'Weighted Moving Average (WMA)'
tr_f := ta.wma(tr_nf, look_back_period)
else if tr_calculation == 'Arnaud Legoux Moving Average (ALMA)'
tr_f := ta.alma(tr_nf, look_back_period,0,3)
else if tr_calculation == 'Symmetrically weighted moving average with fixed length (SWMA)'
tr_f := ta.swma(tr_nf)
else if tr_calculation == 'Volume-weighted Moving Average (VWMA)'
tr_f := ta.vwma(tr_nf, look_back_period)
indicator_tr_14 = tr_f
[middle_tr_14, upper_tr_14, lower_tr_14] = ta.bb(indicator_tr_14, 5, 4)
bb_gap_of_tr_14 = indicator_tr_14 - middle_tr_14
st_dev_of_bb_gap_of_tr_14 = ta.stdev(bb_gap_of_tr_14, look_back_period)
st_dev_of_indicator_tr_14 = ta.stdev(indicator_tr_14, look_back_period)
corelation_btw_price_avg_14_and_indicator_tr_14 = ta.correlation(indicator_tr_14,price_avg_14,look_back_period)
first_degree_indicator_tr_14 = st_dev_of_indicator_tr_14 * corelation_btw_price_avg_14_and_indicator_tr_14*st_dev_of_bb_gap_of_tr_14
//Volume-weighted average price
var float vwap_f = 0
vwap_nf = ta.vwap
if vwap_calculation == 'NONE'
vwap_f := vwap_nf
else if vwap_calculation == 'Lenior regression'
vwap_f := ta.linreg(vwap_nf, look_back_period, 0)
else if vwap_calculation == 'Simple Moving Average (SMA)'
vwap_f := ta.sma(vwap_nf, look_back_period)
else if vwap_calculation == 'Exponentially Weighted Moving Average (EMA)'
vwap_f := ta.ema(vwap_nf, look_back_period)
else if vwap_calculation == 'Hull Moving Average (HMA)'
vwap_f := ta.hma(vwap_nf, look_back_period)
else if vwap_calculation == 'Exponentially Weighted Moving average with alpha length (RMA)'
vwap_f := ta.rma(vwap_nf, look_back_period)
else if vwap_calculation == 'Weighted Moving Average (WMA)'
vwap_f := ta.wma(vwap_nf, look_back_period)
else if vwap_calculation == 'Arnaud Legoux Moving Average (ALMA)'
vwap_f := ta.alma(vwap_nf, look_back_period,0,3)
else if vwap_calculation == 'Symmetrically weighted moving average with fixed length (SWMA)'
vwap_f := ta.swma(vwap_nf)
else if vwap_calculation == 'Volume-weighted Moving Average (VWMA)'
vwap_f := ta.vwma(vwap_nf, look_back_period)
indicator_vwap_14 = vwap_f
[middle_vwap_14, upper_vwap_14, lower_vwap_14] = ta.bb(indicator_vwap_14, 5, 4)
bb_gap_of_vwap_14 = indicator_vwap_14 - middle_vwap_14
st_dev_of_bb_gap_of_vwap_14 = ta.stdev(bb_gap_of_vwap_14, look_back_period)
st_dev_of_indicator_vwap_14 = ta.stdev(indicator_vwap_14, look_back_period)
corelation_btw_price_avg_14_and_indicator_vwap_14 = ta.correlation(indicator_vwap_14,price_avg_14,look_back_period)
first_degree_indicator_vwap_14 = st_dev_of_indicator_vwap_14 * corelation_btw_price_avg_14_and_indicator_vwap_14*st_dev_of_bb_gap_of_vwap_14
//Williams Accumulation/Distribution
var float wad_f = 0
wad_nf = ta.wad
if wad_calculation == 'NONE'
wad_f := wad_nf
else if wad_calculation == 'Lenior regression'
wad_f := ta.linreg(wad_nf, look_back_period, 0)
else if wad_calculation == 'Simple Moving Average (SMA)'
wad_f := ta.sma(wad_nf, look_back_period)
else if wad_calculation == 'Exponentially Weighted Moving Average (EMA)'
wad_f := ta.ema(wad_nf, look_back_period)
else if wad_calculation == 'Hull Moving Average (HMA)'
wad_f := ta.hma(wad_nf, look_back_period)
else if wad_calculation == 'Exponentially Weighted Moving average with alpha length (RMA)'
wad_f := ta.rma(wad_nf, look_back_period)
else if wad_calculation == 'Weighted Moving Average (WMA)'
wad_f := ta.wma(wad_nf, look_back_period)
else if wad_calculation == 'Arnaud Legoux Moving Average (ALMA)'
wad_f := ta.alma(wad_nf, look_back_period,0,3)
else if wad_calculation == 'Symmetrically weighted moving average with fixed length (SWMA)'
wad_f := ta.swma(wad_nf)
else if wad_calculation == 'Volume-weighted Moving Average (VWMA)'
wad_f := ta.vwma(wad_nf, look_back_period)
indicator_wad_14 = wad_f
[middle_wad_14, upper_wad_14, lower_wad_14] = ta.bb(indicator_wad_14, 5, 4)
bb_gap_of_wad_14 = indicator_wad_14 - middle_wad_14
st_dev_of_bb_gap_of_wad_14 = ta.stdev(bb_gap_of_wad_14, look_back_period)
st_dev_of_indicator_wad_14 = ta.stdev(indicator_wad_14, look_back_period)
corelation_btw_price_avg_14_and_indicator_wad_14 = ta.correlation(indicator_wad_14,price_avg_14,look_back_period)
first_degree_indicator_wad_14 = st_dev_of_indicator_wad_14 * corelation_btw_price_avg_14_and_indicator_wad_14*st_dev_of_bb_gap_of_wad_14
//Williams Variable Accumulation/Distribution
var float wvad_f = 0
wvad_nf = ta.wvad
if wvad_calculation == 'NONE'
wvad_f := wvad_nf
else if wvad_calculation == 'Lenior regression'
wvad_f := ta.linreg(wvad_nf, look_back_period, 0)
else if wvad_calculation == 'Simple Moving Average (SMA)'
wvad_f := ta.sma(wvad_nf, look_back_period)
else if wvad_calculation == 'Exponentially Weighted Moving Average (EMA)'
wvad_f := ta.ema(wvad_nf, look_back_period)
else if wvad_calculation == 'Hull Moving Average (HMA)'
wvad_f := ta.hma(wvad_nf, look_back_period)
else if wvad_calculation == 'Exponentially Weighted Moving average with alpha length (RMA)'
wvad_f := ta.rma(wvad_nf, look_back_period)
else if wvad_calculation == 'Weighted Moving Average (WMA)'
wvad_f := ta.wma(wvad_nf, look_back_period)
else if wvad_calculation == 'Arnaud Legoux Moving Average (ALMA)'
wvad_f := ta.alma(wvad_nf, look_back_period,0,3)
else if wvad_calculation == 'Symmetrically weighted moving average with fixed length (SWMA)'
wvad_f := ta.swma(wvad_nf)
else if wvad_calculation == 'Volume-weighted Moving Average (VWMA)'
wvad_f := ta.vwma(wvad_nf, look_back_period)
indicator_wvad_14 = wvad_f
[middle_wvad_14, upper_wvad_14, lower_wvad_14] = ta.bb(indicator_wvad_14, 5, 4)
bb_gap_of_wvad_14 = indicator_wvad_14 - middle_wvad_14
st_dev_of_bb_gap_of_wvad_14 = ta.stdev(bb_gap_of_wvad_14, look_back_period)
st_dev_of_indicator_wvad_14 = ta.stdev(indicator_wvad_14, look_back_period)
corelation_btw_price_avg_14_and_indicator_wvad_14 = ta.correlation(indicator_wvad_14,price_avg_14,look_back_period)
first_degree_indicator_wvad_14 = st_dev_of_indicator_wvad_14 * corelation_btw_price_avg_14_and_indicator_wvad_14*st_dev_of_bb_gap_of_wvad_14
//Simple Moving Average
indicator_sma_14 = ta.sma(source_of_sma,look_back_period) - ta.sma(source_of_sma,200)
[middle_sma_14, upper_sma_14, lower_sma_14] = ta.bb(indicator_sma_14, 5, 4)
bb_gap_of_sma_14 = indicator_sma_14 - middle_sma_14
st_dev_of_bb_gap_of_sma_14 = ta.stdev(bb_gap_of_sma_14, look_back_period)
st_dev_of_indicator_sma_14 = ta.stdev(indicator_sma_14, look_back_period)
corelation_btw_price_avg_14_and_indicator_sma_14 = ta.correlation(indicator_sma_14,price_avg_14,look_back_period)
first_degree_indicator_sma_14 = st_dev_of_indicator_sma_14 * corelation_btw_price_avg_14_and_indicator_sma_14*st_dev_of_bb_gap_of_sma_14
//Exponential Moving Average
indicator_ema_14 = ta.ema(source_of_ema,look_back_period) - ta.sma(source_of_ema,200)
[middle_ema_14, upper_ema_14, lower_ema_14] = ta.bb(indicator_ema_14, 5, 4)
bb_gap_of_ema_14 = indicator_ema_14 - middle_ema_14
st_dev_of_bb_gap_of_ema_14 = ta.stdev(bb_gap_of_ema_14, look_back_period)
st_dev_of_indicator_ema_14 = ta.stdev(indicator_ema_14, look_back_period)
corelation_btw_price_avg_14_and_indicator_ema_14 = ta.correlation(indicator_ema_14,price_avg_14,look_back_period)
first_degree_indicator_ema_14 = st_dev_of_indicator_ema_14 * corelation_btw_price_avg_14_and_indicator_ema_14*st_dev_of_bb_gap_of_ema_14
//CCI (commodity channel index)
indicator_cci_14 = ta.cci(source_of_cci, look_back_period)
[middle_cci_14, upper_cci_14, lower_cci_14] = ta.bb(indicator_cci_14, 5, 4)
bb_gap_of_cci_14 = indicator_cci_14 - middle_cci_14
st_dev_of_bb_gap_of_cci_14 = ta.stdev(bb_gap_of_cci_14, look_back_period)
st_dev_of_indicator_cci_14 = ta.stdev(indicator_cci_14, look_back_period)
corelation_btw_price_avg_14_and_indicator_cci_14 = ta.correlation(indicator_cci_14,price_avg_14,look_back_period)
first_degree_indicator_cci_14 = st_dev_of_indicator_cci_14 * corelation_btw_price_avg_14_and_indicator_cci_14 * st_dev_of_bb_gap_of_cci_14
//Chop Zone
source = source_of_cz
avg = source_of_cz_avg
var float ema34_f = 0
cz_nf = ta.ema(source, 34)
if cz_calculation == 'Lenior regression'
ema34_f := ta.linreg(cz_nf, look_back_period, 0)
else if cz_calculation == 'Simple Moving Average (SMA)'
ema34_f := ta.sma(cz_nf, look_back_period)
else if cz_calculation == 'Exponentially Weighted Moving Average (EMA)'
ema34_f := cz_nf
else if cz_calculation == 'Hull Moving Average (HMA)'
ema34_f := ta.hma(cz_nf, look_back_period)
else if cz_calculation == 'Exponentially Weighted Moving average with alpha length (RMA)'
ema34_f := ta.rma(cz_nf, look_back_period)
else if cz_calculation == 'Weighted Moving Average (WMA)'
ema34_f := ta.wma(cz_nf, look_back_period)
else if cz_calculation == 'Arnaud Legoux Moving Average (ALMA)'
ema34_f := ta.alma(cz_nf, look_back_period,0,3)
else if cz_calculation == 'Symmetrically weighted moving average with fixed length (SWMA)'
ema34_f := ta.swma(cz_nf)
else if cz_calculation == 'Volume-weighted Moving Average (VWMA)'
ema34_f := ta.vwma(cz_nf, look_back_period)
pi = math.atan(1) * 4
periods = 30
highestHigh = ta.highest(periods)
lowestLow = ta.lowest(periods)
span = 25 / (highestHigh - lowestLow) * lowestLow
ema34 = ema34_f
x1_ema34 = 0
x2_ema34 = 1
y1_ema34 = 0
y2_ema34 = (ema34[1] - ema34) / avg * span
c_ema34 = math.sqrt((x2_ema34 - x1_ema34)*(x2_ema34 - x1_ema34) + (y2_ema34 - y1_ema34)*(y2_ema34 - y1_ema34))
emaAngle_1 = math.round(180 * math.acos((x2_ema34 - x1_ema34)/c_ema34) / pi)
emaAngle = y2_ema34 > 0? - emaAngle_1: emaAngle_1
indicator_chop_zone_14 = emaAngle
[middle_chop_zone_14, upper_chop_zone_14, lower_chop_zone_14] = ta.bb(indicator_chop_zone_14, 5, 4)
bb_gap_of_chop_zone_14 = indicator_chop_zone_14 - middle_chop_zone_14
st_dev_of_bb_gap_of_chop_zone_14 = ta.stdev(bb_gap_of_chop_zone_14, look_back_period)
st_dev_of_indicator_chop_zone_14 = ta.stdev(indicator_chop_zone_14, look_back_period)
corelation_btw_price_avg_14_and_indicator_chop_zone_14 = ta.correlation(indicator_chop_zone_14,price_avg_14,look_back_period)
first_degree_indicator_chop_zone_14 = st_dev_of_indicator_chop_zone_14 * corelation_btw_price_avg_14_and_indicator_chop_zone_14 * st_dev_of_bb_gap_of_chop_zone_14
//Ease of Movement
var cumVol = 0.
cumVol += nz(volume)
if barstate.islast and cumVol == 0
runtime.error("No volume is provided by the data vendor.")
div = 10000 //input.int(10000, title="Divisor", minval=1)
eom_nf = (div * ta.change(source_of_eom) * (high - low) / volume)
var float eom_f = 0
if eom_calculation == 'Lenior regression'
eom_f := ta.linreg(eom_nf, look_back_period, 0)
else if eom_calculation == 'Simple Moving Average (SMA)'
eom_f := ta.sma(eom_nf, look_back_period)
else if eom_calculation == 'Exponentially Weighted Moving Average (EMA)'
eom_f := eom_nf
else if eom_calculation == 'Hull Moving Average (HMA)'
eom_f := ta.hma(eom_nf, look_back_period)
else if eom_calculation == 'Exponentially Weighted Moving average with alpha length (RMA)'
eom_f := ta.rma(eom_nf, look_back_period)
else if eom_calculation == 'Weighted Moving Average (WMA)'
eom_f := ta.wma(eom_nf, look_back_period)
else if eom_calculation == 'Arnaud Legoux Moving Average (ALMA)'
eom_f := ta.alma(eom_nf, look_back_period,0,3)
else if eom_calculation == 'Symmetrically weighted moving average with fixed length (SWMA)'
eom_f := ta.swma(eom_nf)
else if eom_calculation == 'Volume-weighted Moving Average (VWMA)'
eom_f := ta.vwma(eom_nf, look_back_period)
eom = eom_f
indicator_eom_14 = eom
[middle_eom_14, upper_eom_14, lower_eom_14] = ta.bb(indicator_eom_14, 5, 4)
bb_gap_of_eom_14 = indicator_eom_14 - middle_eom_14
st_dev_of_bb_gap_of_eom_14 = ta.stdev(bb_gap_of_eom_14, look_back_period)
st_dev_of_indicator_eom_14 = ta.stdev(indicator_eom_14, look_back_period)
corelation_btw_price_avg_14_and_indicator_eom_14 = ta.correlation(indicator_eom_14,price_avg_14,look_back_period)
first_degree_indicator_eom_14 = st_dev_of_indicator_eom_14 * corelation_btw_price_avg_14_and_indicator_eom_14 * st_dev_of_bb_gap_of_eom_14
//Detrended Price Oscillator
var float ma_f = 0
ma_nf = ta.sma(source_of_dpo, look_back_period)
if dpo_calculation == 'Lenior regression'
ma_f:= ta.linreg(ma_nf, look_back_period, 0)
else if dpo_calculation == 'Simple Moving Average (SMA)'
ma_f:= ta.sma(source_of_dpo, look_back_period)
else if dpo_calculation == 'Exponentially Weighted Moving Average (EMA)'
ma_f:= ta.ema(source_of_dpo, look_back_period)
else if dpo_calculation == 'Hull Moving Average (HMA)'
ma_f:= ta.hma(source_of_dpo, look_back_period)
else if dpo_calculation == 'Exponentially Weighted Moving average with alpha length (RMA)'
ma_f:= ta.rma(source_of_dpo, look_back_period)
else if dpo_calculation == 'Weighted Moving Average (WMA)'
ma_f:= ta.wma(source_of_dpo, look_back_period)
else if dpo_calculation == 'Arnaud Legoux Moving Average (ALMA)'
ma_f:= ta.alma(source_of_dpo, look_back_period,0,3)
else if dpo_calculation == 'Symmetrically weighted moving average with fixed length (SWMA)'
ma_f:= ta.swma(source_of_dpo)
else if dpo_calculation == 'Volume-weighted Moving Average (VWMA)'
ma_f:= ta.vwma(source_of_dpo, look_back_period)
barsback = look_back_period/2 + 1
ma = ma_f
dpo = isCentered ? close[barsback] - ma : close - ma[barsback]
indicator_dpo_14 = dpo
[middle_dpo_14, upper_dpo_14, lower_dpo_14] = ta.bb(indicator_dpo_14, 5, 4)
bb_gap_of_dpo_14 = indicator_dpo_14 - middle_dpo_14
st_dev_of_bb_gap_of_dpo_14 = ta.stdev(bb_gap_of_dpo_14, look_back_period)
st_dev_of_indicator_dpo_14 = ta.stdev(indicator_dpo_14, look_back_period)
corelation_btw_price_avg_14_and_indicator_dpo_14 = ta.correlation(indicator_dpo_14,price_avg_14,look_back_period)
first_degree_indicator_dpo_14 = st_dev_of_indicator_dpo_14 * corelation_btw_price_avg_14_and_indicator_dpo_14 * st_dev_of_bb_gap_of_dpo_14
//Advance Decline Line
sym(s) => request.security(s, timeframe.period, source_of_adl)
difference = (sym("USI:ADVN.NY") - sym("USI:DECL.NY"))/(sym("USI:UNCH.NY") + 1)
adline = ta.cum(difference > 0 ? math.sqrt(difference) : -math.sqrt(-difference))
indicator_adl_14 = adline
[middle_adl_14, upper_adl_14, lower_adl_14] = ta.bb(indicator_adl_14, 5, 4)
bb_gap_of_adl_14 = indicator_adl_14 - middle_adl_14
st_dev_of_bb_gap_of_adl_14 = ta.stdev(bb_gap_of_adl_14, look_back_period)
st_dev_of_indicator_adl_14 = ta.stdev(indicator_adl_14, look_back_period)
corelation_btw_price_avg_14_and_indicator_adl_14 = ta.correlation(indicator_adl_14,price_avg_14,look_back_period)
first_degree_indicator_adl_14 = st_dev_of_indicator_adl_14 * corelation_btw_price_avg_14_and_indicator_adl_14 * st_dev_of_bb_gap_of_adl_14
//Bull Bear Power
var float bullp_f = 0
var float bearp_f = 0
bullp_nf = ta.ema(source_of_cal_bullp, look_back_period)
bearp_nf = ta.ema(source_of_cal_bullp, look_back_period)
if bullp_calculation == 'Lenior regression'
bullp_f := ta.linreg(bullp_nf, look_back_period, 0)
else if bullp_calculation == 'Simple Moving Average (SMA)'
bullp_f := ta.sma(source_of_bullp, look_back_period)
else if bullp_calculation == 'Exponentially Weighted Moving Average (EMA)'
bullp_f := ta.ema(source_of_bullp, look_back_period)
else if bullp_calculation == 'Hull Moving Average (HMA)'
bullp_f := ta.hma(source_of_bullp, look_back_period)
else if bullp_calculation == 'Exponentially Weighted Moving average with alpha length (RMA)'
bullp_f := ta.rma(source_of_bullp, look_back_period)
else if bullp_calculation == 'Weighted Moving Average (WMA)'
bullp_f := ta.wma(source_of_bullp, look_back_period)
else if bullp_calculation == 'Arnaud Legoux Moving Average (ALMA)'
bullp_f := ta.alma(source_of_bullp, look_back_period,0,3)
else if bullp_calculation == 'Symmetrically weighted moving average with fixed length (SWMA)'
bullp_f := ta.swma(source_of_bullp)
else if bullp_calculation == 'Volume-weighted Moving Average (VWMA)'
bullp_f := ta.vwma(source_of_bullp, look_back_period)
if bearp_calculation == 'Lenior regression'
bearp_f := ta.linreg(bearp_nf, look_back_period, 0)
else if bearp_calculation == 'Simple Moving Average (SMA)'
bearp_f := ta.sma(source_of_bearp, look_back_period)
else if bearp_calculation == 'Exponentially Weighted Moving Average (EMA)'
bearp_f := ta.ema(source_of_bearp, look_back_period)
else if bearp_calculation == 'Hull Moving Average (HMA)'
bearp_f := ta.hma(source_of_bearp, look_back_period)
else if bearp_calculation == 'Exponentially Weighted Moving average with alpha length (RMA)'
bearp_f := ta.rma(source_of_bearp, look_back_period)
else if bearp_calculation == 'Weighted Moving Average (WMA)'
bearp_f := ta.wma(source_of_bearp, look_back_period)
else if bearp_calculation == 'Arnaud Legoux Moving Average (ALMA)'
bearp_f := ta.alma(source_of_bearp, look_back_period,0,3)
else if bearp_calculation == 'Symmetrically weighted moving average with fixed length (SWMA)'
bearp_f := ta.swma(source_of_bearp)
else if bearp_calculation == 'Volume-weighted Moving Average (VWMA)'
bearp_f := ta.vwma(source_of_bearp, look_back_period)
bullPower = source_of_bullp - bullp_f
bearPower = source_of_bearp - bearp_f
indicator_bbp_14 = bullPower + bearPower
[middle_bbp_14, upper_bbp_14, lower_bbp_14] = ta.bb(indicator_bbp_14, 5, 4)
bb_gap_of_bbp_14 = indicator_bbp_14 - middle_bbp_14
st_dev_of_bb_gap_of_bbp_14 = ta.stdev(bb_gap_of_bbp_14, look_back_period)
st_dev_of_indicator_bbp_14 = ta.stdev(indicator_bbp_14, look_back_period)
corelation_btw_price_avg_14_and_indicator_bbp_14 = ta.correlation(indicator_bbp_14,price_avg_14,look_back_period)
first_degree_indicator_bbp_14 = st_dev_of_indicator_bbp_14 * corelation_btw_price_avg_14_and_indicator_bbp_14 * st_dev_of_bb_gap_of_bbp_14
//high
var float high_f = 0
if high_impact_calculation == 'Lenior regression'
high_f := ta.linreg(high, look_back_period, 0)
else if high_impact_calculation == 'Simple Moving Average (SMA)'
high_f := ta.sma(high, look_back_period)
else if high_impact_calculation == 'Exponentially Weighted Moving Average (EMA)'
high_f := ta.ema(high, look_back_period)
else if high_impact_calculation == 'Hull Moving Average (HMA)'
high_f := ta.hma(high, look_back_period)
else if high_impact_calculation == 'Exponentially Weighted Moving average with alpha length (RMA)'
high_f := ta.rma(high, look_back_period)
else if high_impact_calculation == 'Weighted Moving Average (WMA)'
high_f := ta.wma(high, look_back_period)
else if high_impact_calculation == 'Arnaud Legoux Moving Average (ALMA)'
high_f := ta.alma(high, look_back_period,0,3)
else if high_impact_calculation == 'Symmetrically weighted moving average with fixed length (SWMA)'
high_f := ta.swma(high)
else if high_impact_calculation == 'Volume-weighted Moving Average (VWMA)'
high_f := ta.vwma(high, look_back_period)
indicator_high_14 = high_f
[middle_high_14, upper_high_14, lower_high_14] = ta.bb(indicator_high_14, 5, 4)
bb_gap_of_high_14 = indicator_high_14 - middle_high_14
st_dev_of_bb_gap_of_high_14 = ta.stdev(bb_gap_of_high_14, look_back_period)
st_dev_of_indicator_high_14 = ta.stdev(indicator_high_14, look_back_period)
corelation_btw_price_avg_14_and_indicator_high_14 = ta.correlation(indicator_high_14,price_avg_14,look_back_period)
first_degree_indicator_high_14 = st_dev_of_indicator_high_14 * corelation_btw_price_avg_14_and_indicator_high_14 * st_dev_of_bb_gap_of_high_14
//low
var float low_f = 0
if low_impact_calculation == 'Lenior regression'
low_f := ta.linreg(low, look_back_period, 0)
else if low_impact_calculation == 'Simple Moving Average (SMA)'
low_f := ta.sma(low, look_back_period)
else if low_impact_calculation == 'Exponentially Weighted Moving Average (EMA)'
low_f := ta.ema(low, look_back_period)
else if low_impact_calculation == 'Hull Moving Average (HMA)'
low_f := ta.hma(low, look_back_period)
else if low_impact_calculation == 'Exponentially Weighted Moving average with alpha length (RMA)'
low_f := ta.rma(low, look_back_period)
else if low_impact_calculation == 'Weighted Moving Average (WMA)'
low_f := ta.wma(low, look_back_period)
else if low_impact_calculation == 'Arnaud Legoux Moving Average (ALMA)'
low_f := ta.alma(low, look_back_period,0,3)
else if low_impact_calculation == 'Symmetrically weighted moving average with fixed length (SWMA)'
low_f := ta.swma(low)
else if low_impact_calculation == 'Volume-weighted Moving Average (VWMA)'
low_f := ta.vwma(low, look_back_period)
indicator_low_14 = low_f
[middle_low_14, upper_low_14, lower_low_14] = ta.bb(indicator_low_14, 5, 4)
bb_gap_of_low_14 = indicator_low_14 - middle_low_14
st_dev_of_bb_gap_of_low_14 = ta.stdev(bb_gap_of_low_14, look_back_period)
st_dev_of_indicator_low_14 = ta.stdev(indicator_low_14, look_back_period)
corelation_btw_price_avg_14_and_indicator_low_14 = ta.correlation(indicator_low_14,price_avg_14,look_back_period)
first_degree_indicator_low_14 = st_dev_of_indicator_low_14 * corelation_btw_price_avg_14_and_indicator_low_14 * st_dev_of_bb_gap_of_low_14
//open
var float open_f = 0
if open_impact_calculation == 'Lenior regression'
open_f := ta.linreg(open, look_back_period, 0)
else if open_impact_calculation == 'Simple Moving Average (SMA)'
open_f := ta.sma(open, look_back_period)
else if open_impact_calculation == 'Exponentially Weighted Moving Average (EMA)'
open_f := ta.ema(open, look_back_period)
else if open_impact_calculation == 'Hull Moving Average (HMA)'
open_f := ta.hma(open, look_back_period)
else if open_impact_calculation == 'Exponentially Weighted Moving average with alpha length (RMA)'
open_f := ta.rma(open, look_back_period)
else if open_impact_calculation == 'Weighted Moving Average (WMA)'
open_f := ta.wma(open, look_back_period)
else if open_impact_calculation == 'Arnaud Legoux Moving Average (ALMA)'
open_f := ta.alma(open, look_back_period,0,3)
else if open_impact_calculation == 'Symmetrically weighted moving average with fixed length (SWMA)'
open_f := ta.swma(open)
else if open_impact_calculation == 'Volume-weighted Moving Average (VWMA)'
open_f := ta.vwma(open, look_back_period)
indicator_open_14 = open_f
[middle_open_14, upper_open_14, lower_open_14] = ta.bb(indicator_open_14, 5, 4)
bb_gap_of_open_14 = indicator_open_14 - middle_open_14
st_dev_of_bb_gap_of_open_14 = ta.stdev(bb_gap_of_open_14, look_back_period)
st_dev_of_indicator_open_14 = ta.stdev(indicator_open_14, look_back_period)
corelation_btw_price_avg_14_and_indicator_open_14 = ta.correlation(indicator_open_14,price_avg_14,look_back_period)
first_degree_indicator_open_14 = st_dev_of_indicator_open_14 * corelation_btw_price_avg_14_and_indicator_open_14 * st_dev_of_bb_gap_of_open_14
//close
var float close_f = 0
if close_impact_calculation == 'Lenior regression'
close_f := ta.linreg(close, look_back_period, 0)
else if close_impact_calculation == 'Simple Moving Average (SMA)'
close_f := ta.sma(close, look_back_period)
else if close_impact_calculation == 'Exponentially Weighted Moving Average (EMA)'
close_f := ta.ema(close, look_back_period)
else if close_impact_calculation == 'Hull Moving Average (HMA)'
close_f := ta.hma(close, look_back_period)
else if close_impact_calculation == 'Exponentially Weighted Moving average with alpha length (RMA)'
close_f := ta.rma(close, look_back_period)
else if close_impact_calculation == 'Weighted Moving Average (WMA)'
close_f := ta.wma(close, look_back_period)
else if close_impact_calculation == 'Arnaud Legoux Moving Average (ALMA)'
close_f := ta.alma(close, look_back_period,0,3)
else if close_impact_calculation == 'Symmetrically weighted moving average with fixed length (SWMA)'
close_f := ta.swma(close)
else if close_impact_calculation == 'Volume-weighted Moving Average (VWMA)'
close_f := ta.vwma(close, look_back_period)
indicator_close_14 = close_f
[middle_close_14, upper_close_14, lower_close_14] = ta.bb(indicator_close_14, 5, 4)
bb_gap_of_close_14 = indicator_close_14 - middle_close_14
st_dev_of_bb_gap_of_close_14 = ta.stdev(bb_gap_of_close_14, look_back_period)
st_dev_of_indicator_close_14 = ta.stdev(indicator_close_14, look_back_period)
corelation_btw_price_avg_14_and_indicator_close_14 = ta.correlation(indicator_close_14,price_avg_14,look_back_period)
first_degree_indicator_close_14 = st_dev_of_indicator_close_14 * corelation_btw_price_avg_14_and_indicator_close_14 * st_dev_of_bb_gap_of_close_14
//Primary indicator
all_indicators_final_graph = first_degree_indicator_sar_14 + first_degree_indicator_st_14 + first_degree_indicator_rsi_14 + first_degree_indicator_mfi_14 + first_degree_indicator_bop_14 + first_degree_indicator_mom_14 + first_degree_indicator_cog_14+ first_degree_indicator_dmi_14 + first_degree_indicator_stoch_14 + first_degree_indicator_swma_14 + first_degree_indicator_wpr_14 + first_degree_indicator_tsi_14 + first_degree_indicator_iii_14 + first_degree_indicator_nvi_14 + first_degree_indicator_pvi_14 + first_degree_indicator_obv_14 + first_degree_indicator_accdist_14 + first_degree_indicator_pvt_14 + first_degree_indicator_tr_14 + first_degree_indicator_vwap_14 + first_degree_indicator_wad_14 + first_degree_indicator_sma_14 + first_degree_indicator_ema_14 + first_degree_indicator_cci_14 + first_degree_indicator_chop_zone_14 + first_degree_indicator_eom_14 + first_degree_indicator_dpo_14 + first_degree_indicator_adl_14 + first_degree_indicator_bbp_14 + first_degree_indicator_high_14 + first_degree_indicator_low_14 + first_degree_indicator_open_14 + first_degree_indicator_close_14
//st. dev, co-relation, degree of change and rate of change of primary indicator
st_dev_of_all_indicators_final_graph = ta.stdev(all_indicators_final_graph, look_back_period)
corelation_btw_price_avg_14_and_all_indicators_final_graph = ta.correlation(all_indicators_final_graph,price_avg_14,look_back_period)
first_degree_change_of_st_dev_of_all_indicators_final_graph = ta.change(all_indicators_final_graph, 2)
first_degree_of_rate_of_change_first_degree_change_of_st_dev_of_all_indicators_final_graph = 100 * (ta.change(first_degree_change_of_st_dev_of_all_indicators_final_graph, 2)/ first_degree_change_of_st_dev_of_all_indicators_final_graph[1])
final_graph_of_corelation = all_indicators_final_graph * corelation_btw_price_avg_14_and_all_indicators_final_graph
final_graph_of_st_dev = corelation_btw_price_avg_14_and_all_indicators_final_graph * st_dev_of_all_indicators_final_graph
//final_graph_of_corelation
st_dev_of_final_graph_of_corelation = ta.stdev(final_graph_of_corelation, look_back_period)
corelation_btw_price_avg_14_and_final_graph_of_corelation = ta.correlation(final_graph_of_corelation,price_avg_14,look_back_period)
second_degree_change_of_st_dev_of_final_graph_of_corelation = ta.change(final_graph_of_corelation, 2)
second_degree_of_rate_of_change_first_degree_change_of_st_dev_of_all_indicators_final_graph_1 = 100 * (ta.change(second_degree_change_of_st_dev_of_final_graph_of_corelation, 2)/ second_degree_change_of_st_dev_of_final_graph_of_corelation[1])
second_degree_final_graph_of_corelation_one = final_graph_of_corelation * corelation_btw_price_avg_14_and_final_graph_of_corelation
second_degree_final_graph_of_st_dev_one = corelation_btw_price_avg_14_and_final_graph_of_corelation * st_dev_of_final_graph_of_corelation
//final_graph_of_st_dev
st_dev_of_final_graph_of_st_dev = ta.stdev(final_graph_of_st_dev, look_back_period)
corelation_btw_price_avg_14_and_final_graph_of_st_dev = ta.correlation(final_graph_of_st_dev,price_avg_14,look_back_period)
second_degree_change_of_st_dev_of_final_graph_of_st_dev = st_dev_of_final_graph_of_st_dev - st_dev_of_final_graph_of_st_dev [1]
second_degree_of_rate_of_change_first_degree_change_of_st_dev_of_all_indicators_final_graph_2 = second_degree_change_of_st_dev_of_final_graph_of_st_dev - second_degree_change_of_st_dev_of_final_graph_of_st_dev[1]
second_degree_final_graph_of_corelation_two = final_graph_of_st_dev * corelation_btw_price_avg_14_and_final_graph_of_st_dev
second_degree_final_graph_of_st_dev_two = corelation_btw_price_avg_14_and_final_graph_of_st_dev * st_dev_of_final_graph_of_st_dev
//second_degree_final_graph_of_corelation_one
st_dev_of_second_degree_final_graph_of_corelation_one = ta.stdev(second_degree_final_graph_of_corelation_one, look_back_period)
corelation_btw_price_avg_14_and_second_degree_final_graph_of_corelation_one = ta.correlation(second_degree_final_graph_of_corelation_one,price_avg_14,look_back_period)
third_degree_final_graph_of_corelation_three = second_degree_final_graph_of_corelation_one * corelation_btw_price_avg_14_and_second_degree_final_graph_of_corelation_one
//second_degree_final_graph_of_corelation_two
st_dev_of_second_degree_final_graph_of_corelation_two = ta.stdev(second_degree_final_graph_of_corelation_two, look_back_period)
corelation_btw_price_avg_14_and_second_degree_final_graph_of_corelation_two = ta.correlation(second_degree_final_graph_of_corelation_two,price_avg_14,look_back_period)
third_degree_final_graph_of_corelation_four = st_dev_of_second_degree_final_graph_of_corelation_two * corelation_btw_price_avg_14_and_second_degree_final_graph_of_corelation_two
//final_graph_of_corelation
change_of_final_graph_of_corelation = final_graph_of_corelation - final_graph_of_corelation[1]
second_level_change_of_change_of_final_graph_of_corelation = (change_of_final_graph_of_corelation - change_of_final_graph_of_corelation[1])*math.pow(ta.correlation(change_of_final_graph_of_corelation,price_avg_14,look_back_period),3)*ta.stdev(change_of_final_graph_of_corelation, look_back_period)
//Graph Identification
show_graph_1 = input.bool(defval = false, title = "(1) Show Cumilative graph(CG)", group = "Graphs")
show_graph_2 = input.bool(defval = false, title = "(2) CG corelation to price", group = "Graphs")
show_graph_3 = input.bool(defval = false, title = "(3) St dev of CG", group = "Graphs")
show_graph_4 = input.bool(defval = false, title = "(4) Degree of change - CG", group = "Graphs")
show_graph_5 = input.bool(defval = false, title = "(5) Rate of change - CG", inline = 'Graph 5', group = "Graphs")
scale_of_graph_5 = input.int(defval = 1, title = "& scale (n) will be 10 to the power n", inline = 'Graph 5', group = "Graphs")
show_graph_6 = input.bool(defval = false, title = "(6) Co-relation of CG (CCG), corelation to price", group = "Graphs")
show_graph_7 = input.bool(defval = false, title = "(7) St dev of corelation of CCG", group = "Graphs")
show_graph_8 = input.bool(defval = false, title = "(8) Degree of change - CCG", group = "Graphs")
show_graph_9 = input.bool(defval = false, title = "(9) Rate of change - CCG", inline = 'Graph 9', group = "Graphs")
scale_of_graph_9 = input.int(defval = 1, title = "& scale (n) will be 10 to the power n", inline = 'Graph 9', group = "Graphs")
show_graph_10 = input.bool(defval = false, title = "(10) STDV of CG (SCG), corelation to price", group = "Graphs")
show_graph_11 = input.bool(defval = false, title = "(11) St dev of corelation of SCG", group = "Graphs")
show_graph_12 = input.bool(defval = false, title = "(12) Degree of change - SCG", group = "Graphs")
show_graph_13 = input.bool(defval = false, title = "(13) Rate of change - SCG", inline = 'Graph 13', group = "Graphs")
scale_of_graph_13 = input.int(defval = 1, title = "& scale (n) will be 10 to the power n", inline = 'Graph 13', group = "Graphs")
show_graph_14 = input.bool(defval = false, title = "(14) Third degree cor to price", group = "Graphs")
show_graph_15 = input.bool(defval = false, title = "(15) Third degree cor to price", group = "Graphs")
show_graph_16 = input.bool(defval = false, title = "(16) Change of graph no 2", group = "Graphs")
graph_1 = all_indicators_final_graph
graph_2 = final_graph_of_corelation
graph_3 = final_graph_of_st_dev
graph_4 = first_degree_change_of_st_dev_of_all_indicators_final_graph
graph_5 = first_degree_of_rate_of_change_first_degree_change_of_st_dev_of_all_indicators_final_graph
graph_6 = second_degree_final_graph_of_corelation_one
graph_7 = second_degree_final_graph_of_st_dev_one
graph_8 = second_degree_change_of_st_dev_of_final_graph_of_corelation
graph_9 = second_degree_of_rate_of_change_first_degree_change_of_st_dev_of_all_indicators_final_graph_1
graph_10 = second_degree_final_graph_of_corelation_two
graph_11 = second_degree_final_graph_of_st_dev_two
graph_12 = second_degree_change_of_st_dev_of_final_graph_of_st_dev
graph_13 = second_degree_of_rate_of_change_first_degree_change_of_st_dev_of_all_indicators_final_graph_2
graph_14 = third_degree_final_graph_of_corelation_three
graph_15 = third_degree_final_graph_of_corelation_four
graph_16 = second_level_change_of_change_of_final_graph_of_corelation
//buy signal generation
buy_1 = price_falling and ta.crossunder(graph_7,0)
buy_2 = price_falling and ta.cross(graph_11,0)
buy_3 = price_falling and ta.cross(graph_5,0) and ta.cross(graph_9,0) and ta.cross(graph_13,0)
buy_4 = price_falling and ta.cross(graph_4,0) and ta.cross(graph_8,0) and ta.cross(graph_12,0)
buy_5 = price_falling and ta.cross(graph_2,0) and ta.cross(graph_3,0) and ta.cross(graph_4,0)
buy_6 = price_falling and ta.cross(graph_4,graph_8) and ta.cross(graph_4,graph_12) and ta.cross(graph_12,graph_8)
// Trading Arrangement
//Buy and Sell range
hi_high = ta.highest(buy_comand_high_value,buy_or_sell_lookback)
lowerlowest = ta.lowest(buy_comand_low_value,buy_or_sell_lookback)
var float hi_point = na
var float low_point = na
for i = 1 to 0 by 1
if hi_high[i] < hi_high[i+1]
hi_point := hi_high[i+1]
else if lowerlowest [i] > lowerlowest [i+1]
low_point := lowerlowest [i+1]
//Trading Arrangement
// Generate sell signal
var bool sell_comand = false
[pinesupertrend, pinedirection] = ta.supertrend(factor_of_supertrend_to_determine_sell_comand, artperiod_of_supertrend_to_determine_sell_comand)
if pinedirection[1] < 0 and pinedirection > 0
sell_comand := true
else if pinedirection > 0 and (buy_1 or buy_2 or buy_3 or buy_4 or buy_5 or buy_6)
sell_comand := true
else
sell_comand := false
//Intermediate selling count & Count of open trades
var int open_trades = 0
var int x = 0
if strategy.position_size == 0
open_trades := 0
else if strategy.position_size[1] == 0 and strategy.position_size > 0
open_trades := 1
else if strategy.position_size[1] < strategy.position_size
open_trades := open_trades + 1
else if strategy.position_size[1] > strategy.position_size and strategy.position_size > 0
open_trades := open_trades - 1
else
open_trades := open_trades
if strategy.position_size[1] < strategy.position_size and strategy.position_size[1] > 0
x := open_trades
else if strategy.position_size[1] < strategy.position_size and strategy.position_size[1] == 0
x := 1
else if strategy.position_size[1] > strategy.position_size and strategy.position_size > 0
x := x - 1
else if strategy.position_size[1] > strategy.position_size and strategy.position_size == 0
x := 0
else
x := x
// Max count of open trades
var float max_open_trades = 0
if strategy.opentrades > max_open_trades
max_open_trades := strategy.opentrades
else
max_open_trades := max_open_trades
// Contrall Selling
var bool int_selling = false
if strategy.opentrades == strategy.opentrades [1] and intermidiate_selling == true
int_selling := true
else if strategy.opentrades == strategy.opentrades [1] - 1 or intermidiate_selling == false
int_selling := false
// Calculation of profit precentage
var float cal_profit_precentage = 0
if strategy.position_size == 0
cal_profit_precentage := na
else if strategy.position_size > 0
cal_profit_precentage := (profit_precentage/100) + 1
else
cal_profit_precentage := cal_profit_precentage
//Open trades entry price
var float result = 0
for i = 0 to strategy.opentrades-1
result := strategy.opentrades.entry_price(i)
var int y = 0
var int z = 0
if strategy.position_size[1] > 0 and strategy.position_size == 0
y := 0
z := 0
else if strategy.position_size[1] == 0 and strategy.position_size > 0
y := 1
z := 1
else if strategy.position_size[1] > strategy.position_size and strategy.position_size[1] > 0 and strategy.position_size > 0
y := y - 1
z := z + 1
else if strategy.position_size[1] < strategy.position_size and strategy.position_size[1] > 0 and strategy.position_size > 0
z := z + 1
y := y + 1
m = result
// Fund management - r value calculation
var float int_val_3 = 0
var float installment_2 = 0
var float installment_3 = 0
var float installment_4 = 0
var float r_f = 0
var float int_val = 0
if int_cap * int_val_prc/100 <= 15 and int_val_allocation != "USDT"
int_val := 15
if int_val_prc <= 15 and int_val_allocation == "USDT"
int_val := 15
if int_cap * int_val_prc/100 > 15 and int_val_allocation != "USDT"
int_val := int_cap * int_val_prc/100
if int_val_prc > 15 and int_val_allocation == "USDT"
int_val := int_val_prc
var float r_change = 0
if r_finetune == false
r_change := r_change_input
else if r_finetune == true
r_change := 0.001
for i = 0 to piramiding+2 by 1
if i == 0
int_val_3 := int_val
if i <= piramiding
installment_2 := int_val_3*math.pow((1 + r/100),i)
if i >= 0 and i < piramiding+1
installment_3 := installment_3 + installment_2
if i == piramiding+1
installment_4 := installment_3 - installment_3[1]
if installment_4 < int_cap
r := r + r_change
else if installment_4 > int_cap
r := r - r_change
else
r := r
if r[1] < r
r_f := r[1]
//Fund Management
var float total_investment = int_cap
if strategy.position_size[1] >0 and strategy.position_size == 0
total_investment := int_cap + strategy.netprofit
else
total_investment := total_investment
// Stratergy possition size
var float last_purchase = 0
if strategy.position_size[1] < strategy.position_size and strategy.position_size[1] == 0
last_purchase := strategy.position_size
else if strategy.position_size[1] < strategy.position_size and strategy.position_size[1] > 0
last_purchase := (strategy.position_size - strategy.position_size[1])
else if strategy.position_size == 0
last_purchase := 0
else
last_purchase := last_purchase
//Quantity Calculation
var float value_of_purchase = 0
var float initial_quantity = 0
if purchaseing_method == 'Equal amounts' and dev_of_equal_amounts == 'Equal amounts with fixed entries'
value_of_purchase := (total_investment/(piramiding + 1))
else if purchaseing_method == 'Equal amounts' and dev_of_equal_amounts == 'Equal amounts with fixed USDT'
value_of_purchase := int_val_prc
if purchaseing_method == 'Incremental amounts' and int_val_allocation == '% of cumilative investment'
value_of_purchase := (total_investment * (int_val_prc/100))* math.pow((1+(r_value/100)),y)
else if purchaseing_method == 'Incremental amounts' and int_val_allocation == 'USDT'
value_of_purchase := (int_val_prc)* math.pow((1 + (r_value/100)),y)
var float final_value_of_purchase = 0
if value_of_purchase <= 21
final_value_of_purchase := 21
else
final_value_of_purchase := value_of_purchase
quantity = final_value_of_purchase/low
var float r_ff = 0
if purchaseing_method == 'Equal amounts'
r_ff := na
else
r_ff := r_f
//current expenditure
currentexpenditure() =>
result_v2 = 0.
for i = 0 to strategy.opentrades-1
result_v2 += strategy.opentrades.entry_price(i) * strategy.opentrades.size(i)
strategy.opentrades > 0 ? result_v2 : na
//cash in hand
var float cash_in_hand = 0
if currentexpenditure() > 0
cash_in_hand := total_investment - currentexpenditure()
else
cash_in_hand := total_investment
//unrealised profit
unrealised_profit = (high+low)/2*strategy.position_size - currentexpenditure()
//last entry price
lastentryprice() =>
result_v3 = 0.
for i = 0 to strategy.opentrades-1
result_v3 := strategy.opentrades.entry_price(i)// * strategy.opentrades.size(i)
strategy.opentrades > 0 ? result_v3 : na
var float last_entry_price = 0
var index_of_array_maxval = 0
var index_of_array_minval = 0
var entryprice = array.new_float(49)
if currentexpenditure() [1] < currentexpenditure()
last_entry_price := lastentryprice()
array.push(entryprice, last_entry_price)
else if strategy.opentrades [1] == 0 and strategy.opentrades > 0
last_entry_price := lastentryprice()
array.push(entryprice, last_entry_price)
else if strategy.position_size == 0
last_entry_price := 0
array.clear(entryprice)
array_maxval = array.max(entryprice)
array_minval = array.min(entryprice)
if array.lastindexof(entryprice, array_maxval) >= 0
index_of_array_maxval := array.lastindexof(entryprice, array_maxval) + 1
index_of_array_minval := array.lastindexof(entryprice, array_minval) + 1
else
index_of_array_maxval := na
index_of_array_minval := na
if ta.sma(close,9)> array_minval*(1 + profit_precentage_intermidiate/100)// and int_selling == true and hi_point[1] and low_point and strategy.position_avg_price > ma_9
array.clear(entryprice)
//Calculation of profit line
var float profit_line = 0
profit_line_nf = strategy.position_avg_price * cal_profit_precentage
//strategy.position_avg_price * cal_profit_precentage
if strategy.position_size[1] == 0 and strategy.position_size > 0
profit_line := profit_line_nf
else if strategy.position_size [1] < strategy.position_size
profit_line := profit_line - profit_line_nf[1] + profit_line_nf
else if strategy.position_size [1] > strategy.position_size
profit_line := profit_line [1]
else if strategy.opentrades == 0
profit_line := 0
// count of max trade count
var int max_trade_count = 0
if purchaseing_method == 'Incremental amounts'
max_trade_count := piramiding - 1
else if purchaseing_method == 'Equal amounts' and dev_of_equal_amounts == 'Equal amounts with fixed USDT'
max_trade_count := math.floor(total_investment / int_val_prc) - 1
else if purchaseing_method == 'Equal amounts' and dev_of_equal_amounts == 'Equal amounts with fixed entries'
max_trade_count := piramiding - 1
//Enter Coustom comand to perform buy and sell actions link with webhook
string buy_comment = "BUY"
string sell_comment = "SELL"
//Trading
if ((buy_1 or buy_2 or buy_3 )) and window and strategy.position_size == 0 and source_of_lower_point < low_point
strategy.entry("long", strategy.long, comment = buy_comment, qty = quantity)
else if ((buy_1 or buy_2 or buy_3 or buy_4 ) and window and ma_9 < strategy.position_avg_price *.99 and strategy.position_size > 0 ) and strategy.opentrades <= (max_trade_count * 0.75) //and source_of_lower_point < low_point
strategy.entry("long", strategy.long, comment = buy_comment, qty = quantity)
else if ((buy_6) and ma_9 < strategy.position_avg_price and window and strategy.position_size > 0 ) and strategy.opentrades > (max_trade_count * 0.75) and strategy.opentrades <= max_trade_count //and source_of_lower_point < low_point
strategy.entry("long", strategy.long, comment = buy_comment, qty = quantity)
if (sell_comand==true) and profit_line < ma_9 and hi_point[1] and low_point
strategy.close("long", qty = strategy.position_size, comment = sell_comment)
//intermediate selling
if ta.sma(close,9)> array_minval*(1 + profit_precentage_intermidiate/100) and int_selling == true and hi_point[1] and low_point and strategy.position_avg_price > ma_9
strategy.close("long", qty = last_purchase[x], comment = sell_comment)
//Graphs
//color change
plot(r_ff, title = "Calculated R value", color = color.new(color.white,100))
plot(strategy.position_avg_price, title = "AVG", color = color.green, style = plot.style_circles)
plot(profit_line, title = "Adj.Profit", color = color.yellow, style = plot.style_circles)
plot(strategy.opentrades, title = "Numbers of open trades", color = color.new(color.white,100))
plot(max_open_trades, title = "Max Opentrades", color = color.new(color.red,100))
plot(strategy.netprofit, title = "Cumilative Profit", color = color.new(color.white,100))
plot(unrealised_profit, title = "Unrealised Profit", color = color.new(color.blue,100))
plot(currentexpenditure(), title = "Current Expenditure", color = color.new(color.blue,100))
plot(cash_in_hand, title = "Cash in Hand", color = color.new(color.blue,100))
plot(total_investment, title = "Total Investment", color = color.new(color.white,100))
plot(last_purchase, title = "Quantity Last purchase", color = color.new(color.white,100))
plot(final_value_of_purchase, title = "Value of Purchase", color = color.new(color.white,100))
//plot(last_entry_price, title = "Lastentry Price", color = color.new(color.blue,100))
//plot(result, title = "Entry Price", color = color.new(color.white,100))
hidden_color = color.new(color.white,100)
var color_1 = color.white
var color_2 = color.red
var color_3 = color.yellow
var color_4 = color.blue
var color_5 = color.green
var color_6 = color.orange //line
var color_7 = color.maroon //bar
var color_8 = color.new(color.gray,50) //area
var color_9 = color.new(color.aqua,50) //area
var color_10 = color.orange //line
var color_11 = color.maroon //bar
var color_12 = color.new(color.gray,50) //area
var color_13 = color.new(color.aqua,50) //area
var color_14 = color.orange //line
var color_15 = color.maroon //bar
var color_16 = color.maroon //bar
if show_graph_1 == true
color_1 := color.white
else
color_1 := hidden_color
if show_graph_2 == true
color_2 := color.red
else
color_2 := hidden_color
if show_graph_3 == true
color_3 := color.new(color.yellow,50)
else
color_3 := hidden_color
if show_graph_4 == true
color_4 := color.new(color.blue,50)
else
color_4 := hidden_color
if show_graph_5 == true
color_5 := color.new(color.green,30)
else
color_5 := hidden_color
if show_graph_6 == true
color_6 := color.orange
else
color_6 := hidden_color
if show_graph_7 == true
color_7 := color.green
else
color_7 := hidden_color
if show_graph_8 == true
color_8 := color.new(color.silver,50)
else
color_8 := hidden_color
if show_graph_9 == true
color_9 := color.new(color.yellow,50)
else
color_9 := hidden_color
if show_graph_10 == true
color_10 := color.new(color.teal,50)
else
color_10 := hidden_color
if show_graph_11 == true
color_11 := color.new(color.maroon,50)
else
color_11 := hidden_color
if show_graph_12 == true
color_12 := color.new(color.aqua,50)
else
color_12 := hidden_color
if show_graph_13 == true
color_13 := color.new(color.red,50)
else
color_13 := hidden_color
if show_graph_14 == true
color_14 := color.new(color.red,50)
else
color_14 := hidden_color
if show_graph_15 == true
color_15 := color.new(color.blue,50)
else
color_15 := hidden_color
if show_graph_16 == true
color_16 := color.new(color.blue,50)
else
color_16 := hidden_color
hline(0, color = color.white, title = "o")
plot(show_graph_1 == true ? graph_1:na, color = color_1, title = "(1) Cumilative graph(CG)", style = plot.style_linebr)
plot(show_graph_2 == true ? graph_2:na, color = color_2, title = "(2) CG corelation to price", style = plot.style_linebr)
plot(show_graph_3 == true ? graph_3:na, color = color_3, title = "(3) St dev of CG", style = plot.style_columns)
plot(show_graph_4 == true ? graph_4:na, color = color_4, title = "(4) Degree of change - CG", style = plot.style_linebr)
plot(show_graph_5 == true ? graph_5*math.pow(10,scale_of_graph_5):na, color = color_5, title = "(5) Rate of change - CG", style = plot.style_area)
plot(show_graph_6 == true ? graph_6:na, color = color_6, title = "(6) corelation of CG (CCG), corelation to price", style = plot.style_linebr)
plot(show_graph_7 == true ? graph_7:na, color = color_7, title = "(7) St dev of corelation of CCG", style = plot.style_columns)
plot(show_graph_8 == true ? graph_8:na, color = color_8, title = "(8) Degree of change - CCG", style = plot.style_linebr)
plot(show_graph_9 == true ? graph_9*math.pow(10,scale_of_graph_9):na, color = color_9, title = "(9) Rate of change - CCG", style = plot.style_area)
plot(show_graph_10 == true ? graph_10:na, color = color_10, title = "(10) STDV of CG (SCG), corelation to price", style = plot.style_linebr)
plot(show_graph_11 == true ? graph_11:na, color = color_11, title = "(11) St dev of corelation of SCG", style = plot.style_columns)
plot(show_graph_12 == true ? graph_12:na, color = color_12, title = "(12) Degree of change - SCG", style = plot.style_linebr)
plot(show_graph_13 == true ? graph_13*math.pow(10,scale_of_graph_13):na, color = color_13, title = "(13) Rate of change - SCG", style = plot.style_area)
plot(show_graph_14 == true ? graph_14:na, color = color_14, title = "(14) Third degree cor to price", style = plot.style_linebr)
plot(show_graph_15 == true ? graph_15:na, color = color_15, title = "(15) Third degree cor to price", style = plot.style_columns)
plot(show_graph_16 == true ? ta.ema(graph_16,14):na, color = color_16, title = "(16) Degree of change - SCG", style = plot.style_area)
plotshape(ma_9 < strategy.position_avg_price *.99 and strategy.opentrades <= (max_trade_count * 0.75) ? buy_1: na, style = shape.arrowdown, location = location.abovebar, size = size.large, text = "1")
plotshape(ma_9 < strategy.position_avg_price *.99 and strategy.opentrades <= (max_trade_count * 0.75) ? buy_2: na, style = shape.arrowdown, location = location.abovebar, size = size.large, text = "2")
plotshape(ma_9 < strategy.position_avg_price *.99 and strategy.opentrades <= (max_trade_count * 0.75) ? buy_3: na, style = shape.arrowdown, location = location.abovebar, size = size.large, text = "3")
plotshape(ma_9 < strategy.position_avg_price *.99 and strategy.opentrades <= (max_trade_count * 0.75) ? buy_4: na, style = shape.arrowdown, location = location.abovebar, size = size.large, text = "4", color = color.green)
plotshape(ma_9 < strategy.position_avg_price *.99 and strategy.opentrades <= (max_trade_count * 0.75) ? buy_5: na, style = shape.arrowdown, location = location.abovebar, size = size.large, text = "5", color = color.red)
plotshape(ma_9 < strategy.position_avg_price *.99 ? buy_6: na, style = shape.arrowdown, location = location.abovebar, size = size.large, text = "6", color = color.orange)
//Table
var tbl = table.new(position.top_right, 2, 9, frame_color=#151715, frame_width=1, border_width=2, border_color=color.new(color.white, 100))
//column values
table.cell(tbl, 0,0, text = "Cumilative profit (USDT)", text_color = color.white, text_halign = text.align_left, text_valign = text.align_center, bgcolor = color.green)
table.cell(tbl, 0,1, text = "Current Expenditure", text_color = color.red, text_halign = text.align_left, text_valign = text.align_center)
table.cell(tbl, 0,2, text = "Cash balance", text_color = color.red, text_halign = text.align_left, text_valign = text.align_center)
table.cell(tbl, 0,3, text = "Cumilative assert (USDT)", text_color = color.red, text_halign = text.align_left, text_valign = text.align_center)
table.cell(tbl, 0,4, text = "Count of open trades", text_color = color.red, text_halign = text.align_left, text_valign = text.align_center)
table.cell(tbl, 0,5, text = "Strategy position Size", text_color = color.red, text_halign = text.align_left, text_valign = text.align_center)
table.cell(tbl, 1,0, str.tostring(strategy.netprofit, format.mintick), text_color = color.white, text_halign = text.align_right, text_valign = text.align_center, bgcolor = color.green)
table.cell(tbl, 1,1, str.tostring(currentexpenditure(), format.mintick), text_color = color.red, text_halign = text.align_right, text_valign = text.align_center)
table.cell(tbl, 1,2, str.tostring(cash_in_hand, format.mintick), text_color = color.red, text_halign = text.align_right, text_valign = text.align_center)
table.cell(tbl, 1,3, str.tostring(total_investment, format.mintick), text_color = color.red, text_halign = text.align_right, text_valign = text.align_center)
table.cell(tbl, 1,4, str.tostring(strategy.opentrades, format.mintick), text_color = color.red, text_halign = text.align_right, text_valign = text.align_center)
table.cell(tbl, 1,5, str.tostring(strategy.position_size, format.mintick), text_color = color.red, text_halign = text.align_right, text_valign = text.align_center)
|
Mayer Multiple Strategy | https://www.tradingview.com/script/TlNlaIid-Mayer-Multiple-Strategy/ | xtradernet | https://www.tradingview.com/u/xtradernet/ | 19 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © xtradernet
//@version=4
// Quick script to backtest a strategy based on Mayer Multiple
strategy("Mayer Multiple Strategy", shorttitle="Mayer_Crypto", overlay=true)
length = input(200, type=input.integer, title="Price SMA Length")
threshold = input(1.48, step=.1, type=input.float, title="Threshold")
exit = input(1.70, step=.1, type=input.float, title="Exit Level")
// Bitcoin price / 200 day moving average value = Mayer Multiple
ma = sma(close, length)
multiple = close / ma
if (crossunder(threshold,multiple))
strategy.entry("Long", strategy.long, comment="MayerLong")
strategy.close("Long", when=crossover(multiple,exit), comment="MayerClose")
|
CCI Strategy | https://www.tradingview.com/script/0QgigMhj-CCI-Strategy/ | REV0LUTI0N | https://www.tradingview.com/u/REV0LUTI0N/ | 160 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © REV0LUTI0N
//@version=4
strategy(title="CCI Strategy", overlay=true, initial_capital = 10000, default_qty_value = 10000, default_qty_type = strategy.cash)
//CCI Code
length = input(20, minval=1, title="CCI Length")
src = input(close, title="Source")
ma = sma(src, length)
cci = (src - ma) / (0.015 * dev(src, length))
// Strategy Backtesting
startDate = input(timestamp("2021-10-01T00:00:00"), type = input.time, title='Backtesting Start Date')
finishDate = input(timestamp("9999-12-31T00:00:00"), type = input.time, title='Backtesting End Date')
time_cond = time >= startDate and time <= finishDate
//Time Restriction Settings
startendtime = input("", title='Time Frame To Enter Trades')
enableclose = input(false, title='Enable Close Trade At End Of Time Frame')
timetobuy = (time(timeframe.period, startendtime))
timetoclose = na(time(timeframe.period, startendtime))
//Strategy Settings
//Strategy Settings - Enable Check Boxes
enableentry = input(true, title="Enter First Trade ASAP")
enableconfirmation = input(false, title="Wait For Cross To Enter First Trade")
enablezero =input(true, title="Use CCI Simple Cross Line For Entries & Exits")
enablebands = input(false, title="Use Upper & Lower Bands For Entries & Exits")
//Strategy Settings - Band Sources
ccisource = input(0, title="CCI Simple Cross")
upperbandsource =input(100, title="CCI Enter Long Band")
upperbandexitsource =input(100, title="CCI Exit Long Band")
lowerbandsource =input(-100, title="CCI Enter Short Band")
lowerbandexitsource =input(-100, title="CCI Exit Short Band")
//Strategy Settings - Crosses
simplecrossup = crossover(cci, ccisource)
simplecrossdown = crossunder(cci, ccisource)
uppercrossup = crossover(cci, upperbandsource)
lowercrossdown = crossunder(cci, lowerbandsource)
uppercrossdown = crossunder(cci, upperbandexitsource)
lowercrossup = crossover(cci, lowerbandexitsource)
upperstop = crossunder(cci, upperbandsource)
lowerstop = crossover(cci, lowerbandsource)
// Stop Loss & Take Profit % Based
enablesl = input(false, title='Enable Stop Loss')
enabletp = input(false, title='Enable Take Profit')
stopTick = input(5.0, title='Stop Loss %', type=input.float, step=0.1) / 100
takeTick = input(10.0, title='Take Profit %', type=input.float, step=0.1) / 100
longStop = strategy.position_avg_price * (1 - stopTick)
shortStop = strategy.position_avg_price * (1 + stopTick)
shortTake = strategy.position_avg_price * (1 - takeTick)
longTake = strategy.position_avg_price * (1 + takeTick)
plot(strategy.position_size > 0 and enablesl ? longStop : na, style=plot.style_linebr, color=color.red, linewidth=1, title="Long Fixed SL")
plot(strategy.position_size < 0 and enablesl ? shortStop : na, style=plot.style_linebr, color=color.red, linewidth=1, title="Short Fixed SL")
plot(strategy.position_size > 0 and enabletp ? longTake : na, style=plot.style_linebr, color=color.green, linewidth=1, title="Long Take Profit")
plot(strategy.position_size < 0 and enabletp ? shortTake : na, style=plot.style_linebr, color=color.green, linewidth=1, title="Short Take Profit")
// Alert messages
message_enterlong = input("", title="Long Entry message")
message_entershort = input("", title="Short Entry message")
message_closelong = input("", title="Close Long message")
message_closeshort = input("", title="Close Short message")
//Strategy Execution
//Strategy Execution - Simple Line Cross
if (cci > ccisource and enablezero and enableentry and time_cond and timetobuy)
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if (cci < ccisource and enablezero and enableentry and time_cond and timetobuy)
strategy.entry("Short", strategy.short, alert_message = message_entershort)
if (simplecrossup and enablezero and enableconfirmation and time_cond and timetobuy)
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if (simplecrossdown and enablezero and enableconfirmation and time_cond and timetobuy)
strategy.entry("Short", strategy.short, alert_message = message_entershort)
//Strategy Execution - Upper and Lower Band Entry
if (uppercrossup and enablebands and time_cond and timetobuy)
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if (lowercrossdown and enablebands and time_cond and timetobuy)
strategy.entry("Short", strategy.short, alert_message = message_entershort)
//Strategy Execution - Upper and Lower Band Exit
if strategy.position_size > 0 and uppercrossdown and enablebands and time_cond and timetobuy
strategy.close_all(alert_message = message_closelong)
if strategy.position_size < 0 and lowercrossup and enablebands and time_cond and timetobuy
strategy.close_all(alert_message = message_closeshort)
//Strategy Execution - Upper and Lower Band Stops
if strategy.position_size > 0 and upperstop and enablebands and time_cond and timetobuy
strategy.close_all(alert_message = message_closelong)
if strategy.position_size < 0 and lowerstop and enablebands and time_cond and timetobuy
strategy.close_all(alert_message = message_closeshort)
//Strategy Execution - Close Trade At End Of Time Frame
if strategy.position_size > 0 and timetoclose and enableclose and time_cond
strategy.close_all(alert_message = message_closelong)
if strategy.position_size < 0 and timetoclose and enableclose and time_cond
strategy.close_all(alert_message = message_closeshort)
//Strategy Execution - Stop Loss and Take Profit
if strategy.position_size > 0 and enablesl and time_cond
strategy.exit(id="Close Long", stop=longStop, limit=longTake, alert_message = message_closelong)
if strategy.position_size < 0 and enablesl and time_cond
strategy.exit(id="Close Short", stop=shortStop, limit=shortTake, alert_message = message_closeshort)
if strategy.position_size > 0 and enabletp and time_cond
strategy.exit(id="Close Long", stop=longStop, limit=longTake, alert_message = message_closelong)
if strategy.position_size < 0 and enabletp and time_cond
strategy.exit(id="Close Short", stop=shortStop, limit=shortTake, alert_message = message_closeshort)
|
3 Candle Strike Stretegy | https://www.tradingview.com/script/zqbs2shU-3-Candle-Strike-Stretegy/ | PtGambler | https://www.tradingview.com/u/PtGambler/ | 722 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © platsn
//
// *****************************************************************************************************************************************************************************************************
//@version=5
strategy("3 Candle Strike Strategy", overlay=true, pyramiding=1, initial_capital=5000)
// ******************** Period **************************************
startY = input(title='Start Year', defval=2011, group = "Trading window")
startM = input.int(title='Start Month', defval=1, minval=1, maxval=12, group = "Trading window")
startD = input.int(title='Start Day', defval=1, minval=1, maxval=31, group = "Trading window")
finishY = input(title='Finish Year', defval=2050, group = "Trading window")
finishM = input.int(title='Finish Month', defval=12, minval=1, maxval=12, group = "Trading window")
finishD = input.int(title='Finish Day', defval=31, minval=1, maxval=31, group = "Trading window")
timestart = timestamp(startY, startM, startD, 00, 00)
timefinish = timestamp(finishY, finishM, finishD, 23, 59)
t1_session = input.session("0930-1554:23456", "Entry Session", group="Sessions", tooltip = "Entry Signal only generated within this period.")
t1 = time(timeframe.period, t1_session)
window = time >= timestart and time <= timefinish and t1 ? true : false
src = close
margin_req = input.float(10, title="Margin Requirement / Leverage", step=0.1, group = "Trading Options")
qty_per_trade = input.float(100, title = "% of initial capital per trade", group = "Trading Options")
reinvest = input.bool(defval=false,title="Reinvest profit", group = "Trading Options")
reinvest_percent = input.float(defval=20, title = "Reinvest percentage", group="Trading Options")
profit = strategy.netprofit
trade_amount = math.floor(strategy.initial_capital*margin_req / close)
if strategy.netprofit > 0 and reinvest
trade_amount := math.floor((strategy.initial_capital* (qty_per_trade/100)+(profit*reinvest_percent*0.01))*margin_req/ close)
else
trade_amount := math.floor(strategy.initial_capital* (qty_per_trade/100)*margin_req / close)
trade_amount := math.min(trade_amount, 1000)
// ***************************************************************************************************** Daily ATR *****************************************************
// Inputs
atrlen = input.int(14, minval=1, title="ATR period", group = "Daily ATR")
iPercent = input.float(5, minval=1, maxval=100, step=0.1, title="% ATR to use for SL / PT", group = "Daily ATR")
// PTPercent = input.int(100, minval=1, title="% ATR for PT")
// Logic
percentage = iPercent * 0.01
datr = request.security(syminfo.tickerid, "1D", ta.rma(ta.tr, atrlen))
datrp = datr * percentage
// datrPT = datr * PTPercent * 0.01
plot(datr,"Daily ATR")
plot(datrp, "Daily % ATR")
// ***************************************************************************************************************** Moving Averages ************************
show_ema1 = input.bool(false, "", group = "Moving Averages", inline = "ema1")
len0 = input.int(8, minval=1, title='Fast EMA', group= "Moving Averages", inline = "ema1")
ema1 = ta.ema(src, len0)
show_smma1 = input.bool(false, "", group = "Moving Averages", inline = "smma1")
len1 = input.int(21, minval=1, title='Fast SMMA', group= "Moving Averages", inline = "smma1")
smma1 = 0.0
sma_1 = ta.sma(src, len1)
smma1 := na(smma1[1]) ? sma_1 : (smma1[1] * (len1 - 1) + src) / len1
show_smma2 = input.bool(false, "", group = "Moving Averages", inline = "smma2")
len2 = input.int(50, minval=1, title='Medium SMMA', group= "Moving Averages", inline = "smma2")
smma2 = 0.0
sma_2 = ta.sma(src, len2)
smma2 := na(smma2[1]) ? sma_2 : (smma2[1] * (len2 - 1) + src) / len2
show_smma3 = input.bool(false, "", group = "Moving Averages", inline = "smma3")
len3 = input.int(200, minval=1, title='Slow SMMA', group= "Moving Averages", inline = "smma3")
smma3 = 0.0
sma_3 = ta.sma(src, len3)
smma3 := na(smma3[1]) ? sma_3 : (smma3[1] * (len3 - 1) + src) / len3
ma_bull = smma1 > smma2 and smma1 > smma1[1]
ma_bear = smma1 < smma2 and smma1 < smma1[1]
ma_bull_macro = smma1 > smma3 and smma2 > smma3
ma_bear_macro = smma1 < smma3 and smma2 < smma3
plot(show_ema1 ? ema1 : na, 'Fast EMA', color.white, linewidth = 2)
plot(show_smma1 ? smma1 : na, 'Fast SMMA', color.yellow, linewidth = 2)
plot(show_smma2 ? smma2 : na, 'Medium SMMA', color.orange, linewidth = 2)
plot(show_smma3 ? smma3 : na, 'Fast SMMA', color.red, linewidth = 2)
// **************************************************************************************************************** Linear Regression *************************
//Input
clen = input.int(defval = 50, minval = 1, title = "Linear Regression Period", group = "Linear Regression")
slen = input.int(defval=50, minval=1, title="LR Slope Period" , group = "Linear Regression")
glen = input.int(defval=14, minval=1, title="LR Signal Period", group = "Linear Regression")
LR_thres = input.float(0.03, minval=0, step=0.001, title="LR Threshold for Ranging vs Trending" , group = "Linear Regression")
//Linear Regression Curve
lrc = ta.linreg(src, clen, 0)
//Linear Regression Slope
lrs = (lrc-lrc[1])/1
//Smooth Linear Regression Slope
slrs = ta.ema(lrs, slen)
//Signal Linear Regression Slope
alrs = ta.sma(slrs, glen)
up_accel = lrs > alrs and lrs > 0
down_accel = lrs < alrs and lrs < 0
LR_ranging = math.abs(slrs) <= LR_thres
LR_trending = math.abs(slrs) > LR_thres
// plot(slrs, "LR slope")
// plot(LR_trending?1:0, "LR Trending")
barcolor(LR_ranging? color.gray : na, title = "Ranging")
// *********************************************************************************************************************************** Candle conditions **************************
bull_3s = close[3] <= open[3] and close[2] <= open[2] and close[1] <= open[1] and close > open[1]
bear_3s = close[3] >= open[3] and close[2] >= open[2] and close[1] >= open[1] and close < open[1]
plotshape(bull_3s, style=shape.triangleup, color=color.new(color.green, 0), location=location.belowbar, size=size.small, text='3s-Bull', title='3 Line Strike Up')
plotshape(bear_3s, style=shape.triangledown, color=color.new(color.red, 0), location=location.abovebar, size=size.small, text='3s-Bear', title='3 Line Strike Down')
if barstate.isconfirmed
if bull_3s
alert(message = "3s Bull")
if bear_3s
alert(message = "3s Bear")
// ***************************************************************************************************************************************** SL & PT ***********************************
RR = input.float(3.0, minval = 0.1, step = 0.1, title="Reward to Risk Ratio", group = "Trading Options")
trade_trailing = input.bool(true, "Switch to trailing SL after TP hit", group = "Trading Options", tooltip = "Set SL to previous low after TP hit")
barsSinceLastEntry()=>
strategy.opentrades > 0 ? (bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades-1)) : na
// plot(barsSinceLastEntry(),"BSLE")
last_high = math.max(high, high[1], high[2], high[3])
last_low = math.min(low, low[1], low[2], low[3])
long_SL = last_low - datrp
short_SL = last_high + datrp
long_PT = last_high
short_PT = last_low
last_entry = strategy.opentrades.entry_price(strategy.opentrades-1)
risk = last_entry - long_SL
if strategy.opentrades > 0
long_SL := math.min(long_SL[barsSinceLastEntry()], last_low)
short_SL := math.max(short_SL[barsSinceLastEntry()], last_high)
risk := last_entry - long_SL
long_PT := last_entry + (last_entry - long_SL) * RR
short_PT := last_entry - (short_SL - last_entry) * RR
var PT_hit = false
if trade_trailing
if high > long_PT
long_SL := low
PT_hit := true
if low < short_PT
short_SL := high
PT_hit := true
if PT_hit
long_SL := math.max(low[1], long_SL[1])
short_SL := math.min(high[1], short_SL[1])
PT_hit := strategy.opentrades == 0 ? false : PT_hit
SSL = plot(short_SL,title = "Short SL", color= strategy.opentrades.size(0) < 0 and barsSinceLastEntry() > 0 ? color.red: na, linewidth = 3, style = plot.style_linebr)
LSL = plot(long_SL,title = "Long SL", color= strategy.opentrades.size(0) > 0 and barsSinceLastEntry() > 0 ? color.red: na, linewidth = 3, style = plot.style_linebr)
LPT = plot(long_PT,title = "Long PT", color= strategy.opentrades.size(0) > 0 and barsSinceLastEntry() > 0 ? color.green: na, linewidth = 3, style = plot.style_linebr)
SPT = plot(short_PT,title = "Short PT", color= strategy.opentrades.size(0) < 0 and barsSinceLastEntry() > 0 ? color.green: na, linewidth = 3, style = plot.style_linebr)
LE = plot(last_entry, title = "Last entry", color = strategy.opentrades > 0 ? color.gray : na, style = plot.style_linebr)
plot(risk, title = "Risk")
fill(LPT, LE, color = strategy.opentrades.size(0) > 0 ? color.new(color.green,90) : na)
fill(LE, LSL, color = strategy.opentrades.size(0) > 0 ? color.new(color.red,90): na)
fill(SPT, LE, color = strategy.opentrades.size(0) < 0 ? color.new(color.green,90) : na)
fill(LE, SSL, color = strategy.opentrades.size(0) < 0 ? color.new(color.red,90) : na)
// **************************************************************************************************************************************** Trade Pauses ****************************************
bool trade_pause = false
bool trade_pause2 = false
no_entry = input.bool(true, title="No entry between:", group = "Trading Options", inline = 'no_entry')
t2_session = input.session("1000-1030",'', group = "Trading Options", inline = 'no_entry', tooltip = "To avoid high volatility")
t2 = time(timeframe.period, t2_session)
if high - low > datr*0.3
trade_pause := true
else
trade_pause := false
if no_entry and t2
trade_pause2 := true
else
trade_pause2 := false
// ************************************************************************************************************************************ Entry conditions **************************
trade_3s = input.bool(title='Trade 3s candle pattern', defval=true, group = "Trading Options", tooltip = "Can use alert() function calls for all 3 Candle strike signals")
L_entry1 = trade_3s and bull_3s and ma_bull and LR_trending
S_entry1 = trade_3s and bear_3s and ma_bear and LR_trending
trade_ma_reversal = input.bool(title='Trade MA Cross Reversal Signal', defval=true, group = "Trading Options")
L_entry2 = trade_ma_reversal and ma_bear_macro and ema1 > smma1 and bull_3s and ta.barssince(ta.cross(ema1,smma1)) < 10
S_entry2 = trade_ma_reversal and ma_bull_macro and ema1 < smma1 and bear_3s and ta.barssince(ta.cross(ema1,smma1)) < 10
// ************************************************************************************************************************************** Exit Conditions ********************************
L_exit1 = bear_3s
S_exit1 = bull_3s
// ************************************************************************************************************************************ Entry and Exit orders *****************************
if not trade_pause and not trade_pause2 and window
if L_entry1
strategy.entry("Long", strategy.long, trade_amount, comment="Long 3s")
if L_entry2
strategy.entry("Long", strategy.long, trade_amount, comment="Long MA cross")
if S_entry1
strategy.entry("Short", strategy.short, trade_amount, comment = "Short 3s")
if S_entry2
strategy.entry("Short", strategy.short, trade_amount, comment = "Short MA corss")
if trade_trailing
strategy.exit("Exit", "Long", stop= long_SL, comment = "Exit Long SL hit")
strategy.exit("Exit", "Short", stop= short_SL, comment = "Exit Short SL hit")
else if barsSinceLastEntry() > 0
strategy.exit("Exit", "Long",limit = long_PT, stop= long_SL, comment_profit = "Exit Long PT hit", comment_loss = "Exit Long SL hit")
strategy.exit("Exit", "Short",limit = short_PT, stop= short_SL, comment_profit = "Exit Short PT hit", comment_loss = "Exit Short SL hit")
if strategy.opentrades > 0 and not t1
strategy.close_all(comment = 'End of day')
// ************************************************************************************************************************************ Alerts *****************************
|
action zone - ATR stop reverse order strategy v0.1 by 9nck | https://www.tradingview.com/script/C6b8iwJt-action-zone-ATR-stop-reverse-order-strategy-v0-1-by-9nck/ | fenirlix | https://www.tradingview.com/u/fenirlix/ | 349 | 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/
// © fenirlix
//@version=5
// Strategy parameter incl. position size, commission and initial capital
strategy("ACTIONZONE-ATR REVERSEORDER STRATEGY", "ACTIONZONEATR-REVERSEORDER", overlay=true
,default_qty_type=strategy.percent_of_equity, default_qty_value=25
,commission_type='strategy.commission_percent', commission_value=0.01
,initial_capital=3000)
// User Input Variable
fastMaInput = input.int(12, "Fast MA Period", minval=2, step=1)
slowMaInput = input.int(26, "Slow MA Period", minval=2, step=1)
atrLengthInput = input.int(14, "ATR length", minval=2,step=1)
atrInnerMultInput = input.float(1, "atr inner multiplier", minval=0.1, step=0.1)
atrMidMultInput = input.float(2, "atr middle multiplier", minval=0.1, step=0.1) //***** MOST OF RISK MANAGEMENT LOGIC BASE ON THIS INPUT *****//
atrOuterMultInput = input.float(3, "atr outer multiplier", minval=0.1, step=0.1)
// Backtesting Date range
startYearInput = input.int(2021, "Start Year", minval=1900, maxval=2100, step=1)
startMonthInput = input.int(12, "Start Month", minval=1, maxval=12, step=1)
startDateInput = input.int(1, "Start Day", minval=1, maxval=31, step=1)
setEndRangeInput = input.bool(false, "Using Specific End Test Date") //Set specific End date or use present(end of candle) data
endYearInput = input.int(2022, "End Year", minval=1900, maxval=2100, step=1)
endMonthInput = input.int(1, "End Month", minval=1, maxval=12, step=1)
endDateInput = input.int(31, "End Day", minval=1, maxval=31, step=1)
startDate = timestamp(syminfo.timezone, startYearInput, startMonthInput, startDateInput)
endDate = timestamp(syminfo.timezone, endYearInput, endMonthInput, endDateInput)
inDateRange = time >= startDate //Set backtest date range to present data
if setEndRangeInput
inDateRange and time <= endDate //set backtest date range to specific date
// minimum position hold period (to get rid of false signal in sideway trend)
minHoldInput = input.int(8, 'Minimum position Hold Limit', minval=1, maxval=365, step=1) // Set Minimum Position Hold
var bool reverseToLong = false // Assign reverse order operator
var bool reverseToShort = false // Assign reverse order operator
// Indicator Declaration
fastEma = ta.ema(close, fastMaInput)
slowEma = ta.ema(close, slowMaInput)
atr = ta.atr(atrLengthInput)
// Declare trend of asset
isBullish = fastEma > slowEma
isBearish = fastEma <= slowEma
// Record position hold length, to limit minimum hold period(candle)
var int hold_length = 0
if strategy.opentrades > 0 or strategy.opentrades < 0
hold_length := hold_length + 1
else
hold_length := 0
// create permanent variable of stop price
var float longStopPrice = na
var float shortStopPrice = na
// Chart-Indicator COLOR declaration
REDBEAR = color.new(color.red, 80)
GREENBULL = color.new(color.green, 80)
greenLong = isBullish and close > fastEma
yellowLong = isBullish and close < fastEma
blueShort = isBearish and close > fastEma
redShort = isBearish and close < fastEma
// assign oversold, overbought condition(in this case, price over middle atr plus/minus fastEma)
overBand = high[1] > fastEma + (atrMidMultInput * atr)
underBand = low[1] < fastEma - (atrMidMultInput * atr)
// Strategy
// Main Entry Condition
goLong = isBullish and isBullish[1] == 0
goShort = isBearish and isBearish[1] == 0
inPosition = strategy.position_size != 0
minHoldPeriod = hold_length > minHoldInput ? true : false
// Entry Condition
if not inPosition and inDateRange and barstate.isconfirmed == true //compute after close of the bar to avoid repainting
if goLong or reverseToLong // Long if longcondition or reverse order receive.
strategy.entry('long', strategy.long)
longStopPrice := fastEma - (atr * atrMidMultInput) // Set stop loss price
reverseToLong := false // Reset reverse order status
else if goShort or reverseToShort
strategy.entry('short', strategy.short)
shortStopPrice := fastEma + (atr * atrMidMultInput)
reverseToShort := false
// Take profit and Set Higher Stop
if inPosition and minHoldPeriod and barstate.isconfirmed == true // check if we're in position and pass minimum hold period, confirm no repainting
if strategy.position_size > 0
// if exit position by Sellcondition(which is the same as ShortCondition), Exit Long position and make Short order(by set reverse order to true)
strategy.close('long', when=goShort, comment='exitLong(' + str.tostring(hold_length) + ')')
reverseToShort := true
if overBand //If overbought condition met, set Stop price to LAST LOW, and not reverse any position
longStopPrice := low[1]
reverseToShort := false
else if strategy.position_size < 0
strategy.close('short', when=goLong, comment='exitShort(' + str.tostring(hold_length) + ')')
reverseToLong := true
if underBand
shortStopPrice := high[1]
reverseToLong := false
// Stop Loss and Set calculate stop loss using Atr Channel
if inPosition
if strategy.position_size > 0
if fastEma - (atr * atrMidMultInput) > longStopPrice // set long stop price to the higher of latest long stop price and ATR lower channel
longStopPrice := fastEma - (atr * atrMidMultInput)
strategy.exit('Long Stop atr ', 'long', stop=longStopPrice)
else if strategy.position_size < 0
if fastEma + (atr * atrMidMultInput) < shortStopPrice
shortStopPrice := fastEma + (atr * atrMidMultInput)
strategy.exit('Short Stop atr ', 'short', stop=shortStopPrice)
// Plotting
fastLine = plot(fastEma, title='fast ema line', linewidth=1, color=isBullish ? color.green : color.red)
slowLine = plot(slowEma, title='slow ema line', linewidth=2, color= isBullish? color.green : color.red)
atrUpperLine1 = plot(fastEma + (atr * atrInnerMultInput), title='ATR Upperline1', color=color.new(color.black,85))
atrLowerLine1 = plot(fastEma - (atr * atrInnerMultInput), title='ATR Lowerline1', color=color.new(color.black,85))
atrUpperLine2 = plot(fastEma + (atr * atrMidMultInput), title='ATR Upperline2', color=color.new(color.black,75))
atrLowerLine2 = plot(fastEma - (atr * atrMidMultInput), title='ATR Lowerline2', color=color.new(color.black,75))
atrUpperLine3 = plot(fastEma + (atr * atrOuterMultInput), title='ATR Upperline3', color=color.new(color.black,50))
atrLowerLine3 = plot(fastEma - (atr * atrOuterMultInput), title='ATR Lowerline3', color=color.new(color.black,50))
plot(longStopPrice, color=strategy.position_size > 0 ? color.blue : na, linewidth=2)
plot(shortStopPrice, color=strategy.position_size < 0 ? color.blue : na, linewidth=2)
// Filling
fill(fastLine, slowLine, color=isBullish ? GREENBULL : REDBEAR)
fill(atrUpperLine3, atrLowerLine3, color=inPosition and (minHoldInput - hold_length > 0) ? color.new(color.blue,90): na)
barColor = switch
greenLong => color.green
yellowLong => color.yellow
blueShort => color.blue
redShort => color.red
=> color.black
barcolor(color=barColor)
// Fill background to distinguish inactive time(Zulu time)
nightTime = time(timeframe.period, "1500-0100") ? color.new(color.black, 95): na
bgcolor(nightTime)
|
Open Price Strategy | https://www.tradingview.com/script/3O6kPXzS-Open-Price-Strategy/ | REV0LUTI0N | https://www.tradingview.com/u/REV0LUTI0N/ | 91 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © REV0LUTI0N
//@version=4
//------------------------------------------------------------------------------
// Strategy
strategy("Open Price Strategy", overlay=true, initial_capital = 10000, default_qty_value = 10000, default_qty_type = strategy.cash)
notes = input("", title="Note For Your Reference Only")
//------------------------------------------------------------------------------
// Strategy Backtesting
startDate = input(timestamp("2021-10-01T00:00:00"), type = input.time, title='Backtesting Start Date', group="Backtesting")
finishDate = input(timestamp("9999-12-31T00:00:00"), type = input.time, title='Backtesting End Date', group="Backtesting")
time_cond = time >= startDate and time <= finishDate
//------------------------------------------------------------------------------
//Time Restriction Settings
firsttradetime = input("0930-0931", title='Time Frame For Enter ASAP', group="Time Restriction")
startendtime = input("0930-1555", title='Time Frame For Wait To Enter', group="Time Restriction")
endtime = input("0930-1555", title='Time Frame To Exit Trades', group="Time Restriction")
enableclose = input(true, title='Enable Close Trade At End Of Exit Time Frame', group="Time Restriction")
firsttradetimetobuy = (time(timeframe.period, firsttradetime))
timetobuy = (time(timeframe.period, startendtime))
timetoclose = na(time(timeframe.period, endtime))
//------------------------------------------------------------------------------
// Contrarian Settings
nocontrarian = input(true, title="Trade Regular Signals", inline="1", group="Contrarian Settings")
usecontrarian = input(false, title="Trade Contrarian Signals", inline="1", group="Contrarian Settings")
//------------------------------------------------------------------------------
// Open Price Code
openpricetime = input('0930-0931', title="Time To Get Open Price", group="Strategy Settings")
opencondition = input(open, title="Open Price Source", group="Strategy Settings")
entrycondition = input(close, title="Entry Price Source", group="Strategy Settings")
OpenValueTime = time("1", openpricetime)
var OpenPA = 0.0
if OpenValueTime
if not OpenValueTime[1]
OpenPA := opencondition
plot(not OpenValueTime ? OpenPA : na, title="Open Price", color=color.red, linewidth=2, style=plot.style_linebr)
//------------------------------------------------------------------------------
// EMA Open Line Cross Condition (Wait To Enter)
enterasap = input(true, title="Enter Trade ASAP", inline="1", group="Wait To Enter Settings")
waittoenter = input(false, title="Wait For EMA To Cross Open Line", inline="1", group="Wait To Enter Settings")
wait_ema_length = input(defval=15, minval=1, title="EMA Length", group="Wait To Enter Settings")
wait_emasrc = input(close, title="EMA Source", group="Wait To Enter Settings")
wait_ema = ema(wait_emasrc, wait_ema_length)
plot(waittoenter ? wait_ema : na, "EMA - Wait To Enter", style=plot.style_linebr, color=#2962ff, linewidth=1)
emacrossup = crossover(wait_ema, OpenPA)
emacrossdown = crossunder(wait_ema, OpenPA)
//------------------------------------------------------------------------------
// EMA Filter (Enter ASAP)
noemafilter_asap = input(true, title="No EMA Filter", inline="1", group="EMA Filter (Enter ASAP)")
useemafilter_asap = input(false, title="Use EMA Filter", inline="1", group="EMA Filter (Enter ASAP)")
ema_length_asap = input(defval=15, minval=1, title="EMA Length", group="EMA Filter (Enter ASAP)")
emasrc_asap = input(close, title="EMA Source", group="EMA Filter (Enter ASAP)")
ema_asap = ema(emasrc_asap, ema_length_asap)
//plot(ema_asap, "EMA (Enter ASAP)", style=plot.style_linebr, color=#cad850, linewidth=2)
plot(useemafilter_asap ? ema_asap : na, "EMA (Enter ASAP)", style=plot.style_linebr, color=#cad850, linewidth=2)
//------------------------------------------------------------------------------
// EMA Filter (Wait To Enter)
noemafilter = input(true, title="No EMA Filter", inline="1", group="EMA Filter (Wait To Enter)")
useemafilter = input(false, title="Use EMA Filter", inline="1", group="EMA Filter (Wait To Enter)")
ema_length = input(defval=15, minval=1, title="EMA Length", group="EMA Filter (Wait To Enter)")
emasrc = input(close, title="EMA Source", group="EMA Filter (Wait To Enter)")
ema = ema(emasrc, ema_length)
//plot(ema, "EMA (Wait To Enter)", style=plot.style_linebr, color=#cad850, linewidth=2)
plot(useemafilter ? ema : na, "EMA (Wait To Enter)", style=plot.style_linebr, color=#cad850, linewidth=2)
//------------------------------------------------------------------------------
// CMF Filter (Enter ASAP)
nocmffilter_asap = input(true, title="No CMF Filter", inline="1", group="CMF Filter (Enter ASAP)")
usecmffilter_asap = input(false, title="Use CMF Filter", inline="1", group="CMF Filter (Enter ASAP)")
mflength_asap = input(title="CMF length", group="CMF Filter (Enter ASAP)", type=input.integer, defval=20)
ad_asap = close==high and close==low or high==low ? 0 : ((2*close-low-high)/(high-low))*volume
mf_asap = sum(ad_asap, mflength_asap) / sum(volume, mflength_asap)
//------------------------------------------------------------------------------
// CMF Filter (Wait To Enter)
nocmffilter = input(true, title="No CMF Filter", inline="1", group="CMF Filter (Wait To Enter)")
usecmffilter = input(false, title="Use CMF Filter", inline="1", group="CMF Filter (Wait To Enter)")
mflength = input(title="CMF length", group="CMF Filter (Wait To Enter)", type=input.integer, defval=20)
ad = close==high and close==low or high==low ? 0 : ((2*close-low-high)/(high-low))*volume
mf = sum(ad, mflength) / sum(volume, mflength)
//------------------------------------------------------------------------------
// EMA For Cross Over Open Line Stop Loss
openlineclose = input(false, title='Exit When Stop Loss EMA Crosses Open Line', group="Open Line As Stop Loss")
stop_ema_length = input(defval=15, minval=1, title="EMA Length", group="Open Line As Stop Loss")
stop_emasrc = input(close, title="EMA Source", group="Open Line As Stop Loss")
stop_ema = ema(stop_emasrc, stop_ema_length)
//plot(stop_ema, "EMA - Wait To Enter", style=plot.style_linebr, color=#2962ff, linewidth=1)
plot(openlineclose ? stop_ema : na, "EMA - Wait To Enter", style=plot.style_linebr, color=#2962ff, linewidth=1)
pricecrossup = crossover(stop_ema, OpenPA)
pricecrossdown = crossunder(stop_ema, OpenPA)
//------------------------------------------------------------------------------
// Stop Loss & Take Profit % Based
enablesltp = input(false, title='Enable Stop Loss & Take Profit', group="% Stop Loss & Take Profit")
stopTick = input(2.0, title='Stop Loss %', group="% Stop Loss & Take Profit", type=input.float, step=0.1) / 100
takeTick = input(4.0, title='Take Profit %', group="% Stop Loss & Take Profit", type=input.float, step=0.1) / 100
longStop = strategy.position_avg_price * (1 - stopTick)
shortStop = strategy.position_avg_price * (1 + stopTick)
shortTake = strategy.position_avg_price * (1 - takeTick)
longTake = strategy.position_avg_price * (1 + takeTick)
plot(strategy.position_size > 0 and enablesltp ? longStop : na, style=plot.style_linebr, color=color.red, linewidth=1, title="Long Stop Loss")
plot(strategy.position_size < 0 and enablesltp ? shortStop : na, style=plot.style_linebr, color=color.red, linewidth=1, title="Short Stop Loss")
plot(strategy.position_size > 0 and enablesltp ? longTake : na, style=plot.style_linebr, color=color.green, linewidth=1, title="Long Take Profit")
plot(strategy.position_size < 0 and enablesltp ? shortTake : na, style=plot.style_linebr, color=color.green, linewidth=1, title="Short Take Profit")
//------------------------------------------------------------------------------
// Alert messages
message_enterlong = input("", title="Long Entry message", group="Alert Messages")
message_entershort = input("", title="Short Entry message", group="Alert Messages")
message_closelong = input("", title="Close Long message", group="Alert Messages")
message_closeshort = input("", title="Close Short message", group="Alert Messages")
//------------------------------------------------------------------------------
// Strategy Execution
//------------------------------------------------------------------------------
// Entry Alerts - No EMA or CMF
if entrycondition > OpenPA and time_cond and firsttradetimetobuy and noemafilter_asap and nocmffilter_asap and enterasap and nocontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if entrycondition < OpenPA and time_cond and firsttradetimetobuy and noemafilter_asap and nocmffilter_asap and enterasap and nocontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
// Entry Alerts (Wait To Enter) - No EMA or CMF
if emacrossup and time_cond and timetobuy and noemafilter and nocmffilter and waittoenter and nocontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if emacrossdown and time_cond and timetobuy and noemafilter and nocmffilter and waittoenter and nocontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
//------------------------------------------------------------------------------
// Contrarian - Entry Alerts - No EMA or CMF
if entrycondition > OpenPA and time_cond and firsttradetimetobuy and noemafilter_asap and nocmffilter_asap and enterasap and usecontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
if entrycondition < OpenPA and time_cond and firsttradetimetobuy and noemafilter_asap and nocmffilter_asap and enterasap and usecontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
// Contrarian - Entry Alerts (Wait To Enter) - No EMA or CMF
if emacrossup and time_cond and timetobuy and noemafilter and nocmffilter and waittoenter and usecontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
if emacrossdown and time_cond and timetobuy and noemafilter and nocmffilter and waittoenter and usecontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
//------------------------------------------------------------------------------
// Entry Alerts - Use EMA but No CMF
if entrycondition > OpenPA and close > ema_asap and time_cond and firsttradetimetobuy and useemafilter_asap and nocmffilter_asap and enterasap and nocontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if entrycondition < OpenPA and close < ema_asap and time_cond and firsttradetimetobuy and useemafilter_asap and nocmffilter_asap and enterasap and nocontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
// Entry Alerts (Wait To Enter) - Use EMA but No CMF
if emacrossup and close > ema and time_cond and timetobuy and useemafilter and nocmffilter and waittoenter and nocontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if emacrossdown and close < ema and time_cond and timetobuy and useemafilter and nocmffilter and waittoenter and nocontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
//------------------------------------------------------------------------------
// Contrarian - Entry Alerts - Use EMA but No CMF
if entrycondition > OpenPA and close > ema_asap and time_cond and firsttradetimetobuy and useemafilter_asap and nocmffilter_asap and enterasap and usecontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
if entrycondition < OpenPA and close < ema_asap and time_cond and firsttradetimetobuy and useemafilter_asap and nocmffilter_asap and enterasap and usecontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
// Contrarian - Entry Alerts (Wait To Enter) - Use EMA but No CMF
if emacrossup and close > ema and time_cond and timetobuy and useemafilter and nocmffilter and waittoenter and usecontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
if emacrossdown and close < ema and time_cond and timetobuy and useemafilter and nocmffilter and waittoenter and usecontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
//------------------------------------------------------------------------------
// Entry Alerts - Use CMF but No EMA
if entrycondition > OpenPA and mf_asap > 0 and time_cond and firsttradetimetobuy and noemafilter_asap and usecmffilter_asap and enterasap and nocontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if entrycondition < OpenPA and mf_asap < 0 and time_cond and firsttradetimetobuy and noemafilter_asap and usecmffilter_asap and enterasap and nocontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
// Entry Alerts (Wait To Enter) - Use CMF but No EMA
if emacrossup and mf > 0 and time_cond and timetobuy and noemafilter and usecmffilter and waittoenter and nocontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if emacrossdown and mf < 0 and time_cond and timetobuy and noemafilter and usecmffilter and waittoenter and nocontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
//------------------------------------------------------------------------------
// Contrarian - Entry Alerts - Use CMF but No EMA
if entrycondition > OpenPA and mf_asap > 0 and time_cond and firsttradetimetobuy and noemafilter_asap and usecmffilter_asap and enterasap and usecontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
if entrycondition < OpenPA and mf_asap < 0 and time_cond and firsttradetimetobuy and noemafilter_asap and usecmffilter_asap and enterasap and usecontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
// Contrarian - Entry Alerts (Wait To Enter) - Use CMF but No EMA
if emacrossup and mf > 0 and time_cond and timetobuy and noemafilter and usecmffilter and waittoenter and usecontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
if emacrossdown and mf < 0 and time_cond and timetobuy and noemafilter and usecmffilter and waittoenter and usecontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
//------------------------------------------------------------------------------
// Entry Alerts - Use EMA and CMF
if entrycondition > OpenPA and close > ema_asap and mf_asap > 0 and time_cond and firsttradetimetobuy and useemafilter_asap and usecmffilter_asap and enterasap and nocontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if entrycondition < OpenPA and close < ema_asap and mf_asap < 0 and time_cond and firsttradetimetobuy and useemafilter_asap and usecmffilter_asap and enterasap and nocontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
// Entry Alerts (Wait To Enter) - Use EMA and CMF
if emacrossup and close > ema and mf > 0 and time_cond and timetobuy and useemafilter and usecmffilter and waittoenter and nocontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if emacrossdown and close < ema and mf < 0 and time_cond and timetobuy and useemafilter and usecmffilter and waittoenter and nocontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
//------------------------------------------------------------------------------
// Contrarian - Entry Alerts - Use EMA and CMF
if entrycondition > OpenPA and close > ema_asap and mf_asap > 0 and time_cond and firsttradetimetobuy and useemafilter_asap and usecmffilter_asap and enterasap and usecontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
if entrycondition < OpenPA and close < ema_asap and mf_asap < 0 and time_cond and firsttradetimetobuy and useemafilter_asap and usecmffilter_asap and enterasap and usecontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
// Contrarian - Entry Alerts (Wait To Enter) - Use EMA and CMF
if emacrossup and close > ema and mf > 0 and time_cond and timetobuy and useemafilter and usecmffilter and waittoenter and usecontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
if emacrossdown and close < ema and mf < 0 and time_cond and timetobuy and useemafilter and usecmffilter and waittoenter and usecontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
//------------------------------------------------------------------------------
// Hours exits
if strategy.position_size > 0 and timetoclose and enableclose
strategy.close_all(alert_message = message_closelong)
if strategy.position_size < 0 and timetoclose and enableclose
strategy.close_all(alert_message = message_closeshort)
//------------------------------------------------------------------------------
// Open Line exits
if strategy.position_size > 0 and pricecrossdown and openlineclose
strategy.close_all(alert_message = message_closelong)
if strategy.position_size < 0 and pricecrossup and openlineclose
strategy.close_all(alert_message = message_closeshort)
//------------------------------------------------------------------------------
// % TP and SL exits
if strategy.position_size > 0 and enablesltp and time_cond
strategy.exit(id="Close Long", stop=longStop, limit=longTake, alert_message = message_closelong)
if strategy.position_size < 0 and enablesltp and time_cond
strategy.exit(id="Close Short", stop=shortStop, limit=shortTake, alert_message = message_closeshort)
|
ABCD Strategy | https://www.tradingview.com/script/20aoz32a-ABCD-Strategy/ | kerok3g | https://www.tradingview.com/u/kerok3g/ | 409 | 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/
// © kerok3g
//@version=5
strategy("ABCD Strategy", shorttitle="ABCDS", overlay=true, commission_value=0.04)
calcdev(fprice, lprice, fbars, lbars) =>
rise = lprice - fprice
run = lbars - fbars
avg = rise/run
((bar_index - lbars) * avg) + lprice
len = input(5)
ph = ta.pivothigh(len, len)
pl = ta.pivotlow(len, len)
var bool ishigh = false
ishigh := ishigh[1]
var float currph = 0.0
var int currphb = 0
currph := nz(currph)
currphb := nz(currphb)
var float oldph = 0.0
var int oldphb = 0
oldph := nz(oldph)
oldphb := nz(oldphb)
var float currpl = 0.0
var int currplb = 0
currpl := nz(currpl)
currplb := nz(currplb)
var float oldpl = 0.0
var int oldplb = 0
oldpl := nz(oldpl)
oldplb := nz(oldplb)
if (not na(ph))
ishigh := true
oldph := currph
oldphb := currphb
currph := ph
currphb := bar_index[len]
else
if (not na(pl))
ishigh := false
oldpl := currpl
oldplb := currplb
currpl := pl
currplb := bar_index[len]
endHighPoint = calcdev(oldph, currph, oldphb, currphb)
endLowPoint = calcdev(oldpl, currpl, oldplb, currplb)
plotshape(ph, style=shape.triangledown, color=color.red, location=location.abovebar, offset=-len)
plotshape(pl, style=shape.triangleup, color=color.green, location=location.belowbar, offset=-len)
var line lnhigher = na
var line lnlower = na
lnhigher := line.new(oldphb, oldph, bar_index, endHighPoint)
lnlower := line.new(oldplb, oldpl, bar_index, endLowPoint)
line.delete(lnhigher[1])
line.delete(lnlower[1])
formlong = oldphb < oldplb and oldplb < currphb and currphb < currplb
longratio1 = (currph - oldpl) / (oldph - oldpl)
longratio2 = (currph - currpl) / (currph - oldpl)
formshort = oldplb < oldphb and oldphb < currplb and currplb < currphb
shortratio1 = (oldph - currpl) / (oldph - oldpl)
shortratio2 = (currph - currpl) / (oldph - currpl)
// prevent multiple entry for one pattern
var int signalid = 0
signalid := nz(signalid[1])
longCond = formlong and
longratio1 < 0.786 and
longratio1 > 0.5 and
longratio2 > 1 and
longratio2 < 1.414 and
close < oldph and
close > currpl and
signalid != oldplb
if (longCond)
signalid := oldplb
longsl = currpl - ta.tr
longtp = ((close - longsl) * 1.5) + close
strategy.entry("Long", strategy.long)
strategy.exit("Exit Long", "Long", limit=math.min(longtp, oldph), stop=longsl)
shortCond = formshort and
shortratio1 < 0.786 and
shortratio1 > 0.5 and
shortratio2 > 1.1 and
shortratio2 < 1.414 and
close > oldpl and
close < currph and
signalid != oldphb
if (shortCond)
signalid := oldphb
shortsl = currph + ta.tr
shorttp = close - ((shortsl - close) * 1.5)
strategy.entry("Short", strategy.short)
strategy.exit("Exit Short", "Short", limit=math.max(shorttp, oldpl), stop=shortsl)
|
KDJ Strategy @ionvolution | https://www.tradingview.com/script/bgS2Ww4R/ | ionvolution | https://www.tradingview.com/u/ionvolution/ | 73 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Buys if there is crossover in J and D and the crossover is above an SMA defined as an input parameter
// Sells if the close is below the SMA or there is a crossunder in J and D
// The KDJ calculation is done using ll21LAMBOS21 script. I added start date, end date, stop loss margin and stop profit margin to
// ease the simulation on diferent conditions of the market.
// Tested on BTCBUSD pair. Gives good results in 30m candles with K period = 7 and D period = 3, but also works fine with K period = 14 and D period = 8
// It works fine when market is bullish and gives false signals in flat markets.
// I just developed long strategy, as it is developed to work in SPOT trading.
// © ionvolution
// @version = 5
//strategy("KDJ IAM Strategy",shorttitle="kdj @ionvolution",overlay=true,default_qty_value=1,initial_capital=100,currency=currency.EUR)
strategy("KDJ IAM Strategy",shorttitle="kdj @ionvolution",overlay=true)
// Input parameters
ilong = input.int(14,"Period")
isig = input.int(8, "Signal")
isma = input.int(200, "SMA")
// Function to compute average for KDJ
bcwsma(s, l, m) =>
_bcwsma = float(na)
_s = s
_l = l
_m = m
_bcwsma := (_m * _s + (_l - _m) * nz(_bcwsma[1])) / _l
_bcwsma
profit_m = input.float(1.20,"Profit Margin",minval=1.0,maxval=1.99,step=0.01)
stop_m = input.float(0.98,"Stop Loss Margin",minval=0.0,maxval=1,step=0.01)
// Make input options that configure backtest date range
startDate = input.int(title="Start Date", defval=1, minval=1,maxval=31)
startMonth = input.int(title="Start Month", defval=1,minval=1,maxval=12)
startYear = input.int(title="Start Year", defval=2022,minval=2018,maxval=2023)
endDate = input.int(title="End Date", defval=1, minval=1,maxval=31)
endMonth = input.int(title="End Month", defval=1,minval=1,maxval=12)
endYear = input.int(title="End Year", defval=2022,minval=2018,maxval=2099)
// intialization of variables
// 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))
c = close
ma = ta.sma(close,isma)
h = ta.highest(high, ilong)
l = ta.lowest(low,ilong)
RSV = 100*((c-l)/(h-l))
pK = bcwsma(RSV, isig, 1)
pD = bcwsma(pK, isig, 1)
pJ = 3 * pK-2 * pD
go_long= ta.crossover(pJ,pD) and close >ma
go_short= ta.crossover(pD,pJ) or close < ma
if (inDateRange and go_long)
strategy.entry("S",strategy.long,comment="C")
strategy.exit("S", limit=c*profit_m, stop=c*stop_m, comment="SL/SP")
if (inDateRange and go_short)
strategy.close("S",when=go_short,comment="V")
// Plot options
//plot(pK, color= #1E88E5,transp=0)
//plot(pD, color=#FF6F00,transp=0)
plot(ma, color=color.yellow)
bgcolor(pJ>pD? color.green : color.red, transp=75)
//h0 = hline(80)
//h1 = hline(20) |
adx efi 50 ema channel, trend pullback | https://www.tradingview.com/script/yPKaaUL2-adx-efi-50-ema-channel-trend-pullback/ | trent777brown | https://www.tradingview.com/u/trent777brown/ | 96 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © trent777brown
//@version=5
strategy("adx efi 50 ema channel, trend pullback", overlay=true, margin_long=100, margin_short=100, currency=currency.USD, initial_capital= 100000, close_entries_rule="ANY")
//bollingerbands
[basis, upperband, lowerband]= ta.bb(ohlc4, 50, 3)
[basis2, upperband2, lowerband2]= ta.bb(ohlc4, 50, 2)
psar= ta.sar(.1, .1, .09)
ema50= ta.ema(hlc3, 50)
ema50hi= ta.ema(high, 50)
ema50lo= ta.ema(low, 50)
ema18= ta.wma(hlc3, 15)
wma9= ta.wma(open, 9)
wma5= ta.wma(ohlc4, 5)
ema34= ta.rma(hlc3, 10)
[macdline, signalline, histline]= ta.macd(hlc3, 5, 34, 5)
[macdline2, signalline2, histline2]= ta.macd(hlc3, 15,70, 24)
[diplus, diminus, adx]= ta.dmi(20, 20)
[diplus2, diminus2, adx2]= ta.dmi(12, 12)
rsi= ta.rsi(hlc3, 14)
rsisma= ta.sma(rsi, 10)
stoch= ta.stoch(close, high, low, 21)
k= ta.wma(stoch, 3)
d= ta.wma(k, 3)
trendline5= ta.wma(hlc3, 300)
trendline9= ta.wma(open, 540)
trendline18= ta.wma(open, 1080)
atr=ta.atr(14)
plot(psar, color=color.red, style=plot.style_circles)
plot(ema50, color=color.white, linewidth=4)
plot(ema50hi, color=color.yellow, linewidth=4)
plot(ema50lo, color=color.yellow, linewidth=4)
plot(ema34, color=color.aqua, linewidth=4)
plot(wma9, color=color.gray, linewidth=4)
plot(wma5, color=color.lime, linewidth=4)
plot(trendline18, color=color.orange, linewidth=4)
plot(upperband, color=color.navy, linewidth=4)
plot(lowerband, color=color.navy, linewidth=4)
plot(upperband2, color=color.navy, linewidth=4)
plot(lowerband2, color=color.navy, linewidth=4)
plot(trendline9, color=color.maroon, linewidth=4)
plot(trendline5, color=color.yellow, linewidth=4)
efi = ta.rma(ta.change(close) * volume, 15)
efi2= ta.rma(ta.change(close) * volume, 120)
buy= efi2 > 0 and efi < 0 and efi[1] < efi and adx >= 20 and open < ema50hi
sell= efi2 < 0 and efi > 0 and efi[1] > efi and adx >= 20 and open > ema50lo
//ell= rsi > 50 and ta.crossunder(wma5, wma9) and psar > high and ema18 <= ema50hi and macdline > 0 and macdline < signalline
//buy= ta.crossunder(close, ema50) and rsi < 50 and adx2 < adx2[1] and k < 25 and psar > high
//uy= rsi < 60 and ta.crossover(wma5, wma9) and psar < low and ema18 >= ema50 and macdline2 > 0 and diplus2 < 30 // and histline2 < 0
//buy= ema18 > ema50 and ta.crossunder(rsi, 45) and open < ema50hi and adx2[3] < adx2 and diplus2 < 25 and macdline < 0 and adx < 10
//sell= ta.crossover(close, ema50) and rsi > 50 and adx2 < adx2[1] and k > 75 and psar < low
//ell= ema18 < ema50 and ta.crossover(rsi, 60) and open > ema50lo and diminus2 < 30 and macdline2 < 0 and adx2[2] < adx2
//buy sell conditions 1
//buy= ta.crossover(wma5, ema18) and ema18 > ema50lo and diplus > 22 and diminus < 22 and adx > 15
//ell= ta.crossover(psar, high) and macdline2 < signalline2 and rsi < rsisma
//when conditions
buytrig= ema34 >= ema50lo
selltrig= ema34 <= ema50hi
//strategy
sl= low - atr * 8
tp= high + atr * 4
sellsl= high + atr * 8
selltp= low - atr * 4
if(buy)
strategy.entry("buy", strategy.long, 5000, when= buytrig)
strategy.exit("exit buy", "buy", limit= tp, stop= sl)
strategy.close("close", when= ta.crossunder(ema34, ema50lo))
if(sell)
strategy.entry("sell", strategy.short, 5000, when= selltrig)
strategy.exit("exit sell", "sell", limit= selltp, stop= sellsl)
|
RSI Strategy | https://www.tradingview.com/script/YtiO7ClG-RSI-Strategy/ | REV0LUTI0N | https://www.tradingview.com/u/REV0LUTI0N/ | 280 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © REV0LUTI0N
//@version=4
strategy("RSI Strategy", overlay=true, initial_capital = 10000, default_qty_value = 10000, default_qty_type = strategy.cash)
// Strategy Backtesting
startDate = input(timestamp("2021-10-01T00:00:00"), type = input.time, title='Backtesting Start Date')
finishDate = input(timestamp("9999-12-31T00:00:00"), type = input.time, title='Backtesting End Date')
time_cond = time >= startDate and time <= finishDate
// Strategy
Length = input(12, minval=1)
src = input(close, title="Source")
overbought = input(70, minval=1)
oversold = input(30, minval=1)
xRSI = rsi(src, Length)
rsinormal = input(true, title="Overbought Go Long & Oversold Go Short")
rsiflipped = input(false, title="Overbought Go Short & Oversold Go Long")
// EMA Filter
noemafilter = input(true, title="No EMA Filter")
useemafilter = input(false, title="Use EMA Filter")
ema_length = input(defval=15, minval=1, title="EMA Length")
emasrc = input(close, title="Source")
ema = ema(emasrc, ema_length)
plot(ema, "EMA", style=plot.style_linebr, color=#cad850, linewidth=2)
//Time Restriction Settings
startendtime = input("", title='Time Frame To Enter Trades')
enableclose = input(false, title='Enable Close Trade At End Of Time Frame')
timetobuy = (time(timeframe.period, startendtime))
timetoclose = na(time(timeframe.period, startendtime))
// Stop Loss & Take Profit % Based
enablesl = input(false, title='Enable Stop Loss')
enabletp = input(false, title='Enable Take Profit')
stopTick = input(5.0, title='Stop Loss %', type=input.float, step=0.1) / 100
takeTick = input(10.0, title='Take Profit %', type=input.float, step=0.1) / 100
longStop = strategy.position_avg_price * (1 - stopTick)
shortStop = strategy.position_avg_price * (1 + stopTick)
shortTake = strategy.position_avg_price * (1 - takeTick)
longTake = strategy.position_avg_price * (1 + takeTick)
plot(strategy.position_size > 0 and enablesl ? longStop : na, style=plot.style_linebr, color=color.red, linewidth=1, title="Long Fixed SL")
plot(strategy.position_size < 0 and enablesl ? shortStop : na, style=plot.style_linebr, color=color.red, linewidth=1, title="Short Fixed SL")
plot(strategy.position_size > 0 and enabletp ? longTake : na, style=plot.style_linebr, color=color.green, linewidth=1, title="Long Take Profit")
plot(strategy.position_size < 0 and enabletp ? shortTake : na, style=plot.style_linebr, color=color.green, linewidth=1, title="Short Take Profit")
// Alert messages
message_enterlong = input("", title="Long Entry message")
message_entershort = input("", title="Short Entry message")
message_closelong = input("", title="Close Long message")
message_closeshort = input("", title="Close Short message")
// Strategy Execution
if (xRSI > overbought and close > ema and time_cond and timetobuy and rsinormal and useemafilter)
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if (xRSI < oversold and close < ema and time_cond and timetobuy and rsinormal and useemafilter)
strategy.entry("Short", strategy.short, alert_message = message_entershort)
if (xRSI < oversold and close > ema and time_cond and timetobuy and rsiflipped and useemafilter)
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if (xRSI > overbought and close < ema and time_cond and timetobuy and rsiflipped and useemafilter)
strategy.entry("Short", strategy.short, alert_message = message_entershort)
if (xRSI > overbought and time_cond and timetobuy and rsinormal and noemafilter)
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if (xRSI < oversold and time_cond and timetobuy and rsinormal and noemafilter)
strategy.entry("Short", strategy.short, alert_message = message_entershort)
if (xRSI < oversold and time_cond and timetobuy and rsiflipped and noemafilter)
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if (xRSI > overbought and time_cond and timetobuy and rsiflipped and noemafilter)
strategy.entry("Short", strategy.short, alert_message = message_entershort)
if strategy.position_size > 0 and timetoclose and enableclose
strategy.close_all(alert_message = message_closelong)
if strategy.position_size < 0 and timetoclose and enableclose
strategy.close_all(alert_message = message_closeshort)
if strategy.position_size > 0 and enablesl and time_cond
strategy.exit(id="Close Long", stop=longStop, limit=longTake, alert_message = message_closelong)
if strategy.position_size < 0 and enablesl and time_cond
strategy.exit(id="Close Short", stop=shortStop, limit=shortTake, alert_message = message_closeshort)
if strategy.position_size > 0 and enabletp and time_cond
strategy.exit(id="Close Long", stop=longStop, limit=longTake, alert_message = message_closelong)
if strategy.position_size < 0 and enabletp and time_cond
strategy.exit(id="Close Short", stop=shortStop, limit=shortTake, alert_message = message_closeshort)
|
Linear Channel - Scalp Strategy 15M | https://www.tradingview.com/script/loS16r1z-Linear-Channel-Scalp-Strategy-15M/ | TradingAmmo | https://www.tradingview.com/u/TradingAmmo/ | 567 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TradingAmmo
//@version=4
strategy("Linear Channel", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=0.075, currency='USD')
startP = timestamp(input(2017, "Start Year"), input(12, "Month"), input(17, "Day"), 0, 0)
end = timestamp(input(9999, "End Year"), 1, 1, 0, 0)
_testPeriod() =>
iff(time >= startP and time <= end, true, false)
//linreg
length = input(55)
linreg = linreg(close, length, 0)
plot(linreg, color=color.white)
//calc band
Value = input(-2)
sub = (Value/100)+1
Band2 = linreg*sub
plot(Band2, color=color.red)
//HMA as a filter
HMA = input(400, minval=1)
plot(hma(close, HMA), color=color.purple)
long_condition = close < Band2 and hma(close, HMA) < close and _testPeriod()
strategy.entry('BUY', strategy.long, when=long_condition)
short_condition = close > linreg
strategy.close('BUY', when=short_condition)
|
MA Bollinger Bands + RSI | https://www.tradingview.com/script/2MMNHl97-MA-Bollinger-Bands-RSI/ | LucasVivien | https://www.tradingview.com/u/LucasVivien/ | 1,320 | strategy | 5 | MPL-2.0 | // This close code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Special credits: ChartArt / Matthew J. Slabosz / Zen & The Art of Trading
// Scipt Author: © LucasVivien
//@version=5
strategy('MA Bollinger Bands + RSI (Strategy)', shorttitle='MABB+RSI (Strat)', calc_on_order_fills=true, overlay=true, initial_capital=10000, default_qty_type=strategy.cash, default_qty_value=10000, commission_value=0.1)
//==============================================================================
//================================ INPUTS ==================================
//==============================================================================
var g_trades = ' Trade Parameters'
longTradesON = input.bool (title='Long trades' , defval=true , group=g_trades, inline='a', tooltip='')
shortTradesON = input.bool (title='Short trades' , defval=true , group=g_trades, inline='a', tooltip='Switch on/off long and short trades')
useTP = input.bool (title='Use Take Profit' , defval=false, group=g_trades, inline='' , tooltip='Fixed Take Profit value')
useSL = input.bool (title='Use Stop Loss' , defval=false, group=g_trades, inline='' , tooltip='Fixed Stop Loss value')
useTSL = input.bool (title='Use Trailing Stop' , defval=true , group=g_trades, inline='' , tooltip='ATR Trailing Stop Loss value ')
reEnterAfterSLTP = input.bool (title='Re-Entry after SL/TP', defval=true , group=g_trades, inline='' , tooltip='Allows to re-enter trades in the same direction as previous trade if previous trade\'s stop loss or take profit was hit')
TSLlookback = input.int (title='Trailing lookback' , defval=2 , group=g_trades, inline='' , tooltip='How many bars back will trailing stops look for a swing low (longs) or sing high (short) to get a starting point', minval=0, maxval=1000, step=1)
atrMult = input.float(title='ATR Mult' , defval=9.0 , group=g_trades, inline='' , tooltip='Increase/decrease to set stops and/or targets further/closer to trade entry price', minval=0.1)
atrLen = input.int (title='ATR Length' , defval=14 , group=g_trades, inline='' , tooltip='Average of the \'True Range\' over x past bars', minval=0)
rr = input.float(title='Risk:Reward' , defval=1 , group=g_trades, inline='' , tooltip='Multiplies the take profit distance by this number ', minval=0, maxval=100, step=0.1)
var g_volatility = ' Volatility Filters'
UseVolHigh = input.bool (title='High Volatility' , defval=true , group=g_volatility, inline='b', tooltip='')
UseVolLow = input.bool (title='Low Volatility' , defval=true , group=g_volatility, inline='b', tooltip='Filters out trade signals during high volatility / low volatility or both.')
BBvolX = input.float(title='Volatility Factor' , defval=5.0 , group=g_volatility, inline='' , tooltip='Lower this number to filter out more trades when volatility at extremes', maxval=10, minval=0.1, step=0.1)
AddVol = input.bool (title='Volatility Visuals', defval=false, group=g_volatility, inline='' , tooltip='Plots additionnal graphs on the chart to illustrate how extreme levels of volatility are defined (how Bollinger Bands are colored)')
var g_MABB = ' Moving Average & Bollinger Bands'
MAtype = input.string(title='MA Type', defval='SMA', group=g_MABB, inline='c', tooltip='Type of moving average used for standard deviation', options=['SMA', 'EMA', 'WMA', 'VWMA', 'HMA'])
MAlen = input.int (title='MA Length', defval=200, group=g_MABB, inline='c', tooltip='Moving average lookback')
BBX = input.float (title=' BB Mult', defval=2.0 , group=g_MABB, inline='d', tooltip='Set upper & lower bands closer / appart', step=0.01, minval=0.001)
BBlen = input.int (title='BB Length', defval=200, group=g_MABB, inline='d', tooltip='Bollinger bands, standard deviation lookback')
var g_RSI = ' Relative Strength Index'
RSINlen = input.int(title='RSI Cross Loockback ', defval=10, group=g_RSI, tooltip='How many bars back (from price crossing-over lower bound or crossing-under upper bound) to look for corresponding RSI neutral crossover/under', minval=0, maxval=1000)
RSIN = input.int(title='RSI Neutral' , defval=50, group=g_RSI, tooltip='Defines the value at wich RSI neutral crossover or crossunder occurs')
RSIlen = input.int(title='RSI Length' , defval=6 , group=g_RSI, tooltip='Relative Strenght Index lookback')
var g_datetime = ' Date & Time Filters'
UseDateFilter = input.bool (title='Enable Date Filter' , defval=false , group=g_datetime, tooltip='Turns on/off date filter')
StartDate = input.time (title='Start Date Filter' , defval=timestamp('1 Jan 2022 00:00 +0000'), group=g_datetime, tooltip='Date & time to start excluding trades')
EndDate = input.time (title='End Date Filter' , defval=timestamp('1 Jan 2023 00:00 +0000'), group=g_datetime, tooltip='Date & time to stop excluding trades')
UseTimeFilter = input.bool (title='Enable Session Filter', defval=false , group=g_datetime, tooltip='Turns on/off time session filter')
TradingSession = input.session(title='Trading Session' , defval='1000-2200:1234567' , group=g_datetime, tooltip='No trades will be taken outside of this range')
var g_messages = ' Alert Messages'
openLongAlertMessage = input.string(title='Open Long' , defval='', group=g_messages, inline='e', tooltip='If you use 3 Commas, Paste \'\'Message for deal start signal\'\' (in Open Long) & \'\'Message to close order at Market Price\'\' (in Close Long) from your 3Commas long bot. \n\nOtherwise, you can dynamically change the alert text you wrote here by using Pinescript {{placeholders}} (Google: \'\'variables in alerts tradingview\'\' for more details)')
closeLongAlertMessage = input.string(title='Close Long' , defval='', group=g_messages, inline='e', tooltip='')
openShortAlertMessage = input.string(title='Open Short' , defval='', group=g_messages, inline='f', tooltip='If you use 3 Commas, Paste \'\'Message for deal start signal\'\' (in Open Short) & \'\'Message to close order at Market Price\'\' (in Close Short) from your 3Commas short bot. \n\nOtherwise, you can dynamically change the alert text you wrote here by using Pinescript {{placeholders}} (Google: \'\'variables in alerts tradingview\'\' for more details)')
closeShortAlertMessage = input.string(title='Close Short', defval='', group=g_messages, inline='f', tooltip='')
//==============================================================================
//================================ SIGNALS =================================
//==============================================================================
//---------------------------- BOLLINGER BANDS -----------------------------
BBdev = ta.stdev(close, BBlen) * BBX
MA = ta.sma(close, MAlen)
if MAtype == 'HMA'
MA := ta.hma(close, MAlen)
if MAtype == 'WMA'
MA := ta.wma(close, MAlen)
if MAtype == 'EMA'
MA := ta.ema(close, MAlen)
if MAtype == 'VWMA'
MA := ta.vwma(close, MAlen)
BBupper = MA + BBdev
BBlower = MA - BBdev
BBbull = open < BBlower and close > BBlower
BBbear = open > BBupper and close < BBupper
//---------------------------------- RSI -----------------------------------
RSI = ta.rsi(close, RSIlen)
RSIcrossover = ta.crossover(RSI, RSIN)
RSIcrossunder = ta.crossunder(RSI, RSIN)
RSIbull = false
for i = 0 to RSINlen by 1
if RSIcrossover[i] == true
RSIbull := true
RSIbull
RSIbear = false
for i = 0 to RSINlen by 1
if RSIcrossunder[i] == true
RSIbear := true
RSIbear
//------------------------------ VOLATILITY --------------------------------
BBvol = BBupper - BBlower
SignalLine = ta.sma(BBvol, 50)
BaseLine = ta.sma(BBvol, 2000)
HighVolLvl = BaseLine + BaseLine * BBvolX / 10
LowVolLvl = BaseLine - BaseLine * BBvolX / 10
var volExtrmHigh = false
if BBvol > HighVolLvl and UseVolHigh
volExtrmHigh := true
volExtrmHigh
else
volExtrmHigh := false
volExtrmHigh
var volExtrmLow = false
if BBvol < LowVolLvl and UseVolLow
volExtrmLow := true
volExtrmLow
else
volExtrmLow := false
volExtrmLow
//--------------------------- DATE/TIME FILTER -----------------------------
In(t) => na(time(timeframe.period, t)) == false
TimeFilter = UseTimeFilter and not In(TradingSession) or not UseTimeFilter
DateFilter = time >= StartDate and time <= EndDate
DateTime = (UseDateFilter ? not DateFilter : true) and (UseTimeFilter ? In(TradingSession) : true)
//-------------------------- SIGNALS VALIDATION ----------------------------
validLong = BBbull and RSIbull and not volExtrmHigh and not volExtrmLow and DateTime and barstate.isconfirmed
validShort = BBbear and RSIbear and not volExtrmHigh and not volExtrmLow and DateTime and barstate.isconfirmed
//==============================================================================
//======================== STOP LOSS & TAKE PROFIT =========================
//==============================================================================
//------------------------ TRADE DIRECTION CHANGE --------------------------
var lastsignalislong = false
var lastsignalisshort = false
var newTradeDirection = false
if validLong
lastsignalislong := true
lastsignalisshort := false
lastsignalisshort
if validShort
lastsignalislong := false
lastsignalisshort := true
lastsignalisshort
if lastsignalislong == true and lastsignalislong[1] == false
or lastsignalisshort == true and lastsignalisshort[1] == false
newTradeDirection := true
newTradeDirection
else
newTradeDirection := false
newTradeDirection
//--------------------------- DATA & VARIABLES -----------------------------
SPS = strategy.position_size
atr = ta.atr(atrLen)
var SLsaved = 0.0
var TPsaved = 0.0
var float TSLsaved = na
var float entryPrice = na
//---------------------------- STRAIGHT STOPS ------------------------------
SLdist = atr * atrMult
longSL = close - SLdist
longSLDist = close - longSL
longTP = close + longSLDist * rr
shortSL = close + SLdist
shortSLDist = shortSL - close
shortTP = close - shortSLDist * rr
if validLong and SPS[1] <= 0 or validShort and SPS[1] >= 0
or (validLong or validShort) and SPS[1] == 0 and reEnterAfterSLTP
SLsaved := validLong ? longSL : validShort ? shortSL : na
TPsaved := validLong ? longTP : validShort ? shortTP : na
TPsaved
//---------------------------- TRAILING STOPS ------------------------------
longTrailStart = ta.lowest(low, TSLlookback) - atr * atrMult
shortTrailStart = ta.highest(high, TSLlookback) + atr * atrMult
if validLong and SPS[1] <= 0 or validShort and SPS[1] >= 0
or (validLong or validShort) and SPS[1] == 0 and reEnterAfterSLTP
TSLsaved := validLong ? longTrailStart : validShort ? shortTrailStart : na
entryPrice := close
if SPS > 0
TSLsaved := math.max(longTrailStart , TSLsaved, TSLsaved[1])
if SPS < 0
TSLsaved := math.min(shortTrailStart, TSLsaved, TSLsaved[1])
if SPS[1] != 0 and SPS == 0
TSLsaved := na
//------------------------------ SL TP HITS --------------------------------
var longSLTPhit = false
if SPS[1] > 0 and((useTP ? high >= TPsaved[1] : false)
or (useSL ? low <= SLsaved[1] : false)
or (useTSL ? low <= TSLsaved[1] : false))
longSLTPhit := true
else
longSLTPhit := false
var shortSLTPhit = false
if SPS[1] < 0 and ((useTP ? low <= TPsaved[1] : false)
or (useSL ? high >= SLsaved[1] : false)
or (useTSL ? high >= TSLsaved[1] : false))
shortSLTPhit := true
else
shortSLTPhit := false
//==============================================================================
//================================= PLOTS ==================================
//==============================================================================
//-------------------------------- SIGNALS ---------------------------------
plotchar(validLong , title='Long Signal' , char='⬆',
location=location.belowbar, size=size.tiny, color=color.new(#3064fc, 0))
plotchar(validShort, title='Short Signal', char='⬇',
location=location.abovebar, size=size.tiny, color=color.new(#fc1049, 0))
//---------------------------- STRAIGHT STOPS ------------------------------
plot(useTP and SPS != 0 and not newTradeDirection ? TPsaved : na,
color=color.new(color.green, 0), style=plot.style_linebr)
plot(useSL and SPS != 0 and not newTradeDirection ? SLsaved : na,
color=color.new(color.red, 0), style=plot.style_linebr)
//---------------------------- TRAILING STOPS ------------------------------
TSLcolor = SPS > 0 and entryPrice > TSLsaved ? color.red : SPS > 0 and entryPrice < TSLsaved ? color.green :
SPS < 0 and entryPrice < TSLsaved ? color.red : SPS < 0 and entryPrice > TSLsaved ? color.green : na
plot(useTSL and SPS != 0 and not newTradeDirection ? TSLsaved : na, color=TSLcolor, style=plot.style_linebr)
//---------------------------- BOLLINGER BANDS -----------------------------
plot(MA, title='Moving Average', color=color.new(color.white, 50))
PriceUpperLine = plot(BBupper, title='BBprice Upper', color=color.new(color.gray, transp=60))
PriceLowerLine = plot(BBlower, title='BBprice Lower', color=color.new(color.gray, transp=60))
fill(PriceUpperLine, PriceLowerLine, title='BBprice Fill', color=
volExtrmHigh and BBvol > BBvol[1] ? color.new(#ff1010, 70) :
volExtrmHigh and BBvol < BBvol[1] ? color.new(#ff1010, 75) :
volExtrmLow and BBvol < BBvol[1] ? color.new(#10ff10, 70) :
volExtrmLow and BBvol > BBvol[1] ? color.new(#10ff10, 75) :
color.new(color.white, 90))
//------------------------------ VOLATILITY --------------------------------
plot((UseVolHigh or UseVolLow) and AddVol ? BBvol : na, title='BBvol' , color=color.new(color.blue , 10))
plot((UseVolHigh or UseVolLow) and AddVol ? SignalLine : na, title='Signal Line', color=color.new(color.fuchsia, 10))
plot((UseVolHigh or UseVolLow) and AddVol ? BaseLine : na, title='Base Line' , color=color.new(color.yellow , 10))
VolUpperLine = plot((UseVolHigh or UseVolLow) and AddVol ? HighVolLvl : na, title='BBvol Upper', color=color.new(color.yellow, 70))
VolLowerLine = plot((UseVolHigh or UseVolLow) and AddVol ? LowVolLvl : na, title='BBvol Lower', color=color.new(color.yellow, 70))
fill(VolUpperLine, VolLowerLine, title='BBvol Fill', color=color.new(color.yellow, 98))
//--------------------------- DATE/TIME FILTER -----------------------------
bgcolor(DateFilter and UseDateFilter ? color.rgb(255, 70, 70, 85) : na, title='Date Filter')
bgcolor(TimeFilter and UseTimeFilter ? color.rgb(255, 70, 70, 85) : na, title='Time Filter')
//==============================================================================
//=========================== STRATEGY & ALERTS ===========================
//==============================================================================
//--------------------------------- LONGS ----------------------------------
if longTradesON and validLong and newTradeDirection
or longTradesON and validLong and SPS[1] == 0 and reEnterAfterSLTP
and not (validLong and longSLTPhit)
strategy.entry(id='Long', direction=strategy.long)
alert(openLongAlertMessage , alert.freq_once_per_bar_close)
strategy.exit(id='Long exit', from_entry='Long',
stop = useSL ? SLsaved : useTSL ? TSLsaved : newTradeDirection ? BBupper : na,
limit = useTP ? TPsaved : na,
when = SPS > 0)
if longSLTPhit or (shortTradesON and validShort and newTradeDirection)
alert(closeLongAlertMessage , alert.freq_once_per_bar)
//-------------------------------- SHORTS ----------------------------------
if shortTradesON and validShort and newTradeDirection
or shortTradesON and validShort and SPS[1] == 0 and reEnterAfterSLTP
and not (validShort and shortSLTPhit)
strategy.entry(id='Short', direction=strategy.short)
alert(openShortAlertMessage , alert.freq_once_per_bar_close)
strategy.exit(id='Short exit', from_entry='Short',
stop = useSL ? SLsaved : useTSL ? TSLsaved : newTradeDirection ? BBlower : na,
limit = useTP ? TPsaved : na,
when = SPS < 0)
if shortSLTPhit or (longTradesON and validLong and newTradeDirection)
alert(closeShortAlertMessage, alert.freq_once_per_bar)
|
Jigga - Survival Level | https://www.tradingview.com/script/SGxQ10Y3-Jigga-Survival-Level/ | jigneshjc | https://www.tradingview.com/u/jigneshjc/ | 199 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jigneshjc
//@version=5
strategy("Jigga - Survival Level", shorttitle='Jigga - Survival Level', overlay=true)
doBackTesting = input(false, 'Run Back Testing')
entryCondition = false
exitCondition = false
ab21 = 14, gh41 = ab21
gh42 = ab21, ju51 = 14
ki61 = ju51
lkolkp = true ,ab22 = 58
cd31 = 5 , ab23 = 42
aa12 = 29, cd32 = 26
op71 = 5, aa11 = 12
aa13 = 9, op72 = 2.0
movnwx = false
kahachale(byju, h, l) =>
mika = ta.change(h)
awer = -ta.change(l)
uikmhDM = na(mika) ? na : mika > awer and mika > 0 ? mika : 0
wrtdfcDM = na(awer) ? na : awer > mika and awer > 0 ? awer : 0
bbct = ta.rma(ta.tr, byju)
uikmh = fixnan(100 * ta.rma(uikmhDM, byju) / bbct)
wrtdfc = fixnan(100 * ta.rma(wrtdfcDM, byju) / bbct)
[uikmh, wrtdfc]
trial(gh42, gh41, h, l) =>
[uikmh, wrtdfc] = kahachale(gh42, h, l)
uuolop = uikmh + wrtdfc
trial = 100 * ta.rma(math.abs(uikmh - wrtdfc) / (uuolop == 0 ? 1 : uuolop), gh41)
trial
_pr(src, byjugth) =>
max = ta.highest(byjugth)
min = ta.lowest(byjugth)
100 * (src - max) / (max - min)
kyukarna(khulmkhula, mikaarwala, nichewala, bandhwala, partiwala) =>
sig = trial(gh42, gh41, mikaarwala, nichewala)
trialIncreasing = sig > ta.ema(sig, 5) ? lkolkp : movnwx
rolkmn = ta.ema(bandhwala, aa11)
psolkmn = ta.ema(bandhwala, aa12)
ujghd = rolkmn - psolkmn
wrtycv = ta.ema(ujghd, aa13)
kimnjg = ujghd - wrtycv
mikalilo = ta.rma(math.max(ta.change(bandhwala), 0), ab21)
awerlilo = ta.rma(-math.min(ta.change(bandhwala), 0), ab21)
lilo = awerlilo == 0 ? 100 : mikalilo == 0 ? 0 : 100 - 100 / (1 + mikalilo / awerlilo)
juylknlilo = ta.ema(lilo, 3)
rjuylkn = ta.ema(bandhwala, cd31)
psjuylkn = ta.ema(bandhwala, cd32)
percentR = _pr(bandhwala, ju51)
juylknpercentR = ta.ema(percentR, 3)
ad = bandhwala == mikaarwala and bandhwala == nichewala or mikaarwala == nichewala ? 0 : (2 * bandhwala - nichewala - mikaarwala) / (mikaarwala - nichewala) * partiwala
kiloValue = math.sum(ad, ki61) / math.sum(partiwala, ki61)
liiopn = ta.atr(op71)
mikaliiopn = (mikaarwala + nichewala) / 2 - op72 * liiopn
mika1liiopn = nz(mikaliiopn[1], mikaliiopn)
mikaliiopn := bandhwala[1] > mika1liiopn ? math.max(mikaliiopn, mika1liiopn) : mikaliiopn
dnliiopn = (mikaarwala + nichewala) / 2 + op72 * liiopn
dn1liiopn = nz(dnliiopn[1], dnliiopn)
dnliiopn := bandhwala[1] < dn1liiopn ? math.min(dnliiopn, dn1liiopn) : dnliiopn
omnerliiopn = 1
omnerliiopn := nz(omnerliiopn[1], omnerliiopn)
omnerliiopn := omnerliiopn == -1 and bandhwala > dn1liiopn ? 1 : omnerliiopn == 1 and bandhwala < mika1liiopn ? -1 : omnerliiopn
fitur = ujghd > 0 ? ujghd > wrtycv ? 1 : 0 : ujghd > wrtycv ? 0 : -1
mitur = kimnjg >= 0 ? kimnjg > kimnjg[1] ? 1 : 0 : kimnjg > kimnjg[1] ? 0 : -1
ritur = juylknlilo > ab22 ? 1 : juylknlilo < ab23 ? -1 : 0
circuits = rjuylkn > psjuylkn ? 1 : -1
trialPoints = trialIncreasing ? close > ta.ema(close, 3) ? 1 : -1 : 0
virar = juylknpercentR > -ab23 ? 1 : juylknpercentR < -ab22 ? -1 : 0
chikar = kiloValue > 0.1 ? 1 : kiloValue < -0.1 ? -1 : 0
sitar = omnerliiopn
p = fitur + mitur + ritur + circuits + trialPoints + virar + chikar + sitar
p
currentP = kyukarna(open, high, low, close, volume)
currentPNew = currentP >= 0 and currentP[1] <= 0 ? 0 : currentP <= 0 and currentP[1] >= 0 ? 0 : currentP
colorPNew = currentPNew == 0 ? color.black : currentPNew >= 0 ? color.green : color.red
//plot(currentPNew, color=colorPNew, title='CurrentTimeFrame')
LTN = 0.0
LTN := nz(LTN) ? 0.0 : (currentPNew[1] < 0 and currentPNew >= 0) ? high * 1.005 : (currentPNew[1] > 0 and currentPNew <= 0) ? low * 0.995 : LTN[1]
LClr = color.green
LClr := (currentPNew[1] < 0 and currentPNew >= 0) ? color.green : (currentPNew[1] > 0 and currentPNew <= 0) ? color.red : LClr[1]
plot(LTN,color=LClr,title="Level", style=plot.style_circles)
entryCondition:= high > LTN and LClr == color.green or(currentPNew[1] > 0 and currentPNew > 0) ? lkolkp : movnwx
exitCondition:= (low < LTN and LClr == color.red) or(currentPNew[1] < 0 and currentPNew < 0) ? lkolkp : movnwx
tradeRunning = movnwx
tradeRunning := nz(tradeRunning) ? movnwx : (not tradeRunning[1]) and entryCondition ? lkolkp : tradeRunning[1] and exitCondition ? movnwx : tradeRunning[1]
plotshape(tradeRunning and (not tradeRunning[1]) and (not doBackTesting), style=shape.labelup, location=location.belowbar, color=color.new(#00FF00, 50), size=size.tiny, title='Buy wrtycv', text='➹', textcolor=color.new(color.black,0))
plotshape((not tradeRunning) and tradeRunning[1] and (not doBackTesting), style=shape.labeldown, location=location.abovebar, color=color.new(#FF0000, 50), size=size.tiny, title='Sell wrtycv', text='➷', textcolor=color.new(color.white, 0))
if entryCondition and doBackTesting
strategy.entry(id="Buy",direction=strategy.long)
if exitCondition and doBackTesting
strategy.close(id="Buy")
|
Donchian Channel Strategy Idea | https://www.tradingview.com/script/KA6ZtxT8-Donchian-Channel-Strategy-Idea/ | QuantCT | https://www.tradingview.com/u/QuantCT/ | 193 | strategy | 4 | MPL-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("Donchian Channel Strategy Idea",
shorttitle="Donchian",
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
high_period = input(title="High Period", defval=10)
low_period = input(title="Low 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
highest_high = highest(high, high_period)
lowest_low = lowest(low, low_period)
base_line = (highest_high + lowest_low) / 2
enter_long = (close > highest_high[1])
exit_long = (close < base_line)
enter_short = (close < lowest_low[1])
exit_short = (close > base_line)
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 =
strategy.position_size > 0 ? #27D600 :
strategy.position_size < 0 ? #E30202 :
color.orange
highest_high_plot = plot(highest_high, color=colors)
lowest_low_plot = plot(lowest_low, color=colors)
plot(base_line, color=color.silver)
fill(highest_high_plot, lowest_low_plot, color=colors, transp=90)
|
Pivot Point Breakout | https://www.tradingview.com/script/TW0P138b/ | EduardoMattje | https://www.tradingview.com/u/EduardoMattje/ | 165 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © EduardoMattje
//@version=5
strategy("Pivot Point Breakout", "PPB", true, default_qty_type=strategy.percent_of_equity, default_qty_value=100, process_orders_on_close=true)
// Constants
var L_PIVOT_HIGH = "Pivot high"
var L_PIVOT_LOW = "Pivot low"
var LEFT = "Left"
var RIGHT = "Right"
var BOTH = "Both"
var LONG = "Long"
var SHORT = "Short"
var DATES = "Date selection"
var DATES_TOOLTIP = "Change it to limit the trades for the given time interval.\n\nLeave it to disable this behaviour."
// Inputs
var orderDirection = input.string(LONG, "Order direction", options=[BOTH, LONG, SHORT])
var leftHigh = input.int(3, LEFT, minval=0, inline=L_PIVOT_HIGH, group=L_PIVOT_HIGH)
var rightHigh = input.int(3, RIGHT, minval=0, inline=L_PIVOT_HIGH, group=L_PIVOT_HIGH)
var leftLow = input.int(3, LEFT, minval=0, inline=L_PIVOT_LOW, group=L_PIVOT_LOW)
var rightLow = input.int(3, RIGHT, minval=0, inline=L_PIVOT_LOW, group=L_PIVOT_LOW)
var startDate = input.time(0, "Starting date", group=DATES)
var endDate = input.time(0, "Final date", group=DATES)
//
var float lastHigh = na
var float lastLow = na
lowPivot = ta.pivotlow(leftLow, rightLow)
highPivot = ta.pivothigh(leftHigh, rightHigh)
f_updateLevels(pivot_) =>
var float pastLevel = na
if not na(pivot_)
pastLevel := pivot_
pastLevel
lastLow := f_updateLevels(lowPivot)
lastHigh := f_updateLevels(highPivot)
// Validates the time interval
validTrade = (startDate == 0 ? true : time >= startDate) and
(endDate == 0 ? true : time <= endDate)
// Orders
if high > lastHigh
strategy.entry("Long", strategy.long, when=orderDirection != SHORT and validTrade)
strategy.close("Short", when=orderDirection == SHORT)
if low < lastLow
strategy.entry("Short", strategy.short, when=orderDirection != LONG and validTrade)
strategy.close("Long", when=orderDirection == LONG)
// Plots
plot(lastLow, "Last pivot low", color.red, offset=1)
plot(lastHigh, "Last pivot high", color.teal, offset=1)
plotshape(lowPivot, "Pivot low", location=location.belowbar, color=color.red, offset=-rightLow)
plotshape(highPivot, "Pivot high", color=color.teal, offset=-rightHigh)
|
Heikin Ashi Candle Startegy for Long Position | https://www.tradingview.com/script/CX4l7Dmy-Heikin-Ashi-Candle-Startegy-for-Long-Position/ | YohanNaftali | https://www.tradingview.com/u/YohanNaftali/ | 170 | 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/
// © YohanNaftali
//@version=5
///////////////////////////////////////////////////////////////////////////////
// Heikin Ashi Candle Startegy
// ver 2021.12.29
// © YohanNaftali
// This script composed by Yohan Naftali for educational purpose only
// Reader who will use this signal must do own research
///////////////////////////////////////////////////////////////////////////////
strategy(
title = 'Heikin Ashi Candle Startegy Long',
shorttitle = 'HA Strategy Long',
format = format.price,
precision = 6,
overlay = true)
// Input
validationPeriod = input.int(
defval = 3,
title = 'Validation Period',
group = 'Candle')
qtyOrder = input.float(
defval = 1.0,
title = 'Qty',
group = 'Order')
maxActive = input.float(
defval = 1.0,
title = 'Maximum Active Open Position',
group = 'Order')
// Long Strategy
tpLong = input.float(
defval = 1,
title = "Take Profit (%)",
minval = 0.0,
step = 0.1,
group = "Long") * 0.01
slLong = input.float(
defval = 25,
title = "Stop Loss (%)",
minval=0.0,
step=0.1,
group="Long") * 0.01
trailingStopLong = input.float(
defval = 0.2,
title = "Trailing Stop (%)",
minval = 0.0,
step = 0.1,
group = 'Long') * 0.01
// Calculation
haTicker = ticker.heikinashi(syminfo.tickerid)
haClose = request.security(haTicker, timeframe.period, close)
haOpen = request.security(haTicker, timeframe.period, open)
// Long
limitLong = tpLong > 0.0 ? strategy.position_avg_price * (1 + tpLong) : na
stopLong = slLong > 0.0 ? strategy.position_avg_price * (1 - slLong) : na
float trailLong = 0.0
trailLong := if strategy.position_size > 0
trailClose = close * (1 - trailLong)
math.max(trailClose, trailLong[1])
else
0
isGreen = true
for i = 0 to validationPeriod-1
isGreen := isGreen and haClose[i] > haOpen[i]
isLong = isGreen and haClose[validationPeriod] < haOpen[validationPeriod]
plot(
limitLong,
title = 'Limit',
color = color.rgb(0, 0, 255, 0),
style = plot.style_stepline,
linewidth = 1)
plot(
trailLong,
title = 'Trailing',
color = color.rgb(255, 255, 0, 0),
style = plot.style_stepline,
linewidth = 1)
plot(
stopLong,
title = 'Stop',
style = plot.style_stepline,
color = color.rgb(255, 0, 0, 0),
linewidth = 1)
// plotshape(
// isLong,
// title = 'Entry',
// style = shape.arrowup,
// location = location.belowbar,
// offset = 1,
// color = color.new(color.green, 0),
// text = 'Long Entry',
// size = size.small)
// Strategy
strategy.risk.max_position_size(maxActive)
strategy.risk.allow_entry_in(strategy.direction.long)
strategy.entry(
id = "Long",
direction = strategy.long,
qty = qtyOrder,
when = isLong,
alert_message = "LN")
if (strategy.position_size > 0)
strategy.exit(
id = "Long Exit",
from_entry = "Long",
limit = limitLong,
stop = stopLong,
trail_price = trailLong,
alert_message = "LX") |
TFO + ATR Strategy with Trailing Stop Loss | https://www.tradingview.com/script/yYklJwRt-TFO-ATR-Strategy-with-Trailing-Stop-Loss/ | Chart0bserver | https://www.tradingview.com/u/Chart0bserver/ | 157 | 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/
// © Chart0bserver
//
// Open Source attributions:
// portions © allanster (date window code)
// portions © Dr. John Ehlers (Trend Flex Oscillator)
//
// READ THIS CAREFULLY!!! ----------------//
// This code is provided for educational purposes only. The results of this strategy should not be considered investment advice.
// The user of this script acknolwedges that it can cause serious financial loss when used as a trading tool
// This strategy has a bias for HODL (Holds on to Losses) meaning that it provides NO STOP LOSS protection!
// Also note that the default behavior is designed for up to 15 open long orders, and executes one order to close them all at once.
// Opening a long position is predicated on The Trend Flex Oscillator (TFO) rising after being oversold, and ATR above a certain volatility threshold.
// Closing a long is handled either by TFO showing overbought while above a certain ATR level, or the Trailing Stop Loss. Pick one or both.
// If the strategy is allowed to sell before a Trailing Stop Loss is triggered, you can set a "must exceed %". Do not mistake this for a stop loss.
// Short positions are not supported in this version. Back-testing should NEVER be considered an accurate representation of actual trading results.
//@version=5
strategy('TFO + ATR Strategy with Trailing Stop Loss', 'TFO ATR Trailing Stop Loss', overlay=true, pyramiding=15, default_qty_type=strategy.cash, default_qty_value=10000, initial_capital=150000, currency='USD', commission_type=strategy.commission.percent, commission_value=0.5)
strategy.risk.allow_entry_in(strategy.direction.long) // There will be no short entries, only exits from long.
// -----------------------------------------------------------------------------------------------------------//
// Back-testing Date Range code ----------------------------------------------------------------------------//
// ---------------------------------------------------------------------------------------------------------//
fromMonth = input.int(defval=9, title='From Month', minval=1, maxval=12, group='Back-Testing Start Date')
fromDay = input.int(defval=1, title='From Day', minval=1, maxval=31, group='Back-Testing Start Date')
fromYear = input.int(defval=2021, title='From Year', minval=1970, group='Back-Testing Start Date')
thruMonth = 1 //input(defval = 1, title = "Thru Month", type = input.integer, minval = 1, maxval = 12, group="Back-Testing Date Range")
thruDay = 1 //input(defval = 1, title = "Thru Day", type = input.integer, minval = 1, maxval = 31, group="Back-Testing Date Range")
thruYear = 2112 //input(defval = 2112, title = "Thru Year", type = input.integer, minval = 1970, group="Back-Testing Date Range")
// === FUNCTION EXAMPLE ===
start = timestamp(fromYear, fromMonth, fromDay, 00, 00) // backtest start window
finish = timestamp(thruYear, thruMonth, thruDay, 23, 59) // backtest finish window
window() => // create function "within window of time
time >= start and time <= finish ? true : false
// Date range code -----//
// -----------------------------------------------------------------------------------------------------------//
// ATR Indicator Code --------------------------------------------------------------------------------------//
// ---------------------------------------------------------------------------------------------------------//
length = 18 //input(title="ATR Length", defval=18, minval=1)
Period = 18 //input(18,title="ATR EMA Period")
basicEMA = ta.ema(close, length)
ATR_Function = ta.ema(ta.tr(true), length)
EMA_ATR = ta.ema(ATR_Function, Period)
ATR = ta.ema(ta.tr(true), length)
ATR_diff = ATR - EMA_ATR
volatility = 100 * ATR_diff / EMA_ATR // measure of spread between ATR and EMA
volatilityAVG = math.round((volatility + volatility[1] + volatility[2]) / 3)
buyVolatility = input.int(3, 'Min Volatility for Buy', minval=-20, maxval=20, step=1, group='Average True Range')
sellVolatility = input.int(13, 'Min Volatility for Sell', minval=-10, maxval=20, step=1, group='Average True Range')
useAvgVolatility = input.bool(defval=false, title='Average the Volatility over 3 bars', group='Average True Range')
// End of ATR ------------/
// -----------------------------------------------------------------------------------------------------------//
// TFO Indicator code --------------------------------------------------------------------------------------//
// ---------------------------------------------------------------------------------------------------------//
trendflex(Series, PeriodSS, PeriodTrendFlex, PeriodEMA) =>
var SQRT2xPI = math.sqrt(8.0) * math.asin(1.0) // 4.44288293815 Constant
alpha = SQRT2xPI / PeriodSS
beta = math.exp(-alpha)
gamma = -beta * beta
delta = 2.0 * beta * math.cos(alpha)
float superSmooth = na
superSmooth := (1.0 - delta - gamma) * (Series + nz(Series[1])) * 0.5 + delta * nz(superSmooth[1]) + gamma * nz(superSmooth[2])
E = 0.0
for i = 1 to PeriodTrendFlex by 1
E += superSmooth - nz(superSmooth[i])
E
epsilon = E / PeriodTrendFlex
zeta = 2.0 / (PeriodEMA + 1.0)
float EMA = na
EMA := zeta * epsilon * epsilon + (1.0 - zeta) * nz(EMA[1])
return_1 = EMA == 0.0 ? 0.0 : epsilon / math.sqrt(EMA)
return_1
upperLevel = input.float(1.2, 'TFO Upper Level', minval=0.1, maxval=2.0, step=0.1, group='Trend Flex Ocillator')
lowerLevel = input.float(-0.9, 'TFO Lower Level', minval=-2.0, maxval=-0.1, step=0.1, group='Trend Flex Ocillator')
periodTrendFlex = input.int(14, 'TrendFlex Period', minval=2, group='Trend Flex Ocillator')
useSuperSmootherOveride = true //input( true, "Apply SuperSmoother Override Below*", input.bool, group="Trend Flex Ocillator")
periodSuperSmoother = 8.0 //input(8.0, "SuperSmoother Period*", input.float , minval=4.0, step=0.5, group="Trend Flex Ocillator")
postSmooth = 33 //input(33.0, "Post Smooth Period**", input.float , minval=1.0, step=0.5, group="Trend Flex Ocillator")
trendFlexOscillator = trendflex(close, periodSuperSmoother, periodTrendFlex, postSmooth)
// End of TFO -------------//
// -----------------------------------------------------------------------------------------------------------//
// HODL Don't sell if losing n% ---------------------------------------------------------------------------- //
// ---------------------------------------------------------------------------------------------------------//
sellOnStrategy = input.bool(defval=true, title='Allow Stategy to close positions', group='Selling Conditions')
doHoldLoss = true // input(defval = true, title = "Strategy can sell for a loss", type = input.bool, group="Selling Conditions")
holdLoss = input.int(defval=0, title='Value (%) must exceed ', minval=-25, maxval=10, step=1, group='Selling Conditions')
totalInvest = strategy.position_avg_price * strategy.position_size
openProfitPerc = strategy.openprofit / totalInvest
bool acceptableROI = openProfitPerc * 100 > holdLoss
// -----------------------//
// -----------------------------------------------------------------------------------------------------------//
// Buying and Selling conditions -------------------------------------------------------------------------- //
// ---------------------------------------------------------------------------------------------------------//
if useAvgVolatility
volatility := volatilityAVG
volatility
tfoBuy = trendFlexOscillator < lowerLevel and trendFlexOscillator[1] < trendFlexOscillator // Always make a purchase if TFO is in this lowest range
atrBuy = volatility > buyVolatility
tfoSell = ta.crossunder(trendFlexOscillator, upperLevel)
consensusBuy = tfoBuy and atrBuy
consensusSell = tfoSell and volatility > sellVolatility
if doHoldLoss
consensusSell := consensusSell and acceptableROI
consensusSell
// --------------------//
// -----------------------------------------------------------------------------------------------------------//
// Tracing & Debugging --------------------------------------------------------------------------------------//
// ---------------------------------------------------------------------------------------------------------//
plotchar(strategy.opentrades, 'Number of open trades', ' ', location.top)
plotarrow(100 * openProfitPerc, 'Profit on open longs', color.new(color.green, 75), color.new(color.red, 75))
// plotchar(strategy.position_size, "Shares on hand", " ", location.top)
// plotchar(totalInvest, "Total Invested", " ", location.top)
// plotarrow(strategy.openprofit, "Open profit dollar amount", color.new(color.green,100), color.new(color.red, 100))
// plotarrow(strategy.netprofit, "Net profit for session", color.new(color.green,100), color.new(color.red, 100))
// plotchar(acceptableROI, "Acceptable ROI", " ", location.top)
// plotarrow(volatility, "ATR volatility value", color.new(color.green,75), color.new(color.red, 75))
// plotchar(strategy.position_avg_price, "Avgerage price of holdings", " ", location.top)
// plotchar(volatilityAVG, "AVG volatility", " ", location.top)
// plotchar(fiveBarsVal, "change in 5bars", " ", location.top)
// plotchar(crossingUp, "crossingUp", "x", location.belowbar, textcolor=color.white)
// plotchar(crossingDown, "crossingDn", "x", location.abovebar, textcolor=color.white)
// plotchar(strategy.closedtrades, "closedtrades", " ", location.top)
// plotchar(strategy.wintrades, "wintrades", " ", location.top)
// plotchar(strategy.losstrades, "losstrades", " ", location.top)
// plotchar(close, "close", " ", location.top)
//--------------------//
// -----------------------------------------------------------------------------------------------------------//
// Trade Alert Execution ------------------------------------------------------------------------------------//
// ---------------------------------------------------------------------------------------------------------//
strategy.entry('long', strategy.long, when=window() and consensusBuy, comment='long')
if sellOnStrategy
strategy.close('long', when=window() and consensusSell, qty_percent=100, comment='Strat')
// -----------------------------------------------------------------------------------------------------------//
// Trailing Stop Loss logic -------------------------------------------------------------------------------- //
// ---------------------------------------------------------------------------------------------------------//
useTrailStop = input.bool(defval=true, title='Set Trailing Stop Loss on avg positon value', group='Selling Conditions')
arm = input.float(defval=15, title='Trailing Stop Arms At (%)', minval=1, maxval=30, step=1, group='Selling Conditions') * 0.01
trail = input.float(defval=2, title='Trailing Stop Loss (%)', minval=0.25, maxval=9, step=0.25, group='Selling Conditions') * 0.01
longStopPrice = 0.0
stopLossPrice = 0.0
if strategy.position_size > 0
longStopPrice := strategy.position_avg_price * (1 + arm)
stopLossPrice := strategy.position_avg_price * ((100 - math.abs(holdLoss)) / 100) // for use with 'stop' in strategy.exit
stopLossPrice
else
longStopPrice := close
longStopPrice
// If you want to hide the Trailing Stop Loss threshold (green line), comment this out
plot(longStopPrice, 'Arm Trail Stop at', color.new(color.green, 60), linewidth=2)
if strategy.position_size > 0 and useTrailStop
strategy.exit('exit', 'long', when=window(), qty_percent=100, trail_price=longStopPrice, trail_offset=trail * close / syminfo.mintick, comment='Trail')
//-----------------------------------------------------------------------------------------------------------//
|
EMA 9 & 20 Cross Strategy | https://www.tradingview.com/script/FwyqBaAX-EMA-9-20-Cross-Strategy/ | pdsreenivasu | https://www.tradingview.com/u/pdsreenivasu/ | 53 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// This strategy has been created for illustration purposes only and should not be relied upon as a basis for buying, selling, or holding any asset or security.
// © kirilov
//@version=4
strategy(
"EMA Cross Strategy",
overlay=true,
calc_on_every_tick=true,
currency=currency.USD
)
// INPUT:
// Options to enter fast and slow Exponential Moving Average (EMA) values
emaFast = input(title="Fast EMA", type=input.integer, defval=9, minval=1, maxval=9999)
emaSlow = input(title="Slow EMA", type=input.integer, defval=20, minval=1, maxval=9999)
// Option to select trade directions
tradeDirection = input(title="Trade Direction", options=["Long", "Short", "Both"], defval="Both")
// Options that configure the backtest date range
startDate = input(title="Start Date", type=input.time, defval=timestamp("01 Jan 1970 00:00"))
endDate = input(title="End Date", type=input.time, defval=timestamp("31 Dec 2170 23:59"))
// CALCULATIONS:
// Use the built-in function to calculate two EMA lines
fastEMA = ema(close, emaFast)
slowEMA = ema(close, emaSlow)
// PLOT:
// Draw the EMA lines on the chart
plot(series=fastEMA, color=color.black, linewidth=2)
plot(series=slowEMA, color=color.red, linewidth=2)
// CONDITIONS:
// Check if the close time of the current bar falls inside the date range
inDateRange = (time >= startDate) and (time < endDate)
// Translate input into trading conditions
longOK = (tradeDirection == "Long") or (tradeDirection == "Both")
shortOK = (tradeDirection == "Short") or (tradeDirection == "Both")
// Decide if we should go long or short using the built-in functions
longCondition = crossover(fastEMA, slowEMA)
shortCondition = crossunder(fastEMA, slowEMA)
// ORDERS:
// Submit entry (or reverse) orders
if (longCondition and inDateRange)
strategy.entry(id="long", long=true, when = longOK)
if (shortCondition and inDateRange)
strategy.entry(id="short", long=false, when = shortOK)
// Submit exit orders in the cases where we trade only long or only short
if (strategy.position_size > 0 and shortCondition)
strategy.exit(id="exit long", stop=close)
if (strategy.position_size < 0 and longCondition)
strategy.exit(id="exit short", stop=close)
|
Gap Absorption Strategy | https://www.tradingview.com/script/Di9tH7dZ-Gap-Absorption-Strategy/ | noop-noop | https://www.tradingview.com/u/noop-noop/ | 293 | 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/
// © noop42
//@version=5
strategy(title="Gap Absortion Strategy", shorttitle="GAS", overlay=true)
gap_value = 0.0
pct_trig = input(0.5, 'trigger (% of the price corresponding to the gap amount)')
stop_pct = input(0.25, 'StopLoss (in % of the gap)')
target_pct = input(0.8, 'Target, (in % of the gap) (default is the whole gap value)')
tp_color = input.color(color.green, "Target color")
sl_color = input.color(color.red, "Stop Loss Color")
entry_color = input.color(color.gray, "Entry color")
var line tpl = na
var line sll = na
gap = close[1] > open ? close[1] - open : close[1] < open ? open - close[1] : 0
gap_side = close[1] > open ? 1 : -1
gap_pct = gap / close[1] * 100
interesting_gap = gap_pct >= pct_trig
long = interesting_gap and gap_side == 1 and strategy.position_size == 0.0
short = interesting_gap and gap_side == -1 and strategy.position_size == 0.0
var entry = 0.0
var stop = 0.0
var target = 0.0
if gap and interesting_gap
if long
entry := open
target := entry + gap * target_pct
stop := entry - gap * stop_pct
stop
if short
entry := open
target := entry - gap * target_pct
stop := entry + gap * stop_pct
stop
exitTP = strategy.position_size != 0.0 and (ta.cross(high, target) or ta.cross(low, target))
exitSL = strategy.position_size != 0.0 and ta.cross(close, stop)
exit = exitTP or exitSL
strategy.entry('Buy', strategy.long, when=long)
strategy.close('Buy', when=exit)
strategy.entry('Sell', strategy.short, when=short)
strategy.close('Sell', when=exit)
if exit
entry := 0.0
target := 0.0
stop := 0.0
line.delete(tpl)
line.delete(sll)
plotshape(long ? 1 : 0, style=shape.triangleup, size=size.tiny, location=location.bottom, color=color.new(color.lime, 0), text='Bearish gap\nBuy signal')
plotshape(short ? 1 : 0, style=shape.triangledown, size=size.tiny, location=location.bottom, color=color.new(color.red, 0), text='Bullish gap\nSell signal')
plotshape(exitTP ? 1 : 0, style=shape.xcross, size=size.tiny, location=location.bottom, color=color.new(color.green, 0), text='Hit TP')
plotshape(exitSL ? 1 : 0, style=shape.xcross, size=size.tiny, location=location.bottom, color=color.new(color.orange, 0), text='Hit SL')
var tbl = table.new(position.top_right, 2, 5)
if target[1] == 0.0 and target != 0.0
tpl := line.new(bar_index[1], target, bar_index, target, extend=extend.right, color=tp_color)
sll := line.new(bar_index[1], stop, bar_index, stop, extend=extend.right, color=sl_color)
table.cell(tbl, 0, 0, 'Current target', bgcolor=#cccccc)
table.cell(tbl, 1, 0, str.tostring(target, "#.####"), bgcolor=tp_color)
table.cell(tbl, 0, 1, 'Entry Signal', bgcolor=#cccccc)
table.cell(tbl, 1, 1, str.tostring(entry, "#.####"), bgcolor=entry_color)
table.cell(tbl, 0, 2, 'Stop Signal', bgcolor=#cccccc)
table.cell(tbl, 1, 2, str.tostring(stop, "#.####"), bgcolor=sl_color)
|
Supertrend Strategy | https://www.tradingview.com/script/XVSrrhQw-Supertrend-Strategy/ | REV0LUTI0N | https://www.tradingview.com/u/REV0LUTI0N/ | 263 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © REV0LUTI0N
//@version=4
//------------------------------------------------------------------------------
// Strategy
strategy("Supertrend Strategy", overlay=true, initial_capital = 10000, default_qty_value = 10000, default_qty_type = strategy.cash)
notes = input("", title="Note For Your Reference Only")
//------------------------------------------------------------------------------
// Strategy Backtesting
startDate = input(timestamp("2021-10-01T00:00:00"), type = input.time, title='Backtesting Start Date', group="Backtesting")
finishDate = input(timestamp("9999-12-31T00:00:00"), type = input.time, title='Backtesting End Date', group="Backtesting")
time_cond = time >= startDate and time <= finishDate
//------------------------------------------------------------------------------
//Time Restriction Settings
startendtime = input("", title='Time Frame To Enter Trades', group="Time Restriction")
endtime = input("", title='Time Frame To Exit Trades', group="Time Restriction")
enableclose = input(false, title='Enable Close Trade At End Of Exit Time Frame', group="Time Restriction")
timetobuy = (time(timeframe.period, startendtime))
timetoclose = na(time(timeframe.period, endtime))
enableentry = input(true, title="Enter Supertrend ASAP", inline="1", group="Time Restriction")
waitentry = input(false, title="Wait To Enter Supertrend", inline="1", group="Time Restriction")
//------------------------------------------------------------------------------
// Contrarian Settings
nocontrarian = input(true, title="Trade Regular Signals", inline="1", group="Contrarian Settings")
usecontrarian = input(false, title="Trade Contrarian Signals", inline="1", group="Contrarian Settings")
//------------------------------------------------------------------------------
// Supertrend Code
nosupertrend = input(false, title="No Supertrend", inline="1", group="Supertrend Settings")
usesupertrend = input(true, title="Use Supertrend", inline="1", group="Supertrend Settings")
Periods = input(title="ATR Period", type=input.integer, defval=10, group="Supertrend Settings")
src = input(hl2, title="ATR Source", group="Supertrend Settings")
Multiplier = input(title="ATR Multiplier", type=input.float, step=0.1, defval=3.0, group="Supertrend Settings")
changeATR= input(title="Change ATR Calculation Method ?", type=input.bool, defval=true, group="Supertrend Settings")
atr2 = sma(tr, Periods)
atr= changeATR ? atr(Periods) : atr2
up=src-(Multiplier*atr)
up1 = nz(up[1],up)
up := close[1] > up1 ? max(up,up1) : up
dn=src+(Multiplier*atr)
dn1 = nz(dn[1], dn)
dn := close[1] < dn1 ? min(dn, dn1) : dn
trend = 1
trend := nz(trend[1], trend)
trend := trend == -1 and close > dn1 ? 1 : trend == 1 and close < up1 ? -1 : trend
upPlot = plot(trend == 1 ? up : na, title="Up Trend", style=plot.style_linebr, linewidth=2, color=color.green)
Long = (trend == 1 ? up : na)
buySignal = trend == 1 and trend[1] == -1
dnPlot = plot(trend == 1 ? na : dn, title="Down Trend", style=plot.style_linebr, linewidth=2, color=color.red)
Short = (trend == 1 ? na : dn)
sellSignal = trend == -1 and trend[1] == 1
//------------------------------------------------------------------------------
// EMA Filter
noemafilter = input(true, title="No EMA Filter", inline="1", group="EMA Filter")
useemafilter = input(false, title="Use EMA Filter", inline="1", group="EMA Filter")
ema_length = input(defval=15, minval=1, title="EMA Length", group="EMA Filter")
emasrc = input(close, title="EMA Source", group="EMA Filter")
emapricesrc = input(close, title="EMA Price Source", group="EMA Filter")
ema = ema(emasrc, ema_length)
plot(useemafilter ? ema : na, "EMA", style=plot.style_linebr, color=#cad850, linewidth=2)
//------------------------------------------------------------------------------
// CMF Filter
nocmffilter = input(true, title="No CMF Filter", inline="1", group="CMF Filter")
usecmffilter = input(false, title="Use CMF Filter", inline="1", group="CMF Filter")
mflength = input(title="CMF length", group="CMF Filter", type=input.integer, defval=20)
mfsrc = input(close, title="CMF Source", group="CMF Filter")
ad = mfsrc==high and mfsrc==low or high==low ? 0 : ((2*mfsrc-low-high)/(high-low))*volume
mf = sum(ad, mflength) / sum(volume, mflength)
//------------------------------------------------------------------------------
// Stop Loss & Take Profit % Based
enablesltp = input(false, title='Enable Stop Loss & Take Profit', group="% Stop Loss & Take Profit")
stopTick = input(2.0, title='Stop Loss %', group="% Stop Loss & Take Profit", type=input.float, step=0.1) / 100
takeTick = input(4.0, title='Take Profit %', group="% Stop Loss & Take Profit", type=input.float, step=0.1) / 100
longStop = strategy.position_avg_price * (1 - stopTick)
shortStop = strategy.position_avg_price * (1 + stopTick)
shortTake = strategy.position_avg_price * (1 - takeTick)
longTake = strategy.position_avg_price * (1 + takeTick)
plot(strategy.position_size > 0 and enablesltp and nocontrarian ? longStop : na, style=plot.style_linebr, color=color.red, linewidth=1, title="Long Stop Loss")
plot(strategy.position_size < 0 and enablesltp and nocontrarian ? shortStop : na, style=plot.style_linebr, color=color.red, linewidth=1, title="Short Stop Loss")
plot(strategy.position_size > 0 and enablesltp and nocontrarian ? longTake : na, style=plot.style_linebr, color=color.green, linewidth=1, title="Long Take Profit")
plot(strategy.position_size < 0 and enablesltp and nocontrarian ? shortTake : na, style=plot.style_linebr, color=color.green, linewidth=1, title="Short Take Profit")
plot(strategy.position_size > 0 and enablesltp and usecontrarian ? longStop : na, style=plot.style_linebr, color=color.red, linewidth=1, title="Contrarian Long Stop Loss")
plot(strategy.position_size < 0 and enablesltp and usecontrarian ? shortStop : na, style=plot.style_linebr, color=color.red, linewidth=1, title="Contrarian Short Stop Loss")
plot(strategy.position_size > 0 and enablesltp and usecontrarian ? longTake : na, style=plot.style_linebr, color=color.green, linewidth=1, title="Contrarian Long Take Profit")
plot(strategy.position_size < 0 and enablesltp and usecontrarian ? shortTake : na, style=plot.style_linebr, color=color.green, linewidth=1, title="Contrarian Short Take Profit")
//------------------------------------------------------------------------------
// Alert messages
message_enterlong = input("", title="Long Entry message", group="Alert Messages")
message_entershort = input("", title="Short Entry message", group="Alert Messages")
message_closelong = input("", title="Close Long message", group="Alert Messages")
message_closeshort = input("", title="Close Short message", group="Alert Messages")
//------------------------------------------------------------------------------
// Strategy Execution
//------------------------------------------------------------------------------
// No EMA or CMF Entry
if Long and time_cond and timetobuy and enableentry and noemafilter and nocmffilter and usesupertrend and nocontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if Short and time_cond and timetobuy and enableentry and noemafilter and nocmffilter and usesupertrend and nocontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
if buySignal and time_cond and timetobuy and waitentry and noemafilter and nocmffilter and usesupertrend and nocontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if sellSignal and time_cond and timetobuy and waitentry and noemafilter and nocmffilter and usesupertrend and nocontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
// Contrarian - No EMA or CMF Entry
if Long and time_cond and timetobuy and enableentry and noemafilter and nocmffilter and usesupertrend and usecontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
if Short and time_cond and timetobuy and enableentry and noemafilter and nocmffilter and usesupertrend and usecontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if buySignal and time_cond and timetobuy and waitentry and noemafilter and nocmffilter and usesupertrend and usecontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
if sellSignal and time_cond and timetobuy and waitentry and noemafilter and nocmffilter and usesupertrend and usecontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
//------------------------------------------------------------------------------
// Use EMA but No CMF Entry with supertrend
if Long and emapricesrc > ema and time_cond and timetobuy and enableentry and useemafilter and nocmffilter and usesupertrend and nocontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if Short and emapricesrc < ema and time_cond and timetobuy and enableentry and useemafilter and nocmffilter and usesupertrend and nocontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
if buySignal and emapricesrc > ema and time_cond and timetobuy and waitentry and useemafilter and nocmffilter and usesupertrend and nocontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if sellSignal and emapricesrc < ema and time_cond and timetobuy and waitentry and useemafilter and nocmffilter and usesupertrend and nocontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
// Use EMA but No CMF Entry no supertrend
if emapricesrc > ema and time_cond and timetobuy and enableentry and useemafilter and nocmffilter and nosupertrend and nocontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if emapricesrc < ema and time_cond and timetobuy and enableentry and useemafilter and nocmffilter and nosupertrend and nocontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
if emapricesrc > ema and time_cond and timetobuy and waitentry and useemafilter and nocmffilter and nosupertrend and nocontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if emapricesrc < ema and time_cond and timetobuy and waitentry and useemafilter and nocmffilter and nosupertrend and nocontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
// Contrarian - Use EMA but No CMF Entry with supertrend
if Long and emapricesrc > ema and time_cond and timetobuy and enableentry and useemafilter and nocmffilter and usesupertrend and usecontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
if Short and emapricesrc < ema and time_cond and timetobuy and enableentry and useemafilter and nocmffilter and usesupertrend and usecontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if buySignal and emapricesrc > ema and time_cond and timetobuy and waitentry and useemafilter and nocmffilter and usesupertrend and usecontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
if sellSignal and emapricesrc < ema and time_cond and timetobuy and waitentry and useemafilter and nocmffilter and usesupertrend and usecontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
// Contrarian - Use EMA but No CMF Entry no supertrend
if emapricesrc > ema and time_cond and timetobuy and enableentry and useemafilter and nocmffilter and nosupertrend and usecontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
if emapricesrc < ema and time_cond and timetobuy and enableentry and useemafilter and nocmffilter and nosupertrend and usecontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if emapricesrc > ema and time_cond and timetobuy and waitentry and useemafilter and nocmffilter and nosupertrend and usecontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
if emapricesrc < ema and time_cond and timetobuy and waitentry and useemafilter and nocmffilter and nosupertrend and usecontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
//------------------------------------------------------------------------------
// Use CMF but No EMA Entry with supertrend
if Long and mf > 0 and time_cond and timetobuy and enableentry and noemafilter and usecmffilter and usesupertrend and nocontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if Short and mf < 0 and time_cond and timetobuy and enableentry and noemafilter and usecmffilter and usesupertrend and nocontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
if buySignal and mf > 0 and time_cond and timetobuy and waitentry and noemafilter and usecmffilter and usesupertrend and nocontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if sellSignal and mf < 0 and time_cond and timetobuy and waitentry and noemafilter and usecmffilter and usesupertrend and nocontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
// Use CMF but No EMA Entry no supertrend
if mf > 0 and time_cond and timetobuy and enableentry and noemafilter and usecmffilter and nosupertrend and nocontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if mf < 0 and time_cond and timetobuy and enableentry and noemafilter and usecmffilter and nosupertrend and nocontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
if mf > 0 and time_cond and timetobuy and waitentry and noemafilter and usecmffilter and nosupertrend and nocontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if mf < 0 and time_cond and timetobuy and waitentry and noemafilter and usecmffilter and nosupertrend and nocontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
// Contrarian - Use CMF but No EMA Entry with supertrend
if Long and mf > 0 and time_cond and timetobuy and enableentry and noemafilter and usecmffilter and usesupertrend and usecontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
if Short and mf < 0 and time_cond and timetobuy and enableentry and noemafilter and usecmffilter and usesupertrend and usecontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if buySignal and mf > 0 and time_cond and timetobuy and waitentry and noemafilter and usecmffilter and usesupertrend and usecontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
if sellSignal and mf < 0 and time_cond and timetobuy and waitentry and noemafilter and usecmffilter and usesupertrend and usecontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
// Contrarian - Use CMF but No EMA Entry no supertrend
if mf > 0 and time_cond and timetobuy and enableentry and noemafilter and usecmffilter and nosupertrend and usecontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
if mf < 0 and time_cond and timetobuy and enableentry and noemafilter and usecmffilter and nosupertrend and usecontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if mf > 0 and time_cond and timetobuy and waitentry and noemafilter and usecmffilter and nosupertrend and usecontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
if mf < 0 and time_cond and timetobuy and waitentry and noemafilter and usecmffilter and nosupertrend and usecontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
//------------------------------------------------------------------------------
// Use EMA and CMF Entry with supertrend
if Long and emapricesrc > ema and mf > 0 and time_cond and timetobuy and enableentry and useemafilter and usecmffilter and usesupertrend and nocontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if Short and emapricesrc < ema and mf < 0 and time_cond and timetobuy and enableentry and useemafilter and usecmffilter and usesupertrend and nocontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
if buySignal and emapricesrc > ema and mf > 0 and time_cond and timetobuy and waitentry and useemafilter and usecmffilter and usesupertrend and nocontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if sellSignal and emapricesrc < ema and mf < 0 and time_cond and timetobuy and waitentry and useemafilter and usecmffilter and usesupertrend and nocontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
// Use EMA and CMF Entry no supertrend
if emapricesrc > ema and mf > 0 and time_cond and timetobuy and enableentry and useemafilter and usecmffilter and nosupertrend and nocontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if emapricesrc < ema and mf < 0 and time_cond and timetobuy and enableentry and useemafilter and usecmffilter and nosupertrend and nocontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
if emapricesrc > ema and mf > 0 and time_cond and timetobuy and waitentry and useemafilter and usecmffilter and nosupertrend and nocontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if emapricesrc < ema and mf < 0 and time_cond and timetobuy and waitentry and useemafilter and usecmffilter and nosupertrend and nocontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
// Contrarian - Use EMA and CMF Entry with supertrend
if Long and emapricesrc > ema and mf > 0 and time_cond and timetobuy and enableentry and useemafilter and usecmffilter and usesupertrend and usecontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
if Short and emapricesrc < ema and mf < 0 and time_cond and timetobuy and enableentry and useemafilter and usecmffilter and usesupertrend and usecontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if buySignal and emapricesrc > ema and mf > 0 and time_cond and timetobuy and waitentry and useemafilter and usecmffilter and usesupertrend and usecontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
if sellSignal and emapricesrc < ema and mf < 0 and time_cond and timetobuy and waitentry and useemafilter and usecmffilter and usesupertrend and usecontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
// Contrarian - Use EMA and CMF Entry no supertrend
if emapricesrc > ema and mf > 0 and time_cond and timetobuy and enableentry and useemafilter and usecmffilter and nosupertrend and usecontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
if emapricesrc < ema and mf < 0 and time_cond and timetobuy and enableentry and useemafilter and usecmffilter and nosupertrend and usecontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if emapricesrc > ema and mf > 0 and time_cond and timetobuy and waitentry and useemafilter and usecmffilter and nosupertrend and usecontrarian
strategy.entry("Short", strategy.short, alert_message = message_entershort)
if emapricesrc < ema and mf < 0 and time_cond and timetobuy and waitentry and useemafilter and usecmffilter and nosupertrend and usecontrarian
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
//------------------------------------------------------------------------------
// Hours exits
if strategy.position_size > 0 and timetoclose and enableclose
strategy.close_all(alert_message = message_closelong)
if strategy.position_size < 0 and timetoclose and enableclose
strategy.close_all(alert_message = message_closeshort)
//------------------------------------------------------------------------------
// % TP and SL exits
if strategy.position_size > 0 and enablesltp and time_cond and nocontrarian
strategy.exit(id="Close Long", stop=longStop, limit=longTake, alert_message = message_closelong)
if strategy.position_size < 0 and enablesltp and time_cond and nocontrarian
strategy.exit(id="Close Short", stop=shortStop, limit=shortTake, alert_message = message_closeshort)
// Contrarian - % TP and SL exits
if strategy.position_size > 0 and enablesltp and time_cond and usecontrarian
strategy.exit(id="Close Long", stop=longStop, limit=longTake, alert_message = message_closelong)
if strategy.position_size < 0 and enablesltp and time_cond and usecontrarian
strategy.exit(id="Close Short", stop=shortStop, limit=shortTake, alert_message = message_closeshort)
|
200DMA last DOM - ajh | https://www.tradingview.com/script/APoeqsEr-200DMA-last-DOM-ajh/ | muscleriot | https://www.tradingview.com/u/muscleriot/ | 38 | 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/
// © muscleriot
//200 dma
//1 signal per month - trade only at 'end of month' to cut whipsawing in and out. 'End of Month' is whatever trading day is
// nearest to the default day 28 of month in pinescript - there is no easy method to obtain trading end of month date.
// Day 28 is default so not to miss Feburary.
//If > 200DMA enter long
//If < 200DMA goto cash
// Important Steve Burns used SPY TOTAL RETURN INDEX used not just SPY Price. Please use the ADJ at bottom of chart in Trading View.
// 3 Jan 2000 to 28 Jun 2021 - https://www.newtraderu.com/2021/06/30/200-day-moving-average-vs-buy-and-hold/
//Steve Burns Results : 585.8% return on SPY vs 365% buy and hold with 12 trades
// My Results : 415% return (on SPY with ADJ) vs BUY and HOLD of 318.9% in 12 trades so not perfect
//@version=5
strategy("200DMA last DOM - ajh", overlay =true,default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital = 10000)
// Use 100% of equity always
ma_days = input.int(defval=200, title="SMA (Chart Period)", minval=1, maxval=600)
trade_dom = input.int(defval=28, title="trade day of month or 0 for none", minval=0, maxval=31)
//e =dayofmonth(time)
// backtesting date range
from_day = input.int(defval=3, title="From Day", minval=1, maxval=31)
from_month = input.int(defval=1, title="From Month", minval=1, maxval=12)
from_year = input.int(defval=2000, title="From Year", minval=1900)
to_day = input.int(defval=28, title="To Day", minval=1, maxval=31)
to_month = input.int(defval=6, title="To Month", minval=1, maxval=12)
to_year = input.int(defval=2021, title="To Year", minval=1900)
dateStart = timestamp(syminfo.timezone, from_year, from_month, from_day, 0, 0) // 2000-01-03
dateEnd = timestamp(syminfo.timezone, to_year, to_month, to_day, 0, 0) //2021-06-28
inDateRange = time >= dateStart and time <= dateEnd
// 200 day ma
dma200 = ta.sma(close, ma_days)
plot(dma200, color=color.red, linewidth = 2)
//Day of month
dom = dayofmonth(time_tradingday, syminfo.timezone)
// Set trade entry conditions -
enterLong = close > dma200
enterSale = close < dma200
TradeTime = (trade_dom == 0) ? true: (dom == trade_dom)? true: false //Is it the time (eom) to decide to go long or short?
//bgcolor((TradeTime) ? color.gray:na)
xLong = TradeTime and enterLong
xSell = TradeTime and enterSale
plotchar(xLong, "long","L", color=color.green, location=location.abovebar, size=size.tiny)
plotchar(xSell, "Sell","S", color=color.red, location = location.abovebar, size = size.tiny)
if TradeTime and inDateRange and enterLong
strategy.entry("long", strategy.long)
if TradeTime and inDateRange and enterSale
strategy.close("long")
// Exit open market position when date range ends
if (not inDateRange)
strategy.close_all() |
PickingupFromBottom Strategy | https://www.tradingview.com/script/YKGx8Yp4-PickingupFromBottom-Strategy/ | mohanee | https://www.tradingview.com/u/mohanee/ | 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/
// © mohanee
//Using the lowest of low of ema200, you can find the bottom
//wait for price to close below ema200Lows line
//when pivot
//@version=4
strategy(title="PickingupFromBottom Strategy", overlay=true, pyramiding=2, default_qty_type=strategy.percent_of_equity, default_qty_value=30, initial_capital=10000, currency=currency.USD) //default_qty_value=10, default_qty_type=strategy.fixed,
//HMA
HMA(src1, length1) => wma(2 * wma(src1, length1/2) - wma(src1, length1), round(sqrt(length1)))
//variables BEGIN
length1=input(200,title="EMA 1 Length")
length2=input(50,title="EMA 2 Length")
length3=input(20,title="EMA 3 Length")
sourceForHighs= input(hlc3, title="Source for Highs", type=input.source)
sourceForLows = input(hlc3, title="Source for Lows" , type=input.source)
hiLoLength=input(7, title="HiLo Band Length")
atrLength=input(14, title="ATR Length")
atrMultiplier=input(3.5, title="ATR Multiplier")
//takePartialProfits = input(true, title="Take Partial Profits (if this selected, RSI 13 higher reading over 80 is considered for partial closing ) ")
ema200=ema(close,length1)
hma200=HMA(close,length1)
////Camarilla pivot points
//study(title="Camarilla Pivots", shorttitle="Camarilla", overlay=true)
t = input(title = "Pivot Resolution", defval="D", options=["D","W","M"])
//Get previous day/week bar and avoiding realtime calculation by taking the previous to current bar
sopen = security(syminfo.tickerid, t, open[1], barmerge.gaps_off, barmerge.lookahead_on)
shigh = security(syminfo.tickerid, t, high[1], barmerge.gaps_off, barmerge.lookahead_on)
slow = security(syminfo.tickerid, t, low[1], barmerge.gaps_off, barmerge.lookahead_on)
sclose = security(syminfo.tickerid, t, close[1], barmerge.gaps_off, barmerge.lookahead_on)
r = shigh-slow
//Calculate pivots
//center=(sclose)
//center=(close[1] + high[1] + low[1])/3
center=sclose - r*(0.618)
h1=sclose + r*(1.1/12)
h2=sclose + r*(1.1/6)
h3=sclose + r*(1.1/4)
h4=sclose + r*(1.1/2)
h5=(shigh/slow)*sclose
l1=sclose - r*(1.1/12)
l2=sclose - r*(1.1/6)
l3=sclose - r*(1.1/4)
l4=sclose - r*(1.1/2)
l5=sclose - (h5-sclose)
//Colors (<ternary conditional operator> expression prevents continuous lines on history)
c5=sopen != sopen[1] ? na : color.red
c4=sopen != sopen[1] ? na : color.purple
c3=sopen != sopen[1] ? na : color.fuchsia
c2=sopen != sopen[1] ? na : color.blue
c1=sopen != sopen[1] ? na : color.gray
cc=sopen != sopen[1] ? na : color.blue
//Plotting
//plot(center, title="Central",color=color.blue, linewidth=2)
//plot(h5, title="H5",color=c5, linewidth=1)
//plot(h4, title="H4",color=c4, linewidth=2)
//plot(h3, title="H3",color=c3, linewidth=1)
//plot(h2, title="H2",color=c2, linewidth=1)
//plot(h1, title="H1",color=c1, linewidth=1)
//plot(l1, title="L1",color=c1, linewidth=1)
//plot(l2, title="L2",color=c2, linewidth=1)
//plot(l3, title="L3",color=c3, linewidth=1)
//plot(l4, title="L4",color=c4, linewidth=2)
//plot(l5, title="L5",color=c5, linewidth=1)////Camarilla pivot points
ema_s3_9=ema(l3, 9)
ema_s3_50=ema(l3, 50)
ema_h4_9=ema(h4, 9)
ema_center_9=ema(center, 9)
plot(ema_h4_9, title="Camariall R4 Resistance EMA 9", color=color.fuchsia)
plot(ema_s3_9, title="Camarilla S3 support EMA 9", color=color.gray, linewidth=1)
//plot(ema_s3_50, title="Camarilla S3 support EMA 50", color=color.green, linewidth=2)
plot(ema_center_9, title="Camarilla Center Point EMA 9", color=color.blue)
plot(hma200, title="HULL 200", color=color.yellow, transp=25)
plotEma200=plot(ema200, title="EMA 200", style=plot.style_linebr, linewidth=2 , color=color.orange)
ema200High = ema(highest(sourceForHighs,length1), hiLoLength)
ema200Low= ema(lowest(sourceForLows,length1), hiLoLength)
ema50High = ema(highest(sourceForHighs,length2), hiLoLength)
ema50Low= ema(lowest(sourceForLows,length2), hiLoLength)
ema20High = ema(highest(sourceForHighs,length3), hiLoLength)
ema20Low= ema(lowest(sourceForLows,length3), hiLoLength)
//plot(ema200High, title="EMA 200 Highs", linewidth=2, color=color.orange, transp=30)
plotEma200Low=plot(ema200Low, title="EMA 200 Lows", linewidth=2, color=color.green, transp=30, style=plot.style_linebr)
//plot(ema50High, title="EMA 50 Highs", linewidth=2, color=color.blue, transp=30)
//plotEma50Low=plot(ema50Low, title="EMA 50 Lows", linewidth=2, color=color.blue, transp=30)
fill(plotEma200, plotEma200Low, color=color.green )
// Drawings /////////////////////////////////////////
//Highlight when centerpont crossing up ema200Low a
ema200LowBuyColor=color.new(color.green, transp=50)
bgcolor(crossover(ema_center_9,ema200Low) and (close[1]<ema200Low or close[2]<ema200Low or close[3]<ema200Low)? ema200LowBuyColor : na)
//ema200LowBuyCondition= (close[1]<ema200Low or close[2]<ema200Low or close[3]<ema200Low)
strategy.entry(id="ema200Low Buy", comment="LE2", qty=2, long=true, when= crossover(ema_center_9,ema200Low) and (close[1]<ema200Low or close[2]<ema200Low or close[3]<ema200Low) ) //or (close>open and low<ema20Low and close>ema20Low) ) ) // // aroonOsc<0
//Trailing StopLoss
////// Calculate trailing SL
/////////////////////////////////////////////////////
sl_val = atrMultiplier * atr(atrLength)
trailing_sl = 0.0
//trailing_sl := max(low[1] - sl_val, nz(trailing_sl[1]))
trailing_sl := strategy.position_size>=1 ? max(low - sl_val, nz(trailing_sl[1])) : na
//draw initil stop loss
//plot(strategy.position_size>=1 ? trailing_sl : na, color = color.blue , style=plot.style_linebr, linewidth = 2, title = "stop loss")
plot(trailing_sl, title="ATR Trailing Stop Loss", style=plot.style_linebr, linewidth=1, color=color.red, transp=30)
//Trailing StopLoss
////// Calculate trailing SL
/////////////////////////////////////////////////////
strategy.close(id="ema200Low Buy", comment="TP1="+tostring(close - strategy.position_avg_price, "####.##"), qty=1, when=abs(strategy.position_size)>=1 and crossunder(close, ema_h4_9) ) //close<ema55 and rsi5Val<20 //ema34<ema55 //close<ema89
strategy.close(id="ema200Low Buy", comment="TP2="+tostring(close - strategy.position_avg_price, "####.##"), qty=1, when=abs(strategy.position_size)>=1 and crossunder(close, ema_s3_9) ) //close<ema55 and rsi5Val<20 //ema34<ema55 //close<ema89
|
3RSI 3CCI BB 5orders DCA strategy+ | https://www.tradingview.com/script/Jicyr9hK-3rsi-3cci-bb-5orders-dca-strategy/ | rrolik66 | https://www.tradingview.com/u/rrolik66/ | 121 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © rrolik66
//@version=5
strategy(title="3RSI 3CCI BB 5orders DCA strategy+", overlay=true, default_qty_type=strategy.cash, initial_capital=0.1, commission_type=strategy.commission.percent, commission_value=0.075)
start_time = input.time(defval=timestamp('01 January 2021 00:00'), title='Start Time')
end_time = input.time(defval=timestamp('01 January 2022 00:00'), title='End Time')
src_bot = input.source(close, 'Source Bot')
tradeDirection = input.string(title='Trade Direction', options=['Long Bot', 'Short Bot'], defval='Long Bot')
weight_order0 = input.float(13.03, title='1 order (%)', group='weight of orders in %', inline='Input 0') * 0.01
weight_order1 = input.float(14.29, title='2 order (%)', group='weight of orders in %', inline='Input 0') * 0.01
weight_order2 = input.float(17.19, title='3 order (%)', group='weight of orders in %', inline='Input 1') * 0.01
weight_order3 = input.float(22.67, title='4 order (%)', group='weight of orders in %', inline='Input 1') * 0.01
weight_order4 = input.float(32.80, title='5 order (%)', group='weight of orders in %', inline='Input 2') * 0.01
st_long_orders = input.float(title='Rate cover (%)', minval=1, defval=80, group='Long Bot', inline='Input 1') / 4 * 0.01
longTakeProfit = input.float(1.4, step=0.05, title='Take Profit (%)', group='Long Bot', inline='Input 1') * 0.01
entry_long_SL = input.bool(defval=false, title='StopLoss', group='Long Bot', inline='Input 2')
longStopLoss = input.float(80, step=0.1, title='for Long Bot (%)', group='Long Bot', inline='Input 2') * 0.01
st_short_orders = input.float(title='Rate cover (%)', minval=1, defval=500, group='Short Bot', inline='Input 1') / 4 * 0.01
shortTakeProfit = input.float(1.4, step=0.05, title='Take Profit (%)', group='Short Bot', inline='Input 1') * 0.01
entry_short_SL = input.bool(defval=false, title='StopLoss', group='Short Bot', inline='Input 2')
shortStopLoss = input.float(500, step=0.1, title='for Short Bot (%)', group='Short Bot', inline='Input 2') * 0.01
//inputs for indicators
src = input.source(close, 'Source', group='indicators')
rsi1_input = input.bool(defval=true, title='RSI-1', group='RSI-1', inline='Input 0')
rsi1_res = input.timeframe(title='resolution', defval='5', group='RSI-1', inline='Input 0')
rsi1_low = input.int(65, minval=0, maxval=100, title='long <', group='RSI-1', inline='Input 1')
rsi1_len_long = input.int(14, minval=1, title='Length', group='RSI-1', inline='Input 1')
rsi1_up = input.int(37, minval=0, maxval=100, title='short >', group='RSI-1', inline='Input 2')
rsi1_len_short = input.int(14, minval=1, title='Length', group='RSI-1', inline='Input 2')
rsi2_input = input.bool(defval=true, title='RSI-2', group='RSI-2', inline='Input 0')
rsi2_res = input.timeframe(title='resolution', defval='15', group='RSI-2', inline='Input 0')
rsi2_low = input.int(72, minval=0, maxval=100, title='long <', group='RSI-2', inline='Input 1')
rsi2_len_long = input.int(14, minval=1, title='Length', group='RSI-2', inline='Input 1')
rsi2_up = input.int(37, minval=0, maxval=100, title='short >', group='RSI-2', inline='Input 2')
rsi2_len_short = input.int(14, minval=1, title='Length', group='RSI-2', inline='Input 2')
rsi3_input = input.bool(defval=true, title='RSI-3', group='RSI-3', inline='Input 0')
rsi3_res = input.timeframe(title='resolution', defval='30', group='RSI-3', inline='Input 0')
rsi3_low = input.int(74, minval=0, maxval=100, title='long <', group='RSI-3', inline='Input 1')
rsi3_len_long = input.int(14, minval=1, title='Length', group='RSI-3', inline='Input 1')
rsi3_up = input.int(34, minval=0, maxval=100, title='short >', group='RSI-3', inline='Input 2')
rsi3_len_short = input.int(14, minval=1, title='Length', group='RSI-3', inline='Input 2')
cci1_input = input.bool(defval=true, title='CCI-1', group='CCI-1', inline='Input 0')
cci1_res = input.timeframe(title='resolution', defval='5', group='CCI-1', inline='Input 0')
cci1_low = input.int(190, step=5, title='long <', group='CCI-1', inline='Input 1')
cci1_len_long = input.int(20, minval=1, title='Length', group='CCI-1', inline='Input 1')
cci1_up = input.int(-175, step=5, title='short >', group='CCI-1', inline='Input 2')
cci1_len_short = input.int(20, minval=1, title='Length', group='CCI-1', inline='Input 2')
cci2_input = input.bool(defval=true, title='CCI-2', group='CCI-2', inline='Input 0')
cci2_res = input.timeframe(title='resolution', defval='15', group='CCI-2', inline='Input 0')
cci2_low = input.int(195, step=5, title='long <', group='CCI-2', inline='Input 1')
cci2_len_long = input.int(20, minval=1, title='Length', group='CCI-2', inline='Input 1')
cci2_up = input.int(-205, step=5, title='short >', group='CCI-2', inline='Input 2')
cci2_len_short = input.int(20, minval=1, title='Length', group='CCI-2', inline='Input 2')
cci3_input = input.bool(defval=true, title='CCI-3', group='CCI-3', inline='Input 0')
cci3_res = input.timeframe(title='resolution', defval='30', group='CCI-3', inline='Input 0')
cci3_low = input.int(200, step=5, title='long <', group='CCI-3', inline='Input 1')
cci3_len_long = input.int(20, minval=1, title='Length', group='CCI-3', inline='Input 1')
cci3_up = input.int(-220, step=5, title='short >', group='CCI-3', inline='Input 2')
cci3_len_short = input.int(20, minval=1, title='Length', group='CCI-3', inline='Input 2')
bb_input = input.bool(defval=false, title='BB', group='Bollinger Bands', tooltip='(for long trading) the price is below the lower band, (for short trading) the price is abowe the upper band, для лонга цена под нижней линией, для шорта цена над верхней линией', inline='Input 0')
bb_res = input.timeframe(title='resolution', defval='5', group='Bollinger Bands', inline='Input 0')
bb_dev = input.float(2.0, minval=0.1, maxval=50, step=0.1, title='Deviation', group='Bollinger Bands', inline='Input 2')
bb_len = input.int(20, minval=1, title='Length', group='Bollinger Bands', inline='Input 2')
cci_input = input.bool(defval=false, title='band CCI', group='band CCI', tooltip='this setting sets the trading range by the level of the "CCI" indicator, эта настройка задает диапазон торговли по уровню индикатора "CCI" (я не использую)', inline='Input 0')
cci_res = input.timeframe(title='resolution', defval='60', group='band CCI', inline='Input 0')
cci_len = input.int(20, minval=1, title='CCI Length', group='band CCI', inline='Input 1')
cci_low = input.int(-110, step=10, title='CCI >', group='band CCI', inline='Input 2')
cci_up = input.int(110, step=10, title='CCI <', group='band CCI', inline='Input 2')
show_signals = input.bool(defval=false, title='Show signals', inline='Input')
//Input to trading conditions
longOK = tradeDirection == 'Long Bot'
shortOK = tradeDirection == 'Short Bot'
within_window() =>
time >= start_time and time <= end_time
// get indicators
rsi1_sec_long = request.security(syminfo.tickerid, rsi1_res, ta.rsi(src, rsi1_len_long))
rsi1_sec_short = request.security(syminfo.tickerid, rsi1_res, ta.rsi(src, rsi1_len_short))
rsi2_sec_long = request.security(syminfo.tickerid, rsi2_res, ta.rsi(src, rsi2_len_long))
rsi2_sec_short = request.security(syminfo.tickerid, rsi2_res, ta.rsi(src, rsi2_len_short))
rsi3_sec_long = request.security(syminfo.tickerid, rsi3_res, ta.rsi(src, rsi3_len_long))
rsi3_sec_short = request.security(syminfo.tickerid, rsi3_res, ta.rsi(src, rsi3_len_short))
cci1_sec_long = request.security(syminfo.tickerid, cci1_res, ta.cci(src, cci1_len_long))
cci1_sec_short = request.security(syminfo.tickerid, cci1_res, ta.cci(src, cci1_len_short))
cci2_sec_long = request.security(syminfo.tickerid, cci2_res, ta.cci(src, cci2_len_long))
cci2_sec_short = request.security(syminfo.tickerid, cci2_res, ta.cci(src, cci2_len_short))
cci3_sec_long = request.security(syminfo.tickerid, cci3_res, ta.cci(src, cci3_len_long))
cci3_sec_short = request.security(syminfo.tickerid, cci3_res, ta.cci(src, cci3_len_short))
[basis, upper_bb, lower_bb] = request.security(syminfo.tickerid, bb_res, ta.bb(src, bb_len, bb_dev))
cci_sec = request.security(syminfo.tickerid, cci_res, ta.cci(src, cci_len))
// calculate indicators
float rating_long = 0
float rating_long_num = 0
float rating_short = 0
float rating_short_num = 0
float rsi1_long = na
float rsi1_short = na
if not na(rsi1_sec_long) and rsi1_input and longOK
rsi1_long := rsi1_sec_long < rsi1_low ? 1 : 0
if not na(rsi1_sec_short) and rsi1_input and shortOK
rsi1_short := rsi1_sec_short > rsi1_up ? 1 : 0
if not na(rsi1_long)
rating_long += rsi1_long
rating_long_num += 1
if not na(rsi1_short)
rating_short += rsi1_short
rating_short_num += 1
float rsi2_long = na
float rsi2_short = na
if not na(rsi2_sec_long) and rsi2_input and longOK
rsi2_long := rsi2_sec_long < rsi2_low ? 1 : 0
if not na(rsi2_sec_short) and rsi2_input and shortOK
rsi2_short := rsi2_sec_short > rsi2_up ? 1 : 0
if not na(rsi2_long)
rating_long += rsi2_long
rating_long_num += 1
if not na(rsi2_short)
rating_short += rsi2_short
rating_short_num += 1
float rsi3_long = na
float rsi3_short = na
if not na(rsi3_sec_long) and rsi3_input and longOK
rsi3_long := rsi3_sec_long < rsi3_low ? 1 : 0
if not na(rsi3_sec_short) and rsi3_input and shortOK
rsi3_short := rsi3_sec_short > rsi3_up ? 1 : 0
if not na(rsi3_long)
rating_long += rsi3_long
rating_long_num += 1
if not na(rsi3_short)
rating_short += rsi3_short
rating_short_num += 1
float cci1_long = na
float cci1_short = na
if not na(cci1_sec_long) and cci1_input and longOK
cci1_long := cci1_sec_long < cci1_low ? 1 : 0
if not na(cci1_sec_short) and cci1_input and shortOK
cci1_short := cci1_sec_short > cci1_up ? 1 : 0
if not na(cci1_long)
rating_long += cci1_long
rating_long_num += 1
if not na(cci1_short)
rating_short += cci1_short
rating_short_num += 1
float cci2_long = na
float cci2_short = na
if not na(cci2_sec_long) and cci2_input and longOK
cci2_long := cci2_sec_long < cci2_low ? 1 : 0
if not na(cci2_sec_short) and cci2_input and shortOK
cci2_short := cci2_sec_short > cci2_up ? 1 : 0
if not na(cci2_long)
rating_long += cci2_long
rating_long_num += 1
if not na(cci2_short)
rating_short += cci2_short
rating_short_num += 1
float cci3_long = na
float cci3_short = na
if not na(cci3_sec_long) and cci3_input and longOK
cci3_long := cci3_sec_long < cci3_low ? 1 : 0
if not na(cci3_sec_short) and cci3_input and shortOK
cci3_short := cci3_sec_short > cci3_up ? 1 : 0
if not na(cci3_long)
rating_long += cci3_long
rating_long_num += 1
if not na(cci3_short)
rating_short += cci3_short
rating_short_num += 1
float bb_long = na
float bb_short = na
if not(na(lower_bb) or na(src) or na(src[1])) and bb_input and longOK
bb_long := src < lower_bb ? 1 : 0
if not(na(upper_bb) or na(src) or na(src[1])) and bb_input and shortOK
bb_short := src > upper_bb ? 1 : 0
if not na(bb_long)
rating_long += bb_long
rating_long_num += 1
if not na(bb_short)
rating_short += bb_short
rating_short_num += 1
float cci_band = na
if not na(cci_sec) and cci_input
cci_band := cci_sec < cci_up and cci_sec > cci_low ? 1 : 0
if not na(cci_band)
rating_long += cci_band
rating_long_num += 1
rating_short += cci_band
rating_short_num += 1
//Buy Sell
Buy_ok = rating_long_num != 0 and longOK ? rating_long == rating_long_num : true
Sell_ok = rating_short_num != 0 and shortOK ? rating_short == rating_short_num : true
// Plotting
plotshape(Buy_ok and show_signals and longOK, title='Buy', text='Long', textcolor=color.new(color.white, 0), style=shape.labelup, location=location.belowbar, color=color.new(color.green, 0), size=size.tiny)
plotshape(Sell_ok and show_signals and shortOK, title='Sell', text='Short', textcolor=color.new(color.white, 0), style=shape.labeldown, location=location.abovebar, color=color.new(color.red, 0), size=size.tiny)
//Figure in entry orders price
longEntryPrice0 = src_bot
longEntryPrice1 = longEntryPrice0 * (1 - st_long_orders)
longEntryPrice2 = longEntryPrice0 * (1 - st_long_orders * 2)
longEntryPrice3 = longEntryPrice0 * (1 - st_long_orders * 3)
longEntryPrice4 = longEntryPrice0 * (1 - st_long_orders * 4)
longEntryqty0 = strategy.initial_capital * weight_order0 / longEntryPrice0
longEntryqty1 = strategy.initial_capital * weight_order1 / longEntryPrice1
longEntryqty2 = strategy.initial_capital * weight_order2 / longEntryPrice2
longEntryqty3 = strategy.initial_capital * weight_order3 / longEntryPrice3
longEntryqty4 = strategy.initial_capital * weight_order4 / longEntryPrice4
shortEntryPrice0 = src_bot
shortEntryPrice1 = shortEntryPrice0 * (1 + st_short_orders)
shortEntryPrice2 = shortEntryPrice0 * (1 + st_short_orders * 2)
shortEntryPrice3 = shortEntryPrice0 * (1 + st_short_orders * 3)
shortEntryPrice4 = shortEntryPrice0 * (1 + st_short_orders * 4)
shortcontracts = strategy.initial_capital / shortEntryPrice0
shortEntryqty0 = shortcontracts * weight_order0
shortEntryqty1 = shortcontracts * weight_order1
shortEntryqty2 = shortcontracts * weight_order2
shortEntryqty3 = shortcontracts * weight_order3
shortEntryqty4 = shortcontracts * weight_order4
long_entry_price = strategy.opentrades.entry_price (0)
short_entry_price = strategy.opentrades.entry_price (0)
longTP = strategy.position_avg_price * (1 + longTakeProfit)
longSL = long_entry_price * (1 - longStopLoss)
shortTP = strategy.position_avg_price * (1 - shortTakeProfit)
shortSL = short_entry_price * (1 + shortStopLoss)
plot(series=strategy.position_size > 0 and longOK ? longTP : na, color=color.new(color.red, 0), style=plot.style_circles, linewidth=3, title='Long Take Profit')
plot(series=strategy.position_size > 0 and entry_long_SL and longOK ? longSL : na, color=color.new(color.black, 0), style=plot.style_circles, linewidth=1, title='Long Stop Loss')
plot(series=strategy.position_size < 0 and shortOK ? shortTP : na, color=color.new(color.green, 0), style=plot.style_circles, linewidth=3, title='Long Take Profit')
plot(series=strategy.position_size < 0 and entry_short_SL and shortOK ? shortSL : na, color=color.new(color.black, 0), style=plot.style_circles, linewidth=1, title='Long Stop Loss')
// Submit entry orders
if strategy.opentrades == 0 and longOK and within_window()
strategy.order(id='Long0', direction=strategy.long, qty=longEntryqty0, limit=longEntryPrice0, when=Buy_ok)
strategy.order(id='Long1', direction=strategy.long, qty=longEntryqty1, limit=longEntryPrice1, when=Buy_ok)
strategy.order(id='Long2', direction=strategy.long, qty=longEntryqty2, limit=longEntryPrice2, when=Buy_ok)
strategy.order(id='Long3', direction=strategy.long, qty=longEntryqty3, limit=longEntryPrice3, when=Buy_ok)
strategy.order(id='Long4', direction=strategy.long, qty=longEntryqty4, limit=longEntryPrice4, when=Buy_ok)
if strategy.opentrades == 0 and shortOK and within_window()
strategy.order(id='Short0', direction=strategy.short, qty=shortEntryqty0, limit=shortEntryPrice0, when=Sell_ok)
strategy.order(id='Short1', direction=strategy.short, qty=shortEntryqty1, limit=shortEntryPrice1, when=Sell_ok)
strategy.order(id='Short2', direction=strategy.short, qty=shortEntryqty2, limit=shortEntryPrice2, when=Sell_ok)
strategy.order(id='Short3', direction=strategy.short, qty=shortEntryqty3, limit=shortEntryPrice3, when=Sell_ok)
strategy.order(id='Short4', direction=strategy.short, qty=shortEntryqty4, limit=shortEntryPrice4, when=Sell_ok)
// exit position
if (strategy.position_size > 0) and not entry_long_SL and longOK
strategy.exit(id='exit_Long', limit=longTP, qty=strategy.position_size, when=strategy.position_size[1] > 0)
if (strategy.position_size > 0) and entry_long_SL and longOK
strategy.exit(id='exit_Long', limit=longTP, stop=longSL, qty=strategy.position_size, when=strategy.position_size[1] > 0)
if (strategy.position_size < 0) and not entry_short_SL and shortOK
strategy.exit(id='exit_Short', limit=shortTP, qty=math.abs(strategy.position_size), when=strategy.position_size[1] < 0)
if (strategy.position_size < 0) and entry_short_SL and shortOK
strategy.exit(id='exit_Short', limit=shortTP, stop=shortSL, qty=math.abs(strategy.position_size), when=strategy.position_size[1] < 0)
// Cleanup
if ta.crossunder(strategy.opentrades, 0.5)
strategy.close_all()
strategy.cancel_all()
|
Super Auto Breakout Day Trade Volatile stocks | https://www.tradingview.com/script/6Kubkdf3-Super-Auto-Breakout-Day-Trade-Volatile-stocks/ | beststockalert | https://www.tradingview.com/u/beststockalert/ | 404 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © beststockalert
//@version=4
strategy(title="Auto Breakout", shorttitle = "Autotrade BB-BO",default_qty_type = strategy.percent_of_equity,default_qty_value = 100, overlay=true)
source = close
length = input(130, title="VFI length")
coef = input(0.2)
vcoef = input(2.5, title="Max. vol. cutoff")
signalLength=input(5)
// session
pre = input( type=input.session, defval="0400-0930")
trade_session = input( type=input.session, defval="0940-1700")
use_trade_session = true
isinsession = use_trade_session ? not na(time('1', trade_session)) : true
is_newbar(sess) =>
t = time("D", sess)
not na(t) and (na(t[1]) or t > t[1])
is_session(sess) =>
not na(time(timeframe.period, sess))
preNew = is_newbar(pre)
preSession = is_session(pre)
float preLow = na
preLow := preSession ? preNew ? low : min(preLow[1], low) : preLow[1]
float preHigh = na
preHigh := preSession ? preNew ? high : max(preHigh[1], high) : preHigh[1]
// vfi 9lazybear
ma(x,y) => 0 ? sma(x,y) : x
typical=hlc3
inter = log( typical ) - log( typical[1] )
vinter = stdev(inter, 30 )
cutoff = coef * vinter * close
vave = sma( volume, length )[1]
vmax = vave * vcoef
vc = iff(volume < vmax, volume, vmax) //min( volume, vmax )
mf = typical - typical[1]
vcp = iff( mf > cutoff, vc, iff ( mf < -cutoff, -vc, 0 ) )
vfi = ma(sum( vcp , length )/vave, 3)
vfima=ema( vfi, signalLength )
//ema diff
ema20 = ema(close,20)
ema50 = ema(close,50)
diff = (ema20-ema50)*100/ema20
ediff = ema(diff,20)
//
basis = sma(source, 20)
dev = 1.5 * stdev(source, 20)
upper = basis *1.014
lower = basis *.985
if close >19.9
upper = basis + 0.65
lower = basis - 0.5
sma20 = sma(source, 20)
/// bar color
barColour = (open>=upper) ? color.green : (close>=upper) ? color.green : (close>basis) ? color.green : (open<lower) ? color.purple : color.blue
sell = close < lower or close> strategy.position_avg_price*1.1 or close <strategy.position_avg_price-0.4 or vfi<-3 or vfima<-3 or close<open*.94
barcolor(color=barColour)
///
if (isinsession and ( close[3]>upper and close>sma20 and vfi[3]>0 and vfi>0 and vfi>vfi[5] and barssince(sell)>5 ) or close>open*1.04)
strategy.entry("Long", strategy.long)
if (sell )
strategy.close("Long")
plot(basis, color=color.red,title= "SMA")
p1 = plot(upper, color=color.blue,title= "UB")
p2 = plot(lower, color=color.blue,title= "LB")
|
Trend Following with Donchian Channels and MACD | https://www.tradingview.com/script/bGjB7COd-Trend-Following-with-Donchian-Channels-and-MACD/ | Robrecht99 | https://www.tradingview.com/u/Robrecht99/ | 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/
// © Robrecht99
//@version=5
strategy("Trend Following with Donchian Channels and MACD", overlay=true, margin_long=0, margin_short=0, pyramiding=1)
// Donchian Channels //
Length1 = input.int(title="Length Upper Channel", defval=50, minval=1, group="Donchian Channels Inputs")
Length2 = input.int(title="Length Lower Channel", defval=50, minval=1, group="Donchian Channels Inputs")
h1 = ta.highest(high[1], Length1)
l1 = ta.lowest(low[1], Length2)
fillColor = input.color(color.new(color.purple, 95), title = "Fill Color", group = "Donchian Channels Inputs")
upperColor = input.color(color.new(color.orange, 0), title = " Color Upper Channel", group = "Donchian Channels Inputs", inline = "upper")
lowerColor = input.color(color.new(color.orange, 0), title = " Color Lower Channel", group = "Donchian Channels Inputs", inline = "lower")
u = plot(h1, "Upper", color=upperColor)
l = plot(l1, "Lower", color=upperColor)
fill(u, l, color=fillColor)
// MACD //
fast_length = input(title="Fast Length", defval=12)
slow_length = input(title="Slow Length", defval=26)
src = input(title="Source", defval=close)
signal_length = input.int(title="Signal Smoothing", minval = 1, maxval = 50, defval = 9)
sma_source = input.string(title="Oscillator MA Type", defval="EMA", options=["SMA", "EMA"])
sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"])
fast_ma = sma_source == "SMA" ? ta.sma(src, fast_length) : ta.ema(src, fast_length)
slow_ma = sma_source == "SMA" ? ta.sma(src, slow_length) : ta.ema(src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)
hist = macd - signal
// ATR and Position Size //
leverage = input.int(title = "Leverage Used", defval = 1, minval = 1, group = "ATR Position Size Inputs")
pointvalue = input.int(title = "Point Value/ATR Multipliers from Entry", defval = 4, minval = 1, group = "ATR Position Size Inputs")
length = input.int(title = "ATR Period", defval = 14, minval = 1, group ="ATR Position Size Inputs")
risk = input(title = "Risk Per Trade", defval = 0.01, group = "ATR Position Size Inputs")
atr = ta.atr(length)
amount = (risk * strategy.initial_capital / (pointvalue * atr * leverage))
// ATR Trailing Stops //
xATRPeriod = input.int(14, "ATR Period", group = "ATR Trailing Stop Inputs")
xATRMultiplier = input.float(4, "ATR Multiplier", step = .1, group = "ATR Trailing Stop Inputs")
xATR = ta.atr(xATRPeriod)
Stop = xATRMultiplier * xATR
var xATRTrailingStop = 0.0
xATRTrailingStop := if close>xATRTrailingStop[1] and close[1] > xATRTrailingStop[1]
math.max(xATRTrailingStop[1], close - Stop)
else if close < xATRTrailingStop[1] and close[1] < xATRTrailingStop[1]
math.min(xATRTrailingStop[1], close + Stop)
else if close > xATRTrailingStop[1]
close - Stop
else
close + Stop
var Position = 0.0
Position := if close[1] < xATRTrailingStop[1] and close > xATRTrailingStop[1]
1
else if close[1] > xATRTrailingStop[1] and close < xATRTrailingStop[1]
-1
else
Position[1]
PlotColor = Position == -1 ? color.orange : Position == 1 ? color.orange : color.orange
plot(xATRTrailingStop, color=PlotColor, linewidth = input(2, "Line Width", group = "ATR Trailing Stop Inputs"), style = plot.style_circles, title = "ATR Trailing Stop")
// Buy and Sell Conditions //
entrycondition1 = ta.crossover(macd, signal)
entrycondition2 = macd > signal
entrycondition3 = macd and signal > 0
sellcondition1 = ta.crossover(signal, macd)
sellcondition2 = signal > macd
sellcondition3 = macd and signal < 0
// Buy and Sell Signals //
if (close > h1 and entrycondition2 and entrycondition3)
strategy.entry("long", strategy.long, qty=amount)
stoploss = close - atr * xATRMultiplier
strategy.exit("exit sl", stop=stoploss, trail_offset=stoploss)
if (sellcondition1 and sellcondition2 and sellcondition3)
strategy.close(id="long")
if (close < l1 and sellcondition2 and sellcondition3)
strategy.entry("short", strategy.short, qty=amount)
stoploss = close + atr * xATRMultiplier
strategy.exit("exit sl", stop=stoploss, trail_offset=stoploss)
if (entrycondition1 and entrycondition2 and entrycondition3)
strategy.close(id="short")
|
Classic Long Term Trend Following System | https://www.tradingview.com/script/xM16I5bD-Classic-Long-Term-Trend-Following-System/ | Robrecht99 | https://www.tradingview.com/u/Robrecht99/ | 159 | 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/
// © Robrecht99
//@version=5
strategy("Classic Trend Following System", overlay=true, margin_long=0, margin_short=0, pyramiding=1)
// Backtest Range //
Start = input.time(defval = timestamp("01 Jan 2017 00:00 +0000"), title = "Backtest Start Date", group = "backtest window")
Finish = input.time(defval = timestamp("01 Jan 2100 00:00 +0000"), title = "Backtest End Date", group = "backtest window")
// Moving Averages //
len1 = input.int(50, minval = 1, title = "Length Fast EMA", group = "Moving Average Inputs")
len2 = input.int(150, minval = 1, title = "Length Slow EMA", group = "Moving Average Inputs")
src1 = input(close, title = "Source Fast MA")
src2 = input(close, title = "Source Slow MA")
maFast = input.color(color.new(color.red, 0), title = "Color Fast EMA", group = "Moving Average Inputs", inline = "maFast")
maSlow = input.color(color.new(color.blue, 0), title = "Color Slow EMA", group = "Moving Average Inputs", inline = "maSlow")
fast = ta.ema(src1, len1)
slow = ta.ema(src2, len2)
plot(fast, color = maFast, title = "Fast EMA")
plot(slow, color = maSlow, title = "Slow EMA")
// Donchian Channels //
Length1 = input.int(title = "Length Upper Channel", defval=50, minval=1, group = "Donchian Channels Inputs")
Length2 = input.int(title = "Length Lower Channel", defval=50, minval=1, group = "Donchian Channels Inputs")
h1 = ta.highest(high[1], Length1)
l1 = ta.lowest(low[1], Length2)
fillColor = input.color(color.new(color.purple, 95), title = "Fill Color", group = "Donchian Channels Inputs")
upperColor = input.color(color.new(color.orange, 0), title = " Color Upper Channel", group = "Donchian Channels Inputs", inline = "upper")
lowerColor = input.color(color.new(color.orange, 0), title = " Color Lower Channel", group = "Donchian Channels Inputs", inline = "lower")
u = plot(h1, "Upper", color = upperColor)
l = plot(l1, "Lower", color = upperColor)
fill(u, l, color=fillColor)
// ATR and Position Size //
leverage = input.int(title = "Leverage Used", defval = 1, minval = 1, group = "ATR Position Size Inputs")
pointvalue = input.int(title = "Point Value/ATR Multipliers from Entry", defval = 4, minval = 1, group = "ATR Position Size Inputs")
length = input.int(title = "ATR Period", defval = 14, minval = 1, group ="ATR Position Size Inputs")
risk = input(title = "Risk Per Trade", defval = 0.01, group = "ATR Position Size Inputs")
atr = ta.atr(length)
amount = (risk * strategy.initial_capital / (pointvalue * atr * leverage))
// ATR Trailing Stops //
xATRPeriod = input.int(14, "ATR Period", group = "ATR Trailing Stop Inputs")
xATRMultiplier = input.float(4, "ATR Multiplier", step = .1, group = "ATR Trailing Stop Inputs")
xATR = ta.atr(xATRPeriod)
Stop = xATRMultiplier * xATR
var xATRTrailingStop = 0.0
xATRTrailingStop := if close>xATRTrailingStop[1] and close[1] > xATRTrailingStop[1]
math.max(xATRTrailingStop[1], close - Stop)
else if close < xATRTrailingStop[1] and close[1] < xATRTrailingStop[1]
math.min(xATRTrailingStop[1], close + Stop)
else if close > xATRTrailingStop[1]
close - Stop
else
close+Stop
var Position = 0.0
Position := if close[1] < xATRTrailingStop[1] and close > xATRTrailingStop[1]
1
else if close[1] > xATRTrailingStop[1] and close < xATRTrailingStop[1]
-1
else
Position[1]
PlotColor = Position == -1 ? color.orange : Position == 1 ? color.orange : color.orange
plot(xATRTrailingStop, color=PlotColor, linewidth = input(2, "Line Width", group = "ATR Trailing Stop Inputs"), style = plot.style_circles, title = "ATR Trailing Stop")
// Buy and Sell Conditions //
entrycondition1 = ta.crossover(fast, slow)
entrycondition2 = fast > slow
sellcondition1 = ta.crossunder(fast, slow)
sellcondition2 = slow > fast
// Buy and Sell Signals //
if (close > h1 and entrycondition2)
strategy.entry("long", strategy.long, qty=amount)
stoploss = close - atr * xATRMultiplier
strategy.exit("exit sl", stop=stoploss, trail_offset=stoploss)
if (sellcondition1 and sellcondition2)
strategy.close(id="long")
if (close < l1 and sellcondition2)
strategy.entry("short", strategy.short, qty=amount)
stoploss = close + atr * xATRMultiplier
strategy.exit("exit sl", stop=stoploss, trail_offset=stoploss)
if (entrycondition1 and entrycondition2)
strategy.close(id="short") |
Trend Following with Bollinger Bands | https://www.tradingview.com/script/YBv96eln-Trend-Following-with-Bollinger-Bands/ | Robrecht99 | https://www.tradingview.com/u/Robrecht99/ | 168 | 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/
// © Robrecht99
//@version=5
strategy("Trend Following with Bollinger Bands", overlay=true, margin_long=0, margin_short=0, pyramiding=1)
// Bollinger Bands //
length = input.int(20, minval=1, group="Bollinger Bands Inputs")
src = input(close, title="Source", group="Bollinger Bands Inputs")
mult = input.float(2.0, minval=0.001, maxval=50, title="StdDev")
basis = ta.sma(src, length)
dev = mult * ta.stdev(src, length)
upper = basis + dev
lower = basis - dev
offset = input.int(0, "Offset", minval = -500, maxval = 500, group="Bollinger Bands Inputs")
plot(basis, "Basis", color=color.orange, offset = offset)
p1 = plot(upper, "Upper", color=color.orange, offset = offset)
p2 = plot(lower, "Lower", color=color.orange, offset = offset)
fill(p1, p2, title = "Background", color=color.rgb(255, 0, 255, 95))
// Moving Averages //
len1 = input.int(40, minval=1, title="Length Fast MA", group="Moving Average Inputs")
len2 = input.int(120, minval=1, title="Length Slow MA", group="Moving Average Inputs")
src1 = input(close, title="Source Fast MA")
src2 = input(close, title="Source Slow MA")
maColorFast = input.color(color.new(color.red, 0), title = "Color Fast MA", group = "Moving Average Inputs", inline = "maFast")
maColorSlow = input.color(color.new(color.purple, 0), title = "Color Slow MA", group = "Moving Average Inputs", inline = "maSlow")
fast = ta.ema(src1, len1)
slow = ta.ema(src2, len2)
plot(fast, color=maColorFast, title="Fast EMA")
plot(slow, color=maColorSlow, title="Slow EMA")
// ATR and Position Size //
leverage = input.int(title = "Leverage Used", defval = 1, minval = 1, group = "ATR Position Size Inputs")
pointvalue = input.int(title = "Point Value/ATR Multipliers from Entry", defval = 4, minval = 1, group = "ATR Position Size Inputs")
length1 = input.int(title = "ATR Period", defval = 14, minval = 1, group ="ATR Position Size Inputs")
risk = input(title = "Risk Per Trade", defval = 0.01, group = "ATR Position Size Inputs")
atr = ta.atr(length1)
amount = (risk * strategy.initial_capital / (pointvalue * atr * leverage))
// ATR Trailing Stops //
xATRPeriod = input.int(14, "ATR Period", group = "ATR Trailing Stop Inputs")
xATRMultiplier = input.float(4, "ATR Multiplier", step = .1, group = "ATR Trailing Stop Inputs")
xATR = ta.atr(xATRPeriod)
Stop = xATRMultiplier * xATR
var xATRTrailingStop = 0.0
xATRTrailingStop := if close>xATRTrailingStop[1] and close[1] > xATRTrailingStop[1]
math.max(xATRTrailingStop[1], close - Stop)
else if close < xATRTrailingStop[1] and close[1] < xATRTrailingStop[1]
math.min(xATRTrailingStop[1], close + Stop)
else if close > xATRTrailingStop[1]
close - Stop
else
close + Stop
var Position = 0.0
Position := if close[1] < xATRTrailingStop[1] and close > xATRTrailingStop[1]
1
else if close[1] > xATRTrailingStop[1] and close < xATRTrailingStop[1]
-1
else
Position[1]
PlotColor = Position == -1 ? color.orange : Position == 1 ? color.orange : color.orange
plot(xATRTrailingStop, color=PlotColor, linewidth = input(2, "Line Width", group = "ATR Trailing Stop Inputs"), style = plot.style_circles, title = "ATR Trailing Stop")
// Buy and Sell Conditions //
entrycondition1 = ta.crossover(fast, slow)
entrycondition2 = fast > slow
sellcondition1 = ta.crossunder(fast, slow)
sellcondition2 = slow > fast
// Buy and Sell Signals //
if (close > upper and entrycondition2)
strategy.entry("long", strategy.long, qty=amount)
stoploss = close - atr * xATRMultiplier
strategy.exit("exit sl", stop=stoploss, trail_offset=stoploss)
if (sellcondition1 and sellcondition2)
strategy.close(id="long")
if (close < lower and sellcondition2)
strategy.entry("short", strategy.short, qty=amount)
stoploss = close + atr * xATRMultiplier
strategy.exit("exit sl", stop=stoploss, trail_offset=stoploss)
if (entrycondition1 and entrycondition2)
strategy.close(id="short") |
A simple trading strategy for XTZ/EUR (December 2021) | https://www.tradingview.com/script/ZIdwUww4-A-simple-trading-strategy-for-XTZ-EUR-December-2021/ | hugodanielcom | https://www.tradingview.com/u/hugodanielcom/ | 20 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © hugodanielcom
//@version=5
//
// Welcome, this is a simple scalping strategy for trading XTZ.
//
// It works well for the Bear months, specially when configured with as much fiat than crypto at a starting state.
// This strategy underperforms Buy&Hold for the Bull months.
//
// It tries to do one market operation per candle whenever the candle happens in a buy/sell trading window of the
// Rebalance Bear/Bull indicator (https://www.tradingview.com/script/Y0omflqx-Rebalance-as-a-Bear-Bull-indicator/).
//
// It always buys/sells the same amount by default (you can set it in the cog menu in the option "Base Crypto Amount To Trade"),
// for XTZ this is set to 19.5XTZ.
//
// This is my attempt at scalping, it differs slightly from the standards because it does not require fast
// response candles or immediate market operations (it can work well with limit trading) and on top of this it also
// does not require a stop loss since it uses an indicator that provides the trading windows (surprises can still happen though).
//
// The main logic for this strategy is simple and happens down at the bottom, in the "Actions" section.
//
//
// This code makes use of the following libraries, they are open-source as well
// and you can check them out here: https://www.tradingview.com/u/hugodanielcom/#published-scripts
import hugodanielcom/PureRebalance/3 as rebalancer
import hugodanielcom/TradingPortfolio/1 as portfolio
strategy("S2", overlay=false, calc_on_order_fills = false, initial_capital = 10000.0)
starting_crypto = input.float(defval = 1.0, title = "Initial Crypto", minval = 1.0, maxval = 10000.0)
starting_fiat = input.float(defval = 1.0, title = "Initial Fiat", minval = 1.0, maxval = 10000.0)
base_amount = input.float(defval = 1.0, title = "Base Crypto Amount To Trade", minval = 0.1, maxval = 100.0)
min_value = input.float(defval = 11.0, title = "Min Fiat Trading Value", minval = 1.0, maxval = 100.0)
float precision = input.float(defval = 15.0, title = "Rebalance Precision", minval = 1.0, maxval = 100.0)
fromHour = input.int(defval = 1, title = "hh", group = "From", inline="fromClock", minval = 1, maxval = 24)
fromMin = input.int(defval = 0, title = "mm", group = "From", inline="fromClock", minval = 0, maxval = 60)
fromMonth = input.int(defval = 11, title = "MM", group = "From", inline="fromDate", minval = 1, maxval = 12)
fromDay = input.int(defval = 1, title = "DD", group = "From", inline="fromDate", minval = 1, maxval = 31)
fromYear = input.int(defval = 2021, title = "YYYY", group = "From", inline="fromDate", minval = 1970)
thruMonth = input.int(defval = 11, title = "MM", group = "Thru", inline="thruDate", minval = 1, maxval = 12)
thruDay = input.int(defval = 31, title = "DD", group = "Thru", inline="thruDate", minval = 1, maxval = 31)
thruYear = input.int(defval = 2021, title = "YYYY", group = "Thru", inline="thruDate", minval = 1970)
float MIN_AMOUNT = min_value / close
// === FUNCTION EXAMPLE ===
start = timestamp(fromYear, fromMonth, fromDay, fromHour, fromMin) // 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"
accum_profit = input.float(defval = 2.5, group = "Profit", title = "Profit", minval = 0.1, maxval = 99.9)
rebull_rebear_precision = input.float(defval = 2.5, group = "Bear/Bull Market Indicator", title = "Rebalance when portfolio differs by %", tooltip="Bigger values make the rebalance hold more and become less sensitive to peaks/bottoms and act less often.", minval = 0.1, maxval = 99.9)
rebull_rebear_from_month = fromMonth // input.int(defval = 11, group = "Bear/Bull Market Indicator", title = "Start At Month", minval = 1, maxval = 12)
rebull_rebear_from_day = input.int(defval = 1, group = "Bear/Bull Market Indicator", title = "Start At Day", minval = 1, maxval = 31)
rebull_rebear_from_year = fromYear // input.int(defval = 2021, group = "Bear/Bull Market Indicator", title = "Start At Year", minval = 2020)
rebull_rebear_capital = input.float(defval = 10000.0, group = "Bear/Bull Market Indicator", title = "Initial capital", minval = 1, tooltip="The total portfolio value to start with. A higher value makes the rebalancer more sensitive to peaks/bottoms and act more often")
rebull_rebear_percentage = input.float(defval = 60.0, group = "Bear/Bull Market Indicator", title = "Rebalance Token %", minval = 0.01, maxval = 100.0, tooltip="Percentage of Token / Money.\n60 means the targeted balance is 60% token and 40% money")
rebull_rebear_show_force = input.bool(defval = false, group = "Bear/Bull Market Indicator", title = "Show force")
rebull_rebear_show_opos = input.bool(defval = true, group = "Bear/Bull Market Indicator", title = "Show buy/sell windows of opportunities")
// Backtest start window
rebull_rebear_start = timestamp(rebull_rebear_from_year, rebull_rebear_from_month, rebull_rebear_from_day)
// Function returns true when the current bar time is
// "within the window of time" for this indicator
rebull_rebear_window() => time >= rebull_rebear_start
// The two market trend indicator portfolios
var float[] percentage_portfolio = portfolio.init()
var float[] signal_portfolio = portfolio.init()
// Initialization starts by doing a rebalance at the first bar within
// the window
var bool rebull_rebear_init1 = true
if rebull_rebear_window() and rebull_rebear_init1
// Only do this once, for the first bar, set init1 to false to disallow
// this block from running again
rebull_rebear_init1 := false
first_rebalance_amount = rebalancer.rebalance(close, 0.0, rebull_rebear_capital, rebull_rebear_percentage / 100)
portfolio.set_balance(percentage_portfolio, first_rebalance_amount, rebull_rebear_capital - (first_rebalance_amount * close))
float signal_capital = close*100.0
signal_first_rebalance_amount = rebalancer.rebalance(close, 0.0, signal_capital, rebull_rebear_percentage / 100)
portfolio.set_balance(signal_portfolio, signal_first_rebalance_amount, signal_capital - (signal_first_rebalance_amount * close))
var float signal = 0.0
float signal_rebalance_amount = rebalancer.rebalance(close, portfolio.crypto(signal_portfolio), portfolio.fiat(signal_portfolio), rebull_rebear_percentage / 100.0)
float signal_percentage_change = math.abs(signal_rebalance_amount) / portfolio.crypto(signal_portfolio)
bool signal_is_rebalance_needed = signal_percentage_change >= ((rebull_rebear_precision / 4.0) / 100.0)
bool signal_is_rebalance_buying = signal_is_rebalance_needed and signal_rebalance_amount > 0
bool signal_is_rebalance_selling = signal_is_rebalance_needed and signal_rebalance_amount < 0
// This is where the rebalance gets done
float percentage_rebalance_amount = rebalancer.rebalance(close, portfolio.crypto(percentage_portfolio), portfolio.fiat(percentage_portfolio), rebull_rebear_percentage / 100.0)
// Check if the amount to rebalance is bigger than the percentage
float percentage_change = math.abs(percentage_rebalance_amount) / portfolio.crypto(percentage_portfolio)
bool percentage_is_rebalance_needed = percentage_change >= (rebull_rebear_precision / 100.0)
bool percentage_is_rebalance_buying = percentage_is_rebalance_needed and percentage_rebalance_amount > 0
bool percentage_is_rebalance_selling = percentage_is_rebalance_needed and percentage_rebalance_amount < 0
var int bear_bull_balance = 0
var int bear_balance = 0
var int bull_balance = 0
var int signal_bear_balance = 0
var int signal_bull_balance = 0
var float percentage_signal = 0.0
// Update the percentage portfolio and the signal portfolio number of operations
// and bear/bull market balance. The values calculated here will then be used
// to set the "market_value" and "signal_market_value" below, which are the
// main indicators of the bear/bull market strength.
if rebull_rebear_window()
if percentage_is_rebalance_buying
portfolio.buy(percentage_portfolio, percentage_rebalance_amount, close)
bear_balance += 1
if percentage_is_rebalance_selling
portfolio.sell(percentage_portfolio, math.abs(percentage_rebalance_amount), close)
bull_balance += 1
if signal_is_rebalance_buying
if portfolio.buy(signal_portfolio, signal_rebalance_amount, close)
signal += signal_rebalance_amount
signal_bear_balance += 1
if signal_is_rebalance_selling
if portfolio.sell(signal_portfolio, math.abs(signal_rebalance_amount), close)
signal += signal_rebalance_amount
signal_bull_balance += 1
market_value = bull_balance - bear_balance
signal_market_value = signal_bull_balance - signal_bear_balance
// Store the signal_market_value at the entry point of a new market_value, this
// is used to subtract to the current signal value, useful as an indicator of
// the market force within the current market_value quantity.
var market_value_start = signal_market_value
if market_value[0] != market_value[1]
market_value_start := signal_market_value
// The colors to be used when the market is considered bear or bull
bear_down_color = color.new(color.red, 15)
bear_up_color = color.new(color.red, 15)
bull_down_color = color.new(color.green, 15)
bull_up_color = color.new(color.green, 15)
// A special color to be used when it is neither.
nothing_color = color.new(color.gray, 0)
// By default it is neither:
color market_color = nothing_color
// Look at the market_value and decide which color to use
market_color := nothing_color
bool is_signal_going_up = signal > 0
bool is_signal_going_down = not is_signal_going_up
if market_value > 0 and is_signal_going_up
market_color := bull_up_color
if market_value > 0 and is_signal_going_down
market_color := bull_down_color
if market_value < 0 and is_signal_going_up
market_color := bear_up_color
if market_value < 0 and is_signal_going_down
market_color := bear_down_color
// The market force is the second indicator that this code outputs, it represents
// the tendency of the market to go up or down within a "market_value" block.
force=signal_market_value - market_value_start
// It can be used to find buying and selling windows
bool is_force_selling_opportunity = force > 0 and ((market_value < 0 and force >= 2) or (market_value > 0 and force >= 1))
bool is_force_buying_opportunity = force < 0 and ((market_value < 0 and force <= -2) or (market_value > 0 and force <= -3))
bool is_buying_opportunity = is_force_buying_opportunity or (is_force_buying_opportunity[1] and close[1] >= close[0])
bool is_selling_opportunity = is_force_selling_opportunity or (is_force_selling_opportunity[1] and close[1] <= close[0])
// Paint these extra values if they are being drawn:
color force_color = na
if is_selling_opportunity
force_color := color.new(color.red, 80)
if is_buying_opportunity
force_color := color.new(color.blue, 80)
// The final bear/bull output
bgcolor(rebull_rebear_show_opos ? force_color : na, title="Buy/Sell opportunities")
plot(market_value, "Bear/Bull Strength", color=market_color, style=plot.style_area)
plot(force, "Force", color=rebull_rebear_show_force ? color.orange : na)
hline(0, "Middle Band", color=color.new(#787B86, 50))
////////////////////////////////////////////////////////////////////////////////////
// Rebalancer oscillator
////////////////////////////////////////////////////////////////////////////////////
// Calculate the HODL money in the portfolio - this is necessary because the
// TradingView strategy tester is targeted for single position strategies, which
// is not the case of this one.
var float token_start = 0.0
if window() and token_start == 0.0
token_start := close
var float hold = 0
var float window_close = 0.0
float initial_capital = starting_crypto * token_start + starting_fiat
if window()
window_close := close
hold := (initial_capital / token_start)
float hold_profit = hold * window_close - token_start * hold
plot(hold_profit, "Hold Profit", color=na)
// Arrays to keep track of previous orders (the TradingView strategy object
// works with a single position, this strategy doesn't follow pyramiding or a
// position - these arrays help to keep track of the orders being issued and
// get updated when they get matched by an requivalent upper/lower sale/buy)
var buy_orders_value = array.new_float()
var buy_orders_amount = array.new_float()
var buy_orders_fullfillment = array.new_float()
var sell_orders_value = array.new_float()
var sell_orders_amount = array.new_float()
var sell_orders_fullfillment = array.new_float()
var tmp_fullfillment_indices = array.new_int()
var tmp_fullfillment_amounts = array.new_float()
// Returns [ticker value, total amount sold, amount available]
get_past_unfulfilled_sell(int i) =>
if i >= 0 and i < array.size(sell_orders_value) and i < array.size(sell_orders_amount) and i < array.size(sell_orders_fullfillment)
fullfillment = array.get(sell_orders_fullfillment, i)
if fullfillment < 1.0
initial_amount_sold = array.get(sell_orders_amount, i)
available_amount = initial_amount_sold * (1.0 - fullfillment)
[array.get(sell_orders_value, i), initial_amount_sold, available_amount]
else
[0.0, 0.0, 0.0]
else
[0.0, 0.0, 0.0]
set_fullfillment_amount_in_sell(int i, float amount) =>
[_, initial_sell_amount, sell_available_amount] = get_past_unfulfilled_sell(i)
fullfilled_amount = initial_sell_amount - sell_available_amount
array.set(sell_orders_fullfillment, i, (amount + fullfilled_amount) / initial_sell_amount)
fullfill_sell_at(float value, float fiat_account_balance, int at) =>
amount_to_buy = 0.0
[sell_close, initial_sell_amount, sell_available_amount] = get_past_unfulfilled_sell(at)
if sell_available_amount * value < fiat_account_balance
// Fullfill 100% immediately
amount_to_buy += sell_available_amount
else
// Try to fullfill in parcels
amount_fullfilled = 0.0
total_parcels = 20
for j = 0 to total_parcels-1
current_parcel_amount = j*sell_available_amount/total_parcels
// Do we have fiat enough to buy a parcel this big?
if fiat_account_balance > current_parcel_amount * value
amount_fullfilled := current_parcel_amount
// Fullfill this
amount_to_buy += amount_fullfilled
profit = sell_close * amount_to_buy - value * amount_to_buy
[amount_to_buy, sell_close, profit]
// Tries to buy enough
fullfill_sells_gt(float value, float fiat_account_balance) =>
array.clear(tmp_fullfillment_indices)
array.clear(tmp_fullfillment_amounts)
float profit = 0.0
float amount_to_buy = 0.0
float tmp_fiat_balance = fiat_account_balance
int _size = array.size(sell_orders_value)
if _size > 0 and fiat_account_balance > 1.0
for i = 0 to _size-1
cur_order_value = array.get(sell_orders_value, i)
if cur_order_value > value
[amount_possible, sell_value, order_profit] = fullfill_sell_at(value, tmp_fiat_balance, i)
tmp_fiat_balance -= amount_possible * sell_value
amount_to_buy += amount_possible
profit += order_profit
// Mark this to be fullfilled
array.push(tmp_fullfillment_indices, i)
array.push(tmp_fullfillment_amounts, amount_possible)
[amount_to_buy, profit]
fullfill_oldest_sale(float value, float fiat_account_balance) =>
array.clear(tmp_fullfillment_indices)
array.clear(tmp_fullfillment_amounts)
int _size = array.size(sell_orders_value)
float amount_to_buy = MIN_AMOUNT
bool _is_done = false
if _size > 0
for i = 0 to _size-1
[amount_possible, sell_close, _] = fullfill_sell_at(value, fiat_account_balance, i)
if not _is_done
// This is the percentage of the profit to take in float: 1.XXX
price_adjustment = (1.0 - (sell_close / value)) + 1.0
if amount_possible > 0.0 and amount_possible * price_adjustment < fiat_account_balance
amount_to_buy := amount_possible * price_adjustment
_is_done := true
array.push(tmp_fullfillment_indices, i)
array.push(tmp_fullfillment_amounts, amount_to_buy)
amount_to_buy
else
amount_to_buy := 0.03
else
amount_to_buy
clear_fullfilled_sells() =>
old_sell_orders_value = array.copy(sell_orders_value)
old_sell_orders_amount = array.copy(sell_orders_amount)
old_sell_orders_fullfillment = array.copy(sell_orders_fullfillment)
array.clear(sell_orders_value)
array.clear(sell_orders_amount)
array.clear(sell_orders_fullfillment)
_size = array.size(old_sell_orders_fullfillment)
if _size > 0
for i = 0 to _size-1
if array.get(old_sell_orders_fullfillment, i) < 1.0
array.push(sell_orders_fullfillment, array.get(old_sell_orders_fullfillment, i))
array.push(sell_orders_value, array.get(old_sell_orders_value, i))
array.push(sell_orders_amount, array.get(old_sell_orders_amount, i))
close_buy() =>
_size = array.size(tmp_fullfillment_indices)
if _size > 0
for i = 0 to _size-1
sell_index = array.get(tmp_fullfillment_indices, i)
sell_amount = array.get(tmp_fullfillment_amounts, i)
set_fullfillment_amount_in_sell(sell_index, sell_amount)
clear_fullfilled_sells()
register_sell(value, amount) =>
array.push(sell_orders_value, value)
array.push(sell_orders_amount, amount)
array.push(sell_orders_fullfillment, 0.0)
// Returns [ticker value, total amount sold, amount available]
get_past_unfulfilled_buy(int i) =>
if i >= 0 and i < array.size(buy_orders_value) and i < array.size(buy_orders_amount) and i < array.size(buy_orders_fullfillment)
fullfillment = array.get(buy_orders_fullfillment, i)
if fullfillment < 1.0
initial_amount_bought = array.get(buy_orders_amount, i)
available_amount = initial_amount_bought * (1.0 - fullfillment)
[array.get(buy_orders_value, i), initial_amount_bought, available_amount]
else
[0.0, 0.0, 0.0]
else
[0.0, 0.0, 0.0]
set_fullfillment_amount_in_buy(int i, float amount) =>
[_, initial_buy_amount, buy_available_amount] = get_past_unfulfilled_buy(i)
fullfilled_amount = initial_buy_amount - buy_available_amount
array.set(buy_orders_fullfillment, i, (amount + fullfilled_amount) / initial_buy_amount)
fullfill_buy_at(float value, float fiat_account_balance, int at) =>
amount_to_sell = 0.0
[buy_close, initial_buy_amount, buy_available_amount] = get_past_unfulfilled_buy(at)
if buy_available_amount * value < fiat_account_balance
// Fullfill 100% immediately
amount_to_sell += buy_available_amount
else
// Try to fullfill in parcels
amount_fullfilled = 0.0
total_parcels = 20
for j = 0 to total_parcels-1
current_parcel_amount = j*buy_available_amount/total_parcels
// Do we have fiat enough to buy a parcel this big?
if fiat_account_balance > current_parcel_amount * value
amount_fullfilled := current_parcel_amount
// Fullfill this
amount_to_sell += amount_fullfilled
profit = buy_close * amount_to_sell - value * amount_to_sell
[amount_to_sell, buy_close, profit]
// Tries to buy enough
fullfill_buys_lt(float value, float fiat_account_balance) =>
array.clear(tmp_fullfillment_indices)
array.clear(tmp_fullfillment_amounts)
float profit = 0.0
float amount_to_sell = 0.0
float tmp_fiat_balance = fiat_account_balance
int _size = array.size(buy_orders_value)
if _size > 0 and fiat_account_balance > 1.0
for i = 0 to _size-1
cur_order_value = array.get(buy_orders_value, i)
if cur_order_value < value
[amount_possible, buy_value, order_profit] = fullfill_buy_at(value, tmp_fiat_balance, i)
tmp_fiat_balance -= amount_possible * buy_value
amount_to_sell += amount_possible
profit += order_profit
// Mark this to be fullfilled
array.push(tmp_fullfillment_indices, i)
array.push(tmp_fullfillment_amounts, amount_possible)
[amount_to_sell, profit]
fullfill_oldest_buy(float value, float fiat_account_balance) =>
array.clear(tmp_fullfillment_indices)
array.clear(tmp_fullfillment_amounts)
int _size = array.size(buy_orders_value)
float amount_to_sell = 1.0
bool _is_done = false
if _size > 0
for i = 0 to _size-1
[amount_possible, buy_close, _] = fullfill_buy_at(value, fiat_account_balance, i)
if not _is_done
price_adjustment = (1.0 - (buy_close / value)) + 1.0
if amount_possible > 0.0 and amount_possible * price_adjustment < fiat_account_balance
amount_to_sell := amount_possible * price_adjustment
_is_done := true
array.push(tmp_fullfillment_indices, i)
array.push(tmp_fullfillment_amounts, amount_to_sell)
amount_to_sell
else
amount_to_sell := 0.03
else
amount_to_sell
clear_fullfilled_buys() =>
old_buy_orders_value = array.copy(buy_orders_value)
old_buy_orders_amount = array.copy(buy_orders_amount)
old_buy_orders_fullfillment = array.copy(buy_orders_fullfillment)
array.clear(buy_orders_value)
array.clear(buy_orders_amount)
array.clear(buy_orders_fullfillment)
_size = array.size(old_buy_orders_fullfillment)
if _size > 0
for i = 0 to _size-1
if array.get(old_buy_orders_fullfillment, i) < 1.0
array.push(buy_orders_fullfillment, array.get(old_buy_orders_fullfillment, i))
array.push(buy_orders_value, array.get(old_buy_orders_value, i))
array.push(buy_orders_amount, array.get(old_buy_orders_amount, i))
close_sell() =>
_size = array.size(tmp_fullfillment_indices)
if _size > 0
for i = 0 to _size-1
buy_index = array.get(tmp_fullfillment_indices, i)
buy_amount = array.get(tmp_fullfillment_amounts, i)
set_fullfillment_amount_in_buy(buy_index, buy_amount)
clear_fullfilled_buys()
register_buy(value, amount) =>
array.push(buy_orders_value, value)
array.push(buy_orders_amount, amount)
array.push(buy_orders_fullfillment, 0.0)
// Virtual Portfolio (useful to get the rebalancer buy/sell points without
// suffering interference from the real buy/sales being done)
var float[] virtual = portfolio.init()
// The Real Portfolio
var float[] balance = portfolio.init()
buy_order(float amount) =>
strategy.order("buy", strategy.long, amount, when = window(), alert_message = str.tostring(amount))
sell_order(float amount) =>
strategy.order("sell", strategy.short, amount, when = window(), alert_message = str.tostring(-amount))
// Initialization starts by buying MIN_AMOUNT token and selling it right away.
// this is to ensure proper values in the Strategy Tester that start at the
// first block. Strategy Tester by default starts at the block of the first
// order - a buy/sell order is done on the first block so that it starts at it.
var init1 = true
var init2 = false
var init3 = false
var first_full_amount = MIN_AMOUNT
var last_rebalance_at = 0
ratio_of_first_rebalance = 0.5
float capital = initial_capital
// Start by selling enough crypto to have this
// amount of fiat
fiat_offset = 2000
on_the_side = 0
if window() and init1
init1 := false
init2 := true
strategy.order("buy", strategy.long, first_full_amount, when = window())
init1
else if window() and init2
init2 := false
init3 := true
strategy.order("sell", strategy.short, first_full_amount, when = window())
init2
else if window() and init3
init3 := false
first_rebalance_amount = rebalancer.rebalance(close, 0.0, capital, ratio_of_first_rebalance)
portfolio.set_balance(virtual, first_rebalance_amount, strategy.initial_capital - (first_rebalance_amount * close))
portfolio.set_balance(balance, starting_crypto, starting_fiat)
init3
// Adjust the precision to the current token value,
// This way the amount to rebalance is adjusted to be meaningful in very high
// value tokens, or very low value tokens
float token_adjustment = 2000.0 / (initial_capital / close)
// The virtual portfolio is frequently rebalanced at 60% crypto
// this allows it to be used to output buy/sales points while the real
// portfolio gets messed up with the trading action
// amount = portfolio.get_rebalance_amount(virtual, 0.60, close)
float virtual_amount = window() ? rebalancer.rebalance(close, portfolio.crypto(virtual), portfolio.fiat(virtual), 0.60) : 0.0
color virtual_rebalance_color = na
bool is_rebalance_selling = virtual_amount * token_adjustment < -precision
bool is_rebalance_buying = virtual_amount * token_adjustment > precision
if window()
if is_rebalance_buying
portfolio.buy(virtual, virtual_amount, close)
virtual_rebalance_color := color.new(color.teal, 80)
if is_rebalance_selling
portfolio.sell(virtual, math.abs(virtual_amount), close)
virtual_rebalance_color := color.new(color.maroon, 80)
bgcolor(window() ? virtual_rebalance_color : na, title="Buy/Sell Bar")
////////////////////////////////////////////////////////////////////////////////
// MAIN - balance = portfolio.init()
////////////////////////////////////////////////////////////////////////////////
bool is_selling_opportunity_finished = (not is_selling_opportunity) and is_selling_opportunity[1]
bool is_buying_opportunity_finished = (not is_buying_opportunity) and is_buying_opportunity[1]
bool is_selling_opportunity_starting = (not is_selling_opportunity[1]) and is_selling_opportunity[0]
bool is_buying_opportunity_starting = (not is_buying_opportunity[1]) and is_buying_opportunity[0]
buy(portfolio, amount, value) =>
[prev_sold_amount, profit_if_bought] = fullfill_sells_gt(value*(1.0 + (accum_profit / 100.0)), portfolio.fiat(balance))
if math.abs(amount) > MIN_AMOUNT
if portfolio.buy(portfolio, math.abs(amount) + math.abs(prev_sold_amount), value)
buy_order(math.abs(amount) + math.abs(prev_sold_amount))
register_buy(value, math.abs(amount))
close_buy()
sell(portfolio, amount, value) =>
[prev_bought_amount, profit_if_sold] = fullfill_buys_lt(value*(1.0 - (accum_profit / 100.0)), portfolio.fiat(balance))
if math.abs(amount) > MIN_AMOUNT
if portfolio.sell(portfolio, math.abs(amount) + math.abs(prev_bought_amount), value)
sell_order(math.abs(amount) + math.abs(prev_bought_amount))
register_sell(value, math.abs(amount))
close_sell()
// Overall performance of this strategy
float strategy_total = portfolio.fiat(balance) + portfolio.crypto(balance) * window_close
float vs_hold = (strategy_total + portfolio.retained(balance)) - (hold * window_close)
float did_profit = (portfolio.retained(balance) + strategy_total) - initial_capital
//////////////
// Actions //
//////////////
// These vars try to find the average lenght of a bar, this is useful
// to detect pumps and dumps
var int number_of_bars = 0
var float total_candle_size = 0.0
var float avg_candle_size = 0.0
float cur_candle_size = high - low
if window()
number_of_bars += 1
total_candle_size += (high - low)
avg_candle_size := total_candle_size / float(number_of_bars)
// Avoid trading at pumps and dumps
if cur_candle_size < 0.28
// Double the amount to trade if the rebalance oscillator is sayin that this is a good
// trade opportunity.
float amount = is_rebalance_selling or is_rebalance_buying ? base_amount * 2.0 : base_amount
// Perform the expected trading actions whenever the current candle is within a
// trading window of the bear/bull market indicator.
if is_selling_opportunity
sell(balance, amount, open)
if is_buying_opportunity
buy(balance, amount, open)
//////////////////////////////////////////////////////////////////////////////
// ANALYSIS - Open the Trading Window in the right menu to see these values //
//////////////////////////////////////////////////////////////////////////////
plot(avg_candle_size, "Avg Candle Size")
plot(cur_candle_size, "Cur Candle Size")
plot(portfolio.fiat(balance) + portfolio.retained(balance), title = "Fiat in Balance")
plot(portfolio.crypto(balance), title = "Crypto in Balance")
// How much profit did this strategy make when compared to the initial investment capital?
plot( did_profit, title = "Did Profit? (dif. from initial capital)", color = ((portfolio.retained(balance) + strategy_total) - initial_capital) > 0 ? color.green : color.red)
// How much profit did this strategy make when compared to a 100% buy at the first candle?
plot(vs_hold, title = "Total profit vs Hold (in Fiat)", color = (vs_hold > 0 ? color.green : color.red))
|
Portfolio Performance - 2 Assets | https://www.tradingview.com/script/RDWaf6Q6-Portfolio-Performance-2-Assets/ | Skywalking2874 | https://www.tradingview.com/u/Skywalking2874/ | 47 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Skywalking2874
//@version=5
strategy("Portfolio Performance - 2 Assets", overlay=false, margin_long=100, margin_short=100, process_orders_on_close=true, max_bars_back=5000)
//****************************************************************** Define the time interval ******************************************************************//
entrytime = input.time(defval=timestamp("2021-12-16"), title="Entry Time", tooltip="Enter the starting date", confirm=true, group="Time Interval")
exittime = input.time(defval=timestamp("2021-12-17"), title="Exit Time", tooltip="Enter the ending date", confirm=true, group="Time Interval")
entrycondition = time >= entrytime and time < exittime
exitcondition = time >= exittime
strategy.entry("Buy", strategy.long, qty=10000/close, when=entrycondition)
strategy.close_all(when = exitcondition)
//****************************************************************** Define the second asset ******************************************************************//
second_asset_prefix = input.string(defval = "NASDAQ", title = "Prefix", group="Second Asset", inline="Asset2")
second_asset_ticker = input.string(defval = "BND", title="Ticker", group="Second Asset", inline="Asset2")
second_ticker = ticker.new(prefix = second_asset_prefix, ticker = second_asset_ticker, session = session.regular, adjustment = adjustment.dividends)
second_symbol = request.security(second_ticker, "D", close)
//****************************************************************** Define the portfolio weights ******************************************************************//
portfolio1_weight1 = input.float(defval=100.00, title="First Weight (%)", minval=0, maxval=100, step=0.1, tooltip="Input the weight of this asset relative to your portfolio", inline="Asset1", group="First Portfolio")
portfolio1_weight2 = input.float(defval=0.00, title="Second Weight (%)", minval=0, maxval=100, step=0.1, tooltip="Input the weight of this asset relative to your portfolio", inline="Asset1", group="First Portfolio")
portfolio2_weight1 = input.float(defval=80.00, title="First Weight (%)", minval=0, maxval=100, step=0.1, tooltip="Input the weight of this asset relative to your portfolio", inline="Asset2", group="Second Portfolio")
portfolio2_weight2 = input.float(defval=20.00, title="Second Weight (%)", minval=0, maxval=100, step=0.1, tooltip="Input the weight of this asset relative to your portfolio", inline="Asset2", group="Second Portfolio")
portfolio3_weight1 = input.float(defval=60.00, title="First Weight (%)", minval=0, maxval=100, step=0.1, tooltip="Input the weight of this asset relative to your portfolio", inline="Asset3", group="Third Portfolio")
portfolio3_weight2 = input.float(defval=40.00, title="Second Weight (%)", minval=0, maxval=100, step=0.1, tooltip="Input the weight of this asset relative to your portfolio", inline="Asset3", group="Third Portfolio")
portfolio4_weight1 = input.float(defval=40.00, title="First Weight (%)", minval=0, maxval=100, step=0.1, tooltip="Input the weight of this asset relative to your portfolio", inline="Asset4", group="Fourth Portfolio")
portfolio4_weight2 = input.float(defval=60.00, title="Second Weight (%)", minval=0, maxval=100, step=0.1, tooltip="Input the weight of this asset relative to your portfolio", inline="Asset4", group="Fourth Portfolio")
portfolio5_weight1 = input.float(defval=20.00, title="First Weight (%)", minval=0, maxval=100, step=0.1, tooltip="Input the weight of this asset relative to your portfolio", inline="Asset5", group="Fifth Portfolio")
portfolio5_weight2 = input.float(defval=80.00, title="Second Weight (%)", minval=0, maxval=100, step=0.1, tooltip="Input the weight of this asset relative to your portfolio", inline="Asset5", group="Fifth Portfolio")
portfolio6_weight1 = input.float(defval=0.00, title="First Weight (%)", minval=0, maxval=100, step=0.1, tooltip="Input the weight of this asset relative to your portfolio", inline="Asset6", group="Sixth Portfolio")
portfolio6_weight2 = input.float(defval=100.00, title="Second Weight (%)", minval=0, maxval=100, step=0.1, tooltip="Input the weight of this asset relative to your portfolio", inline="Asset6", group="Sixth Portfolio")
//****************************************************************** Calculate %Return and %Risk Adjusted Return ******************************************************************//
trade_open_time = time >= strategy.opentrades.entry_time(strategy.opentrades-1) ? strategy.opentrades.entry_time(strategy.opentrades-1) : 2524608000000
bar_count = ta.barssince(time <= trade_open_time)
percent_return_first_asset = ((close - close[bar_count])/close[bar_count])*100
risk_adjusted_return_first_asset = percent_return_first_asset/ta.stdev(percent_return_first_asset, bar_count+1)
percent_return_second_asset = ((second_symbol - second_symbol[bar_count])/second_symbol[bar_count])*100
risk_adjusted_return_second_asset = percent_return_second_asset/ta.stdev(percent_return_second_asset, bar_count+1)
onehundred_zero_weighted_return = (portfolio1_weight1/100.00)*percent_return_first_asset + (portfolio1_weight2/100.00)*percent_return_second_asset
onehundred_zero_risk_adjusted_weighted_return = (portfolio1_weight1/100.00)*risk_adjusted_return_first_asset + (portfolio1_weight2/100.00)*risk_adjusted_return_second_asset
eighty_twenty_weighted_return = (portfolio2_weight1/100.00)*percent_return_first_asset + (portfolio2_weight2/100.00)*percent_return_second_asset
eighty_twenty_risk_adjusted_weighted_return = (portfolio2_weight1/100.00)*risk_adjusted_return_first_asset + (portfolio2_weight2/100.00)*risk_adjusted_return_second_asset
sixty_fourty_weighted_return = (portfolio3_weight1/100.00)*percent_return_first_asset + (portfolio3_weight2/100.00)*percent_return_second_asset
sixty_fourty_risk_adjusted_weighted_return = (portfolio3_weight1/100.00)*risk_adjusted_return_first_asset + (portfolio3_weight2/100.00)*risk_adjusted_return_second_asset
fourty_sixty_weighted_return = (portfolio4_weight1/100.00)*percent_return_first_asset + (portfolio4_weight2/100.00)*percent_return_second_asset
fourty_sixty_risk_adjusted_weighted_return = (portfolio4_weight1/100.00)*risk_adjusted_return_first_asset + (portfolio4_weight2/100.00)*risk_adjusted_return_second_asset
twenty_eighty_weighted_return = (portfolio5_weight1/100.00)*percent_return_first_asset + (portfolio5_weight2/100.00)*percent_return_second_asset
twenty_eighty_risk_adjusted_weighted_return = (portfolio5_weight1/100.00)*risk_adjusted_return_first_asset + (portfolio5_weight2/100.00)*risk_adjusted_return_second_asset
zero_onehundred_weighted_return = (portfolio6_weight1/100.00)*percent_return_first_asset + (portfolio6_weight2/100.00)*percent_return_second_asset
zero_onehundred_adjusted_weighted_return = (portfolio6_weight1/100.00)*risk_adjusted_return_first_asset + (portfolio6_weight2/100.00)*risk_adjusted_return_second_asset
//****************************************************************** Plot ******************************************************************//
portfolio1_return = input.bool(defval=true, title="Plot Weighted Return", inline="Asset11", group="First Portfolio")
portfolio2_return = input.bool(defval=true, title="Plot Weighted Return", inline="Asset22", group="Second Portfolio")
portfolio3_return = input.bool(defval=true, title="Plot Weighted Return", inline="Asset33", group="Third Portfolio")
portfolio4_return = input.bool(defval=true, title="Plot Weighted Return", inline="Asset44", group="Fourth Portfolio")
portfolio5_return = input.bool(defval=true, title="Plot Weighted Return", inline="Asset55", group="Fifth Portfolio")
portfolio6_return = input.bool(defval=true, title="Plot Weighted Return", inline="Asset66", group="Sixth Portfolio")
portfolio1_risk_adjusted_return = input.bool(defval=false, title="Plot Risk Adjusted Weighted Return", inline="Asset11", group="First Portfolio")
portfolio2_risk_adjusted_return = input.bool(defval=false, title="Plot Risk Adjusted Weighted Return", inline="Asset22", group="Second Portfolio")
portfolio3_risk_adjusted_return = input.bool(defval=false, title="Plot Risk Adjusted Weighted Return", inline="Asset33", group="Third Portfolio")
portfolio4_risk_adjusted_return = input.bool(defval=false, title="Plot Risk Adjusted Weighted Return", inline="Asset44", group="Fourth Portfolio")
portfolio5_risk_adjusted_return = input.bool(defval=false, title="Plot Risk Adjusted Weighted Return", inline="Asset55", group="Fifth Portfolio")
portfolio6_risk_adjusted_return = input.bool(defval=false, title="Plot Risk Adjusted Weighted Return", inline="Asset66", group="Sixth Portfolio")
trade_close_time = time >= strategy.closedtrades.entry_time(strategy.closedtrades-1) ? strategy.closedtrades.entry_time(strategy.closedtrades-1) : 2524608000000
transparant = color.rgb(0, 0, 0, 100)
//Fixed Weight Palette
fixed_color1 = time >= trade_open_time ? color.new(#10B22D, 0) : transparant
fixed_color2 = time >= trade_open_time ? color.new(#00FF1E, 0) : transparant
fixed_color3 = time >= trade_open_time ? color.new(#FFFB00, 0) : transparant
fixed_color4 = time >= trade_open_time ?color.new(#FF6600, 0) : transparant
fixed_color5 = time >= trade_open_time ? color.new(#FF0000, 0) : transparant
fixed_color6 = time >= trade_open_time ? color.new(#9C0000, 0) : transparant
//Fixed Weight Risk Adjusted Palette
fixed_risk_color1 = time >= trade_open_time ? color.new(#72A97C, 0) : transparant
fixed_risk_color2 = time >= trade_open_time ? color.new(#8AF897, 0) : transparant
fixed_risk_color3 = time >= trade_open_time ? color.new(#FFFD78, 0) : transparant
fixed_risk_color4 = time >= trade_open_time ?color.new(#FFAD77, 0) : transparant
fixed_risk_color5 = time >= trade_open_time ? color.new(#FF7D7D, 0) : transparant
fixed_risk_color6 = time >= trade_open_time ? color.new(#904747, 0) : transparant
plot(onehundred_zero_weighted_return, title="100/0 Weighted Return", color= portfolio1_return == true ? fixed_color1 : transparant)
plot(eighty_twenty_weighted_return, title="80/20 Weighted Return", color= portfolio2_return == true ? fixed_color2 : transparant)
plot(sixty_fourty_weighted_return, title="60/40 Weighted Return", color= portfolio3_return == true ? fixed_color3: transparant)
plot(fourty_sixty_weighted_return, title="40/60 Weighted Return", color= portfolio4_return == true ? fixed_color4: transparant)
plot(twenty_eighty_weighted_return, title="20/80 Weighted Return", color= portfolio5_return == true ? fixed_color5: transparant)
plot(zero_onehundred_weighted_return, title="0/100 Weighted Return", color= portfolio6_return == true ? fixed_color6: transparant)
plot(onehundred_zero_risk_adjusted_weighted_return, title="100/0 Risk Adjusted Weighted Return", color= portfolio1_risk_adjusted_return == true ? fixed_risk_color1 : transparant)
plot(eighty_twenty_risk_adjusted_weighted_return, title="80/20 Risk Adjusted Weighted Return", color= portfolio2_risk_adjusted_return == true ? fixed_risk_color2 : transparant)
plot(sixty_fourty_risk_adjusted_weighted_return, title="60/40 Risk Adjusted Weighted Return", color= portfolio3_risk_adjusted_return == true ? fixed_risk_color3: transparant)
plot(fourty_sixty_risk_adjusted_weighted_return, title="40/60 Risk Adjusted Weighted Return", color= portfolio4_risk_adjusted_return == true ? fixed_risk_color4: transparant)
plot(twenty_eighty_risk_adjusted_weighted_return, title="20/80 Risk Adjusted Weighted Return", color= portfolio5_risk_adjusted_return == true ? fixed_risk_color5: transparant)
plot(zero_onehundred_adjusted_weighted_return, title="0/100 Risk Adjusted Weighted Return", color= portfolio6_risk_adjusted_return == true ? fixed_risk_color6: transparant)
|
RSI Average Swing Bot | https://www.tradingview.com/script/uhXx6pUI-RSI-Average-Swing-Bot/ | exlux99 | https://www.tradingview.com/u/exlux99/ | 219 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © exlux99
//@version=5
strategy("RSI Average Swing Bot")
long_only=input.bool(true, title="Allow Long entries", group="Entries Type")
short_only=input.bool(true, title="Allow Short entries", group="Entries Type")
rsiohlc4= ta.rsi(ohlc4,50)/100
rsiclose= ta.rsi(close,50)/100
rsiopen= ta.rsi(open,50)/100
rsihigh= ta.rsi(high,50)/100
rsihlc3= ta.rsi(hlc3,50)/100
rsihl2= ta.rsi(hl2,50)/100
hline(0.3, color=color.white, linestyle=hline.style_dashed, linewidth=2)
hline(0.5, color=color.white, linestyle=hline.style_dotted, linewidth=2)
hline(0.7, color=color.white, linestyle=hline.style_dashed, linewidth=2)
rsi_avg = (rsiohlc4+rsiclose+rsiopen+rsihigh+rsihl2+rsihlc3)/6
culoare = rsi_avg > 0.50? color.green : rsi_avg<0.50 ? color.red : color.yellow
plot(rsi_avg,color=culoare )
long = rsi_avg > 0.5 and rsi_avg[1]< 0.5
longexit = rsi_avg >= input.float(0.65, step=0.05)
short = rsi_avg < 0.5 and rsi_avg[1] >0.5
shortexit=rsi_avg<=input.float(0.35, step=0.05)
if(long_only)
strategy.entry("long",strategy.long,when=long)
strategy.close("long",when=longexit or short)
if(short_only)
strategy.entry("short",strategy.short,when=short)
strategy.close("short",when=shortexit or long)
|
EMA Cross V1 for eth 4H | https://www.tradingview.com/script/DEy6ZWIq/ | chadsadachai | https://www.tradingview.com/u/chadsadachai/ | 10 | 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/
// © chadsadachai
//@version=5
strategy("EMA Cross V1", overlay= true)
//rsi
length = input.int(title = "Rsi Lenght" , defval=26 , minval=1, maxval=50)
overS = input.int(title = "Rsi OVS line" , defval=30 , minval=1, maxval=40)
overB = input.int(title = "Rsi OVB line" , defval=70 , minval=1, maxval=100)
mLine = input.int(title = "Rsi Medium line" , defval=42 , minval=1, maxval=60)
price = close
vrsi = ta.rsi(price, length)
co = vrsi >= mLine and vrsi < overB
cu = ta.crossunder(vrsi, overB)
//ema
F = input.int(title = "EMA Fast" , defval=17 , minval=1, maxval=50)
M = input.int(title = "EMA Medium" , defval=35, minval=1, maxval=100)
S = input.int(title = "EMA Slow" , defval=142, minval=1, maxval=200)
emaF = ta.ema(price , F)
emaM = ta.ema(price , M)
emaS = ta.ema(price , S)
//plot
plot(emaF , color = color.green , linewidth=1)
plot(emaM , color = color.yellow , linewidth=1)
plot(emaS , color = color.red , linewidth=1)
//Time Stamp
start = timestamp(input.int(title = "Start Year" , defval=2011 , minval=2011, maxval=2025), input.int(title = "Start Month" , defval=1 , minval=1, maxval=12), input.int(title = "Start Day" , defval=1 , minval=1, maxval=31), 0, 0)
end = timestamp(input.int(title = "End Year" , defval=2025 , minval=2011, maxval=2025), input.int(title = "End Month" , defval=1 , minval=1, maxval=12), input.int(title = "End Day" , defval=1 , minval=1, maxval=31), 0, 0)
// years = input.int(title = "Year" , defval=2018 , minval=2011, maxval=2025)
// months = input.int(title = "Month" , defval=1 , minval=1, maxval=12)
// days = input.int(title = "Day" , defval=1 , minval=1, maxval=31)
//longCondition Default
// longCondition1 = EMA_Fast >= EMA_Slow and EMA_Fast >= EMA_Medium//ta.crossover(EMA_Fast, EMA_Slow) EMA_Fast > EMA_Slow and EMA_Medium > EMA_Slow
// longCondition3 = price >= EMA_Medium and price > EMA_Slow
// longCondition2 = vrsi >= overSold and vrsi <= overBought
//longCondition & shortCondition ETHUSD
// 1.price > emaF > emaM > emaS
// 2.rsi overcross overS
longC1 = price > emaF and price > emaM and price > emaS
// longC1 = ta.crossover(emaF, emaM)
longC2 = if longC1
co
// shortC1 = EMA_Fast < EMA_Medium //and EMA_Fast < EMA_Slow and EMA_Medium < EMA_Slow //and cu
// shortC2 = overBought > vrsi //and vrsi < overBought //overSold < vrsi and vrsi < mediumLine
// exitLong Condition
// 1.price < emaF < emaM < emaS
// 2.rsi overcross mediumLine
exitLong1 = ta.crossunder(emaF, emaM) //or emaF < emaM//and price < emaM and price < emaF
exitLong2 = ta.crossunder(vrsi,mLine)
//exitLong3 = price < emaM
//strategy.entry
if time >=start and time <=end
strategy.entry("Buy", strategy.long , when = longC1 and longC2)
// if(exitLong1 or exitLong2)
strategy.close("Buy" , when = exitLong1 or exitLong2)
// exitShort1 = EMA_Fast > EMA_Medium
// //exitShort2 = ta.crossover(vrsi , mediumLine)
// exitShort2 = ta.crossunder (vrsi,mediumLine)
// strategy.close("Short" , when = exitShort1 or exitShort2)
// //shortCondition = cu
// //if (shortCondition1 and shortCondition2)
// //strategy.entry("My Short Entry Id", strategy.short)
|
Joint Conditions Strategy Suite + TradingConnector alerts bot | https://www.tradingview.com/script/2SMDLIj7-Joint-Conditions-Strategy-Suite-TradingConnector-alerts-bot/ | Peter_O | https://www.tradingview.com/u/Peter_O/ | 992 | 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('Joint Conditions Strategy Suite + TradingConnector alerts bot'
, shorttitle='JCSS+TradingConnector bot'
, overlay=true
, margin_long=100
, margin_short=100
, close_entries_rule='ANY'
, default_qty_type=strategy.fixed
, default_qty_value=100
, commission_type=strategy.commission.cash_per_order
, commission_value=0.0003)
import Peter_O/MTFindicators/8 as MTFLIBRARY
var string tooltipValue = '4th field is used only if \'value\' is selected in the 3rd dropdown. '
+ 'Otherwise it is ignored and value of indicator selected in 3rd dropdown is used. '
var string tooltipCustomIndicator = 'Custom indicator or series has to be selected here, so you can use it entry conditions dropdowns.'
+ 'Read this script description to see example use.'
var string tooltipMTF = 'MTF is timeframe multiplayer. '
+ 'For example, it you want to use RSI from 4h chart, being on 1h chart, you should enter 4 here. '
+ 'This refers to all MTF parameters in this section.'
var string tooltipKeltner = 'Keltner Channels settings: Basis Length, ATR Length, Multiplier, MTF x. Sorry, didn\'t fit in single line :)'
var string tooltipMACD = 'MACD settings: Fast Length, Slow Length, Signal Length, MTF x. Sorry, didn\'t fit in single line :)'
//------------------------------------------------------------------------------
var string longEntryGroup = 'Long Entry - when all conditions are jointly true/skipped'
var string shortEntryGroup = 'Short Entry - when all conditions are jointly true/skipped'
var string CrossingUpOption = 'Crossing Up'
var string CrossingDownOption = 'Crossing Down'
var string GreaterThanOption = 'Greater Than'
var string LessThanOption = 'Less Than'
var string skipOption = '...SKIP...'
var string openOption = 'open'
var string highOption = 'high'
var string lowOption = 'low'
var string closeOption = 'close'
var string ohlc4Option = 'ohlc4'
var string valueOption = 'value'
var string rsiAOption = 'rsiA'
var string rsiBOption = 'rsiB'
var string rsiCOption = 'rsiC'
var string maAOption = 'maA (Moving Average A)'
var string maBOption = 'maB (Moving Average B)'
var string maCOption = 'maC (Moving Average C)'
var string adxOption = 'ADX'
var string diPlusOption = 'DI-Plus'
var string diMinusOption = 'DI-Minus'
var string stochKOption = 'Stoch%K'
var string stochDOption = 'Stoch%D'
var string bbBasisOption = 'Basis Bollinger Band'
var string bbUpperOption = 'Upper Bollinger Band'
var string bbLowerOption = 'Lower Bollinger Band'
var string kcUpperOption = 'Upper Keltner Channel Band'
var string kcLowerOption = 'Lower Keltner Channel Band'
var string macdOption = 'MACD'
var string macdSignalOption = 'MACD Signal'
var string macdHistOption = 'MACD Histogram'
var string volumeOption = 'volume'
var string volumeMAOption = 'volumeMA'
var string customIndicatorOption = 'custom indicator'
longIndicatorSelector1 = input.string(defval=maBOption,
options=[skipOption, openOption, highOption, lowOption, closeOption, ohlc4Option, rsiAOption, rsiBOption, rsiCOption, maAOption, maBOption, maCOption, adxOption, diPlusOption, diMinusOption, stochKOption, stochDOption, bbBasisOption, bbUpperOption, bbLowerOption, kcUpperOption, kcLowerOption, macdOption, macdSignalOption, macdHistOption, volumeOption, volumeMAOption, customIndicatorOption],
title='', inline='cond1long', group=longEntryGroup)
longConditionTrigger1 = input.string(defval=CrossingUpOption,
options=[CrossingUpOption, CrossingDownOption, GreaterThanOption, LessThanOption],
title='', inline='cond1long', group=longEntryGroup)
longLevelSelector1 = input.string(defval=maCOption,
options=[valueOption, rsiAOption, rsiBOption, rsiCOption, maAOption, maBOption, maCOption, adxOption, diPlusOption, diMinusOption, stochKOption, stochDOption, bbBasisOption, bbUpperOption, bbLowerOption, kcUpperOption, kcLowerOption, macdOption, macdSignalOption, macdHistOption, volumeOption, volumeMAOption, customIndicatorOption],
title='', inline='cond1long', group=longEntryGroup)
longLevelValue1 = input.float(defval=0.00, title='', inline='cond1long', group=longEntryGroup, tooltip=tooltipValue)
//------------------------------------------------------------------------------
longIndicatorSelector2 = input.string(defval=macdHistOption,
options=[skipOption, openOption, highOption, lowOption, closeOption, ohlc4Option, rsiAOption, rsiBOption, rsiCOption, maAOption, maBOption, maCOption, adxOption, diPlusOption, diMinusOption, stochKOption, stochDOption, bbBasisOption, bbUpperOption, bbLowerOption, kcUpperOption, kcLowerOption, macdOption, macdSignalOption, macdHistOption, volumeOption, volumeMAOption, customIndicatorOption],
title='and', inline='cond2long', group=longEntryGroup)
longConditionTrigger2 = input.string(defval=GreaterThanOption,
options=[CrossingUpOption, CrossingDownOption, GreaterThanOption, LessThanOption],
title='', inline='cond2long', group=longEntryGroup)
longLevelSelector2 = input.string(defval=valueOption,
options=[valueOption, rsiAOption, rsiBOption, rsiCOption, maAOption, maBOption, maCOption, adxOption, diPlusOption, diMinusOption, stochKOption, stochDOption, bbBasisOption, bbUpperOption, bbLowerOption, kcUpperOption, kcLowerOption, macdOption, macdSignalOption, macdHistOption, volumeOption, volumeMAOption, customIndicatorOption],
title='', inline='cond2long', group=longEntryGroup)
longLevelValue2 = input.float(defval=0.00, title='', inline='cond2long', group=longEntryGroup)
//------------------------------------------------------------------------------
longIndicatorSelector3 = input.string(defval=adxOption,
options=[skipOption, openOption, highOption, lowOption, closeOption, ohlc4Option, rsiAOption, rsiBOption, rsiCOption, maAOption, maBOption, maCOption, adxOption, diPlusOption, diMinusOption, stochKOption, stochDOption, bbBasisOption, bbUpperOption, bbLowerOption, kcUpperOption, kcLowerOption, macdOption, macdSignalOption, macdHistOption, volumeOption, volumeMAOption, customIndicatorOption],
title='and', inline='cond3long', group=longEntryGroup)
longConditionTrigger3 = input.string(defval=GreaterThanOption,
options=[CrossingUpOption, CrossingDownOption, GreaterThanOption, LessThanOption],
title='', inline='cond3long', group=longEntryGroup)
longLevelSelector3 = input.string(defval=valueOption,
options=[valueOption, rsiAOption, rsiBOption, rsiCOption, maAOption, maBOption, maCOption, adxOption, diPlusOption, diMinusOption, stochKOption, stochDOption, bbBasisOption, bbUpperOption, bbLowerOption, kcUpperOption, kcLowerOption, macdOption, macdSignalOption, macdHistOption, volumeOption, volumeMAOption, customIndicatorOption],
title='', inline='cond3long', group=longEntryGroup)
longLevelValue3 = input.float(defval=25.00, title='', inline='cond3long', group=longEntryGroup)
//------------------------------------------------------------------------------
shortIndicatorSelector1 = input.string(defval=maBOption,
options=[skipOption, openOption, highOption, lowOption, closeOption, ohlc4Option, rsiAOption, rsiBOption, rsiCOption, maAOption, maBOption, maCOption, adxOption, diPlusOption, diMinusOption, stochKOption, stochDOption, bbBasisOption, bbUpperOption, bbLowerOption, kcUpperOption, kcLowerOption, macdOption, macdSignalOption, macdHistOption, volumeOption, volumeMAOption, customIndicatorOption],
title='', inline='cond1short', group=shortEntryGroup)
shortConditionTrigger1 = input.string(defval=CrossingDownOption,
options=[CrossingUpOption, CrossingDownOption, GreaterThanOption, LessThanOption],
title='', inline='cond1short', group=shortEntryGroup)
shortLevelSelector1 = input.string(defval=maCOption,
options=[valueOption, rsiAOption, rsiBOption, rsiCOption, maAOption, maBOption, maCOption, adxOption, diPlusOption, diMinusOption, stochKOption, stochDOption, bbBasisOption, bbUpperOption, bbLowerOption, kcUpperOption, kcLowerOption, macdOption, macdSignalOption, macdHistOption, volumeOption, volumeMAOption, customIndicatorOption],
title='', inline='cond1short', group=shortEntryGroup)
shortLevelValue1 = input.float(defval=0.00, title='', inline='cond1short', group=shortEntryGroup)
//------------------------------------------------------------------------------
shortIndicatorSelector2 = input.string(defval=macdHistOption,
options=[skipOption, openOption, highOption, lowOption, closeOption, ohlc4Option, rsiAOption, rsiBOption, rsiCOption, maAOption, maBOption, maCOption, adxOption, diPlusOption, diMinusOption, stochKOption, stochDOption, bbBasisOption, bbUpperOption, bbLowerOption, kcUpperOption, kcLowerOption, macdOption, macdSignalOption, macdHistOption, volumeOption, volumeMAOption, customIndicatorOption],
title='and', inline='cond2short', group=shortEntryGroup)
shortConditionTrigger2 = input.string(defval=LessThanOption,
options=[CrossingUpOption, CrossingDownOption, GreaterThanOption, LessThanOption],
title='', inline='cond2short', group=shortEntryGroup)
shortLevelSelector2 = input.string(defval=valueOption,
options=[valueOption, rsiAOption, rsiBOption, rsiCOption, maAOption, maBOption, maCOption, adxOption, diPlusOption, diMinusOption, stochKOption, stochDOption, bbBasisOption, bbUpperOption, bbLowerOption, kcUpperOption, kcLowerOption, macdOption, macdSignalOption, macdHistOption, volumeOption, volumeMAOption, customIndicatorOption],
title='', inline='cond2short', group=shortEntryGroup)
shortLevelValue2 = input.float(defval=0.00, title='', inline='cond2short', group=shortEntryGroup)
//------------------------------------------------------------------------------
shortIndicatorSelector3 = input.string(defval=adxOption,
options=[skipOption, openOption, highOption, lowOption, closeOption, ohlc4Option, rsiAOption, rsiBOption, rsiCOption, maAOption, maBOption, maCOption, adxOption, diPlusOption, diMinusOption, stochKOption, stochDOption, bbBasisOption, bbUpperOption, bbLowerOption, kcUpperOption, kcLowerOption, macdOption, macdSignalOption, macdHistOption, volumeOption, volumeMAOption, customIndicatorOption],
title='and', inline='cond3short', group=shortEntryGroup)
shortConditionTrigger3 = input.string(defval=GreaterThanOption,
options=[CrossingUpOption, CrossingDownOption, GreaterThanOption, LessThanOption],
title='', inline='cond3short', group=shortEntryGroup)
shortLevelSelector3 = input.string(defval=valueOption,
options=[valueOption, rsiAOption, rsiBOption, rsiCOption, maAOption, maBOption, maCOption, adxOption, diPlusOption, diMinusOption, stochKOption, stochDOption, bbBasisOption, bbUpperOption, bbLowerOption, kcUpperOption, kcLowerOption, macdOption, macdSignalOption, macdHistOption, volumeOption, volumeMAOption, customIndicatorOption],
title='', inline='cond3short', group=shortEntryGroup)
shortLevelValue3 = input.float(defval=25.00, title='', inline='cond3short', group=shortEntryGroup)
//------------------------------------------------------------------------------
var string exitSettingsGroup = 'Exit settings'
var string bracketPercent = 'Percent'
var string bracketATR = 'ATR'
var string bracketPoints = 'Points'
tpType = input.string(title='Take profit type', defval=bracketPoints, options=[bracketPercent, bracketATR, bracketPoints], inline='takeprofit', group=exitSettingsGroup)
tpValue = input.float(title='Take profit', step=0.1, minval=0.1, defval=100, inline='takeprofit', group=exitSettingsGroup)
slType = input.string(title='Stop Loss type', defval=bracketPoints, options=[bracketPercent, bracketATR, bracketPoints], inline='stoploss', group=exitSettingsGroup)
slValue = input.float(title='Stop Loss', step=0.1, minval=0.1, defval=100, inline='stoploss', group=exitSettingsGroup)
enableTrailing = input.bool(title='Enable Trailing Stop', defval=false, inline='trailing', group=exitSettingsGroup)
trailTriggerInput = input.int(title=' Trigger', minval=1, defval=80, inline='trailing', group=exitSettingsGroup)
trailPoints = enableTrailing == false ? na : trailTriggerInput
trailOffsetInput = input.int(title='Offset', minval=1, defval=10, inline='trailing', group=exitSettingsGroup)
trailOffset = enableTrailing == false ? na : trailOffsetInput
SL =
slType == bracketPercent ? slValue * close / 100 :
slType == bracketATR ? ta.atr(14) * slValue :
slValue
TP =
tpType == bracketPercent ? tpValue * close / 100 :
tpType == bracketATR ? ta.atr(14) * tpValue :
tpValue
//------------------------------------------------------------------------------
// Time settings for strategy
var string timeSettingsGroup = 'Time Settings'
filterTradingTimes = input.bool(true, title='Trade Only Within Sessions', inline='times', group=timeSettingsGroup)
tradingTimes = input.session('0900-1600', title='', inline='times', group=timeSettingsGroup)
isTradingSession = filterTradingTimes ? not na(time(timeframe.period, tradingTimes)) : true
bgcolor(filterTradingTimes and na(time(timeframe.period, tradingTimes)) ? color.new(color.black,85) : na, title='Not in Trading Session')
//------------------------------------------------------------------------------
var string indicatorDefinitionsGroup = 'Indicator Definitions'
var string emaOption = 'EMA'
var string smaOption = 'SMA'
var string wmaOption = 'WMA'
var string vwmaOption = 'VWMA'
var string hmaOption = 'HMA'
var string rmaOption = 'RMA'
var string demaOption = 'DEMA'
customIndicator = input.source(close, title='Custom Indicator aka Imported Source', group=indicatorDefinitionsGroup, inline='custom', tooltip=tooltipCustomIndicator)
rsiA_source = input.string(defval=closeOption, title='rsiA', options=[openOption, highOption, lowOption, closeOption, ohlc4Option], group=indicatorDefinitionsGroup, inline='rsiA')
rsiA_length = input.int(defval=5, title='', group=indicatorDefinitionsGroup, inline='rsiA')
rsiA_mtf = input.int(defval=1, title='mtf', group=indicatorDefinitionsGroup, inline='rsiA', tooltip=tooltipMTF)
rsiB_source = input.string(defval=closeOption, title='rsiB', options=[openOption, highOption, lowOption, closeOption, ohlc4Option], group=indicatorDefinitionsGroup, inline='rsiB')
rsiB_length = input.int(defval=14, title='', group=indicatorDefinitionsGroup, inline='rsiB')
rsiB_mtf = input.int(defval=1, title='mtf', group=indicatorDefinitionsGroup, inline='rsiB')
rsiC_source = input.string(defval=closeOption, title='rsiC', options=[openOption, highOption, lowOption, closeOption, ohlc4Option], group=indicatorDefinitionsGroup, inline='rsiC')
rsiC_length = input.int(defval=23, title='', group=indicatorDefinitionsGroup, inline='rsiC')
rsiC_mtf = input.int(defval=1, title='mtf', group=indicatorDefinitionsGroup, inline='rsiC')
maA_type = input.string(title='MaA', defval=emaOption, options=[emaOption, smaOption, wmaOption, vwmaOption, hmaOption, rmaOption, demaOption], inline='maA', group=indicatorDefinitionsGroup)
maA_source = input.string(defval=closeOption, options=[openOption, highOption, lowOption, closeOption, ohlc4Option], title='', inline='maA', group=indicatorDefinitionsGroup)
maA_length = input.int(defval=9, title='', inline='maA', group=indicatorDefinitionsGroup)
maA_mtf = input.int(defval=1, title='mtf', inline='maA', group=indicatorDefinitionsGroup)
maB_type = input.string(title='MaB', defval=emaOption, options=[emaOption, smaOption, wmaOption, vwmaOption, hmaOption, rmaOption, demaOption], inline='maB', group=indicatorDefinitionsGroup)
maB_source = input.string(defval=closeOption, options=[openOption, highOption, lowOption, closeOption, ohlc4Option], title='', inline='maB', group=indicatorDefinitionsGroup)
maB_length = input.int(defval=50, title='', inline='maB', group=indicatorDefinitionsGroup)
maB_mtf = input.int(defval=1, title='mtf', inline='maB', group=indicatorDefinitionsGroup)
maC_type = input.string(title='MaC', defval=emaOption, options=[emaOption, smaOption, wmaOption, vwmaOption, hmaOption, rmaOption, demaOption], inline='maC', group=indicatorDefinitionsGroup)
maC_source = input.string(defval=closeOption, options=[openOption, highOption, lowOption, closeOption, ohlc4Option], title='', inline='maC', group=indicatorDefinitionsGroup)
maC_length = input.int(defval=200, title='', inline='maC', group=indicatorDefinitionsGroup)
maC_mtf = input.int(defval=1, title='mtf', inline='maC', group=indicatorDefinitionsGroup)
diLength = input.int(defval=14, title='ADX-DMI', minval=1, maxval=50, inline='adx', group=indicatorDefinitionsGroup)
adxLength = input.int(defval=14, minval=1, title='DI Length', inline='adx', group=indicatorDefinitionsGroup)
mtf4adx = input.int(defval=1, title='mtf', inline='adx', group=indicatorDefinitionsGroup)
periodK = input.int(defval=14, title='Stch', minval=1, inline='stoch', group=indicatorDefinitionsGroup)
smoothK = input.int(defval=3, title='', minval=1, inline='stoch', group=indicatorDefinitionsGroup)
periodD = input.int(defval=3, title='', minval=1, inline='stoch', group=indicatorDefinitionsGroup)
mtf4stoch = input.int(defval=1, title='mtf', inline='stoch', group=indicatorDefinitionsGroup)
bbLength = input.int(defval=20, minval=1, title='BB', inline='bbands', group=indicatorDefinitionsGroup)
bbSource = input.string(defval=closeOption, options=[openOption, highOption, lowOption, closeOption, ohlc4Option], title='', inline='bbands', group=indicatorDefinitionsGroup)
bbMult = input.float(defval=2.0, minval=0.001, maxval=50, title='σ', inline='bbands', group=indicatorDefinitionsGroup)
mtf4bb = input.int(defval=1, title='mtf', inline='bbands', group=indicatorDefinitionsGroup)
kcLength = input.int(defval=13, minval=1, title='KC', inline='keltner', group=indicatorDefinitionsGroup, tooltip=tooltipKeltner)
kcSource = close //input.source(defval=close, title='', inline='keltner', group=indicatorDefinitionsGroup)
kcAtrLength = input.int(defval=13, minval=1, title='', inline='keltner', group=indicatorDefinitionsGroup)
kcMult = input.float(defval=1.5, minval=0.01, maxval=50, title='', inline='keltner', group=indicatorDefinitionsGroup)
mtf4keltner = input.int(defval=1, title='', inline='keltner', group=indicatorDefinitionsGroup)
macdFastLength = input.int(defval=12, title='MC', inline='macd', group=indicatorDefinitionsGroup, tooltip=tooltipMACD)
macdSource = close //input.source(defval=close, title='', inline='macd', group=indicatorDefinitionsGroup)
macdSlowLength = input.int(defval=26, title='', inline='macd', group=indicatorDefinitionsGroup)
macdSignalLength = input.int(defval=9, title='', minval = 1, maxval = 50, inline='macd', group=indicatorDefinitionsGroup)
mtf4macd = input.int(defval=1, title='', inline='macd', group=indicatorDefinitionsGroup)
//------------------------------------------------------------------------------
convertSource(sourceInput) =>
out =
sourceInput == closeOption ? close :
sourceInput == openOption ? open :
sourceInput == highOption ? high :
sourceInput == lowOption ? low :
sourceInput == ohlc4Option ? ohlc4 :
close
out
maA = MTFLIBRARY.moving_average_mtf(maA_mtf, maA_type, convertSource(maA_source), maA_length)
maB = MTFLIBRARY.moving_average_mtf(maB_mtf, maB_type, convertSource(maB_source), maB_length)
maC = MTFLIBRARY.moving_average_mtf(maC_mtf, maC_type, convertSource(maC_source), maC_length)
rsiA = MTFLIBRARY.rsi_mtf(rsiA_mtf, convertSource(rsiA_source), rsiA_length)
rsiB = MTFLIBRARY.rsi_mtf(rsiB_mtf, convertSource(rsiB_source), rsiB_length)
rsiC = MTFLIBRARY.rsi_mtf(rsiC_mtf, convertSource(rsiC_source), rsiC_length)
[adx, diPlus, diMinus] = MTFLIBRARY.adx_mtf(mtf4adx, adxLength, diLength)
[stochK, stochD] = MTFLIBRARY.stoch_mtf(mtf4stoch, periodK, smoothK, periodD)
[bbBasis, bbUpper, bbLower] = MTFLIBRARY.bollingerbands_mtf(mtf4bb, bbLength, convertSource(bbSource), bbMult)
[kcUpper, kcLower] = MTFLIBRARY.keltnerchannels_mtf(mtf4keltner, kcSource, kcLength, kcAtrLength, kcMult)
[macd, macdSignal, macdHist] = MTFLIBRARY.macd_mtf(mtf4macd, macdSource, macdFastLength, macdSlowLength, macdSignalLength)
volumeMA = ta.ema(volume, 20)
getIndicator(selectionInput) =>
out =
selectionInput == openOption ? open :
selectionInput == highOption ? high :
selectionInput == lowOption ? low :
selectionInput == closeOption ? close :
selectionInput == ohlc4Option ? ohlc4 :
selectionInput == rsiAOption ? rsiA :
selectionInput == rsiBOption ? rsiB :
selectionInput == rsiCOption ? rsiC :
selectionInput == maAOption ? maA :
selectionInput == maBOption ? maB :
selectionInput == maCOption ? maC :
selectionInput == adxOption ? adx :
selectionInput == diPlusOption ? diPlus :
selectionInput == diMinusOption ? diMinus :
selectionInput == stochKOption ? stochK :
selectionInput == stochDOption ? stochD :
selectionInput == bbBasisOption ? bbBasis :
selectionInput == bbUpperOption ? bbUpper :
selectionInput == bbLowerOption ? bbLower :
selectionInput == kcUpperOption ? kcUpper :
selectionInput == kcLowerOption ? kcLower :
selectionInput == macdOption ? macd :
selectionInput == macdSignalOption ? macdSignal :
selectionInput == macdHistOption ? macdHist :
selectionInput == volumeOption ? volume :
selectionInput == volumeMAOption ? volumeMA :
selectionInput == customIndicatorOption ? customIndicator :
close
out
getIndicatorIfSelected(selectionInput, selectionValue) =>
out =
selectionInput == rsiAOption ? rsiA :
selectionInput == rsiBOption ? rsiB :
selectionInput == rsiCOption ? rsiC :
selectionInput == maAOption ? maA :
selectionInput == maBOption ? maB :
selectionInput == maCOption ? maC :
selectionInput == adxOption ? adx :
selectionInput == diPlusOption ? diPlus :
selectionInput == diMinusOption ? diMinus :
selectionInput == stochKOption ? stochK :
selectionInput == stochDOption ? stochD :
selectionInput == bbBasisOption ? bbBasis :
selectionInput == bbUpperOption ? bbUpper :
selectionInput == bbLowerOption ? bbLower :
selectionInput == kcUpperOption ? kcUpper :
selectionInput == kcLowerOption ? kcLower :
selectionInput == macdOption ? macd :
selectionInput == macdSignalOption ? macdSignal :
selectionInput == macdHistOption ? macdHist :
selectionInput == volumeOption ? volume :
selectionInput == volumeMAOption ? volumeMA :
selectionInput == customIndicatorOption ? customIndicator :
selectionValue
out
longIndicator1 = getIndicator(longIndicatorSelector1)
longLevel1 = getIndicatorIfSelected(longLevelSelector1, longLevelValue1)
longIndicator2 = getIndicator(longIndicatorSelector2)
longLevel2 = getIndicatorIfSelected(longLevelSelector2, longLevelValue2)
longIndicator3 = getIndicator(longIndicatorSelector3)
longLevel3 = getIndicatorIfSelected(longLevelSelector3, longLevelValue3)
shortIndicator1 = getIndicator(shortIndicatorSelector1)
shortLevel1 = getIndicatorIfSelected(shortLevelSelector1, shortLevelValue1)
shortIndicator2 = getIndicator(shortIndicatorSelector2)
shortLevel2 = getIndicatorIfSelected(shortLevelSelector2, shortLevelValue2)
shortIndicator3 = getIndicator(shortIndicatorSelector3)
shortLevel3 = getIndicatorIfSelected(shortLevelSelector3, shortLevelValue3)
GoLong1 =
longConditionTrigger1 == CrossingUpOption ? ta.crossover(longIndicator1, longLevel1) :
longConditionTrigger1 == CrossingDownOption ? ta.crossunder(longIndicator1, longLevel1) :
longConditionTrigger1 == GreaterThanOption ? longIndicator1 > longLevel1 :
longConditionTrigger1 == LessThanOption ? longIndicator1 < longLevel1 :
true
GoLong2 =
longConditionTrigger2 == CrossingUpOption ? ta.crossover(longIndicator2, longLevel2) :
longConditionTrigger2 == CrossingDownOption ? ta.crossunder(longIndicator2, longLevel2) :
longConditionTrigger2 == GreaterThanOption ? longIndicator2 > longLevel2 :
longConditionTrigger2 == LessThanOption ? longIndicator2 < longLevel2 :
true
GoLong3 =
longConditionTrigger3 == CrossingUpOption ? ta.crossover(longIndicator3, longLevel3) :
longConditionTrigger3 == CrossingDownOption ? ta.crossunder(longIndicator3, longLevel3) :
longConditionTrigger3 == GreaterThanOption ? longIndicator3 > longLevel3 :
longConditionTrigger3 == LessThanOption ? longIndicator3 < longLevel3 :
true
GoShort1 =
shortConditionTrigger1 == CrossingUpOption ? ta.crossover(shortIndicator1, shortLevel1) :
shortConditionTrigger1 == CrossingDownOption ? ta.crossunder(shortIndicator1, shortLevel1) :
shortConditionTrigger1 == GreaterThanOption ? shortIndicator1 > shortLevel1 :
shortConditionTrigger1 == LessThanOption ? shortIndicator1 < shortLevel1 :
true
GoShort2 =
shortConditionTrigger2 == CrossingUpOption ? ta.crossover(shortIndicator2, shortLevel2) :
shortConditionTrigger2 == CrossingDownOption ? ta.crossunder(shortIndicator2, shortLevel2) :
shortConditionTrigger2 == GreaterThanOption ? shortIndicator2 > shortLevel2 :
shortConditionTrigger2 == LessThanOption ? shortIndicator2 < shortLevel2 :
true
GoShort3 =
shortConditionTrigger3 == CrossingUpOption ? ta.crossover(shortIndicator3, shortLevel3) :
shortConditionTrigger3 == CrossingDownOption ? ta.crossunder(shortIndicator3, shortLevel3) :
shortConditionTrigger3 == GreaterThanOption ? shortIndicator3 > shortLevel3 :
shortConditionTrigger3 == LessThanOption ? shortIndicator3 < shortLevel3 :
true
GoLong = longIndicatorSelector1 == skipOption and longIndicatorSelector2 == skipOption and longIndicatorSelector3 == skipOption
? false
: (
(longIndicatorSelector1 == skipOption ? true : GoLong1)
and (longIndicatorSelector2 == skipOption ? true : GoLong2)
and (longIndicatorSelector3 == skipOption ? true : GoLong3)
)
GoShort = shortIndicatorSelector1 == skipOption and shortIndicatorSelector2 == skipOption and shortIndicatorSelector3 == skipOption
? false
: (
(shortIndicatorSelector1 == skipOption ? true : GoShort1)
and (shortIndicatorSelector2 == skipOption ? true : GoShort2)
and (shortIndicatorSelector3 == skipOption ? true : GoShort3)
)
////////////
//STRATEGY//
////////////
if GoLong and isTradingSession and strategy.position_size <= 0
strategy.entry('long', strategy.long)
alertMessage =
'long sl=' + str.tostring(SL)
+ ' tp=' + str.tostring(TP)
+ (enableTrailing ? ' trail=true trailtrig=' + str.tostring(trailPoints) + ' traildist=' + str.tostring(trailOffset) : '')
alert(message=alertMessage, freq=alert.freq_once_per_bar_close)
strategy.exit('xl', from_entry='long', loss=SL, profit=TP, trail_points=trailPoints, trail_offset=trailOffset)
if GoShort and isTradingSession and strategy.position_size >= 0
strategy.entry('short', strategy.short, when=GoShort)
alertMessage =
'short sl=' + str.tostring(SL)
+ ' tp=' + str.tostring(TP)
+ (enableTrailing ? ' trail=true trailtrig=' + str.tostring(trailPoints) + ' traildist=' + str.tostring(trailOffset) : '')
alert(message=alertMessage, freq=alert.freq_once_per_bar_close)
strategy.exit('xs', from_entry='short', loss=SL, profit=TP, trail_points=trailPoints, trail_offset=trailOffset)
///////////
// PLOTS //
///////////
plot(maA, title='maA', linewidth=1, color=color.new(color.lime, 0))
plot(maB, title='maB', linewidth=2, color=color.new(color.fuchsia, 0))
plot(maC, title='maC', linewidth=3, color=color.new(color.orange, 0))
////////////
//WARNINGS//
////////////
atrFullChart = ta.atr(2000) / syminfo.mintick
showWarning = (SL > 0 and SL <= atrFullChart) or (TP > 0 and TP <= atrFullChart) or (trailOffset > 0 and trailOffset <= atrFullChart)
whichBracketsAreTooTight =
(SL > 0 and SL <= atrFullChart) and (TP == 0 or TP > atrFullChart) and (trailOffset == 0 or na(trailOffset) or trailOffset > atrFullChart) ? 'StopLoss' :
(SL > 0 and SL <= atrFullChart) and (TP > 0 and TP <= atrFullChart) and (trailOffset == 0 or na(trailOffset) or trailOffset > atrFullChart) ? 'StopLoss, TakeProfit' :
(SL > 0 and SL <= atrFullChart) and (TP > 0 and TP <= atrFullChart) and (trailOffset > 0 and trailOffset <= atrFullChart) ? 'StopLoss, TakeProfit, Trail' :
(SL > 0 and SL <= atrFullChart) and (TP == 0 or TP > atrFullChart) and (trailOffset > 0 and trailOffset <= atrFullChart) ? 'StopLoss, Trail' :
(SL == 0 or SL > atrFullChart) and (TP > 0 and TP <= atrFullChart) and (trailOffset == 0 or na(trailOffset) or trailOffset > atrFullChart) ? 'TakeProfit' :
(SL == 0 or SL > atrFullChart) and (TP > 0 and TP <= atrFullChart) and (trailOffset > 0 and trailOffset <= atrFullChart) ? 'TakeProfit, Trail' :
(SL == 0 or SL > atrFullChart) and (TP == 0 or TP > atrFullChart) and (trailOffset > 0 and trailOffset <= atrFullChart) ? 'Trail' :
''
warningHeader = 'WARNING!'
warningHeader2 = 'Too tight ' + whichBracketsAreTooTight
warningText = 'Due to non-tick-data candle mechanisms here of TradingView, backtest results\nyou are seeing right now in the Strategy Tester are probably better than in reality.'
+ '\n\nWhy?\n\nStrategy Tester assumes that at each candle market has first moved in your\nfavor (so while in Long position market first reached HIGH of a candle, and while\nin Short position first reached LOW), and against you after that. '
+ 'The suggested\nworkaround, to make backtester results more real, is to increase SL/TP/Trail,\nso they are higher than ATR for this chart (this instrument on this timeframe).'
+ '\n\nThat was in quick words, but you can learn more from this\nvideo: https://www.youtube.com/watch?v=uM5m_iUAP8g\n\nATR value (in ticks) for this chart is '
+ str.tostring(atrFullChart)
warningText2 = 'You can proceed with the current settings, because you still might want to set\ntight SL/TP/Trail for alerts, but be assured that backtest results ain\'t real.'
var table warningsTable = table.new(position=position.top_right, columns=1, rows=4, border_width=1)
if barstate.islastconfirmedhistory and showWarning
table.cell(warningsTable, column=0, row=0, text=warningHeader, bgcolor=na, text_color=color.orange, text_size=size.large)
table.cell(warningsTable, column=0, row=1, text=warningHeader2, bgcolor=na, text_color=color.orange, text_size=size.large)
table.cell(warningsTable, column=0, row=2, text=warningText, bgcolor=na, text_color=color.teal, text_size=size.normal, text_halign=text.align_right)
table.cell(warningsTable, column=0, row=3, text=warningText2, bgcolor=na, text_color=color.teal, text_size=size.normal, text_halign=text.align_right)
|
Crypto MF S/R Strategy - cespanol | https://www.tradingview.com/script/rjNH1y4k-Crypto-MF-S-R-Strategy-cespanol/ | cespanol | https://www.tradingview.com/u/cespanol/ | 91 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © cespanol
//Credit to CryptoMF for the source code.
//Credit to rouxam for the 3commas backtesting template.
//This strategy uses CryptoMF's indicator to autogenerate horizontal support/resistance lines.
//Buy signals are generated on support tests and sell signals are generated on resistance tests.
//Rouxam's code is used to include 3commas input settings.
//Suggestions/code clean-up are appreciated!
//@version=4
strategy("Cespanol S/R V3 Strategy", overlay=true, pyramiding=99, process_orders_on_close=true, commission_type=strategy.commission.percent, commission_value=0.05, initial_capital=10000)
// Crypto MF Inputs
ln = input(1, title="Pivot Length", type=input.integer) // Number of bars to use to calculate pivot
mb = input(1, title="Max Breaks", type=input.integer) // Maximum number of times a line can be broken before it's invalidated
//md = input(50, title="Max Distance %", type=input.integer) // Maximum distance PA can move away from line before it's invalidated
//fo = input(2, title="Frontrun/Overshoot Threshold %", type=input.float, step=0.1) // If PA reverses within this distance of an existing S&R line, consider it a frontrun / overshoot
fo = ((atr(20) / close) * 100) / 2 // Dynamic fo using ATR
md = fo * 30 // Dynamic md
alt = input(true, title="Show Level Test", type=input.bool) // Show arrow when level is tested
mtm = input(3, title="Level Test Sensitivity", minval=0, type=input.integer) // (this value * 10 * mintick <> level to trigger test)
alb = input(false, title="Show Level Break", type=input.bool) // Colourise candle if a level is broken
// Line colors
lc = input(color.blue, title="Line Colour", type=input.color) // Default line color
// Important Note : Initial Capital above is written to match the default value based on bot parameters.
// It is expected the user will update the initial_capital via the GUI Parameters > Properties tab
// A warning will displayed in case initial capital and max amount for bot usage do not match.
// ----------------------------------
// Rouxam Strategy Inputs
// ----------------------------------
dsc = input(defval="Cespanol S/R", title="Deal Start Condition", options=["Cespanol S/R", "Start ASAP", "RSI-7", "TV presets"])
base_order = input(100.0, type=input.float,title="Base Order")
safe_order = input(7.0, type=input.float,title="Safety Order")
order_size_type = input(defval="% of equity", title="Order Size Type", options=["Fixed", "% of equity"])
max_safe_order = input(0, title="Max Safety Trades Count", minval=0, maxval=99, step=1)
price_deviation = input(1, type=input.float, title="Price deviation to open safety order (%)", minval=0.0, step=0.1)/100
safe_order_volume_scale = input(1, type=input.float, title="Safety Order Volume Scale", step=0.1)
safe_order_step_scale = input(1, type=input.float, title="Safety Order Step Scale", step=0.1)
start_time = input(defval=timestamp("01 Sept 2021 06:00"), title="Start Time", type=input.time)
end_time = input(defval=timestamp("31 Dec 2021 20:00"), title="End Time", type=input.time)
take_profit = input(999, type=input.float, title="Take Profit (%)", minval=0.0, step=0.1)/100
take_profit_type = input(defval="% from total volume", title="Take Profit Type", options=["% from total volume", "% from base order"])
ttp = input(0.0, type=input.float, title="Trailing Take Profit (%) [0 = Disabled]", minval=0.0, step=0.1)/100
stop_loss = input(0.0, type=input.float, title="Stop Loss (%) [0 = Disabled]", minval=0.0, step=0.1)/100
dsc_rsi_threshold = input(defval=30, title="[RSI-7 only] RSI Threshold", minval=1, maxval=99)
dsc_technicals = input(defval="Strong", title="[TV presets only] Strength", options=["Strong", "Weak"])
dsc_res = input("", title="[RSI-7 and TV presets Only] Indicator Timeframe", type=input.resolution)
bot_direction = input(defval="Long", title="Bot Direction", options=["Long", "Short"])
// CryptoMF Array definitions
var sr = array.new_float(15, na) // SR levels
var br = array.new_int(15, 0) // Amount of times an S&R line has been broken
var li = array.new_line(15, na) // Lines
// Check if a pivot is actually just a swing failure off an existing S&R level
issfp(level) =>
((open[ln] < level) and (high[ln] > level) and (close[ln] < level)) or ((open[ln] > level) and (low[ln] < level) and (close[ln] > level)) or ((open[ln+1] < level) and (high[ln+1] > level) and (close[ln+1] < level)) or ((open[ln+1] > level) and (low[ln+1] < level) and (close[ln+1] > level))
// Check if pivot is actually just a frontrun or overshoot of an existing S&R level (<fo% diff)
isfros(level) =>
((open[ln] < level) and ((abs(level - high[ln]) / level) * 100 < fo) and (close[ln] < level)) or ((open[ln] > level) and ((abs(low[ln] - level) / level) * 100 < fo) and (close[ln] > level)) or ((open[ln-1] < level) and ((abs(level - high[ln-1]) / level) * 100 < fo) and (close[ln-1] < level)) or ((open[ln-1] > level) and ((abs(low[ln-1] - level) / level) * 100 < fo) and (close[ln-1] > level))
// Check for S&R level break
isbreak(level) =>
((open < level) and (close > level)) or ((open > level) and (close < level))
// Check potential pivot to see it if just a break failure of exisitng S&R level (frontrun or sfp)
isbreakfailure() =>
bf = array.new_int(15, 0)
for i = 0 to 14
level = array.get(sr, i)
array.set(bf, i, (issfp(level) or isfros(level)) ? 1 : 0)
array.max(bf) == 1 ? true : false
// Check if candle breaks a level
lvlbreak() =>
result = 0
for i = 0 to 14
level = array.get(sr, i)
if (open < level and close > level)
result := 1
if (open > level and close < level)
result := -1
result
// Check if candle is a test of level
lvltest() =>
result = 0
for i = 0 to 14
level = array.get(sr, i)
if (open < level and high > level - (syminfo.mintick * 10 * mtm) and close < level)
result := -1
if (open > level and low < level + (syminfo.mintick * 10 * mtm) and close > level)
result := 1
result
// Get levels % distance from current close
pctfromclose(level) =>
(abs(level - close) / close) * 100
// Custom Pivot Function
pv() =>
c = close
bl = ln * 2 + 1
m = c[ln]
ph = m == highest(c, bl) ? true : false
pl = m == lowest(c, bl) ? true : false
(ph or pl) and not isbreakfailure() ? c[ln] : na
p = pv() // Get pivot
lb = ln // Offset of pivot line
// Find an unused pivot level and use it
if not na(p)
for i = 0 to 14
if na(array.get(sr, i))
array.set(li, i, line.new(bar_index - lb, p, bar_index, p, extend=extend.right, color=lc))
array.set(sr, i, p)
break
// Count number of times a S&R line has been broken
for i = 0 to 14
if isbreak(array.get(sr, i))
array.set(br, i, array.get(br, i) + 1)
// Check number of times an S&R line has been broken, or calculate distance to current PA and invalidate the S&R level if necessary
for i = 0 to 14
if array.get(br, i) >= mb or pctfromclose(array.get(sr, i)) >= md
array.set(sr, i, na)
array.set(br, i, 0)
line.delete(array.get(li, i))
array.set(li, i, na)
// Level Test Plots
lts = lvltest() == 1 // Level Test (Support)
ltr = lvltest() == -1 // Level Test (Resistance)
plotshape(alt and lts, style=shape.cross, location=location.belowbar, color=color.green, offset=0, title="Level Test (Support)", transp=0)
plotshape(alt and ltr, style=shape.cross, location=location.abovebar, color=color.red, offset=0, title="Level Test (Resistance)", transp=0)
// Level Break Plots
lbr = lvlbreak() == 1 // Level Break (Resistance)
lbs = lvlbreak() == -1 // Level Break (Support)
barcolor(alb and lbr ? color.green : (alb and lbs ? color.red : na), title="Level Break")
// Alerts
alertcondition(lts or ltr or lbr or lbs, "Level Test or Break", "Level Test or Break")
alertcondition(lts or ltr, "Level Test", "Level Test")
alertcondition(lts, "Level Test (Support)", "Level Test (Support)")
alertcondition(ltr, "Level Test (Resistance)", "Level Test (Resistance)")
alertcondition(lbr or lbs, "Level Break", "Level Break")
alertcondition(lbs, "Level Break (Support)", "Level Break (Support)")
alertcondition(lbr, "Level Break (Resistance)", "Level Break (Resistance)")
//End CryptoMF
// Cespanol Strategy - Longs only
isLong = (strategy.position_size > 0)
strategy.risk.allow_entry_in(strategy.direction.long)
//Rouxam codes
// ----------------------------------
// Declarations
// ----------------------------------
var bo_level = 0.0
var last_so_level = 0.0
var so_level = 0.0
var ttp_active = false
var ttp_extremum = 0.0
var ttp_level = 0.0
var stop_level = 0.0
var take_profit_level = 0.0
var deal_counter = 0
var stop_loss_counter = 0
var stop_loss_on_bar = false
var latest_price = close
var deal_start_condition = false
var start_time_actual = start_time
var end_time_actual = start_time
// CONSTANTS
var float init_price = na
var IS_LONG = bot_direction == "Long"
// ----------------------------------
// Utilities functions
// ----------------------------------
pretty_date(t) => tostring(dayofmonth(t)) + "/" + tostring(month(t)) + "/" + tostring(year(t))
within_window() => time >= start_time and time <= end_time
base_order_size() => order_size_type == "Fixed" ? base_order : base_order/100 * strategy.equity
safe_order_size() => order_size_type == "Fixed" ? safe_order : safe_order/100 * strategy.equity
safety_order_deviation(index) => price_deviation * pow(safe_order_step_scale, index - 1)
safety_order_price(index, last_safety_order_price) =>
if IS_LONG
last_safety_order_price * (1 - safety_order_deviation(index))
else
last_safety_order_price * (1 + safety_order_deviation(index))
safety_order_qty(index) => safe_order_size() * pow(safe_order_volume_scale, index - 1)
max_amount_for_bot_usage() =>
var total_qty = 0.0
var last_order_qty = 0.0
total_qty := base_order_size()
last_order_qty := safe_order_size()
if max_safe_order > 0
for index = 1 to max_safe_order
total_qty := total_qty + safety_order_qty(index)
total_qty // returned value
max_deviation() =>
var total_deviation = 0.0
total_deviation := 0.0
for index = 1 to max_safe_order
total_deviation := total_deviation + safety_order_deviation(index)
currency_format() =>
if syminfo.currency == "USDT" or syminfo.currency == "USD" or syminfo.currency == "TUSD" or syminfo.currency == "BUSD" or syminfo.currency == "USDC" or syminfo.currency == "EUR" or syminfo.currency == "AUD"
"#.##"
else if syminfo.currency == "BTC"
"#.########"
else
// TODO (rouxam) list more options
"#.####"
// ***********************************
// Deal Start Condition Strategies
// ***********************************
// RSI-7
// ***********************************
rsi_signal() =>
// Regular strat would be crossover but not for 3C DCA Bot
rsi7 = rsi(close, 7)
if IS_LONG
[rsi7 < dsc_rsi_threshold, close]
else
[rsi7 > dsc_rsi_threshold, close]
// TV presets
// ***********************************
// This whole section is from the TradingView "Technical Ratings" code.
// Adding the Technical Ratings "indicator" as input to this "strategy" is not sufficient for our purpose,
// Therefore the code is copy-pasted.
// ***********************************
// Awesome Oscillator
AO() =>
sma(hl2, 5) - sma(hl2, 34)
// Stochastic RSI
StochRSI() =>
rsi1 = rsi(close, 14)
K = sma(stoch(rsi1, rsi1, rsi1, 14), 3)
D = sma(K, 3)
[K, D]
// Ultimate Oscillator
tl() => close[1] < low ? close[1]: low
uo(ShortLen, MiddlLen, LongLen) =>
Value1 = sum(tr, ShortLen)
Value2 = sum(tr, MiddlLen)
Value3 = sum(tr, LongLen)
Value4 = sum(close - tl(), ShortLen)
Value5 = sum(close - tl(), MiddlLen)
Value6 = sum(close - tl(), LongLen)
float UO = na
if Value1 != 0 and Value2 != 0 and Value3 != 0
var0 = LongLen / ShortLen
var1 = LongLen / MiddlLen
Value7 = (Value4 / Value1) * (var0)
Value8 = (Value5 / Value2) * (var1)
Value9 = (Value6 / Value3)
UO := (Value7 + Value8 + Value9) / (var0 + var1 + 1)
UO
// Ichimoku Cloud
donchian(len) => avg(lowest(len), highest(len))
ichimoku_cloud() =>
conversionLine = donchian(9)
baseLine = donchian(26)
leadLine1 = avg(conversionLine, baseLine)
leadLine2 = donchian(52)
[conversionLine, baseLine, leadLine1, leadLine2]
calcRatingMA(ma, src) => na(ma) or na(src) ? na : (ma == src ? 0 : ( ma < src ? 1 : -1 ))
calcRating(buy, sell) => buy ? 1 : ( sell ? -1 : 0 )
ta_presets_signal() =>
//============== MA =================
SMA10 = sma(close, 10)
SMA20 = sma(close, 20)
SMA30 = sma(close, 30)
SMA50 = sma(close, 50)
SMA100 = sma(close, 100)
SMA200 = sma(close, 200)
EMA10 = ema(close, 10)
EMA20 = ema(close, 20)
EMA30 = ema(close, 30)
EMA50 = ema(close, 50)
EMA100 = ema(close, 100)
EMA200 = ema(close, 200)
HullMA9 = hma(close, 9)
// Volume Weighted Moving Average (VWMA)
VWMA = vwma(close, 20)
[IC_CLine, IC_BLine, IC_Lead1, IC_Lead2] = ichimoku_cloud()
// ======= Other =============
// Relative Strength Index, RSI
RSI = rsi(close,14)
// Stochastic
lengthStoch = 14
smoothKStoch = 3
smoothDStoch = 3
kStoch = sma(stoch(close, high, low, lengthStoch), smoothKStoch)
dStoch = sma(kStoch, smoothDStoch)
// Commodity Channel Index, CCI
CCI = cci(close, 20)
// Average Directional Index
float adxValue = na, float adxPlus = na, float adxMinus = na
[P, M, V] = dmi(14, 14)
adxValue := V
adxPlus := P
adxMinus := M
// Awesome Oscillator
ao = AO()
// Momentum
Mom = mom(close, 10)
// Moving Average Convergence/Divergence, MACD
[macdMACD, signalMACD, _] = macd(close, 12, 26, 9)
// Stochastic RSI
[Stoch_RSI_K, Stoch_RSI_D] = StochRSI()
// Williams Percent Range
WR = wpr(14)
// Bull / Bear Power
BullPower = high - ema(close, 13)
BearPower = low - ema(close, 13)
// Ultimate Oscillator
UO = uo(7,14,28)
if not na(UO)
UO := UO * 100
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
PriceAvg = ema(close, 50)
DownTrend = close < PriceAvg
UpTrend = close > PriceAvg
// calculate trading recommendation based on SMA/EMA
float ratingMA = 0
float ratingMAC = 0
if not na(SMA10)
ratingMA := ratingMA + calcRatingMA(SMA10, close)
ratingMAC := ratingMAC + 1
if not na(SMA20)
ratingMA := ratingMA + calcRatingMA(SMA20, close)
ratingMAC := ratingMAC + 1
if not na(SMA30)
ratingMA := ratingMA + calcRatingMA(SMA30, close)
ratingMAC := ratingMAC + 1
if not na(SMA50)
ratingMA := ratingMA + calcRatingMA(SMA50, close)
ratingMAC := ratingMAC + 1
if not na(SMA100)
ratingMA := ratingMA + calcRatingMA(SMA100, close)
ratingMAC := ratingMAC + 1
if not na(SMA200)
ratingMA := ratingMA + calcRatingMA(SMA200, close)
ratingMAC := ratingMAC + 1
if not na(EMA10)
ratingMA := ratingMA + calcRatingMA(EMA10, close)
ratingMAC := ratingMAC + 1
if not na(EMA20)
ratingMA := ratingMA + calcRatingMA(EMA20, close)
ratingMAC := ratingMAC + 1
if not na(EMA30)
ratingMA := ratingMA + calcRatingMA(EMA30, close)
ratingMAC := ratingMAC + 1
if not na(EMA50)
ratingMA := ratingMA + calcRatingMA(EMA50, close)
ratingMAC := ratingMAC + 1
if not na(EMA100)
ratingMA := ratingMA + calcRatingMA(EMA100, close)
ratingMAC := ratingMAC + 1
if not na(EMA200)
ratingMA := ratingMA + calcRatingMA(EMA200, close)
ratingMAC := ratingMAC + 1
if not na(HullMA9)
ratingHullMA9 = calcRatingMA(HullMA9, close)
ratingMA := ratingMA + ratingHullMA9
ratingMAC := ratingMAC + 1
if not na(VWMA)
ratingVWMA = calcRatingMA(VWMA, close)
ratingMA := ratingMA + ratingVWMA
ratingMAC := ratingMAC + 1
float ratingIC = na
if not (na(IC_Lead1) or na(IC_Lead2) or na(close) or na(close[1]) or na(IC_BLine) or na(IC_CLine))
ratingIC := calcRating(
IC_Lead1 > IC_Lead2 and close > IC_Lead1 and close < IC_BLine and close[1] < IC_CLine and close > IC_CLine,
IC_Lead2 > IC_Lead1 and close < IC_Lead2 and close > IC_BLine and close[1] > IC_CLine and close < IC_CLine)
if not na(ratingIC)
ratingMA := ratingMA + ratingIC
ratingMAC := ratingMAC + 1
ratingMA := ratingMAC > 0 ? ratingMA / ratingMAC : na
float ratingOther = 0
float ratingOtherC = 0
ratingRSI = RSI
if not(na(ratingRSI) or na(ratingRSI[1]))
ratingOtherC := ratingOtherC + 1
ratingOther := ratingOther + calcRating(ratingRSI < 30 and ratingRSI[1] < ratingRSI, ratingRSI > 70 and ratingRSI[1] > ratingRSI)
if not(na(kStoch) or na(dStoch) or na(kStoch[1]) or na(dStoch[1]))
ratingOtherC := ratingOtherC + 1
ratingOther := ratingOther + calcRating(kStoch < 20 and dStoch < 20 and kStoch > dStoch and kStoch[1] < dStoch[1], kStoch > 80 and dStoch > 80 and kStoch < dStoch and kStoch[1] > dStoch[1])
ratingCCI = CCI
if not(na(ratingCCI) or na(ratingCCI[1]))
ratingOtherC := ratingOtherC + 1
ratingOther := ratingOther + calcRating(ratingCCI < -100 and ratingCCI > ratingCCI[1], ratingCCI > 100 and ratingCCI < ratingCCI[1])
if not(na(adxValue) or na(adxPlus[1]) or na(adxMinus[1]) or na(adxPlus) or na(adxMinus))
ratingOtherC := ratingOtherC + 1
ratingOther := ratingOther + calcRating(adxValue > 20 and adxPlus[1] < adxMinus[1] and adxPlus > adxMinus, adxValue > 20 and adxPlus[1] > adxMinus[1] and adxPlus < adxMinus)
if not(na(ao) or na(ao[1]))
ratingOtherC := ratingOtherC + 1
ratingOther := ratingOther + calcRating(crossover(ao,0) or (ao > 0 and ao[1] > 0 and ao > ao[1] and ao[2] > ao[1]), crossunder(ao,0) or (ao < 0 and ao[1] < 0 and ao < ao[1] and ao[2] < ao[1]))
if not(na(Mom) or na(Mom[1]))
ratingOtherC := ratingOtherC + 1
ratingOther := ratingOther + calcRating(Mom > Mom[1], Mom < Mom[1])
if not(na(macdMACD) or na(signalMACD))
ratingOtherC := ratingOtherC + 1
ratingOther := ratingOther + calcRating(macdMACD > signalMACD, macdMACD < signalMACD)
float ratingStoch_RSI = na
if not(na(DownTrend) or na(UpTrend) or na(Stoch_RSI_K) or na(Stoch_RSI_D) or na(Stoch_RSI_K[1]) or na(Stoch_RSI_D[1]))
ratingStoch_RSI := calcRating(
DownTrend and Stoch_RSI_K < 20 and Stoch_RSI_D < 20 and Stoch_RSI_K > Stoch_RSI_D and Stoch_RSI_K[1] < Stoch_RSI_D[1],
UpTrend and Stoch_RSI_K > 80 and Stoch_RSI_D > 80 and Stoch_RSI_K < Stoch_RSI_D and Stoch_RSI_K[1] > Stoch_RSI_D[1])
if not na(ratingStoch_RSI)
ratingOtherC := ratingOtherC + 1
ratingOther := ratingOther + ratingStoch_RSI
float ratingWR = na
if not(na(WR) or na(WR[1]))
ratingWR := calcRating(WR < -80 and WR > WR[1], WR > -20 and WR < WR[1])
if not na(ratingWR)
ratingOtherC := ratingOtherC + 1
ratingOther := ratingOther + ratingWR
float ratingBBPower = na
if not(na(UpTrend) or na(DownTrend) or na(BearPower) or na(BearPower[1]) or na(BullPower) or na(BullPower[1]))
ratingBBPower := calcRating(
UpTrend and BearPower < 0 and BearPower > BearPower[1],
DownTrend and BullPower > 0 and BullPower < BullPower[1])
if not na(ratingBBPower)
ratingOtherC := ratingOtherC + 1
ratingOther := ratingOther + ratingBBPower
float ratingUO = na
if not(na(UO))
ratingUO := calcRating(UO > 70, UO < 30)
if not na(ratingUO)
ratingOtherC := ratingOtherC + 1
ratingOther := ratingOther + ratingUO
ratingOther := ratingOtherC > 0 ? ratingOther / ratingOtherC : na
float ratingTotal = 0
float ratingTotalC = 0
if not na(ratingMA)
ratingTotal := ratingTotal + ratingMA
ratingTotalC := ratingTotalC + 1
if not na(ratingOther)
ratingTotal := ratingTotal + ratingOther
ratingTotalC := ratingTotalC + 1
ratingTotal := ratingTotalC > 0 ? ratingTotal / ratingTotalC : na
// little piece of @rouxam logic
var bool start_condition = false
float bound = dsc_technicals == "Strong" ? 0.5 : 0.1
if IS_LONG
start_condition := ratingTotal > bound
else
start_condition := ratingTotal < -bound
[start_condition, close]
// ----------------------------------
// (Re-)Initialize
// ----------------------------------
var max_amount = max_amount_for_bot_usage()
var max_dev = max_deviation()
init_price := na(init_price) and within_window() ? open : init_price
latest_price := within_window() ? close : latest_price
// Actualize the start and end time of the backtesting window because number of bars is limited.
// NOTE: limits on number of available bars:
// TradingView FREE account: 5000 bars available,
// TradingView PRO/PRO+ account: 10000 bars available,
// TradingView PREMIUM account: 20000 bars available.
start_time_actual := barstate.isfirst and time > start_time_actual ? time : start_time_actual
end_time_actual := time > end_time_actual and time <= end_time ? time : end_time_actual
if strategy.position_size == 0.0
ttp_extremum := 0.0
ttp_active := false
deal_start_condition := false
// ----------------------------------
// Open deal with Base Order on Deal Start Condition
// ----------------------------------
[dsc_rsi, bo_level_rsi] = security(syminfo.tickerid, dsc_res, rsi_signal())
[dsc_ta, bo_level_ta] = security(syminfo.tickerid, dsc_res, ta_presets_signal())
if(strategy.opentrades == 0 and within_window() and close > 0 and strategy.equity > 0.0)
// Compute deal start condition
if dsc == "Start ASAP"
deal_start_condition := true
bo_level := close
if dsc == "RSI-7"
deal_start_condition := dsc_rsi
bo_level := bo_level_rsi
if dsc == "TV presets"
deal_start_condition := dsc_ta
bo_level := bo_level_ta
if dsc == "Cespanol S/R"
deal_start_condition := lts
bo_level := close
// Place Buy Order
if deal_start_condition
deal_counter := deal_counter + 1
if IS_LONG
strategy.entry("Buy", limit=bo_level, long=strategy.long, qty=base_order_size()/bo_level)
else
strategy.entry("Buy", limit=bo_level, long=strategy.short, qty=base_order_size()/bo_level)
last_so_level := bo_level
// Place Safety Orders
if max_safe_order > 0
for index = 1 to max_safe_order
so_level := safety_order_price(index, last_so_level)
so_name = "SO" + tostring(index)
if IS_LONG
strategy.entry(so_name, long=strategy.long, limit=so_level, qty=safety_order_qty(index)/so_level)
else
strategy.entry(so_name, long=strategy.short, limit=so_level, qty=safety_order_qty(index)/so_level)
last_so_level := so_level
// ----------------------------------
// Close Deal on SL, TP, TTP, or Resistance Test
// ----------------------------------
if abs(strategy.position_size) > 0
take_profit_factor = IS_LONG ? (1 + take_profit) : (1 - take_profit)
stop_loss_factor = IS_LONG ? (1 - stop_loss) : (1 + stop_loss)
ttp_factor = IS_LONG ? (1 - ttp) : (1 + ttp)
stop_level := bo_level * stop_loss_factor
if take_profit_type == "% from total volume"
take_profit_level := strategy.position_avg_price * take_profit_factor
else
take_profit_level := bo_level * take_profit_factor
// Stop Loss
stop_loss_on_bar := false
if stop_loss > max_dev and not ttp_active
if IS_LONG and low < stop_level
stop_loss_counter := stop_loss_counter + 1
strategy.exit(id="x", stop=stop_level, comment="SL")
stop_loss_on_bar := true
else if not IS_LONG and high > stop_level
stop_loss_counter := stop_loss_counter + 1
strategy.exit(id="x", stop=stop_level, comment="SL")
stop_loss_on_bar := true
if not stop_loss_on_bar
if ttp == 0.0
// Simple take profit
strategy.exit(id="x", limit=take_profit_level, comment="TP")
else
// Trailing take profit
if IS_LONG and high >= take_profit_level
ttp_extremum := max(high, ttp_extremum)
ttp_active := true
if not IS_LONG and low <= take_profit_level
ttp_extremum := min(low, ttp_extremum)
ttp_active := true
if ttp_active
ttp_level := ttp_extremum * ttp_factor
strategy.exit(id="x", stop=ttp_level, comment="TTP")
if isLong and ltr
strategy.entry("Sell", strategy.short)
// Cleanup
if (crossunder(strategy.opentrades, 0.5))
strategy.close_all()
strategy.cancel_all()
// ----------------------------------
// Results
// ----------------------------------
profit = max(strategy.equity, 0.0) - strategy.initial_capital
profit_pct = profit / strategy.initial_capital
add_line(the_table, the_row, the_label, the_value, is_warning) =>
// if providing a value, the row is shown as: the_label | the_value
// else: the_label is considered to be a title
is_even = (the_row % 2) == 1
is_title = na(the_value) ? true : false
text = is_title ? "" : tostring(the_value)
bg_color = is_title ? color.black : is_warning ? color.red : is_even ? color.silver : color.white
text_color = is_title ? color.white : color.black
left_cell_align = is_title ? text.align_right : text.align_left
table.cell(the_table, 0, the_row, the_label, bgcolor=bg_color, text_color=text_color, text_size=size.auto, text_halign=left_cell_align)
table.cell(the_table, 1, the_row, text, bgcolor=bg_color, text_color=text_color, text_size=size.auto, text_halign=text.align_right)
var string warnings_text = ""
var warnings = array.new_string(0, "")
if (max_amount / strategy.initial_capital > 1.005 or max_amount / strategy.initial_capital < 0.995)
if order_size_type == "Fixed"
array.push(warnings, "Strategy Initial Capital (currently " + tostring(strategy.initial_capital, currency_format()) + " " + syminfo.currency
+ ") must match Max Amount For Bot Usage (" + tostring(max_amount, currency_format()) + " " + syminfo.currency + ")")
else
array.push(warnings, "Please adjust Base Order and Safe Order percentage to reach 100% of usage of capital. Currently using " + tostring(max_amount / strategy.initial_capital, "#.##%"))
if (max_dev >= 1.0)
array.push(warnings, "Max Price Deviation (" + tostring(max_dev, "#.##%") + ") cannot be >= 100.0%")
if (stop_loss > 0.0 and stop_loss <= max_dev)
array.push(warnings, "Stop Loss (" + tostring(stop_loss, "#.##%") + ") should be greater than Max Price Deviation (" + tostring(max_dev, "#.##%") + ")")
if ((timeframe.isminutes and not (tonumber(timeframe.period) < 30)) or timeframe.isdwm)
array.push(warnings, "Backtesting may be inaccurate. Recommended to use timeframe of 15m or less")
if (ttp >= take_profit)
array.push(warnings, "Trailing Take Profit (" + tostring(ttp, "#.##%") + ") cannot be greater than Take Profit (" + tostring(take_profit, "#.##%") + ")")
// Making the results table
var results_table = table.new(position.top_right, 2, 20, frame_color=color.black)
curr_row = -1
None = int(na)
curr_row += 1, add_line(results_table, curr_row, "Bot setup", None, false)
if (array.size(warnings) > 0)
for index = 1 to array.size(warnings)
curr_row += 1
add_line(results_table, curr_row, "Please review your strategy settings", array.pop(warnings), true)
curr_row += 1, add_line(results_table, curr_row, "Dates", pretty_date(start_time_actual) + " to " + pretty_date(end_time_actual), false)
curr_row += 1, add_line(results_table, curr_row, "Deal Start Condition", dsc, false)
curr_row += 1, add_line(results_table, curr_row, "Base and Safety Orders", "BO: " + tostring(base_order, currency_format()) + " " + (order_size_type == "Fixed" ? "" : "% ") + syminfo.currency + " / " + "SO: " + tostring(safe_order, currency_format()) + " " + (order_size_type == "Fixed" ? "" : "% ") + syminfo.currency, false)
curr_row += 1, add_line(results_table, curr_row, "Price Deviation", tostring(price_deviation, "#.##%"), false)
curr_row += 1, add_line(results_table, curr_row, "Safe Order Scale", "Volume: " + tostring(safe_order_volume_scale) + " / Scale: " + tostring(safe_order_step_scale), false)
curr_row += 1, add_line(results_table, curr_row, "Take Profit / Stop Loss", tostring(take_profit, "#.##%") + (ttp > 0.0 ? "( Trailing: " + tostring(ttp, "#.##%") + ")" : "") + "/ " + (stop_loss > 0.0 ? tostring(stop_loss, "#.##%") : "No Stop Loss"), false)
curr_row += 1, add_line(results_table, curr_row, "Max Amount For Bot Usage", tostring(max_amount, currency_format()) + " " + syminfo.currency, false)
curr_row += 1, add_line(results_table, curr_row, "Max Coverage", tostring(max_safe_order) + " Safety Orders / " + tostring(max_dev, "#.##%"), false)
curr_row += 1, add_line(results_table, curr_row, "Summary", None, false)
curr_row += 1, add_line(results_table, curr_row, "Initial Capital", tostring(strategy.initial_capital, currency_format()) + " " + syminfo.currency, false)
curr_row += 1, add_line(results_table, curr_row, "Final Capital", tostring(max(strategy.equity, 0.0), currency_format()) + " " + syminfo.currency, false)
curr_row += 1, add_line(results_table, curr_row, "Net Result", tostring(profit, currency_format()) + " " + syminfo.currency + " (" + tostring(profit_pct, "#.##%") + ")", false)
curr_row += 1, add_line(results_table, curr_row, "Total Deals", tostring(deal_counter), false)
if stop_loss > 0.0
curr_row += 1, add_line(results_table, curr_row, "Deals Closed on Stop Loss", tostring(stop_loss_counter), false)
if IS_LONG
buy_hold_profit = (latest_price - init_price) / init_price * strategy.initial_capital
buy_hold_profit_pct = buy_hold_profit / strategy.initial_capital
ratio = profit_pct / buy_hold_profit_pct
curr_row += 1, add_line(results_table, curr_row, "Comparison to Buy-And-Hold", None, false)
curr_row += 1, add_line(results_table, curr_row, "Net Result for Buy-and-hold", tostring(buy_hold_profit, currency_format()) + " " + syminfo.currency + " (" + tostring(buy_hold_profit_pct, "#.##%") + ")", false)
curr_row += 1, add_line(results_table, curr_row, "(Bot Performance) / (Buy-and-hold Performance)", tostring(ratio, "#.###"), false)
//End Rouxam
|
Outside Day | https://www.tradingview.com/script/fDlj1Tvf/ | EduardoMattje | https://www.tradingview.com/u/EduardoMattje/ | 50 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © EduardoMattje
//@version=5
strategy("Outside Day", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=50,
process_orders_on_close=true, margin_long=100, margin_short=100)
// Constants
var G_ATR = "ATR settings"
var G_ENTRY = "Entry settings"
var G_EXIT = "Exit settings"
var LONG = "Long"
var SHORT = "Short"
var BOTH = "Both"
// Inputs
var ATR_PERIOD = input.int(20, "Period", 1, inline=G_ATR, group=G_ATR)
var ATR_MULT = input.float(1.0, "Multiplier", minval=0.0, step=0.1, inline=G_ATR, group=G_ATR)
var MAX_BARS = input.int(3, "Max bars with open trading", minval=0,
tooltip="Determine how many bars you can stay with an open position.\nEntries longer than this will automatically be closed.", group=G_ENTRY)
var DIRECTION = input.string(BOTH, "Direction of orders", [BOTH, LONG, SHORT])
var MEAN_REVERSE = input.bool(true, "Mean reverse", tooltip="Entries will be done as a mean reverse, so it will sell at up days, and buy at down days.", group=G_EXIT)
// ATR
var float atr = na
if ATR_MULT != 0.0
atr := ta.atr(ATR_PERIOD) * ATR_MULT
// Conditions
outsideDay = high[0] > high[1] and low[0] < low[1]
outsideLow = close[0] < low[1]
outsideHigh = close[0] > high[1]
// Entry orders
enterLong() => strategy.entry(LONG, strategy.long, when=DIRECTION != SHORT)
enterShort() => strategy.entry(SHORT, strategy.short, when=DIRECTION != LONG)
if not na(atr) or (DIRECTION == BOTH and ATR_MULT == 0)
if outsideDay
if outsideLow
if MEAN_REVERSE
enterLong()
else
enterShort()
else if outsideHigh
if MEAN_REVERSE
enterShort()
else
enterLong()
// Exit orders
var float entryPrice = na
var float longTarget = na
var float shortTarget = na
targetCalc(increment_) => entryPrice + increment_
if strategy.position_size[0] == 0.0
entryPrice := close
longTarget := targetCalc(atr)
shortTarget := targetCalc(-atr)
if ATR_MULT != 0.0
strategy.exit("Long", "Long", limit=longTarget)
strategy.exit("Short", "Short", limit=shortTarget)
daysInTrade = ta.barssince(strategy.opentrades == 0)
exitMessage = "This position has remained open for more than " + str.tostring(MAX_BARS) + " day" + (MAX_BARS > 1 ? "s" : "")
exitLateCond = daysInTrade >= MAX_BARS and MAX_BARS != 0
strategy.close_all(exitLateCond, exitMessage)
// Plots
plotTarget = strategy.position_size > 0 ? longTarget : strategy.position_size < 0 ? shortTarget : na
plotTarget := not exitLateCond[1] and strategy.position_size[1] != 0 ? plotTarget[1] : plotTarget[0]
var color p_color = na
if strategy.position_size > 0
p_color := color.teal
else if strategy.position_size < 0
p_color := color.red
plot(plotTarget, "Take profit", p_color, 2, plot.style_linebr)
|
pomila | https://www.tradingview.com/script/QaU5wFXk-pomila/ | cryptostartegy | https://www.tradingview.com/u/cryptostartegy/ | 19 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © KivancOzbilgic
//@version=4
strategy("pomila", overlay=true)
Periods = input(title="ATR Period", type=input.integer, defval=10)
src = input(hl2, title="Source")
Multiplier = input(title="ATR Multiplier", type=input.float, step=0.1, defval=3.0)
changeATR= input(title="Change ATR Calculation Method ?", type=input.bool, defval=true)
showsignals = input(title="Show Buy/Sell Signals ?", type=input.bool, defval=false)
highlighting = input(title="Highlighter On/Off ?", type=input.bool, defval=true)
barcoloring = input(title="Bar Coloring On/Off ?", type=input.bool, defval=true)
atr2 = sma(tr, Periods)
atr= changeATR ? atr(Periods) : atr2
up=src-(Multiplier*atr)
up1 = nz(up[1],up)
up := close[1] > up1 ? max(up,up1) : up
dn=src+(Multiplier*atr)
dn1 = nz(dn[1], dn)
dn := close[1] < dn1 ? min(dn, dn1) : dn
trend = 1
trend := nz(trend[1], trend)
trend := trend == -1 and close > dn1 ? 1 : trend == 1 and close < up1 ? -1 : trend
upPlot = plot(trend == 1 ? up : na, title="Up Trend", style=plot.style_linebr, linewidth=2, color=color.green)
buySignal = trend == 1 and trend[1] == -1
plotshape(buySignal ? up : na, title="UpTrend Begins", location=location.absolute, style=shape.circle, size=size.tiny, color=color.green, transp=0)
plotshape(buySignal and showsignals ? up : na, title="Buy", text="Buy", location=location.absolute, style=shape.labelup, size=size.tiny, color=color.green, textcolor=color.white, transp=0)
dnPlot = plot(trend == 1 ? na : dn, title="Down Trend", style=plot.style_linebr, linewidth=2, color=color.red)
sellSignal = trend == -1 and trend[1] == 1
plotshape(sellSignal ? dn : na, title="DownTrend Begins", location=location.absolute, style=shape.circle, size=size.tiny, color=color.red, transp=0)
plotshape(sellSignal and showsignals ? dn : na, title="Sell", text="Sell", location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.red, textcolor=color.white, transp=0)
mPlot = plot(ohlc4, title="", style=plot.style_circles, linewidth=0)
longFillColor = highlighting ? (trend == 1 ? color.green : color.white) : color.white
shortFillColor = highlighting ? (trend == -1 ? color.red : color.white) : color.white
fill(mPlot, upPlot, title="UpTrend Highligter", color=longFillColor)
fill(mPlot, dnPlot, title="DownTrend Highligter", color=shortFillColor)
FromMonth = input(defval = 9, title = "From Month", minval = 1, maxval = 12)
FromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31)
FromYear = input(defval = 2018, title = "From Year", minval = 999)
ToMonth = input(defval = 1, title = "To Month", minval = 1, maxval = 12)
ToDay = input(defval = 1, title = "To Day", minval = 1, maxval = 31)
ToYear = input(defval = 9999, title = "To Year", minval = 999)
start = timestamp(FromYear, FromMonth, FromDay, 00, 00)
finish = timestamp(ToYear, ToMonth, ToDay, 23, 59)
window() => time >= start and time <= finish ? true : false
longCondition = buySignal
if (longCondition)
strategy.entry("BUY", strategy.long, when = window())
shortCondition = sellSignal
if (shortCondition)
strategy.entry("SELL", strategy.short, when = window())
buy1= barssince(buySignal)
sell1 = barssince(sellSignal)
color1 = buy1[1] < sell1[1] ? color.green : buy1[1] > sell1[1] ? color.red : na
barcolor(barcoloring ? color1 : na) |
Linear trend | https://www.tradingview.com/script/JlivLSt3-Linear-trend/ | TradingAmmo | https://www.tradingview.com/u/TradingAmmo/ | 91 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TradingAmmo
//@version=4
strategy("Linear trend", overlay=false, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=0.075, currency='USD')
startP = timestamp(input(2017, "Start Year"), input(12, "Month"), input(17, "Day"), 0, 0)
end = timestamp(input(9999, "End Year"), input(1, "Month"), input(1, "Day"), 0, 0)
_testPeriod() =>
iff(time >= startP and time <= end, true, false)
src = close
len1 = input(defval=13, minval=1, title="Fast LR")
len2 = input(defval=55, minval=1, title="Slow LR")
lag1 = input(0, title="Lag for fast")
lag2 = input(0, title="Lag for slow")
threshold = input(0,step=0.5, title="Threshold")
fast_lr = linreg(src, len1, lag1)
slow_lr = linreg(src, len2, lag2)
lr = fast_lr - slow_lr
plot_fast = plot(lr, color = lr > 0 ? color.green : color.red)
plot(threshold, color=color.purple)
long_condition = crossover(lr, threshold) and close > ema(close, 200) and _testPeriod()
strategy.entry('BUY', strategy.long, when=long_condition)
short_condition = crossunder(lr, threshold)
strategy.close('BUY', when=short_condition)
|
Simple/Compounded Returns & Drawdowns Table | https://www.tradingview.com/script/IIkpJ5KR-Simple-Compounded-Returns-Drawdowns-Table/ | antondmt | https://www.tradingview.com/u/antondmt/ | 232 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © antondmt
//@version=5
strategy("Returns & Drawdowns Table", "R & DD", true, calc_on_every_tick = false, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, process_orders_on_close = true)
i_eq_to_dd = input.string("Compound Equity", "Mode", ["Simple Equity", "Compound Equity", "Drawdown"], group = "R & DD Table")
i_precision = input.int(2, "Return Precision", group = "R & DD Table")
i_headers_col = input.color(#D4D4D4, "Headers Color", group = "R & DD Table")
i_headers_text_col = input.color(color.black, "Headers Text Color", group = "R & DD Table")
i_pos_col = input.color(color.green, "Positive Color", group = "R & DD Table")
i_neg_col = input.color(color.red, "Negative Color", group = "R & DD Table")
i_zero_col = input.color(#DDDDDD, "Zero Color", group = "R & DD Table")
i_cell_text_col = input.color(color.white, "Cell Text Color", group = "R & DD Table")
// TIME {
var month_times = array.new_int(0) // Array of all month times
new_month = month(time) != month(time[1])
if(new_month or barstate.isfirst)
array.push(month_times, time)
var year_times = array.new_int(0)
new_year = year(time) != year(time[1])
if (new_year or barstate.isfirst)
array.push(year_times, time)
//}
// SIMPLE EQUITY CALCULATIONS {
// Simple equity is strictly calculated from start to end of each month/year equity. There is no compound
var monthly_simp_pnls = array.new_float(0) // Array of all monthly profits and losses
var yearly_simp_pnls = array.new_float(0)
if(i_eq_to_dd == "Simple Equity")
var initial_monthly_equity = strategy.equity // Starting equity for each month
cur_month_pnl = nz((strategy.equity - initial_monthly_equity) / initial_monthly_equity) // Current month's equity change
if(new_month or barstate.isfirst)
initial_monthly_equity := strategy.equity
array.push(monthly_simp_pnls, cur_month_pnl)
else
array.set(monthly_simp_pnls, array.size(monthly_simp_pnls) - 1, cur_month_pnl)
var initial_yearly_equity = strategy.equity
cur_year_pnl = nz((strategy.equity - initial_yearly_equity) / initial_yearly_equity)
if (new_year or barstate.isfirst)
initial_yearly_equity := strategy.equity
array.push(yearly_simp_pnls, cur_year_pnl)
else
array.set(yearly_simp_pnls, array.size(yearly_simp_pnls) - 1, cur_year_pnl)
// }
// COMPOUND EQUITY CALCULATIONS {
// Compound equity is strictly calculated based on equity state from the beginning of time until the end of each month/year equity. It shows the exact equity movement through time
var monthly_comp_pnls = array.new_float(0) // Array of all monthly profits and losses
var yearly_comp_pnls = array.new_float(0)
if(i_eq_to_dd == "Compound Equity")
var initial_equity = strategy.equity
cur_month_pnl = nz((strategy.equity - initial_equity) / initial_equity) // Current month's equity change
if(new_month or barstate.isfirst)
array.push(monthly_comp_pnls, cur_month_pnl)
else
array.set(monthly_comp_pnls, array.size(monthly_comp_pnls) - 1, cur_month_pnl)
cur_year_pnl = nz((strategy.equity - initial_equity) / initial_equity)
if (new_year or barstate.isfirst)
array.push(yearly_comp_pnls, cur_year_pnl)
else
array.set(yearly_comp_pnls, array.size(yearly_comp_pnls) - 1, cur_year_pnl)
// }
// DRAWDOWN CALCULATIONS {
// Drawdowns are calculated from highest equity to lowest trough for the month/year
var monthly_dds = array.new_float(0) // Array of all monthly drawdowns
var yearly_dds = array.new_float(0)
if (i_eq_to_dd == "Drawdown")
total_equity = strategy.equity - strategy.openprofit
var cur_month_dd = 0.0
var m_ATH = total_equity // Monthly All-Time-High (ATH). It is reset each month
m_ATH := math.max(total_equity, nz(m_ATH[1]))
m_drawdown = -math.abs(total_equity / m_ATH * 100 - 100) / 100 // Drawdown at current bar
if(m_drawdown < cur_month_dd)
cur_month_dd := m_drawdown
if(new_month or barstate.isfirst)
cur_month_dd := 0.0
m_ATH := strategy.equity - strategy.openprofit
array.push(monthly_dds, 0)
else
array.set(monthly_dds, array.size(monthly_dds) - 1, cur_month_dd)
var cur_year_dd = 0.0
var y_ATH = total_equity
y_ATH := math.max(total_equity, nz(y_ATH[1]))
y_drawdown = -math.abs(total_equity / y_ATH * 100 - 100) / 100
if(y_drawdown < cur_year_dd)
cur_year_dd := y_drawdown
if (new_year or barstate.isfirst)
cur_year_dd := 0.0
y_ATH := strategy.equity - strategy.openprofit
array.push(yearly_dds, 0)
else
array.set(yearly_dds, array.size(yearly_dds) - 1, cur_year_dd)
// }
// TABLE LOGIC {
var main_table = table(na)
table.clear(main_table, 0, 0, 13, new_year ? array.size(year_times) - 1 : array.size(year_times))
main_table := table.new(position.bottom_right, columns = 14, rows = array.size(year_times) + 1, border_width = 1)
t_set_headers() => // Sets time headers of the table
// Set month headers
table.cell(main_table, 0, 0, "", text_color = i_headers_text_col, bgcolor = i_headers_col)
table.cell(main_table, 1, 0, "Jan", text_color = i_headers_text_col, bgcolor = i_headers_col)
table.cell(main_table, 2, 0, "Feb", text_color = i_headers_text_col, bgcolor = i_headers_col)
table.cell(main_table, 3, 0, "Mar", text_color = i_headers_text_col, bgcolor = i_headers_col)
table.cell(main_table, 4, 0, "Apr", text_color = i_headers_text_col, bgcolor = i_headers_col)
table.cell(main_table, 5, 0, "May", text_color = i_headers_text_col, bgcolor = i_headers_col)
table.cell(main_table, 6, 0, "Jun", text_color = i_headers_text_col, bgcolor = i_headers_col)
table.cell(main_table, 7, 0, "Jul", text_color = i_headers_text_col, bgcolor = i_headers_col)
table.cell(main_table, 8, 0, "Aug", text_color = i_headers_text_col, bgcolor = i_headers_col)
table.cell(main_table, 9, 0, "Sep", text_color = i_headers_text_col, bgcolor = i_headers_col)
table.cell(main_table, 10, 0, "Oct", text_color = i_headers_text_col, bgcolor = i_headers_col)
table.cell(main_table, 11, 0, "Nov", text_color = i_headers_text_col, bgcolor = i_headers_col)
table.cell(main_table, 12, 0, "Dec", text_color = i_headers_text_col, bgcolor = i_headers_col)
table.cell(main_table, 13, 0, str.tostring(i_eq_to_dd), text_color = i_headers_text_col, bgcolor = i_headers_col)
// Set year headers
for i = 0 to array.size(year_times) - 1
table.cell(main_table, 0, i + 1, str.tostring(year(array.get(year_times, i))), text_color = i_headers_text_col, bgcolor = i_headers_col)
t_set_months() => // Sets inner monthly data of the table
display_array = switch i_eq_to_dd
"Simple Equity" => monthly_simp_pnls
"Compound Equity" => monthly_comp_pnls
=> monthly_dds
for i = 0 to array.size(month_times) - 1
m_row = year(array.get(month_times, i)) - year(array.get(year_times, 0)) + 1
m_col = month(array.get(month_times, i))
m_color = array.get(display_array, i) == 0 ? color.new(i_zero_col, transp = 30) : array.get(display_array, i) > 0 ? color.new(i_pos_col, transp = 30) : color.new(i_neg_col, transp = 30)
table.cell(main_table, m_col, m_row, str.tostring(math.round(array.get(display_array, i) * 100, i_precision)), bgcolor = m_color, text_color = i_cell_text_col)
t_set_years() => // Sets inner yearly data of the table
display_array = switch i_eq_to_dd
"Simple Equity" => yearly_simp_pnls
"Compound Equity" => yearly_comp_pnls
=> yearly_dds
for i = 0 to array.size(year_times) - 1
y_color = array.get(display_array, i) == 0 ? color.new(i_zero_col, transp = 30) : array.get(display_array, i) > 0 ? color.new(i_pos_col, transp = 20) : color.new(i_neg_col, transp = 20)
table.cell(main_table, 13, i + 1, str.tostring(math.round(array.get(display_array, i) * 100, i_precision)), bgcolor = y_color, text_color = i_cell_text_col)
t_set_headers()
t_set_months()
t_set_years()
// }
// PLACE YOUR STRATEGY CODE HERE {
// This is a sample code of a working strategy to show the table in action
fastLength = input(12)
slowlength = input(26)
MACDLength = input(9)
MACD = ta.ema(close, fastLength) - ta.ema(close, slowlength)
aMACD = ta.ema(MACD, MACDLength)
delta = MACD - aMACD
if (ta.crossover(delta, 0))
strategy.entry("MacdLE", strategy.long, comment = "MacdLE")
if (ta.crossunder(delta, 0))
strategy.entry("MacdSE", strategy.short, comment = "MacdSE")
// } |
New Highs-Lows Strategy | https://www.tradingview.com/script/zK0YQ9ou-New-Highs-Lows-Strategy/ | pieroliviermarquis | https://www.tradingview.com/u/pieroliviermarquis/ | 148 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © pieroliviermarquis
//@version=4
strategy(title = "New Highs-Lows", shorttitle="New Highs-Lows Strategy", overlay=false, default_qty_type=strategy.percent_of_equity, default_qty_value=100, calc_on_every_tick=true)
newhigh = security("HIGQ", timeframe.period, close)
newlow = security("LOWQ", timeframe.period, close)
net = newhigh - newlow
sum_ = sum(net, 20)
avg_fast = ema(net, 10)
avg_slow = ema(net, 20)
buy = avg_fast > avg_slow and net > 0
sell = avg_fast < avg_slow and net < 0
plot(net, title="Net NASDAQ", color=net > 0? color.green: color.red, style=plot.style_columns, linewidth=2)
if buy
strategy.entry("Long", strategy.long, comment="")
if sell
strategy.close("Long", comment="", alert_message="")
|
XTZ trading strategy for Bear months | https://www.tradingview.com/script/nhGoViTg-XTZ-trading-strategy-for-Bear-months/ | hugodanielcom | https://www.tradingview.com/u/hugodanielcom/ | 16 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © hugodanielcom
//@version=5
//
// Welcome, this is a strategy for trading XTZ in the Bear months.
//
// It also works in Bull months but loses money versus the Buy&Hold approach
//
import hugodanielcom/PureRebalance/3 as rebalancer
import hugodanielcom/TradingPortfolio/1 as portfolio
strategy("V3", overlay=false, calc_on_order_fills = false, initial_capital = 10000.0)
min_value = input.float(defval = 11.0, title = "Min. Trading Fiat Value", minval = 1.0, maxval = 100.0)
float precision = input.float(defval = 11.5, title = "Rebalance Precision", minval = 1.0, maxval = 100.0)
fromHour = input.int(defval = 1, title = "hh", group = "From", inline="fromClock", minval = 1, maxval = 24)
fromMin = input.int(defval = 0, title = "mm", group = "From", inline="fromClock", minval = 0, maxval = 60)
fromMonth = input.int(defval = 11, title = "MM", group = "From", inline="fromDate", minval = 1, maxval = 12)
fromDay = input.int(defval = 1, title = "DD", group = "From", inline="fromDate", minval = 1, maxval = 31)
fromYear = input.int(defval = 2021, title = "YYYY", group = "From", inline="fromDate", minval = 1970)
thruMonth = input.int(defval = 11, title = "MM", group = "Thru", inline="thruDate", minval = 1, maxval = 12)
thruDay = input.int(defval = 31, title = "DD", group = "Thru", inline="thruDate", minval = 1, maxval = 31)
thruYear = input.int(defval = 2021, title = "YYYY", group = "Thru", inline="thruDate", minval = 1970)
float MIN_AMOUNT = min_value / close
// === FUNCTION EXAMPLE ===
start = timestamp(fromYear, fromMonth, fromDay, fromHour, fromMin) // 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"
rebull_rebear_precision = input.float(defval = 3.0, group = "Bear/Bull Market Indicator", title = "Rebalance when portfolio differs by %", tooltip="Bigger values make the rebalance hold more and become less sensitive to peaks/bottoms and act less often.", minval = 0.1, maxval = 99.9)
rebull_rebear_from_month = fromMonth // input.int(defval = 11, group = "Bear/Bull Market Indicator", title = "Start At Month", minval = 1, maxval = 12)
rebull_rebear_from_day = input.int(defval = 1, group = "Bear/Bull Market Indicator", title = "Start At Day", minval = 1, maxval = 31)
rebull_rebear_from_year = fromYear // input.int(defval = 2021, group = "Bear/Bull Market Indicator", title = "Start At Year", minval = 2020)
rebull_rebear_capital = input.float(defval = 10000.0, group = "Bear/Bull Market Indicator", title = "Initial capital", minval = 1, tooltip="The total portfolio value to start with. A higher value makes the rebalancer more sensitive to peaks/bottoms and act more often")
rebull_rebear_percentage = input.float(defval = 60.0, group = "Bear/Bull Market Indicator", title = "Rebalance Token %", minval = 0.01, maxval = 100.0, tooltip="Percentage of Token / Money.\n60 means the targeted balance is 60% token and 40% money")
rebull_rebear_show_force = input.bool(defval = false, group = "Bear/Bull Market Indicator", title = "Show force")
rebull_rebear_show_opos = input.bool(defval = true, group = "Bear/Bull Market Indicator", title = "Show buy/sell windows of opportunities")
// Backtest start window
rebull_rebear_start = timestamp(rebull_rebear_from_year, rebull_rebear_from_month, rebull_rebear_from_day)
// Function returns true when the current bar time is
// "within the window of time" for this indicator
rebull_rebear_window() => time >= rebull_rebear_start
// The two market trend indicator portfolios
var float[] percentage_portfolio = portfolio.init()
var float[] signal_portfolio = portfolio.init()
// Initialization starts by doing a rebalance at the first bar within
// the window
var bool rebull_rebear_init1 = true
if rebull_rebear_window() and rebull_rebear_init1
// Only do this once, for the first bar, set init1 to false to disallow
// this block from running again
rebull_rebear_init1 := false
first_rebalance_amount = rebalancer.rebalance(close, 0.0, rebull_rebear_capital, rebull_rebear_percentage / 100)
portfolio.set_balance(percentage_portfolio, first_rebalance_amount, rebull_rebear_capital - (first_rebalance_amount * close))
float signal_capital = close*100.0
signal_first_rebalance_amount = rebalancer.rebalance(close, 0.0, signal_capital, rebull_rebear_percentage / 100)
portfolio.set_balance(signal_portfolio, signal_first_rebalance_amount, signal_capital - (signal_first_rebalance_amount * close))
var float signal = 0.0
float signal_rebalance_amount = rebalancer.rebalance(close, portfolio.crypto(signal_portfolio), portfolio.fiat(signal_portfolio), rebull_rebear_percentage / 100.0)
float signal_percentage_change = math.abs(signal_rebalance_amount) / portfolio.crypto(signal_portfolio)
bool signal_is_rebalance_needed = signal_percentage_change >= ((rebull_rebear_precision / 4.0) / 100.0)
bool signal_is_rebalance_buying = signal_is_rebalance_needed and signal_rebalance_amount > 0
bool signal_is_rebalance_selling = signal_is_rebalance_needed and signal_rebalance_amount < 0
// This is where the rebalance gets done
float percentage_rebalance_amount = rebalancer.rebalance(close, portfolio.crypto(percentage_portfolio), portfolio.fiat(percentage_portfolio), rebull_rebear_percentage / 100.0)
// Check if the amount to rebalance is bigger than the percentage
float percentage_change = math.abs(percentage_rebalance_amount) / portfolio.crypto(percentage_portfolio)
bool percentage_is_rebalance_needed = percentage_change >= (rebull_rebear_precision / 100.0)
bool percentage_is_rebalance_buying = percentage_is_rebalance_needed and percentage_rebalance_amount > 0
bool percentage_is_rebalance_selling = percentage_is_rebalance_needed and percentage_rebalance_amount < 0
var int bear_bull_balance = 0
var int bear_balance = 0
var int bull_balance = 0
var int signal_bear_balance = 0
var int signal_bull_balance = 0
var float percentage_signal = 0.0
// Update the percentage portfolio and the signal portfolio number of operations
// and bear/bull market balance. The values calculated here will then be used
// to set the "market_value" and "signal_market_value" below, which are the
// main indicators of the bear/bull market strength.
if rebull_rebear_window()
if percentage_is_rebalance_buying
portfolio.buy(percentage_portfolio, percentage_rebalance_amount, close)
bear_balance += 1
if percentage_is_rebalance_selling
portfolio.sell(percentage_portfolio, math.abs(percentage_rebalance_amount), close)
bull_balance += 1
if signal_is_rebalance_buying
if portfolio.buy(signal_portfolio, signal_rebalance_amount, close)
signal += signal_rebalance_amount
signal_bear_balance += 1
if signal_is_rebalance_selling
if portfolio.sell(signal_portfolio, math.abs(signal_rebalance_amount), close)
signal += signal_rebalance_amount
signal_bull_balance += 1
market_value = bull_balance - bear_balance
signal_market_value = signal_bull_balance - signal_bear_balance
// Store the signal_market_value at the entry point of a new market_value, this
// is used to subtract to the current signal value, useful as an indicator of
// the market force within the current market_value quantity.
var market_value_start = signal_market_value
if market_value[0] != market_value[1]
market_value_start := signal_market_value
// The colors to be used when the market is considered bear or bull
bear_down_color = color.new(color.red, 15)
bear_up_color = color.new(color.red, 15)
bull_down_color = color.new(color.green, 15)
bull_up_color = color.new(color.green, 15)
// A special color to be used when it is neither.
nothing_color = color.new(color.gray, 0)
// By default it is neither:
color market_color = nothing_color
// Look at the market_value and decide which color to use
market_color := nothing_color
bool is_signal_going_up = signal > 0
bool is_signal_going_down = not is_signal_going_up
if market_value > 0 and is_signal_going_up
market_color := bull_up_color
if market_value > 0 and is_signal_going_down
market_color := bull_down_color
if market_value < 0 and is_signal_going_up
market_color := bear_up_color
if market_value < 0 and is_signal_going_down
market_color := bear_down_color
// The market force is the second indicator that this code outputs, it represents
// the tendency of the market to go up or down within a "market_value" block.
force=signal_market_value - market_value_start
// It can be used to find buying and selling windows
bool is_force_selling_opportunity = force > 0 and ((market_value < 0 and force >= 2) or (market_value > 0 and force >= 1))
bool is_force_buying_opportunity = force < 0 and ((market_value < 0 and force <= -2) or (market_value > 0 and force <= -3))
bool is_buying_opportunity = is_force_buying_opportunity or (is_force_buying_opportunity[1] and close[1] >= close[0])
bool is_selling_opportunity = is_force_selling_opportunity or (is_force_selling_opportunity[1] and close[1] <= close[0])
// Paint these extra values if they are being drawn:
color force_color = na
if is_selling_opportunity
force_color := color.new(color.red, 80)
if is_buying_opportunity
force_color := color.new(color.blue, 80)
// The final bear/bull output
bgcolor(rebull_rebear_show_opos ? force_color : na, title="Buy/Sell opportunities")
plot(market_value, "Bear/Bull Strength", color=market_color, style=plot.style_area)
plot(force, "Force", color=rebull_rebear_show_force ? color.orange : na)
hline(0, "Middle Band", color=color.new(#787B86, 50))
////////////////////////////////////////////////////////////////////////////////////
// Rebalancer oscillator
////////////////////////////////////////////////////////////////////////////////////
// Calculate the HODL money in the portfolio - this is necessary because the
// TradingView strategy tester is targeted for single position strategies, which
// is not the case of this one.
var float token_start = 0.0
if window() and token_start == 0.0
token_start := close
var float hold = 0
var float window_close = 0.0
if window()
window_close := close
hold := (strategy.initial_capital / token_start)
float hold_profit = hold * window_close - token_start * hold
plot(hold_profit, "Hold Profit", color=na)
// Arrays to keep track of previous orders (the TradingView strategy object
// works with a single position, this strategy doesn't follow pyramiding or a
// position - these arrays help to keep track of the orders being issued and
// get updated when they get matched by an requivalent upper/lower sale/buy)
var buy_orders_value = array.new_float()
var buy_orders_amount = array.new_float()
var buy_orders_fullfillment = array.new_float()
var sell_orders_value = array.new_float()
var sell_orders_amount = array.new_float()
var sell_orders_fullfillment = array.new_float()
var tmp_fullfillment_indices = array.new_int()
var tmp_fullfillment_amounts = array.new_float()
// Returns [ticker value, total amount sold, amount available]
get_past_unfulfilled_sell(int i) =>
if i >= 0 and i < array.size(sell_orders_value) and i < array.size(sell_orders_amount) and i < array.size(sell_orders_fullfillment)
fullfillment = array.get(sell_orders_fullfillment, i)
if fullfillment < 1.0
initial_amount_sold = array.get(sell_orders_amount, i)
available_amount = initial_amount_sold * (1.0 - fullfillment)
[array.get(sell_orders_value, i), initial_amount_sold, available_amount]
else
[0.0, 0.0, 0.0]
else
[0.0, 0.0, 0.0]
set_fullfillment_amount_in_sell(int i, float amount) =>
[_, initial_sell_amount, sell_available_amount] = get_past_unfulfilled_sell(i)
fullfilled_amount = initial_sell_amount - sell_available_amount
array.set(sell_orders_fullfillment, i, (amount + fullfilled_amount) / initial_sell_amount)
fullfill_sell_at(float value, float fiat_account_balance, int at) =>
amount_to_buy = 0.0
[sell_close, initial_sell_amount, sell_available_amount] = get_past_unfulfilled_sell(at)
if sell_available_amount * value < fiat_account_balance
// Fullfill 100% immediately
amount_to_buy += sell_available_amount
else
// Try to fullfill in parcels
amount_fullfilled = 0.0
total_parcels = 20
for j = 0 to total_parcels-1
current_parcel_amount = j*sell_available_amount/total_parcels
// Do we have fiat enough to buy a parcel this big?
if fiat_account_balance > current_parcel_amount * value
amount_fullfilled := current_parcel_amount
// Fullfill this
amount_to_buy += amount_fullfilled
profit = sell_close * amount_to_buy - value * amount_to_buy
[amount_to_buy, sell_close, profit]
// Tries to buy enough
fullfill_sells_gt(float value, float fiat_account_balance) =>
array.clear(tmp_fullfillment_indices)
array.clear(tmp_fullfillment_amounts)
float profit = 0.0
float amount_to_buy = 0.0
float tmp_fiat_balance = fiat_account_balance
int _size = array.size(sell_orders_value)
if _size > 0 and fiat_account_balance > 1.0
for i = 0 to _size-1
cur_order_value = array.get(sell_orders_value, i)
if cur_order_value > value
[amount_possible, sell_value, order_profit] = fullfill_sell_at(value, tmp_fiat_balance, i)
tmp_fiat_balance -= amount_possible * sell_value
amount_to_buy += amount_possible
profit += order_profit
// Mark this to be fullfilled
array.push(tmp_fullfillment_indices, i)
array.push(tmp_fullfillment_amounts, amount_possible)
[amount_to_buy, profit]
fullfill_oldest_sale(float value, float fiat_account_balance) =>
array.clear(tmp_fullfillment_indices)
array.clear(tmp_fullfillment_amounts)
int _size = array.size(sell_orders_value)
float amount_to_buy = MIN_AMOUNT
bool _is_done = false
if _size > 0
for i = 0 to _size-1
[amount_possible, sell_close, _] = fullfill_sell_at(value, fiat_account_balance, i)
if not _is_done
// This is the percentage of the profit to take in float: 1.XXX
price_adjustment = (1.0 - (sell_close / value)) + 1.0
if amount_possible > 0.0 and amount_possible * price_adjustment < fiat_account_balance
amount_to_buy := amount_possible * price_adjustment
_is_done := true
array.push(tmp_fullfillment_indices, i)
array.push(tmp_fullfillment_amounts, amount_to_buy)
amount_to_buy
else
amount_to_buy := 0.03
else
amount_to_buy
clear_fullfilled_sells() =>
old_sell_orders_value = array.copy(sell_orders_value)
old_sell_orders_amount = array.copy(sell_orders_amount)
old_sell_orders_fullfillment = array.copy(sell_orders_fullfillment)
array.clear(sell_orders_value)
array.clear(sell_orders_amount)
array.clear(sell_orders_fullfillment)
_size = array.size(old_sell_orders_fullfillment)
if _size > 0
for i = 0 to _size-1
if array.get(old_sell_orders_fullfillment, i) < 1.0
array.push(sell_orders_fullfillment, array.get(old_sell_orders_fullfillment, i))
array.push(sell_orders_value, array.get(old_sell_orders_value, i))
array.push(sell_orders_amount, array.get(old_sell_orders_amount, i))
close_buy() =>
_size = array.size(tmp_fullfillment_indices)
if _size > 0
for i = 0 to _size-1
sell_index = array.get(tmp_fullfillment_indices, i)
sell_amount = array.get(tmp_fullfillment_amounts, i)
set_fullfillment_amount_in_sell(sell_index, sell_amount)
clear_fullfilled_sells()
register_sell(value, amount) =>
array.push(sell_orders_value, value)
array.push(sell_orders_amount, amount)
array.push(sell_orders_fullfillment, 0.0)
// Returns [ticker value, total amount sold, amount available]
get_past_unfulfilled_buy(int i) =>
if i >= 0 and i < array.size(buy_orders_value) and i < array.size(buy_orders_amount) and i < array.size(buy_orders_fullfillment)
fullfillment = array.get(buy_orders_fullfillment, i)
if fullfillment < 1.0
initial_amount_bought = array.get(buy_orders_amount, i)
available_amount = initial_amount_bought * (1.0 - fullfillment)
[array.get(buy_orders_value, i), initial_amount_bought, available_amount]
else
[0.0, 0.0, 0.0]
else
[0.0, 0.0, 0.0]
set_fullfillment_amount_in_buy(int i, float amount) =>
[_, initial_buy_amount, buy_available_amount] = get_past_unfulfilled_buy(i)
fullfilled_amount = initial_buy_amount - buy_available_amount
array.set(buy_orders_fullfillment, i, (amount + fullfilled_amount) / initial_buy_amount)
fullfill_buy_at(float value, float fiat_account_balance, int at) =>
amount_to_sell = 0.0
[buy_close, initial_buy_amount, buy_available_amount] = get_past_unfulfilled_buy(at)
if buy_available_amount * value < fiat_account_balance
// Fullfill 100% immediately
amount_to_sell += buy_available_amount
else
// Try to fullfill in parcels
amount_fullfilled = 0.0
total_parcels = 20
for j = 0 to total_parcels-1
current_parcel_amount = j*buy_available_amount/total_parcels
// Do we have fiat enough to buy a parcel this big?
if fiat_account_balance > current_parcel_amount * value
amount_fullfilled := current_parcel_amount
// Fullfill this
amount_to_sell += amount_fullfilled
profit = buy_close * amount_to_sell - value * amount_to_sell
[amount_to_sell, buy_close, profit]
// Tries to buy enough
fullfill_buys_lt(float value, float fiat_account_balance) =>
array.clear(tmp_fullfillment_indices)
array.clear(tmp_fullfillment_amounts)
float profit = 0.0
float amount_to_sell = 0.0
float tmp_fiat_balance = fiat_account_balance
int _size = array.size(buy_orders_value)
if _size > 0 and fiat_account_balance > 1.0
for i = 0 to _size-1
cur_order_value = array.get(buy_orders_value, i)
if cur_order_value < value
[amount_possible, buy_value, order_profit] = fullfill_buy_at(value, tmp_fiat_balance, i)
tmp_fiat_balance -= amount_possible * buy_value
amount_to_sell += amount_possible
profit += order_profit
// Mark this to be fullfilled
array.push(tmp_fullfillment_indices, i)
array.push(tmp_fullfillment_amounts, amount_possible)
[amount_to_sell, profit]
fullfill_oldest_buy(float value, float fiat_account_balance) =>
array.clear(tmp_fullfillment_indices)
array.clear(tmp_fullfillment_amounts)
int _size = array.size(buy_orders_value)
float amount_to_sell = 1.0
bool _is_done = false
if _size > 0
for i = 0 to _size-1
[amount_possible, buy_close, _] = fullfill_buy_at(value, fiat_account_balance, i)
if not _is_done
price_adjustment = (1.0 - (buy_close / value)) + 1.0
if amount_possible > 0.0 and amount_possible * price_adjustment < fiat_account_balance
amount_to_sell := amount_possible * price_adjustment
_is_done := true
array.push(tmp_fullfillment_indices, i)
array.push(tmp_fullfillment_amounts, amount_to_sell)
amount_to_sell
else
amount_to_sell := 0.03
else
amount_to_sell
clear_fullfilled_buys() =>
old_buy_orders_value = array.copy(buy_orders_value)
old_buy_orders_amount = array.copy(buy_orders_amount)
old_buy_orders_fullfillment = array.copy(buy_orders_fullfillment)
array.clear(buy_orders_value)
array.clear(buy_orders_amount)
array.clear(buy_orders_fullfillment)
_size = array.size(old_buy_orders_fullfillment)
if _size > 0
for i = 0 to _size-1
if array.get(old_buy_orders_fullfillment, i) < 1.0
array.push(buy_orders_fullfillment, array.get(old_buy_orders_fullfillment, i))
array.push(buy_orders_value, array.get(old_buy_orders_value, i))
array.push(buy_orders_amount, array.get(old_buy_orders_amount, i))
close_sell() =>
_size = array.size(tmp_fullfillment_indices)
if _size > 0
for i = 0 to _size-1
buy_index = array.get(tmp_fullfillment_indices, i)
buy_amount = array.get(tmp_fullfillment_amounts, i)
set_fullfillment_amount_in_buy(buy_index, buy_amount)
clear_fullfilled_buys()
register_buy(value, amount) =>
array.push(buy_orders_value, value)
array.push(buy_orders_amount, amount)
array.push(buy_orders_fullfillment, 0.0)
// Virtual Portfolio (useful to get the rebalancer buy/sell points without
// suffering interference from the real buy/sales being done)
var float[] virtual = portfolio.init()
// The Real Portfolio
var float[] balance = portfolio.init()
buy_order(float amount) =>
strategy.order("buy", strategy.long, amount, when = window(), alert_message = str.tostring(amount))
sell_order(float amount) =>
strategy.order("sell", strategy.short, amount, when = window(), alert_message = str.tostring(-amount))
// Initialization starts by buying MIN_AMOUNT token and selling it right away.
// this is to ensure proper values in the Strategy Tester that start at the
// first block. Strategy Tester by default starts at the block of the first
// order - a buy/sell order is done on the first block so that it starts at it.
var init1 = true
var init2 = false
var init3 = false
var first_full_amount = MIN_AMOUNT
var last_rebalance_at = 0
ratio_of_first_rebalance = 0.5
float capital = float(strategy.initial_capital[0])
// Start by selling enough crypto to have this
// amount of fiat
fiat_offset = 2000
on_the_side = 0
if window() and init1
init1 := false
init2 := true
strategy.order("buy", strategy.long, first_full_amount, when = window())
init1
else if window() and init2
init2 := false
init3 := true
strategy.order("sell", strategy.short, first_full_amount, when = window())
init2
else if window() and init3
init3 := false
first_rebalance_amount = rebalancer.rebalance(close, 0.0, capital, ratio_of_first_rebalance)
portfolio.set_balance(virtual, first_rebalance_amount, strategy.initial_capital - (first_rebalance_amount * close))
// first_amount_to_buy = (strategy.initial_capital - fiat_offset) / close // 100% crypto - offset
// Start with `offset` FIAT on the side
initial_crypto = (strategy.initial_capital - fiat_offset) / close
portfolio.set_balance(balance, initial_crypto, fiat_offset + on_the_side)
// last_rebalance_at := month(time)
// strategy.order("buy", strategy.long, first_rebalance_amount, when = window(), alert_message = str.tostring(first_rebalance_amount))
init3
// Adjust the precision to the current token value,
// This way the amount to rebalance is adjusted to be meaningful in very high
// value tokens, or very low value tokens
float token_adjustment = 2000.0 / (strategy.initial_capital / close)
// The virtual portfolio is frequently rebalanced at 60% crypto
// this allows it to be used to output buy/sales points while the real
// portfolio gets messed up with the trading action
// amount = portfolio.get_rebalance_amount(virtual, 0.60, close)
float virtual_amount = window() ? rebalancer.rebalance(close, portfolio.crypto(virtual), portfolio.fiat(virtual), 0.60) : 0.0
color virtual_rebalance_color = na
bool is_rebalance_selling = virtual_amount * token_adjustment < -precision
bool is_rebalance_buying = virtual_amount * token_adjustment > precision
if window()
if is_rebalance_buying
portfolio.buy(virtual, virtual_amount, close)
virtual_rebalance_color := color.new(color.teal, 80)
if is_rebalance_selling
portfolio.sell(virtual, math.abs(virtual_amount), close)
virtual_rebalance_color := color.new(color.maroon, 80)
bgcolor(window() ? virtual_rebalance_color : na, title="Buy/Sell Bar")
////////////////////////////////////////////////////////////////////////////////
// MAIN - balance = portfolio.init()
////////////////////////////////////////////////////////////////////////////////
bool is_selling_opportunity_finished = (not is_selling_opportunity) and is_selling_opportunity[1]
bool is_buying_opportunity_finished = (not is_buying_opportunity) and is_buying_opportunity[1]
bool is_selling_opportunity_starting = (not is_selling_opportunity[1]) and is_selling_opportunity[0]
bool is_buying_opportunity_starting = (not is_buying_opportunity[1]) and is_buying_opportunity[0]
buy(portfolio, amount, value) =>
[prev_sold_amount, profit_if_bought] = fullfill_sells_gt(value*1.12, portfolio.fiat(balance))
if math.abs(amount) > MIN_AMOUNT
if portfolio.buy(portfolio, math.abs(amount) + math.abs(prev_sold_amount), value)
buy_order(math.abs(amount) + math.abs(prev_sold_amount))
register_buy(value, math.abs(amount))
close_buy()
sell(portfolio, amount, value) =>
[prev_bought_amount, profit_if_sold] = fullfill_buys_lt(value*0.88, portfolio.fiat(balance))
if math.abs(amount) > MIN_AMOUNT
if portfolio.sell(portfolio, math.abs(amount) + math.abs(prev_bought_amount), value)
sell_order(math.abs(amount) + math.abs(prev_bought_amount))
register_sell(value, math.abs(amount))
close_sell()
var bool has_pending_sell = false
var bool has_pending_buy = false
if is_rebalance_selling and is_selling_opportunity
has_pending_sell := true
if is_rebalance_buying and is_buying_opportunity
has_pending_buy := true
bool buy_now = false
bool sell_now = false
float default_ratio = market_value > 0 ? 0.8 : (market_value < 0 ? 0.6 : 0.7)
float rebalance_ratio = default_ratio
// Overall performance of this strategy
float strategy_total = portfolio.fiat(balance) + portfolio.crypto(balance) * window_close
float vs_hold = (strategy_total + portfolio.retained(balance)) - (hold * window_close)
float did_profit = (portfolio.retained(balance) + strategy_total) - strategy.initial_capital
///////////////
// Positions //
///////////////
// [amount, value]
var float[] bought = array.new_float(8, 0.0)
var float[] sold = array.new_float(8, 0.0)
var int position_at = 0 // index
int POSITION_NO_ACTION = 0
int POSITION_BUYING = 1
int POSITION_SELLING = 2
var int position_state = POSITION_NO_ACTION
var int sell_signal_count = 0
var int buy_signal_count = 0
int NEEDED_BUY_SIGNALS = 5
int NEEDED_SELL_SIGNALS = 5
// Amount of portfolio to buy/sell at each position
float AMOUNT_PERCENTAGE = 9.0/100.0
float PROFIT_MARGIN = 8.0/100.0
///////////////
// Actions
///////////////
// Close At Start records the `close` value at the start of a market trend (bear/bull)
var float close_at_start = 0
// The maximum bull strength found:
var int max_market_value = 0
if market_value > max_market_value
max_market_value := market_value
// BEAR MARKET STRATEGY:
if market_value < 0
// Don't rebalance in Bear Market
buy_now := false
sell_now := false
if is_buying_opportunity_starting or is_buying_opportunity_finished
close_at_start := close
///////////////
/// SELLING
float margin = PROFIT_MARGIN / 2.0
if (not is_selling_opportunity) and is_rebalance_buying and (close_at_start*(1.0 + margin)) <= close
float sell_amount = portfolio.crypto(balance)*AMOUNT_PERCENTAGE
sell(balance, sell_amount, close)
//////////////
/// BUYING
if is_buying_opportunity and is_rebalance_buying and (close_at_start*(1.0 - margin)) >= close
float buy_amount = (portfolio.fiat(balance)/close) * AMOUNT_PERCENTAGE
buy(balance, buy_amount, close)
// BULL MARKET:
if market_value > 0
// Don't rebalance in Bull Market
buy_now := false
sell_now := false
if is_selling_opportunity_starting or is_selling_opportunity_finished
close_at_start := close
///////////////
/// SELLING
float margin = PROFIT_MARGIN
if is_selling_opportunity and is_rebalance_selling and (close_at_start*(1.0 + margin)) <= close
float sell_amount = portfolio.crypto(balance)*AMOUNT_PERCENTAGE
sell(balance, sell_amount, close)
//////////////
/// BUYING
if (not is_selling_opportunity) and is_rebalance_buying and (close_at_start*(1.0 - margin)) >= close
float buy_amount = (portfolio.fiat(balance)/close) * AMOUNT_PERCENTAGE
buy(balance, buy_amount, close)
// Buy 99% crypto when entering
if market_value[1] == 0
sell_now := false
buy_now := true
rebalance_ratio := 0.99
// NEUTRAL MARKET
if market_value == 0
buy_now := false
sell_now := false
position_at := 0
array.clear(bought)
array.clear(sold)
// Sell 70% of crypto when entering from BULL (i.e. going down)
if market_value[1] == 1 and did_profit < 0.0 // Only sell if bleeding cash
sell_now := true
buy_now := false
rebalance_ratio := 0.3
////////////////////////////////////////
// Rebalance buy_now/sell_now signals //
////////////////////////////////////////
float unbalanced_amount = window() ? rebalancer.rebalance(close, portfolio.crypto(balance), portfolio.fiat(balance), rebalance_ratio) : 0.0
float abs_unbalanced_amount = math.abs(unbalanced_amount)
if sell_now and MIN_AMOUNT <= abs_unbalanced_amount
// SELL NOW
sell(balance, abs_unbalanced_amount, close)
has_pending_sell := false
if buy_now and MIN_AMOUNT <= abs_unbalanced_amount
// BUY NOW
buy(balance, abs_unbalanced_amount, close)
has_pending_buy := false
//////////////////////////////////////////////////////////////////////////////
// ANALYSIS
//////////////////////////////////////////////////////////////////////////////
plot(portfolio.fiat(balance) + portfolio.retained(balance), title = "Fiat in Balance")
plot(portfolio.crypto(balance), title = "Crypto in Balance")
plot( did_profit, title = "Did Profit? (dif. from initial capital)", color = ((portfolio.retained(balance) + strategy_total) - strategy.initial_capital) > 0 ? color.green : color.red)
plot(vs_hold, title = "Total profit vs Hold (in Fiat)", color = (vs_hold > 0 ? color.green : color.red))
|
MZ SRSI Strategy V1.0 | https://www.tradingview.com/script/GcZaI7pn-MZ-SRSI-Strategy-V1-0/ | MightyZinger | https://www.tradingview.com/u/MightyZinger/ | 221 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © MightyZinger
//@version=4
strategy(shorttitle="MZ SRSI",title="MightyZinger SRSI Strategy", overlay=false, pyramiding=1, calc_on_order_fills=true, calc_on_every_tick=true, default_qty_type=strategy.fixed, default_qty_value=5,commission_value=0.1)
//heiking ashi calculation
UseHAcandles = input(true, title="Use Heikin Ashi Candles in Algo Calculations")
////
// === /INPUTS ===
// === BASE FUNCTIONS ===
haClose = UseHAcandles ? security(heikinashi(syminfo.tickerid), timeframe.period, close) : close
haOpen = UseHAcandles ? security(heikinashi(syminfo.tickerid), timeframe.period, open) : open
haHigh = UseHAcandles ? security(heikinashi(syminfo.tickerid), timeframe.period, high) : high
haLow = UseHAcandles ? security(heikinashi(syminfo.tickerid), timeframe.period, low) : low
//Backtest dates
fromMonth = input(defval = 1, title = "From Month", type = input.integer, minval = 1, maxval = 12)
fromDay = input(defval = 1, title = "From Day", type = input.integer, minval = 1, maxval = 31)
fromYear = input(defval = 2021, title = "From Year", type = input.integer, minval = 1970)
thruMonth = input(defval = 12, title = "Thru Month", type = input.integer, minval = 1, maxval = 12)
thruDay = input(defval = 30, title = "Thru Day", type = input.integer, minval = 1, maxval = 31)
thruYear = input(defval = 2021, 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"
src = UseHAcandles ? haClose : input(close, title="Source")
TopBand = input(80, step=0.01)
LowBand = input(20, step=0.01)
lengthRSI = input(2, minval=1,title="RSI Length")
lengthMA = input(50, minval=1,title="MA Length")
lengthRSI_MA= input(5, minval=1,title="RSI MA Length")
//RSI Source
maType = input(title="MA Type", type=input.string, defval="LRC", options=["SMA","EMA","DEMA","TEMA","LRC","WMA","MF","VAMA","TMA","HMA", "JMA", "Kijun v2", "EDSMA","McGinley"])
rsiMaType = input(title="RSI MA Type", type=input.string, defval="TMA", options=["SMA","EMA","DEMA","TEMA","LRC","WMA","MF","VAMA","TMA","HMA", "JMA", "Kijun v2", "EDSMA","McGinley"])
//MA Function
// Pre-reqs
//
tema(src, len) =>
ema1 = ema(src, len)
ema2 = ema(ema1, len)
ema3 = ema(ema2, len)
(3 * ema1) - (3 * ema2) + ema3
kidiv = input(defval=1,maxval=4, title="Kijun MOD Divider")
jurik_phase = input(title="* Jurik (JMA) Only - Phase", type=input.integer, defval=3)
jurik_power = input(title="* Jurik (JMA) Only - Power", type=input.integer, defval=1)
volatility_lookback = input(10, title="* Volatility Adjusted (VAMA) Only - Volatility lookback length")
// MF
beta = input(0.8,minval=0,maxval=1,step=0.1, title="Modular Filter, General Filter Only - Beta")
feedback = input(false, title="Modular Filter Only - Feedback")
z = input(0.5,title="Modular Filter Only - Feedback Weighting",step=0.1, minval=0, maxval=1)
//EDSMA
ssfLength = input(title="EDSMA - Super Smoother Filter Length", type=input.integer, minval=1, defval=20)
ssfPoles = input(title="EDSMA - Super Smoother Filter Poles", type=input.integer, defval=2, options=[2, 3])
//----
// EDSMA
get2PoleSSF(src, length) =>
PI = 2 * asin(1)
arg = sqrt(2) * PI / length
a1 = exp(-arg)
b1 = 2 * a1 * cos(arg)
c2 = b1
c3 = -pow(a1, 2)
c1 = 1 - c2 - c3
ssf = 0.0
ssf := c1 * src + c2 * nz(ssf[1]) + c3 * nz(ssf[2])
get3PoleSSF(src, length) =>
PI = 2 * asin(1)
arg = PI / length
a1 = exp(-arg)
b1 = 2 * a1 * cos(1.738 * arg)
c1 = pow(a1, 2)
coef2 = b1 + c1
coef3 = -(c1 + b1 * c1)
coef4 = pow(c1, 2)
coef1 = 1 - coef2 - coef3 - coef4
ssf = 0.0
ssf := coef1 * src + coef2 * nz(ssf[1]) + coef3 * nz(ssf[2]) + coef4 * nz(ssf[3])
// MA Main function
ma(type, src, len) =>
float result = 0
if type=="TMA"
result := sma(sma(src, ceil(len / 2)), floor(len / 2) + 1)
if type=="MF"
ts=0.,b=0.,c=0.,os=0.
//----
alpha = 2/(len+1)
a = feedback ? z*src + (1-z)*nz(ts[1],src) : src
//----
b := a > alpha*a+(1-alpha)*nz(b[1],a) ? a : alpha*a+(1-alpha)*nz(b[1],a)
c := a < alpha*a+(1-alpha)*nz(c[1],a) ? a : alpha*a+(1-alpha)*nz(c[1],a)
os := a == b ? 1 : a == c ? 0 : os[1]
//----
upper = beta*b+(1-beta)*c
lower = beta*c+(1-beta)*b
ts := os*upper+(1-os)*lower
result := ts
if type=="LRC"
result := linreg(src, len, 0)
if type=="SMA" // Simple
result := sma(src, len)
if type=="EMA" // Exponential
result := ema(src, len)
if type=="DEMA" // Double Exponential
e = ema(src, len)
result := 2 * e - ema(e, len)
if type=="TEMA" // Triple Exponential
e = ema(src, len)
result := 3 * (e - ema(e, len)) + ema(ema(e, len), len)
if type=="WMA" // Weighted
result := wma(src, len)
if type=="VAMA" // Volatility Adjusted
/// Copyright © 2019 to present, Joris Duyck (JD)
mid=ema(src,len)
dev=src-mid
vol_up=highest(dev,volatility_lookback)
vol_down=lowest(dev,volatility_lookback)
result := mid+avg(vol_up,vol_down)
if type=="HMA" // Hull
result := wma(2 * wma(src, len / 2) - wma(src, len), round(sqrt(len)))
if type=="JMA" // Jurik
/// Copyright © 2018 Alex Orekhov (everget)
/// Copyright © 2017 Jurik Research and Consulting.
phaseRatio = jurik_phase < -100 ? 0.5 : jurik_phase > 100 ? 2.5 : jurik_phase / 100 + 1.5
beta = 0.45 * (len - 1) / (0.45 * (len - 1) + 2)
alpha = pow(beta, jurik_power)
jma = 0.0
e0 = 0.0
e0 := (1 - alpha) * src + alpha * nz(e0[1])
e1 = 0.0
e1 := (src - e0) * (1 - beta) + beta * nz(e1[1])
e2 = 0.0
e2 := (e0 + phaseRatio * e1 - nz(jma[1])) * pow(1 - alpha, 2) + pow(alpha, 2) * nz(e2[1])
jma := e2 + nz(jma[1])
result := jma
if type=="Kijun v2"
kijun = avg(lowest(len), highest(len))//, (open + close)/2)
conversionLine = avg(lowest(len/kidiv), highest(len/kidiv))
delta = (kijun + conversionLine)/2
result :=delta
if type=="McGinley"
mg = 0.0
mg := na(mg[1]) ? ema(src, len) : mg[1] + (src - mg[1]) / (len * pow(src/mg[1], 4))
result :=mg
if type=="EDSMA"
zeros = src - nz(src[2])
avgZeros = (zeros + zeros[1]) / 2
// Ehlers Super Smoother Filter
ssf = ssfPoles == 2
? get2PoleSSF(avgZeros, ssfLength)
: get3PoleSSF(avgZeros, ssfLength)
// Rescale filter in terms of Standard Deviations
stdev = stdev(ssf, len)
scaledFilter = stdev != 0
? ssf / stdev
: 0
alpha = 5 * abs(scaledFilter) / len
edsma = 0.0
edsma := alpha * src + (1 - alpha) * nz(edsma[1])
result := edsma
result
//Indicator
hline(TopBand, color=color.red,linestyle=hline.style_dotted, linewidth=2)
hline(LowBand, color=color.green, linestyle=hline.style_dashed, linewidth=2)
// RSI Definition
rsiSource = ma(maType, src , lengthMA)
frsi = rsi(rsiSource, lengthRSI)
fsma = ma(rsiMaType, frsi , lengthRSI_MA)
plot(frsi,title='frsi', color= color.lime, linewidth=3)
fsmaColor=color.new(color.red, 80)
plot(fsma,title='fsma', color= fsmaColor , linewidth=3, style=plot.style_area)
//Background
bgcolor(frsi > fsma ? color.lime : color.orange, 80)
longcondition = crossover (frsi , fsma)
shortcondition = crossunder(frsi , fsma)
////////////////////////////////
//if (longcondition)
// strategy.entry("BUY", strategy.long, when = window())
//if (shortcondition)
// strategy.close("SELL", strategy.short, when = window())
strategy.entry(id="long", long = true, when = longcondition and window())
strategy.close("long", when = shortcondition and window()) |
Two Moving Average Cross test | https://www.tradingview.com/script/LxJV6uyx-Two-Moving-Average-Cross-test/ | darkbrewery | https://www.tradingview.com/u/darkbrewery/ | 15 | 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/
// © darkbrewery
// @version=5
// Huge Thank-you to SGJoe and DTKing for their help!
// Ehlers / Kaufman Code borrowed from Franklin Moormann (cheatcountry)
strategy("Two Moving Average Cross", "2MAX", true, default_qty_value = 100, default_qty_type = strategy.percent_of_equity, initial_capital=1000, commission_value = 0.08)
// ---- User Inputs ----
Timeframe = input.timeframe( '','TimeFrame', inline='top')
Repaint = input( false,'Allow Repainting', inline='top')
MA_T1 = input.string( "Exponential", "Fast", ["Simple","Exponential","Double Exponential","Triple Exponential","Quadruple Exponential","Weighted","Volume-weighted","Hull","Symmetrical","Arnaud Legoux","Welles Wilder","Triangular","Least Squares","Relative Strength","Ehlers Kaufman"], inline="MA", group="Moving Averages")
MA_S1_Input = input.source( close, "Src", inline="MA", group="Moving Averages")
MA_L1 = input.int( 20, "Len", 1, 200, inline="MA", group="Moving Averages")
MA_T2 = input.string( "Exponential", "Slow", ["Simple","Exponential","Double Exponential","Triple Exponential","Quadruple Exponential","Weighted","Volume-weighted","Hull","Symmetrical","Arnaud Legoux","Welles Wilder","Triangular","Least Squares","Relative Strength","Ehlers Kaufman"], inline="MA2", group="Moving Averages")
MA_S2_Input = input.source( close, "Src", inline="MA2", group="Moving Averages")
MA_L2 = input.int( 50,"Len", 1, 200, inline="MA2", group="Moving Averages")
MA_S1 = request.security(syminfo.tickerid, Timeframe, MA_S1_Input[Repaint ? 0 : barstate.isrealtime ? 1 : 0])[Repaint ? 0 : barstate.isrealtime ? 0 : 1]
MA_S2 = request.security(syminfo.tickerid, Timeframe, MA_S2_Input[Repaint ? 0 : barstate.isrealtime ? 1 : 0])[Repaint ? 0 : barstate.isrealtime ? 0 : 1]
// ---- RSI Inputs ----
RSI_Length = input.int(9, "RSI Length", inline="RSI", group="RSI")
RSI_Source = input.source(close, "RSI Source", inline="RSI", group="RSI")
MinRSI = input.int(39,"Min RSI", inline="RSI", group="RSI")
MaxRSI = input.int(80,"Max RSI", inline="RSI", group="RSI")
// ---- Strategy Inputs ----
Stop_Perc = input.float(10, "Stop %", inline="Strat", group="Strategy")
Stop_Multi = (Stop_Perc - 100) * -0.01
// ---- Calculate Moving Averages ----
MA_1 = switch MA_T1
"Simple" => ta.sma(MA_S1,MA_L1)
"Exponential" => ta.ema(MA_S1,MA_L1)
"Double Exponential" => 2 * ta.ema(MA_S1, MA_L1) - ta.ema(ta.ema(MA_S1, MA_L1), MA_L1)
"Triple Exponential" => 3 * (ta.ema(MA_S1, MA_L1) - ta.ema(ta.ema(MA_S1, MA_L1), MA_L1)) + ta.ema(ta.ema(ta.ema(MA_S1, MA_L1), MA_L1), MA_L1)
"Quadruple Exponential" => 5 * ta.ema(MA_S1,MA_L1) - 10 * ta.ema(ta.ema(MA_S1, MA_L1), MA_L1) + 10 * ta.ema(ta.ema(ta.ema(MA_S1, MA_L1), MA_L1), MA_L1) - 5 * ta.ema(ta.ema(ta.ema(ta.ema(MA_S1, MA_L1), MA_L1), MA_L1), MA_L1) + ta.ema(ta.ema(ta.ema(ta.ema(ta.ema(MA_S1, MA_L1), MA_L1), MA_L1), MA_L1), MA_L1)
"Weighted" => ta.wma(MA_S1,MA_L1)
"Volume-weighted" => ta.vwma(MA_S1,MA_L1)
"Hull" => ta.hma(MA_S1,MA_L1)
"Symmetrical" => ta.swma(MA_S1)
"Arnaud Legoux" => ta.alma(MA_S1, MA_L1, 0.85, 6)
"Least Squares" => ta.linreg(MA_S1, MA_L1, 0)
"Relative Strength" => ta.rma(MA_S1,MA_L1)
"Welles Wilder" =>
Wilder_MA1 = .0
Wilder_MA1 := 1 / MA_L1 * MA_S1 + (1 - 1 / MA_L1) * nz(Wilder_MA1[1])
"Triangular" => ta.sma(ta.sma(MA_S1,MA_L1),MA_L1)
"Ehlers Kaufman" =>
KA_D1 = .0
for int i = 0 to MA_L1 - 1 by 1
KA_D1 += math.abs(nz(MA_S1[i]) - nz(MA_S1[i + 1]))
KA_EF1 = KA_D1 != 0 ? math.min(math.abs(MA_S1 - nz(MA_S1[MA_L1 - 1])) / KA_D1, 1) : 0
KAMA1 = .0
KAMA1 := (math.pow((0.6667 * KA_EF1) + 0.0645, 2) * MA_S1) + ((1 - math.pow((0.6667 * KA_EF1) + 0.0645, 2)) * nz(KAMA1[1]))
MA_2 = switch MA_T2
"Simple" => ta.sma(MA_S2,MA_L2)
"Exponential" => ta.ema(MA_S2,MA_L2)
"Double Exponential" => 2 * ta.ema(MA_S2, MA_L2) - ta.ema(ta.ema(MA_S2, MA_L2), MA_L2)
"Triple Exponential" => 3 * (ta.ema(MA_S2, MA_L2) - ta.ema(ta.ema(MA_S2, MA_L2), MA_L2)) + ta.ema(ta.ema(ta.ema(MA_S2, MA_L2), MA_L2), MA_L2)
"Quadruple Exponential" => 5 * ta.ema(MA_S2,MA_L2) - 10 * ta.ema(ta.ema(MA_S2, MA_L2), MA_L2) + 10 * ta.ema(ta.ema(ta.ema(MA_S2, MA_L2), MA_L2), MA_L2) - 5 * ta.ema(ta.ema(ta.ema(ta.ema(MA_S2, MA_L2), MA_L2), MA_L2), MA_L2) + ta.ema(ta.ema(ta.ema(ta.ema(ta.ema(MA_S2, MA_L2), MA_L2), MA_L2), MA_L2), MA_L2)
"Weighted" => ta.wma(MA_S2,MA_L2)
"Volume-weighted" => ta.vwma(MA_S2,MA_L2)
"Hull" => ta.hma(MA_S2,MA_L2)
"Symmetrical" => ta.swma(MA_S2)
"Arnaud Legoux" => ta.alma(MA_S2, MA_L2, 0.85, 6)
"Least Squares" => ta.linreg(MA_S2, MA_L2, 0)
"Relative Strength" => ta.rma(MA_S2,MA_L2)
"Welles Wilder" =>
Wilder_MA2 = .0
Wilder_MA2 := 1 / MA_L2 * MA_S2 + (1 - 1 / MA_L2) * nz(Wilder_MA2[1])
"Triangular" => ta.sma(ta.sma(MA_S2,MA_L2),MA_L2)
"Ehlers Kaufman" =>
KA_D2 = .0
for int i = 0 to MA_L2 - 1 by 1
KA_D2 += math.abs(nz(MA_S2[i]) - nz(MA_S2[i + 1]))
KA_EF2 = KA_D2 != 0 ? math.min(math.abs(MA_S2 - nz(MA_S2[MA_L2 - 1])) / KA_D2, 1) : 0
KAMA2 = .0
KAMA2 := (math.pow((0.6667 * KA_EF2) + 0.0645, 2) * MA_S2) + ((1 - math.pow((0.6667 * KA_EF2) + 0.0645, 2)) * nz(KAMA2[1]))
// ---- Plot Moving Averages ----
plot(MA_1, title="Fast MA", color=color.yellow)
plot(MA_2, title="Slow MA", color=color.blue)
// ---- Moving Average Crossovers ----
Show_MA_Cross = input.bool(false, "Show Crossings")
Bull_MA_Cross = ta.crossover(MA_1,MA_2)
Bear_MA_Cross = ta.crossover(MA_2,MA_1)
plotshape(Bull_MA_Cross and Show_MA_Cross, "Bullish Cross", shape.triangleup, location.belowbar, color.green, size="small")
plotshape(Bear_MA_Cross and Show_MA_Cross, "Bearish Cross", shape.triangledown, location.abovebar, color.red, size="small")
// ---- Strategy ----
Longcond1 = ta.crossover(MA_1, MA_2)
Longcond2 = ta.rsi(close,RSI_Length) > MinRSI
Exitcond1 = ta.crossover(MA_2, MA_1)
Exitcond2 = ta.rsi(RSI_Source,RSI_Length) < MinRSI
Exitcond3 = ta.rsi(RSI_Source,RSI_Length) > MaxRSI
InPos = strategy.position_size > 0
NoPos = strategy.position_size <=0
TimePeriod = time >= timestamp(syminfo.timezone, 2020, 1, 1, 0, 0)
if (TimePeriod and Longcond1 and Longcond2 and NoPos)
strategy.entry("Long", strategy.long)
stoploss = low * Stop_Multi
strategy.exit("Exit", "Long", stop=stoploss)
if (Exitcond1 and Exitcond2 and InPos) or (Exitcond3 and InPos)
strategy.close("Long") |
Simple scalping strategy for SOL | https://www.tradingview.com/script/QeCFrzFP-Simple-scalping-strategy-for-SOL/ | hugodanielcom | https://www.tradingview.com/u/hugodanielcom/ | 100 | 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/
// © hugodanielcom
//@version=5
//
// Welcome, this is a simple scalping strategy for trading SOL.
//
// It works well for the Bear months (check Nov.) but considerably underperforms Buy&Hold for the Bull months.
//
// It tries to do a market operation per candle whenever the candle happens in a buy/sell trading window of the
// Rebalance Bear/Bull indicator (https://www.tradingview.com/script/Y0omflqx-Rebalance-as-a-Bear-Bull-indicator/).
//
// It always buys/sells the same amount by default (you can set it in the cog menu in the option "Base Crypto Amount To Trade"),
// for SOL this is set to 1.0SOL.
//
// This is my first attempt at scalping, it differs slightly from the standards because it does not require fast
// response candles or immediate market operations (it can work well with limit trading) and on top of this it also
// does not require a stop loss since it uses an indicator that provides the trading windows (surprises can still happen though).
//
// The main logic for this strategy is simple and happens down at the bottom, in the "Actions" section.
//
//
// This code makes use of the following libraries, they are open-source as well
// and you can check them out here: https://www.tradingview.com/u/hugodanielcom/#published-scripts
import hugodanielcom/PureRebalance/3 as rebalancer
import hugodanielcom/TradingPortfolio/1 as portfolio
strategy("S1", overlay=false, calc_on_order_fills = false, initial_capital = 10000.0)
base_amount = input.float(defval = 1.0, title = "Base Crypto Amount To Trade", minval = 0.1, maxval = 100.0)
min_value = input.float(defval = 11.0, title = "Min Fiat Trading Value", minval = 1.0, maxval = 100.0)
float precision = input.float(defval = 15.0, title = "Rebalance Precision", minval = 1.0, maxval = 100.0)
fromHour = input.int(defval = 1, title = "hh", group = "From", inline="fromClock", minval = 1, maxval = 24)
fromMin = input.int(defval = 0, title = "mm", group = "From", inline="fromClock", minval = 0, maxval = 60)
fromMonth = input.int(defval = 11, title = "MM", group = "From", inline="fromDate", minval = 1, maxval = 12)
fromDay = input.int(defval = 1, title = "DD", group = "From", inline="fromDate", minval = 1, maxval = 31)
fromYear = input.int(defval = 2021, title = "YYYY", group = "From", inline="fromDate", minval = 1970)
thruMonth = input.int(defval = 11, title = "MM", group = "Thru", inline="thruDate", minval = 1, maxval = 12)
thruDay = input.int(defval = 31, title = "DD", group = "Thru", inline="thruDate", minval = 1, maxval = 31)
thruYear = input.int(defval = 2021, title = "YYYY", group = "Thru", inline="thruDate", minval = 1970)
float MIN_AMOUNT = min_value / close
// === FUNCTION EXAMPLE ===
start = timestamp(fromYear, fromMonth, fromDay, fromHour, fromMin) // 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"
rebull_rebear_precision = input.float(defval = 2.5, group = "Bear/Bull Market Indicator", title = "Rebalance when portfolio differs by %", tooltip="Bigger values make the rebalance hold more and become less sensitive to peaks/bottoms and act less often.", minval = 0.1, maxval = 99.9)
rebull_rebear_from_month = fromMonth // input.int(defval = 11, group = "Bear/Bull Market Indicator", title = "Start At Month", minval = 1, maxval = 12)
rebull_rebear_from_day = input.int(defval = 1, group = "Bear/Bull Market Indicator", title = "Start At Day", minval = 1, maxval = 31)
rebull_rebear_from_year = fromYear // input.int(defval = 2021, group = "Bear/Bull Market Indicator", title = "Start At Year", minval = 2020)
rebull_rebear_capital = input.float(defval = 10000.0, group = "Bear/Bull Market Indicator", title = "Initial capital", minval = 1, tooltip="The total portfolio value to start with. A higher value makes the rebalancer more sensitive to peaks/bottoms and act more often")
rebull_rebear_percentage = input.float(defval = 60.0, group = "Bear/Bull Market Indicator", title = "Rebalance Token %", minval = 0.01, maxval = 100.0, tooltip="Percentage of Token / Money.\n60 means the targeted balance is 60% token and 40% money")
rebull_rebear_show_force = input.bool(defval = false, group = "Bear/Bull Market Indicator", title = "Show force")
rebull_rebear_show_opos = input.bool(defval = true, group = "Bear/Bull Market Indicator", title = "Show buy/sell windows of opportunities")
// Backtest start window
rebull_rebear_start = timestamp(rebull_rebear_from_year, rebull_rebear_from_month, rebull_rebear_from_day)
// Function returns true when the current bar time is
// "within the window of time" for this indicator
rebull_rebear_window() => time >= rebull_rebear_start
// The two market trend indicator portfolios
var float[] percentage_portfolio = portfolio.init()
var float[] signal_portfolio = portfolio.init()
// Initialization starts by doing a rebalance at the first bar within
// the window
var bool rebull_rebear_init1 = true
if rebull_rebear_window() and rebull_rebear_init1
// Only do this once, for the first bar, set init1 to false to disallow
// this block from running again
rebull_rebear_init1 := false
first_rebalance_amount = rebalancer.rebalance(close, 0.0, rebull_rebear_capital, rebull_rebear_percentage / 100)
portfolio.set_balance(percentage_portfolio, first_rebalance_amount, rebull_rebear_capital - (first_rebalance_amount * close))
float signal_capital = close*100.0
signal_first_rebalance_amount = rebalancer.rebalance(close, 0.0, signal_capital, rebull_rebear_percentage / 100)
portfolio.set_balance(signal_portfolio, signal_first_rebalance_amount, signal_capital - (signal_first_rebalance_amount * close))
var float signal = 0.0
float signal_rebalance_amount = rebalancer.rebalance(close, portfolio.crypto(signal_portfolio), portfolio.fiat(signal_portfolio), rebull_rebear_percentage / 100.0)
float signal_percentage_change = math.abs(signal_rebalance_amount) / portfolio.crypto(signal_portfolio)
bool signal_is_rebalance_needed = signal_percentage_change >= ((rebull_rebear_precision / 4.0) / 100.0)
bool signal_is_rebalance_buying = signal_is_rebalance_needed and signal_rebalance_amount > 0
bool signal_is_rebalance_selling = signal_is_rebalance_needed and signal_rebalance_amount < 0
// This is where the rebalance gets done
float percentage_rebalance_amount = rebalancer.rebalance(close, portfolio.crypto(percentage_portfolio), portfolio.fiat(percentage_portfolio), rebull_rebear_percentage / 100.0)
// Check if the amount to rebalance is bigger than the percentage
float percentage_change = math.abs(percentage_rebalance_amount) / portfolio.crypto(percentage_portfolio)
bool percentage_is_rebalance_needed = percentage_change >= (rebull_rebear_precision / 100.0)
bool percentage_is_rebalance_buying = percentage_is_rebalance_needed and percentage_rebalance_amount > 0
bool percentage_is_rebalance_selling = percentage_is_rebalance_needed and percentage_rebalance_amount < 0
var int bear_bull_balance = 0
var int bear_balance = 0
var int bull_balance = 0
var int signal_bear_balance = 0
var int signal_bull_balance = 0
var float percentage_signal = 0.0
// Update the percentage portfolio and the signal portfolio number of operations
// and bear/bull market balance. The values calculated here will then be used
// to set the "market_value" and "signal_market_value" below, which are the
// main indicators of the bear/bull market strength.
if rebull_rebear_window()
if percentage_is_rebalance_buying
portfolio.buy(percentage_portfolio, percentage_rebalance_amount, close)
bear_balance += 1
if percentage_is_rebalance_selling
portfolio.sell(percentage_portfolio, math.abs(percentage_rebalance_amount), close)
bull_balance += 1
if signal_is_rebalance_buying
if portfolio.buy(signal_portfolio, signal_rebalance_amount, close)
signal += signal_rebalance_amount
signal_bear_balance += 1
if signal_is_rebalance_selling
if portfolio.sell(signal_portfolio, math.abs(signal_rebalance_amount), close)
signal += signal_rebalance_amount
signal_bull_balance += 1
market_value = bull_balance - bear_balance
signal_market_value = signal_bull_balance - signal_bear_balance
// Store the signal_market_value at the entry point of a new market_value, this
// is used to subtract to the current signal value, useful as an indicator of
// the market force within the current market_value quantity.
var market_value_start = signal_market_value
if market_value[0] != market_value[1]
market_value_start := signal_market_value
// The colors to be used when the market is considered bear or bull
bear_down_color = color.new(color.red, 15)
bear_up_color = color.new(color.red, 15)
bull_down_color = color.new(color.green, 15)
bull_up_color = color.new(color.green, 15)
// A special color to be used when it is neither.
nothing_color = color.new(color.gray, 0)
// By default it is neither:
color market_color = nothing_color
// Look at the market_value and decide which color to use
market_color := nothing_color
bool is_signal_going_up = signal > 0
bool is_signal_going_down = not is_signal_going_up
if market_value > 0 and is_signal_going_up
market_color := bull_up_color
if market_value > 0 and is_signal_going_down
market_color := bull_down_color
if market_value < 0 and is_signal_going_up
market_color := bear_up_color
if market_value < 0 and is_signal_going_down
market_color := bear_down_color
// The market force is the second indicator that this code outputs, it represents
// the tendency of the market to go up or down within a "market_value" block.
force=signal_market_value - market_value_start
// It can be used to find buying and selling windows
bool is_force_selling_opportunity = force > 0 and ((market_value < 0 and force >= 2) or (market_value > 0 and force >= 1))
bool is_force_buying_opportunity = force < 0 and ((market_value < 0 and force <= -2) or (market_value > 0 and force <= -3))
bool is_buying_opportunity = is_force_buying_opportunity or (is_force_buying_opportunity[1] and close[1] >= close[0])
bool is_selling_opportunity = is_force_selling_opportunity or (is_force_selling_opportunity[1] and close[1] <= close[0])
// Paint these extra values if they are being drawn:
color force_color = na
if is_selling_opportunity
force_color := color.new(color.red, 80)
if is_buying_opportunity
force_color := color.new(color.blue, 80)
// The final bear/bull output
bgcolor(rebull_rebear_show_opos ? force_color : na, title="Buy/Sell opportunities")
plot(market_value, "Bear/Bull Strength", color=market_color, style=plot.style_area)
plot(force, "Force", color=rebull_rebear_show_force ? color.orange : na)
hline(0, "Middle Band", color=color.new(#787B86, 50))
////////////////////////////////////////////////////////////////////////////////////
// Rebalancer oscillator
////////////////////////////////////////////////////////////////////////////////////
// Calculate the HODL money in the portfolio - this is necessary because the
// TradingView strategy tester is targeted for single position strategies, which
// is not the case of this one.
var float token_start = 0.0
if window() and token_start == 0.0
token_start := close
var float hold = 0
var float window_close = 0.0
if window()
window_close := close
hold := (strategy.initial_capital / token_start)
float hold_profit = hold * window_close - token_start * hold
plot(hold_profit, "Hold Profit", color=na)
// Arrays to keep track of previous orders (the TradingView strategy object
// works with a single position, this strategy doesn't follow pyramiding or a
// position - these arrays help to keep track of the orders being issued and
// get updated when they get matched by an requivalent upper/lower sale/buy)
var buy_orders_value = array.new_float()
var buy_orders_amount = array.new_float()
var buy_orders_fullfillment = array.new_float()
var sell_orders_value = array.new_float()
var sell_orders_amount = array.new_float()
var sell_orders_fullfillment = array.new_float()
var tmp_fullfillment_indices = array.new_int()
var tmp_fullfillment_amounts = array.new_float()
// Returns [ticker value, total amount sold, amount available]
get_past_unfulfilled_sell(int i) =>
if i >= 0 and i < array.size(sell_orders_value) and i < array.size(sell_orders_amount) and i < array.size(sell_orders_fullfillment)
fullfillment = array.get(sell_orders_fullfillment, i)
if fullfillment < 1.0
initial_amount_sold = array.get(sell_orders_amount, i)
available_amount = initial_amount_sold * (1.0 - fullfillment)
[array.get(sell_orders_value, i), initial_amount_sold, available_amount]
else
[0.0, 0.0, 0.0]
else
[0.0, 0.0, 0.0]
set_fullfillment_amount_in_sell(int i, float amount) =>
[_, initial_sell_amount, sell_available_amount] = get_past_unfulfilled_sell(i)
fullfilled_amount = initial_sell_amount - sell_available_amount
array.set(sell_orders_fullfillment, i, (amount + fullfilled_amount) / initial_sell_amount)
fullfill_sell_at(float value, float fiat_account_balance, int at) =>
amount_to_buy = 0.0
[sell_close, initial_sell_amount, sell_available_amount] = get_past_unfulfilled_sell(at)
if sell_available_amount * value < fiat_account_balance
// Fullfill 100% immediately
amount_to_buy += sell_available_amount
else
// Try to fullfill in parcels
amount_fullfilled = 0.0
total_parcels = 20
for j = 0 to total_parcels-1
current_parcel_amount = j*sell_available_amount/total_parcels
// Do we have fiat enough to buy a parcel this big?
if fiat_account_balance > current_parcel_amount * value
amount_fullfilled := current_parcel_amount
// Fullfill this
amount_to_buy += amount_fullfilled
profit = sell_close * amount_to_buy - value * amount_to_buy
[amount_to_buy, sell_close, profit]
// Tries to buy enough
fullfill_sells_gt(float value, float fiat_account_balance) =>
array.clear(tmp_fullfillment_indices)
array.clear(tmp_fullfillment_amounts)
float profit = 0.0
float amount_to_buy = 0.0
float tmp_fiat_balance = fiat_account_balance
int _size = array.size(sell_orders_value)
if _size > 0 and fiat_account_balance > 1.0
for i = 0 to _size-1
cur_order_value = array.get(sell_orders_value, i)
if cur_order_value > value
[amount_possible, sell_value, order_profit] = fullfill_sell_at(value, tmp_fiat_balance, i)
tmp_fiat_balance -= amount_possible * sell_value
amount_to_buy += amount_possible
profit += order_profit
// Mark this to be fullfilled
array.push(tmp_fullfillment_indices, i)
array.push(tmp_fullfillment_amounts, amount_possible)
[amount_to_buy, profit]
fullfill_oldest_sale(float value, float fiat_account_balance) =>
array.clear(tmp_fullfillment_indices)
array.clear(tmp_fullfillment_amounts)
int _size = array.size(sell_orders_value)
float amount_to_buy = MIN_AMOUNT
bool _is_done = false
if _size > 0
for i = 0 to _size-1
[amount_possible, sell_close, _] = fullfill_sell_at(value, fiat_account_balance, i)
if not _is_done
// This is the percentage of the profit to take in float: 1.XXX
price_adjustment = (1.0 - (sell_close / value)) + 1.0
if amount_possible > 0.0 and amount_possible * price_adjustment < fiat_account_balance
amount_to_buy := amount_possible * price_adjustment
_is_done := true
array.push(tmp_fullfillment_indices, i)
array.push(tmp_fullfillment_amounts, amount_to_buy)
amount_to_buy
else
amount_to_buy := 0.03
else
amount_to_buy
clear_fullfilled_sells() =>
old_sell_orders_value = array.copy(sell_orders_value)
old_sell_orders_amount = array.copy(sell_orders_amount)
old_sell_orders_fullfillment = array.copy(sell_orders_fullfillment)
array.clear(sell_orders_value)
array.clear(sell_orders_amount)
array.clear(sell_orders_fullfillment)
_size = array.size(old_sell_orders_fullfillment)
if _size > 0
for i = 0 to _size-1
if array.get(old_sell_orders_fullfillment, i) < 1.0
array.push(sell_orders_fullfillment, array.get(old_sell_orders_fullfillment, i))
array.push(sell_orders_value, array.get(old_sell_orders_value, i))
array.push(sell_orders_amount, array.get(old_sell_orders_amount, i))
close_buy() =>
_size = array.size(tmp_fullfillment_indices)
if _size > 0
for i = 0 to _size-1
sell_index = array.get(tmp_fullfillment_indices, i)
sell_amount = array.get(tmp_fullfillment_amounts, i)
set_fullfillment_amount_in_sell(sell_index, sell_amount)
clear_fullfilled_sells()
register_sell(value, amount) =>
array.push(sell_orders_value, value)
array.push(sell_orders_amount, amount)
array.push(sell_orders_fullfillment, 0.0)
// Returns [ticker value, total amount sold, amount available]
get_past_unfulfilled_buy(int i) =>
if i >= 0 and i < array.size(buy_orders_value) and i < array.size(buy_orders_amount) and i < array.size(buy_orders_fullfillment)
fullfillment = array.get(buy_orders_fullfillment, i)
if fullfillment < 1.0
initial_amount_bought = array.get(buy_orders_amount, i)
available_amount = initial_amount_bought * (1.0 - fullfillment)
[array.get(buy_orders_value, i), initial_amount_bought, available_amount]
else
[0.0, 0.0, 0.0]
else
[0.0, 0.0, 0.0]
set_fullfillment_amount_in_buy(int i, float amount) =>
[_, initial_buy_amount, buy_available_amount] = get_past_unfulfilled_buy(i)
fullfilled_amount = initial_buy_amount - buy_available_amount
array.set(buy_orders_fullfillment, i, (amount + fullfilled_amount) / initial_buy_amount)
fullfill_buy_at(float value, float fiat_account_balance, int at) =>
amount_to_sell = 0.0
[buy_close, initial_buy_amount, buy_available_amount] = get_past_unfulfilled_buy(at)
if buy_available_amount * value < fiat_account_balance
// Fullfill 100% immediately
amount_to_sell += buy_available_amount
else
// Try to fullfill in parcels
amount_fullfilled = 0.0
total_parcels = 20
for j = 0 to total_parcels-1
current_parcel_amount = j*buy_available_amount/total_parcels
// Do we have fiat enough to buy a parcel this big?
if fiat_account_balance > current_parcel_amount * value
amount_fullfilled := current_parcel_amount
// Fullfill this
amount_to_sell += amount_fullfilled
profit = buy_close * amount_to_sell - value * amount_to_sell
[amount_to_sell, buy_close, profit]
// Tries to buy enough
fullfill_buys_lt(float value, float fiat_account_balance) =>
array.clear(tmp_fullfillment_indices)
array.clear(tmp_fullfillment_amounts)
float profit = 0.0
float amount_to_sell = 0.0
float tmp_fiat_balance = fiat_account_balance
int _size = array.size(buy_orders_value)
if _size > 0 and fiat_account_balance > 1.0
for i = 0 to _size-1
cur_order_value = array.get(buy_orders_value, i)
if cur_order_value < value
[amount_possible, buy_value, order_profit] = fullfill_buy_at(value, tmp_fiat_balance, i)
tmp_fiat_balance -= amount_possible * buy_value
amount_to_sell += amount_possible
profit += order_profit
// Mark this to be fullfilled
array.push(tmp_fullfillment_indices, i)
array.push(tmp_fullfillment_amounts, amount_possible)
[amount_to_sell, profit]
fullfill_oldest_buy(float value, float fiat_account_balance) =>
array.clear(tmp_fullfillment_indices)
array.clear(tmp_fullfillment_amounts)
int _size = array.size(buy_orders_value)
float amount_to_sell = 1.0
bool _is_done = false
if _size > 0
for i = 0 to _size-1
[amount_possible, buy_close, _] = fullfill_buy_at(value, fiat_account_balance, i)
if not _is_done
price_adjustment = (1.0 - (buy_close / value)) + 1.0
if amount_possible > 0.0 and amount_possible * price_adjustment < fiat_account_balance
amount_to_sell := amount_possible * price_adjustment
_is_done := true
array.push(tmp_fullfillment_indices, i)
array.push(tmp_fullfillment_amounts, amount_to_sell)
amount_to_sell
else
amount_to_sell := 0.03
else
amount_to_sell
clear_fullfilled_buys() =>
old_buy_orders_value = array.copy(buy_orders_value)
old_buy_orders_amount = array.copy(buy_orders_amount)
old_buy_orders_fullfillment = array.copy(buy_orders_fullfillment)
array.clear(buy_orders_value)
array.clear(buy_orders_amount)
array.clear(buy_orders_fullfillment)
_size = array.size(old_buy_orders_fullfillment)
if _size > 0
for i = 0 to _size-1
if array.get(old_buy_orders_fullfillment, i) < 1.0
array.push(buy_orders_fullfillment, array.get(old_buy_orders_fullfillment, i))
array.push(buy_orders_value, array.get(old_buy_orders_value, i))
array.push(buy_orders_amount, array.get(old_buy_orders_amount, i))
close_sell() =>
_size = array.size(tmp_fullfillment_indices)
if _size > 0
for i = 0 to _size-1
buy_index = array.get(tmp_fullfillment_indices, i)
buy_amount = array.get(tmp_fullfillment_amounts, i)
set_fullfillment_amount_in_buy(buy_index, buy_amount)
clear_fullfilled_buys()
register_buy(value, amount) =>
array.push(buy_orders_value, value)
array.push(buy_orders_amount, amount)
array.push(buy_orders_fullfillment, 0.0)
// Virtual Portfolio (useful to get the rebalancer buy/sell points without
// suffering interference from the real buy/sales being done)
var float[] virtual = portfolio.init()
// The Real Portfolio
var float[] balance = portfolio.init()
buy_order(float amount) =>
strategy.order("buy", strategy.long, amount, when = window(), alert_message = str.tostring(amount))
sell_order(float amount) =>
strategy.order("sell", strategy.short, amount, when = window(), alert_message = str.tostring(-amount))
// Initialization starts by buying MIN_AMOUNT token and selling it right away.
// this is to ensure proper values in the Strategy Tester that start at the
// first block. Strategy Tester by default starts at the block of the first
// order - a buy/sell order is done on the first block so that it starts at it.
var init1 = true
var init2 = false
var init3 = false
var first_full_amount = MIN_AMOUNT
var last_rebalance_at = 0
ratio_of_first_rebalance = 0.5
float capital = float(strategy.initial_capital[0])
// Start by selling enough crypto to have this
// amount of fiat
fiat_offset = 2000
on_the_side = 0
if window() and init1
init1 := false
init2 := true
strategy.order("buy", strategy.long, first_full_amount, when = window())
init1
else if window() and init2
init2 := false
init3 := true
strategy.order("sell", strategy.short, first_full_amount, when = window())
init2
else if window() and init3
init3 := false
first_rebalance_amount = rebalancer.rebalance(close, 0.0, capital, ratio_of_first_rebalance)
portfolio.set_balance(virtual, first_rebalance_amount, strategy.initial_capital - (first_rebalance_amount * close))
// first_amount_to_buy = (strategy.initial_capital - fiat_offset) / close // 100% crypto - offset
// Start with `offset` FIAT on the side
initial_crypto = (strategy.initial_capital - fiat_offset) / close
portfolio.set_balance(balance, initial_crypto, fiat_offset + on_the_side)
// last_rebalance_at := month(time)
// strategy.order("buy", strategy.long, first_rebalance_amount, when = window(), alert_message = str.tostring(first_rebalance_amount))
init3
// Adjust the precision to the current token value,
// This way the amount to rebalance is adjusted to be meaningful in very high
// value tokens, or very low value tokens
float token_adjustment = 2000.0 / (strategy.initial_capital / close)
// The virtual portfolio is frequently rebalanced at 60% crypto
// this allows it to be used to output buy/sales points while the real
// portfolio gets messed up with the trading action
// amount = portfolio.get_rebalance_amount(virtual, 0.60, close)
float virtual_amount = window() ? rebalancer.rebalance(close, portfolio.crypto(virtual), portfolio.fiat(virtual), 0.60) : 0.0
color virtual_rebalance_color = na
bool is_rebalance_selling = virtual_amount * token_adjustment < -precision
bool is_rebalance_buying = virtual_amount * token_adjustment > precision
if window()
if is_rebalance_buying
portfolio.buy(virtual, virtual_amount, close)
virtual_rebalance_color := color.new(color.teal, 80)
if is_rebalance_selling
portfolio.sell(virtual, math.abs(virtual_amount), close)
virtual_rebalance_color := color.new(color.maroon, 80)
bgcolor(window() ? virtual_rebalance_color : na, title="Buy/Sell Bar")
////////////////////////////////////////////////////////////////////////////////
// MAIN - balance = portfolio.init()
////////////////////////////////////////////////////////////////////////////////
bool is_selling_opportunity_finished = (not is_selling_opportunity) and is_selling_opportunity[1]
bool is_buying_opportunity_finished = (not is_buying_opportunity) and is_buying_opportunity[1]
bool is_selling_opportunity_starting = (not is_selling_opportunity[1]) and is_selling_opportunity[0]
bool is_buying_opportunity_starting = (not is_buying_opportunity[1]) and is_buying_opportunity[0]
buy(portfolio, amount, value) =>
[prev_sold_amount, profit_if_bought] = fullfill_sells_gt(value*1.12, portfolio.fiat(balance))
if math.abs(amount) > MIN_AMOUNT
if portfolio.buy(portfolio, math.abs(amount) + math.abs(prev_sold_amount), value)
buy_order(math.abs(amount) + math.abs(prev_sold_amount))
register_buy(value, math.abs(amount))
close_buy()
sell(portfolio, amount, value) =>
[prev_bought_amount, profit_if_sold] = fullfill_buys_lt(value*0.88, portfolio.fiat(balance))
if math.abs(amount) > MIN_AMOUNT
if portfolio.sell(portfolio, math.abs(amount) + math.abs(prev_bought_amount), value)
sell_order(math.abs(amount) + math.abs(prev_bought_amount))
register_sell(value, math.abs(amount))
close_sell()
// Overall performance of this strategy
float strategy_total = portfolio.fiat(balance) + portfolio.crypto(balance) * window_close
float vs_hold = (strategy_total + portfolio.retained(balance)) - (hold * window_close)
float did_profit = (portfolio.retained(balance) + strategy_total) - strategy.initial_capital
///////////////
// Actions
///////////////
if window()
// Double the amount to trade if the rebalance oscillator is sayin that this is a good
// trade opportunity.
float amount = is_rebalance_selling or is_rebalance_buying ? base_amount * 2.0 : base_amount
// Perform the expected trading actions whenever the current candle is within a
// trading window of the bear/bull market indicator.
if is_selling_opportunity and open > close[1]
sell(balance, amount, open)
if is_buying_opportunity and open < close[1]
buy(balance, amount, open)
if portfolio.crypto(balance) <= amount and is_rebalance_buying
buy(balance, amount, close)
if portfolio.fiat(balance) <= close and is_rebalance_selling
sell(balance, amount, close)
//////////////////////////////////////////////////////////////////////////////
// ANALYSIS - Open the Trading Window in the right menu to see these values //
//////////////////////////////////////////////////////////////////////////////
plot(portfolio.fiat(balance) + portfolio.retained(balance), title = "Fiat in Balance")
plot(portfolio.crypto(balance), title = "Crypto in Balance")
// How much profit did this strategy make when compared to the initial investment capital?
plot( did_profit, title = "Did Profit? (dif. from initial capital)", color = ((portfolio.retained(balance) + strategy_total) - strategy.initial_capital) > 0 ? color.green : color.red)
// How much profit did this strategy make when compared to a 100% buy at the first candle?
plot(vs_hold, title = "Total profit vs Hold (in Fiat)", color = (vs_hold > 0 ? color.green : color.red))
|
B.Bands | Augmented | Intra-range | Long-Only | https://www.tradingview.com/script/elhM73oi/ | JCGMarkets | https://www.tradingview.com/u/JCGMarkets/ | 125 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © JCGMarkets
//@version=5
strategy("B.Bands | Augmented | Intra-range | Long-Only", shorttitle = "BB|A|IR|L", initial_capital=1000, commission_value=0.075, slippage = 0, overlay = true)
// TODO stop loss plot add short
// Control Panel ============================================================================================================================================================
//Technical Indicators Data
show_simp = input.bool(true, title="Simple Bollinger Bands ", inline='1', group="Strategy System")
show_augm = input.bool(false, title="Augmented Bollinger Bands", inline='1', group="Strategy System",tooltip='Select Bollinger Band Indicator to trade Simple or Augmented')
periods = input.int(20, title="Periods", minval = 2, step = 1,inline='2', group="Technical Inputs")
std = input.float(2, title="Std", minval=0.1 , step = 0.1, group="Technical Inputs",inline='2', tooltip='Technical inputs for indicator calculation, Periods for MA and Standard Deviation')
// Strategy data
entry_source = input(close, title="Entry source", group="Strategy Inputs", inline='3')
exit_source = input(high, title="Exit source", group="Strategy Inputs", inline='3',tooltip='For entry: Activate signal if the source lies below (for Long) or above (for Short). For exit: When price reach target selected')
max_spread_bb = input.float(99999.0, title="Max Spread Tolerance Beetween Bands", step=0.1, group="Strategy Inputs",tooltip='Max. Tolerance beetween lower and upper band to allow trade for range systems')
// Profit
take_profit = input.string("opposite", title = "Profit to band:", inline='4', options = ["middle", "opposite"], group="Profit Target")
sell_profit = input(false, title="Only sell in profit", group="Profit Target", inline='4', tooltip='Sell only if position is on profit, unless Stop Loss active')
// Risk Management
stop_loss = input.float(3.00, title="Stop Loss %", inline='5', step=0.05, group="Risk Management")
isStopLoss = input(true, 'Implement Stop Loss?', inline='5', group="Risk Management", tooltip='Activate Stop Loss')
stop_perc = input.float(6.00, title="Trailing %", step=0.125, inline='6', group="Risk Management") * 0.01
trailing = input(false, title="Implement trailing stop?",inline='6', group="Risk Management")
// Position Management
riskPerc = input.float(title="% of available capital", maxval=100 , inline='7', group='Position Size', defval=5, step=0.25, tooltip='Use a % of the total capital selected for strategy')
usePosSize = input.bool(title="Limit strategy capital?", defval=false, inline='7', group='Position Size', tooltip='If activated, only uses the percentage of capital selected from the properties tab. Default 1000$')
// Backtest Range
start = input.time(timestamp("2019-11-01T00:00:00"),inline='9', title="Starting Date",group="BACKTEST RANGE" )
end = input.time(timestamp("2023-12-12T00:00:00"), inline='9',title="Ending Date",group="BACKTEST RANGE",tooltip='Select the range for backtest and live strategy')
// Helper Functions ============================================================================================================================================================
// Date Condition
In_date() =>
from_date = time >= start
to_date = time <= end
from_date and to_date
position = usePosSize ? math.round((strategy.equity * (riskPerc / 100) / close) , 6) : math.round((strategy.equity / close) , 6)
in_position = strategy.position_size > 0
// Initialize variables ========================================================================================================================================================
var SL = 0.0
var SLT= 0.0
SLT := if in_position and In_date()
stop_inicial = entry_source * (1 - stop_perc)
math.max(stop_inicial, SLT[1])
else
0
slts = (low <= SLT) and (trailing == true)
//Simple BB Calculation -> adapt if needed with different std for upper-lower, sma-ema, etc
middle_sim = ta.sma(close, periods)
//Augmented BB Calculation -> adapt if needed with different std for upper lower, etc
middle_augm = ta.ema(close, periods)
middle_upp = ta.ema(high, periods)
middle_low = ta.ema(low, periods)
//Multiplier
dev = ta.stdev(close, periods) * std
//Upper & Lower Bands
upper = (middle_sim + dev)
lower = (middle_sim - dev)
//Augmented Bands
upper_augm = (middle_upp + dev)
lower_augm = (middle_low - dev)
//Bands Spread
spread = upper - lower
spread_augm = upper_augm - lower_augm
//Trading Conditions
entry_long = (entry_source <= lower) and (spread < max_spread_bb)
entry_long_augm = (entry_source <= lower_augm) and (spread_augm < max_spread_bb)
// Simple Bollinger
if (not in_position and show_simp and In_date())
if entry_long
// Trigger buy order
strategy.entry("Entry", strategy.long, qty = position )
SL := close * (1 - (stop_loss / 100)) // You could determine wether or not implement stop loss with bool input and if condition here.
if in_position and show_simp and not sell_profit and In_date()
//Exits if not sell in profit
if take_profit == "middle"
strategy.exit("Target", "Entry", limit = middle_sim, stop = isStopLoss ? SL: na, comment="Exit")
if take_profit == "opposite"
strategy.exit("Target", "Entry", limit = upper, stop = isStopLoss ? SL :na , comment="Exit")
if in_position and show_simp and sell_profit and In_date()
//Exits if sell in profit
if take_profit == "middle"
strategy.exit("Target", "Entry", limit = (strategy.openprofit > 0 ? middle_sim: na), stop = isStopLoss ? SL: na, comment="Exit")
if take_profit == "opposite"
strategy.exit("Target", "Entry", limit = (strategy.openprofit > 0 ? upper: na), stop = isStopLoss ? SL : na, comment="Exit")
if in_position and show_simp and slts and In_date()
//Trailing activation
strategy.close("Entry", comment="SLT")
if not In_date()
//Exit due out of date range
strategy.close("Entry", comment="Out of date range")
// Augmented Bollinger Conditions
if (not in_position and show_augm and In_date())
if entry_long_augm
// Trigger buy order
strategy.entry("Entry_A", strategy.long, qty = position )
SL := close * (1 - (stop_loss / 100) )
if in_position and show_augm and not sell_profit and In_date()
//Exits and not sell in profit
if take_profit == "middle"
strategy.exit("Target", "Entry_A", limit = middle_augm, stop = isStopLoss ? SL : na, comment="Exit")
if take_profit == "opposite"
strategy.exit("Target", "Entry_A", limit = upper_augm, stop = isStopLoss ? SL : na, comment="Exit")
if in_position and show_augm and sell_profit and In_date()
//Exit only in profit
if take_profit == "middle"
strategy.exit("Target", "Entry_A", limit = (strategy.openprofit > 0 ? middle_augm:na), stop = isStopLoss ? SL : na, comment="Exit")
if take_profit == "opposite"
strategy.exit("Target", "Entry_A", limit = (strategy.openprofit > 0 ? upper_augm: na) , stop = isStopLoss ? SL : na, comment="Exit")
if in_position and show_augm and slts and In_date()
//Trigger trailing
strategy.close("Entry_A", comment="SLT")
if not In_date()
//Out of date trigger
strategy.close("Entry_A", comment= "Out of date range")
// Plotting ==========================================================================================================================
plot(in_position ? SL > 0 ? SL : na : na , style = plot.style_circles, color = color.red, title = "Stop Loss")
plot(in_position ? trailing ? SLT > 0 ? SLT : na : na : na , style = plot.style_circles, color = color.blue, title = "Trailing Stop" )
s = plot(show_simp ? upper : na , color = color.aqua, title='Simple Upper Bollinger Band')
plot(show_simp ? middle_sim : na , color=color.red, title='Simple Moving Average')
i = plot(show_simp ? lower : na , color = color.aqua, title='Simple Lower Bollinger Band')
fill(s,i, color=color.new(color.aqua,90))
plot(show_augm ? middle_augm : na , color=color.blue, title='Augmented Moving Average')
s_a = plot( show_augm ? upper_augm : na, color=color.orange, title='Augmented Upper Bollinger Band')
i_a = plot( show_augm ? lower_augm : na, color= color.orange, title='Simple Lower Bollinger Band')
fill(s_a,i_a, color=color.new(color.orange, 90)) |
Manual Buy & Sell Alerts | https://www.tradingview.com/script/b56Kz6j3-Manual-Buy-Sell-Alerts/ | MGTG | https://www.tradingview.com/u/MGTG/ | 124 | 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/
// © MGTG
title_name = 'Manual Buy & Sell Alerts'
//@version=5
strategy(
title=title_name, overlay=true, initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=100,
pyramiding=1, commission_type=strategy.commission.percent, commission_value=0.1)
// Period
sTime = input.time(timestamp("2020-01-01"), "Start", group="Period", inline='1')
eTime = input.time(timestamp("2030-01-01"), "End", group="Period", inline='2')
inDateRange = time >= sTime and time <= eTime
// Bot Set-up
buy_type = input.string('stop', 'Buy Type', group='Buy&Sell', inline='1', options=['stop', 'limit'])
buy_price = input.float(49000, 'Buy Price', group='Buy&Sell', inline='1')
target_price = input.float(51000, 'Target Price', group='Buy&Sell', inline='2')
stop_price = input.float(47000, 'Stop Price', group='Buy&Sell', inline='2')
avg_price = strategy.position_avg_price
division = 1
// Alert message
AlertLong=input.string("Buy message", "Buy Alert Message", group='Alert set-up', inline='1')
AlertExit=input.string("Sell message", "Sell Alert Message", group='Alert set-up', inline='1')
plot(buy_price, 'Buy Price', color=color.new(#009688, 0), style=plot.style_linebr, offset=1)
plot(target_price, 'Take Profit', color=color.new(color.orange, 0), style=plot.style_linebr, offset=1)
plot(stop_price, 'Safety', color=color.new(color.aqua, 0), style=plot.style_linebr, offset=1)
posSize =
strategy.equity / close
strategy.exit("sell", "buy", limit=target_price, stop=stop_price, alert_message=AlertExit)
longCondition = inDateRange and strategy.position_size == 0
if longCondition and buy_type == 'stop'
strategy.entry("buy", strategy.long, qty=posSize, stop=buy_price, when=close < buy_price, comment="buy_STOP", alert_message=AlertLong)
if longCondition and buy_type == 'limit'
strategy.entry("buy", strategy.long, qty=posSize, limit=buy_price, when=close > buy_price, comment="buy_LIMIT", alert_message=AlertLong) |
[cache_that_pass] 1m 15m Function - Weighted Standard Deviation | https://www.tradingview.com/script/JezprTpT-cache-that-pass-1m-15m-Function-Weighted-Standard-Deviation/ | cache_that_pass | https://www.tradingview.com/u/cache_that_pass/ | 68 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © rumpypumpydumpy © cache_that_pass
//@version=4
strategy("[cache_that_pass] 1m 15m Function - Weighted Standard Deviation", overlay=true, pyramiding=0, default_qty_type=strategy.percent_of_equity, default_qty_value=20, initial_capital=10000, commission_type=strategy.commission.percent, commission_value=0.075)
f_weighted_sd_from_series(_src, _weight, _n) => //{
// @function: Calculates weighted mean, variance, standard deviation, MSE and RMSE from time series variables
// @parameters:
// _src: time series variable of sample values
// _weight: time series of corresponding weight values.
// _n : number of samples
_xw = _src * _weight
_sum_weight = sum(_weight, _n)
_mean = sum(_xw, _n) / _sum_weight
float _sqerror_sum = 0
int _nonzero_n = 0
for _i = 0 to _n - 1
_sqerror_sum := _sqerror_sum + pow(_mean - _src[_i], 2) * _weight[_i]
_nonzero_n := _weight[_i] != 0 ? _nonzero_n + 1 : _nonzero_n
_variance = _sqerror_sum / ((_nonzero_n - 1) * _sum_weight / _nonzero_n)
_dev = sqrt(_variance)
_mse = _sqerror_sum / _sum_weight
_rmse = sqrt(_mse)
[_mean, _variance, _dev, _mse, _rmse]
//}
// -----------------------------------------------------------------------------
f_weighted_sd_from_arrays(_a_src, _a_weight, _n) => //{
// @function: Calculates weighted mean, variance, standard deviation, MSE and RMSE from arrays
// Expects index 0 of the arrays to be the most recent sample and weight values!
// @parameters:
// _a_src: array of sample values
// _a_weight: array of corresponding weight values.
// _n : number of samples
float _mean = na, float _variance = na, float _dev = na, float _mse = na
float _rmse = na, float _sqerror_sum = na, float _sum_weight = na
float[] _a_xw = array.new_float(_n)
int _nonzero_n = 0
if array.size(_a_src) >= _n
_sum_weight := 0
_sqerror_sum := 0
for _i = 0 to _n - 1
array.set(_a_xw, _i, array.get(_a_src, _i) * array.get(_a_weight, _i))
_sum_weight := _sum_weight + array.get(_a_weight, _i)
_nonzero_n := array.get(_a_weight, _i) != 0 ? _nonzero_n + 1 : _nonzero_n
_mean := array.sum(_a_xw) / _sum_weight
for _j = 0 to _n - 1
_sqerror_sum := _sqerror_sum + pow(_mean - array.get(_a_src, _j), 2) * array.get(_a_weight, _j)
_variance := _sqerror_sum / ((_nonzero_n - 1) * _sum_weight / _nonzero_n)
_dev := sqrt(_variance)
_mse := _sqerror_sum / _sum_weight
_rmse := sqrt(_mse)
[_mean, _variance, _dev, _mse, _rmse]
//}
// -----------------------------------------------------------------------------
// Example usage :
// -----------------------------------------------------------------------------
len = input(20)
// -----------------------------------------------------------------------------
// From series :
// -----------------------------------------------------------------------------
[m, v, d, mse, rmse] = f_weighted_sd_from_series(close, volume, len)
plot(m, color = color.blue)
plot(m + d * 2, color = color.blue)
plot(m - d * 2, color = color.blue)
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// From arrays :
// -----------------------------------------------------------------------------
var float[] a_src = array.new_float()
var float[] a_weight = array.new_float()
if barstate.isfirst
for i = 1 to len
array.unshift(a_weight, i)
array.unshift(a_src, close)
if array.size(a_src) > len
array.pop(a_src)
[a_m, a_v, a_d, a_mse, a_rmse] = f_weighted_sd_from_arrays(a_src, a_weight, len)
plot(a_m, color = color.orange)
plot(a_m + a_d * 2, color = color.orange)
plot(a_m - a_d * 2, color = color.orange)
// -----------------------------------------------------------------------------
series_text = "Mean : " + tostring(m) + "\nVariance : " + tostring(v) + "\nSD : " + tostring(d) + "\nMSE : " + tostring(mse) + "\nRMSE : " + tostring(rmse)
array_text = "Mean : " + tostring(a_m) + "\nVariance : " + tostring(a_v) + "\nSD : " + tostring(a_d) + "\nMSE : " + tostring(a_mse) + "\nRMSE : " + tostring(a_rmse)
debug_text = "Volume weighted from time series : \n" + series_text + "\n\nLinearly weighted from arrays : \n" + array_text
//debug = label.new(x = bar_index, y = close, text = debug_text, style = label.style_label_left)
//.delete(debug[1])
//test strategy
if low <= (m - d * 2)
strategy.entry("LE", strategy.long)
if high >= (m + d * 2)
strategy.entry("SE", strategy.short)
// User Options to Change Inputs (%)
stopPer = input(3.11, title='Stop Loss %', type=input.float) / 100
takePer = input(7.50, title='Take Profit %', type=input.float) / 100
// Determine where you've entered and in what direction
longStop = strategy.position_avg_price * (1 - stopPer)
shortStop = strategy.position_avg_price * (1 + stopPer)
shortTake = strategy.position_avg_price * (1 - takePer)
longTake = strategy.position_avg_price * (1 + takePer)
if strategy.position_size > 0
strategy.exit(id="Close Long", stop=longStop, limit=longTake)
// strategy.close("LE", when = (longStop) or (longTake), qty_percent = 100)
if strategy.position_size < 0
strategy.exit(id="Close Short", stop=shortStop, limit=shortTake)
// strategy.close("SE", when = (shortStop) or (shortTake), qty_percent = 100) |
3Commas Visible DCA Strategy | https://www.tradingview.com/script/6q79diem/ | MGTG | https://www.tradingview.com/u/MGTG/ | 478 | 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/
// © MGTG
//@version=5
Strategy = input.string('Long', options=['Long'], group='Strategy', inline='1',
tooltip='Long bots profit when asset prices rise, Short bots profit when asset prices fall'
+ '\n\n' + 'Please note: to run a Short bot on a spot exchange account, you need to own the asset you want to trade. The bot will sell the asset at the current chart price and buy it back at a lower price - the profit made is actually trapped equity released from an asset you own that is declining in value.')
Profit_currency = input.string('Quote (USDT)', 'Profit currency', options=['Quote (USDT)', 'Quote (BTC)', 'Quote (BUSD)'], group='Strategy', inline='1')
Base_order_size = input.int(10, 'Base order Size', group='Strategy', inline='2',
tooltip='The Base Order is the first order the bot will create when starting a new deal.')
Safety_order_size = input.int(20, 'Safety order Size', group='Strategy', inline='2',
tooltip="Enter the amount of funds your Safety Orders will use to Average the cost of the asset being traded, this can help your bot to close deals faster with more profit. Safety Orders are also known as Dollar Cost Averaging and help when prices moves in the opposite direction to your bot's take profit target.")
Triger_Type = input.string('Over', 'Entry at Cross Over / Under', options=['Over', 'Under'], group='Deal start condition > Trading View custom signal', inline='1',
tooltip='Deal start condition decision')
Short_Moving_Average = input.string('SMA', 'Short Moving Average', group='Deal start condition > Trading View custom signal', inline='2',
options=["SMA", "EMA", "HMA"])
Short_Period = input.int(5, 'Period', group='Deal start condition > Trading View custom signal', inline='2')
Long_Moving_Average = input.string('HMA', 'Long Moving Average', group='Deal start condition > Trading View custom signal', inline='3',
options=["SMA", "EMA", "HMA"])
Long_Period = input.int(50, 'Period', group='Deal start condition > Trading View custom signal', inline='3')
Target_profit = input.float(1.5, 'Target profit (%)', step=0.05, group='Take profit / Stop Loss', inline='1') * 0.01
Stop_Loss = input.int(15, 'Stop Loss (%)', group='Take profit / Stop Loss', inline='1',
tooltip='This is the percentage that price needs to move in the opposite direction to your take profit target, at which point the bot will execute a Market Order on the exchange account to close the deal for a smaller loss than keeping the deal open.'
+ '\n' + 'Please note, the Stop Loss is calculated from the price the Safety Order at on the exchange account and not the Dollar Cost Average price.') * 0.01
Max_safety_trades_count = input.int(10, 'Max safety trades count', maxval=10, group='Safety orders', inline='1')
Price_deviation = input.float(0.4, 'Price deviation to open safety orders (% from initial order)', step=0.01, group='Safety orders', inline='2') * 0.01
Safety_order_volume_scale = input.float(1.8, 'Safety order volume scale', step=0.01, group='Safety orders', inline='3')
Safety_order_step_scale = input.float(1.19, 'Safety order step scale', step=0.01, group='Safety orders', inline='3')
initial_capital = 8913
strategy(
title='3Commas Visible DCA Strategy',
overlay=true,
initial_capital=initial_capital,
pyramiding=11,
process_orders_on_close=true,
commission_type=strategy.commission.percent,
commission_value=0.01,
max_bars_back=5000,
max_labels_count=50)
// Position
status_none = strategy.position_size == 0
status_long = strategy.position_size[1] == 0 and strategy.position_size > 0
status_long_offset = strategy.position_size[2] == 0 and strategy.position_size[1] > 0
status_short = strategy.position_size[1] == 0 and strategy.position_size < 0
status_increase = strategy.opentrades[1] < strategy.opentrades
Short_Moving_Average_Line =
Short_Moving_Average == 'SMA' ? ta.sma(close, Short_Period) :
Short_Moving_Average == 'EMA' ? ta.ema(close, Short_Period) :
Short_Moving_Average == 'HMA' ? ta.sma(close, Short_Period) : na
Long_Moving_Average_Line =
Long_Moving_Average == 'SMA' ? ta.sma(close, Long_Period) :
Long_Moving_Average == 'EMA' ? ta.ema(close, Long_Period) :
Long_Moving_Average == 'HMA' ? ta.sma(close, Long_Period) : na
Base_order_Condition = Triger_Type == "Over" ? ta.crossover(Short_Moving_Average_Line, Long_Moving_Average_Line) : ta.crossunder(Short_Moving_Average_Line, Long_Moving_Average_Line) // Buy when close crossing lower band
safety_order_deviation(index) => Price_deviation * math.pow(Safety_order_step_scale, index - 1)
pd = Price_deviation
ss = Safety_order_step_scale
step(i) =>
i == 1 ? pd :
i == 2 ? pd + pd * ss :
i == 3 ? pd + (pd + pd * ss) * ss :
i == 4 ? pd + (pd + (pd + pd * ss) * ss) * ss :
i == 5 ? pd + (pd + (pd + (pd + pd * ss) * ss) * ss) * ss :
i == 6 ? pd + (pd + (pd + (pd + (pd + pd * ss) * ss) * ss) * ss) * ss :
i == 7 ? pd + (pd + (pd + (pd + (pd + (pd + pd * ss) * ss) * ss) * ss) * ss) * ss :
i == 8 ? pd + (pd + (pd + (pd + (pd + (pd + (pd + pd * ss) * ss) * ss) * ss) * ss) * ss) * ss :
i == 9 ? pd + (pd + (pd + (pd + (pd + (pd + (pd + (pd + pd * ss) * ss) * ss) * ss) * ss) * ss) * ss) * ss :
i == 10 ? pd + (pd + (pd + (pd + (pd + (pd + (pd + (pd + (pd + pd * ss) * ss) * ss) * ss) * ss) * ss) * ss) * ss) * ss : na
long_line(i) =>
close[1] - close[1] * (step(i))
Safe_order_line(i) =>
i == 0 ? ta.valuewhen(status_long, long_line(0), 0) :
i == 1 ? ta.valuewhen(status_long, long_line(1), 0) :
i == 2 ? ta.valuewhen(status_long, long_line(2), 0) :
i == 3 ? ta.valuewhen(status_long, long_line(3), 0) :
i == 4 ? ta.valuewhen(status_long, long_line(4), 0) :
i == 5 ? ta.valuewhen(status_long, long_line(5), 0) :
i == 6 ? ta.valuewhen(status_long, long_line(6), 0) :
i == 7 ? ta.valuewhen(status_long, long_line(7), 0) :
i == 8 ? ta.valuewhen(status_long, long_line(8), 0) :
i == 9 ? ta.valuewhen(status_long, long_line(9), 0) :
i == 10 ? ta.valuewhen(status_long, long_line(10), 0) : na
TP_line = strategy.position_avg_price * (1 + Target_profit)
SL_line = Safe_order_line(Max_safety_trades_count) * (1 - Stop_Loss)
safety_order_size(i) => Safety_order_size * math.pow(Safety_order_volume_scale, i - 1)
plot(Short_Moving_Average_Line, 'Short MA', color=color.new(color.white, 0), style=plot.style_line)
plot(Long_Moving_Average_Line, 'Long MA', color=color.new(color.green, 0), style=plot.style_line)
plot(strategy.position_size > 0 and Max_safety_trades_count >= 1 ? Safe_order_line(1) : na, 'Safety order1', color=color.new(#009688, 0), style=plot.style_linebr)
plot(strategy.position_size > 0 and Max_safety_trades_count >= 2 ? Safe_order_line(2) : na, 'Safety order2', color=color.new(#009688, 0), style=plot.style_linebr)
plot(strategy.position_size > 0 and Max_safety_trades_count >= 3 ? Safe_order_line(3) : na, 'Safety order3', color=color.new(#009688, 0), style=plot.style_linebr)
plot(strategy.position_size > 0 and Max_safety_trades_count >= 4 ? Safe_order_line(4) : na, 'Safety order4', color=color.new(#009688, 0), style=plot.style_linebr)
plot(strategy.position_size > 0 and Max_safety_trades_count >= 5 ? Safe_order_line(5) : na, 'Safety order5', color=color.new(#009688, 0), style=plot.style_linebr)
plot(strategy.position_size > 0 and Max_safety_trades_count >= 6 ? Safe_order_line(6) : na, 'Safety order6', color=color.new(#009688, 0), style=plot.style_linebr)
plot(strategy.position_size > 0 and Max_safety_trades_count >= 7 ? Safe_order_line(7) : na, 'Safety order7', color=color.new(#009688, 0), style=plot.style_linebr)
plot(strategy.position_size > 0 and Max_safety_trades_count >= 8 ? Safe_order_line(8) : na, 'Safety order8', color=color.new(#009688, 0), style=plot.style_linebr)
plot(strategy.position_size > 0 and Max_safety_trades_count >= 9 ? Safe_order_line(9) : na, 'Safety order9', color=color.new(#009688, 0), style=plot.style_linebr)
plot(strategy.position_size > 0 and Max_safety_trades_count >= 10 ? Safe_order_line(10) : na, 'Safety order10', color=color.new(#009688, 0), style=plot.style_linebr)
plot(strategy.position_size > 0 ? TP_line : na, 'Take Profit', color=color.new(color.orange, 0), style=plot.style_linebr)
plot(strategy.position_size > 0 ? SL_line : na, 'Safety', color=color.new(color.aqua, 0), style=plot.style_linebr)
currency =
Profit_currency == 'Quote (USDT)' ? ' USDT' :
Profit_currency == 'Quote (BTC)' ? ' BTC' :
Profit_currency == 'Quote (BUSD)' ? ' BUSD' : na
if Base_order_Condition
strategy.entry('Base order', strategy.long, qty=Base_order_size/close, when=Base_order_Condition and strategy.opentrades == 0,
comment='BO' + ' - ' + str.tostring(Base_order_size) + str.tostring(currency))
for i = 1 to Max_safety_trades_count by 1
i_s = str.tostring(i)
strategy.entry('Safety order' + i_s, strategy.long, qty=safety_order_size(i)/close,
limit=Safe_order_line(i), when=(strategy.opentrades <= i) and strategy.position_size > 0 and not(strategy.position_size == 0),
comment='SO' + i_s + ' - ' + str.tostring(safety_order_size(i)) + str.tostring(currency))
for i = 1 to Max_safety_trades_count by 1
i_s = str.tostring(i)
strategy.cancel('Safety order' + i_s, when=status_none)
strategy.exit('TP/SL','Base order', limit=TP_line, stop=SL_line, comment = Safe_order_line(100) > close ? 'SL' + i_s + ' - ' + str.tostring(Base_order_size) + str.tostring(currency) : 'TP' + i_s + ' - ' + str.tostring(Base_order_size) + str.tostring(currency))
strategy.exit('TP/SL','Safety order' + i_s, limit=TP_line, stop=SL_line, comment = Safe_order_line(100) > close ? 'SL' + i_s + ' - ' + str.tostring(safety_order_size(i)) + str.tostring(currency) : 'TP' + i_s + ' - ' + str.tostring(safety_order_size(i)) + str.tostring(currency))
bot_usage(i) =>
i == 1 ? Base_order_size + safety_order_size(1) :
i == 2 ? Base_order_size + safety_order_size(1) + safety_order_size(2) :
i == 3 ? Base_order_size + safety_order_size(1) + safety_order_size(2) + safety_order_size(3) :
i == 4 ? Base_order_size + safety_order_size(1) + safety_order_size(2) + safety_order_size(3) + safety_order_size(4) :
i == 5 ? Base_order_size + safety_order_size(1) + safety_order_size(2) + safety_order_size(3) + safety_order_size(4) + safety_order_size(5) :
i == 6 ? Base_order_size + safety_order_size(1) + safety_order_size(2) + safety_order_size(3) + safety_order_size(4) + safety_order_size(5) + safety_order_size(6) :
i == 7 ? Base_order_size + safety_order_size(1) + safety_order_size(2) + safety_order_size(3) + safety_order_size(4) + safety_order_size(5) + safety_order_size(6) + safety_order_size(7) :
i == 8 ? Base_order_size + safety_order_size(1) + safety_order_size(2) + safety_order_size(3) + safety_order_size(4) + safety_order_size(5) + safety_order_size(6) + safety_order_size(7) + safety_order_size(8) :
i == 9 ? Base_order_size + safety_order_size(1) + safety_order_size(2) + safety_order_size(3) + safety_order_size(4) + safety_order_size(5) + safety_order_size(6) + safety_order_size(7) + safety_order_size(8) + safety_order_size(9) :
i == 10 ? Base_order_size + safety_order_size(1) + safety_order_size(2) + safety_order_size(3) + safety_order_size(4) + safety_order_size(5) + safety_order_size(6) + safety_order_size(7) + safety_order_size(8) + safety_order_size(9) + safety_order_size(10) : na
equity = strategy.equity
bot_use = bot_usage(Max_safety_trades_count)
bot_dev = float(step(Max_safety_trades_count)) * 100
bot_ava = (bot_use / equity) * 100
string label =
'Balance : ' + str.tostring(math.round(equity, 0), '###,###,###,###') + ' USDT' + '\n' +
'Max amount for bot usage : ' + str.tostring(math.round(bot_use, 0), '###,###,###,###') + ' USDT' + '\n' +
'Max safety order price deviation : ' + str.tostring(math.round(bot_dev, 0), '##.##') + ' %' + '\n' +
'% of available balance : ' + str.tostring(math.round(bot_ava, 0), '###,###,###,###') + ' %'
+ (bot_ava > 100 ? '\n \n' + '⚠ Warning! Bot will use amount greater than you have on exchange' : na)
if status_long
day_label =
label.new(
x=time[1],
y=high * 1.03,
text=label,
xloc=xloc.bar_time,
yloc=yloc.price,
color=bot_ava > 100 ? color.new(color.yellow, 0) : color.new(color.black, 50),
style=label.style_label_lower_right,
textcolor=bot_ava > 100 ? color.new(color.red, 0) : color.new(color.silver, 0),
size=size.normal,
textalign=text.align_left) |
Linear Regression Channel Breakout Strategy | https://www.tradingview.com/script/7USLDe0j/ | chanu_lev10k | https://www.tradingview.com/u/chanu_lev10k/ | 357 | 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/
// © LonesomeTheBlue © chanu_lev10k
//@version=5
strategy('Linear Regression Channel Breakout Strategy', overlay=true)
src = input(defval=close, title='Source')
len = input.int(defval=20, title='Length', minval=10)
devlen = input.float(defval=2.3, title='Deviation', minval=0.1, step=0.1)
extendit = input(defval=true, title='Extend Lines')
showfibo = input(defval=false, title='Show Fibonacci Levels')
showbroken = input.bool(defval=true, title='Show Broken Channel', inline='brk')
brokencol = input.color(defval=color.blue, title='', inline='brk')
upcol = input.color(defval=color.lime, title='Up/Down Trend Colors', inline='trcols')
dncol = input.color(defval=color.red, title='', inline='trcols')
widt = input(defval=2, title='Line Width')
issl = input.bool(title='SL', inline='linesl1', group='Stop Loss / Take Profit:', defval=false)
slpercent = input.float(title=', %', inline='linesl1', group='Stop Loss / Take Profit:', defval=18.0, minval=0.0, step=0.1)
istp = input.bool(title='TP', inline='linetp1', group='Stop Loss / Take Profit:', defval=false)
tppercent = input.float(title=', %', inline='linetp1', group='Stop Loss / Take Profit:', defval=18.0, minval=0.0, step=0.1)
var fibo_ratios = array.new_float(0)
var colors = array.new_color(2)
if barstate.isfirst
array.unshift(colors, upcol)
array.unshift(colors, dncol)
array.push(fibo_ratios, 0.236)
array.push(fibo_ratios, 0.382)
array.push(fibo_ratios, 0.618)
array.push(fibo_ratios, 0.786)
get_channel(src, len) =>
mid = math.sum(src, len) / len
slope = ta.linreg(src, len, 0) - ta.linreg(src, len, 1)
intercept = mid - slope * math.floor(len / 2) + (1 - len % 2) / 2 * slope
endy = intercept + slope * (len - 1)
dev = 0.0
for x = 0 to len - 1 by 1
dev += math.pow(src[x] - (slope * (len - x) + intercept), 2)
dev
dev := math.sqrt(dev / len)
[intercept, endy, dev, slope]
[y1_, y2_, dev, slope] = get_channel(src, len)
outofchannel = slope > 0 and close < y2_ - dev * devlen ? 0 : slope < 0 and close > y2_ + dev * devlen ? 2 : -1
var reglines = array.new_line(3)
var fibolines = array.new_line(4)
for x = 0 to 2 by 1
if not showbroken or outofchannel != x or nz(outofchannel[1], -1) != -1
line.delete(array.get(reglines, x))
else
line.set_color(array.get(reglines, x), color=brokencol)
line.set_width(array.get(reglines, x), width=2)
line.set_style(array.get(reglines, x), style=line.style_dotted)
line.set_extend(array.get(reglines, x), extend=extend.none)
array.set(reglines, x, line.new(x1=bar_index - (len - 1), y1=y1_ + dev * devlen * (x - 1), x2=bar_index, y2=y2_ + dev * devlen * (x - 1), color=array.get(colors, math.round(math.max(math.sign(slope), 0))), style=x % 2 == 1 ? line.style_solid : line.style_dashed, width=widt, extend=extendit ? extend.right : extend.none))
if showfibo
for x = 0 to 3 by 1
line.delete(array.get(fibolines, x))
array.set(fibolines, x, line.new(x1=bar_index - (len - 1), y1=y1_ - dev * devlen + dev * devlen * 2 * array.get(fibo_ratios, x), x2=bar_index, y2=y2_ - dev * devlen + dev * devlen * 2 * array.get(fibo_ratios, x), color=array.get(colors, math.round(math.max(math.sign(slope), 0))), style=line.style_dotted, width=widt, extend=extendit ? extend.right : extend.none))
var label sidelab = label.new(x=bar_index - (len - 1), y=y1_, text='S', size=size.large)
txt = slope > 0 ? slope > slope[1] ? '⇑' : '⇗' : slope < 0 ? slope < slope[1] ? '⇓' : '⇘' : '⇒'
stl = slope > 0 ? slope > slope[1] ? label.style_label_up : label.style_label_upper_right : slope < 0 ? slope < slope[1] ? label.style_label_down : label.style_label_lower_right : label.style_label_right
label.set_style(sidelab, stl)
label.set_text(sidelab, txt)
label.set_x(sidelab, bar_index - (len - 1))
label.set_y(sidelab, slope > 0 ? y1_ - dev * devlen : slope < 0 ? y1_ + dev * devlen : y1_)
label.set_color(sidelab, slope > 0 ? upcol : slope < 0 ? dncol : color.blue)
// Long Short conditions
longCondition = (slope < 0 and close > y2_ + dev * devlen) or (slope > 0 and close > y2_ + dev * devlen)
if longCondition
strategy.entry('Long', strategy.long)
shortCondition = (slope > 0 and close < y2_ - dev * devlen) or (slope < 0 and close < y2_ - dev * devlen)
if shortCondition
strategy.entry('Short', strategy.short)
// Entry price / Take Profit / Stop Loss
//entryprice = strategy.position_avg_price
entryprice = ta.valuewhen(condition=longCondition or shortCondition, source=close, occurrence=0)
pm = longCondition ? 1 : shortCondition ? -1 : 1 / math.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='Exit Long')
strategy.exit(id='Exit Short', from_entry='Short', stop=issl ? stoploss : na, limit=istp ? takeprofit : na, alert_message='Exit Short') |
GRB Long | https://www.tradingview.com/script/Q6jGd9xT-GRB-Long/ | omkarkondhekar | https://www.tradingview.com/u/omkarkondhekar/ | 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/
// © omkarkondhekar
//@version=4
strategy("GRBLong", overlay=true)
highInput = input(title = "High Days", type = input.integer, defval = 21, minval = 11)
lowInput = input(title = "Low Days", type = input.integer, defval = 21, minval = 5)
// Configure backtest start date with inputs
startDate = input(title="Start Date", type=input.integer,
defval=1, minval=1, maxval=31)
startMonth = input(title="Start Month", type=input.integer,
defval=1, minval=1, maxval=12)
startYear = input(title="Start Year", type=input.integer,
defval=2019, minval=1800, maxval=2100)
// See if this bar's time happened on/after start date
afterStartDate = (time >= timestamp(syminfo.timezone,
startYear, startMonth, startDate, 0, 0))
high21 = highest(high, highInput)
low21 = lowest(low, lowInput)
diff = high21 - low21
longEntrySignal = low > low21 + (diff * 0.382) and close[1] > open[1]
strategy.entry("Long", strategy.long, when = longEntrySignal and afterStartDate)
strategy.exit("Long Exit", "Long", stop = low21 + (diff * 0.236))
plot(low21 + (diff * 0.382), color= color.green)
plot(low21 + (diff * 0.236), color = color.red)
|
DMI (Multi timeframe) DI Strategy [KL] | https://www.tradingview.com/script/vG981wTz-DMI-Multi-timeframe-DI-Strategy-KL/ | DojiEmoji | https://www.tradingview.com/u/DojiEmoji/ | 245 | 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("DI+/- multi TF Strat [KL]", overlay=true, pyramiding=1, initial_capital=1000000000, default_qty_type=strategy.percent_of_equity, default_qty_value=5)
var string GROUP_ALERT = "Alerts"
var string GROUP_SL = "Stop loss"
var string GROUP_ORDER = "Order size"
var string GROUP_TP = "Profit taking"
var string GROUP_HORIZON = "Time horizon of backtests"
var string GROUP_IND = "Directional IndicatorDI+ DI-"
// ADX Indicator {
adx_len = input(14, group=GROUP_IND, tooltip="Typically 14")
tf1 = input.timeframe("", title="DI +/- in Timeframe 1", group=GROUP_IND, tooltip="Main: DI+ > DI-")
tf2 = input.timeframe("1D", title="DI +/- in Timeframe 2", group=GROUP_IND, tooltip="Confirmation: DI+ > DI-")
// adx_thres = input(20, group=GROUP_IND) //threshold not used in this strategy
get_ADX(_high, _close, _low) =>
// (high, close, mid) -> [plus_DM, minus_DM]
// Based on TradingView user BeikabuOyaji's implementation
_tr = math.max(math.max(_high - _low, math.abs(_high - nz(_close[1]))), math.abs(_low - nz(_close[1])))
smooth_tr = 0.0
smooth_tr := nz(smooth_tr[1]) - nz(smooth_tr[1]) / adx_len + _tr
smooth_directional_mov_plus = 0.0
smooth_directional_mov_plus := nz(smooth_directional_mov_plus[1]) - nz(smooth_directional_mov_plus[1]) / adx_len + (_high - nz(_high[1]) > nz(_low[1]) - _low ? math.max(_high - nz(_high[1]), 0) : 0)
smooth_directional_mov_minus = 0.0
smooth_directional_mov_minus := nz(smooth_directional_mov_minus[1]) - nz(smooth_directional_mov_minus[1]) / adx_len + (nz(_low[1]) - _low > _high - nz(_high[1]) ? math.max(nz(_low[1]) - _low, 0) : 0)
plus_DM = smooth_directional_mov_plus / smooth_tr * 100
minus_DM = smooth_directional_mov_minus / smooth_tr * 100
// DX = math.abs(plus_DM - minus_DM) / (plus_DM + minus_DM) * 100 // DX not used in this strategy
[plus_DM, minus_DM]
nrp_security(_symbol, _tf, _src) =>
// Wrapper function around request.security() - don't use developing bars
request.security(_symbol, _tf, _src[barstate.isrealtime ? 1 : 0], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
// DI +/- from timeframes 1 and 2
[plus_DM_tf1, minus_DM_tf1] = get_ADX(nrp_security(syminfo.tickerid, tf1, high), nrp_security(syminfo.tickerid, tf1, close), nrp_security(syminfo.tickerid, tf1, low))
[plus_DM_tf2, minus_DM_tf2] = get_ADX(nrp_security(syminfo.tickerid, tf2, high), nrp_security(syminfo.tickerid, tf2, close), nrp_security(syminfo.tickerid, tf2, low))
// } end of block: ADX Indicator
var string ENUM_LONG = "LONG"
var string LONG_MSG_ENTER = input.string("Long entered", title="Alert MSG for buying (Long position)", group=GROUP_ALERT)
var string LONG_MSG_EXIT = input.string("Long closed", title="Alert MSG for closing (Long position)", group=GROUP_ALERT)
backtest_timeframe_start = input.time(defval=timestamp("01 Apr 2020 13:30 +0000"), title="Backtest Start Time", group=GROUP_HORIZON)
within_timeframe = time >= backtest_timeframe_start
// Signals for entry
_uptrend_confirmed = plus_DM_tf1 > minus_DM_tf1 and plus_DM_tf2 > minus_DM_tf2
entry_signal_long = _uptrend_confirmed
plotshape(_uptrend_confirmed, style=shape.triangleup, location=location.bottom, color=color.green)
plotshape(not _uptrend_confirmed, style=shape.triangledown, location=location.bottom, color=color.red)
// Trailing stop loss ("TSL") {
tsl_multi = input.float(2.0, title="ATR Multiplier for trailing stoploss", group=GROUP_SL)
SL_buffer = ta.atr(input.int(14, title="Length of ATR for trailing stoploss", group=GROUP_SL)) * tsl_multi
TSL_source_long = low
var stop_loss_price_long = float(0)
var pos_opened_long = false
stop_loss_price_long := pos_opened_long ? math.max(stop_loss_price_long, TSL_source_long - SL_buffer) : TSL_source_long - SL_buffer
// MAIN: {
if pos_opened_long and TSL_source_long <= stop_loss_price_long
pos_opened_long := false
alert(LONG_MSG_EXIT, alert.freq_once_per_bar)
strategy.close(ENUM_LONG, comment=close < strategy.position_avg_price ? "stop loss" : "take profit")
// (2) Update the stoploss to latest trailing amt.
if pos_opened_long
strategy.exit(ENUM_LONG, stop=stop_loss_price_long, comment="SL")
// (3) INITIAL ENTRY:
if within_timeframe and entry_signal_long
pos_opened_long := true
alert(LONG_MSG_ENTER, alert.freq_once_per_bar)
strategy.entry(ENUM_LONG, strategy.long, comment="long")
// Plotting:
TSL_transp_long = pos_opened_long and within_timeframe ? 0 : 100
plot(stop_loss_price_long, color=color.new(color.green, TSL_transp_long))
// CLEAN UP: Setting variables back to default values once no longer in use
if ta.change(strategy.position_size) and strategy.position_size == 0
pos_opened_long := false
if not pos_opened_long
stop_loss_price_long := float(0)
// } end of MAIN block
|
grid strategy long | https://www.tradingview.com/script/6Nayl7hU/ | zxcvbnm3260 | https://www.tradingview.com/u/zxcvbnm3260/ | 76 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © zxcvbnm3260
//@version=5
strategy("grid strategy long", overlay=true)
// 版本更新记录:
// v1.0 2021/11/09 只做多、不做空,选择大趋势向上的时间段。网格大小默认为1倍ATR,往下1、2、3个网格吃单,第5个网格止损。空仓时到达往上一个网格则网格整体抬升。(Only go long, not short, choose a time period when the general trend is up. The default grid size is 1x ATR, the next one, two, and three grids will take orders, and the fifth grid will stop loss. When the empty position reaches the upper grid, the grid as a whole rises.)
X_ATR = input.float(title='网格大小是多少倍ATR?', defval = 1)
// 1.基础变量
ema169 = ta.ema(close, 169)
ema144 = ta.ema(close, 144)
ema12 = ta.ema(close, 12)
ema576 = ta.ema(close, 576)
ema676 = ta.ema(close, 676)
plot(ema169, color=color.new(color.orange, 0), linewidth=2)
// plot(ema144, color=color.orange)
plot(ema12, color=color.blue)
// plot(ema676, color=color.orange, linewidth=1)
mtr = math.max(high - low, math.abs(close[1] - high), math.abs(close[1] - low))
atr = ta.ema(mtr, 30)
is_0930 = hour(time, 'GMT-4') == 9 and minute(time, 'GMT-4') == 30
is_1500 = hour(time, 'GMT-4') == 15 and minute(time, 'GMT-4') == 00
is_1530 = hour(time, 'GMT-4') == 15 and minute(time, 'GMT-4') == 30
is_yangxian = close>open
is_yinxian = close<open
// 2.基本趋势标记
big_trend = ema12 >= ema169 ? 1 : 0
big_trend2 = ema12 <= ema169 ? 1 : 0
// 背景的变色处理:
bgcolor(big_trend == 1 ? color.new(color.green, 90) : color.new(color.red, 90) )
// 3.网格点位初始化
grid_size = atr * X_ATR // 网格大小
price_entry1 = open - grid_size*1
price_entry2 = open - grid_size*2
price_entry3 = open - grid_size*3
price_stop_loss = open - grid_size*5
price_exit1 = price_entry1 + grid_size*1
price_exit2 = price_entry2 + grid_size*1
price_exit3 = price_entry3 + grid_size*1
qty1 = int(1000/price_entry1)
qty2 = int(1000/price_entry2)
qty3 = int(1000/price_entry3)
// 标出各种点位
slm_lines_time(time, price_entry1, price_entry2, price_entry3, price_stop_loss, price_exit1)=>
time2 = time + 1000*3600*24*5
line.new(time, price_stop_loss, time2, price_stop_loss, color=color.red, xloc = xloc.bar_time, width=2) // 止损位
line.new(time, price_entry1, time2, price_entry1, color=color.green, xloc = xloc.bar_time) //
line.new(time, price_entry2, time2, price_entry2, color=color.green, xloc = xloc.bar_time) //
line.new(time, price_entry3, time2, price_entry3, color=color.green, xloc = xloc.bar_time) //
line.new(time, price_exit1, time2, price_exit1, color=color.green, xloc = xloc.bar_time, width=2) //
slm_lines(time, price_entry1, price_entry2, price_entry3, price_stop_loss, price_exit1)=>
line.new(bar_index, price_stop_loss, bar_index[5], price_stop_loss, color=color.red, xloc = xloc.bar_index, width=2) // 止损位
line.new(bar_index, price_entry1, bar_index[5], price_entry1, color=color.green, xloc = xloc.bar_index) //
line.new(bar_index, price_entry2, bar_index[5], price_entry2, color=color.green, xloc = xloc.bar_index) //
line.new(bar_index, price_entry3, bar_index[5], price_entry3, color=color.green, xloc = xloc.bar_index) //
line.new(bar_index, price_exit1, bar_index[5], price_exit1, color=color.green, xloc = xloc.bar_index, width=2) //
// 4.网格点位更新和下单
is_entry0 = big_trend==1 and year>=2020
var is_entry = false
// 未进场时:
if is_entry0 and not is_entry
is_entry := true
grid_size := atr * X_ATR // 网格大小
price_entry1 := close - grid_size*1
price_entry2 := close - grid_size*2
price_entry3 := close - grid_size*3
price_stop_loss := close - grid_size*5
price_exit1 := price_entry1 + grid_size*1
price_exit2 := price_entry2 + grid_size*1
price_exit3 := price_entry3 + grid_size*1
qty1 := int(1000/price_entry1)
qty2 := int(1000/price_entry2)
qty3 := int(1000/price_entry3)
// slm_lines(time, price_entry1, price_entry2, price_entry3, price_stop_loss, price_exit1)
strategy.entry("open1", strategy.long, qty1, limit = price_entry1)
strategy.entry("open2", strategy.long, qty2, limit = price_entry2)
strategy.entry("open3", strategy.long, qty3, limit = price_entry3)
strategy.exit("close1", qty = qty1, limit = price_exit1, stop = price_stop_loss)
strategy.exit("close2", qty = qty2, limit = price_exit2, stop = price_stop_loss)
strategy.exit("close3", qty = qty3, limit = price_exit3, stop = price_stop_loss)
// 已进场的各类情况
// 1.止损
if is_entry and close <= price_stop_loss
strategy.close_all()
is_entry := false
// 2.网格抬升
if is_entry and close >= price_exit1
is_entry := false
|
Low-High-Trend Strategy | https://www.tradingview.com/script/o97hSCY4-Low-High-Trend-Strategy/ | TradeAutomation | https://www.tradingview.com/u/TradeAutomation/ | 1,151 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// @version=5
// Author = TradeAutomation
strategy(title="Low-High-Trend Strategy", shorttitle="Low-High-Trend Strategy", process_orders_on_close=true, overlay=true, commission_type=strategy.commission.cash_per_order, commission_value=1, slippage=1, initial_capital = 100000000, margin_long=50, margin_short=50, default_qty_type=strategy.percent_of_equity, default_qty_value=100)
// Backtest Date Range Inputs //
StartTime = input.time(defval=timestamp('01 Jan 2000 05:00 +0000'), title='Start Time')
EndTime = input.time(defval=timestamp('01 Jan 2099 00:00 +0000'), title='End Time')
InDateRange = time>=StartTime and time<=EndTime
// Strategy Calculations //
lowcriteria = ta.lowest(close, input(20, "Lowest Price Lookback", tooltip="The strategy will BUY when the price crosses over the lowest it has been in the last X amount of bars"))[1]
highcriteria = ta.highest(close, input(10, "Highest Price Lookback", tooltip="If Take-Profit is not checked, the strategy will SELL when the price crosses under the highest it has been in the last X amount of bars"))[1]
plot(highcriteria, color=color.green)
plot(lowcriteria, color=color.red)
// Take Profit //
TakeProfitInput = input(true, "Sell with Take-Profit % intead of highest price cross?")
TakeProfit = ta.crossover(close,strategy.position_avg_price*(1+(.01*input.float(8, title="Take Profit %", step=.25))))
// Operational Functions //
TrendFilterInput = input(true, "Only buy when price is above EMA trend?")
ema = ta.ema(close, input(200, "EMA Length"))
TrendisLong = (close>ema)
plot(ema)
// Entry & Exit Functions//
if (InDateRange and TrendFilterInput==true)
strategy.entry("Long", strategy.long, when = ta.crossover(close, lowcriteria) and TrendisLong)
if (InDateRange and TrendFilterInput==false)
strategy.entry("Long", strategy.long, when = ta.crossover(close, lowcriteria))
if (InDateRange and TakeProfitInput==true)
strategy.close("Long", when = TakeProfit)
if (InDateRange and TakeProfitInput==false)
strategy.close("Long", when = ta.crossunder(close, highcriteria))
if (not InDateRange)
strategy.close_all()
|
Swing VWAP Crypto and Stocks Strategy | https://www.tradingview.com/script/rAwb2sPd-Swing-VWAP-Crypto-and-Stocks-Strategy/ | exlux99 | https://www.tradingview.com/u/exlux99/ | 310 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © exlux99
//@version=5
strategy('VWAP strategy ', overlay=true, initial_capital=100, default_qty_type=strategy.percent_of_equity, default_qty_value=100, calc_on_every_tick=true, commission_type=strategy.commission.percent, commission_value=0.03)
long = close> ta.vwap and close[1] < ta.vwap
stopPer = input.float(10.0, title='LONG Stop Loss % ', group='Fixed Risk Management') / 100
takePer = input.float(29.0, title='LONG Take Profit %', group='Fixed Risk Management') / 100
longStop = strategy.position_avg_price * (1 - stopPer)
longTake = strategy.position_avg_price * (1 + takePer)
strategy.entry("long",strategy.long,when=long and dayofweek==dayofweek.monday)
strategy.exit('LONG EXIT', "long", limit=longTake, stop=longStop)
strategy.close_all(when=dayofweek==dayofweek.sunday)
|
Swing Multi Moving Averages Crypto and Stocks Strategy | https://www.tradingview.com/script/9qO85KUb-Swing-Multi-Moving-Averages-Crypto-and-Stocks-Strategy/ | exlux99 | https://www.tradingview.com/u/exlux99/ | 306 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © exlux99
//@version=5
strategy('Time MA strategy ', overlay=true, initial_capital=100, default_qty_type=strategy.percent_of_equity, default_qty_value=100, calc_on_every_tick=true, commission_type=strategy.commission.percent, commission_value=0.03)
longEntry = input.bool(true, group="Type of Entries")
shortEntry = input.bool(false, group="Type of Entries")
//==========DEMA
getDEMA(src, len) =>
dema = 2 * ta.ema(src, len) - ta.ema(ta.ema(src, len), len)
dema
//==========HMA
getHULLMA(src, len) =>
hullma = ta.wma(2 * ta.wma(src, len / 2) - ta.wma(src, len), math.round(math.sqrt(len)))
hullma
//==========KAMA
getKAMA(src, len, k1, k2) =>
change = math.abs(ta.change(src, len))
volatility = math.sum(math.abs(ta.change(src)), len)
efficiency_ratio = volatility != 0 ? change / volatility : 0
kama = 0.0
fast = 2 / (k1 + 1)
slow = 2 / (k2 + 1)
smooth_const = math.pow(efficiency_ratio * (fast - slow) + slow, 2)
kama := nz(kama[1]) + smooth_const * (src - nz(kama[1]))
kama
//==========TEMA
getTEMA(src, len) =>
e = ta.ema(src, len)
tema = 3 * (e - ta.ema(e, len)) + ta.ema(ta.ema(e, len), len)
tema
//==========ZLEMA
getZLEMA(src, len) =>
zlemalag_1 = (len - 1) / 2
zlemadata_1 = src + src - src[zlemalag_1]
zlema = ta.ema(zlemadata_1, len)
zlema
//==========FRAMA
getFRAMA(src, len) =>
Price = src
N = len
if N % 2 != 0
N := N + 1
N
N1 = 0.0
N2 = 0.0
N3 = 0.0
HH = 0.0
LL = 0.0
Dimen = 0.0
alpha = 0.0
Filt = 0.0
N3 := (ta.highest(N) - ta.lowest(N)) / N
HH := ta.highest(N / 2 - 1)
LL := ta.lowest(N / 2 - 1)
N1 := (HH - LL) / (N / 2)
HH := high[N / 2]
LL := low[N / 2]
for i = N / 2 to N - 1 by 1
if high[i] > HH
HH := high[i]
HH
if low[i] < LL
LL := low[i]
LL
N2 := (HH - LL) / (N / 2)
if N1 > 0 and N2 > 0 and N3 > 0
Dimen := (math.log(N1 + N2) - math.log(N3)) / math.log(2)
Dimen
alpha := math.exp(-4.6 * (Dimen - 1))
if alpha < .01
alpha := .01
alpha
if alpha > 1
alpha := 1
alpha
Filt := alpha * Price + (1 - alpha) * nz(Filt[1], 1)
if bar_index < N + 1
Filt := Price
Filt
Filt
//==========VIDYA
getVIDYA(src, len) =>
mom = ta.change(src)
upSum = math.sum(math.max(mom, 0), len)
downSum = math.sum(-math.min(mom, 0), len)
out = (upSum - downSum) / (upSum + downSum)
cmo = math.abs(out)
alpha = 2 / (len + 1)
vidya = 0.0
vidya := src * alpha * cmo + nz(vidya[1]) * (1 - alpha * cmo)
vidya
//==========JMA
getJMA(src, len, power, phase) =>
phase_ratio = phase < -100 ? 0.5 : phase > 100 ? 2.5 : phase / 100 + 1.5
beta = 0.45 * (len - 1) / (0.45 * (len - 1) + 2)
alpha = math.pow(beta, power)
MA1 = 0.0
Det0 = 0.0
MA2 = 0.0
Det1 = 0.0
JMA = 0.0
MA1 := (1 - alpha) * src + alpha * nz(MA1[1])
Det0 := (src - MA1) * (1 - beta) + beta * nz(Det0[1])
MA2 := MA1 + phase_ratio * Det0
Det1 := (MA2 - nz(JMA[1])) * math.pow(1 - alpha, 2) + math.pow(alpha, 2) * nz(Det1[1])
JMA := nz(JMA[1]) + Det1
JMA
//==========T3
getT3(src, len, vFactor) =>
ema1 = ta.ema(src, len)
ema2 = ta.ema(ema1, len)
ema3 = ta.ema(ema2, len)
ema4 = ta.ema(ema3, len)
ema5 = ta.ema(ema4, len)
ema6 = ta.ema(ema5, len)
c1 = -1 * math.pow(vFactor, 3)
c2 = 3 * math.pow(vFactor, 2) + 3 * math.pow(vFactor, 3)
c3 = -6 * math.pow(vFactor, 2) - 3 * vFactor - 3 * math.pow(vFactor, 3)
c4 = 1 + 3 * vFactor + math.pow(vFactor, 3) + 3 * math.pow(vFactor, 2)
T3 = c1 * ema6 + c2 * ema5 + c3 * ema4 + c4 * ema3
T3
//==========TRIMA
getTRIMA(src, len) =>
N = len + 1
Nm = math.round(N / 2)
TRIMA = ta.sma(ta.sma(src, Nm), Nm)
TRIMA
src = input.source(close, title='Source', group='Parameters')
len = input.int(17, minval=1, title='Moving Averages', group='Parameters')
out_ma_source = input.string(title='MA Type', defval='ALMA', options=['SMA', 'EMA', 'WMA', 'ALMA', 'SMMA', 'LSMA', 'VWMA', 'DEMA', 'HULL', 'KAMA', 'FRAMA', 'VIDYA', 'JMA', 'TEMA', 'ZLEMA', 'T3', 'TRIM'], group='Parameters')
out_ma = out_ma_source == 'SMA' ? ta.sma(src, len) : out_ma_source == 'EMA' ? ta.ema(src, len) : out_ma_source == 'WMA' ? ta.wma(src, len) : out_ma_source == 'ALMA' ? ta.alma(src, len, 0.85, 6) : out_ma_source == 'SMMA' ? ta.rma(src, len) : out_ma_source == 'LSMA' ? ta.linreg(src, len, 0) : out_ma_source == 'VWMA' ? ta.vwma(src, len) : out_ma_source == 'DEMA' ? getDEMA(src, len) : out_ma_source == 'HULL' ? ta.hma(src, len) : out_ma_source == 'KAMA' ? getKAMA(src, len, 2, 30) : out_ma_source == 'FRAMA' ? getFRAMA(src, len) : out_ma_source == 'VIDYA' ? getVIDYA(src, len) : out_ma_source == 'JMA' ? getJMA(src, len, 2, 50) : out_ma_source == 'TEMA' ? getTEMA(src, len) : out_ma_source == 'ZLEMA' ? getZLEMA(src, len) : out_ma_source == 'T3' ? getT3(src, len, 0.7) : out_ma_source == 'TRIM' ? getTRIMA(src, len) : na
plot(out_ma)
long = close> out_ma and close[1] < out_ma and dayofweek==dayofweek.monday
short = close< out_ma and close[1] > out_ma and dayofweek==dayofweek.monday
stopPer = input.float(10.0, title='LONG Stop Loss % ', group='Fixed Risk Management') / 100
takePer = input.float(30.0, title='LONG Take Profit %', group='Fixed Risk Management') / 100
stopPerShort = input.float(5.0, title='SHORT Stop Loss % ', group='Fixed Risk Management') / 100
takePerShort = input.float(10.0, title='SHORT Take Profit %', group='Fixed Risk Management') / 100
longStop = strategy.position_avg_price * (1 - stopPer)
longTake = strategy.position_avg_price * (1 + takePer)
shortStop = strategy.position_avg_price * (1 + stopPerShort)
shortTake = strategy.position_avg_price * (1 - takePerShort)
strategy.risk.max_intraday_filled_orders(2) // After 10 orders are filled, no more strategy orders will be placed (except for a market order to exit current open market position, if there is any).
if(longEntry)
strategy.entry("long",strategy.long,when=long )
strategy.exit('LONG EXIT', "long", limit=longTake, stop=longStop)
strategy.close("long",when=dayofweek==dayofweek.sunday)
if(shortEntry)
strategy.entry("short",strategy.short,when=short )
strategy.exit('SHORT EXIT', "short", limit=shortTake, stop=shortStop)
strategy.close("short",when=dayofweek==dayofweek.sunday)
|
ATR + STC + MA | https://www.tradingview.com/script/nx2eFkZe-ATR-STC-MA/ | Romedius | https://www.tradingview.com/u/Romedius/ | 66 | 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/
// © Romedius
//@version=5
strategy("My Strategy", overlay=true, margin_long=100, margin_short=100)
// STC
EEEEEE=input(12,"Length",group="STC")
BBBB=input(26,"FastLength",group="STC")
BBBBB=input(50,"SlowLength",group="STC")
AAAA(BBB, BBBB, BBBBB) =>
fastMA = ta.ema(BBB, BBBB)
slowMA = ta.ema(BBB, BBBBB)
AAAA = fastMA - slowMA
AAAA
AAAAA(EEEEEE, BBBB, BBBBB) =>
//AAA=input(0.5)
var AAA = 0.5
var CCCCC = 0.0
var DDD = 0.0
var DDDDDD = 0.0
var EEEEE = 0.0
BBBBBB = AAAA(close,BBBB,BBBBB)
CCC = ta.lowest(BBBBBB, EEEEEE)
CCCC = ta.highest(BBBBBB, EEEEEE) - CCC
CCCCC := (CCCC > 0 ? ((BBBBBB - CCC) / CCCC) * 100 : nz(CCCCC[1]))
DDD := (na(DDD[1]) ? CCCCC : DDD[1] + (AAA * (CCCCC - DDD[1])))
DDDD = ta.lowest(DDD, EEEEEE)
DDDDD = ta.highest(DDD, EEEEEE) - DDDD
DDDDDD := (DDDDD > 0 ? ((DDD - DDDD) / DDDDD) * 100 : nz(DDDDDD[1]))
EEEEE := (na(EEEEE[1]) ? DDDDDD : EEEEE[1] + (AAA * (DDDDDD - EEEEE[1])))
EEEEE
mAAAAA = AAAAA(EEEEEE,BBBB,BBBBB)
stc = mAAAAA > mAAAAA[1] ? true : false
stc_sig = stc == true and stc[1] == false ? 1 : stc == false and stc[1] == true ? -1 : 0
stc_long = stc_sig == 1
stc_short = stc_sig == -1
// STC end
// ATR stops
nATRPeriod = input(5,group="ATR Stops")
nATRMultip = input(3.5,group="ATR Stops")
xATR = ta.atr(nATRPeriod)
nLoss = nATRMultip * xATR
xATRTrailingStop = 0.0
xATRTrailingStop := close > nz(xATRTrailingStop[1], 0) and close[1] > nz(xATRTrailingStop[1], 0) ? math.max(nz(xATRTrailingStop[1]), close - nLoss) : close < nz(xATRTrailingStop[1], 0) and close[1] < nz(xATRTrailingStop[1], 0) ? math.min(nz(xATRTrailingStop[1]), close + nLoss) : close > nz(xATRTrailingStop[1], 0) ? close - nLoss : close + nLoss
pos = 0
pos := close[1] < nz(xATRTrailingStop[1], 0) and close > nz(xATRTrailingStop[1], 0) ? 1 : close[1] > nz(xATRTrailingStop[1], 0) and close < nz(xATRTrailingStop[1], 0) ? -1 : nz(pos[1], 0)
atr_sig = pos == -1 ? false : true
// ATR stops end
// ma
ma_len = input(200, title="MA Length", group="Moving Average")
ma = ta.sma(close, 200)
ma_sig = close < ma ? false : true
// ma end
// strategy entries
tp_mult = input(2, title="Take Profit ATR Multiplier", group="Strategy")
sl_mult = input(1, title="Stop Loss ATR Multiplier", group="Strategy")
early_stop = input(true, title="Close position when ATR changes color")
atr_stop = if close < xATRTrailingStop
close - (close - xATRTrailingStop) * sl_mult
else
close + (xATRTrailingStop - close) * sl_mult
longCondition = atr_sig == true and stc_sig == 1 and ma_sig == true
shortCondition = atr_sig == false and stc_sig == -1 and ma_sig == false
if (longCondition)
strategy.entry("Long", strategy.long)
strategy.exit("Exit Long", "Long", limit=close + xATR * tp_mult, stop=atr_stop)
else if atr_sig == false and early_stop
strategy.close("Long")
if (shortCondition)
strategy.entry("Short", strategy.short)
strategy.exit("Exit Short", "Short", limit=close - xATR * tp_mult, stop=atr_stop)
else if atr_sig == true and early_stop
strategy.close("Short")
// plot stuff
atr_color = pos == -1 ? color.red: pos == 1 ? color.green : color.blue
plot(atr_stop, title="ATR Stop", color=atr_color)
ma_color = ma_sig ? color.green : color.red
plot(ma, title="Moving Average", color=ma_color)
stc_color = stc_long ? color.green : color.red
plotshape(stc_long, style=shape.triangleup, color=stc_color, title="STC Long Signal", size=size.tiny)
plotshape(stc_short, style=shape.triangledown, color=stc_color, title="STC Short Signal", size=size.tiny)
// plot stuff end |
DC Breakout Strategy | This is simplicity at its finest. | https://www.tradingview.com/script/t8RsAhP7-DC-Breakout-Strategy-This-is-simplicity-at-its-finest/ | Robrecht99 | https://www.tradingview.com/u/Robrecht99/ | 172 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Robrecht99
//@version=5
strategy("Simplicity at its finest", overlay=true, margin_long=0, margin_short=0, pyramiding=3)
// Backtest Range //
Start = input.time(defval = timestamp("01 Jan 2017 00:00 +0000"), title = "Backtest Start Date", group = "backtest window")
Finish = input.time(defval = timestamp("01 Jan 2100 00:00 +0000"), title = "Backtest End Date", group = "backtest window")
// Moving Averages //
len1 = input.int(8, minval=1, title="Length Fast MA", group="Moving Average Inputs")
len2 = input.int(32, minval=1, title="Length Slow MA", group="Moving Average Inputs")
src1 = input(close, title="Source Fast MA")
src2 = input(close, title="Source Slow MA")
maFast = input.color(color.new(color.red, 0), title = "Color Fast MA", group = "Moving Average Inputs", inline = "maFast")
maSlow = input.color(color.new(color.purple, 0), title = "Color Slow MA", group = "Moving Average Inputs", inline = "maSlow")
fast = ta.sma(src1, len1)
slow = ta.sma(src2, len2)
plot(fast, color=maFast, title="Fast MA")
plot(slow, color=maSlow, title="Slow MA")
// Donchian Channels //
Length1 = input.int(title="Length Upper Channel", defval=20, minval=1, group="Donchian Channels Inputs")
Length2 = input.int(title="Length Lower Channel", defval=20, minval=1, group="Donchian Channels Inputs")
h1 = ta.highest(high[1], Length1)
l1 = ta.lowest(low[1], Length2)
fillColor = input.color(color.new(color.gray, 100), title = "Fill Color", group = "Donchian Channels Inputs")
upperColor = input.color(color.new(color.white, 0), title = " Color Upper Channel", group = "Donchian Channels Inputs", inline = "upper")
lowerColor = input.color(color.new(color.white, 0), title = " Color Lower Channel", group = "Donchian Channels Inputs", inline = "lower")
u = plot(h1, "Upper", color=upperColor)
l = plot(l1, "Lower", color=upperColor)
fill(u, l, color=fillColor)
// ATR and Position Size //
leverage = input.int(title = "Leverage Used", defval = 1, minval = 1, group = "ATR Position Size Inputs")
pointvalue = input.int(title = "Point Value/ATR Multipliers from Entry", defval = 4, minval = 1, group = "ATR Position Size Inputs")
length = input.int(title = "ATR Period", defval = 14, minval = 1, group ="ATR Position Size Inputs")
risk = input(title = "Risk Per Trade", defval = 0.01, group = "ATR Position Size Inputs")
atr = ta.atr(length)
amount = (risk * strategy.initial_capital / (pointvalue * atr * leverage))
// Buy and Sell Conditions //
entrycondition1 = ta.crossover(fast, slow)
entrycondition2 = fast > slow
sellcondition1 = ta.crossunder(fast, slow)
sellcondition2 = slow > fast
// Buy and Sell Signals //
if (close > h1 and entrycondition2)
strategy.entry("long", strategy.long, qty=amount)
if (sellcondition1 and sellcondition2)
strategy.close(id="long")
if (close < l1 and sellcondition2)
strategy.entry("short", strategy.short, qty=amount)
if (entrycondition1 and entrycondition2)
strategy.close(id="short") |
OBV MA Strategy | https://www.tradingview.com/script/Jgo8w4m1-OBV-MA-Strategy/ | sonnyparlin | https://www.tradingview.com/u/sonnyparlin/ | 236 | 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/
// © sonnyparlin
//@version=5
strategy("OBV Strategy V2", overlay=true,
commission_type=strategy.commission.percent,
currency=currency.USD,
commission_value=0.075,
slippage=2, initial_capital=10000)
plot(close)
// Removed script |
No-lose trading targets (Based on EoRfA) By Mustafa ÖZVER | https://www.tradingview.com/script/iCzeNf6N/ | Mustafaozver | https://www.tradingview.com/u/Mustafaozver/ | 397 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Mustafaozver
//@version=4
strategy("No-lose trading targets (Based on EoRfA) By Mustafa ÖZVER", "NLTT_EoRfA_STRATEGY", overlay=true)
ref = input(hlc3)
var line U_AREA_LINE = na
var line D_AREA_LINE = na
BUY__AREA = 0
SELL_AREA = 0
// EoRfA
FPrice = wma((vwap + ref),3)
len = input(13,"Length")
limit0 = 1 // natural action
limit1 = 1.66 // wave edge
limit2 = 2.58 // way to infinitive
limit3 = 2.72 // hard breakout
limit = input(1.68)
stdev = stdev(FPrice,len)
ema = ema(FPrice,len)
vEorfa = (FPrice - ema) / stdev
BUY__SIGNAL = (vEorfa < -limit and change(vEorfa) > 0) ? 1 : 0
SELL_SIGNAL = (vEorfa > +limit and change(vEorfa) < 0) ? 1 : 0
U_AREA_ = min(ohlc4,hlc3,hl2,open,close)
D_AREA_ = max(ohlc4,hlc3,hl2,open,close)
U_AREA = U_AREA_
D_AREA = D_AREA_
maxLine = high
minLine = low
BUY__AREA := nz(BUY__SIGNAL[1],0) == 1 ? 1 : (nz(BUY__AREA[1],0) == 1 ? 1 : 0)
SELL_AREA := nz(SELL_SIGNAL[1],0) == 1 ? 1 : (nz(SELL_AREA[1],0) == 1 ? 1 : 0)
U_AREA := SELL_AREA == 1 ? nz(U_AREA[1],U_AREA_) : U_AREA_
D_AREA := BUY__AREA == 1 ? nz(D_AREA[1],D_AREA_) : D_AREA_
maxLine := SELL_AREA == 1 ? max(nz(maxLine[1],0),high) : high
minLine := BUY__AREA == 1 ? min(nz(minLine[1],0),low) : low
refLine = plot(ref,color=#00000000,display=display.none,offset=1)
D_Line = plot(D_AREA,color=BUY__AREA==1?#00FF00A0:#00000000,linewidth=2,offset=2)
U_Line = plot(U_AREA,color=SELL_AREA==1?#FF0000A0:#00000000,linewidth=2,offset=2)
fibo_0236 = input(0.23606797749979)
fibo_0381 = input(0.38196601125011)
fibo_0500 = input(0.5)
fibo_0618 = input(0.61803398874990)
fibo_0763 = input(0.76393202250021)
fibo_1618 = input(1.61803398874990)
SelllineforBuying = fibo_0763 * (D_AREA - minLine) + minLine
BuylineforSelling = fibo_0236 * (maxLine - U_AREA) + U_AREA
//if (U_AREA < close)
// line.set_x2(U_AREA_LINE,bar_index)
//if (D_AREA > close)
// line.set_x2(D_AREA_LINE,bar_index)
if (U_AREA >= min(close,open) or BUY__SIGNAL == 1 or nz(BuylineforSelling[1],low) > close)
SELL_AREA := 0
if (D_AREA <= max(close,open) or SELL_SIGNAL == 1 or nz(SelllineforBuying[1],high) < close)
BUY__AREA := 0
if (SELL_AREA == 0 and SELL_SIGNAL == 1)
U_AREA_LINE := line.new(bar_index-1, U_AREA, bar_index+5, U_AREA, xloc.bar_index, extend.none, #FF0000A0, line.style_solid, 3)
if (BUY__AREA == 0 and BUY__SIGNAL == 1)
D_AREA_LINE := line.new(bar_index-1, D_AREA, bar_index+5, D_AREA, xloc.bar_index, extend.none, #00FF00A0, line.style_solid, 3)
//fill(D_Line, refLine, color=BUY__AREA==1?#00FF0020:#00000000)
//fill(U_Line, refLine, color=SELL_AREA==1?#FF000020:#00000000)
// draw fibonacci
max_ = BUY__AREA == 1 ? D_AREA : (SELL_AREA == 1 ? maxLine : ref)
min_ = SELL_AREA == 1 ? U_AREA : (BUY__AREA == 1 ? minLine : ref)
tolerance = input(0.015)
verify_Revision = change(max_ + min_) == 0 and max_/min_ > (tolerance+1)
verify_Draw = (BUY__AREA == 1 or SELL_AREA == 1) and verify_Revision
fibo_rate = (close - min_) / (max_ - min_)
fibo_0000_line = plot(min_,color=(BUY__AREA==1 and verify_Revision)?#FFFFFF80:#00000000,linewidth=2)
fibo_1000_line = plot(max_,color=(SELL_AREA==1 and verify_Revision)?#FFFFFF80:#00000000,linewidth=2)
fibo_1618_line1 = plot((max_ - min_)*fibo_1618 + min_,color=(verify_Draw?#FF000050:#00000000),linewidth=2)
fibo_1618_line2 = plot(-(max_ - min_)*fibo_1618 + min_,color=(verify_Draw?#00FF0050:#00000000),linewidth=2)
fibo_0236_line = plot((max_ - min_)*fibo_0236 + min_,color=(verify_Draw?#FFFFFF50:#00000000),linewidth=1)
fibo_0381_line = plot((max_ - min_)*fibo_0381 + min_,color=(verify_Draw?#00FF0080:#00000000),linewidth=1)
fibo_0500_line = plot((max_ - min_)*fibo_0500 + min_,color=(verify_Draw?#FFFFFF50:#00000000),linewidth=1)
fibo_0618_line = plot((max_ - min_)*fibo_0618 + min_,color=(verify_Draw?#FF000080:#00000000),linewidth=1)
fibo_0763_line = plot((max_ - min_)*fibo_0763 + min_,color=(verify_Draw?#FFFFFF50:#00000000),linewidth=1)
fill(fibo_0236_line, fibo_0381_line, color=verify_Draw==1?#00FF0020:#00000000)
fill(fibo_0763_line, fibo_0618_line, color=verify_Draw==1?#FF000020:#00000000)
//min_Line = plot(SelllineforBuying,color=BUY__AREA==1?#FF000080:#00000000,linewidth=2)
//max_Line = plot(BuylineforSelling,color=SELL_AREA==1?#00FF0080:#00000000,linewidth=2)
plotshape(BUY__SIGNAL == 1 and BUY__AREA == 0,style=shape.triangledown,location=location.abovebar,color=#00FF00FF,size=size.auto)
plotshape(SELL_SIGNAL == 1 and SELL_AREA == 0,style=shape.triangleup, location=location.belowbar,color=#FF0000FF,size=size.auto)
// Report
var label lbl = na
label.delete(lbl)
if (verify_Draw)
var string reports = ""
reports := reports + (BUY__AREA==1?"LONG":"")
reports := reports + (SELL_AREA==1?"SHORT":"")
reports := reports + " SETUP => % " + tostring(round((max_-min_)*0.5/close*10000)/100)
lbl := label.new(x=barstate.islast ? time : na,y=max_,text=reports,xloc=xloc.bar_time,color=#2020AA,textcolor=#FFFFFF)
reports := ""
//alertcondition(condition=verify_Draw, title="Trading Setup from NLTTa_EoRfA", message="Trading setup action from NLTTa based on EoRfA")
EXIT_PRICE = 0.0
EXIT_PRICE := nz(EXIT_PRICE[1],0.0)
if (BUY__AREA == 1 and verify_Draw and strategy.position_size == 0.0 and fibo_rate < fibo_0381 and fibo_rate > fibo_0236 and change(vEorfa) > 0)
strategy.order("LONG1",true)
EXIT_PRICE := (max_ - min_)*fibo_0618 + min_
if (EXIT_PRICE < close and strategy.position_size > 0)
//line.new(bar_index-1, U_AREA*1.03, bar_index+1, U_AREA*0.97, xloc.bar_index, extend.none, #FFFFFF, line.style_solid, 3)
strategy.close("LONG1")
EXIT_PRICE := 0.0
if (SELL_AREA == 1 and verify_Draw and strategy.position_size == 0.0 and fibo_rate < fibo_0763 and fibo_rate > fibo_0618 and change(vEorfa) < 0)
strategy.order("SHORT1",false)
EXIT_PRICE := (max_ - min_)*fibo_0381 + min_
if (EXIT_PRICE > close and strategy.position_size < 0)
//line.new(bar_index-1, U_AREA*1.03, bar_index+1, U_AREA*0.97, xloc.bar_index, extend.none, #FFFFFF, line.style_solid, 3)
strategy.close("SHORT1")
EXIT_PRICE := 0.0 |
Moon Phases Strategy [LuxAlgo] | https://www.tradingview.com/script/yvDyq0pv-Moon-Phases-Strategy-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 3,754 | strategy | 4 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © LuxAlgo
//@version=4
strategy("Moon Phases Strategy [LuxAlgo]", overlay=true,process_orders_on_close=true)
new = input(title="New Moon Reference Date", type=input.time, defval=timestamp("2021-01-13:05:00"))
buy = input('Full Moon',options=['New Moon','Full Moon','Higher Moon','Lower Moon'],inline='buy')
sell = input('New Moon',options=['New Moon','Full Moon','Higher Moon','Lower Moon'],inline='sell')
longcol = input(color.new(#2157f3,80),'',inline='buy')
shortcol = input(color.new(#ff1100,80),'',inline='sell')
//----
n = bar_index
cycle = 2551442876.8992
day = 8.64e+7
diff = (new + time + day*2)%cycle/cycle
//----
newmoon = crossover(diff,.5)
fullmoon = diff < diff[1]
plotshape(newmoon ? low : na,"New Moon",shape.labelup,location.top,na,0,text="🌑",size=size.tiny)
plotshape(fullmoon ? high : na,"Full Moon",shape.labeldown,location.bottom,na,0,text="🌕",size=size.tiny)
//----
src = close
var bool long = na
var bool short = na
if buy == 'New Moon'
long := newmoon
else if buy == 'Full Moon'
long := fullmoon
else if buy == 'Higher Moon'
long := valuewhen(newmoon or fullmoon,src,0) > valuewhen(newmoon or fullmoon,src,1)
else
long := valuewhen(newmoon or fullmoon,src,0) < valuewhen(newmoon or fullmoon,src,1)
//----
if sell == 'New Moon'
short := newmoon
else if sell == 'Full Moon'
short := fullmoon
else if sell == 'Higher Moon'
short := valuewhen(newmoon or fullmoon,src,0) > valuewhen(newmoon or fullmoon,src,1)
else
short := valuewhen(newmoon or fullmoon,src,0) < valuewhen(newmoon or fullmoon,src,1)
//----
var pos = 0
if long
pos := 1
strategy.close("Short")
strategy.entry("Long", strategy.long)
if short
pos := -1
strategy.close("Long")
strategy.entry("Short", strategy.short)
bgcolor(pos == 1 ? longcol : shortcol) |
[001] Entry_Test [TradeStand] | https://www.tradingview.com/script/eCV5ib4r/ | Strategy_Distributor | https://www.tradingview.com/u/Strategy_Distributor/ | 20 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Dr_KV
//@version=4
strategy("[001] Entry_Test [TradeStand]", overlay=true)
strategy_code = "tradestand"
//////////////////////////////////
//
// インプット
//
//////////////////////////////////
Section1 = input(title = "▒▒▒▒▒▒▒▒▒▒▒▒▒ トレードモード ▒▒▒▒▒▒▒▒▒▒▒▒▒", defval = true, type = input.bool)
int_TradeMode = input("OFF", options = ["OFF","新規買い","新規売り","返済買い","返済売り"], title = "トレードモード")
Section71 = input(title = "▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ 表 示 ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒", defval = true, type = input.bool)
int_MA_monitor = input("OFF", options = ["OFF","ON"], title = "日足MA表示")
Section3 = input(title = "▒▒▒▒▒▒▒▒▒▒▒▒▒▒ トレード条件 ▒▒▒▒▒▒▒▒▒▒▒▒▒", defval = true, type = input.bool)
i_startTime = input(defval = timestamp("18 oct 2021 13:30 +0900"), title = "実行日時", type = input.time)
i_byou = input(0, minval = 0, maxval = 59, title = " 秒数")
int_EntryLimit_cMA_switch = "OFF"
int_EntryLimit_cMA_MA = "OFF"
int_EntryLimit_cMA_jg_switch = "超えたら"
//////////////////////////////////
//
// 素材
//
//////////////////////////////////
//移動平均線 //////////////////////////////////////////////////////////////////////////////////////////////////////
//当日~3日前 4本値
var float open_today = open
var float high_today = open
var float low_today = open
var float open_yesterday = open
var float high_yesterday = high
var float low_yesterday = low
var float open_2days_ago = open
var float high_2days_ago = high
var float low_2days_ago = low
var float open_3days_ago = open
var float high_3days_ago = high
var float low_3days_ago = low
var float close_yesterday = close
var float close_2days_ago = close
var float close_3days_ago = close
var float close_4days_ago = close
var float close_5days_ago = close
var float close_6days_ago = close
var float close_7days_ago = close
var float close_8days_ago = close
var float close_9days_ago = close
var float close_10days_ago = close
var float close_11days_ago = close
var float close_12days_ago = close
var float close_13days_ago = close
var float close_14days_ago = close
var float close_15days_ago = close
var float close_16days_ago = close
var float close_17days_ago = close
var float close_18days_ago = close
var float close_19days_ago = close
var float close_20days_ago = close
var float close_21days_ago = close
var float close_22days_ago = close
var float close_23days_ago = close
var float close_24days_ago = close
if(dayofweek[1] != dayofweek)
open_today := open
high_today := high
low_today := low
open_yesterday := open_today[1]
high_yesterday := high_today[1]
low_yesterday := low_today[1]
open_2days_ago := open_yesterday[1]
high_2days_ago := high_yesterday[1]
low_2days_ago := low_yesterday[1]
open_3days_ago := open_2days_ago[1]
high_3days_ago := high_2days_ago[1]
low_3days_ago := low_2days_ago[1]
close_yesterday := close[1]
close_2days_ago := close_yesterday[1]
close_3days_ago := close_2days_ago[1]
close_4days_ago := close_3days_ago[1]
close_5days_ago := close_4days_ago[1]
close_6days_ago := close_5days_ago[1]
close_7days_ago := close_6days_ago[1]
close_8days_ago := close_7days_ago[1]
close_9days_ago := close_8days_ago[1]
close_10days_ago:=close_9days_ago[1]
close_11days_ago:=close_10days_ago[1]
close_12days_ago:=close_11days_ago[1]
close_13days_ago:=close_12days_ago[1]
close_14days_ago:=close_13days_ago[1]
close_15days_ago:=close_14days_ago[1]
close_16days_ago:=close_15days_ago[1]
close_17days_ago:=close_16days_ago[1]
close_18days_ago:=close_17days_ago[1]
close_19days_ago:=close_18days_ago[1]
close_20days_ago:=close_19days_ago[1]
close_21days_ago:=close_20days_ago[1]
close_22days_ago:=close_21days_ago[1]
close_23days_ago:=close_22days_ago[1]
close_24days_ago:=close_23days_ago[1]
//日々カウント
var int var_everyday_cnt = 1
if(dayofweek[1] != dayofweek )
var_everyday_cnt := var_everyday_cnt +1
//短期 中期 長期 基準 MA
[ma_short_D,ma_short_prev_D,ma_short_prev2_D,ma_middle_D,ma_middle_prev_D,ma_middle_prev2_D,ma_long,ma_long_prev,ma_long_prev2] = security(syminfo.tickerid, "D", [sma(close, 5)[0],sma(close, 5)[1],sma(close, 5)[2],sma(close, 25)[0],sma(close, 25)[1],sma(close, 25)[2],sma(close, 75)[0],sma(close, 75)[1],sma(close, 75)[2]], barmerge.gaps_off, barmerge.lookahead_off)
ma_short = var_everyday_cnt < 5 ? ma_short_D : (close + close_yesterday + close_2days_ago + close_3days_ago + close_4days_ago )/5
ma_middle = var_everyday_cnt < 25 ? ma_middle_D : (close + close_yesterday + close_2days_ago + close_3days_ago + close_4days_ago + close_5days_ago + close_6days_ago + close_7days_ago + close_8days_ago + close_9days_ago + close_10days_ago + close_11days_ago + close_12days_ago + close_13days_ago + close_14days_ago + close_15days_ago + close_16days_ago + close_17days_ago + close_18days_ago + close_19days_ago + close_20days_ago + close_21days_ago + close_22days_ago + close_23days_ago + close_24days_ago)/25
ma_short_monitor = int_MA_monitor == "ON" ? ma_short : close
ma_middle_monitor = int_MA_monitor == "ON" ? ma_short : close
ma_long_monitor = int_MA_monitor == "ON" ? ma_long : close
plot(ma_short_monitor, color = int_MA_monitor == "ON" ? color.aqua : na, linewidth=2, title="日足5MA")
plot(ma_middle_monitor, color = int_MA_monitor == "ON" ? color.yellow : na , linewidth=2, title="日足25MA")
plot(ma_long_monitor, color = int_MA_monitor == "ON" ? color.lime : na , linewidth=2, title="日足75MA")
//////////////////////////////////
//
// ロジック
//
//////////////////////////////////
// 実行時間 //////////////////////////////////////////////////////////////////////////////////////////////////////
inDateRange = time >= i_startTime
var int var_byou = 0
if(dayofweek[1] != dayofweek)
var_byou := 0
if(inDateRange[1] == false and inDateRange == true )
var_byou := time + i_byou*1000
//inDateRange_2 = 実行時間満たし
inDateRange_2 = time >= var_byou and inDateRange
// 日足MA基準トレード ////////////////////////////////////////////////////////////////////////////
ver_EntryLimit_cMA_line = int_EntryLimit_cMA_MA == "5MA" ? ma_short : int_EntryLimit_cMA_MA == "25MA" ? ma_middle : int_EntryLimit_cMA_MA == "75MA" ? ma_long : close
Condition_EntryLimit_cMA_buysell = (int_EntryLimit_cMA_switch == "OFF") ? true :
(int_EntryLimit_cMA_jg_switch == "超えたら" and close > ver_EntryLimit_cMA_line)
or
(int_EntryLimit_cMA_jg_switch == "割ったら" and close < ver_EntryLimit_cMA_line)
//////////////////////////////////
//
// ロジック まとめ
//
//////////////////////////////////
logic_pass = inDateRange_2
and Condition_EntryLimit_cMA_buysell
//////////////////////////////////
//
// 処理まとめ
//
//////////////////////////////////
var int var_position_count = 0
var int var_position_count_entry_only = 0
//ポジション取ったよ
if(var_position_count == 0 and strategy.position_size[1] == 0 and strategy.position_size != 0)
var_position_count := var_position_count + 1
//先に買っとく
if (int_TradeMode == "返済売り" and var_position_count == 0 and time[1] != time)
strategy.entry(":新規買い", strategy.long, alert_message=strategy_code)
var_position_count := var_position_count + 1
if (int_TradeMode == "返済買い" and var_position_count == 0 and time[1] != time)
strategy.entry(":新規売り", strategy.short, alert_message=strategy_code)
var_position_count := var_position_count + 1
//エントリー ///////////////////////////////////
if ((int_TradeMode == "新規買い")and inDateRange_2 and var_position_count == 0)
strategy.entry(":新規買い", strategy.long, qty = 10000000, alert_message=strategy_code)
var_position_count := var_position_count + 1
var_position_count_entry_only := var_position_count_entry_only + 1
if ((int_TradeMode == "新規売り")and inDateRange_2 and var_position_count == 0)
strategy.entry(":新規売り", strategy.short, qty = 10000000, alert_message=strategy_code)
var_position_count := var_position_count + 1
var_position_count_entry_only := var_position_count_entry_only + 1
//決済 //////////////////////////////////////////
strategy.close(":新規買い",
comment = ':返済売り',
alert_message=strategy_code ,
when = inDateRange_2 and var_position_count_entry_only == 0
)
strategy.close(":新規売り",
comment = ':返済買い',
alert_message=strategy_code ,
when = inDateRange_2 and var_position_count_entry_only == 0
)
|
DI Crossing Daily Straregy HulkTrading | https://www.tradingview.com/script/pAsSZCGD-di-crossing-daily-straregy-hulktrading/ | TheHulkTrading | https://www.tradingview.com/u/TheHulkTrading/ | 314 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TheHulkTrading
//@version=4
strategy("DI Crossing Daily Straregy HulkTrading", overlay=true)
// ATR Multiplier. Recommended values between 1..4
atr_multiplier = input(1, minval=1, title="ATR Multiplier")
//Length of DI. Recommended default value = 14
length = input(14, minval=1, title="Length di")
up = change(high)
down = -change(low)
range = rma(tr, 14)
//DI+ and DI- Calculations
di_plus = fixnan(100 * rma(up > down and up > 0 ? up : 0, length) / range)
di_minus = fixnan(100 * rma(down > up and down > 0 ? down : 0, length) / range)
//Long and short conditions
longCond = crossover(di_plus,di_minus)
shortCond = crossunder(di_plus,di_minus)
//Stop levels and take profits
stop_level_long = strategy.position_avg_price - atr_multiplier*atr(14)
take_level_long = strategy.position_avg_price + 2*atr_multiplier*atr(14)
stop_level_short = strategy.position_avg_price + atr_multiplier*atr(14)
take_level_short = strategy.position_avg_price - 2*atr_multiplier*atr(14)
//Entries and exits
strategy.entry("Long", strategy.long, when=longCond)
strategy.exit("Close Long","Long", stop=stop_level_long, limit = take_level_long)
strategy.entry("Short", strategy.short, when=shortCond)
strategy.exit("Close Short","Short", stop=stop_level_short, limit = take_level_short)
|
LPB MicroCycles Strategy | https://www.tradingview.com/script/jsQq8rUJ-LPB-MicroCycles-Strategy/ | tathal | https://www.tradingview.com/u/tathal/ | 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/
// © tathal animouse hajixde
//@version=4
strategy("LPB MicroCycles Strategy", "HPVWAP", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100, max_bars_back=5000)
startDate = input(title="Start Date", type=input.integer,
defval=1, minval=1, maxval=31)
startMonth = input(title="Start Month", type=input.integer,
defval=1, minval=1, maxval=12)
startYear = input(title="Start Year", type=input.integer,
defval=2010, minval=1800, maxval=2100)
endDate = input(title="End Date", type=input.integer,
defval=31, minval=1, maxval=31)
endMonth = input(title="End Month", type=input.integer,
defval=12, minval=1, maxval=12)
endYear = input(title="End Year", type=input.integer,
defval=2021, minval=1800, maxval=2100)
// STEP 2:
// Look if the close time of the current bar
// falls inside the date range
inDateRange = (time >= timestamp(syminfo.timezone, startYear,
startMonth, startDate, 0, 0)) and
(time < timestamp(syminfo.timezone, endYear, endMonth, endDate, 0, 0))
///
// Strategy Settings
var g_strategy = "Strategy Settings"
stopMultiplier = input(title="Stop Loss ATR", type=input.float, defval=1.0, group=g_strategy, tooltip="Stop loss multiplier (x ATR)")
rr = input(title="R:R", type=input.float, defval=1.0, group=g_strategy, tooltip="Risk:Reward profile")
/// Backtester Settings
var g_tester = "Backtester Settings"
startBalance = input(title="Starting Balance", type=input.float, defval=10000.0, group=g_tester, tooltip="Your starting balance for the custom inbuilt tester system")
riskPerTrade = input(title="Risk Per Trade", type=input.float, defval=1.0, group=g_tester, tooltip="Your desired % risk per trade (as a whole number)")
drawTester = input(title="Draw Backtester", type=input.bool, defval=true, group=g_tester, tooltip="Turn on/off inbuilt backtester display")
////////////////INPUTS///////////////////
lambda = input(defval = 1000, type = input.float, title = "Smoothing Factor (Lambda)", minval = 1)
leng = input(defval = 100, type = input.integer, title = "Filter Length", minval = 1)
src = ohlc4
atr = atr(14)
///////////Construct Arrays///////////////
a = array.new_float(leng, 0.0)
b = array.new_float(leng, 0.0)
c = array.new_float(leng, 0.0)
d = array.new_float(leng, 0.0)
e = array.new_float(leng, 0.0)
f = array.new_float(leng, 0.0)
/////////Initialize the Values///////////
ll1 = leng-1
ll2 = leng-2
for i = 0 to ll1
array.set(a,i, lambda*(-4))
array.set(b,i, src[i])
array.set(c,i, lambda*(-4))
array.set(d,i, lambda*6 + 1)
array.set(e,i, lambda)
array.set(f,i, lambda)
array.set(d, 0, lambda + 1.0)
array.set(d, ll1, lambda + 1.0)
array.set(d, 1, lambda * 5.0 + 1.0)
array.set(d, ll2, lambda * 5.0 + 1.0)
array.set(c, 0 , lambda * (-2.0))
array.set(c, ll2, lambda * (-2.0))
array.set(a, 0 , lambda * (-2.0))
array.set(a, ll2, lambda * (-2.0))
//////////////Solve the optimization issue/////////////////////
float r = array.get(a, 0)
float s = array.get(a, 1)
float t = array.get(e, 0)
float xmult = 0.0
for i = 1 to ll2
xmult := r / array.get(d, i-1)
array.set(d, i, array.get(d, i) - xmult * array.get(c, i-1))
array.set(c, i, array.get(c, i) - xmult * array.get(f, i-1))
array.set(b, i, array.get(b, i) - xmult * array.get(b, i-1))
xmult := t / array.get(d, i-1)
r := s - xmult*array.get(c, i-1)
array.set(d, i+1, array.get(d, i+1) - xmult * array.get(f, i-1))
array.set(b, i+1, array.get(b, i+1) - xmult * array.get(b, i-1))
s := array.get(a, i+1)
t := array.get(e, i)
xmult := r / array.get(d, ll2)
array.set(d, ll1, array.get(d, ll1) - xmult * array.get(c, ll2))
x = array.new_float(leng, 0)
array.set(x, ll1, (array.get(b, ll1) - xmult * array.get(b, ll2)) / array.get(d, ll1))
array.set(x, ll2, (array.get(b, ll2) - array.get(c, ll2) * array.get(x, ll1)) / array.get(d, ll2))
for j = 0 to leng-3
i = leng-3 - j
array.set(x, i, (array.get(b,i) - array.get(f,i)*array.get(x,i+2) - array.get(c,i)*array.get(x,i+1)) / array.get(d, i))
//////////////Construct the output///////////////////
HP = array.get(x,0)
///////////////Custom VWAP////////////////////////
TimeFrame = input('1', type=input.resolution)
start = security(syminfo.tickerid, TimeFrame, time)
//------------------------------------------------
newSession = iff(change(start), 1, 0)
//------------------------------------------------
vwapsum = 0.0
vwapsum := iff(newSession, HP*volume, vwapsum[1]+HP*volume)
volumesum = 0.0
volumesum := iff(newSession, volume, volumesum[1]+volume)
v2sum = 0.0
v2sum := iff(newSession, volume*HP*HP, v2sum[1]+volume*HP*HP)
myvwap = vwapsum/volumesum
dev = sqrt(max(v2sum/volumesum - myvwap*myvwap, 0))
Coloring=close>myvwap?color.new(#81c784, 62):color.new(#c2185b, 38)
av=myvwap
showBcol = input(true, type=input.bool, title="Show barcolors")
///////////////Entry & Exit///////////////////
// Custom function to convert pips into whole numbers
toWhole(number) =>
return = atr < 1.0 ? (number / syminfo.mintick) / (10 / syminfo.pointvalue) : number
return := atr >= 1.0 and atr < 100.0 and syminfo.currency == "JPY" ? return * 100 : return
// Custom function to convert whole numbers back into pips
toPips(number) =>
return = atr >= 1.0 ? number : (number * syminfo.mintick) * (10 / syminfo.pointvalue)
return := atr >= 1.0 and atr < 100.0 and syminfo.currency == "JPY" ? return / 100 : return
// Custom function to truncate (cut) excess decimal places
truncate(_number, _decimalPlaces) =>
_factor = pow(10, _decimalPlaces)
int(_number * _factor) / _factor
///////////////Conditional Strategy Logic//////////////
Long = crossover(av, ohlc4)
Sell = crossunder(av, ohlc4)
// Check if we have confirmation for our setup
validLong = Long and strategy.position_size == 0 and inDateRange and barstate.isconfirmed
validShort = Sell and strategy.position_size == 0 and inDateRange and barstate.isconfirmed
// Calculate our stop distance & size for the current bar
stopSize = atr * stopMultiplier
longStopPrice = low < low[1] ? low - stopSize : low[1] - stopSize
longStopDistance = close - longStopPrice
longTargetPrice = close + (longStopDistance * rr)
// Save trade stop & target & position size if a valid setup is detected
var t_entry = 0.0
var t_stop = 0.0
var t_target = 0.0
var t_direction = 0
// Detect valid long setups & trigger alert
if validLong
t_entry := close
t_stop := longStopPrice
t_target := longTargetPrice
t_direction := 1
strategy.entry(id="Long", long=strategy.long, when=validLong, comment="(SL=" + tostring(truncate(toWhole(longStopDistance),2)) + " pips)")
// Fire alerts
alert(message="Long Detected", freq=alert.freq_once_per_bar_close)
// Check if price has hit long stop loss or target
if t_direction == 1 and (low <= t_stop or high >= t_target)
t_direction := 0
// Check if price has hit short stop loss or target
if t_direction == -1 and (high >= t_stop or low <= t_target)
t_direction := 0
// Exit trades whenever our stop or target is hit
strategy.exit(id="Long Exit", from_entry="Long", limit=t_target, stop=t_stop, when=strategy.position_size > 0)
// Draw trade data
plot(strategy.position_size != 0 or validLong? t_stop : na, title="Trade Stop Price", color=color.red, style=plot.style_linebr)
plot(strategy.position_size != 0 or validLong? t_target : na, title="Trade Target Price", color=color.green, style=plot.style_linebr)
/////////////////////Plotting//////////////////////////
A=plot(av, color=Coloring, title="HP VWAP")
barcolor(showBcol?Coloring:na)
fill(A, plot(ohlc4), Coloring)
// Draw price action setup arrows
plotshape(validLong ? 1 : na, style=shape.triangleup, location=location.belowbar, color=color.green, title="Bullish Setup")
// --- BEGIN TESTER CODE --- //
// Declare performance tracking variables
var balance = startBalance
var drawdown = 0.0
var maxDrawdown = 0.0
var maxBalance = 0.0
var totalPips = 0.0
var totalWins = 0
var totalLoss = 0
// Detect winning trades
if strategy.wintrades != strategy.wintrades[1]
balance := balance + ((riskPerTrade / 100) * balance) * rr
totalPips := totalPips + abs(t_entry - t_target)
totalWins := totalWins + 1
if balance > maxBalance
maxBalance := balance
// Detect losing trades
if strategy.losstrades != strategy.losstrades[1]
balance := balance - ((riskPerTrade / 100) * balance)
totalPips := totalPips - abs(t_entry - t_stop)
totalLoss := totalLoss + 1
// Update drawdown
drawdown := (balance / maxBalance) - 1
if drawdown < maxDrawdown
maxDrawdown := drawdown
// Prepare stats table
var table testTable = table.new(position.top_right, 5, 2, border_width=1)
f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) =>
_cellText = _title + "\n" + _value
table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor)
// Draw stats table
var bgcolor = color.new(color.black,0)
if drawTester
if barstate.islastconfirmedhistory
// Update table
dollarReturn = balance - startBalance
f_fillCell(testTable, 0, 0, "Total Trades:", tostring(strategy.closedtrades), bgcolor, color.white)
f_fillCell(testTable, 0, 1, "Win Rate:", tostring(truncate((strategy.wintrades/strategy.closedtrades)*100,2)) + "%", bgcolor, color.white)
f_fillCell(testTable, 1, 0, "Starting:", "$" + tostring(startBalance), bgcolor, color.white)
f_fillCell(testTable, 1, 1, "Ending:", "$" + tostring(truncate(balance,2)), bgcolor, color.white)
f_fillCell(testTable, 2, 0, "Return:", "$" + tostring(truncate(dollarReturn,2)), dollarReturn > 0 ? color.green : color.red, color.white)
f_fillCell(testTable, 2, 1, "Pips:", (totalPips > 0 ? "+" : "") + tostring(truncate(toWhole(totalPips),2)), bgcolor, color.white)
f_fillCell(testTable, 3, 0, "Return:", (dollarReturn > 0 ? "+" : "") + tostring(truncate((dollarReturn / startBalance)*100,2)) + "%", dollarReturn > 0 ? color.green : color.red, color.white)
f_fillCell(testTable, 3, 1, "Max DD:", tostring(truncate(maxDrawdown*100,2)) + "%", color.red, color.white)
// --- END TESTER CODE --- // |
Indicators & Conditions Test Framework [DTU] | https://www.tradingview.com/script/2kwE117F-Indicators-Conditions-Test-Framework-DTU/ | dturkuler | https://www.tradingview.com/u/dturkuler/ | 300 | 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/
// © dturkuler
//v1.06
//ADD: Custom CRONEX T DEMARKER indicator added to custom indicator 4
//ADD: Plotting Type constants added, fn_plotFunction and Inputs options updated
//UPD: Increased number of spare operators to be used in future
//UPD: Condition tooltip updated
//v1.05
//ADD: Number of custom indicators increased from 3 to 5 (see the cutom indicator inputs and functions)
//ADD: Added double triple, Quatr factorizer for all indicators (like convert EMA to DEMA, TEMA, QEMA...)
//ADD: fn_factor function added
//UPD: fn_get_indicator updated
//UPD: Some tooltips updated
//v1.04
//ADD: Number condition increased from 3 to 4 for aech combination (longentry, shortentry, longclose, shortclose)
//ADD: Stochastic, Percent value added for each indicator
//ADD: Source data added for each indicator
//UPD: Calculation bug on src_data removed
//UPD: Indicators default values updated (Arranged to BTCUSDT for testing purpose)
//v1.03
//UPD: Longlose and shortclose codes updated. Now works as expected
//v1.02
//ADD: Tooltips addec to the settings screen. (Tooltip constants added)
//ADD: Falling and rising operators added to combinations. USAGE:(1st Indicator---Falling---IS(1st Indicator,VALUE)----int VALUE)
// Calculates: ta.falling(1st indicator, VALUE)... VALUE Should be integer (1,2...n)
// Desc: if the 1st indicator is falling since the previous # of bars (VALUE).
//ADD: use Simple Log addded for testing purpose but not available for usage (to be corrected)
//UPD: Strategy part improved. Long close and short close now works as expected (without opposite close)
//UPD: Constants Updated: CONDITION INDICATOR SOURCE CONSTANTS, CONDITION OPERATOR CONSTANTS
//UPD: functions updated: fn_get_source() , fn_plotFunction(), fn_get_indicator(), fn_get_Condition_Indicator(), fn_get_Condition_Result()
//v1.01
//UPD: Document violations removed
//v1.00
//UPD: Condition indicator value input will be previous value of the selected indicator if "VALUE" is not selected
//ADD: Added Profit gfx (should be improved!!!)
//UPD: Updated condition result & join conditions functions with constants variables
//ADD: Added area for Custom indicators on input panel
//ADD: Added External indicator import on settings panel
//ADD: Prepared documentation
//v_x.xx
//TODO: Add factorized Fibo avg range indicator (good for trend definition and entry exit points)
//TODO: Add bands to the indicator and conditions
//TODO: Add debug window for exporting indicator's parameters
//TODO: Add Alerts, Condiional alerts for indicator (study) part
//TODO: Create export function v3 for Pinecoders Indicator framework
//@version=5
SystemVersion = 'v1.06 STRATEGY'
SystemName = 'Indicators & Conditions Test Framework '+SystemVersion+' [DTU]'
TradeId = 'IND COND TEST FRMWRK STRT'+SystemVersion
InitCapital = 1000
InitPosition = 100.0 // %10 of capital with x10 leverage
InitCommission = 0.04
InitPyramidMax = 5 // Arrange it regarding to no margin call in strategy/performance tab
CalcOnorderFills = false
ProcessOrdersOnClose = false
CalcOnEveryTick = false
marginlong= 1./10*50 // (1/10x leverage) * 50 (Margin ratio in general)
marginshort= 1./10*50 // (1/10x leverage) * 50 (Margin ratio in general)
precision_= 4 // Keep it >=4 (I use it for data export )
float indicator1= 0.0
float indicator2= 0.0
float indicator3= 0.0
float indicator4= 0.0
float indicator5= 0.0
//indicator(title=SystemName,shorttitle=TradeId,overlay=true, precision=precision_)
strategy( title=SystemName, shorttitle=SystemName, overlay=true,
margin_short=marginshort, margin_long=marginlong,
pyramiding=InitPyramidMax, initial_capital=InitCapital,
default_qty_type=strategy.percent_of_equity, default_qty_value=InitPosition,
commission_type=strategy.commission.percent, commission_value=InitCommission,
calc_on_order_fills=CalcOnorderFills, precision=precision_,
process_orders_on_close=ProcessOrdersOnClose, calc_on_every_tick=CalcOnEveryTick,
scale=scale.left, currency=currency.USD)
import dturkuler/lib_Indicators_DT/1 as ind //CREDITS: library includes indicators, snippets from tradingview , @03.freeman ("All MAs displayed") public script.. Thanks to all!!!
//************CONSTANTS{
//_______________GROUP NAME CONSTANTS
s_grp_settings= "A) ═════════════ SETTINGS ══════════"
s_grp_plottype= "B)══════════ PLOT TYPE OPS ═════════"
s_grp_indicators= "C)════════════ INDICATORS ══════════"
s_grp_LEC= "D1)══════ LONG ENTRY CONDITION ═════"
s_grp_SEC= "D2)══════ SHORT ENTRY CONDITION ════"
s_grp_LCC= "D3)══════ LONG CLOSE CONDITION ═════"
s_grp_SCC= "D4)══════ SHORT CLOSE CONDITION ════"
s_grp_custom_ind= "E) ═══════ CUSTOM INDICATORS ══════"
s_grp_custom_ind1= "E1)═══════ CUSTOM INDICATOR 1 ══════"
s_grp_custom_ind2= "E2)═══════ CUSTOM INDICATOR 2 ══════"
s_grp_custom_ind3= "E3)═══════ CUSTOM INDICATOR 3 ══════"
s_grp_custom_ind4= "E4)═══════ CUSTOM INDICATOR 4 ══════"
s_grp_custom_ind5= "E5)═══════ CUSTOM INDICATOR 5 ══════"
//_______________INDICATOR CONSTANTS
//i29-i33 (*ma1-*ma5) reserved for future moving average indicators that will be installed into library
h01='Hide',
i00='▼▼▼ MOV AVGs ▼▼▼'
i01='alma', i02='cma', i03='dema', i04='ema', i05='gmma', i06='hl2ma', i07='hull', i08='lagAdapt', i09='lagAdaptV',i10='laguerre', i11='lesrcp'
i12='linreg', i13='lexp', i14='percntl', i15='percntli', i16='rema', i17='rma', i18='sma', i19='smma', i20='ssma', i21='super2', i22='super3'
i23='swma', i24='tema', i25='tma', i26='vida', i27='vwma', i28='wma', i29='*ma1', i30='*ma2', i31='*ma3', i32='*ma4', i33='*ma5'
//o25-i29 (*ot1-*ot5) reserved for future other indicators that will be installed into library
o00='▼▼▼ OTHER INDICATORS ▼▼▼'
o01='bbr', o02='bbw', o03='cci', o04='cctbbo', o05='change', o06='cmo', o07='cog', o08='copcurve', o09='correl', o10='count', o11='dev'
o12='kcr', o13='kcw', o14='macd', o15='mfi', o16='roc', o17='rsi', o18='smi_Osc', o19='smi_sig', o20='stdev', o21='trix' , o22='tsi'
o23='variance', o24='willprc', o25='*ot1', o26='*ot2', o27='*ot3', o28='*ot4', o29='*ot5'
// Currently 5 custom indicators inserted into the current Indicator code
//c06-c08 (*ci6-*ci8) reserved for future usage. custom indicators can be added/updated in the indicator code area
c00='▼▼▼ CUSTOM INDICATORS ▼▼▼'
c01='cust ind1',c02='Custom Squeeze MOM',c03='Custom SuperTrend',c04='cust CRONEX', c05='cust ind5', c06='*ci6', c07='*ci7', c08='*ci8'
//_______________INDICATOR PLOTTING TYPE CONSTANTS
//Currently there are 4 plotting type exist in the system
p01='Original' , p02='Stochastic' , p03='PercentRank' , p04='Org. Range (-1,1)'
//_______________CONDITION INDICATOR SOURCE CONSTANTS
//s16-s19 (*s01-*s04) reserved for future indicator sources
s00= "NONE", s01="IND1", s02="IND2", s03="IND3", s04="IND4", s05="IND5", s06="VALUE", s07="close", s08="open", s09="high", s10="low", s11="hl2", s12="hlc3", s13="ohlc4", s14="heikin"
s15="EXT", s16="IS(1st Indicator,VALUE)", s17="*s02", s18="*s03", s19="*s04"
//_______________CONDITION OPERATOR CONSTANTS
//op09-op11 (*op01-*op03) reserved for future operators
op01="crossover", op02="crossunder", op03="cross", op04=">", op05="<", op06=">=", op07="<=", op08="=", op09="!=", op10="rising", op11="falling", op12="%", op13="*op01", op14="*op02", op15="*op03"
//_______________TOOLTIPS CONSTANTS
s_tt_settings= "Select the Source, timeframe and Secure type that your indicators will use.\n
SOURCE: Used to feed indicators source \n
TIMEFRAME: indicators timeframe \n
SECURE: option is defined as reducing repaint in tradingview calculations as much as possible. The following function is used.\n
Here, the Secure entry consists of 3 parts and the f_security function is used to determine it.\n
a) SECURE: This option is defined as reducing repaint in tradingview calculations as much as possible\n
b) SEMI SECURE : While this option can reduce repaint in tradingview calculations as much as possible, it is less secure. \n
c) REPAINT: This option turns on the repaint feature."
s_tt_data_ext= "EXT SOURCE: You can import external Indicator sources from here . It appears on condition/combination area as EXT. \n To impor it you should export your indicator value as PLOT with a title.\n Then It will be visible in Ext data source dropdown input "
s_tt_testPeriod= "TEST PERIOD: Determine your strategy testing period range by selecting start and end date/time"
s_tt_settings1= "PLOT ALERTS: Plot condition result as alerts arrows on the chart's bottom for LONG and the top for SHORT entries, exits\n
CLOSE ON OPPOSITE: When selected, a long entry gets closed when a short entry opens and vice versa"
s_tt_Profit= "SHOW PROFIT:It appears if the script is in strategy mode (not in study) this can display current or open profit for better reanalyzing your strategy entry exit points. (Currently under development)"
s_tt_PlotType= "MULT:Sets the multiplier for the selected Plot Type EXAMPLE: When 1000 is selected, the indicator in the range of (-1,1) will appear in the range of (-1000, 1000) on the screen other than Original\n
SHIFT:It determines the shift that will appear on the screen for the selected Plot Type ( stochastic , Percentrank, Org Range (-1,1) ) in the range (-1,1) other than Original.\n
SMOOTH:This option (only for Stochastic & PercentRank) allows to smooth the indicator to be displayed.\n
HLINE:Adjusts the horizontal lines to appear on the screen according to the mult factor for the range (-1,1). The lines represent the values (-1, -05, 0, 05 , 1)"
s_tt_ind= "INDICATOR INPUTS:\n"+
"A) INDICATOR:\n" +
" 1) MOVING AVERAGES : These are indicators such as EMA , SMA that you can show on the stock. \n " +
" 2) OTHER INDICATORS : These are different indicators from the stock value such as RSI , COG. \n" +
" 3) CUSTOM INDICATORS: These indicators are the ones you can create by programming yourself in the source code..\n" +
"B) INDICATOR SOURCE: \n" +
" indicator source such as close, open... (Not: it does not work for custom indicators since they have their parameter on cust. Ind. input screen ) \n" +
"C) INDICATOR LENGTH: \n" +
" indicator length value . (Not: it does not work for custom indicators since they have their parameter on cust. Ind. input screen ) \n" +
"D) INDICATOR PLOTTING TYPE: This is an input selection field about how indicaor will be displayed on the screen. \n" +
" 1) ORIGINAL: The indicator is displayed on the screen with its current values. Can be used to display moving average indicators such as ( EMA , SMA ) \n" +
" 2) STOCHASTIC, PERCENTRANK: The indicator is displayed on the screen with stochastic calculation in the range of -1.1.It uses the stochastic (50) calculation method to spread indicators such as ( RSI , COB) over the range (-1,1). Indicators in. You can see the original values of the relevant indicator on the Data Window screen.\n" +
" 3) ORG RANGE (-1,1): If your indicator is in the range of -1.1, your indicator will be displayed on the screen with its original calculation in the range of -1.1.\n" +
"E) STOCHASTIC/PERCENTAGE VALUE:\n" +
" Stoch, Perc plot type value. (Not: it does not impact plot type ORIGINAL )\n" +
"F) FACTORIZER VALUE:\n" +
" double triple, Quatr factorizer value (like convert EMA to DEMA, TEMA, QEMA...) 1=Original \n" +
"G) INDICATOR COLOR:\n" +
" Define indicator color on the chart "
s_tt_combination= "Each combination are build from 4 parts\n"+
"1)1ST INDICATOR: If set to NONE this combination will not be used on calculations. You can select IND1-5: from indicators (See above), EXT: value from externally imported indicator Stock built-in values: close, open...\n"+
"2)OPERATOR : Selected Operator compares 1st Indicator with the 2nd one. You can select different operators such as crossover, crossunder, cross,>,<,=....\n"+
" Standart operators USAGE 1: [ 1)1st Indicator 2)cross 3)2nd Indicator 4)2nd indicator[VALUE] ] \n"+
" Standart operators USAGE 2: [ 1)1st Indicator 2)cross 3)VALUE 4)Value ] \n"+
" FALLING/RISING operators USAGE:[ 1)1st Indicator---2)Falling---3)IS(1st Indicator,VALUE)----4)int VALUE ] \n"+
"3)2ND INDICATOR : This indicator will be compared with the 1st one via selected Operator. You can select\n" +
" IND1-5: from indicators (See above),\n"+
" VALUE: a float value defined in the combinations value parameter\n "+
" EXT: value from externally imported indicator.\n"+
" Stock builtin values: close,open...\n"+
"4)VALUE: When the 2nd indicator field selected as VALUE, value area compares the entered flaot value with indicator 1\n"+
" When the 2nd indicator field selected other than VALUE, Value area define 2nd indicator's previous value ex: close[2] \n"+
" When the 2nd indicator and operator fields are rising, falling , Value area define rising/falling bars ex: rising(IND1, 2)\n"
s_tt_Comb_op= "Each combination in Condition is compared with the next one via JOIN operator. The join operator can be selected as AND or OR."
s_tt_custind= "There is an area in the code for designing Custom Indicators.\n
Here you can design your own indicators and use them in the framework.\n
You can also create unlimited parameters for your indicators in the SETTINGS custom indicator field.\n
Examples are entered in the code for custom indicators."
//************CONSTANTS}
//************INPUTS{
//_______________F_SECURITY***NOREPAINT
data = input.string( defval="close", title='Ind Source', options=[s07, s08, s09, s10, s11, s12, s13, s14], group=s_grp_settings, inline="settings",tooltip=s_tt_settings)
Timeframe = input.timeframe(defval='', title='', group=s_grp_settings, inline="settings")
secure = input.string( defval='Secure',options=['Secure', 'Semi Secure', 'Repaint'], title='', group=s_grp_settings, inline="settings")
data_ext = input.source( defval=close, title='Ext Source', group=s_grp_settings, inline="data_ext", tooltip=s_tt_data_ext) //The ext source Accept extrenal Indicator sources also. To export the External indicator plot it with a title. It will be visible in source dropdown input
//_______________END F_SECURITY***NOREPAINT
//_______________SETTINGS
t_testPeriodStart= input.time( defval=timestamp('01 Apr 2021 00:00'),title='Start Time:', group=s_grp_settings, inline='test period', tooltip=s_tt_testPeriod)
t_testPeriodStop = input.time( defval=timestamp('30 Dec 2021 23:30'),title='End Time :', group=s_grp_settings, inline='test period')
b_plotalert = input.bool( defval=true, title='Plot Alerts', group=s_grp_settings, inline="settings1", tooltip=s_tt_settings1)
b_isopposite = input.bool( defval=true, title="Close on opposite", group=s_grp_settings, inline="settings1")
//_______________PLOT TYPE INPUTS
i_ind_mult= input.int( defval=2000, title="mult", group= s_grp_plottype,inline="plot type", step=100, tooltip=s_tt_PlotType)
i_ind_shift= input.int( defval=35000, title="shift", group= s_grp_plottype,inline="plot type", step=1000)
//b_ind_log= input.bool( defval=true, title="Use log", group= s_grp_plottype,inline="plot type")
b_ind_pSWMA= input.bool( defval=true, title="Smooth", group= s_grp_plottype,inline="plot type")
b_ind_hline= input.bool( defval=true, title="hline", group= s_grp_plottype,inline="plot type")
//_______________INDICATORS DEFINITIONS
//_______________INDICATOR 1
s_ind1_src= input.string( defval='alma', title='IND1', options=[h01, i00, i01, i02, i03, i04, i05, i06, i07, i08, i09, i10, i11, i12, i13, i14, i15, i16, i17, i18,
i19, i20, i21, i22, i23, i24, i25, i26, i27, i28, i29, i30, i31, i32, i33, o00, o01, o02, o03, o04,
o05, o06, o07, o08, o09, o10, o11, o12, o13, o14, o15, o16, o17, o18, o19, o20, o21, o22, o23, o24,
o25, o26, o27, o28, o29, c00, c01, c02, c03, c04, c05, c06, c07, c08]
, group= s_grp_indicators, inline="ind1")
s_ind1_data = input.string( defval="high", title='', options=[s07, s08, s09, s10, s11, s12, s13, s14], group= s_grp_indicators, inline="ind1")
i_ind1_len = input.int( defval=300, title='', group= s_grp_indicators, inline="ind1")
s_ind1_pType = input.string( defval="Original", title="", group= s_grp_indicators, inline="ind1", options=[p01, p02, p03, p04])
i_ind1_stoch = input.int( defval=50, title='', group= s_grp_indicators, inline="ind1")
i_ind1_fact_ = input.int( defval=1, title='', group= s_grp_indicators, inline="ind1", minval=1,maxval=4)
c_ind1_color = input.color( defval=color.green, title="", group= s_grp_indicators, inline="ind1", tooltip=s_tt_ind)
//_______________INDICATOR 2
s_ind2_src= input.string(defval='rma', title='IND2', options= [h01, i00, i01, i02, i03, i04, i05, i06, i07, i08, i09, i10, i11, i12, i13, i14, i15, i16, i17, i18,
i19, i20, i21, i22, i23, i24, i25, i26, i27, i28, i29, i30, i31, i32, i33, o00, o01, o02, o03, o04,
o05, o06, o07, o08, o09, o10, o11, o12, o13, o14, o15, o16, o17, o18, o19, o20, o21, o22, o23, o24,
o25, o26, o27, o28, o29, c00, c01, c02, c03, c04, c05, c06, c07, c08]
, group= s_grp_indicators, inline="ind2")
s_ind2_data = input.string( defval="close", title='', options=[s07, s08, s09, s10, s11, s12, s13, s14], group= s_grp_indicators, inline="ind2")
i_ind2_len = input.int( defval=220, title='', group= s_grp_indicators, inline="ind2")
s_ind2_pType = input.string( defval="Stochastic",title="", group= s_grp_indicators, inline="ind2", options=[p01, p02, p03, p04])
i_ind2_stoch = input.int( defval=50, title='', group= s_grp_indicators, inline="ind2")
i_ind2_fact_ = input.int( defval=1, title='', group= s_grp_indicators, inline="ind2", minval=1,maxval=4)
c_ind2_color = input.color( defval=color.red, title="", group= s_grp_indicators, inline="ind2", tooltip=s_tt_ind)
//_______________INDICATOR 3
s_ind3_src= input.string(defval='super3', title='IND3', options= [h01, i00, i01, i02, i03, i04, i05, i06, i07, i08, i09, i10, i11, i12, i13, i14, i15, i16, i17, i18,
i19, i20, i21, i22, i23, i24, i25, i26, i27, i28, i29, i30, i31, i32, i33, o00, o01, o02, o03, o04,
o05, o06, o07, o08, o09, o10, o11, o12, o13, o14, o15, o16, o17, o18, o19, o20, o21, o22, o23, o24,
o25, o26, o27, o28, o29, c00, c01, c02, c03, c04, c05, c06, c07, c08]
, group= s_grp_indicators, inline="ind3")
s_ind3_data = input.string( defval="close", title='', options=[s07, s08, s09, s10, s11, s12, s13, s14], group= s_grp_indicators, inline="ind3")
i_ind3_len = input.int( defval=210, title='', group= s_grp_indicators, inline="ind3")
s_ind3_pType = input.string( defval="Stochastic",title="", group= s_grp_indicators, inline="ind3", options=[p01, p02, p03, p04])
i_ind3_stoch = input.int( defval=50, title='', group= s_grp_indicators, inline="ind3")
i_ind3_fact_ = input.int( defval=1, title='', group= s_grp_indicators, inline="ind3", minval=1,maxval=4)
c_ind3_color = input.color( defval=color.blue, title="", group= s_grp_indicators, inline="ind3", tooltip=s_tt_ind)
//_______________INDICATOR 4
s_ind4_src= input.string(defval='Hide', title='IND4', options= [h01, i00, i01, i02, i03, i04, i05, i06, i07, i08, i09, i10, i11, i12, i13, i14, i15, i16, i17, i18,
i19, i20, i21, i22, i23, i24, i25, i26, i27, i28, i29, i30, i31, i32, i33, o00, o01, o02, o03, o04,
o05, o06, o07, o08, o09, o10, o11, o12, o13, o14, o15, o16, o17, o18, o19, o20, o21, o22, o23, o24,
o25, o26, o27, o28, o29, c00, c01, c02, c03, c04, c05, c06, c07, c08]
, group= s_grp_indicators, inline="ind4")
s_ind4_data = input.string( defval="close", title='', options=[s07, s08, s09, s10, s11, s12, s13, s14], group= s_grp_indicators, inline="ind4")
i_ind4_len = input.int( defval=25, title='', group= s_grp_indicators, inline="ind4")
s_ind4_pType = input.string( defval="Stochastic",title="", group= s_grp_indicators, inline="ind4", options=[p01, p02, p03, p04])
i_ind4_stoch = input.int( defval=50, title='', group= s_grp_indicators, inline="ind4")
i_ind4_fact_ = input.int( defval=1, title='', group= s_grp_indicators, inline="ind4", minval=1,maxval=4)
c_ind4_color = input.color( defval=color.black, title="", group= s_grp_indicators, inline="ind4", tooltip=s_tt_ind)
//_______________INDICATOR 5
s_ind5_src= input.string(defval='Hide', title='IND5', options= [h01, i00, i01, i02, i03, i04, i05, i06, i07, i08, i09, i10, i11, i12, i13, i14, i15, i16, i17, i18,
i19, i20, i21, i22, i23, i24, i25, i26, i27, i28, i29, i30, i31, i32, i33, o00, o01, o02, o03, o04,
o05, o06, o07, o08, o09, o10, o11, o12, o13, o14, o15, o16, o17, o18, o19, o20, o21, o22, o23, o24,
o25, o26, o27, o28, o29, c00, c01, c02, c03, c04, c05, c06, c07, c08]
, group= s_grp_indicators, inline="ind5")
s_ind5_data = input.string( defval="close", title='', options=[s07, s08, s09, s10, s11, s12, s13, s14], group= s_grp_indicators, inline="ind5")
i_ind5_len = input.int( defval=51, title='', group= s_grp_indicators, inline="ind5")
s_ind5_pType = input.string( defval="Original", title="", group= s_grp_indicators, inline="ind5", options=[p01, p02, p03, p04])
i_ind5_stoch = input.int( defval=50, title='', group= s_grp_indicators, inline="ind5")
i_ind5_fact_ = input.int( defval=1, title='', group= s_grp_indicators, inline="ind5", minval=1,maxval=4)
c_ind5_color = input.color( defval=color.purple,title="", group= s_grp_indicators, inline="ind5", tooltip=s_tt_ind)
//************LONG ENTRY CONDITIONS
//_______________LONG ENTRY 1 CONDITION
s_Cond_LE_1_ind1= input.string(defval="IND2", title="", options=[s00, s01, s02, s03, s04, s05, s07, s08, s09, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19], group= s_grp_LEC,inline="LE_cond1")
s_Cond_LE_1_op= input.string(defval="crossover", title="", options=[op01, op02, op03, op04, op05, op06, op07, op08, op09, op10, op11, op12, op13, op14, op15], group= s_grp_LEC,inline="LE_cond1")
s_Cond_LE_1_ind2= input.string(defval="IND3", title="", options=[s01, s02, s03, s04, s05, s06, s07, s08, s09, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19], group= s_grp_LEC,inline="LE_cond1")
f_Cond_LE_1_ind2_val=input.float( defval=0, title="", group= s_grp_LEC, inline="LE_cond1",step=0.1, tooltip=s_tt_combination)
//_______________LONG ENTRY 1-2 JOIN
s_Cond_LE_1_join_2= input.string(defval="AND", title="", options=["AND","OR"] , group= s_grp_LEC, tooltip=s_tt_Comb_op)
//_______________LONG ENTRY 2 CONDITION
s_Cond_LE_2_ind1= input.string(defval="IND2", title="", options=[s00, s01, s02, s03, s04, s05, s07, s08, s09, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19], group= s_grp_LEC,inline="LE_cond2")
s_Cond_LE_2_op= input.string(defval="<", title="", options=[op01, op02, op03, op04, op05, op06, op07, op08, op09, op10, op11, op12, op13, op14, op15], group= s_grp_LEC,inline="LE_cond2")
s_Cond_LE_2_ind2= input.string(defval="VALUE", title="", options=[s01, s02, s03, s04, s05, s06, s07, s08, s09, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19], group= s_grp_LEC,inline="LE_cond2")
f_Cond_LE_2_ind2_val=input.float( defval=-0.9, title="", group= s_grp_LEC, inline="LE_cond2",step=0.1, tooltip=s_tt_combination)
//_______________LONG ENTRY 2-3 JOIN
s_Cond_LE_2_join_3= input.string(defval="AND", title="", options=["AND","OR"] , group= s_grp_LEC, tooltip=s_tt_Comb_op)
//_______________LONG ENTRY 3 CONDITION
s_Cond_LE_3_ind1= input.string(defval="IND1", title="", options=[s00, s01, s02, s03, s04, s05, s07, s08, s09, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19], group= s_grp_LEC,inline="LE_cond3")
s_Cond_LE_3_op= input.string(defval="<", title="", options=[op01, op02, op03, op04, op05, op06, op07, op08, op09, op10, op11, op12, op13, op14, op15], group= s_grp_LEC,inline="LE_cond3")
s_Cond_LE_3_ind2= input.string(defval="low", title="", options=[s01, s02, s03, s04, s05, s06, s07, s08, s09, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19], group= s_grp_LEC,inline="LE_cond3")
f_Cond_LE_3_ind2_val=input.float( defval=0, title="", group= s_grp_LEC, inline="LE_cond3",step=0.1, tooltip=s_tt_combination)
//_______________LONG ENTRY 3-4 JOIN
s_Cond_LE_3_join_4= input.string(defval="AND", title="", options=["AND","OR"] , group= s_grp_LEC, tooltip=s_tt_Comb_op)
//_______________LONG ENTRY 4 CONDITION
s_Cond_LE_4_ind1= input.string(defval="NONE", title="", options=[s00, s01, s02, s03, s04, s05, s07, s08, s09, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19], group= s_grp_LEC,inline="LE_cond4")
s_Cond_LE_4_op= input.string(defval="<", title="", options=[op01, op02, op03, op04, op05, op06, op07, op08, op09, op10, op11, op12, op13, op14, op15], group= s_grp_LEC,inline="LE_cond4")
s_Cond_LE_4_ind2= input.string(defval="low", title="", options=[s01, s02, s03, s04, s05, s06, s07, s08, s09, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19], group= s_grp_LEC,inline="LE_cond4")
f_Cond_LE_4_ind2_val=input.float( defval=0, title="", group= s_grp_LEC, inline="LE_cond4",step=0.1, tooltip=s_tt_combination)
//************SHORT ENTRY CONDITIONS
//_______________SHORT ENTRY 1 CONDITION
s_Cond_SE_1_ind1= input.string(defval="IND2", title="", options=[s00, s01, s02, s03, s04, s05, s07, s08, s09, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19], group= s_grp_SEC,inline="SE_cond1")
s_Cond_SE_1_op= input.string(defval="crossunder", title="", options=[op01, op02, op03, op04, op05, op06, op07, op08, op09, op10, op11, op12, op13, op14, op15], group= s_grp_SEC,inline="SE_cond1")
s_Cond_SE_1_ind2= input.string(defval="IND3", title="", options=[s01, s02, s03, s04, s05, s06, s07, s08, s09, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19], group= s_grp_SEC,inline="SE_cond1")
f_Cond_SE_1_ind2_val=input.float( defval=0, title="", group= s_grp_SEC, inline="SE_cond1",step=0.1, tooltip=s_tt_combination)
//_______________SHORT ENTRY 1-2 JOIN
s_Cond_SE_1_join_2= input.string(defval="AND", title="", options=["AND","OR"] , group= s_grp_SEC, tooltip=s_tt_Comb_op)
//_______________SHORT ENTRY 2 CONDITION
s_Cond_SE_2_ind1= input.string(defval="IND2", title="", options=[s00, s01, s02, s03, s04, s05, s07, s08, s09, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19], group= s_grp_SEC,inline="SE_cond2")
s_Cond_SE_2_op= input.string(defval=">", title="", options=[op01, op02, op03, op04, op05, op06, op07, op08, op09, op10, op11, op12, op13, op14, op15], group= s_grp_SEC,inline="SE_cond2")
s_Cond_SE_2_ind2= input.string(defval="VALUE", title="", options=[s01, s02, s03, s04, s05, s06, s07, s08, s09, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19], group= s_grp_SEC,inline="SE_cond2")
f_Cond_SE_2_ind2_val=input.float( defval=0.9, title="", group= s_grp_SEC, inline="SE_cond2",step=0.1, tooltip=s_tt_combination)
//_______________SHORT ENTRY 2-3 JOIN
s_Cond_SE_2_join_3= input.string(defval="AND", title="", options=["AND","OR"] , group= s_grp_SEC, tooltip=s_tt_Comb_op)
//_______________SHORT ENTRY 3 CONDITION
s_Cond_SE_3_ind1= input.string(defval="IND1", title="", options=[s00, s01, s02, s03, s04, s05, s07, s08, s09, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19], group= s_grp_SEC,inline="SE_cond3")
s_Cond_SE_3_op= input.string(defval=">", title="", options=[op01, op02, op03, op04, op05, op06, op07, op08, op09, op10, op11, op12, op13, op14, op15], group= s_grp_SEC,inline="SE_cond3")
s_Cond_SE_3_ind2= input.string(defval="high", title="", options=[s01, s02, s03, s04, s05, s06, s07, s08, s09, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19], group= s_grp_SEC,inline="SE_cond3")
f_Cond_SE_3_ind2_val=input.float( defval=0, title="", group= s_grp_SEC, inline="SE_cond3",step=0.1, tooltip=s_tt_combination)
//_______________SHORT ENTRY 3-4 JOIN
s_Cond_SE_3_join_4= input.string(defval="AND", title="", options=["AND","OR"] , group= s_grp_SEC, tooltip=s_tt_Comb_op)
//_______________SHORT ENTRY 4 CONDITION
s_Cond_SE_4_ind1= input.string(defval="NONE", title="", options=[s00, s01, s02, s03, s04, s05, s07, s08, s09, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19], group= s_grp_SEC,inline="SE_cond4")
s_Cond_SE_4_op= input.string(defval=">", title="", options=[op01, op02, op03, op04, op05, op06, op07, op08, op09, op10, op11, op12, op13, op14, op15], group= s_grp_SEC,inline="SE_cond4")
s_Cond_SE_4_ind2= input.string(defval="high", title="", options=[s01, s02, s03, s04, s05, s06, s07, s08, s09, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19], group= s_grp_SEC,inline="SE_cond4")
f_Cond_SE_4_ind2_val=input.float( defval=0, title="", group= s_grp_SEC, inline="SE_cond4",step=0.1, tooltip=s_tt_combination)
//************LONG CLOSE CONDITIONS
//_______________LONG CLOSE 1 CONDITION
s_Cond_LC_1_ind1= input.string(defval="NONE", title="", options=[s00, s01, s02, s03, s04, s05, s07, s08, s09, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19], group= s_grp_LCC,inline="LC_cond1")
s_Cond_LC_1_op= input.string(defval="crossover", title="", options=[op01, op02, op03, op04, op05, op06, op07, op08, op09, op10, op11, op12, op13, op14, op15], group= s_grp_LCC,inline="LC_cond1")
s_Cond_LC_1_ind2= input.string(defval="IND1", title="", options=[s01, s02, s03, s04, s05, s06, s07, s08, s09, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19], group= s_grp_LCC,inline="LC_cond1")
f_Cond_LC_1_ind2_val=input.float( defval=0, title="", group= s_grp_LCC, inline="LC_cond1",step=0.1, tooltip=s_tt_combination)
//_______________LONG CLOSE 1-2 JOIN
s_Cond_LC_1_join_2= input.string(defval="AND", title="", options=["AND","OR"] , group= s_grp_LCC, tooltip=s_tt_Comb_op)
//_______________LONG CLOSE 2 CONDITION
s_Cond_LC_2_ind1= input.string(defval="NONE", title="", options=[s00, s01, s02, s03, s04, s05, s07, s08, s09, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19], group= s_grp_LCC,inline="LC_cond2")
s_Cond_LC_2_op= input.string(defval="crossover", title="", options=[op01, op02, op03, op04, op05, op06, op07, op08, op09, op10, op11, op12, op13, op14, op15], group= s_grp_LCC,inline="LC_cond2")
s_Cond_LC_2_ind2= input.string(defval="IND2", title="", options=[s01, s02, s03, s04, s05, s06, s07, s08, s09, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19], group= s_grp_LCC,inline="LC_cond2")
f_Cond_LC_2_ind2_val=input.float( defval=0, title="", group= s_grp_LCC, inline="LC_cond2",step=0.1, tooltip=s_tt_combination)
//_______________LONG CLOSE 2-3 JOIN
s_Cond_LC_2_join_3= input.string(defval="AND", title="", options=["AND","OR"] , group= s_grp_LCC, tooltip=s_tt_Comb_op)
//_______________LONG CLOSE 3 CONDITION
s_Cond_LC_3_ind1= input.string(defval="NONE", title="", options=[s00, s01, s02, s03, s04, s05, s07, s08, s09, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19], group= s_grp_LCC,inline="LC_cond3")
s_Cond_LC_3_op= input.string(defval="crossover", title="", options=[op01, op02, op03, op04, op05, op06, op07, op08, op09, op10, op11, op12, op13, op14, op15], group= s_grp_LCC,inline="LC_cond3")
s_Cond_LC_3_ind2= input.string(defval="IND3", title="", options=[s01, s02, s03, s04, s05, s06, s07, s08, s09, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19], group= s_grp_LCC,inline="LC_cond3")
f_Cond_LC_3_ind2_val=input.float( defval=0, title="", group= s_grp_LCC, inline="LC_cond3",step=0.1, tooltip=s_tt_combination)
//_______________LONG CLOSE 3-4 JOIN
s_Cond_LC_3_join_4= input.string(defval="AND", title="", options=["AND","OR"] , group= s_grp_LCC, tooltip=s_tt_Comb_op)
//_______________LONG CLOSE 4 CONDITION
s_Cond_LC_4_ind1= input.string(defval="NONE", title="", options=[s00, s01, s02, s03, s04, s05, s07, s08, s09, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19], group= s_grp_LCC,inline="LC_cond4")
s_Cond_LC_4_op= input.string(defval="crossover", title="", options=[op01, op02, op03, op04, op05, op06, op07, op08, op09, op10, op11, op12, op13, op14, op15], group= s_grp_LCC,inline="LC_cond4")
s_Cond_LC_4_ind2= input.string(defval="IND3", title="", options=[s01, s02, s03, s04, s05, s06, s07, s08, s09, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19], group= s_grp_LCC,inline="LC_cond4")
f_Cond_LC_4_ind2_val=input.float( defval=0, title="", group= s_grp_LCC, inline="LC_cond4",step=0.1, tooltip=s_tt_combination)
//************SHORT CLOSE CONDITIONS
//_______________SHORT CLOSE 1 CONDITION
s_Cond_SC_1_ind1= input.string(defval="NONE", title="", options=[s00, s01, s02, s03, s04, s05, s07, s08, s09, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19], group= s_grp_SCC,inline="SC_cond1")
s_Cond_SC_1_op= input.string(defval="crossover", title="", options=[op01, op02, op03, op04, op05, op06, op07, op08, op09, op10, op11, op12, op13, op14, op15], group= s_grp_SCC,inline="SC_cond1")
s_Cond_SC_1_ind2= input.string(defval="IND1", title="", options=[s01, s02, s03, s04, s05, s06, s07, s08, s09, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19], group= s_grp_SCC,inline="SC_cond1")
f_Cond_SC_1_ind2_val=input.float( defval=0, title="", group= s_grp_SCC, inline="SC_cond1",step=0.1, tooltip=s_tt_combination)
//_______________SHORT CLOSE 1-2 JOIN
s_Cond_SC_1_join_2= input.string(defval="AND", title="", options=["AND","OR"] , group= s_grp_SCC, tooltip=s_tt_Comb_op)
//_______________SHORT CLOSE 2 CONDITION
s_Cond_SC_2_ind1= input.string(defval="NONE", title="", options=[s00, s01, s02, s03, s04, s05, s07, s08, s09, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19], group= s_grp_SCC,inline="SC_cond2")
s_Cond_SC_2_op= input.string(defval="crossover", title="", options=[op01, op02, op03, op04, op05, op06, op07, op08, op09, op10, op11, op12, op13, op14, op15], group= s_grp_SCC,inline="SC_cond2")
s_Cond_SC_2_ind2= input.string(defval="IND2", title="", options=[s01, s02, s03, s04, s05, s06, s07, s08, s09, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19], group= s_grp_SCC,inline="SC_cond2")
f_Cond_SC_2_ind2_val=input.float( defval=0, title="", group= s_grp_SCC, inline="SC_cond2",step=0.1, tooltip=s_tt_combination)
//_______________SHORT CLOSE 2-3 JOIN
s_Cond_SC_2_join_3= input.string(defval="AND", title="", options=["AND","OR"] , group= s_grp_SCC, tooltip=s_tt_Comb_op)
//_______________SHORT CLOSE 3 CONDITION
s_Cond_SC_3_ind1= input.string(defval="NONE", title="", options=[s00, s01, s02, s03, s04, s05, s07, s08, s09, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19], group= s_grp_SCC,inline="SC_cond3")
s_Cond_SC_3_op= input.string(defval="crossover", title="", options=[op01, op02, op03, op04, op05, op06, op07, op08, op09, op10, op11, op12, op13, op14, op15], group= s_grp_SCC,inline="SC_cond3")
s_Cond_SC_3_ind2= input.string(defval="IND3", title="", options=[s01, s02, s03, s04, s05, s06, s07, s08, s09, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19], group= s_grp_SCC,inline="SC_cond3")
f_Cond_SC_3_ind2_val=input.float( defval=0, title="", group= s_grp_SCC, inline="SC_cond3",step=0.1, tooltip=s_tt_combination)
//_______________SHORT CLOSE 3-4 JOIN
s_Cond_SC_3_join_4= input.string(defval="AND", title="", options=["AND","OR"] , group= s_grp_SCC, tooltip=s_tt_Comb_op)
//_______________SHORT CLOSE 4 CONDITION
s_Cond_SC_4_ind1= input.string(defval="NONE", title="", options=[s00, s01, s02, s03, s04, s05, s07, s08, s09, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19], group= s_grp_SCC,inline="SC_cond4")
s_Cond_SC_4_op= input.string(defval="crossover", title="", options=[op01, op02, op03, op04, op05, op06, op07, op08, op09, op10, op11, op12, op13, op14, op15], group= s_grp_SCC,inline="SC_cond4")
s_Cond_SC_4_ind2= input.string(defval="IND3", title="", options=[s01, s02, s03, s04, s05, s06, s07, s08, s09, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19], group= s_grp_SCC,inline="SC_cond4")
f_Cond_SC_4_ind2_val=input.float( defval=0, title="", group= s_grp_SCC, inline="SC_cond4",step=0.1, tooltip=s_tt_combination)
//************CUSTOM INDICATORS //This area can be by personal usage
b_cut_ind = input.bool( defval=true, title=s_grp_custom_ind, tooltip=s_tt_custind)
//_______________CUSTOM INDICATOR 1
//EMA indicator paramaeters (@ tradingview)
s_cind1_src = input.string( defval='close', title='Source', options=['close', 'open', 'high', 'low', 'hlc3', 'hl2','ohlc4', 'heikin'], group= s_grp_custom_ind1, inline="cind1")
i_cind1_len = input.int( defval=520, title='Len', group= s_grp_custom_ind1, inline="cind1")
//_______________CUSTOM INDICATOR 2
//Squeeze Momentum indicator parameters (@LazyBear)
s_cind2_src = input.string( defval='close', title='Source', options=['close', 'open', 'high', 'low', 'hlc3', 'hl2','ohlc4', 'heikin'], group= s_grp_custom_ind2, inline="cind2_1")
b_cind2_TR = input.bool( defval=true, title="True Range", group= s_grp_custom_ind2, inline="cind2_1")
i_cind2_lenBB = input.int( defval=20, title='BB Len', group= s_grp_custom_ind2, inline="cind2_2")
f_cind2_multBB = input.float( defval=2.0, title='Fact', step=0.1, group= s_grp_custom_ind2, inline="cind2_2")
i_cind2_lenKC = input.int( defval=20, title='KC Len', group= s_grp_custom_ind2, inline="cind2_3")
f_cind2_multKC = input.float( defval=1.5, title='Fact', step=0.1, group= s_grp_custom_ind2, inline="cind2_3")
//_______________CUSTOM INDICATOR 3
//Supertrend indicator parameters (@ tradingview)
s_cind3_src = input.string( defval='close', title='Source', options=['close', 'open', 'high', 'low', 'hlc3', 'hl2','ohlc4', 'heikin'], group= s_grp_custom_ind3, inline="cind3_1")
b_cind3_chgATR = input.bool( defval=true, title="Change ATR Method", group= s_grp_custom_ind3, inline="cind3_1")
i_cind3_atrP = input.int( defval=10, title='ATR Len', group= s_grp_custom_ind3, inline="cind3_2")
f_cind3_factor = input.float( defval=3.0, title='Fact', step=0.1, group= s_grp_custom_ind3, inline="cind3_2")
//_______________CUSTOM INDICATOR 4
//EMA indicator paramaeters (@ tradingview)
s_cind4_src= input.string( defval='vwma', title='CIND4', options=[h01, i00, i01, i02, i03, i04, i05, i06, i07, i08, i09, i10, i11, i12, i13, i14, i15, i16, i17, i18,
i19, i20, i21, i22, i23, i24, i25, i26, i27, i28, i29, i30, i31, i32, i33, o00, o01, o02, o03, o04,
o05, o06, o07, o08, o09, o10, o11, o12, o13, o14, o15, o16, o17, o18, o19, o20, o21, o22, o23, o24,
o25, o26, o27, o28, o29, c00, c01, c02, c03, c04, c05, c06, c07, c08]
, group= s_grp_custom_ind4, inline="cind4_1")
s_cind4_data = input.string( defval="close", title='', options=[s07, s08, s09, s10, s11, s12, s13, s14], group= s_grp_custom_ind4, inline="cind4_1")
i_cind4_demlen = input.int( defval=24, title='Len', group= s_grp_custom_ind4, inline="cind4_2")
i_cind4_step = input.int( defval=4, title='Step', group= s_grp_custom_ind4, inline="cind4_2")
f_cind4_curv = input.float( defval=0.618, title='Curv', group= s_grp_custom_ind4, inline="cind4_2")
b_cind4_cross = input.bool( defval=false, title="Cross", group= s_grp_custom_ind4, inline="cind4_3")
//_______________CUSTOM INDICATOR 5
//EMA indicator paramaeters (@ tradingview)
s_cind5_src = input.string( defval='close', title='Source', options=['close', 'open', 'high', 'low', 'hlc3', 'hl2','ohlc4', 'heikin'], group= s_grp_custom_ind5, inline="cind5")
i_cind5_len = input.int( defval=100, title='Len', group= s_grp_custom_ind5, inline="cind5")
//************END INPUTS}
//************FUNCTIONS{
//_____________PERIOD DEFINITION
fn_testPeriod() =>
time >= t_testPeriodStart and time <= t_testPeriodStop ? true : false
//___________________#GET SECURE SOURCE
//_____________F_SECURITY***NOREPAINT (or Minimize it)
f_security(_symbol, _res, _src, _secure) =>
_secure == 'Secure' ? request.security(_symbol, _res, _src[1], lookahead=barmerge.lookahead_on) : _secure == 'Semi Secure' ? request.security(_symbol, _res, _src[barstate.isrealtime ? 1 : 0])[barstate.isrealtime ? 0 : 1] : _secure == 'Repaint' ? request.security(_symbol, _res, _src[0])[0] : na
src_open = f_security(syminfo.tickerid, Timeframe, open, secure)
src_close = f_security(syminfo.tickerid, Timeframe, close, secure)
src_high = f_security(syminfo.tickerid, Timeframe, high, secure)
src_low = f_security(syminfo.tickerid, Timeframe, low, secure)
src_hl2 = f_security(syminfo.tickerid, Timeframe, hl2, secure)
src_hlc3 = f_security(syminfo.tickerid, Timeframe, hlc3, secure)
src_ohlc4 = f_security(syminfo.tickerid, Timeframe, ohlc4, secure)
src_heikin = f_security(ticker.heikinashi(syminfo.tickerid), Timeframe, close, secure)
fn_get_source(string source_) =>
// source_ == 'Avg Price'? close :
result = switch source_
s07 => src_close
s08 => src_open
s09 => src_high
s10 => src_low
s11 => src_hl2
s12 => src_hlc3
s13 => src_ohlc4
s14 => src_heikin
=>na
result
//src_data = f_security(syminfo.tickerid, Timeframe, fn_get_source(data), secure)
src_external = f_security(syminfo.tickerid, Timeframe, data_ext, secure)
//___________________#PLOTTING FUNCTIONS
fn_plotFunction(float src_, simple string plotingType_="Original", simple int stochlen_=50, bool plotSWMA_ = false, bool useSimpleLog_=false) =>
f_plot_= switch plotingType_
p02 => ta.stoch(src_, src_, src_, stochlen_) / 50 - 1
p03 => ta.percentrank(src_, stochlen_) / 50 - 1
p01 => src_
p04 => src_
=> src_
f_plot_:=plotSWMA_ ? ta.swma(f_plot_) : f_plot_
f_plot_:=useSimpleLog_ ? math.log(f_plot_) : f_plot_
//**********************************************************
//_____________CUSTOM INDICATORS DEFINITIONS
//**********************************************************
//_____________CUSTOM INDICATOR 1 DESIGN
// define custom indicator 1 below. Define and Get input parameters from INPUTS/CUSTOM INDICATOR 1
// you can change the name of the custom indicator by updating CONSTANTS/CUSTOM INDICATORS c01="Cust Ind1" to your preffered name Ex: c01="My Custom EMA". (name should be unique and be different from other indicators names)
// NOTE:!!! Custom indicators dont use the value on the SETTINGS / INDICATOR selection screen.. Just accepts the parameters on the current custom indicator(n) setting area
//Builtin tradingview EMA indicator for customization example
fn_custom_ind1()=>
source_ = fn_get_source(s_cind1_src) //secure selected source
len_ = i_cind1_len //ex: get len for custom indicator 1 from INPUTS/CUSTOM INDICATOR 1
result = ta.ema(source_,len_) //indicator calculation return float value to result variable as output
result
//_____________CUSTOM INDICATOR 2 DESIGN
// Squeeze Momentum Indicator [LazyBear] a little bit Modified and only squeeze part with -1,1 range added to show Indicator "Org. Range (-1,1)" PlotType
// Additionally For showing indicator name change, Custom indicator name of constant "C02" updated from "Cust Ind2" to "Custom Squeeze MOM"
fn_custom_ind2()=>
source_ = fn_get_source(s_cind2_src) //secure selected source
high_ = fn_get_source("high") //secure "high"
low_ = fn_get_source("low") //secure "low"
multBB_ = f_cind2_multBB //ex: get "BB multiplier" parameter for custom indicator 2 from INPUTS/CUSTOM INDICATOR 2
lenBB_ = i_cind2_lenBB //ex: get "BB Length" parameter for custom indicator 2 from INPUTS/CUSTOM INDICATOR 2
multKC_ = f_cind2_multKC //ex: get "KC multiplier" parameter for custom indicator 2 from INPUTS/CUSTOM INDICATOR 2
lenKC_ = i_cind2_lenKC //ex: get "KC Length" parameter for custom indicator 2 from INPUTS/CUSTOM INDICATOR 2
useTR_ = b_cind2_TR //ex: get "Use True Range" parameter for custom indicator 2 from INPUTS/CUSTOM INDICATOR 2
// Calculate BB
basis_ = ta.sma(source_, lenBB_)
dev_ = multBB_ * ta.stdev(source_, lenBB_)
upperBB_ = basis_ + dev_
lowerBB_ = basis_ - dev_
// Calculate KC
ma_ = ta.sma(source_, lenKC_)
range_ = useTR_ ? ta.tr : (high_ - low_)
rangema_ = ta.sma(range_, lenKC_)
upperKC_ = ma_ + rangema_ * multKC_
lowerKC_ = ma_ - rangema_ * multKC_
// Calculate Squeeze
sqzOn_ = (lowerBB_ > lowerKC_) and (upperBB_ < upperKC_)
sqzOff_ = (lowerBB_ < lowerKC_) and (upperBB_ > upperKC_)
noSqz_ = (sqzOn_ == false) and (sqzOff_ == false)
result = sqzOn_? 1.0: sqzOff_? -1.0: noSqz_? 0.0: na //indicator calculation return float value to result variable as indicator output
result
//_____________CUSTOM INDICATOR 3 DESIGN
// SuperTrend Indicator [@KivancOzbilgic] a little bit Modified
// Additionally For showing indicator name change, Custom indicator name of constant "C03" updated from "Cust Ind3" to "Custom SuperTrend"
fn_custom_ind3()=>
source_ = fn_get_source(s_cind3_src) //secure selected source
close_ = fn_get_source("close") //secure "close"
chg_ATR_= b_cind3_chgATR //ex: get ATR Method parameter for custom indicator 3 from INPUTS/CUSTOM INDICATOR 3
atr_per_= i_cind3_atrP //ex: get ATR period parameter for custom indicator 3 from INPUTS/CUSTOM INDICATOR 3
atr_fct_= f_cind3_factor //ex: get ATR Factor parameter for custom indicator 3 from INPUTS/CUSTOM INDICATOR 3
atr2_ = ta.sma(ta.tr, atr_per_)
atr_ = chg_ATR_ ? ta.atr(atr_per_) : atr2_
up_ = source_-(atr_fct_*atr_)
up1_ = nz(up_[1], up_)
up_ := close_[1] > up1_ ? math.max(up_,up1_) : up_
dn_ = source_ + (atr_fct_ * atr_)
dn1_ = nz(dn_[1], dn_)
dn_ := close_[1] < dn1_ ? math.min(dn_, dn1_) : dn_
trend_ = 1
trend_ := nz(trend_[1], trend_)
trend_ := trend_ == -1 and close_ > dn1_ ? 1 : trend_ == 1 and close_ < up1_ ? -1 : trend_
result = trend_ == 1 ? up_ : dn_ //indicator calculation return float value to result variable as indicator output
result
//_____________CUSTOM INDICATOR 4 DESIGN
//Cronex T Demarker indicator for customization example
fn_demarker(simple int dem_length) =>
deMax = src_high - src_high[1] > 0 ? src_high - src_high[1] : 0
deMin = src_low[1] - src_low > 0 ? src_low[1] - src_low : 0
sma_deMax = ind.f_funcPlot(s_cind4_src,deMax, length_=dem_length)
sma_deMin = ind.f_funcPlot(s_cind4_src,deMin, length_=dem_length)
sma_deMax / (sma_deMax + sma_deMin)
fn_cronex() =>
bool crossing = b_cind4_cross
int demarker_length = i_cind4_demlen
int dem_step = i_cind4_step
float curvature = f_cind4_curv
e1 = 0.0, e2 = 0.0,e3 = 0.0, e4 = 0.0, e5 = 0.0, e6 = 0.0
n = 1 + 0.5 * (demarker_length - 1)
w1 = 2 / (demarker_length + 1)
w2 = 1 - w1
b2 = curvature * curvature
b3 = b2 * curvature
c1 = -b3
c2 = (3 * (b2 + b3))
c3 = -3 * (2 * b2 + curvature + b3)
c4 = (1 + 3 * curvature + b3 + 3 * b2)
demarker_v = (fn_demarker(demarker_length) + fn_demarker(demarker_length + dem_step) + fn_demarker(demarker_length + dem_step * 2) + fn_demarker(demarker_length + dem_step * 3)) * 100 / 4 - 50
e1 := not na(demarker_v) ? w1 * demarker_v + w2 * e1[1] : 0
e2 := not na(demarker_v) ? w1 * e1 + w2 * e2[1] : 0
e3 := not na(demarker_v) ? w1 * e2 + w2 * e3[1] : 0
e4 := not na(demarker_v) ? w1 * e3 + w2 * e4[1] : 0
e5 := not na(demarker_v) ? w1 * e4 + w2 * e5[1] : 0
e6 := not na(demarker_v) ? w1 * e5 + w2 * e6[1] : 0
demarker_t = c1*e6 + c2*e5 + c3*e4 + c4*e3
signal = 0
if crossing
signal := ta.crossover(demarker_v,demarker_t)?1:ta.crossunder(demarker_v,demarker_t)?-1:0
else
signal := (demarker_v > demarker_t)? 1:-1
[signal,demarker_v,demarker_t]
fn_custom_ind4()=>
[x,y,z]=fn_cronex()
result=x
//_____________CUSTOM INDICATOR 5 DESIGN
//Builtin tradingview EMA indicator for customization example
fn_custom_ind5()=>
source_ = fn_get_source(s_cind5_src) //secure selected source
len_ = i_cind5_len //ex: get len for custom indicator 1 from INPUTS/CUSTOM INDICATOR 1
result = ta.ema(source_,len_) //indicator calculation return float value to result variable as output
result
//**********************************************************
//_____________END CUSTOM INDICATORS DEFINITIONS
//**********************************************************
//_____________FACTORIZE INDICATOR
//Add double triple, Quatr factor to selected indicator (like convert EMA to DEMA, TEMA, QEMA...)
fn_factor(simple string ind_src_,float source_,simple int length_,simple int fact_=1)=>
float xIND1 = ind.f_funcPlot(ind_src_,source_, length_=length_)
float xIND2 = ind.f_funcPlot(ind_src_,xIND1, length_=length_)
float xIND3 = ind.f_funcPlot(ind_src_,xIND2, length_=length_)
float xIND4 = ind.f_funcPlot(ind_src_,xIND3, length_=length_)
float xIND5 = ind.f_funcPlot(ind_src_,xIND4, length_=length_)
//float indfact_=0
indfact_ = switch fact_
1 => xIND1
2 => (2 * xIND1) - xIND2
3 => 3 * (xIND1 - xIND2) + xIND3
4 => 5 * xIND1 - 10 * xIND2 + 10 * xIND3 - 5 * xIND4 + xIND5
float result=indfact_
result
//_____________GET SELECTED INDICATOR VALUE
fn_get_indicator(simple string ind_src_, simple string ind_src_data_="close",simple int length_, simple string plotingType_,simple int stoch_length_=50,simple int ind_factor_=1)=>
float indicator_=0.0
bool b_ind_pSWMA_= switch plotingType_
"Original" => false
"Org. Range (-1,1)" => false
=> b_ind_pSWMA
// bool b_ind_log_= switch plotingType_
// "Original" => false
// "Org. Range (-1,1)" => false
// => b_ind_log
indicator_ := switch ind_src_
c01 => fn_custom_ind1()
c02 => fn_custom_ind2()
c03 => fn_custom_ind3()
c04 => fn_custom_ind4()
c05 => fn_custom_ind5()
=> fn_factor(ind_src_=ind_src_,source_=fn_get_source(ind_src_data_), length_=length_, fact_=ind_factor_)
// => ind.f_funcPlot(ind_src_,fn_get_source(ind_src_data_), length_=length_)
indicator_:=fn_plotFunction(src_=indicator_, plotingType_=plotingType_, stochlen_=stoch_length_, plotSWMA_ = b_ind_pSWMA_)
indicator_
//_____________CONDITION RESULT
fn_get_Condition_Indicator(string cond_ind_,float cond_ind_value_,bool first_ind=true)=>
// if selection other than "VALUE"
// and if first_ind=false then use condition's value field for second indicator's #previous value
float cond_ind_val_ = switch cond_ind_
s00 => 0.
s01 => first_ind?indicator1 : indicator1[cond_ind_value_]
s02 => first_ind?indicator2 : indicator2[cond_ind_value_]
s03 => first_ind?indicator3 : indicator3[cond_ind_value_]
s04 => first_ind?indicator4 : indicator4[cond_ind_value_]
s05 => first_ind?indicator5 : indicator5[cond_ind_value_]
s06 => cond_ind_value_
s07 => first_ind? src_close : src_close[cond_ind_value_]
s08 => first_ind? src_open : src_open[cond_ind_value_]
s09 => first_ind? src_high : src_high[cond_ind_value_]
s10 => first_ind? src_low : src_low[cond_ind_value_]
s11 => first_ind? src_hl2 : src_hl2[cond_ind_value_]
s12 => first_ind? src_hlc3 : src_hlc3[cond_ind_value_]
s13 => first_ind? src_ohlc4 : src_ohlc4[cond_ind_value_]
s14 => first_ind? src_heikin: src_heikin[cond_ind_value_]
s15 => first_ind? src_external: src_external[cond_ind_value_]
s16 => cond_ind_value_
s17 => 0.
s18 => 0.
s19 => 0.
=> 0.
cond_ind_val_
fn_get_Condition_Result(string cond_ind1_,string cond_op_,string cond_ind2_,float cond_ind2_value_)=>
result=0
if fn_testPeriod()
cond_ind1_val_ = fn_get_Condition_Indicator(cond_ind1_, cond_ind2_value_, true)
cond_ind2_val_ = fn_get_Condition_Indicator(cond_ind2_, cond_ind2_value_, false)
int cond_result_= switch cond_op_
op01 => ta.crossover(cond_ind1_val_,cond_ind2_val_)? 1 : -1
op02 => ta.crossunder(cond_ind1_val_,cond_ind2_val_)? 1 : -1
op03 => ta.cross(cond_ind1_val_,cond_ind2_val_)? 1 : -1
op04 => cond_ind1_val_ > cond_ind2_val_ ? 1 : -1
op05 => cond_ind1_val_ < cond_ind2_val_ ? 1 : -1
op06 => cond_ind1_val_ >= cond_ind2_val_ ? 1 : -1
op07 => cond_ind1_val_ <= cond_ind2_val_ ? 1 : -1
op08 => cond_ind1_val_ == cond_ind2_val_ ? 1 : -1
op09 => cond_ind1_val_ != cond_ind2_val_ ? 1 : -1
op10 => ta.rising( cond_ind1_val_,int(cond_ind2_val_))?1:-1
op11 => ta.falling(cond_ind1_val_,int(cond_ind2_val_))?1:-1
op12 => 0
=> 0
result:=cond_ind1_=="NONE"?0:cond_result_
result
//_____________JOIN CONDITIONS
fn_join_Condition_Result(int cond1_=0,int cond2_=0,int cond3_=0,int cond4_=0, string cond_1_join_2_="AND", string cond_2_join_3_="AND", string cond_3_join_4_="AND")=>
bool cond_=false
if cond1_!=0
cond_:=cond1_==1
if cond1_!=0 and cond2_ !=0
cond_ := switch cond_1_join_2_
"AND" => cond1_==1 and cond2_==1
"OR" => cond1_==1 or cond2_ ==1
if cond3_ !=0
cond_:= switch cond_2_join_3_
"AND" => cond_==1 and cond3_==1
"OR" => cond_==1 or cond3_==1
if cond4_ !=0
cond_:= switch cond_3_join_4_
"AND" => cond_==1 and cond4_==1
"OR" => cond_==1 or cond4_==1
result=cond_
//_____________GET CONDITIONS
fn_get_conditions(string type_)=>
result=false
if type_=="LONG" and (s_Cond_LE_1_ind1!="NONE" or s_Cond_LE_2_ind1!="NONE" or s_Cond_LE_3_ind1!="NONE")
int long_entry1=fn_get_Condition_Result(s_Cond_LE_1_ind1,s_Cond_LE_1_op,s_Cond_LE_1_ind2,f_Cond_LE_1_ind2_val)
int long_entry2=fn_get_Condition_Result(s_Cond_LE_2_ind1,s_Cond_LE_2_op,s_Cond_LE_2_ind2,f_Cond_LE_2_ind2_val)
int long_entry3=fn_get_Condition_Result(s_Cond_LE_3_ind1,s_Cond_LE_3_op,s_Cond_LE_3_ind2,f_Cond_LE_3_ind2_val)
int long_entry4=fn_get_Condition_Result(s_Cond_LE_4_ind1,s_Cond_LE_4_op,s_Cond_LE_4_ind2,f_Cond_LE_4_ind2_val)
result := fn_join_Condition_Result(cond1_=long_entry1,cond2_=long_entry2,cond3_=long_entry3,cond4_=long_entry4, cond_1_join_2_=s_Cond_LE_1_join_2, cond_2_join_3_=s_Cond_LE_2_join_3, cond_3_join_4_=s_Cond_LE_3_join_4)
if type_=="SHORT" and (s_Cond_SE_1_ind1!="NONE" or s_Cond_SE_2_ind1!="NONE" or s_Cond_SE_3_ind1!="NONE")
int short_entry1=fn_get_Condition_Result(s_Cond_SE_1_ind1,s_Cond_SE_1_op,s_Cond_SE_1_ind2,f_Cond_SE_1_ind2_val)
int short_entry2=fn_get_Condition_Result(s_Cond_SE_2_ind1,s_Cond_SE_2_op,s_Cond_SE_2_ind2,f_Cond_SE_2_ind2_val)
int short_entry3=fn_get_Condition_Result(s_Cond_SE_3_ind1,s_Cond_SE_3_op,s_Cond_SE_3_ind2,f_Cond_SE_3_ind2_val)
int short_entry4=fn_get_Condition_Result(s_Cond_SE_4_ind1,s_Cond_SE_4_op,s_Cond_SE_4_ind2,f_Cond_SE_4_ind2_val)
// result := fn_join_Condition_Result(short_entry1,short_entry2,short_entry3, s_Cond_SE_1_join_2, s_Cond_SE_2_join_3)
result := fn_join_Condition_Result(cond1_=short_entry1,cond2_=short_entry2,cond3_=short_entry3,cond4_=short_entry4, cond_1_join_2_=s_Cond_SE_1_join_2, cond_2_join_3_=s_Cond_SE_2_join_3, cond_3_join_4_=s_Cond_SE_3_join_4)
if type_=="LONGCLOSE" and (s_Cond_LC_1_ind1!="NONE" or s_Cond_LC_2_ind1!="NONE" or s_Cond_LC_3_ind1!="NONE")
int long_close1=fn_get_Condition_Result(s_Cond_LC_1_ind1,s_Cond_LC_1_op,s_Cond_LC_1_ind2,f_Cond_LC_1_ind2_val)
int long_close2=fn_get_Condition_Result(s_Cond_LC_2_ind1,s_Cond_LC_2_op,s_Cond_LC_2_ind2,f_Cond_LC_2_ind2_val)
int long_close3=fn_get_Condition_Result(s_Cond_LC_3_ind1,s_Cond_LC_3_op,s_Cond_LC_3_ind2,f_Cond_LC_3_ind2_val)
int long_close4=fn_get_Condition_Result(s_Cond_LC_4_ind1,s_Cond_LC_4_op,s_Cond_LC_4_ind2,f_Cond_LC_4_ind2_val)
// result := fn_join_Condition_Result(long_close1,long_close2,long_close3, s_Cond_LC_1_join_2, s_Cond_LC_2_join_3)
result := fn_join_Condition_Result(cond1_=long_close1,cond2_=long_close2,cond3_=long_close3,cond4_=long_close4, cond_1_join_2_=s_Cond_LC_1_join_2, cond_2_join_3_=s_Cond_LC_2_join_3, cond_3_join_4_=s_Cond_LC_3_join_4)
if type_=="SHORTCLOSE" and (s_Cond_SC_1_ind1!="NONE" or s_Cond_SC_2_ind1!="NONE" or s_Cond_SC_3_ind1!="NONE")
int short_close1=fn_get_Condition_Result(s_Cond_SC_1_ind1,s_Cond_SC_1_op,s_Cond_SC_1_ind2,f_Cond_SC_1_ind2_val)
int short_close2=fn_get_Condition_Result(s_Cond_SC_2_ind1,s_Cond_SC_2_op,s_Cond_SC_2_ind2,f_Cond_SC_2_ind2_val)
int short_close3=fn_get_Condition_Result(s_Cond_SC_3_ind1,s_Cond_SC_3_op,s_Cond_SC_3_ind2,f_Cond_SC_3_ind2_val)
int short_close4=fn_get_Condition_Result(s_Cond_SC_4_ind1,s_Cond_SC_4_op,s_Cond_SC_4_ind2,f_Cond_SC_4_ind2_val)
// result := fn_join_Condition_Result(short_close1,short_close2,short_close3, s_Cond_SC_1_join_2, s_Cond_SC_2_join_3)
result := fn_join_Condition_Result(cond1_=short_close1,cond2_=short_close2,cond3_=short_close3,cond4_=short_close4, cond_1_join_2_=s_Cond_SC_1_join_2, cond_2_join_3_=s_Cond_SC_2_join_3, cond_3_join_4_=s_Cond_SC_3_join_4)
result
//************END FUNCTIONS}
//************CUSTOM INDICATORS CALCULATIONS{
float custom_ind1=fn_custom_ind1() //dont change "float custom_ind1". this is result of the indicator used by the system
float custom_ind2=fn_custom_ind2() //dont change "float custom_ind2". this is result of the indicator used by the system
float custom_ind3=fn_custom_ind3() //dont change "float custom_ind3". this is result of the indicator used by the system
float custom_ind4=fn_custom_ind4() //dont change "float custom_ind4". this is result of the indicator used by the system
float custom_ind5=fn_custom_ind5() //dont change "float custom_ind5". this is result of the indicator used by the system
//******END CUSTOM INDICATORS CALCULATIONS}
//************SIGNAL CALCULATIONS{
indicator1:= fn_get_indicator(s_ind1_src,ind_src_data_=s_ind1_data,length_=i_ind1_len, plotingType_=s_ind1_pType,stoch_length_=i_ind1_stoch, ind_factor_=i_ind1_fact_)
indicator2:= fn_get_indicator(s_ind2_src,ind_src_data_=s_ind2_data,length_=i_ind2_len, plotingType_=s_ind2_pType,stoch_length_=i_ind2_stoch, ind_factor_=i_ind2_fact_)
indicator3:= fn_get_indicator(s_ind3_src,ind_src_data_=s_ind3_data,length_=i_ind3_len, plotingType_=s_ind3_pType,stoch_length_=i_ind3_stoch, ind_factor_=i_ind3_fact_)
indicator4:= fn_get_indicator(s_ind4_src,ind_src_data_=s_ind4_data,length_=i_ind4_len, plotingType_=s_ind4_pType,stoch_length_=i_ind4_stoch, ind_factor_=i_ind4_fact_)
indicator5:= fn_get_indicator(s_ind5_src,ind_src_data_=s_ind5_data,length_=i_ind5_len, plotingType_=s_ind5_pType,stoch_length_=i_ind5_stoch, ind_factor_=i_ind5_fact_)
bool long= fn_get_conditions("LONG")
bool short= fn_get_conditions("SHORT")
bool longclose= fn_get_conditions("LONGCLOSE")
bool shortclose=fn_get_conditions("SHORTCLOSE")
if b_isopposite
longclose:= longclose or short
shortclose:=shortclose or long
//************END SIGNAL CALCULATIONS}
//************PLOTs{
//_________PLOT INDICATORS (if Indicator PlotType is "Original" plot over chart otherwise plot between HLines)
plot(s_ind1_src!="Hide" ? (s_ind1_pType=="Original"?indicator1: i_ind_shift + (indicator1 * i_ind_mult)):na, "",c_ind1_color)
plot(s_ind2_src!="Hide" ? (s_ind2_pType=="Original"?indicator2: i_ind_shift + (indicator2 * i_ind_mult)):na, "",c_ind2_color)
plot(s_ind3_src!="Hide" ? (s_ind3_pType=="Original"?indicator3: i_ind_shift + (indicator3 * i_ind_mult)):na, "",c_ind3_color)
plot(s_ind4_src!="Hide" ? (s_ind4_pType=="Original"?indicator4: i_ind_shift + (indicator4 * i_ind_mult)):na, "",c_ind4_color)
plot(s_ind5_src!="Hide" ? (s_ind5_pType=="Original"?indicator5: i_ind_shift + (indicator5 * i_ind_mult)):na, "",c_ind5_color)
//_________SHOW REAL INDICATOR VALUES ON DATA WINDOW
plotshape(s_ind1_src!="Hide" ? indicator1:na, "INDICATOR1", text="",color=color.new(c_ind1_color,100))
plotshape(s_ind1_src!="Hide" ? indicator2:na, "INDICATOR2", text="",color=color.new(c_ind2_color,100))
plotshape(s_ind1_src!="Hide" ? indicator3:na, "INDICATOR3", text="",color=color.new(c_ind3_color,100))
plotshape(s_ind1_src!="Hide" ? indicator4:na, "INDICATOR4", text="",color=color.new(c_ind4_color,100))
plotshape(s_ind1_src!="Hide" ? indicator5:na, "INDICATOR5", text="",color=color.new(c_ind5_color,100))
//_________PLOT HLINE for Stochastic/Precentage/Org Range(-1,1) between range -1 and 1
hline(b_ind_hline?i_ind_shift + (1 * i_ind_mult):na, title="LINE 1", linestyle=hline.style_dashed ,color=color.new(color.black, 0))
hline(b_ind_hline?i_ind_shift + (0.5 *i_ind_mult):na, title="LINE 0.5", linestyle=hline.style_dashed ,color=color.new(color.black, 75))
hline(b_ind_hline?i_ind_shift + (0 * i_ind_mult):na, title="LINE 0", linestyle=hline.style_dashed ,color=color.new(color.black, 0))
hline(b_ind_hline?i_ind_shift + (-0.5*i_ind_mult):na, title="LINE -0.5",linestyle=hline.style_dashed ,color=color.new(color.black, 75))
hline(b_ind_hline?i_ind_shift + (-1 * i_ind_mult):na, title="LINE -1", linestyle=hline.style_dashed ,color=color.new(color.black, 0))
//_________PLOT ALERTS for LONG at Bottom and for SHORT at TOP of the screen
plotshape(b_plotalert ? long : na, title='LONG', style=shape.triangleup, location=location.bottom, color=color.new(color.green, 0),size=size.tiny)
plotshape(b_plotalert ? short : na, title='SHORT', style=shape.triangledown, location=location.top, color=color.new(color.blue, 0), size=size.tiny)
plotshape(b_plotalert ? longclose : na, title='EXIT LONG', style=shape.triangledown, location=location.bottom, color=color.new(color.red, 0), size=size.tiny)
plotshape(b_plotalert ? shortclose : na, title='EXIT SHORT',style=shape.triangleup, location=location.top, color=color.new(color.black, 0),size=size.tiny)
//************END PLOTs}
//************STRATEGY DEFINITIONS (For indicator usage: Mark following lines & Change strategy(....) to indicator(....) at start of the code {
//________________STRATEGY ENTRIES & EXITS
if fn_testPeriod() and long
// strategy.entry("buy",strategy.long,alert_message=web_hook("Buy",close,bot_json))
strategy.entry("buy", strategy.long, alert_message="L",comment="L")
if fn_testPeriod() and short
// strategy.entry("sell",strategy.short,alert_message=web_hook("Sell",close,bot_json))
strategy.entry("sell",strategy.short,alert_message="S",comment="S")
if fn_testPeriod() and longclose
// strategy.close_all(alert_message=web_hook("Close",close,bot_json))
strategy.close("buy", alert_message="CL",comment="CL")
if fn_testPeriod() and shortclose
// strategy.close_all(alert_message=web_hook("Close",close,bot_json))
strategy.close("sell",alert_message="CS",comment="CS")
//-------------------------------------------------------------
//_____________SHOW PROFIT // Should be improved I am stucked !!!
s_showProfit= input.string( defval="None", title="Show Profit", options=["None", "Open Profit", "Current Profit" ], group=s_grp_settings,inline="show profit")
i_showProfit_trans= input.int( defval=80, title="Transparency", group=s_grp_settings,inline="show profit", tooltip=s_tt_Profit)
fn_get_profit_bytype(string s_profitType_)=>
float f_profit_=switch s_profitType_
"None" => na
"Current Profit"=> (strategy.netprofit+strategy.openprofit)
"Open Profit" => strategy.openprofit
f_profit_
var openposprof= array.new_float(0)
float cur=0.
float max=1.
float min=0.
if s_showProfit!="None"
array.push(openposprof,fn_get_profit_bytype(s_showProfit)/strategy.initial_capital)
cur:=array.get(openposprof,bar_index)
max:=array.max(openposprof)
min:=array.min(openposprof)
float f_profit=cur/ (max - min)
f_profitper=f_profit
fill(plot(s_showProfit!="None"?i_ind_shift + (f_profit * i_ind_mult):na, title="",color=f_profit<0?color.new(color.red,i_showProfit_trans):color.new(color.green,i_showProfit_trans)),
plot(s_showProfit!="None"?i_ind_shift:na, title="",color=color.new(color.white,100)),
f_profit<0?color.new(color.red,i_showProfit_trans+5):color.new(color.green,i_showProfit_trans+5)) //Fill area on Profit value on between hlines
plotshape(s_showProfit!="None"?f_profit*100:na, title="PROFIT%",text="",color=color.new(color.white,100)) //Show Real Profit value on Data Window
//************END STRATEGY DEFINITIONS}
////************INDICATOR's SIGNALS EXPORT{
//// Followings are for my personal usage on my own strategy framework.
//// Created Parallel data transfer algorithm (@DTurkuler)
//// With this algo all builded signals can be transferred to another strategy/indicator without interferring with another signal
//longCondition =long
//shortCondition = short
//ExitLongCondition = longclose
//ExitshortCondition = shortclose
//
//Signal1 = 0.
////Long Entry Signals
////(10:Long Entry 20:Long Exit 30:No Operation)
//Signal1 := longCondition ? 10 : ExitLongCondition ? 20 : 30
////Short Entry Signals
////(10:Long Entry 20:Long Exit 30:No Operation)
//Signal1 := Signal1 + (shortCondition ? 1 : ExitshortCondition ? 2 : 3)
////TODO: Entry/Exit Filter Signals (1:Entry 2:No Entry 3:No Operation)
////Signal1 := Signal1 + (entryFilter ? 100 : exitFilter ? 200 : 300)
////TODO: Trend Filter Signals (1:Up 2:down 3:Sideways)
////Signal1 := Signal1 + (trend==1 ? 1000 : trend==-1 ? 2000 : 3000)
//
////_______________DATA ENCODER V2 (Set precision to 4)
//// V2 is used to plot the indicator values over the stock.
//// Signal data shifted to digit area and close value added as carrier to the fractional part
//ext_version= input.int( title='External Data Version', defval=1, group='═════════════ SETTINGS ═════════════' )
//encoder(float data_, source_=close)=>
// float Signal_=0.
// float f_carrier=int(source_)
// Signal_:=0.0001*data_
// Signal_+=f_carrier
// result=Signal_
//Signal1:=ext_version==2?encoder(data_=Signal1):Signal1
////_______________DATA ENCODER
//
//plot(Signal1, title='🔌Connector🔌', color=color.new(color.blue,100))
//plotshape(b_plotalert ? longCondition : na,title='LONG', style=shape.triangleup, location=location.bottom, color=color.new(color.green, 0), size=size.tiny)
//plotshape(b_plotalert ? shortCondition : na, title='SHORT', style=shape.triangledown, location=location.top, color=color.new(color.blue, 0), size=size.tiny)
//plotshape(b_plotalert ? ExitLongCondition : na, title='EXIT LONG', style=shape.triangledown, location=location.bottom, color=color.new(color.red, 0), size=size.tiny)
//plotshape(b_plotalert ? ExitshortCondition : na, title='EXIT SHORT', style=shape.triangleup, location=location.top, color=color.new(color.black, 0), size=size.tiny)
////************END INDICATOR's SIGNALS EXPORT}
|
Tendency EMA + RSI [Alorse] | https://www.tradingview.com/script/X6K0ARDV-Tendency-EMA-RSI-Alorse/ | alorse | https://www.tradingview.com/u/alorse/ | 456 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@author Alorse
//@version=5
strategy(title='Tendency EMA + RSI [Alorse]', shorttitle='Tendece EMA + RSI [Alorse]', overlay=true, pyramiding=0, currency=currency.USD, default_qty_type=strategy.percent_of_equity, initial_capital=1000, default_qty_value=20, commission_type=strategy.commission.percent, commission_value=0.01)
// Bollinger Bands
len = input.int(14, minval=1, title='Length', group='RSI')
src = input.source(close, 'Source', group='RSI')
rsi = ta.rsi(src, len)
// Moving Averages
len_a = input.int(10, minval=1, title='EMA A Length', group='Moving Averages')
out_a = ta.ema(close, len_a)
plot(out_a, title='EMA A', color=color.purple)
len_b = input.int(20, minval=1, title='EMA B Length', group='Moving Averages')
out_b = ta.ema(close, len_b)
plot(out_b, title='EMA B', color=color.orange)
len_c = input.int(100, minval=1, title='EMA C Length', group='Moving Averages')
out_c = ta.ema(close, len_c)
plot(out_c, title='EMA B', color=color.green)
// Strategy Conditions
stratGroup = 'Strategy'
showLong = input.bool(true, title='Long entries', group=stratGroup)
showShort = input.bool(false, title='Short entries', group=stratGroup)
closeAfterXBars = input.bool(true, title='Close after X # bars', tooltip='If trade is in profit', group=stratGroup)
xBars = input.int(24, title='# bars')
entryLong = ta.crossover(out_a, out_b) and out_a > out_c and close > open
exitLong = rsi > 70
entryShort = ta.crossunder(out_a, out_b) and out_a < out_c and close < open
exitShort = rsi < 30
bought = strategy.opentrades[0] == 1 and strategy.position_size[0] > strategy.position_size[1]
entry_price = ta.valuewhen(bought, open, 0)
var int nPastBars = 0
if strategy.position_size > 0
nPastBars := nPastBars + 1
nPastBars
if strategy.position_size == 0
nPastBars := 0
nPastBars
if closeAfterXBars
exitLong := nPastBars >= xBars and close > entry_price ? true : exitLong
exitLong
exitShort := nPastBars >= xBars and close < entry_price ? true : exitShort
exitShort
// Long Entry
strategy.entry('Long', strategy.long, when=entryLong and showLong)
strategy.close('Long', when=exitLong)
// Short Entry
strategy.entry('Short', strategy.short, when=entryShort and showShort)
strategy.close('Short', when=exitShort)
|
GMH : ATH 200d | https://www.tradingview.com/script/Bhrx27uW-GMH-ATH-200d/ | gmhfund | https://www.tradingview.com/u/gmhfund/ | 17 | 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/
// © gmhfund
//@version=5
strategy(title='ATH Strategy',overlay=true ,default_qty_type=strategy.percent_of_equity ,initial_capital=10000, default_qty_value=100 ,currency=currency.USD)
// Backtest Period
on_customPeriod = input.bool(true, "Backtesting custom dates")
start_date = input.time(timestamp("1 Jan 2019"), "From")
end_date = input.time(timestamp("1 Jan 2025"), "to")
checkPeriod() =>
time >= start_date and time <= end_date ? true : false
testPeriod = checkPeriod()
isPeriod = on_customPeriod == true ? testPeriod : true
//Input
bar_ath = input.int(200,"ATH Period",minval=5,maxval=500,step=1) // ATH days
sl = input.int(10,"%Stoploss",minval=0,maxval=100,step=1) // Stoploss %
on_percent = input.bool(true,"Close order 1/2 position when reach profit target ") // Profit Target Mode : ON
pt1 = input.int(50,"%Profit Target 1",minval=0,maxval=2000,step=1)
pt2 = input.int(100,"%Profit Target 2",minval=0,maxval=2000,step=1)
pt3 = input.int(300,"%Profit Target 3",minval=0,maxval=2000,step=1)
on_cross = input.bool(true,"Close order all position when cross under SMA") // CrossUnder Mode : ON
bar_sma = input.int(90,"sma_length",minval=0,maxval=300,step=1) // SMA
var target_price = 0.0
var target1 = 0.0
var target2 = 0.0
var target3 = 0.0
var stock_share = 0.0
ath = ta.highest(bar_ath)[1] // Seeking price of highest bar , exclude current one
plot(ath,color=color.white)
sma = ta.sma(close,bar_sma)[1]
plot(sma)
// Price //
if close > ath and strategy.position_size == 0 // Update target price when ATH condition occurred
stock_share := math.floor(strategy.equity/close)
target1 := close*(1+pt1/100)
target2 := close*(1+pt2/100)
target3 := close*(1+pt3/100)
string pt_label = ""
if strategy.position_size >= stock_share // Hold full position
target_price := target1
pt_label := str.tostring(pt1)
else if strategy.position_size >= stock_share/2 // Remain half position
target_price := target2
pt_label := str.tostring(pt2)
else if strategy.position_size >= stock_share/4 // Remain 1/4 position
target_price := target3
pt_label := str.tostring(pt3)
// Long Condition
strategy.entry("long", strategy.long, stock_share, when = close > ath, comment = "buy" + " @" + str.tostring(close))
// Close Condition
// 1) by % stoploss
strategy.close("long", when = close < strategy.position_avg_price*(1-sl/100) , comment = "stoploss" + " @" + str.tostring(close) , qty_percent = 100)
// 2) by target price
strategy.close("long", when = on_percent == true and close > target_price, comment = "hit target"+ pt_label + "%" + " @" + str.tostring(close) , qty_percent = 50)
// 3) by sma crossunder
strategy.close("long", when = on_cross == true and ta.crossunder(close,sma) == true, comment = "sma cross" + " @" + str.tostring(close) , qty_percent = 100)
// END
if not isPeriod
strategy.cancel_all()
strategy.close_all()
|
Automatic Moving Average Strategy | https://www.tradingview.com/script/guPLDcYm-Automatic-Moving-Average-Strategy/ | fondDealer96636 | https://www.tradingview.com/u/fondDealer96636/ | 156 | 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/
// © fondDealer96636
//@version=5
strategy('Automatic Moving Average', overlay=true, max_bars_back=201, pyramiding=0, currency=currency.USD, default_qty_type=strategy.cash, default_qty_value=10000, initial_capital=10000)
// input
start = 20
lookback = input(20, "Sensitivity", tooltip="Low (High Sensitivity), High (Low Sensitivity).\n\nAdjust according to timeframe and asset.")
smoothing = input(3, "Smoothing")
source = input(close, "Source")
startYear = input(2020, "Start year")
resp = 1
in_date_range = time >= timestamp(syminfo.timezone, startYear, 1, 1, 0, 0)
// global
var ix = -1
var mal = array.new_int(0)
// functions
avg(source, len) =>
sum = 0.0
for i = 0 to len-1
sum += source[i]
sum/len
bull = close > open
wick_touch(x) =>
bull ? ((close <= x and x <= high) or (low <= x and x <= open)) : ((open <= x and x <= high) or (low <= x and x <= close))
body_touch(x) =>
bull ? (open < x and x < close) : (close < x and x < open)
touches(t) =>
touches = 0
for i = 0 to lookback-1
touches += t[i] ? 1 : 0
touches
// local
ix := ix+1
prev_mal = ix >= 1 ? array.get(mal, ix-1) : start
cma = avg(source, prev_mal)
cma_p1 = avg(source, prev_mal+1)
cma_m1 = avg(source, prev_mal-1)
d = touches(wick_touch(cma))
d_p1 = touches(wick_touch(cma_p1))
d_m1 = touches(wick_touch(cma_m1))
d_b = touches(body_touch(cma))
d_p1_b = touches(body_touch(cma_p1))
d_m1_b = touches(body_touch(cma_m1))
any_body_touch = d_b > 0 or d_p1_b > 0 or d_m1_b > 0
no_wick_touch = d <= 0 and d_p1 <= 0 and d_m1 <= 0
wick_maximized = d >= d_p1 and d >= d_m1 ? prev_mal : (d_p1 >= d and d_p1 >= d_m1 ? prev_mal+resp : (d_m1 >= d and d_m1 >= d_p1 ? prev_mal-resp : na))
up = cma > cma[1]
down = cma < cma[1]
against_trend = (up and close < cma) or (down and close > cma)
new_mal = no_wick_touch or against_trend ? prev_mal-resp : (any_body_touch ? prev_mal+resp : wick_maximized)
next_mal = na(new_mal) ? prev_mal : new_mal
array.push(mal, next_mal < 2 ? 2 : (next_mal > 200 ? 200 : next_mal))
// graph
scma = ta.ema(cma, smoothing)
uptrend = scma > scma[1]
downtrend = scma < scma[1]
plot(scma, "Automatic MA", color=uptrend ? color.green : color.red)
uptrending = close > scma and uptrend
downtrending = close < scma and downtrend
defy = not uptrending and not downtrending
defy_cross = defy and body_touch(scma)
barcolor(uptrending ? color.lime : (downtrending ? color.red : (defy_cross ? color.black : color.white)))
// strategy
change_to_uptrend = uptrending and not uptrending[1]
change_to_downtrend = downtrending and not downtrending[1]
if in_date_range
if change_to_uptrend
strategy.entry("Long", strategy.long)
if change_to_downtrend
strategy.entry("Short", strategy.short)
|
BBPBΔ(OBV-PVT)BB - Time Series Decomposition & Volume Weighted | https://www.tradingview.com/script/cFO2GbAp-BBPB%CE%94-OBV-PVT-BB-Time-Series-Decomposition-Volume-Weighted/ | tathal | https://www.tradingview.com/u/tathal/ | 184 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © oakwhiz and tathal
//@version=4
strategy("BBPBΔ(OBV-PVT)BB", default_qty_type=strategy.percent_of_equity, default_qty_value=100)
startDate = input(title="Start Date", type=input.integer,
defval=1, minval=1, maxval=31)
startMonth = input(title="Start Month", type=input.integer,
defval=1, minval=1, maxval=12)
startYear = input(title="Start Year", type=input.integer,
defval=2010, minval=1800, maxval=2100)
endDate = input(title="End Date", type=input.integer,
defval=31, minval=1, maxval=31)
endMonth = input(title="End Month", type=input.integer,
defval=12, minval=1, maxval=12)
endYear = input(title="End Year", type=input.integer,
defval=2021, minval=1800, maxval=2100)
// Normalize Function
normalize(_src, _min, _max) =>
// Normalizes series with unknown min/max using historical min/max.
// _src : series to rescale.
// _min, _min: min/max values of rescaled series.
var _historicMin = 10e10
var _historicMax = -10e10
_historicMin := min(nz(_src, _historicMin), _historicMin)
_historicMax := max(nz(_src, _historicMax), _historicMax)
_min + (_max - _min) * (_src - _historicMin) / max(_historicMax - _historicMin, 10e-10)
// STEP 2:
// Look if the close time of the current bar
// falls inside the date range
inDateRange = (time >= timestamp(syminfo.timezone, startYear,
startMonth, startDate, 0, 0)) and
(time < timestamp(syminfo.timezone, endYear, endMonth, endDate, 0, 0))
// Stop
f_secureSecurity(_symbol, _res, _src) => security(_symbol, _res, _src[1], lookahead = barmerge.lookahead_on)
// Stop loss & Take Profit Section
icreturn = false
innercandle = if (high < high[1]) and (low > low[1])
icreturn := true
src = close
float change_src = change(src)
float i_obv = cum(change_src > 0 ? volume : change_src < 0 ? -volume : 0*volume)
float i_pvt = pvt
float result = change(i_obv - i_pvt)
float nresult = ema(normalize(result, -1, 1), 20)
length = input(20, minval=1)
mult = input(2.0, minval=0.001, maxval=50, title="StdDev")
basis = ema(nresult, length)
dev = mult * stdev(nresult, length)
upper = basis + dev
lower = basis - dev
bbr = (nresult - lower)/(upper - lower)
////////////////INPUTS///////////////////
lambda = input(defval = 1000, type = input.float, title = "Smoothing Factor (Lambda)", minval = 1)
leng = input(defval = 100, type = input.integer, title = "Filter Length", minval = 1)
srcc = close
///////////Construct Arrays///////////////
a = array.new_float(leng, 0.0)
b = array.new_float(leng, 0.0)
c = array.new_float(leng, 0.0)
d = array.new_float(leng, 0.0)
e = array.new_float(leng, 0.0)
f = array.new_float(leng, 0.0)
/////////Initialize the Values///////////
//for more details visit:
// https://asmquantmacro.com/2015/06/25/hodrick-prescott-filter-in-excel/
ll1 = leng-1
ll2 = leng-2
for i = 0 to ll1
array.set(a,i, lambda*(-4))
array.set(b,i, src[i])
array.set(c,i, lambda*(-4))
array.set(d,i, lambda*6 + 1)
array.set(e,i, lambda)
array.set(f,i, lambda)
array.set(d, 0, lambda + 1.0)
array.set(d, ll1, lambda + 1.0)
array.set(d, 1, lambda * 5.0 + 1.0)
array.set(d, ll2, lambda * 5.0 + 1.0)
array.set(c, 0 , lambda * (-2.0))
array.set(c, ll2, lambda * (-2.0))
array.set(a, 0 , lambda * (-2.0))
array.set(a, ll2, lambda * (-2.0))
//////////////Solve the optimization issue/////////////////////
float r = array.get(a, 0)
float s = array.get(a, 1)
float t = array.get(e, 0)
float xmult = 0.0
for i = 1 to ll2
xmult := r / array.get(d, i-1)
array.set(d, i, array.get(d, i) - xmult * array.get(c, i-1))
array.set(c, i, array.get(c, i) - xmult * array.get(f, i-1))
array.set(b, i, array.get(b, i) - xmult * array.get(b, i-1))
xmult := t / array.get(d, i-1)
r := s - xmult*array.get(c, i-1)
array.set(d, i+1, array.get(d, i+1) - xmult * array.get(f, i-1))
array.set(b, i+1, array.get(b, i+1) - xmult * array.get(b, i-1))
s := array.get(a, i+1)
t := array.get(e, i)
xmult := r / array.get(d, ll2)
array.set(d, ll1, array.get(d, ll1) - xmult * array.get(c, ll2))
x = array.new_float(leng, 0)
array.set(x, ll1, (array.get(b, ll1) - xmult * array.get(b, ll2)) / array.get(d, ll1))
array.set(x, ll2, (array.get(b, ll2) - array.get(c, ll2) * array.get(x, ll1)) / array.get(d, ll2))
for j = 0 to leng-3
i = leng-3 - j
array.set(x, i, (array.get(b,i) - array.get(f,i)*array.get(x,i+2) - array.get(c,i)*array.get(x,i+1)) / array.get(d, i))
//////////////Construct the output///////////////////
o5 = array.get(x,0)
////////////////////Plottingd///////////////////////
TimeFrame = input('1', type=input.resolution)
start = f_secureSecurity(syminfo.tickerid, TimeFrame, time)
//------------------------------------------------
newSession = iff(change(start), 1, 0)
//------------------------------------------------
vwapsum = 0.0
vwapsum := iff(newSession, o5*volume, vwapsum[1]+o5*volume)
volumesum = 0.0
volumesum := iff(newSession, volume, volumesum[1]+volume)
v2sum = 0.0
v2sum := iff(newSession, volume*o5*o5, v2sum[1]+volume*o5*o5)
myvwap = vwapsum/volumesum
dev2 = sqrt(max(v2sum/volumesum - myvwap*myvwap, 0))
Coloring=close>myvwap?color.green:color.red
av=myvwap
showBcol = input(false, type=input.bool, title="Show barcolors")
showPrevVWAP = input(false, type=input.bool, title="Show previous VWAP close")
prevwap = 0.0
prevwap := iff(newSession, myvwap[1], prevwap[1])
nprevwap= normalize(prevwap, 0, 1)
l1= input(20, minval=1)
src2 = close
mult1 = input(2.0, minval=0.001, maxval=50, title="StdDev")
basis1 = sma(src2, l1)
dev1 = mult1 * stdev(src2, l1)
upper1 = basis1 + dev1
lower1 = basis1 - dev1
bbr1 = (src - lower1)/(upper1 - lower1)
az = plot(bbr, "Δ(OBV-PVT)", color.rgb(0,153,0,0), style=plot.style_columns)
bz = plot(bbr1, "BB%B", color.rgb(0,125,125,50), style=plot.style_columns)
fill(az, bz, color=color.white)
deltabbr = bbr1 - bbr
oneline = hline(1)
twoline = hline(1.2)
zline = hline(0)
xx = input(.3)
yy = input(.7)
zz = input(-1)
xxx = hline(xx)
yyy = hline(yy)
zzz = hline(zz)
fill(oneline, twoline, color=color.red, title="Sell Zone")
fill(yyy, oneline, color=color.orange, title="Slightly Overbought")
fill(yyy, zline, color=color.white, title="DO NOTHING ZONE")
fill(zzz, zline, color=color.green, title="GO LONG ZONE")
l20 = crossover(deltabbr, 0)
l30 = crossunder(deltabbr, 0)
l40 = crossover(o5, 0)
l50 = crossunder(o5, 0)
z1 = bbr1 >= 1
z2 = bbr1 < 1 and bbr1 >= .7
z3 = bbr1 < .7 and bbr1 >= .3
z4 = bbr1 < .3 and bbr1 >= 0
z5 = bbr1 < 0
a1 = bbr >= 1
a2 = bbr < 1 and bbr >= .7
a4 = bbr < .3 and bbr >= 0
a5 = bbr < 0
b4 = deltabbr < .3 and deltabbr >= 0
b5 = deltabbr < 0
c4 = o5 < .3 and o5 >= 0
c5 = o5 < 0
b1 = deltabbr >= 1
b2 = deltabbr < 1 and o5 >= .7
c1 = o5 >= 1
c2 = o5 < 1 and o5 >= .7
///
n = input(16,"Period")
H = highest(hl2,n)
L = lowest(hl2,n)
hi = H[1]
lo = L[1]
up = high>hi
dn = low<lo
lowerbbh = lowest(10)[1]
bbh = (low == open ? open < lowerbbh ? open < close ? close > ((high[1] - low[1]) / 2) + low[1] :na : na : na)
plot(normalize(av,-1,1), linewidth=2, title="Trendline", color=color.yellow)
long5 = close < av and av[0] > av[1]
sell5 = close > av
cancel = false
if open >= high[1]
cancel = true
long = (long5 or z5 or a5) and (icreturn or bbh or up)
sell = ((z1 or a1) or (l40 and l20)) and (icreturn or dn) and (c1 or b1)
short = ((z1 or z2 or a1 or sell5) and (l40 or l20)) and icreturn
buy= (z5 or z4 or a5 or long5) and (icreturn or dn)
plotshape(long and not sell ? -0.5 : na, title="Long", location=location.absolute, style=shape.circle, size=size.tiny, color=color.green, transp=0)
plotshape(short and not sell? 1 : na, title="Short", location=location.absolute, style=shape.circle, size=size.tiny, color=color.red, transp=0)
if (inDateRange)
strategy.entry("long", true, when = long )
if (inDateRange) and (strategy.position_size > 0)
strategy.close_all(when = sell or cancel)
if (inDateRange)
strategy.entry("short", false, when = short )
if (inDateRange) and (strategy.position_size < 0)
strategy.close_all(when = buy) |
Repaint Demonstration in Security Function Call using Higher TF | https://www.tradingview.com/script/tOxtvIxI-Repaint-Demonstration-in-Security-Function-Call-using-Higher-TF/ | akrit8888 | https://www.tradingview.com/u/akrit8888/ | 11 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © akrit8888
// @version=4
// "This Script is for demonstration of repaint by using security function to lookup the Future"
// "And should NOT by any means be use in as a real trading strategy."
strategy("Repaint Demonstration in Security Function Call using Higher TF", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100)
bigTF = input("W", "Future Sight: ", input.resolution)
bigTFClose = security(syminfo.tickerid, bigTF, close)
buy = crossover(close, bigTFClose)
sell = crossover(bigTFClose, close)
plot(close)
plot(bigTFClose)
strategy.entry("L", true, when = buy)
strategy.close("L", when = sell) |
Forex Fractal EMA Scalper | https://www.tradingview.com/script/pgsJGhIg-Forex-Fractal-EMA-Scalper/ | exlux99 | https://www.tradingview.com/u/exlux99/ | 765 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © exlux99
//@version=5
strategy("Forex Fractal EMA Scalper", overlay=true)
// Define "n" as the number of periods and keep a minimum value of 2 for error handling.
n = input.int(title="Period Fractals", defval=2, minval=2, group="Optimization Parameters")
src = input(hl2, title="Source for EMA's", group="Optimization Parameters")
len1 = input.int(10, minval=1, title="Length EMA 1", group="Optimization Parameters")
out1 = ta.ema(src, len1)
len2 = input.int(20, minval=1, title="Length EMA 2", group="Optimization Parameters")
out2 = ta.ema(src, len2)
len3 = input.int(100, minval=1, title="Length EMA 3", group="Optimization Parameters")
out3 = ta.ema(src, len3)
// UpFractal
bool upflagDownFrontier = true
bool upflagUpFrontier0 = true
bool upflagUpFrontier1 = true
bool upflagUpFrontier2 = true
bool upflagUpFrontier3 = true
bool upflagUpFrontier4 = true
for i = 1 to n
upflagDownFrontier := upflagDownFrontier and (high[n-i] < high[n])
upflagUpFrontier0 := upflagUpFrontier0 and (high[n+i] < high[n])
upflagUpFrontier1 := upflagUpFrontier1 and (high[n+1] <= high[n] and high[n+i + 1] < high[n])
upflagUpFrontier2 := upflagUpFrontier2 and (high[n+1] <= high[n] and high[n+2] <= high[n] and high[n+i + 2] < high[n])
upflagUpFrontier3 := upflagUpFrontier3 and (high[n+1] <= high[n] and high[n+2] <= high[n] and high[n+3] <= high[n] and high[n+i + 3] < high[n])
upflagUpFrontier4 := upflagUpFrontier4 and (high[n+1] <= high[n] and high[n+2] <= high[n] and high[n+3] <= high[n] and high[n+4] <= high[n] and high[n+i + 4] < high[n])
flagUpFrontier = upflagUpFrontier0 or upflagUpFrontier1 or upflagUpFrontier2 or upflagUpFrontier3 or upflagUpFrontier4
upFractal = (upflagDownFrontier and flagUpFrontier)
// downFractal
bool downflagDownFrontier = true
bool downflagUpFrontier0 = true
bool downflagUpFrontier1 = true
bool downflagUpFrontier2 = true
bool downflagUpFrontier3 = true
bool downflagUpFrontier4 = true
for i = 1 to n
downflagDownFrontier := downflagDownFrontier and (low[n-i] > low[n])
downflagUpFrontier0 := downflagUpFrontier0 and (low[n+i] > low[n])
downflagUpFrontier1 := downflagUpFrontier1 and (low[n+1] >= low[n] and low[n+i + 1] > low[n])
downflagUpFrontier2 := downflagUpFrontier2 and (low[n+1] >= low[n] and low[n+2] >= low[n] and low[n+i + 2] > low[n])
downflagUpFrontier3 := downflagUpFrontier3 and (low[n+1] >= low[n] and low[n+2] >= low[n] and low[n+3] >= low[n] and low[n+i + 3] > low[n])
downflagUpFrontier4 := downflagUpFrontier4 and (low[n+1] >= low[n] and low[n+2] >= low[n] and low[n+3] >= low[n] and low[n+4] >= low[n] and low[n+i + 4] > low[n])
flagDownFrontier = downflagUpFrontier0 or downflagUpFrontier1 or downflagUpFrontier2 or downflagUpFrontier3 or downflagUpFrontier4
downFractal = (downflagDownFrontier and flagDownFrontier)
// plotshape(downFractal, style=shape.triangledown, location=location.belowbar, offset=-n, color=#F44336, size = size.small)
// plotshape(upFractal, style=shape.triangleup, location=location.abovebar, offset=-n, color=#009688, size = size.small)
long= out1 > out2 and out2>out3 and upFractal
short= out1 < out2 and out2<out3 and downFractal
strategy.entry("long",strategy.long,when= short)
strategy.entry("short",strategy.short,when=long)
tp=input(25, title="TP in PIPS", group="Risk Management")*10
sl=input(25, title="SL in PIPS", group="Risk Management")*10
strategy.exit("X_long", "long", profit=tp, loss=sl )
strategy.exit("x_short", "short",profit=tp, loss=sl )
|
Scalping Trading System bot Crypto and Stocks | https://www.tradingview.com/script/YotdMm0M-Scalping-Trading-System-bot-Crypto-and-Stocks/ | exlux99 | https://www.tradingview.com/u/exlux99/ | 1,946 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © exlux99
//@version=5
strategy(title="Scalping Trading System Crypto and Stocks", overlay=true)
src = input(low, title="Source")
//sma and ema
len = input.int(25, minval=1, title="Length SMA" , group="Moving Averages")
len2 = input.int(200, minval=1, title="Length EMA", group="Moving Averages")
out = ta.sma(src, len)
out2 = ta.ema(src, len2)
//keltner
lengthk = input.int(10, minval=1, title="Length Keltner Channel",group="Keltner")
mult = input(2.0, "Multiplier",group="Keltner")
BandsStyle = input.string("Average True Range", options = ["Average True Range", "True Range", "Range"], title="Bands Style",group="Keltner")
atrlength = input(14, "ATR Length",group="Keltner")
ma = ta.sma(src, lengthk)
rangema = BandsStyle == "True Range" ? ta.tr(true) : BandsStyle == "Average True Range" ? ta.atr(atrlength) : ta.rma(high - low, lengthk)
upper = ma + rangema * mult
lower = ma - rangema * mult
//stoch
periodK = input.int(10, title="%K Length", minval=1,group="Stochastic")
smoothK = input.int(1, title="%K Smoothing", minval=1,group="Stochastic")
periodD = input.int(1, title="%D Smoothing", minval=1,group="Stochastic")
k = ta.sma(ta.stoch(close, high, low, periodK), smoothK)
d = ta.sma(k, periodD)
//macd 1
fast_length = input(title="Fast Length MACD", defval=4,group="MACD Fast")
slow_length = input(title="Slow Length MACD", defval=34,group="MACD Fast")
signal_length = input.int(title="Signal Smoothing MACD", minval = 1, maxval = 50, defval = 5,group="MACD Fast")
sma_source = input.string(title="Oscillator MA Type MACD", defval="EMA", options=["SMA", "EMA"],group="MACD Fast")
sma_signal = input.string(title="Signal Line MA Type MACD", defval="EMA", options=["SMA", "EMA"],group="MACD Fast")
fast_ma = sma_source == "SMA" ? ta.sma(src, fast_length) : ta.ema(src, fast_length)
slow_ma = sma_source == "SMA" ? ta.sma(src, slow_length) : ta.ema(src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)
hist = macd - signal
long= close > out and close < upper and close > lower and hist < 0 and k < 50 and close > out2
short= close < out and close < upper and close > lower and hist > 0 and k > 50 and close < out2
strategy.entry("long",strategy.long,when= long)
strategy.entry("short",strategy.short,when=short)
|
Auto Fib Golden Pocket Band - Strategy with Buy Signals | https://www.tradingview.com/script/zXerPHbi-Auto-Fib-Golden-Pocket-Band-Strategy-with-Buy-Signals/ | imal_max | https://www.tradingview.com/u/imal_max/ | 396 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © imal_max reeee
//@version=5
strategy(title="Auto Fib Golden Pocket Band - Autofib Moving Average", shorttitle="Auto Fib Golden Pocket Band", overlay=true, pyramiding=15, process_orders_on_close=true, calc_on_every_tick=true, initial_capital=10000, currency = currency.USD, default_qty_value=100, default_qty_type=strategy.percent_of_equity, commission_type=strategy.commission.percent, commission_value=0.05, slippage=2)
//indicator("Auto Fib Golden Pocket Band - Autofib Moving Average", overlay=true, shorttitle="Auto Fib Golden Pocket Band", timeframe""")
// Fibs
// auto fib ranges
// fib band Strong Trend
enable_StrongBand_Bull = input.bool(title='enable Upper Bullish Band . . . Fib Level', defval=true, group='══════ Strong Trend Levels ══════', inline="0")
select_StrongBand_Fib_Bull = input.float(0.236, title=" ", options=[-0.272, 0, 0.236, 0.382, 0.5, 0.618, 0.702, 0.71, 0.786, 0.83, 0.886, 1, 1.272], group='══════ Strong Trend Levels ══════', inline="0")
enable_StrongBand_Bear = input.bool(title='enable Lower Bearish Band . . . Fib Level', defval=false, group='══════ Strong Trend Levels ══════', inline="1")
select_StrongBand_Fib_Bear = input.float(0.382, '', options=[-0.272, 0, 0.236, 0.382, 0.5, 0.618, 0.702, 0.71, 0.786, 0.83, 0.886, 1, 1.272], group='══════ Strong Trend Levels ══════', inline="1")
StrongBand_Lookback = input.int(title='Pivot Look Back', minval=1, defval=400, group='══════ Strong Trend Levels ══════', inline="2")
StrongBand_EmaLen = input.int(title='Fib EMA Length', minval=1, defval=120, group='══════ Strong Trend Levels ══════', inline="2")
// fib middle Band regular Trend
enable_MiddleBand_Bull = input.bool(title='enable Middle Bullish Band . . . Fib Level', defval=true, group='══════ Regular Trend Levels ══════', inline="0")
select_MiddleBand_Fib_Bull = input.float(0.618, '', options=[-0.272, 0, 0.236, 0.382, 0.5, 0.6, 0.618, 0.702, 0.71, 0.786, 0.83, 0.886, 1, 1.272], group='══════ Regular Trend Levels ══════', inline="0")
enable_MiddleBand_Bear = input.bool(title='enable Middle Bearish Band . . . Fib Level', defval=true, group='══════ Regular Trend Levels ══════', inline="1")
select_MiddleBand_Fib_Bear = input.float(0.382, '', options=[-0.272, 0, 0.236, 0.382, 0.5, 0.618, 0.702, 0.71, 0.786, 0.83, 0.886, 1, 1.272], group='══════ Regular Trend Levels ══════', inline="1")
MiddleBand_Lookback = input.int(title='Pivot Look Back', minval=1, defval=900, group='══════ Regular Trend Levels ══════', inline="2")
MiddleBand_EmaLen = input.int(title='Fib EMA Length', minval=1, defval=400, group='══════ Regular Trend Levels ══════', inline="2")
// fib Sideways Band
enable_SidewaysBand_Bull = input.bool(title='enable Lower Bullish Band . . . Fib Level', defval=true, group='══════ Sideways Trend Levels ══════', inline="0")
select_SidewaysBand_Fib_Bull = input.float(0.6, '', options=[-0.272, 0, 0.236, 0.382, 0.5, 0.6, 0.618, 0.702, 0.71, 0.786, 0.83, 0.886, 1, 1.272], group='══════ Sideways Trend Levels ══════', inline="0")
enable_SidewaysBand_Bear = input.bool(title='enable Upper Bearish Band . . . Fib Level', defval=true, group='══════ Sideways Trend Levels ══════', inline="1")
select_SidewaysBand_Fib_Bear = input.float(0.5, '', options=[-0.272, 0, 0.236, 0.382, 0.5, 0.618, 0.702, 0.71, 0.786, 0.83, 0.886, 1, 1.272], group='══════ Sideways Trend Levels ══════', inline="1")
SidewaysBand_Lookback = input.int(title='Pivot Look Back', minval=1, defval=4000, group='══════ Sideways Trend Levels ══════', inline="2")
SidewaysBand_EmaLen = input.int(title='Fib EMA Length', minval=1, defval=150, group='══════ Sideways Trend Levels ══════', inline="2")
// Strong Band
isBelow_StrongBand_Bull = true
isBelow_StrongBand_Bear = true
StrongBand_Price_of_Low = float(na)
StrongBand_Price_of_High = float(na)
StrongBand_Bear_Fib_Price = float(na)
StrongBand_Bull_Fib_Price = float(na)
/// Middle Band
isBelow_MiddleBand_Bull = true
isBelow_MiddleBand_Bear = true
MiddleBand_Price_of_Low = float(na)
MiddleBand_Price_of_High = float(na)
MiddleBand_Bear_Fib_Price = float(na)
MiddleBand_Bull_Fib_Price = float(na)
// Sideways Band
isBelow_SidewaysBand_Bull = true
isBelow_SidewaysBand_Bear = true
SidewaysBand_Price_of_Low = float(na)
SidewaysBand_Price_of_High = float(na)
SidewaysBand_Bear_Fib_Price = float(na)
SidewaysBand_Bull_Fib_Price = float(na)
// get Fib Levels
if enable_StrongBand_Bull
StrongBand_Price_of_High := ta.highest(high, StrongBand_Lookback)
StrongBand_Price_of_Low := ta.lowest(low, StrongBand_Lookback)
StrongBand_Bull_Fib_Price := (StrongBand_Price_of_High - StrongBand_Price_of_Low) * (1 - select_StrongBand_Fib_Bull) + StrongBand_Price_of_Low //+ fibbullHighDivi
isBelow_StrongBand_Bull := StrongBand_Bull_Fib_Price > ta.lowest(low, 2) or not enable_StrongBand_Bull
if enable_StrongBand_Bear
StrongBand_Price_of_High := ta.highest(high, StrongBand_Lookback)
StrongBand_Price_of_Low := ta.lowest(low, StrongBand_Lookback)
StrongBand_Bear_Fib_Price := (StrongBand_Price_of_High - StrongBand_Price_of_Low) * (1 - select_StrongBand_Fib_Bear) + StrongBand_Price_of_Low// + fibbullLowhDivi
isBelow_StrongBand_Bear := StrongBand_Bear_Fib_Price < ta.highest(low, 2) or not enable_StrongBand_Bear
if enable_MiddleBand_Bull
MiddleBand_Price_of_High := ta.highest(high, MiddleBand_Lookback)
MiddleBand_Price_of_Low := ta.lowest(low, MiddleBand_Lookback)
MiddleBand_Bull_Fib_Price := (MiddleBand_Price_of_High - MiddleBand_Price_of_Low) * (1 - select_MiddleBand_Fib_Bull) + MiddleBand_Price_of_Low //+ fibbullHighDivi
isBelow_MiddleBand_Bull := MiddleBand_Bull_Fib_Price > ta.lowest(low, 2) or not enable_MiddleBand_Bull
if enable_MiddleBand_Bear
MiddleBand_Price_of_High := ta.highest(high, MiddleBand_Lookback)
MiddleBand_Price_of_Low := ta.lowest(low, MiddleBand_Lookback)
MiddleBand_Bear_Fib_Price := (MiddleBand_Price_of_High - MiddleBand_Price_of_Low) * (1 - select_MiddleBand_Fib_Bear) + MiddleBand_Price_of_Low// + fibbullLowhDivi
isBelow_MiddleBand_Bear := MiddleBand_Bear_Fib_Price < ta.highest(low, 2) or not enable_MiddleBand_Bear
if enable_SidewaysBand_Bull
SidewaysBand_Price_of_High := ta.highest(high, SidewaysBand_Lookback)
SidewaysBand_Price_of_Low := ta.lowest(low, SidewaysBand_Lookback)
SidewaysBand_Bull_Fib_Price := (SidewaysBand_Price_of_High - SidewaysBand_Price_of_Low) * (1 - select_SidewaysBand_Fib_Bull) + SidewaysBand_Price_of_Low //+ fibbullHighDivi
isBelow_SidewaysBand_Bull := SidewaysBand_Bull_Fib_Price > ta.lowest(low, 2) or not enable_SidewaysBand_Bull
if enable_SidewaysBand_Bear
SidewaysBand_Price_of_High := ta.highest(high, SidewaysBand_Lookback)
SidewaysBand_Price_of_Low := ta.lowest(low, SidewaysBand_Lookback)
SidewaysBand_Bear_Fib_Price := (SidewaysBand_Price_of_High - SidewaysBand_Price_of_Low) * (1 - select_SidewaysBand_Fib_Bear) + SidewaysBand_Price_of_Low// + fibbullLowhDivi
isBelow_SidewaysBand_Bear := SidewaysBand_Bear_Fib_Price < ta.highest(low, 2) or not enable_SidewaysBand_Bear
// Fib EMAs
// fib ema Strong Trend
StrongBand_current_Trend_EMA = float(na)
StrongBand_Bull_EMA = ta.ema(StrongBand_Bull_Fib_Price, StrongBand_EmaLen)
StrongBand_Bear_EMA = ta.ema(StrongBand_Bear_Fib_Price, StrongBand_EmaLen)
StrongBand_Ema_in_Uptrend = ta.change(StrongBand_Bull_EMA) > 0 or ta.change(StrongBand_Bear_EMA) > 0
StrongBand_Ema_Sideways = ta.change(StrongBand_Bull_EMA) == 0 or ta.change(StrongBand_Bear_EMA) == 0
StrongBand_Ema_in_Downtrend = ta.change(StrongBand_Bull_EMA) < 0 or ta.change(StrongBand_Bear_EMA) < 0
if StrongBand_Ema_in_Uptrend or StrongBand_Ema_Sideways
StrongBand_current_Trend_EMA := StrongBand_Bull_EMA
if StrongBand_Ema_in_Downtrend
StrongBand_current_Trend_EMA := StrongBand_Bear_EMA
// fib ema Normal Trend
MiddleBand_current_Trend_EMA = float(na)
MiddleBand_Bull_EMA = ta.ema(MiddleBand_Bull_Fib_Price, MiddleBand_EmaLen)
MiddleBand_Bear_EMA = ta.ema(MiddleBand_Bear_Fib_Price, MiddleBand_EmaLen)
MiddleBand_Ema_in_Uptrend = ta.change(MiddleBand_Bull_EMA) > 0 or ta.change(MiddleBand_Bear_EMA) > 0
MiddleBand_Ema_Sideways = ta.change(MiddleBand_Bull_EMA) == 0 or ta.change(MiddleBand_Bear_EMA) == 0
MiddleBand_Ema_in_Downtrend = ta.change(MiddleBand_Bull_EMA) < 0 or ta.change(MiddleBand_Bear_EMA) < 0
if MiddleBand_Ema_in_Uptrend or MiddleBand_Ema_Sideways
MiddleBand_current_Trend_EMA := MiddleBand_Bull_EMA
if MiddleBand_Ema_in_Downtrend
MiddleBand_current_Trend_EMA := MiddleBand_Bear_EMA
// fib ema Sideways Trend
SidewaysBand_current_Trend_EMA = float(na)
SidewaysBand_Bull_EMA = ta.ema(SidewaysBand_Bull_Fib_Price, SidewaysBand_EmaLen)
SidewaysBand_Bear_EMA = ta.ema(SidewaysBand_Bear_Fib_Price, SidewaysBand_EmaLen)
SidewaysBand_Ema_in_Uptrend = ta.change(SidewaysBand_Bull_EMA) > 0 or ta.change(SidewaysBand_Bear_EMA) > 0
SidewaysBand_Ema_Sideways = ta.change(SidewaysBand_Bull_EMA) == 0 or ta.change(SidewaysBand_Bear_EMA) == 0
SidewaysBand_Ema_in_Downtrend = ta.change(SidewaysBand_Bull_EMA) < 0 or ta.change(SidewaysBand_Bear_EMA) < 0
if SidewaysBand_Ema_in_Uptrend or SidewaysBand_Ema_Sideways
SidewaysBand_current_Trend_EMA := SidewaysBand_Bull_EMA
if SidewaysBand_Ema_in_Downtrend
SidewaysBand_current_Trend_EMA := SidewaysBand_Bear_EMA
// trend states and colors
all_Fib_Emas_Trending = StrongBand_Ema_in_Uptrend and MiddleBand_Ema_in_Uptrend and SidewaysBand_Ema_in_Uptrend
all_Fib_Emas_Downtrend = MiddleBand_Ema_in_Downtrend and StrongBand_Ema_in_Downtrend and SidewaysBand_Ema_in_Downtrend
all_Fib_Emas_Sideways = MiddleBand_Ema_Sideways and StrongBand_Ema_Sideways and SidewaysBand_Ema_Sideways
all_Fib_Emas_Trend_or_Sideways = (MiddleBand_Ema_Sideways or StrongBand_Ema_Sideways or SidewaysBand_Ema_Sideways) or (StrongBand_Ema_in_Uptrend or MiddleBand_Ema_in_Uptrend or SidewaysBand_Ema_in_Uptrend) and not (MiddleBand_Ema_in_Downtrend or StrongBand_Ema_in_Downtrend or SidewaysBand_Ema_in_Downtrend)
allFibsUpAndDownTrend = (MiddleBand_Ema_in_Downtrend or StrongBand_Ema_in_Downtrend or SidewaysBand_Ema_in_Downtrend) and (MiddleBand_Ema_Sideways or SidewaysBand_Ema_Sideways or StrongBand_Ema_Sideways or StrongBand_Ema_in_Uptrend or MiddleBand_Ema_in_Uptrend or SidewaysBand_Ema_in_Uptrend)
Middle_and_Sideways_Emas_Trending = MiddleBand_Ema_in_Uptrend and SidewaysBand_Ema_in_Uptrend
Middle_and_Sideways_Fib_Emas_Downtrend = MiddleBand_Ema_in_Downtrend and SidewaysBand_Ema_in_Downtrend
Middle_and_Sideways_Fib_Emas_Sideways = MiddleBand_Ema_Sideways and SidewaysBand_Ema_Sideways
Middle_and_Sideways_Fib_Emas_Trend_or_Sideways = (MiddleBand_Ema_Sideways or SidewaysBand_Ema_Sideways) or (MiddleBand_Ema_in_Uptrend or SidewaysBand_Ema_in_Uptrend) and not (MiddleBand_Ema_in_Downtrend or SidewaysBand_Ema_in_Downtrend)
Middle_and_Sideways_UpAndDownTrend = (MiddleBand_Ema_in_Downtrend or SidewaysBand_Ema_in_Downtrend) and (MiddleBand_Ema_Sideways or SidewaysBand_Ema_Sideways or MiddleBand_Ema_in_Uptrend or SidewaysBand_Ema_in_Uptrend)
UpperBand_Ema_Color = all_Fib_Emas_Trend_or_Sideways ? color.lime : all_Fib_Emas_Downtrend ? color.red : allFibsUpAndDownTrend ? color.white : na
MiddleBand_Ema_Color = Middle_and_Sideways_Fib_Emas_Trend_or_Sideways ? color.lime : Middle_and_Sideways_Fib_Emas_Downtrend ? color.red : Middle_and_Sideways_UpAndDownTrend ? color.white : na
SidewaysBand_Ema_Color = SidewaysBand_Ema_in_Uptrend ? color.lime : SidewaysBand_Ema_in_Downtrend ? color.red : (SidewaysBand_Ema_in_Downtrend and (SidewaysBand_Ema_Sideways or SidewaysBand_Ema_in_Uptrend)) ? color.white : na
plotStrong_Ema = plot(StrongBand_current_Trend_EMA, color=UpperBand_Ema_Color, title="Strong Trend")
plotMiddle_Ema = plot(MiddleBand_current_Trend_EMA, color=MiddleBand_Ema_Color, title="Normal Trend")
plotSideways_Ema = plot(SidewaysBand_current_Trend_EMA, color=SidewaysBand_Ema_Color, title="Sidewaysd")
Strong_Middle_fillcolor = color.new(color.green, 90)
if all_Fib_Emas_Trend_or_Sideways
Strong_Middle_fillcolor := color.new(color.green, 90)
if all_Fib_Emas_Downtrend
Strong_Middle_fillcolor := color.new(color.red, 90)
if allFibsUpAndDownTrend
Strong_Middle_fillcolor := color.new(color.white, 90)
Middle_Sideways_fillcolor = color.new(color.green, 90)
if Middle_and_Sideways_Fib_Emas_Trend_or_Sideways
Middle_Sideways_fillcolor := color.new(color.green, 90)
if Middle_and_Sideways_Fib_Emas_Downtrend
Middle_Sideways_fillcolor := color.new(color.red, 90)
if Middle_and_Sideways_UpAndDownTrend
Middle_Sideways_fillcolor := color.new(color.white, 90)
fill(plotStrong_Ema, plotMiddle_Ema, color=Strong_Middle_fillcolor, title="fib band background")
fill(plotMiddle_Ema, plotSideways_Ema, color=Middle_Sideways_fillcolor, title="fib band background")
// buy condition
StrongBand_Price_was_below_Bull_level = ta.lowest(low, 1) < StrongBand_current_Trend_EMA
StrongBand_Price_is_above_Bull_level = close > StrongBand_current_Trend_EMA
StronBand_Price_Average_above_Bull_Level = ta.ema(low, 10) > StrongBand_current_Trend_EMA
StrongBand_Low_isnt_toLow = (ta.lowest(StrongBand_current_Trend_EMA, 15) - ta.lowest(low, 15)) < close * 0.005
StronBand_Trend_isnt_fresh = ta.barssince(StrongBand_Ema_in_Downtrend) > 50 or na(ta.barssince(StrongBand_Ema_in_Downtrend))
MiddleBand_Price_was_below_Bull_level = ta.lowest(low, 1) < MiddleBand_current_Trend_EMA
MiddleBand_Price_is_above_Bull_level = close > MiddleBand_current_Trend_EMA
MiddleBand_Price_Average_above_Bull_Level = ta.ema(close, 20) > MiddleBand_current_Trend_EMA
MiddleBand_Low_isnt_toLow = (ta.lowest(MiddleBand_current_Trend_EMA, 10) - ta.lowest(low, 10)) < close * 0.0065
MiddleBand_Trend_isnt_fresh = ta.barssince(MiddleBand_Ema_in_Downtrend) > 50 or na(ta.barssince(MiddleBand_Ema_in_Downtrend))
SidewaysBand_Price_was_below_Bull_level = ta.lowest(low, 1) < SidewaysBand_current_Trend_EMA
SidewaysBand_Price_is_above_Bull_level = close > SidewaysBand_current_Trend_EMA
SidewaysBand_Price_Average_above_Bull_Level = ta.ema(low, 80) > SidewaysBand_current_Trend_EMA
SidewaysBand_Low_isnt_toLow = (ta.lowest(SidewaysBand_current_Trend_EMA, 150) - ta.lowest(low, 150)) < close * 0.0065
SidewaysBand_Trend_isnt_fresh = ta.barssince(SidewaysBand_Ema_in_Downtrend) > 50 or na(ta.barssince(SidewaysBand_Ema_in_Downtrend))
StrongBand_Buy_Alert = StronBand_Trend_isnt_fresh and StrongBand_Low_isnt_toLow and StronBand_Price_Average_above_Bull_Level and StrongBand_Price_was_below_Bull_level and StrongBand_Price_is_above_Bull_level and all_Fib_Emas_Trend_or_Sideways
MiddleBand_Buy_Alert = MiddleBand_Trend_isnt_fresh and MiddleBand_Low_isnt_toLow and MiddleBand_Price_Average_above_Bull_Level and MiddleBand_Price_was_below_Bull_level and MiddleBand_Price_is_above_Bull_level and Middle_and_Sideways_Fib_Emas_Trend_or_Sideways
SidewaysBand_Buy_Alert = SidewaysBand_Trend_isnt_fresh and SidewaysBand_Low_isnt_toLow and SidewaysBand_Price_Average_above_Bull_Level and SidewaysBand_Price_was_below_Bull_level and SidewaysBand_Price_is_above_Bull_level and (SidewaysBand_Ema_Sideways or SidewaysBand_Ema_in_Uptrend and ( not SidewaysBand_Ema_in_Downtrend))
// Sell condition
StrongBand_Price_was_above_Bear_level = ta.highest(high, 1) > StrongBand_current_Trend_EMA
StrongBand_Price_is_below_Bear_level = close < StrongBand_current_Trend_EMA
StronBand_Price_Average_below_Bear_Level = ta.sma(high, 10) < StrongBand_current_Trend_EMA
StrongBand_High_isnt_to_High = (ta.highest(high, 15) - ta.highest(StrongBand_current_Trend_EMA, 15)) < close * 0.005
StrongBand_Bear_Trend_isnt_fresh = ta.barssince(StrongBand_Ema_in_Uptrend) > 50
MiddleBand_Price_was_above_Bear_level = ta.highest(high, 1) > MiddleBand_current_Trend_EMA
MiddleBand_Price_is_below_Bear_level = close < MiddleBand_current_Trend_EMA
MiddleBand_Price_Average_below_Bear_Level = ta.sma(high, 9) < MiddleBand_current_Trend_EMA
MiddleBand_High_isnt_to_High = (ta.highest(high, 10) - ta.highest(MiddleBand_current_Trend_EMA, 10)) < close * 0.0065
MiddleBand_Bear_Trend_isnt_fresh = ta.barssince(MiddleBand_Ema_in_Uptrend) > 50
SidewaysBand_Price_was_above_Bear_level = ta.highest(high, 1) > SidewaysBand_current_Trend_EMA
SidewaysBand_Price_is_below_Bear_level = close < SidewaysBand_current_Trend_EMA
SidewaysBand_Price_Average_below_Bear_Level = ta.sma(high, 20) < SidewaysBand_current_Trend_EMA
SidewaysBand_High_isnt_to_High = (ta.highest(high, 20) - ta.highest(SidewaysBand_current_Trend_EMA, 15)) < close * 0.0065
SidewaysBand_Bear_Trend_isnt_fresh = ta.barssince(SidewaysBand_Ema_in_Uptrend) > 50
StrongBand_Sell_Alert = StronBand_Price_Average_below_Bear_Level and StrongBand_High_isnt_to_High and StrongBand_Bear_Trend_isnt_fresh and StrongBand_Price_was_above_Bear_level and StrongBand_Price_is_below_Bear_level and all_Fib_Emas_Downtrend and not all_Fib_Emas_Trend_or_Sideways
MiddleBand_Sell_Alert = MiddleBand_Price_Average_below_Bear_Level and MiddleBand_High_isnt_to_High and MiddleBand_Bear_Trend_isnt_fresh and MiddleBand_Price_was_above_Bear_level and MiddleBand_Price_is_below_Bear_level and Middle_and_Sideways_Fib_Emas_Downtrend and not Middle_and_Sideways_Fib_Emas_Trend_or_Sideways
SidewaysBand_Sell_Alert = SidewaysBand_Price_Average_below_Bear_Level and SidewaysBand_High_isnt_to_High and SidewaysBand_Bear_Trend_isnt_fresh and SidewaysBand_Price_was_above_Bear_level and SidewaysBand_Price_is_below_Bear_level and SidewaysBand_Ema_in_Downtrend and not (SidewaysBand_Ema_Sideways or SidewaysBand_Ema_in_Uptrend and ( not SidewaysBand_Ema_in_Downtrend))
// Backtester
////////////////// Stop Loss
// Stop loss
enableSL = input.bool(true, title='enable Stop Loss', group='══════════ Stop Loss Settings ══════════')
whichSL = input.string(defval='low/high as SL', title='SL based on static % or based on the low/high', options=['low/high as SL', 'static % as SL'], group='══════════ Stop Loss Settings ══════════')
whichOffset = input.string(defval='% as offset', title='choose offset from the low/high', options=['$ as offset', '% as offset'], group='Stop Loss at the low/high')
lowPBuffer = input.float(1.4, title='SL Offset from the Low/high in %', group='Stop Loss at the low/high') / 100
lowDBuffer = input.float(100, title='SL Offset from the Low/high in $', group='Stop Loss at the low/high')
SlLowLookback = input.int(title='SL lookback for Low/high', defval=5, minval=1, maxval=50, group='Stop Loss at the low/high')
longSlLow = float(na)
shortSlLow = float(na)
if whichOffset == "% as offset" and whichSL == "low/high as SL" and enableSL
longSlLow := ta.lowest(low, SlLowLookback) * (1 - lowPBuffer)
shortSlLow := ta.highest(high, SlLowLookback) * (1 + lowPBuffer)
if whichOffset == "$ as offset" and whichSL == "low/high as SL" and enableSL
longSlLow := ta.lowest(low, SlLowLookback) - lowDBuffer
shortSlLow := ta.highest(high, SlLowLookback) + lowDBuffer
//plot(shortSlLow, title="stoploss", color=color.new(#00bcd4, 0))
// long settings - 🔥 uncomment the 6 lines below to disable the alerts and enable the backtester
longStopLoss = input.float(0.5, title='Long Stop Loss in %', group='static % Stop Loss', inline='Input 1') / 100
// short settings - 🔥 uncomment the 6 lines below to disable the alerts and enable the backtester
shortStopLoss = input.float(0.5, title='Short Stop Loss in %', group='static % Stop Loss', inline='Input 1') / 100
/////// Take profit
longTakeProfit1 = input.float(4, title='Long Take Profit in %', group='Take Profit', inline='Input 1') / 100
/////// Take profit
shortTakeProfit1 = input.float(1.6, title='Short Take Profit in %', group='Take Profit', inline='Input 1') / 100
////////////////// SL TP END
/////////////////// alerts
selectalertFreq = input.string(defval='once per bar close', title='Alert Options', options=['once per bar', 'once per bar close', 'all'], group='═══════════ alert settings ═══════════')
BuyAlertMessage = input.string(defval="Bullish Divergence detected, put your SL @", title='Buy Alert Message', group='═══════════ alert settings ═══════════')
enableSlMessage = input.bool(true, title='enable Stop Loss Value at the end of "buy Alert message"', group='═══════════ alert settings ═══════════')
AfterSLMessage = input.string(defval="", title='Buy Alert message after SL Value', group='═══════════ alert settings ═══════════')
////////////////// Backtester
// 🔥 uncomment the all lines below for the backtester and revert for alerts
shortTrading = enable_MiddleBand_Bear or enable_StrongBand_Bear or enable_SidewaysBand_Bear
longTrading = enable_StrongBand_Bull or enable_MiddleBand_Bull or enable_SidewaysBand_Bull
longTP1 = strategy.position_size > 0 ? strategy.position_avg_price * (1 + longTakeProfit1) : strategy.position_size < 0 ? strategy.position_avg_price * (1 - longTakeProfit1) : na
longSL = strategy.position_size > 0 ? strategy.position_avg_price * (1 - longStopLoss) : strategy.position_size < 0 ? strategy.position_avg_price * (1 + longStopLoss) : na
shortTP = strategy.position_size > 0 ? strategy.position_avg_price * (1 + shortTakeProfit1) : strategy.position_size < 0 ? strategy.position_avg_price * (1 - shortTakeProfit1) : na
shortSL = strategy.position_size > 0 ? strategy.position_avg_price * (1 - shortStopLoss) : strategy.position_size < 0 ? strategy.position_avg_price * (1 + shortStopLoss) : na
strategy.risk.allow_entry_in(longTrading == true and shortTrading == true ? strategy.direction.all : longTrading == true ? strategy.direction.long : shortTrading == true ? strategy.direction.short : na)
strategy.entry('Bull', strategy.long, comment='Upper Band Long', when=StrongBand_Buy_Alert)
strategy.entry('Bull', strategy.long, comment='Lower Band Long', when=MiddleBand_Buy_Alert)
strategy.entry('Bull', strategy.long, comment='Lower Band Long', when=SidewaysBand_Buy_Alert)
strategy.entry('Bear', strategy.short, comment='Upper Band Short', when=StrongBand_Sell_Alert)
strategy.entry('Bear', strategy.short, comment='Lower Band Short', when=MiddleBand_Sell_Alert)
strategy.entry('Bear', strategy.short, comment='Lower Band Short', when=SidewaysBand_Sell_Alert)
// check which SL to use
if enableSL and whichSL == 'static % as SL'
strategy.exit(id='longTP-SL', from_entry='Bull', limit=longTP1, stop=longSL)
strategy.exit(id='shortTP-SL', from_entry='Bear', limit=shortTP, stop=shortSL)
// get bars since last entry for the SL at low to work
barsSinceLastEntry()=>
strategy.opentrades > 0 ? (bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades-1)) : na
if enableSL and whichSL == 'low/high as SL' and ta.barssince(StrongBand_Buy_Alert or MiddleBand_Buy_Alert or SidewaysBand_Buy_Alert) < 2 and barsSinceLastEntry() < 2
strategy.exit(id='longTP-SL', from_entry='Bull', limit=longTP1, stop=longSlLow)
if enableSL and whichSL == 'low/high as SL' and ta.barssince(StrongBand_Sell_Alert or MiddleBand_Sell_Alert or SidewaysBand_Sell_Alert) < 2 and barsSinceLastEntry() < 2
strategy.exit(id='shortTP-SL', from_entry='Bear', limit=shortTP, stop=shortSlLow)
if not enableSL
strategy.exit(id='longTP-SL', from_entry='Bull', limit=longTP1)
strategy.exit(id='shortTP-SL', from_entry='Bear', limit=shortTP) |
Simple Ema_ATR Strategy HulkTrading | https://www.tradingview.com/script/r0itJoqz-simple-ema-atr-strategy-hulktrading/ | TheHulkTrading | https://www.tradingview.com/u/TheHulkTrading/ | 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/
// © TheHulkTrading
// Simple EMA strategy, based on ema55+ema21 and ATR(Average True Range) and it enters a deal from ema55 when the other entry conditions are met
//@version=4
strategy("Simple Ema_ATR Strategy HulkTrading", overlay=true)
atr_multiplier = input(2, minval=1, title="ATR Multiplier") // ATR Multiplier. Recommended values between 1..4
emaFast=ema(close,21)
emaSlow=ema(close,55)
//Basically long and short conditions
//If long:
// 1) close must be less than open (because we are searching for a pullback)
// 2) emaFast(21) must be bigger than emaSlow(55) - for a trend detection
// 3) Difference between emaFast and emaSlow must be greater than ATR(14) - for excluding flat
longCond = close < open and emaFast > emaSlow and abs(emaSlow-emaFast) > atr(14)
//For short conditions are opposite
shortCond = close > open and emaFast < emaSlow and abs(emaSlow-emaFast) > atr(14)
//Stop levels and take profits, based on ATR multiplier
stop_level_long = strategy.position_avg_price - atr_multiplier*atr(14)
take_level_long = strategy.position_avg_price + atr_multiplier*atr(14)
stop_level_short = strategy.position_avg_price + atr_multiplier*atr(14)
take_level_short = strategy.position_avg_price - atr_multiplier*atr(14)
//Entries and exits
strategy.entry("Long", strategy.long, when=longCond, limit = emaSlow)
strategy.exit("Stop Loss/TP","Long", stop=stop_level_long, limit = take_level_long)
strategy.entry("Short", strategy.short, when=shortCond, limit = emaSlow)
strategy.exit("Stop Loss/TP","Short", stop=stop_level_short, limit = take_level_short)
|
Volume Difference Delta Cycle Oscillator | https://www.tradingview.com/script/SseQ02vi-Volume-Difference-Delta-Cycle-Oscillator/ | tathal | https://www.tradingview.com/u/tathal/ | 535 | 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/
// © tathal and special thanks to oakwhiz for his porting of my custom volume indicator
//@version=5
strategy('Volume Difference Delta Cycle Oscillator', 'VDDC Osc', default_qty_type=strategy.percent_of_equity, default_qty_value=100, max_bars_back=5000)
startDate = input.int(title='Start Date', defval=1, minval=1, maxval=31)
startMonth = input.int(title='Start Month', defval=1, minval=1, maxval=12)
startYear = input.int(title='Start Year', defval=2010, minval=1800, maxval=2100)
endDate = input.int(title='End Date', defval=31, minval=1, maxval=31)
endMonth = input.int(title='End Month', defval=12, minval=1, maxval=12)
endYear = input.int(title='End Year', defval=2021, minval=1800, maxval=2100)
// Normalize Function
normalize(_src, _min, _max) =>
// Normalizes series with unknown min/max using historical min/max.
// _src : series to rescale.
// _min, _min: min/max values of rescaled series.
var _historicMin = 10e10
var _historicMax = -10e10
_historicMin := math.min(nz(_src, _historicMin), _historicMin)
_historicMax := math.max(nz(_src, _historicMax), _historicMax)
_min + (_max - _min) * (_src - _historicMin) / math.max(_historicMax - _historicMin, 10e-10)
// STEP 2:
// Look if the close time of the current bar
// falls inside the date range
inDateRange = time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0) and time < timestamp(syminfo.timezone, endYear, endMonth, endDate, 0, 0)
// Stop loss & Take Profit Section
l_sl_inp = input(2.0, title='Long Stop Loss %') / 100
l_tp_inp = input(4.0, title='Long Take Profit %') / 100
l_stop_level = strategy.position_avg_price * (1 - l_sl_inp)
l_take_level = strategy.position_avg_price * (1 + l_tp_inp)
s_sl_inp = input(2.0, title='Short Stop Loss %') / 100
s_tp_inp = input(4.0, title='Short Take Profit %') / 100
s_stop_level = strategy.position_avg_price * (1 + s_sl_inp)
s_take_level = strategy.position_avg_price * (1 - s_tp_inp)
src = close
// Volume Differnce Indicator Delta
float change_src = ta.change(src)
float i_obv = ta.cum(change_src > 0 ? volume : change_src < 0 ? -volume : 0 * volume)
float i_pvt = ta.pvt
float result = ta.change(i_obv - i_pvt)
float nresult = ta.ema(normalize(result, -1, 1), 20)
// Volume Differnce Indicator Delta %B
length = input.int(20, minval=1, title='Volume Bands Length')
mult = input.float(2.0, minval=0.001, maxval=50, title='Volume Bands StdDev')
basis = ta.ema(nresult, length)
dev = mult * ta.stdev(nresult, length)
upper = basis + dev
lower = basis - dev
bbr = (nresult - lower) / (upper - lower)
// Normal %B, Based on close
l1 = input.int(20, minval=1, title='Bollinger Bands Length')
src2 = close
mult1 = input.float(2.0, minval=0.001, maxval=50, title='Bollinger Bands StdDev')
basis1 = ta.sma(src2, l1)
dev1 = mult1 * ta.stdev(src2, l1)
upper1 = basis1 + dev1
lower1 = basis1 - dev1
bbr1 = (src - lower1) / (upper1 - lower1)
/// Final Output Line
hist = ta.ema(ta.ema(ta.ema(bbr1 - bbr, input(2, title='Hist Smoothing Factor #1')), input(2, title='Hist Smoothing Factor #2')), input(2, title='Hist Smoothing Factor #3'))
/// Overbought / Oversold Line Creation
oversold = input(-.1)
overbought = input(.4)
hline(oversold, linewidth=2, color=color.new(#81c784, 62))
hline(overbought, linewidth=2, color=color.new(#c2185b, 38))
/// Long & Short Conditions
short = hist > overbought
long = hist < oversold
/// Colors & Plotting
histColor = hist >= 0 ? hist[1] < hist ? #26A69A : #B2DFDB : hist[1] < hist ? #FFCDD2 : #EF5350
plot(hist, title='Histogram', style=plot.style_columns, color=color.new(histColor, 0))
CrossBgColor = long ? color.new(#81c784, 62) : short ? color.new(#c2185b, 38) : na
bgcolor(color.new(CrossBgColor, 90))
/// Strategy Methodology
if inDateRange
strategy.entry('long', strategy.long, when=long, stop=l_stop_level, limit=l_take_level)
if inDateRange and strategy.position_size > 0
strategy.close_all(when=short)
if inDateRange
strategy.entry('short', strategy.short, when=short, stop=s_stop_level, limit=s_take_level)
if inDateRange and strategy.position_size < 0
strategy.close_all(when=long)
|
Daily HIGH/LOW strategy | https://www.tradingview.com/script/AHWDGy1z-Daily-HIGH-LOW-strategy/ | exlux99 | https://www.tradingview.com/u/exlux99/ | 199 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © exlux99
//@version=5
strategy(title='Daily HIGH/LOW strategy', overlay=true, initial_capital=10000, calc_on_every_tick=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=0.1)
////////////////////////////GENERAL INPUTS//////////////////////////////////////
len = input.int(24, minval=1, title='Length MA', group='Optimization paramters')
src = input.source(close, title='Source MA', group='Optimization paramters')
out = ta.ema(src, len)
length = input.int(20, minval=1, title='CMF Length', group='Optimization paramters')
ad = close == high and close == low or high == low ? 0 : (2 * close - low - high) / (high - low) * volume
mf = math.sum(ad, length) / math.sum(volume, length)
f_secureSecurity(_symbol, _res, _src) =>
request.security(_symbol, _res, _src[1], lookahead=barmerge.lookahead_on)
pricehigh = f_secureSecurity(syminfo.tickerid, 'D', high)
pricelow = f_secureSecurity(syminfo.tickerid, 'D', low)
plot(pricehigh, title='Previous Daily High', style=plot.style_linebr, linewidth=2, color=color.new(color.white, 0))
plot(pricelow, title='Previous Daily Low', style=plot.style_linebr, linewidth=2, color=color.new(color.white, 0))
short = ta.crossunder(low, pricelow) and close < out and mf < 0
long = ta.crossover(high, pricehigh) and close > out and mf > 0
if short and barstate.isconfirmed
strategy.entry('short', strategy.short, when=barstate.isconfirmed, stop=pricelow[1])
strategy.close('short', when=close > out)
if long and barstate.isconfirmed
strategy.entry('long', strategy.long, when=barstate.isconfirmed, stop=pricehigh[1])
strategy.close('long', when=close < out)
|
AMRS_LongOnly_PartTimer | https://www.tradingview.com/script/5Fge9be1-AMRS-LongOnly-PartTimer/ | ThePartTimeNSE | https://www.tradingview.com/u/ThePartTimeNSE/ | 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/
// © Part Timer
//This script accepts from and to date parameter for backtesting.
//This script generates white arrow for each buying signal
//@version=4
strategy("AMRS_LongOnly_PartTimer", overlay = true)
//i_endTime = input(defval = timestamp("02 Jun 2021 15:30 +0000"), title = "End Time", type=input.time)
StartYear=input(defval = 2000, title ="Start Year", type=input.integer)
StartMonth=input(defval = 01, title ="Start Month", type=input.integer)
StartDate=input(defval = 01, title ="Start Date", type=input.integer)
endYear=input(defval = 2021, title ="End Year", type=input.integer)
endMonth=input(defval = 06, title ="End Month", type=input.integer)
endDate=input(defval = 03, title ="End Date", type=input.integer)
ema11=ema(close,11)
ema13=ema(close,13)
ema21=ema(close,21)
afterStartDate = (time >= timestamp(syminfo.timezone,StartYear, StartMonth, StartDate, 0, 0))
//g=bar_index==1
//ath()=>
//a=0.0
//a:=g ? high : high>a[1] ? high:a[1]
//a = security(syminfo.tickerid, 'M', ath(),lookahead=barmerge.lookahead_on)
newHigh = (high > highest(high,504)[1])
//plot down arrows whenever it's a new high
plotshape(newHigh, style=shape.triangleup, location=location.abovebar, color=color.green, size=size.tiny)
b=highest(high,504)[1]
VarChk=((b-ema13)/b)*100
TrigLow = (low <= ema13) and (low >= ema21) and (VarChk <= 10)
plotshape(TrigLow, style=shape.triangleup, location=location.belowbar, color=color.white, size=size.tiny)
ExitPrice=(ema21 - (ema21*0.05))
DrawPrice=(b - (b*0.20))
stopprice=0.0
if (close <= ExitPrice)
stopprice := ExitPrice
if (close <= DrawPrice)
stopprice := DrawPrice
if (TrigLow and afterStartDate)
strategy.entry("Long", strategy.long)
strategy.exit("exit","Long", stop=stopprice)
//beforeEndDate = (time < i_endTime)
beforeEndDate = (time >= timestamp(syminfo.timezone,endYear, endMonth, endDate, 0, 0))
if (beforeEndDate)
strategy.close_all() |
RSI Overbought Oversold Divergence Strategy w/ Buy/Sell Signals | https://www.tradingview.com/script/d92hvFQx-RSI-Overbought-Oversold-Divergence-Strategy-w-Buy-Sell-Signals/ | imal_max | https://www.tradingview.com/u/imal_max/ | 532 | 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/
// made by Imal_Max
// thanks to The1IamNeo's and brandons idea
//
// thanks to JayTradingCharts RSI Divergence /w Alerts indicator for the base code.
//@version=5
//
// 🔥 uncomment the line below to enable the alerts and disable the backtester
//indicator(title="Ultimate Bullish Divergence for RSI MFI RVSI OBV TRIXRSI w/ Buy Alerts", shorttitle="Ultimate Bull Divergence", format=format.price)//, timeframe="")
// 🔥 comment the line below to disable the backtester + uncomment the lines slightly below and at the bottom of the script
strategy(title="Ultimate Bullish Divergence for RSI MFI RVSI OBV TRIXRSI w/ Buy Signals", shorttitle="Ultimate Bull Divergence Backtester", overlay=false, pyramiding=1, process_orders_on_close=true, calc_on_every_tick=true, initial_capital=1000, currency = currency.USD, default_qty_value=100, default_qty_type=strategy.percent_of_equity, commission_type=strategy.commission.percent, commission_value=0.05, slippage=2)
selectOsc = input.string("RSI", title="Select Oscillator", group='═════════ Oscillator settings ══════════', options=["RSI","OBV","RVSI","MFI","TRIX RSI"], tooltip="RSI = Relative Strengh Index; OBV = On Balance Volume; RVSI = Relative Volume Strengh Index; MFI Money Flow Index; TRIX RSI = Tripple Exponetial Relative Strength")
src = input.source(title='Oscillator Source', defval=low, group='═════════ Oscillator settings ══════════', tooltip="RSI, RVSI, OBV and TRIX RSI default Source: Close; MFI default Source: hlc3")
len = input.int(title='Oscillator Length', minval=1, defval=14, group='═════════ Oscillator settings ══════════', tooltip="RSI/MFI default Period = 14; RVSI = 10; TRIX RSI = 9; OBV has no period.")
seclen = input.int(9, minval=1, title="Oscillator secondary length", group="═════════ Oscillator settings ══════════", tooltip="affects only RVSI and Trix RSI. For the TRIX RSI this defines the length of the TRIX. default value = 9 and for the RVSI it defines the Volume moving average length, default value = 5")
emalen = input(9, 'Oscillator Moving Average Length', group='═════════ Oscillator settings ══════════', tooltip="defines the length of the of the Oscillator moving average")
rangeLower = input.int(title='Min Lookback Range', defval=0, group='═════ Oscillator Divergence Settings ══════', inline='Input 0')
rangeUpper = input.int(title='Max Lookback', defval=200, group='═════ Oscillator Divergence Settings ══════', inline='Input 0', tooltip="reduces the Lookback range that you define with Pivot Lookback Left 1-30 ")
enableonlyOneLB = input.bool(title='Only use the first look back period', defval=false, group='═════ Oscillator Divergence Settings ══════')
lbL1 = input.int(title='Pivot Lookback Left-1', defval=2, group='═════ Oscillator Divergence Settings ══════', inline='Input 1', tooltip="Amount of bars to look back to find pivot lows on the Oscillator and Price")
lbL2 = input.int(title='Lookback Left-2', defval=3, group='═════ Oscillator Divergence Settings ══════', inline='Input 1')
lbL3 = input.int(title='Pivot Lookback Left-3', defval=4, group='═════ Oscillator Divergence Settings ══════', inline='Input 2')
lbL4 = input.int(title='Lookback Left-4', defval=5, group='═════ Oscillator Divergence Settings ══════', inline='Input 2')
lbL5 = input.int(title='Pivot Lookback Left-5', defval=6, group='═════ Oscillator Divergence Settings ══════', inline='Input 2')
lbL6 = input.int(title='Lookback Left-6', defval=7, group='═════ Oscillator Divergence Settings ══════', inline='Input 2')
lbL7 = input.int(title='Pivot Lookback Left-7', defval=9, group='═════ Oscillator Divergence Settings ══════', inline='Input 2')
lbL8 = input.int(title='Lookback Left-8', defval=10, group='═════ Oscillator Divergence Settings ══════', inline='Input 2')
lbL9 = input.int(title='Pivot Lookback Left-9', defval=11, group='═════ Oscillator Divergence Settings ══════', inline='Input 2')
lbL10 = input.int(title='Lookback Left-10', defval=12, group='═════ Oscillator Divergence Settings ══════', inline='Input 2')
lbL11 = input.int(title='Pivot Lookback Left-11', defval=13, group='═════ Oscillator Divergence Settings ══════', inline='Input 2')
lbL12 = input.int(title='Lookback Left-12', defval=14, group='═════ Oscillator Divergence Settings ══════', inline='Input 2')
lbL13 = input.int(title='Pivot Lookback Left-13', defval=15, group='═════ Oscillator Divergence Settings ══════', inline='Input 2')
lbL14 = input.int(title='Lookback Left-14', defval=16, group='═════ Oscillator Divergence Settings ══════', inline='Input 2')
lbL15 = input.int(title='Pivot Lookback Left-15', defval=17, group='═════ Oscillator Divergence Settings ══════', inline='Input 2')
lbL16 = input.int(title='Lookback Left-16', defval=18, group='═════ Oscillator Divergence Settings ══════', inline='Input 2')
lbL17 = input.int(title='Pivot Lookback Left-17', defval=19, group='═════ Oscillator Divergence Settings ══════', inline='Input 2')
lbL18 = input.int(title='Lookback Left-18', defval=20, group='═════ Oscillator Divergence Settings ══════', inline='Input 2')
lbL19 = input.int(title='Pivot Lookback Left-19', defval=22, group='═════ Oscillator Divergence Settings ══════', inline='Input 2')
lbL20 = input.int(title='Lookback Left-20', defval=25, group='═════ Oscillator Divergence Settings ══════', inline='Input 2')
lbL21 = input.int(title='Pivot Lookback Left-21', defval=28, group='═════ Oscillator Divergence Settings ══════', inline='Input 2')
lbL22 = input.int(title='Lookback Left-22', defval=31, group='═════ Oscillator Divergence Settings ══════', inline='Input 2')
lbL23 = input.int(title='Pivot Lookback Left-23', defval=34, group='═════ Oscillator Divergence Settings ══════', inline='Input 2')
lbL24 = input.int(title='Lookback Left-24', defval=37, group='═════ Oscillator Divergence Settings ══════', inline='Input 2')
lbL25 = input.int(title='Pivot Lookback Left-25', defval=39, group='═════ Oscillator Divergence Settings ══════', inline='Input 2')
lbL26 = input.int(title='Lookback Left-26', defval=42, group='═════ Oscillator Divergence Settings ══════', inline='Input 2')
lbL27 = input.int(title='Pivot Lookback Left-27', defval=45, group='═════ Oscillator Divergence Settings ══════', inline='Input 2')
lbL28 = input.int(title='Lookback Left-28', defval=48, group='═════ Oscillator Divergence Settings ══════', inline='Input 2')
lbL29 = input.int(title='Pivot Lookback Left-29', defval=51, group='═════ Oscillator Divergence Settings ══════', inline='Input 2')
lbL30 = input.int(title='Lookback Left-30', defval=54, group='═════ Oscillator Divergence Settings ══════', inline='Input 2')
plotBull = input.bool(title='Plot Bullish', defval=true, group='═════ Oscillator Divergence Settings ══════', inline='Input 4', tooltip="Price makes a lower low while the Oscillator is making a higher low")
plotHiddenBull = input.bool(title='Plot Hidden Bullish', defval=false, group='═════ Oscillator Divergence Settings ══════', inline='Input 4', tooltip="Price makes a higher low while Oscillator is making a lower low")
///////////// Delay inputs
// Price bounce delay
enablepriceBounceNeeded = input.bool(title='enable $ bounce delay', defval=false, group='═══════════ Signal Delays ═══════════')
priceBounceNeeded = input.int(title='min $ bounce needed to flash buy', defval=35, group='═══════════ Signal Delays ═══════════')
priceBounceNeededLbL = input.int(title='Amount of Candles until giving up', defval=3, minval=0, maxval=10, group='═══════════ Signal Delays ═══════════')
// bars delay
lbR = input.int(title='Confirmation Time (bars) needed', minval=0, defval=0, group='Time Delay', tooltip='0 means the first candle - no candle close needed to flash a signal. Wait for a candle close to be sure (for alerts on the first cadle close set it to 0 and set the to "once per bar close")')
// EMA break delay
enableWaitForEmaBreak = input.bool(title='enable wait for moving average break', defval=false, group='EMA break Delay', tooltip="waits for a break of the moving average to flash a signal")
WaitForEmaBreakLen = input(5, 'EMA Length', group='EMA break Delay', tooltip="defines the length of the moving average which it needs to break before a signal flashes")
// wait Oscillator and Oscillator EMA cross
enableOscCross = input.bool(title='enable wait for Oscillator and Oscillator EMA Cross', defval=false, group='Oscillator EMA Cross Delay', tooltip="")
oscCrosslookback = input.int(title='Amount of Candles until giving up', defval=3, minval=0, maxval=10, group='Oscillator EMA Cross Delay')
// ranges and filter
// only long on rising EMA inputs
enableOnlyLongUptrend = input.bool(title='only long on in an uptrend (rising moving average)', defval=false, group='═══════════ Ranges & Filter ═══════════', tooltip="")
OnlyLongUptrendEmaLen = input(200, 'EMA Length to determine an uptrend', group='═══════════ Ranges & Filter ═══════════', tooltip="defines the length of the of the moving average")
EmaUptrend = ta.ema(src, OnlyLongUptrendEmaLen)
isInEMAUptrend = ta.change(EmaUptrend) > 0 or not enableOnlyLongUptrend
// ob/os divergence settings
enableRsiLimit = input.bool(title='enable Oversold limits', defval=false, group='divergence below OverSold', tooltip="only works with RSI, MFI and RVSI")
osvalue = input.int(title='only show Signals if the Oscillator was below', defval=30, group='divergence below OverSold', inline='Input 1')
oslookback = input.int(title='within the last (x candles)', defval=2, group='divergence below OverSold', inline='Input 1')
maxBullRSI = input.int(title='only show signals if the Oscillator is', defval=35, group='divergence below OverSold')
// manual ranges for divergence
enableManualbull1 = input.bool(title='enable manual Bullish Range-1', defval=false, group='══════ manual Range for divergence signal')
manualbullHigh1 = input.int(title='Range 1 - Bullish high', defval=10000000, group='══════ manual Range for divergence signal', inline='Input 0')
manualbullLow1 = input.int(title='Range 1 - Bullish low', defval=0, group='══════ manual Range for divergence signal', inline='Input 0')
enableManualbull2 = input.bool(title='enable manual Bullish Range-2', defval=false, group='══════ manual Range for divergence signal')
manualbullHigh2 = input.int(title='Range 2 - Bullish high', defval=10000000, group='══════ manual Range for divergence signal', inline='Input 1')
manualbullLow2 = input.int(title='Range 2 - Bullish low', defval=0, group='══════ manual Range for divergence signal', inline='Input 1')
enableManualbull3 = input.bool(title='enable manual Bullish Range-1', defval=false, group='══════ manual Range for divergence signal')
manualbullHigh3 = input.int(title='Range 3 - Bullish high', defval=10000000, group='══════ manual Range for divergence signal', inline='Input 2')
manualbullLow3 = input.int(title='Range 3 - Bullish low', defval=0, group='══════ manual Range for divergence signal', inline='Input 2')
enableManualbull4 = input.bool(title='enable manual Bullish Range-2', defval=false, group='══════ manual Range for divergence signal')
manualbullHigh4 = input.int(title='Range 4 - Bullish high', defval=10000000, group='══════ manual Range for divergence signal', inline='Input 3')
manualbullLow4 = input.int(title='Range 4 - Bullish low', defval=0, group='══════ manual Range for divergence signal', inline='Input 3')
// check if divergence happend within manual levels
isWithinLongRange1 = (close < manualbullHigh1 and close > manualbullLow1)
isWithinLongRange2 = (close < manualbullHigh2 and close > manualbullLow2)
isWithinLongRange3 = (close < manualbullHigh3 and close > manualbullLow3)
isWithinLongRange4 = (close < manualbullHigh4 and close > manualbullLow4)
isWithinLongRange = true
if enableManualbull1 or enableManualbull2 or enableManualbull3 or enableManualbull4
isWithinLongRange := (isWithinLongRange1 and enableManualbull1) or (isWithinLongRange2 and enableManualbull2) or (isWithinLongRange3 and enableManualbull3) or (isWithinLongRange4 and enableManualbull4)
/////////////////////////// Get ranges to look for divergences from indicators
// EMA
// EMA Bull range high
enableEmaBullHigh = input.bool(title='enable EMA as High of the Long Range', defval=false, group='══════ EMA Range for divergence signal')
emaBullHighLen = input.int(9, minval=1, title='Length', group='══════ EMA Range for divergence signal', inline='Input 4')
emaBullHighSrc = input(close, title='Source', group='══════ EMA Range for divergence signal', inline='Input 4')
emaBullHighDevi = input.int(title='deviation', defval=0, minval=-500, maxval=500, group='══════ EMA Range for divergence signal', inline='Input 4')
emaBullHighOut = ta.sma(emaBullHighSrc, emaBullHighLen)
isBelowEmaBullHigh = close < emaBullHighOut or not enableEmaBullHigh
// EMA Bull range low
enableEmaBullLow = input.bool(title='enable EMA as Low of the Long Range', defval=false, group='══════ EMA Range for divergence signal')
emaBullLowLen = input.int(55, minval=1, title='Length', group='══════ EMA Range for divergence signal', inline='Input 5')
emaBullLowSrc = input(close, title='Source', group='══════ EMA Range for divergence signal', inline='Input 5')
emaBullLowOffset = input.int(title='deviation', defval=0, minval=-500, maxval=500, group='══════ EMA Range for divergence signal', inline='Input 5')
emaBullLowOut = ta.sma(emaBullLowSrc, emaBullLowLen)
isBelowEmaBullLow = close > emaBullLowOut or not enableEmaBullLow
iswithinEmaRange = isBelowEmaBullHigh and isBelowEmaBullLow
// EMA END
// VWAP
enableVwapBullHigh = input.bool(title='enable VWAP as High of the Long Range', defval=false, group='════ VWAP Range for divergence signal')
enableVwapBullLow = input.bool(title='enable VWAP as Low of the Long Range', defval=false, group='════ VWAP Range for divergence signal')
enableVwapDiviBullHigh = input.bool(title='enable VWAP Upper Diviation as High of the Long Range', defval=false, group='════ VWAP Range for divergence signal')
enableVwapDiviBullLow = input.bool(title='enable VWAP Lower Diviation as Low of the Long Range', defval=false, group='════ VWAP Range for divergence signal')
computeVWAP(src, isNewPeriod, stDevMultiplier) =>
var float sumSrcVol = na
var float sumVol = na
var float sumSrcSrcVol = na
sumSrcVol := isNewPeriod ? src * volume : src * volume + sumSrcVol[1]
sumVol := isNewPeriod ? volume : volume + sumVol[1]
// sumSrcSrcVol calculates the dividend of the equation that is later used to calculate the standard deviation
sumSrcSrcVol := isNewPeriod ? volume * math.pow(src, 2) : volume * math.pow(src, 2) + sumSrcSrcVol[1]
_vwap = sumSrcVol / sumVol
variance = sumSrcSrcVol / sumVol - math.pow(_vwap, 2)
variance := variance < 0 ? 0 : variance
stDev = math.sqrt(variance)
lowerBand = _vwap - stDev * stDevMultiplier
upperBand = _vwap + stDev * stDevMultiplier
[_vwap, lowerBand, upperBand]
hideonDWM = false
var anchor = input.string(defval='Session', title='Anchor Period', options=['Session', 'Week', 'Month', 'Quarter', 'Year', 'Decade', 'Century', 'Earnings', 'Dividends', 'Splits'], group='VWAP Settings')
vsrc = input.source(title='Source', defval=hlc3, group='VWAP Settings')
offset = input.int(0, title='Offset', group='VWAP Settings')
stdevMult = input.float(1.0, title='Bands Standard Diviation Multiplier', group='VWAP Settings')
timeChange(period) =>
ta.change(time(period))
new_earnings = request.earnings(syminfo.tickerid, earnings.actual, barmerge.gaps_on, barmerge.lookahead_on)
new_dividends = request.dividends(syminfo.tickerid, dividends.gross, barmerge.gaps_on, barmerge.lookahead_on)
new_split = request.splits(syminfo.tickerid, splits.denominator, barmerge.gaps_on, barmerge.lookahead_on)
isNewPeriod = anchor == 'Earnings' ? new_earnings : anchor == 'Dividends' ? new_dividends : anchor == 'Splits' ? new_split : na(vsrc[1]) ? true : anchor == 'Session' ? timeChange('D') : anchor == 'Week' ? timeChange('W') : anchor == 'Month' ? timeChange('M') : anchor == 'Quarter' ? timeChange('3M') : anchor == 'Year' ? timeChange('12M') : anchor == 'Decade' ? timeChange('12M') and year % 10 == 0 : anchor == 'Century' ? timeChange('12M') and year % 100 == 0 : false
float vwapValue = na
float std = na
float upperBandValue = na
float lowerBandValue = na
showBands = true
if not(hideonDWM and timeframe.isdwm)
[_vwap, bottom, top] = computeVWAP(vsrc, isNewPeriod, stdevMult)
vwapValue := _vwap
upperBandValue := showBands ? top : na
lowerBandValue := showBands ? bottom : na
// check if inside VWAP Range
isBelowVwap = vwapValue < close or not enableVwapBullHigh
isAboveVwap = vwapValue > close or not enableVwapBullLow
isAboveVwapLowerDivi = lowerBandValue < close or not enableVwapDiviBullLow
isBelowVwapUpperDivi = upperBandValue > close or not enableVwapDiviBullHigh
isWithinVwapRange = isBelowVwap and isAboveVwap and isAboveVwapLowerDivi and isBelowVwapUpperDivi
// VWAP END
// auto fib ranges
// fib fibbull range high
enablefibbullHigh = input.bool(title='enable Auto fib as High of the Long Range', defval=false, group='════ auto fib range for divergence signal', inline='Input 0')
selectfibbullHigh = input.float(0.5, 'fib Level', options=[0, 0.236, 0.382, 0.5, 0.618, 0.702, 0.71, 0.786, 0.83, 0.886, 1], group='══ auto fib range for divergence signal')
fibbullHighLookback = input.int(title='Auto Fib Lookback', minval=1, defval=200, group='════ auto fib range for divergence signal', inline='Input 1')
//fibbullHighDivi = input.int(title='diviation in %', defval=5, group='══ auto fib range for divergence signal', inline='Input 1')
// fib fibbull range low
enablefibbullLow = input.bool(title='enable Auto fib as Low of the Long Range', defval=false, group='════ auto fib range for divergence signal', inline='Input 2')
selectfibbullLow = input.float(0.886, 'fib Level', options=[0, 0.236, 0.382, 0.5, 0.618, 0.702, 0.71, 0.786, 0.83, 0.886, 1], group='════ auto fib range for divergence signal')
fibbullLowhLookback = input.int(title='Auto Fib Lookback', minval=1, defval=200, group='════ auto fib range for divergence signal', inline='Input 3')
//fibbullLowhDivi = input.int(title='diviation in %', defval=5, group='══ auto fib range for divergence signal', inline='Input 3')
isBelowfibbullHigh = true
isBelowfibbullLow = true
fibLowPrice = 0.1
fibHighPrice = 0.1
fibHighLow = 0.1
fibHighHigh = 0.1
fibLowHigh = 0.1
fibLowLow = 0.1
if enablefibbullHigh
fibHighHigh := ta.highest(high, fibbullHighLookback)
fibHighLow := ta.lowest(low, fibbullHighLookback)
fibHighPrice := (fibHighHigh - fibHighLow) * (1 - selectfibbullHigh) + fibHighLow //+ fibbullHighDivi
isBelowfibbullHigh := fibHighPrice > ta.lowest(low, 2) or not enablefibbullHigh
if enablefibbullLow
fibLowHigh := ta.highest(high, fibbullLowhLookback)
fibLowLow := ta.lowest(low, fibbullLowhLookback)
fibLowPrice := (fibLowHigh - fibLowLow) * (1 - selectfibbullLow) + fibLowLow// + fibbullLowhDivi
isBelowfibbullLow := fibLowPrice < ta.highest(low, 2) or not enablefibbullLow
//plot(fibHighHigh)
//plot(fibHighLow)
//plot(fibHighPrice, color=color.orange)
//plot(fibLowPrice, color=color.orange)
isWithinFibRange = isBelowfibbullHigh and isBelowfibbullLow
/////// auto fib END
/// Ranges checks
isWithinLongRanges = isWithinLongRange and iswithinEmaRange and isWithinVwapRange and isWithinFibRange and isInEMAUptrend
// divergence label colors
bullColor = color.purple
bullColor1 = color.aqua
bullColor2 = color.black
bullColor3 = color.blue
bullColor4 = color.fuchsia
bullColor5 = color.gray
bullColor6 = color.green
bullColor7 = color.lime
bullColor8 = color.maroon
bullColor9 = color.navy
bullColor10 = color.olive
bullColor11 = color.orange
bullColor12 = color.purple
bullColor13 = color.red
bullColor14 = color.silver
bullColor15 = color.teal
bullColor16 = color.blue
bullColor17 = color.navy
bullColor18 = color.purple
bullColor19 = color.purple
bullColor20 = color.red
bullColor21 = color.orange
bullColor22 = color.purple
bullColor23 = color.red
bullColor24 = color.silver
bullColor25 = color.teal
bullColor26 = color.lime
bullColor27 = color.fuchsia
bullColor28 = color.lime
bullColor29 = color.purple
bullColor30 = color.red
bullColor31 = color.aqua
bullColor32 = color.black
bullColor33 = color.blue
bullColor34 = color.fuchsia
bullColor35 = color.gray
hiddenBullColor = color.new(color.purple, 80)
textColor = color.white
noneColor = color.new(color.white, 100)
//// Oscillators
// set the var to RSI to make it work
osc = ta.rsi(src, len)
// calculate RSI
if selectOsc == "RSI"
osc := ta.rsi(src, len)
// calculate RVSI
if selectOsc == "RVSI"
nv = ta.cum(ta.change(src) * volume)
av = ta.ema(nv, seclen)
RVSI = ta.rsi(av, len)
osc := RVSI
// getting OBV
if selectOsc == "OBV"
osc := ta.obv
// calculate MFI
if selectOsc == "MFI"
upper = math.sum(volume * (ta.change(src) <= 0 ? 0 : src), len)
lower = math.sum(volume * (ta.change(src) >= 0 ? 0 : src), len)
osc := 100.0 - 100.0 / (1.0 + upper / lower)
if selectOsc == "TRIX RSI"
trix = 10000 * ta.change(ta.ema(ta.ema(ta.ema(math.log(src), seclen), seclen), seclen))
osc := ta.rsi(trix, len)
oscema = ta.ema(osc, emalen)
//// Oscillators
//////////////// Oscillator Conditions
// check if RSI was OS or OB recently
osLowestRsi = ta.lowest(osc, oslookback)
RSIwasBelowOS = osLowestRsi < osvalue or not enableRsiLimit
// check if RSI is below maxBullRSI and above minBearRSI
isBelowRsiBull = osc < maxBullRSI or not enableRsiLimit
/////////////////// plot ob os levels
osLevel = hline(osvalue, title='Oversold', linestyle=hline.style_dotted)
maxRSIline = hline(maxBullRSI, title='max RSI for Bull divergence', linestyle=hline.style_dotted)
//fill(osLevel, maxRSIline, title='Bull Zone Background', color=color.new(#4caf50, 90))
//RSI0line = hline(0, title='RSI 0 Line', linestyle=hline.style_dotted)
//RSI100line = hline(100, title='RSI 100 Line', linestyle=hline.style_dotted)
//fill(osLevel, RSI0line, title='Oversold Zone Background', color=color.new(#4caf50, 75))
////////////////////// plot Oscillator, histogram and Oscillator ema
plot(osc, title='Oscillator', linewidth=2, color=color.new(#00bcd4, 0))
plot(oscema, color=color.purple, title='Oscillator EMA', style=plot.style_circles)
//hist = osc - oscema
//plot(hist, title='Oscillator Histogram', style=plot.style_columns, color=hist >= 0 ? hist[1] < hist ? color.lime : color.purple : hist[1] < hist ? color.orange : color.red)
//////////////////// plot Oscillator, histogram and Oscillator ema END
//////////////// divergence stuff start
////// divergence Lookback period #1
// get pivots
plFound1 = na(ta.pivotlow(osc, lbL1, lbR)) ? false : true
_inRange1(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL1 = osc[lbR] > ta.valuewhen(plFound1, osc[lbR], 1) and _inRange1(plFound1[1])
// Price: Lower Low
priceLL1 = low[lbR] < ta.valuewhen(plFound1, low[lbR], 1)
bullCond1 = plotBull and priceLL1 and oscHL1 and plFound1 and RSIwasBelowOS and isWithinLongRanges
//plot(plFound1 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish', linewidth=2, color=bullCond1 ? bullColor : noneColor)
plotshape(bullCond1 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish 1 Label', text=' B1 ', style=shape.labelup, location=location.absolute, color=bullColor1, textcolor=textColor)
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL1 = osc[lbR] < ta.valuewhen(plFound1, osc[lbR], 1) and _inRange1(plFound1[1])
// Price: Higher Low
priceHL1 = low[lbR] > ta.valuewhen(plFound1, low[lbR], 1)
hiddenBullCond1 = plotHiddenBull and priceHL1 and oscLL1 and plFound1 and RSIwasBelowOS and isWithinLongRanges
//plot(plFound1 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish', linewidth=2, color=hiddenBullCond1 ? hiddenBullColor : noneColor)
plotshape(hiddenBullCond1 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish 1 Label', text=' H B1 ', style=shape.labelup, location=location.absolute, color=bullColor1, textcolor=textColor)
//------------------------------------------------------------------------------
////// divergence Lookback period #1 END
////// divergence Lookback period #2
// get pivots
plFound2 = na(ta.pivotlow(osc, lbL2, lbR)) ? false : true
_inRange2(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL2 = osc[lbR] > ta.valuewhen(plFound2, osc[lbR], 1) and _inRange2(plFound2[1])
// Price: Lower Low
priceLL2 = low[lbR] < ta.valuewhen(plFound2, low[lbR], 1)
bullCond2 = plotBull and priceLL2 and oscHL2 and plFound2 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound2 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish', linewidth=2, color=bullCond2 ? bullColor : noneColor)
plotshape(bullCond2 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish 2 Label', text=' B2 ', style=shape.labelup, location=location.absolute, color=bullColor2, textcolor=textColor)
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL2 = osc[lbR] < ta.valuewhen(plFound2, osc[lbR], 1) and _inRange2(plFound2[1])
// Price: Higher Low
priceHL2 = low[lbR] > ta.valuewhen(plFound2, low[lbR], 1)
hiddenBullCond2 = plotHiddenBull and priceHL2 and oscLL2 and plFound2 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound2 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish', linewidth=2, color=hiddenBullCond2 ? hiddenBullColor : noneColor)
plotshape(hiddenBullCond2 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish 2 Label', text=' H B2 ', style=shape.labelup, location=location.absolute, color=bullColor2, textcolor=textColor)
//------------------------------------------------------------------------------
////// divergence Lookback period #3
// get pivots
plFound3 = na(ta.pivotlow(osc, lbL3, lbR)) ? false : true
_inRange3(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL3 = osc[lbR] > ta.valuewhen(plFound3, osc[lbR], 1) and _inRange3(plFound3[1])
// Price: Lower Low
priceLL3 = low[lbR] < ta.valuewhen(plFound3, low[lbR], 1)
bullCond3 = plotBull and priceLL3 and oscHL3 and plFound3 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound3 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish', linewidth=2, color=bullCond3 ? bullColor : noneColor)
plotshape(bullCond3 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish 3 Label', text=' B3 ', style=shape.labelup, location=location.absolute, color=bullColor3, textcolor=textColor)
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL3 = osc[lbR] < ta.valuewhen(plFound3, osc[lbR], 1) and _inRange3(plFound3[1])
// Price: Higher Low
priceHL3 = low[lbR] > ta.valuewhen(plFound3, low[lbR], 1)
hiddenBullCond3 = plotHiddenBull and priceHL3 and oscLL3 and plFound3 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound3 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish', linewidth=2, color=hiddenBullCond3 ? hiddenBullColor : noneColor)
plotshape(hiddenBullCond3 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish 3 Label', text=' H B3 ', style=shape.labelup, location=location.absolute, color=bullColor3, textcolor=textColor)
//------------------------------------------------------------------------------
////// divergence Lookback period #3 END
////// divergence Lookback period #4
// get pivots
plFound4 = na(ta.pivotlow(osc, lbL4, lbR)) ? false : true
_inRange4(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL4 = osc[lbR] > ta.valuewhen(plFound4, osc[lbR], 1) and _inRange4(plFound4[1])
// Price: Lower Low
priceLL4 = low[lbR] < ta.valuewhen(plFound4, low[lbR], 1)
bullCond4 = plotBull and priceLL4 and oscHL4 and plFound4 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound4 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish', linewidth=2, color=bullCond4 ? bullColor : noneColor)
plotshape(bullCond4 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish 4 Label', text=' B4 ', style=shape.labelup, location=location.absolute, color=bullColor4, textcolor=textColor)
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL4 = osc[lbR] < ta.valuewhen(plFound4, osc[lbR], 1) and _inRange4(plFound4[1])
// Price: Higher Low
priceHL4 = low[lbR] > ta.valuewhen(plFound4, low[lbR], 1)
hiddenBullCond4 = plotHiddenBull and priceHL4 and oscLL4 and plFound4 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound4 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish', linewidth=2, color=hiddenBullCond4 ? hiddenBullColor : noneColor)
plotshape(hiddenBullCond4 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish 4 Label', text=' H B4 ', style=shape.labelup, location=location.absolute, color=bullColor4, textcolor=textColor)
//------------------------------------------------------------------------------
////// divergence Lookback period #4 END
////// divergence Lookback period #5
// get pivots
plFound5 = na(ta.pivotlow(osc, lbL5, lbR)) ? false : true
_inRange5(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL5 = osc[lbR] > ta.valuewhen(plFound5, osc[lbR], 1) and _inRange5(plFound5[1])
// Price: Lower Low
priceLL5 = low[lbR] < ta.valuewhen(plFound5, low[lbR], 1)
bullCond5 = plotBull and priceLL5 and oscHL5 and plFound5 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound5 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish', linewidth=2, color=bullCond5 ? bullColor : noneColor)
plotshape(bullCond5 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish 5 Label', text=' B5 ', style=shape.labelup, location=location.absolute, color=bullColor5, textcolor=textColor)
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL5 = osc[lbR] < ta.valuewhen(plFound5, osc[lbR], 1) and _inRange5(plFound5[1])
// Price: Higher Low
priceHL5 = low[lbR] > ta.valuewhen(plFound5, low[lbR], 1)
hiddenBullCond5 = plotHiddenBull and priceHL5 and oscLL5 and plFound5 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound5 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish', linewidth=2, color=hiddenBullCond5 ? hiddenBullColor : noneColor)
plotshape(hiddenBullCond5 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish 5 Label', text=' H B5 ', style=shape.labelup, location=location.absolute, color=bullColor5, textcolor=textColor)
//------------------------------------------------------------------------------
////// divergence Lookback period #5 END
////// divergence Lookback period #6
// get pivots
plFound6 = na(ta.pivotlow(osc, lbL6, lbR)) ? false : true
_inRange6(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL6 = osc[lbR] > ta.valuewhen(plFound6, osc[lbR], 1) and _inRange6(plFound6[1])
// Price: Lower Low
priceLL6 = low[lbR] < ta.valuewhen(plFound6, low[lbR], 1)
bullCond6 = plotBull and priceLL6 and oscHL6 and plFound6 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound6 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish', linewidth=2, color=bullCond6 ? bullColor : noneColor)
plotshape(bullCond6 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish 6 Label', text=' B6 ', style=shape.labelup, location=location.absolute, color=bullColor6, textcolor=textColor)
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL6 = osc[lbR] < ta.valuewhen(plFound6, osc[lbR], 1) and _inRange6(plFound6[1])
// Price: Higher Low
priceHL6 = low[lbR] > ta.valuewhen(plFound6, low[lbR], 1)
hiddenBullCond6 = plotHiddenBull and priceHL6 and oscLL6 and plFound6 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound6 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish', linewidth=2, color=hiddenBullCond6 ? hiddenBullColor : noneColor)
plotshape(hiddenBullCond6 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish 6 Label', text=' H B6 ', style=shape.labelup, location=location.absolute, color=bullColor6, textcolor=textColor)
//------------------------------------------------------------------------------
////// divergence Lookback period #6 END
////// divergence Lookback period #7
// get pivots
plFound7 = na(ta.pivotlow(osc, lbL7, lbR)) ? false : true
_inRange7(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL7 = osc[lbR] > ta.valuewhen(plFound7, osc[lbR], 1) and _inRange7(plFound7[1])
// Price: Lower Low
priceLL7 = low[lbR] < ta.valuewhen(plFound7, low[lbR], 1)
bullCond7 = plotBull and priceLL7 and oscHL7 and plFound7 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound7 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish', linewidth=2, color=bullCond7 ? bullColor : noneColor)
plotshape(bullCond7 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish 7 Label', text=' B7 ', style=shape.labelup, location=location.absolute, color=bullColor7, textcolor=textColor)
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL7 = osc[lbR] < ta.valuewhen(plFound7, osc[lbR], 1) and _inRange7(plFound7[1])
// Price: Higher Low
priceHL7 = low[lbR] > ta.valuewhen(plFound7, low[lbR], 1)
hiddenBullCond7 = plotHiddenBull and priceHL7 and oscLL7 and plFound7 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound7 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish', linewidth=2, color=hiddenBullCond7 ? hiddenBullColor : noneColor)
plotshape(hiddenBullCond7 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish 7 Label', text=' H B7 ', style=shape.labelup, location=location.absolute, color=bullColor7, textcolor=textColor)
//------------------------------------------------------------------------------
////// divergence Lookback period #7 END
////// divergence Lookback period #8
// get pivots
plFound8 = na(ta.pivotlow(osc, lbL8, lbR)) ? false : true
_inRange8(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL8 = osc[lbR] > ta.valuewhen(plFound8, osc[lbR], 1) and _inRange8(plFound8[1])
// Price: Lower Low
priceLL8 = low[lbR] < ta.valuewhen(plFound8, low[lbR], 1)
bullCond8 = plotBull and priceLL8 and oscHL8 and plFound8 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound8 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish', linewidth=2, color=bullCond8 ? bullColor : noneColor)
plotshape(bullCond8 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish 8 Label', text=' B8 ', style=shape.labelup, location=location.absolute, color=bullColor8, textcolor=textColor)
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL8 = osc[lbR] < ta.valuewhen(plFound8, osc[lbR], 1) and _inRange8(plFound8[1])
// Price: Higher Low
priceHL8 = low[lbR] > ta.valuewhen(plFound8, low[lbR], 1)
hiddenBullCond8 = plotHiddenBull and priceHL8 and oscLL8 and plFound8 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound8 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish', linewidth=2, color=hiddenBullCond8 ? hiddenBullColor : noneColor)
plotshape(hiddenBullCond8 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish 8 Label', text=' H B8 ', style=shape.labelup, location=location.absolute, color=bullColor8, textcolor=textColor)
//------------------------------------------------------------------------------
////// divergence Lookback period #8 END
////// divergence Lookback period #9
// get pivots
plFound9 = na(ta.pivotlow(osc, lbL9, lbR)) ? false : true
_inRange9(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL9 = osc[lbR] > ta.valuewhen(plFound9, osc[lbR], 1) and _inRange9(plFound9[1])
// Price: Lower Low
priceLL9 = low[lbR] < ta.valuewhen(plFound9, low[lbR], 1)
bullCond9 = plotBull and priceLL9 and oscHL9 and plFound9 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound9 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish', linewidth=2, color=bullCond9 ? bullColor : noneColor)
plotshape(bullCond9 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish 9 Label', text=' B9 ', style=shape.labelup, location=location.absolute, color=bullColor9, textcolor=textColor)
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL9 = osc[lbR] < ta.valuewhen(plFound9, osc[lbR], 1) and _inRange9(plFound9[1])
// Price: Higher Low
priceHL9 = low[lbR] > ta.valuewhen(plFound9, low[lbR], 1)
hiddenBullCond9 = plotHiddenBull and priceHL9 and oscLL9 and plFound9 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound9 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish', linewidth=2, color=hiddenBullCond9 ? hiddenBullColor : noneColor)
plotshape(hiddenBullCond9 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish 9 Label', text=' H B9 ', style=shape.labelup, location=location.absolute, color=bullColor9, textcolor=textColor)
//------------------------------------------------------------------------------
////// divergence Lookback period #9 END
////// divergence Lookback period #10
// get pivots
plFound10 = na(ta.pivotlow(osc, lbL10, lbR)) ? false : true
_inRange10(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL10 = osc[lbR] > ta.valuewhen(plFound10, osc[lbR], 1) and _inRange10(plFound10[1])
// Price: Lower Low
priceLL10 = low[lbR] < ta.valuewhen(plFound10, low[lbR], 1)
bullCond10 = plotBull and priceLL10 and oscHL10 and plFound10 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound10 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish', linewidth=2, color=bullCond10 ? bullColor : noneColor)
plotshape(bullCond10 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish 10 Label', text=' B10 ', style=shape.labelup, location=location.absolute, color=bullColor10, textcolor=textColor)
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL10 = osc[lbR] < ta.valuewhen(plFound10, osc[lbR], 1) and _inRange10(plFound10[1])
// Price: Higher Low
priceHL10 = low[lbR] > ta.valuewhen(plFound10, low[lbR], 1)
hiddenBullCond10 = plotHiddenBull and priceHL10 and oscLL10 and plFound10 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound10 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish', linewidth=2, color=hiddenBullCond10 ? hiddenBullColor : noneColor)
plotshape(hiddenBullCond10 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish 10 Label', text=' H B10 ', style=shape.labelup, location=location.absolute, color=bullColor10, textcolor=textColor)
//------------------------------------------------------------------------------
////// divergence Lookback period #10 END
////// divergence Lookback period #11
// get pivots
plFound11 = na(ta.pivotlow(osc, lbL11, lbR)) ? false : true
_inRange11(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL11 = osc[lbR] > ta.valuewhen(plFound11, osc[lbR], 1) and _inRange11(plFound11[1])
// Price: Lower Low
priceLL11 = low[lbR] < ta.valuewhen(plFound11, low[lbR], 1)
bullCond11 = plotBull and priceLL11 and oscHL11 and plFound11 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound11 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish', linewidth=2, color=bullCond11 ? bullColor : noneColor)
plotshape(bullCond11 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish 11 Label', text=' B11 ', style=shape.labelup, location=location.absolute, color=bullColor11, textcolor=textColor)
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL11 = osc[lbR] < ta.valuewhen(plFound11, osc[lbR], 1) and _inRange11(plFound11[1])
// Price: Higher Low
priceHL11 = low[lbR] > ta.valuewhen(plFound11, low[lbR], 1)
hiddenBullCond11 = plotHiddenBull and priceHL11 and oscLL11 and plFound11 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound11 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish', linewidth=2, color=hiddenBullCond11 ? hiddenBullColor : noneColor)
plotshape(hiddenBullCond11 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish 11 Label', text=' H B11 ', style=shape.labelup, location=location.absolute, color=bullColor11, textcolor=textColor)
//------------------------------------------------------------------------------
////// divergence Lookback period #11 END
////// divergence Lookback period #12
// get pivots
plFound12 = na(ta.pivotlow(osc, lbL12, lbR)) ? false : true
_inRange12(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL12 = osc[lbR] > ta.valuewhen(plFound12, osc[lbR], 1) and _inRange12(plFound12[1])
// Price: Lower Low
priceLL12 = low[lbR] < ta.valuewhen(plFound12, low[lbR], 1)
bullCond12 = plotBull and priceLL12 and oscHL12 and plFound12 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound12 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish', linewidth=2, color=bullCond12 ? bullColor : noneColor)
plotshape(bullCond12 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish 12 Label', text=' B12 ', style=shape.labelup, location=location.absolute, color=bullColor12, textcolor=textColor)
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL12 = osc[lbR] < ta.valuewhen(plFound12, osc[lbR], 1) and _inRange12(plFound12[1])
// Price: Higher Low
priceHL12 = low[lbR] > ta.valuewhen(plFound12, low[lbR], 1)
hiddenBullCond12 = plotHiddenBull and priceHL12 and oscLL12 and plFound12 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound12 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish', linewidth=2, color=hiddenBullCond12 ? hiddenBullColor : noneColor)
plotshape(hiddenBullCond12 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish 12 Label', text=' H B12 ', style=shape.labelup, location=location.absolute, color=bullColor12, textcolor=textColor)
//------------------------------------------------------------------------------
////// divergence Lookback period #12 END
////// divergence Lookback period #13
// get pivots
plFound13 = na(ta.pivotlow(osc, lbL13, lbR)) ? false : true
_inRange13(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL13 = osc[lbR] > ta.valuewhen(plFound13, osc[lbR], 1) and _inRange13(plFound13[1])
// Price: Lower Low
priceLL13 = low[lbR] < ta.valuewhen(plFound13, low[lbR], 1)
bullCond13 = plotBull and priceLL13 and oscHL13 and plFound13 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound13 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish', linewidth=2, color=bullCond13 ? bullColor : noneColor)
plotshape(bullCond13 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish 13 Label', text=' B13 ', style=shape.labelup, location=location.absolute, color=bullColor13, textcolor=textColor)
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL13 = osc[lbR] < ta.valuewhen(plFound13, osc[lbR], 1) and _inRange13(plFound13[1])
// Price: Higher Low
priceHL13 = low[lbR] > ta.valuewhen(plFound13, low[lbR], 1)
hiddenBullCond13 = plotHiddenBull and priceHL13 and oscLL13 and plFound13 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound13 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish', linewidth=2, color=hiddenBullCond13 ? hiddenBullColor : noneColor)
plotshape(hiddenBullCond13 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish 13 Label', text=' H B13 ', style=shape.labelup, location=location.absolute, color=bullColor13, textcolor=textColor)
//------------------------------------------------------------------------------
////// divergence Lookback period #13 END
////// divergence Lookback period #14
// get pivots
plFound14 = na(ta.pivotlow(osc, lbL14, lbR)) ? false : true
_inRange14(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL14 = osc[lbR] > ta.valuewhen(plFound14, osc[lbR], 1) and _inRange14(plFound14[1])
// Price: Lower Low
priceLL14 = low[lbR] < ta.valuewhen(plFound14, low[lbR], 1)
bullCond14 = plotBull and priceLL14 and oscHL14 and plFound14 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound14 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish', linewidth=2, color=bullCond14 ? bullColor : noneColor)
plotshape(bullCond14 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish 14 Label', text=' B14 ', style=shape.labelup, location=location.absolute, color=bullColor14, textcolor=textColor)
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL14 = osc[lbR] < ta.valuewhen(plFound14, osc[lbR], 1) and _inRange14(plFound14[1])
// Price: Higher Low
priceHL14 = low[lbR] > ta.valuewhen(plFound14, low[lbR], 1)
hiddenBullCond14 = plotHiddenBull and priceHL14 and oscLL14 and plFound14 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound14 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish', linewidth=2, color=hiddenBullCond14 ? hiddenBullColor : noneColor)
plotshape(hiddenBullCond14 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish 14 Label', text=' H B14 ', style=shape.labelup, location=location.absolute, color=bullColor14, textcolor=textColor)
//------------------------------------------------------------------------------
////// divergence Lookback period #14 END
////// divergence Lookback period #15
// get pivots
plFound15 = na(ta.pivotlow(osc, lbL15, lbR)) ? false : true
_inRange15(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL15 = osc[lbR] > ta.valuewhen(plFound15, osc[lbR], 1) and _inRange15(plFound15[1])
// Price: Lower Low
priceLL15 = low[lbR] < ta.valuewhen(plFound15, low[lbR], 1)
bullCond15 = plotBull and priceLL15 and oscHL15 and plFound15 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound15 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish', linewidth=2, color=bullCond15 ? bullColor : noneColor)
plotshape(bullCond15 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish 15 Label', text=' B15 ', style=shape.labelup, location=location.absolute, color=bullColor15, textcolor=textColor)
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL15 = osc[lbR] < ta.valuewhen(plFound15, osc[lbR], 1) and _inRange15(plFound15[1])
// Price: Higher Low
priceHL15 = low[lbR] > ta.valuewhen(plFound15, low[lbR], 1)
hiddenBullCond15 = plotHiddenBull and priceHL15 and oscLL15 and plFound15 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound15 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish', linewidth=2, color=hiddenBullCond15 ? hiddenBullColor : noneColor)
plotshape(hiddenBullCond15 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish 15 Label', text=' H B15 ', style=shape.labelup, location=location.absolute, color=bullColor15, textcolor=textColor)
//------------------------------------------------------------------------------
////// divergence Lookback period #15 END
////// divergence Lookback period #16
// get pivots
plFound16 = na(ta.pivotlow(osc, lbL16, lbR)) ? false : true
_inRange16(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL16 = osc[lbR] > ta.valuewhen(plFound16, osc[lbR], 1) and _inRange16(plFound16[1])
// Price: Lower Low
priceLL16 = low[lbR] < ta.valuewhen(plFound16, low[lbR], 1)
bullCond16 = plotBull and priceLL16 and oscHL16 and plFound16 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound16 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish', linewidth=2, color=bullCond16 ? bullColor : noneColor)
plotshape(bullCond16 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish 16 Label', text=' B16 ', style=shape.labelup, location=location.absolute, color=bullColor16, textcolor=textColor)
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL16 = osc[lbR] < ta.valuewhen(plFound16, osc[lbR], 1) and _inRange16(plFound16[1])
// Price: Higher Low
priceHL16 = low[lbR] > ta.valuewhen(plFound16, low[lbR], 1)
hiddenBullCond16 = plotHiddenBull and priceHL16 and oscLL16 and plFound16 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound16 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish', linewidth=2, color=hiddenBullCond16 ? hiddenBullColor : noneColor)
plotshape(hiddenBullCond16 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish 16 Label', text=' H B16 ', style=shape.labelup, location=location.absolute, color=bullColor16, textcolor=textColor)
//------------------------------------------------------------------------------
////// divergence Lookback period #16 END
////// divergence Lookback period #17
// get pivots
plFound17 = na(ta.pivotlow(osc, lbL17, lbR)) ? false : true
_inRange17(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL17 = osc[lbR] > ta.valuewhen(plFound17, osc[lbR], 1) and _inRange17(plFound17[1])
// Price: Lower Low
priceLL17 = low[lbR] < ta.valuewhen(plFound17, low[lbR], 1)
bullCond17 = plotBull and priceLL17 and oscHL17 and plFound17 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound17 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish', linewidth=2, color=bullCond17 ? bullColor : noneColor)
plotshape(bullCond17 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish 17 Label', text=' B17 ', style=shape.labelup, location=location.absolute, color=bullColor17, textcolor=textColor)
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL17 = osc[lbR] < ta.valuewhen(plFound17, osc[lbR], 1) and _inRange17(plFound17[1])
// Price: Higher Low
priceHL17 = low[lbR] > ta.valuewhen(plFound17, low[lbR], 1)
hiddenBullCond17 = plotHiddenBull and priceHL17 and oscLL17 and plFound17 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound17 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish', linewidth=2, color=hiddenBullCond17 ? hiddenBullColor : noneColor)
plotshape(hiddenBullCond17 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish 17 Label', text=' H B17 ', style=shape.labelup, location=location.absolute, color=bullColor17, textcolor=textColor)
//------------------------------------------------------------------------------
////// divergence Lookback period #17 END
////// divergence Lookback period #18
// get pivots
plFound18 = na(ta.pivotlow(osc, lbL18, lbR)) ? false : true
_inRange18(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL18 = osc[lbR] > ta.valuewhen(plFound18, osc[lbR], 1) and _inRange18(plFound18[1])
// Price: Lower Low
priceLL18 = low[lbR] < ta.valuewhen(plFound18, low[lbR], 1)
bullCond18 = plotBull and priceLL18 and oscHL18 and plFound18 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound18 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish', linewidth=2, color=bullCond18 ? bullColor : noneColor)
plotshape(bullCond18 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish 18 Label', text=' B18 ', style=shape.labelup, location=location.absolute, color=bullColor18, textcolor=textColor)
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL18 = osc[lbR] < ta.valuewhen(plFound18, osc[lbR], 1) and _inRange18(plFound18[1])
// Price: Higher Low
priceHL18 = low[lbR] > ta.valuewhen(plFound18, low[lbR], 1)
hiddenBullCond18 = plotHiddenBull and priceHL18 and oscLL18 and plFound18 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound18 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish', linewidth=2, color=hiddenBullCond18 ? hiddenBullColor : noneColor)
plotshape(hiddenBullCond18 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish 18 Label', text=' H B18 ', style=shape.labelup, location=location.absolute, color=bullColor18, textcolor=textColor)
//------------------------------------------------------------------------------
////// divergence Lookback period #18 END
////// divergence Lookback period #19
// get pivots
plFound19 = na(ta.pivotlow(osc, lbL19, lbR)) ? false : true
_inRange19(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL19 = osc[lbR] > ta.valuewhen(plFound19, osc[lbR], 1) and _inRange19(plFound19[1])
// Price: Lower Low
priceLL19 = low[lbR] < ta.valuewhen(plFound19, low[lbR], 1)
bullCond19 = plotBull and priceLL19 and oscHL19 and plFound19 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound19 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish', linewidth=2, color=bullCond19 ? bullColor : noneColor)
plotshape(bullCond19 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish 19 Label', text=' B19 ', style=shape.labelup, location=location.absolute, color=bullColor19, textcolor=textColor)
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL19 = osc[lbR] < ta.valuewhen(plFound19, osc[lbR], 1) and _inRange19(plFound19[1])
// Price: Higher Low
priceHL19 = low[lbR] > ta.valuewhen(plFound19, low[lbR], 1)
hiddenBullCond19 = plotHiddenBull and priceHL19 and oscLL19 and plFound19 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound19 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish', linewidth=2, color=hiddenBullCond19 ? hiddenBullColor : noneColor)
plotshape(hiddenBullCond19 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish 19 Label', text=' H B19 ', style=shape.labelup, location=location.absolute, color=bullColor19, textcolor=textColor)
//------------------------------------------------------------------------------
////// divergence Lookback period #19 END
////// divergence Lookback period #20
// get pivots
plFound20 = na(ta.pivotlow(osc, lbL20, lbR)) ? false : true
_inRange20(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL20 = osc[lbR] > ta.valuewhen(plFound20, osc[lbR], 1) and _inRange20(plFound20[1])
// Price: Lower Low
priceLL20 = low[lbR] < ta.valuewhen(plFound20, low[lbR], 1)
bullCond20 = plotBull and priceLL20 and oscHL20 and plFound20 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound20 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish', linewidth=2, color=bullCond20 ? bullColor : noneColor)
plotshape(bullCond20 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish 20 Label', text=' B20 ', style=shape.labelup, location=location.absolute, color=bullColor20, textcolor=textColor)
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL20 = osc[lbR] < ta.valuewhen(plFound20, osc[lbR], 1) and _inRange20(plFound20[1])
// Price: Higher Low
priceHL20 = low[lbR] > ta.valuewhen(plFound20, low[lbR], 1)
hiddenBullCond20 = plotHiddenBull and priceHL20 and oscLL20 and plFound20 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound20 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish', linewidth=2, color=hiddenBullCond20 ? hiddenBullColor : noneColor)
plotshape(hiddenBullCond20 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish 20 Label', text=' H B20 ', style=shape.labelup, location=location.absolute, color=bullColor20, textcolor=textColor)
//------------------------------------------------------------------------------
////// divergence Lookback period #20 END
////// divergence Lookback period #21
// get pivots
plFound21 = na(ta.pivotlow(osc, lbL21, lbR)) ? false : true
_inRange21(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL21 = osc[lbR] > ta.valuewhen(plFound21, osc[lbR], 1) and _inRange21(plFound21[1])
// Price: Lower Low
priceLL21 = low[lbR] < ta.valuewhen(plFound21, low[lbR], 1)
bullCond21 = plotBull and priceLL21 and oscHL21 and plFound21 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound21 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish', linewidth=2, color=bullCond21 ? bullColor : noneColor)
plotshape(bullCond21 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish 21 Label', text=' B21 ', style=shape.labelup, location=location.absolute, color=bullColor21, textcolor=textColor)
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL21 = osc[lbR] < ta.valuewhen(plFound21, osc[lbR], 1) and _inRange21(plFound21[1])
// Price: Higher Low
priceHL21 = low[lbR] > ta.valuewhen(plFound21, low[lbR], 1)
hiddenBullCond21 = plotHiddenBull and priceHL21 and oscLL21 and plFound21 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound21 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish', linewidth=2, color=hiddenBullCond21 ? hiddenBullColor : noneColor)
plotshape(hiddenBullCond21 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish 21 Label', text=' H B21 ', style=shape.labelup, location=location.absolute, color=bullColor21, textcolor=textColor)
//------------------------------------------------------------------------------
////// divergence Lookback period #21 END
////// divergence Lookback period #22
// get pivots
plFound22 = na(ta.pivotlow(osc, lbL22, lbR)) ? false : true
_inRange22(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL22 = osc[lbR] > ta.valuewhen(plFound22, osc[lbR], 1) and _inRange22(plFound22[1])
// Price: Lower Low
priceLL22 = low[lbR] < ta.valuewhen(plFound22, low[lbR], 1)
bullCond22 = plotBull and priceLL22 and oscHL22 and plFound22 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound22 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish', linewidth=2, color=bullCond22 ? bullColor : noneColor)
plotshape(bullCond22 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish 22 Label', text=' B22 ', style=shape.labelup, location=location.absolute, color=bullColor22, textcolor=textColor)
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL22 = osc[lbR] < ta.valuewhen(plFound22, osc[lbR], 1) and _inRange22(plFound22[1])
// Price: Higher Low
priceHL22 = low[lbR] > ta.valuewhen(plFound22, low[lbR], 1)
hiddenBullCond22 = plotHiddenBull and priceHL22 and oscLL22 and plFound22 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound22 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish', linewidth=2, color=hiddenBullCond22 ? hiddenBullColor : noneColor)
plotshape(hiddenBullCond22 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish 22 Label', text=' H B22 ', style=shape.labelup, location=location.absolute, color=bullColor22, textcolor=textColor)
//------------------------------------------------------------------------------
////// divergence Lookback period #22 END
////// divergence Lookback period #23
// get pivots
plFound23 = na(ta.pivotlow(osc, lbL23, lbR)) ? false : true
_inRange23(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL23 = osc[lbR] > ta.valuewhen(plFound23, osc[lbR], 1) and _inRange23(plFound23[1])
// Price: Lower Low
priceLL23 = low[lbR] < ta.valuewhen(plFound23, low[lbR], 1)
bullCond23 = plotBull and priceLL23 and oscHL23 and plFound23 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound23 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish', linewidth=2, color=bullCond23 ? bullColor : noneColor)
plotshape(bullCond23 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish 23 Label', text=' B23 ', style=shape.labelup, location=location.absolute, color=bullColor23, textcolor=textColor)
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL23 = osc[lbR] < ta.valuewhen(plFound23, osc[lbR], 1) and _inRange23(plFound23[1])
// Price: Higher Low
priceHL23 = low[lbR] > ta.valuewhen(plFound23, low[lbR], 1)
hiddenBullCond23 = plotHiddenBull and priceHL23 and oscLL23 and plFound23 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound23 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish', linewidth=2, color=hiddenBullCond23 ? hiddenBullColor : noneColor)
plotshape(hiddenBullCond23 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish 23 Label', text=' H B23 ', style=shape.labelup, location=location.absolute, color=bullColor23, textcolor=textColor)
//------------------------------------------------------------------------------
////// divergence Lookback period #23 END
////// divergence Lookback period #24
// get pivots
plFound24 = na(ta.pivotlow(osc, lbL24, lbR)) ? false : true
_inRange24(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL24 = osc[lbR] > ta.valuewhen(plFound24, osc[lbR], 1) and _inRange24(plFound24[1])
// Price: Lower Low
priceLL24 = low[lbR] < ta.valuewhen(plFound24, low[lbR], 1)
bullCond24 = plotBull and priceLL24 and oscHL24 and plFound24 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound24 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish', linewidth=2, color=bullCond24 ? bullColor : noneColor)
plotshape(bullCond24 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish 24 Label', text=' B24 ', style=shape.labelup, location=location.absolute, color=bullColor24, textcolor=textColor)
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL24 = osc[lbR] < ta.valuewhen(plFound24, osc[lbR], 1) and _inRange24(plFound24[1])
// Price: Higher Low
priceHL24 = low[lbR] > ta.valuewhen(plFound24, low[lbR], 1)
hiddenBullCond24 = plotHiddenBull and priceHL24 and oscLL24 and plFound24 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound24 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish', linewidth=2, color=hiddenBullCond24 ? hiddenBullColor : noneColor)
plotshape(hiddenBullCond24 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish 24 Label', text=' H B24 ', style=shape.labelup, location=location.absolute, color=bullColor24, textcolor=textColor)
//------------------------------------------------------------------------------
////// divergence Lookback period #24 END
////// divergence Lookback period #25
// get pivots
plFound25 = na(ta.pivotlow(osc, lbL25, lbR)) ? false : true
_inRange25(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL25 = osc[lbR] > ta.valuewhen(plFound25, osc[lbR], 1) and _inRange25(plFound25[1])
// Price: Lower Low
priceLL25 = low[lbR] < ta.valuewhen(plFound25, low[lbR], 1)
bullCond25 = plotBull and priceLL25 and oscHL25 and plFound25 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound25 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish', linewidth=2, color=bullCond25 ? bullColor : noneColor)
plotshape(bullCond25 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish 25 Label', text=' B25 ', style=shape.labelup, location=location.absolute, color=bullColor25, textcolor=textColor)
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL25 = osc[lbR] < ta.valuewhen(plFound25, osc[lbR], 1) and _inRange25(plFound25[1])
// Price: Higher Low
priceHL25 = low[lbR] > ta.valuewhen(plFound25, low[lbR], 1)
hiddenBullCond25 = plotHiddenBull and priceHL25 and oscLL25 and plFound25 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound25 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish', linewidth=2, color=hiddenBullCond25 ? hiddenBullColor : noneColor)
plotshape(hiddenBullCond25 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish 25 Label', text=' H B25 ', style=shape.labelup, location=location.absolute, color=bullColor25, textcolor=textColor)
//------------------------------------------------------------------------------
////// divergence Lookback period #25 END
////// divergence Lookback period #26
// get pivots
plFound26 = na(ta.pivotlow(osc, lbL26, lbR)) ? false : true
_inRange26(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL26 = osc[lbR] > ta.valuewhen(plFound26, osc[lbR], 1) and _inRange26(plFound26[1])
// Price: Lower Low
priceLL26 = low[lbR] < ta.valuewhen(plFound26, low[lbR], 1)
bullCond26 = plotBull and priceLL26 and oscHL26 and plFound26 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound26 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish 26', linewidth=2, color=bullCond26 ? bullColor : noneColor)
plotshape(bullCond26 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish 26 Label', text=' B26 ', style=shape.labelup, location=location.absolute, color=bullColor26, textcolor=textColor)
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL26 = osc[lbR] < ta.valuewhen(plFound26, osc[lbR], 1) and _inRange26(plFound26[1])
// Price: Higher Low
priceHL26 = low[lbR] > ta.valuewhen(plFound26, low[lbR], 1)
hiddenBullCond26 = plotHiddenBull and priceHL26 and oscLL26 and plFound26 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound26 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish 26', linewidth=2, color=hiddenBullCond26 ? hiddenBullColor : noneColor)
plotshape(hiddenBullCond26 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish 26 Label', text=' H B26 ', style=shape.labelup, location=location.absolute, color=bullColor26, textcolor=textColor)
//------------------------------------------------------------------------------
////// divergence Lookback period #26 END
////// divergence Lookback period #27
// get pivots
plFound27 = na(ta.pivotlow(osc, lbL27, lbR)) ? false : true
_inRange27(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL27 = osc[lbR] > ta.valuewhen(plFound27, osc[lbR], 1) and _inRange27(plFound27[1])
// Price: Lower Low
priceLL27 = low[lbR] < ta.valuewhen(plFound27, low[lbR], 1)
bullCond27 = plotBull and priceLL27 and oscHL27 and plFound27 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound27 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish 27', linewidth=2, color=bullCond27 ? bullColor : noneColor)
plotshape(bullCond27 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish 27 Label ', text=' B27 ', style=shape.labelup, location=location.absolute, color=bullColor27, textcolor=textColor)
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL27 = osc[lbR] < ta.valuewhen(plFound27, osc[lbR], 1) and _inRange27(plFound27[1])
// Price: Higher Low
priceHL27 = low[lbR] > ta.valuewhen(plFound27, low[lbR], 1)
hiddenBullCond27 = plotHiddenBull and priceHL27 and oscLL27 and plFound27 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound27 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish 27', linewidth=2, color=hiddenBullCond27 ? hiddenBullColor : noneColor)
plotshape(hiddenBullCond27 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish 27 Label', text=' H B27 ', style=shape.labelup, location=location.absolute, color=bullColor27, textcolor=textColor)
//------------------------------------------------------------------------------
////// divergence Lookback period #27 END
////// divergence Lookback period #28
// get pivots
plFound28 = na(ta.pivotlow(osc, lbL28, lbR)) ? false : true
_inRange28(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL28 = osc[lbR] > ta.valuewhen(plFound28, osc[lbR], 1) and _inRange28(plFound28[1])
// Price: Lower Low
priceLL28 = low[lbR] < ta.valuewhen(plFound28, low[lbR], 1)
bullCond28 = plotBull and priceLL28 and oscHL28 and plFound28 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound28 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish 28', linewidth=2, color=bullCond28 ? bullColor : noneColor)
plotshape(bullCond28 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish 28 Label ', text=' B28 ', style=shape.labelup, location=location.absolute, color=bullColor28, textcolor=textColor)
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL28 = osc[lbR] < ta.valuewhen(plFound28, osc[lbR], 1) and _inRange28(plFound28[1])
// Price: Higher Low
priceHL28 = low[lbR] > ta.valuewhen(plFound28, low[lbR], 1)
hiddenBullCond28 = plotHiddenBull and priceHL28 and oscLL28 and plFound28 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound28 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish 28', linewidth=2, color=hiddenBullCond28 ? hiddenBullColor : noneColor)
plotshape(hiddenBullCond28 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish 28 Label', text=' H B28 ', style=shape.labelup, location=location.absolute, color=bullColor28, textcolor=textColor)
//------------------------------------------------------------------------------
////// divergence Lookback period #28 END
////// divergence Lookback period #29
// get pivots
plFound29 = na(ta.pivotlow(osc, lbL29, lbR)) ? false : true
_inRange29(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL29 = osc[lbR] > ta.valuewhen(plFound29, osc[lbR], 1) and _inRange29(plFound29[1])
// Price: Lower Low
priceLL29 = low[lbR] < ta.valuewhen(plFound29, low[lbR], 1)
bullCond29 = plotBull and priceLL29 and oscHL29 and plFound29 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound29 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish 29', linewidth=2, color=bullCond29 ? bullColor : noneColor)
plotshape(bullCond29 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish 29 Label ', text=' B29 ', style=shape.labelup, location=location.absolute, color=bullColor29, textcolor=textColor)
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL29 = osc[lbR] < ta.valuewhen(plFound29, osc[lbR], 1) and _inRange29(plFound29[1])
// Price: Higher Low
priceHL29 = low[lbR] > ta.valuewhen(plFound29, low[lbR], 1)
hiddenBullCond29 = plotHiddenBull and priceHL29 and oscLL29 and plFound29 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound29 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish 29', linewidth=2, color=hiddenBullCond29 ? hiddenBullColor : noneColor)
plotshape(hiddenBullCond29 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish 29 Label', text=' H B29 ', style=shape.labelup, location=location.absolute, color=bullColor29, textcolor=textColor)
//------------------------------------------------------------------------------
////// divergence Lookback period #29 END
////// divergence Lookback period #30
// get pivots
plFound30 = na(ta.pivotlow(osc, lbL30, lbR)) ? false : true
_inRange30(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL30 = osc[lbR] > ta.valuewhen(plFound30, osc[lbR], 1) and _inRange30(plFound30[1])
// Price: Lower Low
priceLL30 = low[lbR] < ta.valuewhen(plFound30, low[lbR], 1)
bullCond30 = plotBull and priceLL30 and oscHL30 and plFound30 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound30 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish 30', linewidth=2, color=bullCond30 ? bullColor : noneColor)
plotshape(bullCond30 ? osc[lbR] : na, offset=-lbR, title='Regular Bullish 30 Label ', text=' B30 ', style=shape.labelup, location=location.absolute, color=bullColor30, textcolor=textColor)
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL30 = osc[lbR] < ta.valuewhen(plFound30, osc[lbR], 1) and _inRange30(plFound30[1])
// Price: Higher Low
priceHL30 = low[lbR] > ta.valuewhen(plFound30, low[lbR], 1)
hiddenBullCond30 = plotHiddenBull and priceHL30 and oscLL30 and plFound30 and RSIwasBelowOS and isWithinLongRanges and not enableonlyOneLB
//plot(plFound30 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish 30', linewidth=2, color=hiddenBullCond30 ? hiddenBullColor : noneColor)
plotshape(hiddenBullCond30 ? osc[lbR] : na, offset=-lbR, title='Hidden Bullish 30 Label', text=' H B30 ', style=shape.labelup, location=location.absolute, color=bullColor30, textcolor=textColor)
//------------------------------------------------------------------------------
////// divergence Lookback period #30 END
// combine divergence alerts intwo bullish and hidden
combibullCond = (bullCond1 or bullCond2 or bullCond3 or bullCond4 or bullCond5 or bullCond6 or bullCond7 or bullCond8 or bullCond9 or bullCond10 or bullCond11 or bullCond12 or bullCond13 or bullCond14 or bullCond15 or bullCond16 or bullCond17 or bullCond18 or bullCond19 or bullCond20 or bullCond21 or bullCond22 or bullCond23 or bullCond24 or bullCond25 or bullCond26 or bullCond27 or bullCond28 or bullCond29 or bullCond30)
combihiddenBullCond = (hiddenBullCond1 or hiddenBullCond2 or hiddenBullCond3 or hiddenBullCond4 or hiddenBullCond5 or hiddenBullCond6 or hiddenBullCond7 or hiddenBullCond8 or hiddenBullCond9 or hiddenBullCond10 or hiddenBullCond11 or hiddenBullCond12 or hiddenBullCond13 or hiddenBullCond14 or hiddenBullCond15 or hiddenBullCond16 or hiddenBullCond17 or hiddenBullCond18 or hiddenBullCond19 or hiddenBullCond20 or hiddenBullCond21 or hiddenBullCond22 or hiddenBullCond23 or hiddenBullCond24 or hiddenBullCond25 or hiddenBullCond26 or hiddenBullCond27 or hiddenBullCond28 or hiddenBullCond29 or hiddenBullCond30)
///////////////////////// Delays
// wait for a Oscillator and Oscillator EMA cross
oscCross = ((1 < (osc - oscema)) and (ta.barssince(combihiddenBullCond or combibullCond) <= oscCrosslookback) ) or not enableOscCross
// wait for price to go above ema
EmaIsBroken = (ta.ema(src, WaitForEmaBreakLen) < close) or not enableWaitForEmaBreak
///////////// check if price bounced before the alert
priceBounced = priceBounceNeeded < (ta.highest(high, 1) - ta.lowest(low, priceBounceNeededLbL)) or not enablepriceBounceNeeded
delaysEnabled = enablepriceBounceNeeded or enableOscCross or enableWaitForEmaBreak
DelayState = oscCross and EmaIsBroken and priceBounced
// dirty workaround to dont reprint the final hidden bull alert
HiddenBullAndBounce0 = DelayState and (ta.barssince(combihiddenBullCond) == 0)
HiddenBullAndBounce1 = DelayState and (ta.barssince(combihiddenBullCond) == 1) and not (ta.barssince(HiddenBullAndBounce0) < 1)
HiddenBullAndBounce2 = DelayState and (ta.barssince(combihiddenBullCond) == 2) and not (ta.barssince(HiddenBullAndBounce1 or HiddenBullAndBounce0) < 2)
HiddenBullAndBounce3 = DelayState and (ta.barssince(combihiddenBullCond) == 3) and not (ta.barssince(HiddenBullAndBounce1 or HiddenBullAndBounce0 or HiddenBullAndBounce2) < 3)
HiddenBullAndBounce4 = DelayState and (ta.barssince(combihiddenBullCond) == 4) and not (ta.barssince(HiddenBullAndBounce1 or HiddenBullAndBounce0 or HiddenBullAndBounce2 or HiddenBullAndBounce3) < 5)
HiddenBullAndBounce5 = DelayState and (ta.barssince(combihiddenBullCond) == 5) and not (ta.barssince(HiddenBullAndBounce1 or HiddenBullAndBounce0 or HiddenBullAndBounce2 or HiddenBullAndBounce3 or HiddenBullAndBounce4) < 6)
HiddenBullAndBounce6 = DelayState and (ta.barssince(combihiddenBullCond) == 6) and not (ta.barssince(HiddenBullAndBounce1 or HiddenBullAndBounce0 or HiddenBullAndBounce2 or HiddenBullAndBounce3 or HiddenBullAndBounce4 or HiddenBullAndBounce5) < 7)
HiddenBullAndBounce7 = DelayState and (ta.barssince(combihiddenBullCond) == 7) and not (ta.barssince(HiddenBullAndBounce1 or HiddenBullAndBounce0 or HiddenBullAndBounce2 or HiddenBullAndBounce3 or HiddenBullAndBounce4 or HiddenBullAndBounce5 or HiddenBullAndBounce6) < 8)
HiddenBullAndBounce8 = DelayState and (ta.barssince(combihiddenBullCond) == 8) and not (ta.barssince(HiddenBullAndBounce1 or HiddenBullAndBounce0 or HiddenBullAndBounce2 or HiddenBullAndBounce3 or HiddenBullAndBounce4 or HiddenBullAndBounce5 or HiddenBullAndBounce6 or HiddenBullAndBounce7) < 9)
HiddenBullAndBounce9 = DelayState and (ta.barssince(combihiddenBullCond) == 9) and not (ta.barssince(HiddenBullAndBounce1 or HiddenBullAndBounce0 or HiddenBullAndBounce2 or HiddenBullAndBounce3 or HiddenBullAndBounce4 or HiddenBullAndBounce5 or HiddenBullAndBounce6 or HiddenBullAndBounce7 or HiddenBullAndBounce8) < 10)
HiddenBullAndBounce10 = DelayState and (ta.barssince(combihiddenBullCond) == 10) and not (ta.barssince(HiddenBullAndBounce1 or HiddenBullAndBounce0 or HiddenBullAndBounce2 or HiddenBullAndBounce3 or HiddenBullAndBounce4 or HiddenBullAndBounce5 or HiddenBullAndBounce6 or HiddenBullAndBounce7 or HiddenBullAndBounce8 or HiddenBullAndBounce9) < 11)
FinalHiddenBullDelayAlert = delaysEnabled and (HiddenBullAndBounce1 or HiddenBullAndBounce0 or HiddenBullAndBounce2 or HiddenBullAndBounce3 or HiddenBullAndBounce4 or HiddenBullAndBounce5 or HiddenBullAndBounce6 or HiddenBullAndBounce7 or HiddenBullAndBounce8 or HiddenBullAndBounce9 or HiddenBullAndBounce10)
FinalHiddenBullAlert = false
FinalHiddenBullAlert2 = false
if delaysEnabled
FinalHiddenBullAlert := FinalHiddenBullDelayAlert
FinalHiddenBullAlert2 := false
if not delaysEnabled
FinalHiddenBullAlert := false
FinalHiddenBullAlert2 := combihiddenBullCond
// dirty workaround to dont reprint the final bull alert
BullAndBounce0 = DelayState and (ta.barssince(combibullCond) == 0)
BullAndBounce1 = DelayState and (ta.barssince(combibullCond) == 1) and not (ta.barssince(BullAndBounce0) < 2)
BullAndBounce2 = DelayState and (ta.barssince(combibullCond) == 2) and not (ta.barssince(BullAndBounce1 or BullAndBounce0) < 3)
BullAndBounce3 = DelayState and (ta.barssince(combibullCond) == 3) and not (ta.barssince(BullAndBounce1 or BullAndBounce0 or BullAndBounce2) < 4)
BullAndBounce4 = DelayState and (ta.barssince(combibullCond) == 4) and not (ta.barssince(BullAndBounce1 or BullAndBounce0 or BullAndBounce2 or BullAndBounce3) < 5)
BullAndBounce5 = DelayState and (ta.barssince(combibullCond) == 5) and not (ta.barssince(BullAndBounce1 or BullAndBounce0 or BullAndBounce2 or BullAndBounce3 or BullAndBounce4) < 6)
BullAndBounce6 = DelayState and (ta.barssince(combibullCond) == 6) and not (ta.barssince(BullAndBounce1 or BullAndBounce0 or BullAndBounce2 or BullAndBounce3 or BullAndBounce4 or BullAndBounce5) < 7)
BullAndBounce7 = DelayState and (ta.barssince(combibullCond) == 7) and not (ta.barssince(BullAndBounce1 or BullAndBounce0 or BullAndBounce2 or BullAndBounce3 or BullAndBounce4 or BullAndBounce5 or BullAndBounce6) < 8)
BullAndBounce8 = DelayState and (ta.barssince(combibullCond) == 8) and not (ta.barssince(BullAndBounce1 or BullAndBounce0 or BullAndBounce2 or BullAndBounce3 or BullAndBounce4 or BullAndBounce5 or BullAndBounce6 or BullAndBounce7) < 9)
BullAndBounce9 = DelayState and (ta.barssince(combibullCond) == 9) and not (ta.barssince(BullAndBounce1 or BullAndBounce0 or BullAndBounce2 or BullAndBounce3 or BullAndBounce4 or BullAndBounce5 or BullAndBounce6 or BullAndBounce7 or BullAndBounce8) < 10)
BullAndBounce10 = DelayState and (ta.barssince(combibullCond) == 10) and not (ta.barssince(BullAndBounce1 or BullAndBounce0 or BullAndBounce2 or BullAndBounce3 or BullAndBounce4 or BullAndBounce5 or BullAndBounce6 or BullAndBounce7 or BullAndBounce8 or BullAndBounce9) < 11)
FinalBullDelayAlert = delaysEnabled and (BullAndBounce1 or BullAndBounce0 or BullAndBounce2 or BullAndBounce3 or BullAndBounce4 or BullAndBounce5 or BullAndBounce6 or BullAndBounce7 or BullAndBounce8 or BullAndBounce9 or BullAndBounce10)
FinalBullAlert = false
FinalBullAlert2 = false
if delaysEnabled
FinalBullAlert := FinalBullDelayAlert
FinalBullAlert2 := false
if not delaysEnabled
FinalBullAlert := false
FinalBullAlert2 := combibullCond
///////////// check if price bounced before the alert END
// plot delay buy
plotshape(FinalBullAlert ? osc : na, offset=0, title='Buy ', text=" buy ", style=shape.labelup, location=location.absolute, color=color.lime, textcolor=textColor)
////////////////// Stop Loss
// Stop loss
enableSL = input.bool(true, title='enable Stop Loss', group='══════════ Stop Loss Settings ══════════')
whichSL = input.string(defval='use the low as SL', title='SL based on static % or based on the low', options=['use the low as SL', 'use the static % as SL'], group='══════════ Stop Loss Settings ══════════')
whichOffset = input.string(defval='use % as offset', title='choose offset from the low', options=['use $ as offset', 'use % as offset'], group='Stop Loss at the low')
lowPBuffer = input.float(0.35, title='SL Offset from the Low in %', group='Stop Loss at the low') / 100
lowDBuffer = input.float(100, title='SL Offset from the Low in $', group='Stop Loss at the low')
SlLowLookback = input.int(title='SL lookback for Low', defval=5, minval=1, maxval=50, group='Stop Loss at the low')
longSlLow = float(na)
if whichOffset == "use % as offset" and whichSL == "use the low as SL" and enableSL
longSlLow := ta.lowest(low, SlLowLookback) * (1 - lowPBuffer)
if whichOffset == "use $ as offset" and whichSL == "use the low as SL" and enableSL
longSlLow := ta.lowest(low, SlLowLookback) - lowDBuffer
//plot(longSlLow, title="stoploss", color=color.new(#00bcd4, 0))
// long settings - 🔥 uncomment the 6 lines below to disable the alerts and enable the backtester
longStopLoss = input.float(0.5, title='Stop Loss in %', group='static % Stop Loss', inline='Input 1') / 100
/////// Take profit
longTakeProfit1 = input.float(2, title='Take Profit in %', group='Take Profit', inline='Input 1') / 100
//longTakeProfit2 = input.float(2, title='25% Take Profit in %', group='Take Profit', inline='Input 1') / 100
//longTakeProfit3 = input.float(2, title='25% Take Profit in %', group='Take Profit', inline='Input 1') / 100
//longTakeProfit4 = input.float(2, title='25% Take Profit in %', group='Take Profit', inline='Input 1') / 100
////////////////// SL TP END
/////////////////// alerts
///////////////ver final alert variable
veryFinalAlert = FinalHiddenBullAlert2 or FinalHiddenBullAlert or FinalBullAlert or FinalBullAlert2
/////////////////// alerts
selectalertFreq = input.string(defval='once per bar close', title='Alert Options', options=['once per bar', 'once per bar close', 'all'], group='═══════════ alert settings ═══════════')
BuyAlertMessage = input.string(defval="Bullish Divergence detected, put your SL @", title='Buy Alert Message', group='═══════════ alert settings ═══════════')
enableSlMessage = input.bool(true, title='enable Stop Loss Value at the end of "buy Alert message"', group='═══════════ alert settings ═══════════')
AfterSLMessage = input.string(defval="", title='Buy Alert message after SL Value', group='═══════════ alert settings ═══════════')
alertFreq = selectalertFreq == "once per bar" ? alert.freq_once_per_bar : selectalertFreq == "once per bar close" ? alert.freq_once_per_bar_close : selectalertFreq == "all" ? alert.freq_all : na
if not enableSlMessage and veryFinalAlert
alert(str.tostring(BuyAlertMessage), alertFreq)
if enableSlMessage and veryFinalAlert
alert(str.tostring(BuyAlertMessage) + str.tostring(longSlLow) + str.tostring(AfterSLMessage), alertFreq)
if enableSlMessage
alert(str.tostring(BuyAlertMessage) + str.tostring(longSlLow) + str.tostring(AfterSLMessage), alertFreq)
alertcondition(veryFinalAlert, title='Bullish divergence', message='Bull Div {{ticker}}')
////////////////// Backtester
////////////////// Backtester input stuff
// Backtesting Range settings - 🔥 uncomment the 6 lines below to disable the alerts and enable the backtester
//startDate = input.int(title='Start Date', defval=1, minval=1, maxval=31, group='Backtesting range')
//startMonth = input.int(title='Start Month', defval=1, minval=1, maxval=12, group='Backtesting range')
//startYear = input.int(title='Start Year', defval=2016, minval=1800, maxval=2100, group='Backtesting range')
//endDate = input.int(title='End Date', defval=1, minval=1, maxval=31, group='Backtesting range')
//endMonth = input.int(title='End Month', defval=1, minval=1, maxval=12, group='Backtesting range')
//endYear = input.int(title='End Year', defval=2040, minval=1800, maxval=2100, group='Backtesting range')
////////////////// Backtester
// 🔥 uncomment the all lines below for the backtester and revert for alerts
shortTrading = false
longTrading = plotBull or plotHiddenBull
longTP1 = strategy.position_size > 0 ? strategy.position_avg_price * (1 + longTakeProfit1) : strategy.position_size < 0 ? strategy.position_avg_price * (1 - longTakeProfit1) : na
//longTP2 = strategy.position_size > 0 ? strategy.position_avg_price * (1 + longTakeProfit2) : strategy.position_size < 0 ? strategy.position_avg_price * (1 - longTakeProfit2) : na
//longTP3 = strategy.position_size > 0 ? strategy.position_avg_price * (1 + longTakeProfit3) : strategy.position_size < 0 ? strategy.position_avg_price * (1 - longTakeProfit3) : na
//longTP4 = strategy.position_size > 0 ? strategy.position_avg_price * (1 + longTakeProfit4) : strategy.position_size < 0 ? strategy.position_avg_price * (1 - longTakeProfit4) : na
longSL = strategy.position_size > 0 ? strategy.position_avg_price * (1 - longStopLoss) : strategy.position_size < 0 ? strategy.position_avg_price * (1 + longStopLoss) : na
strategy.risk.allow_entry_in(longTrading == true and shortTrading == true ? strategy.direction.all : longTrading == true ? strategy.direction.long : shortTrading == true ? strategy.direction.short : na)
strategy.entry('Bull', strategy.long, comment='B Long', when=FinalBullAlert or FinalBullAlert2)
strategy.entry('Bull', strategy.long, comment='HB Long', when=FinalHiddenBullAlert2 or FinalHiddenBullAlert)
// check which SL to use
if enableSL and whichSL == 'use the static % as SL'
strategy.exit(id='longTP-SL', from_entry='Bull', limit=longTP1, stop=longSL)
// strategy.exit(id='longTP-SL', qty_percent=25, from_entry='Bull', limit=longTP2, stop=longSlLow)
// strategy.exit(id='longTP-SL', qty_percent=25, from_entry='Bull', limit=longTP3, stop=longSlLow)
// strategy.exit(id='longTP-SL', qty_percent=25, from_entry='Bull', limit=longTP4, stop=longSlLow)
// get bars since last entry for the SL at low to work
barsSinceLastEntry()=>
strategy.opentrades > 0 ? (bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades-1)) : na
if enableSL and whichSL == 'use the low as SL' and ta.barssince(veryFinalAlert) < 2 and barsSinceLastEntry() < 2
strategy.exit(id='longTP-SL', from_entry='Bull', limit=longTP1, stop=longSlLow)
// strategy.exit(id='longTP-SL', qty_percent=25, from_entry='Bull', limit=longTP2, stop=longSlLow)
// strategy.exit(id='longTP-SL', qty_percent=25, from_entry='Bull', limit=longTP3, stop=longSlLow)
// strategy.exit(id='longTP-SL', qty_percent=25, from_entry='Bull', limit=longTP4, stop=longSlLow)
if not enableSL
strategy.exit(id='longTP-SL', from_entry='Bull', limit=longTP1)
// strategy.exit(id='longTP-SL', qty_percent=25, from_entry='Bull', limit=longTP2)
// strategy.exit(id='longTP-SL', qty_percent=25, from_entry='Bull', limit=longTP3)
// strategy.exit(id='longTP-SL', qty_percent=25, from_entry='Bull', limit=longTP4)
|
Three EMAs Trend-following Strategy (by Coinrule) | https://www.tradingview.com/script/7k9T1VNU-Three-EMAs-Trend-following-Strategy-by-Coinrule/ | Coinrule | https://www.tradingview.com/u/Coinrule/ | 198 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=4
strategy(shorttitle='Three EMAs Trend-following Strategy',title='Three EMAs Trend-following Strategy (by Coinrule)', overlay=true, initial_capital = 100, process_orders_on_close=true, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type=strategy.commission.percent, commission_value=0.1)
//Backtest dates
fromMonth = input(defval = 1, title = "From Month", type = input.integer, minval = 1, maxval = 12)
fromDay = input(defval = 1, title = "From Day", type = input.integer, minval = 1, maxval = 31)
fromYear = input(defval = 2020, title = "From Year", type = input.integer, minval = 1970)
thruMonth = input(defval = 1, title = "Thru Month", type = input.integer, minval = 1, maxval = 12)
thruDay = input(defval = 1, title = "Thru Day", type = input.integer, minval = 1, maxval = 31)
thruYear = input(defval = 2112, title = "Thru Year", type = input.integer, minval = 1970)
showDate = input(defval = true, title = "Show Date Range", type = input.bool)
start = timestamp(fromYear, fromMonth, fromDay, 00, 00) // backtest start window
finish = timestamp(thruYear, thruMonth, thruDay, 23, 59) // backtest finish window
window() => time >= start and time <= finish ? true : false // create function "within window of time"
ema_1 = ema(close, input(7))
ema_2 = ema(close, input(12))
ema_3 = ema(close, input(21))
Take_profit= ((input (4))/100)
longTakeProfit = strategy.position_avg_price * (1 + Take_profit)
length = input(20, "Length", minval = 2)
src = input(close, "Source")
factor = input(3.0, "Multiplier", minval = 0.25, step = 0.25)
volStop(src, atrlen, atrfactor) =>
var max = src
var min = src
var uptrend = true
var stop = 0.0
atrM = nz(atr(atrlen) * atrfactor, tr)
max := max(max, src)
min := min(min, src)
stop := nz(uptrend ? max(stop, max - atrM) : min(stop, min + atrM), src)
uptrend := src - stop >= 0.0
if uptrend != nz(uptrend[1], true)
max := src
min := src
stop := uptrend ? max - atrM : min + atrM
[stop, uptrend]
[vStop, uptrend] = volStop(src, length, factor)
go_long = crossover(close, ema_1) and crossover(close, ema_2) and crossover(close, ema_3)
closeLong = close > longTakeProfit or crossunder(close, vStop)
//Entry
strategy.entry(id="long", long = true, when = go_long and window())
//Exit
strategy.close("long", when = closeLong and window())
plot(vStop,"Vstop", color.black, linewidth=2)
plot(ema_1,"EMA Short", color.green, linewidth=1)
plot(ema_2,"EMA Mid", color.purple, linewidth=1)
plot(ema_3,"EMA Long", color.red, linewidth=1)
|
3x Supertrend and Stoch RSI | https://www.tradingview.com/script/Kls9JTiM/ | M3RZI | https://www.tradingview.com/u/M3RZI/ | 338 | strategy | 4 | MPL-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("3x Supertrend and Stoch RSI", overlay = true, max_bars_back = 1000)
//INPUTS
STATRLENGTH1 = input(10, title = "Fast Supertrend ATR Length", type = input.integer, group = "SUPERTREND SETTINGS")
STATRMULT1 = input(1, title = "Fast Supertrend ATR Multiplier", type = input.float, group = "SUPERTREND SETTINGS")
STATRLENGTH2 = input(11, title = "Medium Supertrend ATR Length", type = input.integer, group = "SUPERTREND SETTINGS")
STATRMULT2 = input(2, title = "Medium Supertrend ATR Multiplier", type = input.float, group = "SUPERTREND SETTINGS")
STATRLENGTH3 = input(12, title = "Slow Supertrend ATR Length", type = input.integer, group = "SUPERTREND SETTINGS")
STATRMULT3 = input(3, title = "Slow Supertrend ATR Multiplier", type = input.float, group = "SUPERTREND SETTINGS")
stochK = input(3, title = "K (Stochastic Fast)", type = input.integer, group = "STOCHASTIC RSI SETTINGS")
stochD = input(3, title = "D (Signal Line)", type = input.integer, group = "STOCHASTIC RSI SETTINGS")
rsiLength = input(14, title = "RSI Length", type = input.integer, group = "STOCHASTIC RSI SETTINGS")
stochLength = input(14, title = "Stochastic Length", type = input.integer, group = "STOCHASTIC RSI SETTINGS")
rsiSource = input(close, title = "RSI Source", type = input.source, group = "STOCHASTIC RSI SETTINGS")
stochRestrictions = input(false, title = "Restrict crosses to overbought/oversold territory", type = input.bool, group = "STOCHASTIC RSI SETTINGS")
overboughtLine = input(80, title = "Stochastic RSI Upper Band", type = input.integer, group = "STOCHASTIC RSI SETTINGS")
oversoldLine = input(20, title = "Stochastic RSI Lower Band", type = input.integer, group = "STOCHASTIC RSI SETTINGS")
EMALength = input(200, title = "EMA Length", type = input.integer, group = "EMA SETTINGS")
SLStrategy = input("ATR Based", title = "Stop Loss Strategy", options = ["ATR Based"],type = input.string, group = "POSITION EXIT SETTINGS")
SLATRLength = input(14, title = "Stop Loss ATR Length", type = input.integer, group = "POSITION EXIT SETTINGS")
SLATRMult = input(2.7, title = "Stop Loss ATR Multiplier", type = input.float, group = "POSITION EXIT SETTINGS")
TPStrategy = input("ATR Based", title = "Take Profit Strategy", options = ["ATR Based"],type = input.string, group = "POSITION EXIT SETTINGS")
TPATRLength = input(14, title = "Take Profit ATR Length", type = input.integer, group = "POSITION EXIT SETTINGS")
TPATRMult = input(1.6, title = "Take Profit ATR Multiplier", type = input.float, group = "POSITION EXIT SETTINGS")
alertLongCondition = input("", title = "Long Signal", type = input.string, group = "ALERT SETTINGS")
alertShortCondition = input("", title = "Short Signal", type = input.string, group = "ALERT SETTINGS")
alertLongProfit = input("", title = "Long Take Profit", type = input.string, group = "ALERT SETTINGS")
alertLongLoss = input("", title = "Long Stop Loss", type = input.string, group = "ALERT SETTINGS")
alertShortProfit = input("", title = "Short Take Profit", type = input.string, group = "ALERT SETTINGS")
alertShortLoss = input("", title = "Short Stop loss", type = input.string, group = "ALERT SETTINGS")
//SUPERTRENDS
[superTrend1,dir1] = supertrend(STATRMULT1,STATRLENGTH1)
[superTrend2,dir2] = supertrend(STATRMULT2,STATRLENGTH2)
[superTrend3,dir3] = supertrend(STATRMULT3,STATRLENGTH3)
directionST1 = dir1 == 1 and dir1[1] == 1 ? false : dir1 == -1 and dir1[1] == -1 ? true : na
directionST2 = dir2 == 1 and dir2[1] == 1 ? false : dir2 == -1 and dir2[1] == -1 ? true : na
directionST3 = dir3 == 1 and dir3[1] == 1 ? false : dir3 == -1 and dir3[1] == -1 ? true : na
//STOCH RSI
rsi = rsi(rsiSource, rsiLength)
k = sma(stoch(rsi, rsi, rsi, stochLength), stochK)
d = sma(k, stochD)
//EMA
ema = ema(close,EMALength)
//CONDITIONS LONG AND SHORT
var long = false
var longCondition = false
var short = false
var shortCondition = false
var drawing = false
var TP = 0.0
var SL = 0.0
var middle = 0.0
var initial = 0
stopSize = atr(SLATRLength) * SLATRMult
profitSize = atr(TPATRLength) * TPATRMult
longStop = close - stopSize
longProfit = close + profitSize
current = close
shortStop = close + stopSize
shortProfit = close - profitSize
barInitial = bar_index
if stochRestrictions
longCondition := close > ema and ((directionST1 == true and directionST2 == true) or (directionST2 == true and directionST3 == true)) and crossover(k,d) and k < oversoldLine and not long and not drawing
shortCondition := close < ema and ((directionST1 == false and directionST2 == false) or (directionST2 == false and directionST3 == false)) and crossunder(k,d) and k > overboughtLine and not short and not drawing
else
longCondition := close > ema and ((directionST1 == true and directionST2 == true) or (directionST2 == true and directionST3 == true)) and crossover(k,d) and not long and not drawing
shortCondition := close < ema and ((directionST1 == false and directionST2 == false) or (directionST2 == false and directionST3 == false)) and crossunder(k,d) and not short and not drawing
if longCondition
long := true
short := false
drawing := true
TP := longProfit
middle := current
SL := longStop
initial := barInitial
strategy.entry("Long", strategy.long, 10)
strategy.exit("Long exit","Long", limit = TP, stop = SL)
alert(alertLongCondition,alert.freq_once_per_bar_close)
//label.new(bar_index,low,text = "Long\nTP:"+tostring(TP)+"\nSL:"+tostring(SL)+"\nAbierto:"+tostring(current), yloc = yloc.belowbar, textcolor = color.white, color = color.green, size = size.small, style = label.style_label_up)
if shortCondition
short := true
long := false
drawing := true
TP := shortProfit
middle := current
SL := shortStop
initial := barInitial
strategy.entry("Short", strategy.short, 10)
strategy.exit("Short exit","Short",limit = TP , stop = SL)
alert(alertShortCondition,alert.freq_once_per_bar_close)
//label.new(bar_index,high,text = "Short\nTP:"+tostring(TP)+"\nSL:"+tostring(SL)+"\nAbierto:"+tostring(current), yloc = yloc.abovebar, textcolor = color.white, color = color.red, size = size.small, style = label.style_label_down)
if long and (high[1] >= TP or low[1] <= SL)
drawing := false
long := false
if high[1] >= TP
label.new(bar_index[int((bar_index - initial)/2)],TP, text = "Win (Long)", textcolor = color.white, color = color.green, size = size.small, style = label.style_label_down)
alert(alertLongProfit,alert.freq_once_per_bar_close)
else
label.new(bar_index[int((bar_index - initial)/2)],SL, text = "Lose (Long)", textcolor = color.white, color = color.red, size = size.small, style = label.style_label_up)
alert(alertLongLoss,alert.freq_once_per_bar_close)
if short and (low[1] <= TP or high[1] >= SL)
drawing := false
short := false
if low[1] <= TP
label.new(bar_index[int((bar_index - initial)/2)],TP, text = "Win (short)", textcolor = color.white, color = color.green, size = size.small, style = label.style_label_up)
alert(alertShortProfit,alert.freq_once_per_bar_close)
else
label.new(bar_index[int((bar_index - initial)/2)],SL, text = "Lose (short)", textcolor = color.white, color = color.red, size = size.small, style = label.style_label_down)
alert(alertShortLoss,alert.freq_once_per_bar_close)
//DRAWING
plotshape(longCondition, title = "Long Signal", location=location.belowbar, style=shape.labelup, color=color.green, textcolor=color.white, size=size.small, text="Long")
plotshape(shortCondition, title = "Short Signal", location=location.abovebar, style=shape.labeldown, color=color.red, textcolor=color.white, size=size.small, text="Short")
profitLine = plot(drawing and drawing[1] ? TP : na, title = "Take profit", color = color.green, style = plot.style_linebr)
currentLine =plot(drawing and drawing[1] ? middle : na, title = "Middle Line", color = color.white, style = plot.style_linebr)
lossLine = plot(drawing and drawing[1] ? SL : 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(superTrend1, title = "Fast Supertrend", color = dir1 == 1 and dir1[1] == 1 ? color.red : dir1 == -1 and dir1[1] == -1 ? color.green : na)
plot(superTrend2, title = "Medium Supertrend", color = dir2 == 1 and dir2[1] == 1 ? color.red : dir2 == -1 and dir2[1] == -1 ? color.green : na)
plot(superTrend3, title = "Slow Supertrend", color = dir3 == 1 and dir3[1] == 1 ? color.red : dir3 == -1 and dir3[1] == -1 ? color.green : na)
plot(ema, title = "EMA",color = color.yellow)
//plot(k, color = color.blue)
//plot(d, color = color.orange)
//h1 = hline(80)
//h2 = hline(20)
//fill(h1,h2, color = color.new(color.purple,60))
|
Kaufman's Efficiency Ratio Strategy [KL] | https://www.tradingview.com/script/WRhJ1RJb-Kaufman-s-Efficiency-Ratio-Strategy-KL/ | DojiEmoji | https://www.tradingview.com/u/DojiEmoji/ | 184 | 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 (kevinhhl)
//@version=5
strategy("[KL] Eff. Ratio Strategy", overlay=true, pyramiding=1, initial_capital=1000000000)
var string GROUP_ALERT = "Alerts"
var string GROUP_SL = "Stop loss"
var string GROUP_ORDER = "Order size"
var string GROUP_TP = "Profit taking"
var string GROUP_HORIZON = "Time horizon of backtests"
var string GROUP_ER = "Main Signal: Kaufman's Eff. Ratio"
var string ENUM_LONG = "LONG"
var string LONG_MSG_ENTER = input.string("Long entered", title="Alert MSG for buying (Long position)", group=GROUP_ALERT)
var string LONG_MSG_EXIT = input.string("Long closed", title="Alert MSG for closing (Long position)", group=GROUP_ALERT)
USE_SHORT = input(false, title="Enter into short positions", group=GROUP_ALERT)
ENUM_SHORT = "SHORT"
SHORT_MSG_ENTER = input.string("Short entered", title="Alert MSG for selling (Short position)")
SHORT_MSG_EXIT = input.string("Short covered", title="Alert MSG for covering (Short position)")
backtest_timeframe_start = input.time(defval=timestamp("01 Apr 2020 13:30 +0000"), title="Backtest Start Time", group=GROUP_HORIZON)
USE_ENDTIME = input.bool(false, title="Define backtest end-time", group=GROUP_HORIZON, tooltip="If false, will test up to most recent candle")
backtest_timeframe_end = input.time(defval=timestamp("19 Apr 2021 19:30 +0000"), title="Backtest End Time (if checked above)", group=GROUP_HORIZON)
within_timeframe = time >= backtest_timeframe_start and (time <= backtest_timeframe_end or not USE_ENDTIME)
// Kaufman"s efficiency ratio {
er_lookbackperiod = input.int(10, title="Lookback period", group=GROUP_ER)
kaufman_ER(src, len) =>
total_abs_chng = float(0) // [B]
for i = 1 to len by 1
total_abs_chng := total_abs_chng + math.abs(src[i - 1] - src[i])
total_abs_chng
net_chng = src - src[len] // [A]
er = net_chng / total_abs_chng * 100 // = ([A]/[B]) * 100
er
ER = kaufman_ER(close, er_lookbackperiod)
// Removed: Confirmation of ER being low/med/high; through backtesting, noticed it's better to simply use "entry_signal_long = ER > 0"
// ER_bar = ta.sma(math.abs(ER), er_lookbackperiod)
// ER_sigma = ta.stdev(math.abs(ER), er_lookbackperiod)
// ER_std_err = ER_sigma / math.pow(er_lookbackperiod, 0.5)
// ER_sigma_mult = input.float(1.0, "stdev multiplier", tooltip="For determining low/medium/high ER.", group=GROUP_ER)
// dynamic_low = ER_bar - ER_sigma * ER_sigma_mult * ER_std_err
// dynamic_high = ER_bar + ER_sigma * ER_sigma_mult * ER_std_err
// ER_is_low = math.abs(ER) <= dynamic_low
// ER_is_mid = math.abs(ER) > dynamic_low and math.abs(ER) < dynamic_high
// ER_is_high = math.abs(ER) >= dynamic_high
// } end of block: Kaufman"s efficiency ratio
// Signals for entry
entry_signal_long = ER > 0
entry_signal_short = ER < 0 and ta.tr > ta.atr(14) and volume > ta.sma(volume, 5) and USE_SHORT
// Portfolio mgt
pcnt_alloc = input.int(5, title="Allocation (%) of portfolio into this security", tooltip="Assume no rebalancing", minval=0, maxval=100, group=GROUP_ORDER) / 100
// Trailing stop loss ("TSL") {
tsl_multi = input.float(2.0, title="ATR Multiplier for trailing stoploss", group=GROUP_SL)
SL_buffer = ta.atr(input.int(14, title="Length of ATR for trailing stoploss", group=GROUP_SL)) * tsl_multi
TSL_source_long = low
TSL_source_short = high
var stop_loss_price_long = float(0)
var stop_loss_price_short = float(9999999999)
var pos_opened_long = false
var pos_opened_short = false
stop_loss_price_long := pos_opened_long ? math.max(stop_loss_price_long, TSL_source_long - SL_buffer) : TSL_source_long - SL_buffer
stop_loss_price_short := pos_opened_short ? math.min(stop_loss_price_short, TSL_source_short + SL_buffer) : TSL_source_short + SL_buffer
// } end of block: Trailing stop loss
// Profit taking
var int tp_count_long = 0 // counts how many levels of profits had been taken during holding period; resets when position size becomes zero
var int tp_count_short = 0
var float initial_order_size = 0 // to be divided by 3, then math.floor'ed to determine size of disposal
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)
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)
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)
// MAIN: {
var float initial_entry_p = float(0) // initial entry price
var float risk_amt = float(0) // initial entry price minus initial stop loss price
// (1) Taking profits at user defined target levels relative to risked amount (i.e 1R, 2R, 3R)
if not entry_signal_long
if tp_count_long == 0 and close >= strategy.position_avg_price + (FIRST_LVL_PROFIT * risk_amt)
strategy.close(ENUM_LONG, comment="TP lvl1", qty=math.floor(initial_order_size / 3))
tp_count_long := tp_count_long + 1
else if tp_count_long == 1 and close >= strategy.position_avg_price + (SECOND_LVL_PROFIT * risk_amt)
strategy.close(ENUM_LONG, comment="TP lvl2", qty=math.floor(initial_order_size / 3))
tp_count_long := tp_count_long + 1
else if tp_count_long == 2 and close >= strategy.position_avg_price + (THIRD_LVL_PROFIT * risk_amt)
strategy.close(ENUM_LONG, comment="TP lvl3", qty=math.floor(initial_order_size / 3))
tp_count_long := tp_count_long + 1
if not entry_signal_short
if tp_count_short == 0 and close <= strategy.position_avg_price + (-FIRST_LVL_PROFIT * risk_amt)
strategy.close(ENUM_SHORT, comment="TP lvl1", qty=math.floor(initial_order_size / 3))
tp_count_short := tp_count_short + 1
else if tp_count_short == 1 and close <= strategy.position_avg_price + (-SECOND_LVL_PROFIT * risk_amt)
strategy.close(ENUM_SHORT, comment="TP lvl2", qty=math.floor(initial_order_size / 3))
tp_count_short := tp_count_short + 1
else if tp_count_short == 2 and close <= strategy.position_avg_price + (-THIRD_LVL_PROFIT * risk_amt)
strategy.close(ENUM_SHORT, comment="TP lvl3", qty=math.floor(initial_order_size / 3))
tp_count_short := tp_count_short + 1
// (2) States update: pos_opened_long, pos_opened_short
if pos_opened_long and TSL_source_long <= stop_loss_price_long
pos_opened_long := false
alert(LONG_MSG_EXIT, alert.freq_once_per_bar)
strategy.close(ENUM_LONG, comment=close < strategy.position_avg_price ? "stop loss" : "take profit")
if pos_opened_short and (TSL_source_short >= stop_loss_price_short)
pos_opened_short := false
alert(SHORT_MSG_EXIT, alert.freq_once_per_bar)
strategy.close(ENUM_SHORT, comment=close > strategy.position_avg_price ? "stop loss" : "take profit")
// (3) Update the stoploss to latest trailing amt.
if pos_opened_long
strategy.exit(ENUM_LONG, stop=stop_loss_price_long, comment="SL")
if pos_opened_short
strategy.exit(ENUM_SHORT, stop=stop_loss_price_short, comment="SL")
// (4) INITIAL ENTRY:
if within_timeframe and entry_signal_long
pos_opened_long := true
alert(LONG_MSG_ENTER, alert.freq_once_per_bar)
initial_order_size := math.floor(pcnt_alloc * strategy.equity / close)
strategy.entry(ENUM_LONG, strategy.long, comment="long", qty=initial_order_size)
risk_amt := SL_buffer // for taking profits at 1R, 2R, and 3R
initial_entry_p := close // ""
if within_timeframe and entry_signal_short
pos_opened_short := true
alert(SHORT_MSG_ENTER, alert.freq_once_per_bar)
strategy.entry(ENUM_SHORT, strategy.short, comment="short")
// Plotting:
TSL_transp_long = pos_opened_long and within_timeframe ? 0 : 100
TSL_transp_short = pos_opened_short and within_timeframe ? 0 : 100
plot(stop_loss_price_long, color=color.new(color.green, TSL_transp_long))
plot(stop_loss_price_short, color=color.new(color.red, TSL_transp_short))
// CLEAN UP: Setting variables back to default values once no longer in use
if ta.change(strategy.position_size) and strategy.position_size == 0
risk_amt := float(0)
initial_entry_p := float(0)
initial_order_size := 0
pos_opened_long := false
pos_opened_short := false
if not pos_opened_long
stop_loss_price_long := float(0)
tp_count_long := 0
if not pos_opened_short
stop_loss_price_short := float(9999999999)
tp_count_short := 0
// } end of MAIN block
|
Volume and Moving average,will this model working in real-trade? | https://www.tradingview.com/script/FSrXNpiW/ | Ayden_C | https://www.tradingview.com/u/Ayden_C/ | 177 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © KAIST291
//@version=4
strategy("prototype",initial_capital=1,commission_type=strategy.commission.percent,commission_value=0.1, format=format.volume, precision=0,overlay=true)
// SETTING //
length1=input(1)
length3=input(3)
length7=input(7)
length14=input(14)
length20=input(20)
length60=input(60)
length120=input(120)
ma1= sma(close,length1)
ma3= sma(close,length3)
ma7= sma(close,length7)
ma14=sma(close,length14)
ma20=sma(close,length20)
ma60=sma(close,length60)
ma120=sma(close,length120)
rsi=rsi(close,14)
// BUYING VOLUME AND SELLING VOLUME //
BV = iff( (high==low), 0, volume*(close-low)/(high-low))
SV = iff( (high==low), 0, volume*(high-close)/(high-low))
vol = iff(volume > 0, volume, 1)
dailyLength = input(title = "Daily MA length", type = input.integer, defval = 50, minval = 1, maxval = 100)
weeklyLength = input(title = "Weekly MA length", type = input.integer, defval = 10, minval = 1, maxval = 100)
//-----------------------------------------------------------
Davgvol = sma(volume, dailyLength)
Wavgvol = sma(volume, weeklyLength)
//-----------------------------------------------------------
length = input(20, minval=1)
src = input(close, title="Source")
mult = input(2.0, minval=0.001, maxval=50, title="StdDev")
mult2= input(1.5, minval=0.001, maxval=50, title="exp")
mult3= input(1.0, minval=0.001, maxval=50, title="exp1")
basis = sma(src, length)
dev = mult * stdev(src, length)
upper = basis + dev
lower = basis - dev
dev2= mult2 * stdev(src, length)
Supper= basis + dev2
Slower= basis - dev2
dev3= mult3 * stdev(src, length)
upper1= basis + dev3
lower1= basis - dev3
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))
//----------------------------------------------------
exit=(close-strategy.position_avg_price / strategy.position_avg_price*100)
bull=(close>Supper and high > upper and BV>SV and BV>Davgvol)
bull2=(BV>SV and BV>Davgvol)
bux =(close<Supper and close>Slower and volume<Wavgvol)
bear=(close<Slower and close<lower and SV>BV and SV>Wavgvol)
hi=highest(exit,10)
imInATrade = strategy.position_size != 0
highestPriceAfterEntry = valuewhen(imInATrade, high, 0)
// STRATEGY LONG //
if (bull and close>ma3 and ma20>ma60 and rsi<75)
strategy.entry("Long",strategy.long,0.1)
if (strategy.position_avg_price*1.05<close)
strategy.close("Long",1)
else if (highestPriceAfterEntry*0.999<close and close>strategy.position_avg_price*1.002)
strategy.close("Long",1)
else if (highestPriceAfterEntry*0.997<close and close>strategy.position_avg_price*1.002)
strategy.close("Long",1)
else if (highestPriceAfterEntry*0.995<close and close>strategy.position_avg_price*1.002)
strategy.close("Long",1)
else if (strategy.openprofit < strategy.position_avg_price*0.9-close)
strategy.close("Long",1)
else if (strategy.position_avg_price*0.9 > close)
strategy.close("Long",1)
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
if (bear and close<ma3 and crossunder(ma60,ma120))
strategy.entry("Short",strategy.short,0.1)
if (strategy.position_avg_price*0.95>close)
strategy.close("Short",1)
|
Volatility Stop Strategy (by Coinrule) | https://www.tradingview.com/script/SYICP93E-Volatility-Stop-Strategy-by-Coinrule/ | Coinrule | https://www.tradingview.com/u/Coinrule/ | 173 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=4
strategy(shorttitle='Volatility Stop Strategy',title='Volatility Stop Strategy (by Coinrule)', overlay=true, initial_capital = 100, process_orders_on_close=true, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type=strategy.commission.percent, commission_value=0.1)
// Works better on 3h, 1h, 2h, 4h
// Best time frame 2H
//Backtest dates
fromMonth = input(defval = 1, title = "From Month", type = input.integer, minval = 1, maxval = 12)
fromDay = input(defval = 1, title = "From Day", type = input.integer, minval = 1, maxval = 31)
fromYear = input(defval = 2021, 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"
length = input(20, "Length", minval = 2)
src = input(close, "Source")
factor = input(3.0, "vStop Multiplier", minval = 0.25, step = 0.25)
volStop(src, atrlen, atrfactor) =>
var max = src
var min = src
var uptrend = true
var stop = 0.0
atrM = nz(atr(atrlen) * atrfactor, tr)
max := max(max, src)
min := min(min, src)
stop := nz(uptrend ? max(stop, max - atrM) : min(stop, min + atrM), src)
uptrend := src - stop >= 0.0
if uptrend != nz(uptrend[1], true)
max := src
min := src
stop := uptrend ? max - atrM : min + atrM
[stop, uptrend]
[vStop, uptrend] = volStop(src, length, factor)
//Entry
strategy.entry(id="long", long = true, when = crossover(close, vStop) and window())
//Exit
strategy.close("long", when = crossunder(close, vStop))
plot(vStop,"Vstop", color.black, linewidth=2)
|
Bollinger band & Volume based strategy V2 | https://www.tradingview.com/script/P3ujZzmY/ | Ayden_C | https://www.tradingview.com/u/Ayden_C/ | 186 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © KAIST291
//@version=4
initial_capital=1000
strategy("prototype", overlay=true,default_qty_type=strategy.cash,default_qty_value=500,commission_type=strategy.commission.percent,commission_value=0.04)
Periods = input(title="ATR Period", type=input.integer, defval=10)//sefval원래값이10이였음(이평선 일)
src1 = input(hl2, title="Source")
Multiplier = input(title="ATR Multiplier", type=input.float, step=0.1, defval=3.0)
changeATR= input(title="Change ATR Calculation Method ?", type=input.bool, defval=true)
showsignals = input(title="Show Buy/Sell Signals ?", type=input.bool, defval=true)
highlighting = input(title="Highlighter On/Off ?", type=input.bool, defval=true)
atr2 = sma(tr, Periods)
atr= changeATR ? atr(Periods) : atr2
up=src1-(Multiplier*atr)
up1 = nz(up[1],up)
up := close[1] > up1 ? max(up,up1) : up
dn=src1+(Multiplier*atr)
dn1 = nz(dn[1], dn)
dn := close[1] < dn1 ? min(dn, dn1) : dn
trend = 1
trend := nz(trend[1], trend)
trend := trend == -1 and close > dn1 ? 1 : trend == 1 and close < up1 ? -1 : trend
upPlot = plot(trend == 1 ? up : na, title="Up Trend", style=plot.style_linebr, linewidth=2, color=color.green)
buySignal = trend == 1 and trend[1] == -1
plotshape(buySignal ? up : na, title="UpTrend Begins", location=location.absolute, style=shape.circle, size=size.tiny, color=color.green, transp=0)
plotshape(buySignal and showsignals ? up : na, title="Buy", text="Buy", location=location.absolute, style=shape.labelup, size=size.tiny, color=color.green, textcolor=color.white, transp=0)
dnPlot = plot(trend == 1 ? na : dn, title="Down Trend", style=plot.style_linebr, linewidth=2, color=color.red)
sellSignal = trend == -1 and trend[1] == 1
plotshape(sellSignal ? dn : na, title="DownTrend Begins", location=location.absolute, style=shape.circle, size=size.tiny, color=color.red, transp=0)
plotshape(sellSignal and showsignals ? dn : na, title="Sell", text="Sell", location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.red, textcolor=color.white, transp=0)
length1=input(1)
length3=input(3)
length7=input(7)
length9=input(9)
length14=input(14)
length20=input(20)
length60=input(60)
length120=input(120)
ma1= sma(close,length1)
ma3= sma(close,length3)
ma7= sma(close,length7)
ma9= sma(close,length9)
ma14=sma(close,length14)
ma20=sma(close,length20)
ma60=sma(close,length60)
ma120=sma(close,length120)
rsi=rsi(close,14)
// BUYING VOLUME AND SELLING VOLUME //
BV = iff( (high==low), 0, volume*(close-low)/(high-low))
SV = iff( (high==low), 0, volume*(high-close)/(high-low))
vol = iff(volume > 0, volume, 1)
dailyLength = input(title = "Daily MA length", type = input.integer, defval = 50, minval = 1, maxval = 100)
weeklyLength = input(title = "Weekly MA length", type = input.integer, defval = 10, minval = 1, maxval = 100)
//-----------------------------------------------------------
Davgvol = sma(volume, dailyLength)
Wavgvol = sma(volume, weeklyLength)
//-----------------------------------------------------------
length = input(20, minval=1)
src = input(close, title="Source")
mult = input(2.0, minval=0.001, maxval=50, title="StdDev")
mult2= input(1.5, minval=0.001, maxval=50, title="exp")
mult3= input(1.0, minval=0.001, maxval=50, title="exp1")
mult4= input(2.5, minval=0.001, maxval=50, title="exp2")
basis = sma(src, length)
dev = mult * stdev(src, length)
upper = basis + dev
lower = basis - dev
dev2= mult2 * stdev(src, length)
Supper= basis + dev2
Slower= basis - dev2
dev3= mult3 * stdev(src, length)
upper1= basis + dev3
lower1= basis - dev3
dev4= mult4 * stdev(src, length)
upper2=basis + dev4
lower2=basis - dev4
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))
//----------------------------------------------------
exit=(close-strategy.position_avg_price / strategy.position_avg_price*100)
bull=( BV>SV and BV>Davgvol)
bull2=(BV>SV and BV>Davgvol)
bux =(close>Supper and close>Slower and volume<Davgvol)
bear=(SV>BV and SV>Davgvol)
con=(BV>Wavgvol and rsi>80)
imInATrade = strategy.position_size != 0
highestPriceAfterEntry = valuewhen(imInATrade, high, 0)
//////////////////////////////////////////////////////////////////////////////////
sec=((open[1]-close[1])/(high[1]-low[1]))
wgt=1-sec
longcondition = (low+wgt)<(open)
shortcondition= (low+wgt)>(open)
// STRATEGY LONG //
if (bull and open>upper1 and open>Supper and open>upper and (trend == 1 ? up : na) and longcondition)
strategy.entry("Long",strategy.long)
//////////////////////////////////////////////////////////////////////////////////
if (strategy.openprofit>5)
strategy.close("Long")
else if (rsi>80 and strategy.position_avg_price*1.004<close)
strategy.close("Long")
else if (close < strategy.position_avg_price*0.91)
strategy.close("Long")
else if (open>upper and strategy.position_avg_price*1.004<close)
strategy.close("Long")
//////////////////////////////////////////////////////////////////////////////////
if (strategy.position_size>0 and (trend == 1 ? na : dn))
strategy.close("Long")
//////////////////////////////////////////////////////////////////////////////////
if (low<ma20 and low<lower1 and close<Slower and crossunder(ma60,ma120)and bear)
strategy.entry("Short",strategy.short)
else if (ma3<ma9 and ma9<ma20 and ma20<ma60 and bear and (trend == 1 ? na : dn) and high<ma20 and close<lower1 and high<Slower and rsi>30)
strategy.entry("Short",strategy.short)
if (strategy.openprofit>10)
strategy.close("Short")
else if (rsi<20 and close<strategy.position_avg_price*0.996)
strategy.close("Short")
else if (high<lower and close<strategy.position_avg_price*0.996)
strategy.close("Short")
else if (strategy.openprofit < strategy.position_avg_price*0.92-close)
strategy.close("Short")
else if (strategy.position_size<0 and (trend == 1 ? up : na))
strategy.close("Short")
else if (open<lower and close<strategy.position_avg_price*0.996)
strategy.close("Short") |
Cumulative RSI Strategy | https://www.tradingview.com/script/nI9Csm8g-Cumulative-RSI-Strategy/ | TradeAutomation | https://www.tradingview.com/u/TradeAutomation/ | 1,308 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// @version=5
// Author = TradeAutomation
strategy(title="Cumulative RSI Strategy", shorttitle="CRSI Strategy", process_orders_on_close=true, overlay=true, commission_type=strategy.commission.cash_per_contract, commission_value=.0035, slippage = 1, margin_long = 75, initial_capital = 25000, default_qty_type=strategy.percent_of_equity, default_qty_value=110)
// Cumulative RSI Indicator Calculations //
rlen = input.int(title="RSI Length", defval=3, minval=1)
cumlen = input(3, "RSI Cumulation Length")
rsi = ta.rsi(close, rlen)
cumRSI = math.sum(rsi, cumlen)
ob = (100*cumlen*input(94, "Oversold Level")*.01)
os = (100*cumlen*input(20, "Overbought Level")*.01)
// Operational Function //
TrendFilterInput = input(false, "Only Trade When Price is Above EMA?")
ema = ta.ema(close, input(100, "EMA Length"))
TrendisLong = (close>ema)
plot(ema)
// Backtest Timeframe Inputs //
startDate = input.int(title="Start Date", defval=1, minval=1, maxval=31)
startMonth = input.int(title="Start Month", defval=1, minval=1, maxval=12)
startYear = input.int(title="Start Year", defval=2010, minval=1950, maxval=2100)
endDate = input.int(title="End Date", defval=1, minval=1, maxval=31)
endMonth = input.int(title="End Month", defval=1, minval=1, maxval=12)
endYear = input.int(title="End Year", defval=2099, minval=1950, maxval=2100)
InDateRange = (time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0)) and (time < timestamp(syminfo.timezone, endYear, endMonth, endDate, 0, 0))
// Buy and Sell Functions //
if (InDateRange and TrendFilterInput==true)
strategy.entry("Long", strategy.long, when = ta.crossover(cumRSI, os) and TrendisLong, comment="Buy", alert_message="buy")
strategy.close("Long", when = ta.crossover(cumRSI, ob) , comment="Sell", alert_message="Sell")
if (InDateRange and TrendFilterInput==false)
strategy.entry("Long", strategy.long, when = ta.crossover(cumRSI, os), comment="Buy", alert_message="buy")
strategy.close("Long", when = ta.crossover(cumRSI, ob), comment="Sell", alert_message="sell")
if (not InDateRange)
strategy.close_all() |
Bagheri IG Ether v2 | https://www.tradingview.com/script/Mr3RnpLc-Bagheri-IG-Ether-v2/ | Bagheri_IG | https://www.tradingview.com/u/Bagheri_IG/ | 46 | strategy | 4 | MPL-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 v2", overlay=true, margin_long=100, margin_short=100)
TP = input(3000, minval = 1 , title ="Take Profit")
SL = input(2200, minval = 1 , title ="Stop Loss")
//_________________ RoC Definition _________________
rocLength = input(title="ROC Length", type=input.integer, minval=1, defval=186)
smoothingLength = input(title="Smoothing Length", type=input.integer, minval=1, defval=50)
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(53, minval=1, title="Upper Channel")
length2 = input(53, minval=1, title="Lower Channel")
offset_bar = input(91,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(65,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 __________________//
if strategy.position_size == 0
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" +
"╚═══════╝")
|
8 Day Extended Runs | https://www.tradingview.com/script/gl17fzdf-8-Day-Extended-Runs/ | Marcn5_ | https://www.tradingview.com/u/Marcn5_/ | 87 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Marcuscor
//@version=4
// Inpsired by Linda Bradford Raschke: a strategy for the T-note futures (ZN1!) that finds 8 day extended runs above/ below the 5sma and buys/ sells the first pullback below/ above the 5sma
// as of 01/10/2021 the t-test score is 4.06
strategy("8DayRun", overlay=true)
SMA = sma(close,5)
TrendUp = close > SMA
TrendDown = close < SMA
//logic to long
TriggerBuy = barssince(close < SMA) > 8
Buy = TriggerBuy[1] and TrendDown
strategy.entry("EL", strategy.long, when = Buy)
strategy.close(id = "EL", when = barssince(Buy) >10)
bgcolor(TriggerBuy ? color.red : na)
bgcolor(Buy ? color.blue : na)
// logic to short
TriggerSell = barssince(close > SMA) > 8
Sell = TriggerSell[1] and TrendUp
strategy.entry("ES", strategy.short, when = Sell)
strategy.close(id = "ES", when = barssince(Sell) > 10)
bgcolor(TriggerSell ? color.white : na)
bgcolor(Sell ? color.fuchsia : na)
|
Moving Average Band - Taylor V1 | https://www.tradingview.com/script/U3pe4O9q-Moving-Average-Band-Taylor-V1/ | TaylorTneh | https://www.tradingview.com/u/TaylorTneh/ | 134 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TaylorTneh
//@version=4
strategy("Moving Average Band Taylor V1",shorttitle="MA Band+",overlay=true,default_qty_type=strategy.cash,default_qty_value=1000,initial_capital=1000,currency=currency.USD,commission_value=.1)
price = input(close, title="Source")
mabtype = input(title="Moving Average Type", defval="RMA", options=["SMA", "EMA", "RMA", "WMA"])
malen = input(10, "MA Period : 10")
magap = input(0.6, "Band Gap : 0.6", minval = -10, maxval = 10, step = 0.1)
mabup = if mabtype == "SMA"
sma(high, malen)
else
if mabtype == "EMA"
ema(high, malen)
else
if mabtype == "WMA"
wma(high, malen)
else
if mabtype == "RMA"
rma(high, malen)
mabdn = if mabtype == "SMA"
sma(low, malen)
else
if mabtype == "EMA"
ema(low, malen)
else
if mabtype == "WMA"
wma(low, malen)
else
if mabtype == "RMA"
rma(low, malen)
upex = mabup * (1 + magap/100)
dnex = mabdn * (1 - magap/100)
plot(upex, "Upper MA Band", color.orange)
plot(dnex, "Lower MA Band", color.orange)
//-------------------------------------------- (Strategy)
strategy.entry("Long", strategy.long, stop = upex)
strategy.entry("Short", strategy.short, stop = dnex)
//Long Only//strategy.entry("Long", strategy.long, stop = upex)
//Long Only//strategy.exit("Short", stop = dnex)
//Short Only//strategy.entry("Short", strategy.short, stop = dnex)
//Short Only//strategy.exit("Long", stop = upex)
//-------------------------------------------- (Take Profit & Stop Lose)
stopPer = input(500.0, title='# Stop Loss %', type=input.float) / 100
takePer = input(500.0, title='# Take Profit %', type=input.float) / 100
//Determine where you've entered and in what direction
longStop = strategy.position_avg_price * (1 - stopPer)
shortStop = strategy.position_avg_price * (1 + stopPer)
shortTake = strategy.position_avg_price * (1 - takePer)
longTake = strategy.position_avg_price * (1 + takePer)
if strategy.position_size > 0
strategy.exit(id="L-TP/SL", stop=longStop, limit=longTake)
if strategy.position_size < 0
strategy.exit(id="S-TP/SL", stop=shortStop, limit=shortTake)
//-------------------------------------------- (Sample Time Filter Strategy)
//fromyear = input(2018, defval = 1900, minval = 1900, maxval = 2100, title = "From Year")
//toyear = input(2100, defval = 2100, minval = 1900, maxval = 2100, title = "To Year")
//frommonth = input(01, defval = 01, minval = 01, maxval = 12, title = "From Month")
//tomonth = input(10, defval = 10, minval = 01, maxval = 12, title = "To Month")
//fromday = input(01, defval = 01, minval = 01, maxval = 31, title = "From day")
//today = input(31, defval = 31, minval = 01, maxval = 31, title = "To day")
//strategy.entry("Long", strategy.long, stop = upex, when = (time > timestamp(fromyear, frommonth, fromday, 00, 00) and time < timestamp(toyear, tomonth, today, 23, 59)))
//strategy.entry("Short", strategy.short, stop = dnex, when = (time > timestamp(fromyear, frommonth, fromday, 00, 00) and time < timestamp(toyear, tomonth, today, 23, 59)))
//--------------------------------------------
|
SQV Cross | https://www.tradingview.com/script/m26U0ZYM-SQV-Cross/ | tbernache | https://www.tradingview.com/u/tbernache/ | 15 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © tbernache
//@version=4
strategy("SQV Cross", overlay=true, margin_long=100, margin_short=100)
slow = input(5, title="Fast EMA", minval=0, maxval=100)
fast = input(35, title="Slow EMA", minval=0, maxval=500)
//res = input("10", title="Resolution")
res = timeframe.period
spy = security("SPY", res, close)
spy_fast = ema(spy, fast)
spy_slow = ema(spy, slow)
spy_up = spy_fast > spy_slow and spy_slow > spy_slow[1]
vix = security("VIX", res, close)
vix_fast = ema(vix, fast)
vix_slow = ema(vix, slow)
vix_down = vix_slow > vix_fast and vix_slow[1] > vix_slow
qqq = security("QQQ", res, close)
qqq_fast = ema(qqq, fast)
qqq_slow = ema(qqq, slow)
qqq_up = qqq_fast > qqq_slow and qqq_slow > qqq_slow[1]
xUp = spy_up and qqq_up and vix_down
plotchar(xUp, "Long", "▲", location.bottom, color.lime, size = size.tiny)
if (xUp)
strategy.entry("long", strategy.long)
strategy.exit ("Exit Long","long", trail_points = 10,trail_offset = 50, loss =70)
|
Aphrodite | https://www.tradingview.com/script/xdXPlLf1-Aphrodite/ | Eliza123123 | https://www.tradingview.com/u/Eliza123123/ | 124 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Eliza123123
//@version=4
strategy("Aphrodite", default_qty_type = strategy.percent_of_equity, default_qty_value = 1, overlay=true, commission_type = strategy.commission.percent, commission_value=0.075, calc_on_every_tick=false, pyramiding = 999)
// v4
//pump/dump trend following strategy idea added.
//Pseudo Random Number Generator Box Muller Normal Distribution Method - code from [RS]Function - Functions to generate Random values by RicardoSantos. Dots are calculated by an adaptation of the ideas
//in this script.
// volume accumulates when dots are green for buys, red for sells. This setup is just looking for buys but this is very easy to change
//just go to trading day and swap all strategy.long commands for strategy.short commands
// Exits on minutes where OHLC all return 'primeness'
//Reinforced dots (with black) when last three dots are all of same colour
//==================================================================================================================================================================================================================
//UPDATE HISTORY:
// v2
// more workable version of yesterdays script. please still only use on assets $10 to $100 as scalability hasn't been added for all assets yet. BG colors are theres to show historic prevalence of "primeness".
// The table in the top right will flash purple when the open high low or close encounters "primeness".
// When they all light up thats when you can potentially expect a reversal. Use on lower time frame to see the effect quickly. Note this still isn't a foolproof method for finding primes but I will be improving it in later editions
// v3
// added scaling for pairs from $0.10 up to $1000. May still be slight different in indicator performance betwwen the two extremes of that scale.
// Clear OHLC prime pivot points have been added
// Introducing the volumeometer. Pretty self explanatory.
//==================================================================================================================================================================================================================
day_of_month = input(3, "Day of Month", input.integer)
this_month = input(10, "Month", input.integer)
randomhour1 = floor(random(0,271))
// randomflip = round(random(0,1))
// randomflip2 = round(random(0,1))
// randomflip3 = round(random(0,1))
// day_before1 = day_of_month - 1
// day_before2 = day_of_month - 2
// day_before3 = day_of_month - 3
// day_before4 = day_of_month - 4
// day_before5 = day_of_month - 5
// day_before6 = day_of_month - 6
// day_before7 = day_of_month - 7
// day_before8 = day_of_month - 8
// day_before9 = day_of_month - 9
// day_before10 = day_of_month - 10
f_close = close, f_low = low, f_high = high, f_open = open
flagc = 0, flagl = 0, flagh = 0, flago = 0
//SCALING (JUST USE ASSETS $10 to $1000 as this needs more work still)
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Assets $0.10-1
if close >= 0.100 and close < 0.9999
f_close := f_close * 100000
if low >= 0.100 and low < 0.9999
f_low := f_low * 100000
if high >= 0.100 and high < 0.9999
f_high := f_high * 100000
if open >= 0.100 and open < 0.9999
f_open := f_open * 100000
//Assets $1-10
if close >= 1.000 and close < 9.999
f_close := f_close * 10000
if low >= 1.000 and low < 9.999
f_low := f_low * 10000
if high >= 1.000 and high < 9.999
f_high := f_high * 10000
if open >= 1.000 and open < 9.999
f_open := f_open * 10000
//Assets $10-100
if close >= 10.000 and close < 99.999
f_close := f_close * 1000
if low >= 10.000 and low < 99.999
f_low := f_low * 1000
if high >= 10.000 and high < 99.999
f_high := f_high * 1000
if open >= 10.000 and open < 99.999
f_open := f_open * 1000
//Assets $100-1000
if close >= 100.000 and close < 999.999
f_close := f_close * 100
if low >= 100.000 and low < 999.999
f_low := f_low * 100
if high >= 100.000 and high < 999.999
f_high := f_high * 100
if open >= 100.000 and open < 999.999
f_open := f_open * 100
//Assets $1000-10000
if close >= 1000.000 and close < 9999.999
f_close := f_close * 10
if low >= 1000.000 and low < 9999.999
f_low := f_low * 10
if high >= 1000.000 and high < 9999.999
f_high := f_high * 10
if open >= 1000.000 and open < 9999.999
f_open := f_open * 10
//Assets $10000-100000
if close >= 10000.000 and close < 99999.999
f_close := f_close
if low >= 10000.000 and low < 99999.999
f_low := f_low
if high >= 10000.000 and high < 99999.999
f_high := f_high
if open >= 10000.000 and open < 99999.999
f_open := f_open
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Prime Checking
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if f_close > 1
for i = 2 to 3
if (f_close % i) == 0
flagc := 1
for i = 4 to 5
if (f_close % i) == 0
flagc := 1
for i = 6 to 7
if (f_close % i) == 0
flagc := 1
for i = 8 to 9
if (f_close % i) == 0
flagc := 1
if f_low > 1
for i = 2 to 3
if (f_low % i) == 0
flagl := 1
for i = 4 to 5
if (f_low % i) == 0
flagl := 1
for i = 6 to 7
if (f_low % i) == 0
flagl := 1
for i = 8 to 9
if (f_low % i) == 0
flagl := 1
if f_high > 1
for i = 2 to 3
if (f_high % i) == 0
flagh := 1
for i = 4 to 5
if (f_high % i) == 0
flagh := 1
for i = 6 to 7
if (f_high % i) == 0
flagh := 1
for i = 8 to 9
if (f_high % i) == 0
flagh := 1
if f_open > 1
for i = 2 to 3
if (f_open % i) == 0
flago := 1
for i = 4 to 5
if (f_open % i) == 0
flago := 1
for i = 6 to 7
if (f_open % i) == 0
flago := 1
for i = 8 to 9
if (f_open % i) == 0
flago := 1
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Pseudo Random Number Generator Box Muller Normal Distribution Method - code from [RS]Function - Functions to generate Random values by RicardoSantos
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
f_pseudo_random_number(_range, _seed) =>
_return = 1.0
if na(_seed)
_return := 3.14159 * nz(_return[1], 1) % bar_index
_return
else
_return := 3.14159 * nz(_return[1], 1) % (bar_index + _seed)
_return
_return := _return % _range
_return
f_nd_pseudo_random(_mean, _dev, _seed) =>
_pi = 3.14159265359
_random_1 = f_pseudo_random_number(1.0, _seed)
_random_2 = f_pseudo_random_number(1.0, -_seed)
_return = sqrt(-2 * log(_random_1)) * cos(2 * _pi * _random_2) * _dev + _mean
_return
//My added code:
mean = sma(ohlc4, 27)
dev = stdev(ohlc4, 27)
rng = f_nd_pseudo_random(mean, dev, input(1.0))
absrng = abs(rng)
normalDistributionDots = abs(rng)
trd = 0, tgd = 0
if(abs(rng) > high) and (abs(rng)[1] > high[1]) and (abs(rng)[2] > high[2]) and bar_index
trd := 1
tgd := 0
if (abs(rng) < low) and (abs(rng)[1] < low[1]) and (abs(rng)[2] < low[2]) and bar_index
tgd := 1
trd := 0
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// CONDITION
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
piBear=0
if abs(rng) > high
piBear := 1
piBull=0
if abs(rng) < low
piBull := 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//MORE CALCS
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
volumesBeaten = 0
for i = 1 to 1440
if volume > volume[i]
volumesBeaten := volumesBeaten + 1
volume_percent_class = (volumesBeaten / 1440) * 100
howManyreds = 0
for i = 1 to 100
if open[i] > close[i]
howManyreds := howManyreds + 1
howManygreens = 0
for i = 1 to 100
if open[i] < close[i]
howManygreens := howManygreens + 1
// howManygreendots = 0
// for i = 1 to 100
// if abs(rng)[i] < low[i]
// howManygreendots := howManygreendots + 1
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//OUTPUTS
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
plot(series = normalDistributionDots, title="BLACK DOT", color = trd == 1 ? #000000 : na, linewidth=4, style=plot.style_circles, transp=0)
plot(series = normalDistributionDots, title="BLACK DOT", color = tgd == 1 ? #000000 : na, linewidth=4, style=plot.style_circles, transp=0)
plot(series = normalDistributionDots, title="Normally Distributed Pseudo Random Value", color = abs(rng) > high ? #fa0000 : #0efa00, linewidth=1, style=plot.style_circles, transp=0)
plotcandle(open, high, low, close, color = abs(rng) > high ? #fa0000 : #0efa00, wickcolor= color.white)
bgcolor(color = abs(rng) > high ? #fa0000 : na)
bgcolor(color = trd == 1 ? #fa0000 : na)
bgcolor(color = abs(rng) < low ? #0efa00 : na)
bgcolor(color = tgd == 1 ? #0efa00 : na)
bgcolor(color = flagc == 0 ? color.yellow : na, transp = 99)
bgcolor(color = flagl == 0 ? color.yellow : na, transp = 99)
bgcolor(color = flagh == 0 ? color.yellow : na, transp = 99)
bgcolor(color = flago == 0 ? color.yellow : na, transp = 99)
bgcolor(color = flago == 0 and flagh == 0 ? color.purple : na, transp = 98)
bgcolor(color = flago == 0 and flagl == 0 ? color.purple : na, transp = 98)
bgcolor(color = flago == 0 and flagc == 0 ? color.purple : na, transp = 98)
bgcolor(color = flagl == 0 and flagc == 0 ? color.purple : na, transp = 98)
bgcolor(color = flagl == 0 and flagh == 0 ? color.purple : na, transp = 98)
bgcolor(color = flagc == 0 and flagh == 0 ? color.purple : na, transp = 98)
bgcolor(color = flagc == 0 and flagh == 0 and flago == 0 ? color.fuchsia : na, transp = 97)
bgcolor(color = flagc == 0 and flagh == 0 and flagl == 0 ? color.fuchsia : na, transp = 97)
bgcolor(color = flago == 0 and flagc == 0 and flagl == 0 ? color.fuchsia : na, transp = 97)
bgcolor(color = flago == 0 and flagh == 0 and flagl == 0 ? color.fuchsia : na, transp = 97)
var testTable = table.new(position = position.bottom_right, columns = 2, rows = 4, bgcolor = color.white, border_width = 1)
if barstate.islast
table.cell(table_id = testTable, column = 0, row = 0, text = "Open is " + tostring(open), bgcolor = flago == 0 ? color.fuchsia : na, text_color = #000000)
table.cell(table_id = testTable, column = 1, row = 0, text = "Close is " + tostring(close), bgcolor = flagc == 0 ? color.fuchsia : na, text_color = #000000)
table.cell(table_id = testTable, column = 0, row = 1, text = "High is " + tostring(high), bgcolor = flagh == 0 ? color.fuchsia : na, text_color = #000000)
table.cell(table_id = testTable, column = 1, row = 1, text = "Low is " + tostring(low), bgcolor = flagl == 0 ? color.fuchsia : na, text_color = #000000)
table.cell(table_id = testTable, column = 0, row = 2, text = " Volume higher than " + tostring(volume_percent_class) + "% of recent data", bgcolor = #000000, text_color = color.white)
table.cell(table_id = testTable, column = 1, row = 2, text = "Reds " + tostring(howManyreds), bgcolor = #9f0000, text_color = color.white)
table.cell(table_id = testTable, column = 0, row = 3, text = "HOPE THIS HELPS! ELIZA x", bgcolor = #fc03a5, text_color = #d5ff03)
table.cell(table_id = testTable, column = 1, row = 3, text = "Greens " + tostring(howManygreens), bgcolor = #1e9f00, text_color = color.white)
plotshape(flagc == 0 and flagh == 0 and flago == 0 and flagl == 0, location = location.belowbar, color = color.purple, text = "Piv", textcolor = color.white)
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//TRADING DAY
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//1st order Buy Entries
if abs(rng) < low and (month == (this_month) and dayofmonth == 3)
strategy.entry(id = "buy",
long = strategy.long,
comment = "buy",
alert_message = "Long(" + syminfo.ticker + "): Started"
)
else if flagc == 0 and flagh == 0 and flago == 0 and flagl == 0
strategy.close_all(comment = "close")
//2nd order Buy entries
if tgd == 1 and (month == (this_month) and dayofmonth == 3)
strategy.entry(id = "buy2",
long = strategy.long,
comment = "buy",
alert_message = "Long(" + syminfo.ticker + "): Started"
)
else if flagc == 0 and flagh == 0 and flago == 0 and flagl == 0
strategy.close_all(comment = "close")
if tgd == 1 and (month == (this_month) and dayofmonth == 3)
strategy.entry(id = "buy3",
long = strategy.long,
comment = "buy",
alert_message = "Long(" + syminfo.ticker + "): Started"
)
else if flagc == 0 and flagh == 0 and flago == 0 and flagl == 0
strategy.close_all(comment = "close")
if tgd == 1 and (month == (this_month) and dayofmonth == 3)
strategy.entry(id = "buy4",
long = strategy.long,
comment = "buy",
alert_message = "Long(" + syminfo.ticker + "): Started"
)
else if flagc == 0 and flagh == 0 and flago == 0 and flagl == 0
strategy.close_all(comment = "close")
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
Swing Stock Market Multi MA Correlation | https://www.tradingview.com/script/bwC6KuBy-Swing-Stock-Market-Multi-MA-Correlation/ | exlux99 | https://www.tradingview.com/u/exlux99/ | 177 | strategy | 4 | MPL-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 = "Multi MA Correlation Stocks", overlay = true,initial_capital = 1000, default_qty_type= strategy.percent_of_equity, default_qty_value = 100, commission_type=strategy.commission.percent,commission_value=0.01)
useha = input(false, title="Use Heikin Ashi Candles in Algo Calculations")
usesp500 = input(true, title="Use SP500 Candles in Algo Calculations")
usenasdaq = input(false, title="Use Nasdaq Candles in Algo Calculations")
//
// === /INPUTS ===
// === BASE FUNCTIONS ===
haClose = useha ? security(heikinashi(syminfo.tickerid), timeframe.period, close) : usesp500 ? security(("TVC:SPX"), timeframe.period, close) : usenasdaq ? security(("TVC:NDX"), timeframe.period, close) :close
haOpen = useha ? security(heikinashi(syminfo.tickerid), timeframe.period, open) : usesp500 ? security(("TVC:SPX"), timeframe.period, open) : usenasdaq ? security(("TVC:NDX"), timeframe.period, open) :open
haHigh = useha ? security(heikinashi(syminfo.tickerid), timeframe.period, high) : usesp500 ? security(("TVC:SPX"), timeframe.period, high) : usenasdaq ? security(("TVC:NDX"), timeframe.period, high) :high
haLow = useha ? security(heikinashi(syminfo.tickerid), timeframe.period, low) : usesp500 ? security(("TVC:SPX"), timeframe.period, low) : usenasdaq ? security(("TVC:NDX"), timeframe.period, low) :low
average = (haClose+haOpen+haHigh+haLow)/4
ma(source, length, type) =>
type == "SMA" ? sma(source, length) :
type == "EMA" ? ema(source, length) :
type == "SMMA (RMA)" ? rma(source, length) :
type == "WMA" ? wma(source, length) :
type == "VWMA" ? vwma(source, length) :
na
ma1_type = input("SMMA (RMA)" , "" , inline="MA #1", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"])
ma1_source = average
ma1_length = input(20 , "" , inline="MA #1", minval=1)
ma1 = ma(ma1_source, ma1_length, ma1_type)
ma2_type = input("EMA" , "" , inline="MA #2", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"])
ma2_source = average
ma2_length = input(50 , "" , inline="MA #2", minval=1)
ma2 = ma(ma2_source, ma2_length, ma2_type)
ma3_type = input("WMA" , "" , inline="MA #3", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"])
ma3_source = average
ma3_length = input(100 , "" , inline="MA #3", minval=1)
ma3 = ma(ma3_source, ma3_length, ma3_type)
long= ma1>ma2 and ma2>ma3
short=ma1<ma2 and ma2<ma3
longexit=ma1<ma2 and ma2<ma3
shortexit=ma1>ma2 and ma2>ma3
longEntry=input(true, title="Long Entries ?")
shortEntry=input(true, title="Short Entries ?")
if(longEntry)
strategy.entry("long",1,when=long)
strategy.close("long",when=longexit)
if(shortEntry)
strategy.entry("short",0,when=short)
strategy.close("short",when=shortexit)
|
ICHIMOKU Crypto Swing Strategy | https://www.tradingview.com/script/RyE9fei6-ICHIMOKU-Crypto-Swing-Strategy/ | exlux99 | https://www.tradingview.com/u/exlux99/ | 290 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © exlux99
//@version=4
strategy(title="ICHIMOKU Crypto Swing Strategy", overlay=true, initial_capital = 10000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=0.05 )
//
o = open
c = close
src = close
price = close
uptrendlength = input(4, title="Uptrend Length")
downtrendlength = input(4, title="Downtrend Length")
//KDJ//
ilong = 9
isig = 3
bcwsma(s,l,m) =>
_s = s
_l = l
_m = m
_bcwsma = (_m*_s+(_l-_m))
_bcwsma
h = highest(high, ilong)
l = lowest(low,ilong)
RSV = 100*((c-l)/(h-l))
pK = bcwsma(RSV, isig, 1)
pD = bcwsma(pK, isig, 1)
pJ = 3 * pK-2 * pD
KD = avg(pK,pD)
/// --- TREND --- ///
avghigh = sma(h, uptrendlength)
avglow = sma(l, downtrendlength)
uptrend = h > avghigh
downtrend = l < avglow
//ICHIMOKU BUY & SELL//
conversionPeriods = input(9)
basePeriods = input(26)
laggingSpan2Periods = input(52)
displacement = input(26)
donchian(len) => avg(lowest(len), highest(len))
resolve(src, default) =>
if na(src)
default
else
src
conversionLine = donchian(conversionPeriods)
baseLine = donchian(basePeriods)
leadLine1 = offset(avg(conversionLine, baseLine), displacement)
leadLine2 = offset(donchian(laggingSpan2Periods), displacement)
tk_cross_bull = crossover(conversionLine, baseLine)
tk_cross_bear = crossunder(conversionLine, baseLine)
cross_y = (conversionLine[1] * (baseLine - baseLine[1]) - baseLine[1] * (conversionLine - conversionLine[1])) / ((baseLine - baseLine[1]) - (conversionLine - conversionLine[1]))
tk_cross_below_kumo = cross_y <= leadLine2[1] and cross_y <= leadLine1[1] and cross_y <= leadLine2 and cross_y <= leadLine1
tk_cross_above_kumo = cross_y >= leadLine2[1] and cross_y >= leadLine1[1] and cross_y >= leadLine2 and cross_y >= leadLine1
tk_cross_inside_kumo = (not tk_cross_below_kumo) and (not tk_cross_above_kumo)
//
//BUY & SELL
buycond = (tk_cross_below_kumo or tk_cross_inside_kumo or tk_cross_above_kumo) and rising(pJ[1],1) and uptrend
sellcond = (tk_cross_below_kumo or tk_cross_inside_kumo or tk_cross_above_kumo) and falling(pJ[1],1) and downtrend
fromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31)
fromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12)
fromYear = input(defval = 2020, title = "From Year", minval = 1970)
//monday and session
// To Date Inputs
toDay = input(defval = 31, title = "To Day", minval = 1, maxval = 31)
toMonth = input(defval = 12, title = "To Month", minval = 1, maxval = 12)
toYear = input(defval = 2021, title = "To Year", minval = 1970)
startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00)
finishDate = timestamp(toYear, toMonth, toDay, 00, 00)
time_cond = time >= startDate and time <= finishDate
if(time_cond)
strategy.entry("long",strategy.long,when= buycond, alert_message="LONG")
strategy.entry("short",strategy.short,when=sellcond, alert_message="SHORT")
|
Webhook Starter Kit [HullBuster] | https://www.tradingview.com/script/wvYrM19h-Webhook-Starter-Kit-HullBuster/ | tradingtudi | https://www.tradingview.com/u/tradingtudi/ | 378 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © tradingtudi
//@version=4
strategy(title = "WebhookDrive-V1", overlay = true, pyramiding = 0, initial_capital = 10000, currency = currency.USD)
// -----------------------------
// ---- Strategy Inputs
// -----------------------------
inputBuild = input(defval = 101, type = input.integer, minval = 0.0, title = "Build Number", group = "[ SECTION 1 ]", tooltip = "This is a trend follow script that enters the market long above the purple line and short below. It is prone to losses on ranging markets where the trend line bisects the price stream")
inputTradingMode = input(defval = "BiDir", options = ["Long","Short","BiDir","Flip Flop","Crypto","Range","No Trade"], title = "Trading Mode", group = "[ SECTION 1 ]", tooltip = "BiDir is for margin trading with a stop. Flip Flop will alter direction on trend line cross. Crypto is long only with downward pyramids. Range only enters on a counter-trend")
inputMinProfit = input(defval = 0.50, type = input.float, minval = 0.0, title = "Minimum Profit", group = "[ SECTION 1 ]", tooltip = "Smallest take profit offset to permit a close order. This is a conditional exit not a limit (quote currency units)")
inputStopOffset = input(defval = 0.50, type = input.float, minval = 0.0, title = "Stop Offset", group = "[ SECTION 1 ]", tooltip = "Hard stop offset from the trade open price (quote currency units)")
inputTickScaler = input(defval = 10.0, type = input.float, minval = 1.0, title = "Tick Scalar", group = "[ SECTION 1 ]", tooltip = "Value used to remove the pipette from quote currency calculations. See the Summary Report to determine this value")
inputChgDivisor = input(defval = 1000.0, type = input.float, minval = 1.0, title = "Price Normalizer", group = "[ SECTION 1 ]", tooltip = "Value used to normalize bar prices for differential calculations. Serves to increase the magnitude of significant digits. Applied to all inputs specifying net change and roc")
inputPryramidSpan = input(defval = 0.0, type = input.float, minval = 0.0, title = "Pyramid Minimum Span", group = "[ SECTION 1 ]", tooltip = "Minimum spacing between downward pyramid levels (quote currency units). Set to zero to disable downward pyramiding. To fully disable pyramiding zero the value in the Properties tab")
inputPyramidBaleOut = input(defval = true, type = input.bool, title = "Position Bale Out", group = "[ SECTION 1 ]", tooltip = "Enable to exit positions early. The algorithm ensures the position exits at a profit but not at the amount specified in the Minimum Profit input. Reduces the risk when pyramiding")
inputMaxAddOns = input(defval = 0, type = input.integer, minval = 0, maxval = 20, title = "Maximum DCA Increments", group = "[ SECTION 1 ]", tooltip = "Sets a whole number limit on the number of times a losing position can be averaged down")
inputSignalPeriod = input(defval = "60", options = ["60","240","1440"], title = "Signal Line Period", group = "[ SECTION 2 ]", tooltip = "Sets the bar interval for the Blue, Green, Orange signal lines and the ZScore oscillator not visible")
inputTrendPeriod = input(defval = "240", options = ["60","240","1440"], title = "Trend Line Period", group = "[ SECTION 2 ]", tooltip = "Sets the bar interval for the Purple trend line and Stochastic indicator")
inputFastAlmaLen = input(defval = 10, type = input.integer, minval = 1, title = "Fast Alma Length", group = "[ SECTION 2 ]", tooltip = "Sets the period length of the Blue line (Arnaud Legoux Moving Average indicator)")
inputFastLinRegLen = input(defval = 30, type = input.integer, minval = 1, title = "Fast LinReg Length", group = "[ SECTION 2 ]", tooltip = "Sets the period length of the Green line (Linear Regression indicator)")
inputSlowLinRegLen = input(defval = 100, type = input.integer, minval = 1, title = "Slow LinReg Length", group = "[ SECTION 2 ]", tooltip = "Sets the period length of the Orange line (Linear Regression indicator)")
inputTrendDEMALen = input(defval = 200, type = input.integer, minval = 1, title = "Trend Line Length", group = "[ SECTION 2 ]", tooltip = "Sets the period length of the Purple line (Double Smoothed Moving Average indicator)")
inputStochastLen = input(defval = 14, type = input.integer, minval = 1, title = "Stochastic Length", group = "[ SECTION 2 ]", tooltip = "Sets the period length of two Stochastic indicators. One at the Purple line. Second at the chart interval")
inputFastCrossLen = input(defval = 9, type = input.integer, minval = 1, title = "Fast Cross Length", group = "[ SECTION 3 ]", tooltip = "Sets the period length of the Simple Moving Average indicator used for trade entry (Crossover Setup). The same exact one used in the TV example strategy. Cross up is a long entry. Cross down is short")
inputSlowCrossLen = input(defval = 24, type = input.integer, minval = 1, title = "Slow Cross Length", group = "[ SECTION 3 ]", tooltip = "Sets the period length of the Simple Moving Average indicator used for trade entry (Crossover Setup). The same exact one used in the TV example strategy. Cross up is a long entry. Cross down is short")
inputFastEMALen = input(defval = 8, type = input.integer, minval = 1, title = "Fast EMA Length", group = "[ SECTION 3 ]", tooltip = "Sets the period length of the Yellow line (Exponential Moving Average indicator). This is a chart interval indicator")
inputFastEMARiseNet = input(defval = 3.0, type = input.float, minval = 0.00, title = "Fast EMA Rise NetChg", group = "[ SECTION 3 ]", tooltip = "Measures the delta percentage from the upward cross of the Yellow over the Blue line. A larger number means the market must swing higher to generate a signal. Trades will stay in longer")
inputFastEMARiseROC = input(defval = 0.8, type = input.float, minval = 0.00, title = "Fast EMA Rise ROC", group = "[ SECTION 3 ]", tooltip = "Measures the rate of change from the upward cross of the Yellow over the Blue line. A larger number means the swing higher has to occur over a commensurately shorter time. Trades will stay in longer")
inputFastEMAFallNet = input(defval = 4.0, type = input.float, minval = 0.00, title = "Fast EMA Fall NetChg", group = "[ SECTION 3 ]", tooltip = "Measures the delta percentage from the downward cross of the Yellow under the Blue line. A larger number means the market must swing lower to generate a signal. Trades will stay in longer")
inputFastEMAFallROC = input(defval = 0.8, type = input.float, minval = 0.00, title = "Fast EMA Fall ROC", group = "[ SECTION 3 ]", tooltip = "Measures the rate of change from the downward cross of the Yellow under the Blue line. A larger number means the swing lower has to occur over a commensurately shorter time. Trades will stay in longer")
inputLongNascent = input(defval = false, type = input.bool, title = "Enter Long On Nascent", group = "[ SECTION 4 ]", tooltip = "Enables rudimentary counter-trend trading. If checked long trades will signal below the Purple trend line and will exit above. The strategy will perform poorly in trending markets")
inputLongCrossExit = input(defval = true, type = input.bool, title = "Long Natural Exit", group = "[ SECTION 4 ]", tooltip = "A natural long exit is when the Blue line crosses under the Green Line (downward). The position must be profitable to exit")
inputLongSignalExit = input(defval = true, type = input.bool, title = "Long Signal Exit", group = "[ SECTION 4 ]", tooltip = "A signal event is when the Blue crosses over the Green line at the magnitude and rate specified in section #6. The ZScore oscillator must have reached the positive value specified in section #6. The position must be profitable to exit")
inputLongEventExit = input(defval = true, type = input.bool, title = "Long Price Event Exit", group = "[ SECTION 4 ]", tooltip = "A price event is when the Yellow crosses over the Blue line at the magnitude and rate specified in section #3. The position must be profitable to exit")
inputLongStochExit = input(defval = true, type = input.bool, title = "Long Stochastic Exit", group = "[ SECTION 4 ]", tooltip = "This exit occurs when the Stochastic oscillator measuring the Purple line exceeds the overbought threshold (80). The position must be profitable to exit")
inputShortNascent = input(defval = false, type = input.bool, title = "Enter Short On Nascent", group = "[ SECTION 5 ]", tooltip = "Enables rudimentary counter-trend trading. If checked short trades will signal above the Purple trend line and will exit below. The strategy will perform poorly in trending markets")
inputShortCrossExit = input(defval = true, type = input.bool, title = "Short Natural Exit", group = "[ SECTION 5 ]", tooltip = "A natural short exit is when the Blue line crosses over the Green Line. (upward) The position must be profitable to exit")
inputShortSignalExit = input(defval = true, type = input.bool, title = "Short Signal Exit", group = "[ SECTION 5 ]", tooltip = "A signal event is when the Blue crosses under the Green line at the magnitude and rate specified in section #6. The ZScore oscillator must have reached the negative value specified in section #6. The position must be profitable to exit")
inputShortEventExit = input(defval = true, type = input.bool, title = "Short Price Event Exit", group = "[ SECTION 5 ]", tooltip = "A price event is when the Yellow crosses under the Blue line at the magnitude and rate specified in section #3. The position must be profitable to exit")
inputShortStochExit = input(defval = true, type = input.bool, title = "Short Stochastic Exit", group = "[ SECTION 5 ]", tooltip = "This exit occurs when the Stochastic oscillator measuring the Purple line exceeds the oversold threshold (20). The position must be profitable to exit")
inputRiseEventNet = input(defval = 10.0, type = input.float, minval = 0.00, title = "Rise Event Net Change", group = "[ SECTION 6 ]", tooltip = "Measures the delta percentage from the upward cross of the Blue over the Green line. A larger number means the market must swing higher to generate a signal. Trades will stay in longer")
inputRiseEventROC = input(defval = 0.1, type = input.float, minval = 0.00, title = "Rise Event ROC", group = "[ SECTION 6 ]", tooltip = "Measures the rate of change from the upward cross of the Blue over the Green line. A larger number means the swing higher has to occur over a commensurately shorter time. Trades will stay in longer")
inputMinZScoreABZ = input(defval = 5.0, type = input.float, minval = 0.00, title = "Min Above Zero ZScore", group = "[ SECTION 6 ]", tooltip = "Specifies the overbought threshold of the ZScore oscillator. If the [Long Signal Exit] option in Section #4 is enabled a high value here will cause the long trade to stay in the market longer")
inputFallEventNet = input(defval = 10.0, type = input.float, minval = 0.00, title = "Fall Event Net Change", group = "[ SECTION 6 ]", tooltip = "Measures the delta percentage from the downward cross of the Blue under the Green line. A larger number means the market must swing lower to generate a signal. Trades will stay in longer")
inputFallEventROC = input(defval = 0.1, type = input.float, minval = 0.00, title = "Fall Event ROC", group = "[ SECTION 6 ]", tooltip = "Measures the rate of change from the downward cross of the Blue under the Green line. A larger number means the swing lower has to occur over a commensurately shorter time. Trades will stay in longer")
inputMinZScoreBLZ = input(defval = 5.0, type = input.float, minval = 0.00, title = "Min Below Zero ZScore", group = "[ SECTION 6 ]", tooltip = "Specifies the oversold threshold of the ZScore oscillator. If the [Short Signal Exit] option in Section #5 is enabled a high value here will cause the short trade to stay in the market longer")
inputShowLines = input(defval = true, type = input.bool, title = "Show Trend Lines", group = "[ SECTION 7 ]", tooltip = "Display the Yellow, Blue, Green, Orange and Purple trend lines. They are rendered at a width of 2")
inputShowCrosses = input(defval = false, type = input.bool, title = "Show Entry Regions", group = "[ SECTION 7 ]", tooltip = "Background fill for the SMA crossovers specified in Section #3. The SMA is on the chart time frame so will display frequent transitions. Blue is an upward cross. Red is downward")
inputShowEvents = input(defval = false, type = input.bool, title = "Display Event Regions", group = "[ SECTION 7 ]", tooltip = "Background fill for signal events specified in Section #6. The Blue crossing the Green lines. Use it to configure Section #6. Blue is exceeding rise values. Red is is exceeding fall values")
inputShowEMPeaks = input(defval = false, type = input.bool, title = "Display EMA Peaks", group = "[ SECTION 7 ]", tooltip = "Background fill for price events specified in Section #3. The Yellow crossing the Blue lines. Use it to configure Section #3. Blue is exceeding rise values. Red is is exceeding fall values")
inputShowStochEvent = input(defval = false, type = input.bool, title = "Show Stochastic Events", group = "[ SECTION 7 ]", tooltip = "Background fill for Stochastic events occurring on the Purple line. Use it verify selected exits in Section #4 and #5. Blue is exceeding overbought levels. Red is is exceeding oversold levels")
inputShowConsecLoss = input(defval = false, type = input.bool, title = "Show Consecutive Losses",group = "[ SECTION 7 ]", tooltip = "Background fill for periods when consecutive losses are occurring. Red areas mean stops where hit and have not encountered a profitable exit. Use it to make adjustments to the values in Section #1")
inputShowBaleOuts = input(defval = false, type = input.bool, title = "Show Bale Outs", group = "[ SECTION 7 ]", tooltip = "Displays red labels under the bars where a position was exited prematurely. Each box contains information about the state of the trade at exit time. Use it when [Position Bale Out] in Section #1 is enabled")
inputReport = input(defval = false, type = input.bool, title = "Show Summary Report", group = "[ SECTION 7 ]", tooltip = "Displays a blue label at the live end of the chart. Contains useful strategy metrics which can aid in the development of the script. Relevant information should be added here as the script logic evolves. Happy Trading!")
int inputNormalizeLen = 100
bool inputAccumulateLong = false
bool inputAccumulateShort = false
bool inputExclusiveLong = false
bool inputExclusiveShort = false
if (inputTradingMode == "Long")
inputExclusiveLong := true
if (inputTradingMode == "Short")
inputExclusiveShort := true
if (inputTradingMode == "Crypto")
inputAccumulateLong := true
inputLongNascent := true
inputExclusiveLong := true
if (inputTradingMode == "Range")
inputAccumulateLong := true
inputAccumulateShort := true
inputLongNascent := true
inputShortNascent := true
strategy.risk.allow_entry_in((inputTradingMode == "Long") ? strategy.direction.long : (inputTradingMode == "Short") ? strategy.direction.short : (inputTradingMode == "Crypto") ? strategy.direction.long : strategy.direction.all)
if (inputTradingMode == "Crypto")
inputTradingMode := "Flip Flop"
// -----------------------------
// ---- Indicator Configurations
// -----------------------------
float fltBarPrice = close
// Linear Regression
int ncSlowLinRegLen = inputSlowLinRegLen
int ncFastLinRegLen = inputFastLinRegLen
int ncLinRegOffset = 0
// Arnaud Legoux Moving Average
int ncFastAlmaLen = inputFastAlmaLen
// Double Exponential Moving Average
int ncTrendDEMALen = inputTrendDEMALen
// ZScore Simple Moving Average
int ncNormalizeLen = inputNormalizeLen
// Fast Cross Simple Moving Average
int ncFastCrossLen = inputFastCrossLen
// Slow Cross Simple Moving Average
int ncSlowCrossLen = inputSlowCrossLen
// Fast Exponential Moving Average
int ncFastEMALen = inputFastEMALen
// Stochastic Oscillator
int ncStochasLen = inputStochastLen
int ncKn2Period = 3
int ncDn3Period = 3
// -----------------------------
// ---- Series Utilities
// -----------------------------
int indexClosedBar = barstate.isrealtime ? 1 : 0
int indexReadBar = barstate.isrealtime ? 0 : 1
calcDEMA(seriesData, ncMALength) =>
float emaAlpha = ema(seriesData, ncMALength)
float emaOfEma = ema(emaAlpha, ncMALength)
float seriesDema = (2 * emaAlpha) - emaOfEma
calcTrendDEMA() =>
float seriesOut = calcDEMA(fltBarPrice[indexClosedBar], ncTrendDEMALen)
calcSlowLinReg() =>
float seriesOut = linreg(fltBarPrice[indexClosedBar], ncSlowLinRegLen, ncLinRegOffset)
calcFastLinReg() =>
float seriesOut = linreg(fltBarPrice[indexClosedBar], ncFastLinRegLen, ncLinRegOffset)
calcFastAlma() =>
float seriesOut = alma(fltBarPrice[indexClosedBar], ncFastAlmaLen, 0.85, 6)
calcStochastic() =>
float seriesOut = stoch(close[indexClosedBar], high[indexClosedBar], low[indexClosedBar], ncStochasLen)
// ----------------------------
// ---- Series Creation
// ----------------------------
float seriesClose = close[indexClosedBar]
float seriesHigh = high[indexClosedBar]
float seriesLow = low[indexClosedBar]
// ---- [ HIGHER TIME FRAME ] ----
// Linear Regression
float htf_seriesSlowLinReg = security(syminfo.tickerid, inputSignalPeriod, calcSlowLinReg())[indexReadBar]
float htf_seriesFastLinReg = security(syminfo.tickerid, inputSignalPeriod, calcFastLinReg())[indexReadBar]
// Arnaud Legoux Moving Average
float htf_seriesFastAlma = security(syminfo.tickerid, inputSignalPeriod, calcFastAlma())[indexReadBar]
// Double Exponential Moving Average
float htf_seriesTrendDEMA = security(syminfo.tickerid, inputTrendPeriod, calcTrendDEMA())[indexReadBar]
// ZScore Simple Moving Average
float htf_seriesAlmaMean = sma(htf_seriesFastAlma, ncNormalizeLen)
// ZScore Series
float htf_seriesMarks = htf_seriesFastAlma - htf_seriesAlmaMean
float htf_seriesZScore = htf_seriesMarks / stdev(htf_seriesMarks, ncNormalizeLen)
// Stochastic Oscillator
float htf_seriesFastK = security(syminfo.tickerid, inputTrendPeriod, calcStochastic())[indexReadBar]
float htf_seriesDLine = sma(htf_seriesFastK, ncKn2Period)
float htf_seriesSlowD = sma(htf_seriesDLine, ncDn3Period)
// ---- [ CHART TIME FRAME ] ----
// Fast Cross Simple Moving Average
float seriesFastCross = sma(fltBarPrice, ncFastCrossLen)
// Slow Cross Simple Moving Average
float seriesSlowCross = sma(fltBarPrice, ncSlowCrossLen)
// Fast Exponential Moving Average
float seriesFastEMA = ema(fltBarPrice, ncFastEMALen)
// Stochastic Oscillator
float seriesFastK = stoch(seriesClose, seriesHigh, seriesLow, ncStochasLen)
float seriesDLine = sma(seriesFastK, ncKn2Period)
float seriesSlowD = sma(seriesDLine, ncDn3Period)
// ----------------------------
// ---- Indicator Conditions
// ----------------------------
bool bHTFSignalRise = (htf_seriesFastAlma > htf_seriesFastLinReg)
bool bHTFSignalFall = (htf_seriesFastAlma < htf_seriesFastLinReg)
bool bHTFFastAboveTrend = ((htf_seriesFastAlma > htf_seriesTrendDEMA) and (htf_seriesFastLinReg > htf_seriesTrendDEMA))
bool bHTFFastBelowTrend = ((htf_seriesFastAlma < htf_seriesTrendDEMA) and (htf_seriesFastLinReg < htf_seriesTrendDEMA))
bool bFastAboveSignal = ((seriesFastEMA > htf_seriesFastAlma) and (htf_seriesFastAlma > htf_seriesFastLinReg))
bool bFastBelowSignal = ((seriesFastEMA < htf_seriesFastAlma) and (htf_seriesFastAlma < htf_seriesFastLinReg))
bool bFullFanCone = ((bFastAboveSignal == true) and (htf_seriesFastLinReg > htf_seriesSlowLinReg))
bool bDownFanCone = ((bFastBelowSignal == true) and (htf_seriesFastLinReg < htf_seriesSlowLinReg))
bool bPartialTrendRise = ((seriesFastEMA > htf_seriesFastAlma) and (htf_seriesFastAlma > htf_seriesSlowLinReg) and (htf_seriesFastLinReg > htf_seriesSlowLinReg))
bool bPartialTrendFall = ((seriesFastEMA < htf_seriesFastAlma) and (htf_seriesFastAlma < htf_seriesSlowLinReg) and (htf_seriesFastLinReg < htf_seriesSlowLinReg))
bool bDurableTrendRise = ((bPartialTrendRise == true) and (htf_seriesSlowLinReg > htf_seriesTrendDEMA))
bool bDurableTrendFall = ((bPartialTrendFall == true) and (htf_seriesSlowLinReg < htf_seriesTrendDEMA))
bool bHTFNascentRise = ((htf_seriesFastAlma > htf_seriesSlowLinReg) and (htf_seriesFastLinReg > htf_seriesSlowLinReg) and (htf_seriesSlowLinReg < htf_seriesTrendDEMA))
bool bHTFNascentFall = ((htf_seriesFastAlma < htf_seriesSlowLinReg) and (htf_seriesFastLinReg < htf_seriesSlowLinReg) and (htf_seriesSlowLinReg > htf_seriesTrendDEMA))
// -------------------------------
// ---- Event Utilities
// -------------------------------
float fltFXMinTick = syminfo.mintick * inputTickScaler
calcRiseNetChg(fltFastPrice, fltSlowPrice) =>
float fltPercentChg = 0.0
float fltChgDivisor = (inputChgDivisor > 1.0) ? inputChgDivisor : fltSlowPrice
if (((na(fltSlowPrice) == false) and (fltSlowPrice > 0.0) and (fltFastPrice > fltSlowPrice)) == true)
fltPercentChg := (((fltFastPrice - fltSlowPrice) / fltFXMinTick) / fltChgDivisor) * 100.0
float fltResult = fltPercentChg
calcFallNetChg(fltFastPrice, fltSlowPrice) =>
float fltPercentChg = 0.0
float fltChgDivisor = (inputChgDivisor > 1.0) ? inputChgDivisor : fltSlowPrice
if (((na(fltSlowPrice) == false) and (fltSlowPrice > 0.0) and (fltFastPrice < fltSlowPrice)) == true)
fltPercentChg := (((fltSlowPrice - fltFastPrice) / fltFXMinTick) / fltChgDivisor) * 100.0
float fltResult = fltPercentChg
// -------------------------------
// ---- HTF Fast Alma Crosses HTF Fast LinReg
// -------------------------------
// Alma Above and Below LinReg (AL)
var float fltRiseALCrossPrice = 0.0
var float fltRiseALNetChg = 0.0
var float fltFallALCrossPrice = 0.0
var float fltFallALNetChg = 0.0
var int ncRiseALBarsSince = 0
var int ncFallALBarsSince = 0
if (htf_seriesFastAlma > htf_seriesFastLinReg)
if (ncFallALBarsSince > 0) // We were previously falling
ncFallALBarsSince := 0 // Zero means not in that direction
fltFallALCrossPrice := 0.0
ncRiseALBarsSince := 1 // Non-zero means currently rising
fltRiseALCrossPrice := seriesClose
fltRiseALNetChg := 0.0
else
ncRiseALBarsSince := ncRiseALBarsSince + 1 // Rise continues
fltRiseALNetChg := calcRiseNetChg(seriesClose, fltRiseALCrossPrice) // Rising
if (htf_seriesFastAlma < htf_seriesFastLinReg)
if (ncRiseALBarsSince > 0) // We were previously rising
ncRiseALBarsSince := 0 // Zero means not in that direction
fltRiseALCrossPrice := 0.0
ncFallALBarsSince := 1 // Non-zero means currently falling
fltFallALCrossPrice := seriesClose
fltFallALNetChg := 0.0
else
ncFallALBarsSince := ncFallALBarsSince + 1 // Fall continues
fltFallALNetChg := calcFallNetChg(seriesClose, fltFallALCrossPrice) // Falling
isMinimumNetChgROC(ncTypeBarsSince, fltTypeNetChg, fltMinNetChg, fltMinROC) =>
bool bPassed = false
bPassed := (((ncTypeBarsSince > 0) and (fltTypeNetChg > 0.0)) and (fltTypeNetChg >= fltMinNetChg) and ((fltTypeNetChg / ncTypeBarsSince) >= fltMinROC))
// -------------------------------
// ---- Fast EMA Crosses HTF Alma
// -------------------------------
// LTF EMA Above and Below HTF Alma (EM)
var float fltRiseEMCrossPrice = 0.0
var float fltRiseEMNetChg = 0.0
var float fltFallEMCrossPrice = 0.0
var float fltFallEMNetChg = 0.0
var int ncRiseEMBarsSince = 0
var int ncFallEMBarsSince = 0
if (seriesFastEMA > htf_seriesFastAlma)
if (ncFallEMBarsSince > 0) // We were previously falling
ncFallEMBarsSince := 0 // Zero means not in that direction
fltFallEMCrossPrice := 0.0
ncRiseEMBarsSince := 1 // Non-zero means currently rising
fltRiseEMCrossPrice := seriesClose
fltRiseEMNetChg := 0.0
else
ncRiseEMBarsSince := ncRiseEMBarsSince + 1 // Rise continues
fltRiseEMNetChg := calcRiseNetChg(seriesClose, fltRiseEMCrossPrice) // Rising
if (seriesFastEMA < htf_seriesFastAlma)
if (ncRiseEMBarsSince > 0) // We were previously rising
ncRiseEMBarsSince := 0 // Zero means not in that direction
fltRiseEMCrossPrice := 0.0
ncFallEMBarsSince := 1 // Non-zero means currently falling
fltFallEMCrossPrice := seriesClose
fltFallEMNetChg := 0.0
else
ncFallEMBarsSince := ncFallEMBarsSince + 1 // Fall continues
fltFallEMNetChg := calcFallNetChg(seriesClose, fltFallEMCrossPrice) // Falling
// ----------------------------
// ---- ZScore Histogram Tracking
// ----------------------------
// ZScore Above and Below Zero Line (ZS)
bool bNewRiseZSHigh = false
bool bNewFallZSLow = false
var int ncRiseZSSince = 0
var int ncFallZSSince = 0
var int ncRiseZSCount = 0
var int ncFallZSCount = 0
var float fltRiseZSValue = 0.0
var float fltFallZSValue = 0.0
var float fltRiseZSHigh = 0.0
var float fltFallZSLow = 0.0
var int ncAboveZSCount = 0
var int ncBelowZSCount = 0
var int ncAboveZSSince = 0
var int ncBelowZSSince = 0
ncRiseZSSince := ncRiseZSSince + 1
ncFallZSSince := ncFallZSSince + 1
ncAboveZSSince := ncAboveZSSince + 1
ncBelowZSCount := ncBelowZSCount + 1
if (htf_seriesZScore > htf_seriesZScore[1])
fltRiseZSValue := htf_seriesZScore[0]
fltRiseZSHigh := seriesClose[0] // High
bNewRiseZSHigh := true
if (ncRiseZSSince > 0) // We were previously falling
ncRiseZSSince := 0
ncRiseZSCount := 1
else
ncRiseZSSince := 0
ncRiseZSCount := ncRiseZSCount + 1 // Rise continues
if (htf_seriesZScore > 0.0)
if (ncAboveZSSince > 0) // We were previously below zero
ncAboveZSSince := 0
ncAboveZSCount := 1
else
ncAboveZSSince := 0
ncAboveZSCount := ncAboveZSCount + 1 // Above zero continues
if (htf_seriesZScore < htf_seriesZScore[1])
fltFallZSValue := htf_seriesZScore[0]
fltFallZSLow := seriesClose[0] // Low
bNewFallZSLow := true
if (ncFallZSSince > 0) // We were previously rising
ncFallZSSince := 0
ncFallZSCount := 1
else
ncFallZSSince := 0
ncFallZSCount := ncFallZSCount + 1 // Fall continues
if (htf_seriesZScore < 0.0)
if (ncBelowZSSince > 0) // We were previously above zero
ncBelowZSSince := 0
ncBelowZSCount := 1
else
ncBelowZSSince := 0
ncBelowZSCount := ncBelowZSCount + 1 // Below zero continues
// ----------------------------
// ---- Strategy Variables
// ----------------------------
var float fltEntryPrice = 0.0
var float fltExitPrice = 0.0
var float fltStopPrice = 0.0
var float fltEntryHigh = 0.0
var float fltEntryLow = 0.0
var float fltDefaultSize = 0.0
var float fltCurrentSize = 0.0
var bool bPullback = false
var bool bFEERise = false
var bool bFEEFall = false
var int ncPyramidCount = 0
var int nPyramidWaveID = 0
var int nEntryTrendDir = 0
var int ncConsecLosses = 0
var bool bNascentEntry = false
var bool bHemiTransit = false
var float fltLastLevel = 0.0
var float fltMAELevel = 0.0
string strLongName = "WBHDrive-L"
string strShortName = "WBHDrive-S"
string strLongStop = "WBHD-L-Stop"
string strShortStop = "WBHD-S-Stop"
string strTradingMode = inputTradingMode
float fltMinProfit = inputMinProfit
float fltStopOffset = inputStopOffset
float fltPryramidSpan = inputPryramidSpan
float fltRiseEventNet = inputRiseEventNet
float fltRiseEventROC = inputRiseEventROC
float fltMinZScoreABZ = inputMinZScoreABZ
float fltFallEventNet = inputFallEventNet
float fltFallEventROC = inputFallEventROC
float fltMinZScoreBLZ = inputMinZScoreBLZ
float fltFastEMARiseNet = inputFastEMARiseNet
float fltFastEMARiseROC = inputFastEMARiseROC
float fltFastEMAFallNet = inputFastEMAFallNet
float fltFastEMAFallROC = inputFastEMAFallROC
int ncMaxAddOns = inputMaxAddOns
bool bPyramidBaleOut = inputPyramidBaleOut
bool bAccumulateLong = inputAccumulateLong
bool bAccumulateShort = inputAccumulateShort
bool bLongNascent = inputLongNascent
bool bLongCrossExit = inputLongCrossExit
bool bLongSignalExit = inputLongSignalExit
bool bLongEventExit = inputLongEventExit
bool bLongStochExit = inputLongStochExit
bool bShortNascent = inputShortNascent
bool bShortCrossExit = inputShortCrossExit
bool bShortSignalExit = inputShortSignalExit
bool bShortEventExit = inputShortEventExit
bool bShortStochExit = inputShortStochExit
float fltNetProfit = 0.0
float fltNumShares = 0.0
float fltExpected = 0.0
bool bAlreadyIn = false
bool bProfitable = false
int nPositionDir = 0
bool bCrossRise = false
bool bCrossFall = false
bool bOpenLong = false
bool bOpenShort = false
bool bOpenTrade = false
bool bCloseLong = false
bool bCloseShort = false
bool bCloseTrade = false
calcPipsProfit(nTradeDir, fltPriceNow, fltOpenPrice) =>
float fltProfit = 0.0
if (nTradeDir == 1)
fltProfit := fltPriceNow - fltOpenPrice
if (nTradeDir == -1)
fltProfit := fltOpenPrice - fltPriceNow
float fltResult = fltProfit
// ---------------------------------
// --- Statistical Event Calculation
// ---------------------------------
bool bRiseALEvent = (((fltRiseEventNet > 0.0) and (fltRiseEventROC > 0.0)) and (isMinimumNetChgROC(ncRiseALBarsSince, fltRiseALNetChg, fltRiseEventNet, fltRiseEventROC) == true))
bool bFallALEvent = (((fltFallEventNet > 0.0) and (fltFallEventROC > 0.0)) and (isMinimumNetChgROC(ncFallALBarsSince, fltFallALNetChg, fltFallEventNet, fltFallEventROC) == true))
bool bRiseEMEvent = (((fltFastEMARiseNet > 0.0) and (fltFastEMARiseROC > 0.0)) and (isMinimumNetChgROC(ncRiseEMBarsSince, fltRiseEMNetChg, fltFastEMARiseNet, fltFastEMARiseROC) == true))
bool bFallEMEvent = (((fltFastEMAFallNet > 0.0) and (fltFastEMAFallROC > 0.0)) and (isMinimumNetChgROC(ncFallEMBarsSince, fltFallEMNetChg, fltFastEMAFallNet, fltFastEMAFallROC) == true))
var float fltHTFEventHigh = 0.0
var float fltHTFEventLow = 0.0
var int nLastHTFEvent = 0
if (bRiseALEvent == true)
fltHTFEventHigh := seriesClose
nLastHTFEvent := 1
if (bFallALEvent == true)
fltHTFEventLow := seriesClose
nLastHTFEvent := -1
bool bRiseStochas = (((htf_seriesDLine > 80) and (bFullFanCone == true)) or ((htf_seriesSlowD > 90) and (bDurableTrendRise == true)) or ((htf_seriesDLine > 90) and (bPartialTrendRise == true) and (fltHTFEventHigh > 0.0) and (seriesClose > fltHTFEventHigh)))
bool bFallStochas = (((htf_seriesDLine < 20) and (bDownFanCone == true)) or ((htf_seriesSlowD < 10) and (bDurableTrendFall == true)) or ((htf_seriesDLine < 10) and (bPartialTrendFall == true) and (fltHTFEventLow > 0.0) and (seriesClose < fltHTFEventLow)))
var int nImpulseWaveDir = 0
var int nImpulseWaveID = 0
int nWaveDirNow = 0
if (htf_seriesFastLinReg > htf_seriesSlowLinReg)
nWaveDirNow := 1
if (htf_seriesFastLinReg < htf_seriesSlowLinReg)
nWaveDirNow := -1
if (nWaveDirNow != nImpulseWaveDir)
nImpulseWaveDir := nWaveDirNow
nImpulseWaveID := nImpulseWaveID + 1
// ----------------------------
// ---- Actual Strategy
// ----------------------------
nPositionDir := (strategy.position_size < 0) ? -1 : (strategy.position_size > 0) ? 1 : 0
fltNumShares := abs(strategy.position_size)
fltNetProfit := strategy.openprofit
fltExpected := (fltMinProfit * fltNumShares)
bProfitable := (fltNetProfit >= fltExpected)
if ((strategy.position_entry_name == strLongName) or (strategy.position_entry_name == strShortName))
bAlreadyIn := true
if (bProfitable == true)
bProfitable := (calcPipsProfit(nPositionDir, seriesClose, fltEntryPrice) >= fltMinProfit)
if (bAlreadyIn == false)
if (fltEntryPrice > 0.0)
ncConsecLosses := ncConsecLosses + 1
ncPyramidCount := 0
fltLastLevel := 0.0
fltEntryPrice := 0.0
fltStopPrice := 0.0
bPullback := false
bFEERise := false
bFEEFall := false
// ----------------------------
// ---- Entry Condition - Long
// ----------------------------
bCrossRise := crossover(seriesFastCross, seriesSlowCross)
if ((bAlreadyIn == false) and (strTradingMode != "No Trade"))
if (bCrossRise == true)
if ((seriesClose > htf_seriesTrendDEMA) and (strTradingMode != "Range"))
bOpenLong := true
bNascentEntry := false
else if ((bLongNascent == true) and (bHTFNascentRise == true))
bOpenLong := true
bNascentEntry := true
// ----------------------------
// ---- Entry Condition - Short
// ----------------------------
bCrossFall := crossunder(seriesFastCross, seriesSlowCross)
if ((bAlreadyIn == false) and (bOpenLong == false) and (strTradingMode != "No Trade"))
if (bCrossFall == true)
if ((seriesClose < htf_seriesTrendDEMA) and (strTradingMode != "Range"))
bOpenShort := true
bNascentEntry := false
else if ((bShortNascent == true) and (bHTFNascentFall == true))
bOpenShort := true
bNascentEntry := true
// ----------------------------
// ---- Conditional Close
// ----------------------------
if (bAlreadyIn == true)
if (htf_seriesZScore > fltMinZScoreABZ)
bFEERise := true
if (htf_seriesZScore < (fltMinZScoreBLZ * (-1)))
bFEEFall := true
if (bAlreadyIn == true)
if ((nPositionDir == 1) and (bProfitable == true))
if ((bLongCrossExit == true) and (bHTFSignalFall == true))
bCloseLong := true
if ((bLongSignalExit == true) and (bHTFSignalRise == true) and (bRiseALEvent == true) and (bFEERise == true))
bCloseLong := true
if ((bLongEventExit == true) and (bRiseEMEvent == true) and (bFastAboveSignal == true) and (bHTFFastAboveTrend == true))
bCloseLong := true
if ((bLongStochExit == true) and (bRiseStochas == true))
bCloseLong := true
if ((nPositionDir == -1) and (bProfitable == true))
if ((bShortCrossExit == true) and (bHTFSignalRise == true))
bCloseShort := true
if ((bShortSignalExit == true) and (bHTFSignalFall == true) and (bFallALEvent == true) and (bFEEFall == true))
bCloseShort := true
if ((bShortEventExit == true) and (bFallEMEvent == true) and (bFastBelowSignal == true) and (bHTFFastBelowTrend == true))
bCloseShort := true
if ((bShortStochExit == true) and (bFallStochas == true))
bCloseShort := true
// ----------------------------
// ---- Flip Flop Condition
// ----------------------------
if (bAlreadyIn == true)
if ((nPositionDir == 1) and (seriesClose > htf_seriesTrendDEMA) and (bNascentEntry == true))
bHemiTransit := true
if ((nPositionDir == -1) and (seriesClose < htf_seriesTrendDEMA) and (bNascentEntry == true))
bHemiTransit := true
if ((bAlreadyIn == true) and (strTradingMode == "Flip Flop"))
if (nPositionDir == 1)
if ((seriesClose < fltEntryPrice) and (bFallEMEvent == true) and (bFastBelowSignal == true) and (bHTFFastBelowTrend == true) and (htf_seriesSlowLinReg < htf_seriesTrendDEMA))
if ((bNascentEntry == true) and (bHemiTransit == true))
bCloseLong := true
if ((bNascentEntry == true) and (htf_seriesFastAlma < htf_seriesSlowLinReg) and (htf_seriesFastLinReg < htf_seriesSlowLinReg) and (bFallALEvent == true) and (bAccumulateLong == false))
bCloseLong := true
if ((nEntryTrendDir == 1) and (bNascentEntry == false) and (inputExclusiveLong == false))
bCloseLong := true
if (nPositionDir == -1)
if ((seriesClose > fltEntryPrice) and (bRiseEMEvent == true) and (bFastAboveSignal == true) and (bHTFFastAboveTrend == true) and (htf_seriesSlowLinReg > htf_seriesTrendDEMA))
if ((bNascentEntry == true) and (bHemiTransit == true))
bCloseShort := true
if ((bNascentEntry == true) and (htf_seriesFastAlma > htf_seriesSlowLinReg) and (htf_seriesFastLinReg > htf_seriesSlowLinReg) and (bRiseALEvent == true) and (bAccumulateShort == false))
bCloseShort := true
if ((nEntryTrendDir == -1) and (bNascentEntry == false) and (inputExclusiveShort == false))
bCloseShort := true
// ----------------------------
// ---- Bale Out Condition
// ----------------------------
bool bBailingOut = false
if (nPositionDir == 1)
if ((bPyramidBaleOut == true) and (seriesClose > htf_seriesTrendDEMA) and (bRiseStochas == true) and (htf_seriesFastAlma > htf_seriesSlowLinReg) and (htf_seriesFastLinReg > htf_seriesSlowLinReg) and (htf_seriesSlowLinReg > htf_seriesTrendDEMA))
if (fltNetProfit > (fltExpected * 2.0))
bCloseLong := true
bBailingOut := true
if (nPositionDir == -1)
if ((bPyramidBaleOut == true) and (seriesClose < htf_seriesTrendDEMA) and (bFallEMEvent == true) and (bFastBelowSignal == true) and (bHTFFastBelowTrend == true) and (htf_seriesSlowLinReg < htf_seriesTrendDEMA))
if (fltNetProfit > (fltExpected * 2.0))
bCloseShort := true
bBailingOut := true
// ----------------------------
// ---- Open Trade
// ----------------------------
calcQuantity() =>
float fltTradeSize = fltCurrentSize
if (fltDefaultSize > 0.0)
fltTradeSize := ((ncMaxAddOns > 0) and (fltDefaultSize > 0.0) and (ncConsecLosses > 0) and (ncConsecLosses < ncMaxAddOns)) ? (fltDefaultSize * (ncConsecLosses + 1)) : fltDefaultSize
float fltResult = fltTradeSize
float fltQuantity = 0.0
if ((bOpenLong == true) or (bOpenShort == true))
fltQuantity := calcQuantity()
fltEntryPrice := seriesClose
fltEntryHigh := seriesHigh
fltEntryLow := seriesLow
fltLastLevel := fltEntryPrice
fltMAELevel := 0.0
fltStopPrice := 0.0
bOpenTrade := true
bFEERise := false
bFEEFall := false
bPullback := false
bHemiTransit := false
ncPyramidCount := 0
nEntryTrendDir := (seriesClose > htf_seriesTrendDEMA) ? 1 : -1
if (bOpenLong == true)
if (fltStopOffset > 0.0)
fltStopPrice := (seriesLow - fltStopOffset)
if (fltQuantity > 0.0)
strategy.entry(strLongName, strategy.long, qty = fltQuantity, alert_message = "entry stop = " + tostring(fltStopPrice))
if (fltQuantity == 0.0)
strategy.entry(strLongName, strategy.long, alert_message = "entry stop = " + tostring(fltStopPrice))
fltCurrentSize := abs(strategy.position_size)
if (fltStopPrice > 0.0)
strategy.exit(strLongStop, strLongName, stop = fltStopPrice, alert_message = "stop = " + tostring(fltStopPrice))
if (bOpenShort == true)
if (fltStopOffset > 0.0)
fltStopPrice := (seriesHigh + fltStopOffset)
if (fltQuantity > 0.0)
strategy.entry(strShortName, strategy.short, qty = fltQuantity, alert_message = "entry stop = " + tostring(fltStopPrice))
if (fltQuantity == 0.0)
strategy.entry(strShortName, strategy.short, alert_message = "entry stop = " + tostring(fltStopPrice))
fltCurrentSize := abs(strategy.position_size)
if (fltStopPrice > 0.0)
strategy.exit(strShortStop, strShortName, stop = fltStopPrice, alert_message = "stop = " + tostring(fltStopPrice))
if (fltDefaultSize == 0.0)
fltDefaultSize := abs(strategy.position_size)
// ----------------------------
// ---- Close Trade
// ----------------------------
var int ncLastConsecs = 0
if (bCloseLong == true)
fltExitPrice := seriesClose
strategy.close( strLongName, when = true, alert_message = "exit profit = " + tostring(fltExitPrice - fltEntryPrice))
strategy.cancel(strLongName)
bCloseTrade := true
if (bCloseShort == true)
fltExitPrice := seriesClose
strategy.close( strShortName, when = true, alert_message = "exit profit = " + tostring(fltEntryPrice - fltExitPrice))
strategy.cancel(strShortName)
bCloseTrade := true
if (bCloseTrade == true)
ncLastConsecs := ncConsecLosses
ncConsecLosses := (bProfitable == true) ? 0 : ncConsecLosses + 1
fltLastLevel := 0.0
fltEntryPrice := 0.0
fltStopPrice := 0.0
bPullback := false
bFEERise := false
bFEEFall := false
var string strBadRunDate = ""
var int ncMaxConsecs = 0
if (ncConsecLosses > ncMaxConsecs)
ncMaxConsecs := ncConsecLosses
strBadRunDate := tostring(year) + "-" + tostring(month, "##") + "-" + tostring(dayofmonth, "##") + " [" + tostring(hour, "##") + ":" + tostring(minute, "##") + ":00]"
// ----------------------------
// ---- Pyramid Technology
// ----------------------------
if ((nPositionDir == 1) and (seriesSlowD < 20) and ((bFallALEvent == true) or (bFallStochas == true)))
bPullback := true
if ((nPositionDir == -1) and (seriesSlowD > 80) and ((bRiseALEvent == true) or (bRiseStochas == true)))
bPullback := true
IsPyramidFall() =>
bool bResult = false
bool bPassed = false
bool bExceedingSpan = ((fltPryramidSpan > 0.0) and ((fltLastLevel - seriesClose) > fltPryramidSpan))
if ((bCrossRise == true) and (seriesClose > htf_seriesTrendDEMA) and (bHTFFastAboveTrend == true) and (seriesClose > fltLastLevel) and (bPullback == true))
bPassed := true
else if ((seriesClose < fltLastLevel) and (bExceedingSpan == true) and (seriesClose > fltEntryPrice) and ((bFallALEvent == true) or (bFallEMEvent == true) or (bFallStochas == true)))
bPassed := true
else if ((seriesClose < fltLastLevel) and (bExceedingSpan == true) and (seriesClose < fltEntryPrice) and (bFallALEvent == true) and (bFallStochas == true) and (bAccumulateLong == true) and (nImpulseWaveID > nPyramidWaveID))
bPassed := true
bResult := bPassed
IsPyramidRise() =>
bool bResult = false
bool bPassed = false
bool bExceedingSpan = ((fltPryramidSpan > 0.0) and ((seriesClose - fltLastLevel) > fltPryramidSpan))
if ((bCrossFall == true) and (seriesClose < htf_seriesTrendDEMA) and (bHTFFastBelowTrend == true) and (seriesClose < fltLastLevel) and (bPullback == true))
bPassed := true
else if ((seriesClose > fltLastLevel) and (bExceedingSpan == true) and (seriesClose < fltEntryPrice) and ((bRiseALEvent == true) or (bRiseEMEvent == true) or (bRiseStochas == true)))
bPassed := true
else if ((seriesClose > fltLastLevel) and (bExceedingSpan == true) and (seriesClose > fltEntryPrice) and (bRiseALEvent == true) and (bRiseStochas == true) and (bAccumulateShort == true) and (nImpulseWaveID > nPyramidWaveID))
bPassed := true
bResult := bPassed
bool bNewPyramidLevel = false
bool bPyramidFall = IsPyramidFall()
bool bPyramidRise = IsPyramidRise()
if (bAlreadyIn == true)
if ((nPositionDir == 1) and (bPyramidFall == true))
bNewPyramidLevel := true
strategy.entry(strLongName, strategy.long, alert_message="pyramid level = " + tostring(ncPyramidCount + 1))
strategy.exit(strLongStop, strLongName, stop = fltStopPrice, alert_message="scale out level = " + tostring(ncPyramidCount + 1))
if ((nPositionDir == -1) and (bPyramidRise == true))
bNewPyramidLevel := true
strategy.entry(strShortName, strategy.short, alert_message="pyramid level = " + tostring(ncPyramidCount + 1))
strategy.exit(strShortStop, strShortName, stop = fltStopPrice, alert_message="scale out level = " + tostring(ncPyramidCount + 1))
if (bNewPyramidLevel == true)
ncPyramidCount := ncPyramidCount + 1
nPyramidWaveID := nImpulseWaveID
fltLastLevel := seriesClose
bPullback := false
if (ncPyramidCount == 1)
fltMAELevel := seriesClose
if ((nPositionDir == 1) and (seriesClose < fltMAELevel))
fltMAELevel := seriesClose
if ((nPositionDir == -1) and (seriesClose > fltMAELevel))
fltMAELevel := seriesClose
var int ncHighestLevel = 0
if (ncPyramidCount > ncHighestLevel)
ncHighestLevel := ncPyramidCount
// ----------------------------
// ---- Strategy Plots
// ----------------------------
// HTF Trend Lines
float plotSlowLinReg = na
float plotFastLinReg = na
float plotTrendDEMA = na
float plotFastAlma = na
float plotFastEMA = na
if (inputShowLines == true)
plotSlowLinReg := htf_seriesSlowLinReg
plotFastLinReg := htf_seriesFastLinReg
plotTrendDEMA := htf_seriesTrendDEMA
plotFastAlma := htf_seriesFastAlma
plotFastEMA := seriesFastEMA
plot(plotSlowLinReg, color = color.orange, linewidth = 2, title = "SlowLinReg")
plot(plotFastLinReg, color = color.green, linewidth = 2, title = "FastLinReg")
plot(plotTrendDEMA, color = color.purple, linewidth = 2, title = "TrendDEMA")
plot(plotFastAlma, color = color.blue, linewidth = 2, title = "FastAlma")
plot(plotFastEMA, color = color.yellow, linewidth = 2, title = "FastEMA")
// Entry Crossover Background Fill
bgcolor(((inputShowCrosses == true) and (bCrossRise == true)) ? color.blue : na)
bgcolor(((inputShowCrosses == true) and (bCrossFall == true)) ? color.red : na)
// HTF Event Background Fill
bgcolor(((inputShowEvents == true) and (bRiseALEvent == true)) ? color.blue : na)
bgcolor(((inputShowEvents == true) and (bFallALEvent == true)) ? color.red : na)
// Entry EMA Event Background Fill
bgcolor(((inputShowEMPeaks == true) and (bRiseEMEvent == true)) ? color.blue : na)
bgcolor(((inputShowEMPeaks == true) and (bFallEMEvent == true)) ? color.red : na)
// Stochastic Event Background Fill
bgcolor(((inputShowStochEvent == true) and (bRiseStochas == true)) ? color.blue : na)
bgcolor(((inputShowStochEvent == true) and (bFallStochas == true)) ? color.red : na)
// Consecutive Losses Background Fill
bgcolor(((inputShowConsecLoss == true) and (ncConsecLosses > 0)) ? color.red : na)
// -----------------------------------------------------------------------------
// ----- [ BALE OUT MARKERS ] -------------------------------------------------
// -----------------------------------------------------------------------------
if ((inputShowBaleOuts == true) and (bBailingOut == true))
string txtReport = " Bale Out Exit"
txtReport := txtReport + "\n" + " Net Profit: " + tostring(fltNetProfit, "#.####")
txtReport := txtReport + "\n" + " Position Size: " + tostring(fltNumShares, "#.####")
txtReport := txtReport + "\n" + " Pyramid Count: " + tostring(ncPyramidCount)
txtReport := txtReport + "\n" + " MAE Level: " + tostring(fltMAELevel, "#.####")
txtReport := txtReport + "\n" + " Consec Losses: " + tostring(ncLastConsecs)
label.new(bar_index, high, txtReport, xloc=xloc.bar_index, yloc=yloc.belowbar, style=label.style_labelup, color=#FF0000, textcolor=color.white, size=size.normal, textalign=text.align_left)
// -----------------------------------------------------------------------------
// ----- [ REPORT ] ------------------------------------------------------------
// -----------------------------------------------------------------------------
int ncBarsOffChart = 8
string txtReport = ""
txtReport := txtReport + "╒═════════════════╕"
txtReport := txtReport + "\n" + " Minimum Tick Size: " + tostring(syminfo.mintick)
txtReport := txtReport + "\n" + " Maximum Pyramids: " + tostring(ncHighestLevel + 1)
txtReport := txtReport + "\n" + " Consecutive Losses: " + tostring(ncMaxConsecs)
txtReport := txtReport + "\n" + " Date: " + strBadRunDate
txtReport := txtReport + "\n" + " Max TV Drawdown: " + tostring(strategy.max_drawdown, "#.####")
txtReport := txtReport + "\n" + " Max TV Contracts: " + tostring(strategy.max_contracts_held_all, "#.####")
txtReport := txtReport + "\n" + "╘═════════════════╛"
if (inputReport == true)
lblEndOfChart = label.new(time + (40 * (time - time[1])), low, txtReport, xloc=xloc.bar_time, yloc=yloc.price, style=label.style_labeldown, color=color.navy, textcolor=color.white, size=size.normal, textalign=text.align_left)
label.delete(lblEndOfChart[1])
|
MACD + DMI Scalping with Volatility Stop by (Coinrule) | https://www.tradingview.com/script/nD83sb4E-MACD-DMI-Scalping-with-Volatility-Stop-by-Coinrule/ | Coinrule | https://www.tradingview.com/u/Coinrule/ | 391 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=4
strategy(shorttitle='(MACD + DMI Scalping with Volatility Stop',title='MACD + DMI Scalping with Volatility Stop by (Coinrule)', overlay=true, initial_capital = 100, process_orders_on_close=true, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type=strategy.commission.percent, commission_value=0.1)
// Works better on 3h, 1h, 2h, 4h
//Backtest dates
fromMonth = input(defval = 1, title = "From Month", type = input.integer, minval = 1, maxval = 12)
fromDay = input(defval = 1, title = "From Day", type = input.integer, minval = 1, maxval = 31)
fromYear = input(defval = 2021, 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"
// DMI and MACD inputs and calculations
[pos_dm, neg_dm, avg_dm] = dmi(14, 14)
[macd, macd_signal, macd_histogram] = macd(close, 12, 26, 9)
Take_profit= ((input (3))/100)
longTakeProfit = strategy.position_avg_price * (1 + Take_profit)
length = input(20, "Length", minval = 2)
src = input(close, "Source")
factor = input(2.0, "vStop Multiplier", minval = 0.25, step = 0.25)
volStop(src, atrlen, atrfactor) =>
var max = src
var min = src
var uptrend = true
var stop = 0.0
atrM = nz(atr(atrlen) * atrfactor, tr)
max := max(max, src)
min := min(min, src)
stop := nz(uptrend ? max(stop, max - atrM) : min(stop, min + atrM), src)
uptrend := src - stop >= 0.0
if uptrend != nz(uptrend[1], true)
max := src
min := src
stop := uptrend ? max - atrM : min + atrM
[stop, uptrend]
[vStop, uptrend] = volStop(src, length, factor)
closeLong = close > longTakeProfit or crossunder(close, vStop)
//Entry
strategy.entry(id="long", long = true, when = crossover(macd, macd_signal) and pos_dm > neg_dm and window())
//Exit
strategy.close("long", when = closeLong and window())
|
Momentum Strategy | https://www.tradingview.com/script/XhCZbT4b-Momentum-Strategy/ | REV0LUTI0N | https://www.tradingview.com/u/REV0LUTI0N/ | 124 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © REV0LUTI0N
//@version=4
// Strategy
strategy("Momentum Strategy", overlay=true, initial_capital = 10000, default_qty_value = 10000, default_qty_type = strategy.cash)
// Strategy Backtesting
startDate = input(timestamp("2021-10-01T00:00:00"), type = input.time, title='Backtesting Start Date')
finishDate = input(timestamp("9999-12-31T00:00:00"), type = input.time, title='Backtesting End Date')
time_cond = time >= startDate and time <= finishDate
//Time Restriction Settings
startendtime = input("", title='Time Frame To Enter Trades')
enableclose = input(false, title='Enable Close Trade At End Of Time Frame')
timetobuy = (time(timeframe.period, startendtime))
timetoclose = na(time(timeframe.period, startendtime))
// Momentum Code
i_len = input(defval = 12, title = "Momentum Length", minval = 1)
i_src = input(defval = close, title = "Momentum Source")
i_percent = input(defval = true, title = "Percent?")
i_mom = input(defval = "MOM2", title = "MOM Choice", options = ["MOM1", "MOM2"])
momentum(seria, length, percent) =>
_mom = percent ? ( (seria / seria[length]) - 1) * 100 : seria - seria[length]
_mom
mom0 = momentum(i_src, i_len, i_percent)
mom1 = momentum(mom0, 1, i_percent)
mom2 = momentum(i_src, 1, i_percent)
momX = mom1
if i_mom == "MOM2"
momX := mom2
doublemom = input(true, title="Use Double Momentum Entries")
singlemom = input(false, title="Use Single Momentum Entries")
// EMA Filter
noemafilter = input(true, title="No EMA Filter")
useemafilter = input(false, title="Use EMA Filter")
ema_length = input(defval=15, minval=1, title="EMA Length")
emasrc = input(close, title="EMA Source")
ema = ema(emasrc, ema_length)
plot(ema, "EMA", style=plot.style_linebr, color=#cad850, linewidth=2)
// Stop Loss & Take Profit % Based
enablesl = input(false, title='Enable Stop Loss')
enabletp = input(false, title='Enable Take Profit')
stopTick = input(5.0, title='Stop Loss %', type=input.float, step=0.1) / 100
takeTick = input(10.0, title='Take Profit %', type=input.float, step=0.1) / 100
longStop = strategy.position_avg_price * (1 - stopTick)
shortStop = strategy.position_avg_price * (1 + stopTick)
shortTake = strategy.position_avg_price * (1 - takeTick)
longTake = strategy.position_avg_price * (1 + takeTick)
plot(strategy.position_size > 0 and enablesl ? longStop : na, style=plot.style_linebr, color=color.red, linewidth=1, title="Long Fixed SL")
plot(strategy.position_size < 0 and enablesl ? shortStop : na, style=plot.style_linebr, color=color.red, linewidth=1, title="Short Fixed SL")
plot(strategy.position_size > 0 and enabletp ? longTake : na, style=plot.style_linebr, color=color.green, linewidth=1, title="Long Take Profit")
plot(strategy.position_size < 0 and enabletp ? shortTake : na, style=plot.style_linebr, color=color.green, linewidth=1, title="Short Take Profit")
// Alert messages
message_enterlong = input("", title="Long Entry message")
message_entershort = input("", title="Short Entry message")
message_closelong = input("", title="Close Long message")
message_closeshort = input("", title="Close Short message")
// Strategy Execution
// Entry No EMA
if (mom0 > 0 and momX > 0 and time_cond and timetobuy and doublemom and noemafilter)
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if (mom0 < 0 and momX < 0 and time_cond and timetobuy and doublemom and noemafilter)
strategy.entry("Short", strategy.short, alert_message = message_entershort)
if (mom0 > 0 and time_cond and timetobuy and singlemom and noemafilter)
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if (mom0 < 0 and time_cond and timetobuy and singlemom and noemafilter)
strategy.entry("Short", strategy.short, alert_message = message_entershort)
// Entry Use EMA
if (mom0 > 0 and momX > 0 and close > ema and time_cond and timetobuy and doublemom and useemafilter)
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if (mom0 < 0 and momX < 0 and close < ema and time_cond and timetobuy and doublemom and useemafilter)
strategy.entry("Short", strategy.short, alert_message = message_entershort)
if (mom0 > 0 and time_cond and close > ema and timetobuy and singlemom and useemafilter)
strategy.entry("Long", strategy.long, alert_message = message_enterlong)
if (mom0 < 0 and time_cond and close < ema and timetobuy and singlemom and useemafilter)
strategy.entry("Short", strategy.short, alert_message = message_entershort)
// Exit at close
if strategy.position_size > 0 and timetoclose and enableclose
strategy.close_all(alert_message = message_closelong)
if strategy.position_size < 0 and timetoclose and enableclose
strategy.close_all(alert_message = message_closeshort)
// Exit SL and TP
if strategy.position_size > 0 and enablesl and time_cond
strategy.exit(id="Close Long", stop=longStop, limit=longTake, alert_message = message_closelong)
if strategy.position_size < 0 and enablesl and time_cond
strategy.exit(id="Close Short", stop=shortStop, limit=shortTake, alert_message = message_closeshort)
if strategy.position_size > 0 and enabletp and time_cond
strategy.exit(id="Close Long", stop=longStop, limit=longTake, alert_message = message_closelong)
if strategy.position_size < 0 and enabletp and time_cond
strategy.exit(id="Close Short", stop=shortStop, limit=shortTake, alert_message = message_closeshort)
|
Vin's Playzone Strategy | https://www.tradingview.com/script/QL0BFJH8-Vin-s-Playzone-Strategy/ | Vvaz_ | https://www.tradingview.com/u/Vvaz_/ | 144 | strategy | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Vvaz_
//base-on CDC ActionZone By Piriya a simple 2EMA and is most suitable for use with medium volatility market
//@version=5
strategy(title='Playzone', shorttitle='VXIZ', overlay=true, initial_capital=1000)
//variable
srcf = input(title='Source of price', defval=close)
tffix = input(title='Fixed Timeframe?', defval=true)
tfn = input.timeframe(title='Timeframe in', defval='D')
ema1 = input(title='Fast EMA', defval=13)
ema2 = input(title='Slow EMA', defval=26)
ema3 = input(title='Base-Line', defval=60)
smooter = input(title='Smoothing period', defval=2)
fillbar = input(title='Fill Bar Color', defval=false)
emasw = input(title='Show Green-Red EMA?', defval=true)
bssw = input(title='Show Buy-Sell signal?', defval=true)
blsw = input(title='Show Base-line?', defval=true)
fxbl = input(title='Fixed Base-line?', defval=true)
plotmm = input(title='Show Long-Short?', defval=true)
plotmmsm = input.int(title='RSI Smoothing', defval=3, minval=0, maxval=3)
//ema
xcross = ta.ema(srcf, smooter)
efast = tffix ? ta.ema(request.security(syminfo.tickerid, tfn, ta.ema(srcf, ema1), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on), smooter) : ta.ema(xcross, ema1)
eslow = tffix ? ta.ema(request.security(syminfo.tickerid, tfn, ta.ema(srcf, ema2), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on), smooter) : ta.ema(xcross, ema2)
ema3x = fxbl ? ta.ema(request.security(syminfo.tickerid, tfn, ta.ema(srcf, ema3), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on), smooter) : ta.ema(xcross, ema3)
emabl = ta.ema(xcross, 1)
//Zone
Bull = efast > eslow
Bear = efast < eslow
G1 = Bull and xcross > efast //buy
G2 = Bear and xcross > efast and xcross > eslow //pre-buy1
G3 = Bear and xcross > efast and xcross < eslow //pre-buy2
R1 = Bear and xcross < efast //sell
R2 = Bull and xcross < efast and xcross < eslow //pre-sell1
R3 = Bull and xcross < efast and xcross > eslow //pre-sell2
//color
bcl = G1 ? color.green : G2 ? color.yellow : G3 ? color.orange : R1 ? color.red : R2 ? color.orange : R3 ? color.yellow : color.black
barcolor(color=fillbar ? bcl : na)
//plots
line1 = plot(blsw ? ema3x : na, 'Base-Line', color=color.new(color.yellow, 0))
line2 = plot(emasw ? efast : na, 'Fast EMA', color=color.new(color.green, 0))
line3 = plot(emasw ? eslow : na, 'Slow EMA', color=color.new(color.red, 30))
fillcl = Bull ? color.new(color.green, 80) : Bear ? color.new(color.red, 80) : color.new(color.black, 99)
fill(line2, line3, fillcl )
//actions
buywhen = G1 and G1[1] == 0
sellwhen = R1 and R1[1] == 0
bullish = ta.barssince(buywhen) < ta.barssince(sellwhen)
bearish = ta.barssince(sellwhen) < ta.barssince(buywhen)
buy = bearish[1] and buywhen
sell = bullish[1] and sellwhen
//plot trend
plotshape(bssw ? buy : na, style=shape.diamond, title='BUY', location=location.belowbar, color=color.new(color.green, 0), size=size.tiny)
plotshape(bssw ? sell : na, style=shape.diamond, title='Sell', location=location.abovebar, color=color.new(color.red, 0), size=size.tiny)
// Momentum Signal using StochRSI
smoothK = input.int(27, 'StochRSI smooth K', minval=1)
smoothD = input.int(18, 'StochRSI smooth D', minval=1)
RSIlen = input.int(42, 'RSI length', minval=1)
STOlen = input.int(42, 'Stochastic length', minval=1)
SRsrc = input(close, 'Source for StochasticRSI')
OSlel = input.float(30, 'Oversold Threshold', minval=0.00)
OBlel = input.float(70, 'overbought Threshold', minval=0.00)
rsil = ta.rsi(SRsrc, RSIlen)
K = ta.sma(ta.stoch(rsil, rsil, rsil, STOlen), smoothK)
D = ta.sma(K, smoothD)
crossover_1 = ta.crossover(K, D)
crossover_2 = ta.crossover(K, D)
iff_1 = D > OSlel and crossover_2 ? 2 : 0
iff_2 = D < OSlel and crossover_1 ? 4 : iff_1
buymore = bullish ? iff_2 : 0
crossunder_1 = ta.crossunder(K, D)
crossunder_2 = ta.crossunder(K, D)
iff_3 = D < OBlel and crossunder_2 ? 2 : 0
iff_4 = D > OBlel and crossunder_1 ? 4 : iff_3
sellmore = bearish ? iff_4 : 0
//plot momentum
plotshape(plotmm ? buymore > plotmmsm ? buymore : na : na, 'Long', style=shape.triangleup, location=location.belowbar, color=color.new(color.green, 0), size=size.tiny)
plotshape(plotmm ? sellmore > plotmmsm ? sellmore : na : na, 'Short', style=shape.triangledown, location=location.abovebar, color=color.new(color.red, 0), size=size.tiny)
//stratgy excuter
//condition
buycon = buy
sellcon = sell
buycon1 = buymore > plotmmsm
sellcon1 = sellmore > plotmmsm
//confirm_trend
buyfirm = emabl >= ema3x and Bull
sellfirm = emabl <= ema3x and Bear
//Long
strategy.entry('Long', strategy.long, when= buycon and buyfirm , comment='Buy', alert_message='Buy Now!')
strategy.entry('Long', strategy.long, when= buycon1 and buyfirm , comment='Long', alert_message='Buy More!')
strategy.close('Long', when= sell or Bear, comment='Stop-L', alert_message='Take profit Long')
//Short
strategy.entry('Short', strategy.short, when= sellcon and sellfirm , comment='Sell', alert_message='Sell Now!')
strategy.entry('Short', strategy.short, when= sellcon1 and sellfirm , comment='Short', alert_message='Sell More!')
strategy.close('Short', when= buy or Bull, comment='Stop-S', alert_message='Take profit Short') |
Buy and Hold, which day of month is best to buy? | https://www.tradingview.com/script/zw7TUjjg-Buy-and-Hold-which-day-of-month-is-best-to-buy/ | DDecoene | https://www.tradingview.com/u/DDecoene/ | 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/
// © dennis.decoene
//@version=4
strategy(title="Buy and Hold, which day of month is best to buy?", overlay=true, pyramiding=20000)
// Make input options that configure backtest date range
startDate = input(title="Start Date", type=input.integer,
defval=1, minval=1, maxval=31, group="Starting From")
startMonth = input(title="Start Month", type=input.integer,
defval=1, minval=1, maxval=12, group="Starting From")
startYear = input(title="Start Year", type=input.integer,
defval=2021, minval=1800, maxval=2100, group="Starting From")
endDate = input(title="End Date", type=input.integer,
defval=2, minval=1, maxval=31, group="Until")
endMonth = input(title="End Month", type=input.integer,
defval=10, minval=1, maxval=12, group="Until")
endYear = input(title="End Year", type=input.integer,
defval=2021, minval=1800, maxval=2100, group="Until")
entryday = input(title="Entry Day", type=input.integer,
defval=26, minval=1, maxval=31, tooltip="When to enter (buy the asset) each month")
exitday = input(title="Exit Day", type=input.integer,
defval=6, minval=1, maxval=31, tooltip="When to exit (sell the asset) each month")
useExitDay= input(title="Close position on exit day?", type=input.bool, defval=false, tooltip="Use the Exit Day to close each months position it true or close at the end of the period (if false)")
isEntryDay= (dayofmonth(time)==entryday)
isExitDay= (dayofmonth(time)==exitday-1)
inDateRange = (time >= timestamp(syminfo.timezone, startYear,
startMonth, startDate, 0, 0)) and
(time < timestamp(syminfo.timezone, endYear, endMonth, endDate, 0, 0))
if (isEntryDay and inDateRange)
strategy.entry(id="Buy", long=true)
if (isExitDay and useExitDay)
strategy.close_all()
// Exit open market position when date range ends
if (not inDateRange and not useExitDay)
strategy.close_all()
|
Moon Phases Strategy 2015 till 2021 | https://www.tradingview.com/script/nxFDZMC6-Moon-Phases-Strategy-2015-till-2021/ | Joy_Bangla | https://www.tradingview.com/u/Joy_Bangla/ | 275 | strategy | 4 | MPL-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: Joy Bangla
// Full credit goes to Author: Dustin Drummond https://www.tradingview.com/u/Dustin_D_RLT/
// He has allowed me to use his Moon Phase strategy code and modify it.
// Thank you Dustin Drummond for allowing me. I really wanted to test out accuracy of moon phase. And I could not done it
// without your code
//Simple Moon Phases Strategy
//It was created to test the Moon Phase theory compared to just a buy and hold strategy.
// It buy on full Moon and sell on new Moon.
// I also have added ability to add stop loss and target profit if anyone wants to tinker with it.
//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="Moon Phases Strategy 2015 till 2021", shorttitle = "Moon Phases Strategy", 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.lime, 10), offset=1, size=size.normal)
plotshape(newMoon, "New Moon", shape.circle, location.abovebar, color.new(color.red, 10), offset=1, size=size.normal)
// STRATEGY
// === INPUT BACKTEST RANGE ===
fromMonth = input(defval = 1, title = "From Month", type = input.integer, minval = 1, maxval = 12)
fromDay = input(defval = 1, title = "From Day", type = input.integer, minval = 1, maxval = 31)
fromYear = input(defval = 2015, title = "From Year", type = input.integer, minval = 2015, maxval = 2030)
thruMonth = input(defval = 12, title = "Thru Month", type = input.integer, minval = 1, maxval = 11)
thruDay = input(defval = 30, title = "Thru Day", type = input.integer, minval = 1, maxval = 30)
thruYear = input(defval = 2022, title = "Thru Year", type = input.integer, minval = 1900, maxval = 2030)
// === INPUT SHOW PLOT ===
showDate = input(defval = true, title = "Show Date Range", type = input.bool)
// === FUNCTION EXAMPLE ===
start = timestamp(fromYear, fromMonth, fromDay, 00, 00) // backtest start window
finish = timestamp(thruYear, thruMonth, thruDay, 23, 59) // backtest finish window
window() => time >= start and time <= finish ? true : false // create function "within window of time"
longLossPerc = input(title="Long Stop Loss (%)", minval=0.0, step=0.1, defval=9) * 0.01
shortLossPerc = input(title="Short Stop Loss (%)", minval=0.0, step=0.1, defval=9) * 0.01
// Determine stop loss price
longStopPrice = strategy.position_avg_price * (1 - longLossPerc)
shortStopPrice = strategy.position_avg_price * (1 + shortLossPerc)
testLongOnly = input (true, "Test Long Only")
testShortOnly = input (true, "Test Short ONly")
if (window() and testLongOnly)
strategy.entry("buy", strategy.long, when=fullMoon)
strategy.close_all(when=newMoon)
if (window() and testShortOnly)
strategy.entry("sell", strategy.short, when=newMoon)
strategy.close_all(when=fullMoon)
useLongSL = input (false, "Use Long SL")
useShorSL = input (false, "Use Short SL")
// Submit exit orders based on calculated stop loss price
if (strategy.position_size > 0 and useLongSL)
strategy.exit(id="XL STP", stop=longStopPrice)
// Submit exit orders based on calculated stop loss price
if (strategy.position_size < 0 and useShorSL)
strategy.exit(id="XS STP", stop=shortStopPrice) |
[KL] Double Bollinger Bands Strategy (for Crypto/FOREX) | https://www.tradingview.com/script/PKlb8VhL-KL-Double-Bollinger-Bands-Strategy-for-Crypto-FOREX/ | DojiEmoji | https://www.tradingview.com/u/DojiEmoji/ | 253 | strategy | 4 | MPL-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] Double BB Strategy",overlay=true,pyramiding=1)
ENUM_LONG = "LONG"
LONG_MSG_ENTER = input("Long +1 entered", type=input.string, title="Alert MSG for buying (Long position)")
LONG_MSG_EXIT = input("Long -1 closed", type=input.string, title="Alert MSG for closing (Long position)")
ENUM_SHORT = "SHORT"
SHORT_MSG_ENTER = input("Short -1 entered", type=input.string, title="Alert MSG for selling (Short position)")
SHORT_MSG_EXIT = input("Short +1 covered", type=input.string, title="Alert MSG for covering (Short position)")
// Timeframe {
backtest_timeframe_start = input(defval = timestamp("01 Apr 2020 13:30 +0000"), title = "Backtest Start Time", type = input.time)
USE_ENDTIME = input(false,title="Define backtest end-time (If false, will test up to most recent candle)")
backtest_timeframe_end = input(defval = timestamp("19 Apr 2021 19:30 +0000"), title = "Backtest End Time (if checked above)", type = input.time)
within_timeframe = time >= backtest_timeframe_start and (time <= backtest_timeframe_end or not USE_ENDTIME)
// } Timeframe
// Bollinger bands {
BOLL_length = 20, BOLL_src = close, SMA20 = sma(BOLL_src, BOLL_length)
BOLL_sDEV = stdev(BOLL_src, BOLL_length)
BOLL_upper1 = SMA20 + BOLL_sDEV, BOLL_lower1 = SMA20 - BOLL_sDEV
BOLL_upper2 = SMA20 + BOLL_sDEV*2, BOLL_lower2 = SMA20 - BOLL_sDEV*2
SMA_20_plot = plot(SMA20, "Basis", color=#872323, offset = 0)
BOLL_upper1_plot = plot(BOLL_upper1, "BOLL Upper1", color=color.new(color.navy, 50), offset = 0)
BOLL_lower1_plot = plot(BOLL_lower1, "BOLL Lower1", color=color.new(color.navy, 50), offset = 0)
BOLL_upper2_plot = plot(BOLL_upper2, "BOLL Upper2", color=color.new(color.navy, 50), offset = 0)
BOLL_lower2_plot = plot(BOLL_lower2, "BOLL Lower2", color=color.new(color.navy, 50), offset = 0)
fill(BOLL_upper2_plot, BOLL_upper1_plot, title = "Background", color=color.new(#198787, 85))
fill(BOLL_upper1_plot, SMA_20_plot, title = "Background", color=color.new(#198787, 75))
fill(SMA_20_plot, BOLL_lower1_plot, title = "Background", color=color.new(#198787, 75))
fill(BOLL_lower1_plot, BOLL_lower2_plot, title = "Background", color=color.new(#198787, 85))
// { Bollinger bands
// Quantative methods - used for setting stop losses and entry/exit signals {
cv = stdev(close,20)/sma(close,20)
len_drift = input(14,title="lookback period for drift calc.")
percentage_chng = log(close/close[1])
drift = sma(percentage_chng, len_drift) - pow(stdev(percentage_chng, len_drift),2) * 0.5
// } Quant methods
// 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_long = low, TSL_source_short = high
var stop_loss_price_long = float(0)
var stop_loss_price_short = float(2147483647)
var pos_opened_long = false // to be updated in MAIN loop
var pos_opened_short = false // to be updated in MAIN loop
stop_loss_price_long := pos_opened_long ? max(stop_loss_price_long, TSL_source_long - ATR_X2_TSL) : TSL_source_long - ATR_X2_TSL
stop_loss_price_short := pos_opened_short ? min(stop_loss_price_short, TSL_source_short + ATR_X2_TSL) : TSL_source_short + ATR_X2_TSL
// tighten TSL
is_consol = cv < sma(cv,50)
TIGHTEN_TSL = input(true, title="Tighten stop loss when price moves sharply in favorable direction")
if TIGHTEN_TSL
if not is_consol
if pos_opened_long and cv > cv[1]
stop_loss_price_long := max(stop_loss_price_long * (1+percentage_chng*0.5), stop_loss_price_long[1])
if pos_opened_short and cv > cv[1]
stop_loss_price_short := min(stop_loss_price_long * (1+percentage_chng*0.5), stop_loss_price_short[1])
// Plot TSL
TSL_transp_long = pos_opened_long and within_timeframe ? 0 : 100
TSL_transp_short = pos_opened_short and within_timeframe ? 0 : 100
plot(stop_loss_price_long, color=color.new(color.green, TSL_transp_long))
plot(stop_loss_price_short, color=color.new(color.red, TSL_transp_short))
// } Trailing stop loss
// Signals for entry {
is_neutral = close < BOLL_upper1 and close > BOLL_lower1
below_neutral = close < BOLL_lower1 and close > BOLL_lower2
above_neutral = close > BOLL_upper1 and close < BOLL_upper2
atr14 = atr(14)
entry_signal_long = is_consol and close > BOLL_upper1 and atr14 > sma(atr14,5) and drift > 0
entry_signal_short = is_consol and close < BOLL_lower1 and atr14 > sma(atr14,5) and drift < 0
// } Signals for entry
// MAIN:
if within_timeframe
// EXIT ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
if pos_opened_long
strategy.exit(ENUM_LONG, stop=stop_loss_price_long, comment="SL")
if pos_opened_short
strategy.exit(ENUM_SHORT, stop=stop_loss_price_short, comment="SL")
end_of_rally = close < BOLL_upper1 and strategy.position_avg_price > stop_loss_price_long and low < low[1]
if pos_opened_long and (TSL_source_long <= stop_loss_price_long or end_of_rally and not is_consol)
pos_opened_long := false
alert(LONG_MSG_EXIT, alert.freq_once_per_bar)
strategy.close(ENUM_LONG, comment=close < strategy.position_avg_price ? "stop loss" : "take profit")
if pos_opened_short and (TSL_source_short >= stop_loss_price_short)
pos_opened_short := false
alert(SHORT_MSG_EXIT, alert.freq_once_per_bar)
strategy.close(ENUM_SHORT, comment=close > strategy.position_avg_price ? "stop loss" : "take profit")
// ENTRY :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
if entry_signal_long and close > stop_loss_price_long
pos_opened_long := true
alert(LONG_MSG_ENTER, alert.freq_once_per_bar)
strategy.entry(ENUM_LONG, strategy.long, comment="long")
if entry_signal_short
pos_opened_short := true
alert(SHORT_MSG_ENTER, alert.freq_once_per_bar)
strategy.entry(ENUM_SHORT, strategy.short, comment="short")
// CLEAN UP:
if not pos_opened_long
stop_loss_price_long := float(0)
if not pos_opened_short
stop_loss_price_short := float(2147483647) |
Bollinger Bands And Aroon Scalping (by Coinrule) | https://www.tradingview.com/script/iL1kUEgM-Bollinger-Bands-And-Aroon-Scalping-by-Coinrule/ | Coinrule | https://www.tradingview.com/u/Coinrule/ | 397 | strategy | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © relevantLeader16058
//@version=4
strategy(shorttitle='Bollinger bands And Aroon Scalping',title='Bollinger bands And Aroon Scalping (by Coinrule)', overlay=true, initial_capital = 1000, process_orders_on_close=true, default_qty_type = strategy.percent_of_equity, default_qty_value = 30, commission_type=strategy.commission.percent, commission_value=0.1)
//Backtest dates
fromMonth = input(defval = 1, title = "From Month", type = input.integer, minval = 1, maxval = 12)
fromDay = input(defval = 1, title = "From Day", type = input.integer, minval = 1, maxval = 31)
fromYear = input(defval = 2020, title = "From Year", type = input.integer, minval = 1970)
thruMonth = input(defval = 1, title = "Thru Month", type = input.integer, minval = 1, maxval = 12)
thruDay = input(defval = 1, title = "Thru Day", type = input.integer, minval = 1, maxval = 31)
thruYear = input(defval = 2112, title = "Thru Year", type = input.integer, minval = 1970)
showDate = input(defval = true, title = "Show Date Range", type = input.bool)
start = timestamp(fromYear, fromMonth, fromDay, 00, 00) // backtest start window
finish = timestamp(thruYear, thruMonth, thruDay, 23, 59) // backtest finish window
window() => time >= start and time <= finish ? true : false // create function "within window of time"
// BB inputs and calculations
lengthBB = input(20, minval=1)
src = input(close, title="Source")
mult = input(2.0, minval=0.001, maxval=50, title="StdDev")
basis = sma(src, lengthBB)
dev = mult * stdev(src, lengthBB)
upper = basis + dev
lower = basis - dev
offset = input(0, "Offset", type = input.integer, minval = -500, maxval = 500)
lengthAr = input(288, minval=1)
AroonUP = 100 * (highestbars(high, lengthAr+1) + lengthAr)/lengthAr
AroonDown = 100 * (lowestbars(low, lengthAr+1) + lengthAr)/lengthAr
Confirmation = input(90, "Aroon Confirmation")
Stop = input(70, "Aroon Stop")
Bullish = crossunder (close, basis)
Bearish = crossunder (close, upper)
//Entry
strategy.entry(id="long", long = true, when = Bullish and AroonUP > Confirmation and window())
//Exit
strategy.close("long", when = Bearish or AroonUP < Stop and window())
|
Traffic Lights Strategy | https://www.tradingview.com/script/ojICH8B7-Traffic-Lights-Strategy/ | Trading_Solutions_ | https://www.tradingview.com/u/Trading_Solutions_/ | 232 | strategy | 4 | MPL-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
// 4HS Crypto Market Strategy
// This strategy uses 4 ema to get Long or Short Signals
// Length are: 8, 14, 16, 100
// We take long positions when the order of the emas is the following:
// green > yellow > red (As the color of Traffic Lights) and they are above white ema (Used as a filter for long positions)
// We take short positions when the order of the emas is the following:
// green < yellow < red (As the color of inverse Traffic Lights) and they are below white ema (Used as a filter for short positions)
//@version=4
strategy(title="Trafic Lights Strategy",
shorttitle="TLS",
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(defval = timestamp("28 May 2017 13:30 +0000"), title = "Start Time", type = input.time) //Starting time for Backtesting
sep1 = input(title="============ System Conditions ============", type=input.bool, defval=false)
enable_Long = input(true, title="Enable Long Positions") // Enable long Positions
enable_Short = input(true, title="Enable Short Positions") // Enable short Positions
sep2 = input(title="============ Indicator Parameters ============", type=input.bool, defval=false)
f_length = input(title="Fast EMA Length", type=input.integer, defval=8, minval=1)
m_length = input(title="Medium EMA Length", type=input.integer, defval=14, minval=1)
s_length = input(title="Slow EMA Length", type=input.integer, defval=16, minval=1)
filter_L = input(title="EMA Filter", type=input.integer, defval=100, minval=1)
filterRes = input(title="Filter Resolution", type=input.resolution, defval="D") // ema Filter Time Frame
sep3 = input(title="============LONG Profit-Loss Parameters============", type=input.bool, defval=false)
e_Long_TP = input(true, title="Enable a Profit Level?")
e_Long_SL = input(false, title="Enable a S.Loss Level?")
e_Long_TS = input(true, title="Enable a Trailing Stop?")
long_TP_Input = input(40.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
atrLongMultip = input(2.0, title='ATR Multiplier', type=input.float, minval=0.1) // Parameters to calculate Trailing Stop Loss
atrLongLength = input(14, title='ATR Length', type=input.integer, minval=1)
sep4 = input(title="============SHORT Profit-Loss Parameters============", type=input.bool, defval=false)
e_Short_TP = input(true, title="Enable a Profit Level?")
e_Short_SL = input(false, title="Enable a S.Loss Level?")
e_Short_TS = input(true, title="Enable a Trailing Stop?")
short_TP_Input = input(30.0, title='Take Profit %', type=input.float, minval=0)/100
short_SL_Input = input(1.0, title='Stop Loss %', type=input.float, minval=0)/100
atrShortMultip = input(2.0, title='ATR Multiplier', type=input.float, minval=0.1)
atrShortLength = input(14, title='ATR Length', type=input.integer, minval=1)
// Indicators
fema = ema(close, f_length)
mema = ema(close, m_length)
sema = ema(close, s_length)
filter = security(syminfo.tickerid, filterRes, ema(close, filter_L))
plot(fema, title="Fast EMA", color=color.new(color.green, 0))
plot(mema, title="Medi EMA", color=color.new(color.yellow, 0))
plot(sema, title="Slow EMA", color=color.new(color.red, 0))
plot(filter, title="EMA Filter", color=color.new(color.white, 0))
// Entry Conditions
longTrade = strategy.position_size > 0
shortTrade = strategy.position_size < 0
notInTrade = strategy.position_size == 0
inTrade = strategy.position_size != 0
priceEntry = strategy.position_avg_price
goLong = fema > mema and mema > sema and fema > filter and time > i_time and enable_Long and (crossover (fema, mema) or crossover (mema, sema) or crossover (sema, filter))
goShort = fema < mema and mema < sema and fema < filter and time > i_time and enable_Short and (crossunder (fema, mema) or crossunder (mema, sema) or crossunder (sema, filter))
close_L = crossunder(fema, mema)
close_S = crossover (fema, mema)
// Profit and Loss conditions
// Long
long_TP = priceEntry * (1 + long_TP_Input) // Long Position Take Profit Calculation
long_SL = priceEntry * (1 - long_SL_Input) // Long Position Stop Loss Calculation
atrLong = atr(atrLongLength) // Long Position ATR Calculation
long_TS = low - atrLong * atrLongMultip
long_T_stop = 0.0 // Code for calculating Long Positions Trailing Stop Loss/
long_T_stop := if (longTrade)
longStop = long_TS
max(long_T_stop[1], longStop)
else
0
//Short
short_TP = priceEntry * (1 - short_TP_Input) // Long Position Take Profit Calculation
short_SL = priceEntry * (1 + short_SL_Input) // Short Position Stop Loss Calculation
atrShort = atr(atrShortLength) // Short Position ATR Calculation
short_TS = high + atrShort * atrShortMultip
short_T_stop = 0.0 // Code for calculating Short Positions Trailing Stop Loss/
short_T_stop := if shortTrade
shortStop = short_TS
min(short_T_stop[1], shortStop)
else
9999999
// Strategy Long Entry
if goLong and notInTrade
strategy.entry("Go Long", long=strategy.long, comment="Go Long", alert_message="Open Long Position")
if longTrade and close_L
strategy.close("Go Long", when=close_L, comment="Close Long", alert_message="Close Long Position")
if e_Long_TP // Algorithm for Enabled Long Position Profit Loss Parameters
if (e_Long_TS and not e_Long_SL)
strategy.exit("Long TP & TS", "Go Long", limit = long_TP, stop = long_T_stop)
else
if (e_Long_SL and not e_Long_TS)
strategy.exit("Long TP & TS", "Go Long",limit = long_TP, stop = long_SL)
else
strategy.exit("Long TP & TS", "Go Long",limit = long_TP)
else
if not e_Long_TP
if (e_Long_TS and not e_Long_SL)
strategy.exit("Long TP & TS", "Go Long", stop = long_T_stop)
else
if (e_Long_SL and not e_Long_TS)
strategy.exit("Long TP & TS", "Go Long",stop = long_SL)
// Strategy Short Entry
if goShort and notInTrade
strategy.entry("Go Short", long=strategy.short, comment="Go Short", alert_message="Open Short Position")
if shortTrade and close_S
strategy.close("Go Short", comment="Close Short", alert_message="Close Short Position")
if e_Short_TP // Algorithm for Enabled Short Position Profit Loss Parameters
if (e_Short_TS and not e_Short_SL)
strategy.exit("Short TP & TS", "Go Short", limit = short_TP, stop = short_T_stop)
else
if (e_Short_SL and not e_Short_TS)
strategy.exit("Short TP & SL", "Go Short",limit = short_TP, stop = short_SL)
else
strategy.exit("Short TP & TS", "Go Short",limit = short_TP)
else
if not e_Short_TP
if (e_Short_TS and not e_Short_SL)
strategy.exit("Short TS", "Go Short", stop = short_T_stop)
else
if (e_Short_SL and not e_Short_TS)
strategy.exit("Short SL", "Go Short",stop = short_SL)
// Long Position Profit and Loss Plotting
plot(longTrade and e_Long_TP and long_TP ? long_TP : na, title="TP Level", color=color.green, style=plot.style_linebr, linewidth=2)
plot(longTrade and e_Long_SL and long_SL and not e_Long_TS ? long_SL : na, title="SL Level", color=color.red, style=plot.style_linebr, linewidth=2)
plot(longTrade and e_Long_TS and long_T_stop and not e_Long_SL ? long_T_stop : na, title="TS Level", color=color.red, style=plot.style_linebr, linewidth=2)
// Short Position Profit and Loss Plotting
plot(shortTrade and e_Short_TP and short_TP ? short_TP : na, title="TP Level", color=color.green, style=plot.style_linebr, linewidth=2)
plot(shortTrade and e_Short_SL and short_SL and not e_Short_TS ? short_SL : na, title="SL Level", color=color.red, style=plot.style_linebr, linewidth=2)
plot(shortTrade and e_Short_TS and short_T_stop and not e_Short_SL ? short_T_stop : na, title="TS Level", color=color.red, style=plot.style_linebr, linewidth=2)
|