gr_Basic_Settings = "⭐Basic Settings⭐"
Strategy_Select = input.string("Confirmation", title = "Strategy Selector", options = ["None", "Confirmation", "RE Beta", "MS Beta", "SRT Beta" ], group = gr_Basic_Settings, tooltip = "-None: No Strategies will display on the chart \n-Lune - Confirmation: Used to help you confirm your trades and trend direction.\n-RE Beta: This is a simple strategy used primarily for day trades and scalping.\n-MS Beta: This strategy helps you trade momentum, Also primarily used for day trading and scalping.\n-SRT Beta: This is an advanced trading strategy, that helps you with swing trades.")
Sensitivity = input.int(4, title = "Strategy Sensivity", group =gr_Basic_Settings)
Rigor = input.int(5, title = "Strategy Rigor", group =gr_Basic_Settings)
//Use_Color_Pallet = input.bool(defval = true, title = "Color Theme: ", inline = "Color Theme", group = gr_Basic_Settings )
Select_Color_Pallet = input.string(defval = "None", title = "Color Theme:", options = ["None", "Default", "Bright", "Lune", "Ice"], inline = "Color Theme", group = gr_Basic_Settings)
Trade_Bar_Color = input.bool(false, title = "Color Candles based on Trade", group = gr_Basic_Settings)
Dashboard_Loc_1 = input.string("Bottom", title = "Dashboard Location:", options = ["Bottom", "Middle", "Top", "None"], group = GR_Adv_Settings, inline = "Dashboard")
Dashboard_Loc_2 = input.string("Right", title = "-", options = ["Right", "Center", "Left", "None"], group = GR_Adv_Settings, inline = "Dashboard" )
Stats_Loc_1 = input.string("Bottom", title = "Statistics Location: ", options = ["Bottom", "Middle", "Top", "None"], group = GR_Adv_Settings, inline = "Dashboard")
Stats_Loc_2 = input.string("Left", title = "-", options = ["Right", "Center", "Left", "None"], group = GR_Adv_Settings, inline = "Dashboard" )
var string Dashboard_Position = na
if Dashboard_Loc_1 == "Bottom" and Dashboard_Loc_2 == "Right"
Dashboard_Position := position.bottom_right
else if Dashboard_Loc_1 == "Middle" and Dashboard_Loc_2 == "Right"
Dashboard_Position := position.middle_right
else if Dashboard_Loc_1 == "Top" and Dashboard_Loc_2 == "Right"
Dashboard_Position := position.top_right
else if Dashboard_Loc_1 == "Bottom" and Dashboard_Loc_2 == "Center"
Dashboard_Position := position.bottom_center
else if Dashboard_Loc_1 == "Middle" and Dashboard_Loc_2 == "Center"
Dashboard_Position := position.middle_center
else if Dashboard_Loc_1 == "Top" and Dashboard_Loc_2 == "Center"
Dashboard_Position := position.top_center
else if Dashboard_Loc_1 == "Bottom" and Dashboard_Loc_2 == "Left"
Dashboard_Position := position.bottom_left
else if Dashboard_Loc_1 == "Middle" and Dashboard_Loc_2 == "Left"
Dashboard_Position := position.middle_left
else if Dashboard_Loc_1 == "Top" and Dashboard_Loc_2 == "Left"
Dashboard_Position := position.top_left
else if Dashboard_Loc_1 == "None" or Dashboard_Loc_2 == "None"
Dashboard_Position := position.top_left
var string Stats_Position = na
if Stats_Loc_1 == "Bottom" and Stats_Loc_2 == "Right"
Stats_Position := position.bottom_right
else if Stats_Loc_1 == "Middle" and Stats_Loc_2 == "Right"
Stats_Position := position.middle_right
else if Stats_Loc_1 == "Top" and Stats_Loc_2 == "Right"
Stats_Position := position.top_right
else if Stats_Loc_1 == "Bottom" and Stats_Loc_2 == "Center"
Stats_Position := position.bottom_center
else if Stats_Loc_1 == "Middle" and Stats_Loc_2 == "Center"
Stats_Position := position.middle_center
else if Stats_Loc_1 == "Top" and Stats_Loc_2 == "Center"
Stats_Position := position.top_center
else if Stats_Loc_1 == "Bottom" and Stats_Loc_2 == "Left"
Stats_Position := position.bottom_left
else if Stats_Loc_1 == "Middle" and Stats_Loc_2 == "Left"
Stats_Position := position.middle_left
else if Stats_Loc_1 == "Top" and Stats_Loc_2 == "Left"
Stats_Position := position.top_left
else if Stats_Loc_1 == "None" or Stats_Loc_2 == "None"
Stats_Position := position.top_left
// Variables
var bool InLong = false
var bool InShort = false
var bool InLong_Sig = false
var bool InShort_Sig = false
var bool InTrade = false
var float Entry_level = na
var float nLoss = na
var float nProfit_1 = na
var float short_stop_level = na
var float long_stop_level = na
var float long_profit_level_1 = na
var float long_profit_level_2 = na
var float long_profit_level_3 = na
var float short_profit_level_1 = na
var float short_profit_level_2 = na
var float short_profit_level_3 = na
var Bars_In_Trade = 0
var Long_Trades = 0
var Short_Trades = 0
var SL_Exit = 0
var TP_1 = 0
var TP_2 = 0
var TP_3 = 0
//Below is a modified version of the code written by LuxAlgo for https://www.tradingview.com/script/5MggSfGG-Volume-Profile-LUX/
var rowsBoxes = array.new_box()
if barstate.isfirst
for i = 0 to numRows - 1 by 1
array.push(rowsBoxes, box.new(na, na, na, na))
var pocLine = line.new(na, na, na, na, width=2)
line poc = na
box rowBox = na
levels = array.new_float(0)
sumVol = array.new_float(0)
if barstate.islast and Plot_Vol_Pro
for i = 0 to numRows by 1
array.push(levels, lowest + i / numRows * (highest - lowest))
for j = 0 to numRows - 1 by 1
sum = 0.
for k = 0 to lookbackLength - 1 by 1
sum := high[k] > array.get(levels, j) and low[k] < array.get(levels, j + 1) ? sum + volume[k] : sum
array.push(sumVol, sum)
for j = 0 to numRows - 1 by 1
mult = math.pow(array.get(sumVol, j) / array.max(sumVol),gradientMult)
rowBox := array.get(rowsBoxes, j)
volumeLevel = array.get(levels, j)
// // Check if we get new Pivot High Or Pivot Low
// float ph = ta.pivothigh(source == 'Close' ? close : high, prd_Div, prd_Div)
// float pl = ta.pivotlow(source == 'Close' ? close : low, prd_Div, prd_Div)
// // keep values and positions of Pivot Highs/Lows in the arrays
// var int maxarraysize = 20
// var ph_positions = array.new_int(maxarraysize, 0)
// var pl_positions = array.new_int(maxarraysize, 0)
// var ph_vals = array.new_float(maxarraysize, 0.)
// var pl_vals = array.new_float(maxarraysize, 0.)
// // add PHs to the array
// if ph
// array.unshift(ph_positions, bar_index)
// array.unshift(ph_vals, ph)
// if array.size(ph_positions) > maxarraysize
// array.pop(ph_positions)
// array.pop(ph_vals)
// // add PLs to the array
// if pl
// array.unshift(pl_positions, bar_index)
// array.unshift(pl_vals, pl)
// if array.size(pl_positions) > maxarraysize
// array.pop(pl_positions)
// array.pop(pl_vals)
// // functions to check Regular Divergences and Hidden Divergences
// // function to check positive regular or negative hidden divergence
// // cond == 1 => positive_regular, cond == 2=> negative_hidden
// positive_regular_positive_hidden_divergence(src, cond) =>
// divlen = 0
// prsc = source == 'Close' ? close : low
// // if indicators higher than last value and close price is higher than las close
// if dontconfirm or src > src[1] or close > close[1]
// startpoint = dontconfirm ? 0 : 1 // don't check last candle
// // we search last 15 PPs
// for x = 0 to maxpp - 1 by 1
// len = bar_index - array.get(pl_positions, x) + prd_Div
// // if we reach non valued array element or arrived 101. or previous bars then we don't search more
// if array.get(pl_positions, x) == 0 or len > maxbars
// break
// if len > 5 and (cond == 1 and src[startpoint] > src[len] and prsc[startpoint] < nz(array.get(pl_vals, x)) or cond == 2 and src[startpoint] < src[len] and prsc[startpoint] > nz(array.get(pl_vals, x)))
// slope1 = (src[startpoint] - src[len]) / (len - startpoint)
// virtual_line1 = src[startpoint] - slope1
// slope2 = (close[startpoint] - close[len]) / (len - startpoint)
// virtual_line2 = close[startpoint] - slope2
// arrived = true
// for y = 1 + startpoint to len - 1 by 1
// if src[y] < virtual_line1 or nz(close[y]) < virtual_line2
// arrived := false
// break
// virtual_line1 -= slope1
// virtual_line2 -= slope2
// virtual_line2
// if arrived
// divlen := len
// break
// divlen
// // function to check negative regular or positive hidden divergence
// // cond == 1 => negative_regular, cond == 2=> positive_hidden
// negative_regular_negative_hidden_divergence(src, cond) =>
// divlen = 0
// prsc = source == 'Close' ? close : high
// // if indicators higher than last value and close price is higher than las close
// if dontconfirm or src < src[1] or close < close[1]
// startpoint = dontconfirm ? 0 : 1 // don't check last candle
// // we search last 15 PPs
// for x = 0 to maxpp - 1 by 1
// len = bar_index - array.get(ph_positions, x) + prd_Div
// // if we reach non valued array element or arrived 101. or previous bars then we don't search more
// if array.get(ph_positions, x) == 0 or len > maxbars
// break
// if len > 5 and (cond == 1 and src[startpoint] < src[len] and prsc[startpoint] > nz(array.get(ph_vals, x)) or cond == 2 and src[startpoint] > src[len] and prsc[startpoint] < nz(array.get(ph_vals, x)))
// slope1 = (src[startpoint] - src[len]) / (len - startpoint)
// virtual_line1 = src[startpoint] - slope1
// slope2 = (close[startpoint] - nz(close[len])) / (len - startpoint)
// virtual_line2 = close[startpoint] - slope2
// arrived = true
// for y = 1 + startpoint to len - 1 by 1
// if src[y] > virtual_line1 or nz(close[y]) > virtual_line2
// arrived := false
// break
// virtual_line1 -= slope1
// virtual_line2 -= slope2
// virtual_line2
// if arrived
// divlen := len
// break
// divlen
// // calculate 4 types of divergence if enabled in the options and return divergences in an array
// calculate_divs(cond, indicator_1) =>
// divs = array.new_int(4, 0)
// array.set(divs, 0, cond and (searchdiv == 'Regular' or searchdiv == 'Regular/Hidden') ? positive_regular_positive_hidden_divergence(indicator_1, 1) : 0)
// array.set(divs, 1, cond and (searchdiv == 'Regular' or searchdiv == 'Regular/Hidden') ? negative_regular_negative_hidden_divergence(indicator_1, 1) : 0)
// array.set(divs, 2, cond and (searchdiv == 'Hidden' or searchdiv == 'Regular/Hidden') ? positive_regular_positive_hidden_divergence(indicator_1, 2) : 0)
// array.set(divs, 3, cond and (searchdiv == 'Hidden' or searchdiv == 'Regular/Hidden') ? negative_regular_negative_hidden_divergence(indicator_1, 2) : 0)
// divs
// // array to keep all divergences
// var all_divergences = array.new_int(44) // 11 indicators * 4 divergence = 44 elements
// // set related array elements
// array_set_divs(div_pointer, index) =>
// for x = 0 to 3 by 1
// array.set(all_divergences, index * 4 + x, array.get(div_pointer, x))
// // check minimum number of divergence, if less than showlimit then delete all divergence
// total_div = 0
// for x = 0 to array.size(all_divergences) - 1 by 1
// total_div += math.round(math.sign(array.get(all_divergences, x)))
// total_div
// if total_div < showlimit
// array.fill(all_divergences, 0)
// // keep line in an array
// var pos_div_lines = array.new_line(0)
// var neg_div_lines = array.new_line(0)
// var pos_div_labels = array.new_label(0)
// var neg_div_labels = array.new_label(0)
// // remove old lines and labels if showlast option is enabled
// delete_old_pos_div_lines() =>
// if array.size(pos_div_lines) > 0
// for j = 0 to array.size(pos_div_lines) - 1 by 1
// line.delete(array.get(pos_div_lines, j))
// array.clear(pos_div_lines)
// delete_old_neg_div_lines() =>
// if array.size(neg_div_lines) > 0
// for j = 0 to array.size(neg_div_lines) - 1 by 1
// line.delete(array.get(neg_div_lines, j))
// array.clear(neg_div_lines)
// delete_old_pos_div_labels() =>
// if array.size(pos_div_labels) > 0
// for j = 0 to array.size(pos_div_labels) - 1 by 1
// label.delete(array.get(pos_div_labels, j))
// array.clear(pos_div_labels)
// delete_old_neg_div_labels() =>
// if array.size(neg_div_labels) > 0
// for j = 0 to array.size(neg_div_labels) - 1 by 1
// label.delete(array.get(neg_div_labels, j))
// array.clear(neg_div_labels)
// // delete last creted lines and labels until we met new PH/PV
// delete_last_pos_div_lines_label(n) =>
// if n > 0 and array.size(pos_div_lines) >= n
// asz = array.size(pos_div_lines)
// for j = 1 to n by 1
// line.delete(array.get(pos_div_lines, asz - j))
// array.pop(pos_div_lines)
// if array.size(pos_div_labels) > 0
// label.delete(array.get(pos_div_labels, array.size(pos_div_labels) - 1))
// array.pop(pos_div_labels)
// delete_last_neg_div_lines_label(n) =>
// if n > 0 and array.size(neg_div_lines) >= n
// asz = array.size(neg_div_lines)
// for j = 1 to n by 1
// line.delete(array.get(neg_div_lines, asz - j))
// array.pop(neg_div_lines)
// if array.size(neg_div_labels) > 0
// label.delete(array.get(neg_div_labels, array.size(neg_div_labels) - 1))
// array.pop(neg_div_labels)
// Calculations
C_Len = 14 // ta.ema depth for bodyAvg
C_ShadowPercent = 5.0 // size of shadows
C_ShadowEqualsPercent = 100.0
C_DojiBodyPercent = 5.0
C_Factor = 2.0 // shows the number of times the shadow dominates the candlestick body
//Calculations
C_EngulfingBullishNumberOfCandles = 2
C_EngulfingBullish = C_WhiteBody and C_LongBody and C_BlackBody[1] and C_SmallBody[1] and close >= open[1] and open <= close[1] and ( close > open[1] or open < close[1] )
C_EngulfingBearishNumberOfCandles = 2
C_EngulfingBearish = C_BlackBody and C_LongBody and C_WhiteBody[1] and C_SmallBody[1] and close <= open[1] and open >= close[1] and ( close < open[1] or open > close[1] )
//Plot
plotshape(C_EngulfingBullish and Plot_Engulf ? close : na, title = "Bullish Engulf", style = shape.triangleup, location = location.belowbar, size = size.tiny, color = label_color_bullish)
plotshape(C_EngulfingBearish and Plot_Engulf ? close : na, title = "Bearish Engulf", style = shape.triangledown, location = location.abovebar, size = size.tiny, color = label_color_bearish)
//Long and Short Orders (Confirmation Conditions)
Ind_5_L = true
Ind_5_S = true
//==============================================================================
// // get/keep Pivot levels
// var pivotvals = array.new_float(0)
// var pivotlocs = array.new_float(0)
// if ph_S_R or pl_S_R
// array.unshift(pivotvals, ph_S_R ? ph_S_R : pl_S_R)
// array.unshift(pivotlocs, bar_index)
// for x = array.size(pivotvals) - 1 to 0 by 1
// if bar_index - array.get(pivotlocs, x) > loopback // remove old pivot points
// array.pop(pivotvals)
// array.pop(pivotlocs)
// continue
// break
// //find/create SR channel of a pivot point
// get_sr_vals(ind) =>
// float lo = array.get(pivotvals, ind)
// float hi = lo
// int numpp = 0
// for y = 0 to array.size(pivotvals) - 1 by 1
// float cpp = array.get(pivotvals, y)
// float wdth = cpp <= hi ? hi - cpp : cpp - lo
// if wdth <= cwidth // fits the max channel width?
// if cpp <= hi
// lo := math.min(lo, cpp)
// lo
// else
// hi := math.max(hi, cpp)
// hi
// numpp += 20 // each pivot point added as 20
// numpp
// [hi, lo, numpp]
// // keep old SR channels and calculate/sort new channels if we met new pivot point
// var suportresistance = array.new_float(20, 0) // min/max levels
// changeit(x, y) =>
// tmp = array.get(suportresistance, y * 2)
// array.set(suportresistance, y * 2, array.get(suportresistance, x * 2))
// array.set(suportresistance, x * 2, tmp)
// tmp := array.get(suportresistance, y * 2 + 1)
// array.set(suportresistance, y * 2 + 1, array.get(suportresistance, x * 2 + 1))
// array.set(suportresistance, x * 2 + 1, tmp)
// if ph_S_R or pl_S_R
// supres = array.new_float(0) // number of pivot, strength, min/max levels
// stren = array.new_float(10, 0)
// // get levels and strengs
// for x = 0 to array.size(pivotvals) - 1 by 1
// [hi, lo, strength] = get_sr_vals(x)
// array.push(supres, strength)
// array.push(supres, hi)
// array.push(supres, lo)
// // add each HL to strengh
// for x = 0 to array.size(pivotvals) - 1 by 1
// h = array.get(supres, x * 3 + 1)
// l = array.get(supres, x * 3 + 2)
// s = 0
// for y = 0 to loopback by 1
// if high[y] <= h and high[y] >= l or low[y] <= h and low[y] >= l
// s += 1
// s
// array.set(supres, x * 3, array.get(supres, x * 3) + s)
// //reset SR levels
// array.fill(suportresistance, 0)
// // get strongest SRs
// src = 0
// for x = 0 to array.size(pivotvals) - 1 by 1
// stv = -1. // value
// stl = -1 // location
// for y = 0 to array.size(pivotvals) - 1 by 1
// if array.get(supres, y * 3) > stv and array.get(supres, y * 3) >= minstrength * 20
// stv := array.get(supres, y * 3)
// stl := y
// stl
// if stl >= 0
// //get sr level
// hh = array.get(supres, stl * 3 + 1)
// ll = array.get(supres, stl * 3 + 2)
// array.set(suportresistance, src * 2, hh)
// array.set(suportresistance, src * 2 + 1, ll)
// array.set(stren, src, array.get(supres, stl * 3))
// // make included pivot points' strength zero
// for y = 0 to array.size(pivotvals) - 1 by 1
// if array.get(supres, y * 3 + 1) <= hh and array.get(supres, y * 3 + 1) >= ll or array.get(supres, y * 3 + 2) <= hh and array.get(supres, y * 3 + 2) >= ll
// array.set(supres, y * 3, -1)
// src += 1
// if src >= 10
// break
// for x = 0 to 8 by 1
// for y = x + 1 to 9 by 1
// if array.get(stren, y) > array.get(stren, x)
// tmp = array.get(stren, y)
// array.set(stren, y, array.get(stren, x))
// changeit(x, y)
// get_level(ind) =>
// float ret = na
// if ind < array.size(suportresistance)
// if array.get(suportresistance, ind) != 0
// ret := array.get(suportresistance, ind)
// ret
// ret
// get_color(ind) =>
// color ret = na
// if ind < array.size(suportresistance)
// if array.get(suportresistance, ind) != 0
// ret := array.get(suportresistance, ind) > close and array.get(suportresistance, ind + 1) > close ? res_col : array.get(suportresistance, ind) < close and array.get(suportresistance, ind + 1) < close ? sup_col : inch_col
// ret
// ret
// var srchannels = array.new_box(10)
// for x = 0 to math.min(9, maxnumsr) by 1
// box.delete(array.get(srchannels, x))
// srcol = get_color(x * 2)
// if not na(srcol) and plot_SR
// array.set(srchannels, x, box.new(left=bar_index, top=get_level(x * 2), right=bar_index + 1, bottom=get_level(x * 2 + 1), border_color=srcol, border_width=1, extend=extend.both, bgcolor=srcol))
// // check if it's not in a channel
// not_in_a_channel = true
// for x = 0 to math.min(9, maxnumsr) by 1
// if close <= array.get(suportresistance, x * 2) and close >= array.get(suportresistance, x * 2 + 1)
// not_in_a_channel := false
// not_in_a_channel
// // if price is not in a channel then check broken ones
// if not_in_a_channel
// for x = 0 to math.min(9, maxnumsr) by 1
// if close[1] <= array.get(suportresistance, x * 2) and close > array.get(suportresistance, x * 2)
// resistancebroken := true
// resistancebroken
// if close[1] >= array.get(suportresistance, x * 2 + 1) and close < array.get(suportresistance, x * 2 + 1)
// supportbroken := true
// supportbroken
MOM_Signal_Long = scolor == color.gray and scolor[1] != color.gray and val > 0
MOM_Signal_Short = scolor == color.gray and scolor[1] != color.gray and val < 0
Target_Exit = input.string("Percent (%)", title = "Exit Target Method ", options = ["Percent (%)", "ATR", "Chandelier", "Off"], group = gr_Exit, tooltip = "Percent (%): Targets based on Percent of closing price at trade open\nATR: Target based on value of Average True Range (more suitable for variable Timeframes)\nOff: Disables Take Profit/Stop Loss Settings.")
TP_Level_1 = input.float(defval = 0.5, title = "TP Level 1/2/3", step = 0.1, group = gr_Exit, inline = "TP", tooltip = "Percent Target or Multiple of ATR\nEX: 3 = 3% or 3x ATR depending on Target Method Configuration") * 0.01
TP_Level_2 = input.float(defval = 1, title = "/", step = 0.1, group = gr_Exit, inline = "TP") * 0.01
TP_Level_3 = input.float(defval = 1.5, title = "/", step = 0.1, group = gr_Exit, inline = "TP") * 0.01
// TP_Level_4 = input.float(defval = 4, title = "TP Level 4/5/6 (%)", step = 0.1, group = gr_Exit, inline = "TP2") * 0.01
// TP_Level_5 = input.float(defval = 5, title = "/", step = 0.1, group = gr_Exit, inline = "TP2") * 0.01
// TP_Level_6 = input.float(defval = 6, title = "/", step = 0.1, group = gr_Exit, inline = "TP2") * 0.01
SL_Level_1 = input.float(defval = 1.5, title = "Stop Loss", step = 0.1, group = gr_Exit) * 0.01
ATR_Exit = ta.atr(21)
// var Entry_level = float(0.0)
// //Calculate stop loss and take profit distance (in price)
// var float nLoss = 0.0
// var float nProfit_1 = 0.0
// var float nProfit_2 = 0.0
// var float nProfit_3 = 0.0
// // var float nProfit_4 = 0.0
// // var float nProfit_5 = 0.0
// // var float nProfit_6 = 0.0
// //Find long take profit and stop loss levels
// var long_stop_level = float(0.0) //set float
// var long_profit_level_1 = float(0.0)
// var long_profit_level_2 = float(0.0)
// var long_profit_level_3 = float(0.0)
// // var long_profit_level_4 = float(0.0)
// // var long_profit_level_5 = float(0.0)
// // var long_profit_level_6 = float(0.0)
// //Find short take profit and stop loss levels
// var short_stop_level = float(0.0) //set float
// var short_profit_level_1 = float(0.0)
// var short_profit_level_2 = float(0.0)
// var short_profit_level_3 = float(0.0)
// // var short_profit_level_4 = float(0.0)
// // var short_profit_level_5 = float(0.0)
// // var short_profit_level_6 = float(0.0)
//==============================================================================
//=============== Strategies =========================
//==============================================================================
gr_Trade_MGT = "💻Trade Managmeent💻"
//Strategy_Select = input.string("None", title = "Strategy Selector", options = ["None", "Moving Average Cross", "RE Beta", "MS Beta", "SRT Beta" ], group = gr_Trade_MGT, tooltip = "-None: No Strategies will display on the chart \n-Moving Average Cross: Trade will occur when the two Moving Averages Cross in the direction of the Faster Moving average.\n-RSI/Engulfing: Trade will occur when RSI is inline with Trend and an Engulfing Candle occurs.\n-Momentum Squeeze: Trade will occur when Momentum shifts from Low to High in the direction of the trend.\n-SSL/RSI/TDFI: Trade will occur when the SSL/RSI/TDFI Indicators are all in confluence.")
//Plot_Targets = input.bool(true, title = "Plot Trade Targets (TP/SL Lines)", group = gr_Trade_MGT)
// Strategy_1_long = InTrade == false and dateRange() and Ind_1_L and LongSignals //and Ind_2_L and Ind_3_L and Ind_4_L and Ind_5_L and Ind_6_L
// Strategy_1_short = InTrade == false and dateRange() and Ind_1_S and ShortSignals //and Ind_2_S and Ind_3_S and Ind_4_S and Ind_5_S and Ind_6_S
Strategy_2_long = InTrade == false and MA_1 > MA_2 and rsi_Ind > 50 and C_EngulfingBullish and LongSignals //and Ind_2_L and Ind_3_L and Ind_4_L and Ind_5_L and Ind_6_L
Strategy_2_short = InTrade == false and MA_1 < MA_2 and rsi_Ind < 50 and C_EngulfingBearish and ShortSignals //and Ind_2_S and Ind_3_S and Ind_4_S and Ind_5_S and Ind_6_S
Strategy_2_long_Sig = MA_1 > MA_2 and rsi_Ind > 50 and C_EngulfingBullish //and Ind_2_L and Ind_3_L and Ind_4_L and Ind_5_L and Ind_6_L
Strategy_2_short_Sig = MA_1 < MA_2 and rsi_Ind < 50 and C_EngulfingBearish //and Ind_2_S and Ind_3_S and Ind_4_S and Ind_5_S and Ind_6_S
Strategy_3_long = InTrade == false and MA_1 > MA_2 and LongSignals and MOM_Signal_Long and LongSignals //and Ind_2_L and Ind_3_L and Ind_4_L and Ind_5_L and Ind_6_L
Strategy_3_short = InTrade == false and MA_1 < MA_2 and ShortSignals and MOM_Signal_Short and ShortSignals //and Ind_2_S and Ind_3_S and Ind_4_S and Ind_5_S and Ind_6_S
Strategy_3_long_Sig = MA_1 > MA_2 and LongSignals and MOM_Signal_Long
Strategy_3_short_Sig = MA_1 < MA_2 and ShortSignals and MOM_Signal_Short
Strategy_4_long = InTrade == false and sslDown < sslUp and tdf > triggerUp and ta.crossover(rsi_Ind, 65) and LongSignals //and Ind_2_L and Ind_3_L and Ind_4_L and Ind_5_L and Ind_6_L
Strategy_4_short = InTrade == false and sslDown > sslUp and tdf < triggerDown and ta.crossunder(rsi_Ind, 35) and ShortSignals //and Ind_2_S and Ind_3_S and Ind_4_S and Ind_5_S and Ind_6_S
Strategy_4_long_Sig = sslDown < sslUp and tdf > triggerUp and ta.crossover(rsi_Ind, 65)
Strategy_4_short_Sig = sslDown > sslUp and tdf < triggerDown and ta.crossunder(rsi_Ind, 35)
Strategy_5_long = InTrade == false and ta.crossover(kama,vidya) and LongSignals //and Ind_2_L and Ind_3_L and Ind_4_L and Ind_5_L and Ind_6_L
Strategy_5_short = InTrade == false and ta.crossunder(kama,vidya) and ShortSignals //and Ind_2_S and Ind_3_S and Ind_4_S and Ind_5_S and Ind_6_S
var TP_Levels = array.new_float(3,na)
var SL_Levels = array.new_float(1,na)
var Entry_Levels = array.new_float(1,na)
var Array_Lines = array.new_line(4,na)
var Array_Lables = array.new_label(4,na)
var Array_Lines_Old = array.new_line(10,na)
var Array_Labels_Old = array.new_label(1,na)
var float Entry_ATR = na
if InTrade
Bars_In_Trade += 1
else if entry_long or entry_short
Bars_In_Trade := 0
if entry_long
if TM_Long
Long_Signal_Strength += 1
if ADX_Long
Long_Signal_Strength += 1
if ACC_Long
Long_Signal_Strength += 1
if MFI_Long
Long_Signal_Strength += 1
if MOML_Long
Long_Signal_Strength += 1
if entry_short
if TM_Short
Short_Signal_Strength += 1
if ADX_Short
Short_Signal_Strength += 1
if ACC_Short
Short_Signal_Strength += 1
if MFI_Short
Short_Signal_Strength += 1
if MOML_Short
Short_Signal_Strength += 1
//Plot Buy/Sell Signals on chart
Exit_Long = InLong and (ta.crossunder(low, long_stop_level)) //or Ind_1_L_Exit or Ind_2_S)
Exit_Short = InShort and (ta.crossover(high, short_stop_level)) //or Ind_1_S_Exit or Ind_2_L)
TP_1_Long = InLong and ta.crossover(high, long_profit_level_1)
TP_2_Long = InLong and ta.crossover(high, long_profit_level_2)
TP_3_Long = InLong and ta.crossover(high, long_profit_level_3)
// TP_4_Long = InLong and ta.crossover(high, long_profit_level_4)
// TP_5_Long = InLong and ta.crossover(high, long_profit_level_5)
// TP_6_Long = InLong and ta.crossover(high, long_profit_level_6)
var int TP_Long_Condition = 0
var int TP_Short_Condition = 0
TP_1_Short = InShort and ta.crossunder(low, short_profit_level_1)
TP_2_Short = InShort and ta.crossunder(low, short_profit_level_2)
TP_3_Short = InShort and ta.crossunder(low, short_profit_level_3)
// TP_4_Short = InShort and ta.crossunder(low, short_profit_level_4)
// TP_5_Short = InShort and ta.crossunder(low, short_profit_level_5)
// TP_6_Short = InShort and ta.crossunder(low, short_profit_level_6)
if TP_1_Long and TP_Long_Condition == 0 and not entry_long
if Target_Exit != "Off"
array.push(Array_Labels_Old, label.new(bar_index, high, text = "TP 1", color = #00def6, style = label.style_label_down))
TP_Long_Condition := 1
TP_1 += 1
alert("Long TP 1", alert.freq_once_per_bar)
if (TP_2_Long and TP_Long_Condition == 1)
if Target_Exit != "Off"
lb = array.pop(Array_Labels_Old)
label.delete(lb)
array.push(Array_Labels_Old, label.new(bar_index, high, text = "TP 2", color = #00def6, style = label.style_label_down))
TP_Long_Condition := 2
TP_2 += 1
alert("Long TP 2", alert.freq_once_per_bar)
if (TP_3_Long and TP_Long_Condition == 2)
if Target_Exit != "Off"
lb = array.pop(Array_Labels_Old)
label.delete(lb)
array.push(Array_Labels_Old, label.new(bar_index, high, text = "TP 3", color = #00def6, style = label.style_label_down))
code
for [index, value] in TP_Levels
array.push(Array_Lines_Old, line.new(bar_index[Bars_In_Trade], value, bar_index, value, color = #00def6, width = 1, style = line.style_dotted))
for [index, value] in SL_Levels
array.push(Array_Lines_Old, line.new(bar_index[Bars_In_Trade], value, bar_index, value, color = #ff0015, width = 1, style = line.style_dotted))
for [index, value] in Entry_Levels
array.push(Array_Lines_Old, line.new(bar_index[Bars_In_Trade], value, bar_index, value, color = #ffffff, width = 1, style = line.style_dotted))
TP_Long_Condition := 3
TP_3 += 1
alert("Long TP 3", alert.freq_once_per_bar)
InLong := false
InTrade := false
Entry_level := na
nLoss := na
nProfit_1 := na
long_stop_level := na
long_profit_level_1 := na
long_profit_level_2 := na
long_profit_level_3 := na
TP_Long_Condition := 0
Entry_ATR := na
if (TP_1_Short and TP_Short_Condition == 0)
// if entry_short and InTrade == true
// runtime.error("Target Levels Too Small")
if Target_Exit != "Off"
array.push(Array_Labels_Old, label.new(bar_index, low, text = "TP 1", color = #00def6, style = label.style_label_up))
TP_Short_Condition := 1
TP_1 += 1
alert("Short TP 1", alert.freq_once_per_bar)
if (TP_2_Short and TP_Short_Condition == 1)
if Target_Exit != "Off"
lb = array.pop(Array_Labels_Old)
label.delete(lb)
array.push(Array_Labels_Old, label.new(bar_index, low, text = "TP 2", color = #00def6, style = label.style_label_up))
TP_Short_Condition := 2
TP_2 += 1
alert("Short TP 2", alert.freq_once_per_bar)
if (TP_3_Short and TP_Short_Condition == 2)
if Target_Exit != "Off"
lb = array.pop(Array_Labels_Old)
label.delete(lb)
array.push(Array_Labels_Old, label.new(bar_index, low, text = "TP 3", color = #00def6, style = label.style_label_up))
code
for [index, value] in TP_Levels
array.push(Array_Lines_Old, line.new(bar_index[Bars_In_Trade], value, bar_index, value, color = #00def6, width = 1, style = line.style_dotted))
for [index, value] in SL_Levels
array.push(Array_Lines_Old, line.new(bar_index[Bars_In_Trade], value, bar_index, value, color = #ff0015, width = 1, style = line.style_dotted))
for [index, value] in Entry_Levels
array.push(Array_Lines_Old, line.new(bar_index[Bars_In_Trade], value, bar_index, value, color = #ffffff, width = 1, style = line.style_dotted))
TP_Short_Condition := 3
TP_3 += 1
alert("Short TP 3", alert.freq_once_per_bar)
InShort := false
InTrade := false
Entry_level := na
nLoss := na
nProfit_1 := na
short_stop_level := na
short_profit_level_1 := na
short_profit_level_2 := na
short_profit_level_3 := na
TP_Short_Condition := 0
Entry_ATR := na
if InTrade == true and (Exit_Long)
if Target_Exit != "Off"
if TP_Long_Condition == 0
array.push(Array_Labels_Old, label.new(bar_index, low, text = "SL", color = #ff0015, style = label.style_label_up))
code
for [index, value] in TP_Levels
array.push(Array_Lines_Old, line.new(bar_index[Bars_In_Trade], value, bar_index, value, color = #00def6, width = 1, style = line.style_dotted))
for [index, value] in SL_Levels
array.push(Array_Lines_Old, line.new(bar_index[Bars_In_Trade], value, bar_index, value, color = #ff0015 , width = 1, style = line.style_dotted))
for [index, value] in Entry_Levels
array.push(Array_Lines_Old, line.new(bar_index[Bars_In_Trade], value, bar_index, value, color = #ffffff, width = 1, style = line.style_dotted))
InLong := false
InTrade := false
Entry_level := na
nLoss := na
nProfit_1 := na
long_profit_level_1 := na
long_profit_level_2 := na
long_stop_level := na
TP_Long_Condition := 0
Entry_ATR := na
SL_Exit += 1
else if InTrade == true and (Exit_Short)
if Target_Exit != "Off"
if TP_Short_Condition == 0
array.push(Array_Labels_Old, label.new(bar_index, high, text = "SL", color = #ff0015, style = label.style_label_down))
code
for [index, value] in TP_Levels
array.push(Array_Lines_Old, line.new(bar_index[Bars_In_Trade], value, bar_index, value, color = #00def6, width = 1, style = line.style_dotted))
for [index, value] in SL_Levels
array.push(Array_Lines_Old, line.new(bar_index[Bars_In_Trade], value, bar_index, value, color = #ff0015, width = 1, style = line.style_dotted))
for [index, value] in Entry_Levels
array.push(Array_Lines_Old, line.new(bar_index[Bars_In_Trade], value, bar_index, value, color = #ffffff, width = 1, style = line.style_dotted))
InShort := false
InTrade := false
Entry_level := na
nLoss := na
nProfit_1 := na
short_profit_level_1 := na
short_profit_level_2 := na
short_stop_level := na
TP_Short_Condition := 0
Entry_ATR := na
SL_Exit += 1
// if not Plot_Targets
// array.clear(Array_Lines_Old)
// array.clear(Array_Labels_Old)
// array.clear(Array_Lines)
// array.clear(Array_Lables)
//=============================================================================
// BAR COLOR
//=============================================================================
Green = close > open
Candle_Colors = Select_Color_Pallet == "None" ? na :
InLong_Sig and Target_Exit == "Off" and Trade_Bar_Color ? color_2 : InShort_Sig and Target_Exit == "Off" and Trade_Bar_Color ? color_4 :
Trade_Bar_Color and InLong ? color_2 :
Trade_Bar_Color and InShort ? color_4 :
(not InLong and not InShort) or not Trade_Bar_Color ? Green ? color_1 :
color_3 : na
// Entries
Current_Strategy = Strategy_Select
Current_Signal = if Target_Exit == "Off"
InLong_Sig ? "In Long Trade" : InShort_Sig ? "In Short Trade" : "Not In Trade"
else
InTrade and InLong ? "In Long Trade" : InTrade and InShort ? "In Short Trade" : "Not In Trade"
Signal_Color = Current_Signal == "In Long Trade" ? color.white : Current_Signal == "In Short Trade" ? color.aqua : color.gray
//alertcondition(entry_long, "Long Entry", message = "{{ticker}} Long\nLeverage: Cross 1x\nEntry:" )
//alertcondition(entry_short, "Short Entry", message = "Test")
alertcondition(Exit_Long, "Long Exit", "Long Exit Alert")
alertcondition(Exit_Short, "Short Exit", "Short Exit Alert")
// alertcondition(TP_1_Short and TP_Short_Condition == 0, "TP1 Short", " Short Take Profit 1")
// alertcondition(TP_2_Short and TP_Short_Condition == 1, "TP2 Short", " Short Take Profit 2")
// alertcondition(TP_3_Short and TP_Short_Condition == 2, "TP3 Short", " Short Take Profit 3")
// alertcondition(TP_4_Short and TP_Short_Condition == 3, "TP4 Short", " Short Take Profit 4")
// alertcondition(TP_5_Short and TP_Short_Condition == 4, "TP5 Short", " Short Take Profit 5")
// alertcondition(TP_6_Short and TP_Short_Condition == 5, "TP6 Short", " Short Take Profit 6")
// alertcondition(TP_1_Long and TP_Long_Condition == 0, "TP1 Long", " Long Take Profit 1")
// alertcondition(TP_2_Long and TP_Long_Condition == 1, "TP2 Long", " Long Take Profit 2")
// alertcondition(TP_3_Long and TP_Long_Condition == 2, "TP3 Long", " Long Take Profit 3")
// alertcondition(TP_4_Long and TP_Long_Condition == 3, "TP4 Long", " Long Take Profit 4")
// alertcondition(TP_5_Long and TP_Long_Condition == 4, "TP5 Long", " Long Take Profit 5")
// alertcondition(TP_6_Long and TP_Long_Condition == 5, "TP6 Long", " Long Take Profit 6")
All_Long_TP_Cond = (TP_1_Long and TP_Long_Condition == 0) or (TP_2_Long and TP_Long_Condition == 1) or (TP_3_Long and TP_Long_Condition == 2) // or (TP_4_Long and TP_Long_Condition == 3) or (TP_5_Long and TP_Long_Condition == 4) or (TP_6_Long and TP_Long_Condition == 5)
All_Short_TP_Cond = (TP_1_Short and TP_Short_Condition == 0) or (TP_2_Short and TP_Short_Condition == 1) or (TP_3_Short and TP_Short_Condition == 2) // or (TP_4_Short and TP_Short_Condition == 3) or (TP_5_Short and TP_Short_Condition == 4) or (TP_6_Short and TP_Short_Condition == 5)
// Global alert condition encompassing all
All_Alerts_Cond = Exit_Long or Exit_Short or All_Long_TP_Cond or All_Short_TP_Cond
// Create a single alert that triggers on any of the above conditions
alertcondition(All_Alerts_Cond, "All Alerts", "Global Alert Triggered")
帮我看看 分析下
Certainly! Let's break down and analyze your Pine Script for the "New Testing CRYPTO SLAYA" indicator. This script is quite comprehensive, incorporating multiple indicators and strategies to assist in crypto trading. Here's a detailed analysis of its components, functionalities, potential issues, and suggestions for improvement.
1. Overview
The script is designed to provide trade signals based on various technical indicators and strategies. It includes features such as moving averages, volume profiles, RSI, candlestick patterns, momentum squeezes, volatility measurements, SSL channels, Trend Direction Force Index (TDFI), and more. Additionally, it offers customizable color themes and a dashboard for trade statistics.
2. Structure and Components
a. Inputs and Settings
Basic Settings:
Strategy Selector: Allows users to choose between different strategies: None, Confirmation, RE Beta, MS Beta, and SRT Beta.
Sensitivity & Rigor: Integer inputs to adjust the responsiveness and strictness of the strategies.
Color Theme: Users can select from predefined color palettes or opt for no color theme.
Trade Bar Coloring: Option to color candles based on trade signals.
Features:
Options to plot various indicators like Moving Averages, Reversal Bands, Volume Profile (Vray), Engulfing Signals, Lune Confirmation, and Reversal Signals.
Advanced Settings:
Dashboard & Statistics Location: Users can position the dashboard and statistics table anywhere on the chart.
b. Color Themes
Multiple color palettes are defined using arrays, allowing for consistent and customizable chart aesthetics. Users can switch between themes like Bright, Default, Lune, Ice, or opt for no theme (NA_Palett).
c. Indicators
The script integrates several indicators, each with its own settings and plotting options:
Moving Averages (MA):
Users can select from various MA types (e.g., Simple, Exponential, Hull).
Two MAs (MA_1 and MA_2) are calculated based on user inputs and plotted if enabled.
Volume Profile (Vray):
Displays volume distribution across price levels.
Plots the Point of Control (PoC) as a dashed line.
Highly customizable based on chart timeframe.
RSI:
Standard RSI calculation with options for plotting are present but currently commented out.
Engulfing Patterns:
Detects bullish and bearish engulfing candlestick patterns.
Plots triangles on the chart to indicate these patterns.
Momentum Squeeze:
Uses Bollinger Bands and Keltner Channels to identify squeeze conditions.
Calculates momentum and changes colors based on momentum shifts.
Market Volatility:
Computes ATR-based volatility and classifies it as "High" or "Low".
SSL Channels:
Simple SSL channel calculation based on moving averages.
Plots SSL up and down channels if enabled.
Trend Direction Force Index (TDFI):
An advanced trend indicator that smoothes trend direction using EMA and other methodologies.
Reversal Zones:
Uses Bollinger Bands to identify potential reversal zones.
Plots inner, middle, and outer bands along with breakout signals.
Trend Confidence:
Incorporates multiple indicators like CCI, ADX, Accumulation/Distribution, MFI, and Momentum Linear Regression to assess trend strength and confidence.
d. Strategies and Trade Management
The script supports multiple trading strategies selected via the Strategy Selector:
RE Beta:
Combines Moving Average crossover, RSI above 50, and Bullish Engulfing patterns for long signals.
Opposite conditions for short signals.
MS Beta:
Utilizes Moving Average crossover and Momentum Squeeze signals.
SRT Beta:
Integrates SSL Channels, TDFI, and RSI crossing specific thresholds.
Confirmation:
Based on KAMA and Vidya crossover signals.
Trade Management:
Entry Conditions: Based on the selected strategy and additional filters like trend confidence indicators.
Exit Conditions: Managed via Take Profit (TP) levels and Stop Loss (SL) levels, configurable using Percent, ATR, or Chandelier methods.
Trade Statistics: Displays total trades, long and short trades, loss percentage, TP achievements, and profitability on a dashboard and statistics table.
Alerts: Configured to notify when trades are entered or exited, including TP and SL triggers.
3. Detailed Analysis
a. Functionality and Logic
Trade Signals:
The script effectively combines multiple indicators to generate trade signals, enhancing the robustness of entries.
Different strategies allow for flexibility based on user preference and market conditions.
Color Themes:
The use of arrays for color palettes is efficient, allowing easy switching between themes.
However, the NA_Palett seems to duplicate the Default_Pallet. If "None" implies no coloring, consider simplifying this.
Indicators:
Moving Averages: Comprehensive selection, but ensure that the computations (especially for higher-order EMAs like Quadruple Exponential) do not introduce lag or unnecessary complexity.
Volume Profile: Resource-intensive due to nested loops and box management. Optimize by limiting the number of rows or simplifying the volume calculations.
RSI and Other Indicators: Some plotting is commented out, which might be intentional for customization but could be streamlined.
Engulfing Patterns: Well-implemented with clear plotting for bullish and bearish signals.
Momentum Squeeze and Other Advanced Indicators: Adds depth but increases script complexity. Ensure each component contributes meaningfully to trade signals.
Trade Management:
The script manages TP and SL levels dynamically based on entry conditions.
Uses arrays to track multiple levels and ensures old lines/labels are cleaned to prevent clutter.
Dashboard and statistics provide valuable insights but consider the table's performance impact, especially with high max_labels_count and max_lines_count.
b. Code Efficiency and Readability
Complexity:
The script is extensive, making it harder to maintain or debug. Consider modularizing sections using functions where possible.
Multiple commented-out sections (e.g., Indicator 3 - Divergence, Indicator 6 - Support/Resistance) increase clutter. Remove or clean up unused code to enhance readability.
Performance:
Heavy use of arrays, especially for drawing objects like boxes and lines, can slow down performance. Optimize by reducing the number of objects or limiting their lifespan.
Conditional plotting and frequent label creation might lead to performance issues on longer timeframes or lower-performance devices.
Variables Management:
There are multiple instances of variable declarations (e.g., var float Entry_level = na and later re-declarations). Ensure variables are declared only once to prevent unexpected behavior.
Error Handling:
The script lacks explicit error handling for edge cases, such as division by zero or unexpected array sizes. Incorporate safeguards to handle such scenarios gracefully.
c. Potential Issues
Repainting Indicators:
Some indicators use barstate.isrealtime which might introduce repainting issues. Ensure that signals are reliable and do not change retrospectively.
Array Management:
Improper handling of arrays, especially when popping elements, might lead to mismatched TP/SL levels or trade states.
Ensure that arrays are consistently maintained and synchronized with trade states.
Trade State Flags:
Flags like InLong, InShort, and InTrade are managed manually. Potential race conditions or missed updates could lead to incorrect trade signals.
Consider using Pine's built-in strategy functions for more reliable trade state management.
Alert Conditions:
The script sets multiple alert conditions, but some are commented out. Verify that only necessary alerts are active to prevent alert flooding.
The final All_Alerts_Cond combines multiple conditions. Ensure that this does not miss critical alerts or trigger unnecessary ones.
Dashboard Positioning:
The logic for dashboard positioning defaults to position.top_left if "None" is selected in either row or column. This might lead to unintended placements.
Clarify the behavior when "None" is selected and possibly allow independent positioning for horizontal and vertical placements.
d. Suggestions for Improvement
Modularization:
Break down the script into smaller functions or sections. For example, separate indicator calculations from trade logic and plotting.
This enhances readability and maintainability.
Optimize Plotting:
Limit the number of drawn objects like boxes and lines by capping their lifespan or simplifying their representations.
Use built-in Pine functions wherever possible to reduce computational overhead.
Remove Unused Code:
Clean up commented-out sections unless they're placeholders for future development. This declutters the script and makes active code more prominent.
Enhance Trade State Management:
Consider leveraging Pine's strategy capabilities (if appropriate) for managing trades more reliably.
Ensure that trade flags (InLong, InShort, InTrade) are consistently updated to reflect the actual trade state.
Prevent Repainting:
Ensure that all indicators used for generating trade signals do not repaint. This ensures that backtesting and live trading signals remain accurate.
Improve Alert Management:
Simplify alert conditions by combining related alerts or using more descriptive messages.
Ensure that alerts are essential and do not overwhelm the user with excessive notifications.
Dashboard Enhancements:
Make the dashboard dynamic, updating in real-time without requiring barstate.islast.
Allow users to customize which statistics are displayed for greater flexibility.
Code Documentation:
Add comments and documentation throughout the script to explain complex logic and purpose of variables.
This aids future modifications and helps others understand the script's functionality.
Error Handling and Safeguards:
Incorporate checks to prevent division by zero or accessing array indices out of bounds.
Use Pine's nz() function more strategically to handle na values.
User Inputs Validation:
4. Conclusion
Your Pine Script for the "New Testing CRYPTO SLAYA" indicator is feature-rich and integrates a variety of technical indicators and strategies to assist in making informed trading decisions. While it encompasses comprehensive functionalities, attention to code optimization, readability, and efficient resource management will enhance its performance and reliability. Implementing the suggested improvements can lead to a more robust and user-friendly indicator, better suited for both backtesting and live trading scenarios.
If you have any specific questions or need further assistance with particular sections of the script, feel free to ask!