How to move calculations so only the calcs within a set amount of bars are used

49 views Asked by At

I have two scripts I'm trying to implement this on. I'll use the simple one for the example here. In this example I'm trying to count the number of red candles and the number of green candles within a certain range of bars.

In this code the user can select a begin time and end time to count the candles within that time period (see table at bottom of chart for the counts). If the user selects the 'Update End Time with candle progress' the beginning time can be moved - but, the end time progresses with the current time.

What I can't figure out is the last option - to have the beginning time trail behind the current time by a set number of bars. I'm relatively certain my issue is on the code related to line 33 - how I'm calculating the "trail_time"

I attempted to use timediff = (time - time[i_candle_trl_num]) / 1000 as a means of determining the amount of time in the past to utilize. I used time[5] (as an example) and several other variations. When I deselect "Update Beggining Time withh candle progress" all works as intended. When I select "Update Begginning Time with candle progress." it appears that all the candles on the chart are being counted regardless of any code I've attempted to use.

// Original Script by © Steversteves. Thanks for the idea! I made some cosmetic and usability changes.
//@version=5
indicator("S - Candle Counter", overlay=true, max_bars_back = 500)

// Start-time and End Time
i_start_time = input.time(timestamp("29 Aug 2023 13:00 +000"), title = "Start time", confirm = true)
i_end_time = input.time(timestamp("29 Aug 2023 13:00 +000"), title = "End time", confirm = true)

i_update_endtime = input.bool(true, 'Update End Time with candle progress.')
i_update_begtime = input.bool(true, 'Update Beginning Time with candle progress. Requires Update End time to work.')
i_candle_trl_num = input.int(5, 'Number of Candles to Trail', tooltip = 'Requires both "Update End and Update Beg Time to work. Suggest increments of 5.')

i_background_col = input.color(color.rgb(102, 35, 114, 73), title = 'Background Color') // area of bars being counted

i_alert_interval = input.int(defval = 5, title = "Audible alert every:", options = [5, 10, 20], group = '═════════════ Count Alert ═══════════', tooltip = 'For use with Candle Progression (Above Checkbox)')

tab_grp = '═════════════ Table ═══════════' 
i_tab_pos = input.string(defval = "Bottom Left", title = "Table Position", options = ["Top Right", "Top Center", "Top Left", "Middle Right", "Middle Center", "Middle Left", "Bottom Right", "Bottom Center", "Bottom Left"], group = tab_grp, inline = 'frame')
i_tab_back_col      = input.color(color.rgb(82, 35, 89),   title = 'Background Color',                                              group = tab_grp, inline = 'frame')
i_tab_text_size = input.string(defval = "Normal", title = "Table Font Size", options = ["Tiny", "Small", "Normal", "Large", "Huge"],  group = tab_grp, inline = 'frame1')
i_tab_text_col      = input.color(color.rgb(255, 255, 255), title = 'Text Color',                                                   group = tab_grp, inline = 'frame1')
i_tab_frame_col     = input.color(color.rgb(235, 235, 235), title = 'Frame Color',                                                  group = tab_grp, inline = 'frame2')
i_tab_frame_wid     = input.int(1, 'Table Frame Width',                                                                               group = tab_grp, inline = 'frame2')
i_tab_border_col    = input.color(color.rgb(148, 148, 148), title = 'Border Color',                                                 group = tab_grp, inline = 'frame3')
i_tab_border_wid    = input.int(1, 'Table Border Width',                                                                              group = tab_grp, inline = 'frame3')

//Calculations

// tried using this and couldn't get it to work. timediff = (time - time[i_candle_trl_num]) / 1000

start_prog_time = (time >= i_start_time) and timenow // begin time = time entered by user and end time is last candle
start_end_time = (time >= i_start_time) and (time <= i_end_time)  // begin time = time entered by user. end time = time entered by user
trail_time = time[i_candle_trl_num] and timenow  // begin time needs to be a set number of bars in the past determined by the user. End time = time of last candle

// Fill Colour
color background = i_background_col

bgcolor(start_prog_time and i_update_endtime ? background : start_end_time ? background : na)

