Create Indicator for TradingView that can detect 1. Uptrend (Bullish Trend)
An uptrend is characterized by a series of higher highs and higher lows. This indicates that buyers are consistently pushing the price higher, showing bullish market sentiment.
Higher Highs (HH): Each peak in the trend is higher than the previous one.
Higher Lows (HL): Each trough or pullback does not fall below the last low and is higher than the previous trough.
Example Process:
Identify the initial low point.
Find the next high point that surpasses the previous high.
Confirm that the subsequent low remains above the initial low.
Continue tracking this pattern of increasing highs and lows.
2. Downtrend (Bearish Trend)
A downtrend occurs when there is a series of lower highs and lower lows, signaling that sellers are dominating the market.
Lower Highs (LH): Each peak is lower than the previous one.
Lower Lows (LL): Each trough is lower than the prior low.
Example Process:
Start from an initial high point.
Track the next low point that surpasses the previous low.
Ensure that the following high does not reach the prior high.
Continue following the trend with lower highs and lower lows.
3. Sideways/Range-Bound Trend
A sideways trend happens when price moves within a horizontal range, showing no clear higher highs or lower lows. This is an indication of indecision or consolidation in the market.
Visual Approach
You can use a line or bar chart to connect the significant highs and lows, helping you spot these trends more clearly. Drawing trendlines:
Uptrend Line: Drawn by connecting two or more rising lows.
Downtrend Line: Drawn by connecting two or more declining highs.
Assistant
Certainly! I can help you create a custom TradingView indicator using Pine Script that detects uptrends, downtrends, and sideways ranges based on the criteria you've provided. The indicator will identify patterns of higher highs and higher lows for uptrends, lower highs and lower lows for downtrends, and will recognize sideways movements when neither trend is dominant.
Below is the Pine Script code for the indicator, along with explanations to help you understand how it works.
pine
//@version=5
indicator("Trend Detector by OpenAI", overlay=true)
// Input parameters
lookback = input.int(5, "Swing High/Low Lookback", minval=1)
threshold = input.float(0.5, "Sideways Threshold (%)", minval=0.1, maxval=5.0)
// Detecting Swing Highs and Swing Lows
float hh = ta.pivothigh(high, lookback, lookback)
float ll = ta.pivotlow(low, lookback, lookback)
// Arrays to store swing highs and lows
var swingHighs = array.new_float()
var swingHighsTime = array.new_int()
var swingLows = array.new_float()
var swingLowsTime = array.new_int()
// Collect swing highs
if not na(hh)
array.push(swingHighs, hh)
array.push(swingHighsTime, bar_index - lookback)
// Collect swing lows
if not na(ll)
array.push(swingLows, ll)
array.push(swingLowsTime, bar_index - lookback)
// Function to determine the trend
f_getTrend() =>
trend = 0 // 1 = Uptrend, -1 = Downtrend, 0 = Sideways
if array.size(swingHighs) >= 2 and array.size(swingLows) >= 2
// Get the last two swing highs and lows
hh1 = array.get(swingHighs, array.size(swingHighs) - 1)
hh0 = array.get(swingHighs, array.size(swingHighs) - 2)
lh1 = array.get(swingLows, array.size(swingLows) - 1)
lh0 = array.get(swingLows, array.size(swingLows) - 2)
// Check for uptrend
isHH = hh1 > hh0
isHL = lh1 > lh0
// Check for downtrend
isLH = hh1 < hh0
isLL = lh1 < lh0
if isHH and isHL
trend := 1 // Uptrend
else if isLH and isLL
trend := -1 // Downtrend
else
// Calculate price range for sideways detection
maxRecentHigh = math.max(hh1, hh0)
minRecentLow = math.min(lh1, lh0)
rangePerc = ((maxRecentHigh - minRecentLow) / minRecentLow) * 100
if rangePerc <= threshold
trend := 0 // Sideways
trend
// Determine the current trend
currentTrend = f_getTrend()
// Plotting
plotshape(not na(hh) ? hh : na, title="Swing Highs", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.tiny)
plotshape(not na(ll) ? ll : na, title="Swing Lows", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.tiny)
// Background colors for trend indication
bgcolor(currentTrend == 1 ? color.new(color.green, 85) : currentTrend == -1 ? color.new(color.red, 85) : color.new(color.gray, 85), title="Trend Background")
// Display trend label
var label trendLabel = na
if barstate.islast
label.delete(trendLabel)
trendText = currentTrend == 1 ? "Uptrend" : currentTrend == -1 ? "Downtrend" : "Sideways"
trendColor = currentTrend == 1 ? color.green : currentTrend == -1 ? color.red : color.gray
trendLabel := label.new(bar_index, high, trendText, color=color.new(trendColor, 0), textcolor=color.white, style=label.style_label_upper_left)
How the Indicator Works:
1. Swing Highs and Swing Lows Detection:
The indicator uses the ta.pivothigh and ta.pivotlow functions to detect swing highs and swing lows.
The lookback parameter determines how many bars are considered before and after the current bar to qualify a point as a swing high or low.
Swing highs and lows are stored in arrays along with their respective bar indices.
2. Trend Determination:
The function f_getTrend() analyzes the last two swing highs and swing lows.
Uptrend Criteria:
The most recent swing high (hh1) is higher than the previous swing high (hh0).
The most recent swing low (lh1) is higher than the previous swing low (lh0).
Downtrend Criteria:
The most recent swing high (hh1) is lower than the previous swing high (hh0).
The most recent swing low (lh1) is lower than the previous swing low (lh0).
Sideways Trend Criteria:
If neither uptrend nor downtrend conditions are met, and the price range between recent highs and lows is within the threshold, the market is considered to be moving sideways.
3. Plotting on the Chart:
Swing highs are marked with red downward triangles above the bars.
Swing lows are marked with green upward triangles below the bars.
The background color changes based on the detected trend:
Green for uptrend.
Red for downtrend.
Gray for sideways movement.
A label displays the current trend at the last bar on the chart.
How to Use the Indicator:
Add the Indicator to Your Chart:
Copy the code above.
Open TradingView, go to the Pine Editor, and paste the code.
Click on "Add to Chart."
Adjust the Parameters:
Swing High/Low Lookback (lookback):
Controls the sensitivity of swing point detection.
A smaller number detects more swings (more sensitive), while a larger number detects fewer swings (less sensitive).
Sideways Threshold (threshold):
Defines the percentage range within which the price is considered to be moving sideways.
Adjust this value based on the volatility of the asset you're analyzing.
Interpreting the Signals:
Uptrend:
Look for a series of higher swing highs and higher swing lows.
Background turns green, and the trend label shows "Uptrend."
Downtrend:
Look for a series of lower swing highs and lower swing lows.
Background turns red, and the trend label shows "Downtrend."
Sideways:
When neither uptrend nor downtrend patterns are present, and price movement is within the defined threshold.
Background turns gray, and the trend label shows "Sideways."
Notes and Considerations:
Sensitivity:
The accuracy of trend detection depends on the lookback period for swing points.
Experiment with different lookback values to suit different timeframes and assets.
Threshold Adjustment:
The threshold parameter for sideways detection should be adjusted according to the asset's typical volatility.
For highly volatile assets, you might need a higher threshold.
Limitations:
The indicator relies on past swing points and may lag current price action.
False signals can occur, especially in choppy markets.
Always use this indicator in conjunction with other analysis tools and risk management practices.
Example Process:
Identifying an Uptrend:
The indicator finds an initial swing low (lh0).
Identifies the next swing high (hh0) that is higher than the previous swing high.
Confirms the subsequent swing low (lh1) is higher than lh0.
If both conditions are satisfied, it marks an uptrend.
Identifying a Downtrend:
Starts from a swing high (hh0).
Detects the next swing low (lh0) that is lower than the previous swing low.
Ensures the following swing high (hh1) is lower than hh0.
If these conditions are met, it indicates a downtrend.
Identifying a Sideways Trend:
If the recent swing highs and lows do not make higher highs/lows or lower highs/lows.
Calculates the price range between recent swing highs and lows.
If this range is within the threshold, it signifies sideways movement.
Feel free to customize and adjust the code to better fit your trading style or specific requirements. Always remember to test the indicator on historical data to ensure it works as expected before applying it to live markets.
If you have any questions or need further assistance with the indicator, please let me know!