Certainly! Let's improve your Pine Script code by addressing several areas:
-
Remove Unused Inputs: The num_pivots_to_show input is mentioned as not used anymore. We can remove it to clean up the code.
-
Optimize Trend Determination Logic: The current logic for determining trends can be improved for clarity and accuracy. We'll reorganize it to make it more intuitive.
-
Modularize the Code: We'll create functions for repeated tasks such as trend determination to make the code cleaner and more maintainable.
-
Enhance Customization: Add input options for colors and styles so users can customize the indicator without modifying the code.
-
Add Error Handling: Include checks to handle potential issues with the selected time frames.
-
Improve Plotting: Ensure pivot points and moving averages are plotted accurately with appropriate offsets.
Here's the improved code with the suggested enhancements:
//@version=5
indicator("Multi Time Frame Trend Detector", overlay=true)
// === User Inputs ===
// Time Frame Inputs
higher_tf = input.timeframe("D", "Higher Time Frame")
intermediate_tf = input.timeframe("60", "Intermediate Time Frame")
// Pivot Parameters
pivot_left = input.int(5, "Pivot Left Bars", minval=1)
pivot_right = input.int(5, "Pivot Right Bars", minval=1)
// Moving Average Length
ma_length = input.int(21, "MA Length")
// Customization Inputs
// Trend Colors
htf_trend_up_color = input.color(color.new(color.green, 70), "HTF Uptrend Color")
htf_trend_down_color = input.color(color.new(color.red, 70), "HTF Downtrend Color")
htf_trend_sideways_color = input.color(color.new(color.orange, 70), "HTF Sideways Trend Color")
itf_trend_up_color = input.color(color.new(color.green, 70), "ITF Uptrend Color")
itf_trend_down_color = input.color(color.new(color.red, 70), "ITF Downtrend Color")
itf_trend_sideways_color = input.color(color.new(color.orange, 70), "ITF Sideways Trend Color")
// Pivot Point Colors
htf_pivot_high_color = input.color(color.red, "HTF Pivot High Color")
htf_pivot_low_color = input.color(color.lime, "HTF Pivot Low Color")
itf_pivot_high_color = input.color(color.purple, "ITF Pivot High Color")
itf_pivot_low_color = input.color(color.yellow, "ITF Pivot Low Color")
// Pivot Shape Size
pivot_shape_size = input.string("tiny", "Pivot Shape Size", options=["tiny", "small", "normal", "large", "huge"])
// === Error Handling ===
if timeframe.period == higher_tf or timeframe.period == intermediate_tf
warning_message = "Chart timeframe should be lower than the selected higher/intermediate timeframes."
alert(warning_message, alert.freq_once_per_bar)
runtime.error(warning_message)
// === Time Frame Data Retrieval ===
get_tf_data(_tf) =>
[tf_high, tf_low, tf_close] = request.security(syminfo.tickerid, _tf, [high, low, close], lookahead=barmerge.lookahead_on)
[tf_high, tf_low, tf_close]
// Higher Time Frame Data
[htf_high, htf_low, htf_close] = get_tf_data(higher_tf)
// Intermediate Time Frame Data
[itf_high, itf_low, itf_close] = get_tf_data(intermediate_tf)
// === Pivot Point Detection ===
get_pivots(_high, _low, _pivot_left, _pivot_right) =>
pivot_high = ta.pivothigh(_high, _pivot_left, _pivot_right)
pivot_low = ta.pivotlow(_low, _pivot_left, _pivot_right)
[pivot_high, pivot_low]
// Higher Time Frame Pivots
[htf_pivot_high, htf_pivot_low] = get_pivots(htf_high, htf_low, pivot_left, pivot_right)
// Intermediate Time Frame Pivots
[itf_pivot_high, itf_pivot_low] = get_pivots(itf_high, itf_low, pivot_left, pivot_right)
// === Moving Averages ===
htf_ma = ta.sma(htf_close, ma_length)
itf_ma = ta.sma(itf_close, ma_length)
// === Trend Determination Functions ===
determine_trend(_pivot_high, _pivot_low, _close, _ma) =>
var string trend = "Sideways"
if not na(_pivot_high)
trend := "Downtrend"
else if not na(_pivot_low)
trend := "Uptrend"
// Adjust trend based on price vs MA
if _close > _ma
trend := trend == "Downtrend" ? "Sideways" : "Uptrend"
else if _close < _ma
trend := trend == "Uptrend" ? "Sideways" : "Downtrend"
trend
// Higher Time Frame Trend
htf_trend = determine_trend(htf_pivot_high, htf_pivot_low, htf_close, htf_ma)
// Intermediate Time Frame Trend
itf_trend = determine_trend(itf_pivot_high, itf_pivot_low, itf_close, itf_ma)
// === Trend Table Display ===
// Create Table with 2 rows for HTF and ITF trends
var table trend_table = table.new(position.top_right, 1, 2, border_width=1)
// Apply colors to the trend backgrounds
htf_bgcolor = htf_trend == "Uptrend" ? htf_trend_up_color :
htf_trend == "Downtrend" ? htf_trend_down_color :
htf_trend_sideways_color
itf_bgcolor = itf_trend == "Uptrend" ? itf_trend_up_color :
itf_trend == "Downtrend" ? itf_trend_down_color :
itf_trend_sideways_color
// Update the table cells on every bar
table.cell(trend_table, 0, 0, "HTF Trend: " + htf_trend, text_color=color.white, bgcolor=htf_bgcolor)
table.cell(trend_table, 0, 1, "ITF Trend: " + itf_trend, text_color=color.white, bgcolor=itf_bgcolor)
// === Pivot Plotting Management ===
// Map string input to size constant
shape_size = switch pivot_shape_size
"tiny" => size.tiny
"small" => size.small
"normal" => size.normal
"large" => size.large
"huge" => size.huge
// Plot pivot points for HTF
plotshape(not na(htf_pivot_high) ? htf_high : na, title="HTF Pivot High", style=shape.triangledown, location=location.absolute, color=htf_pivot_high_color, size=shape_size, offset=-pivot_right)
plotshape(not na(htf_pivot_low) ? htf_low : na, title="HTF Pivot Low", style=shape.triangleup, location=location.absolute, color=htf_pivot_low_color, size=shape_size, offset=-pivot_right)
// Plot pivot points for ITF
plotshape(not na(itf_pivot_high) ? itf_high : na, title="ITF Pivot High", style=shape.triangledown, location=location.absolute, color=itf_pivot_high_color, size=shape_size, offset=-pivot_right)
plotshape(not na(itf_pivot_low) ? itf_low : na, title="ITF Pivot Low", style=shape.triangleup, location=location.absolute, color=itf_pivot_low_color, size=shape_size, offset=-pivot_right)
// === Moving Averages Plotting ===
// Plot the moving averages with labels for clarity
plot(htf_ma, title="HTF MA", color=color.blue, linewidth=2)
plot(itf_ma, title="ITF MA", color=color.orange, linewidth=2)
Explanation of Improvements:
-
Removed Unused Input:
- Eliminated
num_pivots_to_show since it's not used.
-
Optimized Trend Determination Logic:
- Created a
determine_trend function to encapsulate the trend logic.
- This function checks for pivot points and adjusts the trend based on the price's relation to the moving average.
- Simplified the logic for better readability and accuracy.
-
Modularized Code with Functions:
- Introduced
get_tf_data and get_pivots functions to reduce repetitive code and improve maintainability.
- Functions enhance code organization and clarity.
-
Enhanced Customization:
- Added inputs for trend colors, pivot point colors, and pivot shape sizes, allowing users to customize the indicator appearance.
- Mapped string inputs to
size constants for pivot shapes.
-
Added Error Handling:
- Included a check to ensure the chart's timeframe is lower than the selected higher and intermediate time frames.
- Displays a warning and stops execution if the condition isn't met to prevent misleading results.
-
Improved Plotting:
- Corrected the pivot point plotting offsets to align accurately with the chart.
- Included labels and custom colors for moving averages for better distinction.
-
Code Formatting and Comments:
- Cleaned up the code formatting for better readability.
- Added comments to explain each section, making it easier for others to understand and maintain the code.
Notes:
-
The pivot points are plotted with an offset of -pivot_right because in Pine Script, pivot points are confirmed after pivot_right bars have passed.
-
The trend determination now consistently checks for the presence of pivot highs or lows and then adjusts based on the moving average.
-
Error handling ensures users select appropriate time frames to avoid confusion.
This improved version should provide more accurate trend detection, a cleaner codebase, and enhanced user customization. Let me know if you need further adjustments or explanations!