// Candle Counter
var greencandlecount = 0
var redcandlecount = 0
var totalcandlecount = 0

if i_update_begtime and i_update_endtime and trail_time and (close > open)
    greencandlecount += 1
    totalcandlecount += 1
else if i_update_endtime and not i_update_begtime and start_prog_time and (close > open)
    greencandlecount += 1
    totalcandlecount += 1
else if start_end_time and (close > open)
    greencandlecount += 1
    totalcandlecount += 1

if i_update_begtime and i_update_endtime and trail_time and (close < open)
    redcandlecount += 1
    totalcandlecount += 1
else if i_update_endtime and not i_update_begtime and start_prog_time and (close < open)
    redcandlecount += 1
    totalcandlecount +=1
else if start_end_time and (close < open)
    redcandlecount += 1
    totalcandlecount +=1

// Candle %
redcandleperc = redcandlecount / totalcandlecount * 100
greencandleperc = greencandlecount / totalcandlecount * 100

// Alerts
var totalcandlecount_alarm = 0

alarm = if start_prog_time and (close > open)
    totalcandlecount_alarm += i_alert_interval

if i_update_endtime and (i_alert_interval == 5) and alarm 
    alert('Five Bars', alert.freq_once_per_bar_close)
if i_update_endtime and (i_alert_interval == 10) and alarm
    alert('Ten Bars', alert.freq_once_per_bar_close)
if i_update_endtime and (i_alert_interval == 20) and alarm
    alert('Twenty Bars', alert.freq_once_per_bar_close)

// Create table
// Map table text size
tab_text_size = switch i_tab_text_size
    "Tiny" => size.tiny
    "Small" => size.small
    "Normal" => size.normal
    "Large" => size.large
    "Huge" => size.huge

// Map table position
tab_pos = switch i_tab_pos
    "Top Right" => position.top_right
    "Top Center" => position.top_center
    "Top Left" => position.top_left
    "Middle Right" => position.middle_right
    "Middle Center" => position.middle_center
    "Middle Left" => position.middle_left
    "Bottom Right" => position.bottom_right
    "Bottom Center" => position.bottom_center
    "Bottom Left" => position.bottom_left

var datatable = table.new(tab_pos, 6, 6, bgcolor = i_tab_back_col, frame_color = i_tab_frame_col, frame_width = 1, border_color = i_tab_border_col, border_width = i_tab_border_wid) 

table.cell(datatable, 1, 1, text = "Red Candle Count: " + str.tostring(redcandlecount) + " \n Percent Red Candle: " + str.tostring(math.round(redcandleperc,2)) + "%", text_size = tab_text_size, bgcolor = i_tab_back_col, text_color=i_tab_text_col)
table.cell(datatable, 1, 2, text = "Green Candle Count: " + str.tostring(greencandlecount) + "\n Percent Green Candle: " + str.tostring(math.round(greencandleperc,2)) + "%", text_size = tab_text_size, bgcolor = i_tab_back_col, text_color = i_tab_text_col)
table.cell(datatable, 1, 3, text = "Total Candle Count: " + str.tostring(totalcandlecount), bgcolor = i_tab_back_col, text_size = tab_text_size, text_color=i_tab_text_col)

Update Dec 7th,2023: Ok. After doing some more research I think I need to add a loop to count the bars back from the current time (instead of that line of code that begins with "trail time"). And,use that to calculate the green/red/total bars for a set number of bars back from the current time. But, I just can't figure out how to do that. I will update if I figure it out.

1

There are 1 answers

0
shaneaus On

This was the section that was causing me the headache and I figured it out. I still needed to clean up the rest of the code to make sure the background and table updated properly. But, this was the loop section that allowed the background to follow the last set number of candles:

{var int greencandlecount = 0
var int redcandlecount = 0
var int totalcandlecount = 0

if i_update_trail_time and barstate.islast
    totalcandlecount := i_candle_trl_num
    for i = 1 to i_candle_trl_num
        if close[i] > open[i]
            greencandlecount += 1
        else
            na
if i_update_trail_time and barstate.islast
    for i = 1 to i_candle_trl_num
        if close[i] < open[i]
            redcandlecount += 1
        else
            na}