SMC style josh )SMC style josh — FVG, OB, BOS/CHoCH, EQH/EQL, PD, HTF, Trendlines
What it does
A clean-room Smart-Money–style study that visualizes market structure and liquidity concepts:
Structure: BOS & CHoCH for swing and internal legs (width/style controls, preview of last pivots)
Order Blocks: internal & swing OBs with midline (50%), mitigated/invalid handling, optional auto Breaker creation
Fair Value Gaps (FVG): auto boxes with optional 50% line, ATR filter, extend length, and “after-CHoCH only” window
Equal High/Low (EQH/EQL): ATR-based proximity threshold
Liquidity Grabs: wick-through/close-back tags
Premium/Discount (PD) zones: live boxes + equilibrium line from latest swing range
HTF levels: previous Daily/Weekly/Monthly highs/lows with labels (PDH/PDL, PWH/PWL, PMH/PML)
Trendlines: auto swing-to-swing lines (liquidity)
Confluence Score: column plot summarizing recent events (+/− weighting)
Key options
Safety switch to pause all drawings
Per-module visibility, label sizes/colors, line styles/widths
ATR-based filters for impulses and gaps
Limits for lines/labels/boxes to avoid runtime errors
How to read
BOS = continuation break of the current leg; CHoCH = potential regime shift
OB mitigated when price returns into the block; invalid when price closes beyond; mitigated-then-invalid can form a Breaker
FVG is considered “filled” when price closes through the gap boundary (optional hide/gray-out)
Strong/Weak High/Low tags reflect the active swing bias (potential liquidity/targets)
Good practice
Combine with risk management, multiple timeframes, and your own rules. All drawings are for study/visualization; signals are not trade instructions.
Compliance / Disclaimer
This script is for educational and research purposes only. It is not financial advice or a solicitation to buy/sell any asset. Past performance does not guarantee future results. Always test and manage risk responsibly.
License / Credits
Built with Pine Script® v5. “SMC style josh” is an original, clean-room implementation and does not reuse third-party code.
在脚本中搜索"TRENDLINES"
Z Distance from VWAP Enhanced (ZVWAP)The "Z Distance from VWAP Enhanced" (ZVWAP) indicator is a comprehensive oscillator that provides deep insights into market dynamics. It calculates a Z-score, which tells you how many standard deviations the current price is away from the VWAP. This normalization makes it a consistent and reliable tool for identifying market extremes.
The indicator comes packed with features, including:
Customizable Overbought & Oversold Zones
Built-in Bullish & Bearish Divergence Detection
Automatic Trendline Plotting
A Moving Exponential Average (MEA) for crossover signals
Fully customizable alerts for every key event.
How to Use It - The BTC Dominance Strategy for Altcoins
As shown in the screenshot, this indicator is an exceptional tool for trading altcoins by analyzing the BTC Dominance (BTC.D) chart. The relationship is typically inverse:
When ZVWAP on BTC.D is RISING (or Overbought) ➔ It's BEARISH for Altcoins.
This means Bitcoin is gaining dominance, and capital is flowing out of altcoins and into Bitcoin. This is a time to be cautious with or short altcoins.
When ZVWAP on BTC.D is FALLING (or Oversold) ➔ It's BULLISH for Altcoins.
This means Bitcoin is losing dominance, and capital is flowing into altcoins, often starting an "altcoin season." This is a great time to look for long entries on your favorite altcoins.
Key Signals on the BTC.D Chart:
Zone Entries: When ZVWAP enters the red (Overbought) zone, prepare for altcoins to weaken. When it enters the blue (Oversold) zone, look for altcoin strength.
MEA Crossover: A crossover of the yellow ZVWAP line below the cyan MEA line is a strong confirmation that dominance is falling and the trend is becoming bullish for altcoins.
Divergences: A bearish divergence on the BTC.D chart can be an early warning that dominance is about to fall, signaling a potential bullish move for altcoins.
Key Features Explained
Overbought / Oversold Zones: The red and blue shaded areas clearly define when an asset is statistically over-extended. These are prime areas to look for mean reversion or trend exhaustion.
Divergence Detection: The script automatically detects and plots divergences between price and the ZVWAP.
• Bullish Divergence: Price makes a lower low, but ZVWAP makes a higher low. (Potential buy signal).
• Bearish Divergence: Price makes a higher high, but ZVWAP makes a lower high. (Potential sell signal).
The Reference Lines (+1 / -1): These gray lines represent one standard deviation from the VWAP. They act as an early warning system. When the ZVWAP crosses these lines, it shows that momentum is building, and the price is starting to deviate significantly from its average.
Automatic Trendlines: The indicator can automatically draw and manage trendlines based on recent pivots in the ZVWAP, helping you visualize the current momentum and potential breakout points. This feature can be turned off if you prefer a cleaner chart.
Customization and Alerts
The indicator is fully customizable. You can adjust the lengths, zone levels, and visual settings to fit your trading style. Most importantly, it includes a comprehensive set of alerts:
Enter Overbought Zone
Enter Oversold Zone
Bullish Divergence Detected
Bearish Divergence Detected
Enter Any Zone (OB/OS) - a single alert for either condition.
Any Divergence (Bull/Bear) - a single alert for any divergence.
This allows you to stay informed of every important signal without having to watch the charts all day.
i.imgur.com
Volume Based Analysis V 1.00
Volume Based Analysis V1.00 – Multi-Scenario Buyer/Seller Power & Volume Pressure Indicator
Description:
1. Overview
The Volume Based Analysis V1.00 indicator is a comprehensive tool for analyzing market dynamics using Buyer Power, Seller Power, and Volume Pressure scenarios. It detects 12 configurable scenarios combining volume-based calculations with price action to highlight potential bullish or bearish conditions.
When used in conjunction with other technical tools such as Ichimoku, Bollinger Bands, and trendline analysis, traders can gain a deeper and more reliable understanding of the market context surrounding each signal.
2. Key Features
12 Configurable Scenarios covering Buyer/Seller Power convergence, divergence, and dominance
Advanced Volume Pressure Analysis detecting when both buy/sell volumes exceed averages
Global Lookback System ensuring consistency across all calculations
Dominance Peak Module for identifying strongest buyer/seller dominance at structural pivots
Real-time Signal Statistics Table showing bullish/bearish counts and volume metrics
Fully customizable inputs (SMA lengths, multipliers, timeframes)
Visual chart markers (S01 to S12) for clear on-chart identification
3. Usage Guide
Enable/Disable Scenarios: Choose which signals to display based on your trading strategy
Fine-tune Parameters: Adjust SMA lengths, multipliers, and lookback periods to fit your market and timeframe
Timeframe Control: Use custom lower timeframes for refined up/down volume calculations
Combine with Other Indicators:
Ichimoku: Confirm volume-based bullish signals with cloud breakouts or trend confirmation
Bollinger Bands: Validate divergence/convergence signals with overbought/oversold zones
Trendlines: Spot high-probability signals at breakout or retest points
Signal Tables & Peaks: Read buy/sell volume dominance at a glance, and activate the Dominance Peak Module to highlight key turning points.
4. Example Scenarios & Suggested Images
Image #1 – S01 Bullish Convergence Above Zero
S01 activated, Buyer Power > 0, both buyer power slope & price slope positive, above-average buy volume. Show S01 ↑ marker below bar.
Image #2 – Combined with Ichimoku
Display a bullish scenario where price breaks above Ichimoku cloud while S01 or S09 bullish signal is active. Highlight both the volume-based marker and Ichimoku cloud breakout.
Image #3 – Combined with Bollinger Bands & Trendlines
Show a bearish S10 signal at the upper Bollinger Band near a descending trendline resistance. Highlight the confluence of the volume pressure signal with the band touch and trendline rejection.
Image #4 – Dominance Peak Module
Pivot low with green ▲ Bull Peak and pivot high with red ▼ Bear Peak, showing strong dominance counts.
Image #5 – Statistics Table in Action
Bottom-left table showing buy/sell volume, averages, and bullish/bearish counts during an active market phase.
5. Feedback & Collaboration
Your feedback and suggestions are welcome — they help improve and refine this system. If you discover interesting use cases or have ideas for new features, please share them in the script’s comments section on TradingView.
6. Disclaimer
This script is for educational purposes only. It is not financial advice. Past performance does not guarantee future results. Always do your own analysis before making trading decisions.
Tip: Use this tool alongside trend confirmation indicators for the most robust signal interpretation.
TrendZoneTrendZone - Fibonacci Trendline Indicator
TrendZone is a custom Pine Script indicator that automatically draws fibonacci-based trendlines between key pivot points on your chart.
Key Features:
3 Pivot Points: Set start point, major pivot (reversal), and end point
Dual Trendlines: First trendline (Point 1 → 2) and second trendline (Point 2 → 3)
Fibonacci Levels: Automatically draws 25%, 50%, and 100% fibonacci levels for each trendline
Auto Trend Detection: Automatically identifies bullish/bearish trends and adjusts colors accordingly
Customizable: Full control over colors, line styles, and widths for each fibonacci level
How it Works:
The indicator uses your selected pivot points to create two connected trendline systems. Point 2 serves as the major pivot where the first trend ends and the reversal begins. Each trendline system includes fibonacci retracement levels that extend to the right, helping identify potential support/resistance zones.
Use Cases:
Identifying trend reversals at key pivot points
Finding potential support/resistance levels using fibonacci projections
Visualizing market structure changes between different time periods
Planning entries/exits based on fibonacci trendline interactions
Perfect for traders who use fibonacci analysis combined with trend structure to identify high-probability trading zones.
Auto FaustAuto Faust – Intraday Market Context & Structure
Auto Faust is a visual market overlay designed for intraday traders who want fast context without relying on signals or automation. It combines classic price tools — VWAP, EMAs, RSI, Chop Score, and market structure trendlines — into a single glanceable dashboard.
🔍 What It Does:
VWAP (Volume Weighted Average Price): Shows the day's fair value price anchor.
EMAs (3, 21, 113, 200): Map short-term to long-term trend alignment. Crossovers can be used for confluence or caution.
RSI (10): Monitors local momentum. Displayed in a compact table.
Chop Score: Measures how directional price action is. High chop = ranging conditions; low = trending.
Session High/Low Tracker: Tracks the daily extremes in real-time.
Volume Monitor: Shows current candle volume, color-coded vs previous bar (green = higher, red = lower).
Dynamic Support & Resistance Lines: Plotted from pivot highs/lows (not static levels).
Automatic Trendlines: Drawn from swing structure, updating live.
📊 How to Use:
Use EMAs + VWAP alignment to assess directional bias.
Confirm clean trends with low Chop Score and RSI support.
Watch for price interaction around dynamic S/R lines and trendline breaks.
Use volume coloring to assess if momentum is increasing or fading.
No buy/sell signals are generated — this is a trader-facing tool to guide discretionary decision-making.
Dow waveform analyzerDow Waveform Analyzer
1. Overview and Features of the Indicator
This indicator is a tool designed to analyze chart waveforms based on Dow Theory, identifying swing lows (support) and swing highs (resistance). It allows users to quickly and consistently determine trend direction. Compared to manual analysis, it provides more efficient and accurate results.
By using swing lows and swing highs, the indicator offers a more detailed understanding of trends than simple updates to highs and lows, aiding in the creation of effective trading strategies.
2. Identifying Wave Lows and Highs
Stock prices do not move in straight lines; instead, they rise and fall in waves. This indicator starts by identifying the wave lows and wave highs.
- Wave Low: The lowest point during a temporary price decline.
- Wave High: The highest point during a temporary price increase.
These are automatically identified using Pine Script’s built-in functions `pivotlow` and `pivothigh`.
3. Drawing the Waveform
The identified wave lows and highs are alternately connected to draw the waveform. However, there are cases where wave lows or highs occur consecutively:
- Consecutive Wave Lows: The lower low is used for drawing the waveform.
- Consecutive Wave Highs: The higher high is used for drawing the waveform.
4. Tracking Swing Lows/Highs and Trend Determination
Swing lows and swing highs are crucial markers that indicate the state of wave progression:
- Swing Low: The starting point of a wave (wave low) when the closing price exceeds the previous wave high.
- Swing High: The starting point of a wave (wave high) when the closing price falls below the previous wave low.
The changes in swing lows and swing highs as the waves progress allow for trend state determination.
5. Examples of Trend States
During an Uptrend:
- When the price surpasses a wave high, the swing low is updated, confirming the continuation of the uptrend.
End of an Uptrend:
- When the price falls below the swing low, the swing low disappears, and a swing high appears, signaling the end of the uptrend.
Sideways Movement:
- Swing lows and swing highs alternately appear, indicating a sideways trend.
Start of a Downtrend:
- When the price breaks below a wave low for the first time, the swing high is updated, confirming the start of the downtrend.
During a Downtrend:
- When the price breaks below a wave low, the swing high is updated, confirming the continuation of the downtrend.
End of a Downtrend:
- When the price surpasses a wave high, the swing high disappears, and a swing low reappears, signaling the end of the downtrend.
Restart of an Uptrend:
- When the swing low is updated, the uptrend resumes. The uptrend begins when the price surpasses a wave high, and the swing low is updated for the first time.
6. Applications
Trade Entries and Exits:
- Set stop orders for entry at the price level where a trend starts.
- Set stop orders for exit at the price level where a trend ends.
Trend Filtering:
- Use the indicator to confirm whether market conditions are suitable for entry based on the trend state. Analyze waveforms to aid trading strategies.
Guide for Drawing Trendlines:
- Utilize wave lows and highs as starting and ending points when drawing trendlines with drawing tools.
7. Parameters and Display Items
Pivot Points:
- Wave lows are marked with circles below the candlestick’s low, and wave highs are marked with circles above the candlestick’s high.
Number of Bars for Pivot Calculation:
- Specify the number of bars on either side used to identify highs (default: 2).
Waveform:
- Specify the color (default: blue) or toggle its visibility (default: visible).
Swing Lows/Highs:
- Displayed as large circles. The rightmost large circle on the chart indicates the current swing low or swing high. Historical swing points are also displayed to show the progression of state changes. Specify the color (default: green) or toggle visibility (default: visible).
1. インジケーターの概要と特徴
このインジケーターは、ダウ理論を基にチャートの波形を分析し、押し安値や戻り高値を特定するツールです。これにより、トレンドの方向を迅速かつ一貫して判断できます。手動での分析と比較して、効率的かつ精度の高い結果が得られる点が特徴です。
押し安値や戻り高値を利用することで、単純な高値・安値の更新よりも詳細にトレンドの状況を把握し、効果的な取引戦略の構築に役立ちます。
2. 波の谷と波の頂の特定
株価は直線的に動くのではなく、波を描きながら上昇や下落を繰り返します。このインジケーターは、まず波の谷と波の頂を特定するところから始まります。
波の谷: 一時的な下落の最安値
波の頂: 一時的な上昇の最高値
これらを Pine Script の内蔵関数(ピボットローとピボットハイ)を用いて自動的に特定しています。
3. 波形の描画方法
特定した波の谷と波の頂を交互に結んで波形を描画します。ただし、波の谷や頂が連続する場合があります。
波の谷が連続する場合: より低い谷を採用して波形を描く
波の頂が連続する場合: より高い頂を採用して波形を描く
4. 押し安値・戻り高値の追跡とトレンド判断
押し安値と戻り高値は、波の進行状況を示す重要な指標です。
押し安値: 終値が前回の高値を超えた際の波の谷
戻り高値: 終値が前回の安値を割り込んだ際の波の頂
波の進行に伴う押し安値・戻り高値の変化から、トレンドの状態を判断します。
5. トレンド状態の具体例
上昇トレンド中:
波の頂を株価が上抜け押し安値が更新され続けることで上昇トレンドを継続。
上昇トレンドの終了:
株価が押し安値を割ると、押し安値が消え、戻り高値が新たに出現して、上昇トレンドを終了。
横ばい状態:
押し安値と戻り高値が交互に切り替わる。
下降トレンドの開始:
波の谷を株価が下抜け戻り高値がはじめて更新されることで下降トレンド開始を確認。
下降トレンド中:
波の谷を株価が下抜け戻り高値が更新され続けることで下降トレンドを継続。
下降トレンドの終了:
株価が波の頂を超えると、戻り高値が消え、押し安値が再び出現して、下降トレンドを終了。
横ばい状態:
押し安値と戻り高値が交互に切り替わる。
上昇トレンドの再開:
押し安値が更新されることで上昇トレンドを確認。
波の頂を株価が上抜け押し安値がはじめて更新されることで上昇トレンド開始を確認。
6. 応用例
トレードのエントリーとエグジット:
トレンド発生の価格に逆指値を設定してエントリー。
トレンド終了の価格に逆指値を設定してエグジット。
トレンドフィルターとして活用:
エントリーに適したトレンド状況かを確認。波形を分析してトレード戦略の参考に。
トレンドラインを描く時の参考として活用:
波の谷と頂を描画ツールを使ってトレンドラインを描く時の起点や終点として活用。
7. パラメーターと表示項目
ピボット: 波の谷はローソク足の安値にサークルを表示、波の頂はローソク足の高値にサークルを表示。
ピボット計算用のバーの数: 高値を特定するために左右何本のローソク足を使用するかを設定(初期値: 2)。
波形: 色(初期値: 青)や表示(初期値: 表示)の指定。
押し安値・戻り高値: 大きなサークルで表示。チャートの一番右の大きなサークルが現在のもの。過去のものも状態変化の経緯を示すために表示。色(初期値: 緑)や表示(初期値: 表示)の指定。
RR SummaThis is my favourite Indicator
Support and resistance are fundamental concepts in technical analysis used by traders to predict potential price movements in financial markets such as stocks, forex, and cryptocurrencies.
### 1. **Support**
Support refers to a price level at which an asset tends to find buying interest, preventing the price from falling further. It acts as a "floor" where demand is strong enough to halt the downward movement and potentially reverse it. When the price approaches support, buyers may step in, believing the asset is undervalued.
- **Characteristics of Support:**
- **Previous lows:** Historical price points where the price has repeatedly bounced upward.
- **Increased buying pressure:** When prices approach the support level, traders tend to buy, believing it's a good entry point.
- **Psychological factor:** Traders view support levels as a point where the price is unlikely to fall below for a while.
- **Example:** A stock may be trading at $50, and whenever it drops near that price, buyers step in and push it back up. In this case, $50 is the support level.
### 2. **Resistance**
Resistance is the opposite of support. It is a price level at which an asset faces selling pressure, preventing the price from rising further. It acts as a "ceiling," where supply exceeds demand, often leading to a reversal or consolidation.
- **Characteristics of Resistance:**
- **Previous highs:** Historical price points where the price has struggled to break through or where it has reversed downward.
- **Increased selling pressure:** Sellers are more likely to take profits or short the asset near resistance levels.
- **Psychological factor:** Traders may perceive resistance levels as a point where the asset is overvalued or where the trend will reverse.
- **Example:** A stock may approach a price of $100, but every time it gets close, sellers appear and push the price back down. In this case, $100 is the resistance level.
### **Key Points about Support and Resistance**
- **Breakout and Breakdown:** If a price moves beyond a support or resistance level, it is considered a breakout (above resistance) or breakdown (below support). This may signal a new trend in the market.
- **Role Reversal:** Once a resistance level is broken, it can turn into a support level, and vice versa. Traders often look for such shifts in market behavior.
- **Trend Continuation or Reversal:** Support and resistance can indicate whether the market is in a trend or preparing for a reversal. A test of support or resistance can lead to a continuation if the level holds, or a reversal if the level is breached.
### **Identifying Support and Resistance**
- **Historical Price Action:** Look for points where the price has reversed or consolidated multiple times.
- **Trendlines:** Draw trendlines that connect swing highs (resistance) and swing lows (support) to identify these levels.
- **Moving Averages:** Key moving averages (e.g., 50-day, 200-day) can act as dynamic support and resistance levels.
### **Why Support and Resistance Matter**
- **Risk Management:** Traders use these levels to place stop-loss orders to manage risk.
- **Entry and Exit Points:** These levels can help traders decide when to enter or exit trades, aiming to buy near support and sell near resistance.
- **Market Sentiment:** Support and resistance levels reflect the collective psychology of market participants, indicating areas where sentiment may shift.
In summary, support and resistance are essential tools for traders to identify potential price points where assets may reverse or consolidate. Understanding these levels allows traders to make more informed decisions about when to buy, sell, or stay on the sidelines.
Support & Resistance AI (K means/median) [ThinkLogicAI]█ OVERVIEW
K-means is a clustering algorithm commonly used in machine learning to group data points into distinct clusters based on their similarities. While K-means is not typically used directly for identifying support and resistance levels in financial markets, it can serve as a tool in a broader analysis approach.
Support and resistance levels are price levels in financial markets where the price tends to react or reverse. Support is a level where the price tends to stop falling and might start to rise, while resistance is a level where the price tends to stop rising and might start to fall. Traders and analysts often look for these levels as they can provide insights into potential price movements and trading opportunities.
█ BACKGROUND
The K-means algorithm has been around since the late 1950s, making it more than six decades old. The algorithm was introduced by Stuart Lloyd in his 1957 research paper "Least squares quantization in PCM" for telecommunications applications. However, it wasn't widely known or recognized until James MacQueen's 1967 paper "Some Methods for Classification and Analysis of Multivariate Observations," where he formalized the algorithm and referred to it as the "K-means" clustering method.
So, while K-means has been around for a considerable amount of time, it continues to be a widely used and influential algorithm in the fields of machine learning, data analysis, and pattern recognition due to its simplicity and effectiveness in clustering tasks.
█ COMPARE AND CONTRAST SUPPORT AND RESISTANCE METHODS
1) K-means Approach:
Cluster Formation: After applying the K-means algorithm to historical price change data and visualizing the resulting clusters, traders can identify distinct regions on the price chart where clusters are formed. Each cluster represents a group of similar price change patterns.
Cluster Analysis: Analyze the clusters to identify areas where clusters tend to form. These areas might correspond to regions of price behavior that repeat over time and could be indicative of support and resistance levels.
Potential Support and Resistance Levels: Based on the identified areas of cluster formation, traders can consider these regions as potential support and resistance levels. A cluster forming at a specific price level could suggest that this level has been historically significant, causing similar price behavior in the past.
Cluster Standard Deviation: In addition to looking at the means (centroids) of the clusters, traders can also calculate the standard deviation of price changes within each cluster. Standard deviation is a measure of the dispersion or volatility of data points around the mean. A higher standard deviation indicates greater price volatility within a cluster.
Low Standard Deviation: If a cluster has a low standard deviation, it suggests that prices within that cluster are relatively stable and less likely to exhibit sudden and large price movements. Traders might consider placing tighter stop-loss orders for trades within these clusters.
High Standard Deviation: Conversely, if a cluster has a high standard deviation, it indicates greater price volatility within that cluster. Traders might opt for wider stop-loss orders to allow for potential price fluctuations without getting stopped out prematurely.
Cluster Density: Each data point is assigned to a cluster so a cluster that is more dense will act more like gravity and
2) Traditional Approach:
Trendlines: Draw trendlines connecting significant highs or lows on a price chart to identify potential support and resistance levels.
Chart Patterns: Identify chart patterns like double tops, double bottoms, head and shoulders, and triangles that often indicate potential reversal points.
Moving Averages: Use moving averages to identify levels where the price might find support or resistance based on the average price over a specific period.
Psychological Levels: Identify round numbers or levels that traders often pay attention to, which can act as support and resistance.
Previous Highs and Lows: Identify significant previous price highs and lows that might act as support or resistance.
The key difference lies in the approach and the foundation of these methods. Traditional methods are based on well-established principles of technical analysis and market psychology, while the K-means approach involves clustering price behavior without necessarily incorporating market sentiment or specific price patterns.
It's important to note that while the K-means approach might provide an interesting way to analyze price data, it should be used cautiously and in conjunction with other traditional methods. Financial markets are influenced by a wide range of factors beyond just price behavior, and the effectiveness of any method for identifying support and resistance levels should be thoroughly tested and validated. Additionally, developments in trading strategies and analysis techniques could have occurred since my last update.
█ K MEANS ALGORITHM
The algorithm for K means is as follows:
Initialize cluster centers
assign data to clusters based on minimum distance
calculate cluster center by taking the average or median of the clusters
repeat steps 1-3 until cluster centers stop moving
█ LIMITATIONS OF K MEANS
There are 3 main limitations of this algorithm:
Sensitive to Initializations: K-means is sensitive to the initial placement of centroids. Different initializations can lead to different cluster assignments and final results.
Assumption of Equal Sizes and Variances: K-means assumes that clusters have roughly equal sizes and spherical shapes. This may not hold true for all types of data. It can struggle with identifying clusters with uneven densities, sizes, or shapes.
Impact of Outliers: K-means is sensitive to outliers, as a single outlier can significantly affect the position of cluster centroids. Outliers can lead to the creation of spurious clusters or distortion of the true cluster structure.
█ LIMITATIONS IN APPLICATION OF K MEANS IN TRADING
Trading data often exhibits characteristics that can pose challenges when applying indicators and analysis techniques. Here's how the limitations of outliers, varying scales, and unequal variance can impact the use of indicators in trading:
Outliers are data points that significantly deviate from the rest of the dataset. In trading, outliers can represent extreme price movements caused by rare events, news, or market anomalies. Outliers can have a significant impact on trading indicators and analyses:
Indicator Distortion: Outliers can skew the calculations of indicators, leading to misleading signals. For instance, a single extreme price spike could cause indicators like moving averages or RSI (Relative Strength Index) to give false signals.
Risk Management: Outliers can lead to overly aggressive trading decisions if not properly accounted for. Ignoring outliers might result in unexpected losses or missed opportunities to adjust trading strategies.
Different Scales: Trading data often includes multiple indicators with varying units and scales. For example, prices are typically in dollars, volume in units traded, and oscillators have their own scale. Mixing indicators with different scales can complicate analysis:
Normalization: Indicators on different scales need to be normalized or standardized to ensure they contribute equally to the analysis. Failure to do so can lead to one indicator dominating the analysis due to its larger magnitude.
Comparability: Without normalization, it's challenging to directly compare the significance of indicators. Some indicators might have a larger numerical range and could overshadow others.
Unequal Variance: Unequal variance in trading data refers to the fact that some indicators might exhibit higher volatility than others. This can impact the interpretation of signals and the performance of trading strategies:
Volatility Adjustment: When combining indicators with varying volatility, it's essential to adjust for their relative volatilities. Failure to do so might lead to overemphasizing or underestimating the importance of certain indicators in the trading strategy.
Risk Assessment: Unequal variance can impact risk assessment. Indicators with higher volatility might lead to riskier trading decisions if not properly taken into account.
█ APPLICATION OF THIS INDICATOR
This indicator can be used in 2 ways:
1) Make a directional trade:
If a trader thinks price will go higher or lower and price is within a cluster zone, The trader can take a position and place a stop on the 1 sd band around the cluster. As one can see below, the trader can go long the green arrow and place a stop on the one standard deviation mark for that cluster below it at the red arrow. using this we can calculate a risk to reward ratio.
Calculating risk to reward: targeting a risk reward ratio of 2:1, the trader could clearly make that given that the next resistance area above that in the orange cluster exceeds this risk reward ratio.
2) Take a reversal Trade:
We can use cluster centers (support and resistance levels) to go in the opposite direction that price is currently moving in hopes of price forming a pivot and reversing off this level.
Similar to the directional trade, we can use the standard deviation of the cluster to place a stop just in case we are wrong.
In this example below we can see that shorting on the red arrow and placing a stop at the one standard deviation above this cluster would give us a profitable trade with minimal risk.
Using the cluster density table in the upper right informs the trader just how dense the cluster is. Higher density clusters will give a higher likelihood of a pivot forming at these levels and price being rejected and switching direction with a larger move.
█ FEATURES & SETTINGS
General Settings:
Number of clusters: The user can select from 3 to five clusters. A good rule of thumb is that if you are trading intraday, less is more (Think 3 rather than 5). For daily 4 to 5 clusters is good.
Cluster Method: To get around the outlier limitation of k means clustering, The median was added. This gives the user the ability to choose either k means or k median clustering. K means is the preferred method if the user things there are no large outliers, and if there appears to be large outliers or it is assumed there are then K medians is preferred.
Bars back To train on: This will be the amount of bars to include in the clustering. This number is important so that the user includes bars that are recent but not so far back that they are out of the scope of where price can be. For example the last 2 years we have been in a range on the sp500 so 505 days in this setting would be more relevant than say looking back 5 years ago because price would have to move far to get there.
Show SD Bands: Select this to show the 1 standard deviation bands around the support and resistance level or unselect this to just show the support and resistance level by itself.
Features:
Besides the support and resistance levels and standard deviation bands, this indicator gives a table in the upper right hand corner to show the density of each cluster (support and resistance level) and is color coded to the cluster line on the chart. Higher density clusters mean price has been there previously more than lower density clusters and could mean a higher likelihood of a reversal when price reaches these areas.
█ WORKS CITED
Victor Sim, "Using K-means Clustering to Create Support and Resistance", 2020, towardsdatascience.com
Chris Piech, "K means", stanford.edu
█ ACKNOLWEDGMENTS
@jdehorty- Thanks for the publish template. It made organizing my thoughts and work alot easier.
Cyatophilum Strategy BuilderAn indicator to create strategies, backtest and setup alerts.
The user can choose one or multiple TA entry conditions, if more than one the conditions are combined with a logical AND.
The entries will open up a trade, which is then handled by a risk management system including Trailing Stop, Take Profit and up to 100 Safety Orders.
This indicator can be used to backtest 3commas DCA bots who are using TA presets, RSI or ULT.
Its main goal is to create strategies by combining indicators.
Let's dive into the details of what's included:
Entry Condition: MACD
Triggers an entry when macd crosses with the signal line.
Configure the fast, slow length, signal smoothing and timeframe to trigger the condition.
Entry Condition: RSI
Triggers an entry when the RSI is higher or lower than the long/short threshold.
Configure the length, timeframe, long and short threshold to trigger the condition.
Entry Condition: ULT (Ultimate Oscillator)
Triggers an entry when the ULT is higher or lower than the long/short threshold.
Configure the 3 lengths, timeframe, long and short threshold to trigger the condition.
Entry Condition: Bollinger Bands
Triggers an entry when the price is above the upper band for long and below the lower band for short.
Configure the length, standard deviation and timeframe to trigger the condition.
Entry Condition: MFI (Money Flow Index)
Similar to RSI, it triggers an entry when the MFI is higher or lower than the long/short threshold.
Configure the length, timeframe, long and short threshold to trigger the condition.
Entry Condition: CCI (Commodity Channel Index)
Another oscillator that triggers an entry when its value is higher or lower than the long/short threshold.
Configure the length, timeframe, long and short threshold to trigger the condition.
Trend Filters
Use one or two trendlines to filter your trades: go only long/short when the trendline is bullish/bearish.
Choose between the several trendlines: ema, sma, wma, hull ma, kama, alma, rma, swma, vwma, Tilson T3, and the unique Adaptive T3 and Adaptive Hull MA.
If this is not enough, you can use the external trendline feature to plug in any other indicator for your trendline.
The second trendline can be MTF and come from another symbol if needed.
Combining Indicators
Most of the time we will not be using a single indicator at a time, but instead, combine them in order to get stronger entries.
The entry conditions are combined using a AND logical gate, meaning all conditions must be true for the entry to trigger.
Here is an example using a combination of 2 indicators: Bollinger Bands and RSI.
We can see less entries are being triggered on the bottom chart than on the top chart because the bottom chart is combining the 2 indicators while the top chart is only using Bollinger Bands.
You can combine up to all 6 indicators if you want, but keep in mind that combining too many may lead to triggering no entry at all.
Risk Management and Trade system
The indicator will not trigger more than one long or short entry in a row.
To start a new trade, the indicator will wait for either take profit, stop loss or an opposite entry if no SL and TP is set.
Stop Loss and Take Profit
Configure your stop loss and take profit for long and short trades.
You can also make a trailing stoploss and a trailing take profit.
Safety Orders
Just like 3commas bots, you can create a strategy with up to 100 safety orders.
Configure their placement and order size using the price deviation, step scale, take profit type (from base order or total volume), and volume scale settings.
Note: only the 20 first safety order steps or so will be plotted due to graphic limiations. The steps after that still trigger alerts and backtest results.
Creating Alerts
The indicator is using the newest alert system:
1. Write your alert messages in the indicator settings (alert section at the bottom)
2. Click "Create Alert" as usual, but choose "alert() function calls only"
Data Window
Since the indicator is applied on top of the price chart, the oscillator indicators cannot be plotted. You can always add them on another pane but if you want to just see their values, you can use the Data Window to see the value of each oscillator on each bar.
Backtest settings
Used to get the results below:
Initial Capital: 100 000$
Base Order Size: 0.1 contract (BTC)
Safety Order Size: 0.1 contract (BTC)
Commission: 0.1%
Slippage: 100 ticks
pyramiding: 6
The indicator settings are plotted in the main chart panel.
Adaptive Trend Breaks Adaptive Trend Breaks
## WHAT IT DOES
This script is a modified and enhanced version of "Trendline Breakouts With Targets" concept by ChartPrime.
Adaptive Trend Breaks (ATB) is a trendline breakout system optimized for scalping liquid futures contracts. The indicator automatically draws dynamic support and resistance trendlines based on pivot points, then generates trade signals when price breaks through these levels with confirmation filters. It includes automated target and stop-loss placement with real-time P&L tracking in dollars.
## HOW IT WORKS
**Trendline Detection Method:**
The indicator uses pivot high/low detection to identify significant price turning points. When a new pivot forms, it calculates the slope between consecutive pivots to draw dynamic trendlines. These lines extend forward based on the established trend angle, creating actionable support and resistance zones.
**Band System:**
Around each trendline, the script creates a "band" using a volatility-adjusted calculation: `ATR(14) * 0.2 * bandwidth multiplier / 2`. This adaptive band accounts for current market conditions - wider during volatile periods, tighter during quiet markets.
**Breakout Logic:**
A breakout signal triggers when:
1. Price closes beyond the trendline + band zone
2. Volume exceeds the 20-period moving average by your set multiplier (default 1.2x)
3. Price is within Regular Trading Hours (9:30-16:00 EST) if session filter enabled
4. Current ATR meets minimum volatility threshold (prevents trading dead markets)
**Target & Stop Calculation:**
Upon breakout confirmation:
- **Entry**: Trendline breach point
- **Target**: Entry ± (bandwidth × target multiplier) - default 8x for quick scalps
- **Stop**: Entry ± (bandwidth × stop multiplier) - default 8x for 1:1 risk/reward
- Multipliers adjust automatically to market volatility through the ATR-based band
**P&L Conversion:**
The script converts point movements to dollars using:
```
Dollar P&L = (Price Points × Contract Point Value × Quantity)
```
For example, a 10-point NQ move with 2 contracts = 10 × $20 × 2 = $400
## HOW TO USE IT
**Setup:**
1. Select your instrument (NQ/ES/YM/RTY) - point values auto-configure
2. Set contract quantity for accurate dollar P&L
3. Choose pivot period (lower = more signals but more noise, default 5 for scalping)
4. Adjust bandwidth multiplier if trendlines are too tight/loose (1-5 range)
**Filters Configuration:**
- **Volume Filter**: Requires breakout volume > moving average × multiplier. Increase multiplier (1.5-2.0) for higher conviction trades
- **Session Filter**: Enable to trade only RTH. Disable for 24-hour trading
- **ATR Filter**: Prevents signals during low volatility. Increase minimum % for more active markets only
**Risk Management:**
- Set target/stop multipliers based on your risk tolerance
- 8x bandwidth = approximately 1:1 risk/reward for most liquid futures
- Enable trailing stops for trend-following approach (moves stop to protect profits)
- Adjust line length to see targets further into the future
**Statistics Table:**
- Choose timeframe to analyze: all-time, today, this week, custom days
- Monitor win rate, profit factor, and net P&L in dollars
- Track long vs short performance separately
- See real-time unrealized P&L on active trades
**Reading Signals:**
- **Green triangle below bar** = Long breakout (resistance broken)
- **Red triangle above bar** = Short breakout (support broken)
- **White dashed line** = Entry price
- **Orange line** = Take profit target with dollar value
- **Red line** = Stop loss with dollar value
- **Green checkmark (✓)** = Target hit, winning trade
- **Red X (✗)** = Stop hit, losing trade
## WHAT IT DOES NOT DO
**Limitations to Understand:**
- Does not predict future trendline formations - it reacts to breakouts after they occur
- Historical trendlines disappear after breakout (not kept on chart for clarity)
- Requires sufficient volatility - may not signal in extremely quiet markets
- Volume filter requires exchange volume data (not available on all symbols)
- Statistics are indicator-based simulations, not actual trading results
- Does not account for slippage, commissions, or order fills
## BEST PRACTICES
**Recommended Settings by Market:**
- **NQ (Nasdaq)**: Default settings work well, consider volume multiplier 1.3-1.5
- **ES (S&P 500)**: Slightly slower, try period 7-8, volume 1.2
- **YM (Dow)**: Lower volatility, reduce bandwidth to 1.5-2
- **RTY (Russell)**: Higher volatility, increase bandwidth to 3-4
**Risk Management:**
- Never risk more than 2-3% of account per trade
- Use contract quantity calculator: Max Risk $ ÷ (Stop Distance × Point Value)
- Start with 1 contract while learning the system
- Backtest your specific timeframe and instrument before live trading
**Optimization Tips:**
- Increase pivot period (7-10) for fewer but higher-quality signals
- Raise volume multiplier (1.5-2.0) in choppy markets
- Lower target/stop multipliers (5-6x) for tighter profit taking
- Use trailing stops in strong trending conditions
- Disable session filter for overnight gaps and Asia session moves
## TECHNICAL DETAILS
**Key Calculations:**
- Pivot Detection: `ta.pivothigh(high, period, period/2)` and `ta.pivotlow(low, period, period/2)`
- Slope Calculation: `(newPivot - oldPivot) / (newTime - oldTime)`
- Adaptive Band: `min(ATR(14) * 0.2, close * 0.002) * multiplier / 2`
- Breakout Confirmation: Price crosses trendline + 10% of band threshold
**Data Requirements:**
- Minimum bars in view: 500 for proper pivot calculation
- Volume data required for volume filter accuracy
- Intraday timeframes recommended (1min - 15min) for scalping
- Works on any timeframe but optimized for fast execution
**Performance Metrics:**
All statistics calculate based on indicator signals:
- Tracks every signal as a trade from entry to TP/SL
- P&L in actual contract dollar values
- Win rate = (Winning trades / Total trades) × 100
- Profit factor = Gross profit / Gross loss
- Separates long/short performance for bias analysis
## IDEAL FOR
- Futures scalpers and day traders
- Traders who prefer visual trendline breakouts
- Those wanting automated TP/SL placement
- Traders tracking performance in dollar terms
- Multiple timeframe analysis (compare 1min vs 5min signals)
## NOT SUITABLE FOR
- Swing trading (targets too close)
- Stocks/forex without modifying point values
- Extremely low timeframes (<30 seconds) - too much noise
- Markets without volume data if using volume filter
- Illiquid contracts (signals may not execute at shown prices)
---
**Settings Summary:**
- Core: Period, bandwidth, extension, trendline style
- Filters: Volume, RTH session, ATR volatility
- Risk: R:R ratio, target/stop multipliers, trailing stop
- Display: Stats table position, size, colors
- Stats: Timeframe selection (all-time to custom days)
**License:** This indicator is published open-source under Mozilla Public License 2.0. You may use and modify the code with proper attribution.
**Disclaimer:** This indicator is for educational purposes. Past performance does not guarantee future results. Always practice proper risk management and test thoroughly before live trading.
---
## CREDITS & ATTRIBUTION
This script builds upon the "Trendline Breakouts With Targets" concept by ChartPrime with significant enhancements:
**Major Improvements Added:**
- **Futures-Specific Calculations**: Automated dollar P&L conversion using actual contract point values (NQ=$20, ES=$50, YM=$5, RTY=$50)
- **Advanced Statistics Engine**: Comprehensive performance tracking with customizable timeframe analysis (today, week, month, custom ranges)
- **Multi-Layer Filtering System**: Volume confirmation, RTH session filter, and ATR volatility filter to reduce false signals
- **Professional Trade Management**: Enhanced visual trade tracking with separate TP/SL lines, dollar value labels, and optional trailing stops
- **Optimized for Scalping**: Faster pivot periods (5 vs 10), tighter bands, and reduced extension bars for quick entries
Original trendline detection methodology by ChartPrime - used with modification under Mozilla Public License 2.0.
Auto Trend Lines v1.0 This advanced Pine Script indicator automatically detects and draws support and resistance trendlines for any instrument based on two independent lookback periods—short-term and long-term—making it suitable for all types of traders. The indicator identifies pivot highs and lows for both user-configurable lookback lengths, draws trendlines from each anchor point to the current bar, and supports a visually intuitive chart by coloring and labeling each line type separately.
Key features:
Dual lookback: Choose separate short-term and long-term sensitivity for pivots and trendlines.
Customizable: Select the number of displayed lines, colors, and line widths to suit your preferences.
Auto-updating: Trendlines update dynamically with new pivots and extend to the latest bar.
This indicator is ideal for those who want to automate trendline analysis, spot key breakout and reversal areas, and streamline technical trading.
Price-Volume w Trendline - Strategy [presentTrading]█ Introduction and How it is Different
The Price-Volume with Trendline Strategy is an innovative strategy that combines volume profile analysis, price-based Z-scores, and dynamic trendline filtering to identify optimal entry and exit points in the market. What sets this strategy apart is the integration of volume concentration (Point of Control or PoC) with dynamic volatility thresholds. Additionally, this strategy introduces a multi-step take profit (TP) mechanism that adjusts based on predefined levels, allowing traders to exit trades progressively while capitalizing on market momentum.
BTCUSD 6hr LS Performance
█ Strategy, How it Works: Detailed Explanation
The combination of multiple indicators and methodologies serves to create a more robust and reliable trading system. Each element is carefully chosen for its complementary role in providing accurate signals while minimizing false entries and exits. Here’s why the different components were chosen and how they work together:
- PoC and Z-Scores: The volume profile identifies key price areas, while the Z-score measures deviations from the mean. Together, they highlight points where the market is likely to react. For example, when the Z-score indicates an oversold condition near a PoC support level, it increases the probability of a reversal, providing a clear entry signal.
- Trendlines and Z-Scores: Trendlines serve as a secondary filter to ensure that price deviations identified by Z-scores align with broader market trends. This ensures that trades are only entered when the price has both deviated from its average and broken through a significant trendline level, reducing the likelihood of false signals.
- Multi-Step TP and Risk Management: Finally, the multi-step take profit logic works in tandem with the entry signals generated by the PoC, Z-scores, and trendlines. As the price moves in favor of the trade, profits are gradually locked in, ensuring the trader captures gains while still leaving room for further upside.
🔶 Point of Control (PoC) and Volume Profile Analysis
The PoC identifies the price level with the highest volume concentration within a specified lookback period. This price level represents where the most trading activity has occurred, often acting as a strong support or resistance. By breaking down the range into several rows (bins), the strategy identifies how much volume was traded at each price level.
🔶 Z-Score Calculation
The Z-score is a statistical metric that measures how far the current price is from its mean, expressed in terms of standard deviations. This is calculated both for price deviation and PoC-based deviation.
🔶 Trendline Breakout Filtering
The trendline filtering is a crucial aspect that refines entry signals by confirming trend continuation or reversals. It calculates trendlines based on pivot highs and lows using the selected method (e.g., ATR or standard deviation).
🔶 Multi-Step Take Profit
The multi-step take profit mechanism allows the strategy to take partial profits at several predefined levels. For example, when the price reaches 3%, 8%, 14%, or 21% above (or below) the entry price, it exits portions of the position. This is a useful technique for locking in profits as the market moves favorably.
Local
█ Usage
The Price-Volume with Trendline Strategy can be applied to various asset classes, including stocks, cryptocurrencies, and commodities. It is particularly effective in volatile markets where price deviations and volume concentrations signal potential reversals or trend continuations. By adjusting the settings for volatility and the lookback period, this strategy can be tailored to both short-term intraday trades and longer-term swing trades.
█ Default Settings
The default settings in the strategy play a vital role in shaping its performance.
- POC_lookbackLength (144): This defines the number of bars used to calculate the PoC. A longer lookback captures more data, leading to a more stable PoC, but may result in delayed signals. A shorter lookback increases responsiveness but may introduce noise.
- priceDeviationLength (200): This determines the period for calculating the standard deviation of price. A higher length smooths out the volatility, reducing the likelihood of false signals. Shorter lengths make the strategy more sensitive to sudden price movements.
- TL_length (14): Controls the swing detection period for trendline calculation. A shorter length will generate more frequent trendline breakouts, while a longer length captures only significant moves.
- Stop Loss and Take Profit: The strategy offers both fixed and SuperTrend-based stop losses. SuperTrend is adaptive to volatility, while fixed stop losses provide simpler risk control. The multi-step take profit ensures that profits are secured progressively, which can improve performance in trending markets by reducing the risk of full reversals.
Each of these settings can significantly affect the strategy’s risk-reward balance. For instance, increasing the stop loss level or the take profit percentages allows the strategy to stay in trades longer, potentially increasing profit per trade but at the cost of larger drawdowns. Conversely, tighter stops and smaller profit targets result in more frequent trades with lower average profit per trade.
GKD-C Adaptive-Lookback Phase Change Index [Loxx]Giga Kaleidoscope GKD-C Adaptive-Lookback Phase Change Index is a Confirmation module included in Loxx's "Giga Kaleidoscope Modularized Trading System".
█ GKD-C Adaptive-Lookback Phase Change Index
What is the Phase Change Index?
The Phase Change Index (PCI) is a technical indicator that has gained popularity among traders in recent years. It is used to identify market phases and make profitable trades based on momentum and price data. The PCI was developed by M.H. Pee and first introduced in the Stocks & Commodities magazine in 2004.
The PCI is calculated using the 35-day momentum and the 35-day price channel index (PCI). The momentum is the difference between the current day's close and the close 35 days ago, while the PCI measures the distance between the highest high and lowest low over a period of 35 days. By combining these two indicators, traders can identify six possible market phases, each with its own trading strategy.
The formula for calculating the Phase Change Index (PCI) is as follows:
PCI = 100 * (C - L) / (H - L)
Where:
- C is the closing price of the current day
- L is the lowest low over a period of 35 days
- H is the highest high over a period of 35 days
The formula for calculating momentum is as follows:
Momentum = C - Cn
Where:
- C is the closing price of the current day
- Cn is the closing price n days ago, where n = 35 in this case.
The first two phases are characterized by negative momentum, with phase one having a low PCI value (less than 20) and phase two having a high PCI value (greater than 80). In these phases, traders should enter short positions. The next two phases have positive momentum, with phase three having a low PCI value and phase four having a high PCI value. In these phases, traders should enter long positions.
The final two phases are characterized by neutral momentum, with phase five having a low PCI value and phase six having a high PCI value. In these phases, traders should maintain their previous positions until there is a clear signal to enter or exit.
Traders can also use other technical indicators in conjunction with the PCI to confirm signals or filter out false signals. For example, some traders use moving averages or trendlines to confirm trend direction before entering a trade based on the PCI.
In conclusion, the Phase Change Index is a powerful technical indicator that can help traders identify market phases and make profitable trades. By combining momentum and price data, traders can enter long or short positions based on the six possible market phases. Backtesting results have shown that the PCI is robust across parameters, markets, and years. However, it is important to use proper risk management and not rely solely on past profitability when making trading decisions.
What is the Jurik Filter?
The Jurik Filter is a technical analysis tool that is used to filter out market noise and identify trends in financial markets. It was developed by Mark Jurik in the 1990s and is based on a non-linear smoothing algorithm that provides a more accurate representation of price movements.
Traditional moving averages, such as the Simple Moving Average ( SMA ) or Exponential Moving Average ( EMA ), are linear filters that produce a lag between price and the moving average line. This can cause false signals during periods of market volatility , which can result in losses for traders and investors.
The Jurik Filter is designed to address this issue by incorporating a damping factor into the smoothing algorithm. This damping factor adjusts the filter's responsiveness to the changes in price, allowing it to filter out market noise without overshooting price peaks and valleys.
The Jurik Filter is calculated using a mathematical formula that takes into account the current and past prices of an asset, as well as the volatility of the market. This formula incorporates the damping factor and produces a smoother price curve than traditional moving average filters.
One of the advantages of the Jurik Filter is its ability to adjust to changing market conditions. The damping factor can be adjusted to suit different securities and time frames, making it a versatile tool for traders and investors.
Traders and investors often use the Jurik Filter in conjunction with other technical analysis tools, such as the MACD or RSI , to confirm or complement their trading strategies. By filtering out market noise and identifying trends in the financial markets, the Jurik Filter can help improve the accuracy of trading signals and reduce the risks of false signals during periods of market volatility .
Overall, the Jurik Filter is a powerful technical analysis tool that can help traders and investors make more informed decisions about buying and selling securities. By providing a smoother price curve and reducing false signals, it can help improve trading performance and reduce risk in volatile markets.
What is the Adaptive Lookback Period?
The adaptive lookback period is a technique used in technical analysis to adjust the period of an indicator based on changes in market conditions. This technique is particularly useful in volatile or rapidly changing markets where a fixed period may not be optimal for detecting trends or signals.
The concept of the adaptive lookback period is relatively simple. By adjusting the lookback period based on changes in market conditions, traders can more accurately identify trends and signals. This can help traders to enter and exit trades at the right time and improve the profitability of their trading strategies.
The adaptive lookback period works by identifying potential swing points in the market. Once these points are identified, the lookback period is calculated based on the number of swings and a speed parameter. The swing count parameter determines the number of swings that must occur before the lookback period is adjusted. The speed parameter controls the rate at which the lookback period is adjusted, with higher values indicating a more rapid adjustment.
The adaptive lookback period can be applied to a wide range of technical indicators, including moving averages, oscillators, and trendlines. By adjusting the period of these indicators based on changes in market conditions, traders can reduce the impact of noise and false signals, leading to more profitable trades.
In summary, the adaptive lookback period is a powerful technique for traders and analysts looking to optimize their technical indicators. By adjusting the period based on changes in market conditions, traders can more accurately identify trends and signals, leading to more profitable trades. While there are various ways to implement the adaptive lookback period, the basic concept remains the same, and traders can adapt and customize the technique to suit their individual needs and trading styles.
What is the Adaptive-Lookback Phase Change Index?
The combination of adaptive lookback and Jurik filtering is an effective technique used in technical analysis to filter out market noise and improve the accuracy of trading signals. When applied to the Phase Change Index (PCI) indicator, the adaptive lookback period can be used to adjust the period of the indicator based on changes in market conditions. Jurik filtering can then be used to filter out market noise and improve the accuracy of the signals produced by the PCI indicator.
The adaptive lookback period is particularly useful in volatile or rapidly changing markets where a fixed period may not be optimal for detecting trends or signals. By adjusting the lookback period based on changes in market conditions, traders can more accurately identify trends and signals, leading to more profitable trades.
Jurik filtering is a more advanced filtering technique that uses a combination of smoothing and phase shift to produce a more accurate signal. This technique is particularly useful in filtering out market noise and improving the accuracy of trading signals. Jurik filtering can be applied to various indicators, including moving averages, oscillators, and trendlines.
Overall, the combination of adaptive lookback and Jurik filtering is a powerful technique used in technical analysis to filter out market noise and improve the accuracy of trading signals. When applied to the Phase Change Index (PCI) indicator, this technique is particularly effective in identifying trend changes and producing more accurate signals for entry and exit points in trading strategies.
Keep in mind, this is an inverse indicator meaning that above the middle-line/signal is short, below is long.
Additional Features
This indicator allows you to select from 33 source types. They are as follows:
Close
Open
High
Low
Median
Typical
Weighted
Average
Average Median Body
Trend Biased
Trend Biased (Extreme)
HA Close
HA Open
HA High
HA Low
HA Median
HA Typical
HA Weighted
HA Average
HA Average Median Body
HA Trend Biased
HA Trend Biased (Extreme)
HAB Close
HAB Open
HAB High
HAB Low
HAB Median
HAB Typical
HAB Weighted
HAB Average
HAB Average Median Body
HAB Trend Biased
HAB Trend Biased (Extreme)
What are Heiken Ashi "better" candles?
Heiken Ashi "better" candles are a modified version of the standard Heiken Ashi candles, which are a popular charting technique used in technical analysis. Heiken Ashi candles help traders identify trends and potential reversal points by smoothing out price data and reducing market noise. The "better formula" was proposed by Sebastian Schmidt in an article published by BNP Paribas in Warrants & Zertifikate, a German magazine, in August 2004. The aim of this formula is to further improve the smoothing of the Heiken Ashi chart and enhance its effectiveness in identifying trends and reversals.
Standard Heiken Ashi candles are calculated using the following formulas:
Heiken Ashi Close = (Open + High + Low + Close) / 4
Heiken Ashi Open = (Previous Heiken Ashi Open + Previous Heiken Ashi Close) / 2
Heiken Ashi High = Max (High, Heiken Ashi Open, Heiken Ashi Close)
Heiken Ashi Low = Min (Low, Heiken Ashi Open, Heiken Ashi Close)
The "better formula" modifies the standard Heiken Ashi calculation by incorporating additional smoothing, which can help reduce noise and make it easier to identify trends and reversals. The modified formulas for Heiken Ashi "better" candles are as follows:
Better Heiken Ashi Close = (Open + High + Low + Close) / 4
Better Heiken Ashi Open = (Previous Better Heiken Ashi Open + Previous Better Heiken Ashi Close) / 2
Better Heiken Ashi High = Max (High, Better Heiken Ashi Open, Better Heiken Ashi Close)
Better Heiken Ashi Low = Min (Low, Better Heiken Ashi Open, Better Heiken Ashi Close)
Smoothing Factor = 2 / (N + 1), where N is the chosen period for smoothing
Smoothed Better Heiken Ashi Open = (Better Heiken Ashi Open * Smoothing Factor) + (Previous Smoothed Better Heiken Ashi Open * (1 - Smoothing Factor))
Smoothed Better Heiken Ashi Close = (Better Heiken Ashi Close * Smoothing Factor) + (Previous Smoothed Better Heiken Ashi Close * (1 - Smoothing Factor))
The smoothed Better Heiken Ashi Open and Close values are then used to calculate the smoothed Better Heiken Ashi High and Low values, resulting in "better" candles that provide a clearer representation of the market trend and potential reversal points.
It's important to note that, like any other technical analysis tool, Heiken Ashi "better" candles are not foolproof and should be used in conjunction with other indicators and analysis techniques to make well-informed trading decisions.
Heiken Ashi "better" candles, as mentioned previously, provide a clearer representation of market trends and potential reversal points by reducing noise and smoothing out price data. When using these candles in conjunction with other technical analysis tools and indicators, traders can gain valuable insights into market behavior and make more informed decisions.
To effectively use Heiken Ashi "better" candles in your trading strategy, consider the following tips:
Trend Identification: Heiken Ashi "better" candles can help you identify the prevailing trend in the market. When the majority of the candles are green (or another color, depending on your chart settings) and there are no or few lower wicks, it may indicate a strong uptrend. Conversely, when the majority of the candles are red (or another color) and there are no or few upper wicks, it may signal a strong downtrend.
Trend Reversals: Look for potential trend reversals when a change in the color of the candles occurs, especially when accompanied by longer wicks. For example, if a green candle with a long lower wick is followed by a red candle, it could indicate a bearish reversal. Similarly, a red candle with a long upper wick followed by a green candle may suggest a bullish reversal.
Support and Resistance: You can use Heiken Ashi "better" candles to identify potential support and resistance levels. When the candles are consistently moving in one direction and then suddenly change color with longer wicks, it could indicate the presence of a support or resistance level.
Stop-Loss and Take-Profit: Using Heiken Ashi "better" candles can help you manage risk by determining optimal stop-loss and take-profit levels. For instance, you can place your stop-loss below the low of the most recent green candle in an uptrend or above the high of the most recent red candle in a downtrend.
Confirming Signals: Heiken Ashi "better" candles should be used in conjunction with other technical indicators, such as moving averages, oscillators, or chart patterns, to confirm signals and improve the accuracy of your analysis.
In this implementation, you have the choice of AMA, KAMA, or T3 smoothing. These are as follows:
Kaufman Adaptive Moving Average (KAMA)
The Kaufman Adaptive Moving Average (KAMA) is a type of adaptive moving average used in technical analysis to smooth out price fluctuations and identify trends. The KAMA adjusts its smoothing factor based on the market's volatility, making it more responsive in volatile markets and smoother in calm markets. The KAMA is calculated using three different efficiency ratios that determine the appropriate smoothing factor for the current market conditions. These ratios are based on the noise level of the market, the speed at which the market is moving, and the length of the moving average. The KAMA is a popular choice among traders who prefer to use adaptive indicators to identify trends and potential reversals.
Adaptive Moving Average
The Adaptive Moving Average (AMA) is a type of moving average that adjusts its sensitivity to price movements based on market conditions. It uses a ratio between the current price and the highest and lowest prices over a certain lookback period to determine its level of smoothing. The AMA can help reduce lag and increase responsiveness to changes in trend direction, making it useful for traders who want to follow trends while avoiding false signals. The AMA is calculated by multiplying a smoothing constant with the difference between the current price and the previous AMA value, then adding the result to the previous AMA value.
T3
The T3 moving average is a type of technical indicator used in financial analysis to identify trends in price movements. It is similar to the Exponential Moving Average (EMA) and the Double Exponential Moving Average (DEMA), but uses a different smoothing algorithm.
The T3 moving average is calculated using a series of exponential moving averages that are designed to filter out noise and smooth the data. The resulting smoothed data is then weighted with a non-linear function to produce a final output that is more responsive to changes in trend direction.
The T3 moving average can be customized by adjusting the length of the moving average, as well as the weighting function used to smooth the data. It is commonly used in conjunction with other technical indicators as part of a larger trading strategy.
█ Giga Kaleidoscope Modularized Trading System
Core components of an NNFX algorithmic trading strategy
The NNFX algorithm is built on the principles of trend, momentum, and volatility. There are six core components in the NNFX trading algorithm:
1. Volatility - price volatility; e.g., Average True Range, True Range Double, Close-to-Close, etc.
2. Baseline - a moving average to identify price trend
3. Confirmation 1 - a technical indicator used to identify trends
4. Confirmation 2 - a technical indicator used to identify trends
5. Continuation - a technical indicator used to identify trends
6. Volatility/Volume - a technical indicator used to identify volatility/volume breakouts/breakdown
7. Exit - a technical indicator used to determine when a trend is exhausted
What is Volatility in the NNFX trading system?
In the NNFX (No Nonsense Forex) trading system, ATR (Average True Range) is typically used to measure the volatility of an asset. It is used as a part of the system to help determine the appropriate stop loss and take profit levels for a trade. ATR is calculated by taking the average of the true range values over a specified period.
True range is calculated as the maximum of the following values:
-Current high minus the current low
-Absolute value of the current high minus the previous close
-Absolute value of the current low minus the previous close
ATR is a dynamic indicator that changes with changes in volatility. As volatility increases, the value of ATR increases, and as volatility decreases, the value of ATR decreases. By using ATR in NNFX system, traders can adjust their stop loss and take profit levels according to the volatility of the asset being traded. This helps to ensure that the trade is given enough room to move, while also minimizing potential losses.
Other types of volatility include True Range Double (TRD), Close-to-Close, and Garman-Klass
What is a Baseline indicator?
The baseline is essentially a moving average, and is used to determine the overall direction of the market.
The baseline in the NNFX system is used to filter out trades that are not in line with the long-term trend of the market. The baseline is plotted on the chart along with other indicators, such as the Moving Average (MA), the Relative Strength Index (RSI), and the Average True Range (ATR).
Trades are only taken when the price is in the same direction as the baseline. For example, if the baseline is sloping upwards, only long trades are taken, and if the baseline is sloping downwards, only short trades are taken. This approach helps to ensure that trades are in line with the overall trend of the market, and reduces the risk of entering trades that are likely to fail.
By using a baseline in the NNFX system, traders can have a clear reference point for determining the overall trend of the market, and can make more informed trading decisions. The baseline helps to filter out noise and false signals, and ensures that trades are taken in the direction of the long-term trend.
What is a Confirmation indicator?
Confirmation indicators are technical indicators that are used to confirm the signals generated by primary indicators. Primary indicators are the core indicators used in the NNFX system, such as the Average True Range (ATR), the Moving Average (MA), and the Relative Strength Index (RSI).
The purpose of the confirmation indicators is to reduce false signals and improve the accuracy of the trading system. They are designed to confirm the signals generated by the primary indicators by providing additional information about the strength and direction of the trend.
Some examples of confirmation indicators that may be used in the NNFX system include the Bollinger Bands, the MACD (Moving Average Convergence Divergence), and the MACD Oscillator. These indicators can provide information about the volatility, momentum, and trend strength of the market, and can be used to confirm the signals generated by the primary indicators.
In the NNFX system, confirmation indicators are used in combination with primary indicators and other filters to create a trading system that is robust and reliable. By using multiple indicators to confirm trading signals, the system aims to reduce the risk of false signals and improve the overall profitability of the trades.
What is a Continuation indicator?
In the NNFX (No Nonsense Forex) trading system, a continuation indicator is a technical indicator that is used to confirm a current trend and predict that the trend is likely to continue in the same direction. A continuation indicator is typically used in conjunction with other indicators in the system, such as a baseline indicator, to provide a comprehensive trading strategy.
What is a Volatility/Volume indicator?
Volume indicators, such as the On Balance Volume (OBV), the Chaikin Money Flow (CMF), or the Volume Price Trend (VPT), are used to measure the amount of buying and selling activity in a market. They are based on the trading volume of the market, and can provide information about the strength of the trend. In the NNFX system, volume indicators are used to confirm trading signals generated by the Moving Average and the Relative Strength Index. Volatility indicators include Average Direction Index, Waddah Attar, and Volatility Ratio. In the NNFX trading system, volatility is a proxy for volume and vice versa.
By using volume indicators as confirmation tools, the NNFX trading system aims to reduce the risk of false signals and improve the overall profitability of trades. These indicators can provide additional information about the market that is not captured by the primary indicators, and can help traders to make more informed trading decisions. In addition, volume indicators can be used to identify potential changes in market trends and to confirm the strength of price movements.
What is an Exit indicator?
The exit indicator is used in conjunction with other indicators in the system, such as the Moving Average (MA), the Relative Strength Index (RSI), and the Average True Range (ATR), to provide a comprehensive trading strategy.
The exit indicator in the NNFX system can be any technical indicator that is deemed effective at identifying optimal exit points. Examples of exit indicators that are commonly used include the Parabolic SAR, the Average Directional Index (ADX), and the Chandelier Exit.
The purpose of the exit indicator is to identify when a trend is likely to reverse or when the market conditions have changed, signaling the need to exit a trade. By using an exit indicator, traders can manage their risk and prevent significant losses.
In the NNFX system, the exit indicator is used in conjunction with a stop loss and a take profit order to maximize profits and minimize losses. The stop loss order is used to limit the amount of loss that can be incurred if the trade goes against the trader, while the take profit order is used to lock in profits when the trade is moving in the trader's favor.
Overall, the use of an exit indicator in the NNFX trading system is an important component of a comprehensive trading strategy. It allows traders to manage their risk effectively and improve the profitability of their trades by exiting at the right time.
How does Loxx's GKD (Giga Kaleidoscope Modularized Trading System) implement the NNFX algorithm outlined above?
Loxx's GKD v1.0 system has five types of modules (indicators/strategies). These modules are:
1. GKD-BT - Backtesting module (Volatility, Number 1 in the NNFX algorithm)
2. GKD-B - Baseline module (Baseline and Volatility/Volume, Numbers 1 and 2 in the NNFX algorithm)
3. GKD-C - Confirmation 1/2 and Continuation module (Confirmation 1/2 and Continuation, Numbers 3, 4, and 5 in the NNFX algorithm)
4. GKD-V - Volatility/Volume module (Confirmation 1/2, Number 6 in the NNFX algorithm)
5. GKD-E - Exit module (Exit, Number 7 in the NNFX algorithm)
(additional module types will added in future releases)
Each module interacts with every module by passing data between modules. Data is passed between each module as described below:
GKD-B => GKD-V => GKD-C(1) => GKD-C(2) => GKD-C(Continuation) => GKD-E => GKD-BT
That is, the Baseline indicator passes its data to Volatility/Volume. The Volatility/Volume indicator passes its values to the Confirmation 1 indicator. The Confirmation 1 indicator passes its values to the Confirmation 2 indicator. The Confirmation 2 indicator passes its values to the Continuation indicator. The Continuation indicator passes its values to the Exit indicator, and finally, the Exit indicator passes its values to the Backtest strategy.
This chaining of indicators requires that each module conform to Loxx's GKD protocol, therefore allowing for the testing of every possible combination of technical indicators that make up the six components of the NNFX algorithm.
What does the application of the GKD trading system look like?
Example trading system:
Backtest: Strategy with 1-3 take profits, trailing stop loss, multiple types of PnL volatility, and 2 backtesting styles
Baseline: Hull Moving Average
Volatility/Volume: Hurst Exponent
Confirmation 1: Adaptive-Lookback Phase Change Index as shown on the chart above
Confirmation 2: Williams Percent Range
Continuation: Fisher Transform
Exit: Rex Oscillator
Each GKD indicator is denoted with a module identifier of either: GKD-BT, GKD-B, GKD-C, GKD-V, or GKD-E. This allows traders to understand to which module each indicator belongs and where each indicator fits into the GKD protocol chain.
Giga Kaleidoscope Modularized Trading System Signals (based on the NNFX algorithm)
Standard Entry
1. GKD-C Confirmation 1 Signal
2. GKD-B Baseline agrees
3. Price is within a range of 0.2x Volatility and 1.0x Volatility of the Goldie Locks Mean
4. GKD-C Confirmation 2 agrees
5. GKD-V Volatility/Volume agrees
Baseline Entry
1. GKD-B Baseline signal
2. GKD-C Confirmation 1 agrees
3. Price is within a range of 0.2x Volatility and 1.0x Volatility of the Goldie Locks Mean
4. GKD-C Confirmation 2 agrees
5. GKD-V Volatility/Volume agrees
6. GKD-C Confirmation 1 signal was less than 7 candles prior
Volatility/Volume Entry
1. GKD-V Volatility/Volume signal
2. GKD-C Confirmation 1 agrees
3. Price is within a range of 0.2x Volatility and 1.0x Volatility of the Goldie Locks Mean
4. GKD-C Confirmation 2 agrees
5. GKD-B Baseline agrees
6. GKD-C Confirmation 1 signal was less than 7 candles prior
Continuation Entry
1. Standard Entry, Baseline Entry, or Pullback; entry triggered previously
2. GKD-B Baseline hasn't crossed since entry signal trigger
3. GKD-C Confirmation Continuation Indicator signals
4. GKD-C Confirmation 1 agrees
5. GKD-B Baseline agrees
6. GKD-C Confirmation 2 agrees
1-Candle Rule Standard Entry
1. GKD-C Confirmation 1 signal
2. GKD-B Baseline agrees
3. Price is within a range of 0.2x Volatility and 1.0x Volatility of the Goldie Locks Mean
Next Candle:
1. Price retraced (Long: close < close or Short: close > close )
2. GKD-B Baseline agrees
3. GKD-C Confirmation 1 agrees
4. GKD-C Confirmation 2 agrees
5. GKD-V Volatility/Volume agrees
1-Candle Rule Baseline Entry
1. GKD-B Baseline signal
2. GKD-C Confirmation 1 agrees
3. Price is within a range of 0.2x Volatility and 1.0x Volatility of the Goldie Locks Mean
4. GKD-C Confirmation 1 signal was less than 7 candles prior
Next Candle:
1. Price retraced (Long: close < close or Short: close > close )
2. GKD-B Baseline agrees
3. GKD-C Confirmation 1 agrees
4. GKD-C Confirmation 2 agrees
5. GKD-V Volatility/Volume Agrees
1-Candle Rule Volatility/Volume Entry
1. GKD-V Volatility/Volume signal
2. GKD-C Confirmation 1 agrees
3. Price is within a range of 0.2x Volatility and 1.0x Volatility of the Goldie Locks Mean
4. GKD-C Confirmation 1 signal was less than 7 candles prior
Next Candle:
1. Price retraced (Long: close < close or Short: close > close)
2. GKD-B Volatility/Volume agrees
3. GKD-C Confirmation 1 agrees
4. GKD-C Confirmation 2 agrees
5. GKD-B Baseline agrees
PullBack Entry
1. GKD-B Baseline signal
2. GKD-C Confirmation 1 agrees
3. Price is beyond 1.0x Volatility of Baseline
Next Candle:
1. Price is within a range of 0.2x Volatility and 1.0x Volatility of the Goldie Locks Mean
2. GKD-C Confirmation 1 agrees
3. GKD-C Confirmation 2 agrees
4. GKD-V Volatility/Volume Agrees
]█ Setting up the GKD
The GKD system involves chaining indicators together. These are the steps to set this up.
Use a GKD-C indicator alone on a chart
1. Inside the GKD-C indicator, change the "Confirmation Type" setting to "Solo Confirmation Simple"
Use a GKD-V indicator alone on a chart
**nothing, it's already useable on the chart without any settings changes
Use a GKD-B indicator alone on a chart
**nothing, it's already useable on the chart without any settings changes
Baseline (Baseline, Backtest)
1. Import the GKD-B Baseline into the GKD-BT Backtest: "Input into Volatility/Volume or Backtest (Baseline testing)"
2. Inside the GKD-BT Backtest, change the setting "Backtest Special" to "Baseline"
Volatility/Volume (Volatility/Volume, Backte st)
1. Inside the GKD-V indicator, change the "Testing Type" setting to "Solo"
2. Inside the GKD-V indicator, change the "Signal Type" setting to "Crossing" (neither traditional nor both can be backtested)
3. Import the GKD-V indicator into the GKD-BT Backtest: "Input into C1 or Backtest"
4. Inside the GKD-BT Backtest, change the setting "Backtest Special" to "Volatility/Volume"
5. Inside the GKD-BT Backtest, a) change the setting "Backtest Type" to "Trading" if using a directional GKD-V indicator; or, b) change the setting "Backtest Type" to "Full" if using a directional or non-directional GKD-V indicator (non-directional GKD-V can only test Longs and Shorts separately)
6. If "Backtest Type" is set to "Full": Inside the GKD-BT Backtest, change the setting "Backtest Side" to "Long" or "Short
7. If "Backtest Type" is set to "Full": To allow the system to open multiple orders at one time so you test all Longs or Shorts, open the GKD-BT Backtest, click the tab "Properties" and then insert a value of something like 10 orders into the "Pyramiding" settings. This will allow 10 orders to be opened at one time which should be enough to catch all possible Longs or Shorts.
Solo Confirmation Simple (Confirmation, Backtest)
1. Inside the GKD-C indicator, change the "Confirmation Type" setting to "Solo Confirmation Simple"
1. Import the GKD-C indicator into the GKD-BT Backtest: "Input into Backtest"
2. Inside the GKD-BT Backtest, change the setting "Backtest Special" to "Solo Confirmation Simple"
Solo Confirmation Complex without Exits (Baseline, Volatility/Volume, Confirmation, Backtest)
1. Inside the GKD-V indicator, change the "Testing Type" setting to "Chained"
2. Import the GKD-B Baseline into the GKD-V indicator: "Input into Volatility/Volume or Backtest (Baseline testing)"
3. Inside the GKD-C indicator, change the "Confirmation Type" setting to "Solo Confirmation Complex"
4. Import the GKD-V indicator into the GKD-C indicator: "Input into C1 or Backtest"
5. Inside the GKD-BT Backtest, change the setting "Backtest Special" to "GKD Full wo/ Exits"
6. Import the GKD-C into the GKD-BT Backtest: "Input into Exit or Backtest"
Solo Confirmation Complex with Exits (Baseline, Volatility/Volume, Confirmation, Exit, Backtest)
1. Inside the GKD-V indicator, change the "Testing Type" setting to "Chained"
2. Import the GKD-B Baseline into the GKD-V indicator: "Input into Volatility/Volume or Backtest (Baseline testing)"
3. Inside the GKD-C indicator, change the "Confirmation Type" setting to "Solo Confirmation Complex"
4. Import the GKD-V indicator into the GKD-C indicator: "Input into C1 or Backtest"
5. Import the GKD-C indicator into the GKD-E indicator: "Input into Exit"
6. Inside the GKD-BT Backtest, change the setting "Backtest Special" to "GKD Full w/ Exits"
7. Import the GKD-E into the GKD-BT Backtest: "Input into Backtest"
Full GKD without Exits (Baseline, Volatility/Volume, Confirmation 1, Confirmation 2, Continuation, Backtest)
1. Inside the GKD-V indicator, change the "Testing Type" setting to "Chained"
2. Import the GKD-B Baseline into the GKD-V indicator: "Input into Volatility/Volume or Backtest (Baseline testing)"
3. Inside the GKD-C 1 indicator, change the "Confirmation Type" setting to "Confirmation 1"
4. Import the GKD-V indicator into the GKD-C 1 indicator: "Input into C1 or Backtest"
5. Inside the GKD-C 2 indicator, change the "Confirmation Type" setting to "Confirmation 2"
6. Import the GKD-C 1 indicator into the GKD-C 2 indicator: "Input into C2"
7. Inside the GKD-C Continuation indicator, change the "Confirmation Type" setting to "Continuation"
8. Inside the GKD-BT Backtest, change the setting "Backtest Special" to "GKD Full wo/ Exits"
9. Import the GKD-E into the GKD-BT Backtest: "Input into Exit or Backtest"
Full GKD with Exits (Baseline, Volatility/Volume, Confirmation 1, Confirmation 2, Continuation, Exit, Backtest)
1. Inside the GKD-V indicator, change the "Testing Type" setting to "Chained"
2. Import the GKD-B Baseline into the GKD-V indicator: "Input into Volatility/Volume or Backtest (Baseline testing)"
3. Inside the GKD-C 1 indicator, change the "Confirmation Type" setting to "Confirmation 1"
4. Import the GKD-V indicator into the GKD-C 1 indicator: "Input into C1 or Backtest"
5. Inside the GKD-C 2 indicator, change the "Confirmation Type" setting to "Confirmation 2"
6. Import the GKD-C 1 indicator into the GKD-C 2 indicator: "Input into C2"
7. Inside the GKD-C Continuation indicator, change the "Confirmation Type" setting to "Continuation"
8. Import the GKD-C Continuation indicator into the GKD-E indicator: "Input into Exit"
9. Inside the GKD-BT Backtest, change the setting "Backtest Special" to "GKD Full w/ Exits"
10. Import the GKD-E into the GKD-BT Backtest: "Input into Backtest"
Baseline + Volatility/Volume (Baseline, Volatility/Volume, Backtest)
1. Inside the GKD-V indicator, change the "Testing Type" setting to "Baseline + Volatility/Volume"
2. Inside the GKD-V indicator, make sure the "Signal Type" setting is set to "Traditional"
3. Import the GKD-B Baseline into the GKD-V indicator: "Input into Volatility/Volume or Backtest (Baseline testing)"
4. Inside the GKD-BT Backtest, change the setting "Backtest Special" to "Baseline + Volatility/Volume"
5. Import the GKD-V into the GKD-BT Backtest: "Input into C1 or Backtest"
6. Inside the GKD-BT Backtest, change the setting "Backtest Type" to "Full". For this backtest, you must test Longs and Shorts separately
7. To allow the system to open multiple orders at one time so you can test all Longs or Shorts, open the GKD-BT Backtest, click the tab "Properties" and then insert a value of something like 10 orders into the "Pyramiding" settings. This will allow 10 orders to be opened at one time which should be enough to catch all possible Longs or Shorts.
Requirements
Inputs
Confirmation 1: GKD-V Volatility / Volume indicator
Confirmation 2: GKD-C Confirmation indicator
Continuation: GKD-C Confirmation indicator
Solo Confirmation Simple: GKD-B Baseline
Solo Confirmation Complex: GKD-V Volatility / Volume indicator
Solo Confirmation Super Complex: GKD-V Volatility / Volume indicator
Stacked 1: None
Stacked 2+: GKD-C, GKD-V, or GKD-B Stacked 1
Outputs
Confirmation 1: GKD-C Confirmation 2 indicator
Confirmation 2: GKD-C Continuation indicator
Continuation: GKD-E Exit indicator
Solo Confirmation Simple: GKD-BT Backtest
Solo Confirmation Complex: GKD-BT Backtest or GKD-E Exit indicator
Solo Confirmation Super Complex: GKD-C Continuation indicator
Stacked 1: GKD-C, GKD-V, or GKD-B Stacked 2+
Stacked 2+: GKD-C, GKD-V, or GKD-B Stacked 2+ or GKD-BT Backtest
Additional features will be added in future releases.
Sachin Bull & Eagle Pro (Invite-Only)Bull & Eagle Pro is a multi-confirmation trend & breakout framework designed for traders who prefer clean, actionable market structure signals.
It combines directional bias, momentum alignment, and trend structure monitoring into one visual system.
🔹 What this script does
✔ Detects directional shift using an ATR-based trailing structure
✔ Marks BUY and SELL signal events when momentum flips
✔ Colors price bars based on trend bias
✔ Tracks trend continuation using a 20-period EMA filter
✔ Draws dynamic adaptive trendlines based on pivots
✔ Highlights breakout events when price breaches a structural swing line
The tool helps traders see:
• Trend continuation
• Trend exhaustion
• Momentum reversals
• Structural breakouts
It is intended as a visual decision-support tool — not a guarantee of future price movement.
🔹 What makes it useful
Instead of acting as a standalone strategy, Bull & Eagle Pro acts as a confluence engine, helping traders:
• Validate breakout strength
• Identify bias shift points
• Spot momentum reversal zones
• Monitor clean price structure
Signals can be used to:
• Time entries
• Trail stops
• Confirm breakouts
• Manage position direction bias
🔹 Key Components
1️⃣ Trend Direction Engine
Based on a dynamic ATR trailing reference point identifying BUY/SELL flips.
2️⃣ 20 EMA Filter
A classic trend tool for acceleration vs. pullback phases.
3️⃣ Adaptive Trendlines
Automatically generated and extended into future bars to project structure.
4️⃣ Breakout Markers & Alerts
Plots “B” tags when price breaches structural trendlines.
🔹 Alerts Included
• Long Signal Trigger
• Short Signal Trigger
• Bullish Breakout
• Bearish Breakout
These allow automation or push notifications when structural shifts occur.
🔹 Intended Usage
This tool is best suited for:
• Trend traders
• Breakout traders
• Positional traders
• Swing traders
Works on:
• Index futures
• Stocks
• Cryptocurrency
• FX
• Options charts
It can be applied across intraday and higher-timeframe environments.
⚠ Important Disclaimer
This script is for educational and research purposes only.
It does not provide financial advice and does not guarantee results.
Trading involves risk — always perform independent analysis before acting on any tool.
IMS 4H Structural Framework (MA / Pivot / MTF Levels)IMS 4H Structural Framework (MA / Pivot / MTF Levels)
✅ SHORT, COMPLIANT DESCRIPTION (Invite-Only Safe)
Description:
This tool visualizes a 4H Institutional Market Structure (IMS) framework by combining three workflow components into a single structural map—MA-based bias shifts, pivot-derived 4H trendlines, and multi-timeframe (1H/45m) structural levels.
It does not generate signals or performance claims.
The framework is designed purely for visual, discretionary analysis of structural flow, risk context, and higher-timeframe alignment.
Core Components:
• 4H Bias Shift (MA): Highlights directional bias transitions.
• 4H Trendlines (Pivot-Based): Shows structural slopes and reaction zones.
• MTF Levels (1H & 45m): Adds micro-structure inside the 4H box for refinement.
• Caution Zones: Marks potential reaction areas near support/resistance or trendlines.
• Dashboard: Displays bias context and educational guidance only.
Intended Use:
For traders who analyze 4H structural flow and wish to visualize bias, context, and multi-timeframe alignment—not for automation or signals.
________________________________________
✅ SHORT, SAFE DISCLAIMER (Invite-Only Approved)
Disclaimer:
This tool is for educational and informational purposes only.
It does not provide trading signals, financial advice, or performance guarantees.
All decisions remain solely with the user.
Custom Support & Resistance LevelsThe Smart Auto Trendline Indicator is designed to help traders quickly identify key market trends without the need for manual drawing. It automatically detects swing highs and lows, plots dynamic trendlines, and updates them in real-time as price evolves.
This tool is especially useful for traders who rely on trendline breakouts, pullback entries, or reversal confirmations. By simplifying chart analysis, it saves time and ensures more consistent results.
Key Features:
🔹 Automatic detection of valid swing highs and lows
🔹 Dynamic trendline plotting (auto-adjusts as price moves)
🔹 Highlights potential breakout and breakdown zones
🔹 Works on all timeframes and instruments (Forex, Stocks, Indices, Crypto)
🔹 Clean, non-intrusive design to keep charts clear
🔹 Customizable settings (line color, style, sensitivity)
How to Use:
Apply the indicator to your chart.
Observe automatically drawn trendlines.
Watch for breakouts above/below trendlines for trade entries.
Use in combination with other tools like RSI, MACD, or support/resistance for stronger confirmation.
Best For:
Breakout traders
Swing traders
Trend followers
Forex, Stocks, Crypto, Indices
Smart Trend EnvelopeThe "Smart Trend Envelope" indicator is a powerful tool that combines the "Nadaraya-Watson Envelope " indicator by LuxAlgo and the "Strongest Trendline" indicator by Julien_Eche.
This indicator provides valuable insights into price trends and projection confidence levels in financial markets. However, it's important to note that the indicator may repaint, meaning that the displayed results can change after the fact.
The "Strongest Trendline" indicator by Julien_Eche focuses on identifying the strongest trendlines using logarithmic transformations of price data. It calculates the slope, average, and intercept of each trendline over user-defined lengths. The indicator also provides standard deviation, Pearson's R correlation coefficient, and upper/lower deviation values to assess the strength and reliability of the trendlines.
In addition, the "Nadaraya-Watson Envelope " indicator developed by LuxAlgo utilizes the Nadaraya-Watson kernel regression technique. It applies a kernel function to smooth the price data and estimate future price movements. The indicator allows adjustment of the bandwidth parameter and multiplier to control the width of the envelope lines around the smoothed line.
Combining these two indicators, the "Smart Trend Envelope" indicator offers traders and investors a comprehensive analysis of price trends and projection confidence levels. It automatically selects the strongest trendline length based on the highest Pearson's R correlation coefficient. Traders can observe the trendlines on the price chart, along with upper and lower envelope lines generated by the Nadaraya-Watson smoothing technique.
The "Smart Trend Envelope" indicator has several qualities that make it a valuable tool for technical analysis:
1. Automatic Length Selection: The indicator dynamically selects the optimal trendline length based on the highest Pearson's R correlation coefficient, ensuring accurate trend analysis.
2. Projection Confidence Level: The indicator provides a projection confidence level ranging from "Ultra Weak" to "Ultra Strong." This allows traders to assess the reliability of the projected trend and make informed trading decisions.
3. Color-Coded Visualization: The indicator uses color schemes, such as teal and red, to highlight the direction of the trend and the corresponding envelope lines. This visual representation makes it easier to interpret the market trends at a glance.
4. Customizable Settings: Traders can adjust parameters such as bandwidth, multiplier, line color, and line width to tailor the indicator to their specific trading strategies and preferences.
The "Smart Trend Envelope" indicator has been specifically designed and coded to be used in logarithmic scale. It takes advantage of the logarithmic scale's ability to represent exponential price movements accurately. Therefore, it is highly recommended to use this indicator with the chart set to logarithmic scale for optimal performance and reliable trend analysis, especially on higher timeframes.
It's important to remember that the "Smart Trend Envelope" indicator may repaint, meaning that the displayed results can change after the fact. Traders should use this indicator as a tool for generating trade ideas and confirmation, rather than relying solely on its historical values. Combining the indicator with other technical analysis tools and considering fundamental factors can lead to more robust trading strategies.
Auto Trend ProjectionAuto Trend Projection is an indicator designed to automatically project the short-term trend based on historical price data. It utilizes a dynamic calculation method to determine the slope of the linear regression line, which represents the trend direction. The indicator takes into account multiple length inputs and calculates the deviation and Pearson's R values for each length.
Using the highest Pearson's R value, Auto Trend Projection identifies the optimal length for the trend projection. This ensures that the projected trend aligns closely with the historical price data.
The indicator visually displays the projected trend using trendlines. These trendlines extend into the future, providing a visual representation of the potential price movement in the short term. The color and style of the trendlines can be customized according to user preferences.
Auto Trend Projection simplifies the process of trend analysis by automating the projection of short-term trends. Traders and investors can use this indicator to gain insights into potential price movements and make informed trading decisions.
Please note that Auto Trend Projection is not a standalone trading strategy but a tool to assist in trend analysis. It is recommended to combine it with other technical analysis tools and indicators for comprehensive market analysis.
Overall, Auto Trend Projection offers a convenient and automated approach to projecting short-term trends, empowering traders with valuable insights into the potential price direction.
Double Supertrend Entry with ADX Filter and ATR Exits/EntriesThe Double Supertrend Entry with ADX Filter and ATR Exits/Entries indicator is a custom trading strategy designed to help traders identify potential buy and sell signals in trending markets. This indicator combines the strengths of multiple technical analysis tools, enhancing the effectiveness of the overall strategy.
Key features:
Two Supertrend Indicators - The indicator includes two Supertrend indicators with customizable parameters. These trend-following indicators calculate upper and lower trendlines based on the ATR and price. Buy signals are generated when the price crosses above both trendlines, and sell signals are generated when the price crosses below both trendlines.
ADX Filter - The Average Directional Index (ADX) is used to filter out weak trends and only generate buy/sell signals when the market exhibits a strong trend. The ADX measures the strength of the trend, and a customizable threshold level ensures that trades are only entered during strong trends.
ATR-based Exits and Entries - The indicator uses the Average True Range (ATR) to set profit target and stop-loss levels. ATR is a measure of market volatility, and these levels help traders determine when to exit a trade to secure profit or minimize loss.
Performance Statistics Table - A table is displayed on the chart, recording and showing the total number of winning trades, losing trades, percentage of profitable trades, average profit, and average loss. This information helps traders evaluate the performance of the strategy over time.
The Double Supertrend Entry with ADX Filter and ATR Exits/Entries indicator is a powerful trend-following strategy that can assist traders in making more informed decisions in the financial markets. By combining multiple technical analysis tools and providing performance statistics, this indicator helps traders improve their trading strategy and evaluate its success.
Fishing The Trend - Setup Classic v7.5.5FTT Classic v7.5.5
HOW Does it work ?
It is the classic version of Fishing The Trend-Setup for ease of trading & for getting the most from the market.
i.e. Combining the most useful indicators and making a whole setup under one roof...
FTT Classic comprises of following --
* IntraDay Range.
* Fishing The Trend.
* Custom VWAP.
* Baseband for Trend.
* Trendlines.
* Support & Resistance Lines.
* BreakOut Area.
* Technical Analysis table.
* Custom alerts.
1) HOW Does Intraday Range work ?
# For calculating the average most probable range for any symbol, it plots two areas - higher range and a lower range.
# This indicator is on - as default.
# Upper and Lower areas act as support and resistance, user may see a reversal in trend from these areas.
# If the price breaks these bands, breakout be considered.
# These bands are calculated by averaging the previous x number of days' high and low of the security.
3) HOW Does Fishing The Trend work ?
# When the market trend may try to reverse, the first signal/label will come showing Stop loss figure, and then if the trend reversal is confirmed, the supporting triangle in the next opening price will be placed at upper or lower side. along with these
there is a trailing stop-loss line, which will help user to trail their profits in-live.
# The CE-PE can be seen through the table with date and time.
# 2nd table also can be placed below the first one, showing the CE-PE Values for different symbol.
# Signals can be controlled by more or less as optioned in the settings.
# CE-PE strike price can be selected from ATM - ITM - OTM.
4) HOW Does Custom VWAP work ?
# VWAP will be placed having a line and current price of VWAP.
# One can have vwap in index chart also, the colour changes as the market goes above or below vwap or at vwap.
5) HOW Does Baseband for Trend work ?
# Baseband will be plotted for least 2 days on 3 min and gradually increases on increase of timeframe.
# If the market is above band, we may consider it a positive side and if market is below it, we may consider a negative side.
# Type 1 band is for trending market and type 2 is for rangebound market.
# Colour intensity also changes as market picks-up momentum or leaves momentum.
6) HOW Does Trendlines work ?
# Most nearest to most touching trendlines are placed for better understanding the trend.
# Easy to understand with the help of colour combinations.
7) HOW Does Support & Resistance Lines work ?
# The support & resistance lines will be drawn when market movement slows down or momentum decrease.
# The Support lines becomes resistance when market falls below it, and vice-versa for other conditions.
# Range development can be easily detected and can be used as range breakout for better understanding the market.
8) HOW Does BreakOut Area work ?
# Market Consolidates at most of the time, where the bulls and bears fight becomes more aggressive, at this point
of time the area will be formed or area will be formed when market trend reverses suddenly, leaving behind the previous
breakout area.
# Ease of trend reversal, previous supports / resistances can be seen easily.
9) HOW Does Technical Analysis table work ?
# There will be RSI displayed and for the better range detection, range area with price can be seen.
# The GAP of the opening market is seen with gap points (Down or Up)
10) HOW Does Custom alerts work ?
# Alerts can enabled for the CE-PE Strike Price through alerts management from Tradingview.
# Alerts can also be set when the Traffic Signal Comes.
Where to use?
# If the chart is of Index or equity, extended trading hours to be selected, time shall be exchange.
# Indicator wont work on timeframes lower than minutes or higher than or equal to day.
# can be used in every type of market.
# Extended to be selected for Index or Equities/Stocks, Regular be selected for futures, etc.
# At every part / portion the tooltip is placed showing the quick reference for that option.
# The main use of this indicator is quick scalping and Intra-day trading.
# Colour Theme can be selected if the chart theme is dark or light.
# The indicator shows a very useful option for early detection of the ongoing trend whether there will be reversal of trend or not ? Stop Loss - That should be done by following ones risk appetite, Ideally the High of the Previous Candle should be the stop loss for the Long / Short but everyone has their own Risk Management Strategies based on the capital deployed.
How to Take entry ?
# Time Frame shall be more than 2 min and less than day for better outcome.
# If buy signal comes and the market is below the baseband then wait for the market to cross and close above the baseband, also look for the immediate support or resistances which are seen in chart and those nearby the current signal.
# The data for the indicator will be very restricted, most of the parts in indicator wont work when the market closes.
# Pre-Opening or Post -Market data is tried to be ignored.
# Utmost Care is taken to implement the suggestions of users and also tried to keep the chart neat and clean.
** N.B.:- There may be cases where warning may come during setting the alert, this because
of alert conditions are taken ONLY when the current candle is CLOSED, real-time alerts are
considered as not feasible to get it.
Disclaimer
# The indicator to be used for understanding / learning the markets.
# User is responsible for his / her profits/losses, that may occur during the markets.
QuantRsi - Quantized Relative Strength Index - SNOW_CITY QuantRsi is a Relative Strength Indicator designed to improve on RSI's divergence confirmation. QuantRsi also functions as an entirely new type of range-bound oscillator, enabling "Hybrid TA" - the study and use of drawing tools on candles painted by the indicator.
QuantRsi paints full OHLC candles by default - displaying the full range of each candle's movement.
This tool sets out to accomplish:
Confirmation of divergence with a 3-anchor trading system
Show key price levels as whole numbers "quantized" from a scale of -10 to + 10; as well as commonly revisited levels within a trend
Anticipate divergence & turning points by charting on the indicator candles - trendlines can be drawn on indicator print - "Hybrid TA"
The result is an indicator able to process nonlinear price movements and draw range-bound candles with peaks and troughs that form repeating collisions with common tangents. QRsi illustrates trends and trend violations in a market with the advantage of behaving like a leading indicator. QRsi possesses a supreme ability to show divergence and confirm reversals/ turning points.
The dynamics of the vertical scale allows the formation of linear trends on the oscillator which classical charting can be applied. The support and resistance values for an asset will follow consistent incidents upon a tangent while the market is trending.
When a trend is violated, the break-up or break-down of price will revisit prior incidents both on frequented horizontal levels ("-1.4" or "+5.0") as well as tangent lines drawn from prior reversal points. Prior, violated trend-lines can be used as anchor points for a new linear trend - establishing a hypothetical market range before price moves into these hidden divergence zones.
Much like RSI, the extremes of a QRsi range (whether that be +/- 7,10 or the trend-established reversal value) are not always indicated turning points. Divergence does not occur at every turning point, but it does occur at most significant turning points.
Unlike RSI, QRsi adds the ability to visualize turning points outside divergence by drawing a trendline from prior turning points to the next anticipated turning point.
QRsi enables an asset to express it's price range within a flexible scale for that trend. The scaling has a higher dynamic range than classic RSI, at the expense of not filling the entire range of the oscillator at all times. An asset's highest and lowest trending values should be established by observation of prior visited values, not by the borders of the oscillator's range.
In the main chart example, trend-lines are drawn on the QuantRsi indicator for ETH/USD - Bitfinex 4H
Here is the same chart with notation:
The dashed trend-lines represent trends that have not been established yet. They turn solid when they have a second anchor(in primary chart).
Trendline violations create anchor points for new trendlines
Turning points with and without divergence depend entirely on asset's prior QRsi values, relative on relative.
In the above chart, Qrsi Value "2" is a common reversal value. In the chart period that is shown, selloff ensues shortly after QRsi reaches 2.
QRsi Values range from -10 to + 10. The boundaries represent the extremes of anticipated market range for that timeframe. Unlike traditional RSI, it is rare that an asset will range from the lowest to the highest boundaries. Instead, common values for that asset are observed by studying historical price data. A lower and upper range is established based on historical trends. When these values are hit, it represents an anchor for divergence. You will find that reversals can occur on the +/- 3, 5, 7 and 10 values frequently, although, this is indication without confirmation.
Depending on the timeframe and asset, the common turning point for an asset may be -2 & +5, with outliers to -5 & +7; or it may be -1.4 & +6.5 for an uptrending asset. The horizontal +/- QRsi values which turning points are likely to occur need to be established by studying the asset and verified by divergence or trend incident.
Confirmation is gained by observing the 3-anchor trading system:
1: Divergence - Locally
2: Trend incident or violation - charted patterns, linear ascending or descending trendlines.
3: Horizontal value incident
In the chart below, common horizontal turning points, divergence, and trendline violation are used as indicators for trading.
Observe how the same horizontal levels are visited as support and resistance depending on the direction of the trend prior to visiting that level.
Note how there are 2 coincidences of Trend / Horizontal / Divergence for most of the indicated trades:
This is the same chart, but with trades shown on the price chart as well as the QRsi chart:
And a simplified view of the same chart with Heffae Clouds enabled:
Notice how once a horizontal level is violated, it is often revisited which confirms it's role-change from S to R or R to S.
Weekly chart showing horizontal support level on lows, and divs for 4 prior All-Time-High's
Example of drawing a trend-line on QRsi and setting up a trade based off of a trend incident:
In the above example, the first two incidents are used as anchor points to reference where the third incident might occur.
In this case, you would have all 3 anchors, and a very successful trade with conformation of a proper entry prior to taking the trade.
Example of using a trend-line to set up trade continuation after divergence prints:
Example of how horizontal levels or ranges can be revisited after much time has passed. This also displays how divergences are used with horizontal levels to establish confidence in a trade:
Example of how QRsi values establish future support / resistance value ranges. Candle-wick sets future lower range:
Example of horizontal levels and divergence:
And, a drawing-free chart of QRsi with Heffae Clouds on BTCUSD Dec 2017 - Nov 2018 - Imagine your own TA on the QRsi.
SETTINGS:
TimeFrame settings:
"ChartTF" follows your chart's selected resolution / TimeFrame
"Non-Chart TimeFrame" is an integer for your custom TimeFrame, the setting below:
"Non-Chart TimeFrame" selects "Minutes, Hours, Days" that corresponds to the above setting for a custom TimeFrame.
Visual Settings:
"Show QuantRSI As Candles" - Toggle this to change from candlesticks to a simplified line. The line's value is determined by "Input for Stochastic" below
"Show Stoch QRSI" - Toggle this to switch to a Stochastic Rsi based off of the QRsi.
"Show Price Per 1.0" - Toggle this to see the range value, in chart denomination (USD,GBP,BTC,JPY) for each 1.0 step in the QRsi range for that timeframe. See this example:
The Quantization range values can be displayed by checking the box in settings "Show value per 1.0"
This will paint a colorless line and display the price value in the indicator's data window. You can calculate the rough price difference to any local value in QRsi by multiplying "value per 1.0" by the expected change in QRsi value.
Configuration Settings:
"Trend Bias" - Experimental setting for different asset classes and market conditions. Changes QRsi bias. Experiment with this on shorter timeframes. Leave on "low" unless you have established that different settings work better for a particular asset.
"Quant Preset" - This is similar to "Path Fitting Preset" on Heffae Clouds. Adjust this to print higher validity patterns on different assets.
The conformation that this setting is adjusted properly for your asset will be evident by backtesting the QRsi. BTC = 0 ETH / FOREX = 1 & 2
Experiment with this, as it adjusts the path-finding algo in order to paint valid patterns. The maths are too complex to integrate a single numerical adjustment, hence the preset.
"Upper/Lower Bounds" - This adjusts scaling and thresholds. Experimental only at this time. Use in conjunction with "Range Multiplier"
"Boundaries" - This adjusts the beginning of the shaded area on the top and bottom of the oscillator. Adjust this to a particular value instead of drawing a trendline on the value of interest. I added this because the shaded areas are easier to see on mobile than a trendline .
"Stochastic Short" - Adjust the length of Stochastic RSI SMA's
"Stochastic Long" - Adjust the length of Stochastic RSI SMA's
"Input for Stochastic" - Select the price source for Stoic & QRsi simplified line.
"Range Multiplier" - This amplifies the QRsi input to occupy a larger or smaller range within the oscillator boundaries. Experimental only at this time. Use in conjunction with "Upper/Lower Bounds". Very fun to play with.
That's all for now! I will do my best to keep this updated with new features / capabilities, as well as continuing to provide use examples and education for my indicators.
If there is a feature you would like, question answered, or a bug, please post in the SNOW_CITY Indicators Chat:
www.tradingview.com
Educational content will be posted here:
aedictiveanalytics.wordpress.com
Please see this pastebin link for access information and links:
pastebin.com
P6●智能资金概念交易系统//@version=5
indicator("P6●智能资金概念交易系统", overlay=true, max_boxes_count = 500, max_labels_count = 500)
// === 参数分类标题 ===
// --------------------------
// 1. 基础指标设置
// --------------------------
// 2. 范围过滤器 设置
// --------------------------
// 3. ADX 趋势过滤器 设置
// --------------------------
// 4. 趋势线 设置
// --------------------------
// 5. 支撑与阻力 设置
// --------------------------
// 6. PMA 设置
// --------------------------
// 7. 交易信息表格 设置
// --------------------------
// 8. 顶部规避 设置
// --------------------------
// 9. 底部规避 设置
// --------------------------
// 10. RSI 动量指标 设置
// --------------------------
// 11. 多时间框架 设置
// --------------------------
// === 显示/隐藏选项 ===
showRangeFilter = input.bool(true, title="显示 范围过滤器", group="1. 基础指标设置")
showADXFilter = input.bool(true, title="启用 ADX 趋势过滤器", group="1. 基础指标设置")
showTrendLines = input.bool(false, title="显示 趋势线", group="1. 基础指标设置")
showSupRes = input.bool(true, title="显示 支撑与阻力", group="1. 基础指标设置")
showPMA = input.bool(true, title="显示 多周期移动平均线", group="1. 基础指标设置")
showTable = input.bool(true, title="显示 交易信息表格", group="1. 基础指标设置")
showTopAvoidance = input.bool(false, title="启用 顶部规避系统", group="1. 基础指标设置")
showBottomAvoidance = input.bool(false, title="启用 底部规避系统", group="1. 基础指标设置")
showRSI = input.bool(false, title="启用 RSI 动量指标", group="1. 基础指标设置")
showMTF = input.bool(true, title="启用 多时间框架分析", group="1. 基础指标设置")
// === RSI 动量指标 设置 ===
rsiLength = input.int(14, title="RSI 周期", minval=1, group="10. RSI 动量指标 设置")
rsiOverbought = input.float(70.0, title="超买阈值", minval=50, maxval=90, step=1, group="10. RSI 动量指标 设置")
rsiOversold = input.float(30.0, title="超卖阈值", minval=10, maxval=50, step=1, group="10. RSI 动量指标 设置")
rsiNeutralUpper = input.float(60.0, title="中性区间上沿", minval=50, maxval=70, step=1, group="10. RSI 动量指标 设置")
rsiNeutralLower = input.float(40.0, title="中性区间下沿", minval=30, maxval=50, step=1, group="10. RSI 动量指标 设置")
// === 多时间框架设置 ===
mtfEnable1m = input.bool(true, title="启用 1分钟", group="11. 多时间框架 设置")
mtfEnable5m = input.bool(true, title="启用 5分钟", group="11. 多时间框架 设置")
mtfEnable15m = input.bool(true, title="启用 15分钟", group="11. 多时间框架 设置")
mtfEnable1h = input.bool(true, title="启用 1小时", group="11. 多时间框架 设置")
mtfEnable4h = input.bool(true, title="启用 4小时", group="11. 多时间框架 设置")
// === RSI 计算与状态判断 ===
rsiValue = ta.rsi(close, rsiLength)
rsiPrevious = ta.rsi(close , rsiLength)
// RSI 动量状态判断
getRSIStatus() =>
status = "动量中性"
// 动量回落条件:RSI从高位下降或处于下降趋势
fallCondition1 = rsiValue < rsiPrevious and rsiValue > rsiNeutralUpper
fallCondition2 = rsiValue >= rsiOverbought and rsiValue < rsiPrevious
fallCondition3 = rsiPrevious >= rsiOverbought and rsiValue < rsiOverbought and rsiValue < rsiPrevious
if fallCondition1 or fallCondition2 or fallCondition3
status := "动量回落"
// 动量回升条件:RSI从低位上升或处于上升趋势
riseCondition1 = rsiValue > rsiPrevious and rsiValue < rsiNeutralLower
riseCondition2 = rsiValue <= rsiOversold and rsiValue > rsiPrevious
riseCondition3 = rsiPrevious <= rsiOversold and rsiValue > rsiOversold and rsiValue > rsiPrevious
if riseCondition1 or riseCondition2 or riseCondition3
status := "动量回升"
// 动量中性条件:RSI在中性区间或无明确趋势
if rsiValue >= rsiNeutralLower and rsiValue <= rsiNeutralUpper
status := "动量中性"
status
rsiStatus = getRSIStatus()
// RSI 信号与其他指标结合
rsiSupportsBuy = rsiStatus == "动量回升" or (rsiValue <= rsiOversold and rsiValue > rsiPrevious)
rsiSupportssell = rsiStatus == "动量回落" or (rsiValue >= rsiOverbought and rsiValue < rsiPrevious)
// === 多时间框架数据获取 ===
// 简化的多时间框架趋势计算
calcSimpleTrend(src) =>
ema21 = ta.ema(src, 21)
ema50 = ta.ema(src, 50)
trend = src > ema21 and ema21 > ema50 ? 1 : src < ema21 and ema21 < ema50 ? -1 : 0
trend
// 获取各时间框架的趋势数据
trend1m = showMTF and mtfEnable1m ? request.security(syminfo.tickerid, "1", calcSimpleTrend(close)) : 0
trend5m = showMTF and mtfEnable5m ? request.security(syminfo.tickerid, "5", calcSimpleTrend(close)) : 0
trend15m = showMTF and mtfEnable15m ? request.security(syminfo.tickerid, "15", calcSimpleTrend(close)) : 0
trend1h = showMTF and mtfEnable1h ? request.security(syminfo.tickerid, "60", calcSimpleTrend(close)) : 0
trend4h = showMTF and mtfEnable4h ? request.security(syminfo.tickerid, "240", calcSimpleTrend(close)) : 0
// === 多时间框架趋势判断函数 ===
getTrendDirection(trend) =>
if trend > 0
"多头倾向"
else if trend < 0
"空头倾向"
else
"震荡"
// 获取各时间框架趋势方向
trend1mDir = getTrendDirection(trend1m)
trend5mDir = getTrendDirection(trend5m)
trend15mDir = getTrendDirection(trend15m)
trend1hDir = getTrendDirection(trend1h)
trend4hDir = getTrendDirection(trend4h)
// === 顶部规避系统 ===
ma_period_top = input.int(10, 'MA Period (Length)', group='8. 顶部规避 设置')
topThreshold = input.int(85, 'VAR顶部阈值', minval=70, maxval=95, step=1, group='8. 顶部规避 设置')
// 计算VAR指标 - 顶部(检测上涨动能)
pre_price_top = close
VAR_top = ta.sma(math.max(close-pre_price_top,0), ma_period_top) / ta.sma(math.abs(close-pre_price_top), ma_period_top) * 100
// 顶部信号 - 当上涨动能达到高位时
isTop = VAR_top > topThreshold and VAR_top <= topThreshold
// 图表显示顶部标记
plotshape(series=showTopAvoidance and isTop, title="顶", style=shape.labeldown, location=location.abovebar,
color=color.new(color.purple, 0), textcolor=color.white, size=size.normal, text="顶")
// === 底部规避系统 ===
ma_period_bottom = input.int(14, 'MA Period (Length)', group='9. 底部规避 设置')
bottomThreshold = input.int(15, 'VAR底部阈值', minval=5, maxval=30, step=1, group='9. 底部规避 设置')
// 计算VAR指标 - 底部(检测下跌动能)
pre_price_bottom = close
VAR_bottom = ta.sma(math.max(pre_price_bottom-close,0), ma_period_bottom) / ta.sma(math.abs(close-pre_price_bottom), ma_period_bottom) * 100
// 底部信号 - 当下跌动能达到高位时
isBottom = VAR_bottom > bottomThreshold and VAR_bottom <= bottomThreshold
// 图表显示底部标记
plotshape(series=showBottomAvoidance and isBottom, title="底", style=shape.labelup, location=location.belowbar,
color=color.new(color.orange, 0), textcolor=color.white, size=size.normal, text="底")
// === 范围过滤器 部分 ===
upColor = color.white
midColor = #90bff9
downColor = color.blue
src = input(defval=close, title="数据源", group="2. 范围过滤器 设置")
per = input.int(defval=100, minval=1, title="采样周期", group="2. 范围过滤器 设置")
mult = input.float(defval=3.0, minval=0.1, title="区间倍数", group="2. 范围过滤器 设置")
smoothrng(x, t, m) =>
wper = t * 2 - 1
avrng = ta.ema(math.abs(x - x ), t)
smoothrng = ta.ema(avrng, wper) * m
smoothrng
smrng = smoothrng(src, per, mult)
rngfilt(x, r) =>
rngfilt = x
rngfilt := x > nz(rngfilt ) ? x - r < nz(rngfilt ) ? nz(rngfilt ) : x - r :
x + r > nz(rngfilt ) ? nz(rngfilt ) : x + r
rngfilt
filt = rngfilt(src, smrng)
upward = 0.0
upward := filt > filt ? nz(upward ) + 1 : filt < filt ? 0 : nz(upward )
downward = 0.0
downward := filt < filt ? nz(downward ) + 1 : filt > filt ? 0 : nz(downward )
hband = filt + smrng
lband = filt - smrng
filtcolor = upward > 0 ? upColor : downward > 0 ? downColor : midColor
barcolor_ = src > filt and src > src and upward > 0 ? upColor :
src > filt and src < src and upward > 0 ? upColor :
src < filt and src < src and downward > 0 ? downColor :
src < filt and src > src and downward > 0 ? downColor : midColor
longCond = bool(na)
shortCond = bool(na)
longCond := src > filt and src > src and upward > 0 or
src > filt and src < src and upward > 0
shortCond := src < filt and src < src and downward > 0 or
src < filt and src > src and downward > 0
CondIni = 0
CondIni := longCond ? 1 : shortCond ? -1 : CondIni
// === ADX 趋势过滤器 部分 ===
adxLength = input.int(defval=14, minval=1, title="ADX 周期", group="3. ADX 趋势过滤器 设置")
adxThreshold = input.float(defval=25.0, minval=0, maxval=100, step=0.5, title="ADX 阈值", tooltip="ADX大于此值才允许交易信号", group="3. ADX 趋势过滤器 设置")
// 简化的ADX计算 - 更准确的方法
calcADX(len) =>
up = ta.change(high)
down = -ta.change(low)
plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
truerange = ta.rma(ta.tr, len)
plus = fixnan(100 * ta.rma(plusDM, len) / truerange)
minus = fixnan(100 * ta.rma(minusDM, len) / truerange)
sum = plus + minus
adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), len)
= calcADX(adxLength)
// ADX状态判断
adxStrong = adxValue >= adxThreshold
adxTrendUp = diPlus > diMinus
adxTrendDown = diMinus > diPlus
// 修改信号生成逻辑,加入顶部和底部规避以及RSI确认
longCondition = longCond and CondIni == -1 and (not showADXFilter or adxStrong) and (not showTopAvoidance or not isTop) and (not showRSI or rsiSupportsBuy)
shortCondition = shortCond and CondIni == 1 and (not showADXFilter or adxStrong) and (not showBottomAvoidance or not isBottom) and (not showRSI or rsiSupportssell)
// === 记录买卖信号价格 ===
var float entryPrice = na
var string entryType = na
var float entryTime = na
// 当出现买入信号时记录
if longCondition
entryPrice := close
entryType := "多单"
entryTime := time
// 当出现卖出信号时记录
if shortCondition
entryPrice := close
entryType := "空单"
entryTime := time
// === 趋势颜色逻辑 ===
var trendColor = color.gray
if longCondition
trendColor := color.green
else if shortCondition
trendColor := color.red
// ADX线绘制(可选)- 已隐藏显示
adxColor = adxStrong ? (adxTrendUp ? color.green : color.red) : color.gray
// plot(showADXLine and showADXFilter ? adxValue : na, title="平均方向指数", color=adxColor, linewidth=1)
// hline(showADXLine and showADXFilter ? adxThreshold : na, title="ADX阈值线", color=color.yellow, linestyle=hline.style_dashed)
// 绘图部分 - 已隐藏线条显示,保留功能
// filtplot = plot(showRangeFilter ? filt : na, color=trendColor, linewidth=2, title="区间过滤器")
// hbandplot = plot(showRangeFilter ? hband : na, color=color.new(trendColor, 30), title="上轨线", linewidth=1)
// lbandplot = plot(showRangeFilter ? lband : na, color=color.new(trendColor, 30), title="下轨线", linewidth=1)
// barcolor(na) - 已隐藏K线颜色
plotshape(showRangeFilter and longCondition, title="买入信号", text="买", textcolor=color.white, style=shape.labelup, size=size.small, location=location.belowbar, color=color.new(color.green, 20))
plotshape(showRangeFilter and shortCondition, title="卖出信号", text="卖", textcolor=color.white, style=shape.labeldown, size=size.small, location=location.abovebar, color=color.new(color.red, 20))
// === 趋势线 部分 ===
length_tl = input.int(14, '分型回溯长度', group="4. 趋势线 设置")
mult_tl = input.float(1., '斜率系数', minval = 0, step = .1, group="4. 趋势线 设置")
calcMethod = input.string('平均真实波幅', '斜率计算方法', options = , group="4. 趋势线 设置")
backpaint = input(true, tooltip = '回溯显示:将可视元素向历史偏移,禁用后可查看实时信号。', group="4. 趋势线 设置")
upCss = input.color(color.teal, '上升趋势线颜色', group = "4. 趋势线 设置")
dnCss = input.color(color.red, '下降趋势线颜色', group = "4. 趋势线 设置")
showExt = input(true, '显示延长线', group="4. 趋势线 设置")
var upper_tl = 0.
var lower_tl = 0.
var slope_ph_tl = 0.
var slope_pl_tl = 0.
var offset_tl = backpaint ? length_tl : 0
n = bar_index
src_tl = close
ph = ta.pivothigh(length_tl, length_tl)
pl = ta.pivotlow(length_tl, length_tl)
slope = switch calcMethod
'平均真实波幅' => ta.atr(length_tl) / length_tl * mult_tl
'标准差' => ta.stdev(src_tl, length_tl) / length_tl * mult_tl
'线性回归' => math.abs(ta.sma(src_tl * n, length_tl) - ta.sma(src_tl, length_tl) * ta.sma(n, length_tl)) / ta.variance(n, length_tl) / 2 * mult_tl
slope_ph_tl := ph ? slope : slope_ph_tl
slope_pl_tl := pl ? slope : slope_pl_tl
upper_tl := ph ? ph : upper_tl - slope_ph_tl
lower_tl := pl ? pl : lower_tl + slope_pl_tl
var upos = 0
var dnos = 0
upos := ph ? 0 : close > upper_tl - slope_ph_tl * length_tl ? 1 : upos
dnos := pl ? 0 : close < lower_tl + slope_pl_tl * length_tl ? 1 : dnos
var uptl = line.new(na,na,na,na, color = upCss, style = line.style_dashed, extend = extend.right)
var dntl = line.new(na,na,na,na, color = dnCss, style = line.style_dashed, extend = extend.right)
if ph and showExt and showTrendLines
line.set_xy1(uptl, n-offset_tl, backpaint ? ph : upper_tl - slope_ph_tl * length_tl)
line.set_xy2(uptl, n-offset_tl+1, backpaint ? ph - slope : upper_tl - slope_ph_tl * (length_tl+1))
if pl and showExt and showTrendLines
line.set_xy1(dntl, n-offset_tl, backpaint ? pl : lower_tl + slope_pl_tl * length_tl)
line.set_xy2(dntl, n-offset_tl+1, backpaint ? pl + slope : lower_tl + slope_pl_tl * (length_tl+1))
plot(showTrendLines ? (backpaint ? upper_tl : upper_tl - slope_ph_tl * length_tl) : na, '上升趋势线', color = ph ? na : upCss, offset = -offset_tl)
plot(showTrendLines ? (backpaint ? lower_tl : lower_tl + slope_pl_tl * length_tl) : na, '下降趋势线', color = pl ? na : dnCss, offset = -offset_tl)
// 趋势线突破也需要ADX确认,并加入顶部和底部规避以及RSI确认
trendLineBuySignal = showTrendLines and upos > upos and (not showADXFilter or adxStrong) and (not showTopAvoidance or not isTop) and (not showRSI or rsiSupportsBuy)
trendLineSellSignal = showTrendLines and dnos > dnos and (not showADXFilter or adxStrong) and (not showBottomAvoidance or not isBottom) and (not showRSI or rsiSupportssell)
plotshape(trendLineBuySignal ? low : na, "上轨突破"
, shape.labelup
, location.absolute
, upCss
, text = "突"
, textcolor = color.white
, size = size.tiny)
plotshape(trendLineSellSignal ? high : na, "下轨突破"
, shape.labeldown
, location.absolute
, dnCss
, text = "突"
, textcolor = color.white
, size = size.tiny)
alertcondition(trendLineBuySignal, '上轨突破', '价格向上突破下趋势线')
alertcondition(trendLineSellSignal, '下轨突破', '价格向下突破上趋势线')
// === 支撑与阻力 部分 ===
g_sr = '5. 支撑与阻力'
g_c = '条件'
g_st = '样式'
t_r = 'K线确认:仅在K线收盘时生成警报(延后1根K线)。\n\n高点与低点:默认情况下,突破/回踩系统使用当前收盘价判断,选择高点与低点后将使用高低点判断条件,不再重绘,结果会不同。'
t_rv = '每当检测到潜在回踩时,指标会判断回踩事件即将发生。此输入用于设置在潜在回踩激活时,最大允许检测多少根K线。\n\n例如,出现潜在回踩标签时,该标签允许存在多少根K线以确认回踩?此功能防止回踩警报在10根K线后才触发导致不准确。'
input_lookback = input.int(defval = 20, title = '回溯区间', minval = 1, tooltip = '检测分型事件的K线数量。', group = g_sr)
input_retSince = input.int(defval = 2, title = '突破后K线数', minval = 1, tooltip = '突破后多少根K线内检测回踩。', group = g_sr)
input_retValid = input.int(defval = 2, title = '回踩检测限制', minval = 1, tooltip = t_rv, group = g_sr)
input_breakout = input.bool(defval = true, title = '显示突破', group = g_c)
input_retest = input.bool(defval = true, title = '显示回踩', group = g_c)
input_repType = input.string(defval = '开启', title = '重绘模式', options = , tooltip = t_r, group = g_c)
input_outL = input.string(defval = line.style_dotted, title = '边框样式', group = g_st, options = )
input_extend = input.string(defval = extend.none, title = '延长方向', group = g_st, options = )
input_labelType = input.string(defval = '详细', title = '标签类型', options = , group = g_st)
input_labelSize = input.string(defval = size.small, title = '标签大小', options = , group = g_st)
st_break_lb_co1 = input.color(defval = color.lime , title = '空头突破标签颜色' ,inline = 'st_break_lb_co', group = g_st)
st_break_lb_co2 = input.color(defval = color.new(color.lime,40) , title = '' ,inline = 'st_break_lb_co', group = g_st)
lg_break_lb_co1 = input.color(defval = color.red , title = '多头突破标签颜色' ,inline = 'lg_break_lb_co', group = g_st)
lg_break_lb_co2 = input.color(defval = color.new(color.red,40) , title = '' ,inline = 'lg_break_lb_co', group = g_st)
st_retest_lb_co1 = input.color(defval = color.lime , title = '空头回踩标签颜色' ,inline = 'st_retest_lb_col', group = g_st)
st_retest_lb_co2 = input.color(defval = color.new(color.lime,40) , title = '' ,inline = 'st_retest_lb_col', group = g_st)
lg_retest_lb_co1 = input.color(defval = color.red , title = '多头回踩标签颜色' ,inline = 'lg_retest_lb_co', group = g_st)
lg_retest_lb_co2 = input.color(defval = color.new(color.red,40) , title = '' ,inline = 'lg_retest_lb_co', group = g_st)
input_plColor1 = input.color(defval = color.lime, title = '支撑方框颜色', inline = 'pl_Color', group = g_st)
input_plColor2 = input.color(defval = color.new(color.lime,85), title = '', inline = 'pl_Color', group = g_st)
input_phColor1 = input.color(defval = color.red, title = '阻力方框颜色', inline = 'ph_Color', group = g_st)
input_phColor2 = input.color(defval = color.new(color.red,85), title = '', inline = 'ph_Color', group = g_st)
input_override = input.bool(defval = false, title = '自定义文字颜色', inline = '覆盖', group = g_st)
input_textColor = input.color(defval = color.white, title = '', inline = '覆盖', group = g_st)
bb = input_lookback
// 兼容label与英文选项
rTon = input_repType == '开启'
rTcc = input_repType == '关闭:K线确认'
rThv = input_repType == '关闭:高低点'
breakText = input_labelType == '简洁' ? '突' : '突破'
// 分型
rs_pl = fixnan(ta.pivotlow(low, bb, bb))
rs_ph = fixnan(ta.pivothigh(high, bb, bb))
// Box 高度
s_yLoc = low > low ? low : low
r_yLoc = high > high ? high : high
//-----------------------------------------------------------------------------
// 函数
//-----------------------------------------------------------------------------
drawBox(condition, y1, y2, color,bgcolor) =>
var box drawBox = na
if condition and showSupRes // 仅在显示开关打开时绘制
box.set_right(drawBox, bar_index - bb)
drawBox.set_extend(extend.none)
drawBox := box.new(bar_index - bb, y1, bar_index, y2, color, bgcolor = bgcolor, border_style = input_outL, extend = input_extend)
updateBox(box) =>
if barstate.isconfirmed and showSupRes
box.set_right(box, bar_index + 5)
breakLabel(y, txt_col,lb_col, style, textform) =>
if showSupRes
label.new(bar_index, y, textform, textcolor = input_override ? input_textColor : txt_col, style = style, color = lb_col, size = input_labelSize)
retestCondition(breakout, condition) =>
ta.barssince(na(breakout)) > input_retSince and condition
repaint(c1, c2, c3) => rTon ? c1 : rThv ? c2 : rTcc ? c3 : na
//-----------------------------------------------------------------------------
// 绘制与更新区间
//-----------------------------------------------------------------------------
= drawBox(ta.change(rs_pl), s_yLoc, rs_pl, input_plColor1,input_plColor2)
= drawBox(ta.change(rs_ph), rs_ph, r_yLoc, input_phColor1,input_phColor2)
sTop = box.get_top(sBox), rTop = box.get_top(rBox)
sBot = box.get_bottom(sBox), rBot = box.get_bottom(rBox)
if showSupRes
updateBox(sBox), updateBox(rBox)
//-----------------------------------------------------------------------------
// 突破事件 - 加入顶部和底部规避以及RSI确认
//-----------------------------------------------------------------------------
var bool sBreak = na
var bool rBreak = na
cu = repaint(ta.crossunder(close, box.get_bottom(sBox)), ta.crossunder(low, box.get_bottom(sBox)), ta.crossunder(close, box.get_bottom(sBox)) and barstate.isconfirmed)
co = repaint(ta.crossover(close, box.get_top(rBox)), ta.crossover(high, box.get_top(rBox)), ta.crossover(close, box.get_top(rBox)) and barstate.isconfirmed)
switch
cu and na(sBreak) and showSupRes and (not showADXFilter or adxStrong) and (not showBottomAvoidance or not isBottom) and (not showRSI or rsiSupportssell) =>
sBreak := true
if input_breakout
breakLabel(sBot, st_break_lb_co1,st_break_lb_co2, label.style_label_upper_right, breakText)
co and na(rBreak) and showSupRes and (not showADXFilter or adxStrong) and (not showTopAvoidance or not isTop) and (not showRSI or rsiSupportsBuy) =>
rBreak := true
if input_breakout
breakLabel(rTop, lg_break_lb_co1,lg_break_lb_co2, label.style_label_lower_right, breakText)
if ta.change(rs_pl) and showSupRes
if na(sBreak)
box.delete(sBox )
sBreak := na
if ta.change(rs_ph) and showSupRes
if na(rBreak)
box.delete(rBox )
rBreak := na
//-----------------------------------------------------------------------------
// 回踩事件
//-----------------------------------------------------------------------------
s1 = retestCondition(sBreak, high >= sTop and close <= sBot)
s2 = retestCondition(sBreak, high >= sTop and close >= sBot and close <= sTop)
s3 = retestCondition(sBreak, high >= sBot and high <= sTop)
s4 = retestCondition(sBreak, high >= sBot and high <= sTop and close < sBot)
r1 = retestCondition(rBreak, low <= rBot and close >= rTop)
r2 = retestCondition(rBreak, low <= rBot and close <= rTop and close >= rBot)
r3 = retestCondition(rBreak, low <= rTop and low >= rBot)
r4 = retestCondition(rBreak, low <= rTop and low >= rBot and close > rTop)
retestEvent(c1, c2, c3, c4, y1, y2, txt_col,lb_col, style, pType) =>
if input_retest and showSupRes
var bool retOccurred = na
retActive = c1 or c2 or c3 or c4
retEvent = retActive and not retActive
retValue = ta.valuewhen(retEvent, y1, 0)
if pType == 'ph' ? y2 < ta.valuewhen(retEvent, y2, 0) : y2 > ta.valuewhen(retEvent, y2, 0)
retEvent := retActive
retValue := ta.valuewhen(retEvent, y1, 0)
retSince = ta.barssince(retEvent)
var retLabel = array.new()
if retEvent
retOccurred := na
array.push(retLabel, label.new(bar_index - retSince, y2 , text = input_labelType == '简洁' ? '潜回' : '潜在回踩', color = lb_col, style = style, textcolor = input_override ? input_textColor : txt_col, size = input_labelSize))
if array.size(retLabel) == 2
label.delete(array.first(retLabel))
array.shift(retLabel)
retConditions = pType == 'ph' ? repaint(close >= retValue, high >= retValue, close >= retValue and barstate.isconfirmed) : repaint(close <= retValue, low <= retValue, close <= retValue and barstate.isconfirmed)
retValid = ta.barssince(retEvent) > 0 and ta.barssince(retEvent) <= input_retValid and retConditions and not retOccurred and (not showADXFilter or adxStrong) and (not showRSI or (pType == 'ph' ? rsiSupportsBuy : rsiSupportssell))
if retValid
label.new(bar_index - retSince, y2 , text = input_labelType == '简洁' ? '回' : '回踩', color = lb_col, style = style, textcolor = input_override ? input_textColor : txt_col, size = input_labelSize)
retOccurred := true
if retValid or ta.barssince(retEvent) > input_retValid
label.delete(array.first(retLabel))
if pType == 'ph' and ta.change(rs_ph) and retOccurred
box.set_right(rBox , bar_index - retSince)
retOccurred := na
if pType == 'pl' and ta.change(rs_pl) and retOccurred
box.set_right(sBox , bar_index - retSince)
retOccurred := na
else
= retestEvent(r1, r2, r3, r4, high, low, lg_retest_lb_co1,lg_retest_lb_co2, label.style_label_upper_left, 'ph')
= retestEvent(s1, s2, s3, s4, low, high, st_retest_lb_co1,st_retest_lb_co2, label.style_label_lower_left, 'pl')
//-----------------------------------------------------------------------------
// 警报
//-----------------------------------------------------------------------------
// 买卖信号警报条件
buySignal = showTrendLines and trendLineBuySignal
sellSignal = showTrendLines and trendLineSellSignal
// 添加买卖信号的警报条件
alertcondition(buySignal, title='买入信号', message='范围过滤器买入信号:上轨突破')
alertcondition(sellSignal, title='卖出信号', message='范围过滤器卖出信号:下轨突破')
alertcondition((showSupRes and ta.change(rs_pl)), '新支撑位')
alertcondition((showSupRes and ta.change(rs_ph)), '新阻力位')
alertcondition((showSupRes and ta.barssince(na(sBreak)) == 1), '支撑位突破')
alertcondition((showSupRes and ta.barssince(na(rBreak)) == 1), '阻力位突破')
alertcondition((showSupRes and sRetValid), '支撑位回踩')
alertcondition((showSupRes and sRetEvent), '潜在支撑回踩')
alertcondition((showSupRes and rRetValid), '阻力位回踩')
alertcondition((showSupRes and rRetEvent), '潜在阻力回踩')
AllAlerts(condition, message) =>
if condition and showSupRes
alert(message)
AllAlerts(ta.change(rs_pl), '新支撑位')
AllAlerts(ta.change(rs_ph), '新阻力位')
AllAlerts(ta.barssince(na(sBreak)) == 1, '支撑位突破')
AllAlerts(ta.barssince(na(rBreak)) == 1, '阻力位突破')
AllAlerts(sRetValid, '支撑位回踩')
AllAlerts(sRetEvent, '潜在支撑回踩')
AllAlerts(rRetValid, '阻力位回踩')
AllAlerts(rRetEvent, '潜在阻力回踩')
AllAlerts(buySignal, '买入信号:上轨突破')
AllAlerts(sellSignal, '卖出信号:下轨突破')
// === 多周期移动平均线 部分 ===
// === 公共函数 ===
strRoundValue(num) =>
strv = ''
if num >= 100000
strv := str.tostring(num/1000, '#千')
else if (num < 100000) and (num >= 100)
strv := str.tostring(num, '#')
else if (num < 100) and (num >= 1)
strv := str.tostring(num, '#.##')
else if (num < 1) and (num >= 0.01)
strv := str.tostring(num, '#.####')
else if (num < 0.01) and (num >= 0.0001)
strv := str.tostring(num, '#.######')
else if (num < 0.0001) and (num >= 0.000001)
strv := str.tostring(num, '#.########')
(strv)
defaultFunction(func, src, len, alma_offst, alma_sigma) =>
has_len = false
ma = ta.swma(close)
if func == '自适应移动平均'
ma := ta.alma(src, len, alma_offst, alma_sigma)
has_len := true
else if func == '指数移动平均'
ma := ta.ema(src, len)
has_len := true
else if func == '修正移动平均'
ma := ta.rma(src, len)
has_len := true
else if func == '简单移动平均'
ma := ta.sma(src, len)
has_len := true
else if func == '对称加权移动平均'
ma := ta.swma(src)
has_len := false
else if func == '成交量加权平均价'
ma := ta.vwap(src)
has_len := false
else if func == '成交量加权移动平均'
ma := ta.vwma(src, len)
has_len := true
else if func == '加权移动平均'
ma := ta.wma(src, len)
has_len := true
def_fn = input.string(title='默认移动平均线', defval='指数移动平均', options= , group="6. PMA 设置")
ma1_on = input.bool(inline='均线1', title='启用移动平均线1', defval=false, group="6. PMA 设置")
ma2_on = input.bool(inline='均线2', title='启用移动平均线2', defval=true, group="6. PMA 设置")
ma3_on = input.bool(inline='均线3', title='启用移动平均线3', defval=true, group="6. PMA 设置")
ma4_on = input.bool(inline='均线4', title='启用移动平均线4', defval=true, group="6. PMA 设置")
ma5_on = input.bool(inline='均线5', title='启用移动平均线5', defval=true, group="6. PMA 设置")
ma6_on = input.bool(inline='均线6', title='启用移动平均线6', defval=true, group="6. PMA 设置")
ma7_on = input.bool(inline='均线7', title='启用移动平均线7', defval=true, group="6. PMA 设置")
ma1_fn = input.string(inline='均线1', title='', defval='默认', options= , group="6. PMA 设置")
ma2_fn = input.string(inline='均线2', title='', defval='默认', options= , group="6. PMA 设置")
ma3_fn = input.string(inline='均线3', title='', defval='默认', options= , group="6. PMA 设置")
ma4_fn = input.string(inline='均线4', title='', defval='默认', options= , group="6. PMA 设置")
ma5_fn = input.string(inline='均线5', title='', defval='默认', options= , group="6. PMA 设置")
ma6_fn = input.string(inline='均线6', title='', defval='默认', options= , group="6. PMA 设置")
ma7_fn = input.string(inline='均线7', title='', defval='默认', options= , group="6. PMA 设置")
ma1_len = input.int(inline='均线1', title='', defval=12, minval=1, group="6. PMA 设置")
ma2_len = input.int(inline='均线2', title='', defval=144, minval=1, group="6. PMA 设置")
ma3_len = input.int(inline='均线3', title='', defval=169, minval=1, group="6. PMA 设置")
ma4_len = input.int(inline='均线4', title='', defval=288, minval=1, group="6. PMA 设置")
ma5_len = input.int(inline='均线5', title='', defval=338, minval=1, group="6. PMA 设置")
ma6_len = input.int(inline='均线6', title='', defval=576, minval=1, group="6. PMA 设置")
ma7_len = input.int(inline='均线7', title='', defval=676, minval=1, group="6. PMA 设置")
alma1_offst = input.float(group='均线1其他设置', inline='均线11', title='自适应偏移', defval=0.85, minval=-1, maxval=1, step=0.01)
alma1_sigma = input.float(group='均线1其他设置', inline='均线11', title=', 西格玛', defval=6, minval=0, maxval=100, step=0.01)
ma1_src = input.source(group='均线1其他设置', inline='均线12', title='数据源', defval=close)
ma1_plt_offst = input.int(group='均线1其他设置', inline='均线12', title=', 绘图偏移', defval=0, minval=-500, maxval=500)
alma2_offst = input.float(group='均线2其他设置', inline='均线21', title='自适应偏移', defval=0.85, minval=-1, maxval=1, step=0.01)
alma2_sigma = input.float(group='均线2其他设置', inline='均线21', title='西格玛', defval=6, minval=0, maxval=100, step=0.01)
ma2_src = input.source(group='均线2其他设置', inline='均线22', title='数据源', defval=close)
ma2_plt_offst = input.int(group='均线2其他设置', inline='均线22', title='绘图偏移', defval=0, minval=-500, maxval=500)
alma3_offst = input.float(group='均线3其他设置', inline='均线31', title='自适应偏移', defval=0.85, minval=-1, maxval=1, step=0.01)
alma3_sigma = input.float(group='均线3其他设置', inline='均线31', title='西格玛', defval=6, minval=0, maxval=100, step=0.01)
ma3_src = input.source(group='均线3其他设置', inline='均线32', title='数据源', defval=close)
ma3_plt_offst = input.int(group='均线3其他设置', inline='均线32', title='绘图偏移', defval=0, minval=-500, maxval=500)
alma4_offst = input.float(group='均线4其他设置', inline='均线41', title='自适应偏移', defval=0.85, minval=-1, maxval=1, step=0.01)
alma4_sigma = input.float(group='均线4其他设置', inline='均线41', title='西格玛', defval=6, minval=0, maxval=100, step=0.01)
ma4_src = input.source(group='均线4其他设置', inline='均线42', title='数据源', defval=close)
ma4_plt_offst = input.int(group='均线4其他设置', inline='均线42', title='绘图偏移', defval=0, minval=-500, maxval=500)
alma5_offst = input.float(group='均线5其他设置', inline='均线51', title='自适应偏移', defval=0.85, minval=-1, maxval=1, step=0.01)
alma5_sigma = input.float(group='均线5其他设置', inline='均线51', title='西格玛', defval=6, minval=0, maxval=100, step=0.01)
ma5_src = input.source(group='均线5其他设置', inline='均线52', title='数据源', defval=close)
ma5_plt_offst = input.int(group='均线5其他设置', inline='均线52', title='绘图偏移', defval=0, minval=-500, maxval=500)
alma6_offst = input.float(group='均线6其他设置', inline='均线61', title='自适应偏移', defval=0.85, minval=-1, maxval=1, step=0.01)
alma6_sigma = input.float(group='均线6其他设置', inline='均线61', title='西格玛', defval=6, minval=0, maxval=100, step=0.01)
ma6_src = input.source(group='均线6其他设置', inline='均线62', title='数据源', defval=close)
ma6_plt_offst = input.int(group='均线6其他设置', inline='均线62', title='绘图偏移', defval=0, minval=-500, maxval=500)
alma7_offst = input.float(group='均线7其他设置', inline='均线71', title='自适应偏移', defval=0.85, minval=-1, maxval=1, step=0.01)
alma7_sigma = input.float(group='均线7其他设置', inline='均线71', title='西格玛', defval=6, minval=0, maxval=100, step=0.01)
ma7_src = input.source(group='均线7其他设置', inline='均线72', title='数据源', defval=close)
ma7_plt_offst = input.int(group='均线7其他设置', inline='均线72', title='绘图偏移', defval=0, minval=-500, maxval=500)
fill_12_on = input.bool(title='启用均线1-2填充', defval=false, group="6. PMA 设置")
fill_23_on = input.bool(title='启用均线2-3填充', defval=true, group="6. PMA 设置")
fill_34_on = input.bool(title='启用均线3-4填充', defval=false, group="6. PMA 设置")
fill_45_on = input.bool(title='启用均线4-5填充', defval=true, group="6. PMA 设置")
fill_56_on = input.bool(title='启用均线5-6填充', defval=false, group="6. PMA 设置")
fill_67_on = input.bool(title='启用均线6-7填充', defval=true, group="6. PMA 设置")
// === 计算移动平均线 ===
= defaultFunction(def_fn, ma1_src, ma1_len, alma1_offst, alma1_sigma)
= defaultFunction(def_fn, ma2_src, ma2_len, alma2_offst, alma2_sigma)
= defaultFunction(def_fn, ma3_src, ma3_len, alma3_offst, alma3_sigma)
= defaultFunction(def_fn, ma4_src, ma4_len, alma4_offst, alma4_sigma)
= defaultFunction(def_fn, ma5_src, ma5_len, alma5_offst, alma5_sigma)
= defaultFunction(def_fn, ma6_src, ma6_len, alma6_offst, alma6_sigma)
= defaultFunction(def_fn, ma7_src, ma7_len, alma7_offst, alma7_sigma)
// === 均线类型切换 ===
if ma1_fn != '默认'
if ma1_fn == '自适应移动平均'
ma1 := ta.alma(ma1_src, ma1_len, alma1_offst, alma1_sigma)
ma1_has_len := true
else if ma1_fn == '指数移动平均'
ma1 := ta.ema(ma1_src, ma1_len)
ma1_has_len := true
else if ma1_fn == '修正移动平均'
ma1 := ta.rma(ma1_src, ma1_len)
ma1_has_len := true
else if ma1_fn == '简单移动平均'
ma1 := ta.sma(ma1_src, ma1_len)
ma1_has_len := true
else if ma1_fn == '对称加权移动平均'
ma1 := ta.swma(ma1_src)
ma1_has_len := false
else if ma1_fn == '成交量加权平均价'
ma1 := ta.vwap(ma1_src)
ma1_has_len := false
else if ma1_fn == '成交量加权移动平均'
ma1 := ta.vwma(ma1_src, ma1_len)
ma1_has_len := true
else if ma1_fn == '加权移动平均'
ma1 := ta.wma(ma1_src, ma1_len)
ma1_has_len := true
if ma2_fn != '默认'
if ma2_fn == '自适应移动平均'
ma2 := ta.alma(ma2_src, ma2_len, alma2_offst, alma2_sigma)
ma2_has_len := true
else if ma2_fn == '指数移动平均'
ma2 := ta.ema(ma2_src, ma2_len)
ma2_has_len := true
else if ma2_fn == '修正移动平均'
ma2 := ta.rma(ma2_src, ma2_len)
ma2_has_len := true
else if ma2_fn == '简单移动平均'
ma2 := ta.sma(ma2_src, ma2_len)
ma2_has_len := true
else if ma2_fn == '对称加权移动平均'
ma2 := ta.swma(ma2_src)
ma2_has_len := false
else if ma2_fn == '成交量加权平均价'
ma2 := ta.vwap(ma2_src)
ma2_has_len := false
else if ma2_fn == '成交量加权移动平均'
ma2 := ta.vwma(ma2_src, ma2_len)
ma2_has_len := true
else if ma2_fn == '加权移动平均'
ma2 := ta.wma(ma2_src, ma2_len)
ma2_has_len := true
if ma3_fn != '默认'
if ma3_fn == '自适应移动平均'
ma3 := ta.alma(ma3_src, ma3_len, alma3_offst, alma3_sigma)
ma3_has_len := true
else if ma3_fn == '指数移动平均'
ma3 := ta.ema(ma3_src, ma3_len)
ma3_has_len := true
else if ma3_fn == '修正移动平均'
ma3 := ta.rma(ma3_src, ma3_len)
ma3_has_len := true
else if ma3_fn == '简单移动平均'
ma3 := ta.sma(ma3_src, ma3_len)
ma3_has_len := true
else if ma3_fn == '对称加权移动平均'
ma3 := ta.swma(ma3_src)
ma3_has_len := false
else if ma3_fn == '成交量加权平均价'
ma3 := ta.vwap(ma3_src)
ma3_has_len := false
else if ma3_fn == '成交量加权移动平均'
ma3 := ta.vwma(ma3_src, ma3_len)
ma3_has_len := true
else if ma3_fn == '加权移动平均'
ma3 := ta.wma(ma3_src, ma3_len)
ma3_has_len := true
if ma4_fn != '默认'
if ma4_fn == '自适应移动平均'
ma4 := ta.alma(ma4_src, ma4_len, alma4_offst, alma4_sigma)
ma4_has_len := true
else if ma4_fn == '指数移动平均'
ma4 := ta.ema(ma4_src, ma4_len)
ma4_has_len := true
else if ma4_fn == '修正移动平均'
ma4 := ta.rma(ma4_src, ma4_len)
ma4_has_len := true
else if ma4_fn == '简单移动平均'
ma4 := ta.sma(ma4_src, ma4_len)
ma4_has_len := true
else if ma4_fn == '对称加权移动平均'
ma4 := ta.swma(ma4_src)
ma4_has_len := false
else if ma4_fn == '成交量加权平均价'
ma4 := ta.vwap(ma4_src)
ma4_has_len := false
else if ma4_fn == '成交量加权移动平均'
ma4 := ta.vwma(ma4_src, ma4_len)
ma4_has_len := true
else if ma4_fn == '加权移动平均'
ma4 := ta.wma(ma4_src, ma4_len)
ma4_has_len := true
if ma5_fn != '默认'
if ma5_fn == '自适应移动平均'
ma5 := ta.alma(ma5_src, ma5_len, alma5_offst, alma5_sigma)
ma5_has_len := true
else if ma5_fn == '指数移动平均'
ma5 := ta.ema(ma5_src, ma5_len)
ma5_has_len := true
else if ma5_fn == '修正移动平均'
ma5 := ta.rma(ma5_src, ma5_len)
ma5_has_len := true
else if ma5_fn == '简单移动平均'
ma5 := ta.sma(ma5_src, ma5_len)
ma5_has_len := true
else if ma5_fn == '对称加权移动平均'
ma5 := ta.swma(ma5_src)
ma5_has_len := false
else if ma5_fn == '成交量加权平均价'
ma5 := ta.vwap(ma5_src)
ma5_has_len := false
else if ma5_fn == '成交量加权移动平均'
ma5 := ta.vwma(ma5_src, ma5_len)
ma5_has_len := true
else if ma5_fn == '加权移动平均'
ma5 := ta.wma(ma5_src, ma5_len)
ma5_has_len := true
if ma6_fn != '默认'
if ma6_fn == '自适应移动平均'
ma6 := ta.alma(ma6_src, ma6_len, alma6_offst, alma6_sigma)
ma6_has_len := true
else if ma6_fn == '指数移动平均'
ma6 := ta.ema(ma6_src, ma6_len)
ma6_has_len := true
else if ma6_fn == '修正移动平均'
ma6 := ta.rma(ma6_src, ma6_len)
ma6_has_len := true
else if ma6_fn == '简单移动平均'
ma6 := ta.sma(ma6_src, ma6_len)
ma6_has_len := true
else if ma6_fn == '对称加权移动平均'
ma6 := ta.swma(ma6_src)
ma6_has_len := false
else if ma6_fn == '成交量加权平均价'
ma6 := ta.vwap(ma6_src)
ma6_has_len := false
else if ma6_fn == '成交量加权移动平均'
ma6 := ta.vwma(ma6_src, ma6_len)
ma6_has_len := true
else if ma6_fn == '加权移动平均'
ma6 := ta.wma(ma6_src, ma6_len)
ma6_has_len := true
if ma7_fn != '默认'
if ma7_fn == '自适应移动平均'
ma7 := ta.alma(ma7_src, ma7_len, alma7_offst, alma7_sigma)
ma7_has_len := true
else if ma7_fn == '指数移动平均'
ma7 := ta.ema(ma7_src, ma7_len)
ma7_has_len := true
else if ma7_fn == '修正移动平均'
ma7 := ta.rma(ma7_src, ma7_len)
ma7_has_len := true
else if ma7_fn == '简单移动平均'
ma7 := ta.sma(ma7_src, ma7_len)
ma7_has_len := true
else if ma7_fn == '对称加权移动平均'
ma7 := ta.swma(ma7_src)
ma7_has_len := false
else if ma7_fn == '成交量加权平均价'
ma7 := ta.vwap(ma7_src)
ma7_has_len := false
else if ma7_fn == '成交量加权移动平均'
ma7 := ta.vwma(ma7_src, ma7_len)
ma7_has_len := true
else if ma7_fn == '加权移动平均'
ma7 := ta.wma(ma7_src, ma7_len)
ma7_has_len := true
// === 均线颜色 ===
ma1_clr = color.new(color.fuchsia, 0)
ma2_clr = color.new(color.aqua, 0)
ma3_clr = color.new(color.yellow, 0)
ma4_clr = color.new(color.blue, 0)
ma5_clr = color.new(color.orange, 0)
ma6_clr = color.new(color.green, 0)
ma7_clr = color.new(color.red, 0)
// === 均线全局绘图 ===
p1 = plot(series=showPMA and ma1_on ? ma1 : na, title="均线1", color=ma1_clr, trackprice=false, offset=ma1_plt_offst, linewidth=2)
p2 = plot(series=showPMA and ma2_on ? ma2 : na, title="均线2", color=ma2_clr, trackprice=false, offset=ma2_plt_offst, linewidth=2)
p3 = plot(series=showPMA and ma3_on ? ma3 : na, title="均线3", color=ma3_clr, trackprice=false, offset=ma3_plt_offst, linewidth=2)
p4 = plot(series=showPMA and ma4_on ? ma4 : na, title="均线4", color=ma4_clr, trackprice=false, offset=ma4_plt_offst, linewidth=2)
p5 = plot(series=showPMA and ma5_on ? ma5 : na, title="均线5", color=ma5_clr, trackprice=false, offset=ma5_plt_offst, linewidth=2)
p6 = plot(series=showPMA and ma6_on ? ma6 : na, title="均线6", color=ma6_clr, trackprice=false, offset=ma6_plt_offst, linewidth=2)
p7 = plot(series=showPMA and ma7_on ? ma7 : na, title="均线7", color=ma7_clr, trackprice=false, offset=ma7_plt_offst, linewidth=2)
// === 多周期移动平均线 填充渲染 ===
fill(p1, p2, color=showPMA and ma1_on and ma2_on and fill_12_on ? color.new(color.purple, 70) : na, title="均线1-2填充")
fill(p2, p3, color=showPMA and ma2_on and ma3_on and fill_23_on ? color.new(color.blue, 70) : na, title="均线2-3填充")
fill(p3, p4, color=showPMA and ma3_on and ma4_on and fill_34_on ? color.new(color.teal, 70) : na, title="均线3-4填充")
fill(p4, p5, color=showPMA and ma4_on and ma5_on and fill_45_on ? color.new(color.green, 70) : na, title="均线4-5填充")
fill(p5, p6, color=showPMA and ma5_on and ma6_on and fill_56_on ? color.new(color.yellow, 70) : na, title="均线5-6填充")
fill(p6, p7, color=showPMA and ma6_on and ma7_on and fill_67_on ? color.new(color.orange, 70) : na, title="均线6-7填充")
// === 交易信息表格 部分 ===
// 表格参数设置 - 修改默认大小为中等
tablePos = input.string("右上角", title="表格位置", options= , group="7. 交易信息表格 设置")
tableSize = input.string("中等", title="表格大小", options= , group="7. 交易信息表格 设置")
showTargets = input.bool(true, title="显示止盈目标", group="7. 交易信息表格 设置")
showRatio = input.bool(true, title="显示盈亏比", group="7. 交易信息表格 设置")
// 辅助函数
getTablePosition() =>
switch tablePos
"右上角" => position.top_right
"右下角" => position.bottom_right
"左上角" => position.top_left
"左下角" => position.bottom_left
getTableSize() =>
switch tableSize
"小" => size.small
"中等" => size.normal
"大" => size.large
formatPrice(price) =>
if na(price)
"N/A"
else
str.tostring(price, "#.####")
calcStopLossPercentage(entryPrice, stopLoss, entryType) =>
if na(entryPrice) or na(stopLoss) or na(entryType)
""
else
pct = 0.0
if entryType == "多单"
pct := (stopLoss - entryPrice) / entryPrice * 100
else if entryType == "空单"
pct := (entryPrice - stopLoss) / entryPrice * 100
" (" + str.tostring(pct, "#.##") + "%)"
calcTakeProfitPercentage(entryPrice, takeProfit, entryType) =>
if na(entryPrice) or na(takeProfit) or na(entryType)
""
else
pct = 0.0
if entryType == "多单"
pct := (takeProfit - entryPrice) / entryPrice * 100
else if entryType == "空单"
pct := (entryPrice - takeProfit) / entryPrice * 100
" (+" + str.tostring(pct, "#.##") + "%)"
calcUnrealizedPnL(entryPrice, currentPrice, entryType) =>
if na(entryPrice) or na(currentPrice) or na(entryType)
""
else
priceDiff = currentPrice - entryPrice
pct = (currentPrice - entryPrice) / entryPrice * 100
if entryType == "多单"
if pct > 0
" (" + formatPrice(priceDiff) + ", +" + str.tostring(pct, "#.##") + "%)"
else
" (" + formatPrice(priceDiff) + ", " + str.tostring(pct, "#.##") + "%)"
else if entryType == "空单"
// 对于空单,价差符号相反
if pct < 0
" (" + formatPrice(-priceDiff) + ", +" + str.tostring(-pct, "#.##") + "%)"
else
" (" + formatPrice(-priceDiff) + ", " + str.tostring(-pct, "#.##") + "%)"
else
""
// RSI状态颜色函数
getRSIStatusColor() =>
switch rsiStatus
"动量回升" => // 绿色
"动量回落" => // 红色
"动量中性" => // 黄色
=> // 默认灰色
// 多时间框架趋势颜色函数
getTrendColor(trendDirection) =>
switch trendDirection
"多头倾向" => // 绿色
"空头倾向" => // 红色
"震荡" => // 黄色
=> // 默认灰色
// === 蓝紫科幻风格表格 ===
// 创建蓝紫色主题的表格
var infoTable = table.new(getTablePosition(), columns=2, rows=26,
bgcolor=color.new(#0f0a1a, 5),
border_width=3,
border_color=color.new(#6633ff, 40),
frame_width=2,
frame_color=color.new(#9966ff, 30))
if showTable and barstate.islast
// 确定止盈止损位
var float stopLoss = na
var float takeProfit1 = na
var float takeProfit2 = na
if not na(entryType)
if entryType == "多单"
stopLoss := na(sBot) ? entryPrice * 0.98 : sBot
takeProfit1 := na(rTop) ? entryPrice * 1.02 : rTop
takeProfit2 := entryPrice * 1.05
else if entryType == "空单"
stopLoss := na(rTop) ? entryPrice * 1.02 : rTop
takeProfit1 := na(sBot) ? entryPrice * 0.98 : sBot
takeProfit2 := entryPrice * 0.95
// 计算盈亏比
riskRewardRatio = na(entryPrice) or na(stopLoss) or na(takeProfit1) ? na :
math.abs(takeProfit1 - entryPrice) / math.abs(entryPrice - stopLoss)
riskRewardStr = na(riskRewardRatio) ? "N/A" : "1:" + str.tostring(riskRewardRatio, "#.##")
rowIndex = 0
// === 作者联系信息行 - 最顶部,大字体 ===
table.cell(infoTable, 0, rowIndex, "合作联系作者", text_color=color.new(#ffcc99, 0),
text_size=size.normal, bgcolor=color.new(#1a1a0d, 0))
table.cell(infoTable, 1, rowIndex, "qq2390107445", text_color=color.new(#66ff99, 0),
text_size=size.normal, bgcolor=color.new(#0d2619, 0))
rowIndex += 1
// === 表格标题行 - 蓝紫主题 ===
table.cell(infoTable, 0, rowIndex, "⚡ P6●智能资金概念交易系统", text_color=color.new(#ccccff, 0),
text_size=getTableSize(), bgcolor=color.new(#1a0d33, 0))
table.cell(infoTable, 1, rowIndex, "『" + syminfo.ticker + "』", text_color=color.new(#9966ff, 0),
text_size=size.normal, bgcolor=color.new(#1a0d33, 0))
rowIndex += 1
// === 当前价格与浮盈浮亏行 - 蓝紫主题 ===
unrealizedPnL = calcUnrealizedPnL(entryPrice, close, entryType)
// 浮盈浮亏颜色逻辑
pnlColor = color.new(#ccccff, 0)
pnlBgColor = color.new(#0d0d1a, 0)
if not na(entryPrice)
if entryType == "多单"
if close > entryPrice
pnlColor := color.new(#66ff99, 0)
pnlBgColor := color.new(#0d2619, 0)
else
pnlColor := color.new(#ff6699, 0)
pnlBgColor := color.new(#260d19, 0)
else if entryType == "空单"
if close < entryPrice
pnlColor := color.new(#66ff99, 0)
pnlBgColor := color.new(#0d2619, 0)
else
pnlColor := color.new(#ff6699, 0)
pnlBgColor := color.new(#260d19, 0)
table.cell(infoTable, 0, rowIndex, "当前价格", text_color=color.new(#b3b3ff, 0),
text_size=getTableSize(), bgcolor=color.new(#0d0d1a, 0))
table.cell(infoTable, 1, rowIndex, formatPrice(close) + unrealizedPnL,
text_color=pnlColor,
text_size=getTableSize(), bgcolor=pnlBgColor)
rowIndex += 1
// === 趋势状态与进场价格行 - 蓝紫主题 ===
trendStatus = na(entryType) ? "待机中" : entryType == "多单" ? "多头执行" : "空头执行"
trendIcon = entryType == "多单" ? " ▲" : entryType == "空单" ? " ▼" : " ●"
trendBgColor = entryType == "多单" ? color.new(#1a4d1a, 0) :
entryType == "空单" ? color.new(#4d1a1a, 0) :
color.new(#1a1a4d, 0)
trendTextColor = entryType == "多单" ? color.new(#66ff99, 0) :
entryType == "空单" ? color.new(#ff6699, 0) :
color.new(#9999ff, 0)
table.cell(infoTable, 0, rowIndex, "交易状态", text_color=color.new(#b3b3ff, 0),
text_size=getTableSize(), bgcolor=color.new(#0d0d1a, 0))
table.cell(infoTable, 1, rowIndex, trendStatus + trendIcon, text_color=trendTextColor,
text_size=getTableSize(), bgcolor=trendBgColor)
rowIndex += 1
// === 进场价格行 - 蓝紫主题 ===
table.cell(infoTable, 0, rowIndex, "进场价位", text_color=color.new(#b3b3ff, 0),
text_size=getTableSize(), bgcolor=color.new(#0d0d1a, 0))
table.cell(infoTable, 1, rowIndex, formatPrice(entryPrice),
text_color=color.new(#ffcc99, 0),
text_size=getTableSize(), bgcolor=color.new(#1a1a0d, 0))
rowIndex += 1
// === 多时间框架分析 - 独立行显示 ===
if showMTF
// 多时间框架标题行
table.cell(infoTable, 0, rowIndex, "━━ 多时间框架趋势 ━━", text_color=color.new(#ccccff, 0),
text_size=getTableSize(), bgcolor=color.new(#1a0d33, 0))
table.cell(infoTable, 1, rowIndex, "━━━━━━━━━━━━━━━━━━━━", text_color=color.new(#6633ff, 0),
text_size=getTableSize(), bgcolor=color.new(#1a0d33, 0))
rowIndex += 1
// 1分钟趋势
if mtfEnable1m
= getTrendColor(trend1mDir)
trend1mIcon = trend1mDir == "多头倾向" ? " ▲" : trend1mDir == "空头倾向" ? " ▼" : " ●"
table.cell(infoTable, 0, rowIndex, "1分钟", text_color=color.new(#b3b3ff, 0),
text_size=getTableSize(), bgcolor=color.new(#0d0d1a, 0))
table.cell(infoTable, 1, rowIndex, trend1mDir + trend1mIcon, text_color=trend1mTextColor,
text_size=getTableSize(), bgcolor=trend1mBgColor)
rowIndex += 1
// 5分钟趋势
if mtfEnable5m
= getTrendColor(trend5mDir)
trend5mIcon = trend5mDir == "多头倾向" ? " ▲" : trend5mDir == "空头倾向" ? " ▼" : " ●"
table.cell(infoTable, 0, rowIndex, "5分钟", text_color=color.new(#b3b3ff, 0),
text_size=getTableSize(), bgcolor=color.new(#0d0d1a, 0))
table.cell(infoTable, 1, rowIndex, trend5mDir + trend5mIcon, text_color=trend5mTextColor,
text_size=getTableSize(), bgcolor=trend5mBgColor)
rowIndex += 1
// 15分钟趋势
if mtfEnable15m
= getTrendColor(trend15mDir)
trend15mIcon = trend15mDir == "多头倾向" ? " ▲" : trend15mDir == "空头倾向" ? " ▼" : " ●"
table.cell(infoTable, 0, rowIndex, "15分钟", text_color=color.new(#b3b3ff, 0),
text_size=getTableSize(), bgcolor=color.new(#0d0d1a, 0))
table.cell(infoTable, 1, rowIndex, trend15mDir + trend15mIcon, text_color=trend15mTextColor,
text_size=getTableSize(), bgcolor=trend15mBgColor)
rowIndex += 1
// 1小时趋势
if mtfEnable1h
= getTrendColor(trend1hDir)
trend1hIcon = trend1hDir == "多头倾向" ? " ▲" : trend1hDir == "空头倾向" ? " ▼" : " ●"
table.cell(infoTable, 0, rowIndex, "1小时", text_color=color.new(#b3b3ff, 0),
text_size=getTableSize(), bgcolor=color.new(#0d0d1a, 0))
table.cell(infoTable, 1, rowIndex, trend1hDir + trend1hIcon, text_color=trend1hTextColor,
text_size=getTableSize(), bgcolor=trend1hBgColor)
rowIndex += 1
// 4小时趋势
if mtfEnable4h
= getTrendColor(trend4hDir)
trend4hIcon = trend4hDir == "多头倾向" ? " ▲" : trend4hDir == "空头倾向" ? " ▼" : " ●"
table.cell(infoTable, 0, rowIndex, "4小时", text_color=color.new(#b3b3ff, 0),
text_size=getTableSize(), bgcolor=color.new(#0d0d1a, 0))
table.cell(infoTable, 1, rowIndex, trend4hDir + trend4hIcon, text_color=trend4hTextColor,
text_size=getTableSize(), bgcolor=trend4hBgColor)
rowIndex += 1
// === RSI 动量状态行 - 蓝紫主题 ===
rsiTextColor = color.new(#ccccff, 0)
rsiBgColor = color.new(#0d0d1a, 0)
if rsiStatus == "动量回升"
rsiTextColor := color.new(#66ff99, 0)
rsiBgColor := color.new(#0d2619, 0)
else if rsiStatus == "动量回落"
rsiTextColor := color.new(#ff6699, 0)
rsiBgColor := color.new(#260d19, 0)
else
rsiTextColor := color.new(#ffcc99, 0)
rsiBgColor := color.new(#1a1a0d, 0)
rsiIcon = rsiStatus == "动量回升" ? " ▲" : rsiStatus == "动量回落" ? " ▼" : " ●"
rsiDisplayText = rsiStatus + rsiIcon + " (" + str.tostring(rsiValue, "#.#") + ")"
table.cell(infoTable, 0, rowIndex, "RSI动量", text_color=color.new(#b3b3ff, 0),
text_size=getTableSize(), bgcolor=color.new(#0d0d1a, 0))
table.cell(infoTable, 1, rowIndex, rsiDisplayText, text_color=rsiTextColor,
text_size=getTableSize(), bgcolor=rsiBgColor)
rowIndex += 1
// === 风险管理分割线 ===
table.cell(infoTable, 0, rowIndex, "━━ 风险管理 ━━", text_color=color.new(#ccccff, 0),
text_size=getTableSize(), bgcolor=color.new(#1a0d33, 0))
table.cell(infoTable, 1, rowIndex, "━━━━━━━━━━━━━━━━━━━━", text_color=color.new(#6633ff, 0),
text_size=getTableSize(), bgcolor=color.new(#1a0d33, 0))
rowIndex += 1
// === 止损行 - 蓝紫主题 ===
slPct = calcStopLossPercentage(entryPrice, stopLoss, entryType)
table.cell(infoTable, 0, rowIndex, "止损价位", text_color=color.new(#b3b3ff, 0),
text_size=getTableSize(), bgcolor=color.new(#0d0d1a, 0))
table.cell(infoTable, 1, rowIndex, formatPrice(stopLoss) + slPct,
text_color=color.new(#ff6699, 0),
text_size=getTableSize(), bgcolor=color.new(#330d1a, 0))
rowIndex += 1
// 止盈目标行
if showTargets
// === 目标位1 - 蓝紫主题 ===
tp1Pct = calcTakeProfitPercentage(entryPrice, takeProfit1, entryType)
tp1Reached = na(takeProfit1) ? false :
(entryType == "多单" ? high >= takeProfit1 : low <= takeProfit1)
tp1Icon = tp1Reached ? " ✓" : ""
tp1Color = tp1Reached ? color.new(#66ff99, 0) : color.new(#99ccff, 0)
tp1BgColor = tp1Reached ? color.new(#0d2619, 0) : color.new(#0d1a26, 0)
table.cell(infoTable, 0, rowIndex, "止盈目标1", text_color=color.new(#b3b3ff, 0),
text_size=getTableSize(), bgcolor=color.new(#0d0d1a, 0))
table.cell(infoTable, 1, rowIndex, formatPrice(takeProfit1) + tp1Pct + tp1Icon,
text_color=tp1Color,
text_size=getTableSize(), bgcolor=tp1BgColor)
rowIndex += 1
// === 目标2 - 蓝紫主题 ===
tp2Pct = calcTakeProfitPercentage(entryPrice, takeProfit2, entryType)
tp2Reached = na(takeProfit2) ? false :
(entryType == "多单" ? high >= takeProfit2 : low <= takeProfit2)
tp2Icon = tp2Reached ? " ✓" : ""
tp2Color = tp2Reached ? color.new(#66ff99, 0) : color.new(#cc99ff, 0)
tp2BgColor = tp2Reached ? color.new(#0d2619, 0) : color.new(#1a0d26, 0)
table.cell(infoTable, 0, rowIndex, "止盈目标2", text_color=color.new(#b3b3ff, 0),
text_size=getTableSize(), bgcolor=color.new(#0d0d1a, 0))
table.cell(infoTable, 1, rowIndex, formatPrice(takeProfit2) + tp2Pct + tp2Icon,
text_color=tp2Color,
text_size=getTableSize(), bgcolor=tp2BgColor)
rowIndex += 1
// === 盈亏比行 - 蓝紫主题 ===
if showRatio
rrColor = color.new(#9999ff, 0)
rrBgColor = color.new(#0d0d1a, 0)
if not na(riskRewardRatio)
if riskRewardRatio >= 2
rrColor := color.new(#66ff99, 0)
rrBgColor := color.new(#0d2619, 0)
else if riskRewardRatio >= 1
rrColor := color.new(#ffcc99, 0)
rrBgColor := color.new(#1a1a0d, 0)
else
rrColor := color.new(#ff9966, 0)
rrBgColor := color.new(#1a1a0d, 0)
table.cell(infoTable, 0, rowIndex, "盈亏比例", text_color=color.new(#b3b3ff, 0),
text_size=getTableSize(), bgcolor=color.new(#0d0d1a, 0))
table.cell(infoTable, 1, rowIndex, riskRewardStr,
text_color=rrColor,
text_size=getTableSize(), bgcolor=rrBgColor)
rowIndex += 1
// === 免责声明行 - 蓝紫主题 ===
table.cell(infoTable, 0, rowIndex, "⚠ 风险提示", text_color=color.new(#9999ff, 0),
text_size=size.small, bgcolor=color.new(#0d0d1a, 0))
table.cell(infoTable, 1, rowIndex, "仅供参考,不构成投资建议,盈亏自负",
text_color=color.new(#9999ff, 0),
text_size=size.small, bgcolor=color.new(#1a1a4d, 0))
MACD Momentum Structure & Volume Profile Sniper [MTF]**Description and Methodology**
This script offers a unique approach to Market Structure by moving away from traditional fractal-based highs and lows (which can be noisy). Instead, it utilizes **MACD Momentum Swings** to identify significant structural points, combined with an automated Fixed Range Volume Profile to pinpoint high-probability entry zones.
**1. Why MACD Structure? (The Core Concept)**
Traditional "ZigZag" or Fractal indicators rely solely on price action, often leading to fake-outs during low-volume consolidation.
* This script defines a "Swing High" only when the MACD Histogram crosses below zero (Momentum shifts Bearish).
* This script defines a "Swing Low" only when MACD crosses above zero (Momentum shifts Bullish).
By linking structure to momentum, we filter out weak price movements and focus on the true "heartbeat" of the trend.
**2. The "Mashup" Synergy: Structure + Volume + Logic**
This is not a random combination of indicators. Each component serves a specific step in the trading execution sequence:
* **Step 1 (Structure):** The script identifies a Change of Character (CHoCH) based on the MACD peaks described above.
* **Step 2 (Liquidity/Value):** When a CHoCH occurs, the script *automatically* draws a **Fixed Range Volume Profile (FRVP)** specifically covering the impulse leg that caused the break. This reveals the "Point of Control" (POC)—the hidden price level where the most volume occurred during the move.
* **Step 3 (The Sniper Entry):** The script creates a "Zone" around that POC. It then waits for Price to retrace into this zone.
* **Step 4 (Confirmation):** Once the zone is touched, the script monitors a lower timeframe (User selectable, default M1) for a fresh MACD crossover to trigger the final entry signal.
**Features**
* **Multi-Timeframe Dashboard:** Monitor the MACD Trend direction across 4 different timeframes simultaneously.
* **Dynamic Trendlines:** Automatically connects confirmed MACD peaks to visualize trend integrity.
* **Fibo Time Zones:** Projects potential future pivot points based on the duration of the previous swing.
* **Alert System:** Integrated alerts for Zone Touches and "Sniper" entries (Zone Touch + LTF Momentum Confirmation).
**How to Use**
1. **Identify Trend:** Look for the CHoCH labels. Green indicates a shift to Bullish, Red to Bearish.
2. **Wait for Pullback:** Do not chase the break. Wait for price to return to the Yellow POC Zone generated by the Volume Profile.
3. **Entry Trigger:** Watch for the "BUY" or "SELL" marks. These appear only when price hits the zone AND the lower-timeframe momentum aligns with the trade direction.
**Settings & Inputs**
* **Global MACD:** Adjust the sensitivity of the swing detection (Default 12, 26, 9).
* **Sniper Entry:** Select the timeframe used for the final confirmation (e.g., use M1 confirmation for an H1 chart structure).
* **VP Settings:** Customize how the Volume Profile looks on the chart.
*Disclaimer: This script is intended for educational purposes and market analysis. It does not provide financial advice.*






















