Skip to content
TheChatArchiveThe Chat Archive
o1-preview-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

Allow User to Customize the Number of Recent Pivot to Determine Trend: //@version=5…

  1. User

    Allow User to Customize the Number of Recent Pivot to Determine Trend: //@version=5 indicator("Higher Time Frame Trend Detector", overlay=true)

    // User Inputs higher_tf = input.timeframe("D", "Higher Time Frame") pivot_left = input.int(5, "Pivot Left Bars", minval=1) pivot_right = input.int(5, "Pivot Right Bars", minval=1) ma_length = input.int(21, "MA Length")

    // Get Higher Time Frame Data htf_high = request.security(syminfo.tickerid, higher_tf, high) htf_low = request.security(syminfo.tickerid, higher_tf, low) htf_close = request.security(syminfo.tickerid, higher_tf, close) htf_bar_index = request.security(syminfo.tickerid, higher_tf, bar_index)

    // Detect Pivots in Higher Time Frame pivot_high = ta.pivothigh(htf_high, pivot_left, pivot_right) pivot_low = ta.pivotlow(htf_low, pivot_left, pivot_right)

    // Shift pivots by pivot_right bars to align them properly pivot_high_shifted = pivot_high[pivot_right] pivot_low_shifted = pivot_low[pivot_right]

    // Initialize arrays to store pivots var string[] pivot_types = array.new_string() var int[] pivot_bars = array.new_int() var float[] pivot_values = array.new_float()

    // Initialize series variables for pivot highs and lows var float pivot_high_plot = na var float pivot_low_plot = na

    // Add pivot highs to arrays if not na(pivot_high_shifted) array.unshift(pivot_types, "H") array.unshift(pivot_bars, htf_bar_index[pivot_right]) array.unshift(pivot_values, pivot_high_shifted) // Assign pivot_high_shifted to pivot_high_plot for plotting pivot_high_plot := pivot_high_shifted else pivot_high_plot := na

    // Add pivot lows to arrays if not na(pivot_low_shifted) array.unshift(pivot_types, "L") array.unshift(pivot_bars, htf_bar_index[pivot_right]) array.unshift(pivot_values, pivot_low_shifted) // Assign pivot_low_shifted to pivot_low_plot for plotting pivot_low_plot := pivot_low_shifted else pivot_low_plot := na

    // Limit the size of the arrays to the last 10 pivots to conserve memory if array.size(pivot_types) > 10 array.pop(pivot_types) array.pop(pivot_bars) array.pop(pivot_values)

    // Initialize Trend Variable var string trend = na

    // Check if we have at least four pivots to analyze if array.size(pivot_types) >= 4 // Extract the last four pivots string pivot1_type = array.get(pivot_types, 0) float pivot1_value = array.get(pivot_values, 0) string pivot2_type = array.get(pivot_types, 1) float pivot2_value = array.get(pivot_values, 1) string pivot3_type = array.get(pivot_types, 2) float pivot3_value = array.get(pivot_values, 2) string pivot4_type = array.get(pivot_types, 3) float pivot4_value = array.get(pivot_values, 3)

    // Define sequences for uptrend and downtrend
    bool is_downtrend_sequence = pivot1_type == "H" and pivot2_type == "L" and pivot3_type == "H" and pivot4_type == "L"
    bool is_uptrend_sequence = pivot1_type == "L" and pivot2_type == "H" and pivot3_type == "L" and pivot4_type == "H"
    
    // Check for Lower Highs and Lower Lows
    bool lower_highs = pivot1_value < pivot3_value
    bool lower_lows = pivot2_value < pivot4_value
    // Check for Higher Highs and Higher Lows
    bool higher_highs = pivot2_value > pivot4_value
    bool higher_lows = pivot1_value > pivot3_value
    
    // Confirm trend with price action crossing pivot levels
    bool price_crossed_below_pivot_low = htf_close < pivot2_value  // For downtrend, price crosses below the recent low
    bool price_crossed_above_pivot_high = htf_close > pivot2_value // For uptrend, price crosses above the recent high
    
    // Determine the trend
    if is_downtrend_sequence and lower_highs and lower_lows and price_crossed_below_pivot_low
        trend := "Downtrend"
    else if is_uptrend_sequence and higher_highs and higher_lows and price_crossed_above_pivot_high
        trend := "Uptrend"
    else
        trend := "Sideways"
    

    else trend := "Sideways"

    // Display Trend Condition using Table var table trend_table = table.new(position.top_right, 1, 1)

    bgcolor = trend == "Uptrend" ? color.new(color.green, 70) : trend == "Downtrend" ? color.new(color.red, 70) : color.new(color.orange, 70)

    // Update the table cell on every bar table.cell(trend_table, 0, 0, "Trend: " + trend, text_color=color.white, bgcolor=bgcolor)

    // Plot the pivot highs and lows outside of any local scope plot(pivot_high_plot, "Pivot High", color=color.red, style=plot.style_circles, linewidth=2) plot(pivot_low_plot, "Pivot Low", color=color.lime, style=plot.style_circles, linewidth=2)

    // Plot the Moving Average (if you wish to include it) htf_ma = ta.sma(htf_close, ma_length) plot(htf_ma, "Higher TF MA", color=color.blue)

  2. Assistant

    Certainly! To allow the user to customize the number of recent pivots to determine the trend, we'll make the following changes to your script:

    1. Add a User Input for the Number of Pivots: Introduce a new input variable that lets the user specify the number of recent pivots to analyze for determining the trend.

    2. Modify the Trend Determination Logic: Adjust the existing logic to use the user-specified number of pivots instead of the fixed number (which was 4 in your original script).

    3. Generalize the Trend Detection Algorithm: Update the algorithm to work dynamically with any number of pivots specified by the user.

    Below is the modified script with the necessary changes, along with explanations:

    //@version=5
    indicator("Higher Time Frame Trend Detector", overlay=true)
    
    // User Inputs
    higher_tf = input.timeframe("D", "Higher Time Frame")
    pivot_left = input.int(5, "Pivot Left Bars", minval=1)
    pivot_right = input.int(5, "Pivot Right Bars", minval=1)
    ma_length = input.int(21, "MA Length")
    num_pivots = input.int(4, "Number of Recent Pivots", minval=2)
    
    // Get Higher Time Frame Data
    htf_high = request.security(syminfo.tickerid, higher_tf, high)
    htf_low = request.security(syminfo.tickerid, higher_tf, low)
    htf_close = request.security(syminfo.tickerid, higher_tf, close)
    htf_bar_index = request.security(syminfo.tickerid, higher_tf, bar_index)
    
    // Detect Pivots in Higher Time Frame
    pivot_high = ta.pivothigh(htf_high, pivot_left, pivot_right)
    pivot_low = ta.pivotlow(htf_low, pivot_left, pivot_right)
    
    // Shift pivots by pivot_right bars to align them properly
    pivot_high_shifted = pivot_high[pivot_right]
    pivot_low_shifted = pivot_low[pivot_right]
    
    // Initialize arrays to store pivots
    var string[] pivot_types = array.new_string()
    var int[] pivot_bars = array.new_int()
    var float[] pivot_values = array.new_float()
    
    // Initialize series variables for pivot highs and lows
    var float pivot_high_plot = na
    var float pivot_low_plot = na
    
    // Add pivot highs to arrays
    if not na(pivot_high_shifted)
        array.unshift(pivot_types, "H")
        array.unshift(pivot_bars, htf_bar_index[pivot_right])
        array.unshift(pivot_values, pivot_high_shifted)
        // Assign pivot_high_shifted to pivot_high_plot for plotting
        pivot_high_plot := pivot_high_shifted
    else
        pivot_high_plot := na
    
    // Add pivot lows to arrays
    if not na(pivot_low_shifted)
        array.unshift(pivot_types, "L")
        array.unshift(pivot_bars, htf_bar_index[pivot_right])
        array.unshift(pivot_values, pivot_low_shifted)
        // Assign pivot_low_shifted to pivot_low_plot for plotting
        pivot_low_plot := pivot_low_shifted
    else
        pivot_low_plot := na
    
    // Limit the size of the arrays to conserve memory
    max_array_size = num_pivots * 2  // Since we can have both highs and lows
    if array.size(pivot_types) > max_array_size
        array.pop(pivot_types)
        array.pop(pivot_bars)
        array.pop(pivot_values)
    
    // Initialize Trend Variable
    var string trend = na
    
    // Check if we have enough pivots to analyze
    if array.size(pivot_types) >= num_pivots
        // Flags to check trend conditions
        bool higher_highs = true
        bool higher_lows = true
        bool lower_highs = true
        bool lower_lows = true
    
        // Iterate over the pivots to determine the trend
        for i = 0 to num_pivots - 2
            string pivot_type_current = array.get(pivot_types, i)
            float pivot_value_current = array.get(pivot_values, i)
            string pivot_type_next = array.get(pivot_types, i + 1)
            float pivot_value_next = array.get(pivot_values, i + 1)
    
            // Check for higher highs and higher lows
            if pivot_type_current == "H" and pivot_type_next == "H"
                higher_highs := higher_highs and (pivot_value_current > pivot_value_next)
                lower_highs := lower_highs and (pivot_value_current < pivot_value_next)
            if pivot_type_current == "L" and pivot_type_next == "L"
                higher_lows := higher_lows and (pivot_value_current > pivot_value_next)
                lower_lows := lower_lows and (pivot_value_current < pivot_value_next)
        
        // Determine the trend based on pivot comparisons
        if higher_highs and higher_lows
            trend := "Uptrend"
        else if lower_highs and lower_lows
            trend := "Downtrend"
        else
            trend := "Sideways"
    else
        trend := "Sideways"
    
    // Display Trend Condition using Table
    var table trend_table = table.new(position.top_right, 1, 1)
    
    bgcolor = trend == "Uptrend" ? color.new(color.green, 70) : trend == "Downtrend" ? color.new(color.red, 70) : color.new(color.orange, 70)
    
    // Update the table cell on every bar
    table.cell(trend_table, 0, 0, "Trend: " + trend, text_color=color.white, bgcolor=bgcolor)
    
    // Plot the pivot highs and lows outside of any local scope
    plot(pivot_high_plot, "Pivot High", color=color.red, style=plot.style_circles, linewidth=2)
    plot(pivot_low_plot, "Pivot Low", color=color.lime, style=plot.style_circles, linewidth=2)
    
    // Plot the Moving Average (if you wish to include it)
    htf_ma = ta.sma(htf_close, ma_length)
    plot(htf_ma, "Higher TF MA", color=color.blue)
    

    Explanation of the Changes:

    1. Added User Input for Number of Pivots:

      num_pivots = input.int(4, "Number of Recent Pivots", minval=2)
      
      • This allows the user to specify how many recent pivots they want to use for trend determination.
      • Minimum value is set to 2 because we need at least two pivots to compare for a trend.
    2. Adjusted Array Size Limitation:

      max_array_size = num_pivots * 2  // Since we can have both highs and lows
      if array.size(pivot_types) > max_array_size
          array.pop(pivot_types)
          array.pop(pivot_bars)
          array.pop(pivot_values)
      
      • The arrays now limit their size based on the num_pivots input to conserve memory.
    3. Modified Trend Determination Logic:

      // Initialize Trend Variable
      var string trend = na
      
      // Check if we have enough pivots to analyze
      if array.size(pivot_types) >= num_pivots
          // Flags to check trend conditions
          bool higher_highs = true
          bool higher_lows = true
          bool lower_highs = true
          bool lower_lows = true
      
          // Iterate over the pivots to determine the trend
          for i = 0 to num_pivots - 2
              string pivot_type_current = array.get(pivot_types, i)
              float pivot_value_current = array.get(pivot_values, i)
              string pivot_type_next = array.get(pivot_types, i + 1)
              float pivot_value_next = array.get(pivot_values, i + 1)
      
              // Check for higher highs and higher lows
              if pivot_type_current == "H" and pivot_type_next == "H"
                  higher_highs := higher_highs and (pivot_value_current > pivot_value_next)
                  lower_highs := lower_highs and (pivot_value_current < pivot_value_next)
              if pivot_type_current == "L" and pivot_type_next == "L"
                  higher_lows := higher_lows and (pivot_value_current > pivot_value_next)
                  lower_lows := lower_lows and (pivot_value_current < pivot_value_next)
          
          // Determine the trend based on pivot comparisons
          if higher_highs and higher_lows
              trend := "Uptrend"
          else if lower_highs and lower_lows
              trend := "Downtrend"
          else
              trend := "Sideways"
      else
          trend := "Sideways"
      
      • The logic now uses a loop to compare each pair of consecutive pivots based on the number specified by the user.
      • It sets flags for higher_highs, higher_lows, lower_highs, and lower_lows.
      • If all the higher_highs and higher_lows conditions are true across the pivots, it determines an uptrend.
      • If all the lower_highs and lower_lows conditions are true, it determines a downtrend.
      • Otherwise, it sets the trend to sideways.
    4. Ensured Minimum Number of Pivots for Analysis:

      if array.size(pivot_types) >= num_pivots
          // Proceed with trend analysis
      else
          trend := "Sideways"
      
      • The script checks if there are enough pivots collected to perform the analysis.

    Notes:

    • Trend Determination Logic: The generalized algorithm considers the sequence of pivots and checks whether each subsequent pivot high is higher (or lower) than the previous one, and likewise for pivots low. This way, it can accommodate any number of pivots specified.

    • Pivot Types and Values: We compare only the same types (Highs with Highs and Lows with Lows) as mixing them could lead to incorrect trend identification.

    • Memory Management: By adjusting the size of the arrays based on the number of pivots, we ensure that the script remains efficient.

    Testing the Script:

    • Uptrend Scenario: If you set num_pivots to 4 and the recent pivot highs and lows are forming higher highs and higher lows, the script should display an "Uptrend".

    • Downtrend Scenario: If the pivot highs and lows are forming lower highs and lower lows, it should display a "Downtrend".

    • Sideways Scenario: If the pivots do not consistently form higher highs/lows or lower highs/lows, the script will display "Sideways".

    Feel free to adjust the num_pivots input to suit your trading strategy and observe how the trend detection adapts accordingly.