te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>pine script - How to count HTF candles backwards on a LTF chart in TradingView - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

pine script - How to count HTF candles backwards on a LTF chart in TradingView - Stack Overflow

programmeradmin3浏览0评论

I'm trying to achieve the following

  • I want to count candles backwards for a specific timeframe (e.g. 1D) and only add the values to an array if they meet some criteria
  • If I'm on a LTF chart (e.g. 1M, 5M, 15M) I want to make sure that my calculation results are unchanged.
  • The idea is to then make a request.security() call to get the criteria specific candle data (e.g. open[1], open[14], open[42])

I'm struggling a bit to implement this. My idea so far has been this, but it isn't working as expected.

step 1: Manually create the historical data / criteria (which is based on the economic calendar). Have to create manually since this isn't available to obtain within PineScript.

Step 2: Define the constants, variables and start the calculations. Basically check if today matches a historical event date and set these values to those variables. Then calculations.

Step 3: The first function calculates the timestamps for these event dates. The second one counts how many candles back this event happens to occur on (however this part isn't exactly correct)

Simplified code sample

//@version=6 
indicator("Simplified Example", overlay = true, max_bars_back=1000)

// === User Inputs ===
tf_1day_enabled = input.bool(true, "D", "1 day", "row 1", "Timeframe")

// === Step 1: Historical Data Section ===
var int[] fomc_dates = array.new_int(0)

if bar_index == 0
    array.push(fomc_dates, timestamp(2025, 3, 18, 0, 0))
    array.push(fomc_dates, timestamp(2025, 2, 18, 0, 0)) // for testing purposes adjust to current date
    array.push(fomc_dates, timestamp(2025, 1, 29, 0, 0))
    array.push(fomc_dates, timestamp(2024, 12, 18, 0, 0))
    array.push(fomc_dates, timestamp(2024, 11, 7, 0, 0))

// === Step 3: Functions Section ===

// Returns an array of past timestamp date values equal to the lookback period (e.g. lookback = 3, 3 values returned)
find_past_events(event_array, int lookback) =>
    var int[] past_dates = array.new_int(0)

    for i = 0 to array.size(event_array) - 1
        if array.size(past_dates) < lookback and array.get(event_array, i) < timestamp(year, month, dayofmonth, hour, 0)
            array.push(past_dates, array.get(event_array, i))
    past_dates

// Returns an array of numbers showing how many candles counting back from current did the event news happen
find_matching_candles(event_array) =>
    var int[] candles_back = array.new_int(0)

    int i = 1
    int j = 0
    int max_allowable_candles = 1000

    while i < max_allowable_candles and j < array.size(event_array) and array.size(candles_back) < array.size(event_array)
        if dayofweek != dayofweek.saturday and dayofweek != dayofweek.sunday
            historical_timestamp = timestamp(year, month, dayofmonth - i, 0, 0)

            if historical_timestamp == array.get(event_array, j)
                if array.size(candles_back) == 0 or array.get(candles_back, array.size(candles_back) - 1) < i
                    array.push(candles_back, i)  // Add only if it is unique
                j := j + 1
        i := i + 1

    candles_back

// === Step 2: Define Constants & variables & start calculations ===
calculation_lookback = 3

var string event_type = "normal"
var event_dates = array.new_int(0)
var past_candles_back = array.new_int(0)

if tf_1day_enabled
    // Get past news event dates
    if array.includes(fomc_dates, timestamp(year, month, dayofmonth, 0, 0))
        event_type := "fomc"
        event_dates := fomc_dates

    past_event_dates = event_type != "normal" ? find_past_events(event_dates, calculation_lookback) : event_dates  // Ignore normal days for now 
    past_candles_back := find_matching_candles(past_event_dates)
    // log.info(str.tostring(past_candles_back)) // returns [1, 43, 107]

bgcolor(bar_index == 10 ? color.yellow : na) // plot something random for it to run

My issues are:

  • This approach isn't calculating 1D candles backwards and it's estimating how many candles back it is based on time. Holidays and weekends have an affect when using time.
  • The returned array I get is [1, 43, 107], but if I manually count the candles on the 1D chart... I should get [1, 14, 42]. I don't get why I have this large of a difference with counting backwards by 1 day (time).
  • I feel that there is a better/easier way to do this and ideally actually counting the 1D candles. So I don't have to worry about weekends and holidays.

Can anyone help me with this?

I'm trying to achieve the following

  • I want to count candles backwards for a specific timeframe (e.g. 1D) and only add the values to an array if they meet some criteria
  • If I'm on a LTF chart (e.g. 1M, 5M, 15M) I want to make sure that my calculation results are unchanged.
  • The idea is to then make a request.security() call to get the criteria specific candle data (e.g. open[1], open[14], open[42])

I'm struggling a bit to implement this. My idea so far has been this, but it isn't working as expected.

step 1: Manually create the historical data / criteria (which is based on the economic calendar). Have to create manually since this isn't available to obtain within PineScript.

Step 2: Define the constants, variables and start the calculations. Basically check if today matches a historical event date and set these values to those variables. Then calculations.

Step 3: The first function calculates the timestamps for these event dates. The second one counts how many candles back this event happens to occur on (however this part isn't exactly correct)

Simplified code sample

//@version=6 
indicator("Simplified Example", overlay = true, max_bars_back=1000)

// === User Inputs ===
tf_1day_enabled = input.bool(true, "D", "1 day", "row 1", "Timeframe")

// === Step 1: Historical Data Section ===
var int[] fomc_dates = array.new_int(0)

if bar_index == 0
    array.push(fomc_dates, timestamp(2025, 3, 18, 0, 0))
    array.push(fomc_dates, timestamp(2025, 2, 18, 0, 0)) // for testing purposes adjust to current date
    array.push(fomc_dates, timestamp(2025, 1, 29, 0, 0))
    array.push(fomc_dates, timestamp(2024, 12, 18, 0, 0))
    array.push(fomc_dates, timestamp(2024, 11, 7, 0, 0))

// === Step 3: Functions Section ===

// Returns an array of past timestamp date values equal to the lookback period (e.g. lookback = 3, 3 values returned)
find_past_events(event_array, int lookback) =>
    var int[] past_dates = array.new_int(0)

    for i = 0 to array.size(event_array) - 1
        if array.size(past_dates) < lookback and array.get(event_array, i) < timestamp(year, month, dayofmonth, hour, 0)
            array.push(past_dates, array.get(event_array, i))
    past_dates

// Returns an array of numbers showing how many candles counting back from current did the event news happen
find_matching_candles(event_array) =>
    var int[] candles_back = array.new_int(0)

    int i = 1
    int j = 0
    int max_allowable_candles = 1000

    while i < max_allowable_candles and j < array.size(event_array) and array.size(candles_back) < array.size(event_array)
        if dayofweek != dayofweek.saturday and dayofweek != dayofweek.sunday
            historical_timestamp = timestamp(year, month, dayofmonth - i, 0, 0)

            if historical_timestamp == array.get(event_array, j)
                if array.size(candles_back) == 0 or array.get(candles_back, array.size(candles_back) - 1) < i
                    array.push(candles_back, i)  // Add only if it is unique
                j := j + 1
        i := i + 1

    candles_back

// === Step 2: Define Constants & variables & start calculations ===
calculation_lookback = 3

var string event_type = "normal"
var event_dates = array.new_int(0)
var past_candles_back = array.new_int(0)

if tf_1day_enabled
    // Get past news event dates
    if array.includes(fomc_dates, timestamp(year, month, dayofmonth, 0, 0))
        event_type := "fomc"
        event_dates := fomc_dates

    past_event_dates = event_type != "normal" ? find_past_events(event_dates, calculation_lookback) : event_dates  // Ignore normal days for now 
    past_candles_back := find_matching_candles(past_event_dates)
    // log.info(str.tostring(past_candles_back)) // returns [1, 43, 107]

bgcolor(bar_index == 10 ? color.yellow : na) // plot something random for it to run

My issues are:

  • This approach isn't calculating 1D candles backwards and it's estimating how many candles back it is based on time. Holidays and weekends have an affect when using time.
  • The returned array I get is [1, 43, 107], but if I manually count the candles on the 1D chart... I should get [1, 14, 42]. I don't get why I have this large of a difference with counting backwards by 1 day (time).
  • I feel that there is a better/easier way to do this and ideally actually counting the 1D candles. So I don't have to worry about weekends and holidays.

Can anyone help me with this?

Share Improve this question asked 2 days ago AlwaysBeLearningAlwaysBeLearning 451 silver badge5 bronze badges 3
  • 1 You need to change the way you are thinking as it is not very optimal for pinescript. You should start from candle #0 and gather your data and later analyze the data you have. You almost never need to go "backwards". Just get your data from security() and store it somewhere. Then apply your conditions to that array and not try to call the security() function conditionally. – vitruvius Commented yesterday
  • @vitruvius Thank you for your comment. I do believe I need to change my thinking to understand. It's just not quite clicking yet. I get that PineScript (PS) is a time based language and the [] is not an index value, but essentially past bars. And PS is looping in nature. The thing that trips me up is looping 1 bar on the LTF does not match 1 bar on the HTF. So I get all available 1D data from security(). Then how does one process that historical data on the LTF? – AlwaysBeLearning Commented yesterday
  • Just to further clarify. Let's say I want to get candle information for the 212th bar back on the 1D chart. So open[212]. This is easy to get from security() when you know exactly how many candles back. If you request everything...then how do you loop through the HTF open values on a LTF (because the LTF chart doesn't go that far back candle wise)? – AlwaysBeLearning Commented yesterday
Add a comment  | 

1 Answer 1

Reset to default 0

In case someone gets stuck with wanting to count candles backwards on a HTF (which is flawed logic in PineScript), I figured out how to solve my problem correctly.

Original problem re-stated

How do I get specific candle data from a HTF chart for select, past dates (in my case based on economic calendar news dates), so I can perform some calculations on them?

Solution

It is actually really easy when you think that PineScript runs a continuous loop from the first candles available until the latest ones. The trick is to pass a function into the request.security() call to perform the (naturally looping) calculations on the HTF chart.

This is a simplified version of how I ended up solving my problem.

//@version=6 
indicator("Simplified Example", overlay = true)

fomc_date = timestamp(2025, 1, 29, 0, 0)

find_candles_on_htf() => 
    var open_prices = array.new_float(0)

    if timestamp(year, month, dayofmonth) == fomc_date
        // do calculations or get price info & store in local variable
        array.push(open_prices, open)

    open_prices

open_price_htf = request.security(syminfo.tickerid, "D", find_candles_on_htf())

// then you can use `open_price_htf` on LTF charts for whatever you need

发布评论

评论列表(0)

  1. 暂无评论